@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,180 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
5
|
+
import type { PaymentListQuery } from './commerce-payment-list'
|
|
6
|
+
import { parsePaymentListQuery, readPaymentPage, readPaymentsForExport } from './commerce-payment-list'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Payments list against each dialect's real engine (stacksjs/stacks#3218),
|
|
10
|
+
* with status and method as real enum columns where the dialect has them.
|
|
11
|
+
*/
|
|
12
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
13
|
+
|
|
14
|
+
const NOW = new Date('2026-11-06T12:00:00.000Z')
|
|
15
|
+
const STATUSES = ['completed', 'failed', 'pending', 'refunded', 'partiallyRefunded'] as const
|
|
16
|
+
const METHODS = ['creditCard', 'paypal', 'cash'] as const
|
|
17
|
+
|
|
18
|
+
/** 24 payments, one every 20 hours back from NOW, each for an order. */
|
|
19
|
+
const PAYMENTS = Array.from({ length: 24 }, (_, index) => {
|
|
20
|
+
const id = index + 1
|
|
21
|
+
const status = STATUSES[id % STATUSES.length]!
|
|
22
|
+
const amount = 1000 + id * 50
|
|
23
|
+
return {
|
|
24
|
+
id,
|
|
25
|
+
amount,
|
|
26
|
+
refund_amount: status === 'refunded' ? amount : status === 'partiallyRefunded' ? 200 : null,
|
|
27
|
+
method: METHODS[id % METHODS.length]!,
|
|
28
|
+
status,
|
|
29
|
+
currency: id % 6 === 0 ? 'usd' : (id % 2 === 0 ? 'USD' : 'EUR'),
|
|
30
|
+
billing_email: id === 7 ? 'pay_100%@shop.test' : `buyer${id}@example.com`,
|
|
31
|
+
order_id: id + 700,
|
|
32
|
+
hoursAgo: index * 20,
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
const SUCCESSFUL = new Set(['completed', 'succeeded', 'partiallyRefunded', 'refunded'])
|
|
37
|
+
|
|
38
|
+
function within(days: number) {
|
|
39
|
+
return PAYMENTS.filter(payment => days === 0 || payment.hoursAgo * 3_600_000 <= days * 86_400_000)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function query(overrides: Partial<PaymentListQuery> = {}): PaymentListQuery {
|
|
43
|
+
return { search: '', status: '', method: '', days: 0, sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
47
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
48
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
49
|
+
let statusType = text
|
|
50
|
+
let methodType = text
|
|
51
|
+
if (dialect === 'postgres') {
|
|
52
|
+
await run(`CREATE TYPE payment_status AS ENUM (${[...STATUSES, 'succeeded', 'processing'].map(s => `'${s}'`).join(', ')})`)
|
|
53
|
+
await run(`CREATE TYPE payment_method AS ENUM (${METHODS.map(m => `'${m}'`).join(', ')})`)
|
|
54
|
+
statusType = 'payment_status'
|
|
55
|
+
methodType = 'payment_method'
|
|
56
|
+
}
|
|
57
|
+
if (dialect === 'mysql') {
|
|
58
|
+
statusType = `ENUM(${[...STATUSES, 'succeeded', 'processing'].map(s => `'${s}'`).join(', ')})`
|
|
59
|
+
methodType = `ENUM(${METHODS.map(m => `'${m}'`).join(', ')})`
|
|
60
|
+
}
|
|
61
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
62
|
+
await run(`CREATE TABLE orders (id ${pk})`)
|
|
63
|
+
await run(`CREATE TABLE customers (id ${pk})`)
|
|
64
|
+
await run(`CREATE TABLE payments (id ${pk}, amount INTEGER, refund_amount INTEGER NULL, method ${methodType}, status ${statusType}, currency ${text}, reference_number ${text} NULL, card_last_four ${text} NULL, card_brand ${text} NULL, billing_email ${text} NULL, transaction_id ${text} NULL, payment_provider ${text} NULL, notes ${text} NULL, order_id INTEGER NULL, customer_id INTEGER NULL, created_at ${time})`)
|
|
65
|
+
const p = (count: number) => Array.from({ length: count }, (_, i) => dialect === 'postgres' ? `$${i + 1}` : '?').join(', ')
|
|
66
|
+
for (const payment of PAYMENTS)
|
|
67
|
+
await run(`INSERT INTO orders (id) VALUES (${p(1)})`, [payment.order_id])
|
|
68
|
+
for (const payment of PAYMENTS) {
|
|
69
|
+
const at = new Date(NOW.getTime() - payment.hoursAgo * 3_600_000).toISOString().slice(0, 19)
|
|
70
|
+
// SQLite gets both text forms, which compare wrongly as plain text.
|
|
71
|
+
const created = dialect === 'sqlite' && payment.id % 2 === 0 ? at.replace('T', ' ') : at.replace('T', dialect === 'sqlite' ? 'T' : ' ')
|
|
72
|
+
await run(
|
|
73
|
+
`INSERT INTO payments (id, amount, refund_amount, method, status, currency, billing_email, order_id, created_at) VALUES (${p(9)})`,
|
|
74
|
+
[payment.id, payment.amount, payment.refund_amount, payment.method, payment.status, payment.currency, payment.billing_email, payment.order_id, created],
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
80
|
+
const read = (overrides: Partial<PaymentListQuery> = {}) => readPaymentPage(query(overrides), runner, dialect, NOW)
|
|
81
|
+
|
|
82
|
+
// Every time range counts exactly the payments inside it.
|
|
83
|
+
for (const days of [1, 7, 30, 0] as const)
|
|
84
|
+
expect((await read({ days })).total).toBe(within(days).length)
|
|
85
|
+
|
|
86
|
+
// The summary and breakdown describe the matching set, not the page.
|
|
87
|
+
const week = await read({ days: 7, perPage: 10 })
|
|
88
|
+
const inWeek = within(7)
|
|
89
|
+
expect(week.records.length).toBeLessThanOrEqual(10)
|
|
90
|
+
expect(week.summary.total).toBe(inWeek.length)
|
|
91
|
+
const successful = inWeek.filter(payment => SUCCESSFUL.has(payment.status))
|
|
92
|
+
const failed = inWeek.filter(payment => payment.status === 'failed')
|
|
93
|
+
expect(week.summary.successful).toBe(successful.length)
|
|
94
|
+
expect(week.summary.successRate).toBe(Math.round((successful.length / (successful.length + failed.length)) * 1000) / 10)
|
|
95
|
+
const captured = (currency: string) => successful.filter(payment => payment.currency.toUpperCase() === currency).reduce((sum, payment) => sum + payment.amount, 0)
|
|
96
|
+
expect(week.summary.capturedByCurrency.USD).toBe(captured('USD'))
|
|
97
|
+
expect(week.summary.capturedByCurrency.EUR).toBe(captured('EUR'))
|
|
98
|
+
expect(week.summary.currencies).toEqual(['EUR', 'USD'])
|
|
99
|
+
const statusCounts = Object.fromEntries(week.breakdown.statuses.map(row => [row.key, row.count]))
|
|
100
|
+
for (const status of new Set(inWeek.map(payment => payment.status)))
|
|
101
|
+
expect(statusCounts[status]).toBe(inWeek.filter(payment => payment.status === status).length)
|
|
102
|
+
|
|
103
|
+
// Newest first with id breaking ties, stable across pages.
|
|
104
|
+
const all = [...PAYMENTS].sort((a, b) => a.hoursAgo - b.hoursAgo || b.id - a.id).map(payment => String(payment.id))
|
|
105
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
106
|
+
expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(all)
|
|
107
|
+
expect((await read({ page: 9 })).page).toBe(3)
|
|
108
|
+
|
|
109
|
+
// Filters on the enum columns, and a value no payment has, which is no match rather than an error.
|
|
110
|
+
expect((await read({ status: 'failed', perPage: 100 })).total).toBe(PAYMENTS.filter(payment => payment.status === 'failed').length)
|
|
111
|
+
expect((await read({ method: 'paypal', perPage: 100 })).total).toBe(PAYMENTS.filter(payment => payment.method === 'paypal').length)
|
|
112
|
+
expect((await read({ status: 'not-a-status' })).total).toBe(0)
|
|
113
|
+
|
|
114
|
+
// Search: enum text in any case, email with a literal %, and the order id.
|
|
115
|
+
expect((await read({ search: 'PAYPAL', perPage: 100 })).total).toBe(PAYMENTS.filter(payment => payment.method === 'paypal').length)
|
|
116
|
+
expect((await read({ search: '100%' })).records.map(record => record.id)).toEqual(['7'])
|
|
117
|
+
expect((await read({ search: '712' })).records.map(record => record.id)).toEqual(['12'])
|
|
118
|
+
|
|
119
|
+
// Amount sorts high first; status sorts by name, newest first within one.
|
|
120
|
+
const amounts = (await read({ sort: 'amount', direction: 'desc', perPage: 100 })).records.map(record => record.amount)
|
|
121
|
+
expect(amounts).toEqual([...amounts].sort((a, b) => b - a))
|
|
122
|
+
const byStatus = (await read({ sort: 'status', direction: 'asc', perPage: 100 })).records.map(record => record.status)
|
|
123
|
+
expect(byStatus).toEqual([...byStatus].sort())
|
|
124
|
+
|
|
125
|
+
// The export holds every match across batches, in order.
|
|
126
|
+
const exported = await readPaymentsForExport({ search: '', status: '', method: '', days: 0, sort: 'created', direction: 'desc' }, runner, dialect, NOW, 5)
|
|
127
|
+
expect(exported.map(record => record.id)).toEqual(all)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
describe('readPaymentPage on SQLite', () => {
|
|
131
|
+
test('ranges, summary, breakdown, filters, search, sorts, pages and export', async () => {
|
|
132
|
+
const database = new Database(':memory:')
|
|
133
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
134
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
135
|
+
})
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
139
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
140
|
+
|
|
141
|
+
test.skipIf(!connection)(`readPaymentPage on ${dialect}: ranges, summary, breakdown, filters, search, sorts, pages and export`, async () => {
|
|
142
|
+
const url = new URL(connection!)
|
|
143
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
144
|
+
throw new Error('Payment list tests require a local disposable database server')
|
|
145
|
+
|
|
146
|
+
const name = `stacks_payment_list_${crypto.randomUUID().replaceAll('-', '')}`
|
|
147
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
148
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
149
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
150
|
+
const scoped = new URL(url.href)
|
|
151
|
+
scoped.pathname = `/${name}`
|
|
152
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
153
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
154
|
+
|
|
155
|
+
try {
|
|
156
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
157
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
await database.close()
|
|
161
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
162
|
+
finally { await admin.close() }
|
|
163
|
+
}
|
|
164
|
+
}, 60_000)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
describe('parsePaymentListQuery', () => {
|
|
168
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
169
|
+
|
|
170
|
+
test('defaults to every payment, newest first, 25 a page', () => {
|
|
171
|
+
expect(parsePaymentListQuery(reader({}))).toEqual({ search: '', status: '', method: '', days: 0, sort: 'created', direction: 'desc', page: 1, perPage: 25 })
|
|
172
|
+
expect(parsePaymentListQuery(reader({ days: 'all' }))).toHaveProperty('days', 0)
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
test('accepts only the ranges the page offers', () => {
|
|
176
|
+
expect(parsePaymentListQuery(reader({ days: '30' }))).toHaveProperty('days', 30)
|
|
177
|
+
expect(parsePaymentListQuery(reader({ days: '45' }))).toHaveProperty('error')
|
|
178
|
+
expect(parsePaymentListQuery(reader({ sort: 'card_last_four' }))).toHaveProperty('error')
|
|
179
|
+
})
|
|
180
|
+
})
|
|
@@ -0,0 +1,272 @@
|
|
|
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 { commerceCurrency, commerceIdentifier, commerceValue, referencedIds } from './commerce-record'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
|
|
8
|
+
import type { PaymentRecord, PaymentSummary } from './payment-records'
|
|
9
|
+
import { normalizePaymentRecord } from './payment-records'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One page of payments, searched, filtered, sorted, counted and summarised by
|
|
13
|
+
* the database (stacksjs/stacks#3218).
|
|
14
|
+
*
|
|
15
|
+
* The Payments page used to read the newest 500 payments and do all of that
|
|
16
|
+
* in the browser, so a payment past the 500th could not be found, and the
|
|
17
|
+
* summary for "the current view" described only what those 500 held.
|
|
18
|
+
*/
|
|
19
|
+
export const PAYMENT_SORTS = ['created', 'id', 'billing', 'amount', 'method', 'status'] as const
|
|
20
|
+
export type PaymentSort = typeof PAYMENT_SORTS[number]
|
|
21
|
+
|
|
22
|
+
/** The time ranges the page offers, in days. `0` is all time. */
|
|
23
|
+
export const PAYMENT_RANGES = [1, 7, 30, 90, 365, 0] as const
|
|
24
|
+
|
|
25
|
+
/** The statuses that count as captured, as `isSuccessfulPayment` has them. */
|
|
26
|
+
const SUCCESSFUL = ['completed', 'succeeded', 'partiallyRefunded', 'refunded']
|
|
27
|
+
|
|
28
|
+
/** What the breakdown panels show for the matching payments. */
|
|
29
|
+
export interface PaymentBreakdown {
|
|
30
|
+
statuses: Array<{ key: string, count: number }>
|
|
31
|
+
methods: Array<{ key: string, count: number }>
|
|
32
|
+
currencies: Array<{ currency: string, captured: number, refunded: number }>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface PaymentListQuery {
|
|
36
|
+
search: string
|
|
37
|
+
status: string
|
|
38
|
+
method: string
|
|
39
|
+
/** Days back from now; 0 for all time. */
|
|
40
|
+
days: number
|
|
41
|
+
sort: PaymentSort
|
|
42
|
+
direction: 'asc' | 'desc'
|
|
43
|
+
page: number
|
|
44
|
+
perPage: number
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function parsePaymentListQuery(read: QueryReader): PaymentListQuery | { error: string } {
|
|
48
|
+
const pageText = queryText(read, 'page')
|
|
49
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
50
|
+
if (!Number.isInteger(page) || page < 1)
|
|
51
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
52
|
+
|
|
53
|
+
const sizeText = queryText(read, 'per_page')
|
|
54
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
55
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
56
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
57
|
+
|
|
58
|
+
const sort = queryText(read, 'sort') || 'created'
|
|
59
|
+
if (!(PAYMENT_SORTS as readonly string[]).includes(sort))
|
|
60
|
+
return { error: `sort must be one of ${PAYMENT_SORTS.join(', ')}.` }
|
|
61
|
+
|
|
62
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
63
|
+
const direction = directionText === '' ? (sort === 'created' || sort === 'amount' ? 'desc' : 'asc') : directionText
|
|
64
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
65
|
+
return { error: 'direction must be asc or desc.' }
|
|
66
|
+
|
|
67
|
+
const rangeText = queryText(read, 'days')
|
|
68
|
+
const days = rangeText === '' || rangeText === 'all' ? 0 : Number(rangeText)
|
|
69
|
+
if (!(PAYMENT_RANGES as readonly number[]).includes(days))
|
|
70
|
+
return { error: 'days must be 1, 7, 30, 90, 365 or all.' }
|
|
71
|
+
|
|
72
|
+
const search = queryText(read, 'q')
|
|
73
|
+
if (search.length > 200)
|
|
74
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
75
|
+
|
|
76
|
+
const status = queryText(read, 'status')
|
|
77
|
+
const method = queryText(read, 'method')
|
|
78
|
+
if (status.length > 100 || method.length > 100)
|
|
79
|
+
return { error: 'status and method must be 100 characters or fewer.' }
|
|
80
|
+
|
|
81
|
+
return { search, status, method, days, sort: sort as PaymentSort, direction, page, perPage }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function sortExpression(sort: PaymentSort, dialect: QueryBuilderDialect): string {
|
|
85
|
+
switch (sort) {
|
|
86
|
+
case 'id': return 'id'
|
|
87
|
+
case 'billing': return `LOWER(COALESCE(billing_email, ''))`
|
|
88
|
+
case 'amount': return 'amount'
|
|
89
|
+
case 'method': return asText('method', dialect)
|
|
90
|
+
case 'status': return asText('status', dialect)
|
|
91
|
+
default: return 'created_at'
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The WHERE clause and its values for a query's search, filters and time range. */
|
|
96
|
+
export function paymentFilter(query: Pick<PaymentListQuery, 'search' | 'status' | 'method' | 'days'>, dialect: QueryBuilderDialect, now: Date = new Date()): { where: string, values: unknown[] } {
|
|
97
|
+
const { bind, values } = binder(dialect)
|
|
98
|
+
const clauses: string[] = []
|
|
99
|
+
if (query.status)
|
|
100
|
+
clauses.push(`${asText('status', dialect)} = ${bind(query.status)}`)
|
|
101
|
+
if (query.method)
|
|
102
|
+
clauses.push(`${asText('method', dialect)} = ${bind(query.method)}`)
|
|
103
|
+
if (query.days > 0) {
|
|
104
|
+
const since = bind(sqlDateTime(new Date(now.getTime() - query.days * 86_400_000)))
|
|
105
|
+
// SQLite keeps timestamps as text and compares them as text, where
|
|
106
|
+
// "2026-11-06 10:00" and "2026-11-06T09:00" sort the wrong way round, so
|
|
107
|
+
// both sides go through datetime() there. The others parse the value.
|
|
108
|
+
clauses.push(dialect === 'sqlite' ? `datetime(created_at) >= datetime(${since})` : `created_at >= ${since}`)
|
|
109
|
+
}
|
|
110
|
+
if (query.search) {
|
|
111
|
+
const pattern = containsPattern(query.search)
|
|
112
|
+
const columns = [
|
|
113
|
+
asText('id', dialect),
|
|
114
|
+
`COALESCE(reference_number, '')`,
|
|
115
|
+
`COALESCE(billing_email, '')`,
|
|
116
|
+
`COALESCE(transaction_id, '')`,
|
|
117
|
+
`COALESCE(payment_provider, '')`,
|
|
118
|
+
`COALESCE(${asText('order_id', dialect)}, '')`,
|
|
119
|
+
asText('method', dialect),
|
|
120
|
+
asText('status', dialect),
|
|
121
|
+
]
|
|
122
|
+
clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
123
|
+
}
|
|
124
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Payments turned into records, against exactly the orders and customers they reference. */
|
|
128
|
+
async function recordsFor(payments: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<PaymentRecord[]> {
|
|
129
|
+
if (payments.length === 0)
|
|
130
|
+
return []
|
|
131
|
+
const orderIds = referencedIds(payments, 'order_id')
|
|
132
|
+
const customerIds = referencedIds(payments, 'customer_id')
|
|
133
|
+
const [orders, customers] = await Promise.all([
|
|
134
|
+
orderIds.length > 0 ? run.unsafe(`SELECT id FROM orders WHERE id IN (${idPlaceholders(orderIds, dialect)})`, orderIds).execute() : [],
|
|
135
|
+
customerIds.length > 0 ? run.unsafe(`SELECT id FROM customers WHERE id IN (${idPlaceholders(customerIds, dialect)})`, customerIds).execute() : [],
|
|
136
|
+
])
|
|
137
|
+
const ids = (result: unknown, source: string) => new Set(sqlRows(result).map(row => commerceIdentifier(commerceValue(row, 'id'), source)))
|
|
138
|
+
const relationships = { orderIds: ids(orders, 'Order'), customerIds: ids(customers, 'Customer') }
|
|
139
|
+
return payments.map(payment => normalizePaymentRecord(payment, relationships))
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The summary and breakdown of the matching payments, as `summarizePayments`
|
|
144
|
+
* and the breakdown panels computed them over the records they had.
|
|
145
|
+
*/
|
|
146
|
+
async function summarize(where: string, values: unknown[], run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<{ summary: PaymentSummary, breakdown: PaymentBreakdown }> {
|
|
147
|
+
const status = asText('status', dialect)
|
|
148
|
+
const successful = `${status} IN (${SUCCESSFUL.map(name => `'${name}'`).join(', ')})`
|
|
149
|
+
const grouped = (column: string) =>
|
|
150
|
+
run.unsafe(`SELECT ${asText(column, dialect)} AS value, COUNT(*) AS item_count FROM payments${where} GROUP BY ${asText(column, dialect)}`, values).execute()
|
|
151
|
+
const [counts, currencies, byStatus, byMethod] = await Promise.all([
|
|
152
|
+
run.unsafe(`SELECT COUNT(*) AS total_count, SUM(CASE WHEN ${successful} THEN 1 ELSE 0 END) AS successful_count, SUM(CASE WHEN ${status} = 'failed' THEN 1 ELSE 0 END) AS failed_count FROM payments${where}`, values).execute(),
|
|
153
|
+
run.unsafe(`SELECT currency, SUM(CASE WHEN ${successful} THEN 1 ELSE 0 END) AS captured_count, SUM(CASE WHEN ${successful} THEN amount ELSE 0 END) AS captured_total, SUM(CASE WHEN refund_amount > 0 THEN 1 ELSE 0 END) AS refund_count, SUM(CASE WHEN refund_amount > 0 THEN refund_amount ELSE 0 END) AS refunded_total FROM payments${where} GROUP BY currency`, values).execute(),
|
|
154
|
+
grouped('status'),
|
|
155
|
+
grouped('method'),
|
|
156
|
+
])
|
|
157
|
+
const count = sqlRows(counts)[0] ?? {}
|
|
158
|
+
const total = countOf(count.total_count)
|
|
159
|
+
const success = countOf(count.successful_count)
|
|
160
|
+
const settled = success + countOf(count.failed_count)
|
|
161
|
+
|
|
162
|
+
const names = new Set<string>()
|
|
163
|
+
const capturedByCurrency: Record<string, number> = {}
|
|
164
|
+
const refundedByCurrency: Record<string, number> = {}
|
|
165
|
+
const perCurrency = new Map<string, { currency: string, captured: number, refunded: number }>()
|
|
166
|
+
for (const row of sqlRows(currencies)) {
|
|
167
|
+
// Normalized as the records are, so "usd" and "USD" are one currency.
|
|
168
|
+
const currency = commerceCurrency(row.currency, 'Payment summary')
|
|
169
|
+
names.add(currency)
|
|
170
|
+
if (countOf(row.captured_count) > 0)
|
|
171
|
+
capturedByCurrency[currency] = (capturedByCurrency[currency] ?? 0) + countOf(row.captured_total)
|
|
172
|
+
if (countOf(row.refund_count) > 0)
|
|
173
|
+
refundedByCurrency[currency] = (refundedByCurrency[currency] ?? 0) + countOf(row.refunded_total)
|
|
174
|
+
const entry = perCurrency.get(currency) ?? { currency, captured: 0, refunded: 0 }
|
|
175
|
+
entry.captured += countOf(row.captured_total)
|
|
176
|
+
entry.refunded += countOf(row.refunded_total)
|
|
177
|
+
perCurrency.set(currency, entry)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const tally = (result: unknown) => {
|
|
181
|
+
const merged = new Map<string, number>()
|
|
182
|
+
for (const row of sqlRows(result)) {
|
|
183
|
+
const key = String(row.value ?? '').trim() || 'unknown'
|
|
184
|
+
merged.set(key, (merged.get(key) ?? 0) + countOf(row.item_count))
|
|
185
|
+
}
|
|
186
|
+
return [...merged.entries()].map(([key, count]) => ({ key, count }))
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
summary: {
|
|
191
|
+
total,
|
|
192
|
+
successful: success,
|
|
193
|
+
currencies: [...names].sort(),
|
|
194
|
+
capturedByCurrency,
|
|
195
|
+
refundedByCurrency,
|
|
196
|
+
successRate: settled ? Math.round((success / settled) * 1000) / 10 : 0,
|
|
197
|
+
},
|
|
198
|
+
breakdown: {
|
|
199
|
+
statuses: tally(byStatus),
|
|
200
|
+
methods: tally(byMethod),
|
|
201
|
+
currencies: [...perCurrency.values()],
|
|
202
|
+
},
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The filter choices: every status and method any payment has. */
|
|
207
|
+
async function choices(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<{ statuses: string[], methods: string[] }> {
|
|
208
|
+
const [statuses, methods] = await Promise.all([
|
|
209
|
+
run.unsafe(`SELECT DISTINCT ${asText('status', dialect)} AS value FROM payments WHERE status IS NOT NULL`).execute(),
|
|
210
|
+
run.unsafe(`SELECT DISTINCT ${asText('method', dialect)} AS value FROM payments WHERE method IS NOT NULL`).execute(),
|
|
211
|
+
])
|
|
212
|
+
const values = (result: unknown) => [...new Set(sqlRows(result).map(row => String(row.value ?? '').trim()).filter(Boolean))].sort()
|
|
213
|
+
return { statuses: values(statuses), methods: values(methods) }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function orderBy(query: Pick<PaymentListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
217
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
218
|
+
// Status sorts newest first within a status, as the page did; the id breaks
|
|
219
|
+
// every remaining tie, so pages never repeat or skip a payment.
|
|
220
|
+
const within = query.sort === 'status' ? ', created_at DESC' : ''
|
|
221
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}${within}, id ${direction}`
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export interface PaymentPage {
|
|
225
|
+
records: PaymentRecord[]
|
|
226
|
+
total: number
|
|
227
|
+
page: number
|
|
228
|
+
summary: PaymentSummary
|
|
229
|
+
breakdown: PaymentBreakdown
|
|
230
|
+
statuses: string[]
|
|
231
|
+
methods: string[]
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export async function readPaymentPage(
|
|
235
|
+
query: PaymentListQuery,
|
|
236
|
+
run: CommerceSqlRunner = db,
|
|
237
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
238
|
+
now: Date = new Date(),
|
|
239
|
+
): Promise<PaymentPage> {
|
|
240
|
+
const { where, values } = paymentFilter(query, dialect, now)
|
|
241
|
+
const [{ summary, breakdown }, options] = await Promise.all([
|
|
242
|
+
summarize(where, values, run, dialect),
|
|
243
|
+
choices(run, dialect),
|
|
244
|
+
])
|
|
245
|
+
const page = pageWithin(query.page, summary.total, query.perPage)
|
|
246
|
+
const payments = await run.unsafe(
|
|
247
|
+
`SELECT * FROM payments${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
248
|
+
values,
|
|
249
|
+
).execute()
|
|
250
|
+
return { records: await recordsFor(sqlRows(payments), run, dialect), total: summary.total, page, summary, breakdown, ...options }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Every payment matching the query, in its order, for the CSV export, a batch at a time. */
|
|
254
|
+
export async function readPaymentsForExport(
|
|
255
|
+
query: Omit<PaymentListQuery, 'page' | 'perPage'>,
|
|
256
|
+
run: CommerceSqlRunner = db,
|
|
257
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
258
|
+
now: Date = new Date(),
|
|
259
|
+
batchSize: number = 500,
|
|
260
|
+
): Promise<PaymentRecord[]> {
|
|
261
|
+
const { where, values } = paymentFilter(query, dialect, now)
|
|
262
|
+
const records: PaymentRecord[] = []
|
|
263
|
+
for (let offset = 0; ; offset += batchSize) {
|
|
264
|
+
const batch = sqlRows(await run.unsafe(
|
|
265
|
+
`SELECT * FROM payments${where}${orderBy(query, dialect)} LIMIT ${batchSize} OFFSET ${offset}`,
|
|
266
|
+
values,
|
|
267
|
+
).execute())
|
|
268
|
+
records.push(...await recordsFor(batch, run, dialect))
|
|
269
|
+
if (batch.length < batchSize)
|
|
270
|
+
return records
|
|
271
|
+
}
|
|
272
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import { searchCustomerChoices } from './commerce-choices'
|
|
5
|
+
import type { PosCatalogQuery } from './commerce-pos-catalog'
|
|
6
|
+
import { parsePosCatalogQuery, parsePosIds, readPosCatalogPage, readPosProducts, readPosSettings } from './commerce-pos-catalog'
|
|
7
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The point of sale's catalogue, settings and customers against each
|
|
11
|
+
* dialect's real engine (stacksjs/stacks#3218), over 520 products,
|
|
12
|
+
* categories, manufacturers and customers: it used to read the first 500 of
|
|
13
|
+
* each.
|
|
14
|
+
*/
|
|
15
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
16
|
+
|
|
17
|
+
const ROWS = 520
|
|
18
|
+
const pad = (id: number) => String(id).padStart(3, '0')
|
|
19
|
+
|
|
20
|
+
/** Products 511 to 520 are in category 515 and by manufacturer 520; the rest share seven categories. */
|
|
21
|
+
const PRODUCTS = Array.from({ length: ROWS }, (_, index) => {
|
|
22
|
+
const id = index + 1
|
|
23
|
+
return {
|
|
24
|
+
id,
|
|
25
|
+
name: id === 9 ? 'Latte_100%' : id === 10 ? 'Latte 1000' : `${id % 2 === 0 ? 'item' : 'Item'} ${pad(id)}`,
|
|
26
|
+
available: id % 4 !== 0,
|
|
27
|
+
inventory: id % 5 === 0 ? 0 : id,
|
|
28
|
+
category: id > 510 ? 515 : (id % 7) + 1,
|
|
29
|
+
manufacturer: id > 510 ? 520 : (id % 3) + 1,
|
|
30
|
+
}
|
|
31
|
+
})
|
|
32
|
+
type Product = typeof PRODUCTS[number]
|
|
33
|
+
const sellable = (product: Product) => product.available && product.inventory > 0
|
|
34
|
+
const byName = (a: Product, b: Product) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()) || a.id - b.id
|
|
35
|
+
|
|
36
|
+
function query(overrides: Partial<PosCatalogQuery> = {}): PosCatalogQuery {
|
|
37
|
+
return { search: '', category: '', availability: '', page: 1, perPage: 50, ...overrides }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
41
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
42
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
43
|
+
const bool = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
|
|
44
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
45
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
46
|
+
const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
|
|
47
|
+
const flag = (value: boolean) => dialect === 'postgres' ? value : (value ? 1 : 0)
|
|
48
|
+
let customerStatus = text
|
|
49
|
+
let rateStatus = text
|
|
50
|
+
if (dialect === 'postgres') {
|
|
51
|
+
await run(`CREATE TYPE customer_status AS ENUM ('Active', 'Inactive')`)
|
|
52
|
+
await run(`CREATE TYPE rate_status AS ENUM ('active', 'inactive')`)
|
|
53
|
+
customerStatus = 'customer_status'
|
|
54
|
+
rateStatus = 'rate_status'
|
|
55
|
+
}
|
|
56
|
+
if (dialect === 'mysql') {
|
|
57
|
+
customerStatus = `ENUM('Active', 'Inactive')`
|
|
58
|
+
rateStatus = `ENUM('active', 'inactive')`
|
|
59
|
+
}
|
|
60
|
+
await run(`CREATE TABLE categories (id ${pk}, name ${text})`)
|
|
61
|
+
await run(`CREATE TABLE manufacturers (id ${pk}, manufacturer ${text})`)
|
|
62
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text}, slug ${text}, description ${text} NULL, price INTEGER, image_url ${text} NULL, is_available ${bool}, inventory_count INTEGER, preparation_time INTEGER, allergens ${text} NULL, nutritional_info ${text} NULL, category_id INTEGER NULL, manufacturer_id INTEGER NULL, created_at ${time})`)
|
|
63
|
+
await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text}, phone ${text} NULL, status ${customerStatus})`)
|
|
64
|
+
await run(`CREATE TABLE tax_rates (id ${pk}, rate INTEGER, status ${rateStatus}, is_default ${bool})`)
|
|
65
|
+
|
|
66
|
+
const all = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
67
|
+
await run(`INSERT INTO categories (id, name) VALUES ${rows(ROWS, 2)}`, all.flatMap(id => [id, id === 3 ? 'bakery' : `Category ${pad(id)}`]))
|
|
68
|
+
await run(`INSERT INTO manufacturers (id, manufacturer) VALUES ${rows(ROWS, 2)}`, all.flatMap(id => [id, `Maker ${pad(id)}`]))
|
|
69
|
+
await run(
|
|
70
|
+
`INSERT INTO products (id, name, slug, price, is_available, inventory_count, preparation_time, allergens, category_id, manufacturer_id, created_at) VALUES ${rows(ROWS, 11)}`,
|
|
71
|
+
PRODUCTS.flatMap(product => [product.id, product.name, `item-${product.id}`, 100 + product.id, flag(product.available), product.inventory, 5, '[]', product.category, product.manufacturer, '2026-11-01 09:00:00']),
|
|
72
|
+
)
|
|
73
|
+
await run(`INSERT INTO customers (id, name, email, phone, status) VALUES ${rows(ROWS, 5)}`, all.flatMap(id => [id, id === 515 ? 'Quinn Late' : `Customer ${pad(id)}`, `buyer${id}@shop.test`, null, id % 2 === 1 ? 'Active' : 'Inactive']))
|
|
74
|
+
// The default active rate wins over an earlier active one and an inactive default.
|
|
75
|
+
await run(`INSERT INTO tax_rates (id, rate, status, is_default) VALUES ${rows(3, 4)}`, [1, 5, 'inactive', flag(true), 2, 7, 'active', flag(false), 3, 9, 'active', flag(true)])
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
79
|
+
const page = (overrides: Partial<PosCatalogQuery> = {}) => readPosCatalogPage(query(overrides), runner, dialect)
|
|
80
|
+
const idsOf = (result: { products: Array<{ id: string }> }) => result.products.map(product => product.id)
|
|
81
|
+
const ids = (products: Product[]) => products.map(product => String(product.id))
|
|
82
|
+
|
|
83
|
+
// Settings, counted over every product.
|
|
84
|
+
const settings = await readPosSettings(runner, dialect)
|
|
85
|
+
expect(settings.taxRate).toBe(9)
|
|
86
|
+
expect(settings.summary).toEqual({
|
|
87
|
+
products: ROWS,
|
|
88
|
+
sellable: PRODUCTS.filter(sellable).length,
|
|
89
|
+
inventory: PRODUCTS.reduce((sum, product) => sum + product.inventory, 0),
|
|
90
|
+
})
|
|
91
|
+
expect(settings.categories.map(category => category.label)).toEqual(['bakery', 'Category 001', 'Category 002', 'Category 004', 'Category 005', 'Category 006', 'Category 007', 'Category 515'])
|
|
92
|
+
|
|
93
|
+
// The catalogue by name ignoring case, paged, and every filter.
|
|
94
|
+
const sorted = [...PRODUCTS].sort(byName)
|
|
95
|
+
expect(idsOf(await page())).toEqual(ids(sorted.slice(0, 50)))
|
|
96
|
+
expect(idsOf(await page({ page: 11 }))).toEqual(ids(sorted.slice(500)))
|
|
97
|
+
expect((await page({ page: 99 })).page).toBe(11)
|
|
98
|
+
expect((await page({ availability: 'sellable' })).total).toBe(PRODUCTS.filter(sellable).length)
|
|
99
|
+
expect((await page({ availability: 'unsellable' })).total).toBe(PRODUCTS.filter(product => !sellable(product)).length)
|
|
100
|
+
expect(idsOf(await page({ category: '515' }))).toEqual(ids(PRODUCTS.filter(product => product.category === 515).sort(byName)))
|
|
101
|
+
expect(idsOf(await page({ search: '100%' }))).toEqual(['9'])
|
|
102
|
+
expect((await page({ search: 'bakery' })).total).toBe(PRODUCTS.filter(product => product.category === 3).length)
|
|
103
|
+
|
|
104
|
+
// Category and manufacturer past the 500th, read by the ids the page references.
|
|
105
|
+
const last = (await page({ category: '515' })).products.find(product => product.id === '520')!
|
|
106
|
+
expect(last).toMatchObject({ name: 'item 520', categoryId: '515', categoryName: 'Category 515' })
|
|
107
|
+
|
|
108
|
+
// The cart's own products, whatever page the catalogue shows; a deleted one is absent.
|
|
109
|
+
expect((await readPosProducts([520, 3, 99_999], runner, dialect)).map(product => product.id).sort()).toEqual(['3', '520'])
|
|
110
|
+
|
|
111
|
+
// The checkout's customers: Active only, and found past the 500th.
|
|
112
|
+
const active = await searchCustomerChoices({ search: '', limit: 5 }, runner, dialect, { activeOnly: true })
|
|
113
|
+
expect(active.total).toBe(ROWS / 2)
|
|
114
|
+
expect((await searchCustomerChoices({ search: 'quinn', limit: 5 }, runner, dialect, { activeOnly: true })).choices.map(choice => choice.id)).toEqual(['515'])
|
|
115
|
+
expect((await searchCustomerChoices({ search: 'customer 002', limit: 5 }, runner, dialect, { activeOnly: true })).total).toBe(0)
|
|
116
|
+
expect((await searchCustomerChoices({ search: 'customer 002', limit: 5 }, runner, dialect)).total).toBe(1)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
describe('point of sale catalogue on SQLite', () => {
|
|
120
|
+
test('settings, catalogue, cart products and customers', async () => {
|
|
121
|
+
const database = new Database(':memory:')
|
|
122
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
123
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
124
|
+
})
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
128
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
129
|
+
|
|
130
|
+
test.skipIf(!connection)(`point of sale catalogue on ${dialect}: settings, catalogue, cart products and customers`, async () => {
|
|
131
|
+
const url = new URL(connection!)
|
|
132
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
133
|
+
throw new Error('Point of sale tests require a local disposable database server')
|
|
134
|
+
|
|
135
|
+
const name = `stacks_pos_catalog_${crypto.randomUUID().replaceAll('-', '')}`
|
|
136
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
137
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
138
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
139
|
+
const scoped = new URL(url.href)
|
|
140
|
+
scoped.pathname = `/${name}`
|
|
141
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
142
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
143
|
+
|
|
144
|
+
try {
|
|
145
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
146
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
await database.close()
|
|
150
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
151
|
+
finally { await admin.close() }
|
|
152
|
+
}
|
|
153
|
+
}, 60_000)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
describe('point of sale query parsing', () => {
|
|
157
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
158
|
+
|
|
159
|
+
test('the catalogue defaults to every product, 50 a page', () => {
|
|
160
|
+
expect(parsePosCatalogQuery(reader({}))).toEqual({ search: '', category: '', availability: '', page: 1, perPage: 50 })
|
|
161
|
+
expect(parsePosCatalogQuery(reader({ availability: 'available' }))).toHaveProperty('error')
|
|
162
|
+
expect(parsePosCatalogQuery(reader({ category: 'drinks' }))).toHaveProperty('error')
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
test('cart ids are bounded product ids', () => {
|
|
166
|
+
expect(parsePosIds(reader({}))).toEqual([])
|
|
167
|
+
expect(parsePosIds(reader({ ids: '3, 520,3' }))).toEqual([3, 520])
|
|
168
|
+
expect(parsePosIds(reader({ ids: '3,x' }))).toHaveProperty('error')
|
|
169
|
+
expect(parsePosIds(reader({ ids: Array.from({ length: 101 }, (_, i) => i + 1).join(',') }))).toHaveProperty('error')
|
|
170
|
+
})
|
|
171
|
+
})
|