@stacksjs/defaults 0.75.529 → 0.75.537

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 (248) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-build/SKILL.md +1 -1
  3. package/ai/skills/stacks-dashboard/SKILL.md +2 -2
  4. package/ai/skills/stacks-database/SKILL.md +1 -1
  5. package/ai/skills/stacks-migrations/SKILL.md +2 -2
  6. package/ai/skills/stacks-native/CATALOG.md +6 -6
  7. package/app/Actions/Dashboard/Commerce/CommerceCouponsAction.ts +27 -15
  8. package/app/Actions/Dashboard/Commerce/CommerceCouponsExportAction.ts +45 -0
  9. package/app/Actions/Dashboard/Commerce/CommerceCustomersAction.ts +22 -12
  10. package/app/Actions/Dashboard/Commerce/CommerceCustomersExportAction.ts +44 -0
  11. package/app/Actions/Dashboard/Commerce/CommercePosCheckoutAction.ts +9 -29
  12. package/app/Actions/Dashboard/Commerce/CommercePrintDevicesAction.ts +7 -9
  13. package/app/Actions/Dashboard/Commerce/CommerceProductDetailAction.ts +9 -8
  14. package/app/Actions/Dashboard/Commerce/CommerceTaxesAction.ts +7 -9
  15. package/app/Actions/Dashboard/Commerce/ManufacturerIndexAction.ts +8 -20
  16. package/app/Actions/Dashboard/Commerce/commerce-coupon-list.test.ts +203 -0
  17. package/app/Actions/Dashboard/Commerce/commerce-coupon-list.ts +248 -0
  18. package/app/Actions/Dashboard/Commerce/commerce-customer-list.test.ts +183 -0
  19. package/app/Actions/Dashboard/Commerce/commerce-customer-list.ts +186 -0
  20. package/app/Actions/Dashboard/Commerce/commerce-customer-records.test.ts +1 -34
  21. package/app/Actions/Dashboard/Commerce/commerce-customer-records.ts +0 -11
  22. package/app/Actions/Dashboard/Commerce/commerce-manufacturer-list.test.ts +118 -0
  23. package/app/Actions/Dashboard/Commerce/commerce-manufacturer-list.ts +41 -0
  24. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +17 -5
  25. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +17 -3
  26. package/app/Actions/Dashboard/Commerce/commerce-print-device-list.test.ts +99 -0
  27. package/app/Actions/Dashboard/Commerce/commerce-print-device-list.ts +18 -0
  28. package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +5 -5
  29. package/app/Actions/Dashboard/Commerce/commerce-product-options.test.ts +81 -0
  30. package/app/Actions/Dashboard/Commerce/commerce-tax-rate-list.test.ts +99 -0
  31. package/app/Actions/Dashboard/Commerce/commerce-tax-rate-list.ts +18 -0
  32. package/app/Actions/Dashboard/Commerce/coupon-records.test.ts +1 -16
  33. package/app/Actions/Dashboard/Commerce/coupon-records.ts +6 -10
  34. package/app/Actions/Dashboard/Commerce/manufacturer-records.test.ts +5 -17
  35. package/app/Actions/Dashboard/Commerce/manufacturer-records.ts +0 -29
  36. package/app/Actions/Dashboard/Email/captured-mail.test.ts +16 -0
  37. package/app/Actions/Dashboard/Email/captured-mail.ts +9 -1
  38. package/app/Actions/Dashboard/Models/model-write.ts +36 -3
  39. package/app/Actions/Dashboard/Notifications/NotificationDeliveryHistoryAction.ts +13 -58
  40. package/app/Actions/Dashboard/Notifications/notification-delivery-history.ts +74 -0
  41. package/app/Actions/SitemapAction.ts +3 -1
  42. package/app/Models/Notification.ts +3 -1
  43. package/app/Models/NotificationDelivery.ts +4 -0
  44. package/app/Models/User.ts +10 -1
  45. package/bootstrap.ts +10 -2
  46. package/functions/commerce/tax-types.ts +21 -0
  47. package/functions/dashboard-list.test.ts +16 -0
  48. package/functions/dashboard-list.ts +14 -6
  49. package/functions/dashboard-model-record.test.ts +139 -0
  50. package/functions/dashboard-model-record.ts +353 -0
  51. package/functions/monitoring/errors.ts +22 -103
  52. package/functions/notifications/deliveries.ts +7 -38
  53. package/functions/queries.ts +7 -10
  54. package/ide/vscode/package.json +1 -1
  55. package/package.json +5 -5
  56. package/resources/components/Dashboard/Analytics/AnalyticsHub.stx +2 -2
  57. package/resources/components/Dashboard/Analytics/CampaignAnalytics.stx +22 -28
  58. package/resources/components/Dashboard/Analytics/EventAnalytics.stx +26 -34
  59. package/resources/components/Dashboard/Analytics/SalesAnalytics.stx +29 -37
  60. package/resources/components/Dashboard/Analytics/WebAnalyticsBreakdown.stx +12 -16
  61. package/resources/components/Dashboard/Analytics/WebAnalyticsDashboard.stx +43 -53
  62. package/resources/components/Dashboard/App/RequestsOverview.stx +2 -1
  63. package/resources/components/Dashboard/App/SourceInventory.stx +2 -1
  64. package/resources/components/Dashboard/Auth/AccessTokens.stx +3 -5
  65. package/resources/components/Dashboard/Billing/BillingPaymentMethodsPanel.stx +9 -11
  66. package/resources/components/Dashboard/Billing/BillingSettings.stx +1 -1
  67. package/resources/components/Dashboard/Buddy/BuddyAssistant.stx +4 -6
  68. package/resources/components/Dashboard/Commerce/CommerceCategoriesDashboard.stx +2 -2
  69. package/resources/components/Dashboard/Commerce/CommerceCategoriesTable.stx +3 -3
  70. package/resources/components/Dashboard/Commerce/CommerceCategoryDialog.stx +2 -2
  71. package/resources/components/Dashboard/Commerce/CommerceCategoryHierarchy.stx +3 -5
  72. package/resources/components/Dashboard/Commerce/CommerceCouponBreakdown.stx +17 -13
  73. package/resources/components/Dashboard/Commerce/CommerceCouponDialog.stx +1 -1
  74. package/resources/components/Dashboard/Commerce/CommerceCouponsDashboard.stx +57 -85
  75. package/resources/components/Dashboard/Commerce/CommerceCouponsTable.stx +32 -9
  76. package/resources/components/Dashboard/Commerce/CommerceCustomerDialog.stx +1 -1
  77. package/resources/components/Dashboard/Commerce/CommerceCustomersDashboard.stx +49 -83
  78. package/resources/components/Dashboard/Commerce/CommerceCustomersTable.stx +32 -9
  79. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +9 -15
  80. package/resources/components/Dashboard/Commerce/CommerceGiftCardDialog.stx +1 -1
  81. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +35 -119
  82. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +3 -3
  83. package/resources/components/Dashboard/Commerce/CommerceManufacturerDialog.stx +1 -1
  84. package/resources/components/Dashboard/Commerce/CommerceManufacturersDashboard.stx +3 -5
  85. package/resources/components/Dashboard/Commerce/CommerceManufacturersTable.stx +2 -2
  86. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +4 -4
  87. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +42 -129
  88. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +3 -3
  89. package/resources/components/Dashboard/Commerce/CommerceOverviewDashboard.stx +1 -1
  90. package/resources/components/Dashboard/Commerce/CommerceOverviewOrdersTable.stx +9 -11
  91. package/resources/components/Dashboard/Commerce/CommerceOverviewProductsTable.stx +5 -7
  92. package/resources/components/Dashboard/Commerce/CommerceOverviewStats.stx +14 -16
  93. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -18
  94. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +41 -120
  95. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +1 -1
  96. package/resources/components/Dashboard/Commerce/CommercePosCart.stx +13 -15
  97. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -19
  98. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +2 -2
  99. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +1 -1
  100. package/resources/components/Dashboard/Commerce/CommercePosReceiptDialog.stx +1 -1
  101. package/resources/components/Dashboard/Commerce/CommerceProductDetailDashboard.stx +5 -5
  102. package/resources/components/Dashboard/Commerce/CommerceProductDialog.stx +3 -3
  103. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +41 -122
  104. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +3 -3
  105. package/resources/components/Dashboard/Commerce/CommerceReviewEditDialog.stx +1 -1
  106. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +38 -122
  107. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +2 -2
  108. package/resources/components/Dashboard/Commerce/CommerceTaxDialog.stx +3 -3
  109. package/resources/components/Dashboard/Commerce/CommerceTaxesDashboard.stx +5 -4
  110. package/resources/components/Dashboard/Commerce/CommerceTaxesTable.stx +4 -3
  111. package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +3 -7
  112. package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +3 -5
  113. package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +2 -2
  114. package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +3 -3
  115. package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +4 -4
  116. package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +3 -5
  117. package/resources/components/Dashboard/Commerce/Delivery/CourierDialog.stx +1 -1
  118. package/resources/components/Dashboard/Commerce/Delivery/CouriersDashboard.stx +1 -1
  119. package/resources/components/Dashboard/Commerce/Delivery/CouriersTable.stx +2 -2
  120. package/resources/components/Dashboard/Commerce/Delivery/DeliveryOverviewDashboard.stx +44 -52
  121. package/resources/components/Dashboard/Commerce/Delivery/DeliveryPagination.stx +2 -2
  122. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRouteDialog.stx +1 -1
  123. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +1 -1
  124. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +2 -2
  125. package/resources/components/Dashboard/Commerce/Delivery/DigitalDeliveriesDashboard.stx +1 -1
  126. package/resources/components/Dashboard/Commerce/Delivery/DigitalDeliveryTable.stx +2 -2
  127. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +3 -3
  128. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +1 -1
  129. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +2 -2
  130. package/resources/components/Dashboard/Commerce/Delivery/ShippingMethodsDashboard.stx +1 -1
  131. package/resources/components/Dashboard/Commerce/Delivery/ShippingMethodsTable.stx +2 -2
  132. package/resources/components/Dashboard/Commerce/Delivery/ShippingRateDialog.stx +2 -2
  133. package/resources/components/Dashboard/Commerce/Delivery/ShippingRatesDashboard.stx +1 -1
  134. package/resources/components/Dashboard/Commerce/Delivery/ShippingRatesTable.stx +2 -2
  135. package/resources/components/Dashboard/Commerce/Delivery/ShippingZoneDialog.stx +1 -1
  136. package/resources/components/Dashboard/Commerce/Delivery/ShippingZonesDashboard.stx +1 -1
  137. package/resources/components/Dashboard/Commerce/Delivery/ShippingZonesTable.stx +4 -8
  138. package/resources/components/Dashboard/Commerce/PaymentDetailsDialog.stx +1 -3
  139. package/resources/components/Dashboard/Commerce/PrintDeviceBreakdown.stx +9 -15
  140. package/resources/components/Dashboard/Commerce/PrintDeviceDialog.stx +1 -1
  141. package/resources/components/Dashboard/Commerce/PrintDevicesDashboard.stx +3 -3
  142. package/resources/components/Dashboard/Commerce/PrintDevicesTable.stx +3 -3
  143. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +3 -9
  144. package/resources/components/Dashboard/Commerce/PrintLogDetailsDialog.stx +1 -1
  145. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +4 -4
  146. package/resources/components/Dashboard/Commerce/PrintLogsTable.stx +8 -10
  147. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +37 -109
  148. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +3 -3
  149. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +2 -2
  150. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +38 -112
  151. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +2 -2
  152. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +2 -2
  153. package/resources/components/Dashboard/Content/AuthorsDashboard.stx +4 -4
  154. package/resources/components/Dashboard/Content/BlogDashboard.stx +4 -4
  155. package/resources/components/Dashboard/Content/CommentsDashboard.stx +36 -83
  156. package/resources/components/Dashboard/Content/ContentDashboard.stx +12 -14
  157. package/resources/components/Dashboard/Content/ContentTaxonomyDashboard.stx +2 -2
  158. package/resources/components/Dashboard/Content/FileManagerDashboard.stx +8 -12
  159. package/resources/components/Dashboard/Content/FileStoragePanel.stx +6 -10
  160. package/resources/components/Dashboard/Content/FileUploadDialog.stx +1 -3
  161. package/resources/components/Dashboard/Content/PagesDashboard.stx +39 -78
  162. package/resources/components/Dashboard/Content/PostEditorDialog.stx +4 -8
  163. package/resources/components/Dashboard/Content/PostsDashboard.stx +44 -85
  164. package/resources/components/Dashboard/Content/SeoDashboard.stx +5 -4
  165. package/resources/components/Dashboard/Data/DataRecords.stx +140 -12
  166. package/resources/components/Dashboard/Deployments/DeploymentList.stx +4 -4
  167. package/resources/components/Dashboard/Deployments/DeploymentTable.stx +3 -1
  168. package/resources/components/Dashboard/Elements/DropdownNavigation.stx +5 -7
  169. package/resources/components/Dashboard/Email/CapturedMailDashboard.stx +1 -3
  170. package/resources/components/Dashboard/Email/CapturedMailList.stx +18 -20
  171. package/resources/components/Dashboard/Email/EmailActivityDashboard.stx +24 -28
  172. package/resources/components/Dashboard/Email/EmailSettingsList.stx +6 -8
  173. package/resources/components/Dashboard/Email/EmailSettingsNavigation.stx +10 -12
  174. package/resources/components/Dashboard/Email/EmailSidebar.stx +33 -37
  175. package/resources/components/Dashboard/Email/InboxMessageDetail.stx +1 -1
  176. package/resources/components/Dashboard/Email/InboxMessageList.stx +16 -18
  177. package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +1 -1
  178. package/resources/components/Dashboard/Environment/EnvironmentDashboard.stx +2 -2
  179. package/resources/components/Dashboard/GlobalSearch.stx +19 -21
  180. package/resources/components/Dashboard/Home/DashboardHome.stx +8 -1
  181. package/resources/components/Dashboard/Infrastructure/CloudDashboard.stx +1 -1
  182. package/resources/components/Dashboard/Infrastructure/DnsDashboard.stx +27 -13
  183. package/resources/components/Dashboard/Infrastructure/LogsDashboard.stx +1 -1
  184. package/resources/components/Dashboard/Infrastructure/MailboxesDashboard.stx +46 -8
  185. package/resources/components/Dashboard/Infrastructure/ServerlessDashboard.stx +1 -1
  186. package/resources/components/Dashboard/Infrastructure/ServersDashboard.stx +1 -1
  187. package/resources/components/Dashboard/Jobs/JobDetail.stx +1 -1
  188. package/resources/components/Dashboard/Jobs/JobHistory.stx +44 -57
  189. package/resources/components/Dashboard/Jobs/JobTable.stx +23 -25
  190. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +1 -1
  191. package/resources/components/Dashboard/Library/ComponentsDashboard.stx +1 -1
  192. package/resources/components/Dashboard/Management/AssignmentDrawer.stx +5 -7
  193. package/resources/components/Dashboard/Management/PermissionsDashboard.stx +35 -43
  194. package/resources/components/Dashboard/Marketing/AbandonedCartsDashboard.stx +11 -13
  195. package/resources/components/Dashboard/Marketing/CampaignDialog.stx +1 -3
  196. package/resources/components/Dashboard/Marketing/CampaignsDashboard.stx +2 -2
  197. package/resources/components/Dashboard/Marketing/CampaignsTable.stx +2 -2
  198. package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +1 -1
  199. package/resources/components/Dashboard/Marketing/MarketingListsTable.stx +2 -2
  200. package/resources/components/Dashboard/Marketing/SocialPostDialog.stx +1 -3
  201. package/resources/components/Dashboard/Marketing/SocialPostsDashboard.stx +2 -2
  202. package/resources/components/Dashboard/Marketing/SocialPostsTable.stx +2 -2
  203. package/resources/components/Dashboard/Models/ModelRecordActions.stx +11 -2
  204. package/resources/components/Dashboard/Models/ModelRecordCreate.stx +193 -0
  205. package/resources/components/Dashboard/Models/ModelRecordDetail.stx +144 -0
  206. package/resources/components/Dashboard/Models/ModelRecordEdit.stx +176 -0
  207. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +52 -186
  208. package/resources/components/Dashboard/Models/ModelsOverview.stx +2 -4
  209. package/resources/components/Dashboard/Monitoring/ErrorDashboard.stx +47 -81
  210. package/resources/components/Dashboard/Monitoring/ErrorTable.stx +4 -2
  211. package/resources/components/Dashboard/NotFoundDashboard.stx +4 -4
  212. package/resources/components/Dashboard/Notifications/NotificationDeliveryHistory.stx +43 -77
  213. package/resources/components/Dashboard/Notifications/NotificationDeliveryOverview.stx +15 -17
  214. package/resources/components/Dashboard/Notifications/NotificationDeliveryTable.stx +1 -1
  215. package/resources/components/Dashboard/Operations/AuditDashboard.stx +1 -1
  216. package/resources/components/Dashboard/Operations/ChangeDashboard.stx +1 -1
  217. package/resources/components/Dashboard/Operations/IncidentDashboard.stx +1 -1
  218. package/resources/components/Dashboard/Operations/MigrationDashboard.stx +2 -2
  219. package/resources/components/Dashboard/Operations/RecoveryDashboard.stx +1 -1
  220. package/resources/components/Dashboard/Operations/SchedulerDashboard.stx +1 -1
  221. package/resources/components/Dashboard/Queries/QueryDashboard.stx +60 -86
  222. package/resources/components/Dashboard/Queries/QueryDetail.stx +5 -9
  223. package/resources/components/Dashboard/Realtime/RealtimeDashboard.stx +6 -8
  224. package/resources/components/Dashboard/Remote/RemoteConsole.stx +14 -20
  225. package/resources/components/Dashboard/Settings/AppearanceSettingsDashboard.stx +48 -54
  226. package/resources/components/Dashboard/Settings/MailSettingsDashboard.stx +8 -8
  227. package/resources/components/Dashboard/Settings/SettingsDashboard.stx +43 -47
  228. package/resources/components/Dashboard/Teams/TeamInvitationDashboard.stx +2 -2
  229. package/resources/components/Dashboard/UI/ActivityTable.stx +2 -1
  230. package/resources/components/Dashboard/UI/Button.stx +15 -0
  231. package/resources/components/Dashboard/UI/MetricCards.stx +5 -7
  232. package/resources/components/Dashboard/UI/Pagination.stx +3 -5
  233. package/resources/components/Dashboard/UI/QuickLinks.stx +2 -2
  234. package/resources/components/Dashboard/UI/Select.stx +1 -0
  235. package/resources/components/Dashboard/UI/Table.stx +139 -96
  236. package/resources/components/Dashboard/UI/Tabs.stx +18 -20
  237. package/routes/dashboard-api.ts +2 -0
  238. package/routes/dashboard.ts +246 -253
  239. package/routes/storefront.ts +31 -0
  240. package/stx-components-plugin.ts +12 -1
  241. package/views/dashboard/content/categories/index.stx +1 -1
  242. package/views/dashboard/content/tags/index.stx +1 -1
  243. package/views/dashboard/layouts/default.stx +27 -12
  244. package/views/dashboard/models/[model]/[id]/edit.stx +8 -0
  245. package/views/dashboard/models/[model]/[id].stx +8 -0
  246. package/views/dashboard/models/[model]/create.stx +8 -0
  247. package/resources/components/Dashboard/CreateRecordModal.stx +0 -138
  248. package/resources/components/Dashboard/Models/EditRecordModal.stx +0 -81
