@stacksjs/defaults 0.75.489 → 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 +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/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 +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 +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 +7 -1
- package/routes/dashboard-api.ts +11 -0
- package/views/dashboard/stores/kanban.ts +38 -6
|
@@ -0,0 +1,276 @@
|
|
|
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 type { CommerceProductRecord, CommerceProductSummary, ProductOption } from './commerce-product-records'
|
|
6
|
+
import { normalizeCommerceProductRecord, normalizeManufacturerOption, normalizeProductOption } from './commerce-product-records'
|
|
7
|
+
import { referencedIds } from './commerce-record'
|
|
8
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
9
|
+
import { asText, binder, idPlaceholders, isTrue, sqlRows } from './commerce-sql'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One page of products, searched, filtered, sorted and counted by the database,
|
|
13
|
+
* with the store-wide summary (stacksjs/stacks#3218).
|
|
14
|
+
*
|
|
15
|
+
* The Products page used to read the newest 500 products and do all of that
|
|
16
|
+
* in the browser, so a product past the 500th could not be found, and its
|
|
17
|
+
* summary cards counted those 500, not the catalogue.
|
|
18
|
+
*/
|
|
19
|
+
export const PRODUCT_SORTS = ['created', 'id', 'name', 'category', 'price', 'inventory', 'available'] as const
|
|
20
|
+
export type ProductSort = typeof PRODUCT_SORTS[number]
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* `sellable` is what the point of sale can ring up: available with stock on
|
|
24
|
+
* hand; `unsellable` is everything else.
|
|
25
|
+
*/
|
|
26
|
+
export const PRODUCT_AVAILABILITY = ['available', 'unavailable', 'out-of-stock', 'sellable', 'unsellable'] as const
|
|
27
|
+
export type ProductAvailability = typeof PRODUCT_AVAILABILITY[number]
|
|
28
|
+
|
|
29
|
+
export interface ProductListQuery {
|
|
30
|
+
search: string
|
|
31
|
+
/** A category id, or '' for any. */
|
|
32
|
+
category: string
|
|
33
|
+
/** '' for any. */
|
|
34
|
+
availability: '' | ProductAvailability
|
|
35
|
+
sort: ProductSort
|
|
36
|
+
direction: 'asc' | 'desc'
|
|
37
|
+
page: number
|
|
38
|
+
perPage: number
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function parseProductListQuery(read: QueryReader): ProductListQuery | { error: string } {
|
|
42
|
+
const pageText = queryText(read, 'page')
|
|
43
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
44
|
+
if (!Number.isInteger(page) || page < 1)
|
|
45
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
46
|
+
|
|
47
|
+
const sizeText = queryText(read, 'per_page')
|
|
48
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
49
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
50
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
51
|
+
|
|
52
|
+
const sort = queryText(read, 'sort') || 'created'
|
|
53
|
+
if (!(PRODUCT_SORTS as readonly string[]).includes(sort))
|
|
54
|
+
return { error: `sort must be one of ${PRODUCT_SORTS.join(', ')}.` }
|
|
55
|
+
|
|
56
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
57
|
+
const direction = directionText === '' ? (['created', 'price', 'inventory'].includes(sort) ? 'desc' : 'asc') : directionText
|
|
58
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
59
|
+
return { error: 'direction must be asc or desc.' }
|
|
60
|
+
|
|
61
|
+
const search = queryText(read, 'q')
|
|
62
|
+
if (search.length > 200)
|
|
63
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
64
|
+
|
|
65
|
+
const category = queryText(read, 'category')
|
|
66
|
+
if (category && !/^\d+$/.test(category))
|
|
67
|
+
return { error: 'category must be a category id.' }
|
|
68
|
+
|
|
69
|
+
const availability = queryText(read, 'availability')
|
|
70
|
+
if (availability && !(PRODUCT_AVAILABILITY as readonly string[]).includes(availability))
|
|
71
|
+
return { error: `availability must be one of ${PRODUCT_AVAILABILITY.join(', ')}.` }
|
|
72
|
+
|
|
73
|
+
return { search, category, availability: availability as ProductListQuery['availability'], sort: sort as ProductSort, direction, page, perPage }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function sortExpression(sort: ProductSort, dialect: QueryBuilderDialect): string {
|
|
77
|
+
switch (sort) {
|
|
78
|
+
case 'id': return 'p.id'
|
|
79
|
+
case 'name': return 'LOWER(p.name)'
|
|
80
|
+
case 'category': return `LOWER(COALESCE(c.name, ''))`
|
|
81
|
+
case 'price': return 'p.price'
|
|
82
|
+
case 'inventory': return 'p.inventory_count'
|
|
83
|
+
case 'available': return `CASE WHEN ${isTrue('p.is_available', dialect)} THEN 1 ELSE 0 END`
|
|
84
|
+
default: return 'p.created_at'
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Products with the category and manufacturer the search and sorts read, as `p`, `c` and `m`. */
|
|
89
|
+
export const PRODUCT_FROM = ' FROM products p LEFT JOIN categories c ON c.id = p.category_id LEFT JOIN manufacturers m ON m.id = p.manufacturer_id'
|
|
90
|
+
const FROM = PRODUCT_FROM
|
|
91
|
+
|
|
92
|
+
export function productFilter(query: Pick<ProductListQuery, 'search' | 'category' | 'availability'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
93
|
+
const { bind, values } = binder(dialect)
|
|
94
|
+
const clauses: string[] = []
|
|
95
|
+
if (query.category)
|
|
96
|
+
clauses.push(`p.category_id = ${bind(Number(query.category))}`)
|
|
97
|
+
if (query.availability === 'available')
|
|
98
|
+
clauses.push(isTrue('p.is_available', dialect))
|
|
99
|
+
if (query.availability === 'unavailable')
|
|
100
|
+
clauses.push(`NOT (${isTrue('p.is_available', dialect)})`)
|
|
101
|
+
if (query.availability === 'out-of-stock')
|
|
102
|
+
clauses.push('p.inventory_count = 0')
|
|
103
|
+
if (query.availability === 'sellable')
|
|
104
|
+
clauses.push(`${isTrue('p.is_available', dialect)} AND p.inventory_count > 0`)
|
|
105
|
+
if (query.availability === 'unsellable')
|
|
106
|
+
clauses.push(`NOT (${isTrue('p.is_available', dialect)} AND p.inventory_count > 0)`)
|
|
107
|
+
if (query.search) {
|
|
108
|
+
const pattern = containsPattern(query.search)
|
|
109
|
+
const columns = [
|
|
110
|
+
asText('p.id', dialect),
|
|
111
|
+
`COALESCE(p.name, '')`,
|
|
112
|
+
`COALESCE(p.description, '')`,
|
|
113
|
+
`COALESCE(c.name, '')`,
|
|
114
|
+
`COALESCE(m.manufacturer, '')`,
|
|
115
|
+
`COALESCE(p.allergens, '')`,
|
|
116
|
+
]
|
|
117
|
+
clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
118
|
+
}
|
|
119
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function orderBy(query: Pick<ProductListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
123
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
124
|
+
// Price, inventory, availability and category ties read by name, as the
|
|
125
|
+
// page sorted them; the id breaks every remaining tie, so pages never repeat
|
|
126
|
+
// or skip a product.
|
|
127
|
+
const byName = ['price', 'inventory', 'available', 'category'].includes(query.sort) ? ', LOWER(p.name) ASC' : ''
|
|
128
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}${byName}, p.id ${direction}`
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** How many rows of `table` each product has, by product id. */
|
|
132
|
+
async function relationCounts(table: 'product_variants' | 'product_units' | 'reviews', productIds: number[], run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<Map<string, number>> {
|
|
133
|
+
if (productIds.length === 0)
|
|
134
|
+
return new Map()
|
|
135
|
+
const rows = sqlRows(await run.unsafe(
|
|
136
|
+
`SELECT product_id, COUNT(*) AS item_count FROM ${table} WHERE product_id IN (${idPlaceholders(productIds, dialect)}) GROUP BY product_id`,
|
|
137
|
+
productIds,
|
|
138
|
+
).execute())
|
|
139
|
+
return new Map(rows.map(row => [String(row.product_id), countOf(row.item_count)]))
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Products turned into records, against exactly the categories and
|
|
144
|
+
* manufacturers they reference. Without `counts`, the variant, unit and review
|
|
145
|
+
* counts are left at zero, for a caller that does not show them (the point of
|
|
146
|
+
* sale).
|
|
147
|
+
*/
|
|
148
|
+
export async function productRecordsFor(
|
|
149
|
+
products: Array<Record<string, unknown>>,
|
|
150
|
+
run: CommerceSqlRunner,
|
|
151
|
+
dialect: QueryBuilderDialect,
|
|
152
|
+
counts: boolean = true,
|
|
153
|
+
): Promise<CommerceProductRecord[]> {
|
|
154
|
+
if (products.length === 0)
|
|
155
|
+
return []
|
|
156
|
+
const productIds = counts ? referencedIds(products, 'id') : []
|
|
157
|
+
const categoryIds = referencedIds(products, 'category_id')
|
|
158
|
+
const manufacturerIds = referencedIds(products, 'manufacturer_id')
|
|
159
|
+
const [categories, manufacturers, variants, units, reviews] = await Promise.all([
|
|
160
|
+
categoryIds.length > 0 ? run.unsafe(`SELECT id, name FROM categories WHERE id IN (${idPlaceholders(categoryIds, dialect)})`, categoryIds).execute() : [],
|
|
161
|
+
manufacturerIds.length > 0 ? run.unsafe(`SELECT id, manufacturer FROM manufacturers WHERE id IN (${idPlaceholders(manufacturerIds, dialect)})`, manufacturerIds).execute() : [],
|
|
162
|
+
relationCounts('product_variants', productIds, run, dialect),
|
|
163
|
+
relationCounts('product_units', productIds, run, dialect),
|
|
164
|
+
relationCounts('reviews', productIds, run, dialect),
|
|
165
|
+
])
|
|
166
|
+
const categoryMap = new Map(sqlRows(categories).map(normalizeProductOption).map(option => [option.id, option.label]))
|
|
167
|
+
const manufacturerMap = new Map(sqlRows(manufacturers).map(normalizeManufacturerOption).map(option => [option.id, option.label]))
|
|
168
|
+
return products.map(product => normalizeCommerceProductRecord(product, categoryMap, manufacturerMap, variants, units, reviews))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** The summary cards, over the whole catalogue as before. */
|
|
172
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<CommerceProductSummary> {
|
|
173
|
+
const row = sqlRows(await run.unsafe(
|
|
174
|
+
`SELECT COUNT(*) AS total_count, SUM(CASE WHEN ${isTrue('is_available', dialect)} THEN 1 ELSE 0 END) AS available_count, SUM(CASE WHEN inventory_count = 0 THEN 1 ELSE 0 END) AS out_count, SUM(inventory_count) AS inventory_total FROM products`,
|
|
175
|
+
).execute())[0] ?? {}
|
|
176
|
+
const total = countOf(row.total_count)
|
|
177
|
+
const available = countOf(row.available_count)
|
|
178
|
+
return {
|
|
179
|
+
total,
|
|
180
|
+
available,
|
|
181
|
+
unavailable: total - available,
|
|
182
|
+
outOfStock: countOf(row.out_count),
|
|
183
|
+
totalInventory: countOf(row.inventory_total),
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Every category and manufacturer, for the filter and the product dialog.
|
|
189
|
+
* These are small reference tables, so they are read whole rather than the
|
|
190
|
+
* first 500 of each.
|
|
191
|
+
*/
|
|
192
|
+
async function options(run: CommerceSqlRunner): Promise<{ categories: ProductOption[], manufacturers: ProductOption[] }> {
|
|
193
|
+
const [categories, manufacturers] = await Promise.all([
|
|
194
|
+
// LOWER, so the order is the same on every dialect: each collates case its own way.
|
|
195
|
+
run.unsafe('SELECT id, name FROM categories ORDER BY LOWER(name) ASC, id ASC').execute(),
|
|
196
|
+
run.unsafe('SELECT id, manufacturer FROM manufacturers ORDER BY LOWER(manufacturer) ASC, id ASC').execute(),
|
|
197
|
+
])
|
|
198
|
+
return {
|
|
199
|
+
categories: sqlRows(categories).map(normalizeProductOption),
|
|
200
|
+
manufacturers: sqlRows(manufacturers).map(normalizeManufacturerOption),
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export interface ProductPage {
|
|
205
|
+
records: CommerceProductRecord[]
|
|
206
|
+
total: number
|
|
207
|
+
page: number
|
|
208
|
+
summary: CommerceProductSummary
|
|
209
|
+
categories: ProductOption[]
|
|
210
|
+
manufacturers: ProductOption[]
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export async function readProductPage(
|
|
214
|
+
query: ProductListQuery,
|
|
215
|
+
run: CommerceSqlRunner = db,
|
|
216
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
217
|
+
): Promise<ProductPage> {
|
|
218
|
+
const { where, values } = productFilter(query, dialect)
|
|
219
|
+
const [counted, summary, choices] = await Promise.all([
|
|
220
|
+
run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
|
|
221
|
+
summarize(run, dialect),
|
|
222
|
+
options(run),
|
|
223
|
+
])
|
|
224
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
225
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
226
|
+
const products = await run.unsafe(
|
|
227
|
+
`SELECT p.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
228
|
+
values,
|
|
229
|
+
).execute()
|
|
230
|
+
return { records: await productRecordsFor(sqlRows(products), run, dialect), total, page, summary, ...choices }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Every product matching the query, in its order, for the CSV export, a batch at a time. */
|
|
234
|
+
export async function readProductsForExport(
|
|
235
|
+
query: Omit<ProductListQuery, 'page' | 'perPage'>,
|
|
236
|
+
run: CommerceSqlRunner = db,
|
|
237
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
238
|
+
batchSize: number = 500,
|
|
239
|
+
): Promise<CommerceProductRecord[]> {
|
|
240
|
+
const { where, values } = productFilter(query, dialect)
|
|
241
|
+
const records: CommerceProductRecord[] = []
|
|
242
|
+
for (let offset = 0; ; offset += batchSize) {
|
|
243
|
+
const batch = sqlRows(await run.unsafe(
|
|
244
|
+
`SELECT p.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${batchSize} OFFSET ${offset}`,
|
|
245
|
+
values,
|
|
246
|
+
).execute())
|
|
247
|
+
records.push(...await productRecordsFor(batch, run, dialect))
|
|
248
|
+
if (batch.length < batchSize)
|
|
249
|
+
return records
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const CSV_HEADER = ['Product ID', 'Name', 'Description', 'Price', 'Currency', 'Availability', 'Inventory', 'Preparation minutes', 'Category', 'Manufacturer', 'Allergens', 'Variants', 'Units', 'Reviews', 'Created at']
|
|
254
|
+
|
|
255
|
+
/** The CSV "Export filtered" downloads: the page's columns, for every matching product. */
|
|
256
|
+
export function productsCsv(records: CommerceProductRecord[], currency: string, minor: (amount: number, currency: string) => string): string {
|
|
257
|
+
const escape = (value: string): string => `"${value.replaceAll('"', '""')}"`
|
|
258
|
+
const lines = records.map(record => [
|
|
259
|
+
record.id,
|
|
260
|
+
record.name,
|
|
261
|
+
record.description,
|
|
262
|
+
minor(record.price, currency),
|
|
263
|
+
currency,
|
|
264
|
+
record.isAvailable ? 'Available' : 'Unavailable',
|
|
265
|
+
String(record.inventoryCount),
|
|
266
|
+
String(record.preparationTime),
|
|
267
|
+
record.categoryName,
|
|
268
|
+
record.manufacturerName,
|
|
269
|
+
record.allergens.join('; '),
|
|
270
|
+
String(record.variantCount),
|
|
271
|
+
String(record.unitCount),
|
|
272
|
+
String(record.reviewCount),
|
|
273
|
+
record.createdAt,
|
|
274
|
+
])
|
|
275
|
+
return `${[CSV_HEADER, ...lines].map(row => row.map(escape).join(',')).join('\n')}`
|
|
276
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { ProductWaitlistListQuery } from './commerce-product-waitlist-list'
|
|
5
|
+
import { parseProductWaitlistListQuery, readProductWaitlistPage } from './commerce-product-waitlist-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The product waitlist against each dialect's real engine
|
|
10
|
+
* (stacksjs/stacks#3218), with status and preference as real enums, and
|
|
11
|
+
* products and customers past the 500 the page used to read.
|
|
12
|
+
*/
|
|
13
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
14
|
+
|
|
15
|
+
const NOW = new Date('2026-11-06T12:00:00.000Z')
|
|
16
|
+
const ROWS = 600
|
|
17
|
+
const STATUSES = ['waiting', 'notified', 'purchased', 'cancelled'] as const
|
|
18
|
+
const PREFERENCES = ['sms', 'email', 'both'] as const
|
|
19
|
+
const PRODUCT_NAMES: Record<number, string> = { 1: 'Coffee Beans', 2: 'apron', 600: 'zebra Tea' }
|
|
20
|
+
const productName = (id: number) => PRODUCT_NAMES[id] ?? `Product ${id}`
|
|
21
|
+
const NAMES = ['ann', 'Ben', 'cat', 'Dan', 'eve']
|
|
22
|
+
|
|
23
|
+
/** 26 entries, one an hour back from NOW; 14 and 15 share a creation time. */
|
|
24
|
+
const ENTRIES = Array.from({ length: 26 }, (_, index) => {
|
|
25
|
+
const id = index + 1
|
|
26
|
+
return {
|
|
27
|
+
id,
|
|
28
|
+
name: id === 9 ? 'Sale_100% Fan' : id === 10 ? 'Sale 1000 Fan' : NAMES[id % NAMES.length]!,
|
|
29
|
+
email: `waiter${id}@shop.test`,
|
|
30
|
+
phone: id === 21 ? '+1 555 0199' : null,
|
|
31
|
+
quantity: (id * 3) % 7 + 1,
|
|
32
|
+
notification_preference: PREFERENCES[id % PREFERENCES.length]!,
|
|
33
|
+
source: id === 17 ? 'in-store' : 'website',
|
|
34
|
+
status: STATUSES[id % STATUSES.length]!,
|
|
35
|
+
product_id: [1, 2, 600][id % 3]!,
|
|
36
|
+
customer_id: id % 5 === 0 ? 599 : null,
|
|
37
|
+
hoursAgo: id === 15 ? 14 : id,
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
type Entry = typeof ENTRIES[number]
|
|
41
|
+
|
|
42
|
+
const ids = (entries: Entry[]) => entries.map(entry => String(entry.id))
|
|
43
|
+
const newestFirst = (a: Entry, b: Entry) => a.hoursAgo - b.hoursAgo || b.id - a.id
|
|
44
|
+
|
|
45
|
+
function query(overrides: Partial<ProductWaitlistListQuery> = {}): ProductWaitlistListQuery {
|
|
46
|
+
return { search: '', status: '', sort: 'created', direction: 'desc', page: 1, perPage: 10, ...overrides }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
50
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
51
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
52
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
53
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
54
|
+
let statusType = text
|
|
55
|
+
let preferenceType = text
|
|
56
|
+
if (dialect === 'postgres') {
|
|
57
|
+
// Declared out of alphabetical order, so a sort that forgets the text cast shows.
|
|
58
|
+
await run(`CREATE TYPE waitlist_status AS ENUM ('waiting', 'notified', 'purchased', 'cancelled')`)
|
|
59
|
+
await run(`CREATE TYPE waitlist_preference AS ENUM ('sms', 'email', 'both')`)
|
|
60
|
+
statusType = 'waitlist_status'
|
|
61
|
+
preferenceType = 'waitlist_preference'
|
|
62
|
+
}
|
|
63
|
+
if (dialect === 'mysql') {
|
|
64
|
+
statusType = `ENUM('waiting', 'notified', 'purchased', 'cancelled')`
|
|
65
|
+
preferenceType = `ENUM('sms', 'email', 'both')`
|
|
66
|
+
}
|
|
67
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text})`)
|
|
68
|
+
await run(`CREATE TABLE customers (id ${pk})`)
|
|
69
|
+
await run(`CREATE TABLE waitlist_products (id ${pk}, name ${text}, email ${text}, phone ${text} NULL, quantity INTEGER, notification_preference ${preferenceType}, source ${text}, notes ${text} NULL, status ${statusType}, product_id INTEGER NULL, customer_id INTEGER NULL, created_at ${time})`)
|
|
70
|
+
const all = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
71
|
+
await run(`INSERT INTO products (id, name) VALUES ${all.map((_, i) => `(${p(2 * i + 1)}, ${p(2 * i + 2)})`).join(', ')}`, all.flatMap(id => [id, productName(id)]))
|
|
72
|
+
await run(`INSERT INTO customers (id) VALUES ${all.map((_, i) => `(${p(i + 1)})`).join(', ')}`, all)
|
|
73
|
+
for (const entry of ENTRIES) {
|
|
74
|
+
await run(
|
|
75
|
+
`INSERT INTO waitlist_products (id, name, email, phone, quantity, notification_preference, source, status, product_id, customer_id, created_at) VALUES (${Array.from({ length: 11 }, (_, i) => p(i + 1)).join(', ')})`,
|
|
76
|
+
[
|
|
77
|
+
entry.id, entry.name, entry.email, entry.phone, entry.quantity, entry.notification_preference, entry.source, entry.status,
|
|
78
|
+
entry.product_id, entry.customer_id, new Date(NOW.getTime() - entry.hoursAgo * 3_600_000).toISOString().slice(0, 19).replace('T', ' '),
|
|
79
|
+
],
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
85
|
+
const read = (overrides: Partial<ProductWaitlistListQuery> = {}) => readProductWaitlistPage(query(overrides), runner, dialect)
|
|
86
|
+
const all = async (overrides: Partial<ProductWaitlistListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => record.id)
|
|
87
|
+
const matching = (keep: (entry: Entry) => boolean) => ids(ENTRIES.filter(keep).sort(newestFirst))
|
|
88
|
+
|
|
89
|
+
// The summary counts every entry, whatever the page is filtered to.
|
|
90
|
+
const filtered = await read({ status: 'cancelled' })
|
|
91
|
+
const purchased = ENTRIES.filter(entry => entry.status === 'purchased').length
|
|
92
|
+
expect(filtered.summary).toEqual({
|
|
93
|
+
total: ENTRIES.length,
|
|
94
|
+
waiting: ENTRIES.filter(entry => entry.status === 'waiting').length,
|
|
95
|
+
notified: ENTRIES.filter(entry => entry.status === 'notified').length,
|
|
96
|
+
purchased,
|
|
97
|
+
conversionRate: Math.round((purchased / ENTRIES.length) * 100),
|
|
98
|
+
})
|
|
99
|
+
expect(filtered.total).toBe(ENTRIES.filter(entry => entry.status === 'cancelled').length)
|
|
100
|
+
|
|
101
|
+
// Search: name with a literal %, email, phone, source, product name and id, ignoring case.
|
|
102
|
+
expect(await all({ search: '100%' })).toEqual(['9'])
|
|
103
|
+
expect(await all({ search: 'WAITER21@' })).toEqual(['21'])
|
|
104
|
+
expect(await all({ search: '0199' })).toEqual(['21'])
|
|
105
|
+
expect(await all({ search: 'IN-STORE' })).toEqual(['17'])
|
|
106
|
+
expect(await all({ search: 'ZEBRA' })).toEqual(matching(entry => entry.product_id === 600))
|
|
107
|
+
expect(await all({ search: 'zebra', status: 'waiting' })).toEqual(matching(entry => entry.product_id === 600 && entry.status === 'waiting'))
|
|
108
|
+
|
|
109
|
+
// Newest first, the id breaking the tie between 14 and 15, stable across pages.
|
|
110
|
+
const newest = [...ENTRIES].sort(newestFirst)
|
|
111
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
112
|
+
expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(ids(newest))
|
|
113
|
+
expect((await read({ page: 9 })).page).toBe(3)
|
|
114
|
+
|
|
115
|
+
// Sorts, ties newest first. Status and preference sort by name, not enum order.
|
|
116
|
+
const by = (key: (entry: Entry) => string | number, direction: 1 | -1 = 1) => (a: Entry, b: Entry) => {
|
|
117
|
+
const left = key(a)
|
|
118
|
+
const right = key(b)
|
|
119
|
+
const order = typeof left === 'number' ? (left - (right as number)) : left.localeCompare(right as string)
|
|
120
|
+
return order * direction || newestFirst(a, b)
|
|
121
|
+
}
|
|
122
|
+
expect(await all({ sort: 'name', direction: 'asc' })).toEqual(ids([...ENTRIES].sort(by(entry => entry.name.toLowerCase()))))
|
|
123
|
+
expect(await all({ sort: 'product', direction: 'asc' })).toEqual(ids([...ENTRIES].sort(by(entry => productName(entry.product_id).toLowerCase()))))
|
|
124
|
+
expect(await all({ sort: 'quantity', direction: 'desc' })).toEqual(ids([...ENTRIES].sort(by(entry => entry.quantity, -1))))
|
|
125
|
+
expect(await all({ sort: 'status', direction: 'asc' })).toEqual(ids([...ENTRIES].sort(by(entry => entry.status))))
|
|
126
|
+
expect(await all({ sort: 'preference', direction: 'asc' })).toEqual(ids([...ENTRIES].sort(by(entry => entry.notification_preference))))
|
|
127
|
+
|
|
128
|
+
// Products and customers past the 500th, read by the ids the page references.
|
|
129
|
+
const records = (await read({ perPage: 100 })).records
|
|
130
|
+
expect(records.find(record => record.productId === '600')).toMatchObject({ productName: 'zebra Tea' })
|
|
131
|
+
expect(records.find(record => record.customerId === '599')).toBeDefined()
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
describe('readProductWaitlistPage on SQLite', () => {
|
|
135
|
+
test('summary, filters, search, sorts, pages and references', async () => {
|
|
136
|
+
const database = new Database(':memory:')
|
|
137
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
138
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
139
|
+
})
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
143
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
144
|
+
|
|
145
|
+
test.skipIf(!connection)(`readProductWaitlistPage on ${dialect}: summary, filters, search, sorts, pages and references`, async () => {
|
|
146
|
+
const url = new URL(connection!)
|
|
147
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
148
|
+
throw new Error('Product waitlist list tests require a local disposable database server')
|
|
149
|
+
|
|
150
|
+
const name = `stacks_product_waitlist_${crypto.randomUUID().replaceAll('-', '')}`
|
|
151
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
152
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
153
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
154
|
+
const scoped = new URL(url.href)
|
|
155
|
+
scoped.pathname = `/${name}`
|
|
156
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
157
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
158
|
+
|
|
159
|
+
try {
|
|
160
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
161
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
await database.close()
|
|
165
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
166
|
+
finally { await admin.close() }
|
|
167
|
+
}
|
|
168
|
+
}, 60_000)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
describe('parseProductWaitlistListQuery', () => {
|
|
172
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
173
|
+
|
|
174
|
+
test('defaults to every entry, newest first, 25 a page', () => {
|
|
175
|
+
expect(parseProductWaitlistListQuery(reader({}))).toEqual({ search: '', status: '', sort: 'created', direction: 'desc', page: 1, perPage: 25 })
|
|
176
|
+
expect(parseProductWaitlistListQuery(reader({ sort: 'name' }))).toHaveProperty('direction', 'asc')
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
test('refuses values the page does not offer', () => {
|
|
180
|
+
expect(parseProductWaitlistListQuery(reader({ status: 'seated' }))).toHaveProperty('error')
|
|
181
|
+
expect(parseProductWaitlistListQuery(reader({ sort: 'notes' }))).toHaveProperty('error')
|
|
182
|
+
})
|
|
183
|
+
})
|
|
@@ -0,0 +1,170 @@
|
|
|
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 { commerceIdentifier, commerceRequiredString, commerceValue, referencedIds } from './commerce-record'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
|
|
8
|
+
import type { ProductWaitlistRecord, ProductWaitlistSummary } from './product-waitlist-records'
|
|
9
|
+
import { normalizeProductWaitlistRecord } from './product-waitlist-records'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One page of the product waitlist, searched, filtered, sorted and counted by
|
|
13
|
+
* the database, with the summary of every entry (stacksjs/stacks#3218).
|
|
14
|
+
*
|
|
15
|
+
* The page used to read the newest 500 entries and do all of that in the
|
|
16
|
+
* browser, and the summary counted those 500. Its record check read the
|
|
17
|
+
* first 500 products and customers by name, so one entry for any later
|
|
18
|
+
* product or customer failed the whole page.
|
|
19
|
+
*/
|
|
20
|
+
export const PRODUCT_WAITLIST_SORTS = ['created', 'id', 'name', 'product', 'quantity', 'status', 'preference'] as const
|
|
21
|
+
export type ProductWaitlistSort = typeof PRODUCT_WAITLIST_SORTS[number]
|
|
22
|
+
|
|
23
|
+
export const PRODUCT_WAITLIST_STATUSES = ['waiting', 'notified', 'purchased', 'cancelled'] as const
|
|
24
|
+
|
|
25
|
+
export interface ProductWaitlistListQuery {
|
|
26
|
+
search: string
|
|
27
|
+
/** '' for any. */
|
|
28
|
+
status: '' | typeof PRODUCT_WAITLIST_STATUSES[number]
|
|
29
|
+
sort: ProductWaitlistSort
|
|
30
|
+
direction: 'asc' | 'desc'
|
|
31
|
+
page: number
|
|
32
|
+
perPage: number
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function parseProductWaitlistListQuery(read: QueryReader): ProductWaitlistListQuery | { error: string } {
|
|
36
|
+
const pageText = queryText(read, 'page')
|
|
37
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
38
|
+
if (!Number.isInteger(page) || page < 1)
|
|
39
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
40
|
+
|
|
41
|
+
const sizeText = queryText(read, 'per_page')
|
|
42
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
43
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
44
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
45
|
+
|
|
46
|
+
const sort = queryText(read, 'sort') || 'created'
|
|
47
|
+
if (!(PRODUCT_WAITLIST_SORTS as readonly string[]).includes(sort))
|
|
48
|
+
return { error: `sort must be one of ${PRODUCT_WAITLIST_SORTS.join(', ')}.` }
|
|
49
|
+
|
|
50
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
51
|
+
const direction = directionText === '' ? (sort === 'created' || sort === 'quantity' ? 'desc' : 'asc') : directionText
|
|
52
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
53
|
+
return { error: 'direction must be asc or desc.' }
|
|
54
|
+
|
|
55
|
+
const search = queryText(read, 'q')
|
|
56
|
+
if (search.length > 200)
|
|
57
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
58
|
+
|
|
59
|
+
const status = queryText(read, 'status')
|
|
60
|
+
if (status && !(PRODUCT_WAITLIST_STATUSES as readonly string[]).includes(status))
|
|
61
|
+
return { error: `status must be one of ${PRODUCT_WAITLIST_STATUSES.join(', ')}.` }
|
|
62
|
+
|
|
63
|
+
return { search, status: status as ProductWaitlistListQuery['status'], sort: sort as ProductWaitlistSort, direction, page, perPage }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const FROM = ' FROM waitlist_products w LEFT JOIN products p ON p.id = w.product_id'
|
|
67
|
+
|
|
68
|
+
function sortExpression(sort: ProductWaitlistSort, dialect: QueryBuilderDialect): string {
|
|
69
|
+
switch (sort) {
|
|
70
|
+
case 'id': return 'w.id'
|
|
71
|
+
case 'name': return 'LOWER(w.name)'
|
|
72
|
+
case 'product': return `LOWER(COALESCE(p.name, ''))`
|
|
73
|
+
case 'quantity': return 'w.quantity'
|
|
74
|
+
// As text: PostgreSQL keeps both as enums, which sort by declaration order.
|
|
75
|
+
case 'status': return asText('w.status', dialect)
|
|
76
|
+
case 'preference': return asText('w.notification_preference', dialect)
|
|
77
|
+
default: return 'w.created_at'
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function productWaitlistFilter(query: Pick<ProductWaitlistListQuery, 'search' | 'status'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
82
|
+
const { bind, values } = binder(dialect)
|
|
83
|
+
const clauses: string[] = []
|
|
84
|
+
if (query.status)
|
|
85
|
+
clauses.push(`${asText('w.status', dialect)} = ${bind(query.status)}`)
|
|
86
|
+
if (query.search) {
|
|
87
|
+
const pattern = containsPattern(query.search)
|
|
88
|
+
const columns = [
|
|
89
|
+
'w.name',
|
|
90
|
+
'w.email',
|
|
91
|
+
`COALESCE(w.phone, '')`,
|
|
92
|
+
'w.source',
|
|
93
|
+
`COALESCE(p.name, '')`,
|
|
94
|
+
`COALESCE(${asText('w.product_id', dialect)}, '')`,
|
|
95
|
+
]
|
|
96
|
+
clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
97
|
+
}
|
|
98
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function orderBy(query: Pick<ProductWaitlistListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
102
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
103
|
+
// Ties read newest first; the id breaks every remaining tie, so pages never
|
|
104
|
+
// repeat or skip an entry.
|
|
105
|
+
if (query.sort === 'created' || query.sort === 'id')
|
|
106
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, w.id ${direction}`
|
|
107
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, w.created_at DESC, w.id DESC`
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Entries turned into records, against exactly the products and customers they reference. */
|
|
111
|
+
async function recordsFor(entries: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ProductWaitlistRecord[]> {
|
|
112
|
+
if (entries.length === 0)
|
|
113
|
+
return []
|
|
114
|
+
const productIds = referencedIds(entries, 'product_id')
|
|
115
|
+
const customerIds = referencedIds(entries, 'customer_id')
|
|
116
|
+
const [products, customers] = await Promise.all([
|
|
117
|
+
productIds.length > 0 ? run.unsafe(`SELECT id, name FROM products WHERE id IN (${idPlaceholders(productIds, dialect)})`, productIds).execute() : [],
|
|
118
|
+
customerIds.length > 0 ? run.unsafe(`SELECT id FROM customers WHERE id IN (${idPlaceholders(customerIds, dialect)})`, customerIds).execute() : [],
|
|
119
|
+
])
|
|
120
|
+
const names = new Map(sqlRows(products).map((row) => {
|
|
121
|
+
const id = commerceIdentifier(commerceValue(row, 'id'), 'Product')
|
|
122
|
+
return [id, commerceRequiredString(commerceValue(row, 'name'), `Product ${id}`, 'name')]
|
|
123
|
+
}))
|
|
124
|
+
const known = new Set(sqlRows(customers).map(row => commerceIdentifier(commerceValue(row, 'id'), 'Customer')))
|
|
125
|
+
return entries.map(entry => normalizeProductWaitlistRecord(entry, names, known))
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The summary cards, over every entry as before. */
|
|
129
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ProductWaitlistSummary> {
|
|
130
|
+
const status = asText('status', dialect)
|
|
131
|
+
const count = (name: string) => `SUM(CASE WHEN ${status} = '${name}' THEN 1 ELSE 0 END)`
|
|
132
|
+
const row = sqlRows(await run.unsafe(
|
|
133
|
+
`SELECT COUNT(*) AS total_count, ${count('waiting')} AS waiting_count, ${count('notified')} AS notified_count, ${count('purchased')} AS purchased_count FROM waitlist_products`,
|
|
134
|
+
).execute())[0] ?? {}
|
|
135
|
+
const total = countOf(row.total_count)
|
|
136
|
+
const purchased = countOf(row.purchased_count)
|
|
137
|
+
return {
|
|
138
|
+
total,
|
|
139
|
+
waiting: countOf(row.waiting_count),
|
|
140
|
+
notified: countOf(row.notified_count),
|
|
141
|
+
purchased,
|
|
142
|
+
conversionRate: total > 0 ? Math.round((purchased / total) * 100) : 0,
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface ProductWaitlistPage {
|
|
147
|
+
records: ProductWaitlistRecord[]
|
|
148
|
+
total: number
|
|
149
|
+
page: number
|
|
150
|
+
summary: ProductWaitlistSummary
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function readProductWaitlistPage(
|
|
154
|
+
query: ProductWaitlistListQuery,
|
|
155
|
+
run: CommerceSqlRunner = db,
|
|
156
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
157
|
+
): Promise<ProductWaitlistPage> {
|
|
158
|
+
const { where, values } = productWaitlistFilter(query, dialect)
|
|
159
|
+
const [counted, summary] = await Promise.all([
|
|
160
|
+
run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
|
|
161
|
+
summarize(run, dialect),
|
|
162
|
+
])
|
|
163
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
164
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
165
|
+
const entries = await run.unsafe(
|
|
166
|
+
`SELECT w.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
167
|
+
values,
|
|
168
|
+
).execute()
|
|
169
|
+
return { records: await recordsFor(sqlRows(entries), run, dialect), total, page, summary }
|
|
170
|
+
}
|
|
@@ -224,3 +224,24 @@ export function commerceOptionalDate(input: unknown, source: string, field: stri
|
|
|
224
224
|
return ''
|
|
225
225
|
return commerceDate(input, source, field)
|
|
226
226
|
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The ids a set of records points at through one field, as integers, once
|
|
230
|
+
* each, so a page reads exactly the related rows it references.
|
|
231
|
+
*
|
|
232
|
+
* The commerce normalizers refuse a record whose order, customer, coupon,
|
|
233
|
+
* category or manufacturer is missing from what they were given, and those
|
|
234
|
+
* used to come from a fixed first 500. Past that, one record pointing further
|
|
235
|
+
* failed the whole page: Orders past 500 customers, Payments past a store's
|
|
236
|
+
* 500th order, Products past 500 categories (stacksjs/stacks#3218).
|
|
237
|
+
*/
|
|
238
|
+
export function referencedIds(records: unknown[], ...keys: string[]): number[] {
|
|
239
|
+
const ids = new Set<number>()
|
|
240
|
+
for (const record of records) {
|
|
241
|
+
const value = commerceValue(record, ...keys)
|
|
242
|
+
const id = Number(value)
|
|
243
|
+
if (value !== undefined && value !== null && value !== '' && Number.isSafeInteger(id) && id > 0)
|
|
244
|
+
ids.add(id)
|
|
245
|
+
}
|
|
246
|
+
return [...ids].sort((left, right) => left - right)
|
|
247
|
+
}
|