@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
|
@@ -81,6 +81,19 @@ export function formatDeliveryDuration(minutes: number): string {
|
|
|
81
81
|
return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
+
/** How many couriers there are, by status, when the database counted them. */
|
|
85
|
+
export interface DeliveryCourierCounts {
|
|
86
|
+
total: number
|
|
87
|
+
active: number
|
|
88
|
+
onDelivery: number
|
|
89
|
+
onBreak: number
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The overview from the rows it shows. `courierRows` are the couriers the
|
|
94
|
+
* routes reference; `courierCounts`, when given, are every courier counted by
|
|
95
|
+
* the database (readDeliveryOverview), and otherwise `courierRows` are counted.
|
|
96
|
+
*/
|
|
84
97
|
export function buildDeliveryOverview(
|
|
85
98
|
methodRows: any[],
|
|
86
99
|
routeRows: any[],
|
|
@@ -88,6 +101,7 @@ export function buildDeliveryOverview(
|
|
|
88
101
|
courierRows: any[],
|
|
89
102
|
currency = 'USD',
|
|
90
103
|
now = new Date(),
|
|
104
|
+
courierCounts?: DeliveryCourierCounts,
|
|
91
105
|
): DeliveryOverviewResult {
|
|
92
106
|
const normalizedCurrency = commerceCurrency(currency, 'Commerce configuration')
|
|
93
107
|
const normalizedCouriers = courierRows.map((courier) => {
|
|
@@ -222,10 +236,16 @@ export function buildDeliveryOverview(
|
|
|
222
236
|
return statusOrder || left.name.localeCompare(right.name)
|
|
223
237
|
})
|
|
224
238
|
|
|
225
|
-
const
|
|
239
|
+
const counted = normalizedCouriers.reduce<Record<string, number>>((counts, courier) => {
|
|
226
240
|
counts[courier.status] = (counts[courier.status] || 0) + 1
|
|
227
241
|
return counts
|
|
228
242
|
}, {})
|
|
243
|
+
const couriers: DeliveryCourierCounts = courierCounts ?? {
|
|
244
|
+
total: normalizedCouriers.length,
|
|
245
|
+
active: counted.active || 0,
|
|
246
|
+
onDelivery: counted.on_delivery || 0,
|
|
247
|
+
onBreak: counted.on_break || 0,
|
|
248
|
+
}
|
|
229
249
|
|
|
230
250
|
const averageRouteMinutes = activeRoutes.length > 0
|
|
231
251
|
? Math.round(activeRoutes.reduce((total, route) => total + (routeMinutesById.get(route.id) || 0), 0) / activeRoutes.length)
|
|
@@ -241,8 +261,8 @@ export function buildDeliveryOverview(
|
|
|
241
261
|
},
|
|
242
262
|
{
|
|
243
263
|
label: 'Couriers on Delivery',
|
|
244
|
-
value:
|
|
245
|
-
detail: `${
|
|
264
|
+
value: couriers.onDelivery.toLocaleString('en-US'),
|
|
265
|
+
detail: `${couriers.total.toLocaleString('en-US')} couriers total`,
|
|
246
266
|
},
|
|
247
267
|
{
|
|
248
268
|
label: 'Average Route',
|
|
@@ -258,12 +278,7 @@ export function buildDeliveryOverview(
|
|
|
258
278
|
routes: activeRoutes.slice(0, 5),
|
|
259
279
|
methods: methods.slice(0, 5),
|
|
260
280
|
zones: zones.slice(0, 5),
|
|
261
|
-
couriers
|
|
262
|
-
total: normalizedCouriers.length,
|
|
263
|
-
active: courierStatusCounts.active || 0,
|
|
264
|
-
onDelivery: courierStatusCounts.on_delivery || 0,
|
|
265
|
-
onBreak: courierStatusCounts.on_break || 0,
|
|
266
|
-
},
|
|
281
|
+
couriers,
|
|
267
282
|
}
|
|
268
283
|
}
|
|
269
284
|
import {
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { GiftCardListQuery } from './commerce-gift-card-list'
|
|
5
|
+
import { giftCardsCsv, parseGiftCardListQuery, readGiftCardPage, readGiftCardsForExport } from './commerce-gift-card-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Gift Cards list against each dialect's real engine (stacksjs/stacks#3218),
|
|
10
|
+
* with status as a real enum and the flags as each dialect stores booleans.
|
|
11
|
+
*/
|
|
12
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
13
|
+
|
|
14
|
+
const NOW = new Date('2026-11-06T12:00:00.000Z')
|
|
15
|
+
const STATUSES = ['ACTIVE', 'USED', 'EXPIRED', 'DEACTIVATED'] as const
|
|
16
|
+
const NAMES = ['alice', 'Bob', 'carol', 'Dave', 'erin', 'Frank', 'gina']
|
|
17
|
+
const CUSTOMERS = 600
|
|
18
|
+
|
|
19
|
+
/** 26 cards, one an hour back from NOW; 11 and 12 share a creation time. */
|
|
20
|
+
const CARDS = Array.from({ length: 26 }, (_, index) => {
|
|
21
|
+
const id = index + 1
|
|
22
|
+
const status = STATUSES[id % STATUSES.length]!
|
|
23
|
+
const initial = 5000 + id * 100
|
|
24
|
+
return {
|
|
25
|
+
id,
|
|
26
|
+
code: id === 9 ? 'SALE_100%' : id === 10 ? 'GC-1000' : `GC-${String(id).padStart(3, '0')}`,
|
|
27
|
+
initial_balance: initial,
|
|
28
|
+
current_balance: status === 'USED' || id === 4 ? 0 : initial - (id % 3) * 250,
|
|
29
|
+
currency: id % 6 === 0 ? 'usd' : id % 2 === 0 ? 'USD' : 'EUR',
|
|
30
|
+
status,
|
|
31
|
+
purchaser_id: id === 21 ? 'PURCH-XYZ' : null,
|
|
32
|
+
recipient_email: id === 13 ? null : `r${id}@example.com`,
|
|
33
|
+
recipient_name: id === 13 ? null : NAMES[id % NAMES.length]!,
|
|
34
|
+
is_digital: id % 2 === 0,
|
|
35
|
+
is_reloadable: id % 5 === 0,
|
|
36
|
+
is_active: id % 3 !== 0,
|
|
37
|
+
expiry_days: id % 4 === 1 ? null : (id * 7) % 26,
|
|
38
|
+
customer_id: id === 1 ? CUSTOMERS : id === 2 ? 3 : null,
|
|
39
|
+
hoursAgo: id === 12 ? 11 : id,
|
|
40
|
+
}
|
|
41
|
+
})
|
|
42
|
+
type Card = typeof CARDS[number]
|
|
43
|
+
|
|
44
|
+
const ids = (cards: Card[]) => cards.map(card => String(card.id))
|
|
45
|
+
const byCode = (a: Card, b: Card) => a.code.toLowerCase().localeCompare(b.code.toLowerCase())
|
|
46
|
+
|
|
47
|
+
function query(overrides: Partial<GiftCardListQuery> = {}): GiftCardListQuery {
|
|
48
|
+
return { search: '', status: '', enabled: '', delivery: '', sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
52
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
53
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
54
|
+
const flag = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
|
|
55
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
56
|
+
let statusType = text
|
|
57
|
+
if (dialect === 'postgres') {
|
|
58
|
+
await run(`CREATE TYPE gift_card_status AS ENUM (${STATUSES.map(s => `'${s}'`).join(', ')})`)
|
|
59
|
+
statusType = 'gift_card_status'
|
|
60
|
+
}
|
|
61
|
+
if (dialect === 'mysql')
|
|
62
|
+
statusType = `ENUM(${STATUSES.map(s => `'${s}'`).join(', ')})`
|
|
63
|
+
await run(`CREATE TABLE customers (id ${pk})`)
|
|
64
|
+
await run(`CREATE TABLE gift_cards (id ${pk}, code ${text}, initial_balance INTEGER, current_balance INTEGER, currency ${text}, status ${statusType}, purchaser_id ${text} NULL, recipient_email ${text} NULL, recipient_name ${text} NULL, personal_message ${text} NULL, is_digital ${flag}, is_reloadable ${flag}, is_active ${flag}, expiry_date ${time} NULL, last_used_date ${time} NULL, template_id ${text} NULL, customer_id INTEGER NULL, created_at ${time})`)
|
|
65
|
+
const p = (count: number) => Array.from({ length: count }, (_, i) => dialect === 'postgres' ? `$${i + 1}` : '?').join(', ')
|
|
66
|
+
// Past the 500 customers the page used to read for its record check.
|
|
67
|
+
const customerIds = Array.from({ length: CUSTOMERS }, (_, i) => i + 1)
|
|
68
|
+
await run(`INSERT INTO customers (id) VALUES ${customerIds.map((_, i) => `(${dialect === 'postgres' ? `$${i + 1}` : '?'})`).join(', ')}`, customerIds)
|
|
69
|
+
const stamp = (date: Date) => date.toISOString().slice(0, 19).replace('T', ' ')
|
|
70
|
+
const bool = (value: boolean) => dialect === 'postgres' ? value : (value ? 1 : 0)
|
|
71
|
+
for (const card of CARDS) {
|
|
72
|
+
await run(
|
|
73
|
+
`INSERT INTO gift_cards (id, code, initial_balance, current_balance, currency, status, purchaser_id, recipient_email, recipient_name, is_digital, is_reloadable, is_active, expiry_date, customer_id, created_at) VALUES (${p(15)})`,
|
|
74
|
+
[
|
|
75
|
+
card.id, card.code, card.initial_balance, card.current_balance, card.currency, card.status, card.purchaser_id,
|
|
76
|
+
card.recipient_email, card.recipient_name, bool(card.is_digital), bool(card.is_reloadable), bool(card.is_active),
|
|
77
|
+
card.expiry_days === null ? null : stamp(new Date(NOW.getTime() + card.expiry_days * 86_400_000)),
|
|
78
|
+
card.customer_id, stamp(new Date(NOW.getTime() - card.hoursAgo * 3_600_000)),
|
|
79
|
+
],
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
85
|
+
const read = (overrides: Partial<GiftCardListQuery> = {}) => readGiftCardPage(query(overrides), runner, dialect)
|
|
86
|
+
const all = (overrides: Partial<GiftCardListQuery> = {}) => read({ perPage: 100, ...overrides })
|
|
87
|
+
|
|
88
|
+
// The summary counts every card, whatever the page is filtered to.
|
|
89
|
+
const filtered = await read({ status: 'USED' })
|
|
90
|
+
const summary = filtered.summary
|
|
91
|
+
expect(summary.total).toBe(CARDS.length)
|
|
92
|
+
expect(summary.available).toBe(CARDS.filter(card => card.status === 'ACTIVE' && card.is_active && card.current_balance > 0).length)
|
|
93
|
+
expect(summary.enabled).toBe(CARDS.filter(card => card.is_active).length)
|
|
94
|
+
expect(summary.digital).toBe(CARDS.filter(card => card.is_digital).length)
|
|
95
|
+
expect(summary.reloadable).toBe(CARDS.filter(card => card.is_reloadable).length)
|
|
96
|
+
for (const status of STATUSES)
|
|
97
|
+
expect(summary.statuses[status]).toBe(CARDS.filter(card => card.status === status).length)
|
|
98
|
+
const inCurrency = (currency: string) => CARDS.filter(card => card.currency.toUpperCase() === currency)
|
|
99
|
+
expect(summary.currencies.map(entry => entry.currency)).toEqual(['EUR', 'USD'])
|
|
100
|
+
for (const entry of summary.currencies) {
|
|
101
|
+
const cards = inCurrency(entry.currency)
|
|
102
|
+
expect(entry.cards).toBe(cards.length)
|
|
103
|
+
expect(entry.initialBalance).toBe(cards.reduce((sum, card) => sum + card.initial_balance, 0))
|
|
104
|
+
expect(entry.currentBalance).toBe(cards.reduce((sum, card) => sum + card.current_balance, 0))
|
|
105
|
+
expect(entry.redeemedBalance).toBe(cards.reduce((sum, card) => sum + Math.max(0, card.initial_balance - card.current_balance), 0))
|
|
106
|
+
}
|
|
107
|
+
expect(filtered.total).toBe(CARDS.filter(card => card.status === 'USED').length)
|
|
108
|
+
|
|
109
|
+
// Filters, alone and together.
|
|
110
|
+
expect((await read({ enabled: 'enabled' })).total).toBe(CARDS.filter(card => card.is_active).length)
|
|
111
|
+
expect((await read({ enabled: 'disabled' })).total).toBe(CARDS.filter(card => !card.is_active).length)
|
|
112
|
+
expect((await read({ delivery: 'digital' })).total).toBe(CARDS.filter(card => card.is_digital).length)
|
|
113
|
+
expect((await read({ delivery: 'physical' })).total).toBe(CARDS.filter(card => !card.is_digital).length)
|
|
114
|
+
expect(ids((await all({ status: 'ACTIVE', enabled: 'enabled', delivery: 'digital', sort: 'id', direction: 'asc' })).records.map(record => CARDS[Number(record.id) - 1]!)))
|
|
115
|
+
.toEqual(ids(CARDS.filter(card => card.status === 'ACTIVE' && card.is_active && card.is_digital)))
|
|
116
|
+
|
|
117
|
+
// Search ignores case, treats % literally, and reaches the purchaser.
|
|
118
|
+
expect((await read({ search: '100%' })).records.map(record => record.id)).toEqual(['9'])
|
|
119
|
+
expect((await read({ search: 'purch-xyz' })).records.map(record => record.id)).toEqual(['21'])
|
|
120
|
+
expect((await read({ search: 'EXAMPLE.COM' })).total).toBe(CARDS.length - 1)
|
|
121
|
+
expect((await read({ search: 'bob' })).total).toBe(CARDS.filter(card => card.recipient_name === 'Bob').length)
|
|
122
|
+
|
|
123
|
+
// Newest first, the id breaking the tie between 11 and 12, stable across pages.
|
|
124
|
+
const newest = [...CARDS].sort((a, b) => a.hoursAgo - b.hoursAgo || b.id - a.id)
|
|
125
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
126
|
+
expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(ids(newest))
|
|
127
|
+
expect(pages[0]!.total).toBe(CARDS.length)
|
|
128
|
+
expect((await read({ page: 9 })).page).toBe(3)
|
|
129
|
+
|
|
130
|
+
// Sorts, with ties read by code.
|
|
131
|
+
const sorted = async (sort: GiftCardListQuery['sort'], direction: 'asc' | 'desc') =>
|
|
132
|
+
(await all({ sort, direction })).records.map(record => record.id)
|
|
133
|
+
expect(await sorted('code', 'asc')).toEqual(ids([...CARDS].sort(byCode)))
|
|
134
|
+
expect(await sorted('balance', 'desc')).toEqual(ids([...CARDS].sort((a, b) => b.current_balance - a.current_balance || byCode(a, b))))
|
|
135
|
+
const recipient = (card: Card) => (card.recipient_name ?? '').toLowerCase()
|
|
136
|
+
expect(await sorted('recipient', 'asc')).toEqual(ids([...CARDS].sort((a, b) => recipient(a).localeCompare(recipient(b)) || byCode(a, b))))
|
|
137
|
+
// Cards without an expiry come last in both directions.
|
|
138
|
+
const dated = CARDS.filter(card => card.expiry_days !== null)
|
|
139
|
+
const undated = [...CARDS.filter(card => card.expiry_days === null)].sort(byCode)
|
|
140
|
+
expect(await sorted('expiry', 'asc')).toEqual(ids([...[...dated].sort((a, b) => a.expiry_days! - b.expiry_days! || byCode(a, b)), ...undated]))
|
|
141
|
+
expect(await sorted('expiry', 'desc')).toEqual(ids([...[...dated].sort((a, b) => b.expiry_days! - a.expiry_days! || byCode(a, b)), ...undated]))
|
|
142
|
+
|
|
143
|
+
// A card's customer is checked against exactly the customers it references.
|
|
144
|
+
const first = (await all({ sort: 'id', direction: 'asc' })).records
|
|
145
|
+
expect(first[0]!.customerId).toBe(String(CUSTOMERS))
|
|
146
|
+
expect(first[1]!.customerId).toBe('3')
|
|
147
|
+
expect(first[0]!.currency).toBe('EUR')
|
|
148
|
+
expect(first[5]!.currency).toBe('USD')
|
|
149
|
+
|
|
150
|
+
// The export holds every match across batches, in order.
|
|
151
|
+
const exported = await readGiftCardsForExport({ search: '', status: '', enabled: '', delivery: '', sort: 'created', direction: 'desc' }, runner, dialect, 4)
|
|
152
|
+
expect(exported.map(record => record.id)).toEqual(ids(newest))
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
describe('readGiftCardPage on SQLite', () => {
|
|
156
|
+
test('summary, filters, search, sorts, pages, customers and export', async () => {
|
|
157
|
+
const database = new Database(':memory:')
|
|
158
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
159
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
160
|
+
})
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
164
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
165
|
+
|
|
166
|
+
test.skipIf(!connection)(`readGiftCardPage on ${dialect}: summary, filters, search, sorts, pages, customers and export`, async () => {
|
|
167
|
+
const url = new URL(connection!)
|
|
168
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
169
|
+
throw new Error('Gift card list tests require a local disposable database server')
|
|
170
|
+
|
|
171
|
+
const name = `stacks_gift_card_list_${crypto.randomUUID().replaceAll('-', '')}`
|
|
172
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
173
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
174
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
175
|
+
const scoped = new URL(url.href)
|
|
176
|
+
scoped.pathname = `/${name}`
|
|
177
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
178
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
179
|
+
|
|
180
|
+
try {
|
|
181
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
182
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
await database.close()
|
|
186
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
187
|
+
finally { await admin.close() }
|
|
188
|
+
}
|
|
189
|
+
}, 60_000)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
describe('parseGiftCardListQuery', () => {
|
|
193
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
194
|
+
|
|
195
|
+
test('defaults to every card, newest first, 25 a page', () => {
|
|
196
|
+
expect(parseGiftCardListQuery(reader({}))).toEqual({ search: '', status: '', enabled: '', delivery: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
|
|
197
|
+
expect(parseGiftCardListQuery(reader({ sort: 'balance' }))).toHaveProperty('direction', 'desc')
|
|
198
|
+
expect(parseGiftCardListQuery(reader({ sort: 'code' }))).toHaveProperty('direction', 'asc')
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
test('refuses values the page does not offer', () => {
|
|
202
|
+
expect(parseGiftCardListQuery(reader({ status: 'active' }))).toHaveProperty('error')
|
|
203
|
+
expect(parseGiftCardListQuery(reader({ enabled: 'yes' }))).toHaveProperty('error')
|
|
204
|
+
expect(parseGiftCardListQuery(reader({ delivery: 'email' }))).toHaveProperty('error')
|
|
205
|
+
expect(parseGiftCardListQuery(reader({ sort: 'personal_message' }))).toHaveProperty('error')
|
|
206
|
+
expect(parseGiftCardListQuery(reader({ per_page: '7' }))).toHaveProperty('error')
|
|
207
|
+
})
|
|
208
|
+
})
|
|
209
|
+
|
|
210
|
+
describe('giftCardsCsv', () => {
|
|
211
|
+
test('writes the page columns with balances in major units', () => {
|
|
212
|
+
const csv = giftCardsCsv([{
|
|
213
|
+
id: '1', code: 'GC-"1"', initialBalance: 5000, currentBalance: 1250, currency: 'USD', status: 'ACTIVE', purchaserId: '',
|
|
214
|
+
recipientEmail: 'a@b.test', recipientName: 'Ann', personalMessage: '', isDigital: true, isReloadable: false, isActive: true,
|
|
215
|
+
expiryDate: '', lastUsedDate: '', templateId: '', customerId: '', createdAt: '2026-11-06T12:00:00.000Z',
|
|
216
|
+
}], (amount, currency) => `${currency} ${(amount / 100).toFixed(2)}`)
|
|
217
|
+
const [header, row] = csv.replace(/^/, '').split('\n')
|
|
218
|
+
expect(header).toBe('"Code","Recipient","Email","Status","Availability","Delivery","Reloading","Currency","Initial balance","Current balance","Expiry date","Last used date"')
|
|
219
|
+
expect(row).toBe('"GC-""1""","Ann","a@b.test","ACTIVE","Enabled","Digital","Single use","USD","USD 50.00","USD 12.50","",""')
|
|
220
|
+
})
|
|
221
|
+
})
|
|
@@ -0,0 +1,259 @@
|
|
|
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 { commerceCurrency, commerceIdentifier, commerceValue, referencedIds } from './commerce-record'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
import { asText, binder, idPlaceholders, isTrue, sqlRows } from './commerce-sql'
|
|
8
|
+
import type { GiftCardCurrencySummary, GiftCardRecord, GiftCardStatus, GiftCardSummary } from './gift-card-records'
|
|
9
|
+
import { normalizeGiftCardRecord } from './gift-card-records'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One page of gift cards, searched, filtered, sorted and counted by the
|
|
13
|
+
* database, with the summary of every card (stacksjs/stacks#3218).
|
|
14
|
+
*
|
|
15
|
+
* The Gift Cards page used to read the newest 500 cards and do all of that in
|
|
16
|
+
* the browser, so a card past the 500th could not be found and the summary
|
|
17
|
+
* counted those 500. The record check read the first 500 customers, so a card
|
|
18
|
+
* belonging to a later customer failed the whole page.
|
|
19
|
+
*/
|
|
20
|
+
export const GIFT_CARD_SORTS = ['created', 'id', 'code', 'recipient', 'balance', 'status', 'delivery', 'expiry'] as const
|
|
21
|
+
export type GiftCardSort = typeof GIFT_CARD_SORTS[number]
|
|
22
|
+
|
|
23
|
+
export const GIFT_CARD_STATUSES: readonly GiftCardStatus[] = ['ACTIVE', 'USED', 'EXPIRED', 'DEACTIVATED']
|
|
24
|
+
|
|
25
|
+
export interface GiftCardListQuery {
|
|
26
|
+
search: string
|
|
27
|
+
/** '' for any. */
|
|
28
|
+
status: '' | GiftCardStatus
|
|
29
|
+
/** '' for any. */
|
|
30
|
+
enabled: '' | 'enabled' | 'disabled'
|
|
31
|
+
/** '' for any. */
|
|
32
|
+
delivery: '' | 'digital' | 'physical'
|
|
33
|
+
sort: GiftCardSort
|
|
34
|
+
direction: 'asc' | 'desc'
|
|
35
|
+
page: number
|
|
36
|
+
perPage: number
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function parseGiftCardListQuery(read: QueryReader): GiftCardListQuery | { error: string } {
|
|
40
|
+
const pageText = queryText(read, 'page')
|
|
41
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
42
|
+
if (!Number.isInteger(page) || page < 1)
|
|
43
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
44
|
+
|
|
45
|
+
const sizeText = queryText(read, 'per_page')
|
|
46
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
47
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
48
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
49
|
+
|
|
50
|
+
const sort = queryText(read, 'sort') || 'created'
|
|
51
|
+
if (!(GIFT_CARD_SORTS as readonly string[]).includes(sort))
|
|
52
|
+
return { error: `sort must be one of ${GIFT_CARD_SORTS.join(', ')}.` }
|
|
53
|
+
|
|
54
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
55
|
+
const direction = directionText === '' ? (sort === 'created' || sort === 'balance' ? 'desc' : 'asc') : directionText
|
|
56
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
57
|
+
return { error: 'direction must be asc or desc.' }
|
|
58
|
+
|
|
59
|
+
const search = queryText(read, 'q')
|
|
60
|
+
if (search.length > 200)
|
|
61
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
62
|
+
|
|
63
|
+
const status = queryText(read, 'status')
|
|
64
|
+
if (status && !(GIFT_CARD_STATUSES as readonly string[]).includes(status))
|
|
65
|
+
return { error: `status must be one of ${GIFT_CARD_STATUSES.join(', ')}.` }
|
|
66
|
+
|
|
67
|
+
const enabled = queryText(read, 'enabled')
|
|
68
|
+
if (enabled && enabled !== 'enabled' && enabled !== 'disabled')
|
|
69
|
+
return { error: 'enabled must be enabled or disabled.' }
|
|
70
|
+
|
|
71
|
+
const delivery = queryText(read, 'delivery')
|
|
72
|
+
if (delivery && delivery !== 'digital' && delivery !== 'physical')
|
|
73
|
+
return { error: 'delivery must be digital or physical.' }
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
search,
|
|
77
|
+
status: status as GiftCardListQuery['status'],
|
|
78
|
+
enabled: enabled as GiftCardListQuery['enabled'],
|
|
79
|
+
delivery: delivery as GiftCardListQuery['delivery'],
|
|
80
|
+
sort: sort as GiftCardSort,
|
|
81
|
+
direction,
|
|
82
|
+
page,
|
|
83
|
+
perPage,
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function sortExpression(sort: GiftCardSort, dialect: QueryBuilderDialect): string {
|
|
88
|
+
switch (sort) {
|
|
89
|
+
case 'id': return 'id'
|
|
90
|
+
case 'code': return 'LOWER(code)'
|
|
91
|
+
case 'recipient': return `LOWER(COALESCE(recipient_name, ''))`
|
|
92
|
+
case 'balance': return 'current_balance'
|
|
93
|
+
case 'status': return asText('status', dialect)
|
|
94
|
+
case 'delivery': return `CASE WHEN ${isTrue('is_digital', dialect)} THEN 1 ELSE 0 END`
|
|
95
|
+
case 'expiry': return 'expiry_date'
|
|
96
|
+
default: return 'created_at'
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function giftCardFilter(query: Pick<GiftCardListQuery, 'search' | 'status' | 'enabled' | 'delivery'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
101
|
+
const { bind, values } = binder(dialect)
|
|
102
|
+
const clauses: string[] = []
|
|
103
|
+
if (query.status)
|
|
104
|
+
// A text comparison: PostgreSQL keeps the status as an enum.
|
|
105
|
+
clauses.push(`${asText('status', dialect)} = ${bind(query.status)}`)
|
|
106
|
+
if (query.enabled === 'enabled')
|
|
107
|
+
clauses.push(isTrue('is_active', dialect))
|
|
108
|
+
if (query.enabled === 'disabled')
|
|
109
|
+
clauses.push(`NOT (${isTrue('is_active', dialect)})`)
|
|
110
|
+
if (query.delivery === 'digital')
|
|
111
|
+
clauses.push(isTrue('is_digital', dialect))
|
|
112
|
+
if (query.delivery === 'physical')
|
|
113
|
+
clauses.push(`NOT (${isTrue('is_digital', dialect)})`)
|
|
114
|
+
if (query.search) {
|
|
115
|
+
const pattern = containsPattern(query.search)
|
|
116
|
+
const columns = [
|
|
117
|
+
'code',
|
|
118
|
+
`COALESCE(recipient_name, '')`,
|
|
119
|
+
`COALESCE(recipient_email, '')`,
|
|
120
|
+
`COALESCE(purchaser_id, '')`,
|
|
121
|
+
'currency',
|
|
122
|
+
]
|
|
123
|
+
clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
124
|
+
}
|
|
125
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function orderBy(query: Pick<GiftCardListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
129
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
130
|
+
// Cards without an expiry come last either way: each dialect puts NULL at
|
|
131
|
+
// a different end of the order.
|
|
132
|
+
const undated = query.sort === 'expiry' ? 'CASE WHEN expiry_date IS NULL THEN 1 ELSE 0 END ASC, ' : ''
|
|
133
|
+
// Ties read by code, as the page sorted them, except the newest-first order,
|
|
134
|
+
// which the page broke by id; the id breaks every remaining tie, so pages
|
|
135
|
+
// never repeat or skip a card.
|
|
136
|
+
const byCode = ['created', 'code', 'id'].includes(query.sort) ? '' : ', LOWER(code) ASC'
|
|
137
|
+
return ` ORDER BY ${undated}${sortExpression(query.sort, dialect)} ${direction}${byCode}, id ${direction}`
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Gift cards turned into records, against exactly the customers they reference. */
|
|
141
|
+
async function recordsFor(cards: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<GiftCardRecord[]> {
|
|
142
|
+
if (cards.length === 0)
|
|
143
|
+
return []
|
|
144
|
+
const customerIds = referencedIds(cards, 'customer_id')
|
|
145
|
+
const customers = customerIds.length > 0
|
|
146
|
+
? await run.unsafe(`SELECT id FROM customers WHERE id IN (${idPlaceholders(customerIds, dialect)})`, customerIds).execute()
|
|
147
|
+
: []
|
|
148
|
+
const known = new Set(sqlRows(customers).map(row => commerceIdentifier(commerceValue(row, 'id'), 'Customer')))
|
|
149
|
+
return cards.map(card => normalizeGiftCardRecord(card, known))
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The summary cards and breakdowns, over every gift card as before. */
|
|
153
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<GiftCardSummary> {
|
|
154
|
+
const status = asText('status', dialect)
|
|
155
|
+
const count = (condition: string) => `SUM(CASE WHEN ${condition} THEN 1 ELSE 0 END)`
|
|
156
|
+
const [totals, byStatus, byCurrency] = await Promise.all([
|
|
157
|
+
run.unsafe(`SELECT COUNT(*) AS total_count, ${count(`${status} = 'ACTIVE' AND ${isTrue('is_active', dialect)} AND current_balance > 0`)} AS available_count, ${count(isTrue('is_active', dialect))} AS enabled_count, ${count(isTrue('is_digital', dialect))} AS digital_count, ${count(isTrue('is_reloadable', dialect))} AS reloadable_count FROM gift_cards`).execute(),
|
|
158
|
+
run.unsafe(`SELECT ${status} AS value, COUNT(*) AS item_count FROM gift_cards GROUP BY ${status}`).execute(),
|
|
159
|
+
run.unsafe('SELECT currency, COUNT(*) AS item_count, SUM(initial_balance) AS initial_total, SUM(current_balance) AS current_total, SUM(CASE WHEN initial_balance > current_balance THEN initial_balance - current_balance ELSE 0 END) AS redeemed_total FROM gift_cards GROUP BY currency').execute(),
|
|
160
|
+
])
|
|
161
|
+
const row = sqlRows(totals)[0] ?? {}
|
|
162
|
+
|
|
163
|
+
const statuses: Record<GiftCardStatus, number> = { ACTIVE: 0, USED: 0, EXPIRED: 0, DEACTIVATED: 0 }
|
|
164
|
+
for (const entry of sqlRows(byStatus)) {
|
|
165
|
+
const key = String(entry.value ?? '') as GiftCardStatus
|
|
166
|
+
if (key in statuses)
|
|
167
|
+
statuses[key] += countOf(entry.item_count)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const currencies = new Map<string, GiftCardCurrencySummary>()
|
|
171
|
+
for (const entry of sqlRows(byCurrency)) {
|
|
172
|
+
// Normalized as the records are, so "usd" and "USD" are one currency.
|
|
173
|
+
const currency = commerceCurrency(entry.currency, 'Gift card summary')
|
|
174
|
+
const current = currencies.get(currency) ?? { currency, cards: 0, initialBalance: 0, currentBalance: 0, redeemedBalance: 0 }
|
|
175
|
+
current.cards += countOf(entry.item_count)
|
|
176
|
+
current.initialBalance += countOf(entry.initial_total)
|
|
177
|
+
current.currentBalance += countOf(entry.current_total)
|
|
178
|
+
current.redeemedBalance += countOf(entry.redeemed_total)
|
|
179
|
+
currencies.set(currency, current)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
total: countOf(row.total_count),
|
|
184
|
+
available: countOf(row.available_count),
|
|
185
|
+
enabled: countOf(row.enabled_count),
|
|
186
|
+
digital: countOf(row.digital_count),
|
|
187
|
+
reloadable: countOf(row.reloadable_count),
|
|
188
|
+
statuses,
|
|
189
|
+
currencies: [...currencies.values()].sort((left, right) => left.currency.localeCompare(right.currency)),
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export interface GiftCardPage {
|
|
194
|
+
records: GiftCardRecord[]
|
|
195
|
+
total: number
|
|
196
|
+
page: number
|
|
197
|
+
summary: GiftCardSummary
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export async function readGiftCardPage(
|
|
201
|
+
query: GiftCardListQuery,
|
|
202
|
+
run: CommerceSqlRunner = db,
|
|
203
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
204
|
+
): Promise<GiftCardPage> {
|
|
205
|
+
const { where, values } = giftCardFilter(query, dialect)
|
|
206
|
+
const [counted, summary] = await Promise.all([
|
|
207
|
+
run.unsafe(`SELECT COUNT(*) AS total_count FROM gift_cards${where}`, values).execute(),
|
|
208
|
+
summarize(run, dialect),
|
|
209
|
+
])
|
|
210
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
211
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
212
|
+
const cards = await run.unsafe(
|
|
213
|
+
`SELECT * FROM gift_cards${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
214
|
+
values,
|
|
215
|
+
).execute()
|
|
216
|
+
return { records: await recordsFor(sqlRows(cards), run, dialect), total, page, summary }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Every gift card matching the query, in its order, for the CSV export, a batch at a time. */
|
|
220
|
+
export async function readGiftCardsForExport(
|
|
221
|
+
query: Omit<GiftCardListQuery, 'page' | 'perPage'>,
|
|
222
|
+
run: CommerceSqlRunner = db,
|
|
223
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
224
|
+
batchSize: number = 500,
|
|
225
|
+
): Promise<GiftCardRecord[]> {
|
|
226
|
+
const { where, values } = giftCardFilter(query, dialect)
|
|
227
|
+
const records: GiftCardRecord[] = []
|
|
228
|
+
for (let offset = 0; ; offset += batchSize) {
|
|
229
|
+
const batch = sqlRows(await run.unsafe(
|
|
230
|
+
`SELECT * FROM gift_cards${where}${orderBy(query, dialect)} LIMIT ${batchSize} OFFSET ${offset}`,
|
|
231
|
+
values,
|
|
232
|
+
).execute())
|
|
233
|
+
records.push(...await recordsFor(batch, run, dialect))
|
|
234
|
+
if (batch.length < batchSize)
|
|
235
|
+
return records
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const CSV_HEADER = ['Code', 'Recipient', 'Email', 'Status', 'Availability', 'Delivery', 'Reloading', 'Currency', 'Initial balance', 'Current balance', 'Expiry date', 'Last used date']
|
|
240
|
+
|
|
241
|
+
/** The CSV "Export filtered" downloads: the page's columns, for every matching card. */
|
|
242
|
+
export function giftCardsCsv(records: GiftCardRecord[], minor: (amount: number, currency: string) => string): string {
|
|
243
|
+
const escape = (value: string): string => `"${value.replaceAll('"', '""')}"`
|
|
244
|
+
const lines = records.map(record => [
|
|
245
|
+
record.code,
|
|
246
|
+
record.recipientName,
|
|
247
|
+
record.recipientEmail,
|
|
248
|
+
record.status,
|
|
249
|
+
record.isActive ? 'Enabled' : 'Disabled',
|
|
250
|
+
record.isDigital ? 'Digital' : 'Physical',
|
|
251
|
+
record.isReloadable ? 'Reloadable' : 'Single use',
|
|
252
|
+
record.currency,
|
|
253
|
+
minor(record.initialBalance, record.currency),
|
|
254
|
+
minor(record.currentBalance, record.currency),
|
|
255
|
+
record.expiryDate,
|
|
256
|
+
record.lastUsedDate,
|
|
257
|
+
])
|
|
258
|
+
return `${[CSV_HEADER, ...lines].map(row => row.map(escape).join(',')).join('\n')}`
|
|
259
|
+
}
|