eletrotupi / tcc/ api/src/lib/queue/processors/insights/utils.tsb36ca93521cd90a436cca219f26ba8cb906448f4
1.7 KB | 58 lines Raw
1
import { tz } from "@date-fns/tz";
2
import { addDays, parse, 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
// Start of the app-timezone day named by a YYYY-MM-DD string
34
export function parseAppDay(day: string): Date {
35
  return parse(day, "yyyy-MM-dd", new Date(), { in: APP_TIMEZONE });
36
}
37

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

48
  return { start, end };
49
}
50

51
export function appDayPeriod(date: Date = new Date()): {
52
  periodStart: string;
53
  periodEnd: string;
54
} {
55
  const { start, end } = appDayWindow(date);
56

57
  return { periodStart: start.toISOString(), periodEnd: end.toISOString() };
58
}