@managesome/eposmatic-toolkit 0.4.21 → 0.4.23

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.
Files changed (22) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +9 -3
  2. package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +148 -9
  3. package/esm/schemas/models/materialized_rider_daily_reports.js +0 -4
  4. package/esm/schemas/models/materialized_tenant_discount_reports.js +6 -2
  5. package/esm/schemas/models/tenant_hr_attendance_records.js +5 -6
  6. package/esm/schemas/models/tenant_hr_shift_schedules.js +1 -1
  7. package/lib/constants/MATERIALIZED_REPORTS.d.ts +9 -0
  8. package/lib/constants/MATERIALIZED_REPORTS.js +9 -3
  9. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +19 -0
  10. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +148 -8
  11. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +3 -2
  12. package/lib/schemas/models/materialized_rider_daily_reports.js +0 -4
  13. package/lib/schemas/models/materialized_tenant_discount_reports.d.ts +6 -6
  14. package/lib/schemas/models/materialized_tenant_discount_reports.js +6 -2
  15. package/lib/schemas/models/tenant_hr_attendance_records.d.ts +3 -3
  16. package/lib/schemas/models/tenant_hr_attendance_records.js +5 -6
  17. package/lib/schemas/models/tenant_hr_shift_schedules.d.ts +3 -3
  18. package/lib/schemas/models/tenant_hr_shift_schedules.js +1 -1
  19. package/lib/schemas/types/tenant_hr_attendance_records.d.ts +1 -1
  20. package/lib/schemas/types/tenant_hr_shift_schedules.d.ts +1 -1
  21. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +108 -4
  22. package/package.json +1 -1