@@ -0,0 +1,186 @@
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 type { CommerceCustomerRecord, CommerceCustomerStatus, CommerceCustomerSummary } from './commerce-customer-records'
6
+ import { normalizeCommerceCustomerRecord } from './commerce-customer-records'
7
+ import type { CommerceSqlRunner } from './commerce-sql'
8
+ import { asText, binder, sqlRows } from './commerce-sql'
9
+
10
+ /**
11
+ * One page of customers, searched, filtered, sorted and counted by the
12
+ * database, with the summary of every customer (stacksjs/stacks#3218).
13
+ *
14
+ * The Customers page used to read the first 500 customers by name and do all
15
+ * of that in the browser, so a customer past the 500th could not be found,
16
+ * the cards counted and summed those 500, and "Export filtered" wrote only
17
+ * them.
18
+ */
19
+ export const CUSTOMER_SORTS = ['name', 'email', 'spend', 'last-order', 'status', 'newest', 'created'] as const
20
+ export type CustomerSort = typeof CUSTOMER_SORTS[number]
21
+
22
+ export const CUSTOMER_STATUSES: readonly CommerceCustomerStatus[] = ['Active', 'Inactive']
23
+
24
+ export interface CustomerListQuery {
25
+ search: string
26
+ /** '' for any. */
27
+ status: '' | CommerceCustomerStatus
28
+ sort: CustomerSort
29
+ direction: 'asc' | 'desc'
30
+ page: number
31
+ perPage: number
32
+ }
33
+
34
+ const DESCENDING: readonly CustomerSort[] = ['spend', 'last-order', 'newest', 'created']
35
+
36
+ export function parseCustomerListQuery(read: QueryReader): CustomerListQuery | { error: string } {
37
+ const pageText = queryText(read, 'page')
38
+ const page = pageText === '' ? 1 : Number(pageText)
39
+ if (!Number.isInteger(page) || page < 1)
40
+ return { error: 'page must be a whole number of 1 or more.' }
41
+
42
+ const sizeText = queryText(read, 'per_page')
43
+ const perPage = sizeText === '' ? 25 : Number(sizeText)
44
+ if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
45
+ return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
46
+
47
+ const sort = queryText(read, 'sort') || 'name'
48
+ if (!(CUSTOMER_SORTS as readonly string[]).includes(sort))
49
+ return { error: `sort must be one of ${CUSTOMER_SORTS.join(', ')}.` }
50
+
51
+ const directionText = queryText(read, 'direction').toLowerCase()
52
+ const direction = directionText === '' ? (DESCENDING.includes(sort as CustomerSort) ? 'desc' : 'asc') : directionText
53
+ if (direction !== 'asc' && direction !== 'desc')
54
+ return { error: 'direction must be asc or desc.' }
55
+
56
+ const search = queryText(read, 'q')
57
+ if (search.length > 200)
58
+ return { error: 'q must be 200 characters or fewer.' }
59
+
60
+ const status = queryText(read, 'status')
61
+ if (status && !(CUSTOMER_STATUSES as readonly string[]).includes(status))
62
+ return { error: `status must be one of ${CUSTOMER_STATUSES.join(', ')}.` }
63
+
64
+ return { search, status: status as CustomerListQuery['status'], sort: sort as CustomerSort, direction, page, perPage }
65
+ }
66
+
67
+ function sortExpression(sort: CustomerSort, dialect: QueryBuilderDialect): string {
68
+ switch (sort) {
69
+ case 'email': return 'LOWER(email)'
70
+ case 'spend': return 'total_spent'
71
+ // Text, as the importer that moves it forward compares it.
72
+ case 'last-order': return `COALESCE(last_order, '')`
73
+ case 'status': return asText('status', dialect)
74
+ case 'newest': return 'id'
75
+ case 'created': return 'created_at'
76
+ default: return 'LOWER(name)'
77
+ }
78
+ }
79
+
80
+ export function customerFilter(query: Pick<CustomerListQuery, 'search' | 'status'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
81
+ const { bind, values } = binder(dialect)
82
+ const clauses: string[] = []
83
+ if (query.status)
84
+ // A text comparison: PostgreSQL keeps the status as an enum.
85
+ clauses.push(`${asText('status', dialect)} = ${bind(query.status)}`)
86
+ if (query.search) {
87
+ const pattern = containsPattern(query.search)
88
+ const columns = ['name', 'email', `COALESCE(phone, '')`]
89
+ clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
90
+ }
91
+ return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
92
+ }
93
+
94
+ function orderBy(query: Pick<CustomerListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
95
+ const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
96
+ if (query.sort === 'newest')
97
+ return ` ORDER BY id ${direction}`
98
+ // Customers who never ordered come last either way, as the page put them.
99
+ const unordered = query.sort === 'last-order' ? `CASE WHEN last_order IS NULL OR last_order = '' THEN 1 ELSE 0 END ASC, ` : ''
100
+ // Ties read by name, as the page sorted them; the id breaks every
101
+ // remaining tie, so pages never repeat or skip a customer.
102
+ const byName = query.sort === 'name' ? '' : ', LOWER(name) ASC'
103
+ return ` ORDER BY ${unordered}${sortExpression(query.sort, dialect)} ${direction}${byName}, id ${direction}`
104
+ }
105
+
106
+ /** The summary cards, over every customer as before. */
107
+ async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<CommerceCustomerSummary> {
108
+ const status = asText('status', dialect)
109
+ const row = sqlRows(await run.unsafe(
110
+ `SELECT COUNT(*) AS total_count, SUM(CASE WHEN ${status} = 'Active' THEN 1 ELSE 0 END) AS active_count, SUM(CASE WHEN ${status} = 'Inactive' THEN 1 ELSE 0 END) AS inactive_count, SUM(total_spent) AS spent_total FROM customers`,
111
+ ).execute())[0] ?? {}
112
+ const total = countOf(row.total_count)
113
+ const totalSpent = countOf(row.spent_total)
114
+ return {
115
+ total,
116
+ active: countOf(row.active_count),
117
+ inactive: countOf(row.inactive_count),
118
+ totalSpent,
119
+ averageSpent: total > 0 ? totalSpent / total : 0,
120
+ }
121
+ }
122
+
123
+ export interface CustomerPage {
124
+ records: CommerceCustomerRecord[]
125
+ total: number
126
+ page: number
127
+ summary: CommerceCustomerSummary
128
+ }
129
+
130
+ export async function readCustomerPage(
131
+ query: CustomerListQuery,
132
+ run: CommerceSqlRunner = db,
133
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
134
+ ): Promise<CustomerPage> {
135
+ const { where, values } = customerFilter(query, dialect)
136
+ const [counted, summary] = await Promise.all([
137
+ run.unsafe(`SELECT COUNT(*) AS total_count FROM customers${where}`, values).execute(),
138
+ summarize(run, dialect),
139
+ ])
140
+ const total = countOf(sqlRows(counted)[0]?.total_count)
141
+ const page = pageWithin(query.page, total, query.perPage)
142
+ const customers = await run.unsafe(
143
+ `SELECT * FROM customers${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
144
+ values,
145
+ ).execute()
146
+ return { records: sqlRows(customers).map(normalizeCommerceCustomerRecord), total, page, summary }
147
+ }
148
+
149
+ /** Every customer matching the query, in its order, for the CSV export, a batch at a time. */
150
+ export async function readCustomersForExport(
151
+ query: Omit<CustomerListQuery, 'page' | 'perPage'>,
152
+ run: CommerceSqlRunner = db,
153
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
154
+ batchSize: number = 500,
155
+ ): Promise<CommerceCustomerRecord[]> {
156
+ const { where, values } = customerFilter(query, dialect)
157
+ const records: CommerceCustomerRecord[] = []
158
+ for (let offset = 0; ; offset += batchSize) {
159
+ const batch = sqlRows(await run.unsafe(
160
+ `SELECT * FROM customers${where}${orderBy(query, dialect)} LIMIT ${batchSize} OFFSET ${offset}`,
161
+ values,
162
+ ).execute())
163
+ records.push(...batch.map(normalizeCommerceCustomerRecord))
164
+ if (batch.length < batchSize)
165
+ return records
166
+ }
167
+ }
168
+
169
+ /** A byte order mark, so spreadsheet apps read the file as UTF-8. */
170
+ const BOM = String.fromCharCode(0xFEFF)
171
+
172
+ /** The CSV "Export filtered" downloads: the page's columns, for every matching customer. */
173
+ export function customersCsv(records: CommerceCustomerRecord[], currency: string, minor: (amount: number, currency: string) => string): string {
174
+ const escape = (value: string): string => `"${value.replaceAll('"', '""')}"`
175
+ const header = ['Name', 'Email', 'Phone', 'Status', `Total spent (${currency})`, 'Last order', 'Avatar URL']
176
+ const lines = records.map(record => [
177
+ record.name,
178
+ record.email,
179
+ record.phone,
180
+ record.status,
181
+ minor(record.totalSpent, currency),
182
+ record.lastOrder,
183
+ record.avatar,
184
+ ])
185
+ return `${BOM}${[header, ...lines].map(row => row.map(escape).join(',')).join('\n')}`
186
+ }
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from 'bun:test'
2
- import { normalizeCommerceCustomerRecord, summarizeCommerceCustomers } from './commerce-customer-records'
2
+ import { normalizeCommerceCustomerRecord } from './commerce-customer-records'
3
3
 
4
4
  describe('dashboard commerce customer records', () => {
5
5
  test('normalizes persisted model columns without inventing contact data', () => {
@@ -36,37 +36,4 @@ describe('dashboard commerce customer records', () => {
36
36
  createdAt: '2026-07-29 12:00:00',
37
37
  })).toThrow('Customer 9.status must be Active or Inactive')
38
38
  })
39
-
40
- test('summarizes persisted status and spend values', () => {
41
- const records = [
42
- normalizeCommerceCustomerRecord({
43
- id: 1,
44
- name: 'Active customer',
45
- email: 'active@example.test',
46
- phone: '+1 555 010 1111',
47
- totalSpent: 100,
48
- status: 'Active',
49
- avatar: 'https://example.test/active.jpg',
50
- createdAt: '2026-07-29 12:00:00',
51
- }),
52
- normalizeCommerceCustomerRecord({
53
- id: 2,
54
- name: 'Inactive customer',
55
- email: 'inactive@example.test',
56
- phone: '+1 555 010 2222',
57
- totalSpent: 50,
58
- status: 'Inactive',
59
- avatar: 'https://example.test/inactive.jpg',
60
- createdAt: '2026-07-29 12:00:00',
61
- }),
62
- ]
63
-
64
- expect(summarizeCommerceCustomers(records)).toEqual({
65
- total: 2,
66
- active: 1,
67
- inactive: 1,
68
- totalSpent: 150,
69
- averageSpent: 75,
70
- })
71
- })
72
39
  })
