@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,152 @@
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 { countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
5
+ import type { CommercePosProduct } from './commerce-pos'
6
+ import { normalizeCommercePosProduct, selectCommercePosTaxRate } from './commerce-pos'
7
+ import { PRODUCT_FROM, productFilter, productRecordsFor } from './commerce-product-list'
8
+ import type { ProductOption } from './commerce-product-records'
9
+ import { normalizeProductOption } from './commerce-product-records'
10
+ import type { CommerceSqlRunner } from './commerce-sql'
11
+ import { asText, idPlaceholders, isTrue, sqlRows } from './commerce-sql'
12
+
13
+ /**
14
+ * The point of sale's catalogue and settings, read by the database
15
+ * (stacksjs/stacks#3218).
16
+ *
17
+ * The point of sale used to read the first 500 products, categories,
18
+ * manufacturers, customers and tax rates by name or id with every load, so a
19
+ * product past the 500th could not be rung up, its category or manufacturer
20
+ * failed the whole screen, and the checkout could not be given a later
21
+ * customer. The catalogue is now searched and paged here, a cart is checked
22
+ * against exactly the products it holds, the checkout searches customers
23
+ * (commerce-choices.ts), and the settings are counted over everything.
24
+ */
25
+ export const POS_AVAILABILITY = ['sellable', 'unsellable'] as const
26
+
27
+ export interface PosCatalogQuery {
28
+ search: string
29
+ /** A category id, or '' for any. */
30
+ category: string
31
+ /** '' for every product. */
32
+ availability: '' | typeof POS_AVAILABILITY[number]
33
+ page: number
34
+ perPage: number
35
+ }
36
+
37
+ /** The most products a cart can be checked against in one request. */
38
+ export const POS_MAX_IDS = 100
39
+
40
+ export function parsePosCatalogQuery(read: QueryReader): PosCatalogQuery | { error: string } {
41
+ const pageText = queryText(read, 'page')
42
+ const page = pageText === '' ? 1 : Number(pageText)
43
+ if (!Number.isInteger(page) || page < 1)
44
+ return { error: 'page must be a whole number of 1 or more.' }
45
+
46
+ const sizeText = queryText(read, 'per_page')
47
+ const perPage = sizeText === '' ? 50 : Number(sizeText)
48
+ if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
49
+ return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
50
+
51
+ const search = queryText(read, 'q')
52
+ if (search.length > 200)
53
+ return { error: 'q must be 200 characters or fewer.' }
54
+
55
+ const category = queryText(read, 'category')
56
+ if (category && !/^\d+$/.test(category))
57
+ return { error: 'category must be a category id.' }
58
+
59
+ const availability = queryText(read, 'availability')
60
+ if (availability && !(POS_AVAILABILITY as readonly string[]).includes(availability))
61
+ return { error: `availability must be one of ${POS_AVAILABILITY.join(', ')}.` }
62
+
63
+ return { search, category, availability: availability as PosCatalogQuery['availability'], page, perPage }
64
+ }
65
+
66
+ /** The product ids in `ids=1,2,3`, or an error. Empty when there is no `ids`. */
67
+ export function parsePosIds(read: QueryReader): number[] | { error: string } {
68
+ const text = queryText(read, 'ids')
69
+ if (!text)
70
+ return []
71
+ const parts = text.split(',').map(part => part.trim()).filter(Boolean)
72
+ if (parts.length > POS_MAX_IDS)
73
+ return { error: `ids can list at most ${POS_MAX_IDS} products.` }
74
+ if (!parts.every(part => /^\d+$/.test(part)))
75
+ return { error: 'ids must be product ids separated by commas.' }
76
+ return [...new Set(parts.map(Number))]
77
+ }
78
+
79
+ async function posProducts(rows: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<CommercePosProduct[]> {
80
+ return (await productRecordsFor(rows, run, dialect, false)).map(normalizeCommercePosProduct)
81
+ }
82
+
83
+ export interface PosCatalogPage {
84
+ products: CommercePosProduct[]
85
+ total: number
86
+ page: number
87
+ }
88
+
89
+ /** One page of the catalogue, by name ignoring case, then id. */
90
+ export async function readPosCatalogPage(
91
+ query: PosCatalogQuery,
92
+ run: CommerceSqlRunner = db,
93
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
94
+ ): Promise<PosCatalogPage> {
95
+ const { where, values } = productFilter({
96
+ search: query.search,
97
+ category: query.category,
98
+ availability: query.availability,
99
+ }, dialect)
100
+ const counted = await run.unsafe(`SELECT COUNT(*) AS total_count${PRODUCT_FROM}${where}`, values).execute()
101
+ const total = countOf(sqlRows(counted)[0]?.total_count)
102
+ const page = pageWithin(query.page, total, query.perPage)
103
+ const rows = await run.unsafe(
104
+ `SELECT p.*${PRODUCT_FROM}${where} ORDER BY LOWER(p.name) ASC, p.id ASC LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
105
+ values,
106
+ ).execute()
107
+ return { products: await posProducts(sqlRows(rows), run, dialect), total, page }
108
+ }
109
+
110
+ /**
111
+ * Exactly the products a cart holds, as they are now, so a reload can update
112
+ * each line's price and stock, or drop it, whatever page the catalogue shows.
113
+ */
114
+ export async function readPosProducts(
115
+ ids: number[],
116
+ run: CommerceSqlRunner = db,
117
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
118
+ ): Promise<CommercePosProduct[]> {
119
+ if (ids.length === 0)
120
+ return []
121
+ const rows = await run.unsafe(`SELECT p.*${PRODUCT_FROM} WHERE p.id IN (${idPlaceholders(ids, dialect)})`, ids).execute()
122
+ return posProducts(sqlRows(rows), run, dialect)
123
+ }
124
+
125
+ export interface PosSettings {
126
+ /** The categories some product is in, by name ignoring case. */
127
+ categories: ProductOption[]
128
+ /** The default active tax rate, or the first active one, or 0. */
129
+ taxRate: number
130
+ summary: { products: number, sellable: number, inventory: number }
131
+ }
132
+
133
+ export async function readPosSettings(
134
+ run: CommerceSqlRunner = db,
135
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
136
+ ): Promise<PosSettings> {
137
+ const [categories, taxRates, totals] = await Promise.all([
138
+ run.unsafe('SELECT c.id, c.name FROM categories c WHERE EXISTS (SELECT 1 FROM products p WHERE p.category_id = c.id) ORDER BY LOWER(c.name) ASC, c.id ASC').execute(),
139
+ run.unsafe(`SELECT id, rate, status, is_default FROM tax_rates WHERE ${asText('status', dialect)} = 'active' ORDER BY CASE WHEN ${isTrue('is_default', dialect)} THEN 0 ELSE 1 END, id LIMIT 1`).execute(),
140
+ run.unsafe(`SELECT COUNT(*) AS product_count, SUM(CASE WHEN ${isTrue('is_available', dialect)} AND inventory_count > 0 THEN 1 ELSE 0 END) AS sellable_count, SUM(inventory_count) AS inventory_total FROM products`).execute(),
141
+ ])
142
+ const row = sqlRows(totals)[0] ?? {}
143
+ return {
144
+ categories: sqlRows(categories).map(normalizeProductOption),
145
+ taxRate: selectCommercePosTaxRate(sqlRows(taxRates)),
146
+ summary: {
147
+ products: countOf(row.product_count),
148
+ sellable: countOf(row.sellable_count),
149
+ inventory: countOf(row.inventory_total),
150
+ },
151
+ }
152
+ }
@@ -2,8 +2,6 @@ import { describe, expect, it } from 'bun:test'
2
2
  import {
3
3
  calculateCommercePosSale,
4
4
  deriveCommercePosTaxRate,
5
- isCommercePosCustomerActive,
6
- normalizeCommercePosCustomer,
7
5
  parseCommercePosLines,
8
6
  selectCommercePosTaxRate,
9
7
  } from './commerce-pos'
@@ -81,16 +79,7 @@ describe('dashboard commerce POS helpers', () => {
81
79
  expect(() => deriveCommercePosTaxRate(100, -1)).toThrow('non-negative')
82
80
  })
83
81
 
84
- it('validates persisted customers and tax rates', () => {
85
- const customer = { id: 1, name: 'Chris', email: 'chris@example.com', status: 'Active' }
86
- expect(isCommercePosCustomerActive(customer)).toBeTrue()
87
- expect(normalizeCommercePosCustomer(customer)).toEqual({
88
- id: '1',
89
- label: 'Chris',
90
- email: 'chris@example.com',
91
- })
92
- expect(() => normalizeCommercePosCustomer({ id: 1, name: '', email: '' }))
93
- .toThrow('Customer 1.name must be a non-empty string')
82
+ it('validates persisted tax rates', () => {
94
83
  expect(() => selectCommercePosTaxRate([{ id: 1, status: 'active', is_default: false, rate: 'invalid' }]))
95
84
  .toThrow('TaxRate 1.rate must be a finite number')
96
85
  })
@@ -13,12 +13,6 @@ export interface CommercePosProduct {
13
13
  categoryName: string
14
14
  }
15
15
 
16
- export interface CommercePosCustomer {
17
- id: string
18
- label: string
19
- email: string
20
- }
21
-
22
16
  export interface CommercePosCheckoutLine {
23
17
  productId: number
24
18
  quantity: number
@@ -142,26 +136,6 @@ export function normalizeCommercePosProduct(record: CommerceProductRecord): Comm
142
136
  }
143
137
  }
144
138
 
145
- export function normalizeCommercePosCustomer(record: any): CommercePosCustomer {
146
- const id = identifier(value(record, 'id'), 'Customer')
147
- const source = `Customer ${id}`
148
- const name = requiredText(value(record, 'name'), source, 'name')
149
- const email = requiredText(value(record, 'email'), source, 'email')
150
- return {
151
- id,
152
- label: name,
153
- email,
154
- }
155
- }
156
-
157
- export function isCommercePosCustomerActive(record: any): boolean {
158
- const id = identifier(value(record, 'id'), 'Customer')
159
- const status = requiredText(value(record, 'status'), `Customer ${id}`, 'status')
160
- if (status !== 'Active' && status !== 'Inactive')
161
- throw recordError(`Customer ${id}`, 'status', 'Active or Inactive')
162
- return status === 'Active'
163
- }
164
-
165
139
  export function parseCommercePosLines(input: unknown): CommercePosLineInputResult {
166
140
  if (!Array.isArray(input) || input.length === 0)
167
141
  return { lines: [], error: 'Add at least one product before checkout.' }
@@ -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
+ })