@@ -127,6 +127,15 @@ export const SALES_OVERVIEW_KEY_FILTERS = [
127
127
  * (`materialized_tenant_discount_entries`), capped at `LOCAL_MONTH` so a
128
128
  * document can never grow unboundedly.
129
129
  *
130
+ * DELIBERATELY MONTH-CAPPED: quarter / semester / year are NOT materialized.
131
+ * The entry documents accumulate every day's rows for their scope, so a
132
+ * quarter-scoped entry document grows without a natural bound and can reach the
133
+ * 16 MB document ceiling at high volume (the credit-ledger reason). The
134
+ * counter documents would be safe to widen, but the scope list is shared by
135
+ * BOTH collections and the entries are the binding constraint. A selection that
136
+ * decodes to a wider scope is refused by the historical route
137
+ * (`allowedScopeContexts`), never silently narrowed to a month.
138
+ *
130
139
  * The report documents themselves are COUNTERS ONLY (see
131
140
  * `schemas/types/materialized_tenant_discount_reports.ts`).
132
141
  */
@@ -136,9 +145,6 @@ export const MATERIALIZED_DISCOUNT_REPORT_SCOPES = [
136
145
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
137
146
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
138
147
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
139
- MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
140
- MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
141
- MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
142
148
  ];
143
149
  /** Ordered key filters of the discounts report (`COMPLETED:POS_WALK-IN`). */
144
150
  export const DISCOUNTS_KEY_FILTERS = [
@@ -1,6 +1,6 @@
1
1
  import { MATERIALIZED_DISCOUNT_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
2
2
  import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
3
- import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields } from './scope-helpers';
3
+ import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields, parseMaterializedLocalDate, } from './scope-helpers';
4
4
  /** Day-scoped documents (replaced wholesale for the compiled day). */
5
5
  const DISCOUNT_DAY_SCOPES = [
6
6
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
@@ -34,6 +34,131 @@ export function getMaterializedDiscountScopeRefsForDay(localDate) {
34
34
  }
35
35
  return refs;
36
36
  }
37
+ /* ------------------------------------------------------------------------ */
38
+ /* Period sibling-day enumeration (the close-day fetch contract) */
39
+ /* ------------------------------------------------------------------------ */
40
+ const pad2 = (value) => String(value).padStart(2, '0');
41
+ /** `'YYYY-MM-DD'` of a UTC calendar date. */
42
+ const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
43
+ /** Adds whole days to a UTC calendar date. */
44
+ const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
45
+ const daysInUtcMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
46
+ /** Adds every day of `count` whole months starting at (year, month). */
47
+ const addMonthDays = (year, month, count, days) => {
48
+ for (let offset = 0; offset < count; offset += 1) {
49
+ const date = new Date(Date.UTC(year, month - 1 + offset, 1));
50
+ const monthYear = date.getUTCFullYear();
51
+ const monthNumber = date.getUTCMonth() + 1;
52
+ const last = daysInUtcMonth(monthYear, monthNumber);
53
+ for (let day = 1; day <= last; day += 1) {
54
+ days.add(`${monthYear}-${pad2(monthNumber)}-${pad2(day)}`);
55
+ }
56
+ }
57
+ return true;
58
+ };
59
+ /**
60
+ * Adds the day labels covered by ONE stored period scope value to `days`.
61
+ *
62
+ * Returns `false` (never throws) for a malformed / non-canonical scope value —
63
+ * a caller must not silently treat an unparseable period as "no sibling days",
64
+ * because that would make the `existingEntriesComplete` acknowledgement lie.
65
+ */
66
+ const addPeriodDays = (scope, scopeField, days) => {
67
+ switch (scope) {
68
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
69
+ // Sunday-based week start (the `localWeek` bucket identity).
70
+ const parts = parseMaterializedLocalDate(scopeField);
71
+ if (parts == null)
72
+ return false;
73
+ const start = new Date(Date.UTC(parts.year, parts.month - 1, parts.day));
74
+ if (start.getUTCDay() !== 0)
75
+ return false;
76
+ for (let offset = 0; offset < 7; offset += 1)
77
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
78
+ return true;
79
+ }
80
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
81
+ // ISO week: the week-year may differ from the calendar year at boundaries.
82
+ const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
83
+ if (match == null)
84
+ return false;
85
+ const weekYear = Number(match[1]);
86
+ const week = Number(match[2]);
87
+ if (!Number.isInteger(week) || week < 1 || week > 53)
88
+ return false;
89
+ // ISO week 1 always contains Jan 4; its Monday is the week-1 Monday.
90
+ const jan4 = new Date(Date.UTC(weekYear, 0, 4));
91
+ const isoWeekday = jan4.getUTCDay() || 7;
92
+ const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
93
+ const start = addUtcDays(weekOneMonday, (week - 1) * 7);
94
+ for (let offset = 0; offset < 7; offset += 1)
95
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
96
+ return true;
97
+ }
98
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH: {
99
+ const match = /^(\d{4})-(\d{2})$/.exec(scopeField);
100
+ if (match == null)
101
+ return false;
102
+ const year = Number(match[1]);
103
+ const month = Number(match[2]);
104
+ if (month < 1 || month > 12)
105
+ return false;
106
+ return addMonthDays(year, month, 1, days);
107
+ }
108
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER: {
109
+ const match = /^(\d{4})-Q([1-4])$/.exec(scopeField);
110
+ if (match == null)
111
+ return false;
112
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 3 + 1, 3, days);
113
+ }
114
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER: {
115
+ const match = /^(\d{4})-S([12])$/.exec(scopeField);
116
+ if (match == null)
117
+ return false;
118
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 6 + 1, 6, days);
119
+ }
120
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR: {
121
+ const match = /^(\d{4})$/.exec(scopeField);
122
+ if (match == null)
123
+ return false;
124
+ return addMonthDays(Number(match[1]), 1, 12, days);
125
+ }
126
+ default:
127
+ return false;
128
+ }
129
+ };
130
+ /**
131
+ * Every `localDate` day label whose day-scoped ENTRY documents can belong to the
132
+ * periods the closing day rolls into (`week`, ISO week, month — whatever
133
+ * `MATERIALIZED_DISCOUNT_REPORT_SCOPES` accumulates).
134
+ *
135
+ * This is the **sibling-day fetch contract** in code: a close caller must fetch
136
+ * every `localDate` entry document whose `scope_field` is in this set, in
137
+ * addition to the day's own scope refs. Period entry documents are DERIVED from
138
+ * day rows, so a period document that was never persisted can only be rebuilt
139
+ * from the sibling days — without them the plan rebuilds the period from the
140
+ * closing day alone and every other day silently disappears from the period
141
+ * drill-down (see `buildTenantDiscountCloseDayPlan`).
142
+ *
143
+ * The returned set always contains `localDate` itself and is sorted. Returns
144
+ * `null` (never throws) for a malformed date or an unparseable period value —
145
+ * a `null` means the caller must fail loudly rather than pass an incomplete
146
+ * `existingEntries` set with `existingEntriesComplete: true`.
147
+ */
148
+ export function getMaterializedDiscountPeriodDayScopeFields(localDate) {
149
+ const periodFields = getMaterializedPeriodScopeFields(localDate);
150
+ if (periodFields == null)
151
+ return null;
152
+ const days = new Set([localDate]);
153
+ for (const scope of DISCOUNT_ACCUMULATED_SCOPES) {
154
+ const scopeField = periodFields[scope];
155
+ if (typeof scopeField !== 'string' || scopeField.length === 0)
156
+ return null;
157
+ if (!addPeriodDays(scope, scopeField, days))
158
+ return null;
159
+ }
160
+ return [...days].sort();
161
+ }
37
162
  /**
38
163
  * Watermark guard: does the stored document need a structural write?
39
164
  * `false` (skip) when the incoming `source_watermark` is not newer than the
@@ -587,15 +712,29 @@ export function buildTenantDiscountCloseDayPlan(input) {
587
712
  doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
588
713
  continue;
589
714
  }
590
- // A PERIOD entry document must drop this day's rows: rows never accumulate,
591
- // so a period doc carries the whole period's rows. When the day lost its
592
- // rows the period doc is rebuilt from the compile's period entry sections
593
- // (which the compile already produces per period scope).
594
- const periodCompiled = compiledEntriesByScope.get(scopeKey(doc));
595
- if (periodCompiled == null) {
596
- // No rows left anywhere in this period scope for the compiled day — the
597
- // caller's fetch includes it only when the compile emitted it, so drop it.
715
+ // The compiled day has no rows in this period scope. That does NOT mean the
716
+ // period is empty: a period entry document accumulates EVERY day's rows, so
717
+ // deleting it would wipe the sibling days that exist nowhere else. Subtract
718
+ // the rows this day currently contributes (read from its day-scoped entry
719
+ // documents) and drop the document only when nothing remains.
720
+ const remaining = subtractMaterializedDiscountEntrySections(doc.discount_entries, storedDayEntrySections);
721
+ const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
722
+ const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
723
+ // Nothing of this day was in that period: leave it untouched.
724
+ if (rowsAfter === rowsBefore)
725
+ continue;
726
+ if (rowsAfter === 0) {
598
727
  staleEntryDocuments.push(doc);
728
+ continue;
729
+ }
730
+ if (addEntryWrite({
731
+ ...doc,
732
+ discount_entries: remaining,
733
+ computed_at: computedAt,
734
+ updatedAt: computedAt,
735
+ iteration: (doc.iteration ?? 1) + 1,
736
+ }) == null) {
737
+ return null;
599
738
  }
600
739
  }
601
740
  return {
@@ -34,10 +34,6 @@ export const MATERIALIZED_RIDER_DAILY_REPORTS_COLLECTION_INDEXES = {
34
34
  _id: { _id: 1 },
35
35
  rider_id__local_date: { rider_id: 1, local_date: 1 },
36
36
  };
37
- MaterializedRiderDailyReportSchema.index(MATERIALIZED_RIDER_DAILY_REPORTS_COLLECTION_INDEXES.rider_id__local_date, {
38
- unique: true,
39
- name: 'rider_id__local_date',
40
- });
41
37
  export const MATERIALIZED_RIDER_DAILY_REPORTS_INDEX_OPTIONS = [
42
38
  {
43
39
  key: MATERIALIZED_RIDER_DAILY_REPORTS_COLLECTION_INDEXES.rider_id__local_date,
@@ -168,15 +168,19 @@ export const MaterializedTenantDiscountReportSchema = new Schema({
168
168
  // `materialized_tenant_discount_entries`. Empty map = a day with no
169
169
  // discounts (kept so watermark comparisons stay uniform).
170
170
  discount_counters: {
171
+ // NULLABLE BY CONTRACT (see the type module): a corrected/emptied period
172
+ // document legitimately holds no keys. `required: true` rejected exactly
173
+ // that close-day output at write time.
171
174
  type: Schema.Types.Mixed,
172
- required: true,
175
+ required: false,
173
176
  default: null,
174
177
  },
175
178
  // The SAME counters as an ARRAY OF ROWS — the read-path shape (see the type
176
179
  // module). Mixed because the counter tree varies per key.
177
180
  discount_counter_rows: {
181
+ // Mirrors `discount_counters`: null when the map is empty.
178
182
  type: Schema.Types.Mixed,
179
- required: true,
183
+ required: false,
180
184
  default: null,
181
185
  },
182
186
  top_sources: {
@@ -54,6 +54,11 @@ export const TenantHrAttendanceRecordSchema = new Schema({
54
54
  required: true,
55
55
  match: /^\d{4}-\d{2}-\d{2}$/,
56
56
  },
57
+ schedule_id: {
58
+ type: String,
59
+ required: true,
60
+ ref: 'tenant_hr_shift_schedules',
61
+ },
57
62
  clock_time: {
58
63
  type: [hrClockTimeSchema],
59
64
  default: [],
@@ -76,10 +81,6 @@ export const TenantHrAttendanceRecordSchema = new Schema({
76
81
  enum: ALL_HR_ATTENDANCE_STATUS_NAMES,
77
82
  default: HR_ATTENDANCE_STATUS_ENUM.PRESENT,
78
83
  },
79
- notes: {
80
- type: String,
81
- default: null,
82
- },
83
84
  createdAt: {
84
85
  type: Schema.Types.Date,
85
86
  required: true,
@@ -96,6 +97,4 @@ export const TenantHrAttendanceRecordSchema = new Schema({
96
97
  versionKey: false,
97
98
  minimize: false,
98
99
  });
99
- TenantHrAttendanceRecordSchema.index({ tenant_id: 1, employee_id: 1, attendance_date: 1 }, { unique: true });
100
- TenantHrAttendanceRecordSchema.index({ tenant_id: 1, attendance_date: 1 });
101
100
  export const TENANT_HR_ATTENDANCE_RECORDS_COLLECTION_NAME = 'tenant_hr_attendance_records';
@@ -60,7 +60,7 @@ export const TenantHrShiftScheduleSchema = new Schema({
60
60
  type: String,
61
61
  default: null,
62
62
  },
63
- template_id: {
63
+ shift_id: {
64
64
  type: String,
65
65
  default: null,
66
66
  ref: 'tenant_hr_shifts',
@@ -99,6 +99,15 @@ export declare const SALES_OVERVIEW_KEY_FILTERS: MATERIALIZED_REPORT_KEY_FILTER_
99
99
  * (`materialized_tenant_discount_entries`), capped at `LOCAL_MONTH` so a
100
100
  * document can never grow unboundedly.
101
101
  *
102
+ * DELIBERATELY MONTH-CAPPED: quarter / semester / year are NOT materialized.
103
+ * The entry documents accumulate every day's rows for their scope, so a
104
+ * quarter-scoped entry document grows without a natural bound and can reach the
105
+ * 16 MB document ceiling at high volume (the credit-ledger reason). The
106
+ * counter documents would be safe to widen, but the scope list is shared by
107
+ * BOTH collections and the entries are the binding constraint. A selection that
108
+ * decodes to a wider scope is refused by the historical route
109
+ * (`allowedScopeContexts`), never silently narrowed to a month.
110
+ *
102
111
  * The report documents themselves are COUNTERS ONLY (see
103
112
  * `schemas/types/materialized_tenant_discount_reports.ts`).
104
113
  */
