@stacksjs/defaults 0.75.489 → 0.75.492

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 (153) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +20 -2
  3. package/ai/skills/stacks-native/CATALOG.md +9 -9
  4. package/ai/skills/stacks-search-engine/SKILL.md +14 -0
  5. package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
  6. package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
  7. package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
  8. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
  9. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
  10. package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
  11. package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
  12. package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
  13. package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
  14. package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
  15. package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
  16. package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
  17. package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
  18. package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
  19. package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
  20. package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
  21. package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
  22. package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
  23. package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
  24. package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
  25. package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
  26. package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
  27. package/app/Actions/Dashboard/Commerce/ProductUnitIndexAction.ts +23 -19
  28. package/app/Actions/Dashboard/Commerce/ProductVariantIndexAction.ts +25 -18
  29. package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
  30. package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
  31. package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
  32. package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
  33. package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
  34. package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
  35. package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
  36. package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
  37. package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
  38. package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
  39. package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
  40. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
  41. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
  42. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
  43. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
  44. package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
  45. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
  46. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
  47. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
  48. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
  49. package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
  50. package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
  51. package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
  52. package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
  53. package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
  54. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
  55. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
  56. package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
  57. package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
  58. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
  59. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
  60. package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
  61. package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
  62. package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.test.ts +146 -0
  63. package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.ts +178 -0
  64. package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.test.ts +165 -0
  65. package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.ts +209 -0
  66. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
  67. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
  68. package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
  69. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
  70. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
  71. package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
  72. package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
  73. package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
  74. package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
  75. package/app/Actions/Dashboard/Commerce/product-unit-records.test.ts +0 -13
  76. package/app/Actions/Dashboard/Commerce/product-unit-records.ts +0 -17
  77. package/app/Actions/Dashboard/Commerce/product-variant-records.test.ts +0 -13
  78. package/app/Actions/Dashboard/Commerce/product-variant-records.ts +0 -17
  79. package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
  80. package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
  81. package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
  82. package/app/Actions/Dashboard/Content/content-list.ts +10 -0
  83. package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
  84. package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
  85. package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
  86. package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
  87. package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
  88. package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
  89. package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
  90. package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
  91. package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
  92. package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
  93. package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
  94. package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
  95. package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
  96. package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
  97. package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +5 -3
  98. package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
  99. package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
  100. package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
  101. package/app/Actions/Dashboard/named-search.test.ts +36 -0
  102. package/app/Actions/Dashboard/named-search.ts +80 -0
  103. package/app/Models/Request.ts +4 -2
  104. package/functions/commerce/shippings/dashboard-resource.ts +12 -1
  105. package/functions/commerce/shippings/delivery-routes.ts +1 -0
  106. package/functions/commerce/shippings/license-keys.ts +1 -0
  107. package/functions/dashboard-list.test.ts +146 -1
  108. package/functions/dashboard-list.ts +216 -1
  109. package/functions/queue.ts +2 -0
  110. package/ide/vscode/package.json +1 -1
  111. package/package.json +2 -2
  112. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
  113. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
  114. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
  115. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
  116. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
  117. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
  118. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
  119. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
  120. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
  121. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
  122. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
  123. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
  124. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
  125. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
  126. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
  127. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
  128. package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +63 -8
  129. package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +48 -60
  130. package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +29 -3
  131. package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +57 -3
  132. package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +59 -61
  133. package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +28 -2
  134. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
  135. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
  136. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
  137. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
  138. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
  139. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
  140. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
  141. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
  142. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
  143. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
  144. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
  145. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
  146. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
  147. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
  148. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
  149. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
  150. package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
  151. package/resources/components/Dashboard/Queue/QueueDashboard.stx +7 -1
  152. package/routes/dashboard-api.ts +11 -0
  153. package/views/dashboard/stores/kanban.ts +38 -6
