@stacksjs/defaults 0.75.489 → 0.75.492
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +20 -2
- package/ai/skills/stacks-native/CATALOG.md +9 -9
- package/ai/skills/stacks-search-engine/SKILL.md +14 -0
- package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
- package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
- package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
- package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
- package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
- package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
- package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
- package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
- package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
- package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
- package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
- package/app/Actions/Dashboard/Commerce/ProductUnitIndexAction.ts +23 -19
- package/app/Actions/Dashboard/Commerce/ProductVariantIndexAction.ts +25 -18
- package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
- package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
- package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
- package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
- package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
- package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
- package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.test.ts +146 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.ts +178 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.test.ts +165 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.ts +209 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
- package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
- package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
- package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
- package/app/Actions/Dashboard/Commerce/product-unit-records.test.ts +0 -13
- package/app/Actions/Dashboard/Commerce/product-unit-records.ts +0 -17
- package/app/Actions/Dashboard/Commerce/product-variant-records.test.ts +0 -13
- package/app/Actions/Dashboard/Commerce/product-variant-records.ts +0 -17
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
- package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
- package/app/Actions/Dashboard/Content/content-list.ts +10 -0
- package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
- package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
- package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
- package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
- package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
- package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
- package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
- package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
- package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
- package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
- package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
- package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
- package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
- package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
- package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +5 -3
- package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
- package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
- package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
- package/app/Actions/Dashboard/named-search.test.ts +36 -0
- package/app/Actions/Dashboard/named-search.ts +80 -0
- package/app/Models/Request.ts +4 -2
- package/functions/commerce/shippings/dashboard-resource.ts +12 -1
- package/functions/commerce/shippings/delivery-routes.ts +1 -0
- package/functions/commerce/shippings/license-keys.ts +1 -0
- package/functions/dashboard-list.test.ts +146 -1
- package/functions/dashboard-list.ts +216 -1
- package/functions/queue.ts +2 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +2 -2
- package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
- package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
- package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
- package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
- package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
- package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
- package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
- package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
- package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
- package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
- package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
- package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
- package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +63 -8
- package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +48 -60
- package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +29 -3
- package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +57 -3
- package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +59 -61
- package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +28 -2
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
- package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
- package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
- package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
- package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
- package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
- package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
- package/resources/components/Dashboard/Queue/QueueDashboard.stx +7 -1
- package/routes/dashboard-api.ts +11 -0
- package/views/dashboard/stores/kanban.ts +38 -6
|
@@ -0,0 +1,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
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { LicenseKeyListQuery } from './commerce-license-key-list'
|
|
5
|
+
import { parseLicenseKeyListQuery, readLicenseKeyPage, searchLicenseKeyChoices } from './commerce-license-key-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Licence Keys list and its dialog's choices against each dialect's real
|
|
10
|
+
* engine (stacksjs/stacks#3218), with template and status as real enums, over
|
|
11
|
+
* 520 customers, products and orders: the page used to read the first 500 of
|
|
12
|
+
* each.
|
|
13
|
+
*/
|
|
14
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
15
|
+
|
|
16
|
+
const NOW = new Date('2026-11-06T12:00:00.000Z')
|
|
17
|
+
const DAY = 86_400_000
|
|
18
|
+
const ROWS = 520
|
|
19
|
+
const TEMPLATES = ['Standard License', 'Premium License', 'Enterprise License'] as const
|
|
20
|
+
const STATUSES = ['active', 'inactive', 'unassigned'] as const
|
|
21
|
+
const stamp = (ms: number) => new Date(ms).toISOString().slice(0, 19).replace('T', ' ')
|
|
22
|
+
const customerName = (id: number) => id === 515 ? 'zelda Late' : id === 3 ? 'Zed early' : `Customer ${String(id).padStart(3, '0')}`
|
|
23
|
+
|
|
24
|
+
/** 30 keys, one a day back from NOW; 11 and 12 share a creation time. */
|
|
25
|
+
const KEYS = Array.from({ length: 30 }, (_, index) => {
|
|
26
|
+
const id = index + 1
|
|
27
|
+
const group = (n: number) => String(n).padStart(4, '0')
|
|
28
|
+
return {
|
|
29
|
+
id,
|
|
30
|
+
key: `K${group(id).slice(1)}-AAAA-BBBB-CCCC-${id === 9 ? 'X1X0' : group(id)}`,
|
|
31
|
+
template: TEMPLATES[id % 3]!,
|
|
32
|
+
status: STATUSES[id % 3]!,
|
|
33
|
+
customerId: id % 4 === 0 ? 515 : id % 4 === 1 ? 3 : null,
|
|
34
|
+
productId: id % 5 === 0 ? 520 : null,
|
|
35
|
+
orderId: id % 6 === 0 ? 510 : null,
|
|
36
|
+
// Day offsets around the 30-day window: some inside, some past, some long gone.
|
|
37
|
+
expiryDays: [-5, 1, 10, 29, 31, 90][id % 6]!,
|
|
38
|
+
daysAgo: id === 12 ? 11 : id,
|
|
39
|
+
}
|
|
40
|
+
})
|
|
41
|
+
type Key = typeof KEYS[number]
|
|
42
|
+
|
|
43
|
+
const ids = (keys: Key[]) => keys.map(key => String(key.id))
|
|
44
|
+
const newestFirst = (a: Key, b: Key) => a.daysAgo - b.daysAgo || b.id - a.id
|
|
45
|
+
|
|
46
|
+
function query(overrides: Partial<LicenseKeyListQuery> = {}): LicenseKeyListQuery {
|
|
47
|
+
return { search: '', sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
51
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
52
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
53
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
54
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
55
|
+
const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
|
|
56
|
+
const enumOf = (values: readonly string[]) => values.map(value => `'${value}'`).join(', ')
|
|
57
|
+
let template = text
|
|
58
|
+
let status = text
|
|
59
|
+
if (dialect === 'postgres') {
|
|
60
|
+
await run(`CREATE TYPE key_template AS ENUM (${enumOf(TEMPLATES)})`)
|
|
61
|
+
await run(`CREATE TYPE key_status AS ENUM (${enumOf(STATUSES)})`)
|
|
62
|
+
template = 'key_template'
|
|
63
|
+
status = 'key_status'
|
|
64
|
+
}
|
|
65
|
+
if (dialect === 'mysql') {
|
|
66
|
+
template = `ENUM(${enumOf(TEMPLATES)})`
|
|
67
|
+
status = `ENUM(${enumOf(STATUSES)})`
|
|
68
|
+
}
|
|
69
|
+
await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text})`)
|
|
70
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text})`)
|
|
71
|
+
await run(`CREATE TABLE orders (id ${pk}, status ${text})`)
|
|
72
|
+
await run(`CREATE TABLE license_keys (id ${pk}, ${dialect === 'mysql' ? '`key`' : 'key'} ${text}, template ${template}, expiry_date ${time}, status ${status}, customer_id INTEGER NULL, product_id INTEGER NULL, order_id INTEGER NULL, created_at ${time}, updated_at ${time} NULL, uuid ${text} NULL)`)
|
|
73
|
+
const all = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
74
|
+
await run(`INSERT INTO customers (id, name, email) VALUES ${rows(ROWS, 3)}`, all.flatMap(id => [id, customerName(id), `buyer${id}@shop.test`]))
|
|
75
|
+
await run(`INSERT INTO products (id, name) VALUES ${rows(ROWS, 2)}`, all.flatMap(id => [id, id === 520 ? 'Zebra Suite' : `Product ${String(id).padStart(3, '0')}`]))
|
|
76
|
+
await run(`INSERT INTO orders (id, status) VALUES ${rows(ROWS, 2)}`, all.flatMap(id => [id, id === 510 ? 'refunded' : 'completed']))
|
|
77
|
+
const keyColumn = dialect === 'mysql' ? '`key`' : 'key'
|
|
78
|
+
await run(
|
|
79
|
+
`INSERT INTO license_keys (id, ${keyColumn}, template, expiry_date, status, customer_id, product_id, order_id, created_at) VALUES ${rows(KEYS.length, 9)}`,
|
|
80
|
+
KEYS.flatMap(key => [key.id, key.key, key.template, stamp(NOW.getTime() + key.expiryDays * DAY), key.status, key.customerId, key.productId, key.orderId, stamp(NOW.getTime() - key.daysAgo * DAY)]),
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
85
|
+
const read = (overrides: Partial<LicenseKeyListQuery> = {}) => readLicenseKeyPage(query(overrides), runner, dialect, NOW)
|
|
86
|
+
const all = async (overrides: Partial<LicenseKeyListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => String(record.id))
|
|
87
|
+
const matching = (keep: (key: Key) => boolean) => ids(KEYS.filter(keep).sort(newestFirst))
|
|
88
|
+
|
|
89
|
+
// The summary counts every key, whatever the page is searched for.
|
|
90
|
+
const searched = await read({ search: 'zelda' })
|
|
91
|
+
expect(searched.summary).toEqual({
|
|
92
|
+
total: KEYS.length,
|
|
93
|
+
active: KEYS.filter(key => key.status === 'active').length,
|
|
94
|
+
assigned: KEYS.filter(key => key.customerId || key.productId || key.orderId).length,
|
|
95
|
+
expiring: KEYS.filter(key => key.expiryDays >= 0 && key.expiryDays <= 30).length,
|
|
96
|
+
})
|
|
97
|
+
expect(searched.total).toBe(KEYS.filter(key => key.customerId === 515).length)
|
|
98
|
+
|
|
99
|
+
// Search: the key with a digit pattern, the customer's name and email, the product, the order id, the enums.
|
|
100
|
+
expect(await all({ search: 'x1x0' })).toEqual(['9'])
|
|
101
|
+
expect(await all({ search: 'BUYER515@' })).toEqual(matching(key => key.customerId === 515))
|
|
102
|
+
expect(await all({ search: 'zebra suite' })).toEqual(matching(key => key.productId === 520))
|
|
103
|
+
expect(await all({ search: '510' })).toEqual(matching(key => key.orderId === 510))
|
|
104
|
+
expect(await all({ search: 'ENTERPRISE' })).toEqual(matching(key => key.template === 'Enterprise License'))
|
|
105
|
+
|
|
106
|
+
// Newest first, the id breaking the tie between 11 and 12, stable across pages.
|
|
107
|
+
const newest = [...KEYS].sort(newestFirst)
|
|
108
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
109
|
+
expect(pages.flatMap(result => result.records.map(record => String(record.id)))).toEqual(ids(newest))
|
|
110
|
+
|
|
111
|
+
// Sorts by name, not enum order; ties newest first.
|
|
112
|
+
const by = (value: (key: Key) => string) => (a: Key, b: Key) => value(a).localeCompare(value(b)) || newestFirst(a, b)
|
|
113
|
+
expect(await all({ sort: 'template', direction: 'asc' })).toEqual(ids([...KEYS].sort(by(key => key.template))))
|
|
114
|
+
expect(await all({ sort: 'status', direction: 'asc' })).toEqual(ids([...KEYS].sort(by(key => key.status))))
|
|
115
|
+
expect(await all({ sort: 'customer', direction: 'asc' })).toEqual(ids([...KEYS].sort(by(key => key.customerId ? customerName(key.customerId).toLowerCase() : ''))))
|
|
116
|
+
|
|
117
|
+
// The links past the 500th come with the key.
|
|
118
|
+
const linked = (await read({ search: 'BUYER515@' })).records.find(record => record.product_id === 520 || record.order_id === 510) ?? (await read({ search: 'BUYER515@' })).records[0]!
|
|
119
|
+
expect(linked.customer).toEqual({ id: 515, label: 'zelda Late', detail: 'buyer515@shop.test' })
|
|
120
|
+
const withProduct = (await read({ search: 'zebra suite' })).records[0]!
|
|
121
|
+
expect(withProduct.product).toEqual({ id: 520, label: 'Zebra Suite' })
|
|
122
|
+
const withOrder = (await read({ search: '510' })).records[0]!
|
|
123
|
+
expect(withOrder.order).toEqual({ id: 510, label: 'Order #510', detail: 'refunded' })
|
|
124
|
+
|
|
125
|
+
// The dialog's choices: bounded, searched, past the 500th.
|
|
126
|
+
const choose = (kind: 'customers' | 'products' | 'orders', search: string, limit = 25) => searchLicenseKeyChoices(kind, { search, limit }, runner, dialect)
|
|
127
|
+
expect((await choose('customers', 'ZE')).choices.map(choice => choice.label)).toEqual(['Zed early', 'zelda Late'])
|
|
128
|
+
expect(await choose('products', '520')).toEqual({ choices: [{ id: 520, label: 'Zebra Suite' }], total: 1 })
|
|
129
|
+
expect((await choose('orders', 'refund')).choices).toEqual([{ id: 510, label: 'Order #510', detail: 'refunded' }])
|
|
130
|
+
const newestOrders = await choose('orders', '', 3)
|
|
131
|
+
expect(newestOrders.choices.map(choice => choice.id)).toEqual([520, 519, 518])
|
|
132
|
+
expect(newestOrders.total).toBe(ROWS)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
describe('readLicenseKeyPage on SQLite', () => {
|
|
136
|
+
test('summary, search, sorts, pages, links and choices', async () => {
|
|
137
|
+
const database = new Database(':memory:')
|
|
138
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
139
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
140
|
+
})
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
144
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
145
|
+
|
|
146
|
+
test.skipIf(!connection)(`readLicenseKeyPage on ${dialect}: summary, search, sorts, pages, links and choices`, async () => {
|
|
147
|
+
const url = new URL(connection!)
|
|
148
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
149
|
+
throw new Error('Licence key list tests require a local disposable database server')
|
|
150
|
+
|
|
151
|
+
const name = `stacks_license_keys_${crypto.randomUUID().replaceAll('-', '')}`
|
|
152
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
153
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
154
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
155
|
+
const scoped = new URL(url.href)
|
|
156
|
+
scoped.pathname = `/${name}`
|
|
157
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
158
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
159
|
+
|
|
160
|
+
try {
|
|
161
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
162
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
await database.close()
|
|
166
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
167
|
+
finally { await admin.close() }
|
|
168
|
+
}
|
|
169
|
+
}, 60_000)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
describe('parseLicenseKeyListQuery', () => {
|
|
173
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
174
|
+
|
|
175
|
+
test('defaults to every key, newest first, 25 a page', () => {
|
|
176
|
+
expect(parseLicenseKeyListQuery(reader({}))).toEqual({ search: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
|
|
177
|
+
expect(parseLicenseKeyListQuery(reader({ sort: 'expiry' }))).toHaveProperty('direction', 'asc')
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
test('refuses values the page does not offer', () => {
|
|
181
|
+
expect(parseLicenseKeyListQuery(reader({ sort: 'uuid' }))).toHaveProperty('error')
|
|
182
|
+
expect(parseLicenseKeyListQuery(reader({ direction: 'up' }))).toHaveProperty('error')
|
|
183
|
+
})
|
|
184
|
+
})
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { db, getDatabaseDialect, sqlDateTime } from '@stacksjs/database/runtime'
|
|
3
|
+
import type { QueryReader } from '../Content/content-list'
|
|
4
|
+
import { containsPattern, countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
|
|
5
|
+
import type { NamedSearchQuery } from '../named-search'
|
|
6
|
+
import { referencedIds } from './commerce-record'
|
|
7
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
8
|
+
import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
|
|
9
|
+
import type { LicenseKeyRecord, LicenseKeyRelatedSummary } from './license-key-records'
|
|
10
|
+
import {
|
|
11
|
+
indexLicenseKeyOptions,
|
|
12
|
+
normalizeLicenseKeyCustomer,
|
|
13
|
+
normalizeLicenseKeyOrder,
|
|
14
|
+
normalizeLicenseKeyProduct,
|
|
15
|
+
normalizeLicenseKeyRecord,
|
|
16
|
+
} from './license-key-records'
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* One page of licence keys, searched, sorted and counted by the database, with
|
|
20
|
+
* the summary of every key, and the customers, products and orders the key
|
|
21
|
+
* dialog offers, searched (stacksjs/stacks#3218).
|
|
22
|
+
*
|
|
23
|
+
* The Licence Keys page used to read the newest 500 keys and do all of that in
|
|
24
|
+
* the browser, so an older key could not be found, and its cards counted those
|
|
25
|
+
* 500. The dialog was handed the first 500 customers, products and orders, so
|
|
26
|
+
* a key could not be linked to any later one, and the page labelled each key's
|
|
27
|
+
* links from those same 500, so a key linked to a later one showed no link.
|
|
28
|
+
*/
|
|
29
|
+
export const LICENSE_KEY_SORTS = ['created', 'id', 'key', 'template', 'customer', 'product', 'order', 'expiry', 'status'] as const
|
|
30
|
+
export type LicenseKeySort = typeof LICENSE_KEY_SORTS[number]
|
|
31
|
+
|
|
32
|
+
export interface LicenseKeyListQuery {
|
|
33
|
+
search: string
|
|
34
|
+
sort: LicenseKeySort
|
|
35
|
+
direction: 'asc' | 'desc'
|
|
36
|
+
page: number
|
|
37
|
+
perPage: number
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface LicenseKeySummary {
|
|
41
|
+
total: number
|
|
42
|
+
active: number
|
|
43
|
+
/** Linked to a customer, a product or an order. */
|
|
44
|
+
assigned: number
|
|
45
|
+
/** Expiring between now and 30 days from now. */
|
|
46
|
+
expiring: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function parseLicenseKeyListQuery(read: QueryReader): LicenseKeyListQuery | { error: string } {
|
|
50
|
+
const pageText = queryText(read, 'page')
|
|
51
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
52
|
+
if (!Number.isInteger(page) || page < 1)
|
|
53
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
54
|
+
|
|
55
|
+
const sizeText = queryText(read, 'per_page')
|
|
56
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
57
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
58
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
59
|
+
|
|
60
|
+
const sort = queryText(read, 'sort') || 'created'
|
|
61
|
+
if (!(LICENSE_KEY_SORTS as readonly string[]).includes(sort))
|
|
62
|
+
return { error: `sort must be one of ${LICENSE_KEY_SORTS.join(', ')}.` }
|
|
63
|
+
|
|
64
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
65
|
+
const direction = directionText === '' ? (sort === 'created' || sort === 'order' ? 'desc' : 'asc') : directionText
|
|
66
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
67
|
+
return { error: 'direction must be asc or desc.' }
|
|
68
|
+
|
|
69
|
+
const search = queryText(read, 'q')
|
|
70
|
+
if (search.length > 200)
|
|
71
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
72
|
+
|
|
73
|
+
return { search, sort: sort as LicenseKeySort, direction, page, perPage }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const FROM = ' FROM license_keys k LEFT JOIN customers c ON c.id = k.customer_id LEFT JOIN products p ON p.id = k.product_id'
|
|
77
|
+
|
|
78
|
+
function sortExpression(sort: LicenseKeySort, dialect: QueryBuilderDialect): string {
|
|
79
|
+
switch (sort) {
|
|
80
|
+
case 'id': return 'k.id'
|
|
81
|
+
case 'key': return 'k.key'
|
|
82
|
+
// As text: PostgreSQL and MySQL keep both as enums, which sort by declaration order.
|
|
83
|
+
case 'template': return asText('k.template', dialect)
|
|
84
|
+
case 'status': return asText('k.status', dialect)
|
|
85
|
+
case 'customer': return `LOWER(COALESCE(c.name, ''))`
|
|
86
|
+
case 'product': return `LOWER(COALESCE(p.name, ''))`
|
|
87
|
+
case 'order': return 'k.order_id'
|
|
88
|
+
case 'expiry': return 'k.expiry_date'
|
|
89
|
+
default: return 'k.created_at'
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function licenseKeyFilter(query: Pick<LicenseKeyListQuery, 'search'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
94
|
+
if (!query.search)
|
|
95
|
+
return { where: '', values: [] }
|
|
96
|
+
const { bind, values } = binder(dialect)
|
|
97
|
+
const pattern = containsPattern(query.search)
|
|
98
|
+
const columns = [
|
|
99
|
+
'k.key',
|
|
100
|
+
asText('k.template', dialect),
|
|
101
|
+
asText('k.status', dialect),
|
|
102
|
+
`COALESCE(c.name, '')`,
|
|
103
|
+
`COALESCE(c.email, '')`,
|
|
104
|
+
`COALESCE(p.name, '')`,
|
|
105
|
+
`COALESCE(${asText('k.order_id', dialect)}, '')`,
|
|
106
|
+
]
|
|
107
|
+
return { where: ` WHERE (${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`, values }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function orderBy(query: Pick<LicenseKeyListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
111
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
112
|
+
// Ties read newest first; the id breaks every remaining tie, so pages never
|
|
113
|
+
// repeat or skip a key.
|
|
114
|
+
if (query.sort === 'created' || query.sort === 'id' || query.sort === 'key')
|
|
115
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, k.id ${direction}`
|
|
116
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, k.created_at DESC, k.id DESC`
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Keys turned into records, against exactly the customers, products and orders they reference. */
|
|
120
|
+
async function recordsFor(keys: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<LicenseKeyRecord[]> {
|
|
121
|
+
if (keys.length === 0)
|
|
122
|
+
return []
|
|
123
|
+
const read = (table: string, columns: string, ids: unknown[]) => ids.length > 0
|
|
124
|
+
? run.unsafe(`SELECT ${columns} FROM ${table} WHERE id IN (${idPlaceholders(ids, dialect)})`, ids).execute()
|
|
125
|
+
: Promise.resolve([])
|
|
126
|
+
const [customers, products, orders] = await Promise.all([
|
|
127
|
+
read('customers', 'id, name, email', referencedIds(keys, 'customer_id')),
|
|
128
|
+
read('products', 'id, name', referencedIds(keys, 'product_id')),
|
|
129
|
+
read('orders', 'id, status', referencedIds(keys, 'order_id')),
|
|
130
|
+
])
|
|
131
|
+
const customerMap = indexLicenseKeyOptions(sqlRows(customers).map(normalizeLicenseKeyCustomer))
|
|
132
|
+
const productMap = indexLicenseKeyOptions(sqlRows(products).map(normalizeLicenseKeyProduct))
|
|
133
|
+
const orderMap = indexLicenseKeyOptions(sqlRows(orders).map(normalizeLicenseKeyOrder))
|
|
134
|
+
return keys.map(key => normalizeLicenseKeyRecord(key, customerMap, productMap, orderMap))
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The summary cards, over every key as before. */
|
|
138
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect, now: Date): Promise<LicenseKeySummary> {
|
|
139
|
+
const { bind, values } = binder(dialect)
|
|
140
|
+
// SQLite keeps timestamps as text, where "2026-11-06 10:00" and
|
|
141
|
+
// "2026-11-06T09:00" compare the wrong way round, so both sides go through
|
|
142
|
+
// datetime() there. The others parse the value.
|
|
143
|
+
const at = (value: string) => dialect === 'sqlite' ? `datetime(${value})` : value
|
|
144
|
+
const from = bind(sqlDateTime(now))
|
|
145
|
+
const until = bind(sqlDateTime(new Date(now.getTime() + 30 * 86_400_000)))
|
|
146
|
+
const row = sqlRows(await run.unsafe(
|
|
147
|
+
`SELECT COUNT(*) AS total_count, SUM(CASE WHEN ${asText('status', dialect)} = 'active' THEN 1 ELSE 0 END) AS active_count, SUM(CASE WHEN customer_id IS NOT NULL OR product_id IS NOT NULL OR order_id IS NOT NULL THEN 1 ELSE 0 END) AS assigned_count, SUM(CASE WHEN ${at('expiry_date')} >= ${at(from)} AND ${at('expiry_date')} <= ${at(until)} THEN 1 ELSE 0 END) AS expiring_count FROM license_keys`,
|
|
148
|
+
values,
|
|
149
|
+
).execute())[0] ?? {}
|
|
150
|
+
return {
|
|
151
|
+
total: countOf(row.total_count),
|
|
152
|
+
active: countOf(row.active_count),
|
|
153
|
+
assigned: countOf(row.assigned_count),
|
|
154
|
+
expiring: countOf(row.expiring_count),
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface LicenseKeyPage {
|
|
159
|
+
records: LicenseKeyRecord[]
|
|
160
|
+
total: number
|
|
161
|
+
page: number
|
|
162
|
+
summary: LicenseKeySummary
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function readLicenseKeyPage(
|
|
166
|
+
query: LicenseKeyListQuery,
|
|
167
|
+
run: CommerceSqlRunner = db,
|
|
168
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
169
|
+
now: Date = new Date(),
|
|
170
|
+
): Promise<LicenseKeyPage> {
|
|
171
|
+
const { where, values } = licenseKeyFilter(query, dialect)
|
|
172
|
+
const [counted, summary] = await Promise.all([
|
|
173
|
+
run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
|
|
174
|
+
summarize(run, dialect, now),
|
|
175
|
+
])
|
|
176
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
177
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
178
|
+
const keys = await run.unsafe(
|
|
179
|
+
`SELECT k.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
180
|
+
values,
|
|
181
|
+
).execute()
|
|
182
|
+
return { records: await recordsFor(sqlRows(keys), run, dialect), total, page, summary }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export const LICENSE_KEY_CHOICE_KINDS = ['customers', 'products', 'orders'] as const
|
|
186
|
+
export type LicenseKeyChoiceKind = typeof LICENSE_KEY_CHOICE_KINDS[number]
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The customers (by name or email), products (by name or id) or orders (by id
|
|
190
|
+
* or status, newest first) the key dialog offers, bounded, with how many
|
|
191
|
+
* matched.
|
|
192
|
+
*/
|
|
193
|
+
export async function searchLicenseKeyChoices(
|
|
194
|
+
kind: LicenseKeyChoiceKind,
|
|
195
|
+
query: NamedSearchQuery,
|
|
196
|
+
run: CommerceSqlRunner = db,
|
|
197
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
198
|
+
): Promise<{ choices: LicenseKeyRelatedSummary[], total: number }> {
|
|
199
|
+
const spec = {
|
|
200
|
+
customers: { columns: 'id, name, email', searched: [`COALESCE(name, '')`, `COALESCE(email, '')`], order: `LOWER(COALESCE(name, '')) ASC, id ASC`, normalize: normalizeLicenseKeyCustomer },
|
|
201
|
+
products: { columns: 'id, name', searched: [`COALESCE(name, '')`, asText('id', dialect)], order: `LOWER(COALESCE(name, '')) ASC, id ASC`, normalize: normalizeLicenseKeyProduct },
|
|
202
|
+
orders: { columns: 'id, status', searched: [asText('id', dialect), asText('status', dialect)], order: 'id DESC', normalize: normalizeLicenseKeyOrder },
|
|
203
|
+
}[kind]
|
|
204
|
+
if (!spec)
|
|
205
|
+
throw new TypeError(`${kind} is not a licence key choice.`)
|
|
206
|
+
const { bind, values } = binder(dialect)
|
|
207
|
+
let where = ''
|
|
208
|
+
if (query.search) {
|
|
209
|
+
const pattern = containsPattern(query.search)
|
|
210
|
+
where = ` WHERE ${spec.searched.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')}`
|
|
211
|
+
}
|
|
212
|
+
const [counted, found] = await Promise.all([
|
|
213
|
+
run.unsafe(`SELECT COUNT(*) AS total_count FROM ${kind}${where}`, values).execute(),
|
|
214
|
+
run.unsafe(`SELECT ${spec.columns} FROM ${kind}${where} ORDER BY ${spec.order} LIMIT ${query.limit}`, values).execute(),
|
|
215
|
+
])
|
|
216
|
+
return { choices: sqlRows(found).map(spec.normalize), total: countOf(sqlRows(counted)[0]?.total_count) }
|
|
217
|
+
}
|