api/insights: add an app-timezone day helper
Day-granular insights need a boundary the server cannot give from its own process zone, which is UTC in the container. The helper resolves a day in America/Sao_Paulo so the window matches the user's local day
Pedro Lucas Porcellis porcellis@eletrotupi.com · 12 days ago
5f128778e17bb00138230b7adc25bc7e69505c1f Browse filesParents
4e0e578Changed files
1
Additions
+32
Deletions
0
api/src/lib/queue/processors/insights/utils.ts
1 +
import { tz } from "@date-fns/tz";
2 +
import { addDays, startOfDay } from "date-fns";
3 +
1 4
export function rollingPeriod(days = 7) {
2 5
const periodEnd = new Date();
3 6
const periodStart = new Date();
4 7
periodStart.setDate(periodEnd.getDate() - days);
5 8
6 9
return {
7 10
periodStart: periodStart.toISOString(),
8 11
periodEnd: periodEnd.toISOString(),
9 12
};
10 13
}
14 +
15 +
const APP_TIMEZONE = tz("America/Sao_Paulo");
16 +
17 +
// Start of the day containing `date`, in the app's timezone
18 +
export function startOfAppDay(date: Date = new Date()): Date {
19 +
return startOfDay(date, { in: APP_TIMEZONE });
20 +
}
21 +
22 +
// The app-timezone day containing `date`, as a half-open [start, end) window
23 +
export function appDayWindow(date: Date = new Date()): {
24 +
start: Date;
25 +
end: Date;
26 +
} {
27 +
const start = startOfDay(date, { in: APP_TIMEZONE });
28 +
const end = startOfDay(addDays(start, 1, { in: APP_TIMEZONE }), {
29 +
in: APP_TIMEZONE,
30 +
});
31 +
32 +
return { start, end };
33 +
}
34 +
35 +
export function appDayPeriod(date: Date = new Date()): {
36 +
periodStart: string;
37 +
periodEnd: string;
38 +
} {
39 +
const { start, end } = appDayWindow(date);
40 +
41 +
return { periodStart: start.toISOString(), periodEnd: end.toISOString() };
42 +
}