@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,88 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import { searchCustomerChoices, searchProductChoices } from './commerce-choices'
|
|
5
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The commerce dialogs' product and customer searches against each dialect's
|
|
9
|
+
* real engine (stacksjs/stacks#3218), over 600 of each: the waitlist dialogs
|
|
10
|
+
* used to be handed the first 500.
|
|
11
|
+
*/
|
|
12
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
13
|
+
|
|
14
|
+
const ROWS = 600
|
|
15
|
+
const productName = (id: number) => id === 600 ? 'Zebra Tea' : id === 7 ? 'apple_50% off' : id === 8 ? 'apple 500 box' : `Product ${String(id).padStart(3, '0')}`
|
|
16
|
+
const customerName = (id: number) => id === 599 ? 'mia Late' : id === 3 ? 'Mia early' : `Customer ${String(id).padStart(3, '0')}`
|
|
17
|
+
|
|
18
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
19
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
20
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
21
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
22
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text}, inventory_count INTEGER)`)
|
|
23
|
+
await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text}, phone ${text} NULL)`)
|
|
24
|
+
const all = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
25
|
+
await run(`INSERT INTO products (id, name, inventory_count) VALUES ${all.map((_, i) => `(${p(3 * i + 1)}, ${p(3 * i + 2)}, ${p(3 * i + 3)})`).join(', ')}`, all.flatMap(id => [id, productName(id), id % 9]))
|
|
26
|
+
await run(`INSERT INTO customers (id, name, email, phone) VALUES ${all.map((_, i) => `(${p(4 * i + 1)}, ${p(4 * i + 2)}, ${p(4 * i + 3)}, ${p(4 * i + 4)})`).join(', ')}`, all.flatMap(id => [id, customerName(id), `buyer${id}@shop.test`, id === 444 ? '+1 555 0444' : null]))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
30
|
+
const products = (search: string, limit = 25) => searchProductChoices({ search, limit }, runner, dialect)
|
|
31
|
+
const customers = (search: string, limit = 25) => searchCustomerChoices({ search, limit }, runner, dialect)
|
|
32
|
+
|
|
33
|
+
// Unsearched: bounded, by name ignoring case, with how many there are.
|
|
34
|
+
const first = await products('')
|
|
35
|
+
expect(first.total).toBe(ROWS)
|
|
36
|
+
expect(first.choices.length).toBe(25)
|
|
37
|
+
expect(first.choices.slice(0, 2).map(choice => choice.label)).toEqual(['apple 500 box', 'apple_50% off'])
|
|
38
|
+
|
|
39
|
+
// The 600th of each can be found, and a literal % matches only itself.
|
|
40
|
+
expect(await products('zebra')).toEqual({ choices: [{ id: '600', label: 'Zebra Tea', detail: '6 in inventory' }], total: 1 })
|
|
41
|
+
expect((await products('50%')).choices.map(choice => choice.id)).toEqual(['7'])
|
|
42
|
+
expect((await products('600')).choices.map(choice => choice.id)).toEqual(['600'])
|
|
43
|
+
expect((await customers('MIA')).choices.map(choice => choice.label)).toEqual(['Mia early', 'mia Late'])
|
|
44
|
+
expect((await customers('buyer599@')).choices).toEqual([{ id: '599', label: 'mia Late', detail: 'buyer599@shop.test', email: 'buyer599@shop.test', phone: '' }])
|
|
45
|
+
expect((await customers('0444')).choices.map(choice => choice.id)).toEqual(['444'])
|
|
46
|
+
|
|
47
|
+
// The limit bounds the choices, not the count.
|
|
48
|
+
const bounded = await customers('customer', 5)
|
|
49
|
+
expect(bounded.choices.length).toBe(5)
|
|
50
|
+
expect(bounded.total).toBe(ROWS - 2)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
describe('commerce choices on SQLite', () => {
|
|
54
|
+
test('products and customers by name, email, phone and id', async () => {
|
|
55
|
+
const database = new Database(':memory:')
|
|
56
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
57
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
58
|
+
})
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
62
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
63
|
+
|
|
64
|
+
test.skipIf(!connection)(`commerce choices on ${dialect}: products and customers by name, email, phone and id`, async () => {
|
|
65
|
+
const url = new URL(connection!)
|
|
66
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
67
|
+
throw new Error('Commerce choice tests require a local disposable database server')
|
|
68
|
+
|
|
69
|
+
const name = `stacks_commerce_choices_${crypto.randomUUID().replaceAll('-', '')}`
|
|
70
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
71
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
72
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
73
|
+
const scoped = new URL(url.href)
|
|
74
|
+
scoped.pathname = `/${name}`
|
|
75
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
76
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
80
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
await database.close()
|
|
84
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
85
|
+
finally { await admin.close() }
|
|
86
|
+
}
|
|
87
|
+
}, 60_000)
|
|
88
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { db, getDatabaseDialect } from '@stacksjs/database/runtime'
|
|
3
|
+
import { containsPattern, countOf } from '../Content/content-list'
|
|
4
|
+
import type { NamedSearchQuery } from '../named-search'
|
|
5
|
+
import type { CustomerChoice, ProductChoice } from './commerce-choice-records'
|
|
6
|
+
import { normalizeCustomerChoice, normalizeProductChoice } from './commerce-choice-records'
|
|
7
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
8
|
+
import { asText, binder, sqlRows } from './commerce-sql'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The products and customers a commerce dialog offers, searched by the
|
|
12
|
+
* database (stacksjs/stacks#3218). The waitlist dialogs used to be handed the
|
|
13
|
+
* first 500 of each by name with every page, so an entry could not be made
|
|
14
|
+
* for a product or customer past the 500th.
|
|
15
|
+
*
|
|
16
|
+
* The query is the pickers' usual `q` and `limit` (`parseNamedSearchQuery`):
|
|
17
|
+
* case is ignored, `%` and `_` are characters to find, the answer is bounded,
|
|
18
|
+
* and `total` says how many matched. The choices themselves, and their
|
|
19
|
+
* normalizers, are in commerce-choice-records.ts.
|
|
20
|
+
*/
|
|
21
|
+
export type { CustomerChoice, ProductChoice } from './commerce-choice-records'
|
|
22
|
+
|
|
23
|
+
async function search<T>(
|
|
24
|
+
table: 'products' | 'customers',
|
|
25
|
+
columns: string,
|
|
26
|
+
searched: string[],
|
|
27
|
+
query: NamedSearchQuery,
|
|
28
|
+
normalize: (row: Record<string, unknown>) => T,
|
|
29
|
+
run: CommerceSqlRunner,
|
|
30
|
+
dialect: QueryBuilderDialect,
|
|
31
|
+
only: string[] = [],
|
|
32
|
+
): Promise<{ choices: T[], total: number }> {
|
|
33
|
+
const { bind, values } = binder(dialect)
|
|
34
|
+
const clauses = [...only]
|
|
35
|
+
if (query.search) {
|
|
36
|
+
const pattern = containsPattern(query.search)
|
|
37
|
+
clauses.push(`(${searched.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
38
|
+
}
|
|
39
|
+
const where = clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : ''
|
|
40
|
+
const [counted, found] = await Promise.all([
|
|
41
|
+
run.unsafe(`SELECT COUNT(*) AS total_count FROM ${table}${where}`, values).execute(),
|
|
42
|
+
// LOWER, so the order is the same on every dialect: each collates case its own way.
|
|
43
|
+
run.unsafe(`SELECT ${columns} FROM ${table}${where} ORDER BY LOWER(COALESCE(name, '')) ASC, id ASC LIMIT ${query.limit}`, values).execute(),
|
|
44
|
+
])
|
|
45
|
+
return { choices: sqlRows(found).map(normalize), total: countOf(sqlRows(counted)[0]?.total_count) }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Products by name or id. */
|
|
49
|
+
export function searchProductChoices(
|
|
50
|
+
query: NamedSearchQuery,
|
|
51
|
+
run: CommerceSqlRunner = db,
|
|
52
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
53
|
+
): Promise<{ choices: ProductChoice[], total: number }> {
|
|
54
|
+
return search('products', 'id, name, inventory_count', [`COALESCE(name, '')`, asText('id', dialect)], query, normalizeProductChoice, run, dialect)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Customers by name, email or phone. `activeOnly` keeps to customers whose
|
|
59
|
+
* status is Active, as the point of sale offers them.
|
|
60
|
+
*/
|
|
61
|
+
export function searchCustomerChoices(
|
|
62
|
+
query: NamedSearchQuery,
|
|
63
|
+
run: CommerceSqlRunner = db,
|
|
64
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
65
|
+
options: { activeOnly?: boolean } = {},
|
|
66
|
+
): Promise<{ choices: CustomerChoice[], total: number }> {
|
|
67
|
+
// A text comparison: PostgreSQL keeps the status as an enum.
|
|
68
|
+
const only = options.activeOnly ? [`${asText('status', dialect)} = 'Active'`] : []
|
|
69
|
+
return search('customers', 'id, name, email, phone', [`COALESCE(name, '')`, `COALESCE(email, '')`, `COALESCE(phone, '')`], query, normalizeCustomerChoice, run, dialect, only)
|
|
70
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import { formatDeliveryDuration } from './commerce-delivery'
|
|
5
|
+
import { readDeliveryOverview } from './commerce-delivery-overview'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The delivery overview against each dialect's real engine
|
|
10
|
+
* (stacksjs/stacks#3218), over 520 couriers, routes and zones: the overview
|
|
11
|
+
* used to read the first 500 of each by id.
|
|
12
|
+
*/
|
|
13
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
14
|
+
|
|
15
|
+
const NOW = new Date('2026-11-06T12:00:00.000Z')
|
|
16
|
+
const HOUR = 3_600_000
|
|
17
|
+
const ROWS = 520
|
|
18
|
+
const COURIER_STATUSES = ['active', 'on_delivery', 'on_break'] as const
|
|
19
|
+
const ZONE_STATUSES = ['active', 'inactive', 'draft'] as const
|
|
20
|
+
|
|
21
|
+
const iso = (ms: number) => new Date(ms).toISOString().slice(0, 19).replace('T', ' ')
|
|
22
|
+
|
|
23
|
+
/** Routes active in the last day, past the 500th and in every stored format; the rest are old. */
|
|
24
|
+
const RECENT: Record<number, { lastActive: string, hoursAgo: number, courierId: number | null }> = {
|
|
25
|
+
2: { lastActive: String(NOW.getTime() - 2 * HOUR), hoursAgo: 2, courierId: 1 },
|
|
26
|
+
503: { lastActive: String(Math.floor((NOW.getTime() - 3 * HOUR) / 1000)), hoursAgo: 3, courierId: null },
|
|
27
|
+
505: { lastActive: String(NOW.getTime() - 1 * HOUR), hoursAgo: 1, courierId: 515 },
|
|
28
|
+
507: { lastActive: iso(NOW.getTime() - 5 * HOUR), hoursAgo: 5, courierId: null },
|
|
29
|
+
510: { lastActive: String(NOW.getTime() - 4 * HOUR), hoursAgo: 4, courierId: 516 },
|
|
30
|
+
515: { lastActive: String(NOW.getTime() - 6 * HOUR), hoursAgo: 6, courierId: null },
|
|
31
|
+
}
|
|
32
|
+
/** Kept out: 30 hours ago as ISO text (inside the superset, outside the day), and one in the future. */
|
|
33
|
+
const STALE: Record<number, string> = {
|
|
34
|
+
512: iso(NOW.getTime() - 30 * HOUR),
|
|
35
|
+
513: String(NOW.getTime() + HOUR),
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const METHODS = [
|
|
39
|
+
{ id: 1, name: 'Zoom Freight', status: 'active' },
|
|
40
|
+
{ id: 2, name: 'economy', status: 'draft' },
|
|
41
|
+
{ id: 3, name: 'Air', status: 'active' },
|
|
42
|
+
{ id: 4, name: 'Bike', status: 'inactive' },
|
|
43
|
+
{ id: 5, name: 'courier Plus', status: 'active' },
|
|
44
|
+
{ id: 6, name: 'Drone', status: 'draft' },
|
|
45
|
+
{ id: 7, name: 'Barge', status: 'inactive' },
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
49
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
50
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
51
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
52
|
+
const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
|
|
53
|
+
let courierStatus = text
|
|
54
|
+
let zoneStatus = text
|
|
55
|
+
if (dialect === 'postgres') {
|
|
56
|
+
await run(`CREATE TYPE courier_status AS ENUM ('active', 'on_delivery', 'on_break', 'offline')`)
|
|
57
|
+
await run(`CREATE TYPE zone_status AS ENUM ('active', 'inactive', 'draft')`)
|
|
58
|
+
courierStatus = 'courier_status'
|
|
59
|
+
zoneStatus = 'zone_status'
|
|
60
|
+
}
|
|
61
|
+
if (dialect === 'mysql') {
|
|
62
|
+
courierStatus = `ENUM('active', 'on_delivery', 'on_break', 'offline')`
|
|
63
|
+
zoneStatus = `ENUM('active', 'inactive', 'draft')`
|
|
64
|
+
}
|
|
65
|
+
await run(`CREATE TABLE couriers (id ${pk}, name ${text}, vehicle_number ${text}, status ${courierStatus})`)
|
|
66
|
+
await run(`CREATE TABLE delivery_routes (id ${pk}, courier_id INTEGER NULL, courier ${text}, vehicle ${text}, stops INTEGER, delivery_time INTEGER, total_distance INTEGER, last_active ${text})`)
|
|
67
|
+
await run(`CREATE TABLE shipping_methods (id ${pk}, name ${text}, status ${zoneStatus}, base_rate INTEGER, free_shipping INTEGER NULL)`)
|
|
68
|
+
await run(`CREATE TABLE shipping_zones (id ${pk}, name ${text}, status ${zoneStatus}, countries ${text}, regions ${text})`)
|
|
69
|
+
|
|
70
|
+
const ids = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
71
|
+
await run(`INSERT INTO couriers (id, name, vehicle_number, status) VALUES ${rows(ROWS, 4)}`, ids.flatMap(id => [id, `Courier ${id}`, `VAN-${id}`, COURIER_STATUSES[id % 3]!]))
|
|
72
|
+
const old = String(NOW.getTime() - 40 * 24 * HOUR)
|
|
73
|
+
await run(
|
|
74
|
+
`INSERT INTO delivery_routes (id, courier_id, courier, vehicle, stops, delivery_time, total_distance, last_active) VALUES ${rows(ROWS, 8)}`,
|
|
75
|
+
ids.flatMap(id => [id, RECENT[id]?.courierId ?? null, `Recorded ${id}`, `Truck ${id}`, id % 9, 30 + id % 120, id % 50, RECENT[id]?.lastActive ?? STALE[id] ?? old]),
|
|
76
|
+
)
|
|
77
|
+
await run(`INSERT INTO shipping_methods (id, name, status, base_rate, free_shipping) VALUES ${rows(METHODS.length, 5)}`, METHODS.flatMap(method => [method.id, method.name, method.status, 1000 + method.id, null]))
|
|
78
|
+
await run(`INSERT INTO shipping_zones (id, name, status, countries, regions) VALUES ${rows(ROWS, 5)}`, ids.flatMap(id => [id, `Zone ${String(id).padStart(3, '0')}`, ZONE_STATUSES[id % 3]!, id % 2 === 0 ? 'US, CA' : '["GB"]', 'North']))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
82
|
+
const overview = await readDeliveryOverview('USD', runner, dialect, NOW)
|
|
83
|
+
const active = Object.entries(RECENT).map(([id, route]) => ({ id: Number(id), ...route }))
|
|
84
|
+
const ids = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
85
|
+
const activeZones = ids.filter(id => ZONE_STATUSES[id % 3] === 'active')
|
|
86
|
+
const couriersIn = (status: string) => ids.filter(id => COURIER_STATUSES[id % 3] === status).length
|
|
87
|
+
const minutes = active.map(route => 30 + route.id % 120)
|
|
88
|
+
const average = Math.round(minutes.reduce((sum, value) => sum + value, 0) / minutes.length)
|
|
89
|
+
|
|
90
|
+
expect(overview.stats.map(stat => stat.value)).toEqual([
|
|
91
|
+
String(active.length),
|
|
92
|
+
String(couriersIn('on_delivery')),
|
|
93
|
+
formatDeliveryDuration(average),
|
|
94
|
+
String(activeZones.length),
|
|
95
|
+
])
|
|
96
|
+
expect(overview.stats[0]!.detail).toBe(`${active.reduce((sum, route) => sum + route.id % 9, 0)} stops active in 24h`)
|
|
97
|
+
expect(overview.stats[1]!.detail).toBe(`${ROWS} couriers total`)
|
|
98
|
+
expect(overview.stats[3]!.detail).toBe(`${activeZones.reduce((sum, id) => sum + (id % 2 === 0 ? 2 : 1), 0)} country assignments`)
|
|
99
|
+
|
|
100
|
+
// The five most recently active routes, past the 500th, with their couriers.
|
|
101
|
+
expect(overview.routes.map(route => route.id)).toEqual([...active].sort((a, b) => a.hoursAgo - b.hoursAgo).slice(0, 5).map(route => route.id))
|
|
102
|
+
expect(overview.routes[0]).toMatchObject({ id: 505, courier: 'Courier 515', vehicle: 'VAN-515' })
|
|
103
|
+
|
|
104
|
+
expect(overview.couriers).toEqual({
|
|
105
|
+
total: ROWS,
|
|
106
|
+
active: couriersIn('active'),
|
|
107
|
+
onDelivery: couriersIn('on_delivery'),
|
|
108
|
+
onBreak: couriersIn('on_break'),
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
// Active first, then by name ignoring case.
|
|
112
|
+
expect(overview.methods.map(method => method.name)).toEqual(['Air', 'courier Plus', 'Zoom Freight', 'Barge', 'Bike'])
|
|
113
|
+
expect(overview.zones.map(zone => zone.name)).toEqual(['Zone 003', 'Zone 006', 'Zone 009', 'Zone 012', 'Zone 015'])
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
describe('readDeliveryOverview on SQLite', () => {
|
|
117
|
+
test('counts every courier, route and zone', async () => {
|
|
118
|
+
const database = new Database(':memory:')
|
|
119
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
120
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
121
|
+
})
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
125
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
126
|
+
|
|
127
|
+
test.skipIf(!connection)(`readDeliveryOverview on ${dialect}: counts every courier, route and zone`, async () => {
|
|
128
|
+
const url = new URL(connection!)
|
|
129
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
130
|
+
throw new Error('Delivery overview tests require a local disposable database server')
|
|
131
|
+
|
|
132
|
+
const name = `stacks_delivery_overview_${crypto.randomUUID().replaceAll('-', '')}`
|
|
133
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
134
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
135
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
136
|
+
const scoped = new URL(url.href)
|
|
137
|
+
scoped.pathname = `/${name}`
|
|
138
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
139
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
140
|
+
|
|
141
|
+
try {
|
|
142
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
143
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
await database.close()
|
|
147
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
148
|
+
finally { await admin.close() }
|
|
149
|
+
}
|
|
150
|
+
}, 60_000)
|
|
151
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { db, getDatabaseDialect } from '@stacksjs/database/runtime'
|
|
3
|
+
import { countOf } from '../Content/content-list'
|
|
4
|
+
import type { DeliveryOverviewResult } from './commerce-delivery'
|
|
5
|
+
import { buildDeliveryOverview } from './commerce-delivery'
|
|
6
|
+
import { referencedIds } from './commerce-record'
|
|
7
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
8
|
+
import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The delivery overview, read from every record (stacksjs/stacks#3218).
|
|
12
|
+
*
|
|
13
|
+
* It used to read the first 500 shipping methods, routes, zones and couriers
|
|
14
|
+
* by id and work everything out from those, so a route, zone or courier past
|
|
15
|
+
* the 500th was left out of every count, and the active routes were whichever
|
|
16
|
+
* of the first 500 happened to be recent.
|
|
17
|
+
*
|
|
18
|
+
* Now the database counts the couriers, picks the five methods and zones the
|
|
19
|
+
* overview lists, and narrows the routes to those that can have been active
|
|
20
|
+
* in the last day; buildDeliveryOverview does the rest, as before, on rows
|
|
21
|
+
* that are bounded by what the overview shows.
|
|
22
|
+
*/
|
|
23
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
24
|
+
|
|
25
|
+
/** Active first, then by name, the order the overview lists methods and zones in. */
|
|
26
|
+
function activeFirst(dialect: QueryBuilderDialect): string {
|
|
27
|
+
return `ORDER BY CASE WHEN ${asText('status', dialect)} = 'active' THEN 0 ELSE 1 END, LOWER(name), id`
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Routes whose `last_active` can be within a day of `now`. The model stores it
|
|
32
|
+
* as text holding Unix milliseconds, and the overview also reads Unix seconds
|
|
33
|
+
* and ISO dates. Digit strings of one length compare as text exactly as they
|
|
34
|
+
* do as numbers, so milliseconds and seconds are narrowed exactly; anything
|
|
35
|
+
* else is kept from the day before the cutoff on, and buildDeliveryOverview
|
|
36
|
+
* makes the exact cut.
|
|
37
|
+
*/
|
|
38
|
+
export function recentRoutes(dialect: QueryBuilderDialect, now: Date): { where: string, values: unknown[] } {
|
|
39
|
+
const { bind, values } = binder(dialect)
|
|
40
|
+
const cutoff = now.getTime() - DAY_MS
|
|
41
|
+
const column = asText('last_active', dialect)
|
|
42
|
+
const length = `LENGTH(${column})`
|
|
43
|
+
const milliseconds = `(${length} = 13 AND ${column} >= ${bind(String(cutoff))} AND ${column} <= ${bind(String(now.getTime()))})`
|
|
44
|
+
const seconds = `(${length} = 10 AND ${column} >= ${bind(String(Math.floor(cutoff / 1000)))} AND ${column} <= ${bind(String(Math.ceil(now.getTime() / 1000)))})`
|
|
45
|
+
const dates = `(${length} NOT IN (10, 13) AND ${column} >= ${bind(new Date(cutoff - DAY_MS).toISOString().slice(0, 10))})`
|
|
46
|
+
return { where: ` WHERE ${milliseconds} OR ${seconds} OR ${dates}`, values }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function readDeliveryOverview(
|
|
50
|
+
currency: string | undefined,
|
|
51
|
+
run: CommerceSqlRunner = db,
|
|
52
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
53
|
+
now: Date = new Date(),
|
|
54
|
+
): Promise<DeliveryOverviewResult> {
|
|
55
|
+
const recent = recentRoutes(dialect, now)
|
|
56
|
+
const status = asText('status', dialect)
|
|
57
|
+
const [methods, topZones, activeZones, routes, couriers] = await Promise.all([
|
|
58
|
+
run.unsafe(`SELECT * FROM shipping_methods ${activeFirst(dialect)} LIMIT 5`).execute(),
|
|
59
|
+
run.unsafe(`SELECT * FROM shipping_zones ${activeFirst(dialect)} LIMIT 5`).execute(),
|
|
60
|
+
// Every active zone, for the count and its country assignments.
|
|
61
|
+
run.unsafe(`SELECT * FROM shipping_zones WHERE ${status} = 'active'`).execute(),
|
|
62
|
+
run.unsafe(`SELECT * FROM delivery_routes${recent.where}`, recent.values).execute(),
|
|
63
|
+
run.unsafe(`SELECT ${status} AS value, COUNT(*) AS item_count FROM couriers GROUP BY ${status}`).execute(),
|
|
64
|
+
])
|
|
65
|
+
|
|
66
|
+
const routeRows = sqlRows(routes)
|
|
67
|
+
const courierIds = referencedIds(routeRows, 'courier_id')
|
|
68
|
+
const linked = courierIds.length > 0
|
|
69
|
+
? sqlRows(await run.unsafe(`SELECT * FROM couriers WHERE id IN (${idPlaceholders(courierIds, dialect)})`, courierIds).execute())
|
|
70
|
+
: []
|
|
71
|
+
|
|
72
|
+
const byStatus = new Map(sqlRows(couriers).map(row => [String(row.value ?? ''), countOf(row.item_count)]))
|
|
73
|
+
const courierCounts = {
|
|
74
|
+
total: [...byStatus.values()].reduce((sum, count) => sum + count, 0),
|
|
75
|
+
active: byStatus.get('active') ?? 0,
|
|
76
|
+
onDelivery: byStatus.get('on_delivery') ?? 0,
|
|
77
|
+
onBreak: byStatus.get('on_break') ?? 0,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const zones = new Map<string, Record<string, unknown>>()
|
|
81
|
+
for (const zone of [...sqlRows(topZones), ...sqlRows(activeZones)])
|
|
82
|
+
zones.set(String(zone.id), zone)
|
|
83
|
+
|
|
84
|
+
return buildDeliveryOverview(sqlRows(methods), routeRows, [...zones.values()], linked, currency, now, courierCounts)
|
|
85
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { DeliveryRouteListQuery } from './commerce-delivery-route-list'
|
|
5
|
+
import { parseDeliveryRouteListQuery, readDeliveryRoutePage } from './commerce-delivery-route-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Delivery Routes list against each dialect's real engine
|
|
10
|
+
* (stacksjs/stacks#3218), over 520 routes and couriers: the page used to read
|
|
11
|
+
* the 500 most recently active routes.
|
|
12
|
+
*/
|
|
13
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
14
|
+
|
|
15
|
+
const NOW = new Date('2026-11-06T12:00:00.000Z')
|
|
16
|
+
const MINUTE = 60_000
|
|
17
|
+
const ROWS = 520
|
|
18
|
+
|
|
19
|
+
/** Route n was last active 7n minutes ago; every 50th is stored as Unix seconds. */
|
|
20
|
+
const ROUTES = Array.from({ length: ROWS }, (_, index) => {
|
|
21
|
+
const id = index + 1
|
|
22
|
+
const at = NOW.getTime() - id * 7 * MINUTE
|
|
23
|
+
return {
|
|
24
|
+
id,
|
|
25
|
+
at,
|
|
26
|
+
lastActive: id % 50 === 0 ? String(Math.floor(at / 1000)) : String(at),
|
|
27
|
+
courierId: id % 4 === 0 ? 500 + (id % 20) + 1 : null,
|
|
28
|
+
courier: `Recorded ${id}`,
|
|
29
|
+
vehicle: id === 9 ? 'Van_100%' : id === 10 ? 'Van 1000' : `Truck ${String(id).padStart(3, '0')}`,
|
|
30
|
+
stops: id % 6,
|
|
31
|
+
time: 20 + id % 40,
|
|
32
|
+
distance: id % 30,
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
type Route = typeof ROUTES[number]
|
|
36
|
+
|
|
37
|
+
const ids = (routes: Route[]) => routes.map(route => String(route.id))
|
|
38
|
+
const recentFirst = (a: Route, b: Route) => b.at - a.at || b.id - a.id
|
|
39
|
+
const courierName = (route: Route) => (route.courierId ? `Courier ${route.courierId}` : route.courier).toLowerCase()
|
|
40
|
+
|
|
41
|
+
function query(overrides: Partial<DeliveryRouteListQuery> = {}): DeliveryRouteListQuery {
|
|
42
|
+
return { search: '', sort: 'active', direction: 'desc', page: 1, perPage: 10, ...overrides }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
46
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
47
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
48
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
49
|
+
const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
|
|
50
|
+
let status = text
|
|
51
|
+
if (dialect === 'postgres') {
|
|
52
|
+
await run(`CREATE TYPE courier_status AS ENUM ('active', 'on_delivery', 'on_break', 'offline')`)
|
|
53
|
+
status = 'courier_status'
|
|
54
|
+
}
|
|
55
|
+
if (dialect === 'mysql')
|
|
56
|
+
status = `ENUM('active', 'on_delivery', 'on_break', 'offline')`
|
|
57
|
+
await run(`CREATE TABLE couriers (id ${pk}, name ${text}, vehicle_number ${text}, status ${status})`)
|
|
58
|
+
await run(`CREATE TABLE delivery_routes (id ${pk}, courier_id INTEGER NULL, courier ${text}, vehicle ${text}, stops INTEGER, delivery_time INTEGER, total_distance INTEGER, last_active ${text}, created_at ${text}, updated_at ${text} NULL, uuid ${text} NULL)`)
|
|
59
|
+
const all = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
60
|
+
await run(`INSERT INTO couriers (id, name, vehicle_number, status) VALUES ${rows(ROWS, 4)}`, all.flatMap(id => [id, `Courier ${id}`, `VAN-${id}`, 'active']))
|
|
61
|
+
await run(
|
|
62
|
+
`INSERT INTO delivery_routes (id, courier_id, courier, vehicle, stops, delivery_time, total_distance, last_active, created_at) VALUES ${rows(ROWS, 9)}`,
|
|
63
|
+
ROUTES.flatMap(route => [route.id, route.courierId, route.courier, route.vehicle, route.stops, route.time, route.distance, route.lastActive, '2026-11-01T00:00:00.000Z']),
|
|
64
|
+
)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
68
|
+
const read = (overrides: Partial<DeliveryRouteListQuery> = {}) => readDeliveryRoutePage(query(overrides), runner, dialect, NOW)
|
|
69
|
+
const all = async (overrides: Partial<DeliveryRouteListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => String(record.id))
|
|
70
|
+
|
|
71
|
+
// The summary counts every route.
|
|
72
|
+
const first = await read({ search: 'van' })
|
|
73
|
+
expect(first.summary).toEqual({
|
|
74
|
+
total: ROWS,
|
|
75
|
+
linked: ROUTES.filter(route => route.courierId).length,
|
|
76
|
+
stops: ROUTES.reduce((sum, route) => sum + route.stops, 0),
|
|
77
|
+
distance: ROUTES.reduce((sum, route) => sum + route.distance, 0),
|
|
78
|
+
active: ROUTES.filter(route => NOW.getTime() - route.at <= 24 * 60 * MINUTE).length,
|
|
79
|
+
})
|
|
80
|
+
expect(first.total).toBe(2)
|
|
81
|
+
|
|
82
|
+
// Most recently active first, seconds and milliseconds in one order, stable across pages.
|
|
83
|
+
const recent = [...ROUTES].sort(recentFirst)
|
|
84
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
85
|
+
expect(pages.flatMap(result => result.records.map(record => String(record.id)))).toEqual(ids(recent).slice(0, 30))
|
|
86
|
+
expect((await read({ page: 99, perPage: 100 })).page).toBe(6)
|
|
87
|
+
expect(await all({ direction: 'asc', page: 6 })).toEqual(ids([...ROUTES].sort((a, b) => a.at - b.at || a.id - b.id)).slice(500))
|
|
88
|
+
|
|
89
|
+
// Search: a literal %, the linked courier's name, and numbers as text.
|
|
90
|
+
expect(await all({ search: '100%' })).toEqual(['9'])
|
|
91
|
+
const linkedTo505 = ROUTES.filter(route => route.courierId === 505)
|
|
92
|
+
expect(linkedTo505.length).toBeGreaterThan(5)
|
|
93
|
+
expect(await all({ search: 'COURIER 505' })).toEqual(ids(linkedTo505.sort(recentFirst)))
|
|
94
|
+
|
|
95
|
+
// Sorts, ties most recently active first.
|
|
96
|
+
expect(await all({ sort: 'stops', direction: 'asc' })).toEqual(ids([...ROUTES].sort((a, b) => a.stops - b.stops || recentFirst(a, b))).slice(0, 100))
|
|
97
|
+
expect(await all({ sort: 'courier', direction: 'asc' })).toEqual(ids([...ROUTES].sort((a, b) => courierName(a).localeCompare(courierName(b)) || recentFirst(a, b))).slice(0, 100))
|
|
98
|
+
|
|
99
|
+
// Couriers past the 500th, read by the ids the page references.
|
|
100
|
+
const linked = (await read({ search: 'COURIER 505' })).records[0]!
|
|
101
|
+
expect(linked.courier_record).toMatchObject({ id: 505, name: 'Courier 505', vehicle_number: 'VAN-505' })
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
describe('readDeliveryRoutePage on SQLite', () => {
|
|
105
|
+
test('summary, order, search, sorts, pages and couriers', async () => {
|
|
106
|
+
const database = new Database(':memory:')
|
|
107
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
108
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
109
|
+
})
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
113
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
114
|
+
|
|
115
|
+
test.skipIf(!connection)(`readDeliveryRoutePage on ${dialect}: summary, order, search, sorts, pages and couriers`, async () => {
|
|
116
|
+
const url = new URL(connection!)
|
|
117
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
118
|
+
throw new Error('Delivery route list tests require a local disposable database server')
|
|
119
|
+
|
|
120
|
+
const name = `stacks_delivery_routes_${crypto.randomUUID().replaceAll('-', '')}`
|
|
121
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
122
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
123
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
124
|
+
const scoped = new URL(url.href)
|
|
125
|
+
scoped.pathname = `/${name}`
|
|
126
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
127
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
128
|
+
|
|
129
|
+
try {
|
|
130
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
131
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
await database.close()
|
|
135
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
136
|
+
finally { await admin.close() }
|
|
137
|
+
}
|
|
138
|
+
}, 60_000)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
describe('parseDeliveryRouteListQuery', () => {
|
|
142
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
143
|
+
|
|
144
|
+
test('defaults to every route, most recently active first, 25 a page', () => {
|
|
145
|
+
expect(parseDeliveryRouteListQuery(reader({}))).toEqual({ search: '', sort: 'active', direction: 'desc', page: 1, perPage: 25 })
|
|
146
|
+
expect(parseDeliveryRouteListQuery(reader({ sort: 'stops' }))).toHaveProperty('direction', 'asc')
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
test('refuses values the page does not offer', () => {
|
|
150
|
+
expect(parseDeliveryRouteListQuery(reader({ sort: 'uuid' }))).toHaveProperty('error')
|
|
151
|
+
expect(parseDeliveryRouteListQuery(reader({ per_page: '500' }))).toHaveProperty('error')
|
|
152
|
+
})
|
|
153
|
+
})
|