@stacksjs/defaults 0.75.487 → 0.75.490

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +27 -2
  3. package/ai/skills/stacks-native/CATALOG.md +9 -9
  4. package/ai/skills/stacks-search-engine/SKILL.md +14 -0
  5. package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
  6. package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
  7. package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
  8. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
  9. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
  10. package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
  11. package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
  12. package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
  13. package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
  14. package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
  15. package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
  16. package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
  17. package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
  18. package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
  19. package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
  20. package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
  21. package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
  22. package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
  23. package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
  24. package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
  25. package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
  26. package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
  27. package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
  28. package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
  29. package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
  30. package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
  31. package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
  32. package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
  33. package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
  34. package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
  35. package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
  36. package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
  37. package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
  38. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
  39. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
  40. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
  41. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
  42. package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
  43. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
  44. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
  45. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
  46. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
  47. package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
  48. package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
  49. package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
  50. package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
  51. package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
  52. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
  53. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
  54. package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
  55. package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
  56. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
  57. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
  58. package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
  59. package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
  60. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
  61. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
  62. package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
  63. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
  64. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
  65. package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
  66. package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
  67. package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
  68. package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
  69. package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
  70. package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
  71. package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
  72. package/app/Actions/Dashboard/Content/content-list.ts +10 -0
  73. package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
  74. package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
  75. package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
  76. package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
  77. package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
  78. package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
  79. package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
  80. package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
  81. package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
  82. package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
  83. package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
  84. package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
  85. package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
  86. package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
  87. package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +9 -6
  88. package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
  89. package/app/Actions/Dashboard/Queue/queue-stats.ts +10 -0
  90. package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
  91. package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
  92. package/app/Actions/Dashboard/named-search.test.ts +36 -0
  93. package/app/Actions/Dashboard/named-search.ts +80 -0
  94. package/app/Models/QueueWorker.ts +1 -0
  95. package/app/Models/Request.ts +4 -2
  96. package/bootstrap.ts +6 -1
  97. package/functions/commerce/shippings/dashboard-resource.ts +12 -1
  98. package/functions/commerce/shippings/delivery-routes.ts +1 -0
  99. package/functions/commerce/shippings/license-keys.ts +1 -0
  100. package/functions/dashboard-list.test.ts +132 -1
  101. package/functions/dashboard-list.ts +198 -1
  102. package/functions/queue.ts +2 -0
  103. package/ide/vscode/package.json +1 -1
  104. package/package.json +2 -2
  105. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
  106. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
  107. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
  108. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
  109. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
  110. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
  111. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
  112. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
  113. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
  114. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
  115. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
  116. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
  117. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
  118. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
  119. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
  120. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
  121. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
  122. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
  123. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
  124. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
  125. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
  126. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
  127. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
  128. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
  129. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
  130. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
  131. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
  132. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
  133. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
  134. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
  135. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
  136. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
  137. package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
  138. package/resources/components/Dashboard/Queue/QueueDashboard.stx +8 -2
  139. package/resources/functions/dashboard/sidebar.ts +26 -1
  140. package/routes/dashboard-api.ts +11 -0
  141. package/views/dashboard/stores/kanban.ts +38 -6
@@ -1,34 +1,35 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
1
2
  import { Action } from '@stacksjs/actions/runtime'
2
- import { Customer, LicenseKey, Order, Product } from '@stacksjs/orm'
3
+ import { response } from '@stacksjs/router'
3
4
  import { dashboardOperationalError } from '../dashboard-response'
4
- import {
5
- indexLicenseKeyOptions,
6
- normalizeLicenseKeyCustomer,
7
- normalizeLicenseKeyOrder,
8
- normalizeLicenseKeyProduct,
9
- normalizeLicenseKeyRecord,
10
- } from './license-key-records'
5
+ import { parseLicenseKeyListQuery, readLicenseKeyPage } from './commerce-license-key-list'
11
6
 
