@stacksjs/defaults 0.75.489 → 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.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +20 -2
- package/ai/skills/stacks-native/CATALOG.md +9 -9
- package/ai/skills/stacks-search-engine/SKILL.md +14 -0
- package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
- package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
- package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
- package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
- package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
- package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
- package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
- package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
- package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
- package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
- package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
- package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
- package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
- package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
- package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
- package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
- package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
- package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
- package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
- package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
- package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
- package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
- package/app/Actions/Dashboard/Content/content-list.ts +10 -0
- package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
- package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
- package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
- package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
- package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
- package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
- package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
- package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
- package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
- package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
- package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
- package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
- package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
- package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
- package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +5 -3
- package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
- package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
- package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
- package/app/Actions/Dashboard/named-search.test.ts +36 -0
- package/app/Actions/Dashboard/named-search.ts +80 -0
- package/app/Models/Request.ts +4 -2
- package/functions/commerce/shippings/dashboard-resource.ts +12 -1
- package/functions/commerce/shippings/delivery-routes.ts +1 -0
- package/functions/commerce/shippings/license-keys.ts +1 -0
- package/functions/dashboard-list.test.ts +132 -1
- package/functions/dashboard-list.ts +198 -1
- package/functions/queue.ts +2 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +2 -2
- package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
- package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
- package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
- package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
- package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
- package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
- package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
- package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
- package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
- package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
- package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
- package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
- package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
- package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
- package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
- package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
- package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
- package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
- package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
- package/resources/components/Dashboard/Queue/QueueDashboard.stx +7 -1
- package/routes/dashboard-api.ts +11 -0
- package/views/dashboard/stores/kanban.ts +38 -6
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { ReviewListQuery } from './commerce-review-list'
|
|
5
|
+
import { parseReviewListQuery, readReviewPage } from './commerce-review-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Reviews list against each dialect's real engine (stacksjs/stacks#3218),
|
|
10
|
+
* with the flags as each dialect stores booleans, and products and customers
|
|
11
|
+
* past the 500 the page used to read.
|
|
12
|
+
*/
|
|
13
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
14
|
+
|
|
15
|
+
const NOW = new Date('2026-11-06T12:00:00.000Z')
|
|
16
|
+
const ROWS = 600
|
|
17
|
+
const PRODUCT_NAMES: Record<number, string> = { 1: 'Coffee Beans', 2: 'apron', 3: 'Mug', 4: 'Unreviewed', 600: 'zebra Tea' }
|
|
18
|
+
const CUSTOMER_NAMES: Record<number, string> = { 5: 'zoe', 6: 'Adam', 599: 'mia' }
|
|
19
|
+
const productName = (id: number) => PRODUCT_NAMES[id] ?? `Product ${id}`
|
|
20
|
+
const customerName = (id: number) => CUSTOMER_NAMES[id] ?? `Customer ${id}`
|
|
21
|
+
|
|
22
|
+
/** 30 reviews, one an hour back from NOW; 20 and 21 share a creation time. */
|
|
23
|
+
const REVIEWS = Array.from({ length: 30 }, (_, index) => {
|
|
24
|
+
const id = index + 1
|
|
25
|
+
return {
|
|
26
|
+
id,
|
|
27
|
+
product_id: id === 29 ? null : [1, 2, 3, 600][id % 4]!,
|
|
28
|
+
customer_id: [5, 6, 599, null][id % 4] ?? null,
|
|
29
|
+
rating: id % 7 === 0 ? null : (id % 5) + 1,
|
|
30
|
+
title: id === 11 ? 'Great_100% value' : id === 12 ? 'Great 1000 value' : `Review ${id}`,
|
|
31
|
+
content: id === 17 ? 'Smells LIKE roses' : `Words for review ${id}`,
|
|
32
|
+
is_approved: id % 2 === 0,
|
|
33
|
+
is_featured: id % 5 === 0,
|
|
34
|
+
is_verified_purchase: id % 3 === 0,
|
|
35
|
+
helpful_votes: (id * 7) % 10,
|
|
36
|
+
unhelpful_votes: id % 3,
|
|
37
|
+
hoursAgo: id === 21 ? 20 : id,
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
type Review = typeof REVIEWS[number]
|
|
41
|
+
|
|
42
|
+
const ids = (reviews: Review[]) => reviews.map(review => String(review.id))
|
|
43
|
+
const newestFirst = (a: Review, b: Review) => a.hoursAgo - b.hoursAgo || b.id - a.id
|
|
44
|
+
|
|
45
|
+
function query(overrides: Partial<ReviewListQuery> = {}): ReviewListQuery {
|
|
46
|
+
return { search: '', product: '', rating: '', moderation: '', sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
50
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
51
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
52
|
+
const flag = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
|
|
53
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
54
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
55
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text})`)
|
|
56
|
+
await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text})`)
|
|
57
|
+
await run(`CREATE TABLE reviews (id ${pk}, rating INTEGER NULL, title ${text} NULL, content ${text} NULL, is_verified_purchase ${flag}, is_approved ${flag}, is_featured ${flag}, helpful_votes INTEGER, unhelpful_votes INTEGER, product_id INTEGER NULL, customer_id INTEGER NULL, created_at ${time})`)
|
|
58
|
+
const all = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
59
|
+
await run(`INSERT INTO products (id, name) VALUES ${all.map((_, i) => `(${p(2 * i + 1)}, ${p(2 * i + 2)})`).join(', ')}`, all.flatMap(id => [id, productName(id)]))
|
|
60
|
+
await run(`INSERT INTO customers (id, name, email) VALUES ${all.map((_, i) => `(${p(3 * i + 1)}, ${p(3 * i + 2)}, ${p(3 * i + 3)})`).join(', ')}`, all.flatMap(id => [id, customerName(id), `customer${id}@shop.test`]))
|
|
61
|
+
const bool = (value: boolean) => dialect === 'postgres' ? value : (value ? 1 : 0)
|
|
62
|
+
for (const review of REVIEWS) {
|
|
63
|
+
await run(
|
|
64
|
+
`INSERT INTO reviews (id, rating, title, content, is_verified_purchase, is_approved, is_featured, helpful_votes, unhelpful_votes, product_id, customer_id, created_at) VALUES (${Array.from({ length: 12 }, (_, i) => p(i + 1)).join(', ')})`,
|
|
65
|
+
[
|
|
66
|
+
review.id, review.rating, review.title, review.content, bool(review.is_verified_purchase), bool(review.is_approved),
|
|
67
|
+
bool(review.is_featured), review.helpful_votes, review.unhelpful_votes, review.product_id, review.customer_id,
|
|
68
|
+
new Date(NOW.getTime() - review.hoursAgo * 3_600_000).toISOString().slice(0, 19).replace('T', ' '),
|
|
69
|
+
],
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
75
|
+
const read = (overrides: Partial<ReviewListQuery> = {}) => readReviewPage(query(overrides), runner, dialect)
|
|
76
|
+
const all = async (overrides: Partial<ReviewListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => record.id)
|
|
77
|
+
|
|
78
|
+
// The summary counts every review, whatever the page is filtered to.
|
|
79
|
+
const filtered = await read({ moderation: 'featured' })
|
|
80
|
+
const rated = REVIEWS.flatMap(review => review.rating === null ? [] : [review.rating])
|
|
81
|
+
expect(filtered.summary).toEqual({
|
|
82
|
+
total: REVIEWS.length,
|
|
83
|
+
approved: REVIEWS.filter(review => review.is_approved).length,
|
|
84
|
+
pending: REVIEWS.filter(review => !review.is_approved).length,
|
|
85
|
+
featured: REVIEWS.filter(review => review.is_featured).length,
|
|
86
|
+
verified: REVIEWS.filter(review => review.is_verified_purchase).length,
|
|
87
|
+
averageRating: Math.round(rated.reduce((sum, rating) => sum + rating, 0) / rated.length * 10) / 10,
|
|
88
|
+
})
|
|
89
|
+
expect(filtered.total).toBe(REVIEWS.filter(review => review.is_featured).length)
|
|
90
|
+
|
|
91
|
+
// The product choices are the reviewed products, by name ignoring case.
|
|
92
|
+
expect(filtered.products).toEqual([
|
|
93
|
+
{ id: '2', label: 'apron' },
|
|
94
|
+
{ id: '1', label: 'Coffee Beans' },
|
|
95
|
+
{ id: '3', label: 'Mug' },
|
|
96
|
+
{ id: '600', label: 'zebra Tea' },
|
|
97
|
+
])
|
|
98
|
+
|
|
99
|
+
// Filters.
|
|
100
|
+
const matching = (keep: (review: Review) => boolean) => ids(REVIEWS.filter(keep).sort(newestFirst))
|
|
101
|
+
expect(await all({ product: '600' })).toEqual(matching(review => review.product_id === 600))
|
|
102
|
+
expect(await all({ rating: '5' })).toEqual(matching(review => review.rating === 5))
|
|
103
|
+
expect(await all({ rating: 'none' })).toEqual(matching(review => review.rating === null))
|
|
104
|
+
expect(await all({ moderation: 'approved' })).toEqual(matching(review => review.is_approved))
|
|
105
|
+
expect(await all({ moderation: 'pending' })).toEqual(matching(review => !review.is_approved))
|
|
106
|
+
expect(await all({ moderation: 'verified' })).toEqual(matching(review => review.is_verified_purchase))
|
|
107
|
+
expect(await all({ product: '1', moderation: 'approved' })).toEqual(matching(review => review.product_id === 1 && review.is_approved))
|
|
108
|
+
|
|
109
|
+
// Search: customer name and email, product name, title with a literal %, content, ignoring case.
|
|
110
|
+
expect(await all({ search: 'ZOE' })).toEqual(matching(review => review.customer_id === 5))
|
|
111
|
+
expect(await all({ search: 'customer599@' })).toEqual(matching(review => review.customer_id === 599))
|
|
112
|
+
expect(await all({ search: 'ZEBRA' })).toEqual(matching(review => review.product_id === 600))
|
|
113
|
+
expect(await all({ search: '100%' })).toEqual(['11'])
|
|
114
|
+
expect(await all({ search: 'like roses' })).toEqual(['17'])
|
|
115
|
+
|
|
116
|
+
// Newest first, the id breaking the tie between 20 and 21, stable across pages.
|
|
117
|
+
const newest = [...REVIEWS].sort(newestFirst)
|
|
118
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
119
|
+
expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(ids(newest))
|
|
120
|
+
expect((await read({ page: 9 })).page).toBe(3)
|
|
121
|
+
|
|
122
|
+
// Sorts: unrated last either way; ties newest first.
|
|
123
|
+
const unrated = REVIEWS.filter(review => review.rating === null).sort(newestFirst)
|
|
124
|
+
const ratedReviews = REVIEWS.filter(review => review.rating !== null)
|
|
125
|
+
expect(await all({ sort: 'rating', direction: 'desc' })).toEqual(ids([...[...ratedReviews].sort((a, b) => b.rating! - a.rating! || newestFirst(a, b)), ...unrated]))
|
|
126
|
+
expect(await all({ sort: 'rating', direction: 'asc' })).toEqual(ids([...[...ratedReviews].sort((a, b) => a.rating! - b.rating! || newestFirst(a, b)), ...unrated]))
|
|
127
|
+
expect(await all({ sort: 'helpful', direction: 'desc' })).toEqual(ids([...REVIEWS].sort((a, b) => b.helpful_votes - a.helpful_votes || newestFirst(a, b))))
|
|
128
|
+
const customerKey = (review: Review) => review.customer_id === null ? '' : customerName(review.customer_id).toLowerCase()
|
|
129
|
+
expect(await all({ sort: 'customer', direction: 'asc' })).toEqual(ids([...REVIEWS].sort((a, b) => customerKey(a).localeCompare(customerKey(b)) || newestFirst(a, b))))
|
|
130
|
+
const productKey = (review: Review) => review.product_id === null ? '' : productName(review.product_id).toLowerCase()
|
|
131
|
+
expect(await all({ sort: 'product', direction: 'asc' })).toEqual(ids([...REVIEWS].sort((a, b) => productKey(a).localeCompare(productKey(b)) || newestFirst(a, b))))
|
|
132
|
+
expect(await all({ sort: 'approved', direction: 'desc' })).toEqual(ids([...REVIEWS].sort((a, b) => Number(b.is_approved) - Number(a.is_approved) || newestFirst(a, b))))
|
|
133
|
+
|
|
134
|
+
// Products and customers past the 500th, read by the ids the page references.
|
|
135
|
+
const records = (await read({ perPage: 100 })).records
|
|
136
|
+
expect(records.find(record => record.productId === '600')).toMatchObject({ productName: 'zebra Tea' })
|
|
137
|
+
expect(records.find(record => record.customerId === '599')).toMatchObject({ customerName: 'mia', customerEmail: 'customer599@shop.test' })
|
|
138
|
+
expect(records.find(record => record.id === '29')).toMatchObject({ productId: '', productName: '' })
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
describe('readReviewPage on SQLite', () => {
|
|
142
|
+
test('summary, product choices, filters, search, sorts, pages and references', async () => {
|
|
143
|
+
const database = new Database(':memory:')
|
|
144
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
145
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
146
|
+
})
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
150
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
151
|
+
|
|
152
|
+
test.skipIf(!connection)(`readReviewPage on ${dialect}: summary, product choices, filters, search, sorts, pages and references`, async () => {
|
|
153
|
+
const url = new URL(connection!)
|
|
154
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
155
|
+
throw new Error('Review list tests require a local disposable database server')
|
|
156
|
+
|
|
157
|
+
const name = `stacks_review_list_${crypto.randomUUID().replaceAll('-', '')}`
|
|
158
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
159
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
160
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
161
|
+
const scoped = new URL(url.href)
|
|
162
|
+
scoped.pathname = `/${name}`
|
|
163
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
164
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
168
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
await database.close()
|
|
172
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
173
|
+
finally { await admin.close() }
|
|
174
|
+
}
|
|
175
|
+
}, 60_000)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
describe('parseReviewListQuery', () => {
|
|
179
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
180
|
+
|
|
181
|
+
test('defaults to every review, newest first, 25 a page', () => {
|
|
182
|
+
expect(parseReviewListQuery(reader({}))).toEqual({ search: '', product: '', rating: '', moderation: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
|
|
183
|
+
expect(parseReviewListQuery(reader({ sort: 'helpful' }))).toHaveProperty('direction', 'desc')
|
|
184
|
+
expect(parseReviewListQuery(reader({ sort: 'customer' }))).toHaveProperty('direction', 'asc')
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
test('refuses values the page does not offer', () => {
|
|
188
|
+
expect(parseReviewListQuery(reader({ product: 'abc' }))).toHaveProperty('error')
|
|
189
|
+
expect(parseReviewListQuery(reader({ rating: '6' }))).toHaveProperty('error')
|
|
190
|
+
expect(parseReviewListQuery(reader({ moderation: 'spam' }))).toHaveProperty('error')
|
|
191
|
+
expect(parseReviewListQuery(reader({ sort: 'images' }))).toHaveProperty('error')
|
|
192
|
+
})
|
|
193
|
+
})
|