@managesome/eposmatic-toolkit 0.2.752 → 0.2.754

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,119 @@
1
+ import { DAY_INDEX_ENUM } from '../../constants';
2
+ import { IShiftWindowSource } from './shift-window-helpers';
3
+ /**
4
+ * Business-day resolution from shift windows — the "which day is the
5
+ * restaurant on?" logic shared by the backend day-open flow and the POS
6
+ * frontends (day label, staleness gating, week boards). All functions are
7
+ * pure; persistence (day sessions, running-day pointer) stays with callers.
8
+ *
9
+ * TWO complementary notions live here:
10
+ * - `resolveBusinessLocalDate` — the date a DAY STARTING NOW belongs to. Used
11
+ * by the backend `openTenantDay`: inside a running shift window it belongs to
12
+ * that window's start date (a store still inside Sunday's 9:00 AM – 2:00 AM
13
+ * window at Monday 12:30 AM opens SUNDAY); in closed hours the new day
14
+ * starts on the tenant's current calendar date.
15
+ * - `getCurrentBusinessDay` — the day the restaurant is CURRENTLY operating /
16
+ * most recently operated, per the POS label model: today once its first
17
+ * ACTIVE shift has started, otherwise the most recent scheduled day.
18
+ */
19
+ /** The default operational start (06:00, minutes from midnight) for legacy non-shift stores. */
20
+ export declare const DEFAULT_OPERATIONAL_START_TIME: number;
21
+ /**
22
+ * Resolves the BUSINESS DATE a moment belongs to, per the tenant's scheduled
23
+ * shift windows — "the restaurant's day", not the raw calendar date.
24
+ *
25
+ * - The moment falls INSIDE a scheduled shift window (overnight windows rolled
26
+ * past midnight) → the date of the day that window STARTED on. A store still
27
+ * inside Sunday's 9:00 AM – 2:00 AM window at Monday 12:30 AM is trading
28
+ * SUNDAY, so a day opened then must be stamped Sunday.
29
+ * - The moment falls in CLOSED hours (e.g. the 2:00 AM – 9:00 AM gap) → the
30
+ * tenant's current calendar date (a new day opened now starts on that date).
31
+ *
32
+ * Only `today`, `yesterday` and the day before are scanned: a shift range is
33
+ * capped at `end_time <= 2 * MS_IN_DAY` (the admin validator's bound), so a
34
+ * window that started earlier than that can never cover the moment. No active
35
+ * shifts at all → calendar date (legacy behavior).
36
+ */
37
+ export declare function resolveBusinessLocalDate(shifts: IShiftWindowSource[], gmtOffset: number, now?: Date): string;
38
+ /** The restaurant's current business day (see `getCurrentBusinessDay`). */
39
+ export interface ICurrentBusinessDay {
40
+ /** `YYYY-MM-DD` label of the business day. */
41
+ localDate: string;
42
+ /** POS-frame midnight of that day. */
43
+ dayMidnightMs: number;
44
+ /** Absolute POS-frame start of its first scheduled shift. */
45
+ firstShiftStartPosition: number;
46
+ /** Absolute POS-frame end of its last scheduled shift (overnight rolled). */
47
+ lastShiftEndPosition: number;
48
+ }
49
+ /**
50
+ * The restaurant's CURRENT business day: today once its first ACTIVE shift has
51
+ * started; otherwise the most recent scheduled day — walking back up to a week
52
+ * and skipping off-days. Before a day's first shift (overnight tail / pre-open
53
+ * gap) the previous business day still applies; on off-days the previous
54
+ * business day applies while its own last shift window runs (an overnight
55
+ * window can cross into a day with no shifts).
56
+ *
57
+ * `null` when the tenant has no active templates (legacy stores).
58
+ */
59
+ export declare function getCurrentBusinessDay(shifts: IShiftWindowSource[], gmtOffset: number, now?: Date): ICurrentBusinessDay | null;
60
+ /**
61
+ * Weekday (`DAY_INDEX_ENUM`) of the restaurant's current business day — what
62
+ * week boards should treat as "today" (e.g. 1:16 AM on Monday is still Sunday
63
+ * while the Sunday Mid-Night shift runs). `null` when no schedule exists;
64
+ * callers fall back to the POS-local calendar weekday.
65
+ */
66
+ export declare function getCurrentBusinessDayIndex(shifts: IShiftWindowSource[], gmtOffset: number, now?: Date): DAY_INDEX_ENUM | null;
67
+ /**
68
+ * True once the day AFTER `dayLocalDate` has effectively begun — the first
69
+ * ACTIVE shift scheduled for that weekday has started. This is the overnight
70
+ * grace: between midnight and the next business day's first shift the previous
71
+ * business day is still legitimately running.
72
+ *
73
+ * When the next calendar day is NOT a business day (nothing scheduled — e.g. a
74
+ * Friday night shift running into an off Saturday), there is no next-day shift
75
+ * to wait for, so the running day is judged by its OWN last shift window: it
76
+ * counts as finished once that window has ended, never at midnight while the
77
+ * shift still runs. No active templates at all → `true` (nothing to wait for).
78
+ */
79
+ export declare function hasNextDayFirstShiftStarted(shifts: IShiftWindowSource[], dayLocalDate: string, gmtOffset: number, now?: Date): boolean;
80
+ /**
81
+ * Counts how many successive business-day entries have happened since
82
+ * `dayLocalDate` — a "new day" counts only once it has effectively begun (its
83
+ * first ACTIVE shift has started), never at calendar midnight. Walks day by
84
+ * day through `hasNextDayFirstShiftStarted` and stops at the first boundary
85
+ * that has not been reached, so the count stays 0 while the running day is
86
+ * still legitimate (e.g. through an overnight tail), is 1 once the next
87
+ * business day has entered, 2 once the day after that has too — and so on.
88
+ * `maxDays` bounds the walk.
89
+ */
90
+ export declare function getBusinessDaysBehind(shifts: IShiftWindowSource[], dayLocalDate: string, gmtOffset: number, maxDays?: number, now?: Date): number;
91
+ /** Options for `getRestaurantDayLabel`. */
92
+ export interface IRestaurantDayLabelOptions {
93
+ /** Tenant's `operational_time_zone_offset_gmt`. */
94
+ gmtOffset: number;
95
+ /**
96
+ * THE shift-mode toggle (`isShiftMode`). Defaults to "the tenant has any
97
+ * active shift template" when omitted — the same rule the POS slice uses.
98
+ */
99
+ isShiftMode?: boolean;
100
+ /**
101
+ * Legacy (non-shift) stores: minutes from midnight when the day rolls.
102
+ * Defaults to `DEFAULT_OPERATIONAL_START_TIME` (06:00).
103
+ */
104
+ operationalStartTime?: number;
105
+ }
106
+ /**
107
+ * The restaurant-day label (`YYYY-MM-DD`, POS-local) for a moment — the day
108
+ * the tenant is actually on, never the raw calendar day.
109
+ *
110
+ * Restaurants come in two shapes and each has exactly ONE operational-hours
111
+ * source of truth (gated by `isShiftMode`):
112
+ * - Shift-enabled stores: the shifts ONLY — the day begins at TODAY's first
113
+ * ACTIVE shift start; before it (overnight tail / pre-open gap) the previous
114
+ * business day still applies, and on off-days the previous business day
115
+ * applies while its own last shift window runs.
116
+ * - Legacy stores: the day rolls at `operationalStartTime` (never at calendar
117
+ * midnight).
118
+ */
119
+ export declare function getRestaurantDayLabel(shifts: IShiftWindowSource[], options: IRestaurantDayLabelOptions, now?: Date): string;
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_OPERATIONAL_START_TIME = void 0;
4
+ exports.resolveBusinessLocalDate = resolveBusinessLocalDate;
5
+ exports.getCurrentBusinessDay = getCurrentBusinessDay;
6
+ exports.getCurrentBusinessDayIndex = getCurrentBusinessDayIndex;
7
+ exports.hasNextDayFirstShiftStarted = hasNextDayFirstShiftStarted;
8
+ exports.getBusinessDaysBehind = getBusinessDaysBehind;
9
+ exports.getRestaurantDayLabel = getRestaurantDayLabel;
10
+ const constants_1 = require("../../constants");
11
+ const shift_window_helpers_1 = require("./shift-window-helpers");
12
+ /**
13
+ * Business-day resolution from shift windows — the "which day is the
14
+ * restaurant on?" logic shared by the backend day-open flow and the POS
15
+ * frontends (day label, staleness gating, week boards). All functions are
16
+ * pure; persistence (day sessions, running-day pointer) stays with callers.
17
+ *
18
+ * TWO complementary notions live here:
19
+ * - `resolveBusinessLocalDate` — the date a DAY STARTING NOW belongs to. Used
20
+ * by the backend `openTenantDay`: inside a running shift window it belongs to
21
+ * that window's start date (a store still inside Sunday's 9:00 AM – 2:00 AM
22
+ * window at Monday 12:30 AM opens SUNDAY); in closed hours the new day
23
+ * starts on the tenant's current calendar date.
24
+ * - `getCurrentBusinessDay` — the day the restaurant is CURRENTLY operating /
25
+ * most recently operated, per the POS label model: today once its first
26
+ * ACTIVE shift has started, otherwise the most recent scheduled day.
27
+ */
28
+ /** The default operational start (06:00, minutes from midnight) for legacy non-shift stores. */
29
+ exports.DEFAULT_OPERATIONAL_START_TIME = 6 * 60;
30
+ /**
31
+ * Resolves the BUSINESS DATE a moment belongs to, per the tenant's scheduled
32
+ * shift windows — "the restaurant's day", not the raw calendar date.
33
+ *
34
+ * - The moment falls INSIDE a scheduled shift window (overnight windows rolled
35
+ * past midnight) → the date of the day that window STARTED on. A store still
36
+ * inside Sunday's 9:00 AM – 2:00 AM window at Monday 12:30 AM is trading
37
+ * SUNDAY, so a day opened then must be stamped Sunday.
38
+ * - The moment falls in CLOSED hours (e.g. the 2:00 AM – 9:00 AM gap) → the
39
+ * tenant's current calendar date (a new day opened now starts on that date).
40
+ *
41
+ * Only `today`, `yesterday` and the day before are scanned: a shift range is
42
+ * capped at `end_time <= 2 * MS_IN_DAY` (the admin validator's bound), so a
43
+ * window that started earlier than that can never cover the moment. No active
44
+ * shifts at all → calendar date (legacy behavior).
45
+ */
46
+ function resolveBusinessLocalDate(shifts, gmtOffset, now = new Date()) {
47
+ const frame = (0, shift_window_helpers_1.getTenantFramePosition)(gmtOffset, now);
48
+ // Most recent first: today, yesterday, then the day before (a maximally long
49
+ // 48h window covers into the day after its start).
50
+ for (let i = 0; i <= 2; i++) {
51
+ const dayMidnightMs = frame.dayMidnightMs - i * shift_window_helpers_1.MS_IN_DAY;
52
+ const dayIndex = constants_1.ALL_DAY_INDEX[new Date(dayMidnightMs).getUTCDay()];
53
+ for (const shift of (0, shift_window_helpers_1.getScheduledShiftsForDay)(shifts, dayIndex)) {
54
+ const startPosition = (0, shift_window_helpers_1.getShiftStartPosition)(dayMidnightMs, shift);
55
+ const endPosition = (0, shift_window_helpers_1.getShiftEndPosition)(dayMidnightMs, shift);
56
+ if (frame.nowPos >= startPosition && frame.nowPos <= endPosition) {
57
+ return (0, shift_window_helpers_1.formatLocalDateFromMidnight)(dayMidnightMs);
58
+ }
59
+ }
60
+ }
61
+ // Closed hours — the upcoming day is the tenant's current calendar date.
62
+ return (0, shift_window_helpers_1.formatLocalDateFromMidnight)(frame.dayMidnightMs);
63
+ }
64
+ /**
65
+ * The restaurant's CURRENT business day: today once its first ACTIVE shift has
66
+ * started; otherwise the most recent scheduled day — walking back up to a week
67
+ * and skipping off-days. Before a day's first shift (overnight tail / pre-open
68
+ * gap) the previous business day still applies; on off-days the previous
69
+ * business day applies while its own last shift window runs (an overnight
70
+ * window can cross into a day with no shifts).
71
+ *
72
+ * `null` when the tenant has no active templates (legacy stores).
73
+ */
74
+ function getCurrentBusinessDay(shifts, gmtOffset, now = new Date()) {
75
+ if (!shifts.some((shift) => shift.active === true))
76
+ return null;
77
+ const frame = (0, shift_window_helpers_1.getTenantFramePosition)(gmtOffset, now);
78
+ // Today first (once its first shift has started), else the most recent
79
+ // scheduled day — search back up to a week.
80
+ for (let i = 0; i <= 7; i++) {
81
+ const dayMidnightMs = frame.dayMidnightMs - i * shift_window_helpers_1.MS_IN_DAY;
82
+ const dayIndex = constants_1.ALL_DAY_INDEX[new Date(dayMidnightMs).getUTCDay()];
83
+ const firstShiftStartPosition = (0, shift_window_helpers_1.getFirstShiftStartPosition)(shifts, dayMidnightMs, dayIndex);
84
+ if (firstShiftStartPosition == null)
85
+ continue;
86
+ if (i === 0 && frame.timeMs < firstShiftStartPosition - dayMidnightMs)
87
+ continue;
88
+ const lastShiftEndPosition = (0, shift_window_helpers_1.getLastShiftEndPosition)(shifts, dayMidnightMs, dayIndex);
89
+ if (lastShiftEndPosition == null)
90
+ continue;
91
+ return {
92
+ localDate: (0, shift_window_helpers_1.formatLocalDateFromMidnight)(dayMidnightMs),
93
+ dayMidnightMs,
94
+ firstShiftStartPosition,
95
+ lastShiftEndPosition,
96
+ };
97
+ }
98
+ return null;
99
+ }
100
+ /**
101
+ * Weekday (`DAY_INDEX_ENUM`) of the restaurant's current business day — what
102
+ * week boards should treat as "today" (e.g. 1:16 AM on Monday is still Sunday
103
+ * while the Sunday Mid-Night shift runs). `null` when no schedule exists;
104
+ * callers fall back to the POS-local calendar weekday.
105
+ */
106
+ function getCurrentBusinessDayIndex(shifts, gmtOffset, now = new Date()) {
107
+ const currentDay = getCurrentBusinessDay(shifts, gmtOffset, now);
108
+ if (currentDay == null)
109
+ return null;
110
+ return constants_1.ALL_DAY_INDEX[new Date(currentDay.dayMidnightMs).getUTCDay()];
111
+ }
112
+ /**
113
+ * True once the day AFTER `dayLocalDate` has effectively begun — the first
114
+ * ACTIVE shift scheduled for that weekday has started. This is the overnight
115
+ * grace: between midnight and the next business day's first shift the previous
116
+ * business day is still legitimately running.
117
+ *
118
+ * When the next calendar day is NOT a business day (nothing scheduled — e.g. a
119
+ * Friday night shift running into an off Saturday), there is no next-day shift
120
+ * to wait for, so the running day is judged by its OWN last shift window: it
121
+ * counts as finished once that window has ended, never at midnight while the
122
+ * shift still runs. No active templates at all → `true` (nothing to wait for).
123
+ */
124
+ function hasNextDayFirstShiftStarted(shifts, dayLocalDate, gmtOffset, now = new Date()) {
125
+ if (!shifts.some((shift) => shift.active === true))
126
+ return true;
127
+ const frame = (0, shift_window_helpers_1.getTenantFramePosition)(gmtOffset, now);
128
+ const dayMidnightMs = (0, shift_window_helpers_1.getLocalDateMidnightMs)(dayLocalDate);
129
+ const nextDayMidnightMs = dayMidnightMs + shift_window_helpers_1.MS_IN_DAY;
130
+ const nextDayIndex = constants_1.ALL_DAY_INDEX[new Date(nextDayMidnightMs).getUTCDay()];
131
+ const firstNextStartPosition = (0, shift_window_helpers_1.getFirstShiftStartPosition)(shifts, nextDayMidnightMs, nextDayIndex);
132
+ if (firstNextStartPosition == null) {
133
+ const dayIndex = constants_1.ALL_DAY_INDEX[new Date(dayMidnightMs).getUTCDay()];
134
+ const lastEndPosition = (0, shift_window_helpers_1.getLastShiftEndPosition)(shifts, dayMidnightMs, dayIndex);
135
+ if (lastEndPosition == null)
136
+ return true;
137
+ return frame.nowPos >= lastEndPosition;
138
+ }
139
+ return frame.nowPos >= firstNextStartPosition;
140
+ }
141
+ /**
142
+ * Counts how many successive business-day entries have happened since
143
+ * `dayLocalDate` — a "new day" counts only once it has effectively begun (its
144
+ * first ACTIVE shift has started), never at calendar midnight. Walks day by
145
+ * day through `hasNextDayFirstShiftStarted` and stops at the first boundary
146
+ * that has not been reached, so the count stays 0 while the running day is
147
+ * still legitimate (e.g. through an overnight tail), is 1 once the next
148
+ * business day has entered, 2 once the day after that has too — and so on.
149
+ * `maxDays` bounds the walk.
150
+ */
151
+ function getBusinessDaysBehind(shifts, dayLocalDate, gmtOffset, maxDays = 31, now = new Date()) {
152
+ let cursor = dayLocalDate;
153
+ let behind = 0;
154
+ for (let i = 0; i < maxDays; i++) {
155
+ if (!hasNextDayFirstShiftStarted(shifts, cursor, gmtOffset, now))
156
+ break;
157
+ behind++;
158
+ cursor = (0, shift_window_helpers_1.addDaysToLocalDate)(cursor, 1);
159
+ }
160
+ return behind;
161
+ }
162
+ /**
163
+ * The restaurant-day label (`YYYY-MM-DD`, POS-local) for a moment — the day
164
+ * the tenant is actually on, never the raw calendar day.
165
+ *
166
+ * Restaurants come in two shapes and each has exactly ONE operational-hours
167
+ * source of truth (gated by `isShiftMode`):
168
+ * - Shift-enabled stores: the shifts ONLY — the day begins at TODAY's first
169
+ * ACTIVE shift start; before it (overnight tail / pre-open gap) the previous
170
+ * business day still applies, and on off-days the previous business day
171
+ * applies while its own last shift window runs.
172
+ * - Legacy stores: the day rolls at `operationalStartTime` (never at calendar
173
+ * midnight).
174
+ */
175
+ function getRestaurantDayLabel(shifts, options, now = new Date()) {
176
+ const frame = (0, shift_window_helpers_1.getTenantFramePosition)(options.gmtOffset, now);
177
+ const todayMidnightMs = frame.dayMidnightMs;
178
+ const isShiftMode = options.isShiftMode ?? shifts.some((shift) => shift.active === true);
179
+ if (isShiftMode) {
180
+ const todayIndex = constants_1.ALL_DAY_INDEX[new Date(todayMidnightMs).getUTCDay()];
181
+ const firstTodayStartPosition = (0, shift_window_helpers_1.getFirstShiftStartPosition)(shifts, todayMidnightMs, todayIndex);
182
+ if (firstTodayStartPosition != null) {
183
+ // Before today's first shift we are still on the previous business day
184
+ // (overnight tail / pre-open gap); from its start it is today.
185
+ return frame.nowPos >= firstTodayStartPosition
186
+ ? (0, shift_window_helpers_1.formatLocalDateFromMidnight)(todayMidnightMs)
187
+ : (0, shift_window_helpers_1.formatLocalDateFromMidnight)(todayMidnightMs - shift_window_helpers_1.MS_IN_DAY);
188
+ }
189
+ // Off-day: still the previous business day while ITS OWN last shift window
190
+ // is running (e.g. a Friday-night window crossing into an off Saturday).
191
+ for (let i = 1; i <= 7; i++) {
192
+ const dayMidnightMs = todayMidnightMs - i * shift_window_helpers_1.MS_IN_DAY;
193
+ const dayIndex = constants_1.ALL_DAY_INDEX[new Date(dayMidnightMs).getUTCDay()];
194
+ const lastEndPosition = (0, shift_window_helpers_1.getLastShiftEndPosition)(shifts, dayMidnightMs, dayIndex);
195
+ if (lastEndPosition == null)
196
+ continue;
197
+ return frame.nowPos >= lastEndPosition
198
+ ? (0, shift_window_helpers_1.formatLocalDateFromMidnight)(todayMidnightMs)
199
+ : (0, shift_window_helpers_1.formatLocalDateFromMidnight)(dayMidnightMs);
200
+ }
201
+ // No scheduled shifts in the last week → the day itself.
202
+ return (0, shift_window_helpers_1.formatLocalDateFromMidnight)(todayMidnightMs);
203
+ }
204
+ // Legacy stores: roll at the tenant's configured operational start, never at
205
+ // calendar midnight.
206
+ const startTimeMs = (options.operationalStartTime ?? exports.DEFAULT_OPERATIONAL_START_TIME) * 60 * 1000;
207
+ return frame.timeMs >= startTimeMs
208
+ ? (0, shift_window_helpers_1.formatLocalDateFromMidnight)(todayMidnightMs)
209
+ : (0, shift_window_helpers_1.formatLocalDateFromMidnight)(todayMidnightMs - shift_window_helpers_1.MS_IN_DAY);
210
+ }
@@ -1,4 +1,5 @@
1
1
  export * from './asaanbill-identifier-helpers';
