@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.
- 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/ProductUnitIndexAction.ts +23 -19
- package/app/Actions/Dashboard/Commerce/ProductVariantIndexAction.ts +25 -18
- 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-unit-list.test.ts +146 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.ts +178 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.test.ts +165 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.ts +209 -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-unit-records.test.ts +0 -13
- package/app/Actions/Dashboard/Commerce/product-unit-records.ts +0 -17
- package/app/Actions/Dashboard/Commerce/product-variant-records.test.ts +0 -13
- package/app/Actions/Dashboard/Commerce/product-variant-records.ts +0 -17
- 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 +146 -1
- package/functions/dashboard-list.ts +216 -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/CommerceUnitDialog.stx +63 -8
- package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +48 -60
- package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +29 -3
- package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +57 -3
- package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +59 -61
- package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +28 -2
- 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,165 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { ProductVariantListQuery } from './commerce-product-variant-list'
|
|
5
|
+
import { parseProductVariantListQuery, readProductVariantPage } from './commerce-product-variant-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Variants list against each dialect's real engine (stacksjs/stacks#3218),
|
|
10
|
+
* with status as a real enum, options as a JSON array or a delimited list,
|
|
11
|
+
* and products past the 500 the page used to read.
|
|
12
|
+
*/
|
|
13
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
14
|
+
|
|
15
|
+
const PRODUCTS = 520
|
|
16
|
+
const STATUSES = ['active', 'inactive', 'draft'] as const
|
|
17
|
+
const TYPES = ['size', 'Color', 'material'] as const
|
|
18
|
+
const productName = (id: number) => id === 515 ? 'zebra Tea' : id === 2 ? 'Apron' : `Product ${String(id).padStart(3, '0')}`
|
|
19
|
+
|
|
20
|
+
/** How variant n stores its options: a JSON array, a comma, bar or newline list, or nothing. */
|
|
21
|
+
function optionsOf(id: number): { stored: string | null, count: number } {
|
|
22
|
+
const values = Array.from({ length: id % 5 }, (_, i) => `opt${i + 1}`)
|
|
23
|
+
if (values.length === 0)
|
|
24
|
+
return { stored: id % 2 === 0 ? null : '', count: 0 }
|
|
25
|
+
const stored = [JSON.stringify(values), values.join(', '), values.join('|'), values.join('\n')][id % 4]!
|
|
26
|
+
return { stored, count: values.length }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 30 variants, a third each status; a quarter belong to product 515 and a quarter to product 2. */
|
|
30
|
+
const VARIANTS = Array.from({ length: 30 }, (_, index) => {
|
|
31
|
+
const id = index + 1
|
|
32
|
+
return {
|
|
33
|
+
id,
|
|
34
|
+
variant: id === 9 ? 'Tall_100%' : id === 10 ? 'Tall 1000' : `${id % 2 === 0 ? 'variant' : 'Variant'} ${String(id).padStart(2, '0')}`,
|
|
35
|
+
type: TYPES[id % 3]!,
|
|
36
|
+
description: id === 17 ? 'Woven from RAFFIA' : null,
|
|
37
|
+
status: STATUSES[id % 3]!,
|
|
38
|
+
productId: id % 4 === 0 ? 515 : id % 4 === 1 ? 2 : null,
|
|
39
|
+
...optionsOf(id),
|
|
40
|
+
}
|
|
41
|
+
})
|
|
42
|
+
type Variant = typeof VARIANTS[number]
|
|
43
|
+
|
|
44
|
+
const ids = (variants: Variant[]) => variants.map(variant => String(variant.id))
|
|
45
|
+
const byName = (a: Variant, b: Variant) => a.variant.toLowerCase().localeCompare(b.variant.toLowerCase()) || a.id - b.id
|
|
46
|
+
|
|
47
|
+
function query(overrides: Partial<ProductVariantListQuery> = {}): ProductVariantListQuery {
|
|
48
|
+
return { search: '', status: '', type: '', product: '', sort: 'variant', direction: 'asc', page: 1, perPage: 10, ...overrides }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
52
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
53
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
54
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
55
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
56
|
+
const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
|
|
57
|
+
let status = text
|
|
58
|
+
if (dialect === 'postgres') {
|
|
59
|
+
await run(`CREATE TYPE variant_status AS ENUM ('active', 'inactive', 'draft')`)
|
|
60
|
+
status = 'variant_status'
|
|
61
|
+
}
|
|
62
|
+
if (dialect === 'mysql')
|
|
63
|
+
status = `ENUM('active', 'inactive', 'draft')`
|
|
64
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text})`)
|
|
65
|
+
await run(`CREATE TABLE product_variants (id ${pk}, variant ${text}, type ${text}, description ${text} NULL, options ${text} NULL, status ${status}, product_id INTEGER NULL, created_at ${time})`)
|
|
66
|
+
const all = Array.from({ length: PRODUCTS }, (_, i) => i + 1)
|
|
67
|
+
await run(`INSERT INTO products (id, name) VALUES ${rows(PRODUCTS, 2)}`, all.flatMap(id => [id, productName(id)]))
|
|
68
|
+
await run(
|
|
69
|
+
`INSERT INTO product_variants (id, variant, type, description, options, status, product_id, created_at) VALUES ${rows(VARIANTS.length, 8)}`,
|
|
70
|
+
VARIANTS.flatMap(variant => [variant.id, variant.variant, variant.type, variant.description, variant.stored, variant.status, variant.productId, `2026-10-${String(1 + variant.id % 28).padStart(2, '0')} 09:00:00`]),
|
|
71
|
+
)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
75
|
+
const read = (overrides: Partial<ProductVariantListQuery> = {}) => readProductVariantPage(query(overrides), runner, dialect)
|
|
76
|
+
const all = async (overrides: Partial<ProductVariantListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => record.id)
|
|
77
|
+
const matching = (keep: (variant: Variant) => boolean) => ids(VARIANTS.filter(keep).sort(byName))
|
|
78
|
+
|
|
79
|
+
// The summary and choices describe every variant, whatever the page is filtered to.
|
|
80
|
+
const filtered = await read({ status: 'inactive' })
|
|
81
|
+
expect(filtered.summary).toEqual({
|
|
82
|
+
total: VARIANTS.length,
|
|
83
|
+
active: VARIANTS.filter(variant => variant.status === 'active').length,
|
|
84
|
+
draft: VARIANTS.filter(variant => variant.status === 'draft').length,
|
|
85
|
+
linkedProducts: 2,
|
|
86
|
+
})
|
|
87
|
+
expect(filtered.types).toEqual(['Color', 'material', 'size'])
|
|
88
|
+
expect(filtered.products).toEqual([{ id: '2', name: 'Apron' }, { id: '515', name: 'zebra Tea' }])
|
|
89
|
+
expect(filtered.total).toBe(VARIANTS.filter(variant => variant.status === 'inactive').length)
|
|
90
|
+
|
|
91
|
+
// Filters and search: a literal %, the description, the product and the options text.
|
|
92
|
+
expect(await all({ product: '515' })).toEqual(matching(variant => variant.productId === 515))
|
|
93
|
+
expect(await all({ type: 'Color', status: 'draft' })).toEqual(matching(variant => variant.type === 'Color' && variant.status === 'draft'))
|
|
94
|
+
expect(await all({ search: '100%' })).toEqual(['9'])
|
|
95
|
+
expect(await all({ search: 'raffia' })).toEqual(['17'])
|
|
96
|
+
expect(await all({ search: 'ZEBRA' })).toEqual(matching(variant => variant.productId === 515))
|
|
97
|
+
expect(await all({ search: 'opt4' })).toEqual(matching(variant => variant.count >= 4))
|
|
98
|
+
|
|
99
|
+
// By name ignoring case, stable across pages.
|
|
100
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
101
|
+
expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(ids([...VARIANTS].sort(byName)))
|
|
102
|
+
|
|
103
|
+
// Most options first, whatever the list is stored as; ties by name.
|
|
104
|
+
expect(await all({ sort: 'options', direction: 'desc' })).toEqual(ids([...VARIANTS].sort((a, b) => b.count - a.count || byName(a, b))))
|
|
105
|
+
const product = (variant: Variant) => variant.productId ? productName(variant.productId).toLowerCase() : ''
|
|
106
|
+
expect(await all({ sort: 'product' })).toEqual(ids([...VARIANTS].sort((a, b) => product(a).localeCompare(product(b)) || byName(a, b))))
|
|
107
|
+
expect(await all({ sort: 'status' })).toEqual(ids([...VARIANTS].sort((a, b) => a.status.localeCompare(b.status) || byName(a, b))))
|
|
108
|
+
|
|
109
|
+
// The records parse every stored form; a product past the 500th is named.
|
|
110
|
+
const records = (await read({ perPage: 100 })).records
|
|
111
|
+
for (const variant of VARIANTS)
|
|
112
|
+
expect(records.find(record => record.id === String(variant.id))?.options.length).toBe(variant.count)
|
|
113
|
+
expect(records.find(record => record.productId === '515')?.productName).toBe('zebra Tea')
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
describe('readProductVariantPage on SQLite', () => {
|
|
117
|
+
test('summary, choices, filters, search, sorts, pages and products', async () => {
|
|
118
|
+
const database = new Database(':memory:')
|
|
119
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
120
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
121
|
+
})
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
125
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
126
|
+
|
|
127
|
+
test.skipIf(!connection)(`readProductVariantPage on ${dialect}: summary, choices, filters, search, sorts, pages and products`, async () => {
|
|
128
|
+
const url = new URL(connection!)
|
|
129
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
130
|
+
throw new Error('Product variant list tests require a local disposable database server')
|
|
131
|
+
|
|
132
|
+
const name = `stacks_product_variants_${crypto.randomUUID().replaceAll('-', '')}`
|
|
133
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
134
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
135
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
136
|
+
const scoped = new URL(url.href)
|
|
137
|
+
scoped.pathname = `/${name}`
|
|
138
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
139
|
+
|
|
140
|
+
try {
|
|
141
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
142
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
await database.close()
|
|
146
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
147
|
+
finally { await admin.close() }
|
|
148
|
+
}
|
|
149
|
+
}, 60_000)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
describe('parseProductVariantListQuery', () => {
|
|
153
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
154
|
+
|
|
155
|
+
test('defaults to every variant by name, 25 a page', () => {
|
|
156
|
+
expect(parseProductVariantListQuery(reader({}))).toEqual({ search: '', status: '', type: '', product: '', sort: 'variant', direction: 'asc', page: 1, perPage: 25 })
|
|
157
|
+
expect(parseProductVariantListQuery(reader({ sort: 'options' }))).toHaveProperty('direction', 'desc')
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
test('refuses values the page does not offer', () => {
|
|
161
|
+
expect(parseProductVariantListQuery(reader({ status: 'archived' }))).toHaveProperty('error')
|
|
162
|
+
expect(parseProductVariantListQuery(reader({ product: 'tea' }))).toHaveProperty('error')
|
|
163
|
+
expect(parseProductVariantListQuery(reader({ sort: 'sku' }))).toHaveProperty('error')
|
|
164
|
+
})
|
|
165
|
+
})
|
|
@@ -0,0 +1,209 @@
|
|
|
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 { ProductVariantRecord, ProductVariantSummary } from './product-variant-records'
|
|
9
|
+
import { normalizeProductVariantRecord } from './product-variant-records'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One page of product variants, searched, filtered, sorted and counted by the
|
|
13
|
+
* database, with the summary of every variant, every variant type, and every
|
|
14
|
+
* product that has a variant (stacksjs/stacks#3218).
|
|
15
|
+
*
|
|
16
|
+
* The Variants page used to read the newest 500 variants and do all of that
|
|
17
|
+
* in the browser, so an older variant could not be found, its cards counted
|
|
18
|
+
* those 500, and the type filter only knew those 500's types. It also read
|
|
19
|
+
* the first 500 products by name, for the product filter, the dialog's
|
|
20
|
+
* product select and to name each variant's product, so a variant of any
|
|
21
|
+
* later product failed the whole page.
|
|
22
|
+
*/
|
|
23
|
+
export const PRODUCT_VARIANT_SORTS = ['variant', 'product', 'options', 'status', 'newest', 'created'] as const
|
|
24
|
+
export type ProductVariantSort = typeof PRODUCT_VARIANT_SORTS[number]
|
|
25
|
+
|
|
26
|
+
export const PRODUCT_VARIANT_STATUSES = ['active', 'inactive', 'draft'] as const
|
|
27
|
+
|
|
28
|
+
export interface ProductVariantListQuery {
|
|
29
|
+
search: string
|
|
30
|
+
/** '' for any. */
|
|
31
|
+
status: '' | typeof PRODUCT_VARIANT_STATUSES[number]
|
|
32
|
+
/** A variant type, or '' for any. */
|
|
33
|
+
type: string
|
|
34
|
+
/** A product id, or '' for any. */
|
|
35
|
+
product: string
|
|
36
|
+
sort: ProductVariantSort
|
|
37
|
+
direction: 'asc' | 'desc'
|
|
38
|
+
page: number
|
|
39
|
+
perPage: number
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function parseProductVariantListQuery(read: QueryReader): ProductVariantListQuery | { error: string } {
|
|
43
|
+
const pageText = queryText(read, 'page')
|
|
44
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
45
|
+
if (!Number.isInteger(page) || page < 1)
|
|
46
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
47
|
+
|
|
48
|
+
const sizeText = queryText(read, 'per_page')
|
|
49
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
50
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
51
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
52
|
+
|
|
53
|
+
const sort = queryText(read, 'sort') || 'variant'
|
|
54
|
+
if (!(PRODUCT_VARIANT_SORTS as readonly string[]).includes(sort))
|
|
55
|
+
return { error: `sort must be one of ${PRODUCT_VARIANT_SORTS.join(', ')}.` }
|
|
56
|
+
|
|
57
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
58
|
+
const direction = directionText === '' ? (['options', 'newest', 'created'].includes(sort) ? 'desc' : 'asc') : directionText
|
|
59
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
60
|
+
return { error: 'direction must be asc or desc.' }
|
|
61
|
+
|
|
62
|
+
const search = queryText(read, 'q')
|
|
63
|
+
if (search.length > 200)
|
|
64
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
65
|
+
|
|
66
|
+
const status = queryText(read, 'status')
|
|
67
|
+
if (status && !(PRODUCT_VARIANT_STATUSES as readonly string[]).includes(status))
|
|
68
|
+
return { error: `status must be one of ${PRODUCT_VARIANT_STATUSES.join(', ')}.` }
|
|
69
|
+
|
|
70
|
+
const type = queryText(read, 'type')
|
|
71
|
+
if (type.length > 100)
|
|
72
|
+
return { error: 'type must be 100 characters or fewer.' }
|
|
73
|
+
|
|
74
|
+
const product = queryText(read, 'product')
|
|
75
|
+
if (product && !/^\d+$/.test(product))
|
|
76
|
+
return { error: 'product must be a product id.' }
|
|
77
|
+
|
|
78
|
+
return { search, status: status as ProductVariantListQuery['status'], type, product, sort: sort as ProductVariantSort, direction, page, perPage }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const FROM = ' FROM product_variants v LEFT JOIN products p ON p.id = v.product_id'
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* How many options a variant lists. `options` is text holding a JSON array
|
|
85
|
+
* or a list split by commas, bars, semicolons or new lines, as
|
|
86
|
+
* commerceStringList reads it; an array is measured by the dialect's JSON
|
|
87
|
+
* functions and a list by its separators. A list that repeats an option, which
|
|
88
|
+
* the page shows once, counts it each time.
|
|
89
|
+
*/
|
|
90
|
+
function optionCount(dialect: QueryBuilderDialect): string {
|
|
91
|
+
const column = `COALESCE(TRIM(v.options), '')`
|
|
92
|
+
const json = dialect === 'postgres'
|
|
93
|
+
? `json_array_length(CAST(v.options AS JSON))`
|
|
94
|
+
: dialect === 'sqlite' ? 'json_array_length(v.options)' : 'JSON_LENGTH(v.options)'
|
|
95
|
+
const newline = dialect === 'sqlite' ? 'char(10)' : dialect === 'postgres' ? 'chr(10)' : 'CHAR(10)'
|
|
96
|
+
const stripped = `REPLACE(REPLACE(REPLACE(REPLACE(${column}, ',', ''), '|', ''), ';', ''), ${newline}, '')`
|
|
97
|
+
return `CASE WHEN ${column} = '' THEN 0 WHEN ${column} LIKE '[%' THEN ${json} ELSE LENGTH(${column}) - LENGTH(${stripped}) + 1 END`
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function sortExpression(sort: ProductVariantSort, dialect: QueryBuilderDialect): string {
|
|
101
|
+
switch (sort) {
|
|
102
|
+
case 'product': return `LOWER(COALESCE(p.name, ''))`
|
|
103
|
+
case 'options': return optionCount(dialect)
|
|
104
|
+
// As text: PostgreSQL and MySQL keep the status as an enum, which sorts by declaration order.
|
|
105
|
+
case 'status': return asText('v.status', dialect)
|
|
106
|
+
case 'newest': return 'v.id'
|
|
107
|
+
case 'created': return 'v.created_at'
|
|
108
|
+
default: return 'LOWER(v.variant)'
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function productVariantFilter(query: Pick<ProductVariantListQuery, 'search' | 'status' | 'type' | 'product'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
113
|
+
const { bind, values } = binder(dialect)
|
|
114
|
+
const clauses: string[] = []
|
|
115
|
+
if (query.status)
|
|
116
|
+
clauses.push(`${asText('v.status', dialect)} = ${bind(query.status)}`)
|
|
117
|
+
if (query.type)
|
|
118
|
+
clauses.push(`v.type = ${bind(query.type)}`)
|
|
119
|
+
if (query.product)
|
|
120
|
+
clauses.push(`v.product_id = ${bind(Number(query.product))}`)
|
|
121
|
+
if (query.search) {
|
|
122
|
+
const pattern = containsPattern(query.search)
|
|
123
|
+
const columns = ['v.variant', 'v.type', `COALESCE(v.description, '')`, `COALESCE(p.name, '')`, `COALESCE(v.options, '')`]
|
|
124
|
+
clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
125
|
+
}
|
|
126
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function orderBy(query: Pick<ProductVariantListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
130
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
131
|
+
// Ties read by name, as the page sorted them; the id breaks every
|
|
132
|
+
// remaining tie, so pages never repeat or skip a variant.
|
|
133
|
+
if (query.sort === 'newest')
|
|
134
|
+
return ` ORDER BY v.id ${direction}`
|
|
135
|
+
const byName = query.sort === 'variant' ? '' : ', LOWER(v.variant) ASC'
|
|
136
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}${byName}, v.id ${direction}`
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function productNames(rows: unknown): Map<string, string> {
|
|
140
|
+
return new Map(sqlRows(rows).map((row) => {
|
|
141
|
+
const id = commerceIdentifier(commerceValue(row, 'id'), 'Product')
|
|
142
|
+
return [id, commerceRequiredString(commerceValue(row, 'name'), `Product ${id}`, 'name')]
|
|
143
|
+
}))
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Variants turned into records, against exactly the products they reference. */
|
|
147
|
+
async function recordsFor(variants: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ProductVariantRecord[]> {
|
|
148
|
+
if (variants.length === 0)
|
|
149
|
+
return []
|
|
150
|
+
const productIds = referencedIds(variants, 'product_id')
|
|
151
|
+
const products = productIds.length > 0
|
|
152
|
+
? await run.unsafe(`SELECT id, name FROM products WHERE id IN (${idPlaceholders(productIds, dialect)})`, productIds).execute()
|
|
153
|
+
: []
|
|
154
|
+
const names = productNames(products)
|
|
155
|
+
return variants.map(variant => normalizeProductVariantRecord(variant, names))
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The summary cards, over every variant as before. */
|
|
159
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ProductVariantSummary> {
|
|
160
|
+
const status = asText('status', dialect)
|
|
161
|
+
const row = sqlRows(await run.unsafe(
|
|
162
|
+
`SELECT COUNT(*) AS total_count, SUM(CASE WHEN ${status} = 'active' THEN 1 ELSE 0 END) AS active_count, SUM(CASE WHEN ${status} = 'draft' THEN 1 ELSE 0 END) AS draft_count, COUNT(DISTINCT product_id) AS product_count FROM product_variants`,
|
|
163
|
+
).execute())[0] ?? {}
|
|
164
|
+
return {
|
|
165
|
+
total: countOf(row.total_count),
|
|
166
|
+
active: countOf(row.active_count),
|
|
167
|
+
draft: countOf(row.draft_count),
|
|
168
|
+
linkedProducts: countOf(row.product_count),
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export interface ProductVariantPage {
|
|
173
|
+
records: ProductVariantRecord[]
|
|
174
|
+
total: number
|
|
175
|
+
page: number
|
|
176
|
+
summary: ProductVariantSummary
|
|
177
|
+
/** Every type any variant has, for the filter and the dialog's suggestions. */
|
|
178
|
+
types: string[]
|
|
179
|
+
/** Every product that has a variant, for the product filter, by name ignoring case. */
|
|
180
|
+
products: Array<{ id: string, name: string }>
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export async function readProductVariantPage(
|
|
184
|
+
query: ProductVariantListQuery,
|
|
185
|
+
run: CommerceSqlRunner = db,
|
|
186
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
187
|
+
): Promise<ProductVariantPage> {
|
|
188
|
+
const { where, values } = productVariantFilter(query, dialect)
|
|
189
|
+
const [counted, summary, typeRows, productRows] = await Promise.all([
|
|
190
|
+
run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
|
|
191
|
+
summarize(run, dialect),
|
|
192
|
+
run.unsafe(`SELECT DISTINCT type AS value FROM product_variants WHERE type IS NOT NULL AND type <> ''`).execute(),
|
|
193
|
+
run.unsafe('SELECT p.id, p.name FROM products p WHERE EXISTS (SELECT 1 FROM product_variants v WHERE v.product_id = p.id) ORDER BY LOWER(p.name) ASC, p.id ASC').execute(),
|
|
194
|
+
])
|
|
195
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
196
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
197
|
+
const variants = await run.unsafe(
|
|
198
|
+
`SELECT v.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
199
|
+
values,
|
|
200
|
+
).execute()
|
|
201
|
+
return {
|
|
202
|
+
records: await recordsFor(sqlRows(variants), run, dialect),
|
|
203
|
+
total,
|
|
204
|
+
page,
|
|
205
|
+
summary,
|
|
206
|
+
types: [...new Set(sqlRows(typeRows).map(row => String(row.value ?? '').trim()).filter(Boolean))].sort(),
|
|
207
|
+
products: [...productNames(productRows)].map(([id, name]) => ({ id, name })),
|
|
208
|
+
}
|
|
209
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { ProductWaitlistListQuery } from './commerce-product-waitlist-list'
|
|
5
|
+
import { parseProductWaitlistListQuery, readProductWaitlistPage } from './commerce-product-waitlist-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The product waitlist against each dialect's real engine
|
|
10
|
+
* (stacksjs/stacks#3218), with status and preference as real enums, and
|
|
11
|
+
* products and 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 ROWS = 600
|
|
17
|
+
const STATUSES = ['waiting', 'notified', 'purchased', 'cancelled'] as const
|
|
18
|
+
const PREFERENCES = ['sms', 'email', 'both'] as const
|
|
19
|
+
const PRODUCT_NAMES: Record<number, string> = { 1: 'Coffee Beans', 2: 'apron', 600: 'zebra Tea' }
|
|
20
|
+
const productName = (id: number) => PRODUCT_NAMES[id] ?? `Product ${id}`
|
|
21
|
+
const NAMES = ['ann', 'Ben', 'cat', 'Dan', 'eve']
|
|
22
|
+
|
|
23
|
+
/** 26 entries, one an hour back from NOW; 14 and 15 share a creation time. */
|
|
24
|
+
const ENTRIES = Array.from({ length: 26 }, (_, index) => {
|
|
25
|
+
const id = index + 1
|
|
26
|
+
return {
|
|
27
|
+
id,
|
|
28
|
+
name: id === 9 ? 'Sale_100% Fan' : id === 10 ? 'Sale 1000 Fan' : NAMES[id % NAMES.length]!,
|
|
29
|
+
email: `waiter${id}@shop.test`,
|
|
30
|
+
phone: id === 21 ? '+1 555 0199' : null,
|
|
31
|
+
quantity: (id * 3) % 7 + 1,
|
|
32
|
+
notification_preference: PREFERENCES[id % PREFERENCES.length]!,
|
|
33
|
+
source: id === 17 ? 'in-store' : 'website',
|
|
34
|
+
status: STATUSES[id % STATUSES.length]!,
|
|
35
|
+
product_id: [1, 2, 600][id % 3]!,
|
|
36
|
+
customer_id: id % 5 === 0 ? 599 : null,
|
|
37
|
+
hoursAgo: id === 15 ? 14 : id,
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
type Entry = typeof ENTRIES[number]
|
|
41
|
+
|
|
42
|
+
const ids = (entries: Entry[]) => entries.map(entry => String(entry.id))
|
|
43
|
+
const newestFirst = (a: Entry, b: Entry) => a.hoursAgo - b.hoursAgo || b.id - a.id
|
|
44
|
+
|
|
45
|
+
function query(overrides: Partial<ProductWaitlistListQuery> = {}): ProductWaitlistListQuery {
|
|
46
|
+
return { search: '', status: '', 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 time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
53
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
54
|
+
let statusType = text
|
|
55
|
+
let preferenceType = text
|
|
56
|
+
if (dialect === 'postgres') {
|
|
57
|
+
// Declared out of alphabetical order, so a sort that forgets the text cast shows.
|
|
58
|
+
await run(`CREATE TYPE waitlist_status AS ENUM ('waiting', 'notified', 'purchased', 'cancelled')`)
|
|
59
|
+
await run(`CREATE TYPE waitlist_preference AS ENUM ('sms', 'email', 'both')`)
|
|
60
|
+
statusType = 'waitlist_status'
|
|
61
|
+
preferenceType = 'waitlist_preference'
|
|
62
|
+
}
|
|
63
|
+
if (dialect === 'mysql') {
|
|
64
|
+
statusType = `ENUM('waiting', 'notified', 'purchased', 'cancelled')`
|
|
65
|
+
preferenceType = `ENUM('sms', 'email', 'both')`
|
|
66
|
+
}
|
|
67
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text})`)
|
|
68
|
+
await run(`CREATE TABLE customers (id ${pk})`)
|
|
69
|
+
await run(`CREATE TABLE waitlist_products (id ${pk}, name ${text}, email ${text}, phone ${text} NULL, quantity INTEGER, notification_preference ${preferenceType}, source ${text}, notes ${text} NULL, status ${statusType}, product_id INTEGER NULL, customer_id INTEGER NULL, created_at ${time})`)
|
|
70
|
+
const all = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
71
|
+
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)]))
|
|
72
|
+
await run(`INSERT INTO customers (id) VALUES ${all.map((_, i) => `(${p(i + 1)})`).join(', ')}`, all)
|
|
73
|
+
for (const entry of ENTRIES) {
|
|
74
|
+
await run(
|
|
75
|
+
`INSERT INTO waitlist_products (id, name, email, phone, quantity, notification_preference, source, status, product_id, customer_id, created_at) VALUES (${Array.from({ length: 11 }, (_, i) => p(i + 1)).join(', ')})`,
|
|
76
|
+
[
|
|
77
|
+
entry.id, entry.name, entry.email, entry.phone, entry.quantity, entry.notification_preference, entry.source, entry.status,
|
|
78
|
+
entry.product_id, entry.customer_id, new Date(NOW.getTime() - entry.hoursAgo * 3_600_000).toISOString().slice(0, 19).replace('T', ' '),
|
|
79
|
+
],
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
85
|
+
const read = (overrides: Partial<ProductWaitlistListQuery> = {}) => readProductWaitlistPage(query(overrides), runner, dialect)
|
|
86
|
+
const all = async (overrides: Partial<ProductWaitlistListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => record.id)
|
|
87
|
+
const matching = (keep: (entry: Entry) => boolean) => ids(ENTRIES.filter(keep).sort(newestFirst))
|
|
88
|
+
|
|
89
|
+
// The summary counts every entry, whatever the page is filtered to.
|
|
90
|
+
const filtered = await read({ status: 'cancelled' })
|
|
91
|
+
const purchased = ENTRIES.filter(entry => entry.status === 'purchased').length
|
|
92
|
+
expect(filtered.summary).toEqual({
|
|
93
|
+
total: ENTRIES.length,
|
|
94
|
+
waiting: ENTRIES.filter(entry => entry.status === 'waiting').length,
|
|
95
|
+
notified: ENTRIES.filter(entry => entry.status === 'notified').length,
|
|
96
|
+
purchased,
|
|
97
|
+
conversionRate: Math.round((purchased / ENTRIES.length) * 100),
|
|
98
|
+
})
|
|
99
|
+
expect(filtered.total).toBe(ENTRIES.filter(entry => entry.status === 'cancelled').length)
|
|
100
|
+
|
|
101
|
+
// Search: name with a literal %, email, phone, source, product name and id, ignoring case.
|
|
102
|
+
expect(await all({ search: '100%' })).toEqual(['9'])
|
|
103
|
+
expect(await all({ search: 'WAITER21@' })).toEqual(['21'])
|
|
104
|
+
expect(await all({ search: '0199' })).toEqual(['21'])
|
|
105
|
+
expect(await all({ search: 'IN-STORE' })).toEqual(['17'])
|
|
106
|
+
expect(await all({ search: 'ZEBRA' })).toEqual(matching(entry => entry.product_id === 600))
|
|
107
|
+
expect(await all({ search: 'zebra', status: 'waiting' })).toEqual(matching(entry => entry.product_id === 600 && entry.status === 'waiting'))
|
|
108
|
+
|
|
109
|
+
// Newest first, the id breaking the tie between 14 and 15, stable across pages.
|
|
110
|
+
const newest = [...ENTRIES].sort(newestFirst)
|
|
111
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
112
|
+
expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(ids(newest))
|
|
113
|
+
expect((await read({ page: 9 })).page).toBe(3)
|
|
114
|
+
|
|
115
|
+
// Sorts, ties newest first. Status and preference sort by name, not enum order.
|
|
116
|
+
const by = (key: (entry: Entry) => string | number, direction: 1 | -1 = 1) => (a: Entry, b: Entry) => {
|
|
117
|
+
const left = key(a)
|
|
118
|
+
const right = key(b)
|
|
119
|
+
const order = typeof left === 'number' ? (left - (right as number)) : left.localeCompare(right as string)
|
|
120
|
+
return order * direction || newestFirst(a, b)
|
|
121
|
+
}
|
|
122
|
+
expect(await all({ sort: 'name', direction: 'asc' })).toEqual(ids([...ENTRIES].sort(by(entry => entry.name.toLowerCase()))))
|
|
123
|
+
expect(await all({ sort: 'product', direction: 'asc' })).toEqual(ids([...ENTRIES].sort(by(entry => productName(entry.product_id).toLowerCase()))))
|
|
124
|
+
expect(await all({ sort: 'quantity', direction: 'desc' })).toEqual(ids([...ENTRIES].sort(by(entry => entry.quantity, -1))))
|
|
125
|
+
expect(await all({ sort: 'status', direction: 'asc' })).toEqual(ids([...ENTRIES].sort(by(entry => entry.status))))
|
|
126
|
+
expect(await all({ sort: 'preference', direction: 'asc' })).toEqual(ids([...ENTRIES].sort(by(entry => entry.notification_preference))))
|
|
127
|
+
|
|
128
|
+
// Products and customers past the 500th, read by the ids the page references.
|
|
129
|
+
const records = (await read({ perPage: 100 })).records
|
|
130
|
+
expect(records.find(record => record.productId === '600')).toMatchObject({ productName: 'zebra Tea' })
|
|
131
|
+
expect(records.find(record => record.customerId === '599')).toBeDefined()
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
describe('readProductWaitlistPage on SQLite', () => {
|
|
135
|
+
test('summary, filters, search, sorts, pages and references', async () => {
|
|
136
|
+
const database = new Database(':memory:')
|
|
137
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
138
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
139
|
+
})
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
143
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
144
|
+
|
|
145
|
+
test.skipIf(!connection)(`readProductWaitlistPage on ${dialect}: summary, filters, search, sorts, pages and references`, async () => {
|
|
146
|
+
const url = new URL(connection!)
|
|
147
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
148
|
+
throw new Error('Product waitlist list tests require a local disposable database server')
|
|
149
|
+
|
|
150
|
+
const name = `stacks_product_waitlist_${crypto.randomUUID().replaceAll('-', '')}`
|
|
151
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
152
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
153
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
154
|
+
const scoped = new URL(url.href)
|
|
155
|
+
scoped.pathname = `/${name}`
|
|
156
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
157
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
158
|
+
|
|
159
|
+
try {
|
|
160
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
161
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
await database.close()
|
|
165
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
166
|
+
finally { await admin.close() }
|
|
167
|
+
}
|
|
168
|
+
}, 60_000)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
describe('parseProductWaitlistListQuery', () => {
|
|
172
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
173
|
+
|
|
174
|
+
test('defaults to every entry, newest first, 25 a page', () => {
|
|
175
|
+
expect(parseProductWaitlistListQuery(reader({}))).toEqual({ search: '', status: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
|
|
176
|
+
expect(parseProductWaitlistListQuery(reader({ sort: 'name' }))).toHaveProperty('direction', 'asc')
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
test('refuses values the page does not offer', () => {
|
|
180
|
+
expect(parseProductWaitlistListQuery(reader({ status: 'seated' }))).toHaveProperty('error')
|
|
181
|
+
expect(parseProductWaitlistListQuery(reader({ sort: 'notes' }))).toHaveProperty('error')
|
|
182
|
+
})
|
|
183
|
+
})
|