Spaces:
Runtime error

File size: 2,253 Bytes
ad79323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  addDays,
  addMonths,
  addYears,
  startOfMonth,
  startOfWeek,
  startOfYear,
} from "date-fns";
import { fromZonedTime, toZonedTime } from "date-fns-tz";

import type { CalendarViewValue, SessionDatePresetValue } from "@/lib/constants";
import { APP_TIME_ZONE } from "@/lib/constants";
import { AppError } from "@/server/errors";

function normalizeCairoDate(input?: Date | string) {
  return toZonedTime(input ? new Date(input) : new Date(), APP_TIME_ZONE);
}

function toUtc(date: Date) {
  return fromZonedTime(date, APP_TIME_ZONE);
}

export function parseCairoDateTimeInput(value: string) {
  const trimmed = value.trim();

  if (!trimmed) {
    throw new AppError("حدد التاريخ والوقت.", 400);
  }

  return fromZonedTime(trimmed, APP_TIME_ZONE);
}

export function getSessionRangeForPreset(
  preset: SessionDatePresetValue,
  now = new Date(),
) {
  if (preset === "all") {
    return undefined;
  }

  const zonedNow = normalizeCairoDate(now);
  const start = new Date(zonedNow);
  start.setHours(0, 0, 0, 0);

  if (preset === "today") {
    return {
      gte: toUtc(start),
      lt: toUtc(addDays(start, 1)),
    };
  }

  if (preset === "tomorrow") {
    const tomorrow = addDays(start, 1);
    return {
      gte: toUtc(tomorrow),
      lt: toUtc(addDays(tomorrow, 1)),
    };
  }

  if (preset === "thisWeek") {
    const weekStart = startOfWeek(start, { weekStartsOn: 6 });
    return {
      gte: toUtc(weekStart),
      lt: toUtc(addDays(weekStart, 7)),
    };
  }

  if (preset === "thisMonth") {
    const monthStart = startOfMonth(start);
    return {
      gte: toUtc(monthStart),
      lt: toUtc(addMonths(monthStart, 1)),
    };
  }

  const yearStart = startOfYear(start);
  return {
    gte: toUtc(yearStart),
    lt: toUtc(addYears(yearStart, 1)),
  };
}

export function getCalendarRange(
  view: CalendarViewValue,
  anchor?: string,
) {
  const zonedAnchor = normalizeCairoDate(anchor);
  const start =
    view === "week"
      ? startOfWeek(zonedAnchor, { weekStartsOn: 6 })
      : startOfMonth(zonedAnchor);
  const end = view === "week" ? addDays(start, 7) : addMonths(start, 1);

  return {
    start,
    end,
    gte: toUtc(start),
    lt: toUtc(end),
    anchor: toUtc(start),
  };
}