2
+ export * from './business-day-helpers';
2
3
  export * from './cart-helpers';
3
4
  export * from './catalog-conversion';
4
5
  export * from './code-redemption-helpers';
@@ -55,6 +56,7 @@ export * from './sales-comparison-report-helpers';
55
56
  export * from './sales-comparitive-report-helpers';
56
57
  export * from './sales-overview-report-helpers';
57
58
  export * from './sales-summary-report-helpers';
59
+ export * from './shift-window-helpers';
58
60
  export * from './simplified-catalog';
59
61
  export * from './simplified-halfhalf';
60
62
  export * from './simplified-specials';
@@ -15,6 +15,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./asaanbill-identifier-helpers"), exports);
18
+ __exportStar(require("./business-day-helpers"), exports);
18
19
  __exportStar(require("./cart-helpers"), exports);
19
20
  __exportStar(require("./catalog-conversion"), exports);
20
21
  __exportStar(require("./code-redemption-helpers"), exports);
@@ -71,6 +72,7 @@ __exportStar(require("./sales-comparison-report-helpers"), exports);
71
72
  __exportStar(require("./sales-comparitive-report-helpers"), exports);
72
73
  __exportStar(require("./sales-overview-report-helpers"), exports);
73
74
  __exportStar(require("./sales-summary-report-helpers"), exports);
