@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,184 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { LicenseKeyListQuery } from './commerce-license-key-list'
|
|
5
|
+
import { parseLicenseKeyListQuery, readLicenseKeyPage, searchLicenseKeyChoices } from './commerce-license-key-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Licence Keys list and its dialog's choices against each dialect's real
|
|
10
|
+
* engine (stacksjs/stacks#3218), with template and status as real enums, over
|
|
11
|
+
* 520 customers, products and orders: the page used to read the first 500 of
|
|
12
|
+
* each.
|
|
13
|
+
*/
|
|
14
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
15
|
+
|
|
16
|
+
const NOW = new Date('2026-11-06T12:00:00.000Z')
|
|
17
|
+
const DAY = 86_400_000
|
|
18
|
+
const ROWS = 520
|
|
19
|
+
const TEMPLATES = ['Standard License', 'Premium License', 'Enterprise License'] as const
|
|
20
|
+
const STATUSES = ['active', 'inactive', 'unassigned'] as const
|
|
21
|
+
const stamp = (ms: number) => new Date(ms).toISOString().slice(0, 19).replace('T', ' ')
|
|
22
|
+
const customerName = (id: number) => id === 515 ? 'zelda Late' : id === 3 ? 'Zed early' : `Customer ${String(id).padStart(3, '0')}`
|
|
23
|
+
|
|
24
|
+
/** 30 keys, one a day back from NOW; 11 and 12 share a creation time. */
|
|
25
|
+
const KEYS = Array.from({ length: 30 }, (_, index) => {
|
|
26
|
+
const id = index + 1
|
|
27
|
+
const group = (n: number) => String(n).padStart(4, '0')
|
|
28
|
+
return {
|
|
29
|
+
id,
|
|
30
|
+
key: `K${group(id).slice(1)}-AAAA-BBBB-CCCC-${id === 9 ? 'X1X0' : group(id)}`,
|
|
31
|
+
template: TEMPLATES[id % 3]!,
|
|
32
|
+
status: STATUSES[id % 3]!,
|
|
33
|
+
customerId: id % 4 === 0 ? 515 : id % 4 === 1 ? 3 : null,
|
|
34
|
+
productId: id % 5 === 0 ? 520 : null,
|
|
35
|
+
orderId: id % 6 === 0 ? 510 : null,
|
|
36
|
+
// Day offsets around the 30-day window: some inside, some past, some long gone.
|
|
37
|
+
expiryDays: [-5, 1, 10, 29, 31, 90][id % 6]!,
|
|
38
|
+
daysAgo: id === 12 ? 11 : id,
|
|
39
|
+
}
|
|
40
|
+
})
|
|
41
|
+
type Key = typeof KEYS[number]
|
|
42
|
+
|
|
43
|
+
const ids = (keys: Key[]) => keys.map(key => String(key.id))
|
|
44
|
+
const newestFirst = (a: Key, b: Key) => a.daysAgo - b.daysAgo || b.id - a.id
|
|
45
|
+
|
|
46
|
+
function query(overrides: Partial<LicenseKeyListQuery> = {}): LicenseKeyListQuery {
|
|
47
|
+
return { search: '', sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
51
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
52
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
53
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
54
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
55
|
+
const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
|
|
56
|
+
const enumOf = (values: readonly string[]) => values.map(value => `'${value}'`).join(', ')
|
|
57
|
+
let template = text
|
|
58
|
+
let status = text
|
|
59
|
+
if (dialect === 'postgres') {
|
|
60
|
+
await run(`CREATE TYPE key_template AS ENUM (${enumOf(TEMPLATES)})`)
|
|
61
|
+
await run(`CREATE TYPE key_status AS ENUM (${enumOf(STATUSES)})`)
|
|
62
|
+
template = 'key_template'
|
|
63
|
+
status = 'key_status'
|
|
64
|
+
}
|
|
65
|
+
if (dialect === 'mysql') {
|
|
66
|
+
template = `ENUM(${enumOf(TEMPLATES)})`
|
|
67
|
+
status = `ENUM(${enumOf(STATUSES)})`
|
|
68
|
+
}
|
|
69
|
+
await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text})`)
|
|
70
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text})`)
|
|
71
|
+
await run(`CREATE TABLE orders (id ${pk}, status ${text})`)
|
|
72
|
+
await run(`CREATE TABLE license_keys (id ${pk}, ${dialect === 'mysql' ? '`key`' : 'key'} ${text}, template ${template}, expiry_date ${time}, status ${status}, customer_id INTEGER NULL, product_id INTEGER NULL, order_id INTEGER NULL, created_at ${time}, updated_at ${time} NULL, uuid ${text} NULL)`)
|
|
73
|
+
const all = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
74
|
+
await run(`INSERT INTO customers (id, name, email) VALUES ${rows(ROWS, 3)}`, all.flatMap(id => [id, customerName(id), `buyer${id}@shop.test`]))
|
|
75
|
+
await run(`INSERT INTO products (id, name) VALUES ${rows(ROWS, 2)}`, all.flatMap(id => [id, id === 520 ? 'Zebra Suite' : `Product ${String(id).padStart(3, '0')}`]))
|
|
76
|
+
await run(`INSERT INTO orders (id, status) VALUES ${rows(ROWS, 2)}`, all.flatMap(id => [id, id === 510 ? 'refunded' : 'completed']))
|
|
77
|
+
const keyColumn = dialect === 'mysql' ? '`key`' : 'key'
|
|
78
|
+
await run(
|
|
79
|
+
`INSERT INTO license_keys (id, ${keyColumn}, template, expiry_date, status, customer_id, product_id, order_id, created_at) VALUES ${rows(KEYS.length, 9)}`,
|
|
80
|
+
KEYS.flatMap(key => [key.id, key.key, key.template, stamp(NOW.getTime() + key.expiryDays * DAY), key.status, key.customerId, key.productId, key.orderId, stamp(NOW.getTime() - key.daysAgo * DAY)]),
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
85
|
+
const read = (overrides: Partial<LicenseKeyListQuery> = {}) => readLicenseKeyPage(query(overrides), runner, dialect, NOW)
|
|
86
|
+
const all = async (overrides: Partial<LicenseKeyListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => String(record.id))
|
|
87
|
+
const matching = (keep: (key: Key) => boolean) => ids(KEYS.filter(keep).sort(newestFirst))
|
|
88
|
+
|
|
89
|
+
// The summary counts every key, whatever the page is searched for.
|
|
90
|
+
const searched = await read({ search: 'zelda' })
|
|
91
|
+
expect(searched.summary).toEqual({
|
|
92
|
+
total: KEYS.length,
|
|
93
|
+
active: KEYS.filter(key => key.status === 'active').length,
|
|
94
|
+
assigned: KEYS.filter(key => key.customerId || key.productId || key.orderId).length,
|
|
95
|
+
expiring: KEYS.filter(key => key.expiryDays >= 0 && key.expiryDays <= 30).length,
|
|
96
|
+
})
|
|
97
|
+
expect(searched.total).toBe(KEYS.filter(key => key.customerId === 515).length)
|
|
98
|
+
|
|
99
|
+
// Search: the key with a digit pattern, the customer's name and email, the product, the order id, the enums.
|
|
100
|
+
expect(await all({ search: 'x1x0' })).toEqual(['9'])
|
|
101
|
+
expect(await all({ search: 'BUYER515@' })).toEqual(matching(key => key.customerId === 515))
|
|
102
|
+
expect(await all({ search: 'zebra suite' })).toEqual(matching(key => key.productId === 520))
|
|
103
|
+
expect(await all({ search: '510' })).toEqual(matching(key => key.orderId === 510))
|
|
104
|
+
expect(await all({ search: 'ENTERPRISE' })).toEqual(matching(key => key.template === 'Enterprise License'))
|
|
105
|
+
|
|
106
|
+
// Newest first, the id breaking the tie between 11 and 12, stable across pages.
|
|
107
|
+
const newest = [...KEYS].sort(newestFirst)
|
|
108
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
109
|
+
expect(pages.flatMap(result => result.records.map(record => String(record.id)))).toEqual(ids(newest))
|
|
110
|
+
|
|
111
|
+
// Sorts by name, not enum order; ties newest first.
|
|
112
|
+
const by = (value: (key: Key) => string) => (a: Key, b: Key) => value(a).localeCompare(value(b)) || newestFirst(a, b)
|
|
113
|
+
expect(await all({ sort: 'template', direction: 'asc' })).toEqual(ids([...KEYS].sort(by(key => key.template))))
|
|
114
|
+
expect(await all({ sort: 'status', direction: 'asc' })).toEqual(ids([...KEYS].sort(by(key => key.status))))
|
|
115
|
+
expect(await all({ sort: 'customer', direction: 'asc' })).toEqual(ids([...KEYS].sort(by(key => key.customerId ? customerName(key.customerId).toLowerCase() : ''))))
|
|
116
|
+
|
|
117
|
+
// The links past the 500th come with the key.
|
|
118
|
+
const linked = (await read({ search: 'BUYER515@' })).records.find(record => record.product_id === 520 || record.order_id === 510) ?? (await read({ search: 'BUYER515@' })).records[0]!
|
|
119
|
+
expect(linked.customer).toEqual({ id: 515, label: 'zelda Late', detail: 'buyer515@shop.test' })
|
|
120
|
+
const withProduct = (await read({ search: 'zebra suite' })).records[0]!
|
|
121
|
+
expect(withProduct.product).toEqual({ id: 520, label: 'Zebra Suite' })
|
|
122
|
+
const withOrder = (await read({ search: '510' })).records[0]!
|
|
123
|
+
expect(withOrder.order).toEqual({ id: 510, label: 'Order #510', detail: 'refunded' })
|
|
124
|
+
|
|
125
|
+
// The dialog's choices: bounded, searched, past the 500th.
|
|
126
|
+
const choose = (kind: 'customers' | 'products' | 'orders', search: string, limit = 25) => searchLicenseKeyChoices(kind, { search, limit }, runner, dialect)
|
|
127
|
+
expect((await choose('customers', 'ZE')).choices.map(choice => choice.label)).toEqual(['Zed early', 'zelda Late'])
|
|
128
|
+
expect(await choose('products', '520')).toEqual({ choices: [{ id: 520, label: 'Zebra Suite' }], total: 1 })
|
|
129
|
+
expect((await choose('orders', 'refund')).choices).toEqual([{ id: 510, label: 'Order #510', detail: 'refunded' }])
|
|
130
|
+
const newestOrders = await choose('orders', '', 3)
|
|
131
|
+
expect(newestOrders.choices.map(choice => choice.id)).toEqual([520, 519, 518])
|
|
132
|
+
expect(newestOrders.total).toBe(ROWS)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
describe('readLicenseKeyPage on SQLite', () => {
|
|
136
|
+
test('summary, search, sorts, pages, links and choices', async () => {
|
|
137
|
+
const database = new Database(':memory:')
|
|
138
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
139
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
140
|
+
})
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
144
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
145
|
+
|
|
146
|
+
test.skipIf(!connection)(`readLicenseKeyPage on ${dialect}: summary, search, sorts, pages, links and choices`, async () => {
|
|
147
|
+
const url = new URL(connection!)
|
|
148
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
149
|
+
throw new Error('Licence key list tests require a local disposable database server')
|
|
150
|
+
|
|
151
|
+
const name = `stacks_license_keys_${crypto.randomUUID().replaceAll('-', '')}`
|
|
152
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
153
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
154
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
155
|
+
const scoped = new URL(url.href)
|
|
156
|
+
scoped.pathname = `/${name}`
|
|
157
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
158
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
159
|
+
|
|
160
|
+
try {
|
|
161
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
162
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
await database.close()
|
|
166
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
167
|
+
finally { await admin.close() }
|
|
168
|
+
}
|
|
169
|
+
}, 60_000)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
describe('parseLicenseKeyListQuery', () => {
|
|
173
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
174
|
+
|
|
175
|
+
test('defaults to every key, newest first, 25 a page', () => {
|
|
176
|
+
expect(parseLicenseKeyListQuery(reader({}))).toEqual({ search: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
|
|
177
|
+
expect(parseLicenseKeyListQuery(reader({ sort: 'expiry' }))).toHaveProperty('direction', 'asc')
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
test('refuses values the page does not offer', () => {
|
|
181
|
+
expect(parseLicenseKeyListQuery(reader({ sort: 'uuid' }))).toHaveProperty('error')
|
|
182
|
+
expect(parseLicenseKeyListQuery(reader({ direction: 'up' }))).toHaveProperty('error')
|
|
183
|
+
})
|
|
184
|
+
})
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { db, getDatabaseDialect, sqlDateTime } from '@stacksjs/database/runtime'
|
|
3
|
+
import type { QueryReader } from '../Content/content-list'
|
|
4
|
+
import { containsPattern, countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
|
|
5
|
+
import type { NamedSearchQuery } from '../named-search'
|
|
6
|
+
import { referencedIds } from './commerce-record'
|
|
7
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
8
|
+
import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
|
|
9
|
+
import type { LicenseKeyRecord, LicenseKeyRelatedSummary } from './license-key-records'
|
|
10
|
+
import {
|
|
11
|
+
indexLicenseKeyOptions,
|
|
12
|
+
normalizeLicenseKeyCustomer,
|
|
13
|
+
normalizeLicenseKeyOrder,
|
|
14
|
+
normalizeLicenseKeyProduct,
|
|
15
|
+
normalizeLicenseKeyRecord,
|
|
16
|
+
} from './license-key-records'
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* One page of licence keys, searched, sorted and counted by the database, with
|
|
20
|
+
* the summary of every key, and the customers, products and orders the key
|
|
21
|
+
* dialog offers, searched (stacksjs/stacks#3218).
|
|
22
|
+
*
|
|
23
|
+
* The Licence Keys page used to read the newest 500 keys and do all of that in
|
|
24
|
+
* the browser, so an older key could not be found, and its cards counted those
|
|
25
|
+
* 500. The dialog was handed the first 500 customers, products and orders, so
|
|
26
|
+
* a key could not be linked to any later one, and the page labelled each key's
|
|
27
|
+
* links from those same 500, so a key linked to a later one showed no link.
|
|
28
|
+
*/
|
|
29
|
+
export const LICENSE_KEY_SORTS = ['created', 'id', 'key', 'template', 'customer', 'product', 'order', 'expiry', 'status'] as const
|
|
30
|
+
export type LicenseKeySort = typeof LICENSE_KEY_SORTS[number]
|
|
31
|
+
|
|
32
|
+
export interface LicenseKeyListQuery {
|
|
33
|
+
search: string
|
|
34
|
+
sort: LicenseKeySort
|
|
35
|
+
direction: 'asc' | 'desc'
|
|
36
|
+
page: number
|
|
37
|
+
perPage: number
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface LicenseKeySummary {
|
|
41
|
+
total: number
|
|
42
|
+
active: number
|
|
43
|
+
/** Linked to a customer, a product or an order. */
|
|
44
|
+
assigned: number
|
|
45
|
+
/** Expiring between now and 30 days from now. */
|
|
46
|
+
expiring: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function parseLicenseKeyListQuery(read: QueryReader): LicenseKeyListQuery | { error: string } {
|
|
50
|
+
const pageText = queryText(read, 'page')
|
|
51
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
52
|
+
if (!Number.isInteger(page) || page < 1)
|
|
53
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
54
|
+
|
|
55
|
+
const sizeText = queryText(read, 'per_page')
|
|
56
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
57
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
58
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
59
|
+
|
|
60
|
+
const sort = queryText(read, 'sort') || 'created'
|
|
61
|
+
if (!(LICENSE_KEY_SORTS as readonly string[]).includes(sort))
|
|
62
|
+
return { error: `sort must be one of ${LICENSE_KEY_SORTS.join(', ')}.` }
|
|
63
|
+
|
|
64
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
65
|
+
const direction = directionText === '' ? (sort === 'created' || sort === 'order' ? 'desc' : 'asc') : directionText
|
|
66
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
67
|
+
return { error: 'direction must be asc or desc.' }
|
|
68
|
+
|
|
69
|
+
const search = queryText(read, 'q')
|
|
70
|
+
if (search.length > 200)
|
|
71
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
72
|
+
|
|
73
|
+
return { search, sort: sort as LicenseKeySort, direction, page, perPage }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const FROM = ' FROM license_keys k LEFT JOIN customers c ON c.id = k.customer_id LEFT JOIN products p ON p.id = k.product_id'
|
|
77
|
+
|
|
78
|
+
function sortExpression(sort: LicenseKeySort, dialect: QueryBuilderDialect): string {
|
|
79
|
+
switch (sort) {
|
|
80
|
+
case 'id': return 'k.id'
|
|
81
|
+
case 'key': return 'k.key'
|
|
82
|
+
// As text: PostgreSQL and MySQL keep both as enums, which sort by declaration order.
|
|
83
|
+
case 'template': return asText('k.template', dialect)
|
|
84
|
+
case 'status': return asText('k.status', dialect)
|
|
85
|
+
case 'customer': return `LOWER(COALESCE(c.name, ''))`
|
|
86
|
+
case 'product': return `LOWER(COALESCE(p.name, ''))`
|
|
87
|
+
case 'order': return 'k.order_id'
|
|
88
|
+
case 'expiry': return 'k.expiry_date'
|
|
89
|
+
default: return 'k.created_at'
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function licenseKeyFilter(query: Pick<LicenseKeyListQuery, 'search'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
94
|
+
if (!query.search)
|
|
95
|
+
return { where: '', values: [] }
|
|
96
|
+
const { bind, values } = binder(dialect)
|
|
97
|
+
const pattern = containsPattern(query.search)
|
|
98
|
+
const columns = [
|
|
99
|
+
'k.key',
|
|
100
|
+
asText('k.template', dialect),
|
|
101
|
+
asText('k.status', dialect),
|
|
102
|
+
`COALESCE(c.name, '')`,
|
|
103
|
+
`COALESCE(c.email, '')`,
|
|
104
|
+
`COALESCE(p.name, '')`,
|
|
105
|
+
`COALESCE(${asText('k.order_id', dialect)}, '')`,
|
|
106
|
+
]
|
|
107
|
+
return { where: ` WHERE (${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`, values }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function orderBy(query: Pick<LicenseKeyListQuery, '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 key.
|
|
114
|
+
if (query.sort === 'created' || query.sort === 'id' || query.sort === 'key')
|
|
115
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, k.id ${direction}`
|
|
116
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, k.created_at DESC, k.id DESC`
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Keys turned into records, against exactly the customers, products and orders they reference. */
|
|
120
|
+
async function recordsFor(keys: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<LicenseKeyRecord[]> {
|
|
121
|
+
if (keys.length === 0)
|
|
122
|
+
return []
|
|
123
|
+
const read = (table: string, columns: string, ids: unknown[]) => ids.length > 0
|
|
124
|
+
? run.unsafe(`SELECT ${columns} FROM ${table} WHERE id IN (${idPlaceholders(ids, dialect)})`, ids).execute()
|
|
125
|
+
: Promise.resolve([])
|
|
126
|
+
const [customers, products, orders] = await Promise.all([
|
|
127
|
+
read('customers', 'id, name, email', referencedIds(keys, 'customer_id')),
|
|
128
|
+
read('products', 'id, name', referencedIds(keys, 'product_id')),
|
|
129
|
+
read('orders', 'id, status', referencedIds(keys, 'order_id')),
|
|
130
|
+
])
|
|
131
|
+
const customerMap = indexLicenseKeyOptions(sqlRows(customers).map(normalizeLicenseKeyCustomer))
|
|
132
|
+
const productMap = indexLicenseKeyOptions(sqlRows(products).map(normalizeLicenseKeyProduct))
|
|
133
|
+
const orderMap = indexLicenseKeyOptions(sqlRows(orders).map(normalizeLicenseKeyOrder))
|
|
134
|
+
return keys.map(key => normalizeLicenseKeyRecord(key, customerMap, productMap, orderMap))
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The summary cards, over every key as before. */
|
|
138
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect, now: Date): Promise<LicenseKeySummary> {
|
|
139
|
+
const { bind, values } = binder(dialect)
|
|
140
|
+
// SQLite keeps timestamps as text, where "2026-11-06 10:00" and
|
|
141
|
+
// "2026-11-06T09:00" compare the wrong way round, so both sides go through
|
|
142
|
+
// datetime() there. The others parse the value.
|
|
143
|
+
const at = (value: string) => dialect === 'sqlite' ? `datetime(${value})` : value
|
|
144
|
+
const from = bind(sqlDateTime(now))
|
|
145
|
+
const until = bind(sqlDateTime(new Date(now.getTime() + 30 * 86_400_000)))
|
|
146
|
+
const row = sqlRows(await run.unsafe(
|
|
147
|
+
`SELECT COUNT(*) AS total_count, SUM(CASE WHEN ${asText('status', dialect)} = 'active' THEN 1 ELSE 0 END) AS active_count, SUM(CASE WHEN customer_id IS NOT NULL OR product_id IS NOT NULL OR order_id IS NOT NULL THEN 1 ELSE 0 END) AS assigned_count, SUM(CASE WHEN ${at('expiry_date')} >= ${at(from)} AND ${at('expiry_date')} <= ${at(until)} THEN 1 ELSE 0 END) AS expiring_count FROM license_keys`,
|
|
148
|
+
values,
|
|
149
|
+
).execute())[0] ?? {}
|
|
150
|
+
return {
|
|
151
|
+
total: countOf(row.total_count),
|
|
152
|
+
active: countOf(row.active_count),
|
|
153
|
+
assigned: countOf(row.assigned_count),
|
|
154
|
+
expiring: countOf(row.expiring_count),
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface LicenseKeyPage {
|
|
159
|
+
records: LicenseKeyRecord[]
|
|
160
|
+
total: number
|
|
161
|
+
page: number
|
|
162
|
+
summary: LicenseKeySummary
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function readLicenseKeyPage(
|
|
166
|
+
query: LicenseKeyListQuery,
|
|
167
|
+
run: CommerceSqlRunner = db,
|
|
168
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
169
|
+
now: Date = new Date(),
|
|
170
|
+
): Promise<LicenseKeyPage> {
|
|
171
|
+
const { where, values } = licenseKeyFilter(query, dialect)
|
|
172
|
+
const [counted, summary] = await Promise.all([
|
|
173
|
+
run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
|
|
174
|
+
summarize(run, dialect, now),
|
|
175
|
+
])
|
|
176
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
177
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
178
|
+
const keys = await run.unsafe(
|
|
179
|
+
`SELECT k.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
180
|
+
values,
|
|
181
|
+
).execute()
|
|
182
|
+
return { records: await recordsFor(sqlRows(keys), run, dialect), total, page, summary }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export const LICENSE_KEY_CHOICE_KINDS = ['customers', 'products', 'orders'] as const
|
|
186
|
+
export type LicenseKeyChoiceKind = typeof LICENSE_KEY_CHOICE_KINDS[number]
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The customers (by name or email), products (by name or id) or orders (by id
|
|
190
|
+
* or status, newest first) the key dialog offers, bounded, with how many
|
|
191
|
+
* matched.
|
|
192
|
+
*/
|
|
193
|
+
export async function searchLicenseKeyChoices(
|
|
194
|
+
kind: LicenseKeyChoiceKind,
|
|
195
|
+
query: NamedSearchQuery,
|
|
196
|
+
run: CommerceSqlRunner = db,
|
|
197
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
198
|
+
): Promise<{ choices: LicenseKeyRelatedSummary[], total: number }> {
|
|
199
|
+
const spec = {
|
|
200
|
+
customers: { columns: 'id, name, email', searched: [`COALESCE(name, '')`, `COALESCE(email, '')`], order: `LOWER(COALESCE(name, '')) ASC, id ASC`, normalize: normalizeLicenseKeyCustomer },
|
|
201
|
+
products: { columns: 'id, name', searched: [`COALESCE(name, '')`, asText('id', dialect)], order: `LOWER(COALESCE(name, '')) ASC, id ASC`, normalize: normalizeLicenseKeyProduct },
|
|
202
|
+
orders: { columns: 'id, status', searched: [asText('id', dialect), asText('status', dialect)], order: 'id DESC', normalize: normalizeLicenseKeyOrder },
|
|
203
|
+
}[kind]
|
|
204
|
+
if (!spec)
|
|
205
|
+
throw new TypeError(`${kind} is not a licence key choice.`)
|
|
206
|
+
const { bind, values } = binder(dialect)
|
|
207
|
+
let where = ''
|
|
208
|
+
if (query.search) {
|
|
209
|
+
const pattern = containsPattern(query.search)
|
|
210
|
+
where = ` WHERE ${spec.searched.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')}`
|
|
211
|
+
}
|
|
212
|
+
const [counted, found] = await Promise.all([
|
|
213
|
+
run.unsafe(`SELECT COUNT(*) AS total_count FROM ${kind}${where}`, values).execute(),
|
|
214
|
+
run.unsafe(`SELECT ${spec.columns} FROM ${kind}${where} ORDER BY ${spec.order} LIMIT ${query.limit}`, values).execute(),
|
|
215
|
+
])
|
|
216
|
+
return { choices: sqlRows(found).map(spec.normalize), total: countOf(sqlRows(counted)[0]?.total_count) }
|
|
217
|
+
}
|
|
@@ -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 { OrderListQuery, OrderListRunner } from './commerce-order-list'
|
|
5
|
+
import { ordersCsv, parseOrderListQuery, readOrderPage, readOrdersForExport } from './commerce-order-list'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The Orders list against each dialect's real engine (stacksjs/stacks#3218):
|
|
9
|
+
* search, filters, sorts, paging, store-wide summary and the full export.
|
|
10
|
+
*/
|
|
11
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
12
|
+
|
|
13
|
+
const CUSTOMERS: Array<[number, string, string]> = [
|
|
14
|
+
[1, 'Ava Stone', 'ava@example.com'],
|
|
15
|
+
[2, 'ben carter', 'BEN@example.com'],
|
|
16
|
+
[3, 'Cara Lim', 'cara@example.com'],
|
|
17
|
+
]
|
|
18
|
+
const STATUSES = ['PENDING', 'preparing', 'DELIVERED', 'CANCELED', 'READY']
|
|
19
|
+
const TYPES = ['DELIVERY', 'TAKEOUT', 'DINE_IN']
|
|
20
|
+
|
|
21
|
+
/** 30 orders: customers 1-3 and unassigned in turn, five statuses, three types. */
|
|
22
|
+
const ORDERS = Array.from({ length: 30 }, (_, index) => {
|
|
23
|
+
const id = index + 1
|
|
24
|
+
return {
|
|
25
|
+
id,
|
|
26
|
+
customer_id: id % 4 === 0 ? null : (id % 3) + 1,
|
|
27
|
+
status: STATUSES[id % STATUSES.length]!,
|
|
28
|
+
total_amount: (id * 37) % 101 * 100,
|
|
29
|
+
// Two spellings of one currency must be one total.
|
|
30
|
+
currency: id % 7 === 0 ? 'eur' : (id % 2 === 0 ? 'EUR' : 'USD'),
|
|
31
|
+
order_type: TYPES[id % TYPES.length]!,
|
|
32
|
+
delivery_address: id === 13 ? '100% Sure Street' : `${id} Main Street`,
|
|
33
|
+
coupon_id: id % 10 === 0 ? 2 : null,
|
|
34
|
+
created_at: `2026-11-${String(1 + (id % 9)).padStart(2, '0')} 10:00:00`,
|
|
35
|
+
}
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
function query(overrides: Partial<OrderListQuery> = {}): OrderListQuery {
|
|
39
|
+
return { search: '', status: '', type: '', sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
43
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
44
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME' : 'TIMESTAMP'
|
|
45
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
46
|
+
await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text})`)
|
|
47
|
+
await run(`CREATE TABLE coupons (id ${pk})`)
|
|
48
|
+
await run(`CREATE TABLE order_items (id ${pk}, order_id INTEGER, quantity INTEGER)`)
|
|
49
|
+
await run(`CREATE TABLE orders (id ${pk}, uuid ${text}, customer_id INTEGER NULL, coupon_id INTEGER NULL, status ${text}, total_amount INTEGER, currency ${text}, tax_amount INTEGER, discount_amount INTEGER, delivery_fee INTEGER, tip_amount INTEGER, order_type ${text}, delivery_address ${text} NULL, special_instructions ${text} NULL, estimated_delivery_time ${text} NULL, applied_coupon_id ${text} NULL, created_at ${time})`)
|
|
50
|
+
const p = (n: number) => dialect === 'postgres' ? `$${n}` : '?'
|
|
51
|
+
const ps = (count: number) => Array.from({ length: count }, (_, i) => p(i + 1)).join(', ')
|
|
52
|
+
for (const customer of CUSTOMERS)
|
|
53
|
+
await run(`INSERT INTO customers (id, name, email) VALUES (${ps(3)})`, customer)
|
|
54
|
+
await run(`INSERT INTO coupons (id) VALUES (${ps(1)})`, [2])
|
|
55
|
+
for (const order of ORDERS) {
|
|
56
|
+
await run(
|
|
57
|
+
`INSERT INTO orders (id, customer_id, coupon_id, status, total_amount, currency, tax_amount, discount_amount, delivery_fee, tip_amount, order_type, delivery_address, created_at) VALUES (${ps(13)})`,
|
|
58
|
+
[order.id, order.customer_id, order.coupon_id, order.status, order.total_amount, order.currency, 0, 0, 0, 0, order.order_type, order.delivery_address, order.created_at],
|
|
59
|
+
)
|
|
60
|
+
}
|
|
61
|
+
// Order 5 has two lines, 3 + 2 items.
|
|
62
|
+
await run(`INSERT INTO order_items (id, order_id, quantity) VALUES (${ps(3)})`, [1, 5, 3])
|
|
63
|
+
await run(`INSERT INTO order_items (id, order_id, quantity) VALUES (${ps(3)})`, [2, 5, 2])
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function exercise(runner: OrderListRunner, dialect: Dialect) {
|
|
67
|
+
const read = (overrides: Partial<OrderListQuery> = {}) => readOrderPage(query(overrides), runner, dialect)
|
|
68
|
+
|
|
69
|
+
// The summary covers every order, not the page of 10.
|
|
70
|
+
const first = await read()
|
|
71
|
+
expect(first.total).toBe(30)
|
|
72
|
+
expect(first.records).toHaveLength(10)
|
|
73
|
+
expect(first.summary.total).toBe(30)
|
|
74
|
+
const statusCount = (names: string[]) => ORDERS.filter(order => names.includes(order.status.toUpperCase())).length
|
|
75
|
+
expect(first.summary.pending).toBe(statusCount(['PENDING', 'NEW']))
|
|
76
|
+
expect(first.summary.inProgress).toBe(statusCount(['PREPARING', 'PROCESSING', 'READY', 'SHIPPED']))
|
|
77
|
+
expect(first.summary.completed).toBe(statusCount(['DELIVERED', 'COMPLETED', 'PAID']))
|
|
78
|
+
expect(first.summary.cancelled).toBe(statusCount(['CANCELED', 'CANCELLED', 'REFUNDED']))
|
|
79
|
+
const sum = (currency: string) => ORDERS.filter(order => order.currency.toUpperCase() === currency).reduce((total, order) => total + order.total_amount, 0)
|
|
80
|
+
expect(first.summary.currencyTotals).toEqual([{ currency: 'EUR', amount: sum('EUR') }, { currency: 'USD', amount: sum('USD') }])
|
|
81
|
+
expect(first.statuses).toContain('preparing')
|
|
82
|
+
|
|
83
|
+
// Newest first, ties broken by id descending: stable across page boundaries.
|
|
84
|
+
const expected = [...ORDERS].sort((a, b) => b.created_at.localeCompare(a.created_at) || b.id - a.id).map(order => String(order.id))
|
|
85
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
86
|
+
expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(expected)
|
|
87
|
+
|
|
88
|
+
// Past the end moves back to the last page.
|
|
89
|
+
expect((await read({ page: 9 })).page).toBe(3)
|
|
90
|
+
|
|
91
|
+
// Search: customer name in any case, address, literal %, id.
|
|
92
|
+
const ben = await read({ search: 'BEN', perPage: 100 })
|
|
93
|
+
expect(ben.total).toBe(ORDERS.filter(order => order.customer_id === 2).length)
|
|
94
|
+
expect(ben.records.every(record => record.customerName === 'ben carter')).toBeTrue()
|
|
95
|
+
expect((await read({ search: '100%' })).records.map(record => record.id)).toEqual(['13'])
|
|
96
|
+
expect((await read({ search: '27', perPage: 100 })).records.map(record => record.id)).toContain('27')
|
|
97
|
+
|
|
98
|
+
// Filters are exact values.
|
|
99
|
+
expect((await read({ status: 'preparing', perPage: 100 })).total).toBe(ORDERS.filter(order => order.status === 'preparing').length)
|
|
100
|
+
expect((await read({ type: 'TAKEOUT', perPage: 100 })).total).toBe(ORDERS.filter(order => order.order_type === 'TAKEOUT').length)
|
|
101
|
+
|
|
102
|
+
// Totals sort, high first.
|
|
103
|
+
const byTotal = await read({ sort: 'total', direction: 'desc', perPage: 100 })
|
|
104
|
+
const totals = byTotal.records.map(record => record.totalAmount)
|
|
105
|
+
expect(totals).toEqual([...totals].sort((a, b) => b - a))
|
|
106
|
+
|
|
107
|
+
// Customer sort: unassigned first ascending, then by name ignoring case.
|
|
108
|
+
const byCustomer = (await read({ sort: 'customer', direction: 'asc', perPage: 100 })).records.map(record => record.customerName)
|
|
109
|
+
const unassigned = ORDERS.filter(order => order.customer_id === null).length
|
|
110
|
+
expect(byCustomer.slice(0, unassigned).every(name => name === '')).toBeTrue()
|
|
111
|
+
expect(byCustomer.slice(unassigned)).toEqual([...byCustomer.slice(unassigned)].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())))
|
|
112
|
+
|
|
113
|
+
// Item counts and coupon references come through.
|
|
114
|
+
const five = (await read({ search: '5 Main', perPage: 100 })).records.find(record => record.id === '5')
|
|
115
|
+
expect(five?.itemCount).toBe(5)
|
|
116
|
+
expect((await read({ search: '10 Main' })).records[0]?.couponId).toBe('2')
|
|
117
|
+
|
|
118
|
+
// The export reads every match, in order, across batches.
|
|
119
|
+
const exported = await readOrdersForExport({ search: '', status: '', type: '', sort: 'created', direction: 'desc' }, runner, dialect, 4)
|
|
120
|
+
expect(exported.map(record => record.id)).toEqual(expected)
|
|
121
|
+
const filtered = await readOrdersForExport({ search: 'ben', status: '', type: '', sort: 'created', direction: 'desc' }, runner, dialect, 4)
|
|
122
|
+
expect(filtered).toHaveLength(ben.total)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
describe('readOrderPage on SQLite', () => {
|
|
126
|
+
test('searches, filters, sorts, pages, summarises and exports', async () => {
|
|
127
|
+
const database = new Database(':memory:')
|
|
128
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
129
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
130
|
+
})
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
134
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
135
|
+
|
|
136
|
+
test.skipIf(!connection)(`readOrderPage on ${dialect} searches, filters, sorts, pages, summarises and exports`, async () => {
|
|
137
|
+
const url = new URL(connection!)
|
|
138
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
139
|
+
throw new Error('Order list tests require a local disposable database server')
|
|
140
|
+
|
|
141
|
+
const name = `stacks_order_list_${crypto.randomUUID().replaceAll('-', '')}`
|
|
142
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
143
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
144
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
145
|
+
const scoped = new URL(url.href)
|
|
146
|
+
scoped.pathname = `/${name}`
|
|
147
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
148
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
152
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
await database.close()
|
|
156
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
157
|
+
finally { await admin.close() }
|
|
158
|
+
}
|
|
159
|
+
}, 60_000)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
describe('parseOrderListQuery', () => {
|
|
163
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
164
|
+
|
|
165
|
+
test('defaults to the newest 25', () => {
|
|
166
|
+
expect(parseOrderListQuery(reader({}))).toEqual({ search: '', status: '', type: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
test('rejects what it cannot honour', () => {
|
|
170
|
+
expect(parseOrderListQuery(reader({ sort: 'secret_column' }))).toHaveProperty('error')
|
|
171
|
+
expect(parseOrderListQuery(reader({ direction: 'sideways' }))).toHaveProperty('error')
|
|
172
|
+
expect(parseOrderListQuery(reader({ per_page: '7' }))).toHaveProperty('error')
|
|
173
|
+
expect(parseOrderListQuery(reader({ page: '0' }))).toHaveProperty('error')
|
|
174
|
+
})
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
test('the CSV keeps the columns the page exported, with every row', () => {
|
|
178
|
+
const record = { id: '7', customerId: '', customerName: 'Ava "A" Stone', customerEmail: 'ava@example.com', status: 'READY', totalAmount: 1250, currency: 'USD', taxAmount: 0, discountAmount: 0, deliveryFee: 0, tipAmount: 0, orderType: 'DELIVERY', deliveryAddress: '1 Main', specialInstructions: '', estimatedDeliveryTime: '', appliedCouponId: '', couponId: '', itemCount: 2, createdAt: '2026-11-01T10:00:00.000Z' }
|
|
179
|
+
const csv = ordersCsv([record], (amount) => (amount / 100).toFixed(2))
|
|
180
|
+
const [header, row] = csv.replace('', '').split('\n')
|
|
181
|
+
expect(header).toBe('"Order ID","Customer","Customer email","Status","Order type","Items","Total","Currency","Tax","Discount","Delivery fee","Tip","Delivery address","Created at"')
|
|
182
|
+
expect(row).toBe('"7","Ava ""A"" Stone","ava@example.com","READY","DELIVERY","2","12.50","USD","0.00","0.00","0.00","0.00","1 Main","2026-11-01T10:00:00.000Z"')
|
|
183
|
+
})
|