@@ -131,6 +131,15 @@ exports.SALES_OVERVIEW_KEY_FILTERS = [
131
131
  * (`materialized_tenant_discount_entries`), capped at `LOCAL_MONTH` so a
132
132
  * document can never grow unboundedly.
133
133
  *
134
+ * DELIBERATELY MONTH-CAPPED: quarter / semester / year are NOT materialized.
135
+ * The entry documents accumulate every day's rows for their scope, so a
136
+ * quarter-scoped entry document grows without a natural bound and can reach the
137
+ * 16 MB document ceiling at high volume (the credit-ledger reason). The
138
+ * counter documents would be safe to widen, but the scope list is shared by
139
+ * BOTH collections and the entries are the binding constraint. A selection that
140
+ * decodes to a wider scope is refused by the historical route
141
+ * (`allowedScopeContexts`), never silently narrowed to a month.
142
+ *
134
143
  * The report documents themselves are COUNTERS ONLY (see
135
144
  * `schemas/types/materialized_tenant_discount_reports.ts`).
136
145
  */
@@ -140,9 +149,6 @@ exports.MATERIALIZED_DISCOUNT_REPORT_SCOPES = [
140
149
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
141
150
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
142
151
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
143
- MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
144
- MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
145
- MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
146
152
  ];
147
153
  /** Ordered key filters of the discounts report (`COMPLETED:POS_WALK-IN`). */
148
154
  exports.DISCOUNTS_KEY_FILTERS = [
@@ -118,6 +118,25 @@ export interface ITenantDiscountCloseDayPlan {
118
118
  }
119
119
  /** Every stored scope one local day's plan needs (date + 3 periods + 24 hours). */
120
120
  export declare function getMaterializedDiscountScopeRefsForDay(localDate: string): IMaterializedDiscountScopeRef[] | null;
121
+ /**
122
+ * Every `localDate` day label whose day-scoped ENTRY documents can belong to the
123
+ * periods the closing day rolls into (`week`, ISO week, month — whatever
124
+ * `MATERIALIZED_DISCOUNT_REPORT_SCOPES` accumulates).
125
+ *
126
+ * This is the **sibling-day fetch contract** in code: a close caller must fetch
127
+ * every `localDate` entry document whose `scope_field` is in this set, in
128
+ * addition to the day's own scope refs. Period entry documents are DERIVED from
129
+ * day rows, so a period document that was never persisted can only be rebuilt
130
+ * from the sibling days — without them the plan rebuilds the period from the
131
+ * closing day alone and every other day silently disappears from the period
132
+ * drill-down (see `buildTenantDiscountCloseDayPlan`).
133
+ *
134
+ * The returned set always contains `localDate` itself and is sorted. Returns
135
+ * `null` (never throws) for a malformed date or an unparseable period value —
136
+ * a `null` means the caller must fail loudly rather than pass an incomplete
137
+ * `existingEntries` set with `existingEntriesComplete: true`.
138
+ */
139
+ export declare function getMaterializedDiscountPeriodDayScopeFields(localDate: string): string[] | null;
121
140
  /**
122
141
  * Watermark guard: does the stored document need a structural write?
123
142
  * `false` (skip) when the incoming `source_watermark` is not newer than the
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.subtractMaterializedDiscountEntrySections = exports.mergeMaterializedDiscountEntrySections = void 0;
4
4
  exports.getMaterializedDiscountScopeRefsForDay = getMaterializedDiscountScopeRefsForDay;
5
+ exports.getMaterializedDiscountPeriodDayScopeFields = getMaterializedDiscountPeriodDayScopeFields;
5
6
  exports.needsMaterializedDiscountReportWrite = needsMaterializedDiscountReportWrite;
6
7
  exports.updateMaterializedDiscountReport = updateMaterializedDiscountReport;
7
8
  exports.updateMaterializedDiscountEntries = updateMaterializedDiscountEntries;
@@ -43,6 +44,131 @@ function getMaterializedDiscountScopeRefsForDay(localDate) {
43
44
  }
44
45
  return refs;
45
46
  }
47
+ /* ------------------------------------------------------------------------ */
48
+ /* Period sibling-day enumeration (the close-day fetch contract) */
49
+ /* ------------------------------------------------------------------------ */
50
+ const pad2 = (value) => String(value).padStart(2, '0');
51
+ /** `'YYYY-MM-DD'` of a UTC calendar date. */
52
+ const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
53
+ /** Adds whole days to a UTC calendar date. */
54
+ const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
55
+ const daysInUtcMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
56
+ /** Adds every day of `count` whole months starting at (year, month). */
57
+ const addMonthDays = (year, month, count, days) => {
58
+ for (let offset = 0; offset < count; offset += 1) {
59
+ const date = new Date(Date.UTC(year, month - 1 + offset, 1));
60
+ const monthYear = date.getUTCFullYear();
61
+ const monthNumber = date.getUTCMonth() + 1;
62
+ const last = daysInUtcMonth(monthYear, monthNumber);
63
+ for (let day = 1; day <= last; day += 1) {
64
+ days.add(`${monthYear}-${pad2(monthNumber)}-${pad2(day)}`);
65
+ }
66
+ }
67
+ return true;
68
+ };
69
+ /**
70
+ * Adds the day labels covered by ONE stored period scope value to `days`.
71
+ *
72
+ * Returns `false` (never throws) for a malformed / non-canonical scope value —
73
+ * a caller must not silently treat an unparseable period as "no sibling days",
74
+ * because that would make the `existingEntriesComplete` acknowledgement lie.
75
+ */
76
+ const addPeriodDays = (scope, scopeField, days) => {
77
+ switch (scope) {
78
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
79
+ // Sunday-based week start (the `localWeek` bucket identity).
80
+ const parts = (0, scope_helpers_1.parseMaterializedLocalDate)(scopeField);
81
+ if (parts == null)
82
+ return false;
83
+ const start = new Date(Date.UTC(parts.year, parts.month - 1, parts.day));
84
+ if (start.getUTCDay() !== 0)
85
+ return false;
86
+ for (let offset = 0; offset < 7; offset += 1)
87
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
88
+ return true;
89
+ }
90
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
91
+ // ISO week: the week-year may differ from the calendar year at boundaries.
92
+ const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
93
+ if (match == null)
94
+ return false;
95
+ const weekYear = Number(match[1]);
96
+ const week = Number(match[2]);
97
+ if (!Number.isInteger(week) || week < 1 || week > 53)
98
+ return false;
99
+ // ISO week 1 always contains Jan 4; its Monday is the week-1 Monday.
100
+ const jan4 = new Date(Date.UTC(weekYear, 0, 4));
101
+ const isoWeekday = jan4.getUTCDay() || 7;
102
+ const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
103
+ const start = addUtcDays(weekOneMonday, (week - 1) * 7);
104
+ for (let offset = 0; offset < 7; offset += 1)
105
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
106
+ return true;
107
+ }
108
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH: {
109
+ const match = /^(\d{4})-(\d{2})$/.exec(scopeField);
110
+ if (match == null)
111
+ return false;
112
+ const year = Number(match[1]);
113
+ const month = Number(match[2]);
114
+ if (month < 1 || month > 12)
115
+ return false;
116
+ return addMonthDays(year, month, 1, days);
117
+ }
118
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER: {
119
+ const match = /^(\d{4})-Q([1-4])$/.exec(scopeField);
120
+ if (match == null)
121
+ return false;
122
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 3 + 1, 3, days);
123
+ }
124
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER: {
125
+ const match = /^(\d{4})-S([12])$/.exec(scopeField);
126
+ if (match == null)
127
+ return false;
128
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 6 + 1, 6, days);
129
+ }
130
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR: {
131
+ const match = /^(\d{4})$/.exec(scopeField);
132
+ if (match == null)
133
+ return false;
134
+ return addMonthDays(Number(match[1]), 1, 12, days);
135
+ }
136
+ default:
137
+ return false;
138
+ }
139
+ };
140
+ /**
141
+ * Every `localDate` day label whose day-scoped ENTRY documents can belong to the
142
+ * periods the closing day rolls into (`week`, ISO week, month — whatever
143
+ * `MATERIALIZED_DISCOUNT_REPORT_SCOPES` accumulates).
144
+ *
145
+ * This is the **sibling-day fetch contract** in code: a close caller must fetch
146
+ * every `localDate` entry document whose `scope_field` is in this set, in
147
+ * addition to the day's own scope refs. Period entry documents are DERIVED from
148
+ * day rows, so a period document that was never persisted can only be rebuilt
149
+ * from the sibling days — without them the plan rebuilds the period from the
150
+ * closing day alone and every other day silently disappears from the period
151
+ * drill-down (see `buildTenantDiscountCloseDayPlan`).
152
+ *
153
+ * The returned set always contains `localDate` itself and is sorted. Returns
154
+ * `null` (never throws) for a malformed date or an unparseable period value —
155
+ * a `null` means the caller must fail loudly rather than pass an incomplete
156
+ * `existingEntries` set with `existingEntriesComplete: true`.
157
+ */
158
+ function getMaterializedDiscountPeriodDayScopeFields(localDate) {
159
+ const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
160
+ if (periodFields == null)
161
+ return null;
162
+ const days = new Set([localDate]);
163
+ for (const scope of DISCOUNT_ACCUMULATED_SCOPES) {
164
+ const scopeField = periodFields[scope];
165
+ if (typeof scopeField !== 'string' || scopeField.length === 0)
166
+ return null;
167
+ if (!addPeriodDays(scope, scopeField, days))
168
+ return null;
169
+ }
170
+ return [...days].sort();
171
+ }
46
172
  /**
47
173
  * Watermark guard: does the stored document need a structural write?
48
174
  * `false` (skip) when the incoming `source_watermark` is not newer than the
@@ -598,15 +724,29 @@ function buildTenantDiscountCloseDayPlan(input) {
598
724
  doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
599
725
  continue;
600
726
  }
601
- // A PERIOD entry document must drop this day's rows: rows never accumulate,
602
- // so a period doc carries the whole period's rows. When the day lost its
603
- // rows the period doc is rebuilt from the compile's period entry sections
604
- // (which the compile already produces per period scope).
605
- const periodCompiled = compiledEntriesByScope.get(scopeKey(doc));
606
- if (periodCompiled == null) {
607
- // No rows left anywhere in this period scope for the compiled day — the
608
- // caller's fetch includes it only when the compile emitted it, so drop it.
727
+ // The compiled day has no rows in this period scope. That does NOT mean the
728
+ // period is empty: a period entry document accumulates EVERY day's rows, so
729
+ // deleting it would wipe the sibling days that exist nowhere else. Subtract
730
+ // the rows this day currently contributes (read from its day-scoped entry
731
+ // documents) and drop the document only when nothing remains.
732
+ const remaining = (0, exports.subtractMaterializedDiscountEntrySections)(doc.discount_entries, storedDayEntrySections);
733
+ const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
734
+ const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
735
+ // Nothing of this day was in that period: leave it untouched.
736
+ if (rowsAfter === rowsBefore)
737
+ continue;
738
+ if (rowsAfter === 0) {
609
739
  staleEntryDocuments.push(doc);
740
+ continue;
741
+ }
742
+ if (addEntryWrite({
743
+ ...doc,
744
+ discount_entries: remaining,
745
+ computed_at: computedAt,
746
+ updatedAt: computedAt,
747
+ iteration: (doc.iteration ?? 1) + 1,
748
+ }) == null) {
749
+ return null;
610
750
  }
611
751
  }
612
752
  return {
@@ -15,8 +15,9 @@ import { IMaterializedTenantDiscountReport } from '../../schemas/types/materiali
15
15
  *
16
16
  * Scope fan-out: an order contributes to its punch HOUR, the DATE, the WEEK,
17
17
  * the ISO WEEK-OF-YEAR and the MONTH — exactly `MATERIALIZED_DISCOUNT_REPORT_SCOPES`.
18
- * Quarter / semester / year are deliberately NOT materialized (the report's
19
- * calendar never asks for them).
18
+ * Quarter / semester / year are deliberately NOT materialized: period ENTRY
19
+ * documents accumulate their days' rows, so a wider scope would grow without a
20
+ * natural bound (see the constant's comment).
20
21
  *
21
22
  * Pure and total: `null` on malformed input, never a throw.
22
23
  */
