@stacksjs/defaults 0.75.487 → 0.75.490

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 (141) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +27 -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/ProductWaitlistIndexAction.ts +22 -22
  28. package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
  29. package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
  30. package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
  31. package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
  32. package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
  33. package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
  34. package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
  35. package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
  36. package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
  37. package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
  38. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
  39. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
  40. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
  41. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
  42. package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
  43. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
  44. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
  45. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
  46. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
  47. package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
  48. package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
  49. package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
  50. package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
  51. package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
  52. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
  53. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
  54. package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
  55. package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
  56. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
  57. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
  58. package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
  59. package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
  60. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
  61. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
  62. package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
  63. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
  64. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
  65. package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
  66. package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
  67. package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
  68. package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
  69. package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
  70. package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
  71. package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
  72. package/app/Actions/Dashboard/Content/content-list.ts +10 -0
  73. package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
  74. package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
  75. package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
  76. package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
  77. package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
  78. package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
  79. package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
  80. package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
  81. package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
  82. package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
  83. package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
  84. package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
  85. package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
  86. package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
  87. package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +9 -6
  88. package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
  89. package/app/Actions/Dashboard/Queue/queue-stats.ts +10 -0
  90. package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
  91. package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
  92. package/app/Actions/Dashboard/named-search.test.ts +36 -0
  93. package/app/Actions/Dashboard/named-search.ts +80 -0
  94. package/app/Models/QueueWorker.ts +1 -0
  95. package/app/Models/Request.ts +4 -2
  96. package/bootstrap.ts +6 -1
  97. package/functions/commerce/shippings/dashboard-resource.ts +12 -1
  98. package/functions/commerce/shippings/delivery-routes.ts +1 -0
  99. package/functions/commerce/shippings/license-keys.ts +1 -0
  100. package/functions/dashboard-list.test.ts +132 -1
  101. package/functions/dashboard-list.ts +198 -1
  102. package/functions/queue.ts +2 -0
  103. package/ide/vscode/package.json +1 -1
  104. package/package.json +2 -2
  105. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
  106. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
  107. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
  108. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
  109. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
  110. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
  111. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
  112. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
  113. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
  114. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
  115. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
  116. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
  117. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
  118. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
  119. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
  120. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
  121. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
  122. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
  123. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
  124. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
  125. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
  126. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
  127. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
  128. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
  129. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
  130. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
  131. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
  132. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
  133. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
  134. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
  135. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
  136. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
  137. package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
  138. package/resources/components/Dashboard/Queue/QueueDashboard.stx +8 -2
  139. package/resources/functions/dashboard/sidebar.ts +26 -1
  140. package/routes/dashboard-api.ts +11 -0
  141. package/views/dashboard/stores/kanban.ts +38 -6