75
+ __exportStar(require("./shift-window-helpers"), exports);
74
76
  __exportStar(require("./simplified-catalog"), exports);
75
77
  __exportStar(require("./simplified-halfhalf"), exports);
76
78
  __exportStar(require("./simplified-specials"), exports);
@@ -0,0 +1,115 @@
1
+ import { DAY_INDEX_ENUM } from '../../constants';
2
+ /**
3
+ * Shared shift-window math for the business-day lifecycle — the single source
4
+ * of truth used by the backend (items-service day/shift/drawer sessions and
5
+ * guards), the POS frontend (day window, staleness gating) and the admin panel
6
+ * (shift-template validation).
7
+ *
8
+ * Time convention (the "POS frame"): every position produced here is an
9
+ * epoch-ms value in a frame where the tenant's local wall clock reads as UTC —
10
+ * `Date.UTC(...)` of the tenant's local date/time components. The frame is
11
+ * built from the tenant's `operational_time_zone_offset_gmt` (via
12
+ * `getTenantTime`), never from the runtime/server timezone, so the same
13
+ * instant yields the same positions in every process (backend, worker,
14
+ * browser).
15
+ *
16
+ * Shift templates (`ITenantInstoreShift`) store `start_time` / `end_time` as
17
+ * milliseconds from their START day's midnight. Overnight windows are normally
18
+ * stored with an `end_time` beyond 24h (e.g. 27:00:59.999 = 3:00:59.999 AM the
19
+ * next day); legacy/wrapped rows may instead carry `end_time <= start_time`,
20
+ * meaning the window crosses midnight — an equal start/end wraps a full +24h
21
+ * (the same `end <= start` convention the admin overlap validator documents).
22
+ */
23
+ /** Milliseconds in a day. */
24
+ export declare const MS_IN_DAY: number;
25
+ /**
26
+ * Minimal shift-template shape the window math reads — `ITenantInstoreShift`
27
+ * satisfies it structurally.
28
+ */
29
+ export interface IShiftWindowSource {
30
+ active: boolean;
31
+ day_indexes: DAY_INDEX_ENUM[];
32
+ start_time: number;
33
+ end_time: number;
34
+ }
35
+ /** A moment resolved into the tenant's POS frame (see module docs). */
36
+ export interface ITenantFramePosition {
37
+ /** The instant shifted into tenant wall-clock (`getTenantTime`). */
38
+ tenantTime: Date;
39
+ /** POS-frame epoch ms of the instant — comparable with every position here. */
40
+ nowPos: number;
41
+ /** POS-frame midnight of the tenant's current local calendar day. */
42
+ dayMidnightMs: number;
43
+ /** Milliseconds since the tenant's local midnight. */
44
+ timeMs: number;
45
+ }
46
+ /**
47
+ * Resolves an instant into the tenant's POS frame: `dayMidnightMs` is the
48
+ * tenant-local calendar day's midnight, `nowPos` the instant itself and
49
+ * `timeMs` the time since local midnight.
50
+ *
51
+ * Server-timezone independent — the wall-clock components are read off the
52
+ * `getTenantTime`-shifted date with local getters (the same convention as
53
+ * `getLocalDocumentFields`).
54
+ */
55
+ export declare function getTenantFramePosition(gmtOffset: number, now?: Date): ITenantFramePosition;
56
+ /** `YYYY-MM-DD` of a POS-frame midnight (UTC getters — deterministic). */
57
+ export declare function formatLocalDateFromMidnight(dayMidnightMs: number): string;
58
+ /**
59
+ * The tenant's current local calendar date (`YYYY-MM-DD`) — the raw clock date
60
+ * in the tenant's timezone, NOT the business date. Use
61
+ * `resolveBusinessLocalDate` / `getCurrentBusinessDay` when the restaurant-day
62
+ * is meant.
63
+ */
64
+ export declare function getTenantLocalDate(gmtOffset: number, now?: Date): string;
65
+ /** POS-frame midnight (ms) of a `YYYY-MM-DD` local date. */
66
+ export declare function getLocalDateMidnightMs(localDate: string): number;
67
+ /** `2026-09-13` + 1 → `2026-09-14` — plain calendar date-string math. */
68
+ export declare function addDaysToLocalDate(localDate: string, days: number): string;
69
+ /**
70
+ * End position of a shift window (absolute POS-frame ms): `dayMidnightMs +
71
+ * end_time`, rolled a full day for wrapped shifts (`end_time <= start_time`).
72
+ * A stored `end_time` beyond 24h rolls naturally past midnight.
73
+ */
74
+ export declare function getShiftEndPosition(dayMidnightMs: number, shift: Pick<IShiftWindowSource, 'start_time' | 'end_time'>): number;
75
+ /** Start position of a shift window (absolute POS-frame ms). */
76
+ export declare function getShiftStartPosition(dayMidnightMs: number, shift: Pick<IShiftWindowSource, 'start_time'>): number;
77
+ /** ACTIVE shifts scheduled for a weekday (`day_indexes` includes it). */
78
+ export declare function getScheduledShiftsForDay<T extends IShiftWindowSource>(shifts: T[], dayIndex: DAY_INDEX_ENUM): T[];
79
+ /** Last end position among a day's scheduled shifts (absolute), or null when none. */
80
+ export declare function getLastShiftEndPosition(shifts: IShiftWindowSource[], dayMidnightMs: number, dayIndex: DAY_INDEX_ENUM): number | null;
81
+ /** Earliest start position among a day's scheduled shifts (absolute), or null when none. */
82
+ export declare function getFirstShiftStartPosition(shifts: IShiftWindowSource[], dayMidnightMs: number, dayIndex: DAY_INDEX_ENUM): number | null;
83
+ /**
84
+ * Whether a new business day may be started for a CLOSED day (mirrors the POS
85
+ * `dayWindow` / the backend day guard): the closed day's `localDate` must be
86
+ * BEHIND the tenant's current local date AND the previous day must have fully
87
+ * elapsed — `now` is past the LAST end position of the shifts scheduled on the
88
+ * closed day's weekday.
89
+ *
90
+ * Returns `null` when there is no anchor to decide with (no shift scheduled on
91
+ * the closed day's weekday or on the next day's weekday) — callers apply their
92
+ * legacy fallback (e.g. "a new day may start only when none is running").
93
+ */
94
+ export declare function canStartNewBusinessDay(shifts: IShiftWindowSource[], dayLocalDate: string, gmtOffset: number, now?: Date): boolean | null;
95
+ /**
96
+ * Normalizes a shift time-range into coverage intervals on the
97
+ * `[0, 2 * MS_IN_DAY)` timeline so overnight windows (`end_time <= start_time`)
98
+ * are handled directly — `22:00–02:00` covers `[22:00, 24:00]` + `[00:00,
99
+ * 02:00]`. Same wrap convention as `getShiftEndPosition` (equal start/end
100
+ * wraps a full day).
101
+ */
102
+ export declare function getShiftCoverageIntervals(startTime: number, endTime: number): [number, number][];
103
+ /**
104
+ * Whether two shift time-ranges overlap. Half-open intervals — back-to-back
105
+ * shifts (one ends exactly when the other starts) do NOT conflict. Day
106
+ * (`day_indexes`) and tenant matching stay with the caller (e.g. the admin
107
+ * panel's shift-template conflict finder).
108
+ */
109
+ export declare function doShiftWindowsOverlap(a: {
110
+ start_time: number;
111
+ end_time: number;
112
+ }, b: {
113
+ start_time: number;
114
+ end_time: number;
115
+ }): boolean;
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MS_IN_DAY = void 0;
4
+ exports.getTenantFramePosition = getTenantFramePosition;
5
+ exports.formatLocalDateFromMidnight = formatLocalDateFromMidnight;
6
+ exports.getTenantLocalDate = getTenantLocalDate;
7
+ exports.getLocalDateMidnightMs = getLocalDateMidnightMs;
8
+ exports.addDaysToLocalDate = addDaysToLocalDate;
9
+ exports.getShiftEndPosition = getShiftEndPosition;
10
+ exports.getShiftStartPosition = getShiftStartPosition;
11
+ exports.getScheduledShiftsForDay = getScheduledShiftsForDay;
12
+ exports.getLastShiftEndPosition = getLastShiftEndPosition;
13
+ exports.getFirstShiftStartPosition = getFirstShiftStartPosition;
14
+ exports.canStartNewBusinessDay = canStartNewBusinessDay;
15
+ exports.getShiftCoverageIntervals = getShiftCoverageIntervals;
16
+ exports.doShiftWindowsOverlap = doShiftWindowsOverlap;
17
+ const constants_1 = require("../../constants");
18
+ const time_helpers_1 = require("./time-helpers");
19
+ /**
20
+ * Shared shift-window math for the business-day lifecycle — the single source
21
+ * of truth used by the backend (items-service day/shift/drawer sessions and
22
+ * guards), the POS frontend (day window, staleness gating) and the admin panel
23
+ * (shift-template validation).
24
+ *
25
+ * Time convention (the "POS frame"): every position produced here is an
26
+ * epoch-ms value in a frame where the tenant's local wall clock reads as UTC —
27
+ * `Date.UTC(...)` of the tenant's local date/time components. The frame is
28
+ * built from the tenant's `operational_time_zone_offset_gmt` (via
29
+ * `getTenantTime`), never from the runtime/server timezone, so the same
30
+ * instant yields the same positions in every process (backend, worker,
31
+ * browser).
32
+ *
33
+ * Shift templates (`ITenantInstoreShift`) store `start_time` / `end_time` as
34
+ * milliseconds from their START day's midnight. Overnight windows are normally
35
+ * stored with an `end_time` beyond 24h (e.g. 27:00:59.999 = 3:00:59.999 AM the
36
+ * next day); legacy/wrapped rows may instead carry `end_time <= start_time`,
37
+ * meaning the window crosses midnight — an equal start/end wraps a full +24h
38
+ * (the same `end <= start` convention the admin overlap validator documents).
39
+ */
40
+ /** Milliseconds in a day. */
41
+ exports.MS_IN_DAY = 24 * 60 * 60 * 1000;
42
+ /**
43
+ * Resolves an instant into the tenant's POS frame: `dayMidnightMs` is the
44
+ * tenant-local calendar day's midnight, `nowPos` the instant itself and
45
+ * `timeMs` the time since local midnight.
46
+ *
47
+ * Server-timezone independent — the wall-clock components are read off the
48
+ * `getTenantTime`-shifted date with local getters (the same convention as
49
+ * `getLocalDocumentFields`).
50
+ */
51
+ function getTenantFramePosition(gmtOffset, now = new Date()) {
52
+ const tenantTime = (0, time_helpers_1.getTenantTime)(gmtOffset, now);
53
+ const dayMidnightMs = Date.UTC(tenantTime.getFullYear(), tenantTime.getMonth(), tenantTime.getDate());
54
+ const timeMs = ((tenantTime.getHours() * 60 + tenantTime.getMinutes()) * 60 + tenantTime.getSeconds()) * 1000 +
55
+ tenantTime.getMilliseconds();
56
+ return { tenantTime, nowPos: dayMidnightMs + timeMs, dayMidnightMs, timeMs };
57
+ }
58
+ /** `YYYY-MM-DD` of a POS-frame midnight (UTC getters — deterministic). */
59
+ function formatLocalDateFromMidnight(dayMidnightMs) {
60
+ const date = new Date(dayMidnightMs);
61
+ return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}-${String(date.getUTCDate()).padStart(2, '0')}`;
62
+ }
63
+ /**
64
+ * The tenant's current local calendar date (`YYYY-MM-DD`) — the raw clock date
65
+ * in the tenant's timezone, NOT the business date. Use
66
+ * `resolveBusinessLocalDate` / `getCurrentBusinessDay` when the restaurant-day
67
+ * is meant.
68
+ */
69
+ function getTenantLocalDate(gmtOffset, now = new Date()) {
70
+ return formatLocalDateFromMidnight(getTenantFramePosition(gmtOffset, now).dayMidnightMs);
71
+ }
72
+ /** POS-frame midnight (ms) of a `YYYY-MM-DD` local date. */
73
+ function getLocalDateMidnightMs(localDate) {
74
+ const [localYear, localMonth, localDay] = localDate.split('-').map(Number);
75
+ return Date.UTC(localYear, localMonth - 1, localDay);
76
+ }
77
+ /** `2026-09-13` + 1 → `2026-09-14` — plain calendar date-string math. */
78
+ function addDaysToLocalDate(localDate, days) {
79
+ return formatLocalDateFromMidnight(getLocalDateMidnightMs(localDate) + days * exports.MS_IN_DAY);
80
+ }
81
+ /**
82
+ * End position of a shift window (absolute POS-frame ms): `dayMidnightMs +
83
+ * end_time`, rolled a full day for wrapped shifts (`end_time <= start_time`).
84
+ * A stored `end_time` beyond 24h rolls naturally past midnight.
85
+ */
86
+ function getShiftEndPosition(dayMidnightMs, shift) {
87
+ return dayMidnightMs + (shift.end_time <= shift.start_time ? exports.MS_IN_DAY : 0) + shift.end_time;
88
+ }
89
+ /** Start position of a shift window (absolute POS-frame ms). */
90
+ function getShiftStartPosition(dayMidnightMs, shift) {
91
+ return dayMidnightMs + shift.start_time;
92
+ }
93
+ /** ACTIVE shifts scheduled for a weekday (`day_indexes` includes it). */
94
+ function getScheduledShiftsForDay(shifts, dayIndex) {
95
+ return shifts.filter((shift) => shift.active === true && shift.day_indexes.includes(dayIndex));
96
+ }
97
+ /** Last end position among a day's scheduled shifts (absolute), or null when none. */
98
+ function getLastShiftEndPosition(shifts, dayMidnightMs, dayIndex) {
99
+ const dayShifts = getScheduledShiftsForDay(shifts, dayIndex);
100
+ if (!dayShifts.length)
101
+ return null;
102
+ return dayShifts.reduce((latest, shift) => Math.max(latest, getShiftEndPosition(dayMidnightMs, shift)), 0);
103
+ }
104
+ /** Earliest start position among a day's scheduled shifts (absolute), or null when none. */
105
+ function getFirstShiftStartPosition(shifts, dayMidnightMs, dayIndex) {
106
+ const dayShifts = getScheduledShiftsForDay(shifts, dayIndex);
107
+ if (!dayShifts.length)
108
+ return null;
109
+ return dayShifts.reduce((earliest, shift) => Math.min(earliest, getShiftStartPosition(dayMidnightMs, shift)), Infinity);
110
+ }
111
+ /**
112
+ * Whether a new business day may be started for a CLOSED day (mirrors the POS
113
+ * `dayWindow` / the backend day guard): the closed day's `localDate` must be
114
+ * BEHIND the tenant's current local date AND the previous day must have fully
115
+ * elapsed — `now` is past the LAST end position of the shifts scheduled on the
116
+ * closed day's weekday.
117
+ *
118
+ * Returns `null` when there is no anchor to decide with (no shift scheduled on
119
+ * the closed day's weekday or on the next day's weekday) — callers apply their
120
+ * legacy fallback (e.g. "a new day may start only when none is running").
121
+ */
122
+ function canStartNewBusinessDay(shifts, dayLocalDate, gmtOffset, now = new Date()) {
123
+ const frame = getTenantFramePosition(gmtOffset, now);
124
+ const dayMidnightMs = getLocalDateMidnightMs(dayLocalDate);
125
+ const nextDayMidnightMs = dayMidnightMs + exports.MS_IN_DAY;
126
+ const dayIndex = constants_1.ALL_DAY_INDEX[new Date(dayMidnightMs).getUTCDay()];
127
+ const nextDayIndex = constants_1.ALL_DAY_INDEX[new Date(nextDayMidnightMs).getUTCDay()];
128
+ const lastEndPosition = getLastShiftEndPosition(shifts, dayMidnightMs, dayIndex);
129
+ const firstNextStartPosition = getFirstShiftStartPosition(shifts, nextDayMidnightMs, nextDayIndex);
130
+ // No shift anchor → the caller applies its legacy fallback.
131
+ if (lastEndPosition == null || firstNextStartPosition == null)
132
+ return null;
133
+ const dayBehind = dayLocalDate < formatLocalDateFromMidnight(frame.dayMidnightMs);
134
+ const pastLastShiftEnd = frame.nowPos > lastEndPosition;
135
+ return dayBehind && pastLastShiftEnd;
136
+ }
137
+ /**
138
+ * Normalizes a shift time-range into coverage intervals on the
139
+ * `[0, 2 * MS_IN_DAY)` timeline so overnight windows (`end_time <= start_time`)
140
+ * are handled directly — `22:00–02:00` covers `[22:00, 24:00]` + `[00:00,
141
+ * 02:00]`. Same wrap convention as `getShiftEndPosition` (equal start/end
142
+ * wraps a full day).
143
+ */
144
+ function getShiftCoverageIntervals(startTime, endTime) {
145
+ const normalizedEnd = endTime <= startTime ? endTime + exports.MS_IN_DAY : endTime;
146
+ if (normalizedEnd <= exports.MS_IN_DAY) {
147
+ return [[startTime, normalizedEnd]];
148
+ }
149
+ return [
150
+ [startTime, exports.MS_IN_DAY],
151
+ [0, normalizedEnd - exports.MS_IN_DAY],
152
+ ];
153
+ }
154
+ /**
155
+ * Whether two shift time-ranges overlap. Half-open intervals — back-to-back
156
+ * shifts (one ends exactly when the other starts) do NOT conflict. Day
157
+ * (`day_indexes`) and tenant matching stay with the caller (e.g. the admin
158
+ * panel's shift-template conflict finder).
159
+ */
160
+ function doShiftWindowsOverlap(a, b) {
161
+ const aCoverage = getShiftCoverageIntervals(a.start_time, a.end_time);
162
+ const bCoverage = getShiftCoverageIntervals(b.start_time, b.end_time);
163
+ return aCoverage.some(([aStart, aEnd]) => bCoverage.some(([bStart, bEnd]) => aStart < bEnd && bStart < aEnd));
164
+ }
@@ -19,9 +19,9 @@ export declare const TenantHrShiftScheduleSchema: Schema<any, import("mongoose")
19
19
  start_date: NativeDate;
20
20
  end_date: NativeDate;
21
21
  status: HR_SHIFT_STATUS_ENUM;
22
+ day_indexes: string[];
22
23
  notes: string;
23
24
  employee_id: string;
24
- day_indexes: string[];
25
25
  template_id: string;
26
26
  }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
27
27
  createdAt: NativeDate;
@@ -38,9 +38,9 @@ export declare const TenantHrShiftScheduleSchema: Schema<any, import("mongoose")
38
38
  start_date: NativeDate;
39
39
  end_date: NativeDate;
40
40
  status: HR_SHIFT_STATUS_ENUM;
41
+ day_indexes: string[];
41
42
  notes: string;
42
43
  employee_id: string;
43
- day_indexes: string[];
44
44
  template_id: string;
45
45
  }>> & import("mongoose").FlatRecord<{
46
46
  createdAt: NativeDate;
@@ -57,9 +57,9 @@ export declare const TenantHrShiftScheduleSchema: Schema<any, import("mongoose")
57
57
  start_date: NativeDate;
58
58
  end_date: NativeDate;
59
59
  status: HR_SHIFT_STATUS_ENUM;
60
+ day_indexes: string[];
60
61
  notes: string;
61
62
  employee_id: string;
62
- day_indexes: string[];
63
63
  template_id: string;
64
64
  }> & Required<{
65
65
  _id: import("mongoose").Types.ObjectId;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../constants");
4
+ const business_day_helpers_1 = require("../helpers/utils/business-day-helpers");
5
+ const shift_window_helpers_1 = require("../helpers/utils/shift-window-helpers");
6
+ const shift = (start_time, end_time, day_indexes = constants_1.ALL_DAY_INDEX) => ({
7
+ active: true,
8
+ day_indexes,
9
+ start_time,
10
+ end_time,
11
+ });
12
+ const NO_MONDAY = constants_1.ALL_DAY_INDEX.filter((day) => day !== constants_1.DAY_INDEX_ENUM.MON);
13
+ // 2026-09-13 = Sunday, 2026-09-14 = Monday, 2026-09-15 = Tuesday.
14
+ const at = (y, m, d, hh, mm) => new Date(Date.UTC(y, m - 1, d, hh, mm));
15
+ // Production shift sets.
16
+ const R1 = [shift(32400000, 61199999), shift(61200000, 97259999)]; // Day 9-17, Night 17-27:00:59.999
17
+ const R1_NO_MONDAY = [shift(32400000, 61199999, NO_MONDAY), shift(61200000, 97259999, NO_MONDAY)];
18
+ const R2 = [
19
+ shift(32400000, 46799999),
20
+ shift(46800000, 61199999),
21
+ shift(61200000, 82799999),
22
+ shift(82800000, 104399999),
23
+ ]; // Mid-Night 23:00-28:59:59.999
24
+ const R5 = [shift(32400000, 57599999), shift(57600000, 93659999)]; // Night 16:00-26:00:59.999
25
+ describe('resolveBusinessLocalDate', () => {
26
+ it('keeps the previous date while its overnight window runs (the reported bug)', () => {
27
+ // Monday 12:30 AM is still inside Sunday's Night window (ends Mon 03:00:59.999).
28
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R1, 0, at(2026, 9, 14, 0, 30))).toBe('2026-09-13');
29
+ });
30
+ it('still resolves Sunday at the last moment of the window', () => {
31
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R1, 0, new Date(Date.UTC(2026, 8, 14, 3, 0, 59)))).toBe('2026-09-13');
32
+ });
33
+ it('switches to the calendar date in closed hours', () => {
34
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R1, 0, at(2026, 9, 14, 3, 1))).toBe('2026-09-14');
35
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R1, 0, at(2026, 9, 14, 8, 59))).toBe('2026-09-14');
36
+ });
37
+ it('resolves the window start date mid-window on the next day', () => {
38
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R1, 0, at(2026, 9, 15, 1, 0))).toBe('2026-09-14');
39
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R1, 0, at(2026, 9, 15, 3, 1))).toBe('2026-09-15');
40
+ });
41
+ it('resolves the same instant identically under a different tenant offset', () => {
42
+ // UTC Sunday 12:30 = tenant (UTC+12) Monday 00:30 → still Sunday.
43
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R1, 12, new Date(Date.UTC(2026, 8, 13, 12, 30)))).toBe('2026-09-13');
44
+ });
45
+ it('handles long overnight windows per restaurant (R2 ends 05:00:59.999, R5 ends 02:00:59.999)', () => {
46
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R2, 0, at(2026, 9, 15, 4, 59))).toBe('2026-09-14');
47
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R2, 0, at(2026, 9, 15, 5, 1))).toBe('2026-09-15');
48
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R5, 0, at(2026, 9, 14, 0, 30))).toBe('2026-09-13');
49
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(R5, 0, at(2026, 9, 14, 2, 1))).toBe('2026-09-14');
50
+ });
51
+ it('covers the full schema-valid window range (48h shift scheduled only on Sunday)', () => {
52
+ const longOvernight = [shift(0, 2 * shift_window_helpers_1.MS_IN_DAY, [constants_1.DAY_INDEX_ENUM.SUN])];
53
+ // Sunday 00:00 + 48h ends exactly at Tuesday 00:00 — still that Sunday's day.
54
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(longOvernight, 0, at(2026, 9, 15, 0, 0))).toBe('2026-09-13');
55
+ // A minute later the window has ended → Tuesday's calendar date.
56
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)(longOvernight, 0, at(2026, 9, 15, 0, 1))).toBe('2026-09-15');
57
+ });
58
+ it('falls back to the calendar date when there are no shifts', () => {
59
+ expect((0, business_day_helpers_1.resolveBusinessLocalDate)([], 0, at(2026, 9, 14, 0, 30))).toBe('2026-09-14');
60
+ });
61
+ });
62
+ describe('getCurrentBusinessDay', () => {
63
+ it('is still the previous day before the next first shift (Mon 00:30)', () => {
64
+ expect((0, business_day_helpers_1.getCurrentBusinessDay)(R1, 0, at(2026, 9, 14, 0, 30))?.localDate).toBe('2026-09-13');
65
+ });
66
+ it('is today once its first shift has started (Mon 10:00)', () => {
67
+ expect((0, business_day_helpers_1.getCurrentBusinessDay)(R1, 0, at(2026, 9, 14, 10, 0))?.localDate).toBe('2026-09-14');
68
+ });
69
+ it('skips off-days and reports the last scheduled business day', () => {
70
+ // Monday has no shifts — before AND after Sunday's window the current
71
+ // business day stays the last scheduled day (Sunday).
72
+ expect((0, business_day_helpers_1.getCurrentBusinessDay)(R1_NO_MONDAY, 0, at(2026, 9, 14, 0, 30))?.localDate).toBe('2026-09-13');
73
+ expect((0, business_day_helpers_1.getCurrentBusinessDay)(R1_NO_MONDAY, 0, at(2026, 9, 14, 10, 0))?.localDate).toBe('2026-09-13');
74
+ });
75
+ it('returns null without active templates', () => {
76
+ expect((0, business_day_helpers_1.getCurrentBusinessDay)([], 0, at(2026, 9, 14, 10, 0))).toBeNull();
77
+ });
78
+ });
79
+ describe('getCurrentBusinessDayIndex', () => {
80
+ it('maps the business day to its weekday', () => {
81
+ expect((0, business_day_helpers_1.getCurrentBusinessDayIndex)(R1, 0, at(2026, 9, 14, 0, 30))).toBe(constants_1.DAY_INDEX_ENUM.SUN);
82
+ expect((0, business_day_helpers_1.getCurrentBusinessDayIndex)(R1, 0, at(2026, 9, 14, 10, 0))).toBe(constants_1.DAY_INDEX_ENUM.MON);
83
+ });
84
+ });
85
+ describe('hasNextDayFirstShiftStarted', () => {
86
+ it('waits for the next day first shift (Monday 09:00)', () => {
87
+ expect((0, business_day_helpers_1.hasNextDayFirstShiftStarted)(R1, '2026-09-13', 0, at(2026, 9, 14, 0, 30))).toBe(false);
88
+ expect((0, business_day_helpers_1.hasNextDayFirstShiftStarted)(R1, '2026-09-13', 0, at(2026, 9, 14, 9, 0))).toBe(true);
89
+ });
90
+ it('falls back to the running day own last shift end on an off-day', () => {
91
+ // Monday has no shifts → Sunday's window (ends Mon 03:00:59.999) governs.
92
+ expect((0, business_day_helpers_1.hasNextDayFirstShiftStarted)(R1_NO_MONDAY, '2026-09-13', 0, at(2026, 9, 13, 23, 0))).toBe(false);
93
+ expect((0, business_day_helpers_1.hasNextDayFirstShiftStarted)(R1_NO_MONDAY, '2026-09-13', 0, at(2026, 9, 14, 10, 0))).toBe(true);
94
+ });
95
+ it('returns true without active templates', () => {
96
+ expect((0, business_day_helpers_1.hasNextDayFirstShiftStarted)([], '2026-09-13', 0, at(2026, 9, 14, 0, 30))).toBe(true);
97
+ });
98
+ });
99
+ describe('getBusinessDaysBehind', () => {
100
+ it('counts business-day entries, not calendar midnights', () => {
101
+ expect((0, business_day_helpers_1.getBusinessDaysBehind)(R1, '2026-09-13', 0, 31, at(2026, 9, 14, 0, 30))).toBe(0);
102
+ expect((0, business_day_helpers_1.getBusinessDaysBehind)(R1, '2026-09-13', 0, 31, at(2026, 9, 14, 8, 59))).toBe(0);
103
+ expect((0, business_day_helpers_1.getBusinessDaysBehind)(R1, '2026-09-13', 0, 31, at(2026, 9, 14, 9, 29))).toBe(1);
104
+ expect((0, business_day_helpers_1.getBusinessDaysBehind)(R1, '2026-09-13', 0, 31, at(2026, 9, 15, 9, 29))).toBe(2);
105
+ });
106
+ });
107
+ describe('getRestaurantDayLabel', () => {
108
+ it('uses the shift windows for shift stores', () => {
109
+ expect((0, business_day_helpers_1.getRestaurantDayLabel)(R1, { gmtOffset: 0 }, at(2026, 9, 14, 0, 30))).toBe('2026-09-13');
110
+ expect((0, business_day_helpers_1.getRestaurantDayLabel)(R1, { gmtOffset: 0 }, at(2026, 9, 14, 9, 30))).toBe('2026-09-14');
111
+ });
112
+ it('keeps the previous label through an off-day tail, then rolls to the off-day', () => {
113
+ expect((0, business_day_helpers_1.getRestaurantDayLabel)(R1_NO_MONDAY, { gmtOffset: 0 }, at(2026, 9, 14, 0, 30))).toBe('2026-09-13');
114
+ expect((0, business_day_helpers_1.getRestaurantDayLabel)(R1_NO_MONDAY, { gmtOffset: 0 }, at(2026, 9, 14, 10, 0))).toBe('2026-09-14');
115
+ });
116
+ it('rolls legacy stores at the operational start, never at midnight', () => {
117
+ const legacy = { gmtOffset: 0, isShiftMode: false, operationalStartTime: 360 };
118
+ expect((0, business_day_helpers_1.getRestaurantDayLabel)([], legacy, at(2026, 9, 14, 5, 0))).toBe('2026-09-13');
119
+ expect((0, business_day_helpers_1.getRestaurantDayLabel)([], legacy, at(2026, 9, 14, 7, 0))).toBe('2026-09-14');
120
+ });
121
+ it('defaults the legacy operational start to 06:00', () => {
122
+ const legacy = { gmtOffset: 0, isShiftMode: false };
123
+ expect((0, business_day_helpers_1.getRestaurantDayLabel)([], legacy, at(2026, 9, 14, 5, 59))).toBe('2026-09-13');
124
+ expect((0, business_day_helpers_1.getRestaurantDayLabel)([], legacy, at(2026, 9, 14, 6, 0))).toBe('2026-09-14');
125
+ });
126
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../constants");
4
+ const shift_window_helpers_1 = require("../helpers/utils/shift-window-helpers");
5
+ const MINUTE = 60 * 1000;
6
+ const HOUR = 60 * MINUTE;
7
+ const shift = (start_time, end_time, day_indexes = constants_1.ALL_DAY_INDEX) => ({
8
+ active: true,
9
+ day_indexes,
10
+ start_time,
11
+ end_time,
12
+ });
13
+ const NO_MONDAY = constants_1.ALL_DAY_INDEX.filter((day) => day !== constants_1.DAY_INDEX_ENUM.MON);
14
+ // Production shift sets (Auckland Thai Lemon: Day 9:00-17:00, Night 17:00-27:00:59.999).
15
+ const R1 = [shift(32400000, 61199999), shift(61200000, 97259999)];
16
+ const R1_NO_MONDAY = [shift(32400000, 61199999, NO_MONDAY), shift(61200000, 97259999, NO_MONDAY)];
17
+ // 2026-09-13 = Sunday, 2026-09-14 = Monday, 2026-09-15 = Tuesday.
18
+ const at = (y, m, d, hh, mm, ss = 0) => new Date(Date.UTC(y, m - 1, d, hh, mm, ss));
19
+ describe('getShiftEndPosition', () => {
20
+ const dayMidnightMs = (0, shift_window_helpers_1.getLocalDateMidnightMs)('2026-09-14');
21
+ it('uses end_time directly for same-day windows', () => {
22
+ expect((0, shift_window_helpers_1.getShiftEndPosition)(dayMidnightMs, shift(9 * HOUR, 17 * HOUR - 1))).toBe(dayMidnightMs + 61199999);
23
+ });
24
+ it('rolls naturally past midnight when end_time exceeds 24h', () => {
25
+ // 17:00 -> 27:00:59.999 = 3:00:59.999 AM the next day.
26
+ expect((0, shift_window_helpers_1.getShiftEndPosition)(dayMidnightMs, shift(17 * HOUR, 97259999))).toBe(dayMidnightMs + 97259999);
27
+ });
28
+ it('adds a day for wrapped legacy windows (end_time < start_time)', () => {
29
+ expect((0, shift_window_helpers_1.getShiftEndPosition)(dayMidnightMs, shift(23 * HOUR, 2 * HOUR))).toBe(dayMidnightMs + shift_window_helpers_1.MS_IN_DAY + 2 * HOUR);
30
+ });
31
+ it('treats equal start/end as a full +24h wrap (canonical convention)', () => {
32
+ expect((0, shift_window_helpers_1.getShiftEndPosition)(dayMidnightMs, shift(9 * HOUR, 9 * HOUR))).toBe(dayMidnightMs + shift_window_helpers_1.MS_IN_DAY + 9 * HOUR);
33
+ });
34
+ });
35
+ describe('getTenantFramePosition / formatLocalDateFromMidnight', () => {
36
+ it('resolves the tenant frame for zero offset', () => {
37
+ const frame = (0, shift_window_helpers_1.getTenantFramePosition)(0, at(2026, 9, 14, 0, 30));
38
+ expect(frame.dayMidnightMs).toBe(Date.UTC(2026, 8, 14));
39
+ expect(frame.timeMs).toBe(30 * MINUTE);
40
+ expect(frame.nowPos).toBe(Date.UTC(2026, 8, 14, 0, 30));
41
+ });
42
+ it('resolves the tenant frame across an offset (UTC Sun 12:30 → tenant Mon 00:30)', () => {
43
+ const frame = (0, shift_window_helpers_1.getTenantFramePosition)(12, new Date(Date.UTC(2026, 8, 13, 12, 30)));
44
+ expect((0, shift_window_helpers_1.formatLocalDateFromMidnight)(frame.dayMidnightMs)).toBe('2026-09-14');
45
+ expect(frame.timeMs).toBe(30 * MINUTE);
46
+ });
47
+ it('round-trips local date strings through midnights', () => {
48
+ expect((0, shift_window_helpers_1.formatLocalDateFromMidnight)((0, shift_window_helpers_1.getLocalDateMidnightMs)('2026-09-13'))).toBe('2026-09-13');
49
+ expect((0, shift_window_helpers_1.formatLocalDateFromMidnight)((0, shift_window_helpers_1.getLocalDateMidnightMs)('2026-12-31') + shift_window_helpers_1.MS_IN_DAY)).toBe('2027-01-01');
50
+ });
51
+ it('resolves the tenant local calendar date (raw clock date)', () => {
52
+ expect((0, shift_window_helpers_1.getTenantLocalDate)(0, at(2026, 9, 14, 0, 30))).toBe('2026-09-14');
53
+ // UTC Sunday 12:30 = tenant (UTC+12) Monday 00:30.
54
+ expect((0, shift_window_helpers_1.getTenantLocalDate)(12, new Date(Date.UTC(2026, 8, 13, 12, 30)))).toBe('2026-09-14');
55
+ });
56
+ });
57
+ describe('canStartNewBusinessDay', () => {
58
+ it('blocks while the closed day window is still running (Mon 00:30)', () => {
59
+ expect((0, shift_window_helpers_1.canStartNewBusinessDay)(R1, '2026-09-13', 0, at(2026, 9, 14, 0, 30))).toBe(false);
60
+ });
61
+ it('still blocks at the last millisecond of the window (Mon 03:00:59)', () => {
62
+ expect((0, shift_window_helpers_1.canStartNewBusinessDay)(R1, '2026-09-13', 0, at(2026, 9, 14, 3, 0, 59))).toBe(false);
63
+ });
64
+ it('allows once past the last shift end and the date has rolled (Mon 03:01)', () => {
65
+ expect((0, shift_window_helpers_1.canStartNewBusinessDay)(R1, '2026-09-13', 0, at(2026, 9, 14, 3, 1))).toBe(true);
66
+ });
67
+ it('blocks while the closed date is still the current date', () => {
68
+ expect((0, shift_window_helpers_1.canStartNewBusinessDay)(R1, '2026-09-13', 0, at(2026, 9, 13, 23, 0))).toBe(false);
69
+ });
70
+ it('returns null when there is no shift anchor (off-day next weekday / no shifts)', () => {
71
+ expect((0, shift_window_helpers_1.canStartNewBusinessDay)(R1_NO_MONDAY, '2026-09-13', 0, at(2026, 9, 14, 3, 1))).toBeNull();
72
+ expect((0, shift_window_helpers_1.canStartNewBusinessDay)([], '2026-09-13', 0, at(2026, 9, 14, 3, 1))).toBeNull();
73
+ });
74
+ });
75
+ describe('getShiftCoverageIntervals / doShiftWindowsOverlap', () => {
76
+ it('splits an overnight range across midnight', () => {
77
+ expect((0, shift_window_helpers_1.getShiftCoverageIntervals)(23 * HOUR, 2 * HOUR)).toEqual([
78
+ [23 * HOUR, shift_window_helpers_1.MS_IN_DAY],
79
+ [0, 2 * HOUR],
80
+ ]);
81
+ });
82
+ it('keeps same-day ranges intact', () => {
83
+ expect((0, shift_window_helpers_1.getShiftCoverageIntervals)(9 * HOUR, 17 * HOUR)).toEqual([[9 * HOUR, 17 * HOUR]]);
84
+ });
85
+ it('detects overlapping overnight windows', () => {
86
+ expect((0, shift_window_helpers_1.doShiftWindowsOverlap)(shift(22 * HOUR, 2 * HOUR), shift(23 * HOUR, 3 * HOUR))).toBe(true);
87
+ });
88
+ it('allows back-to-back shifts (one ends exactly when the other starts)', () => {
89
+ expect((0, shift_window_helpers_1.doShiftWindowsOverlap)(shift(9 * HOUR, 17 * HOUR), shift(17 * HOUR, 26 * HOUR))).toBe(false);
90
+ });
91
+ it('treats equal start/end as a 24h-covering window', () => {
92
+ expect((0, shift_window_helpers_1.doShiftWindowsOverlap)(shift(9 * HOUR, 9 * HOUR), shift(12 * HOUR, 13 * HOUR))).toBe(true);
93
+ });
94
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.2.752",
3
+ "version": "0.2.754",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",