-
Notifications
You must be signed in to change notification settings - Fork 35
/
dashboard.tsx
299 lines (265 loc) · 10.1 KB
/
dashboard.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import { Card, CardContent } from "~/components/ui/card";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "~/components/ui/select";
import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/cloudflare";
import { json, redirect } from "@remix-run/cloudflare";
import { useLoaderData, useSearchParams } from "@remix-run/react";
import { AnalyticsEngineAPI } from "../analytics/query";
import TableCard from "~/components/TableCard";
import TimeSeriesChart from "~/components/TimeSeriesChart";
export const meta: MetaFunction = () => {
return [
{ title: "Counterscale: Web Analytics" },
{ name: "description", content: "Counterscale: Web Analytics" },
];
};
declare module "@remix-run/server-runtime" {
export interface AppLoadContext {
env: {
VERSION: string;
CF_BEARER_TOKEN: string;
CF_ACCOUNT_ID: string;
};
}
}
export const loader = async ({ context, request }: LoaderFunctionArgs) => {
if (!context.env.CF_BEARER_TOKEN || !context.env.CF_ACCOUNT_ID) {
throw new Error("Missing Cloudflare credentials");
}
const analyticsEngine = new AnalyticsEngineAPI(
context.env.CF_ACCOUNT_ID,
context.env.CF_BEARER_TOKEN,
);
const url = new URL(request.url);
let interval;
try {
interval = url.searchParams.get("interval") || "7";
interval = Number(interval);
} catch (err) {
interval = 7;
}
// if no siteId is set, redirect to the site with the most hits
if (url.searchParams.has("site") === false) {
const sitesByHits =
await analyticsEngine.getSitesOrderedByHits(interval);
// if at least one result
const redirectSite = sitesByHits[0]?.[0] || "";
const redirectUrl = new URL(request.url);
redirectUrl.searchParams.set("site", redirectSite);
return redirect(redirectUrl.toString());
}
const siteId = url.searchParams.get("site") || "";
const actualSiteId = siteId == "@unknown" ? "" : siteId;
// initiate requests to AE in parallel
const sitesByHits = analyticsEngine.getSitesOrderedByHits(interval);
const counts = analyticsEngine.getCounts(actualSiteId, interval);
const countByPath = analyticsEngine.getCountByPath(actualSiteId, interval);
const countByCountry = analyticsEngine.getCountByCountry(
actualSiteId,
interval,
);
const countByReferrer = analyticsEngine.getCountByReferrer(
actualSiteId,
interval,
);
const countByBrowser = analyticsEngine.getCountByBrowser(
actualSiteId,
interval,
);
const countByDevice = analyticsEngine.getCountByDevice(
actualSiteId,
interval,
);
let intervalType = "DAY";
switch (interval) {
case 1:
intervalType = "HOUR";
break;
case 7:
intervalType = "DAY";
break;
case 30:
intervalType = "DAY";
break;
case 90:
intervalType = "DAY";
break;
}
const tz = context.requestTimezone as string;
const viewsGroupedByInterval = analyticsEngine.getViewsGroupedByInterval(
actualSiteId,
intervalType,
interval,
tz,
);
// await all requests to AE then return the results
return json({
siteId: siteId,
sites: (await sitesByHits).map(([site, _]: [string, number]) => site),
views: (await counts).views,
visits: (await counts).visits,
visitors: (await counts).visitors,
countByPath: await countByPath,
countByBrowser: await countByBrowser,
countByCountry: await countByCountry,
countByReferrer: await countByReferrer,
countByDevice: await countByDevice,
viewsGroupedByInterval: await viewsGroupedByInterval,
intervalType,
});
};
function convertCountryCodesToNames(
countByCountry: [string, number][],
): [string, number][] {
const regionNames = new Intl.DisplayNames(["en"], { type: "region" });
return countByCountry.map((countByBrowserRow) => {
let countryName;
try {
// throws an exception if country code isn't valid
// use try/catch to be defensive and not explode if an invalid
// country code gets insrted into Analytics Engine
countryName = regionNames.of(countByBrowserRow[0])!; // "United States"
} catch (err) {
countryName = "(unknown)";
}
const count = countByBrowserRow[1];
return [countryName, count];
});
}
export default function Dashboard() {
const [, setSearchParams] = useSearchParams();
const data = useLoaderData<typeof loader>();
function changeSite(site: string) {
setSearchParams((prev) => {
prev.set("site", site);
return prev;
});
}
function changeInterval(interval: string) {
setSearchParams((prev) => {
prev.set("interval", interval);
return prev;
});
}
const chartData: { date: string; views: number }[] = [];
data.viewsGroupedByInterval.forEach((row) => {
chartData.push({
date: row[0],
views: row[1],
});
});
const countByCountryName = convertCountryCodesToNames(data.countByCountry);
const countFormatter = Intl.NumberFormat("en", { notation: "compact" });
return (
<div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>
<div className="w-full mb-4 flex gap-4">
<div className="w-1/2 sm:w-1/3 md:w-1/5">
<Select
defaultValue={data.siteId}
onValueChange={(site) => changeSite(site)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{/* SelectItem explodes if given an empty string for `value` so coerce to @unknown */}
{data.sites.map((siteId: string) => (
<SelectItem
key={`k-${siteId}`}
value={siteId || "@unknown"}
>
{siteId || "(unknown)"}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="w-1/2 sm:w-1/3 md:w-1/5">
<Select
defaultValue="7"
onValueChange={(interval) => changeInterval(interval)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">1 day</SelectItem>
<SelectItem value="7">7 days</SelectItem>
<SelectItem value="30">30 days</SelectItem>
<SelectItem value="90">90 days</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="w-full mb-4">
<Card>
<CardContent className="pt-6">
<div className="grid grid-cols-3 gap-10 items-end">
<div>
<div className="text-sm sm:text-lg">Views</div>
<div className="text-4xl">
{countFormatter.format(data.views)}
</div>
</div>
<div>
<div className="text-sm sm:text-lg">Visits</div>
<div className="text-4xl">
{countFormatter.format(data.visits)}
</div>
</div>
<div>
<div className="text-sm sm:text-lg">
Visitors
</div>
<div className="text-4xl">
{countFormatter.format(data.visitors)}
</div>
</div>
</div>
</CardContent>
</Card>
</div>
<div className="w-full mb-4">
<Card>
<CardContent>
<div className="h-80 pt-6 -m-4 -ml-8 sm:m-0">
<TimeSeriesChart
data={chartData}
intervalType={data.intervalType}
></TimeSeriesChart>
</div>
</CardContent>
</Card>
</div>
<div className="grid md:grid-cols-2 gap-4 mb-4">
<TableCard
countByProperty={data.countByPath}
columnHeaders={["Page", "Visitors", "Views"]}
/>
<TableCard
countByProperty={data.countByReferrer}
columnHeaders={["Referrer", "Visitors"]}
/>
</div>
<div className="grid md:grid-cols-3 gap-4 mb-4">
<TableCard
countByProperty={data.countByBrowser}
columnHeaders={["Browser", "Visitors"]}
/>
<TableCard
countByProperty={countByCountryName}
columnHeaders={["Country", "Visitors"]}
/>
<TableCard
countByProperty={data.countByDevice}
columnHeaders={["Device", "Visitors"]}
></TableCard>
</div>
</div>
);
}