@@ -0,0 +1,180 @@
1
+ import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
2
+ import { db, getDatabaseDialect } from '@stacksjs/database/runtime'
3
+ import type { QueryReader } from '../Content/content-list'
4
+ import { containsPattern, countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
5
+ import { deliveryTimestamp } from './commerce-delivery'
6
+ import { recentRoutes } from './commerce-delivery-overview'
7
+ import { referencedIds } from './commerce-record'
8
+ import type { CommerceSqlRunner } from './commerce-sql'
9
+ import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
10
+ import type { DeliveryRouteRecord } from './delivery-route-records'
11
+ import { indexDeliveryRouteCouriers, normalizeDeliveryRouteRecord } from './delivery-route-records'
12
+
13
+ /**
14
+ * One page of delivery routes, searched, sorted and counted by the database,
15
+ * with the summary of every route (stacksjs/stacks#3218).
16
+ *
17
+ * The Delivery Routes page used to read the 500 most recently active routes
18
+ * and do all of that in the browser, so an older route could not be found,
19
+ * and its cards (routes, stops, distance, active in 24h) counted those 500.
20
+ */
21
+ export const DELIVERY_ROUTE_SORTS = ['active', 'id', 'courier', 'vehicle', 'stops', 'time', 'distance'] as const
22
+ export type DeliveryRouteSort = typeof DELIVERY_ROUTE_SORTS[number]
23
+
24
+ export interface DeliveryRouteListQuery {
25
+ search: string
26
+ sort: DeliveryRouteSort
27
+ direction: 'asc' | 'desc'
28
+ page: number
29
+ perPage: number
30
+ }
31
+
32
+ export interface DeliveryRouteSummary {
33
+ total: number
34
+ /** Routes linked to a courier record. */
35
+ linked: number
36
+ stops: number
37
+ distance: number
38
+ /** Routes active within a day of now. */
39
+ active: number
40
+ }
41
+
42
+ export function parseDeliveryRouteListQuery(read: QueryReader): DeliveryRouteListQuery | { error: string } {
43
+ const pageText = queryText(read, 'page')
44
+ const page = pageText === '' ? 1 : Number(pageText)
45
+ if (!Number.isInteger(page) || page < 1)
46
+ return { error: 'page must be a whole number of 1 or more.' }
47
+
48
+ const sizeText = queryText(read, 'per_page')
49
+ const perPage = sizeText === '' ? 25 : Number(sizeText)
50
+ if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
51
+ return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
52
+
53
+ const sort = queryText(read, 'sort') || 'active'
54
+ if (!(DELIVERY_ROUTE_SORTS as readonly string[]).includes(sort))
55
+ return { error: `sort must be one of ${DELIVERY_ROUTE_SORTS.join(', ')}.` }
56
+
57
+ const directionText = queryText(read, 'direction').toLowerCase()
58
+ const direction = directionText === '' ? (sort === 'active' ? 'desc' : 'asc') : directionText
59
+ if (direction !== 'asc' && direction !== 'desc')
60
+ return { error: 'direction must be asc or desc.' }
61
+
62
+ const search = queryText(read, 'q')
63
+ if (search.length > 200)
64
+ return { error: 'q must be 200 characters or fewer.' }
65
+
66
+ return { search, sort: sort as DeliveryRouteSort, direction, page, perPage }
67
+ }
68
+
69
+ const FROM = ' FROM delivery_routes r LEFT JOIN couriers c ON c.id = r.courier_id'
70
+
71
+ /**
72
+ * `last_active` in time order. It is text: the model writes Unix milliseconds,
73
+ * and seconds are read too. A ten-digit seconds value and a thirteen-digit
74
+ * millisecond value from different seconds differ in their first ten digits,
75
+ * so the two already compare as text in time order; only values inside one
76
+ * second could tie the wrong way.
77
+ */
78
+ function lastActive(dialect: QueryBuilderDialect): string {
79
+ return asText('r.last_active', dialect)
80
+ }
81
+
82
+ function sortExpression(sort: DeliveryRouteSort, dialect: QueryBuilderDialect): string {
83
+ switch (sort) {
84
+ case 'id': return 'r.id'
85
+ case 'courier': return 'LOWER(COALESCE(c.name, r.courier))'
86
+ case 'vehicle': return 'LOWER(r.vehicle)'
87
+ case 'stops': return 'r.stops'
88
+ case 'time': return 'r.delivery_time'
89
+ case 'distance': return 'r.total_distance'
90
+ default: return lastActive(dialect)
91
+ }
92
+ }
93
+
94
+ export function deliveryRouteFilter(query: Pick<DeliveryRouteListQuery, 'search'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
95
+ if (!query.search)
96
+ return { where: '', values: [] }
97
+ const { bind, values } = binder(dialect)
98
+ const pattern = containsPattern(query.search)
99
+ const columns = [
100
+ asText('r.id', dialect),
101
+ 'r.courier',
102
+ `COALESCE(c.name, '')`,
103
+ 'r.vehicle',
104
+ asText('r.stops', dialect),
105
+ asText('r.delivery_time', dialect),
106
+ asText('r.total_distance', dialect),
107
+ ]
108
+ return { where: ` WHERE (${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`, values }
109
+ }
110
+
111
+ function orderBy(query: Pick<DeliveryRouteListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
112
+ const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
113
+ // Ties read most recently active first; the id breaks every remaining tie,
114
+ // so pages never repeat or skip a route.
115
+ if (query.sort === 'active' || query.sort === 'id')
116
+ return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, r.id ${direction}`
117
+ return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, ${lastActive(dialect)} DESC, r.id DESC`
118
+ }
119
+
120
+ /** Routes turned into records, against exactly the couriers they reference. */
121
+ async function recordsFor(routes: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<DeliveryRouteRecord[]> {
122
+ if (routes.length === 0)
123
+ return []
124
+ const courierIds = referencedIds(routes, 'courier_id')
125
+ const couriers = courierIds.length > 0
126
+ ? await run.unsafe(`SELECT id, name, vehicle_number, status FROM couriers WHERE id IN (${idPlaceholders(courierIds, dialect)})`, courierIds).execute()
127
+ : []
128
+ const byId = indexDeliveryRouteCouriers(sqlRows(couriers))
129
+ return routes.map(route => normalizeDeliveryRouteRecord(route, byId))
130
+ }
131
+
132
+ /** The summary cards, over every route as before. */
133
+ async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect, now: Date): Promise<DeliveryRouteSummary> {
134
+ const recent = recentRoutes(dialect, now)
135
+ const [totals, candidates] = await Promise.all([
136
+ run.unsafe('SELECT COUNT(*) AS total_count, COUNT(courier_id) AS linked_count, SUM(stops) AS stop_total, SUM(total_distance) AS distance_total FROM delivery_routes').execute(),
137
+ run.unsafe(`SELECT id, last_active FROM delivery_routes${recent.where}`, recent.values).execute(),
138
+ ])
139
+ const row = sqlRows(totals)[0] ?? {}
140
+ // recentRoutes is a superset for anything but Unix times; this is the exact cut.
141
+ const cutoff = now.getTime() - 24 * 60 * 60 * 1000
142
+ const active = sqlRows(candidates).filter((route) => {
143
+ const at = deliveryTimestamp(route.last_active, `DeliveryRoute ${route.id}`)
144
+ return at >= cutoff && at <= now.getTime()
145
+ }).length
146
+ return {
147
+ total: countOf(row.total_count),
148
+ linked: countOf(row.linked_count),
149
+ stops: countOf(row.stop_total),
150
+ distance: countOf(row.distance_total),
151
+ active,
152
+ }
153
+ }
154
+
155
+ export interface DeliveryRoutePage {
156
+ records: DeliveryRouteRecord[]
157
+ total: number
158
+ page: number
159
+ summary: DeliveryRouteSummary
160
+ }
161
+
162
+ export async function readDeliveryRoutePage(
163
+ query: DeliveryRouteListQuery,
164
+ run: CommerceSqlRunner = db,
165
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
166
+ now: Date = new Date(),
167
+ ): Promise<DeliveryRoutePage> {
168
+ const { where, values } = deliveryRouteFilter(query, dialect)
169
+ const [counted, summary] = await Promise.all([
170
+ run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
171
+ summarize(run, dialect, now),
172
+ ])
173
+ const total = countOf(sqlRows(counted)[0]?.total_count)
174
+ const page = pageWithin(query.page, total, query.perPage)
175
+ const routes = await run.unsafe(
176
+ `SELECT r.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
177
+ values,
178
+ ).execute()
179
+ return { records: await recordsFor(sqlRows(routes), run, dialect), total, page, summary }
180
+ }
@@ -81,6 +81,19 @@ export function formatDeliveryDuration(minutes: number): string {
81
81
  return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`
82
82
  }
83
83
 
84
+ /** How many couriers there are, by status, when the database counted them. */
85
+ export interface DeliveryCourierCounts {
86
+ total: number
87
+ active: number
88
+ onDelivery: number
89
+ onBreak: number
90
+ }
91
+
92
+ /**
93
+ * The overview from the rows it shows. `courierRows` are the couriers the
94
+ * routes reference; `courierCounts`, when given, are every courier counted by
95
+ * the database (readDeliveryOverview), and otherwise `courierRows` are counted.
96
+ */
84
97
  export function buildDeliveryOverview(
85
98
  methodRows: any[],
86
99
  routeRows: any[],
@@ -88,6 +101,7 @@ export function buildDeliveryOverview(
88
101
  courierRows: any[],
89
102
  currency = 'USD',
90
103
  now = new Date(),
104
+ courierCounts?: DeliveryCourierCounts,
91
105
  ): DeliveryOverviewResult {
92
106
  const normalizedCurrency = commerceCurrency(currency, 'Commerce configuration')
93
107
  const normalizedCouriers = courierRows.map((courier) => {
@@ -222,10 +236,16 @@ export function buildDeliveryOverview(
222
236
  return statusOrder || left.name.localeCompare(right.name)
223
237
  })
224
238
 
225
- const courierStatusCounts = normalizedCouriers.reduce<Record<string, number>>((counts, courier) => {
239
+ const counted = normalizedCouriers.reduce<Record<string, number>>((counts, courier) => {
226
240
  counts[courier.status] = (counts[courier.status] || 0) + 1
227
241
  return counts
228
242
  }, {})
243
+ const couriers: DeliveryCourierCounts = courierCounts ?? {
244
+ total: normalizedCouriers.length,
245
+ active: counted.active || 0,
246
+ onDelivery: counted.on_delivery || 0,
247
+ onBreak: counted.on_break || 0,
248
+ }
229
249
 
230
250
  const averageRouteMinutes = activeRoutes.length > 0
231
251
  ? Math.round(activeRoutes.reduce((total, route) => total + (routeMinutesById.get(route.id) || 0), 0) / activeRoutes.length)
@@ -241,8 +261,8 @@ export function buildDeliveryOverview(
241
261
  },
242
262
  {
243
263
  label: 'Couriers on Delivery',
244
- value: (courierStatusCounts.on_delivery || 0).toLocaleString('en-US'),
245
- detail: `${courierRows.length.toLocaleString('en-US')} couriers total`,
264
+ value: couriers.onDelivery.toLocaleString('en-US'),
265
+ detail: `${couriers.total.toLocaleString('en-US')} couriers total`,
246
266
  },
247
267
  {
248
268
  label: 'Average Route',
@@ -258,12 +278,7 @@ export function buildDeliveryOverview(
258
278
  routes: activeRoutes.slice(0, 5),
259
279
  methods: methods.slice(0, 5),
260
280
  zones: zones.slice(0, 5),
261
- couriers: {
262
- total: normalizedCouriers.length,
263
- active: courierStatusCounts.active || 0,
264
- onDelivery: courierStatusCounts.on_delivery || 0,
265
- onBreak: courierStatusCounts.on_break || 0,
266
- },
281
+ couriers,
267
282
  }
268
283
  }
269
284
  import {
@@ -0,0 +1,221 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { SQL } from 'bun'
3
+ import { describe, expect, test } from 'bun:test'
4
+ import type { GiftCardListQuery } from './commerce-gift-card-list'
5
+ import { giftCardsCsv, parseGiftCardListQuery, readGiftCardPage, readGiftCardsForExport } from './commerce-gift-card-list'
6
+ import type { CommerceSqlRunner } from './commerce-sql'
7
+
8
+ /**
9
+ * The Gift Cards list against each dialect's real engine (stacksjs/stacks#3218),
10
+ * with status as a real enum and the flags as each dialect stores booleans.
11
+ */
12
+ type Dialect = 'sqlite' | 'postgres' | 'mysql'
13
+
14
+ const NOW = new Date('2026-11-06T12:00:00.000Z')
15
+ const STATUSES = ['ACTIVE', 'USED', 'EXPIRED', 'DEACTIVATED'] as const
16
+ const NAMES = ['alice', 'Bob', 'carol', 'Dave', 'erin', 'Frank', 'gina']
17
+ const CUSTOMERS = 600
18
+
19
+ /** 26 cards, one an hour back from NOW; 11 and 12 share a creation time. */
20
+ const CARDS = Array.from({ length: 26 }, (_, index) => {
21
+ const id = index + 1
22
+ const status = STATUSES[id % STATUSES.length]!
23
+ const initial = 5000 + id * 100
24
+ return {
25
+ id,
26
+ code: id === 9 ? 'SALE_100%' : id === 10 ? 'GC-1000' : `GC-${String(id).padStart(3, '0')}`,
27
+ initial_balance: initial,
28
+ current_balance: status === 'USED' || id === 4 ? 0 : initial - (id % 3) * 250,
29
+ currency: id % 6 === 0 ? 'usd' : id % 2 === 0 ? 'USD' : 'EUR',
30
+ status,
31
+ purchaser_id: id === 21 ? 'PURCH-XYZ' : null,
32
+ recipient_email: id === 13 ? null : `r${id}@example.com`,
33
+ recipient_name: id === 13 ? null : NAMES[id % NAMES.length]!,
34
+ is_digital: id % 2 === 0,
35
+ is_reloadable: id % 5 === 0,
36
+ is_active: id % 3 !== 0,
37
+ expiry_days: id % 4 === 1 ? null : (id * 7) % 26,
38
+ customer_id: id === 1 ? CUSTOMERS : id === 2 ? 3 : null,
39
+ hoursAgo: id === 12 ? 11 : id,
40
+ }
41
+ })
42
+ type Card = typeof CARDS[number]
43
+
44
+ const ids = (cards: Card[]) => cards.map(card => String(card.id))
45
+ const byCode = (a: Card, b: Card) => a.code.toLowerCase().localeCompare(b.code.toLowerCase())
46
+
47
+ function query(overrides: Partial<GiftCardListQuery> = {}): GiftCardListQuery {
48
+ return { search: '', status: '', enabled: '', delivery: '', sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
49
+ }
50
+
51
+ async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
52
+ const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
53
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
54
+ const flag = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
55
+ const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
56
+ let statusType = text
57
+ if (dialect === 'postgres') {
58
+ await run(`CREATE TYPE gift_card_status AS ENUM (${STATUSES.map(s => `'${s}'`).join(', ')})`)
59
+ statusType = 'gift_card_status'
60
+ }
61
+ if (dialect === 'mysql')
62
+ statusType = `ENUM(${STATUSES.map(s => `'${s}'`).join(', ')})`
63
+ await run(`CREATE TABLE customers (id ${pk})`)
64
+ await run(`CREATE TABLE gift_cards (id ${pk}, code ${text}, initial_balance INTEGER, current_balance INTEGER, currency ${text}, status ${statusType}, purchaser_id ${text} NULL, recipient_email ${text} NULL, recipient_name ${text} NULL, personal_message ${text} NULL, is_digital ${flag}, is_reloadable ${flag}, is_active ${flag}, expiry_date ${time} NULL, last_used_date ${time} NULL, template_id ${text} NULL, customer_id INTEGER NULL, created_at ${time})`)
65
+ const p = (count: number) => Array.from({ length: count }, (_, i) => dialect === 'postgres' ? `$${i + 1}` : '?').join(', ')
66
+ // Past the 500 customers the page used to read for its record check.
67
+ const customerIds = Array.from({ length: CUSTOMERS }, (_, i) => i + 1)
68
+ await run(`INSERT INTO customers (id) VALUES ${customerIds.map((_, i) => `(${dialect === 'postgres' ? `$${i + 1}` : '?'})`).join(', ')}`, customerIds)
69
+ const stamp = (date: Date) => date.toISOString().slice(0, 19).replace('T', ' ')
70
+ const bool = (value: boolean) => dialect === 'postgres' ? value : (value ? 1 : 0)
71
+ for (const card of CARDS) {
72
+ await run(
73
+ `INSERT INTO gift_cards (id, code, initial_balance, current_balance, currency, status, purchaser_id, recipient_email, recipient_name, is_digital, is_reloadable, is_active, expiry_date, customer_id, created_at) VALUES (${p(15)})`,
74
+ [
75
+ card.id, card.code, card.initial_balance, card.current_balance, card.currency, card.status, card.purchaser_id,
76
+ card.recipient_email, card.recipient_name, bool(card.is_digital), bool(card.is_reloadable), bool(card.is_active),
77
+ card.expiry_days === null ? null : stamp(new Date(NOW.getTime() + card.expiry_days * 86_400_000)),
78
+ card.customer_id, stamp(new Date(NOW.getTime() - card.hoursAgo * 3_600_000)),
79
+ ],
80
+ )
81
+ }
82
+ }
83
+
84
+ async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
85
+ const read = (overrides: Partial<GiftCardListQuery> = {}) => readGiftCardPage(query(overrides), runner, dialect)
86
+ const all = (overrides: Partial<GiftCardListQuery> = {}) => read({ perPage: 100, ...overrides })
87
+
88
+ // The summary counts every card, whatever the page is filtered to.
89
+ const filtered = await read({ status: 'USED' })
90
+ const summary = filtered.summary
91
+ expect(summary.total).toBe(CARDS.length)
92
+ expect(summary.available).toBe(CARDS.filter(card => card.status === 'ACTIVE' && card.is_active && card.current_balance > 0).length)
93
+ expect(summary.enabled).toBe(CARDS.filter(card => card.is_active).length)
94
+ expect(summary.digital).toBe(CARDS.filter(card => card.is_digital).length)
95
+ expect(summary.reloadable).toBe(CARDS.filter(card => card.is_reloadable).length)
96
+ for (const status of STATUSES)
97
+ expect(summary.statuses[status]).toBe(CARDS.filter(card => card.status === status).length)
98
+ const inCurrency = (currency: string) => CARDS.filter(card => card.currency.toUpperCase() === currency)
99
+ expect(summary.currencies.map(entry => entry.currency)).toEqual(['EUR', 'USD'])
100
+ for (const entry of summary.currencies) {
101
+ const cards = inCurrency(entry.currency)
102
+ expect(entry.cards).toBe(cards.length)
103
+ expect(entry.initialBalance).toBe(cards.reduce((sum, card) => sum + card.initial_balance, 0))
104
+ expect(entry.currentBalance).toBe(cards.reduce((sum, card) => sum + card.current_balance, 0))
105
+ expect(entry.redeemedBalance).toBe(cards.reduce((sum, card) => sum + Math.max(0, card.initial_balance - card.current_balance), 0))
106
+ }
107
+ expect(filtered.total).toBe(CARDS.filter(card => card.status === 'USED').length)
108
+
109
+ // Filters, alone and together.
110
+ expect((await read({ enabled: 'enabled' })).total).toBe(CARDS.filter(card => card.is_active).length)
111
+ expect((await read({ enabled: 'disabled' })).total).toBe(CARDS.filter(card => !card.is_active).length)
112
+ expect((await read({ delivery: 'digital' })).total).toBe(CARDS.filter(card => card.is_digital).length)
113
+ expect((await read({ delivery: 'physical' })).total).toBe(CARDS.filter(card => !card.is_digital).length)
114
+ expect(ids((await all({ status: 'ACTIVE', enabled: 'enabled', delivery: 'digital', sort: 'id', direction: 'asc' })).records.map(record => CARDS[Number(record.id) - 1]!)))
115
+ .toEqual(ids(CARDS.filter(card => card.status === 'ACTIVE' && card.is_active && card.is_digital)))
116
+
117
+ // Search ignores case, treats % literally, and reaches the purchaser.
118
+ expect((await read({ search: '100%' })).records.map(record => record.id)).toEqual(['9'])
119
+ expect((await read({ search: 'purch-xyz' })).records.map(record => record.id)).toEqual(['21'])
120
+ expect((await read({ search: 'EXAMPLE.COM' })).total).toBe(CARDS.length - 1)
121
+ expect((await read({ search: 'bob' })).total).toBe(CARDS.filter(card => card.recipient_name === 'Bob').length)
122
+
123
+ // Newest first, the id breaking the tie between 11 and 12, stable across pages.
124
+ const newest = [...CARDS].sort((a, b) => a.hoursAgo - b.hoursAgo || b.id - a.id)
125
+ const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
126
+ expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(ids(newest))
127
+ expect(pages[0]!.total).toBe(CARDS.length)
128
+ expect((await read({ page: 9 })).page).toBe(3)
129
+
130
+ // Sorts, with ties read by code.
131
+ const sorted = async (sort: GiftCardListQuery['sort'], direction: 'asc' | 'desc') =>
132
+ (await all({ sort, direction })).records.map(record => record.id)
133
+ expect(await sorted('code', 'asc')).toEqual(ids([...CARDS].sort(byCode)))
134
+ expect(await sorted('balance', 'desc')).toEqual(ids([...CARDS].sort((a, b) => b.current_balance - a.current_balance || byCode(a, b))))
135
+ const recipient = (card: Card) => (card.recipient_name ?? '').toLowerCase()
136
+ expect(await sorted('recipient', 'asc')).toEqual(ids([...CARDS].sort((a, b) => recipient(a).localeCompare(recipient(b)) || byCode(a, b))))
137
+ // Cards without an expiry come last in both directions.
138
+ const dated = CARDS.filter(card => card.expiry_days !== null)
139
+ const undated = [...CARDS.filter(card => card.expiry_days === null)].sort(byCode)
140
+ expect(await sorted('expiry', 'asc')).toEqual(ids([...[...dated].sort((a, b) => a.expiry_days! - b.expiry_days! || byCode(a, b)), ...undated]))
141
+ expect(await sorted('expiry', 'desc')).toEqual(ids([...[...dated].sort((a, b) => b.expiry_days! - a.expiry_days! || byCode(a, b)), ...undated]))
142
+
143
+ // A card's customer is checked against exactly the customers it references.
144
+ const first = (await all({ sort: 'id', direction: 'asc' })).records
145
+ expect(first[0]!.customerId).toBe(String(CUSTOMERS))
146
+ expect(first[1]!.customerId).toBe('3')
147
+ expect(first[0]!.currency).toBe('EUR')
148
+ expect(first[5]!.currency).toBe('USD')
149
+
150
+ // The export holds every match across batches, in order.
151
+ const exported = await readGiftCardsForExport({ search: '', status: '', enabled: '', delivery: '', sort: 'created', direction: 'desc' }, runner, dialect, 4)
152
+ expect(exported.map(record => record.id)).toEqual(ids(newest))
153
+ }
154
+
155
+ describe('readGiftCardPage on SQLite', () => {
156
+ test('summary, filters, search, sorts, pages, customers and export', async () => {
157
+ const database = new Database(':memory:')
158
+ await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
159
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
160
+ })
161
+ })
162
+
163
+ for (const dialect of ['postgres', 'mysql'] as const) {
164
+ const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
165
+
166
+ test.skipIf(!connection)(`readGiftCardPage on ${dialect}: summary, filters, search, sorts, pages, customers and export`, async () => {
167
+ const url = new URL(connection!)
168
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
169
+ throw new Error('Gift card list tests require a local disposable database server')
170
+
171
+ const name = `stacks_gift_card_list_${crypto.randomUUID().replaceAll('-', '')}`
172
+ const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
173
+ const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
174
+ await admin.unsafe(`CREATE DATABASE ${quoted}`)
175
+ const scoped = new URL(url.href)
176
+ scoped.pathname = `/${name}`
177
+ // Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
178
+ const database = new SQL({ url: scoped.href, database: name })
179
+
180
+ try {
181
+ await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
182
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
183
+ }
184
+ finally {
185
+ await database.close()
186
+ try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
187
+ finally { await admin.close() }
188
+ }
189
+ }, 60_000)
190
+ }
191
+
192
+ describe('parseGiftCardListQuery', () => {
193
+ const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
194
+
195
+ test('defaults to every card, newest first, 25 a page', () => {
196
+ expect(parseGiftCardListQuery(reader({}))).toEqual({ search: '', status: '', enabled: '', delivery: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
197
+ expect(parseGiftCardListQuery(reader({ sort: 'balance' }))).toHaveProperty('direction', 'desc')
198
+ expect(parseGiftCardListQuery(reader({ sort: 'code' }))).toHaveProperty('direction', 'asc')
199
+ })
200
+
201
+ test('refuses values the page does not offer', () => {
202
+ expect(parseGiftCardListQuery(reader({ status: 'active' }))).toHaveProperty('error')
203
+ expect(parseGiftCardListQuery(reader({ enabled: 'yes' }))).toHaveProperty('error')
204
+ expect(parseGiftCardListQuery(reader({ delivery: 'email' }))).toHaveProperty('error')
205
+ expect(parseGiftCardListQuery(reader({ sort: 'personal_message' }))).toHaveProperty('error')
206
+ expect(parseGiftCardListQuery(reader({ per_page: '7' }))).toHaveProperty('error')
207
+ })
208
+ })
209
+
210
+ describe('giftCardsCsv', () => {
211
+ test('writes the page columns with balances in major units', () => {
212
+ const csv = giftCardsCsv([{
213
+ id: '1', code: 'GC-"1"', initialBalance: 5000, currentBalance: 1250, currency: 'USD', status: 'ACTIVE', purchaserId: '',
214
+ recipientEmail: 'a@b.test', recipientName: 'Ann', personalMessage: '', isDigital: true, isReloadable: false, isActive: true,
215
+ expiryDate: '', lastUsedDate: '', templateId: '', customerId: '', createdAt: '2026-11-06T12:00:00.000Z',
216
+ }], (amount, currency) => `${currency} ${(amount / 100).toFixed(2)}`)
217
+ const [header, row] = csv.replace(/^/, '').split('\n')
218
+ expect(header).toBe('"Code","Recipient","Email","Status","Availability","Delivery","Reloading","Currency","Initial balance","Current balance","Expiry date","Last used date"')
219
+ expect(row).toBe('"GC-""1""","Ann","a@b.test","ACTIVE","Enabled","Digital","Single use","USD","USD 50.00","USD 12.50","",""')
220
+ })
221
+ })