-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics.ts
More file actions
686 lines (628 loc) · 22.3 KB
/
Copy pathanalytics.ts
File metadata and controls
686 lines (628 loc) · 22.3 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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
import { eq, and, gte, lte, sql, desc } from "drizzle-orm";
import { db } from "$lib/server/db";
import { doseLogs, medications } from "$lib/server/db/schema";
import { startOfDay } from "$lib/utils/time";
import { getSchedulesForUser } from "$lib/server/schedules";
import type { MedicationSchedule } from "$lib/server/schedules";
import type { DoseLogStatus } from "$lib/server/db/schema";
import { clampEffectiveDays, isActiveOn } from "$lib/server/analytics/lifecycle";
/**
* Sum expected doses per day across a medication's schedule rows.
* - interval rows contribute 24 / intervalHours
* - fixed_time rows contribute 1, scaled down if daysOfWeek restricts
* the schedule to specific weekdays
* - prn rows contribute 0
*/
export function expectedPerDayForSchedules(schedules: MedicationSchedule[]): number {
let perDay = 0;
for (const s of schedules) {
if (s.scheduleKind === "prn") continue;
if (s.scheduleKind === "interval" && s.intervalHours) {
const hrs = Number(s.intervalHours);
if (hrs > 0) perDay += 24 / hrs;
} else if (s.scheduleKind === "fixed_time" && s.timeOfDay) {
const dayFraction = s.daysOfWeek && s.daysOfWeek.length > 0 ? s.daysOfWeek.length / 7 : 1;
perDay += dayFraction;
}
}
return perDay;
}
const validTimezones = new Set(Intl.supportedValuesOf("timeZone"));
function safeTz(timezone: string): ReturnType<typeof sql.raw> {
const tz = validTimezones.has(timezone) ? timezone : "UTC";
return sql.raw(`'${tz}'`);
}
export interface DateRange {
from?: Date;
to?: Date;
}
function buildDateFilters(
userId: string,
days: number,
timezone: string,
range?: DateRange,
status: DoseLogStatus | "any" = "taken",
) {
const baseUser = eq(doseLogs.userId, userId);
const statusFilter = status === "any" ? undefined : eq(doseLogs.status, status);
if (range?.from && range?.to) {
return and(
baseUser,
...(statusFilter ? [statusFilter] : []),
gte(doseLogs.takenAt, range.from),
lte(doseLogs.takenAt, range.to),
);
}
const since = startOfDay(new Date(Date.now() - days * 86400000), timezone);
return and(baseUser, ...(statusFilter ? [statusFilter] : []), gte(doseLogs.takenAt, since));
}
export function calculateTrend(
current: number,
previous: number,
): { direction: "up" | "down" | "flat"; percent: number } {
if (previous === 0 && current === 0) return { direction: "flat", percent: 0 };
if (previous === 0) return { direction: "up", percent: 100 };
const change = ((current - previous) / previous) * 100;
const rounded = Math.round(Math.abs(change));
if (rounded === 0) return { direction: "flat", percent: 0 };
return { direction: change > 0 ? "up" : "down", percent: rounded };
}
export function calculateStreak(sortedDates: string[], timezone: string = "UTC"): number {
if (sortedDates.length === 0) return 0;
const today = new Intl.DateTimeFormat("en-CA", { timeZone: timezone }).format(new Date());
if (sortedDates[0] !== today) return 0;
let streak = 1;
for (let i = 1; i < sortedDates.length; i++) {
const prev = new Date(sortedDates[i - 1]);
const curr = new Date(sortedDates[i]);
const diffDays = (prev.getTime() - curr.getTime()) / 86400000;
if (Math.round(diffDays) === 1) {
streak++;
} else {
break;
}
}
return streak;
}
// Visual adherence: capped at 100% so the bar never overshoots.
// Use calculateOveruse() for the over-100 overflow.
export function calculateAdherence(taken: number, expected: number): number {
if (expected === 0) return 0;
const raw = Math.round((taken / expected) * 1000) / 10;
return Math.min(100, raw);
}
export function calculateOveruse(taken: number, expected: number): number {
if (expected === 0) return 0;
if (taken <= expected) return 0;
return Math.round(((taken - expected) / expected) * 1000) / 10;
}
export async function getDailyDoseCounts(
userId: string,
days: number,
timezone: string = "UTC",
range?: DateRange,
) {
return db
.select({
date: sql<string>`date(${doseLogs.takenAt} AT TIME ZONE ${safeTz(timezone)})`,
count: sql<number>`count(*)::int`,
})
.from(doseLogs)
.where(buildDateFilters(userId, days, timezone, range))
.groupBy(sql`date(${doseLogs.takenAt} AT TIME ZONE ${safeTz(timezone)})`)
.orderBy(desc(sql`date(${doseLogs.takenAt} AT TIME ZONE ${safeTz(timezone)})`));
}
export async function getPerMedicationStats(
userId: string,
days: number,
timezone: string = "UTC",
range?: DateRange,
options?: { includeAsNeeded?: boolean },
) {
const whereClauseAll = buildDateFilters(userId, days, timezone, range, "any");
const rangeFrom = range?.from ?? new Date(Date.now() - days * 86400000);
const rangeTo = range?.to ?? new Date();
const [rows, schedulesByMed] = await Promise.all([
db
.select({
medicationId: doseLogs.medicationId,
medicationName: medications.name,
colour: medications.colour,
scheduleIntervalHours: medications.scheduleIntervalHours,
scheduleType: medications.scheduleType,
startedAt: medications.startedAt,
endedAt: medications.endedAt,
status: doseLogs.status,
events: sql<number>`count(*)::int`,
quantity: sql<number>`coalesce(sum(${doseLogs.quantity}), 0)::int`,
})
.from(doseLogs)
.innerJoin(
medications,
and(eq(doseLogs.medicationId, medications.id), eq(medications.userId, userId)),
)
.where(whereClauseAll)
.groupBy(
doseLogs.medicationId,
medications.name,
medications.colour,
medications.scheduleIntervalHours,
medications.scheduleType,
medications.startedAt,
medications.endedAt,
doseLogs.status,
),
getSchedulesForUser(userId),
]);
type Bucket = {
medicationId: string;
medicationName: string;
colour: string;
scheduleIntervalHours: string | null;
scheduleType: string;
startedAt: Date;
endedAt: Date | null;
takenEvents: number;
takenQuantity: number;
skippedEvents: number;
};
const buckets = new Map<string, Bucket>();
for (const row of rows) {
const b = buckets.get(row.medicationId) ?? {
medicationId: row.medicationId,
medicationName: row.medicationName,
colour: row.colour,
scheduleIntervalHours: row.scheduleIntervalHours,
scheduleType: row.scheduleType,
startedAt: row.startedAt,
endedAt: row.endedAt,
takenEvents: 0,
takenQuantity: 0,
skippedEvents: 0,
};
if (row.status === "taken") {
b.takenEvents += row.events;
b.takenQuantity += row.quantity;
} else if (row.status === "skipped") {
b.skippedEvents += row.events;
}
buckets.set(row.medicationId, b);
}
const includeAsNeeded = options?.includeAsNeeded ?? false;
return [...buckets.values()]
.filter((b) => {
if (includeAsNeeded) return true;
const sched = schedulesByMed.get(b.medicationId);
// Hide pure-PRN medications by default. Fall back to legacy
// scheduleType column if no schedule rows exist yet (pre-backfill).
if (sched && sched.length > 0) {
return sched.some((s) => s.scheduleKind !== "prn");
}
return b.scheduleType !== "as_needed";
})
.map((b) => {
const sched = schedulesByMed.get(b.medicationId) ?? [];
const expectedPerDay =
sched.length > 0
? expectedPerDayForSchedules(sched)
: b.scheduleIntervalHours
? 24 / Number(b.scheduleIntervalHours)
: 0;
// Clamp the analytics window against this medication's lifecycle
// so a med added yesterday isn't penalised for the days before it
// existed.
const effectiveDays = clampEffectiveDays(rangeFrom, rangeTo, b.startedAt, b.endedAt);
const expectedTotal = Math.round(expectedPerDay * effectiveDays);
return {
medicationId: b.medicationId,
medicationName: b.medicationName,
colour: b.colour,
scheduleIntervalHours: b.scheduleIntervalHours,
scheduleType: b.scheduleType,
doseCount: b.takenEvents,
takenEvents: b.takenEvents,
takenQuantity: b.takenQuantity,
skippedEvents: b.skippedEvents,
expectedTotal,
adherence: calculateAdherence(b.takenEvents, expectedTotal),
overuse: calculateOveruse(b.takenEvents, expectedTotal),
};
});
}
// User-level dose status breakdown. Per the doc, missedCount is
// "expected but unresolved" — for interval schedules we infer it as
// expected - taken - skipped (clamped at 0). For as_needed meds we
// treat expected as 0.
export async function getDoseStatusBreakdown(
userId: string,
days: number,
timezone: string = "UTC",
range?: DateRange,
) {
const stats = await getPerMedicationStats(userId, days, timezone, range, {
includeAsNeeded: true,
});
let takenEvents = 0;
let takenQuantity = 0;
let skippedEvents = 0;
let expectedTotal = 0;
for (const m of stats) {
takenEvents += m.takenEvents;
takenQuantity += m.takenQuantity;
skippedEvents += m.skippedEvents;
expectedTotal += m.expectedTotal;
}
const resolved = takenEvents + skippedEvents;
const missedEvents = Math.max(0, expectedTotal - resolved);
return {
takenEvents,
takenQuantity,
skippedEvents,
missedEvents,
expectedTotal,
adherencePercent: calculateAdherence(takenEvents, expectedTotal),
overusePercent: calculateOveruse(takenEvents, expectedTotal),
};
}
export type DailyAdherencePoint = {
date: string;
doseCount: number;
expected: number;
adherence: number;
};
// Computed expected doses/day from the deprecated medications.scheduleType
// + medications.scheduleIntervalHours columns. Used as fallback when a
// medication has no rows in the medication_schedules table yet.
function expectedPerDayFromLegacy(
scheduleType: string,
scheduleIntervalHours: number | string | null,
): number {
if (scheduleType !== "scheduled") return 0;
const hrs = scheduleIntervalHours !== null ? Number(scheduleIntervalHours) : NaN;
if (!Number.isFinite(hrs) || hrs <= 0) return 0;
return 24 / hrs;
}
// Daily adherence approximation. Expected-per-day is derived from the
// current set of schedules, not a per-day historical reconstruction —
// medications added or archived mid-period are not retro-applied. Good
// enough for a sparkline trend; do not treat as authoritative.
export async function getDailyAdherenceSeries(
userId: string,
days: number,
timezone: string = "UTC",
range?: DateRange,
): Promise<DailyAdherencePoint[]> {
const [dailyCounts, schedulesByMed, activeMeds] = await Promise.all([
getDailyDoseCounts(userId, days, timezone, range),
getSchedulesForUser(userId),
db
.select({
id: medications.id,
scheduleType: medications.scheduleType,
scheduleIntervalHours: medications.scheduleIntervalHours,
startedAt: medications.startedAt,
endedAt: medications.endedAt,
})
.from(medications)
.where(and(eq(medications.userId, userId), eq(medications.isArchived, false))),
]);
// Per-medication expected-per-day so we can include only meds that
// were active on a given day.
const expectedByMed = activeMeds.map((med) => {
const schedules = schedulesByMed.get(med.id);
const perDay =
schedules && schedules.length > 0
? expectedPerDayForSchedules(schedules)
: expectedPerDayFromLegacy(med.scheduleType, med.scheduleIntervalHours);
return { startedAt: med.startedAt, endedAt: med.endedAt, perDay };
});
const fromDate =
range?.from && range?.to
? range.from
: startOfDay(new Date(Date.now() - days * 86400000), timezone);
const toDate = range?.to ?? new Date();
const span = Math.max(1, Math.round((toDate.getTime() - fromDate.getTime()) / 86400000));
const tz = validTimezones.has(timezone) ? timezone : "UTC";
const formatter = new Intl.DateTimeFormat("en-CA", {
timeZone: tz,
year: "numeric",
month: "2-digit",
day: "2-digit",
});
const countByDate = new Map<string, number>();
for (const row of dailyCounts) {
countByDate.set(row.date, row.count);
}
const series: DailyAdherencePoint[] = [];
for (let i = 0; i < span; i++) {
const day = new Date(fromDate.getTime() + i * 86400000);
const dateKey = formatter.format(day);
const doseCount = countByDate.get(dateKey) ?? 0;
// Sum expected only across meds active on this specific day.
const expectedPerDay = expectedByMed.reduce(
(acc, m) => acc + (isActiveOn(day, m.startedAt, m.endedAt) ? m.perDay : 0),
0,
);
const adherence =
expectedPerDay > 0 ? Math.min(100, Math.round((doseCount / expectedPerDay) * 100)) : 0;
series.push({
date: dateKey,
doseCount,
expected: Math.round(expectedPerDay * 10) / 10,
adherence,
});
}
return series;
}
export async function getHourlyDistribution(
userId: string,
days: number,
timezone: string = "UTC",
range?: DateRange,
) {
return db
.select({
hour: sql<number>`extract(hour from ${doseLogs.takenAt} AT TIME ZONE ${safeTz(timezone)})::int`,
count: sql<number>`count(*)::int`,
})
.from(doseLogs)
.where(buildDateFilters(userId, days, timezone, range))
.groupBy(sql`extract(hour from ${doseLogs.takenAt} AT TIME ZONE ${safeTz(timezone)})`)
.orderBy(sql`extract(hour from ${doseLogs.takenAt} AT TIME ZONE ${safeTz(timezone)})`);
}
export async function getDayOfWeekDistribution(
userId: string,
days: number,
timezone: string = "UTC",
range?: DateRange,
) {
return db
.select({
dayOfWeek: sql<number>`extract(dow from ${doseLogs.takenAt} AT TIME ZONE ${safeTz(timezone)})::int`,
count: sql<number>`count(*)::int`,
})
.from(doseLogs)
.where(buildDateFilters(userId, days, timezone, range))
.groupBy(sql`extract(dow from ${doseLogs.takenAt} AT TIME ZONE ${safeTz(timezone)})`)
.orderBy(sql`extract(dow from ${doseLogs.takenAt} AT TIME ZONE ${safeTz(timezone)})`);
}
// Insight type moved to $lib/types so client components (InsightsCard)
// can import without crossing the $lib/server boundary. Re-exported
// here for backward-compatible callers.
export type { Insight } from "$lib/types";
import type { Insight } from "$lib/types";
export type InsightInputs = {
totalDoses: number;
prevTotalDoses: number;
avgAdherence: number;
prevAvgAdherence: number;
medStats: Array<{ medicationName: string; adherence: number; expectedTotal: number }>;
dayOfWeek: Array<{ dayOfWeek: number; count: number }>;
hourly: Array<{ hour: number; count: number }>;
sideEffectsCount: number;
topSideEffect: string | null;
refillCriticalCount: number;
streak: number;
};
const DAY_LABEL_FULL = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
export function buildInsights(input: InsightInputs): Insight[] {
const out: Insight[] = [];
if (input.medStats.length >= 2 && input.prevAvgAdherence > 0) {
const delta = input.avgAdherence - input.prevAvgAdherence;
if (Math.abs(delta) >= 5) {
out.push({
id: "adherence-trend",
severity: delta > 0 ? "positive" : "warning",
text: `Adherence ${delta > 0 ? "improved" : "declined"} ${Math.abs(delta)}% vs. previous period`,
});
}
}
if (input.medStats.length >= 2) {
const sorted = [...input.medStats]
.filter((m) => m.expectedTotal > 0)
.sort((a, b) => b.adherence - a.adherence);
if (sorted.length >= 2) {
const top = sorted[0];
out.push({
id: "highest-adherence-med",
severity: "positive",
text: `Highest adherence: ${top.medicationName} (${top.adherence}%)`,
});
const bottom = sorted[sorted.length - 1];
if (bottom.adherence < 80) {
out.push({
id: "lowest-adherence-med",
severity: "warning",
text: `Lowest adherence: ${bottom.medicationName} (${bottom.adherence}%)`,
});
}
}
}
const totalDow = input.dayOfWeek.reduce((s, d) => s + d.count, 0);
if (totalDow >= 7) {
const avg = totalDow / 7;
const worst = [...input.dayOfWeek].sort((a, b) => a.count - b.count)[0];
if (worst && worst.count < avg * 0.7 && worst.count >= 0) {
out.push({
id: "worst-day",
severity: "info",
text: `Fewest doses on ${DAY_LABEL_FULL[worst.dayOfWeek]}`,
});
}
}
const totalHour = input.hourly.reduce((s, h) => s + h.count, 0);
if (totalHour >= 5) {
const peak = [...input.hourly].sort((a, b) => b.count - a.count)[0];
if (peak && peak.count >= totalHour * 0.3) {
const hh = peak.hour.toString().padStart(2, "0");
out.push({
id: "peak-hour",
severity: "info",
text: `Most consistent dosing time is ${hh}:00`,
});
}
}
if (input.refillCriticalCount > 0) {
out.push({
id: "refill-warning",
severity: "warning",
text:
input.refillCriticalCount === 1
? `1 medication needs a refill within 7 days`
: `${input.refillCriticalCount} medications need a refill within 7 days`,
});
}
if (input.sideEffectsCount >= 3 && input.topSideEffect) {
out.push({
id: "side-effects",
severity: "info",
text: `${input.sideEffectsCount} side effects logged — most common: ${input.topSideEffect}`,
});
}
if (input.streak >= 3) {
out.push({
id: "streak",
severity: "positive",
text: `Current streak: ${input.streak} days`,
});
}
const order = { warning: 0, positive: 1, info: 2 } as const;
return out.sort((a, b) => order[a.severity] - order[b.severity]).slice(0, 5);
}
// Mean abs-minute delta between fixed-time scheduled doses and actual
// taken time. Returns null when no fixed-time schedules or no taken
// doses fell on a med with such a schedule. Interval and PRN schedules
// are excluded — they have no anchor time to compare against.
export async function getScheduleVariance(
userId: string,
days: number,
timezone: string = "UTC",
range?: DateRange,
): Promise<{ avgMinutesOff: number; sampleSize: number } | null> {
const tz = validTimezones.has(timezone) ? timezone : "UTC";
const rows = await db
.select({
medicationId: doseLogs.medicationId,
takenAt: doseLogs.takenAt,
})
.from(doseLogs)
.where(buildDateFilters(userId, days, timezone, range));
if (rows.length === 0) return null;
const schedulesByMed = await getSchedulesForUser(userId);
// For each med, store fixed-time targets together with their
// daysOfWeek restriction (null = every day). At evaluation time we
// only consider targets whose daysOfWeek includes the dose's local
// weekday — otherwise a Mon-only schedule would match a Tue dose.
type FixedTarget = { minutes: number; daysOfWeek: number[] | null };
const fixedTimesByMed = new Map<string, FixedTarget[]>();
for (const [medId, schedules] of schedulesByMed) {
const targets: FixedTarget[] = [];
for (const s of schedules) {
if (s.scheduleKind !== "fixed_time" || !s.timeOfDay) continue;
const [hh, mm] = s.timeOfDay.split(":").map(Number);
if (!Number.isFinite(hh) || !Number.isFinite(mm)) continue;
const restrictedDays = s.daysOfWeek && s.daysOfWeek.length > 0 ? s.daysOfWeek : null;
targets.push({ minutes: hh * 60 + mm, daysOfWeek: restrictedDays });
}
if (targets.length > 0) fixedTimesByMed.set(medId, targets);
}
if (fixedTimesByMed.size === 0) return null;
// Format both wall-clock time and weekday in the user's tz so the
// dayOfWeek check matches the schedule's local day rather than UTC.
const localFmt = new Intl.DateTimeFormat("en-US", {
hour: "2-digit",
minute: "2-digit",
hour12: false,
weekday: "short",
timeZone: tz,
});
const weekdayMap: Record<string, number> = {
Sun: 0,
Mon: 1,
Tue: 2,
Wed: 3,
Thu: 4,
Fri: 5,
Sat: 6,
};
let total = 0;
let count = 0;
for (const row of rows) {
const targets = fixedTimesByMed.get(row.medicationId);
if (!targets) continue;
const parts = localFmt.formatToParts(new Date(row.takenAt));
const hour = Number(parts.find((p) => p.type === "hour")?.value);
const minute = Number(parts.find((p) => p.type === "minute")?.value);
const weekdayStr = parts.find((p) => p.type === "weekday")?.value ?? "";
const weekday = weekdayMap[weekdayStr];
if (!Number.isFinite(hour) || !Number.isFinite(minute) || weekday === undefined) continue;
const taken = hour * 60 + minute;
let best = Infinity;
for (const t of targets) {
if (t.daysOfWeek !== null && !t.daysOfWeek.includes(weekday)) continue;
const delta = Math.min(Math.abs(taken - t.minutes), 1440 - Math.abs(taken - t.minutes));
if (delta < best) best = delta;
}
if (best !== Infinity) {
total += best;
count++;
}
}
if (count === 0) return null;
return { avgMinutesOff: Math.round(total / count), sampleSize: count };
}
export async function getSideEffectStats(
userId: string,
days: number,
timezone: string = "UTC",
range?: DateRange,
) {
const rows = await db
.select({
sideEffects: doseLogs.sideEffects,
medicationName: medications.name,
})
.from(doseLogs)
.innerJoin(medications, eq(doseLogs.medicationId, medications.id))
.where(buildDateFilters(userId, days, timezone, range));
const effectCounts = new Map<string, { count: number; severities: Map<string, number> }>();
const medEffects = new Map<string, Map<string, number>>();
for (const row of rows) {
if (!row.sideEffects) continue;
for (const effect of row.sideEffects) {
const existing = effectCounts.get(effect.name) ?? {
count: 0,
severities: new Map(),
};
existing.count++;
existing.severities.set(effect.severity, (existing.severities.get(effect.severity) ?? 0) + 1);
effectCounts.set(effect.name, existing);
const medMap = medEffects.get(row.medicationName) ?? new Map();
medMap.set(effect.name, (medMap.get(effect.name) ?? 0) + 1);
medEffects.set(row.medicationName, medMap);
}
}
return {
frequency: [...effectCounts.entries()]
.map(([name, { count, severities }]) => ({
name,
count,
severities: Object.fromEntries(severities),
}))
.sort((a, b) => b.count - a.count),
byMedication: [...medEffects.entries()].map(([medication, effects]) => ({
medication,
effects: [...effects.entries()]
.map(([name, count]) => ({ name, count }))
.sort((a, b) => b.count - a.count),
})),
};
}