@@ -37,10 +37,6 @@ exports.MATERIALIZED_RIDER_DAILY_REPORTS_COLLECTION_INDEXES = {
37
37
  _id: { _id: 1 },
38
38
  rider_id__local_date: { rider_id: 1, local_date: 1 },
39
39
  };
40
- exports.MaterializedRiderDailyReportSchema.index(exports.MATERIALIZED_RIDER_DAILY_REPORTS_COLLECTION_INDEXES.rider_id__local_date, {
41
- unique: true,
42
- name: 'rider_id__local_date',
43
- });
44
40
  exports.MATERIALIZED_RIDER_DAILY_REPORTS_INDEX_OPTIONS = [
45
41
  {
46
42
  key: exports.MATERIALIZED_RIDER_DAILY_REPORTS_COLLECTION_INDEXES.rider_id__local_date,
@@ -42,8 +42,6 @@ export declare const MaterializedTenantDiscountReportSchema: Schema<any, import(
42
42
  schema_version: number;
43
43
  source_watermark: NativeDate;
44
44
  computed_at: NativeDate;
45
- discount_counters: any;
46
- discount_counter_rows: any;
47
45
  top_sources: import("mongoose").Types.DocumentArray<{
48
46
  count: number;
49
47
  amount: number;
@@ -63,6 +61,8 @@ export declare const MaterializedTenantDiscountReportSchema: Schema<any, import(
63
61
  sub_kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
64
62
  resolved_amount: number;
65
63
  }>;
64
+ discount_counters?: any;
65
+ discount_counter_rows?: any;
66
66
  }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
67
67
  createdAt: NativeDate;
68
68
  updatedAt: NativeDate;
@@ -80,8 +80,6 @@ export declare const MaterializedTenantDiscountReportSchema: Schema<any, import(
80
80
  schema_version: number;
81
81
  source_watermark: NativeDate;
82
82
  computed_at: NativeDate;
83
- discount_counters: any;
84
- discount_counter_rows: any;
85
83
  top_sources: import("mongoose").Types.DocumentArray<{
86
84
  count: number;
87
85
  amount: number;
@@ -101,6 +99,8 @@ export declare const MaterializedTenantDiscountReportSchema: Schema<any, import(
101
99
  sub_kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
102
100
  resolved_amount: number;
103
101
  }>;
102
+ discount_counters?: any;
103
+ discount_counter_rows?: any;
104
104
  }>> & import("mongoose").FlatRecord<{
105
105
  createdAt: NativeDate;
106
106
  updatedAt: NativeDate;
@@ -118,8 +118,6 @@ export declare const MaterializedTenantDiscountReportSchema: Schema<any, import(
118
118
  schema_version: number;
119
119
  source_watermark: NativeDate;
120
120
  computed_at: NativeDate;
121
- discount_counters: any;
122
- discount_counter_rows: any;
123
121
  top_sources: import("mongoose").Types.DocumentArray<{
124
122
  count: number;
125
123
  amount: number;
@@ -139,6 +137,8 @@ export declare const MaterializedTenantDiscountReportSchema: Schema<any, import(
139
137
  sub_kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
140
138
  resolved_amount: number;
141
139
  }>;
140
+ discount_counters?: any;
141
+ discount_counter_rows?: any;
142
142
  }> & Required<{
143
143
  _id: import("mongoose").Types.ObjectId;
144
144
  }> & {
@@ -171,15 +171,19 @@ exports.MaterializedTenantDiscountReportSchema = new mongoose_1.Schema({
171
171
  // `materialized_tenant_discount_entries`. Empty map = a day with no
172
172
  // discounts (kept so watermark comparisons stay uniform).
173
173
  discount_counters: {
174
+ // NULLABLE BY CONTRACT (see the type module): a corrected/emptied period
175
+ // document legitimately holds no keys. `required: true` rejected exactly
176
+ // that close-day output at write time.
174
177
  type: mongoose_1.Schema.Types.Mixed,
175
- required: true,
178
+ required: false,
176
179
  default: null,
177
180
  },
178
181
  // The SAME counters as an ARRAY OF ROWS — the read-path shape (see the type
179
182
  // module). Mixed because the counter tree varies per key.
180
183
  discount_counter_rows: {
184
+ // Mirrors `discount_counters`: null when the map is empty.
181
185
  type: mongoose_1.Schema.Types.Mixed,
182
- required: true,
186
+ required: false,
183
187
  default: null,
184
188
  },
185
189
  top_sources: {
@@ -13,7 +13,6 @@ export declare const TenantHrAttendanceRecordSchema: Schema<any, import("mongoos
13
13
  updatedAt: NativeDate;
14
14
  tenant_id: string;
15
15
  status: HR_ATTENDANCE_STATUS_ENUM;
16
- notes: string;
17
16
  employee_id: string;
18
17
  break_time: import("mongoose").Types.DocumentArray<{
19
18
  start_time: number;
@@ -26,6 +25,7 @@ export declare const TenantHrAttendanceRecordSchema: Schema<any, import("mongoos
26
25
  end_time: number;
27
26
  }>;
28
27
  attendance_date: string;
28
+ schedule_id: string;
29
29
  clock_time: import("mongoose").Types.DocumentArray<{
30
30
  type: import("../../constants").HR_CLOCK_TIME_TYPE_ENUM;
31
31
  method: import("../../constants").HR_CHECK_IN_METHOD_ENUM;
@@ -50,7 +50,6 @@ export declare const TenantHrAttendanceRecordSchema: Schema<any, import("mongoos
50
50
  updatedAt: NativeDate;
51
51
  tenant_id: string;
52
52
  status: HR_ATTENDANCE_STATUS_ENUM;
53
- notes: string;
54
53
  employee_id: string;
55
54
  break_time: import("mongoose").Types.DocumentArray<{
56
55
  start_time: number;
@@ -63,6 +62,7 @@ export declare const TenantHrAttendanceRecordSchema: Schema<any, import("mongoos
63
62
  end_time: number;
64
63
  }>;
65
64
  attendance_date: string;
65
+ schedule_id: string;
66
66
  clock_time: import("mongoose").Types.DocumentArray<{
67
67
  type: import("../../constants").HR_CLOCK_TIME_TYPE_ENUM;
68
68
  method: import("../../constants").HR_CHECK_IN_METHOD_ENUM;
@@ -87,7 +87,6 @@ export declare const TenantHrAttendanceRecordSchema: Schema<any, import("mongoos
87
87
  updatedAt: NativeDate;
88
88
  tenant_id: string;
89
89
  status: HR_ATTENDANCE_STATUS_ENUM;
90
- notes: string;
91
90
  employee_id: string;
92
91
  break_time: import("mongoose").Types.DocumentArray<{
93
92
  start_time: number;
@@ -100,6 +99,7 @@ export declare const TenantHrAttendanceRecordSchema: Schema<any, import("mongoos
100
99
  end_time: number;
101
100
  }>;
102
101
  attendance_date: string;
102
+ schedule_id: string;
103
103
  clock_time: import("mongoose").Types.DocumentArray<{
104
104
  type: import("../../constants").HR_CLOCK_TIME_TYPE_ENUM;
105
105
  method: import("../../constants").HR_CHECK_IN_METHOD_ENUM;
@@ -57,6 +57,11 @@ exports.TenantHrAttendanceRecordSchema = new mongoose_1.Schema({
57
57
  required: true,
58
58
  match: /^\d{4}-\d{2}-\d{2}$/,
59
59
  },
60
+ schedule_id: {
61
+ type: String,
62
+ required: true,
63
+ ref: 'tenant_hr_shift_schedules',
64
+ },
60
65
  clock_time: {
61
66
  type: [hrClockTimeSchema],
62
67
  default: [],
@@ -79,10 +84,6 @@ exports.TenantHrAttendanceRecordSchema = new mongoose_1.Schema({
79
84
  enum: constants_1.ALL_HR_ATTENDANCE_STATUS_NAMES,
80
85
  default: constants_1.HR_ATTENDANCE_STATUS_ENUM.PRESENT,
81
86
  },
82
- notes: {
83
- type: String,
84
- default: null,
85
- },
86
87
  createdAt: {
87
88
  type: mongoose_1.Schema.Types.Date,
88
89
  required: true,
@@ -99,6 +100,4 @@ exports.TenantHrAttendanceRecordSchema = new mongoose_1.Schema({
99
100
  versionKey: false,
100
101
  minimize: false,
101
102
  });
102
- exports.TenantHrAttendanceRecordSchema.index({ tenant_id: 1, employee_id: 1, attendance_date: 1 }, { unique: true });
103
- exports.TenantHrAttendanceRecordSchema.index({ tenant_id: 1, attendance_date: 1 });
104
103
  exports.TENANT_HR_ATTENDANCE_RECORDS_COLLECTION_NAME = 'tenant_hr_attendance_records';
@@ -22,7 +22,7 @@ export declare const TenantHrShiftScheduleSchema: Schema<any, import("mongoose")
22
22
  day_indexes: string[];
23
23
  notes: string;
24
24
  employee_id: string;
25
- template_id: string;
25
+ shift_id: string;
26
26
  }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
27
27
  createdAt: NativeDate;
28
28
  updatedAt: NativeDate;
@@ -41,7 +41,7 @@ export declare const TenantHrShiftScheduleSchema: Schema<any, import("mongoose")
41
41
  day_indexes: string[];
42
42
  notes: string;
43
43
  employee_id: string;
44
- template_id: string;
44
+ shift_id: string;
45
45
  }>> & import("mongoose").FlatRecord<{
46
46
  createdAt: NativeDate;
47
47
  updatedAt: NativeDate;
@@ -60,7 +60,7 @@ export declare const TenantHrShiftScheduleSchema: Schema<any, import("mongoose")
60
60
  day_indexes: string[];
61
61
  notes: string;
62
62
  employee_id: string;
63
- template_id: string;
63
+ shift_id: string;
64
64
  }> & Required<{
65
65
  _id: import("mongoose").Types.ObjectId;
66
66
  }> & {
@@ -63,7 +63,7 @@ exports.TenantHrShiftScheduleSchema = new mongoose_1.Schema({
63
63
  type: String,
64
64
  default: null,
65
65
  },
66
- template_id: {
66
+ shift_id: {
67
67
  type: String,
68
68
  default: null,
69
69
  ref: 'tenant_hr_shifts',
@@ -13,12 +13,12 @@ export interface ITenantHrAttendanceRecord {
13
13
  tenant_id: string;
14
14
  employee_id: string;
15
15
  attendance_date: string;
16
+ schedule_id: string;
16
17
  clock_time: ITenantHrClockTime[];
17
18
  break_time: ITenantHrBreakTime[];
18
19
  total_break_time: number;
19
20
  total_worked_time: number;
20
21
  status: HR_ATTENDANCE_STATUS_ENUM;
21
- notes?: string | null;
22
22
  createdAt: Date;
23
23
  updatedAt: Date | null;
24
24
  }
@@ -12,7 +12,7 @@ export interface ITenantHrShiftSchedule {
12
12
  type: HR_SHIFT_TYPE_ENUM;
13
13
  status: HR_SHIFT_STATUS_ENUM;
14
14
  notes?: string | null;
15
- template_id?: string | null;
15
+ shift_id?: string | null;
16
16
  createdAt: Date;
17
17
  updatedAt: Date | null;
18
18
  }
@@ -77,13 +77,57 @@ function applyPlan(reports, entries, plan) {
77
77
  return { reports: [...byScope.values()], entries: [...entriesByScope.values()] };
78
78
  }
79
79
  describe('materialized discounts — close-day plan', () => {
80
- it('lists the scopes a day needs: date + 6 periods + 24 hours', () => {
80
+ it('lists the scopes a day needs: date + 3 periods + 24 hours (month-capped)', () => {
81
81
  const refs = (0, materialized_discount_close_day_helpers_1.getMaterializedDiscountScopeRefsForDay)('2026-09-13');
82
- expect(refs).toHaveLength(1 + 6 + 24);
82
+ expect(refs).toHaveLength(1 + 3 + 24);
83
+ const periodScopes = refs
84
+ .filter((ref) => ref.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
85
+ ref.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR)
86
+ .map((ref) => ref.scope_context)
87
+ .sort();
88
+ expect(periodScopes).toEqual([
89
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
90
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
91
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
92
+ ].sort());
93
+ expect(periodScopes).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER);
94
+ expect(periodScopes).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER);
95
+ expect(periodScopes).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR);
83
96
  expect(refs.filter((ref) => ref.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR)).toHaveLength(24);
84
97
  expect(refs[0]).toEqual({ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, scope_field: '2026-09-13' });
85
98
  expect((0, materialized_discount_close_day_helpers_1.getMaterializedDiscountScopeRefsForDay)('nope')).toBeNull();
86
99
  });
100
+ it('enumerates every DAY-scoped sibling document the touched periods can contain', () => {
101
+ // 2026-09-13 is a Sunday: localWeek starts that day, the ISO week (W37)
102
+ // starts Monday 2026-09-07, and the month starts 2026-09-01.
103
+ const days = (0, materialized_discount_close_day_helpers_1.getMaterializedDiscountPeriodDayScopeFields)('2026-09-13');
104
+ expect(days[0]).toBe('2026-09-01');
105
+ expect(days[days.length - 1]).toBe('2026-09-30');
106
+ expect(days).toHaveLength(30);
107
+ expect(days).toContain('2026-09-13');
108
+ // A month-boundary day pulls in the week / ISO-week days from the previous
109
+ // month (Sunday 2026-08-30, ISO Monday 2026-08-31) — the set is the exact
110
+ // union of the touched periods, never just the calendar month.
111
+ const boundary = (0, materialized_discount_close_day_helpers_1.getMaterializedDiscountPeriodDayScopeFields)('2026-09-01');
112
+ expect(boundary[0]).toBe('2026-08-30');
113
+ expect(boundary[boundary.length - 1]).toBe('2026-09-30');
114
+ expect(boundary).toHaveLength(32);
115
+ // Month end pulls in the first days of the next month (week ends Sat
116
+ // 2026-10-03, ISO week W40 ends Sun 2026-10-04).
117
+ const monthEnd = (0, materialized_discount_close_day_helpers_1.getMaterializedDiscountPeriodDayScopeFields)('2026-09-30');
118
+ expect(monthEnd[0]).toBe('2026-09-01');
119
+ expect(monthEnd[monthEnd.length - 1]).toBe('2026-10-04');
120
+ expect(monthEnd).toHaveLength(34);
121
+ // ISO week-year boundary: 2027-01-01 is 2026-W53, whose Monday is
122
+ // 2026-12-28; the Sunday week starts 2026-12-27. The union spans the year.
123
+ const isoBoundary = (0, materialized_discount_close_day_helpers_1.getMaterializedDiscountPeriodDayScopeFields)('2027-01-01');
124
+ expect(isoBoundary[0]).toBe('2026-12-27');
125
+ expect(isoBoundary[isoBoundary.length - 1]).toBe('2027-01-31');
126
+ expect(isoBoundary).toHaveLength(36);
127
+ expect(isoBoundary).toContain('2026-12-28');
128
+ expect(isoBoundary).toContain('2027-01-03');
129
+ expect((0, materialized_discount_close_day_helpers_1.getMaterializedDiscountPeriodDayScopeFields)('nope')).toBeNull();
130
+ });
87
131
  it('first close writes the day with a history row per write', () => {
88
132
  const localDate = '2026-09-13';
89
133
  const compiled = compileDay(localDate);
@@ -108,8 +152,9 @@ describe('materialized discounts — close-day plan', () => {
108
152
  expect(write.iteration.report_type).toBe('TENANT_DISCOUNT_ENTRIES');
109
153
  }
110
154
  // A period doc created by this close (first materialization) is reported
111
- // Six accumulating scopes: week, ISO-week, month, quarter, semester, year.
112
- expect(plan.createdPeriodDocuments.length).toBe(6);
155
+ // Three accumulating scopes: week, ISO-week, month (quarter / semester /
156
+ // year are deliberately not materialized — see the scope constant).
157
+ expect(plan.createdPeriodDocuments.length).toBe(3);
113
158
  });
114
159
  it('a re-close with unchanged source data is IDEMPOTENT', () => {
115
160
  const localDate = '2026-09-13';
@@ -322,6 +367,65 @@ describe('materialized discounts — close-day plan', () => {
322
367
  expect(firstDay).not.toBe('');
323
368
  expect(secondDay).not.toBe('');
324
369
  });
370
+ it('a counter-only close must NOT delete the period rows of sibling days', () => {
371
+ // A day can compile COUNTERS with no ENTRY rows (order-level money no slot
372
+ // explains -> `unattributed_amount`, no drill-down row). The compile then
373
+ // emits no entry document for any scope. The stale-entry branch used to
374
+ // read "the compile did not emit this period scope" as "the period is
375
+ // empty" and mark the whole period ENTRY document stale - deleting every
376
+ // sibling day's rows from the period drill-down.
377
+ const allDays = [...new Set((0, fixtures_1.loadOrdersDataset)('basha').map((o) => o.localDate))]
378
+ .filter((d) => typeof d === 'string')
379
+ .sort();
380
+ const daysWithRows = allDays.filter((d) => compileDay(d).entries.length > 0);
381
+ const firstMonth = daysWithRows[0]?.slice(0, 7);
382
+ const pair = daysWithRows.filter((d) => d.slice(0, 7) === firstMonth).slice(0, 2);
383
+ expect(pair).toHaveLength(2);
384
+ const [a, b] = pair;
385
+ const rowsOf = (doc) => Object.values(doc?.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
386
+ const monthEntry = (state) => state.entries.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
387
+ const dayEntry = (state, day) => state.entries.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === day);
388
+ let state = applyPlan([], [], (0, materialized_discount_close_day_helpers_1.buildTenantDiscountCloseDayPlan)({
389
+ tenantId: TENANT,
390
+ reports: compileDay(a).reports,
391
+ entries: compileDay(a).entries,
392
+ localDate: a,
393
+ reason: 'NEW_DAY',
394
+ computedAt: AT,
395
+ }));
396
+ state = applyPlan(state.reports, state.entries, (0, materialized_discount_close_day_helpers_1.buildTenantDiscountCloseDayPlan)({
397
+ tenantId: TENANT,
398
+ reports: compileDay(b).reports,
399
+ entries: compileDay(b).entries,
400
+ localDate: b,
401
+ ...closeInputs(b, state),
402
+ reason: 'NEW_DAY',
403
+ computedAt: AT,
404
+ }));
405
+ const monthBefore = rowsOf(monthEntry(state));
406
+ const aRows = rowsOf(dayEntry(state, a));
407
+ const bRows = rowsOf(dayEntry(state, b));
408
+ expect(aRows).toBeGreaterThan(0);
409
+ expect(bRows).toBeGreaterThan(0);
410
+ expect(monthBefore).toBe(aRows + bRows);
411
+ // Re-close A with its counters but NO entry documents.
412
+ const plan = (0, materialized_discount_close_day_helpers_1.buildTenantDiscountCloseDayPlan)({
413
+ tenantId: TENANT,
414
+ reports: compileDay(a).reports,
415
+ entries: [],
416
+ localDate: a,
417
+ ...closeInputs(a, state),
418
+ reason: 'CORRECTION',
419
+ computedAt: AT,
420
+ });
421
+ expect(plan.staleEntryDocuments.some((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)).toBe(false);
422
+ expect(plan.entryWrites.some((write) => write.report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)).toBe(true);
423
+ const after = applyPlan(state.reports, state.entries, plan);
424
+ // A's rows are gone from the month; B's rows survive untouched.
425
+ expect(rowsOf(monthEntry(after))).toBe(bRows);
426
+ expect(dayEntry(after, a)).toBeUndefined();
427
+ expect(rowsOf(dayEntry(after, b))).toBe(bRows);
428
+ });
325
429
  it('AUDIT D1: emptying a day must not destroy a SIBLING day rows in the period docs', () => {
326
430
  // Reproduces the defect the round-2 audit reported. The emptied-day path pushes EVERY
327
431
  // entry document stale, including the PERIOD ones, and discount period entries are
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.4.21",
3
+ "version": "0.4.23",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",