@@ -0,0 +1,202 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { SQL } from 'bun'
3
+ import { describe, expect, test } from 'bun:test'
4
+ import type { PrintLogListQuery } from './commerce-print-log-list'
5
+ import { parsePrintLogListQuery, readPrintLogPage, readPrintLogsForExport } from './commerce-print-log-list'
6
+ import type { CommerceSqlRunner } from './commerce-sql'
7
+
8
+ /**
9
+ * The print logs against each dialect's real engine (stacksjs/stacks#3218):
10
+ * status as a real enum, timestamps as each dialect stores them (SQLite text
11
+ * with a time zone suffix, PostgreSQL timestamptz, MySQL DATETIME in UTC), and
12
+ * print devices past the 500 the page used to read.
13
+ */
14
+ type Dialect = 'sqlite' | 'postgres' | 'mysql'
15
+
16
+ const NOW = new Date('2026-11-06T12:00:00.000Z')
17
+ const HOUR = 3_600_000
18
+ const DEVICES = 520
19
+ const STATUSES = ['success', 'failed', 'warning'] as const
20
+ const PRINTERS = ['Kitchen', 'bar printer', 'Front Desk', null] as const
21
+
22
+ /** 40 logs, 7 hours 13 minutes apart back from NOW; the last few are over 30 days old. */
23
+ const LOGS = Array.from({ length: 40 }, (_, index) => {
24
+ const id = index + 1
25
+ return {
26
+ id,
27
+ printer: id === 9 ? 'Laser_100%' : id === 10 ? 'Laser 1000' : PRINTERS[id % PRINTERS.length]!,
28
+ document: `Receipt R-${String(id).padStart(4, '0')}`,
29
+ at: NOW.getTime() - id * (7 * HOUR + 13 * 60_000) - (id > 36 ? 30 * 24 * HOUR : 0),
30
+ status: STATUSES[id % 3]!,
31
+ pages: id % 6,
32
+ duration: (id * 7) % 11,
33
+ deviceId: id % 5 === 0 ? 515 : null,
34
+ }
35
+ })
36
+ type Log = typeof LOGS[number]
37
+
38
+ const ids = (logs: Log[]) => logs.map(log => String(log.id))
39
+ const newestFirst = (a: Log, b: Log) => b.at - a.at || b.id - a.id
40
+ const within = (days: number) => LOGS.filter(log => days === 0 || NOW.getTime() - log.at <= days * 24 * HOUR)
41
+
42
+ function query(overrides: Partial<PrintLogListQuery> = {}): PrintLogListQuery {
43
+ return { search: '', printer: '', status: '', days: 0, sort: 'newest', page: 1, perPage: 10, ...overrides }
44
+ }
45
+
46
+ /** A timestamp as each dialect stores one; SQLite alternates UTC and +08:00 text. */
47
+ function stored(log: Log, dialect: Dialect): string {
48
+ const date = new Date(log.at)
49
+ // PostgreSQL gets the zone: timestamptz reads a bare value in the session's
50
+ // time zone, which on a developer's machine is rarely UTC.
51
+ if (dialect === 'postgres')
52
+ return date.toISOString()
53
+ if (dialect === 'mysql')
54
+ return date.toISOString().slice(0, 23).replace('T', ' ')
55
+ if (log.id % 2 === 0)
56
+ return date.toISOString()
57
+ const shifted = new Date(log.at + 8 * HOUR).toISOString().slice(0, 23)
58
+ return `${shifted}+08:00`
59
+ }
60
+
61
+ async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
62
+ const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
63
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
64
+ const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMPTZ'
65
+ const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
66
+ const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
67
+ let status = text
68
+ if (dialect === 'postgres') {
69
+ await run(`CREATE TYPE receipt_status AS ENUM ('success', 'failed', 'warning')`)
70
+ status = 'receipt_status'
71
+ }
72
+ if (dialect === 'mysql')
73
+ status = `ENUM('success', 'failed', 'warning')`
74
+ await run(`CREATE TABLE print_devices (id ${pk})`)
75
+ await run(`CREATE TABLE receipts (id ${pk}, printer ${text} NULL, document ${text}, timestamp ${time}, status ${status}, size INTEGER, pages INTEGER, duration INTEGER, metadata ${text} NULL, print_device_id INTEGER NULL, created_at ${time})`)
76
+ const all = Array.from({ length: DEVICES }, (_, i) => i + 1)
77
+ await run(`INSERT INTO print_devices (id) VALUES ${rows(DEVICES, 1)}`, all)
78
+ await run(
79
+ `INSERT INTO receipts (id, printer, document, timestamp, status, size, pages, duration, print_device_id, created_at) VALUES ${rows(LOGS.length, 10)}`,
80
+ LOGS.flatMap(log => [log.id, log.printer, log.document, stored(log, dialect), log.status, 4, log.pages, log.duration, log.deviceId, stored(log, dialect)]),
81
+ )
82
+ }
83
+
84
+ async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
85
+ const read = (overrides: Partial<PrintLogListQuery> = {}) => readPrintLogPage(query(overrides), runner, dialect, NOW)
86
+ const all = async (overrides: Partial<PrintLogListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => record.id)
87
+
88
+ // The summary and breakdown describe every matching log, not the page.
89
+ const month = await read({ days: 30 })
90
+ const inMonth = within(30)
91
+ const successful = inMonth.filter(log => log.status === 'success')
92
+ const pages = inMonth.reduce((sum, log) => sum + log.pages, 0)
93
+ expect(month.records.length).toBe(10)
94
+ expect(month.summary).toEqual({
95
+ total: inMonth.length,
96
+ successful: successful.length,
97
+ failed: inMonth.filter(log => log.status === 'failed').length,
98
+ warnings: inMonth.filter(log => log.status === 'warning').length,
99
+ successRate: Math.round((successful.length / inMonth.length) * 1000) / 10,
100
+ totalPages: pages,
101
+ averagePages: Math.round((pages / inMonth.length) * 10) / 10,
102
+ averageSuccessfulDuration: Math.round((successful.reduce((sum, log) => sum + log.duration, 0) / successful.length) * 10) / 10,
103
+ })
104
+ expect(month.pagination).toEqual({ page: 1, perPage: 10, total: inMonth.length, totalPages: Math.ceil(inMonth.length / 10) })
105
+ const printerCounts = Object.fromEntries(month.breakdown.printers.map(row => [row.key, row.count]))
106
+ expect(printerCounts.Kitchen).toBe(inMonth.filter(log => log.printer === 'Kitchen').length)
107
+ expect(printerCounts.Unknown).toBe(inMonth.filter(log => log.printer === null).length)
108
+ expect(Object.fromEntries(month.breakdown.statuses.map(row => [row.key, row.count])).failed).toBe(inMonth.filter(log => log.status === 'failed').length)
109
+
110
+ // UTC day and quarter hour, whatever zone each dialect stored the time in.
111
+ const slots = new Map<string, { day: string, quarter: number, count: number }>()
112
+ for (const log of inMonth) {
113
+ const date = new Date(log.at)
114
+ const day = date.toISOString().slice(0, 10)
115
+ const quarter = date.getUTCHours() * 4 + Math.floor(date.getUTCMinutes() / 15)
116
+ const slot = slots.get(`${day}:${quarter}`) ?? { day, quarter, count: 0 }
117
+ slot.count += 1
118
+ slots.set(`${day}:${quarter}`, slot)
119
+ }
120
+ expect(month.breakdown.slots).toEqual([...slots.values()].sort((a, b) => a.day.localeCompare(b.day) || a.quarter - b.quarter))
121
+
122
+ // Filters, the time range, and a search that ignores case and treats % literally.
123
+ expect((await read({ days: 0 })).summary.total).toBe(LOGS.length)
124
+ expect((await read({ days: 1 })).summary.total).toBe(within(1).length)
125
+ expect(await all({ status: 'warning' })).toEqual(ids(LOGS.filter(log => log.status === 'warning').sort(newestFirst)))
126
+ expect(await all({ printer: 'Kitchen' })).toEqual(ids(LOGS.filter(log => log.printer === 'Kitchen').sort(newestFirst)))
127
+ expect(await all({ search: '100%' })).toEqual(['9'])
128
+ expect(await all({ search: 'BAR PRINTER' })).toEqual(ids(LOGS.filter(log => log.printer === 'bar printer').sort(newestFirst)))
129
+ expect(await all({ search: 'r-0012' })).toEqual(['12'])
130
+
131
+ // Sorts, stable across pages.
132
+ const newest = [...LOGS].sort(newestFirst)
133
+ const paged = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 }), await read({ page: 4 })]
134
+ expect(paged.flatMap(result => result.records.map(record => record.id))).toEqual(ids(newest))
135
+ expect((await read({ page: 9 })).pagination.page).toBe(4)
136
+ expect(await all({ sort: 'oldest' })).toEqual(ids([...LOGS].sort((a, b) => a.at - b.at || a.id - b.id)))
137
+ const printerKey = (log: Log) => (log.printer ?? '').toLowerCase()
138
+ expect(await all({ sort: 'printer' })).toEqual(ids([...LOGS].sort((a, b) => printerKey(a).localeCompare(printerKey(b)) || newestFirst(a, b))))
139
+ expect(await all({ sort: 'duration' })).toEqual(ids([...LOGS].sort((a, b) => b.duration - a.duration || newestFirst(a, b))))
140
+
141
+ // Print devices past the 500th, and every printer as a choice, by name ignoring case.
142
+ expect(month.records.some(record => record.printDeviceId === '515') || (await read({ perPage: 100 })).records.some(record => record.printDeviceId === '515')).toBe(true)
143
+ expect(month.options.printers).toEqual(['bar printer', 'Front Desk', 'Kitchen', 'Laser 1000', 'Laser_100%'])
144
+ expect(month.options.statuses.sort()).toEqual(['failed', 'success', 'warning'])
145
+
146
+ // The export holds every match across batches, in order.
147
+ const exported = await readPrintLogsForExport({ search: '', printer: '', status: '', days: 0, sort: 'newest' }, runner, dialect, NOW, 7)
148
+ expect(exported.map(record => record.id)).toEqual(ids(newest))
149
+ }
150
+
151
+ describe('readPrintLogPage on SQLite', () => {
152
+ test('summary, breakdown, filters, search, sorts, pages, devices and export', async () => {
153
+ const database = new Database(':memory:')
154
+ await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
155
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
156
+ })
157
+ })
158
+
159
+ for (const dialect of ['postgres', 'mysql'] as const) {
160
+ const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
161
+
162
+ test.skipIf(!connection)(`readPrintLogPage on ${dialect}: summary, breakdown, filters, search, sorts, pages, devices and export`, async () => {
163
+ const url = new URL(connection!)
164
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
165
+ throw new Error('Print log list tests require a local disposable database server')
166
+
167
+ const name = `stacks_print_logs_${crypto.randomUUID().replaceAll('-', '')}`
168
+ const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
169
+ const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
170
+ await admin.unsafe(`CREATE DATABASE ${quoted}`)
171
+ const scoped = new URL(url.href)
172
+ scoped.pathname = `/${name}`
173
+ // Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
174
+ const database = new SQL({ url: scoped.href, database: name })
175
+
176
+ try {
177
+ await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
178
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
179
+ }
180
+ finally {
181
+ await database.close()
182
+ try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
183
+ finally { await admin.close() }
184
+ }
185
+ }, 60_000)
186
+ }
187
+
188
+ describe('parsePrintLogListQuery', () => {
189
+ const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
190
+
191
+ test('defaults to the last 30 days, newest first, 20 a page', () => {
192
+ expect(parsePrintLogListQuery(reader({}))).toEqual({ search: '', printer: '', status: '', days: 30, sort: 'newest', page: 1, perPage: 20 })
193
+ expect(parsePrintLogListQuery(reader({ range: 'all', search: 'kitchen' }))).toMatchObject({ days: 0, search: 'kitchen' })
194
+ })
195
+
196
+ test('refuses values the page does not offer', () => {
197
+ expect(parsePrintLogListQuery(reader({ status: 'printing' }))).toHaveProperty('error')
198
+ expect(parsePrintLogListQuery(reader({ range: '45' }))).toHaveProperty('error')
199
+ expect(parsePrintLogListQuery(reader({ sort: 'pages' }))).toHaveProperty('error')
200
+ expect(parsePrintLogListQuery(reader({ per_page: '500' }))).toHaveProperty('error')
201
+ })
202
+ })
@@ -0,0 +1,286 @@
1
+ import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
2
+ import { db, getDatabaseDialect, sqlDateTime } from '@stacksjs/database/runtime'
3
+ import type { QueryReader } from '../Content/content-list'
4
+ import { containsPattern, countOf, pageWithin, queryText } from '../Content/content-list'
5
+ import { commerceIdentifier, commerceValue, referencedIds } from './commerce-record'
6
+ import type { CommerceSqlRunner } from './commerce-sql'
7
+ import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
8
+ import type { PrintLogRecord, PrintLogStatus, PrintLogSummary } from './print-log-records'
9
+ import { normalizePrintLogRecord } from './print-log-records'
10
+
11
+ /**
12
+ * One page of print logs (receipts), with the summary and breakdown of every
13
+ * log the search and filters match, read by the database
14
+ * (stacksjs/stacks#3218).
15
+ *
16
+ * The endpoint already paged, but its cards and breakdowns described only
17
+ * the twenty rows on screen, its export wrote only those, its search was a
18
+ * case-sensitive LIKE on PostgreSQL that read `%` and `_` as wildcards, and
19
+ * its record check read the first 500 print devices, so one log from a later
20
+ * device failed the whole page.
21
+ */
22
+ export const PRINT_LOG_STATUSES: readonly PrintLogStatus[] = ['failed', 'success', 'warning']
23
+ export const PRINT_LOG_RANGES = ['1', '7', '30', '90', 'all'] as const
24
+ export const PRINT_LOG_SORTS = ['newest', 'oldest', 'printer', 'duration'] as const
25
+ export type PrintLogSort = typeof PRINT_LOG_SORTS[number]
26
+
27
+ export interface PrintLogListQuery {
28
+ search: string
29
+ /** A printer name, or '' for any. */
30
+ printer: string
31
+ /** '' for any. */
32
+ status: '' | PrintLogStatus
33
+ /** Days back from now; 0 for all time. */
34
+ days: number
35
+ sort: PrintLogSort
36
+ page: number
37
+ perPage: number
38
+ }
39
+
40
+ /** What the breakdown panels show for the matching logs. */
41
+ export interface PrintLogBreakdown {
42
+ printers: Array<{ key: string, count: number }>
43
+ statuses: Array<{ key: string, count: number }>
44
+ /**
45
+ * How many logs were printed in each quarter hour, by UTC day: at most 96 a
46
+ * day, however many logs there are. Every time zone is a whole number of
47
+ * quarter hours from UTC, so the browser puts each slot in its own local
48
+ * hour exactly, daylight saving included.
49
+ */
50
+ slots: Array<{ day: string, quarter: number, count: number }>
51
+ }
52
+
53
+ export function parsePrintLogListQuery(read: QueryReader): PrintLogListQuery | { error: string } {
54
+ const pageText = queryText(read, 'page')
55
+ const page = pageText === '' ? 1 : Number(pageText)
56
+ if (!Number.isInteger(page) || page < 1)
57
+ return { error: 'page must be a whole number of 1 or more.' }
58
+
59
+ const sizeText = queryText(read, 'per_page')
60
+ const perPage = sizeText === '' ? 20 : Number(sizeText)
61
+ if (!Number.isInteger(perPage) || perPage < 1 || perPage > 100)
62
+ return { error: 'per_page must be a whole number from 1 to 100.' }
63
+
64
+ const sort = queryText(read, 'sort').toLowerCase() || 'newest'
65
+ if (!(PRINT_LOG_SORTS as readonly string[]).includes(sort))
66
+ return { error: `sort must be one of ${PRINT_LOG_SORTS.join(', ')}.` }
67
+
68
+ const range = queryText(read, 'range').toLowerCase() || '30'
69
+ if (!(PRINT_LOG_RANGES as readonly string[]).includes(range))
70
+ return { error: 'range must be 1, 7, 30, 90 or all.' }
71
+
72
+ // `search` is what the page has always sent; `q` is what the other lists take.
73
+ const search = queryText(read, 'search') || queryText(read, 'q')
74
+ if (search.length > 200)
75
+ return { error: 'search must be 200 characters or fewer.' }
76
+
77
+ const printer = queryText(read, 'printer')
78
+ if (printer.length > 100)
79
+ return { error: 'printer must be 100 characters or fewer.' }
80
+
81
+ const status = queryText(read, 'status').toLowerCase()
82
+ if (status && !(PRINT_LOG_STATUSES as readonly string[]).includes(status))
83
+ return { error: `status must be one of ${PRINT_LOG_STATUSES.join(', ')}.` }
84
+
85
+ return {
86
+ search,
87
+ printer,
88
+ status: status as PrintLogListQuery['status'],
89
+ days: range === 'all' ? 0 : Number(range),
90
+ sort: sort as PrintLogSort,
91
+ page,
92
+ perPage,
93
+ }
94
+ }
95
+
96
+ /** The UTC day (YYYY-MM-DD) and quarter hour of that day (0 to 95) a log was printed in. */
97
+ function utcSlot(dialect: QueryBuilderDialect): { day: string, quarter: string } {
98
+ if (dialect === 'sqlite') {
99
+ return {
100
+ day: `date(timestamp)`,
101
+ quarter: `(CAST(strftime('%H', timestamp) AS INTEGER) * 4 + CAST(strftime('%M', timestamp) AS INTEGER) / 15)`,
102
+ }
103
+ }
104
+ if (dialect === 'postgres') {
105
+ // The model stores timestamptz; the cast also reads a text column.
106
+ const utc = `(CAST(timestamp AS TIMESTAMPTZ) AT TIME ZONE 'UTC')`
107
+ return {
108
+ day: `CAST(CAST(${utc} AS DATE) AS TEXT)`,
109
+ quarter: `(CAST(EXTRACT(HOUR FROM ${utc}) AS INTEGER) * 4 + CAST(EXTRACT(MINUTE FROM ${utc}) AS INTEGER) / 15)`,
110
+ }
111
+ }
112
+ return { day: `CAST(DATE(timestamp) AS CHAR)`, quarter: '(HOUR(timestamp) * 4 + MINUTE(timestamp) DIV 15)' }
113
+ }
114
+
115
+ export function printLogFilter(query: Pick<PrintLogListQuery, 'search' | 'printer' | 'status' | 'days'>, dialect: QueryBuilderDialect, now: Date = new Date()): { where: string, values: unknown[] } {
116
+ const { bind, values } = binder(dialect)
117
+ const clauses: string[] = []
118
+ if (query.printer)
119
+ clauses.push(`printer = ${bind(query.printer)}`)
120
+ if (query.status)
121
+ // A text comparison: PostgreSQL keeps the status as an enum.
122
+ clauses.push(`${asText('status', dialect)} = ${bind(query.status)}`)
123
+ if (query.days > 0) {
124
+ const cutoff = new Date(now.getTime() - query.days * 86_400_000)
125
+ if (dialect === 'sqlite') {
126
+ // SQLite keeps timestamps as text, where a time zone suffix or a "T"
127
+ // makes plain text comparison wrong, so both sides go through datetime().
128
+ clauses.push(`datetime(timestamp) >= datetime(${bind(sqlDateTime(cutoff))})`)
129
+ }
130
+ else if (dialect === 'postgres') {
131
+ // The model stores timestamptz, which reads a value without a zone in the
132
+ // session's time zone; the cutoff says it is UTC.
133
+ clauses.push(`timestamp >= CAST(${bind(cutoff.toISOString())} AS TIMESTAMPTZ)`)
134
+ }
135
+ else {
136
+ clauses.push(`timestamp >= ${bind(sqlDateTime(cutoff))}`)
137
+ }
138
+ }
139
+ if (query.search) {
140
+ const pattern = containsPattern(query.search)
141
+ const columns = [`COALESCE(printer, '')`, 'document', asText('status', dialect)]
142
+ clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
143
+ }
144
+ return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
145
+ }
146
+
147
+ function orderBy(sort: PrintLogSort, dialect: QueryBuilderDialect): string {
148
+ // SQLite text timestamps with different zone suffixes do not sort as text;
149
+ // julianday() reads each as the instant it is, milliseconds included.
150
+ const at = dialect === 'sqlite' ? 'julianday(timestamp)' : 'timestamp'
151
+ switch (sort) {
152
+ case 'oldest': return ` ORDER BY ${at} ASC, id ASC`
153
+ // Logs from one printer read newest first; the id breaks every remaining tie.
154
+ case 'printer': return ` ORDER BY LOWER(COALESCE(printer, '')) ASC, ${at} DESC, id DESC`
155
+ case 'duration': return ` ORDER BY duration DESC, ${at} DESC, id DESC`
156
+ default: return ` ORDER BY ${at} DESC, id DESC`
157
+ }
158
+ }
159
+
160
+ /** Logs turned into records, against exactly the print devices they reference. */
161
+ async function recordsFor(logs: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<PrintLogRecord[]> {
162
+ if (logs.length === 0)
163
+ return []
164
+ const deviceIds = referencedIds(logs, 'print_device_id')
165
+ const devices = deviceIds.length > 0
166
+ ? await run.unsafe(`SELECT id FROM print_devices WHERE id IN (${idPlaceholders(deviceIds, dialect)})`, deviceIds).execute()
167
+ : []
168
+ const known = new Set(sqlRows(devices).map(row => commerceIdentifier(commerceValue(row, 'id'), 'PrintDevice')))
169
+ return logs.map(log => normalizePrintLogRecord(log, known))
170
+ }
171
+
172
+ /** The summary cards and breakdowns over every matching log, as summarizePrintLogs had them for a page. */
173
+ async function summarize(where: string, values: unknown[], run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<{ summary: PrintLogSummary, breakdown: PrintLogBreakdown }> {
174
+ const status = asText('status', dialect)
175
+ const count = (name: string) => `SUM(CASE WHEN ${status} = '${name}' THEN 1 ELSE 0 END)`
176
+ const slot = utcSlot(dialect)
177
+ const [totals, printers, statuses, slotRows] = await Promise.all([
178
+ run.unsafe(`SELECT COUNT(*) AS total_count, ${count('success')} AS success_count, ${count('failed')} AS failed_count, ${count('warning')} AS warning_count, SUM(pages) AS page_total, SUM(CASE WHEN ${status} = 'success' THEN duration ELSE 0 END) AS success_duration FROM receipts${where}`, values).execute(),
179
+ run.unsafe(`SELECT printer AS value, COUNT(*) AS item_count FROM receipts${where} GROUP BY printer`, values).execute(),
180
+ run.unsafe(`SELECT ${status} AS value, COUNT(*) AS item_count FROM receipts${where} GROUP BY ${status}`, values).execute(),
181
+ run.unsafe(`SELECT ${slot.day} AS day, ${slot.quarter} AS quarter, COUNT(*) AS item_count FROM receipts${where} GROUP BY ${slot.day}, ${slot.quarter}`, values).execute(),
182
+ ])
183
+ const row = sqlRows(totals)[0] ?? {}
184
+ const total = countOf(row.total_count)
185
+ const successful = countOf(row.success_count)
186
+ const totalPages = countOf(row.page_total)
187
+ const successDuration = countOf(row.success_duration)
188
+
189
+ const tally = (result: unknown) => {
190
+ const merged = new Map<string, number>()
191
+ for (const entry of sqlRows(result)) {
192
+ const key = String(entry.value ?? '').trim() || 'Unknown'
193
+ merged.set(key, (merged.get(key) ?? 0) + countOf(entry.item_count))
194
+ }
195
+ return [...merged.entries()]
196
+ .map(([key, value]) => ({ key, count: value }))
197
+ .sort((left, right) => right.count - left.count || left.key.localeCompare(right.key))
198
+ }
199
+
200
+ const slots = sqlRows(slotRows)
201
+ .map(entry => ({ day: String(entry.day ?? '').slice(0, 10), quarter: Number(entry.quarter), count: countOf(entry.item_count) }))
202
+ .filter(entry => /^\d{4}-\d{2}-\d{2}$/.test(entry.day) && Number.isInteger(entry.quarter) && entry.quarter >= 0 && entry.quarter < 96)
203
+ .sort((left, right) => left.day.localeCompare(right.day) || left.quarter - right.quarter)
204
+
205
+ return {
206
+ summary: {
207
+ total,
208
+ successful,
209
+ failed: countOf(row.failed_count),
210
+ warnings: countOf(row.warning_count),
211
+ successRate: total ? Math.round((successful / total) * 1000) / 10 : 0,
212
+ totalPages,
213
+ averagePages: total ? Math.round((totalPages / total) * 10) / 10 : 0,
214
+ averageSuccessfulDuration: successful ? Math.round((successDuration / successful) * 10) / 10 : 0,
215
+ },
216
+ breakdown: { printers: tally(printers), statuses: tally(statuses), slots },
217
+ }
218
+ }
219
+
220
+ /** The filter choices: every printer any log names, and every status. */
221
+ async function choices(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<{ printers: string[], statuses: string[] }> {
222
+ const [printers, statuses] = await Promise.all([
223
+ run.unsafe(`SELECT DISTINCT printer AS value FROM receipts WHERE printer IS NOT NULL`).execute(),
224
+ run.unsafe(`SELECT DISTINCT ${asText('status', dialect)} AS value FROM receipts`).execute(),
225
+ ])
226
+ const values = (result: unknown) => [...new Set(sqlRows(result).map(row => String(row.value ?? '').trim()).filter(Boolean))]
227
+ .sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase()) || left.localeCompare(right))
228
+ return {
229
+ printers: values(printers),
230
+ statuses: values(statuses).filter(value => (PRINT_LOG_STATUSES as readonly string[]).includes(value)),
231
+ }
232
+ }
233
+
234
+ export interface PrintLogPage {
235
+ records: PrintLogRecord[]
236
+ summary: PrintLogSummary
237
+ breakdown: PrintLogBreakdown
238
+ pagination: { page: number, perPage: number, total: number, totalPages: number }
239
+ options: { printers: string[], statuses: string[] }
240
+ }
241
+
242
+ export async function readPrintLogPage(
243
+ query: PrintLogListQuery,
244
+ run: CommerceSqlRunner = db,
245
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
246
+ now: Date = new Date(),
247
+ ): Promise<PrintLogPage> {
248
+ const { where, values } = printLogFilter(query, dialect, now)
249
+ const [{ summary, breakdown }, options] = await Promise.all([
250
+ summarize(where, values, run, dialect),
251
+ choices(run, dialect),
252
+ ])
253
+ const page = pageWithin(query.page, summary.total, query.perPage)
254
+ const logs = await run.unsafe(
255
+ `SELECT * FROM receipts${where}${orderBy(query.sort, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
256
+ values,
257
+ ).execute()
258
+ return {
259
+ records: await recordsFor(sqlRows(logs), run, dialect),
260
+ summary,
261
+ breakdown,
262
+ pagination: { page, perPage: query.perPage, total: summary.total, totalPages: Math.max(1, Math.ceil(summary.total / query.perPage)) },
263
+ options,
264
+ }
265
+ }
266
+
267
+ /** Every log matching the query, in its order, for the CSV export, a batch at a time. */
268
+ export async function readPrintLogsForExport(
269
+ query: Omit<PrintLogListQuery, 'page' | 'perPage'>,
270
+ run: CommerceSqlRunner = db,
271
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
272
+ now: Date = new Date(),
273
+ batchSize: number = 500,
274
+ ): Promise<PrintLogRecord[]> {
275
+ const { where, values } = printLogFilter(query, dialect, now)
276
+ const records: PrintLogRecord[] = []
277
+ for (let offset = 0; ; offset += batchSize) {
278
+ const batch = sqlRows(await run.unsafe(
279
+ `SELECT * FROM receipts${where}${orderBy(query.sort, dialect)} LIMIT ${batchSize} OFFSET ${offset}`,
280
+ values,
281
+ ).execute())
282
+ records.push(...await recordsFor(batch, run, dialect))
283
+ if (batch.length < batchSize)
284
+ return records
285
+ }
286
+ }
@@ -0,0 +1,174 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { SQL } from 'bun'
3
+ import { describe, expect, test } from 'bun:test'
4
+ import type { CommerceSqlRunner } from './commerce-sql'
5
+ import type { ProductListQuery } from './commerce-product-list'
6
+ import { parseProductListQuery, productsCsv, readProductPage, readProductsForExport } from './commerce-product-list'
7
+
8
+ /**
9
+ * The Products list against each dialect's real engine (stacksjs/stacks#3218),
10
+ * with is_available as each dialect's own boolean.
11
+ */
12
+ type Dialect = 'sqlite' | 'postgres' | 'mysql'
13
+
14
+ const CATEGORIES: Array<[number, string]> = [[1, 'Pastry'], [2, 'drinks'], [3, 'Mains']]
15
+ const MANUFACTURERS: Array<[number, string]> = [[1, 'Acme Mills'], [2, 'Bean Co']]
16
+
17
+ /** 28 products across three categories, some unavailable, some out of stock. */
18
+ const PRODUCTS = Array.from({ length: 28 }, (_, index) => {
19
+ const id = index + 1
20
+ return {
21
+ id,
22
+ name: id === 9 ? 'Flat White 100%' : `Product ${String.fromCharCode(65 + (id % 26))}${id}`,
23
+ slug: `product-${id}`,
24
+ price: (id * 37) % 23 * 100,
25
+ is_available: id % 4 !== 0,
26
+ inventory_count: id % 5 === 0 ? 0 : id * 3,
27
+ category_id: (id % 3) + 1,
28
+ manufacturer_id: id % 2 === 0 ? 2 : (id % 7 === 0 ? null : 1),
29
+ allergens: id === 11 ? '["peanuts","milk"]' : '[]',
30
+ created_at: `2026-10-${String(1 + (id % 10)).padStart(2, '0')} 09:00:00`,
31
+ }
32
+ })
33
+
34
+ function query(overrides: Partial<ProductListQuery> = {}): ProductListQuery {
35
+ return { search: '', category: '', availability: '', sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
36
+ }
37
+
38
+ async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
39
+ const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
40
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
41
+ const bool = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
42
+ const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME' : 'TIMESTAMP'
43
+ await run(`CREATE TABLE categories (id ${pk}, name ${text})`)
44
+ await run(`CREATE TABLE manufacturers (id ${pk}, manufacturer ${text})`)
45
+ for (const table of ['product_variants', 'product_units', 'reviews'])
46
+ await run(`CREATE TABLE ${table} (id ${pk}, product_id INTEGER)`)
47
+ await run(`CREATE TABLE products (id ${pk}, name ${text}, slug ${text}, description ${text} NULL, price INTEGER, image_url ${text} NULL, is_available ${bool}, inventory_count INTEGER, preparation_time INTEGER, allergens ${text} NULL, nutritional_info ${text} NULL, category_id INTEGER NULL, manufacturer_id INTEGER NULL, created_at ${time})`)
48
+ const p = (count: number) => Array.from({ length: count }, (_, i) => dialect === 'postgres' ? `$${i + 1}` : '?').join(', ')
49
+ for (const [id, name] of CATEGORIES)
50
+ await run(`INSERT INTO categories (id, name) VALUES (${p(2)})`, [id, name])
51
+ for (const [id, name] of MANUFACTURERS)
52
+ await run(`INSERT INTO manufacturers (id, manufacturer) VALUES (${p(2)})`, [id, name])
53
+ for (const product of PRODUCTS) {
54
+ await run(
55
+ `INSERT INTO products (id, name, slug, price, is_available, inventory_count, preparation_time, allergens, category_id, manufacturer_id, created_at) VALUES (${p(11)})`,
56
+ [product.id, product.name, product.slug, product.price, dialect === 'postgres' ? product.is_available : (product.is_available ? 1 : 0), product.inventory_count, 5, product.allergens, product.category_id, product.manufacturer_id, product.created_at],
57
+ )
58
+ }
59
+ // Product 4 has two variants, one unit and three reviews.
60
+ let next = 1
61
+ for (const [table, count] of [['product_variants', 2], ['product_units', 1], ['reviews', 3]] as const) {
62
+ for (let i = 0; i < count; i++)
63
+ await run(`INSERT INTO ${table} (id, product_id) VALUES (${p(2)})`, [next++, 4])
64
+ }
65
+ }
66
+
67
+ async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
68
+ const read = (overrides: Partial<ProductListQuery> = {}) => readProductPage(query(overrides), runner, dialect)
69
+
70
+ // The summary covers the catalogue, not the page.
71
+ const first = await read()
72
+ expect(first.total).toBe(28)
73
+ expect(first.records).toHaveLength(10)
74
+ expect(first.summary).toEqual({
75
+ total: 28,
76
+ available: PRODUCTS.filter(product => product.is_available).length,
77
+ unavailable: PRODUCTS.filter(product => !product.is_available).length,
78
+ outOfStock: PRODUCTS.filter(product => product.inventory_count === 0).length,
79
+ totalInventory: PRODUCTS.reduce((sum, product) => sum + product.inventory_count, 0),
80
+ })
81
+ // Case is ignored, the same on every dialect.
82
+ expect(first.categories.map(option => option.label)).toEqual(['drinks', 'Mains', 'Pastry'])
83
+
84
+ // Filters.
85
+ expect((await read({ category: '2', perPage: 100 })).total).toBe(PRODUCTS.filter(product => product.category_id === 2).length)
86
+ expect((await read({ availability: 'available', perPage: 100 })).total).toBe(PRODUCTS.filter(product => product.is_available).length)
87
+ expect((await read({ availability: 'unavailable', perPage: 100 })).total).toBe(PRODUCTS.filter(product => !product.is_available).length)
88
+ expect((await read({ availability: 'out-of-stock', perPage: 100 })).total).toBe(PRODUCTS.filter(product => product.inventory_count === 0).length)
89
+
90
+ // Search: the joined category and manufacturer, allergens, a literal %.
91
+ expect((await read({ search: 'DRINKS', perPage: 100 })).total).toBe(PRODUCTS.filter(product => product.category_id === 2).length)
92
+ expect((await read({ search: 'bean co', perPage: 100 })).total).toBe(PRODUCTS.filter(product => product.manufacturer_id === 2).length)
93
+ expect((await read({ search: 'peanut' })).records.map(record => record.id)).toEqual(['11'])
94
+ expect((await read({ search: '100%' })).records.map(record => record.id)).toEqual(['9'])
95
+
96
+ // Newest first with id breaking ties, stable across pages.
97
+ const newest = [...PRODUCTS].sort((a, b) => b.created_at.localeCompare(a.created_at) || b.id - a.id).map(product => String(product.id))
98
+ const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
99
+ expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(newest)
100
+ expect((await read({ page: 7 })).page).toBe(3)
101
+
102
+ // Price high first, ties by name.
103
+ const byPrice = (await read({ sort: 'price', direction: 'desc', perPage: 100 })).records
104
+ const expectedPrice = [...PRODUCTS].sort((a, b) => b.price - a.price || a.name.toLowerCase().localeCompare(b.name.toLowerCase()) || b.id - a.id).map(product => String(product.id))
105
+ expect(byPrice.map(record => record.id)).toEqual(expectedPrice)
106
+
107
+ // Names sort ignoring case.
108
+ const names = (await read({ sort: 'name', direction: 'asc', perPage: 100 })).records.map(record => record.name)
109
+ expect(names).toEqual([...names].sort((a, b) => a.toLowerCase() < b.toLowerCase() ? -1 : a.toLowerCase() > b.toLowerCase() ? 1 : 0))
110
+
111
+ // Relations and references come through.
112
+ const four = (await read({ search: 'product e4' })).records.find(record => record.id === '4')
113
+ expect(four).toEqual(expect.objectContaining({ variantCount: 2, unitCount: 1, reviewCount: 3, categoryName: 'drinks', manufacturerName: 'Bean Co' }))
114
+
115
+ // The export holds every match, across batches, in order.
116
+ const exported = await readProductsForExport({ search: '', category: '', availability: '', sort: 'created', direction: 'desc' }, runner, dialect, 4)
117
+ expect(exported.map(record => record.id)).toEqual(newest)
118
+ }
119
+
120
+ describe('readProductPage on SQLite', () => {
121
+ test('summary, filters, search, sorts, pages and export', async () => {
122
+ const database = new Database(':memory:')
123
+ await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
124
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
125
+ })
126
+ })
127
+
128
+ for (const dialect of ['postgres', 'mysql'] as const) {
129
+ const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
130
+
131
+ test.skipIf(!connection)(`readProductPage on ${dialect}: summary, filters, search, sorts, pages and export`, async () => {
132
+ const url = new URL(connection!)
133
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
134
+ throw new Error('Product list tests require a local disposable database server')
135
+
136
+ const name = `stacks_product_list_${crypto.randomUUID().replaceAll('-', '')}`
137
+ const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
138
+ const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
139
+ await admin.unsafe(`CREATE DATABASE ${quoted}`)
140
+ const scoped = new URL(url.href)
141
+ scoped.pathname = `/${name}`
142
+ // Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
143
+ const database = new SQL({ url: scoped.href, database: name })
144
+
145
+ try {
146
+ await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
147
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
148
+ }
149
+ finally {
150
+ await database.close()
151
+ try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
152
+ finally { await admin.close() }
153
+ }
154
+ }, 60_000)
155
+ }
156
+
157
+ describe('parseProductListQuery', () => {
158
+ const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
159
+
160
+ test('defaults to the newest 25', () => {
161
+ expect(parseProductListQuery(reader({}))).toEqual({ search: '', category: '', availability: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
162
+ })
163
+
164
+ test('rejects what it cannot honour', () => {
165
+ expect(parseProductListQuery(reader({ category: '1 OR 1=1' }))).toHaveProperty('error')
166
+ expect(parseProductListQuery(reader({ availability: 'maybe' }))).toHaveProperty('error')
167
+ expect(parseProductListQuery(reader({ sort: 'cost' }))).toHaveProperty('error')
168
+ })
169
+ })
170
+
171
+ test('the CSV keeps the columns the page exported', () => {
172
+ const [header] = productsCsv([], 'USD', amount => String(amount)).replace('', '').split('\n')
173
+ expect(header).toBe('"Product ID","Name","Description","Price","Currency","Availability","Inventory","Preparation minutes","Category","Manufacturer","Allergens","Variants","Units","Reviews","Created at"')
174
+ })