@@ -53,14 +53,3 @@ export function normalizeCommerceCustomerRecord(record: any): CommerceCustomerRe
53
53
  export function normalizeCommerceCustomerCurrency(input: unknown): string {
54
54
  return commerceCurrency(input, 'Commerce configuration')
55
55
  }
56
-
57
- export function summarizeCommerceCustomers(records: CommerceCustomerRecord[]): CommerceCustomerSummary {
58
- const totalSpent = records.reduce((sum, record) => sum + record.totalSpent, 0)
59
- return {
60
- total: records.length,
61
- active: records.filter(record => record.status === 'Active').length,
62
- inactive: records.filter(record => record.status === 'Inactive').length,
63
- totalSpent,
64
- averageSpent: records.length > 0 ? totalSpent / records.length : 0,
65
- }
66
- }
@@ -0,0 +1,118 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { SQL } from 'bun'
3
+ import { describe, expect, test } from 'bun:test'
4
+ import { readManufacturers } from './commerce-manufacturer-list'
5
+ import type { CommerceSqlRunner } from './commerce-sql'
6
+
7
+ /**
8
+ * The manufacturers against each dialect's real engine (stacksjs/stacks#3218),
9
+ * over 520 manufacturers and 1,200 products: the page used to read the newest
10
+ * 500 manufacturers and count over the first 500 products.
11
+ */
12
+ type Dialect = 'sqlite' | 'postgres' | 'mysql'
13
+ type Run = (sql: string, values?: unknown[]) => Promise<unknown>
14
+
15
+ const MANUFACTURERS = Array.from({ length: 520 }, (_, index) => {
16
+ const id = index + 1
17
+ return { id, name: `Maker ${String(id).padStart(3, '0')}`, country: `Country ${id % 7}`, featured: id % 5 === 0 }
18
+ })
19
+
20
+ /** Every fourth product has no manufacturer; the rest spread over all 520, the oldest included. */
21
+ const PRODUCTS = Array.from({ length: 1200 }, (_, index) => {
22
+ const id = index + 1
23
+ return { id, manufacturerId: id % 4 === 0 ? null : ((id * 7) % 520) + 1 }
24
+ })
25
+
26
+ function placeholders(rows: number, columns: number, dialect: Dialect): string {
27
+ const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
28
+ return Array.from({ length: rows }, (_, row) => `(${Array.from({ length: columns }, (_, column) => p(row * columns + column + 1)).join(', ')})`).join(', ')
29
+ }
30
+
31
+ async function setUp(run: Run, dialect: Dialect) {
32
+ const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
33
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
34
+ const bool = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
35
+ const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
36
+ await run(`CREATE TABLE manufacturers (id ${pk}, manufacturer ${text}, description ${text} NULL, country ${text}, featured ${bool}, created_at ${time})`)
37
+ await run(`CREATE TABLE products (id ${pk}, name ${text}, manufacturer_id INTEGER NULL)`)
38
+ await run(
39
+ `INSERT INTO manufacturers (id, manufacturer, country, featured, created_at) VALUES ${placeholders(MANUFACTURERS.length, 5, dialect)}`,
40
+ MANUFACTURERS.flatMap(maker => [maker.id, maker.name, maker.country, dialect === 'postgres' ? maker.featured : (maker.featured ? 1 : 0), '2026-11-01 09:00:00']),
41
+ )
42
+ await run(
43
+ `INSERT INTO products (id, name, manufacturer_id) VALUES ${placeholders(PRODUCTS.length, 3, dialect)}`,
44
+ PRODUCTS.flatMap(product => [product.id, `Product ${product.id}`, product.manufacturerId]),
45
+ )
46
+ }
47
+
48
+ async function exercise(runner: CommerceSqlRunner, run: Run, dialect: Dialect) {
49
+ const { records, summary } = await readManufacturers(runner)
50
+
51
+ // Every manufacturer, newest first, the oldest included.
52
+ expect(records.map(record => record.id)).toEqual(MANUFACTURERS.map(maker => String(maker.id)).reverse())
53
+ expect(records.at(-1)).toMatchObject({ id: '1', name: 'Maker 001', country: 'Country 1', featured: false })
54
+
55
+ // Each count is over every product, not the first 500.
56
+ const expected = new Map<string, number>()
57
+ for (const product of PRODUCTS) {
58
+ if (product.manufacturerId)
59
+ expected.set(String(product.manufacturerId), (expected.get(String(product.manufacturerId)) ?? 0) + 1)
60
+ }
61
+ expect(Object.fromEntries(records.map(record => [record.id, record.productCount])))
62
+ .toEqual(Object.fromEntries(MANUFACTURERS.map(maker => [String(maker.id), expected.get(String(maker.id)) ?? 0])))
63
+ // A product past the 500th counts for its manufacturer.
64
+ const late = PRODUCTS.find(product => product.id > 500 && product.manufacturerId)!
65
+ expect(records.find(record => record.id === String(late.manufacturerId))!.productCount).toBeGreaterThan(0)
66
+
67
+ expect(summary).toEqual({
68
+ total: 520,
69
+ featured: MANUFACTURERS.filter(maker => maker.featured).length,
70
+ countries: 7,
71
+ linkedProducts: PRODUCTS.filter(product => product.manufacturerId).length,
72
+ })
73
+
74
+ // A product naming a manufacturer that does not exist still fails the page,
75
+ // named by the first such product, wherever it is.
76
+ const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
77
+ await run(`INSERT INTO products (id, name, manufacturer_id) VALUES (${p(1)}, ${p(2)}, ${p(3)}), (${p(4)}, ${p(5)}, ${p(6)})`, [1300, 'Orphan B', 999, 1250, 'Orphan A', 999])
78
+ await expect(readManufacturers(runner)).rejects.toThrow('Product 1250.manufacturer_id references missing Manufacturer 999.')
79
+ }
80
+
81
+ describe('readManufacturers on SQLite', () => {
82
+ test('every manufacturer, with products counted over every product', async () => {
83
+ const database = new Database(':memory:')
84
+ const run: Run = async (sql, values = []) => database.query(sql).run(...(values as never[]))
85
+ await setUp(run, 'sqlite')
86
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, run, 'sqlite')
87
+ })
88
+ })
89
+
90
+ for (const dialect of ['postgres', 'mysql'] as const) {
91
+ const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
92
+
93
+ test.skipIf(!connection)(`readManufacturers on ${dialect}: every manufacturer, with products counted over every product`, async () => {
94
+ const url = new URL(connection!)
95
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
96
+ throw new Error('Manufacturer list tests require a local disposable database server')
97
+
98
+ const name = `stacks_manufacturers_${crypto.randomUUID().replaceAll('-', '')}`
99
+ const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
100
+ const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
101
+ await admin.unsafe(`CREATE DATABASE ${quoted}`)
102
+ const scoped = new URL(url.href)
103
+ scoped.pathname = `/${name}`
104
+ // Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
105
+ const database = new SQL({ url: scoped.href, database: name })
106
+
107
+ try {
108
+ const run: Run = async (sql, values = []) => await database.unsafe(sql, values)
109
+ await setUp(run, dialect)
110
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, run, dialect)
111
+ }
112
+ finally {
113
+ await database.close()
114
+ try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
115
+ finally { await admin.close() }
116
+ }
117
+ }, 60_000)
118
+ }
@@ -0,0 +1,41 @@
1
+ import type { CommerceSqlRunner } from './commerce-sql'
2
+ import { db } from '@stacksjs/database/runtime'
3
+ import { countOf } from '../Content/content-list'
4
+ import { commerceIdentifier, commerceValue } from './commerce-record'
5
+ import { sqlRows } from './commerce-sql'
6
+ import type { ManufacturerRecord, ManufacturerSummary } from './manufacturer-records'
7
+ import { normalizeManufacturerRecord, summarizeManufacturers } from './manufacturer-records'
8
+
9
+ /**
10
+ * Every manufacturer, newest first, with how many products each one makes
11
+ * (stacksjs/stacks#3218).
12
+ *
13
+ * Manufacturers are reference data, read whole here as the Products page
14
+ * already reads them for its filter and dialog. The page used to read the
15
+ * newest 500, and count products over the first 500 products by id, so an
16
+ * older manufacturer was missing, every count stopped at those 500 products,
17
+ * and a product among them that named a manufacturer past the 500th failed
18
+ * the whole page with "references missing Manufacturer".
19
+ *
20
+ * The products are counted by the database, every one of them. A product
21
+ * whose manufacturer does not exist still fails the page, as before, now
22
+ * whichever product it is.
23
+ */
24
+ export async function readManufacturers(run: CommerceSqlRunner = db): Promise<{ records: ManufacturerRecord[], summary: ManufacturerSummary }> {
25
+ const [manufacturers, linked] = await Promise.all([
26
+ run.unsafe('SELECT * FROM manufacturers ORDER BY id DESC').execute(),
27
+ run.unsafe('SELECT manufacturer_id, COUNT(*) AS product_count, MIN(id) AS first_product_id FROM products WHERE manufacturer_id IS NOT NULL GROUP BY manufacturer_id').execute(),
28
+ ])
29
+ const rows = sqlRows(manufacturers)
30
+ const ids = new Set(rows.map(row => commerceIdentifier(commerceValue(row, 'id'), 'Manufacturer')))
31
+ const counts = new Map<string, number>()
32
+ for (const group of sqlRows(linked)) {
33
+ const product = commerceIdentifier(commerceValue(group, 'first_product_id'), 'Product')
34
+ const id = commerceIdentifier(commerceValue(group, 'manufacturer_id'), `Product ${product}`, 'manufacturer_id')
35
+ if (!ids.has(id))
36
+ throw new TypeError(`Product ${product}.manufacturer_id references missing Manufacturer ${id}.`)
37
+ counts.set(id, countOf(group.product_count))
38
+ }
39
+ const records = rows.map(row => normalizeManufacturerRecord(row, counts))
40
+ return { records, summary: summarizeManufacturers(records) }
41
+ }
@@ -3,7 +3,7 @@ import { SQL } from 'bun'
3
3
  import { describe, expect, test } from 'bun:test'
