@managesome/eposmatic-toolkit 0.4.9 → 0.4.10

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 (333) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +448 -0
  2. package/esm/helpers/index.js +3 -0
  3. package/esm/helpers/materialized-reports/index.js +32 -0
  4. package/esm/helpers/materialized-reports/materialized-cash-accumulator-helpers.js +114 -0
  5. package/esm/helpers/materialized-reports/materialized-cash-classification-helpers.js +286 -0
  6. package/esm/helpers/materialized-reports/materialized-cash-close-day-helpers.js +396 -0
  7. package/esm/helpers/materialized-reports/materialized-cash-compile-helpers.js +244 -0
  8. package/esm/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +170 -0
  9. package/esm/helpers/materialized-reports/materialized-delivery-classification-helpers.js +426 -0
  10. package/esm/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +372 -0
  11. package/esm/helpers/materialized-reports/materialized-delivery-compile-helpers.js +214 -0
  12. package/esm/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +318 -0
  13. package/esm/helpers/materialized-reports/materialized-discount-classification-helpers.js +213 -0
  14. package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +604 -0
  15. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +186 -0
  16. package/esm/helpers/materialized-reports/materialized-hourly-comparison-close-day-helpers.js +155 -0
  17. package/esm/helpers/materialized-reports/materialized-hourly-comparison-compile-helpers.js +199 -0
  18. package/esm/helpers/materialized-reports/materialized-hourly-comparison-selection-helpers.js +111 -0
  19. package/esm/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.js +88 -0
  20. package/esm/helpers/materialized-reports/materialized-payments-comparison-close-day-helpers.js +394 -0
  21. package/esm/helpers/materialized-reports/materialized-payments-comparison-compile-helpers.js +167 -0
  22. package/esm/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +215 -0
  23. package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +476 -0
  24. package/esm/helpers/materialized-reports/materialized-prep-time-compile-helpers.js +201 -0
  25. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  26. package/esm/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.js +189 -0
  27. package/esm/helpers/materialized-reports/materialized-sales-comparison-baseline-helpers.js +157 -0
  28. package/esm/helpers/materialized-reports/materialized-sales-comparison-close-day-helpers.js +588 -0
  29. package/esm/helpers/materialized-reports/materialized-sales-comparison-compile-helpers.js +175 -0
  30. package/esm/helpers/materialized-reports/tenant-cash-in-out-formatter.js +156 -0
  31. package/esm/helpers/materialized-reports/tenant-delivery-formatter.js +230 -0
  32. package/esm/helpers/materialized-reports/tenant-discount-formatter.js +427 -0
  33. package/esm/helpers/materialized-reports/tenant-hourly-comparison-formatter.js +237 -0
  34. package/esm/helpers/materialized-reports/tenant-payments-comparison-formatter.js +279 -0
  35. package/esm/helpers/materialized-reports/tenant-prep-time-formatter.js +228 -0
  36. package/esm/helpers/materialized-reports/tenant-sales-comparison-formatter.js +343 -0
  37. package/esm/helpers/reporting-contract/index.js +2 -0
  38. package/esm/helpers/reporting-contract/overview-contract.js +122 -0
  39. package/esm/helpers/reporting-contract/report-contract.js +228 -0
  40. package/esm/helpers/rider-earnings/index.js +1 -0
  41. package/esm/helpers/rider-earnings/rider-earnings.js +59 -0
  42. package/esm/helpers/rider-reports/index.js +2 -0
  43. package/esm/helpers/rider-reports/rider-daily-report.js +90 -0
  44. package/esm/helpers/rider-reports/rider-report.js +67 -0
  45. package/esm/schemas/models/deliveries.js +75 -0
  46. package/esm/schemas/models/index.js +15 -0
  47. package/esm/schemas/models/materialized_rider_daily_reports.js +39 -0
  48. package/esm/schemas/models/materialized_tenant_cash_entries.js +95 -0
  49. package/esm/schemas/models/materialized_tenant_cash_reports.js +77 -0
  50. package/esm/schemas/models/materialized_tenant_delivery_entries.js +63 -0
  51. package/esm/schemas/models/materialized_tenant_delivery_reports.js +63 -0
  52. package/esm/schemas/models/materialized_tenant_discount_entries.js +156 -0
  53. package/esm/schemas/models/materialized_tenant_discount_reports.js +333 -0
  54. package/esm/schemas/models/materialized_tenant_hourly_comparison_entries.js +87 -0
  55. package/esm/schemas/models/materialized_tenant_hourly_comparison_reports.js +99 -0
  56. package/esm/schemas/models/materialized_tenant_payments_comparison_entries.js +71 -0
  57. package/esm/schemas/models/materialized_tenant_payments_comparison_reports.js +76 -0
  58. package/esm/schemas/models/materialized_tenant_prep_time_entries.js +130 -0
  59. package/esm/schemas/models/materialized_tenant_prep_time_reports.js +109 -0
  60. package/esm/schemas/models/materialized_tenant_sales_comparison_entries.js +130 -0
  61. package/esm/schemas/models/materialized_tenant_sales_comparison_reports.js +154 -0
  62. package/esm/schemas/types/index.js +15 -0
  63. package/esm/schemas/types/materialized_rider_daily_reports.js +1 -0
  64. package/esm/schemas/types/materialized_tenant_cash_entries.js +1 -0
  65. package/esm/schemas/types/materialized_tenant_cash_reports.js +1 -0
  66. package/esm/schemas/types/materialized_tenant_delivery_entries.js +1 -0
  67. package/esm/schemas/types/materialized_tenant_delivery_reports.js +1 -0
  68. package/esm/schemas/types/materialized_tenant_discount_entries.js +1 -0
  69. package/esm/schemas/types/materialized_tenant_discount_reports.js +2 -0
  70. package/esm/schemas/types/materialized_tenant_hourly_comparison_entries.js +1 -0
  71. package/esm/schemas/types/materialized_tenant_hourly_comparison_reports.js +1 -0
  72. package/esm/schemas/types/materialized_tenant_payments_comparison_entries.js +1 -0
  73. package/esm/schemas/types/materialized_tenant_payments_comparison_reports.js +11 -0
  74. package/esm/schemas/types/materialized_tenant_prep_time_entries.js +1 -0
  75. package/esm/schemas/types/materialized_tenant_prep_time_reports.js +1 -0
  76. package/esm/schemas/types/materialized_tenant_sales_comparison_entries.js +1 -0
  77. package/esm/schemas/types/materialized_tenant_sales_comparison_reports.js +14 -0
  78. package/lib/constants/MATERIALIZED_REPORTS.d.ts +339 -2
  79. package/lib/constants/MATERIALIZED_REPORTS.js +450 -1
  80. package/lib/helpers/index.d.ts +3 -0
  81. package/lib/helpers/index.js +3 -0
  82. package/lib/helpers/materialized-reports/index.d.ts +32 -0
  83. package/lib/helpers/materialized-reports/index.js +32 -0
  84. package/lib/helpers/materialized-reports/materialized-cash-accumulator-helpers.d.ts +18 -0
  85. package/lib/helpers/materialized-reports/materialized-cash-accumulator-helpers.js +118 -0
  86. package/lib/helpers/materialized-reports/materialized-cash-classification-helpers.d.ts +90 -0
  87. package/lib/helpers/materialized-reports/materialized-cash-classification-helpers.js +295 -0
  88. package/lib/helpers/materialized-reports/materialized-cash-close-day-helpers.d.ts +102 -0
  89. package/lib/helpers/materialized-reports/materialized-cash-close-day-helpers.js +409 -0
  90. package/lib/helpers/materialized-reports/materialized-cash-compile-helpers.d.ts +72 -0
  91. package/lib/helpers/materialized-reports/materialized-cash-compile-helpers.js +251 -0
  92. package/lib/helpers/materialized-reports/materialized-delivery-accumulator-helpers.d.ts +7 -0
  93. package/lib/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +173 -0
  94. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.d.ts +84 -0
  95. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +438 -0
  96. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.d.ts +97 -0
  97. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +385 -0
  98. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.d.ts +40 -0
  99. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +218 -0
  100. package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.d.ts +52 -0
  101. package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +324 -0
  102. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.d.ts +50 -0
  103. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +222 -0
  104. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +182 -0
  105. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +615 -0
  106. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +47 -0
  107. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +193 -0
  108. package/lib/helpers/materialized-reports/materialized-hourly-comparison-close-day-helpers.d.ts +64 -0
  109. package/lib/helpers/materialized-reports/materialized-hourly-comparison-close-day-helpers.js +163 -0
  110. package/lib/helpers/materialized-reports/materialized-hourly-comparison-compile-helpers.d.ts +61 -0
  111. package/lib/helpers/materialized-reports/materialized-hourly-comparison-compile-helpers.js +207 -0
  112. package/lib/helpers/materialized-reports/materialized-hourly-comparison-selection-helpers.d.ts +23 -0
  113. package/lib/helpers/materialized-reports/materialized-hourly-comparison-selection-helpers.js +116 -0
  114. package/lib/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.d.ts +25 -0
  115. package/lib/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.js +98 -0
  116. package/lib/helpers/materialized-reports/materialized-payments-comparison-close-day-helpers.d.ts +79 -0
  117. package/lib/helpers/materialized-reports/materialized-payments-comparison-close-day-helpers.js +407 -0
  118. package/lib/helpers/materialized-reports/materialized-payments-comparison-compile-helpers.d.ts +35 -0
  119. package/lib/helpers/materialized-reports/materialized-payments-comparison-compile-helpers.js +173 -0
  120. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.d.ts +66 -0
  121. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +224 -0
  122. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.d.ts +128 -0
  123. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +490 -0
  124. package/lib/helpers/materialized-reports/materialized-prep-time-compile-helpers.d.ts +46 -0
  125. package/lib/helpers/materialized-reports/materialized-prep-time-compile-helpers.js +208 -0
  126. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +8 -0
  127. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +8 -1
  128. package/lib/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.d.ts +48 -0
  129. package/lib/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.js +204 -0
  130. package/lib/helpers/materialized-reports/materialized-sales-comparison-baseline-helpers.d.ts +22 -0
  131. package/lib/helpers/materialized-reports/materialized-sales-comparison-baseline-helpers.js +161 -0
  132. package/lib/helpers/materialized-reports/materialized-sales-comparison-close-day-helpers.d.ts +163 -0
  133. package/lib/helpers/materialized-reports/materialized-sales-comparison-close-day-helpers.js +603 -0
  134. package/lib/helpers/materialized-reports/materialized-sales-comparison-compile-helpers.d.ts +68 -0
  135. package/lib/helpers/materialized-reports/materialized-sales-comparison-compile-helpers.js +182 -0
  136. package/lib/helpers/materialized-reports/tenant-cash-in-out-formatter.d.ts +98 -0
  137. package/lib/helpers/materialized-reports/tenant-cash-in-out-formatter.js +159 -0
  138. package/lib/helpers/materialized-reports/tenant-delivery-formatter.d.ts +133 -0
  139. package/lib/helpers/materialized-reports/tenant-delivery-formatter.js +233 -0
  140. package/lib/helpers/materialized-reports/tenant-discount-formatter.d.ts +114 -0
  141. package/lib/helpers/materialized-reports/tenant-discount-formatter.js +431 -0
  142. package/lib/helpers/materialized-reports/tenant-hourly-comparison-formatter.d.ts +60 -0
  143. package/lib/helpers/materialized-reports/tenant-hourly-comparison-formatter.js +243 -0
  144. package/lib/helpers/materialized-reports/tenant-payments-comparison-formatter.d.ts +75 -0
  145. package/lib/helpers/materialized-reports/tenant-payments-comparison-formatter.js +286 -0
  146. package/lib/helpers/materialized-reports/tenant-prep-time-formatter.d.ts +97 -0
  147. package/lib/helpers/materialized-reports/tenant-prep-time-formatter.js +232 -0
  148. package/lib/helpers/materialized-reports/tenant-sales-comparison-formatter.d.ts +105 -0
  149. package/lib/helpers/materialized-reports/tenant-sales-comparison-formatter.js +349 -0
  150. package/lib/helpers/reporting-contract/index.d.ts +2 -0
  151. package/lib/helpers/reporting-contract/index.js +18 -0
  152. package/lib/helpers/reporting-contract/overview-contract.d.ts +55 -0
  153. package/lib/helpers/reporting-contract/overview-contract.js +126 -0
  154. package/lib/helpers/reporting-contract/report-contract.d.ts +159 -0
  155. package/lib/helpers/reporting-contract/report-contract.js +239 -0
  156. package/lib/helpers/rider-earnings/index.d.ts +1 -0
  157. package/lib/helpers/rider-earnings/index.js +17 -0
  158. package/lib/helpers/rider-earnings/rider-earnings.d.ts +58 -0
  159. package/lib/helpers/rider-earnings/rider-earnings.js +64 -0
  160. package/lib/helpers/rider-reports/index.d.ts +2 -0
  161. package/lib/helpers/rider-reports/index.js +18 -0
  162. package/lib/helpers/rider-reports/rider-daily-report.d.ts +26 -0
  163. package/lib/helpers/rider-reports/rider-daily-report.js +93 -0
  164. package/lib/helpers/rider-reports/rider-report.d.ts +49 -0
  165. package/lib/helpers/rider-reports/rider-report.js +70 -0
  166. package/lib/helpers/types/materialized-reports-apis.d.ts +297 -1
  167. package/lib/schemas/models/deliveries.d.ts +54 -0
  168. package/lib/schemas/models/deliveries.js +75 -0
  169. package/lib/schemas/models/expense_details.d.ts +3 -3
  170. package/lib/schemas/models/index.d.ts +15 -0
  171. package/lib/schemas/models/index.js +15 -0
  172. package/lib/schemas/models/materialized_rider_daily_reports.d.ts +27 -0
  173. package/lib/schemas/models/materialized_rider_daily_reports.js +42 -0
  174. package/lib/schemas/models/materialized_tenant_cash_entries.d.ts +181 -0
  175. package/lib/schemas/models/materialized_tenant_cash_entries.js +98 -0
  176. package/lib/schemas/models/materialized_tenant_cash_reports.d.ts +111 -0
  177. package/lib/schemas/models/materialized_tenant_cash_reports.js +80 -0
  178. package/lib/schemas/models/materialized_tenant_delivery_entries.d.ts +98 -0
  179. package/lib/schemas/models/materialized_tenant_delivery_entries.js +66 -0
  180. package/lib/schemas/models/materialized_tenant_delivery_reports.d.ts +98 -0
  181. package/lib/schemas/models/materialized_tenant_delivery_reports.js +66 -0
  182. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +199 -0
  183. package/lib/schemas/models/materialized_tenant_discount_entries.js +159 -0
  184. package/lib/schemas/models/materialized_tenant_discount_reports.d.ts +216 -0
  185. package/lib/schemas/models/materialized_tenant_discount_reports.js +336 -0
  186. package/lib/schemas/models/materialized_tenant_hourly_comparison_entries.d.ts +95 -0
  187. package/lib/schemas/models/materialized_tenant_hourly_comparison_entries.js +82 -0
  188. package/lib/schemas/models/materialized_tenant_hourly_comparison_reports.d.ts +105 -0
  189. package/lib/schemas/models/materialized_tenant_hourly_comparison_reports.js +91 -0
  190. package/lib/schemas/models/materialized_tenant_payments_comparison_entries.d.ts +91 -0
  191. package/lib/schemas/models/materialized_tenant_payments_comparison_entries.js +70 -0
  192. package/lib/schemas/models/materialized_tenant_payments_comparison_reports.d.ts +98 -0
  193. package/lib/schemas/models/materialized_tenant_payments_comparison_reports.js +71 -0
  194. package/lib/schemas/models/materialized_tenant_prep_time_entries.d.ts +181 -0
  195. package/lib/schemas/models/materialized_tenant_prep_time_entries.js +133 -0
  196. package/lib/schemas/models/materialized_tenant_prep_time_reports.d.ts +118 -0
  197. package/lib/schemas/models/materialized_tenant_prep_time_reports.js +112 -0
  198. package/lib/schemas/models/materialized_tenant_sales_comparison_entries.d.ts +139 -0
  199. package/lib/schemas/models/materialized_tenant_sales_comparison_entries.js +120 -0
  200. package/lib/schemas/models/materialized_tenant_sales_comparison_reports.d.ts +167 -0
  201. package/lib/schemas/models/materialized_tenant_sales_comparison_reports.js +137 -0
  202. package/lib/schemas/models/tenant_purchase_order_vendor_returns.d.ts +3 -3
  203. package/lib/schemas/models/warehouse_internal_movements.d.ts +6 -6
  204. package/lib/schemas/models/warehouse_purchase_order_receipts.d.ts +3 -3
  205. package/lib/schemas/models/warehouse_purchase_order_vendor_returns.d.ts +3 -3
  206. package/lib/schemas/models/warehouse_sale_deliveries.d.ts +6 -6
  207. package/lib/schemas/models/warehouse_sale_invoices.d.ts +3 -3
  208. package/lib/schemas/types/deliveries.d.ts +40 -1
  209. package/lib/schemas/types/index.d.ts +15 -0
  210. package/lib/schemas/types/index.js +15 -0
  211. package/lib/schemas/types/materialized_rider_daily_reports.d.ts +37 -0
  212. package/lib/schemas/types/materialized_rider_daily_reports.js +2 -0
  213. package/lib/schemas/types/materialized_tenant_cash_entries.d.ts +87 -0
  214. package/lib/schemas/types/materialized_tenant_cash_entries.js +2 -0
  215. package/lib/schemas/types/materialized_tenant_cash_reports.d.ts +144 -0
  216. package/lib/schemas/types/materialized_tenant_cash_reports.js +2 -0
  217. package/lib/schemas/types/materialized_tenant_delivery_entries.d.ts +98 -0
  218. package/lib/schemas/types/materialized_tenant_delivery_entries.js +2 -0
  219. package/lib/schemas/types/materialized_tenant_delivery_reports.d.ts +179 -0
  220. package/lib/schemas/types/materialized_tenant_delivery_reports.js +2 -0
  221. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +81 -0
  222. package/lib/schemas/types/materialized_tenant_discount_entries.js +2 -0
  223. package/lib/schemas/types/materialized_tenant_discount_reports.d.ts +209 -0
  224. package/lib/schemas/types/materialized_tenant_discount_reports.js +3 -0
  225. package/lib/schemas/types/materialized_tenant_hourly_comparison_entries.d.ts +33 -0
  226. package/lib/schemas/types/materialized_tenant_hourly_comparison_entries.js +2 -0
  227. package/lib/schemas/types/materialized_tenant_hourly_comparison_reports.d.ts +40 -0
  228. package/lib/schemas/types/materialized_tenant_hourly_comparison_reports.js +2 -0
  229. package/lib/schemas/types/materialized_tenant_payments_comparison_entries.d.ts +48 -0
  230. package/lib/schemas/types/materialized_tenant_payments_comparison_entries.js +2 -0
  231. package/lib/schemas/types/materialized_tenant_payments_comparison_reports.d.ts +51 -0
  232. package/lib/schemas/types/materialized_tenant_payments_comparison_reports.js +14 -0
  233. package/lib/schemas/types/materialized_tenant_prep_time_entries.d.ts +88 -0
  234. package/lib/schemas/types/materialized_tenant_prep_time_entries.js +2 -0
  235. package/lib/schemas/types/materialized_tenant_prep_time_reports.d.ts +132 -0
  236. package/lib/schemas/types/materialized_tenant_prep_time_reports.js +2 -0
  237. package/lib/schemas/types/materialized_tenant_sales_comparison_entries.d.ts +43 -0
  238. package/lib/schemas/types/materialized_tenant_sales_comparison_entries.js +2 -0
  239. package/lib/schemas/types/materialized_tenant_sales_comparison_reports.d.ts +74 -0
  240. package/lib/schemas/types/materialized_tenant_sales_comparison_reports.js +17 -0
  241. package/lib/tests/materialized-reports/analytics-growth-helpers.test.d.ts +1 -0
  242. package/lib/tests/materialized-reports/analytics-overview-helpers.test.d.ts +1 -0
  243. package/lib/tests/materialized-reports/analytics-performance-helpers.test.d.ts +1 -0
  244. package/lib/tests/materialized-reports/fixtures.d.ts +15 -1
  245. package/lib/tests/materialized-reports/fixtures.js +1 -0
  246. package/lib/tests/materialized-reports/materialized-cash-compile.test.d.ts +1 -0
  247. package/lib/tests/materialized-reports/materialized-cash-compile.test.js +196 -0
  248. package/lib/tests/materialized-reports/materialized-cash-fold.test.d.ts +1 -0
  249. package/lib/tests/materialized-reports/materialized-cash-fold.test.js +116 -0
  250. package/lib/tests/materialized-reports/materialized-cash-formatter.test.d.ts +1 -0
  251. package/lib/tests/materialized-reports/materialized-cash-formatter.test.js +152 -0
  252. package/lib/tests/materialized-reports/materialized-cash-plan.test.d.ts +1 -0
  253. package/lib/tests/materialized-reports/materialized-cash-plan.test.js +168 -0
  254. package/lib/tests/materialized-reports/materialized-cash-reconciliation.test.d.ts +1 -0
  255. package/lib/tests/materialized-reports/materialized-cash-reconciliation.test.js +267 -0
  256. package/lib/tests/materialized-reports/materialized-delivery-accumulation.test.d.ts +1 -0
  257. package/lib/tests/materialized-reports/materialized-delivery-accumulation.test.js +147 -0
  258. package/lib/tests/materialized-reports/materialized-delivery-compile.test.d.ts +1 -0
  259. package/lib/tests/materialized-reports/materialized-delivery-compile.test.js +241 -0
  260. package/lib/tests/materialized-reports/materialized-delivery-fold.test.d.ts +1 -0
  261. package/lib/tests/materialized-reports/materialized-delivery-fold.test.js +109 -0
  262. package/lib/tests/materialized-reports/materialized-delivery-formatter.test.d.ts +1 -0
  263. package/lib/tests/materialized-reports/materialized-delivery-formatter.test.js +141 -0
  264. package/lib/tests/materialized-reports/materialized-delivery-plan.test.d.ts +1 -0
  265. package/lib/tests/materialized-reports/materialized-delivery-plan.test.js +198 -0
  266. package/lib/tests/materialized-reports/materialized-discount-aggregated-formatter.test.d.ts +1 -0
  267. package/lib/tests/materialized-reports/materialized-discount-aggregated-formatter.test.js +173 -0
  268. package/lib/tests/materialized-reports/materialized-discount-classification.test.d.ts +1 -0
  269. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +339 -0
  270. package/lib/tests/materialized-reports/materialized-discount-close-day.test.d.ts +1 -0
  271. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +506 -0
  272. package/lib/tests/materialized-reports/materialized-discount-compile.test.d.ts +1 -0
  273. package/lib/tests/materialized-reports/materialized-discount-compile.test.js +161 -0
  274. package/lib/tests/materialized-reports/materialized-discount-counter-rows.test.d.ts +1 -0
  275. package/lib/tests/materialized-reports/materialized-discount-counter-rows.test.js +107 -0
  276. package/lib/tests/materialized-reports/materialized-discount-entries-accumulation.test.d.ts +1 -0
  277. package/lib/tests/materialized-reports/materialized-discount-entries-accumulation.test.js +125 -0
  278. package/lib/tests/materialized-reports/materialized-hourly-comparison-compile.test.d.ts +1 -0
  279. package/lib/tests/materialized-reports/materialized-hourly-comparison-compile.test.js +146 -0
  280. package/lib/tests/materialized-reports/materialized-hourly-comparison-formatter.test.d.ts +1 -0
  281. package/lib/tests/materialized-reports/materialized-hourly-comparison-formatter.test.js +127 -0
  282. package/lib/tests/materialized-reports/materialized-hourly-comparison-plan.test.d.ts +1 -0
  283. package/lib/tests/materialized-reports/materialized-hourly-comparison-plan.test.js +138 -0
  284. package/lib/tests/materialized-reports/materialized-hourly-comparison-selection.test.d.ts +1 -0
  285. package/lib/tests/materialized-reports/materialized-hourly-comparison-selection.test.js +90 -0
  286. package/lib/tests/materialized-reports/materialized-payments-comparison-compile.test.d.ts +1 -0
  287. package/lib/tests/materialized-reports/materialized-payments-comparison-compile.test.js +164 -0
  288. package/lib/tests/materialized-reports/materialized-payments-comparison-formatter.test.d.ts +1 -0
  289. package/lib/tests/materialized-reports/materialized-payments-comparison-formatter.test.js +117 -0
  290. package/lib/tests/materialized-reports/materialized-payments-comparison-plan.test.d.ts +1 -0
  291. package/lib/tests/materialized-reports/materialized-payments-comparison-plan.test.js +149 -0
  292. package/lib/tests/materialized-reports/materialized-prep-time-classification.test.d.ts +1 -0
  293. package/lib/tests/materialized-reports/materialized-prep-time-classification.test.js +273 -0
  294. package/lib/tests/materialized-reports/materialized-prep-time-close-day.test.d.ts +1 -0
  295. package/lib/tests/materialized-reports/materialized-prep-time-close-day.test.js +270 -0
  296. package/lib/tests/materialized-reports/materialized-prep-time-compile.test.d.ts +1 -0
  297. package/lib/tests/materialized-reports/materialized-prep-time-compile.test.js +217 -0
  298. package/lib/tests/materialized-reports/materialized-prep-time-constants.test.d.ts +1 -0
  299. package/lib/tests/materialized-reports/materialized-prep-time-constants.test.js +84 -0
  300. package/lib/tests/materialized-reports/materialized-prep-time-plan.test.d.ts +1 -0
  301. package/lib/tests/materialized-reports/materialized-prep-time-plan.test.js +176 -0
  302. package/lib/tests/materialized-reports/materialized-sales-comparison-baseline.test.d.ts +1 -0
  303. package/lib/tests/materialized-reports/materialized-sales-comparison-baseline.test.js +126 -0
  304. package/lib/tests/materialized-reports/materialized-sales-comparison-compile.test.d.ts +1 -0
  305. package/lib/tests/materialized-reports/materialized-sales-comparison-compile.test.js +206 -0
  306. package/lib/tests/materialized-reports/materialized-sales-comparison-formatter.test.d.ts +1 -0
  307. package/lib/tests/materialized-reports/materialized-sales-comparison-formatter.test.js +179 -0
  308. package/lib/tests/materialized-reports/materialized-sales-comparison-parity.test.d.ts +1 -0
  309. package/lib/tests/materialized-reports/materialized-sales-comparison-parity.test.js +196 -0
  310. package/lib/tests/materialized-reports/materialized-sales-comparison-plan.test.d.ts +1 -0
  311. package/lib/tests/materialized-reports/materialized-sales-comparison-plan.test.js +241 -0
  312. package/lib/tests/materialized-reports/materialized-tenant-hourly-comparison-schema.test.d.ts +1 -0
  313. package/lib/tests/materialized-reports/materialized-tenant-hourly-comparison-schema.test.js +96 -0
  314. package/lib/tests/materialized-reports/materialized-tenant-payments-comparison-schema.test.d.ts +1 -0
  315. package/lib/tests/materialized-reports/materialized-tenant-payments-comparison-schema.test.js +112 -0
  316. package/lib/tests/materialized-reports/materialized-tenant-sales-comparison-schema.test.d.ts +1 -0
  317. package/lib/tests/materialized-reports/materialized-tenant-sales-comparison-schema.test.js +142 -0
  318. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +8 -1
  319. package/lib/tests/materialized-reports/sales-comparison-reference.d.ts +55 -0
  320. package/lib/tests/materialized-reports/sales-comparison-reference.js +86 -0
  321. package/lib/tests/materialized-reports/tenant-discount-formatter.test.d.ts +1 -0
  322. package/lib/tests/materialized-reports/tenant-discount-formatter.test.js +289 -0
  323. package/lib/tests/materialized-reports/tenant-prep-time-formatter.test.d.ts +1 -0
  324. package/lib/tests/materialized-reports/tenant-prep-time-formatter.test.js +354 -0
  325. package/lib/tests/reporting-contract.test.d.ts +1 -0
  326. package/lib/tests/reporting-contract.test.js +267 -0
  327. package/lib/tests/rider-daily-report.test.d.ts +1 -0
  328. package/lib/tests/rider-daily-report.test.js +86 -0
  329. package/lib/tests/rider-earnings.test.d.ts +1 -0
  330. package/lib/tests/rider-earnings.test.js +65 -0
  331. package/lib/tests/rider-report.test.d.ts +1 -0
  332. package/lib/tests/rider-report.test.js +98 -0
  333. package/package.json +10 -1
