@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,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
|
+
})
|
|
@@ -0,0 +1,278 @@
|
|
|
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 type { CommerceOrderRecord, CommerceOrderSummary } from './commerce-order-records'
|
|
6
|
+
import {
|
|
7
|
+
addOrderItemQuantity,
|
|
8
|
+
normalizeCommerceOrderRecord,
|
|
9
|
+
normalizeOrderCouponId,
|
|
10
|
+
normalizeOrderCustomerContext,
|
|
11
|
+
} from './commerce-order-records'
|
|
12
|
+
import { commerceCurrency, commerceIdentifier, commerceValue, referencedIds } from './commerce-record'
|
|
13
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
14
|
+
import { asText, binder, idPlaceholders, sqlRows as rows } from './commerce-sql'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* One page of orders, searched, filtered, sorted, counted and summarised by the
|
|
18
|
+
* database (stacksjs/stacks#3218).
|
|
19
|
+
*
|
|
20
|
+
* The Orders page used to read the newest 500 orders and do all of that in the
|
|
21
|
+
* browser, so an order past the 500th could not be found, and the summary
|
|
22
|
+
* cards and currency totals described those 500, not the store.
|
|
23
|
+
*/
|
|
24
|
+
export const ORDER_SORTS = ['created', 'id', 'customer', 'total', 'type', 'status'] as const
|
|
25
|
+
export type OrderSort = typeof ORDER_SORTS[number]
|
|
26
|
+
|
|
27
|
+
export interface OrderListQuery {
|
|
28
|
+
search: string
|
|
29
|
+
status: string
|
|
30
|
+
type: string
|
|
31
|
+
sort: OrderSort
|
|
32
|
+
direction: 'asc' | 'desc'
|
|
33
|
+
page: number
|
|
34
|
+
perPage: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type OrderListRunner = CommerceSqlRunner
|
|
38
|
+
|
|
39
|
+
/** The status groups the summary cards count, matched without regard to case. */
|
|
40
|
+
const STATUS_GROUPS = {
|
|
41
|
+
pending: ['PENDING', 'NEW'],
|
|
42
|
+
inProgress: ['PREPARING', 'PROCESSING', 'READY', 'SHIPPED'],
|
|
43
|
+
completed: ['DELIVERED', 'COMPLETED', 'PAID'],
|
|
44
|
+
cancelled: ['CANCELED', 'CANCELLED', 'REFUNDED'],
|
|
45
|
+
} as const
|
|
46
|
+
|
|
47
|
+
export const DEFAULT_ORDER_STATUSES = ['PENDING', 'PREPARING', 'READY', 'DELIVERED', 'CANCELED']
|
|
48
|
+
export const DEFAULT_ORDER_TYPES = ['DINE_IN', 'TAKEOUT', 'DELIVERY']
|
|
49
|
+
|
|
50
|
+
export function parseOrderListQuery(read: QueryReader): OrderListQuery | { error: string } {
|
|
51
|
+
const pageText = queryText(read, 'page')
|
|
52
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
53
|
+
if (!Number.isInteger(page) || page < 1)
|
|
54
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
55
|
+
|
|
56
|
+
const sizeText = queryText(read, 'per_page')
|
|
57
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
58
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
59
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
60
|
+
|
|
61
|
+
const sort = queryText(read, 'sort') || 'created'
|
|
62
|
+
if (!(ORDER_SORTS as readonly string[]).includes(sort))
|
|
63
|
+
return { error: `sort must be one of ${ORDER_SORTS.join(', ')}.` }
|
|
64
|
+
|
|
65
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
66
|
+
const direction = directionText === '' ? (sort === 'created' || sort === 'total' ? 'desc' : 'asc') : directionText
|
|
67
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
68
|
+
return { error: 'direction must be asc or desc.' }
|
|
69
|
+
|
|
70
|
+
const search = queryText(read, 'q')
|
|
71
|
+
if (search.length > 200)
|
|
72
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
73
|
+
|
|
74
|
+
const status = queryText(read, 'status')
|
|
75
|
+
const type = queryText(read, 'type')
|
|
76
|
+
if (status.length > 100 || type.length > 100)
|
|
77
|
+
return { error: 'status and type must be 100 characters or fewer.' }
|
|
78
|
+
|
|
79
|
+
return { search, status, type, sort: sort as OrderSort, direction, page, perPage }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function sortExpression(sort: OrderSort): string {
|
|
83
|
+
switch (sort) {
|
|
84
|
+
case 'id': return 'o.id'
|
|
85
|
+
// Case-insensitive, with unassigned orders first ascending, the same on
|
|
86
|
+
// every dialect (each sorts NULL differently).
|
|
87
|
+
case 'customer': return `LOWER(COALESCE(c.name, ''))`
|
|
88
|
+
case 'total': return 'o.total_amount'
|
|
89
|
+
case 'type': return 'o.order_type'
|
|
90
|
+
case 'status': return 'o.status'
|
|
91
|
+
default: return 'o.created_at'
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The WHERE clause and its values for a query's search and filters. */
|
|
96
|
+
export function orderFilter(query: Pick<OrderListQuery, 'search' | 'status' | 'type'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
97
|
+
const { bind, values } = binder(dialect)
|
|
98
|
+
const clauses: string[] = []
|
|
99
|
+
if (query.status)
|
|
100
|
+
clauses.push(`o.status = ${bind(query.status)}`)
|
|
101
|
+
if (query.type)
|
|
102
|
+
clauses.push(`o.order_type = ${bind(query.type)}`)
|
|
103
|
+
if (query.search) {
|
|
104
|
+
const pattern = containsPattern(query.search)
|
|
105
|
+
const columns = [
|
|
106
|
+
asText('o.id', dialect),
|
|
107
|
+
`COALESCE(c.name, '')`,
|
|
108
|
+
`COALESCE(c.email, '')`,
|
|
109
|
+
`COALESCE(o.status, '')`,
|
|
110
|
+
`COALESCE(o.order_type, '')`,
|
|
111
|
+
`COALESCE(o.delivery_address, '')`,
|
|
112
|
+
]
|
|
113
|
+
clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
114
|
+
}
|
|
115
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const FROM = ' FROM orders o LEFT JOIN customers c ON c.id = o.customer_id'
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Orders turned into records: their referenced customers and coupons read by
|
|
122
|
+
* id, and their item counts. Shared by the page and the export.
|
|
123
|
+
*/
|
|
124
|
+
async function recordsFor(orders: Array<Record<string, unknown>>, run: OrderListRunner, dialect: QueryBuilderDialect): Promise<CommerceOrderRecord[]> {
|
|
125
|
+
if (orders.length === 0)
|
|
126
|
+
return []
|
|
127
|
+
|
|
128
|
+
const customerIds = referencedIds(orders, 'customer_id')
|
|
129
|
+
const couponIds = referencedIds(orders, 'coupon_id')
|
|
130
|
+
const orderIds = referencedIds(orders, 'id')
|
|
131
|
+
const [customers, coupons, items] = await Promise.all([
|
|
132
|
+
customerIds.length > 0 ? run.unsafe(`SELECT id, name, email FROM customers WHERE id IN (${idPlaceholders(customerIds, dialect)})`, customerIds).execute() : [],
|
|
133
|
+
couponIds.length > 0 ? run.unsafe(`SELECT id FROM coupons WHERE id IN (${idPlaceholders(couponIds, dialect)})`, couponIds).execute() : [],
|
|
134
|
+
orderIds.length > 0 ? run.unsafe(`SELECT id, order_id, quantity FROM order_items WHERE order_id IN (${idPlaceholders(orderIds, dialect)})`, orderIds).execute() : [],
|
|
135
|
+
])
|
|
136
|
+
|
|
137
|
+
const customerMap = new Map(rows(customers).map(normalizeOrderCustomerContext).map(customer => [customer.id, customer.context]))
|
|
138
|
+
const couponSet = new Set(rows(coupons).map(normalizeOrderCouponId))
|
|
139
|
+
const orderKeys = new Set(orders.map(order => commerceIdentifier(commerceValue(order, 'id', 'uuid'), 'Order')))
|
|
140
|
+
const itemCounts = new Map<string, number>()
|
|
141
|
+
for (const item of rows(items))
|
|
142
|
+
addOrderItemQuantity(item, orderKeys, itemCounts)
|
|
143
|
+
|
|
144
|
+
return orders.map(order => normalizeCommerceOrderRecord(order, customerMap, itemCounts, couponSet))
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The summary cards and currency totals, over every order. */
|
|
148
|
+
async function summarize(run: OrderListRunner): Promise<CommerceOrderSummary> {
|
|
149
|
+
const group = (statuses: readonly string[]) =>
|
|
150
|
+
`SUM(CASE WHEN UPPER(TRIM(status)) IN (${statuses.map(status => `'${status}'`).join(', ')}) THEN 1 ELSE 0 END)`
|
|
151
|
+
const [counts, totals] = await Promise.all([
|
|
152
|
+
run.unsafe(`SELECT COUNT(*) AS total_count, ${group(STATUS_GROUPS.pending)} AS pending_count, ${group(STATUS_GROUPS.inProgress)} AS progress_count, ${group(STATUS_GROUPS.completed)} AS completed_count, ${group(STATUS_GROUPS.cancelled)} AS cancelled_count FROM orders`).execute(),
|
|
153
|
+
run.unsafe('SELECT currency, SUM(total_amount) AS amount_total FROM orders GROUP BY currency').execute(),
|
|
154
|
+
])
|
|
155
|
+
const count = rows(counts)[0] ?? {}
|
|
156
|
+
|
|
157
|
+
// Currencies are normalized as the records are, so "eur" and "EUR" are one total.
|
|
158
|
+
const currencyTotals = new Map<string, number>()
|
|
159
|
+
for (const row of rows(totals)) {
|
|
160
|
+
const currency = commerceCurrency(row.currency, 'Order summary')
|
|
161
|
+
currencyTotals.set(currency, (currencyTotals.get(currency) ?? 0) + countOf(row.amount_total))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return {
|
|
165
|
+
total: countOf(count.total_count),
|
|
166
|
+
pending: countOf(count.pending_count),
|
|
167
|
+
inProgress: countOf(count.progress_count),
|
|
168
|
+
completed: countOf(count.completed_count),
|
|
169
|
+
cancelled: countOf(count.cancelled_count),
|
|
170
|
+
currencyTotals: [...currencyTotals.entries()]
|
|
171
|
+
.map(([currency, amount]) => ({ currency, amount }))
|
|
172
|
+
.sort((left, right) => left.currency.localeCompare(right.currency)),
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** The filter choices: the usual ones plus every value an order actually has. */
|
|
177
|
+
async function choices(run: OrderListRunner): Promise<{ statuses: string[], orderTypes: string[] }> {
|
|
178
|
+
const [statuses, types] = await Promise.all([
|
|
179
|
+
run.unsafe('SELECT DISTINCT status FROM orders WHERE status IS NOT NULL').execute(),
|
|
180
|
+
run.unsafe('SELECT DISTINCT order_type FROM orders WHERE order_type IS NOT NULL').execute(),
|
|
181
|
+
])
|
|
182
|
+
const values = (result: unknown, key: string) => rows(result).map(row => String(row[key] ?? '').trim()).filter(Boolean).sort()
|
|
183
|
+
return {
|
|
184
|
+
statuses: [...new Set([...DEFAULT_ORDER_STATUSES, ...values(statuses, 'status')])],
|
|
185
|
+
orderTypes: [...new Set([...DEFAULT_ORDER_TYPES, ...values(types, 'order_type')])],
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export interface OrderPage {
|
|
190
|
+
records: CommerceOrderRecord[]
|
|
191
|
+
total: number
|
|
192
|
+
page: number
|
|
193
|
+
summary: CommerceOrderSummary
|
|
194
|
+
statuses: string[]
|
|
195
|
+
orderTypes: string[]
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function orderBy(query: Pick<OrderListQuery, 'sort' | 'direction'>): string {
|
|
199
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
200
|
+
// The id breaks ties, so a page boundary never repeats or skips an order.
|
|
201
|
+
return ` ORDER BY ${sortExpression(query.sort)} ${direction}, o.id ${direction}`
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export async function readOrderPage(
|
|
205
|
+
query: OrderListQuery,
|
|
206
|
+
run: OrderListRunner = db,
|
|
207
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
208
|
+
): Promise<OrderPage> {
|
|
209
|
+
const { where, values } = orderFilter(query, dialect)
|
|
210
|
+
const [counted, summary, options] = await Promise.all([
|
|
211
|
+
run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
|
|
212
|
+
summarize(run),
|
|
213
|
+
choices(run),
|
|
214
|
+
])
|
|
215
|
+
const total = countOf(rows(counted)[0]?.total_count)
|
|
216
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
217
|
+
const orders = await run.unsafe(
|
|
218
|
+
`SELECT o.*${FROM}${where}${orderBy(query)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
219
|
+
values,
|
|
220
|
+
).execute()
|
|
221
|
+
|
|
222
|
+
return { records: await recordsFor(rows(orders), run, dialect), total, page, summary, ...options }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** How many orders the export reads per query. */
|
|
226
|
+
const EXPORT_BATCH = 500
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Every order matching the query, in its order, for the CSV export. Read a
|
|
230
|
+
* batch at a time, so a large export never needs one enormous result set.
|
|
231
|
+
*/
|
|
232
|
+
export async function readOrdersForExport(
|
|
233
|
+
query: Omit<OrderListQuery, 'page' | 'perPage'>,
|
|
234
|
+
run: OrderListRunner = db,
|
|
235
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
236
|
+
batchSize: number = EXPORT_BATCH,
|
|
237
|
+
): Promise<CommerceOrderRecord[]> {
|
|
238
|
+
const { where, values } = orderFilter(query, dialect)
|
|
239
|
+
const records: CommerceOrderRecord[] = []
|
|
240
|
+
for (let offset = 0; ; offset += batchSize) {
|
|
241
|
+
const batch = rows(await run.unsafe(
|
|
242
|
+
`SELECT o.*${FROM}${where}${orderBy(query)} LIMIT ${batchSize} OFFSET ${offset}`,
|
|
243
|
+
values,
|
|
244
|
+
).execute())
|
|
245
|
+
records.push(...await recordsFor(batch, run, dialect))
|
|
246
|
+
if (batch.length < batchSize)
|
|
247
|
+
return records
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const CSV_HEADER = ['Order ID', 'Customer', 'Customer email', 'Status', 'Order type', 'Items', 'Total', 'Currency', 'Tax', 'Discount', 'Delivery fee', 'Tip', 'Delivery address', 'Created at']
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* The CSV the "Export filtered" button downloads: the same columns the page
|
|
255
|
+
* built from what it had loaded, now from every matching order. Amounts are
|
|
256
|
+
* the major-unit strings a person types (`minor` converts them), and a leading
|
|
257
|
+
* byte-order mark tells spreadsheet apps it is UTF-8.
|
|
258
|
+
*/
|
|
259
|
+
export function ordersCsv(records: CommerceOrderRecord[], minor: (amount: number, currency: string) => string): string {
|
|
260
|
+
const escape = (value: string): string => `"${value.replaceAll('"', '""')}"`
|
|
261
|
+
const lines = records.map(record => [
|
|
262
|
+
record.id,
|
|
263
|
+
record.customerName,
|
|
264
|
+
record.customerEmail,
|
|
265
|
+
record.status,
|
|
266
|
+
record.orderType,
|
|
267
|
+
String(record.itemCount),
|
|
268
|
+
minor(record.totalAmount, record.currency),
|
|
269
|
+
record.currency,
|
|
270
|
+
minor(record.taxAmount, record.currency),
|
|
271
|
+
minor(record.discountAmount, record.currency),
|
|
272
|
+
minor(record.deliveryFee, record.currency),
|
|
273
|
+
minor(record.tipAmount, record.currency),
|
|
274
|
+
record.deliveryAddress,
|
|
275
|
+
record.createdAt,
|
|
276
|
+
])
|
|
277
|
+
return `${[CSV_HEADER, ...lines].map(row => row.map(escape).join(',')).join('\n')}`
|
|
278
|
+
}
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
normalizeOrderCustomerOption,
|
|
7
7
|
summarizeCommerceOrders,
|
|
8
8
|
} from './commerce-order-records'
|
|
9
|
+
import { referencedIds } from './commerce-record'
|
|
9
10
|
|
|
10
11
|
function order(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
|
11
12
|
return {
|
|
@@ -134,3 +135,31 @@ describe('dashboard commerce order records', () => {
|
|
|
134
135
|
})
|
|
135
136
|
})
|
|
136
137
|
})
|
|
138
|
+
|
|
139
|
+
describe('the customers and coupons an order page reads', () => {
|
|
140
|
+
test('are exactly the ids the orders reference, once each, in order', () => {
|
|
141
|
+
const orders = [
|
|
142
|
+
order({ id: 1, customer_id: 704, coupon_id: null }),
|
|
143
|
+
order({ id: 2, customer_id: 12, coupon_id: 9 }),
|
|
144
|
+
order({ id: 3, customer_id: 704, coupon_id: '9' }),
|
|
145
|
+
order({ id: 4, customer_id: null, coupon_id: 3 }),
|
|
146
|
+
]
|
|
147
|
+
expect(referencedIds(orders, 'customer_id', 'customerId')).toEqual([12, 704])
|
|
148
|
+
expect(referencedIds(orders, 'coupon_id', 'couponId')).toEqual([3, 9])
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
test('cover every order, so none is refused for a customer that was not read', () => {
|
|
152
|
+
// The 704th customer by name is past any fixed first-500 read. The map
|
|
153
|
+
// built from the referenced ids still holds it, so the order normalizes.
|
|
154
|
+
const orders = [order({ id: 1, customer_id: 704 })]
|
|
155
|
+
const ids = referencedIds(orders, 'customer_id')
|
|
156
|
+
const customers = new Map(ids.map(id => [String(id), { name: `Customer ${id}`, email: `c${id}@example.com` }]))
|
|
157
|
+
expect(normalizeCommerceOrderRecord(orders[0], customers, new Map()).customerName).toBe('Customer 704')
|
|
158
|
+
// And the refusal it prevents is real: without that customer the order is rejected.
|
|
159
|
+
expect(() => normalizeCommerceOrderRecord(orders[0], new Map(), new Map())).toThrow('references missing Customer 704')
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
test('ignore empty, zero and non-numeric references', () => {
|
|
163
|
+
expect(referencedIds([order({ customer_id: '' }), order({ customer_id: 0 }), order({ customer_id: 'abc' }), order({ customer_id: -4 })], 'customer_id')).toEqual([])
|
|
164
|
+
})
|
|
165
|
+
})
|