4
4
  import { searchCustomerChoices } from './commerce-choices'
5
5
  import type { PosCatalogQuery } from './commerce-pos-catalog'
6
- import { parsePosCatalogQuery, parsePosIds, readPosCatalogPage, readPosProducts, readPosSettings } from './commerce-pos-catalog'
6
+ import { parsePosCatalogQuery, parsePosIds, readPosCatalogPage, readPosProducts, readPosSettings, readPosTaxRate } from './commerce-pos-catalog'
7
7
  import type { CommerceSqlRunner } from './commerce-sql'
8
8
 
9
9
  /**
@@ -71,8 +71,16 @@ async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>,
71
71
  PRODUCTS.flatMap(product => [product.id, product.name, `item-${product.id}`, 100 + product.id, flag(product.available), product.inventory, 5, '[]', product.category, product.manufacturer, '2026-11-01 09:00:00']),
72
72
  )
73
73
  await run(`INSERT INTO customers (id, name, email, phone, status) VALUES ${rows(ROWS, 5)}`, all.flatMap(id => [id, id === 515 ? 'Quinn Late' : `Customer ${pad(id)}`, `buyer${id}@shop.test`, null, id % 2 === 1 ? 'Active' : 'Inactive']))
74
- // The default active rate wins over an earlier active one and an inactive default.
75
- await run(`INSERT INTO tax_rates (id, rate, status, is_default) VALUES ${rows(3, 4)}`, [1, 5, 'inactive', flag(true), 2, 7, 'active', flag(false), 3, 9, 'active', flag(true)])
74
+ // The default active rate wins over earlier active ones and an inactive
75
+ // default, though it is the last of 520: the checkout used to choose among
76
+ // the first 500 by id, and would have charged 7 where the screen showed 11.
77
+ const rates = all.map(id => id === 1
78
+ ? [1, 5, 'inactive', flag(true)]
79
+ : id === 2 ? [2, 7, 'active', flag(false)]
80
+ : id === 3 ? [3, 9, 'active', flag(false)]
81
+ : id === ROWS ? [id, 11, 'active', flag(true)]
82
+ : [id, 3, 'inactive', flag(false)])
83
+ await run(`INSERT INTO tax_rates (id, rate, status, is_default) VALUES ${rows(ROWS, 4)}`, rates.flat())
76
84
  }
77
85
 
78
86
  async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
@@ -82,7 +90,8 @@ async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
82
90
 
83
91
  // Settings, counted over every product.
84
92
  const settings = await readPosSettings(runner, dialect)
85
- expect(settings.taxRate).toBe(9)
93
+ expect(settings.taxRate).toBe(11)
94
+ expect(await readPosTaxRate(runner, dialect)).toBe(11)
86
95
  expect(settings.summary).toEqual({
87
96
  products: ROWS,
88
97
  sellable: PRODUCTS.filter(sellable).length,
@@ -106,7 +115,10 @@ async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
106
115
  expect(last).toMatchObject({ name: 'item 520', categoryId: '515', categoryName: 'Category 515' })
107
116
 
108
117
  // The cart's own products, whatever page the catalogue shows; a deleted one is absent.
109
- expect((await readPosProducts([520, 3, 99_999], runner, dialect)).map(product => product.id).sort()).toEqual(['3', '520'])
118
+ const cart = await readPosProducts([520, 3, 99_999], runner, dialect)
119
+ expect(cart.map(product => product.id).sort()).toEqual(['3', '520'])
120
+ // The checkout prices these, named by a category past the 500th.
121
+ expect(cart.find(product => product.id === '520')).toMatchObject({ categoryName: 'Category 515' })
110
122
 
111
123
  // The checkout's customers: Active only, and found past the 500th.
112
124
  const active = await searchCustomerChoices({ search: '', limit: 5 }, runner, dialect, { activeOnly: true })
@@ -122,6 +122,20 @@ export async function readPosProducts(
122
122
  return posProducts(sqlRows(rows), run, dialect)
123
123
  }
124
124
 
125
+ /**
126
+ * The rate a sale is taxed at: the default active tax rate, else the first
127
+ * active one by id, else 0. The point of sale shows it and the checkout
128
+ * charges it, so both read it here; the checkout used to choose among the
129
+ * first 500 rates by id, so the two could disagree.
130
+ */
131
+ export async function readPosTaxRate(
132
+ run: CommerceSqlRunner = db,
133
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
134
+ ): Promise<number> {
135
+ const rows = await 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()
136
+ return selectCommercePosTaxRate(sqlRows(rows))
137
+ }
138
+
125
139
  export interface PosSettings {
126
140
  /** The categories some product is in, by name ignoring case. */
127
141
  categories: ProductOption[]
@@ -134,15 +148,15 @@ export async function readPosSettings(
134
148
  run: CommerceSqlRunner = db,
135
149
  dialect: QueryBuilderDialect = getDatabaseDialect(),
136
150
  ): Promise<PosSettings> {
137
- const [categories, taxRates, totals] = await Promise.all([
151
+ const [categories, taxRate, totals] = await Promise.all([
138
152
  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(),
153
+ readPosTaxRate(run, dialect),
140
154
  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
155
  ])
142
156
  const row = sqlRows(totals)[0] ?? {}
143
157
  return {
144
158
  categories: sqlRows(categories).map(normalizeProductOption),
145
- taxRate: selectCommercePosTaxRate(sqlRows(taxRates)),
159
+ taxRate,
146
160
  summary: {
147
161
  products: countOf(row.product_count),
148
162
  sellable: countOf(row.sellable_count),
@@ -0,0 +1,99 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { SQL } from 'bun'
3
+ import { describe, expect, test } from 'bun:test'
4
+ import { readPrintDevices } from './commerce-print-device-list'
5
+ import type { CommerceSqlRunner } from './commerce-sql'
6
+
7
+ /**
8
+ * The print devices against each dialect's real engine
9
+ * (stacksjs/stacks#3218), over 520 of them: the page used to read the newest
10
+ * 500.
11
+ */
12
+ type Dialect = 'sqlite' | 'postgres' | 'mysql'
13
+
14
+ const ROWS = 520
15
+ const STATUSES = ['online', 'offline', 'warning'] as const
16
+
17
+ /** 40 locations, the oldest device's among them only once. */
18
+ const DEVICES = Array.from({ length: ROWS }, (_, index) => {
19
+ const id = index + 1
20
+ return {
21
+ id,
22
+ name: `Printer ${id}`,
23
+ mac: `00:1B:44:11:${String(Math.floor(id / 256)).padStart(2, '0')}:${(id % 256).toString(16).padStart(2, '0')}`,
24
+ location: id === 1 ? 'Basement' : `Floor ${id % 39}`,
25
+ terminal: `T${id % 7}`,
26
+ status: STATUSES[id % 3]!,
27
+ prints: id * 3,
28
+ }
29
+ })
30
+
31
+ async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
32
+ const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
33
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
34
+ const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
35
+ const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
36
+ const columns = 9
37
+ await run(`CREATE TABLE print_devices (id ${pk}, name ${text}, mac_address ${text}, location ${text}, terminal ${text}, status ${text}, last_ping ${time}, print_count INTEGER, created_at ${time})`)
38
+ await run(
39
+ `INSERT INTO print_devices (id, name, mac_address, location, terminal, status, last_ping, print_count, created_at) VALUES ${DEVICES.map((_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')}`,
40
+ DEVICES.flatMap(device => [
41
+ device.id, device.name, device.mac, device.location, device.terminal, device.status,
42
+ '2026-11-08 10:00:00', device.prints, '2026-11-01 09:00:00',
43
+ ]),
44
+ )
45
+ }
46
+
47
+ async function exercise(runner: CommerceSqlRunner) {
48
+ const { records, summary } = await readPrintDevices(runner)
49
+
50
+ // Every device, newest first, the oldest included.
51
+ expect(records.map(record => record.id)).toEqual(DEVICES.map(device => String(device.id)).reverse())
52
+ expect(records.at(-1)).toMatchObject({ id: '1', name: 'Printer 1', location: 'Basement', terminal: 'T1', status: 'offline', printCount: 3 })
53
+
54
+ expect(summary).toEqual({
55
+ total: ROWS,
56
+ online: DEVICES.filter(device => device.status === 'online').length,
57
+ offline: DEVICES.filter(device => device.status === 'offline').length,
58
+ warning: DEVICES.filter(device => device.status === 'warning').length,
59
+ locations: 40,
60
+ totalPrints: DEVICES.reduce((sum, device) => sum + device.prints, 0),
61
+ })
62
+ }
63
+
64
+ describe('readPrintDevices on SQLite', () => {
65
+ test('every print device, newest first, with the summary of all of them', async () => {
66
+ const database = new Database(':memory:')
67
+ await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
68
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) })
69
+ })
70
+ })
71
+
72
+ for (const dialect of ['postgres', 'mysql'] as const) {
73
+ const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
74
+
75
+ test.skipIf(!connection)(`readPrintDevices on ${dialect}: every print device, newest first, with the summary of all of them`, async () => {
76
+ const url = new URL(connection!)
77
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
78
+ throw new Error('Print device list tests require a local disposable database server')
79
+
80
+ const name = `stacks_print_devices_${crypto.randomUUID().replaceAll('-', '')}`
81
+ const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
82
+ const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
83
+ await admin.unsafe(`CREATE DATABASE ${quoted}`)
84
+ const scoped = new URL(url.href)
85
+ scoped.pathname = `/${name}`
86
+ // Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
87
+ const database = new SQL({ url: scoped.href, database: name })
88
+
89
+ try {
90
+ await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
91
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) })
92
+ }
93
+ finally {
94
+ await database.close()
95
+ try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
96
+ finally { await admin.close() }
97
+ }
98
+ }, 60_000)
99
+ }
@@ -0,0 +1,18 @@
1
+ import type { CommerceSqlRunner } from './commerce-sql'
2
+ import { db } from '@stacksjs/database/runtime'
3
+ import { sqlRows } from './commerce-sql'
4
+ import type { PrintDeviceRecord, PrintDeviceSummary } from './print-device-records'
5
+ import { normalizePrintDeviceRecord, summarizePrintDevices } from './print-device-records'
6
+
7
+ /**
8
+ * Every print device, newest first (stacksjs/stacks#3218).
9
+ *
10
+ * Print devices are the store's own hardware, configuration the page needs
11
+ * whole: it offers their locations as a filter and totals their prints. It
12
+ * used to read the newest 500, so an older device could not be found or
13
+ * edited, and the cards and the location filter saw only those 500.
14
+ */
15
+ export async function readPrintDevices(run: CommerceSqlRunner = db): Promise<{ records: PrintDeviceRecord[], summary: PrintDeviceSummary }> {
16
+ const records = sqlRows(await run.unsafe('SELECT * FROM print_devices ORDER BY id DESC').execute()).map(normalizePrintDeviceRecord)
17
+ return { records, summary: summarizePrintDevices(records) }
18
+ }
@@ -185,11 +185,11 @@ async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect):
185
185
  }
