eletrotupi / tcc/ api/src/lib/queue/processors/insights/utils.tsde0605fcb0d1980cedfafe4830a7aeaef31de5dc
1.5 KB | 53 lines Raw
1
import { tz } from "@date-fns/tz";
2
import { addDays, startOfDay, subDays } from "date-fns";
3

4
export function rollingPeriod(days = 7) {
5
  const periodEnd = new Date();
6
  const periodStart = new Date();
7
  periodStart.setDate(periodEnd.getDate() - days);
8

9
  return {
10
    periodStart: periodStart.toISOString(),
11
    periodEnd: periodEnd.toISOString(),
12
  };
13
}
14

15
const APP_TIMEZONE = tz("America/Sao_Paulo");
16

17
// pt-BR label for the app-timezone day window, kept beside the window helpers
18
// so the wording and the window it names live in one place
19
export const DAY_WINDOW_LABEL = "hoje";
20

21
// Start of the day containing `date`, in the app's timezone
22
export function startOfAppDay(date: Date = new Date()): Date {
23
  return startOfDay(date, { in: APP_TIMEZONE });
24
}
25

26
// Start of the app-timezone day immediately before the one containing `date`
27
export function previousAppDay(date: Date = new Date()): Date {
28
  return startOfDay(subDays(date, 1, { in: APP_TIMEZONE }), {
29
    in: APP_TIMEZONE,
30
  });
31
}
32

33
// The app-timezone day containing `date`, as a half-open [start, end) window
34
export function appDayWindow(date: Date = new Date()): {
35
  start: Date;
36
  end: Date;
37
} {
38
  const start = startOfDay(date, { in: APP_TIMEZONE });
39
  const end = startOfDay(addDays(start, 1, { in: APP_TIMEZONE }), {
40
    in: APP_TIMEZONE,
41
  });
42

43
  return { start, end };
44
}
45

46
export function appDayPeriod(date: Date = new Date()): {
47
  periodStart: string;
48
  periodEnd: string;
49
} {
50
  const { start, end } = appDayWindow(date);
51

52
  return { periodStart: start.toISOString(), periodEnd: end.toISOString() };
53
}