@stacksjs/defaults 0.75.487 → 0.75.490
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +27 -2
- package/ai/skills/stacks-native/CATALOG.md +9 -9
- package/ai/skills/stacks-search-engine/SKILL.md +14 -0
- package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
- package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
- package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
- package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
- package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
- package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
- package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
- package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
- package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
- package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
- package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
- package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
- package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
- package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
- package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
- package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
- package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
- package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
- package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
- package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
- package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
- package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
- package/app/Actions/Dashboard/Content/content-list.ts +10 -0
- package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
- package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
- package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
- package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
- package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
- package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
- package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
- package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
- package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
- package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
- package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
- package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
- package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
- package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
- package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +9 -6
- package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
- package/app/Actions/Dashboard/Queue/queue-stats.ts +10 -0
- package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
- package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
- package/app/Actions/Dashboard/named-search.test.ts +36 -0
- package/app/Actions/Dashboard/named-search.ts +80 -0
- package/app/Models/QueueWorker.ts +1 -0
- package/app/Models/Request.ts +4 -2
- package/bootstrap.ts +6 -1
- package/functions/commerce/shippings/dashboard-resource.ts +12 -1
- package/functions/commerce/shippings/delivery-routes.ts +1 -0
- package/functions/commerce/shippings/license-keys.ts +1 -0
- package/functions/dashboard-list.test.ts +132 -1
- package/functions/dashboard-list.ts +198 -1
- package/functions/queue.ts +2 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +2 -2
- package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
- package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
- package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
- package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
- package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
- package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
- package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
- package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
- package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
- package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
- package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
- package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
- package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
- package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
- package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
- package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
- package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
- package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
- package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
- package/resources/components/Dashboard/Queue/QueueDashboard.stx +8 -2
- package/resources/functions/dashboard/sidebar.ts +26 -1
- package/routes/dashboard-api.ts +11 -0
- package/views/dashboard/stores/kanban.ts +38 -6
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { db, getDatabaseDialect, sqlDateTime } from '@stacksjs/database/runtime'
|
|
3
|
+
import type { QueryReader } from '../Content/content-list'
|
|
4
|
+
import { containsPattern, countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
|
|
5
|
+
import { commerceCurrency, commerceIdentifier, commerceValue, referencedIds } from './commerce-record'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
|
|
8
|
+
import type { PaymentRecord, PaymentSummary } from './payment-records'
|
|
9
|
+
import { normalizePaymentRecord } from './payment-records'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One page of payments, searched, filtered, sorted, counted and summarised by
|
|
13
|
+
* the database (stacksjs/stacks#3218).
|
|
14
|
+
*
|
|
15
|
+
* The Payments page used to read the newest 500 payments and do all of that
|
|
16
|
+
* in the browser, so a payment past the 500th could not be found, and the
|
|
17
|
+
* summary for "the current view" described only what those 500 held.
|
|
18
|
+
*/
|
|
19
|
+
export const PAYMENT_SORTS = ['created', 'id', 'billing', 'amount', 'method', 'status'] as const
|
|
20
|
+
export type PaymentSort = typeof PAYMENT_SORTS[number]
|
|
21
|
+
|
|
22
|
+
/** The time ranges the page offers, in days. `0` is all time. */
|
|
23
|
+
export const PAYMENT_RANGES = [1, 7, 30, 90, 365, 0] as const
|
|
24
|
+
|
|
25
|
+
/** The statuses that count as captured, as `isSuccessfulPayment` has them. */
|
|
26
|
+
const SUCCESSFUL = ['completed', 'succeeded', 'partiallyRefunded', 'refunded']
|
|
27
|
+
|
|
28
|
+
/** What the breakdown panels show for the matching payments. */
|
|
29
|
+
export interface PaymentBreakdown {
|
|
30
|
+
statuses: Array<{ key: string, count: number }>
|
|
31
|
+
methods: Array<{ key: string, count: number }>
|
|
32
|
+
currencies: Array<{ currency: string, captured: number, refunded: number }>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface PaymentListQuery {
|
|
36
|
+
search: string
|
|
37
|
+
status: string
|
|
38
|
+
method: string
|
|
39
|
+
/** Days back from now; 0 for all time. */
|
|
40
|
+
days: number
|
|
41
|
+
sort: PaymentSort
|
|
42
|
+
direction: 'asc' | 'desc'
|
|
43
|
+
page: number
|
|
44
|
+
perPage: number
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function parsePaymentListQuery(read: QueryReader): PaymentListQuery | { error: string } {
|
|
48
|
+
const pageText = queryText(read, 'page')
|
|
49
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
50
|
+
if (!Number.isInteger(page) || page < 1)
|
|
51
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
52
|
+
|
|
53
|
+
const sizeText = queryText(read, 'per_page')
|
|
54
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
55
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
56
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
57
|
+
|
|
58
|
+
const sort = queryText(read, 'sort') || 'created'
|
|
59
|
+
if (!(PAYMENT_SORTS as readonly string[]).includes(sort))
|
|
60
|
+
return { error: `sort must be one of ${PAYMENT_SORTS.join(', ')}.` }
|
|
61
|
+
|
|
62
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
63
|
+
const direction = directionText === '' ? (sort === 'created' || sort === 'amount' ? 'desc' : 'asc') : directionText
|
|
64
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
65
|
+
return { error: 'direction must be asc or desc.' }
|
|
66
|
+
|
|
67
|
+
const rangeText = queryText(read, 'days')
|
|
68
|
+
const days = rangeText === '' || rangeText === 'all' ? 0 : Number(rangeText)
|
|
69
|
+
if (!(PAYMENT_RANGES as readonly number[]).includes(days))
|
|
70
|
+
return { error: 'days must be 1, 7, 30, 90, 365 or all.' }
|
|
71
|
+
|
|
72
|
+
const search = queryText(read, 'q')
|
|
73
|
+
if (search.length > 200)
|
|
74
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
75
|
+
|
|
76
|
+
const status = queryText(read, 'status')
|
|
77
|
+
const method = queryText(read, 'method')
|
|
78
|
+
if (status.length > 100 || method.length > 100)
|
|
79
|
+
return { error: 'status and method must be 100 characters or fewer.' }
|
|
80
|
+
|
|
81
|
+
return { search, status, method, days, sort: sort as PaymentSort, direction, page, perPage }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function sortExpression(sort: PaymentSort, dialect: QueryBuilderDialect): string {
|
|
85
|
+
switch (sort) {
|
|
86
|
+
case 'id': return 'id'
|
|
87
|
+
case 'billing': return `LOWER(COALESCE(billing_email, ''))`
|
|
88
|
+
case 'amount': return 'amount'
|
|
89
|
+
case 'method': return asText('method', dialect)
|
|
90
|
+
case 'status': return asText('status', dialect)
|
|
91
|
+
default: return 'created_at'
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The WHERE clause and its values for a query's search, filters and time range. */
|
|
96
|
+
export function paymentFilter(query: Pick<PaymentListQuery, 'search' | 'status' | 'method' | 'days'>, dialect: QueryBuilderDialect, now: Date = new Date()): { where: string, values: unknown[] } {
|
|
97
|
+
const { bind, values } = binder(dialect)
|
|
98
|
+
const clauses: string[] = []
|
|
99
|
+
if (query.status)
|
|
100
|
+
clauses.push(`${asText('status', dialect)} = ${bind(query.status)}`)
|
|
101
|
+
if (query.method)
|
|
102
|
+
clauses.push(`${asText('method', dialect)} = ${bind(query.method)}`)
|
|
103
|
+
if (query.days > 0) {
|
|
104
|
+
const since = bind(sqlDateTime(new Date(now.getTime() - query.days * 86_400_000)))
|
|
105
|
+
// SQLite keeps timestamps as text and compares them as text, where
|
|
106
|
+
// "2026-11-06 10:00" and "2026-11-06T09:00" sort the wrong way round, so
|
|
107
|
+
// both sides go through datetime() there. The others parse the value.
|
|
108
|
+
clauses.push(dialect === 'sqlite' ? `datetime(created_at) >= datetime(${since})` : `created_at >= ${since}`)
|
|
109
|
+
}
|
|
110
|
+
if (query.search) {
|
|
111
|
+
const pattern = containsPattern(query.search)
|
|
112
|
+
const columns = [
|
|
113
|
+
asText('id', dialect),
|
|
114
|
+
`COALESCE(reference_number, '')`,
|
|
115
|
+
`COALESCE(billing_email, '')`,
|
|
116
|
+
`COALESCE(transaction_id, '')`,
|
|
117
|
+
`COALESCE(payment_provider, '')`,
|
|
118
|
+
`COALESCE(${asText('order_id', dialect)}, '')`,
|
|
119
|
+
asText('method', dialect),
|
|
120
|
+
asText('status', dialect),
|
|
121
|
+
]
|
|
122
|
+
clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
123
|
+
}
|
|
124
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Payments turned into records, against exactly the orders and customers they reference. */
|
|
128
|
+
async function recordsFor(payments: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<PaymentRecord[]> {
|
|
129
|
+
if (payments.length === 0)
|
|
130
|
+
return []
|
|
131
|
+
const orderIds = referencedIds(payments, 'order_id')
|
|
132
|
+
const customerIds = referencedIds(payments, 'customer_id')
|
|
133
|
+
const [orders, customers] = await Promise.all([
|
|
134
|
+
orderIds.length > 0 ? run.unsafe(`SELECT id FROM orders WHERE id IN (${idPlaceholders(orderIds, dialect)})`, orderIds).execute() : [],
|
|
135
|
+
customerIds.length > 0 ? run.unsafe(`SELECT id FROM customers WHERE id IN (${idPlaceholders(customerIds, dialect)})`, customerIds).execute() : [],
|
|
136
|
+
])
|
|
137
|
+
const ids = (result: unknown, source: string) => new Set(sqlRows(result).map(row => commerceIdentifier(commerceValue(row, 'id'), source)))
|
|
138
|
+
const relationships = { orderIds: ids(orders, 'Order'), customerIds: ids(customers, 'Customer') }
|
|
139
|
+
return payments.map(payment => normalizePaymentRecord(payment, relationships))
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The summary and breakdown of the matching payments, as `summarizePayments`
|
|
144
|
+
* and the breakdown panels computed them over the records they had.
|
|
145
|
+
*/
|
|
146
|
+
async function summarize(where: string, values: unknown[], run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<{ summary: PaymentSummary, breakdown: PaymentBreakdown }> {
|
|
147
|
+
const status = asText('status', dialect)
|
|
148
|
+
const successful = `${status} IN (${SUCCESSFUL.map(name => `'${name}'`).join(', ')})`
|
|
149
|
+
const grouped = (column: string) =>
|
|
150
|
+
run.unsafe(`SELECT ${asText(column, dialect)} AS value, COUNT(*) AS item_count FROM payments${where} GROUP BY ${asText(column, dialect)}`, values).execute()
|
|
151
|
+
const [counts, currencies, byStatus, byMethod] = await Promise.all([
|
|
152
|
+
run.unsafe(`SELECT COUNT(*) AS total_count, SUM(CASE WHEN ${successful} THEN 1 ELSE 0 END) AS successful_count, SUM(CASE WHEN ${status} = 'failed' THEN 1 ELSE 0 END) AS failed_count FROM payments${where}`, values).execute(),
|
|
153
|
+
run.unsafe(`SELECT currency, SUM(CASE WHEN ${successful} THEN 1 ELSE 0 END) AS captured_count, SUM(CASE WHEN ${successful} THEN amount ELSE 0 END) AS captured_total, SUM(CASE WHEN refund_amount > 0 THEN 1 ELSE 0 END) AS refund_count, SUM(CASE WHEN refund_amount > 0 THEN refund_amount ELSE 0 END) AS refunded_total FROM payments${where} GROUP BY currency`, values).execute(),
|
|
154
|
+
grouped('status'),
|
|
155
|
+
grouped('method'),
|
|
156
|
+
])
|
|
157
|
+
const count = sqlRows(counts)[0] ?? {}
|
|
158
|
+
const total = countOf(count.total_count)
|
|
159
|
+
const success = countOf(count.successful_count)
|
|
160
|
+
const settled = success + countOf(count.failed_count)
|
|
161
|
+
|
|
162
|
+
const names = new Set<string>()
|
|
163
|
+
const capturedByCurrency: Record<string, number> = {}
|
|
164
|
+
const refundedByCurrency: Record<string, number> = {}
|
|
165
|
+
const perCurrency = new Map<string, { currency: string, captured: number, refunded: number }>()
|
|
166
|
+
for (const row of sqlRows(currencies)) {
|
|
167
|
+
// Normalized as the records are, so "usd" and "USD" are one currency.
|
|
168
|
+
const currency = commerceCurrency(row.currency, 'Payment summary')
|
|
169
|
+
names.add(currency)
|
|
170
|
+
if (countOf(row.captured_count) > 0)
|
|
171
|
+
capturedByCurrency[currency] = (capturedByCurrency[currency] ?? 0) + countOf(row.captured_total)
|
|
172
|
+
if (countOf(row.refund_count) > 0)
|
|
173
|
+
refundedByCurrency[currency] = (refundedByCurrency[currency] ?? 0) + countOf(row.refunded_total)
|
|
174
|
+
const entry = perCurrency.get(currency) ?? { currency, captured: 0, refunded: 0 }
|
|
175
|
+
entry.captured += countOf(row.captured_total)
|
|
176
|
+
entry.refunded += countOf(row.refunded_total)
|
|
177
|
+
perCurrency.set(currency, entry)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const tally = (result: unknown) => {
|
|
181
|
+
const merged = new Map<string, number>()
|
|
182
|
+
for (const row of sqlRows(result)) {
|
|
183
|
+
const key = String(row.value ?? '').trim() || 'unknown'
|
|
184
|
+
merged.set(key, (merged.get(key) ?? 0) + countOf(row.item_count))
|
|
185
|
+
}
|
|
186
|
+
return [...merged.entries()].map(([key, count]) => ({ key, count }))
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
summary: {
|
|
191
|
+
total,
|
|
192
|
+
successful: success,
|
|
193
|
+
currencies: [...names].sort(),
|
|
194
|
+
capturedByCurrency,
|
|
195
|
+
refundedByCurrency,
|
|
196
|
+
successRate: settled ? Math.round((success / settled) * 1000) / 10 : 0,
|
|
197
|
+
},
|
|
198
|
+
breakdown: {
|
|
199
|
+
statuses: tally(byStatus),
|
|
200
|
+
methods: tally(byMethod),
|
|
201
|
+
currencies: [...perCurrency.values()],
|
|
202
|
+
},
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The filter choices: every status and method any payment has. */
|
|
207
|
+
async function choices(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<{ statuses: string[], methods: string[] }> {
|
|
208
|
+
const [statuses, methods] = await Promise.all([
|
|
209
|
+
run.unsafe(`SELECT DISTINCT ${asText('status', dialect)} AS value FROM payments WHERE status IS NOT NULL`).execute(),
|
|
210
|
+
run.unsafe(`SELECT DISTINCT ${asText('method', dialect)} AS value FROM payments WHERE method IS NOT NULL`).execute(),
|
|
211
|
+
])
|
|
212
|
+
const values = (result: unknown) => [...new Set(sqlRows(result).map(row => String(row.value ?? '').trim()).filter(Boolean))].sort()
|
|
213
|
+
return { statuses: values(statuses), methods: values(methods) }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function orderBy(query: Pick<PaymentListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
217
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
218
|
+
// Status sorts newest first within a status, as the page did; the id breaks
|
|
219
|
+
// every remaining tie, so pages never repeat or skip a payment.
|
|
220
|
+
const within = query.sort === 'status' ? ', created_at DESC' : ''
|
|
221
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}${within}, id ${direction}`
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export interface PaymentPage {
|
|
225
|
+
records: PaymentRecord[]
|
|
226
|
+
total: number
|
|
227
|
+
page: number
|
|
228
|
+
summary: PaymentSummary
|
|
229
|
+
breakdown: PaymentBreakdown
|
|
230
|
+
statuses: string[]
|
|
231
|
+
methods: string[]
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export async function readPaymentPage(
|
|
235
|
+
query: PaymentListQuery,
|
|
236
|
+
run: CommerceSqlRunner = db,
|
|
237
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
238
|
+
now: Date = new Date(),
|
|
239
|
+
): Promise<PaymentPage> {
|
|
240
|
+
const { where, values } = paymentFilter(query, dialect, now)
|
|
241
|
+
const [{ summary, breakdown }, options] = await Promise.all([
|
|
242
|
+
summarize(where, values, run, dialect),
|
|
243
|
+
choices(run, dialect),
|
|
244
|
+
])
|
|
245
|
+
const page = pageWithin(query.page, summary.total, query.perPage)
|
|
246
|
+
const payments = await run.unsafe(
|
|
247
|
+
`SELECT * FROM payments${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
248
|
+
values,
|
|
249
|
+
).execute()
|
|
250
|
+
return { records: await recordsFor(sqlRows(payments), run, dialect), total: summary.total, page, summary, breakdown, ...options }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Every payment matching the query, in its order, for the CSV export, a batch at a time. */
|
|
254
|
+
export async function readPaymentsForExport(
|
|
255
|
+
query: Omit<PaymentListQuery, 'page' | 'perPage'>,
|
|
256
|
+
run: CommerceSqlRunner = db,
|
|
257
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
258
|
+
now: Date = new Date(),
|
|
259
|
+
batchSize: number = 500,
|
|
260
|
+
): Promise<PaymentRecord[]> {
|
|
261
|
+
const { where, values } = paymentFilter(query, dialect, now)
|
|
262
|
+
const records: PaymentRecord[] = []
|
|
263
|
+
for (let offset = 0; ; offset += batchSize) {
|
|
264
|
+
const batch = sqlRows(await run.unsafe(
|
|
265
|
+
`SELECT * FROM payments${where}${orderBy(query, dialect)} LIMIT ${batchSize} OFFSET ${offset}`,
|
|
266
|
+
values,
|
|
267
|
+
).execute())
|
|
268
|
+
records.push(...await recordsFor(batch, run, dialect))
|
|
269
|
+
if (batch.length < batchSize)
|
|
270
|
+
return records
|
|
271
|
+
}
|
|
272
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import { searchCustomerChoices } from './commerce-choices'
|
|
5
|
+
import type { PosCatalogQuery } from './commerce-pos-catalog'
|
|
6
|
+
import { parsePosCatalogQuery, parsePosIds, readPosCatalogPage, readPosProducts, readPosSettings } from './commerce-pos-catalog'
|
|
7
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The point of sale's catalogue, settings and customers against each
|
|
11
|
+
* dialect's real engine (stacksjs/stacks#3218), over 520 products,
|
|
12
|
+
* categories, manufacturers and customers: it used to read the first 500 of
|
|
13
|
+
* each.
|
|
14
|
+
*/
|
|
15
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
16
|
+
|
|
17
|
+
const ROWS = 520
|
|
18
|
+
const pad = (id: number) => String(id).padStart(3, '0')
|
|
19
|
+
|
|
20
|
+
/** Products 511 to 520 are in category 515 and by manufacturer 520; the rest share seven categories. */
|
|
21
|
+
const PRODUCTS = Array.from({ length: ROWS }, (_, index) => {
|
|
22
|
+
const id = index + 1
|
|
23
|
+
return {
|
|
24
|
+
id,
|
|
25
|
+
name: id === 9 ? 'Latte_100%' : id === 10 ? 'Latte 1000' : `${id % 2 === 0 ? 'item' : 'Item'} ${pad(id)}`,
|
|
26
|
+
available: id % 4 !== 0,
|
|
27
|
+
inventory: id % 5 === 0 ? 0 : id,
|
|
28
|
+
category: id > 510 ? 515 : (id % 7) + 1,
|
|
29
|
+
manufacturer: id > 510 ? 520 : (id % 3) + 1,
|
|
30
|
+
}
|
|
31
|
+
})
|
|
32
|
+
type Product = typeof PRODUCTS[number]
|
|
33
|
+
const sellable = (product: Product) => product.available && product.inventory > 0
|
|
34
|
+
const byName = (a: Product, b: Product) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()) || a.id - b.id
|
|
35
|
+
|
|
36
|
+
function query(overrides: Partial<PosCatalogQuery> = {}): PosCatalogQuery {
|
|
37
|
+
return { search: '', category: '', availability: '', page: 1, perPage: 50, ...overrides }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
41
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
42
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
43
|
+
const bool = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
|
|
44
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
45
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
46
|
+
const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
|
|
47
|
+
const flag = (value: boolean) => dialect === 'postgres' ? value : (value ? 1 : 0)
|
|
48
|
+
let customerStatus = text
|
|
49
|
+
let rateStatus = text
|
|
50
|
+
if (dialect === 'postgres') {
|
|
51
|
+
await run(`CREATE TYPE customer_status AS ENUM ('Active', 'Inactive')`)
|
|
52
|
+
await run(`CREATE TYPE rate_status AS ENUM ('active', 'inactive')`)
|
|
53
|
+
customerStatus = 'customer_status'
|
|
54
|
+
rateStatus = 'rate_status'
|
|
55
|
+
}
|
|
56
|
+
if (dialect === 'mysql') {
|
|
57
|
+
customerStatus = `ENUM('Active', 'Inactive')`
|
|
58
|
+
rateStatus = `ENUM('active', 'inactive')`
|
|
59
|
+
}
|
|
60
|
+
await run(`CREATE TABLE categories (id ${pk}, name ${text})`)
|
|
61
|
+
await run(`CREATE TABLE manufacturers (id ${pk}, manufacturer ${text})`)
|
|
62
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text}, slug ${text}, description ${text} NULL, price INTEGER, image_url ${text} NULL, is_available ${bool}, inventory_count INTEGER, preparation_time INTEGER, allergens ${text} NULL, nutritional_info ${text} NULL, category_id INTEGER NULL, manufacturer_id INTEGER NULL, created_at ${time})`)
|
|
63
|
+
await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text}, phone ${text} NULL, status ${customerStatus})`)
|
|
64
|
+
await run(`CREATE TABLE tax_rates (id ${pk}, rate INTEGER, status ${rateStatus}, is_default ${bool})`)
|
|
65
|
+
|
|
66
|
+
const all = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
67
|
+
await run(`INSERT INTO categories (id, name) VALUES ${rows(ROWS, 2)}`, all.flatMap(id => [id, id === 3 ? 'bakery' : `Category ${pad(id)}`]))
|
|
68
|
+
await run(`INSERT INTO manufacturers (id, manufacturer) VALUES ${rows(ROWS, 2)}`, all.flatMap(id => [id, `Maker ${pad(id)}`]))
|
|
69
|
+
await run(
|
|
70
|
+
`INSERT INTO products (id, name, slug, price, is_available, inventory_count, preparation_time, allergens, category_id, manufacturer_id, created_at) VALUES ${rows(ROWS, 11)}`,
|
|
71
|
+
PRODUCTS.flatMap(product => [product.id, product.name, `item-${product.id}`, 100 + product.id, flag(product.available), product.inventory, 5, '[]', product.category, product.manufacturer, '2026-11-01 09:00:00']),
|
|
72
|
+
)
|
|
73
|
+
await run(`INSERT INTO customers (id, name, email, phone, status) VALUES ${rows(ROWS, 5)}`, all.flatMap(id => [id, id === 515 ? 'Quinn Late' : `Customer ${pad(id)}`, `buyer${id}@shop.test`, null, id % 2 === 1 ? 'Active' : 'Inactive']))
|
|
74
|
+
// The default active rate wins over an earlier active one and an inactive default.
|
|
75
|
+
await run(`INSERT INTO tax_rates (id, rate, status, is_default) VALUES ${rows(3, 4)}`, [1, 5, 'inactive', flag(true), 2, 7, 'active', flag(false), 3, 9, 'active', flag(true)])
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
79
|
+
const page = (overrides: Partial<PosCatalogQuery> = {}) => readPosCatalogPage(query(overrides), runner, dialect)
|
|
80
|
+
const idsOf = (result: { products: Array<{ id: string }> }) => result.products.map(product => product.id)
|
|
81
|
+
const ids = (products: Product[]) => products.map(product => String(product.id))
|
|
82
|
+
|
|
83
|
+
// Settings, counted over every product.
|
|
84
|
+
const settings = await readPosSettings(runner, dialect)
|
|
85
|
+
expect(settings.taxRate).toBe(9)
|
|
86
|
+
expect(settings.summary).toEqual({
|
|
87
|
+
products: ROWS,
|
|
88
|
+
sellable: PRODUCTS.filter(sellable).length,
|
|
89
|
+
inventory: PRODUCTS.reduce((sum, product) => sum + product.inventory, 0),
|
|
90
|
+
})
|
|
91
|
+
expect(settings.categories.map(category => category.label)).toEqual(['bakery', 'Category 001', 'Category 002', 'Category 004', 'Category 005', 'Category 006', 'Category 007', 'Category 515'])
|
|
92
|
+
|
|
93
|
+
// The catalogue by name ignoring case, paged, and every filter.
|
|
94
|
+
const sorted = [...PRODUCTS].sort(byName)
|
|
95
|
+
expect(idsOf(await page())).toEqual(ids(sorted.slice(0, 50)))
|
|
96
|
+
expect(idsOf(await page({ page: 11 }))).toEqual(ids(sorted.slice(500)))
|
|
97
|
+
expect((await page({ page: 99 })).page).toBe(11)
|
|
98
|
+
expect((await page({ availability: 'sellable' })).total).toBe(PRODUCTS.filter(sellable).length)
|
|
99
|
+
expect((await page({ availability: 'unsellable' })).total).toBe(PRODUCTS.filter(product => !sellable(product)).length)
|
|
100
|
+
expect(idsOf(await page({ category: '515' }))).toEqual(ids(PRODUCTS.filter(product => product.category === 515).sort(byName)))
|
|
101
|
+
expect(idsOf(await page({ search: '100%' }))).toEqual(['9'])
|
|
102
|
+
expect((await page({ search: 'bakery' })).total).toBe(PRODUCTS.filter(product => product.category === 3).length)
|
|
103
|
+
|
|
104
|
+
// Category and manufacturer past the 500th, read by the ids the page references.
|
|
105
|
+
const last = (await page({ category: '515' })).products.find(product => product.id === '520')!
|
|
106
|
+
expect(last).toMatchObject({ name: 'item 520', categoryId: '515', categoryName: 'Category 515' })
|
|
107
|
+
|
|
108
|
+
// The cart's own products, whatever page the catalogue shows; a deleted one is absent.
|
|
109
|
+
expect((await readPosProducts([520, 3, 99_999], runner, dialect)).map(product => product.id).sort()).toEqual(['3', '520'])
|
|
110
|
+
|
|
111
|
+
// The checkout's customers: Active only, and found past the 500th.
|
|
112
|
+
const active = await searchCustomerChoices({ search: '', limit: 5 }, runner, dialect, { activeOnly: true })
|
|
113
|
+
expect(active.total).toBe(ROWS / 2)
|
|
114
|
+
expect((await searchCustomerChoices({ search: 'quinn', limit: 5 }, runner, dialect, { activeOnly: true })).choices.map(choice => choice.id)).toEqual(['515'])
|
|
115
|
+
expect((await searchCustomerChoices({ search: 'customer 002', limit: 5 }, runner, dialect, { activeOnly: true })).total).toBe(0)
|
|
116
|
+
expect((await searchCustomerChoices({ search: 'customer 002', limit: 5 }, runner, dialect)).total).toBe(1)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
describe('point of sale catalogue on SQLite', () => {
|
|
120
|
+
test('settings, catalogue, cart products and customers', async () => {
|
|
121
|
+
const database = new Database(':memory:')
|
|
122
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
123
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
124
|
+
})
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
128
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
129
|
+
|
|
130
|
+
test.skipIf(!connection)(`point of sale catalogue on ${dialect}: settings, catalogue, cart products and customers`, async () => {
|
|
131
|
+
const url = new URL(connection!)
|
|
132
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
133
|
+
throw new Error('Point of sale tests require a local disposable database server')
|
|
134
|
+
|
|
135
|
+
const name = `stacks_pos_catalog_${crypto.randomUUID().replaceAll('-', '')}`
|
|
136
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
137
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
138
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
139
|
+
const scoped = new URL(url.href)
|
|
140
|
+
scoped.pathname = `/${name}`
|
|
141
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
142
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
143
|
+
|
|
144
|
+
try {
|
|
145
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
146
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
await database.close()
|
|
150
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
151
|
+
finally { await admin.close() }
|
|
152
|
+
}
|
|
153
|
+
}, 60_000)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
describe('point of sale query parsing', () => {
|
|
157
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
158
|
+
|
|
159
|
+
test('the catalogue defaults to every product, 50 a page', () => {
|
|
160
|
+
expect(parsePosCatalogQuery(reader({}))).toEqual({ search: '', category: '', availability: '', page: 1, perPage: 50 })
|
|
161
|
+
expect(parsePosCatalogQuery(reader({ availability: 'available' }))).toHaveProperty('error')
|
|
162
|
+
expect(parsePosCatalogQuery(reader({ category: 'drinks' }))).toHaveProperty('error')
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
test('cart ids are bounded product ids', () => {
|
|
166
|
+
expect(parsePosIds(reader({}))).toEqual([])
|
|
167
|
+
expect(parsePosIds(reader({ ids: '3, 520,3' }))).toEqual([3, 520])
|
|
168
|
+
expect(parsePosIds(reader({ ids: '3,x' }))).toHaveProperty('error')
|
|
169
|
+
expect(parsePosIds(reader({ ids: Array.from({ length: 101 }, (_, i) => i + 1).join(',') }))).toHaveProperty('error')
|
|
170
|
+
})
|
|
171
|
+
})
|
|
@@ -0,0 +1,152 @@
|
|
|
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 { countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
|
|
5
|
+
import type { CommercePosProduct } from './commerce-pos'
|
|
6
|
+
import { normalizeCommercePosProduct, selectCommercePosTaxRate } from './commerce-pos'
|
|
7
|
+
import { PRODUCT_FROM, productFilter, productRecordsFor } from './commerce-product-list'
|
|
8
|
+
import type { ProductOption } from './commerce-product-records'
|
|
9
|
+
import { normalizeProductOption } from './commerce-product-records'
|
|
10
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
11
|
+
import { asText, idPlaceholders, isTrue, sqlRows } from './commerce-sql'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The point of sale's catalogue and settings, read by the database
|
|
15
|
+
* (stacksjs/stacks#3218).
|
|
16
|
+
*
|
|
17
|
+
* The point of sale used to read the first 500 products, categories,
|
|
18
|
+
* manufacturers, customers and tax rates by name or id with every load, so a
|
|
19
|
+
* product past the 500th could not be rung up, its category or manufacturer
|
|
20
|
+
* failed the whole screen, and the checkout could not be given a later
|
|
21
|
+
* customer. The catalogue is now searched and paged here, a cart is checked
|
|
22
|
+
* against exactly the products it holds, the checkout searches customers
|
|
23
|
+
* (commerce-choices.ts), and the settings are counted over everything.
|
|
24
|
+
*/
|
|
25
|
+
export const POS_AVAILABILITY = ['sellable', 'unsellable'] as const
|
|
26
|
+
|
|
27
|
+
export interface PosCatalogQuery {
|
|
28
|
+
search: string
|
|
29
|
+
/** A category id, or '' for any. */
|
|
30
|
+
category: string
|
|
31
|
+
/** '' for every product. */
|
|
32
|
+
availability: '' | typeof POS_AVAILABILITY[number]
|
|
33
|
+
page: number
|
|
34
|
+
perPage: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The most products a cart can be checked against in one request. */
|
|
38
|
+
export const POS_MAX_IDS = 100
|
|
39
|
+
|
|
40
|
+
export function parsePosCatalogQuery(read: QueryReader): PosCatalogQuery | { error: string } {
|
|
41
|
+
const pageText = queryText(read, 'page')
|
|
42
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
43
|
+
if (!Number.isInteger(page) || page < 1)
|
|
44
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
45
|
+
|
|
46
|
+
const sizeText = queryText(read, 'per_page')
|
|
47
|
+
const perPage = sizeText === '' ? 50 : Number(sizeText)
|
|
48
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
49
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
50
|
+
|
|
51
|
+
const search = queryText(read, 'q')
|
|
52
|
+
if (search.length > 200)
|
|
53
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
54
|
+
|
|
55
|
+
const category = queryText(read, 'category')
|
|
56
|
+
if (category && !/^\d+$/.test(category))
|
|
57
|
+
return { error: 'category must be a category id.' }
|
|
58
|
+
|
|
59
|
+
const availability = queryText(read, 'availability')
|
|
60
|
+
if (availability && !(POS_AVAILABILITY as readonly string[]).includes(availability))
|
|
61
|
+
return { error: `availability must be one of ${POS_AVAILABILITY.join(', ')}.` }
|
|
62
|
+
|
|
63
|
+
return { search, category, availability: availability as PosCatalogQuery['availability'], page, perPage }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The product ids in `ids=1,2,3`, or an error. Empty when there is no `ids`. */
|
|
67
|
+
export function parsePosIds(read: QueryReader): number[] | { error: string } {
|
|
68
|
+
const text = queryText(read, 'ids')
|
|
69
|
+
if (!text)
|
|
70
|
+
return []
|
|
71
|
+
const parts = text.split(',').map(part => part.trim()).filter(Boolean)
|
|
72
|
+
if (parts.length > POS_MAX_IDS)
|
|
73
|
+
return { error: `ids can list at most ${POS_MAX_IDS} products.` }
|
|
74
|
+
if (!parts.every(part => /^\d+$/.test(part)))
|
|
75
|
+
return { error: 'ids must be product ids separated by commas.' }
|
|
76
|
+
return [...new Set(parts.map(Number))]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function posProducts(rows: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<CommercePosProduct[]> {
|
|
80
|
+
return (await productRecordsFor(rows, run, dialect, false)).map(normalizeCommercePosProduct)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface PosCatalogPage {
|
|
84
|
+
products: CommercePosProduct[]
|
|
85
|
+
total: number
|
|
86
|
+
page: number
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** One page of the catalogue, by name ignoring case, then id. */
|
|
90
|
+
export async function readPosCatalogPage(
|
|
91
|
+
query: PosCatalogQuery,
|
|
92
|
+
run: CommerceSqlRunner = db,
|
|
93
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
94
|
+
): Promise<PosCatalogPage> {
|
|
95
|
+
const { where, values } = productFilter({
|
|
96
|
+
search: query.search,
|
|
97
|
+
category: query.category,
|
|
98
|
+
availability: query.availability,
|
|
99
|
+
}, dialect)
|
|
100
|
+
const counted = await run.unsafe(`SELECT COUNT(*) AS total_count${PRODUCT_FROM}${where}`, values).execute()
|
|
101
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
102
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
103
|
+
const rows = await run.unsafe(
|
|
104
|
+
`SELECT p.*${PRODUCT_FROM}${where} ORDER BY LOWER(p.name) ASC, p.id ASC LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
105
|
+
values,
|
|
106
|
+
).execute()
|
|
107
|
+
return { products: await posProducts(sqlRows(rows), run, dialect), total, page }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Exactly the products a cart holds, as they are now, so a reload can update
|
|
112
|
+
* each line's price and stock, or drop it, whatever page the catalogue shows.
|
|
113
|
+
*/
|
|
114
|
+
export async function readPosProducts(
|
|
115
|
+
ids: number[],
|
|
116
|
+
run: CommerceSqlRunner = db,
|
|
117
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
118
|
+
): Promise<CommercePosProduct[]> {
|
|
119
|
+
if (ids.length === 0)
|
|
120
|
+
return []
|
|
121
|
+
const rows = await run.unsafe(`SELECT p.*${PRODUCT_FROM} WHERE p.id IN (${idPlaceholders(ids, dialect)})`, ids).execute()
|
|
122
|
+
return posProducts(sqlRows(rows), run, dialect)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface PosSettings {
|
|
126
|
+
/** The categories some product is in, by name ignoring case. */
|
|
127
|
+
categories: ProductOption[]
|
|
128
|
+
/** The default active tax rate, or the first active one, or 0. */
|
|
129
|
+
taxRate: number
|
|
130
|
+
summary: { products: number, sellable: number, inventory: number }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function readPosSettings(
|
|
134
|
+
run: CommerceSqlRunner = db,
|
|
135
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
136
|
+
): Promise<PosSettings> {
|
|
137
|
+
const [categories, taxRates, totals] = await Promise.all([
|
|
138
|
+
run.unsafe('SELECT c.id, c.name FROM categories c WHERE EXISTS (SELECT 1 FROM products p WHERE p.category_id = c.id) ORDER BY LOWER(c.name) ASC, c.id ASC').execute(),
|
|
139
|
+
run.unsafe(`SELECT id, rate, status, is_default FROM tax_rates WHERE ${asText('status', dialect)} = 'active' ORDER BY CASE WHEN ${isTrue('is_default', dialect)} THEN 0 ELSE 1 END, id LIMIT 1`).execute(),
|
|
140
|
+
run.unsafe(`SELECT COUNT(*) AS product_count, SUM(CASE WHEN ${isTrue('is_available', dialect)} AND inventory_count > 0 THEN 1 ELSE 0 END) AS sellable_count, SUM(inventory_count) AS inventory_total FROM products`).execute(),
|
|
141
|
+
])
|
|
142
|
+
const row = sqlRows(totals)[0] ?? {}
|
|
143
|
+
return {
|
|
144
|
+
categories: sqlRows(categories).map(normalizeProductOption),
|
|
145
|
+
taxRate: selectCommercePosTaxRate(sqlRows(taxRates)),
|
|
146
|
+
summary: {
|
|
147
|
+
products: countOf(row.product_count),
|
|
148
|
+
sellable: countOf(row.sellable_count),
|
|
149
|
+
inventory: countOf(row.inventory_total),
|
|
150
|
+
},
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -2,8 +2,6 @@ import { describe, expect, it } from 'bun:test'
|
|
|
2
2
|
import {
|
|
3
3
|
calculateCommercePosSale,
|
|
4
4
|
deriveCommercePosTaxRate,
|
|
5
|
-
isCommercePosCustomerActive,
|
|
6
|
-
normalizeCommercePosCustomer,
|
|
7
5
|
parseCommercePosLines,
|
|
8
6
|
selectCommercePosTaxRate,
|
|
9
7
|
} from './commerce-pos'
|
|
@@ -81,16 +79,7 @@ describe('dashboard commerce POS helpers', () => {
|
|
|
81
79
|
expect(() => deriveCommercePosTaxRate(100, -1)).toThrow('non-negative')
|
|
82
80
|
})
|
|
83
81
|
|
|
84
|
-
it('validates persisted
|
|
85
|
-
const customer = { id: 1, name: 'Chris', email: 'chris@example.com', status: 'Active' }
|
|
86
|
-
expect(isCommercePosCustomerActive(customer)).toBeTrue()
|
|
87
|
-
expect(normalizeCommercePosCustomer(customer)).toEqual({
|
|
88
|
-
id: '1',
|
|
89
|
-
label: 'Chris',
|
|
90
|
-
email: 'chris@example.com',
|
|
91
|
-
})
|
|
92
|
-
expect(() => normalizeCommercePosCustomer({ id: 1, name: '', email: '' }))
|
|
93
|
-
.toThrow('Customer 1.name must be a non-empty string')
|
|
82
|
+
it('validates persisted tax rates', () => {
|
|
94
83
|
expect(() => selectCommercePosTaxRate([{ id: 1, status: 'active', is_default: false, rate: 'invalid' }]))
|
|
95
84
|
.toThrow('TaxRate 1.rate must be a finite number')
|
|
96
85
|
})
|
|
@@ -13,12 +13,6 @@ export interface CommercePosProduct {
|
|
|
13
13
|
categoryName: string
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
export interface CommercePosCustomer {
|
|
17
|
-
id: string
|
|
18
|
-
label: string
|
|
19
|
-
email: string
|
|
20
|
-
}
|
|
21
|
-
|
|
22
16
|
export interface CommercePosCheckoutLine {
|
|
23
17
|
productId: number
|
|
24
18
|
quantity: number
|
|
@@ -142,26 +136,6 @@ export function normalizeCommercePosProduct(record: CommerceProductRecord): Comm
|
|
|
142
136
|
}
|
|
143
137
|
}
|
|
144
138
|
|
|
145
|
-
export function normalizeCommercePosCustomer(record: any): CommercePosCustomer {
|
|
146
|
-
const id = identifier(value(record, 'id'), 'Customer')
|
|
147
|
-
const source = `Customer ${id}`
|
|
148
|
-
const name = requiredText(value(record, 'name'), source, 'name')
|
|
149
|
-
const email = requiredText(value(record, 'email'), source, 'email')
|
|
150
|
-
return {
|
|
151
|
-
id,
|
|
152
|
-
label: name,
|
|
153
|
-
email,
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
export function isCommercePosCustomerActive(record: any): boolean {
|
|
158
|
-
const id = identifier(value(record, 'id'), 'Customer')
|
|
159
|
-
const status = requiredText(value(record, 'status'), `Customer ${id}`, 'status')
|
|
160
|
-
if (status !== 'Active' && status !== 'Inactive')
|
|
161
|
-
throw recordError(`Customer ${id}`, 'status', 'Active or Inactive')
|
|
162
|
-
return status === 'Active'
|
|
163
|
-
}
|
|
164
|
-
|
|
165
139
|
export function parseCommercePosLines(input: unknown): CommercePosLineInputResult {
|
|
166
140
|
if (!Array.isArray(input) || input.length === 0)
|
|
167
141
|
return { lines: [], error: 'Add at least one product before checkout.' }
|