186
186
 
187
187
  /**
188
- * Every category and manufacturer, for the filter and the product dialog.
189
- * These are small reference tables, so they are read whole rather than the
190
- * first 500 of each.
188
+ * Every category and manufacturer, for the filter and the product dialog, here
189
+ * and on the product's own page. These are small reference tables, so they
190
+ * are read whole rather than the first 500 of each.
191
191
  */
192
- async function options(run: CommerceSqlRunner): Promise<{ categories: ProductOption[], manufacturers: ProductOption[] }> {
192
+ export async function readProductOptions(run: CommerceSqlRunner = db): Promise<{ categories: ProductOption[], manufacturers: ProductOption[] }> {
193
193
  const [categories, manufacturers] = await Promise.all([
194
194
  // LOWER, so the order is the same on every dialect: each collates case its own way.
195
195
  run.unsafe('SELECT id, name FROM categories ORDER BY LOWER(name) ASC, id ASC').execute(),
@@ -219,7 +219,7 @@ export async function readProductPage(
219
219
  const [counted, summary, choices] = await Promise.all([
220
220
  run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
221
221
  summarize(run, dialect),
222
- options(run),
222
+ readProductOptions(run),
223
223
  ])
224
224
  const total = countOf(sqlRows(counted)[0]?.total_count)
225
225
  const page = pageWithin(query.page, total, query.perPage)