7
+ /**
8
+ * `GET /api/dashboard/commerce/license-keys` - one page of licence keys,
9
+ * searched, sorted and counted by the database, with the summary of every key
10
+ * and each key's customer, product and order (commerce-license-key-list.ts,
11
+ * stacksjs/stacks#3218). It used to return the newest 500 as a bare array.
12
+ */
12
13
  export default new Action({
13
14
  name: 'Dashboard License Keys',
14
- description: 'Returns license keys with lightweight customer, product, and order summaries.',
15
+ description: 'Returns one page of license keys with lightweight customer, product, and order summaries.',
15
16
  method: 'GET',
16
17
  apiResponse: true,
17
- async handle() {
18
+
19
+ async handle(request: RequestInstance) {
20
+ const query = parseLicenseKeyListQuery(key => request.get<unknown>(key, ''))
21
+ if ('error' in query)
22
+ return response.json({ message: query.error }, 422)
23
+
18
24
  try {
19
- const keys = await LicenseKey.orderByDesc('id').limit(500).get()
20
- const customerIds = [...new Set(keys.map(key => key.get('customer_id')).filter(Boolean))]
21
- const productIds = [...new Set(keys.map(key => key.get('product_id')).filter(Boolean))]
22
- const orderIds = [...new Set(keys.map(key => key.get('order_id')).filter(Boolean))]
23
- const [customers, products, orders] = await Promise.all([
24
- customerIds.length ? Customer.whereIn('id', customerIds).get() : [],
25
- productIds.length ? Product.whereIn('id', productIds).get() : [],
26
- orderIds.length ? Order.whereIn('id', orderIds).get() : [],
27
- ])
28
- const customerMap = indexLicenseKeyOptions(customers.map(normalizeLicenseKeyCustomer))
29
- const productMap = indexLicenseKeyOptions(products.map(normalizeLicenseKeyProduct))
30
- const orderMap = indexLicenseKeyOptions(orders.map(normalizeLicenseKeyOrder))
31
- return keys.map(key => normalizeLicenseKeyRecord(key, customerMap, productMap, orderMap))
25
+ const keys = await readLicenseKeyPage(query)
26
+ return {
27
+ records: keys.records,
28
+ total: keys.total,
29
+ page: keys.page,
30
+ perPage: query.perPage,
31
+ summary: keys.summary,
32
+ }
32
33
  }
33
34
  catch (error) {
34
35
  return dashboardOperationalError(error, 'License key records could not be read.', 'LicenseKeyIndexAction')
@@ -1,28 +1,47 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
1
2
  import { Action } from '@stacksjs/actions/runtime'
2
- import { Customer, Order, Product } from '@stacksjs/orm'
3
+ import { response } from '@stacksjs/router'
3
4
  import { dashboardOperationalError } from '../dashboard-response'
4
- import {
5
- normalizeLicenseKeyCustomer,
6
- normalizeLicenseKeyOrder,
7
- normalizeLicenseKeyProduct,
8
- } from './license-key-records'
5
+ import { parseNamedSearchQuery } from '../named-search'
6
+ import type { LicenseKeyChoiceKind } from './commerce-license-key-list'
7
+ import { LICENSE_KEY_CHOICE_KINDS, searchLicenseKeyChoices } from './commerce-license-key-list'
9
8
 
9
+ /**
10
+ * `GET /api/dashboard/commerce/license-key-options` - the customers, products
11
+ * and orders the licence key dialog offers (stacksjs/stacks#3218). It used to
12
+ * send the first 500 of each.
13
+ *
14
+ * With `kind` (customers, products or orders) and `q`, it searches that one
15
+ * and answers `{ choices, total }`, which is what the dialog asks for as each
16
+ * search box is typed in. Without `kind` it answers the first `limit` of each
17
+ * (25 unless asked) as `{ customers, products, orders, totals }`, the shape
18
+ * useLicenseKeys().fetchLicenseKeyOptions reads, with how many there are.
19
+ */
10
20
  export default new Action({
11
21
  name: 'License Key Options',
12
- description: 'Returns lightweight relationship options for license key forms.',
22
+ description: 'Searches the customers, products and orders the licence key dialog offers.',
13
23
  method: 'GET',
14
24
  apiResponse: true,
15
- async handle() {
25
+
26
+ async handle(request: RequestInstance) {
27
+ const query = parseNamedSearchQuery(key => request.get<unknown>(key, ''))
28
+ if ('error' in query)
29
+ return response.json({ message: query.error }, 422)
30
+ const kind = String(request.get<unknown>('kind', '') ?? '').trim()
31
+ if (kind && !(LICENSE_KEY_CHOICE_KINDS as readonly string[]).includes(kind))
32
+ return response.json({ message: `kind must be one of ${LICENSE_KEY_CHOICE_KINDS.join(', ')}.` }, 422)
33
+
16
34
  try {
17
- const [customers, products, orders] = await Promise.all([
18
- Customer.orderBy('name', 'asc').limit(500).get(),
19
- Product.orderBy('name', 'asc').limit(500).get(),
20
- Order.orderByDesc('id').limit(500).get(),
21
- ])
35
+ if (kind)
36
+ return { ...await searchLicenseKeyChoices(kind as LicenseKeyChoiceKind, query), limit: query.limit }
37
+ const [customers, products, orders] = await Promise.all(
38
+ LICENSE_KEY_CHOICE_KINDS.map(each => searchLicenseKeyChoices(each, query)),
39
+ )
22
40
  return {
23
- customers: customers.map(normalizeLicenseKeyCustomer),
24
- products: products.map(normalizeLicenseKeyProduct),
25
- orders: orders.map(normalizeLicenseKeyOrder),
41
+ customers: customers!.choices,
42
+ products: products!.choices,
43
+ orders: orders!.choices,
44
+ totals: { customers: customers!.total, products: products!.total, orders: orders!.total },
26
45
  }
27
46
  }
28
47
  catch (error) {
@@ -1,35 +1,35 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
1
2
  import { Action } from '@stacksjs/actions/runtime'
2
- import { Customer, Product, WaitlistProduct } from '@stacksjs/orm'
3
+ import { response } from '@stacksjs/router'
3
4
  import { dashboardOperationalError } from '../dashboard-response'
4
- import { normalizeProductWaitlistCustomerOption, normalizeProductWaitlistOption, normalizeProductWaitlistRecord, summarizeProductWaitlist } from './product-waitlist-records'
5
+ import { parseProductWaitlistListQuery, readProductWaitlistPage } from './commerce-product-waitlist-list'
5
6
 
7
+ /**
8
+ * `GET /api/dashboard/commerce/waitlist-products` - one page of the product
9
+ * waitlist, searched, filtered, sorted and counted by the database, with the
10
+ * summary of every entry (commerce-product-waitlist-list.ts,
11
+ * stacksjs/stacks#3218). The entry dialog searches its products and customers
12
+ * itself (commerce-choices.ts); this used to send the first 500 of each.
13
+ */
6
14
  export default new Action({
7
15
  name: 'ProductWaitlistIndexAction',
8
- description: 'Returns native product waitlist records for the dashboard.',
16
+ description: 'Returns one page of native product waitlist records for the dashboard.',
9
17
  method: 'GET',
10
18
  apiResponse: true,
11
19
 
12
- async handle() {
20
+ async handle(request: RequestInstance) {
21
+ const query = parseProductWaitlistListQuery(key => request.get<unknown>(key, ''))
22
+ if ('error' in query)
23
+ return response.json({ message: query.error }, 422)
24
+
13
25
  try {
14
- const [rows, products, customers] = await Promise.all([
15
- WaitlistProduct.orderByDesc('id').limit(500).get(),
16
- Product.orderBy('name').limit(500).get(),
17
- Customer.orderBy('name').limit(500).get(),
18
- ])
19
- const productOptions = products.map(normalizeProductWaitlistOption)
20
- const customerOptions = customers.map(normalizeProductWaitlistCustomerOption)
21
- const productIds = new Set(productOptions.map(product => product.id))
22
- const customerIds = new Set(customerOptions.map(customer => customer.id))
23
- const records = rows.map(row =>
24
- normalizeProductWaitlistRecord(row, productIds, customerIds),
25
- )
26
+ const entries = await readProductWaitlistPage(query)
26
27
  return {
27
- records,
28
- summary: summarizeProductWaitlist(records),
29
- options: {
30
- products: productOptions,
31
- customers: customerOptions,
32
- },
28
+ records: entries.records,
29
+ total: entries.total,
30
+ page: entries.page,
31
+ perPage: query.perPage,
32
+ summary: entries.summary,
33
33
  }
34
34
  }
35
35
  catch (error) {
@@ -1,30 +1,35 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
1
2
  import { Action } from '@stacksjs/actions/runtime'
2
- import { Customer, WaitlistRestaurant } from '@stacksjs/orm'
3
+ import { response } from '@stacksjs/router'
3
4
  import { dashboardOperationalError } from '../dashboard-response'
4
- import { normalizeRestaurantWaitlistCustomerOption, normalizeRestaurantWaitlistRecord, summarizeRestaurantWaitlist } from './restaurant-waitlist-records'
5
+ import { parseRestaurantWaitlistListQuery, readRestaurantWaitlistPage } from './commerce-restaurant-waitlist-list'
5
6
 
7
+ /**
8
+ * `GET /api/dashboard/commerce/waitlist-restaurants` - one page of the
9
+ * restaurant waitlist, searched, filtered, sorted and counted by the database,
10
+ * with the summary of every party (commerce-restaurant-waitlist-list.ts,
11
+ * stacksjs/stacks#3218). The entry dialog searches its customers itself
12
+ * (commerce-choices.ts); this used to send the first 500.
13
+ */
6
14
  export default new Action({
7
15
  name: 'RestaurantWaitlistIndexAction',
8
- description: 'Return native restaurant waitlist records and customer options for the dashboard',
16
+ description: 'Return one page of native restaurant waitlist records for the dashboard',
9
17
  method: 'GET',
10
18
  apiResponse: true,
11
19
 
12
- async handle() {
13
- try {
14
- const [rows, customers] = await Promise.all([
15
- WaitlistRestaurant.orderByDesc('id').limit(500).get(),
16
- Customer.orderBy('name').limit(500).get(),
17
- ])
18
- const customerOptions = customers.map(normalizeRestaurantWaitlistCustomerOption)
19
- const customerIds = new Set(customerOptions.map(customer => customer.id))
20
- const records = rows.map(row => normalizeRestaurantWaitlistRecord(row, customerIds))
20
+ async handle(request: RequestInstance) {
21
+ const query = parseRestaurantWaitlistListQuery(key => request.get<unknown>(key, ''))
22
+ if ('error' in query)
23
+ return response.json({ message: query.error }, 422)
21
24
 
25
+ try {
26
+ const parties = await readRestaurantWaitlistPage(query)
22
27
  return {
23
- records,
24
- summary: summarizeRestaurantWaitlist(records),
25
- options: {
26
- customers: customerOptions,
27
- },
28
+ records: parties.records,
29
+ total: parties.total,
30
+ page: parties.page,
31
+ perPage: query.perPage,
32
+ summary: parties.summary,
28
33
  }
29
34
  }
30
35
  catch (error) {
@@ -1,44 +1,35 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
1
2
  import { Action } from '@stacksjs/actions/runtime'
2
- import { Customer, Product, Review } from '@stacksjs/orm'
3
+ import { response } from '@stacksjs/router'
3
4
  import { dashboardOperationalError } from '../dashboard-response'
4
- import {
5
- normalizeReviewCustomerContext,
6
- normalizeReviewProductOption,
7
- normalizeReviewRecord,
8
- summarizeReviews,
9
- } from './review-records'
5
+ import { parseReviewListQuery, readReviewPage } from './commerce-review-list'
10
6
 
7
+ /**
8
+ * `GET /api/dashboard/commerce/reviews` - one page of reviews, searched,
9
+ * filtered, sorted and counted by the database, with the summary of every
10
+ * review (commerce-review-list.ts, stacksjs/stacks#3218). It used to return
11
+ * the newest 500 for the browser to do all of that with.
12
+ */
11
13
  export default new Action({
12
14
  name: 'ReviewIndexAction',
13
- description: 'Returns persisted reviews with their product and customer context for dashboard moderation.',
15
+ description: 'Returns one page of persisted reviews with their product and customer context for dashboard moderation.',
14
16
  method: 'GET',
15
17
  apiResponse: true,
16
18
 
17
- async handle() {
18
- try {
19
- const [reviews, products, customers] = await Promise.all([
20
- Review.orderByDesc('id').limit(500).get(),
21
- Product.orderBy('name', 'asc').limit(500).get(),
22
- Customer.orderBy('name', 'asc').limit(500).get(),
23
- ])
24
- const productOptions = products
25
- .map(normalizeReviewProductOption)
26
- .sort((left, right) => left.label.localeCompare(right.label))
27
- const productMap = new Map(productOptions.map(product => [
28
- product.id,
29
- { name: product.label },
30
- ]))
31
- const customerContexts = customers.map(normalizeReviewCustomerContext)
32
- const customerMap = new Map(customerContexts.map(customer => [
33
- customer.id,
34
- customer.context,
35
- ]))
36
- const records = reviews.map(review => normalizeReviewRecord(review, productMap, customerMap))
19
+ async handle(request: RequestInstance) {
20
+ const query = parseReviewListQuery(key => request.get<unknown>(key, ''))
21
+ if ('error' in query)
22
+ return response.json({ message: query.error }, 422)
37
23
 
24
+ try {
25
+ const reviews = await readReviewPage(query)
38
26
  return {
39
- records,
40
- summary: summarizeReviews(records),
41
- products: productOptions,
27
+ records: reviews.records,
28
+ total: reviews.total,
29
+ page: reviews.page,
30
+ perPage: query.perPage,
31
+ summary: reviews.summary,
32
+ products: reviews.products,
42
33
  }
43
34
  }
44
35
  catch (error) {
@@ -15,7 +15,9 @@ export default new Action({
15
15
 
16
16
  async handle() {
17
17
  try {
18
- const methods = await ShippingMethod.orderBy('name', 'asc').limit(500).get()
18
+ // Read whole: store configuration, which the page searches in full. The
19
+ // first 500 left the rest unlisted and unsearchable (stacksjs/stacks#3218).
20
+ const methods = await ShippingMethod.orderBy('name', 'asc').get()
19
21
  const methodIds = shippingMethodIds(methods)
20
22
  const zones = methodIds.size
21
23
  ? await ShippingZone.whereIn('shipping_method_id', [...methodIds]).orderBy('name', 'asc').get()
@@ -15,7 +15,9 @@ export default new Action({
15
15
 
16
16
  async handle() {
17
17
  try {
18
- const rates = await ShippingRate.orderBy('weight_from', 'asc').limit(500).get()
18
+ // Read whole: store configuration, which the page searches in full. The
19
+ // first 500 left the rest unlisted and unsearchable (stacksjs/stacks#3218).
20
+ const rates = await ShippingRate.orderBy('weight_from', 'asc').get()
19
21
  const methodIds = [...new Set(rates.map(rate => rate.get('shipping_method_id')).filter(Boolean))]
20
22
  const zoneIds = [...new Set(rates.map(rate => rate.get('shipping_zone_id')).filter(Boolean))]
21
23
  const [methods, zones] = await Promise.all([
@@ -14,7 +14,9 @@ export default new Action({
14
14
 
15
15
  async handle() {
16
16
  try {
17
- const zones = await ShippingZone.orderBy('name', 'asc').limit(500).get()
17
+ // Read whole: store configuration, which the page searches in full. The
18
+ // first 500 left the rest unlisted and unsearchable (stacksjs/stacks#3218).
19
+ const zones = await ShippingZone.orderBy('name', 'asc').get()
18
20
  const methodIds = [...new Set(zones.map(zone => zone.get('shipping_method_id')).filter(Boolean))]
19
21
  const methods = methodIds.length
20
22
  ? await ShippingMethod.whereIn('id', methodIds).get()
@@ -0,0 +1,100 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { SQL } from 'bun'
3
+ import { describe, expect, test } from 'bun:test'
4
+ import { readCommerceCategories } from './commerce-category-list'
5
+ import type { CommerceSqlRunner } from './commerce-sql'
6
+
7
+ /**
8
+ * The product categories against each dialect's real engine
9
+ * (stacksjs/stacks#3218), over 520 of them: the page used to read the first
10
+ * 500 by display order.
11
+ */
12
+ type Dialect = 'sqlite' | 'postgres' | 'mysql'
13
+
14
+ const ROWS = 520
15
+
16
+ /** Category n shows in display order n, except 11, which ties with 10; 3's parent is the last one shown. */
17
+ const CATEGORIES = Array.from({ length: ROWS }, (_, index) => {
18
+ const id = index + 1
19
+ return {
20
+ id,
21
+ name: `Category ${String(id).padStart(3, '0')}`,
22
+ displayOrder: id === 11 ? 10 : id,
23
+ parentId: id === 3 ? 520 : id % 10 === 0 ? 1 : null,
24
+ active: id % 4 !== 0,
25
+ }
26
+ })
27
+
28
+ async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
29
+ const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
30
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
31
+ const bool = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
32
+ const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
33
+ const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
34
+ const columns = 7
35
+ await run(`CREATE TABLE categories (id ${pk}, name ${text}, description ${text} NULL, slug ${text}, image_url ${text} NULL, is_active ${bool}, parent_category_id INTEGER NULL, display_order INTEGER, created_at ${time})`)
36
+ await run(
37
+ `INSERT INTO categories (id, name, slug, is_active, parent_category_id, display_order, created_at) VALUES ${CATEGORIES.map((_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')}`,
38
+ CATEGORIES.flatMap(category => [
39
+ category.id, category.name, `category-${category.id}`, dialect === 'postgres' ? category.active : (category.active ? 1 : 0),
40
+ category.parentId, category.displayOrder, '2026-11-01 09:00:00',
41
+ ]),
42
+ )
43
+ }
44
+
45
+ async function exercise(runner: CommerceSqlRunner) {
46
+ const { records, summary } = await readCommerceCategories(runner)
47
+
48
+ // Every category, in display order, the id breaking the tie between 10 and 11.
49
+ expect(records.length).toBe(ROWS)
50
+ expect(records.map(record => record.id)).toEqual(
51
+ [...CATEGORIES].sort((a, b) => a.displayOrder - b.displayOrder || a.id - b.id).map(category => String(category.id)),
52
+ )
53
+ // A parent shown after the 500th is found.
54
+ expect(records.find(record => record.id === '3')?.parentCategoryId).toBe('520')
55
+
56
+ const roots = CATEGORIES.filter(category => !category.parentId).length
57
+ expect(summary).toMatchObject({
58
+ total: ROWS,
59
+ active: CATEGORIES.filter(category => category.active).length,
60
+ roots,
61
+ children: ROWS - roots,
62
+ })
63
+ }
64
+
65
+ describe('readCommerceCategories on SQLite', () => {
66
+ test('every category, in display order, with parents past the 500th', async () => {
67
+ const database = new Database(':memory:')
68
+ await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
69
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) })
70
+ })
71
+ })
72
+
73
+ for (const dialect of ['postgres', 'mysql'] as const) {
74
+ const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
75
+
76
+ test.skipIf(!connection)(`readCommerceCategories on ${dialect}: every category, in display order, with parents past the 500th`, async () => {
77
+ const url = new URL(connection!)
78
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
79
+ throw new Error('Category list tests require a local disposable database server')
80
+
81
+ const name = `stacks_categories_${crypto.randomUUID().replaceAll('-', '')}`
82
+ const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
83
+ const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
84
+ await admin.unsafe(`CREATE DATABASE ${quoted}`)
85
+ const scoped = new URL(url.href)
86
+ scoped.pathname = `/${name}`
87
+ // Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
88
+ const database = new SQL({ url: scoped.href, database: name })
89
+
90
+ try {
91
+ await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
92
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) })
93
+ }
94
+ finally {
95
+ await database.close()
96
+ try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
97
+ finally { await admin.close() }
98
+ }
99
+ }, 60_000)
100
+ }
@@ -0,0 +1,26 @@
1
+ import type { CommerceSqlRunner } from './commerce-sql'
2
+ import { db } from '@stacksjs/database/runtime'
3
+ import type { CommerceCategoryRecord, CommerceCategorySummary } from './commerce-category-records'
4
+ import { normalizeCommerceCategoryRecord, summarizeCommerceCategories } from './commerce-category-records'
5
+ import { sqlRows } from './commerce-sql'
6
+
7
+ /**
8
+ * Every product category, in display order (stacksjs/stacks#3218).
9
+ *
10
+ * Categories are reference data the page needs whole: it draws them as a
11
+ * tree, offers them as parents in the dialog, and names each one's parent.
12
+ * It used to read the first 500 by display order, so a later category was
13
+ * missing from all of that, and one whose parent was past the 500th failed
14
+ * the whole page with "references missing Category".
15
+ */
16
+ export async function readCommerceCategories(run: CommerceSqlRunner = db): Promise<{ records: CommerceCategoryRecord[], summary: CommerceCategorySummary }> {
17
+ // The id breaks display-order ties, so the order is the same on every load.
18
+ const rows = sqlRows(await run.unsafe('SELECT * FROM categories ORDER BY display_order ASC, id ASC').execute())
19
+ const records = rows.map(normalizeCommerceCategoryRecord)
20
+ const ids = new Set(records.map(record => record.id))
21
+ for (const record of records) {
22
+ if (record.parentCategoryId && !ids.has(record.parentCategoryId))
23
+ throw new TypeError(`Category ${record.id}.parent_category_id references missing Category ${record.parentCategoryId}.`)
24
+ }
25
+ return { records, summary: summarizeCommerceCategories(records) }
26
+ }
@@ -0,0 +1,56 @@
1
+ import {
2
+ commerceEmail,
3
+ commerceIdentifier,
4
+ commerceNumber,
5
+ commerceOptionalString,
6
+ commerceRequiredString,
7
+ commerceValue,
8
+ } from './commerce-record'
9
+
10
+ /**
11
+ * The products and customers a commerce dialog offers, as the dialog shows
12
+ * them (stacksjs/stacks#3218). Kept apart from the search in
13
+ * commerce-choices.ts, which reads the database: the waitlist records modules
14
+ * re-export these, and dashboard components import values from those modules,
15
+ * so anything here ends up in a browser bundle.
16
+ */
17
+ export interface ProductChoice {
18
+ id: string
19
+ label: string
20
+ detail: string
21
+ }
22
+
23
+ export interface CustomerChoice extends ProductChoice {
24
+ email: string
25
+ phone: string
26
+ }
27
+
28
+ export function normalizeProductChoice(record: any): ProductChoice {
29
+ const id = commerceIdentifier(commerceValue(record, 'id', 'uuid'), 'Product')
30
+ const source = `Product ${id}`
31
+ const inventory = commerceNumber(
32
+ commerceValue(record, 'inventory_count', 'inventoryCount'),
33
+ source,
34
+ 'inventory_count',
35
+ { min: 0, integer: true },
36
+ )
37
+ return {
38
+ id,
39
+ label: commerceRequiredString(commerceValue(record, 'name'), source, 'name'),
40
+ detail: `${inventory} in inventory`,
41
+ }
42
+ }
43
+
44
+ export function normalizeCustomerChoice(record: any): CustomerChoice {
45
+ const id = commerceIdentifier(commerceValue(record, 'id', 'uuid'), 'Customer')
46
+ const source = `Customer ${id}`
47
+ const email = commerceEmail(commerceValue(record, 'email'), source)
48
+ const phone = commerceOptionalString(commerceValue(record, 'phone'), source, 'phone')
49
+ return {
50
+ id,
51
+ label: commerceRequiredString(commerceValue(record, 'name'), source, 'name'),
52
+ detail: email || phone,
53
+ email,
54
+ phone,
55
+ }
56
+ }
@@ -0,0 +1,88 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { SQL } from 'bun'
3
+ import { describe, expect, test } from 'bun:test'
4
+ import { searchCustomerChoices, searchProductChoices } from './commerce-choices'
5
+ import type { CommerceSqlRunner } from './commerce-sql'
6
+
7
+ /**
8
+ * The commerce dialogs' product and customer searches against each dialect's
9
+ * real engine (stacksjs/stacks#3218), over 600 of each: the waitlist dialogs
10
+ * used to be handed the first 500.
11
+ */
12
+ type Dialect = 'sqlite' | 'postgres' | 'mysql'
13
+
14
+ const ROWS = 600
15
+ const productName = (id: number) => id === 600 ? 'Zebra Tea' : id === 7 ? 'apple_50% off' : id === 8 ? 'apple 500 box' : `Product ${String(id).padStart(3, '0')}`
16
+ const customerName = (id: number) => id === 599 ? 'mia Late' : id === 3 ? 'Mia early' : `Customer ${String(id).padStart(3, '0')}`
17
+
18
+ async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
19
+ const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
20
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
21
+ const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
22
+ await run(`CREATE TABLE products (id ${pk}, name ${text}, inventory_count INTEGER)`)
23
+ await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text}, phone ${text} NULL)`)
24
+ const all = Array.from({ length: ROWS }, (_, i) => i + 1)
25
+ await run(`INSERT INTO products (id, name, inventory_count) VALUES ${all.map((_, i) => `(${p(3 * i + 1)}, ${p(3 * i + 2)}, ${p(3 * i + 3)})`).join(', ')}`, all.flatMap(id => [id, productName(id), id % 9]))
26
+ await run(`INSERT INTO customers (id, name, email, phone) VALUES ${all.map((_, i) => `(${p(4 * i + 1)}, ${p(4 * i + 2)}, ${p(4 * i + 3)}, ${p(4 * i + 4)})`).join(', ')}`, all.flatMap(id => [id, customerName(id), `buyer${id}@shop.test`, id === 444 ? '+1 555 0444' : null]))
27
+ }
28
+
29
+ async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
30
+ const products = (search: string, limit = 25) => searchProductChoices({ search, limit }, runner, dialect)
31
+ const customers = (search: string, limit = 25) => searchCustomerChoices({ search, limit }, runner, dialect)
32
+
33
+ // Unsearched: bounded, by name ignoring case, with how many there are.
34
+ const first = await products('')
35
+ expect(first.total).toBe(ROWS)
36
+ expect(first.choices.length).toBe(25)
37
+ expect(first.choices.slice(0, 2).map(choice => choice.label)).toEqual(['apple 500 box', 'apple_50% off'])
38
+
39
+ // The 600th of each can be found, and a literal % matches only itself.
40
+ expect(await products('zebra')).toEqual({ choices: [{ id: '600', label: 'Zebra Tea', detail: '6 in inventory' }], total: 1 })
41
+ expect((await products('50%')).choices.map(choice => choice.id)).toEqual(['7'])
42
+ expect((await products('600')).choices.map(choice => choice.id)).toEqual(['600'])
43
+ expect((await customers('MIA')).choices.map(choice => choice.label)).toEqual(['Mia early', 'mia Late'])
44
+ expect((await customers('buyer599@')).choices).toEqual([{ id: '599', label: 'mia Late', detail: 'buyer599@shop.test', email: 'buyer599@shop.test', phone: '' }])
45
+ expect((await customers('0444')).choices.map(choice => choice.id)).toEqual(['444'])
46
+
47
+ // The limit bounds the choices, not the count.
48
+ const bounded = await customers('customer', 5)
49
+ expect(bounded.choices.length).toBe(5)
50
+ expect(bounded.total).toBe(ROWS - 2)
51
+ }
52
+
53
+ describe('commerce choices on SQLite', () => {
54
+ test('products and customers by name, email, phone and id', async () => {
55
+ const database = new Database(':memory:')
56
+ await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
57
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
58
+ })
59
+ })
60
+
61
+ for (const dialect of ['postgres', 'mysql'] as const) {
62
+ const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
63
+
64
+ test.skipIf(!connection)(`commerce choices on ${dialect}: products and customers by name, email, phone and id`, async () => {
65
+ const url = new URL(connection!)
66
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
67
+ throw new Error('Commerce choice tests require a local disposable database server')
68
+
69
+ const name = `stacks_commerce_choices_${crypto.randomUUID().replaceAll('-', '')}`
70
+ const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
71
+ const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
72
+ await admin.unsafe(`CREATE DATABASE ${quoted}`)
73
+ const scoped = new URL(url.href)
74
+ scoped.pathname = `/${name}`
75
+ // Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
76
+ const database = new SQL({ url: scoped.href, database: name })
77
+
78
+ try {
79
+ await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
80
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
81
+ }
82
+ finally {
83
+ await database.close()
84
+ try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
85
+ finally { await admin.close() }
86
+ }
87
+ }, 60_000)
88
+ }