@stacksjs/defaults 0.75.487 → 0.75.490
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +27 -2
- package/ai/skills/stacks-native/CATALOG.md +9 -9
- package/ai/skills/stacks-search-engine/SKILL.md +14 -0
- package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
- package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
- package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
- package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
- package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
- package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
- package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
- package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
- package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
- package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
- package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
- package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
- package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
- package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
- package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
- package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
- package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
- package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
- package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
- package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
- package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
- package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
- package/app/Actions/Dashboard/Content/content-list.ts +10 -0
- package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
- package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
- package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
- package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
- package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
- package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
- package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
- package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
- package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
- package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
- package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
- package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
- package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
- package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
- package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +9 -6
- package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
- package/app/Actions/Dashboard/Queue/queue-stats.ts +10 -0
- 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/QueueWorker.ts +1 -0
- package/app/Models/Request.ts +4 -2
- package/bootstrap.ts +6 -1
- package/functions/commerce/shippings/dashboard-resource.ts +12 -1
- package/functions/commerce/shippings/delivery-routes.ts +1 -0
- package/functions/commerce/shippings/license-keys.ts +1 -0
- package/functions/dashboard-list.test.ts +132 -1
- package/functions/dashboard-list.ts +198 -1
- package/functions/queue.ts +2 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +2 -2
- package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
- package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
- package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
- package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
- package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
- package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
- package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
- package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
- package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
- package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
- package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
- package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
- package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
- package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
- package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
- package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
- package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
- package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
- package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
- package/resources/components/Dashboard/Queue/QueueDashboard.stx +8 -2
- package/resources/functions/dashboard/sidebar.ts +26 -1
- package/routes/dashboard-api.ts +11 -0
- package/views/dashboard/stores/kanban.ts +38 -6
|
@@ -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
|
+
})
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { db, getDatabaseDialect } from '@stacksjs/database/runtime'
|
|
3
|
+
import type { QueryReader } from '../Content/content-list'
|
|
4
|
+
import { containsPattern, countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
|
|
5
|
+
import { deliveryTimestamp } from './commerce-delivery'
|
|
6
|
+
import { recentRoutes } from './commerce-delivery-overview'
|
|
7
|
+
import { referencedIds } from './commerce-record'
|
|
8
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
9
|
+
import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
|
|
10
|
+
import type { DeliveryRouteRecord } from './delivery-route-records'
|
|
11
|
+
import { indexDeliveryRouteCouriers, normalizeDeliveryRouteRecord } from './delivery-route-records'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* One page of delivery routes, searched, sorted and counted by the database,
|
|
15
|
+
* with the summary of every route (stacksjs/stacks#3218).
|
|
16
|
+
*
|
|
17
|
+
* The Delivery Routes page used to read the 500 most recently active routes
|
|
18
|
+
* and do all of that in the browser, so an older route could not be found,
|
|
19
|
+
* and its cards (routes, stops, distance, active in 24h) counted those 500.
|
|
20
|
+
*/
|
|
21
|
+
export const DELIVERY_ROUTE_SORTS = ['active', 'id', 'courier', 'vehicle', 'stops', 'time', 'distance'] as const
|
|
22
|
+
export type DeliveryRouteSort = typeof DELIVERY_ROUTE_SORTS[number]
|
|
23
|
+
|
|
24
|
+
export interface DeliveryRouteListQuery {
|
|
25
|
+
search: string
|
|
26
|
+
sort: DeliveryRouteSort
|
|
27
|
+
direction: 'asc' | 'desc'
|
|
28
|
+
page: number
|
|
29
|
+
perPage: number
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface DeliveryRouteSummary {
|
|
33
|
+
total: number
|
|
34
|
+
/** Routes linked to a courier record. */
|
|
35
|
+
linked: number
|
|
36
|
+
stops: number
|
|
37
|
+
distance: number
|
|
38
|
+
/** Routes active within a day of now. */
|
|
39
|
+
active: number
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function parseDeliveryRouteListQuery(read: QueryReader): DeliveryRouteListQuery | { error: string } {
|
|
43
|
+
const pageText = queryText(read, 'page')
|
|
44
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
45
|
+
if (!Number.isInteger(page) || page < 1)
|
|
46
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
47
|
+
|
|
48
|
+
const sizeText = queryText(read, 'per_page')
|
|
49
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
50
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
51
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
52
|
+
|
|
53
|
+
const sort = queryText(read, 'sort') || 'active'
|
|
54
|
+
if (!(DELIVERY_ROUTE_SORTS as readonly string[]).includes(sort))
|
|
55
|
+
return { error: `sort must be one of ${DELIVERY_ROUTE_SORTS.join(', ')}.` }
|
|
56
|
+
|
|
57
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
58
|
+
const direction = directionText === '' ? (sort === 'active' ? 'desc' : 'asc') : directionText
|
|
59
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
60
|
+
return { error: 'direction must be asc or desc.' }
|
|
61
|
+
|
|
62
|
+
const search = queryText(read, 'q')
|
|
63
|
+
if (search.length > 200)
|
|
64
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
65
|
+
|
|
66
|
+
return { search, sort: sort as DeliveryRouteSort, direction, page, perPage }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const FROM = ' FROM delivery_routes r LEFT JOIN couriers c ON c.id = r.courier_id'
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* `last_active` in time order. It is text: the model writes Unix milliseconds,
|
|
73
|
+
* and seconds are read too. A ten-digit seconds value and a thirteen-digit
|
|
74
|
+
* millisecond value from different seconds differ in their first ten digits,
|
|
75
|
+
* so the two already compare as text in time order; only values inside one
|
|
76
|
+
* second could tie the wrong way.
|
|
77
|
+
*/
|
|
78
|
+
function lastActive(dialect: QueryBuilderDialect): string {
|
|
79
|
+
return asText('r.last_active', dialect)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function sortExpression(sort: DeliveryRouteSort, dialect: QueryBuilderDialect): string {
|
|
83
|
+
switch (sort) {
|
|
84
|
+
case 'id': return 'r.id'
|
|
85
|
+
case 'courier': return 'LOWER(COALESCE(c.name, r.courier))'
|
|
86
|
+
case 'vehicle': return 'LOWER(r.vehicle)'
|
|
87
|
+
case 'stops': return 'r.stops'
|
|
88
|
+
case 'time': return 'r.delivery_time'
|
|
89
|
+
case 'distance': return 'r.total_distance'
|
|
90
|
+
default: return lastActive(dialect)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function deliveryRouteFilter(query: Pick<DeliveryRouteListQuery, 'search'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
95
|
+
if (!query.search)
|
|
96
|
+
return { where: '', values: [] }
|
|
97
|
+
const { bind, values } = binder(dialect)
|
|
98
|
+
const pattern = containsPattern(query.search)
|
|
99
|
+
const columns = [
|
|
100
|
+
asText('r.id', dialect),
|
|
101
|
+
'r.courier',
|
|
102
|
+
`COALESCE(c.name, '')`,
|
|
103
|
+
'r.vehicle',
|
|
104
|
+
asText('r.stops', dialect),
|
|
105
|
+
asText('r.delivery_time', dialect),
|
|
106
|
+
asText('r.total_distance', dialect),
|
|
107
|
+
]
|
|
108
|
+
return { where: ` WHERE (${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`, values }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function orderBy(query: Pick<DeliveryRouteListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
112
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
113
|
+
// Ties read most recently active first; the id breaks every remaining tie,
|
|
114
|
+
// so pages never repeat or skip a route.
|
|
115
|
+
if (query.sort === 'active' || query.sort === 'id')
|
|
116
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, r.id ${direction}`
|
|
117
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, ${lastActive(dialect)} DESC, r.id DESC`
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Routes turned into records, against exactly the couriers they reference. */
|
|
121
|
+
async function recordsFor(routes: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<DeliveryRouteRecord[]> {
|
|
122
|
+
if (routes.length === 0)
|
|
123
|
+
return []
|
|
124
|
+
const courierIds = referencedIds(routes, 'courier_id')
|
|
125
|
+
const couriers = courierIds.length > 0
|
|
126
|
+
? await run.unsafe(`SELECT id, name, vehicle_number, status FROM couriers WHERE id IN (${idPlaceholders(courierIds, dialect)})`, courierIds).execute()
|
|
127
|
+
: []
|
|
128
|
+
const byId = indexDeliveryRouteCouriers(sqlRows(couriers))
|
|
129
|
+
return routes.map(route => normalizeDeliveryRouteRecord(route, byId))
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The summary cards, over every route as before. */
|
|
133
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect, now: Date): Promise<DeliveryRouteSummary> {
|
|
134
|
+
const recent = recentRoutes(dialect, now)
|
|
135
|
+
const [totals, candidates] = await Promise.all([
|
|
136
|
+
run.unsafe('SELECT COUNT(*) AS total_count, COUNT(courier_id) AS linked_count, SUM(stops) AS stop_total, SUM(total_distance) AS distance_total FROM delivery_routes').execute(),
|
|
137
|
+
run.unsafe(`SELECT id, last_active FROM delivery_routes${recent.where}`, recent.values).execute(),
|
|
138
|
+
])
|
|
139
|
+
const row = sqlRows(totals)[0] ?? {}
|
|
140
|
+
// recentRoutes is a superset for anything but Unix times; this is the exact cut.
|
|
141
|
+
const cutoff = now.getTime() - 24 * 60 * 60 * 1000
|
|
142
|
+
const active = sqlRows(candidates).filter((route) => {
|
|
143
|
+
const at = deliveryTimestamp(route.last_active, `DeliveryRoute ${route.id}`)
|
|
144
|
+
return at >= cutoff && at <= now.getTime()
|
|
145
|
+
}).length
|
|
146
|
+
return {
|
|
147
|
+
total: countOf(row.total_count),
|
|
148
|
+
linked: countOf(row.linked_count),
|
|
149
|
+
stops: countOf(row.stop_total),
|
|
150
|
+
distance: countOf(row.distance_total),
|
|
151
|
+
active,
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface DeliveryRoutePage {
|
|
156
|
+
records: DeliveryRouteRecord[]
|
|
157
|
+
total: number
|
|
158
|
+
page: number
|
|
159
|
+
summary: DeliveryRouteSummary
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export async function readDeliveryRoutePage(
|
|
163
|
+
query: DeliveryRouteListQuery,
|
|
164
|
+
run: CommerceSqlRunner = db,
|
|
165
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
166
|
+
now: Date = new Date(),
|
|
167
|
+
): Promise<DeliveryRoutePage> {
|
|
168
|
+
const { where, values } = deliveryRouteFilter(query, dialect)
|
|
169
|
+
const [counted, summary] = await Promise.all([
|
|
170
|
+
run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
|
|
171
|
+
summarize(run, dialect, now),
|
|
172
|
+
])
|
|
173
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
174
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
175
|
+
const routes = await run.unsafe(
|
|
176
|
+
`SELECT r.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
177
|
+
values,
|
|
178
|
+
).execute()
|
|
179
|
+
return { records: await recordsFor(sqlRows(routes), run, dialect), total, page, summary }
|
|
180
|
+
}
|