@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,193 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { SQL } from 'bun'
3
+ import { describe, expect, test } from 'bun:test'
4
+ import type { ReviewListQuery } from './commerce-review-list'
5
+ import { parseReviewListQuery, readReviewPage } from './commerce-review-list'
6
+ import type { CommerceSqlRunner } from './commerce-sql'
7
+
8
+ /**
9
+ * The Reviews list against each dialect's real engine (stacksjs/stacks#3218),
10
+ * with the flags as each dialect stores booleans, and products and customers
11
+ * past the 500 the page used to read.
12
+ */
13
+ type Dialect = 'sqlite' | 'postgres' | 'mysql'
14
+
15
+ const NOW = new Date('2026-11-06T12:00:00.000Z')
16
+ const ROWS = 600
17
+ const PRODUCT_NAMES: Record<number, string> = { 1: 'Coffee Beans', 2: 'apron', 3: 'Mug', 4: 'Unreviewed', 600: 'zebra Tea' }
18
+ const CUSTOMER_NAMES: Record<number, string> = { 5: 'zoe', 6: 'Adam', 599: 'mia' }
19
+ const productName = (id: number) => PRODUCT_NAMES[id] ?? `Product ${id}`
20
+ const customerName = (id: number) => CUSTOMER_NAMES[id] ?? `Customer ${id}`
21
+
22
+ /** 30 reviews, one an hour back from NOW; 20 and 21 share a creation time. */
23
+ const REVIEWS = Array.from({ length: 30 }, (_, index) => {
24
+ const id = index + 1
25
+ return {
26
+ id,
27
+ product_id: id === 29 ? null : [1, 2, 3, 600][id % 4]!,
28
+ customer_id: [5, 6, 599, null][id % 4] ?? null,
29
+ rating: id % 7 === 0 ? null : (id % 5) + 1,
30
+ title: id === 11 ? 'Great_100% value' : id === 12 ? 'Great 1000 value' : `Review ${id}`,
31
+ content: id === 17 ? 'Smells LIKE roses' : `Words for review ${id}`,
32
+ is_approved: id % 2 === 0,
33
+ is_featured: id % 5 === 0,
34
+ is_verified_purchase: id % 3 === 0,
35
+ helpful_votes: (id * 7) % 10,
36
+ unhelpful_votes: id % 3,
37
+ hoursAgo: id === 21 ? 20 : id,
38
+ }
39
+ })
40
+ type Review = typeof REVIEWS[number]
41
+
42
+ const ids = (reviews: Review[]) => reviews.map(review => String(review.id))
43
+ const newestFirst = (a: Review, b: Review) => a.hoursAgo - b.hoursAgo || b.id - a.id
44
+
45
+ function query(overrides: Partial<ReviewListQuery> = {}): ReviewListQuery {
46
+ return { search: '', product: '', rating: '', moderation: '', sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
47
+ }
48
+
49
+ async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
50
+ const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
51
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
52
+ const flag = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
53
+ const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
54
+ const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
55
+ await run(`CREATE TABLE products (id ${pk}, name ${text})`)
56
+ await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text})`)
57
+ await run(`CREATE TABLE reviews (id ${pk}, rating INTEGER NULL, title ${text} NULL, content ${text} NULL, is_verified_purchase ${flag}, is_approved ${flag}, is_featured ${flag}, helpful_votes INTEGER, unhelpful_votes INTEGER, product_id INTEGER NULL, customer_id INTEGER NULL, created_at ${time})`)
58
+ const all = Array.from({ length: ROWS }, (_, i) => i + 1)
59
+ await run(`INSERT INTO products (id, name) VALUES ${all.map((_, i) => `(${p(2 * i + 1)}, ${p(2 * i + 2)})`).join(', ')}`, all.flatMap(id => [id, productName(id)]))
60
+ await run(`INSERT INTO customers (id, name, email) VALUES ${all.map((_, i) => `(${p(3 * i + 1)}, ${p(3 * i + 2)}, ${p(3 * i + 3)})`).join(', ')}`, all.flatMap(id => [id, customerName(id), `customer${id}@shop.test`]))
61
+ const bool = (value: boolean) => dialect === 'postgres' ? value : (value ? 1 : 0)
62
+ for (const review of REVIEWS) {
63
+ await run(
64
+ `INSERT INTO reviews (id, rating, title, content, is_verified_purchase, is_approved, is_featured, helpful_votes, unhelpful_votes, product_id, customer_id, created_at) VALUES (${Array.from({ length: 12 }, (_, i) => p(i + 1)).join(', ')})`,
65
+ [
66
+ review.id, review.rating, review.title, review.content, bool(review.is_verified_purchase), bool(review.is_approved),
67
+ bool(review.is_featured), review.helpful_votes, review.unhelpful_votes, review.product_id, review.customer_id,
68
+ new Date(NOW.getTime() - review.hoursAgo * 3_600_000).toISOString().slice(0, 19).replace('T', ' '),
69
+ ],
70
+ )
71
+ }
72
+ }
73
+
74
+ async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
75
+ const read = (overrides: Partial<ReviewListQuery> = {}) => readReviewPage(query(overrides), runner, dialect)
76
+ const all = async (overrides: Partial<ReviewListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => record.id)
77
+
78
+ // The summary counts every review, whatever the page is filtered to.
79
+ const filtered = await read({ moderation: 'featured' })
80
+ const rated = REVIEWS.flatMap(review => review.rating === null ? [] : [review.rating])
81
+ expect(filtered.summary).toEqual({
82
+ total: REVIEWS.length,
83
+ approved: REVIEWS.filter(review => review.is_approved).length,
84
+ pending: REVIEWS.filter(review => !review.is_approved).length,
85
+ featured: REVIEWS.filter(review => review.is_featured).length,
86
+ verified: REVIEWS.filter(review => review.is_verified_purchase).length,
87
+ averageRating: Math.round(rated.reduce((sum, rating) => sum + rating, 0) / rated.length * 10) / 10,
88
+ })
89
+ expect(filtered.total).toBe(REVIEWS.filter(review => review.is_featured).length)
90
+
91
+ // The product choices are the reviewed products, by name ignoring case.
92
+ expect(filtered.products).toEqual([
93
+ { id: '2', label: 'apron' },
94
+ { id: '1', label: 'Coffee Beans' },
95
+ { id: '3', label: 'Mug' },
96
+ { id: '600', label: 'zebra Tea' },
97
+ ])
98
+
99
+ // Filters.
100
+ const matching = (keep: (review: Review) => boolean) => ids(REVIEWS.filter(keep).sort(newestFirst))
101
+ expect(await all({ product: '600' })).toEqual(matching(review => review.product_id === 600))
102
+ expect(await all({ rating: '5' })).toEqual(matching(review => review.rating === 5))
103
+ expect(await all({ rating: 'none' })).toEqual(matching(review => review.rating === null))
104
+ expect(await all({ moderation: 'approved' })).toEqual(matching(review => review.is_approved))
105
+ expect(await all({ moderation: 'pending' })).toEqual(matching(review => !review.is_approved))
106
+ expect(await all({ moderation: 'verified' })).toEqual(matching(review => review.is_verified_purchase))
107
+ expect(await all({ product: '1', moderation: 'approved' })).toEqual(matching(review => review.product_id === 1 && review.is_approved))
108
+
109
+ // Search: customer name and email, product name, title with a literal %, content, ignoring case.
110
+ expect(await all({ search: 'ZOE' })).toEqual(matching(review => review.customer_id === 5))
111
+ expect(await all({ search: 'customer599@' })).toEqual(matching(review => review.customer_id === 599))
112
+ expect(await all({ search: 'ZEBRA' })).toEqual(matching(review => review.product_id === 600))
113
+ expect(await all({ search: '100%' })).toEqual(['11'])
114
+ expect(await all({ search: 'like roses' })).toEqual(['17'])
115
+
116
+ // Newest first, the id breaking the tie between 20 and 21, stable across pages.
117
+ const newest = [...REVIEWS].sort(newestFirst)
118
+ const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
119
+ expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(ids(newest))
120
+ expect((await read({ page: 9 })).page).toBe(3)
121
+
122
+ // Sorts: unrated last either way; ties newest first.
123
+ const unrated = REVIEWS.filter(review => review.rating === null).sort(newestFirst)
124
+ const ratedReviews = REVIEWS.filter(review => review.rating !== null)
125
+ expect(await all({ sort: 'rating', direction: 'desc' })).toEqual(ids([...[...ratedReviews].sort((a, b) => b.rating! - a.rating! || newestFirst(a, b)), ...unrated]))
126
+ expect(await all({ sort: 'rating', direction: 'asc' })).toEqual(ids([...[...ratedReviews].sort((a, b) => a.rating! - b.rating! || newestFirst(a, b)), ...unrated]))
127
+ expect(await all({ sort: 'helpful', direction: 'desc' })).toEqual(ids([...REVIEWS].sort((a, b) => b.helpful_votes - a.helpful_votes || newestFirst(a, b))))
128
+ const customerKey = (review: Review) => review.customer_id === null ? '' : customerName(review.customer_id).toLowerCase()
129
+ expect(await all({ sort: 'customer', direction: 'asc' })).toEqual(ids([...REVIEWS].sort((a, b) => customerKey(a).localeCompare(customerKey(b)) || newestFirst(a, b))))
130
+ const productKey = (review: Review) => review.product_id === null ? '' : productName(review.product_id).toLowerCase()
131
+ expect(await all({ sort: 'product', direction: 'asc' })).toEqual(ids([...REVIEWS].sort((a, b) => productKey(a).localeCompare(productKey(b)) || newestFirst(a, b))))
132
+ expect(await all({ sort: 'approved', direction: 'desc' })).toEqual(ids([...REVIEWS].sort((a, b) => Number(b.is_approved) - Number(a.is_approved) || newestFirst(a, b))))
133
+
134
+ // Products and customers past the 500th, read by the ids the page references.
135
+ const records = (await read({ perPage: 100 })).records
136
+ expect(records.find(record => record.productId === '600')).toMatchObject({ productName: 'zebra Tea' })
137
+ expect(records.find(record => record.customerId === '599')).toMatchObject({ customerName: 'mia', customerEmail: 'customer599@shop.test' })
138
+ expect(records.find(record => record.id === '29')).toMatchObject({ productId: '', productName: '' })
139
+ }
140
+
141
+ describe('readReviewPage on SQLite', () => {
142
+ test('summary, product choices, filters, search, sorts, pages and references', async () => {
143
+ const database = new Database(':memory:')
144
+ await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
145
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
146
+ })
147
+ })
148
+
149
+ for (const dialect of ['postgres', 'mysql'] as const) {
150
+ const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
151
+
152
+ test.skipIf(!connection)(`readReviewPage on ${dialect}: summary, product choices, filters, search, sorts, pages and references`, async () => {
153
+ const url = new URL(connection!)
154
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
155
+ throw new Error('Review list tests require a local disposable database server')
156
+
157
+ const name = `stacks_review_list_${crypto.randomUUID().replaceAll('-', '')}`
158
+ const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
159
+ const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
160
+ await admin.unsafe(`CREATE DATABASE ${quoted}`)
161
+ const scoped = new URL(url.href)
162
+ scoped.pathname = `/${name}`
163
+ // Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
164
+ const database = new SQL({ url: scoped.href, database: name })
165
+
166
+ try {
167
+ await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
168
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
169
+ }
170
+ finally {
171
+ await database.close()
172
+ try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
173
+ finally { await admin.close() }
174
+ }
175
+ }, 60_000)
176
+ }
177
+
178
+ describe('parseReviewListQuery', () => {
179
+ const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
180
+
181
+ test('defaults to every review, newest first, 25 a page', () => {
182
+ expect(parseReviewListQuery(reader({}))).toEqual({ search: '', product: '', rating: '', moderation: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
183
+ expect(parseReviewListQuery(reader({ sort: 'helpful' }))).toHaveProperty('direction', 'desc')
184
+ expect(parseReviewListQuery(reader({ sort: 'customer' }))).toHaveProperty('direction', 'asc')
185
+ })
186
+
187
+ test('refuses values the page does not offer', () => {
188
+ expect(parseReviewListQuery(reader({ product: 'abc' }))).toHaveProperty('error')
189
+ expect(parseReviewListQuery(reader({ rating: '6' }))).toHaveProperty('error')
190
+ expect(parseReviewListQuery(reader({ moderation: 'spam' }))).toHaveProperty('error')
191
+ expect(parseReviewListQuery(reader({ sort: 'images' }))).toHaveProperty('error')
192
+ })
193
+ })
@@ -0,0 +1,220 @@
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 { referencedIds } from './commerce-record'
6
+ import type { CommerceSqlRunner } from './commerce-sql'
7
+ import { binder, idPlaceholders, isTrue, sqlRows } from './commerce-sql'
8
+ import type { ReviewProductOption, ReviewRecord, ReviewSummary } from './review-records'
9
+ import { normalizeReviewCustomerContext, normalizeReviewProductOption, normalizeReviewRecord } from './review-records'
10
+
11
+ /**
12
+ * One page of reviews, searched, filtered, sorted and counted by the database,
13
+ * with the summary of every review (stacksjs/stacks#3218).
14
+ *
15
+ * The Reviews page used to read the newest 500 reviews and do all of that in
16
+ * the browser, so a review past the 500th could not be found or moderated,
17
+ * and the summary counted those 500. It also read the first 500 products and
18
+ * customers by name, so one review of any later product or by any later
19
+ * customer failed the whole page.
20
+ */
21
+ export const REVIEW_SORTS = ['created', 'id', 'customer', 'product', 'rating', 'helpful', 'approved'] as const
22
+ export type ReviewSort = typeof REVIEW_SORTS[number]
23
+
24
+ export const REVIEW_RATINGS = ['1', '2', '3', '4', '5', 'none'] as const
25
+ export const REVIEW_MODERATION = ['approved', 'pending', 'featured', 'verified'] as const
26
+
27
+ export interface ReviewListQuery {
28
+ search: string
29
+ /** A product id, or '' for any. */
30
+ product: string
31
+ /** '' for any. */
32
+ rating: '' | typeof REVIEW_RATINGS[number]
33
+ /** '' for any. */
34
+ moderation: '' | typeof REVIEW_MODERATION[number]
35
+ sort: ReviewSort
36
+ direction: 'asc' | 'desc'
37
+ page: number
38
+ perPage: number
39
+ }
40
+
41
+ export function parseReviewListQuery(read: QueryReader): ReviewListQuery | { error: string } {
42
+ const pageText = queryText(read, 'page')
43
+ const page = pageText === '' ? 1 : Number(pageText)
44
+ if (!Number.isInteger(page) || page < 1)
45
+ return { error: 'page must be a whole number of 1 or more.' }
46
+
47
+ const sizeText = queryText(read, 'per_page')
48
+ const perPage = sizeText === '' ? 25 : Number(sizeText)
49
+ if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
50
+ return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
51
+
52
+ const sort = queryText(read, 'sort') || 'created'
53
+ if (!(REVIEW_SORTS as readonly string[]).includes(sort))
54
+ return { error: `sort must be one of ${REVIEW_SORTS.join(', ')}.` }
55
+
56
+ const directionText = queryText(read, 'direction').toLowerCase()
57
+ const direction = directionText === '' ? (['created', 'rating', 'helpful'].includes(sort) ? 'desc' : 'asc') : directionText
58
+ if (direction !== 'asc' && direction !== 'desc')
59
+ return { error: 'direction must be asc or desc.' }
60
+
61
+ const search = queryText(read, 'q')
62
+ if (search.length > 200)
63
+ return { error: 'q must be 200 characters or fewer.' }
64
+
65
+ const product = queryText(read, 'product')
66
+ if (product && !/^\d+$/.test(product))
67
+ return { error: 'product must be a product id.' }
68
+
69
+ const rating = queryText(read, 'rating')
70
+ if (rating && !(REVIEW_RATINGS as readonly string[]).includes(rating))
71
+ return { error: `rating must be one of ${REVIEW_RATINGS.join(', ')}.` }
72
+
73
+ const moderation = queryText(read, 'moderation')
74
+ if (moderation && !(REVIEW_MODERATION as readonly string[]).includes(moderation))
75
+ return { error: `moderation must be one of ${REVIEW_MODERATION.join(', ')}.` }
76
+
77
+ return {
78
+ search,
79
+ product,
80
+ rating: rating as ReviewListQuery['rating'],
81
+ moderation: moderation as ReviewListQuery['moderation'],
82
+ sort: sort as ReviewSort,
83
+ direction,
84
+ page,
85
+ perPage,
86
+ }
87
+ }
88
+
89
+ const FROM = ' FROM reviews r LEFT JOIN products p ON p.id = r.product_id LEFT JOIN customers c ON c.id = r.customer_id'
90
+
91
+ function sortExpression(sort: ReviewSort, dialect: QueryBuilderDialect): string {
92
+ switch (sort) {
93
+ case 'id': return 'r.id'
94
+ case 'customer': return `LOWER(COALESCE(c.name, ''))`
95
+ case 'product': return `LOWER(COALESCE(p.name, ''))`
96
+ case 'rating': return 'r.rating'
97
+ case 'helpful': return 'r.helpful_votes'
98
+ case 'approved': return `CASE WHEN ${isTrue('r.is_approved', dialect)} THEN 1 ELSE 0 END`
99
+ default: return 'r.created_at'
100
+ }
101
+ }
102
+
103
+ export function reviewFilter(query: Pick<ReviewListQuery, 'search' | 'product' | 'rating' | 'moderation'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
104
+ const { bind, values } = binder(dialect)
105
+ const clauses: string[] = []
106
+ if (query.product)
107
+ clauses.push(`r.product_id = ${bind(Number(query.product))}`)
108
+ if (query.rating === 'none')
109
+ clauses.push('r.rating IS NULL')
110
+ else if (query.rating)
111
+ clauses.push(`r.rating = ${bind(Number(query.rating))}`)
112
+ if (query.moderation === 'approved')
113
+ clauses.push(isTrue('r.is_approved', dialect))
114
+ if (query.moderation === 'pending')
115
+ clauses.push(`NOT (${isTrue('r.is_approved', dialect)})`)
116
+ if (query.moderation === 'featured')
117
+ clauses.push(isTrue('r.is_featured', dialect))
118
+ if (query.moderation === 'verified')
119
+ clauses.push(isTrue('r.is_verified_purchase', dialect))
120
+ if (query.search) {
121
+ const pattern = containsPattern(query.search)
122
+ const columns = [
123
+ `COALESCE(c.name, '')`,
124
+ `COALESCE(c.email, '')`,
125
+ `COALESCE(p.name, '')`,
126
+ `COALESCE(r.title, '')`,
127
+ `COALESCE(r.content, '')`,
128
+ ]
129
+ clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
130
+ }
131
+ return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
132
+ }
133
+
134
+ function orderBy(query: Pick<ReviewListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
135
+ const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
136
+ // Unrated reviews come last in both directions, as the page sorted them:
137
+ // each dialect would put NULL at a different end.
138
+ const unrated = query.sort === 'rating' ? 'CASE WHEN r.rating IS NULL THEN 1 ELSE 0 END ASC, ' : ''
139
+ // Ties read newest first, as the page broke them; the id breaks every
140
+ // remaining tie, so pages never repeat or skip a review.
141
+ if (query.sort === 'created' || query.sort === 'id')
142
+ return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, r.id ${direction}`
143
+ return ` ORDER BY ${unrated}${sortExpression(query.sort, dialect)} ${direction}, r.created_at DESC, r.id DESC`
144
+ }
145
+
146
+ /** Reviews turned into records, against exactly the products and customers they reference. */
147
+ async function recordsFor(reviews: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ReviewRecord[]> {
148
+ if (reviews.length === 0)
149
+ return []
150
+ const productIds = referencedIds(reviews, 'product_id')
151
+ const customerIds = referencedIds(reviews, 'customer_id')
152
+ const [products, customers] = await Promise.all([
153
+ productIds.length > 0 ? run.unsafe(`SELECT id, name FROM products WHERE id IN (${idPlaceholders(productIds, dialect)})`, productIds).execute() : [],
154
+ customerIds.length > 0 ? run.unsafe(`SELECT id, name, email FROM customers WHERE id IN (${idPlaceholders(customerIds, dialect)})`, customerIds).execute() : [],
155
+ ])
156
+ const productMap = new Map(sqlRows(products).map(normalizeReviewProductOption).map(option => [option.id, { name: option.label }]))
157
+ const customerMap = new Map(sqlRows(customers).map(normalizeReviewCustomerContext).map(customer => [customer.id, customer.context]))
158
+ return reviews.map(review => normalizeReviewRecord(review, productMap, customerMap))
159
+ }
160
+
161
+ /** The summary cards, over every review as before. */
162
+ async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ReviewSummary> {
163
+ const count = (condition: string) => `SUM(CASE WHEN ${condition} THEN 1 ELSE 0 END)`
164
+ const row = sqlRows(await run.unsafe(
165
+ `SELECT COUNT(*) AS total_count, ${count(isTrue('is_approved', dialect))} AS approved_count, ${count(isTrue('is_featured', dialect))} AS featured_count, ${count(isTrue('is_verified_purchase', dialect))} AS verified_count, COUNT(rating) AS rated_count, SUM(rating) AS rating_total FROM reviews`,
166
+ ).execute())[0] ?? {}
167
+ const total = countOf(row.total_count)
168
+ const approved = countOf(row.approved_count)
169
+ const rated = countOf(row.rated_count)
170
+ return {
171
+ total,
172
+ approved,
173
+ pending: total - approved,
174
+ featured: countOf(row.featured_count),
175
+ verified: countOf(row.verified_count),
176
+ // An unrated review is a review, not a 0-star one, so the average is
177
+ // taken over the rated reviews only, as summarizeReviews does.
178
+ averageRating: rated > 0 ? Math.round(countOf(row.rating_total) / rated * 10) / 10 : 0,
179
+ }
180
+ }
181
+
182
+ /**
183
+ * The product filter's choices: every product that has a review, read whole.
184
+ * The page listed the first 500 products by name, reviewed or not.
185
+ */
186
+ async function reviewedProducts(run: CommerceSqlRunner): Promise<ReviewProductOption[]> {
187
+ const rows = sqlRows(await run.unsafe(
188
+ // LOWER, so the order is the same on every dialect: each collates case its own way.
189
+ 'SELECT p.id, p.name FROM products p WHERE EXISTS (SELECT 1 FROM reviews r WHERE r.product_id = p.id) ORDER BY LOWER(p.name) ASC, p.id ASC',
190
+ ).execute())
191
+ return rows.map(normalizeReviewProductOption)
192
+ }
193
+
194
+ export interface ReviewPage {
195
+ records: ReviewRecord[]
196
+ total: number
197
+ page: number
198
+ summary: ReviewSummary
199
+ products: ReviewProductOption[]
200
+ }
201
+
202
+ export async function readReviewPage(
203
+ query: ReviewListQuery,
204
+ run: CommerceSqlRunner = db,
205
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
206
+ ): Promise<ReviewPage> {
207
+ const { where, values } = reviewFilter(query, dialect)
208
+ const [counted, summary, products] = await Promise.all([
209
+ run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
210
+ summarize(run, dialect),
211
+ reviewedProducts(run),
212
+ ])
213
+ const total = countOf(sqlRows(counted)[0]?.total_count)
214
+ const page = pageWithin(query.page, total, query.perPage)
215
+ const reviews = await run.unsafe(
216
+ `SELECT r.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
217
+ values,
218
+ ).execute()
219
+ return { records: await recordsFor(sqlRows(reviews), run, dialect), total, page, summary, products }
220
+ }
@@ -0,0 +1,57 @@
1
+ import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
2
+ import { sqlHelpers } from '@stacksjs/database/runtime'
3
+
4
+ /**
5
+ * The SQL plumbing the commerce lists share (stacksjs/stacks#3218): Orders and
6
+ * Payments read their pages with plain SQL so one test can run them against
7
+ * SQLite, PostgreSQL and MySQL alike.
8
+ */
9
+
10
+ /** What runs the queries: the configured `db`, or a test's own connection. */
11
+ export interface CommerceSqlRunner {
12
+ unsafe: (sql: string, values?: unknown[]) => { execute: () => Promise<unknown> }
13
+ }
14
+
15
+ /** A result as rows, whatever the driver returned for an empty one. */
16
+ export function sqlRows(result: unknown): Array<Record<string, unknown>> {
17
+ return Array.isArray(result) ? result as Array<Record<string, unknown>> : []
18
+ }
19
+
20
+ /** The placeholders for an `IN (...)` over `ids`, numbered from 1. */
21
+ export function idPlaceholders(ids: unknown[], dialect: QueryBuilderDialect): string {
22
+ const sql = sqlHelpers(dialect)
23
+ return ids.map((_, index) => sql.param(index + 1)).join(', ')
24
+ }
25
+
26
+ /**
27
+ * A column as text, for `LOWER`, `LIKE` and comparisons. PostgreSQL enums
28
+ * (payments.status and payments.method) and numbers need it, and comparing an
29
+ * enum to a value it does not list is an error there rather than no match.
30
+ */
31
+ export function asText(column: string, dialect: QueryBuilderDialect): string {
32
+ const type = dialect === 'mysql' || dialect === 'singlestore' || dialect === 'vitess' ? 'CHAR' : 'TEXT'
33
+ return `CAST(${column} AS ${type})`
34
+ }
35
+
36
+ /** Binds values in order and returns each placeholder, for building a WHERE. */
37
+ export function binder(dialect: QueryBuilderDialect): { bind: (value: unknown) => string, values: unknown[] } {
38
+ const sql = sqlHelpers(dialect)
39
+ const values: unknown[] = []
40
+ return {
41
+ values,
42
+ bind: (value: unknown) => {
43
+ values.push(value)
44
+ return sql.param(values.length)
45
+ },
46
+ }
47
+ }
48
+
49
+ /**
50
+ * "This flag is set", the same on every dialect: SQLite and MySQL store 0 and
51
+ * 1, and PostgreSQL a boolean, or an integer in an older schema, which the
52
+ * cast reads either way. A bare `column = 1` is an error on a PostgreSQL
53
+ * boolean.
54
+ */
55
+ export function isTrue(column: string, dialect: QueryBuilderDialect): string {
56
+ return dialect === 'postgres' ? `CAST(${column} AS INTEGER) = 1` : `${column} = 1`
57
+ }
@@ -5,6 +5,7 @@ import {
5
5
  paymentsToCsv,
6
6
  summarizePayments,
7
7
  } from './payment-records'
8
+ import { referencedIds } from './commerce-record'
8
9
 
9
10
  function payment(overrides: Record<string, unknown> = {}): Record<string, unknown> {
10
11
  return {
@@ -103,3 +104,18 @@ describe('dashboard payment records', () => {
103
104
  expect(csv).toContain('1,2026-07-29T10:00:00.000Z,completed,creditCard,1000')
104
105
  })
105
106
  })
107
+
108
+ describe('the orders and customers a payments page reads', () => {
109
+ test('a payment for an order past the 500 oldest normalizes from the referenced read', () => {
110
+ // A store's 704th order is outside a read of its 500 oldest. The ids the
111
+ // payments reference still name it, so the payment is accepted.
112
+ const payments = [payment({ id: 1, order_id: 704, customer_id: 9 }), payment({ id: 2, order_id: 12 })]
113
+ const orderIds = new Set(referencedIds(payments, 'order_id').map(String))
114
+ const customerIds = new Set(referencedIds(payments, 'customer_id').map(String))
115
+ expect(normalizePaymentRecord(payments[0], { orderIds, customerIds }).orderId).toBe('704')
116
+
117
+ // The refusal this prevents is real: without order 704 the payment is rejected.
118
+ const oldest = new Set(Array.from({ length: 500 }, (_, index) => String(index + 1)))
119
+ expect(() => normalizePaymentRecord(payments[0], { orderIds: oldest, customerIds })).toThrow('references missing Order 704')
120
+ })
121
+ })
@@ -1,7 +1,6 @@
1
1
  import { describe, expect, it } from 'bun:test'
2
2
  import {
3
3
  normalizeProductUnitRecord,
4
- productUnitOptions,
5
4
  summarizeProductUnits,
6
5
  } from './product-unit-records'
7
6
 
@@ -75,16 +74,4 @@ describe('dashboard product unit records', () => {
75
74
 
76
75
  expect(summarizeProductUnits(records).defaultConflicts).toBe(1)
77
76
  })
78
-
79
- it('builds stable, validated product options from model rows', () => {
80
- expect(productUnitOptions([
81
- { id: 2, name: 'Tea' },
82
- { id: 1, name: 'Coffee' },
83
- ])).toEqual([
84
- { id: '1', name: 'Coffee' },
85
- { id: '2', name: 'Tea' },
86
- ])
87
- expect(() => productUnitOptions([{ id: 3, name: '' }]))
88
- .toThrow('Product 3.name must be a non-empty string')
89
- })
90
77
  })
@@ -20,11 +20,6 @@ export interface ProductUnitRecord {
20
20
  createdAt: string
21
21
  }
22
22
 
23
- export interface ProductUnitOption {
24
- id: string
25
- name: string
26
- }
27
-
28
23
  export interface ProductUnitSummary {
29
24
  total: number
30
25
  defaults: number
@@ -33,18 +28,6 @@ export interface ProductUnitSummary {
33
28
  defaultConflicts: number
34
29
  }
35
30
 
36
- export function productUnitOptions(products: any[]): ProductUnitOption[] {
37
- return products
38
- .map((product) => {
39
- const id = commerceIdentifier(commerceValue(product, 'id', 'uuid'), 'Product')
40
- return {
41
- id,
42
- name: commerceRequiredString(commerceValue(product, 'name'), `Product ${id}`, 'name'),
43
- }
44
- })
45
- .sort((left, right) => left.name.localeCompare(right.name))
46
- }
47
-
48
31
  export function normalizeProductUnitRecord(
49
32
  record: any,
50
33
  products = new Map<string, string>(),
@@ -2,7 +2,6 @@ import { describe, expect, it } from 'bun:test'
2
2
  import {
3
3
  normalizeProductVariantRecord,
4
4
  parseVariantOptions,
5
- productVariantOptions,
6
5
  summarizeProductVariants,
7
6
  } from './product-variant-records'
8
7
 
@@ -70,16 +69,4 @@ describe('dashboard product variant records', () => {
70
69
  linkedProducts: 2,
71
70
  })
72
71
  })
73
-
74
- it('builds validated Product options', () => {
75
- expect(productVariantOptions([
76
- { id: 2, name: 'Tea' },
77
- { id: 1, name: 'Coffee' },
78
- ])).toEqual([
79
- { id: '1', name: 'Coffee' },
80
- { id: '2', name: 'Tea' },
81
- ])
82
- expect(() => productVariantOptions([{ id: 3, name: '' }]))
83
- .toThrow('Product 3.name must be a non-empty string')
84
- })
85
72
  })
@@ -21,11 +21,6 @@ export interface ProductVariantRecord {
21
21
  createdAt: string
22
22
  }
23
23
 
24
- export interface ProductVariantOption {
25
- id: string
26
- name: string
27
- }
28
-
29
24
  export interface ProductVariantSummary {
30
25
  total: number
31
26
  active: number
@@ -37,18 +32,6 @@ export function parseVariantOptions(input: unknown): string[] {
37
32
  return commerceStringList(input, 'ProductVariant', 'options')
38
33
  }
39
34
 
40
- export function productVariantOptions(products: any[]): ProductVariantOption[] {
41
- return products
42
- .map((product) => {
43
- const id = commerceIdentifier(commerceValue(product, 'id', 'uuid'), 'Product')
44
- return {
45
- id,
46
- name: commerceRequiredString(commerceValue(product, 'name'), `Product ${id}`, 'name'),
47
- }
48
- })
49
- .sort((left, right) => left.name.localeCompare(right.name))
50
- }
51
-
52
35
  export function normalizeProductVariantRecord(
53
36
  record: any,
54
37
  productNames = new Map<string, string>(),
@@ -28,13 +28,14 @@ describe('dashboard product waitlist records', () => {
28
28
  it('normalizes database and model attribute names', () => {
29
29
  expect(normalizeProductWaitlistRecord(
30
30
  entry({ quantity: '3', customer_id: 9 }),
31
- new Set(['8']),
31
+ new Map([['8', 'Native Mug']]),
32
32
  new Set(['9']),
33
33
  )).toMatchObject({
34
34
  id: '4',
35
35
  quantity: 3,
36
36
  notificationPreference: 'email',
37
37
  productId: '8',
38
+ productName: 'Native Mug',
38
39
  customerId: '9',
39
40
  status: 'waiting',
40
41
  createdAt: '2026-07-28T12:00:00.000Z',
@@ -44,21 +45,21 @@ describe('dashboard product waitlist records', () => {
44
45
  it('rejects corrupt fields and missing relationships', () => {
45
46
  expect(() => normalizeProductWaitlistRecord(
46
47
  entry({ quantity: 0 }),
47
- new Set(['8']),
48
+ new Map([['8', 'Native Mug']]),
48
49
  )).toThrow('WaitlistProduct 4.quantity must be at least 1')
49
50
  expect(() => normalizeProductWaitlistRecord(
50
51
  entry({ product_id: 99 }),
51
- new Set(),
52
+ new Map(),
52
53
  )).toThrow('WaitlistProduct 4.product_id references missing Product 99')
53
54
  expect(() => normalizeProductWaitlistRecord(
54
55
  entry({ customer_id: 99 }),
55
- new Set(['8']),
56
+ new Map([['8', 'Native Mug']]),
56
57
  new Set(),
57
58
  )).toThrow('WaitlistProduct 4.customer_id references missing Customer 99')
58
59
  })
59
60
 
60
61
  it('summarizes only native record states', () => {
61
- const productIds = new Set(['8'])
62
+ const productIds = new Map([['8', 'Native Mug']])
62
63
  const records = [
63
64
  normalizeProductWaitlistRecord(entry({ id: 1, status: 'waiting' }), productIds),
64
65
  normalizeProductWaitlistRecord(entry({ id: 2, status: 'notified' }), productIds),