@stacksjs/defaults 0.75.489 → 0.75.492

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +20 -2
  3. package/ai/skills/stacks-native/CATALOG.md +9 -9
  4. package/ai/skills/stacks-search-engine/SKILL.md +14 -0
  5. package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
  6. package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
  7. package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
  8. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
  9. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
  10. package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
  11. package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
  12. package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
  13. package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
  14. package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
  15. package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
  16. package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
  17. package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
  18. package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
  19. package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
  20. package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
  21. package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
  22. package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
  23. package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
  24. package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
  25. package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
  26. package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
  27. package/app/Actions/Dashboard/Commerce/ProductUnitIndexAction.ts +23 -19
  28. package/app/Actions/Dashboard/Commerce/ProductVariantIndexAction.ts +25 -18
  29. package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
  30. package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
  31. package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
  32. package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
  33. package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
  34. package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
  35. package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
  36. package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
  37. package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
  38. package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
  39. package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
  40. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
  41. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
  42. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
  43. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
  44. package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
  45. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
  46. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
  47. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
  48. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
  49. package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
  50. package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
  51. package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
  52. package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
  53. package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
  54. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
  55. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
  56. package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
  57. package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
  58. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
  59. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
  60. package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
  61. package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
  62. package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.test.ts +146 -0
  63. package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.ts +178 -0
  64. package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.test.ts +165 -0
  65. package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.ts +209 -0
  66. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
  67. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
  68. package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
  69. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
  70. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
  71. package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
  72. package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
  73. package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
  74. package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
  75. package/app/Actions/Dashboard/Commerce/product-unit-records.test.ts +0 -13
  76. package/app/Actions/Dashboard/Commerce/product-unit-records.ts +0 -17
  77. package/app/Actions/Dashboard/Commerce/product-variant-records.test.ts +0 -13
  78. package/app/Actions/Dashboard/Commerce/product-variant-records.ts +0 -17
  79. package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
  80. package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
  81. package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
  82. package/app/Actions/Dashboard/Content/content-list.ts +10 -0
  83. package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
  84. package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
  85. package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
  86. package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
  87. package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
  88. package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
  89. package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
  90. package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
  91. package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
  92. package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
  93. package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
  94. package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
  95. package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
  96. package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
  97. package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +5 -3
  98. package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
  99. package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
  100. package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
  101. package/app/Actions/Dashboard/named-search.test.ts +36 -0
  102. package/app/Actions/Dashboard/named-search.ts +80 -0
  103. package/app/Models/Request.ts +4 -2
  104. package/functions/commerce/shippings/dashboard-resource.ts +12 -1
  105. package/functions/commerce/shippings/delivery-routes.ts +1 -0
  106. package/functions/commerce/shippings/license-keys.ts +1 -0
  107. package/functions/dashboard-list.test.ts +146 -1
  108. package/functions/dashboard-list.ts +216 -1
  109. package/functions/queue.ts +2 -0
  110. package/ide/vscode/package.json +1 -1
  111. package/package.json +2 -2
  112. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
  113. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
  114. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
  115. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
  116. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
  117. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
  118. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
  119. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
  120. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
  121. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
  122. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
  123. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
  124. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
  125. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
  126. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
  127. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
  128. package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +63 -8
  129. package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +48 -60
  130. package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +29 -3
  131. package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +57 -3
  132. package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +59 -61
  133. package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +28 -2
  134. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
  135. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
  136. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
  137. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
  138. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
  139. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
  140. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
  141. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
  142. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
  143. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
  144. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
  145. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
  146. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
  147. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
  148. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
  149. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
  150. package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
  151. package/resources/components/Dashboard/Queue/QueueDashboard.stx +7 -1
  152. package/routes/dashboard-api.ts +11 -0
  153. package/views/dashboard/stores/kanban.ts +38 -6