@@ -0,0 +1,604 @@
1
+ import { MATERIALIZED_DISCOUNT_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
3
+ import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields } from './scope-helpers';
4
+ /** Day-scoped documents (replaced wholesale for the compiled day). */
5
+ const DISCOUNT_DAY_SCOPES = [
6
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
7
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
8
+ ];
9
+ /** Period documents (accumulate day deltas; corrected by subtraction). */
10
+ // DERIVED from the report's scope list, like prep / cash / delivery. Hard-coding this list
11
+ // meant a scope added to MATERIALIZED_DISCOUNT_REPORT_SCOPES could be compiled and read but
12
+ // never accumulated here - and an accumulating scope missing from this list is invisible
13
+ // until a period document disagrees with its days.
14
+ const DISCOUNT_ACCUMULATED_SCOPES = MATERIALIZED_DISCOUNT_REPORT_SCOPES.filter((scope) => !DISCOUNT_DAY_SCOPES.includes(scope));
15
+ /** True for the accumulating (period) scopes. */
16
+ const isAccumulatedScope = (scope) => DISCOUNT_ACCUMULATED_SCOPES.includes(scope);
17
+ const scopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
18
+ /** Every stored scope one local day's plan needs (date + 3 periods + 24 hours). */
19
+ export function getMaterializedDiscountScopeRefsForDay(localDate) {
20
+ const periodFields = getMaterializedPeriodScopeFields(localDate);
21
+ if (periodFields == null)
22
+ return null;
23
+ const refs = [
24
+ { scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, scope_field: localDate },
25
+ ];
26
+ for (const scope of DISCOUNT_ACCUMULATED_SCOPES) {
27
+ refs.push({ scope_context: scope, scope_field: periodFields[scope] });
28
+ }
29
+ for (let hour = 0; hour < 24; hour += 1) {
30
+ const scopeField = getMaterializedHourScopeField(localDate, hour);
31
+ if (scopeField == null)
32
+ return null;
33
+ refs.push({ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: scopeField });
34
+ }
35
+ return refs;
36
+ }
37
+ /**
38
+ * Watermark guard: does the stored document need a structural write?
39
+ * `false` (skip) when the incoming `source_watermark` is not newer than the
40
+ * stored one and the schema version + key grammar match.
41
+ */
42
+ export function needsMaterializedDiscountReportWrite(existing, incoming) {
43
+ if (existing == null || incoming == null)
44
+ return true;
45
+ if (existing.schema_version !== incoming.schema_version)
46
+ return true;
47
+ if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
48
+ return true;
49
+ }
50
+ const existingTime = new Date(existing.source_watermark ?? 0).getTime();
51
+ const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
52
+ if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
53
+ return true;
54
+ return incomingTime > existingTime;
55
+ }
56
+ /** Adds or subtracts every numeric counter field, recursively (`sign` = ±1). */
57
+ function applyCounters(target, delta, sign) {
58
+ if (target == null || delta == null)
59
+ return;
60
+ for (const [key, value] of Object.entries(delta)) {
61
+ if (typeof value === 'number') {
62
+ const current = target[key];
63
+ target[key] = (typeof current === 'number' ? current : 0) + sign * value;
64
+ continue;
65
+ }
66
+ if (value != null && typeof value === 'object' && !Array.isArray(value)) {
67
+ const nested = (target[key] ?? (target[key] = {}));
68
+ applyCounters(nested, value, sign);
69
+ }
70
+ }
71
+ }
72
+ /** True when a counter block is all zeros (pruned so an emptied day leaves no key). */
73
+ function isZeroCounters(counters) {
74
+ if (counters == null)
75
+ return true;
76
+ for (const value of Object.values(counters)) {
77
+ if (typeof value === 'number') {
78
+ if (value !== 0)
79
+ return false;
80
+ continue;
81
+ }
82
+ if (value != null && typeof value === 'object' && !isZeroCounters(value)) {
83
+ return false;
84
+ }
85
+ }
86
+ return true;
87
+ }
88
+ /**
89
+ * Applies a counter update to a stored document: optionally REPLACE the counter
90
+ * map wholesale, else subtract the given deltas and add the compiled ones. Keys
91
+ * that end up all-zero are pruned so a corrected day leaves no ghost entry.
92
+ * Returns `null` on a schema / key-grammar conflict (never throws).
93
+ */
94
+ export function updateMaterializedDiscountReport(existing, updates, options = {}) {
95
+ if (existing == null || updates == null)
96
+ return null;
97
+ if ((existing.sale_type_key_filters ?? []).join(':') !==
98
+ ((updates.replacement ?? updates.additions?.[0])?.sale_type_key_filters ??
99
+ existing.sale_type_key_filters ??
100
+ []).join(':')) {
101
+ return null;
102
+ }
103
+ if (updates.replacement != null &&
104
+ (updates.replacement.schema_version !== existing.schema_version ||
105
+ updates.replacement.scope_context !== existing.scope_context ||
106
+ updates.replacement.scope_field !== existing.scope_field)) {
107
+ return null;
108
+ }
109
+ const computedAt = options.computedAt ?? updates.computedAt ?? new Date();
110
+ const counters = updates.replacement != null
111
+ ? JSON.parse(JSON.stringify(updates.replacement.discount_counters ?? {}))
112
+ : JSON.parse(JSON.stringify(existing.discount_counters ?? {}));
113
+ if (updates.replacement == null) {
114
+ for (const delta of updates.subtract ?? []) {
115
+ if (delta.schema_version !== existing.schema_version)
116
+ return null;
117
+ applyCounters(counters, delta.discount_counters, -1);
118
+ }
119
+ for (const delta of updates.additions ?? []) {
120
+ if (delta.schema_version !== existing.schema_version)
121
+ return null;
122
+ const merged = counters;
123
+ for (const [key, value] of Object.entries(delta.discount_counters ?? {})) {
124
+ const bucket = (merged[key] ?? (merged[key] = {}));
125
+ applyCounters(bucket, value, 1);
126
+ }
127
+ }
128
+ }
129
+ // Prune keys the corrections emptied (an all-zero bucket must not survive).
130
+ for (const key of Object.keys(counters)) {
131
+ if (isZeroCounters(counters[key]))
132
+ delete counters[key];
133
+ }
134
+ const watermarkCandidates = [
135
+ existing.source_watermark,
136
+ updates.sourceWatermark ?? null,
137
+ updates.replacement?.source_watermark ?? null,
138
+ ...(updates.additions ?? []).map((doc) => doc.source_watermark),
139
+ ].filter((value) => value != null);
140
+ const sourceWatermark = watermarkCandidates.reduce((max, value) => (new Date(value).getTime() > new Date(max).getTime() ? value : max), existing.source_watermark);
141
+ const finalCounters = Object.keys(counters).length === 0
142
+ ? null
143
+ : counters;
144
+ return {
145
+ ...existing,
146
+ discount_counters: finalCounters,
147
+ // The read-path rows are REBUILT from the folded map rather than mutated in
148
+ // step with it — one source of truth, so the map and the rows can never
149
+ // disagree (and a correction that empties a key drops it from both).
150
+ discount_counter_rows: finalCounters == null ? null : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
151
+ source_watermark: sourceWatermark,
152
+ computed_at: computedAt,
153
+ updatedAt: computedAt,
154
+ iteration: (existing.iteration ?? 1) + 1,
155
+ };
156
+ }
157
+ /** Row identity inside a period document: an order can hold many rows. */
158
+ const discountEntryRowIdentity = (row) => String(row.order_id) + '|' + String(row.entry_key);
159
+ /**
160
+ * Merges a freshly compiled day of rows into a PERIOD document's stored rows.
161
+ *
162
+ * Idempotent by construction: the merge key is `(order_id, entry_key)`, which is
163
+ * globally unique per row - `entry_key` is the row's stable identity INSIDE its
164
+ * order (`item:<itemId>:<slot>` / `order:<slot>` / `payment:<paymentId>`), and an
165
+ * order belongs to exactly one day. So re-closing the SAME day REPLACES its own
166
+ * rows (fresh wins) instead of duplicating them, while a new day ADDS its rows.
167
+ *
168
+ * Without this, a period document held only the last closed day's rows - the
169
+ * measured symptom was a `localMonth` entry document carrying 9 rows where the
170
+ * equivalent credit-ledger month document carried the whole month (20).
171
+ */
172
+ export const mergeMaterializedDiscountEntrySections = (stored, fresh) => {
173
+ const out = {};
174
+ const keys = new Set([...Object.keys(stored ?? {}), ...Object.keys(fresh ?? {})]);
175
+ for (const key of keys) {
176
+ const byIdentity = new Map();
177
+ for (const row of stored?.[key]?.rows ?? []) {
178
+ byIdentity.set(discountEntryRowIdentity(row), row);
179
+ }
180
+ // FRESH wins: a re-close of the same day overwrites its own rows.
181
+ for (const row of fresh?.[key]?.rows ?? []) {
182
+ byIdentity.set(discountEntryRowIdentity(row), row);
183
+ }
184
+ if (byIdentity.size > 0)
185
+ out[key] = { rows: [...byIdentity.values()] };
186
+ }
187
+ return out;
188
+ };
189
+ /**
190
+ * Removes the given rows from a stored document's sections - the MIRROR of
191
+ * `mergeMaterializedDiscountEntrySections`.
192
+ *
193
+ * Deliberately keyed on the SAME `discountEntryRowIdentity`, so the merge and the
194
+ * subtraction cannot drift: whatever the merge treats as one row, this removes.
195
+ * A section left with no rows disappears, matching the merge's own output shape.
196
+ */
197
+ export const subtractMaterializedDiscountEntrySections = (stored, removed) => {
198
+ const out = {};
199
+ for (const key of Object.keys(stored ?? {})) {
200
+ const removedIdentities = new Set((removed?.[key]?.rows ?? []).map(discountEntryRowIdentity));
201
+ const rows = (stored?.[key]?.rows ?? []).filter((row) => !removedIdentities.has(discountEntryRowIdentity(row)));
202
+ if (rows.length > 0)
203
+ out[key] = { rows };
204
+ }
205
+ return out;
206
+ };
207
+ /**
208
+ * Updates a stored ENTRY document.
209
+ *
210
+ * - DAY scopes (`localHour` / `localDate`) are REPLACED wholesale: the day's rows
211
+ * are the whole truth for that scope.
212
+ * - PERIOD scopes (`localWeek` / `localWeekOfYear` / `localMonth`) MERGE, because
213
+ * the compile produces only ONE day of rows: replacing would leave the period
214
+ * showing just its final day.
215
+ *
216
+ * Returns null when the documents disagree on schema/scope (a data issue the
217
+ * caller must surface).
218
+ */
219
+ export function updateMaterializedDiscountEntries(existing, compiled, options = {}) {
220
+ if (existing == null || compiled == null)
221
+ return null;
222
+ if (existing.schema_version !== compiled.schema_version ||
223
+ existing.scope_context !== compiled.scope_context ||
224
+ existing.scope_field !== compiled.scope_field) {
225
+ return null;
226
+ }
227
+ const computedAt = options.computedAt ?? new Date();
228
+ const existingTime = new Date(existing.source_watermark ?? 0).getTime();
229
+ const compiledTime = new Date(compiled.source_watermark ?? 0).getTime();
230
+ return {
231
+ ...existing,
232
+ discount_entries: options.mergePeriodRows === true
233
+ ? mergeMaterializedDiscountEntrySections(existing.discount_entries, compiled.discount_entries)
234
+ : compiled.discount_entries,
235
+ source_watermark: compiledTime > existingTime ? compiled.source_watermark : existing.source_watermark,
236
+ computed_at: computedAt,
237
+ updatedAt: computedAt,
238
+ iteration: (existing.iteration ?? 1) + 1,
239
+ };
240
+ }
241
+ /** True when a stored entry document equals the compiled one's rows + watermark. */
242
+ export function needsMaterializedDiscountEntriesWrite(existing, incoming) {
243
+ if (existing == null || incoming == null)
244
+ return true;
245
+ if (existing.schema_version !== incoming.schema_version)
246
+ return true;
247
+ if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
248
+ return true;
249
+ }
250
+ const existingTime = new Date(existing.source_watermark ?? 0).getTime();
251
+ const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
252
+ if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
253
+ return true;
254
+ return incomingTime > existingTime;
255
+ }
256
+ /**
257
+ * Builds the close-day write plan for ONE tenant-day. Returns `null` (never
258
+ * throws) on inconsistent input — compiled docs of another tenant, duplicate
259
+ * scope documents, a malformed date, duplicate STORED rows for one scope (a
260
+ * missing unique index), or a schema/grammar conflict.
261
+ */
262
+ export function buildTenantDiscountCloseDayPlan(input) {
263
+ if (input == null)
264
+ return null;
265
+ const { tenantId, reports, entries, reason } = input;
266
+ if (typeof tenantId !== 'string' || tenantId.length === 0)
267
+ return null;
268
+ if (typeof reason !== 'string' || reason.length === 0)
269
+ return null;
270
+ if (!Array.isArray(reports) || !Array.isArray(entries))
271
+ return null;
272
+ if (reports.some((doc) => doc == null || doc.tenant_id !== tenantId))
273
+ return null;
274
+ const computedAt = input.computedAt ?? new Date();
275
+ const force = input.force === true;
276
+ const dateDoc = reports.find((doc) => doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE) ?? null;
277
+ // An emptied day has no compiled documents, so the caller supplies the date.
278
+ const localDate = dateDoc?.scope_field ?? input.localDate ?? null;
279
+ if (localDate == null || getMaterializedDiscountScopeRefsForDay(localDate) == null)
280
+ return null;
281
+ if (dateDoc != null && dateDoc.tenant_id !== tenantId)
282
+ return null;
283
+ const compiledByScope = new Map();
284
+ for (const doc of reports) {
285
+ const key = scopeKey(doc);
286
+ if (compiledByScope.has(key))
287
+ return null; // duplicate — data issue
288
+ compiledByScope.set(key, doc);
289
+ }
290
+ const existingByScope = new Map();
291
+ for (const doc of input.existing ?? []) {
292
+ if (doc == null || doc.tenant_id !== tenantId)
293
+ continue;
294
+ const key = scopeKey(doc);
295
+ const prior = existingByScope.get(key);
296
+ if (prior == null) {
297
+ existingByScope.set(key, doc);
298
+ continue;
299
+ }
300
+ if (String(prior._id) !== String(doc._id))
301
+ return null; // two rows for one scope
302
+ }
303
+ const existingEntriesByScope = new Map();
304
+ /**
305
+ * Rebuilds a PERIOD entry document's rows from the DAY entry documents still on hand.
306
+ *
307
+ * Discount period entries ACCUMULATE each day's rows, so a period document that was never
308
+ * persisted - a partial failure between the counter writes and the entry writes - would
309
+ * otherwise be rebuilt from the CLOSING DAY ALONE, silently dropping every sibling day's
310
+ * rows from the period drill-down even though those days' documents are right there. The
311
+ * counters already repair this case explicitly; without this, the entries did not.
312
+ *
313
+ * Only called when the period document is MISSING, so the normal path keeps its
314
+ * accumulate-forward behaviour and pays nothing for this.
315
+ */
316
+ const refoldPeriodEntrySections = (scopeContext, scopeField) => {
317
+ let folded = {};
318
+ for (const doc of existingEntriesByScope.values()) {
319
+ if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
320
+ continue;
321
+ const refs = getMaterializedDiscountScopeRefsForDay(String(doc.scope_field));
322
+ if (refs == null)
323
+ continue;
324
+ const belongs = refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
325
+ if (!belongs)
326
+ continue;
327
+ folded = mergeMaterializedDiscountEntrySections(folded, doc.discount_entries);
328
+ }
329
+ return folded;
330
+ };
331
+ for (const doc of input.existingEntries ?? []) {
332
+ if (doc == null || doc.tenant_id !== tenantId)
333
+ continue;
334
+ const key = scopeKey(doc);
335
+ const prior = existingEntriesByScope.get(key);
336
+ if (prior == null) {
337
+ existingEntriesByScope.set(key, doc);
338
+ continue;
339
+ }
340
+ if (String(prior._id) !== String(doc._id))
341
+ return null;
342
+ }
343
+ const writes = [];
344
+ const entryWrites = [];
345
+ const staleDocuments = [];
346
+ const staleEntryDocuments = [];
347
+ const skippedDocuments = [];
348
+ const skippedEntryDocuments = [];
349
+ const createdPeriodDocuments = [];
350
+ const addWrite = (report) => {
351
+ const persisted = report.iteration == null ? { ...report, iteration: 1 } : report;
352
+ const iteration = buildMaterializedTenantReportIteration(persisted, {
353
+ reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DISCOUNT_REPORTS,
354
+ reason,
355
+ computedAt,
356
+ });
357
+ if (iteration == null)
358
+ return null;
359
+ writes.push({ report: persisted, iteration });
360
+ return persisted;
361
+ };
362
+ const addEntryWrite = (report) => {
363
+ const persisted = report.iteration == null ? { ...report, iteration: 1 } : report;
364
+ const iteration = buildMaterializedTenantReportIteration(persisted, {
365
+ reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DISCOUNT_ENTRIES,
366
+ reason,
367
+ computedAt,
368
+ });
369
+ if (iteration == null)
370
+ return null;
371
+ entryWrites.push({ report: persisted, iteration });
372
+ return persisted;
373
+ };
374
+ const storedDateDoc = existingByScope.get(`${MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
375
+ const storedDateDocInCompiled = compiledByScope.get(`${MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
376
+ // The rows this day CURRENTLY contributes, read from its own day-scoped entry documents.
377
+ // A period entry document MERGES day rows in, and a merge can only ADD or OVERWRITE - it
378
+ // cannot remove. So any close that replaces this day must subtract these rows from every
379
+ // period document first, or rows the correction removed linger there as phantoms while the
380
+ // DAY document correctly shrinks. Two callers need this: the emptied-day path (subtract
381
+ // everything) and the normal path (subtract, then merge the fresh rows back).
382
+ const storedDayEntrySections = {};
383
+ const isThisDayEntryDoc = (doc) => doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
384
+ ? doc.scope_field === localDate
385
+ : doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
386
+ typeof doc.scope_field === 'string' &&
387
+ doc.scope_field.startsWith(`${localDate} `);
388
+ for (const doc of existingEntriesByScope.values()) {
389
+ if (!isThisDayEntryDoc(doc))
390
+ continue;
391
+ for (const [key, section] of Object.entries(doc.discount_entries ?? {})) {
392
+ storedDayEntrySections[key] = {
393
+ rows: [...(storedDayEntrySections[key]?.rows ?? []), ...(section?.rows ?? [])],
394
+ };
395
+ }
396
+ }
397
+ if (reports.length === 0) {
398
+ // The day has NO discounts anymore (orders deleted / moved): subtract the
399
+ // stored day from every period document and drop the day's documents.
400
+ if (storedDateDoc != null) {
401
+ for (const doc of existingByScope.values()) {
402
+ if (!isAccumulatedScope(doc.scope_context))
403
+ continue;
404
+ const updated = updateMaterializedDiscountReport(doc, { subtract: [storedDateDoc] }, { computedAt });
405
+ if (updated == null)
406
+ return null;
407
+ if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
408
+ continue;
409
+ if (addWrite(updated) == null)
410
+ return null;
411
+ }
412
+ for (const doc of existingByScope.values()) {
413
+ if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
414
+ staleDocuments.push(doc);
415
+ }
416
+ // ENTRY documents. A PERIOD entry document ACCUMULATES every day's rows
417
+ // (`updateMaterializedDiscountEntries` merges them in), so DELETING it discards
418
+ // every OTHER day it holds - those rows exist nowhere else. The emptied day must
419
+ // be SUBTRACTED from each period document, and only the day's OWN documents
420
+ // dropped. Deleting the period document would also leave the period drill-down
421
+ // empty until some later close recreated it, holding that one day.
422
+ for (const doc of existingEntriesByScope.values()) {
423
+ if (isThisDayEntryDoc(doc))
424
+ staleEntryDocuments.push(doc);
425
+ }
426
+ for (const doc of existingEntriesByScope.values()) {
427
+ // Another day's document is not this close's business - never touch it.
428
+ if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
429
+ continue;
430
+ const remaining = subtractMaterializedDiscountEntrySections(doc.discount_entries, storedDayEntrySections);
431
+ const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
432
+ const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
433
+ // Nothing of this day was in that period: leave it untouched.
434
+ if (rowsAfter === rowsBefore)
435
+ continue;
436
+ // No rows left anywhere in the period: the document itself goes.
437
+ if (rowsAfter === 0) {
438
+ staleEntryDocuments.push(doc);
439
+ continue;
440
+ }
441
+ if (addEntryWrite({
442
+ ...doc,
443
+ discount_entries: remaining,
444
+ computed_at: computedAt,
445
+ updatedAt: computedAt,
446
+ iteration: (doc.iteration ?? 1) + 1,
447
+ }) == null) {
448
+ return null;
449
+ }
450
+ }
451
+ }
452
+ return {
453
+ writes,
454
+ entryWrites,
455
+ staleDocuments,
456
+ staleEntryDocuments,
457
+ skippedDocuments,
458
+ skippedEntryDocuments,
459
+ createdPeriodDocuments,
460
+ };
461
+ }
462
+ const dayChanged = force || needsMaterializedDiscountReportWrite(storedDateDoc, storedDateDocInCompiled);
463
+ if (!dayChanged) {
464
+ for (const compiled of reports) {
465
+ const existing = existingByScope.get(scopeKey(compiled)) ?? null;
466
+ if (existing != null)
467
+ skippedDocuments.push(existing);
468
+ // Partial-failure repair: the day is up to date but this doc was never persisted.
469
+ else if (addWrite(compiled) == null)
470
+ return null;
471
+ }
472
+ }
473
+ else {
474
+ for (const compiled of reports) {
475
+ const existing = existingByScope.get(scopeKey(compiled)) ?? null;
476
+ if (DISCOUNT_DAY_SCOPES.includes(compiled.scope_context)) {
477
+ if (existing == null) {
478
+ if (addWrite(compiled) == null)
479
+ return null;
480
+ }
481
+ else {
482
+ const updated = updateMaterializedDiscountReport(existing, { replacement: compiled }, { computedAt });
483
+ if (updated == null || addWrite(updated) == null)
484
+ return null;
485
+ }
486
+ continue;
487
+ }
488
+ if (!isAccumulatedScope(compiled.scope_context))
489
+ return null; // unknown scope
490
+ if (existing == null) {
491
+ if (addWrite(compiled) == null)
492
+ return null;
493
+ createdPeriodDocuments.push({ scope_context: compiled.scope_context, scope_field: compiled.scope_field });
494
+ continue;
495
+ }
496
+ const updated = updateMaterializedDiscountReport(existing, { subtract: storedDateDoc != null ? [storedDateDoc] : [], additions: [compiled] }, { computedAt });
497
+ if (updated == null || addWrite(updated) == null)
498
+ return null;
499
+ }
500
+ // Stored hour documents of this day with no activity left.
501
+ for (const doc of existingByScope.values()) {
502
+ if (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
503
+ typeof doc.scope_field === 'string' &&
504
+ doc.scope_field.startsWith(`${localDate} `) &&
505
+ !compiledByScope.has(scopeKey(doc))) {
506
+ staleDocuments.push(doc);
507
+ }
508
+ }
509
+ }
510
+ // ---- entry documents ------------------------------------------------------
511
+ // DAY scopes are replaced wholesale (the day is the whole truth); PERIOD scopes
512
+ // MERGE the day's rows in - see updateMaterializedDiscountEntries. ----------
513
+ const compiledEntriesByScope = new Map();
514
+ for (const doc of entries) {
515
+ if (doc == null || doc.tenant_id !== tenantId)
516
+ return null;
517
+ const key = scopeKey(doc);
518
+ if (compiledEntriesByScope.has(key))
519
+ return null; // duplicate — data issue
520
+ compiledEntriesByScope.set(key, doc);
521
+ }
522
+ for (const compiled of compiledEntriesByScope.values()) {
523
+ const existing = existingEntriesByScope.get(scopeKey(compiled)) ?? null;
524
+ if (!dayChanged && existing != null && !needsMaterializedDiscountEntriesWrite(existing, compiled)) {
525
+ skippedEntryDocuments.push(existing);
526
+ continue;
527
+ }
528
+ if (existing == null) {
529
+ const missingIsPeriod = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
530
+ if (!missingIsPeriod) {
531
+ if (addEntryWrite(compiled) == null)
532
+ return null;
533
+ continue;
534
+ }
535
+ // Never persisted: rebuild from the sibling days, minus this day's stored rows (a
536
+ // correction may have REMOVED rows), then merge this day's fresh rows on top.
537
+ const folded = subtractMaterializedDiscountEntrySections(refoldPeriodEntrySections(compiled.scope_context, String(compiled.scope_field)), storedDayEntrySections);
538
+ const rebuilt = mergeMaterializedDiscountEntrySections(folded, compiled.discount_entries);
539
+ if (addEntryWrite({ ...compiled, discount_entries: rebuilt }) == null)
540
+ return null;
541
+ continue;
542
+ }
543
+ // A PERIOD document accumulates every day of the period; a DAY document is
544
+ // the day itself. Replacing a period wholesale left it holding only the
545
+ // final closed day (measured).
546
+ const isPeriodEntry = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
547
+ // PERIOD documents: remove this day's STORED rows FIRST, then merge the fresh ones.
548
+ // Merging alone cannot remove, so a correction that dropped a row left it behind in
549
+ // the period while the day document shrank - a phantom row in the period drill-down.
550
+ // DAY documents are replaced wholesale and need no subtraction.
551
+ const updated = updateMaterializedDiscountEntries(isPeriodEntry
552
+ ? {
553
+ ...existing,
554
+ discount_entries: subtractMaterializedDiscountEntrySections(existing.discount_entries, storedDayEntrySections),
555
+ }
556
+ : existing, compiled, { computedAt, mergePeriodRows: isPeriodEntry });
557
+ if (updated == null || addEntryWrite(updated) == null)
558
+ return null;
559
+ }
560
+ // Stored entry documents for this day's scopes that the compile no longer has.
561
+ for (const doc of existingEntriesByScope.values()) {
562
+ if (compiledEntriesByScope.has(scopeKey(doc)))
563
+ continue;
564
+ const isDayScoped = doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
565
+ ? doc.scope_field === localDate
566
+ : doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
567
+ typeof doc.scope_field === 'string' &&
568
+ doc.scope_field.startsWith(`${localDate} `);
569
+ if (isDayScoped) {
570
+ staleEntryDocuments.push(doc);
571
+ continue;
572
+ }
573
+ // A DAY-scoped document belonging to ANOTHER day is simply not this close's
574
+ // business. Without this guard it fell through to the period branch below, where
575
+ // the compile had (correctly) not emitted it, so it was marked STALE and DELETED -
576
+ // meaning every close wiped every OTHER day's entry rows. Measured in the demo data
577
+ // before the fix: counters covered 19 discount days while only ONE day of entry rows
578
+ // survived, so the drill-down was empty for 18 days that the summary said had
579
+ // discounts. The period branch must only ever see PERIOD scopes.
580
+ if (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
581
+ doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
582
+ continue;
583
+ }
584
+ // A PERIOD entry document must drop this day's rows: rows never accumulate,
585
+ // so a period doc carries the whole period's rows. When the day lost its
586
+ // rows the period doc is rebuilt from the compile's period entry sections
587
+ // (which the compile already produces per period scope).
588
+ const periodCompiled = compiledEntriesByScope.get(scopeKey(doc));
589
+ if (periodCompiled == null) {
590
+ // No rows left anywhere in this period scope for the compiled day — the
591
+ // caller's fetch includes it only when the compile emitted it, so drop it.
592
+ staleEntryDocuments.push(doc);
593
+ }
594
+ }
595
+ return {
596
+ writes,
597
+ entryWrites,
598
+ staleDocuments,
599
+ staleEntryDocuments,
600
+ skippedDocuments,
601
+ skippedEntryDocuments,
602
+ createdPeriodDocuments,
603
+ };
604
+ }