-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathapp.js
More file actions
425 lines (368 loc) · 12.9 KB
/
Copy pathapp.js
File metadata and controls
425 lines (368 loc) · 12.9 KB
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/* global d3, topojson */
const WORLD_TOPO = "https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json";
const VOTE_POLL_MS = 5_000;
const state = {
locations: [],
candidates: [],
totalVotes: 0,
yourVote: null,
selectedLocationId: null,
sessionId: sessionIdForThisTab(),
};
function sessionIdForThisTab() {
const key = "duckoffee:session";
let id = sessionStorage.getItem(key);
if (!id) {
id = crypto.randomUUID();
sessionStorage.setItem(key, id);
}
return id;
}
function formatMoney(n) {
if (n == null) return "—";
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
}).format(n);
}
function formatMoneyPrecise(n) {
if (n == null) return "—";
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(n);
}
async function fetchJSON(url, init) {
const res = await fetch(url, init);
if (!res.ok) throw new Error(`${url} -> ${res.status}`);
return res.json();
}
async function init() {
const mapEl = document.getElementById("map");
const { projection, path, svg } = setupMap(mapEl);
const world = await fetch(WORLD_TOPO).then((r) => r.json());
drawWorld(svg, world, path);
// Cafes + sales come from MotherDuck. If that call fails (bad token, outage,
// etc.) we still want the map and the voting UI to work, so handle the
// failure here instead of letting it abort init().
try {
state.locations = await fetchJSON("/api/locations");
drawCafes(svg, projection);
await refreshSummaryAndChart();
} catch (err) {
console.warn("cafes/sales unavailable", err);
showStatsError();
}
await refreshVotes();
setInterval(refreshVotes, VOTE_POLL_MS);
document.getElementById("clear-filter").addEventListener("click", () => {
selectLocation(null);
});
window.addEventListener("resize", () => {
mapEl.innerHTML = "";
const rebuilt = setupMap(mapEl);
drawWorld(rebuilt.svg, world, rebuilt.path);
drawCafes(rebuilt.svg, rebuilt.projection);
drawCandidates(rebuilt.svg, rebuilt.projection);
projectionRef.current = rebuilt.projection;
svgRef.current = rebuilt.svg;
});
}
function showStatsError() {
const title = document.getElementById("stats-title");
if (title) title.textContent = "Sales unavailable";
const list = document.getElementById("top-products");
if (list) {
list.innerHTML =
'<li style="list-style:none;padding:0;color:var(--md-ink-soft)">Cafe data could not be loaded. Check the Worker logs and your MotherDuck token, then refresh.</li>';
}
}
const projectionRef = { current: null };
const svgRef = { current: null };
function setupMap(mapEl) {
const width = mapEl.clientWidth;
const height = mapEl.clientHeight;
const svg = d3
.select(mapEl)
.append("svg")
.attr("viewBox", `0 0 ${width} ${height}`)
.attr("preserveAspectRatio", "xMidYMid meet");
const projection = d3
.geoNaturalEarth1()
.scale(width / 6.3)
.translate([width / 2, height / 1.85]);
const path = d3.geoPath(projection);
projectionRef.current = projection;
svgRef.current = svg;
return { projection, path, svg };
}
function drawWorld(svg, world, path) {
const countries = topojson.feature(world, world.objects.countries);
svg
.append("g")
.selectAll("path")
.data(countries.features)
.enter()
.append("path")
.attr("class", "country")
.attr("d", path);
const graticule = d3.geoGraticule();
svg.append("path").datum(graticule).attr("class", "graticule").attr("d", path);
}
function drawCafes(svg, projection) {
svg.selectAll(".cafe-layer").remove();
const g = svg.append("g").attr("class", "cafe-layer");
const tooltip = ensureTooltip();
g.selectAll("circle")
.data(state.locations.filter((d) => d.lat != null && d.lon != null))
.enter()
.append("circle")
.attr("class", (d) =>
d.location_id === state.selectedLocationId ? "cafe cafe--selected" : "cafe",
)
.attr("cx", (d) => projection([d.lon, d.lat])[0])
.attr("cy", (d) => projection([d.lon, d.lat])[1])
.attr("r", 6)
.on("mouseenter", (event, d) => {
tooltip.style.opacity = "1";
tooltip.innerHTML = `<strong>${d.location_name}</strong><br>${d.city}, ${d.country} · ${formatMoney(d.revenue)}`;
positionTooltip(tooltip, event);
})
.on("mousemove", (event) => positionTooltip(tooltip, event))
.on("mouseleave", () => {
tooltip.style.opacity = "0";
})
.on("click", (_event, d) => {
selectLocation(d.location_id === state.selectedLocationId ? null : d.location_id);
});
}
function drawCandidates(svg, projection) {
svg.selectAll(".candidate-layer").remove();
if (!state.candidates.length) return;
const g = svg.append("g").attr("class", "candidate-layer");
const tooltip = ensureTooltip();
const maxVotes = Math.max(1, ...state.candidates.map((c) => c.votes));
const nodes = state.candidates.map((c) => {
const [x, y] = projection([c.lon, c.lat]);
return { ...c, x, y, radius: 7 + 9 * Math.sqrt(c.votes / maxVotes) };
});
g.selectAll(".candidate-pulse")
.data(nodes.filter((n) => n.id === state.yourVote))
.enter()
.append("circle")
.attr("class", "candidate-pulse")
.attr("cx", (d) => d.x)
.attr("cy", (d) => d.y)
.attr("r", (d) => d.radius);
const groups = g
.selectAll(".candidate")
.data(nodes)
.enter()
.append("g")
.attr("class", (d) =>
d.id === state.yourVote ? "candidate candidate--picked" : "candidate",
)
.attr("transform", (d) => `translate(${d.x},${d.y})`)
.on("mouseenter", (event, d) => {
tooltip.style.opacity = "1";
const label = d.votes === 1 ? "vote" : "votes";
const hint = d.id === state.yourVote ? " · your pick" : " · click to vote";
tooltip.innerHTML = `<strong>${d.name}</strong><br>${d.country} · ${d.votes} ${label}${hint}`;
positionTooltip(tooltip, event);
})
.on("mousemove", (event) => positionTooltip(tooltip, event))
.on("mouseleave", () => {
tooltip.style.opacity = "0";
})
.on("click", (_event, d) => castVote(d.id));
groups
.append("circle")
.attr("class", "candidate__dot")
.attr("r", (d) => d.radius);
groups
.append("text")
.attr("class", "candidate__label")
.attr("text-anchor", "middle")
.attr("dy", "0.35em")
.text((d) => d.votes);
}
function ensureTooltip() {
let tip = document.querySelector(".tooltip");
if (!tip) {
tip = document.createElement("div");
tip.className = "tooltip";
document.body.appendChild(tip);
}
return tip;
}
function positionTooltip(tip, event) {
tip.style.left = `${event.pageX}px`;
tip.style.top = `${event.pageY}px`;
}
function selectLocation(locationId) {
state.selectedLocationId = locationId;
const svg = svgRef.current;
if (svg) {
svg
.selectAll(".cafe")
.attr("class", (d) =>
d.location_id === state.selectedLocationId ? "cafe cafe--selected" : "cafe",
);
}
const cleared = document.getElementById("clear-filter");
cleared.hidden = locationId == null;
const title = document.getElementById("stats-title");
const loc = state.locations.find((l) => l.location_id === locationId);
title.textContent = loc ? `${loc.location_name} (${loc.city})` : "Global sales";
refreshSummaryAndChart();
}
function setStatsLoading(isLoading) {
const loader = document.getElementById("stats-loader");
if (!loader) return;
loader.classList.toggle("is-visible", isLoading);
loader.setAttribute("aria-hidden", isLoading ? "false" : "true");
}
async function refreshSummaryAndChart() {
const q = state.selectedLocationId ? `?location_id=${state.selectedLocationId}` : "";
setStatsLoading(true);
try {
const [summary, sales] = await Promise.all([
fetchJSON(`/api/summary${q}`),
fetchJSON(`/api/sales${q}${q ? "&" : "?"}days=90`),
]);
renderSummary(summary);
renderChart(sales.series);
} catch (err) {
console.error("failed to load data", err);
} finally {
setStatsLoading(false);
}
}
function renderSummary(s) {
document.getElementById("stat-orders").textContent = new Intl.NumberFormat().format(s.orders ?? 0);
document.getElementById("stat-revenue").textContent = formatMoney(s.revenue ?? 0);
document.getElementById("stat-avg").textContent = formatMoneyPrecise(s.avg_order ?? 0);
const list = document.getElementById("top-products");
list.innerHTML = "";
(s.top_products || []).forEach((p) => {
const li = document.createElement("li");
li.innerHTML = `<strong>${p.product_name}</strong> · ${new Intl.NumberFormat().format(p.sold)} sold`;
list.appendChild(li);
});
}
function renderChart(series) {
const host = document.getElementById("chart");
host.innerHTML = "";
if (!series || series.length === 0) return;
const width = host.clientWidth;
const height = host.clientHeight;
const margin = { top: 10, right: 10, bottom: 24, left: 48 };
const innerW = width - margin.left - margin.right;
const innerH = height - margin.top - margin.bottom;
const svg = d3
.select(host)
.append("svg")
.attr("viewBox", `0 0 ${width} ${height}`);
const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);
const parsed = series.map((d) => ({ day: new Date(d.day), revenue: +d.revenue }));
const x = d3.scaleTime()
.domain(d3.extent(parsed, (d) => d.day))
.range([0, innerW]);
const y = d3.scaleLinear()
.domain([0, d3.max(parsed, (d) => d.revenue) || 0])
.nice()
.range([innerH, 0]);
g.append("g")
.attr("class", "chart-axis")
.attr("transform", `translate(0,${innerH})`)
.call(d3.axisBottom(x).ticks(Math.min(6, parsed.length)).tickSizeOuter(0));
g.append("g")
.attr("class", "chart-axis")
.call(d3.axisLeft(y).ticks(4).tickFormat((v) => formatMoney(v)));
const area = d3.area()
.x((d) => x(d.day))
.y0(innerH)
.y1((d) => y(d.revenue))
.curve(d3.curveMonotoneX);
const line = d3.line()
.x((d) => x(d.day))
.y((d) => y(d.revenue))
.curve(d3.curveMonotoneX);
g.append("path").datum(parsed).attr("class", "chart-area").attr("d", area);
g.append("path").datum(parsed).attr("class", "chart-line").attr("d", line);
g.selectAll(".chart-point")
.data(parsed)
.enter()
.append("circle")
.attr("class", "chart-point")
.attr("cx", (d) => x(d.day))
.attr("cy", (d) => y(d.revenue))
.attr("r", 2);
}
async function refreshVotes() {
try {
const data = await fetchJSON(`/api/votes?session_id=${encodeURIComponent(state.sessionId)}`);
state.candidates = data.candidates || [];
state.totalVotes = data.total_votes || 0;
state.yourVote = data.your_vote || null;
document.getElementById("vote-count").textContent =
new Intl.NumberFormat().format(state.totalVotes);
renderLeaderboard();
if (svgRef.current && projectionRef.current) {
drawCandidates(svgRef.current, projectionRef.current);
}
} catch (err) {
console.warn("vote refresh failed", err);
}
}
async function castVote(candidateId) {
state.yourVote = candidateId;
try {
await fetch("/api/votes", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ session_id: state.sessionId, candidate_id: candidateId }),
});
await refreshVotes();
} catch (err) {
console.warn("vote failed", err);
}
}
function renderLeaderboard() {
const list = document.getElementById("leaderboard");
const meta = document.getElementById("leaderboard-meta");
if (!list || !meta) return;
list.innerHTML = "";
const sorted = [...state.candidates].sort(
(a, b) => b.votes - a.votes || a.name.localeCompare(b.name),
);
const max = Math.max(1, ...sorted.map((c) => c.votes));
sorted.forEach((c, i) => {
const pct = (c.votes / max) * 100;
const isPick = c.id === state.yourVote;
const li = document.createElement("li");
li.className = isPick ? "leaderboard__row leaderboard__row--picked" : "leaderboard__row";
li.innerHTML = `
<span class="leaderboard__rank">${i + 1}</span>
<span class="leaderboard__name">${c.name}<span class="leaderboard__country"> · ${c.country}</span></span>
<span class="leaderboard__bar"><span class="leaderboard__bar-fill" style="width:${pct}%"></span></span>
<span class="leaderboard__votes">${c.votes}</span>
`;
li.addEventListener("click", () => castVote(c.id));
list.appendChild(li);
});
if (state.totalVotes === 0) {
meta.textContent = "Be the first to vote.";
} else if (state.yourVote) {
const picked = state.candidates.find((c) => c.id === state.yourVote);
meta.textContent = picked ? `You picked ${picked.name}.` : "Your vote is in.";
} else {
meta.textContent = `${state.totalVotes} vote${state.totalVotes === 1 ? "" : "s"} so far.`;
}
}
init().catch((err) => {
console.error("init failed", err);
document.getElementById("map").innerHTML =
'<p style="padding:1rem">Could not load the map. Check the Worker logs.</p>';
});