@@ -0,0 +1,170 @@
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 { commerceIdentifier, commerceRequiredString, commerceValue, referencedIds } from './commerce-record'
6
+ import type { CommerceSqlRunner } from './commerce-sql'
7
+ import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
8
+ import type { ProductWaitlistRecord, ProductWaitlistSummary } from './product-waitlist-records'
9
+ import { normalizeProductWaitlistRecord } from './product-waitlist-records'
10
+
11
+ /**
12
+ * One page of the product waitlist, searched, filtered, sorted and counted by
13
+ * the database, with the summary of every entry (stacksjs/stacks#3218).
14
+ *
15
+ * The page used to read the newest 500 entries and do all of that in the
16
+ * browser, and the summary counted those 500. Its record check read the
17
+ * first 500 products and customers by name, so one entry for any later
18
+ * product or customer failed the whole page.
19
+ */
20
+ export const PRODUCT_WAITLIST_SORTS = ['created', 'id', 'name', 'product', 'quantity', 'status', 'preference'] as const
21
+ export type ProductWaitlistSort = typeof PRODUCT_WAITLIST_SORTS[number]
22
+
23
+ export const PRODUCT_WAITLIST_STATUSES = ['waiting', 'notified', 'purchased', 'cancelled'] as const
24
+
25
+ export interface ProductWaitlistListQuery {
26
+ search: string
27
+ /** '' for any. */
28
+ status: '' | typeof PRODUCT_WAITLIST_STATUSES[number]
29
+ sort: ProductWaitlistSort
30
+ direction: 'asc' | 'desc'
31
+ page: number
32
+ perPage: number
33
+ }
34
+
35
+ export function parseProductWaitlistListQuery(read: QueryReader): ProductWaitlistListQuery | { error: string } {
36
+ const pageText = queryText(read, 'page')
37
+ const page = pageText === '' ? 1 : Number(pageText)
38
+ if (!Number.isInteger(page) || page < 1)
39
+ return { error: 'page must be a whole number of 1 or more.' }
40
+
41
+ const sizeText = queryText(read, 'per_page')
42
+ const perPage = sizeText === '' ? 25 : Number(sizeText)
43
+ if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
44
+ return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
45
+
46
+ const sort = queryText(read, 'sort') || 'created'
47
+ if (!(PRODUCT_WAITLIST_SORTS as readonly string[]).includes(sort))
48
+ return { error: `sort must be one of ${PRODUCT_WAITLIST_SORTS.join(', ')}.` }
49
+
50
+ const directionText = queryText(read, 'direction').toLowerCase()
51
+ const direction = directionText === '' ? (sort === 'created' || sort === 'quantity' ? 'desc' : 'asc') : directionText
52
+ if (direction !== 'asc' && direction !== 'desc')
53
+ return { error: 'direction must be asc or desc.' }
54
+
55
+ const search = queryText(read, 'q')
56
+ if (search.length > 200)
57
+ return { error: 'q must be 200 characters or fewer.' }
58
+
59
+ const status = queryText(read, 'status')
60
+ if (status && !(PRODUCT_WAITLIST_STATUSES as readonly string[]).includes(status))
61
+ return { error: `status must be one of ${PRODUCT_WAITLIST_STATUSES.join(', ')}.` }
62
+
63
+ return { search, status: status as ProductWaitlistListQuery['status'], sort: sort as ProductWaitlistSort, direction, page, perPage }
64
+ }
65
+
66
+ const FROM = ' FROM waitlist_products w LEFT JOIN products p ON p.id = w.product_id'
67
+
68
+ function sortExpression(sort: ProductWaitlistSort, dialect: QueryBuilderDialect): string {
69
+ switch (sort) {
70
+ case 'id': return 'w.id'
71
+ case 'name': return 'LOWER(w.name)'
72
+ case 'product': return `LOWER(COALESCE(p.name, ''))`
73
+ case 'quantity': return 'w.quantity'
74
+ // As text: PostgreSQL keeps both as enums, which sort by declaration order.
75
+ case 'status': return asText('w.status', dialect)
76
+ case 'preference': return asText('w.notification_preference', dialect)
77
+ default: return 'w.created_at'
78
+ }
79
+ }
80
+
81
+ export function productWaitlistFilter(query: Pick<ProductWaitlistListQuery, 'search' | 'status'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
82
+ const { bind, values } = binder(dialect)
83
+ const clauses: string[] = []
84
+ if (query.status)
85
+ clauses.push(`${asText('w.status', dialect)} = ${bind(query.status)}`)
86
+ if (query.search) {
87
+ const pattern = containsPattern(query.search)
88
+ const columns = [
89
+ 'w.name',
90
+ 'w.email',
91
+ `COALESCE(w.phone, '')`,
92
+ 'w.source',
93
+ `COALESCE(p.name, '')`,
94
+ `COALESCE(${asText('w.product_id', dialect)}, '')`,
95
+ ]
96
+ clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
97
+ }
98
+ return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
99
+ }
100
+
101
+ function orderBy(query: Pick<ProductWaitlistListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
102
+ const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
103
+ // Ties read newest first; the id breaks every remaining tie, so pages never
104
+ // repeat or skip an entry.
105
+ if (query.sort === 'created' || query.sort === 'id')
106
+ return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, w.id ${direction}`
107
+ return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, w.created_at DESC, w.id DESC`
108
+ }
109
+
110
+ /** Entries turned into records, against exactly the products and customers they reference. */
111
+ async function recordsFor(entries: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ProductWaitlistRecord[]> {
112
+ if (entries.length === 0)
113
+ return []
114
+ const productIds = referencedIds(entries, 'product_id')
115
+ const customerIds = referencedIds(entries, 'customer_id')
116
+ const [products, customers] = await Promise.all([
117
+ productIds.length > 0 ? run.unsafe(`SELECT id, name FROM products WHERE id IN (${idPlaceholders(productIds, dialect)})`, productIds).execute() : [],
118
+ customerIds.length > 0 ? run.unsafe(`SELECT id FROM customers WHERE id IN (${idPlaceholders(customerIds, dialect)})`, customerIds).execute() : [],
119
+ ])
120
+ const names = new Map(sqlRows(products).map((row) => {
121
+ const id = commerceIdentifier(commerceValue(row, 'id'), 'Product')
122
+ return [id, commerceRequiredString(commerceValue(row, 'name'), `Product ${id}`, 'name')]
123
+ }))
124
+ const known = new Set(sqlRows(customers).map(row => commerceIdentifier(commerceValue(row, 'id'), 'Customer')))
125
+ return entries.map(entry => normalizeProductWaitlistRecord(entry, names, known))
126
+ }
127
+
128
+ /** The summary cards, over every entry as before. */
129
+ async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ProductWaitlistSummary> {
130
+ const status = asText('status', dialect)
131
+ const count = (name: string) => `SUM(CASE WHEN ${status} = '${name}' THEN 1 ELSE 0 END)`
132
+ const row = sqlRows(await run.unsafe(
133
+ `SELECT COUNT(*) AS total_count, ${count('waiting')} AS waiting_count, ${count('notified')} AS notified_count, ${count('purchased')} AS purchased_count FROM waitlist_products`,
134
+ ).execute())[0] ?? {}
135
+ const total = countOf(row.total_count)
136
+ const purchased = countOf(row.purchased_count)
137
+ return {
138
+ total,
139
+ waiting: countOf(row.waiting_count),
140
+ notified: countOf(row.notified_count),
141
+ purchased,
142
+ conversionRate: total > 0 ? Math.round((purchased / total) * 100) : 0,
143
+ }
144
+ }
145
+
146
+ export interface ProductWaitlistPage {
147
+ records: ProductWaitlistRecord[]
148
+ total: number
149
+ page: number
150
+ summary: ProductWaitlistSummary
151
+ }
152
+
153
+ export async function readProductWaitlistPage(
154
+ query: ProductWaitlistListQuery,
155
+ run: CommerceSqlRunner = db,
156
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
157
+ ): Promise<ProductWaitlistPage> {
158
+ const { where, values } = productWaitlistFilter(query, dialect)
159
+ const [counted, summary] = await Promise.all([
160
+ run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
161
+ summarize(run, dialect),
162
+ ])
163
+ const total = countOf(sqlRows(counted)[0]?.total_count)
164
+ const page = pageWithin(query.page, total, query.perPage)
165
+ const entries = await run.unsafe(
166
+ `SELECT w.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
167
+ values,
168
+ ).execute()
169
+ return { records: await recordsFor(sqlRows(entries), run, dialect), total, page, summary }
170
+ }
@@ -224,3 +224,24 @@ export function commerceOptionalDate(input: unknown, source: string, field: stri
224
224
  return ''
225
225
  return commerceDate(input, source, field)
226
226
  }
227
+
228
+ /**
229
+ * The ids a set of records points at through one field, as integers, once
230
+ * each, so a page reads exactly the related rows it references.
231
+ *
232
+ * The commerce normalizers refuse a record whose order, customer, coupon,
233
+ * category or manufacturer is missing from what they were given, and those
234
+ * used to come from a fixed first 500. Past that, one record pointing further
235
+ * failed the whole page: Orders past 500 customers, Payments past a store's
236
+ * 500th order, Products past 500 categories (stacksjs/stacks#3218).
237
+ */
238
+ export function referencedIds(records: unknown[], ...keys: string[]): number[] {
239
+ const ids = new Set<number>()
240
+ for (const record of records) {
241
+ const value = commerceValue(record, ...keys)
242
+ const id = Number(value)
243
+ if (value !== undefined && value !== null && value !== '' && Number.isSafeInteger(id) && id > 0)
244
+ ids.add(id)
245
+ }
246
+ return [...ids].sort((left, right) => left - right)
247
+ }
@@ -0,0 +1,189 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { SQL } from 'bun'
3
+ import { describe, expect, test } from 'bun:test'
4
+ import type { RestaurantWaitlistListQuery } from './commerce-restaurant-waitlist-list'
5
+ import { parseRestaurantWaitlistListQuery, readRestaurantWaitlistPage } from './commerce-restaurant-waitlist-list'
6
+ import type { CommerceSqlRunner } from './commerce-sql'
7
+
8
+ /**
9
+ * The restaurant waitlist against each dialect's real engine
10
+ * (stacksjs/stacks#3218), with status and table preference as real enums, and
11
+ * customers past the 500 the page used to read.
12
+ */
13
+ type Dialect = 'sqlite' | 'postgres' | 'mysql'
14
+
15
+ const NOW = new Date('2026-11-06T12:00:00.000Z')
16
+ const CUSTOMERS = 600
17
+ const STATUSES = ['waiting', 'seated', 'cancelled', 'no_show'] as const
18
+ const PREFERENCES = ['indoor', 'bar', 'booth', 'no_preference'] as const
19
+ const NAMES = ['ann', 'Ben', 'cat', 'Dan', 'eve']
20
+
21
+ /** 26 parties, one an hour back from NOW; 14 and 15 share a creation time. */
22
+ const PARTIES = Array.from({ length: 26 }, (_, index) => {
23
+ const id = index + 1
24
+ return {
25
+ id,
26
+ name: id === 9 ? 'Table_100% Crew' : id === 10 ? 'Table 1000 Crew' : NAMES[id % NAMES.length]!,
27
+ email: `guest${id}@diner.test`,
28
+ phone: id === 21 ? '+1 555 0121' : null,
29
+ party_size: (id * 3) % 7 + 1,
30
+ table_preference: PREFERENCES[id % PREFERENCES.length]!,
31
+ status: STATUSES[id % STATUSES.length]!,
32
+ quoted_wait_time: (id * 5) % 45,
33
+ check_in_minutes: (id * 11) % 90,
34
+ customer_id: id % 5 === 0 ? 599 : null,
35
+ hoursAgo: id === 15 ? 14 : id,
36
+ }
37
+ })
38
+ type Party = typeof PARTIES[number]
39
+
40
+ const ids = (parties: Party[]) => parties.map(party => String(party.id))
41
+ const newestFirst = (a: Party, b: Party) => a.hoursAgo - b.hoursAgo || b.id - a.id
42
+
43
+ function query(overrides: Partial<RestaurantWaitlistListQuery> = {}): RestaurantWaitlistListQuery {
44
+ return { search: '', status: '', preference: '', sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
45
+ }
46
+
47
+ async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
48
+ const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
49
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
50
+ const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
51
+ const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
52
+ const enumOf = (values: readonly string[]) => values.map(value => `'${value}'`).join(', ')
53
+ let statusType = text
54
+ let preferenceType = text
55
+ if (dialect === 'postgres') {
56
+ // Declared out of alphabetical order, so a sort that forgets the text cast shows.
57
+ await run(`CREATE TYPE party_status AS ENUM (${enumOf(STATUSES)})`)
58
+ await run(`CREATE TYPE party_preference AS ENUM (${enumOf(PREFERENCES)})`)
59
+ statusType = 'party_status'
60
+ preferenceType = 'party_preference'
61
+ }
62
+ if (dialect === 'mysql') {
63
+ statusType = `ENUM(${enumOf(STATUSES)})`
64
+ preferenceType = `ENUM(${enumOf(PREFERENCES)})`
65
+ }
66
+ await run(`CREATE TABLE customers (id ${pk})`)
67
+ await run(`CREATE TABLE waitlist_restaurants (id ${pk}, name ${text}, email ${text}, phone ${text} NULL, party_size INTEGER, check_in_time ${time}, table_preference ${preferenceType}, status ${statusType}, quoted_wait_time INTEGER, actual_wait_time INTEGER NULL, queue_position INTEGER NULL, customer_id INTEGER NULL, created_at ${time})`)
68
+ const all = Array.from({ length: CUSTOMERS }, (_, i) => i + 1)
69
+ await run(`INSERT INTO customers (id) VALUES ${all.map((_, i) => `(${p(i + 1)})`).join(', ')}`, all)
70
+ const stamp = (date: Date) => date.toISOString().slice(0, 19).replace('T', ' ')
71
+ for (const party of PARTIES) {
72
+ await run(
73
+ `INSERT INTO waitlist_restaurants (id, name, email, phone, party_size, check_in_time, table_preference, status, quoted_wait_time, customer_id, created_at) VALUES (${Array.from({ length: 11 }, (_, i) => p(i + 1)).join(', ')})`,
74
+ [
75
+ party.id, party.name, party.email, party.phone, party.party_size,
76
+ stamp(new Date(NOW.getTime() - party.check_in_minutes * 60_000)), party.table_preference, party.status,
77
+ party.quoted_wait_time, party.customer_id, stamp(new Date(NOW.getTime() - party.hoursAgo * 3_600_000)),
78
+ ],
79
+ )
80
+ }
81
+ }
82
+
83
+ async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
84
+ const read = (overrides: Partial<RestaurantWaitlistListQuery> = {}) => readRestaurantWaitlistPage(query(overrides), runner, dialect)
85
+ const all = async (overrides: Partial<RestaurantWaitlistListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => record.id)
86
+ const matching = (keep: (party: Party) => boolean) => ids(PARTIES.filter(keep).sort(newestFirst))
87
+
88
+ // The summary counts every party, whatever the page is filtered to.
89
+ const filtered = await read({ status: 'cancelled' })
90
+ const waiting = PARTIES.filter(party => party.status === 'waiting')
91
+ const seated = PARTIES.filter(party => party.status === 'seated').length
92
+ expect(filtered.summary).toEqual({
93
+ total: PARTIES.length,
94
+ waiting: waiting.length,
95
+ seated,
96
+ cancelled: PARTIES.filter(party => party.status === 'cancelled').length,
97
+ noShow: PARTIES.filter(party => party.status === 'no_show').length,
98
+ averageQuotedWait: Math.round(waiting.reduce((sum, party) => sum + party.quoted_wait_time, 0) / waiting.length),
99
+ seatingRate: Math.round((seated / PARTIES.length) * 1000) / 10,
100
+ })
101
+ expect(filtered.total).toBe(PARTIES.filter(party => party.status === 'cancelled').length)
102
+
103
+ // Filters, alone and together.
104
+ expect(await all({ preference: 'booth' })).toEqual(matching(party => party.table_preference === 'booth'))
105
+ expect(await all({ status: 'waiting', preference: 'no_preference' })).toEqual(matching(party => party.status === 'waiting' && party.table_preference === 'no_preference'))
106
+
107
+ // Search: name with a literal %, email, phone, and the enum text, ignoring case.
108
+ expect(await all({ search: '100%' })).toEqual(['9'])
109
+ expect(await all({ search: 'GUEST21@' })).toEqual(['21'])
110
+ expect(await all({ search: '0121' })).toEqual(['21'])
111
+ expect(await all({ search: 'NO_SHOW' })).toEqual(matching(party => party.status === 'no_show'))
112
+
113
+ // Newest first, the id breaking the tie between 14 and 15, stable across pages.
114
+ const newest = [...PARTIES].sort(newestFirst)
115
+ const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
116
+ expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(ids(newest))
117
+ expect((await read({ page: 9 })).page).toBe(3)
118
+
119
+ // Sorts, ties newest first. Status and preference sort by name, not enum order.
120
+ const by = (key: (party: Party) => string | number, direction: 1 | -1 = 1) => (a: Party, b: Party) => {
121
+ const left = key(a)
122
+ const right = key(b)
123
+ const order = typeof left === 'number' ? (left - (right as number)) : left.localeCompare(right as string)
124
+ return order * direction || newestFirst(a, b)
125
+ }
126
+ expect(await all({ sort: 'name', direction: 'asc' })).toEqual(ids([...PARTIES].sort(by(party => party.name.toLowerCase()))))
127
+ expect(await all({ sort: 'party', direction: 'desc' })).toEqual(ids([...PARTIES].sort(by(party => party.party_size, -1))))
128
+ expect(await all({ sort: 'quoted', direction: 'asc' })).toEqual(ids([...PARTIES].sort(by(party => party.quoted_wait_time))))
129
+ expect(await all({ sort: 'status', direction: 'asc' })).toEqual(ids([...PARTIES].sort(by(party => party.status))))
130
+ expect(await all({ sort: 'preference', direction: 'asc' })).toEqual(ids([...PARTIES].sort(by(party => party.table_preference))))
131
+ // Latest check-in first: the fewest minutes ago.
132
+ expect(await all({ sort: 'checkin', direction: 'desc' })).toEqual(ids([...PARTIES].sort(by(party => party.check_in_minutes))))
133
+
134
+ // A customer past the 500th, read by the ids the page references.
135
+ expect((await read({ perPage: 100 })).records.filter(record => record.customerId === '599').length).toBe(PARTIES.filter(party => party.customer_id === 599).length)
136
+ }
137
+
138
+ describe('readRestaurantWaitlistPage on SQLite', () => {
139
+ test('summary, filters, search, sorts, pages and references', async () => {
140
+ const database = new Database(':memory:')
141
+ await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
142
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
143
+ })
144
+ })
145
+
146
+ for (const dialect of ['postgres', 'mysql'] as const) {
147
+ const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
148
+
149
+ test.skipIf(!connection)(`readRestaurantWaitlistPage on ${dialect}: summary, filters, search, sorts, pages and references`, async () => {
150
+ const url = new URL(connection!)
151
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
152
+ throw new Error('Restaurant waitlist list tests require a local disposable database server')
153
+
154
+ const name = `stacks_restaurant_waitlist_${crypto.randomUUID().replaceAll('-', '')}`
155
+ const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
156
+ const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
157
+ await admin.unsafe(`CREATE DATABASE ${quoted}`)
158
+ const scoped = new URL(url.href)
159
+ scoped.pathname = `/${name}`
160
+ // Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
161
+ const database = new SQL({ url: scoped.href, database: name })
162
+
163
+ try {
164
+ await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
165
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
166
+ }
167
+ finally {
168
+ await database.close()
169
+ try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
170
+ finally { await admin.close() }
171
+ }
172
+ }, 60_000)
173
+ }
174
+
175
+ describe('parseRestaurantWaitlistListQuery', () => {
176
+ const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
177
+
178
+ test('defaults to every party, newest first, 25 a page', () => {
179
+ expect(parseRestaurantWaitlistListQuery(reader({}))).toEqual({ search: '', status: '', preference: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
180
+ expect(parseRestaurantWaitlistListQuery(reader({ sort: 'checkin' }))).toHaveProperty('direction', 'desc')
181
+ expect(parseRestaurantWaitlistListQuery(reader({ sort: 'party' }))).toHaveProperty('direction', 'asc')
182
+ })
183
+
184
+ test('refuses values the page does not offer', () => {
185
+ expect(parseRestaurantWaitlistListQuery(reader({ status: 'purchased' }))).toHaveProperty('error')
186
+ expect(parseRestaurantWaitlistListQuery(reader({ preference: 'patio' }))).toHaveProperty('error')
187
+ expect(parseRestaurantWaitlistListQuery(reader({ sort: 'actual_wait_time' }))).toHaveProperty('error')
188
+ })
189
+ })
@@ -0,0 +1,177 @@
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 { commerceIdentifier, commerceValue, referencedIds } from './commerce-record'
6
+ import type { CommerceSqlRunner } from './commerce-sql'
7
+ import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
8
+ import type { RestaurantWaitlistRecord, RestaurantWaitlistSummary } from './restaurant-waitlist-records'
9
+ import { normalizeRestaurantWaitlistRecord } from './restaurant-waitlist-records'
10
+
11
+ /**
12
+ * One page of the restaurant waitlist, searched, filtered, sorted and counted
13
+ * by the database, with the summary of every party (stacksjs/stacks#3218).
14
+ *
15
+ * The page used to read the newest 500 parties and do all of that in the
16
+ * browser, and the summary counted those 500. Its record check read the first
17
+ * 500 customers by name, so one party linked to any later customer failed the
18
+ * whole page.
19
+ */
20
+ export const RESTAURANT_WAITLIST_SORTS = ['created', 'id', 'name', 'party', 'status', 'quoted', 'preference', 'checkin'] as const
21
+ export type RestaurantWaitlistSort = typeof RESTAURANT_WAITLIST_SORTS[number]
22
+
23
+ export const RESTAURANT_WAITLIST_STATUSES = ['waiting', 'seated', 'cancelled', 'no_show'] as const
24
+ export const RESTAURANT_TABLE_PREFERENCES = ['indoor', 'bar', 'booth', 'no_preference'] as const
25
+
26
+ export interface RestaurantWaitlistListQuery {
27
+ search: string
28
+ /** '' for any. */
29
+ status: '' | typeof RESTAURANT_WAITLIST_STATUSES[number]
30
+ /** '' for any. */
31
+ preference: '' | typeof RESTAURANT_TABLE_PREFERENCES[number]
32
+ sort: RestaurantWaitlistSort
33
+ direction: 'asc' | 'desc'
34
+ page: number
35
+ perPage: number
36
+ }
37
+
38
+ export function parseRestaurantWaitlistListQuery(read: QueryReader): RestaurantWaitlistListQuery | { error: string } {
39
+ const pageText = queryText(read, 'page')
40
+ const page = pageText === '' ? 1 : Number(pageText)
41
+ if (!Number.isInteger(page) || page < 1)
42
+ return { error: 'page must be a whole number of 1 or more.' }
43
+
44
+ const sizeText = queryText(read, 'per_page')
45
+ const perPage = sizeText === '' ? 25 : Number(sizeText)
46
+ if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
47
+ return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
48
+
49
+ const sort = queryText(read, 'sort') || 'created'
50
+ if (!(RESTAURANT_WAITLIST_SORTS as readonly string[]).includes(sort))
51
+ return { error: `sort must be one of ${RESTAURANT_WAITLIST_SORTS.join(', ')}.` }
52
+
53
+ const directionText = queryText(read, 'direction').toLowerCase()
54
+ const direction = directionText === '' ? (sort === 'created' || sort === 'checkin' ? 'desc' : 'asc') : directionText
55
+ if (direction !== 'asc' && direction !== 'desc')
56
+ return { error: 'direction must be asc or desc.' }
57
+
58
+ const search = queryText(read, 'q')
59
+ if (search.length > 200)
60
+ return { error: 'q must be 200 characters or fewer.' }
61
+
62
+ const status = queryText(read, 'status')
63
+ if (status && !(RESTAURANT_WAITLIST_STATUSES as readonly string[]).includes(status))
64
+ return { error: `status must be one of ${RESTAURANT_WAITLIST_STATUSES.join(', ')}.` }
65
+
66
+ const preference = queryText(read, 'preference')
67
+ if (preference && !(RESTAURANT_TABLE_PREFERENCES as readonly string[]).includes(preference))
68
+ return { error: `preference must be one of ${RESTAURANT_TABLE_PREFERENCES.join(', ')}.` }
69
+
70
+ return {
71
+ search,
72
+ status: status as RestaurantWaitlistListQuery['status'],
73
+ preference: preference as RestaurantWaitlistListQuery['preference'],
74
+ sort: sort as RestaurantWaitlistSort,
75
+ direction,
76
+ page,
77
+ perPage,
78
+ }
79
+ }
80
+
81
+ function sortExpression(sort: RestaurantWaitlistSort, dialect: QueryBuilderDialect): string {
82
+ switch (sort) {
83
+ case 'id': return 'id'
84
+ case 'name': return 'LOWER(name)'
85
+ case 'party': return 'party_size'
86
+ // As text: PostgreSQL and MySQL keep both as enums, which sort by declaration order.
87
+ case 'status': return asText('status', dialect)
88
+ case 'preference': return asText('table_preference', dialect)
89
+ case 'quoted': return 'quoted_wait_time'
90
+ case 'checkin': return 'check_in_time'
91
+ default: return 'created_at'
92
+ }
93
+ }
94
+
95
+ export function restaurantWaitlistFilter(query: Pick<RestaurantWaitlistListQuery, 'search' | 'status' | 'preference'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
96
+ const { bind, values } = binder(dialect)
97
+ const clauses: string[] = []
98
+ if (query.status)
99
+ clauses.push(`${asText('status', dialect)} = ${bind(query.status)}`)
100
+ if (query.preference)
101
+ clauses.push(`${asText('table_preference', dialect)} = ${bind(query.preference)}`)
102
+ if (query.search) {
103
+ const pattern = containsPattern(query.search)
104
+ const columns = ['name', 'email', `COALESCE(phone, '')`, asText('status', dialect), asText('table_preference', dialect)]
105
+ clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
106
+ }
107
+ return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
108
+ }
109
+
110
+ function orderBy(query: Pick<RestaurantWaitlistListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
111
+ const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
112
+ // Ties read newest first; the id breaks every remaining tie, so pages never
113
+ // repeat or skip a party.
114
+ if (query.sort === 'created' || query.sort === 'id')
115
+ return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, id ${direction}`
116
+ return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, created_at DESC, id DESC`
117
+ }
118
+
119
+ /** Parties turned into records, against exactly the customers they reference. */
120
+ async function recordsFor(parties: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<RestaurantWaitlistRecord[]> {
121
+ if (parties.length === 0)
122
+ return []
123
+ const customerIds = referencedIds(parties, 'customer_id')
124
+ const customers = customerIds.length > 0
125
+ ? await run.unsafe(`SELECT id FROM customers WHERE id IN (${idPlaceholders(customerIds, dialect)})`, customerIds).execute()
126
+ : []
127
+ const known = new Set(sqlRows(customers).map(row => commerceIdentifier(commerceValue(row, 'id'), 'Customer')))
128
+ return parties.map(party => normalizeRestaurantWaitlistRecord(party, known))
129
+ }
130
+
131
+ /** The summary cards, over every party as before. */
132
+ async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<RestaurantWaitlistSummary> {
133
+ const status = asText('status', dialect)
134
+ const count = (name: string) => `SUM(CASE WHEN ${status} = '${name}' THEN 1 ELSE 0 END)`
135
+ const row = sqlRows(await run.unsafe(
136
+ `SELECT COUNT(*) AS total_count, ${count('waiting')} AS waiting_count, ${count('seated')} AS seated_count, ${count('cancelled')} AS cancelled_count, ${count('no_show')} AS no_show_count, SUM(CASE WHEN ${status} = 'waiting' THEN quoted_wait_time ELSE 0 END) AS waiting_quoted FROM waitlist_restaurants`,
137
+ ).execute())[0] ?? {}
138
+ const total = countOf(row.total_count)
139
+ const waiting = countOf(row.waiting_count)
140
+ const seated = countOf(row.seated_count)
141
+ return {
142
+ total,
143
+ waiting,
144
+ seated,
145
+ cancelled: countOf(row.cancelled_count),
146
+ noShow: countOf(row.no_show_count),
147
+ // Over the parties still waiting, as summarizeRestaurantWaitlist has it.
148
+ averageQuotedWait: waiting === 0 ? 0 : Math.round(countOf(row.waiting_quoted) / waiting),
149
+ seatingRate: total === 0 ? 0 : Math.round((seated / total) * 1000) / 10,
150
+ }
151
+ }
152
+
153
+ export interface RestaurantWaitlistPage {
154
+ records: RestaurantWaitlistRecord[]
155
+ total: number
156
+ page: number
157
+ summary: RestaurantWaitlistSummary
158
+ }
159
+
160
+ export async function readRestaurantWaitlistPage(
161
+ query: RestaurantWaitlistListQuery,
162
+ run: CommerceSqlRunner = db,
163
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
164
+ ): Promise<RestaurantWaitlistPage> {
165
+ const { where, values } = restaurantWaitlistFilter(query, dialect)
166
+ const [counted, summary] = await Promise.all([
167
+ run.unsafe(`SELECT COUNT(*) AS total_count FROM waitlist_restaurants${where}`, values).execute(),
168
+ summarize(run, dialect),
169
+ ])
170
+ const total = countOf(sqlRows(counted)[0]?.total_count)
171
+ const page = pageWithin(query.page, total, query.perPage)
172
+ const parties = await run.unsafe(
173
+ `SELECT * FROM waitlist_restaurants${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
174
+ values,
175
+ ).execute()
176
+ return { records: await recordsFor(sqlRows(parties), run, dialect), total, page, summary }
177
+ }