@stacksjs/defaults 0.75.489 → 0.75.492
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +20 -2
- package/ai/skills/stacks-native/CATALOG.md +9 -9
- package/ai/skills/stacks-search-engine/SKILL.md +14 -0
- package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
- package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
- package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
- package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
- package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
- package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
- package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
- package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
- package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
- package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
- package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
- package/app/Actions/Dashboard/Commerce/ProductUnitIndexAction.ts +23 -19
- package/app/Actions/Dashboard/Commerce/ProductVariantIndexAction.ts +25 -18
- package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
- package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
- package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
- package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
- package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
- package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
- package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.test.ts +146 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.ts +178 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.test.ts +165 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.ts +209 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
- package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
- package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
- package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
- package/app/Actions/Dashboard/Commerce/product-unit-records.test.ts +0 -13
- package/app/Actions/Dashboard/Commerce/product-unit-records.ts +0 -17
- package/app/Actions/Dashboard/Commerce/product-variant-records.test.ts +0 -13
- package/app/Actions/Dashboard/Commerce/product-variant-records.ts +0 -17
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
- package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
- package/app/Actions/Dashboard/Content/content-list.ts +10 -0
- package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
- package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
- package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
- package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
- package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
- package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
- package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
- package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
- package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
- package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
- package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
- package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
- package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
- package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
- package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +5 -3
- package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
- package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
- package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
- package/app/Actions/Dashboard/named-search.test.ts +36 -0
- package/app/Actions/Dashboard/named-search.ts +80 -0
- package/app/Models/Request.ts +4 -2
- package/functions/commerce/shippings/dashboard-resource.ts +12 -1
- package/functions/commerce/shippings/delivery-routes.ts +1 -0
- package/functions/commerce/shippings/license-keys.ts +1 -0
- package/functions/dashboard-list.test.ts +146 -1
- package/functions/dashboard-list.ts +216 -1
- package/functions/queue.ts +2 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +2 -2
- package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
- package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
- package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
- package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
- package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
- package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
- package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
- package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
- package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
- package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
- package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
- package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
- package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +63 -8
- package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +48 -60
- package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +29 -3
- package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +57 -3
- package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +59 -61
- package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +28 -2
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
- package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
- package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
- package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
- package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
- package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
- package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
- package/resources/components/Dashboard/Queue/QueueDashboard.stx +7 -1
- package/routes/dashboard-api.ts +11 -0
- package/views/dashboard/stores/kanban.ts +38 -6
|
@@ -0,0 +1,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,146 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { ProductUnitListQuery } from './commerce-product-unit-list'
|
|
5
|
+
import { parseProductUnitListQuery, readProductUnitPage } from './commerce-product-unit-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Units list against each dialect's real engine (stacksjs/stacks#3218),
|
|
10
|
+
* with is_default as each dialect stores a boolean and products past the 500
|
|
11
|
+
* the page used to read.
|
|
12
|
+
*/
|
|
13
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
14
|
+
|
|
15
|
+
const PRODUCTS = 520
|
|
16
|
+
const TYPES = ['weight', 'Volume', 'count'] as const
|
|
17
|
+
const productName = (id: number) => id === 515 ? 'zebra Tea' : `Product ${String(id).padStart(3, '0')}`
|
|
18
|
+
|
|
19
|
+
/** 30 units; weight has two defaults and Volume three, so two types conflict; count has one, which does not. */
|
|
20
|
+
const UNITS = Array.from({ length: 30 }, (_, index) => {
|
|
21
|
+
const id = index + 1
|
|
22
|
+
return {
|
|
23
|
+
id,
|
|
24
|
+
name: id === 9 ? 'Half_100%' : id === 10 ? 'Half 1000' : `${id % 2 === 0 ? 'unit' : 'Unit'} ${String(id).padStart(2, '0')}`,
|
|
25
|
+
abbreviation: `u${id}`,
|
|
26
|
+
type: TYPES[id % 3]!,
|
|
27
|
+
description: id === 17 ? 'Sold LOOSE by the scoop' : null,
|
|
28
|
+
isDefault: [3, 6, 4, 7, 10, 5].includes(id),
|
|
29
|
+
productId: id % 4 === 0 ? 515 : id % 4 === 1 ? 2 : null,
|
|
30
|
+
}
|
|
31
|
+
})
|
|
32
|
+
type Unit = typeof UNITS[number]
|
|
33
|
+
|
|
34
|
+
const ids = (units: Unit[]) => units.map(unit => String(unit.id))
|
|
35
|
+
const byName = (a: Unit, b: Unit) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()) || a.id - b.id
|
|
36
|
+
|
|
37
|
+
function query(overrides: Partial<ProductUnitListQuery> = {}): ProductUnitListQuery {
|
|
38
|
+
return { search: '', type: '', isDefault: '', sort: 'name', direction: 'asc', page: 1, perPage: 10, ...overrides }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
42
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
43
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
44
|
+
const bool = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
|
|
45
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
46
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
47
|
+
const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
|
|
48
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text})`)
|
|
49
|
+
await run(`CREATE TABLE product_units (id ${pk}, name ${text}, abbreviation ${text}, type ${text}, description ${text} NULL, is_default ${bool}, product_id INTEGER NULL, created_at ${time})`)
|
|
50
|
+
const all = Array.from({ length: PRODUCTS }, (_, i) => i + 1)
|
|
51
|
+
await run(`INSERT INTO products (id, name) VALUES ${rows(PRODUCTS, 2)}`, all.flatMap(id => [id, productName(id)]))
|
|
52
|
+
await run(
|
|
53
|
+
`INSERT INTO product_units (id, name, abbreviation, type, description, is_default, product_id, created_at) VALUES ${rows(UNITS.length, 8)}`,
|
|
54
|
+
UNITS.flatMap(unit => [unit.id, unit.name, unit.abbreviation, unit.type, unit.description, dialect === 'postgres' ? unit.isDefault : (unit.isDefault ? 1 : 0), unit.productId, `2026-10-${String(1 + unit.id % 28).padStart(2, '0')} 09:00:00`]),
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
59
|
+
const read = (overrides: Partial<ProductUnitListQuery> = {}) => readProductUnitPage(query(overrides), runner, dialect)
|
|
60
|
+
const all = async (overrides: Partial<ProductUnitListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => record.id)
|
|
61
|
+
const matching = (keep: (unit: Unit) => boolean) => ids(UNITS.filter(keep).sort(byName))
|
|
62
|
+
|
|
63
|
+
// The summary and the types describe every unit, whatever the page is filtered to.
|
|
64
|
+
const filtered = await read({ type: 'count' })
|
|
65
|
+
expect(filtered.summary).toEqual({
|
|
66
|
+
total: UNITS.length,
|
|
67
|
+
defaults: UNITS.filter(unit => unit.isDefault).length,
|
|
68
|
+
types: TYPES.length,
|
|
69
|
+
linkedProducts: new Set(UNITS.map(unit => unit.productId).filter(Boolean)).size,
|
|
70
|
+
defaultConflicts: 2,
|
|
71
|
+
})
|
|
72
|
+
expect(filtered.types).toEqual(['Volume', 'count', 'weight'])
|
|
73
|
+
expect(filtered.total).toBe(UNITS.filter(unit => unit.type === 'count').length)
|
|
74
|
+
|
|
75
|
+
// Filters and search: names with a literal %, descriptions and product names, ignoring case.
|
|
76
|
+
expect(await all({ isDefault: 'default' })).toEqual(matching(unit => unit.isDefault))
|
|
77
|
+
expect(await all({ isDefault: 'not-default', type: 'weight' })).toEqual(matching(unit => !unit.isDefault && unit.type === 'weight'))
|
|
78
|
+
expect(await all({ search: '100%' })).toEqual(['9'])
|
|
79
|
+
expect(await all({ search: 'loose' })).toEqual(['17'])
|
|
80
|
+
expect(await all({ search: 'ZEBRA' })).toEqual(matching(unit => unit.productId === 515))
|
|
81
|
+
|
|
82
|
+
// By name ignoring case, stable across pages.
|
|
83
|
+
const named = [...UNITS].sort(byName)
|
|
84
|
+
const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
|
|
85
|
+
expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(ids(named))
|
|
86
|
+
expect((await read({ page: 9 })).page).toBe(3)
|
|
87
|
+
|
|
88
|
+
// Type and product sorts read ties by name; newest is the id.
|
|
89
|
+
expect(await all({ sort: 'type' })).toEqual(ids([...UNITS].sort((a, b) => a.type.toLowerCase().localeCompare(b.type.toLowerCase()) || byName(a, b))))
|
|
90
|
+
const product = (unit: Unit) => unit.productId ? productName(unit.productId).toLowerCase() : ''
|
|
91
|
+
expect(await all({ sort: 'product' })).toEqual(ids([...UNITS].sort((a, b) => product(a).localeCompare(product(b)) || byName(a, b))))
|
|
92
|
+
expect(await all({ sort: 'newest', direction: 'desc' })).toEqual(ids([...UNITS].sort((a, b) => b.id - a.id)))
|
|
93
|
+
|
|
94
|
+
// A product past the 500th, read by the ids the page references.
|
|
95
|
+
expect((await read({ search: 'zebra' })).records[0]).toMatchObject({ productId: '515', productName: 'zebra Tea' })
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
describe('readProductUnitPage on SQLite', () => {
|
|
99
|
+
test('summary, types, filters, search, sorts, pages and products', async () => {
|
|
100
|
+
const database = new Database(':memory:')
|
|
101
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
102
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
103
|
+
})
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
107
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
108
|
+
|
|
109
|
+
test.skipIf(!connection)(`readProductUnitPage on ${dialect}: summary, types, filters, search, sorts, pages and products`, async () => {
|
|
110
|
+
const url = new URL(connection!)
|
|
111
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
112
|
+
throw new Error('Product unit list tests require a local disposable database server')
|
|
113
|
+
|
|
114
|
+
const name = `stacks_product_units_${crypto.randomUUID().replaceAll('-', '')}`
|
|
115
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
116
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
117
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
118
|
+
const scoped = new URL(url.href)
|
|
119
|
+
scoped.pathname = `/${name}`
|
|
120
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
121
|
+
|
|
122
|
+
try {
|
|
123
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
124
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
await database.close()
|
|
128
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
129
|
+
finally { await admin.close() }
|
|
130
|
+
}
|
|
131
|
+
}, 60_000)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
describe('parseProductUnitListQuery', () => {
|
|
135
|
+
const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
|
|
136
|
+
|
|
137
|
+
test('defaults to every unit by name, 25 a page', () => {
|
|
138
|
+
expect(parseProductUnitListQuery(reader({}))).toEqual({ search: '', type: '', isDefault: '', sort: 'name', direction: 'asc', page: 1, perPage: 25 })
|
|
139
|
+
expect(parseProductUnitListQuery(reader({ sort: 'newest' }))).toHaveProperty('direction', 'desc')
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
test('refuses values the page does not offer', () => {
|
|
143
|
+
expect(parseProductUnitListQuery(reader({ default: 'yes' }))).toHaveProperty('error')
|
|
144
|
+
expect(parseProductUnitListQuery(reader({ sort: 'abbreviation' }))).toHaveProperty('error')
|
|
145
|
+
})
|
|
146
|
+
})
|
|
@@ -0,0 +1,178 @@
|
|
|
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, isTrue, sqlRows } from './commerce-sql'
|
|
8
|
+
import type { ProductUnitRecord, ProductUnitSummary } from './product-unit-records'
|
|
9
|
+
import { normalizeProductUnitRecord } from './product-unit-records'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One page of product units, searched, filtered, sorted and counted by the
|
|
13
|
+
* database, with the summary of every unit and every unit type
|
|
14
|
+
* (stacksjs/stacks#3218).
|
|
15
|
+
*
|
|
16
|
+
* The Units page used to read the newest 500 units and do all of that in the
|
|
17
|
+
* browser, so an older unit could not be found, its cards counted those 500,
|
|
18
|
+
* and the type filter and the dialog's type suggestions only knew the types
|
|
19
|
+
* those 500 used. It also read the first 500 products by name, for the
|
|
20
|
+
* dialog's product select and to name each unit's product, so a unit for any
|
|
21
|
+
* later product failed the whole page.
|
|
22
|
+
*/
|
|
23
|
+
export const PRODUCT_UNIT_SORTS = ['name', 'type', 'product', 'default', 'newest', 'created'] as const
|
|
24
|
+
export type ProductUnitSort = typeof PRODUCT_UNIT_SORTS[number]
|
|
25
|
+
|
|
26
|
+
export interface ProductUnitListQuery {
|
|
27
|
+
search: string
|
|
28
|
+
/** A unit type, or '' for any. */
|
|
29
|
+
type: string
|
|
30
|
+
/** '' for any. */
|
|
31
|
+
isDefault: '' | 'default' | 'not-default'
|
|
32
|
+
sort: ProductUnitSort
|
|
33
|
+
direction: 'asc' | 'desc'
|
|
34
|
+
page: number
|
|
35
|
+
perPage: number
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function parseProductUnitListQuery(read: QueryReader): ProductUnitListQuery | { error: string } {
|
|
39
|
+
const pageText = queryText(read, 'page')
|
|
40
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
41
|
+
if (!Number.isInteger(page) || page < 1)
|
|
42
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
43
|
+
|
|
44
|
+
const sizeText = queryText(read, 'per_page')
|
|
45
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
46
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
47
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
48
|
+
|
|
49
|
+
const sort = queryText(read, 'sort') || 'name'
|
|
50
|
+
if (!(PRODUCT_UNIT_SORTS as readonly string[]).includes(sort))
|
|
51
|
+
return { error: `sort must be one of ${PRODUCT_UNIT_SORTS.join(', ')}.` }
|
|
52
|
+
|
|
53
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
54
|
+
const direction = directionText === '' ? (sort === 'newest' || sort === 'created' || sort === 'default' ? 'desc' : 'asc') : directionText
|
|
55
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
56
|
+
return { error: 'direction must be asc or desc.' }
|
|
57
|
+
|
|
58
|
+
const search = queryText(read, 'q')
|
|
59
|
+
if (search.length > 200)
|
|
60
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
61
|
+
|
|
62
|
+
const type = queryText(read, 'type')
|
|
63
|
+
if (type.length > 255)
|
|
64
|
+
return { error: 'type must be 255 characters or fewer.' }
|
|
65
|
+
|
|
66
|
+
const isDefault = queryText(read, 'default')
|
|
67
|
+
if (isDefault && isDefault !== 'default' && isDefault !== 'not-default')
|
|
68
|
+
return { error: 'default must be default or not-default.' }
|
|
69
|
+
|
|
70
|
+
return { search, type, isDefault: isDefault as ProductUnitListQuery['isDefault'], sort: sort as ProductUnitSort, direction, page, perPage }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const FROM = ' FROM product_units u LEFT JOIN products p ON p.id = u.product_id'
|
|
74
|
+
|
|
75
|
+
function sortExpression(sort: ProductUnitSort, dialect: QueryBuilderDialect): string {
|
|
76
|
+
switch (sort) {
|
|
77
|
+
case 'type': return 'LOWER(u.type)'
|
|
78
|
+
case 'product': return `LOWER(COALESCE(p.name, ''))`
|
|
79
|
+
case 'default': return `CASE WHEN ${isTrue('u.is_default', dialect)} THEN 1 ELSE 0 END`
|
|
80
|
+
case 'newest': return 'u.id'
|
|
81
|
+
case 'created': return 'u.created_at'
|
|
82
|
+
default: return 'LOWER(u.name)'
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function productUnitFilter(query: Pick<ProductUnitListQuery, 'search' | 'type' | 'isDefault'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
87
|
+
const { bind, values } = binder(dialect)
|
|
88
|
+
const clauses: string[] = []
|
|
89
|
+
if (query.type)
|
|
90
|
+
clauses.push(`u.type = ${bind(query.type)}`)
|
|
91
|
+
if (query.isDefault === 'default')
|
|
92
|
+
clauses.push(isTrue('u.is_default', dialect))
|
|
93
|
+
if (query.isDefault === 'not-default')
|
|
94
|
+
clauses.push(`NOT (${isTrue('u.is_default', dialect)})`)
|
|
95
|
+
if (query.search) {
|
|
96
|
+
const pattern = containsPattern(query.search)
|
|
97
|
+
const columns = ['u.name', 'u.abbreviation', 'u.type', `COALESCE(u.description, '')`, `COALESCE(p.name, '')`]
|
|
98
|
+
clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
99
|
+
}
|
|
100
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function orderBy(query: Pick<ProductUnitListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
104
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
105
|
+
// Ties read by name, as the page sorted them; the id breaks every
|
|
106
|
+
// remaining tie, so pages never repeat or skip a unit.
|
|
107
|
+
if (query.sort === 'newest')
|
|
108
|
+
return ` ORDER BY u.id ${direction}`
|
|
109
|
+
const byName = query.sort === 'name' ? '' : ', LOWER(u.name) ASC'
|
|
110
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}${byName}, u.id ${direction}`
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Units turned into records, against exactly the products they reference. */
|
|
114
|
+
async function recordsFor(units: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ProductUnitRecord[]> {
|
|
115
|
+
if (units.length === 0)
|
|
116
|
+
return []
|
|
117
|
+
const productIds = referencedIds(units, 'product_id')
|
|
118
|
+
const products = productIds.length > 0
|
|
119
|
+
? await run.unsafe(`SELECT id, name FROM products WHERE id IN (${idPlaceholders(productIds, dialect)})`, productIds).execute()
|
|
120
|
+
: []
|
|
121
|
+
const names = new Map(sqlRows(products).map((row) => {
|
|
122
|
+
const id = commerceIdentifier(commerceValue(row, 'id'), 'Product')
|
|
123
|
+
return [id, commerceRequiredString(commerceValue(row, 'name'), `Product ${id}`, 'name')]
|
|
124
|
+
}))
|
|
125
|
+
return units.map(unit => normalizeProductUnitRecord(unit, names))
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The summary cards, over every unit as before. */
|
|
129
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ProductUnitSummary> {
|
|
130
|
+
const isDefault = isTrue('is_default', dialect)
|
|
131
|
+
const [totals, conflicts] = await Promise.all([
|
|
132
|
+
run.unsafe(`SELECT COUNT(*) AS total_count, SUM(CASE WHEN ${isDefault} THEN 1 ELSE 0 END) AS default_count, COUNT(DISTINCT CASE WHEN type <> '' THEN type END) AS type_count, COUNT(DISTINCT product_id) AS product_count FROM product_units`).execute(),
|
|
133
|
+
// A type with more than one default unit is a conflict to resolve.
|
|
134
|
+
run.unsafe(`SELECT type FROM product_units WHERE ${isDefault} AND type IS NOT NULL AND type <> '' GROUP BY type HAVING COUNT(*) > 1`).execute(),
|
|
135
|
+
])
|
|
136
|
+
const row = sqlRows(totals)[0] ?? {}
|
|
137
|
+
return {
|
|
138
|
+
total: countOf(row.total_count),
|
|
139
|
+
defaults: countOf(row.default_count),
|
|
140
|
+
types: countOf(row.type_count),
|
|
141
|
+
linkedProducts: countOf(row.product_count),
|
|
142
|
+
defaultConflicts: sqlRows(conflicts).length,
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Every unit type any unit has, for the filter and the dialog's suggestions. */
|
|
147
|
+
async function unitTypes(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<string[]> {
|
|
148
|
+
const rows = sqlRows(await run.unsafe(`SELECT DISTINCT ${asText('type', dialect)} AS value FROM product_units WHERE type IS NOT NULL AND type <> ''`).execute())
|
|
149
|
+
return [...new Set(rows.map(row => String(row.value ?? '').trim()).filter(Boolean))].sort()
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface ProductUnitPage {
|
|
153
|
+
records: ProductUnitRecord[]
|
|
154
|
+
total: number
|
|
155
|
+
page: number
|
|
156
|
+
summary: ProductUnitSummary
|
|
157
|
+
types: string[]
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export async function readProductUnitPage(
|
|
161
|
+
query: ProductUnitListQuery,
|
|
162
|
+
run: CommerceSqlRunner = db,
|
|
163
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
164
|
+
): Promise<ProductUnitPage> {
|
|
165
|
+
const { where, values } = productUnitFilter(query, dialect)
|
|
166
|
+
const [counted, summary, types] = await Promise.all([
|
|
167
|
+
run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
|
|
168
|
+
summarize(run, dialect),
|
|
169
|
+
unitTypes(run, dialect),
|
|
170
|
+
])
|
|
171
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
172
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
173
|
+
const units = await run.unsafe(
|
|
174
|
+
`SELECT u.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
175
|
+
values,
|
|
176
|
+
).execute()
|
|
177
|
+
return { records: await recordsFor(sqlRows(units), run, dialect), total, page, summary, types }
|
|
178
|
+
}
|