@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
|
@@ -1,28 +1,47 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
1
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
2
|
-
import {
|
|
3
|
+
import { response } from '@stacksjs/router'
|
|
3
4
|
import { dashboardOperationalError } from '../dashboard-response'
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
normalizeLicenseKeyProduct,
|
|
8
|
-
} from './license-key-records'
|
|
5
|
+
import { parseNamedSearchQuery } from '../named-search'
|
|
6
|
+
import type { LicenseKeyChoiceKind } from './commerce-license-key-list'
|
|
7
|
+
import { LICENSE_KEY_CHOICE_KINDS, searchLicenseKeyChoices } from './commerce-license-key-list'
|
|
9
8
|
|
|
9
|
+
/**
|
|
10
|
+
* `GET /api/dashboard/commerce/license-key-options` - the customers, products
|
|
11
|
+
* and orders the licence key dialog offers (stacksjs/stacks#3218). It used to
|
|
12
|
+
* send the first 500 of each.
|
|
13
|
+
*
|
|
14
|
+
* With `kind` (customers, products or orders) and `q`, it searches that one
|
|
15
|
+
* and answers `{ choices, total }`, which is what the dialog asks for as each
|
|
16
|
+
* search box is typed in. Without `kind` it answers the first `limit` of each
|
|
17
|
+
* (25 unless asked) as `{ customers, products, orders, totals }`, the shape
|
|
18
|
+
* useLicenseKeys().fetchLicenseKeyOptions reads, with how many there are.
|
|
19
|
+
*/
|
|
10
20
|
export default new Action({
|
|
11
21
|
name: 'License Key Options',
|
|
12
|
-
description: '
|
|
22
|
+
description: 'Searches the customers, products and orders the licence key dialog offers.',
|
|
13
23
|
method: 'GET',
|
|
14
24
|
apiResponse: true,
|
|
15
|
-
|
|
25
|
+
|
|
26
|
+
async handle(request: RequestInstance) {
|
|
27
|
+
const query = parseNamedSearchQuery(key => request.get<unknown>(key, ''))
|
|
28
|
+
if ('error' in query)
|
|
29
|
+
return response.json({ message: query.error }, 422)
|
|
30
|
+
const kind = String(request.get<unknown>('kind', '') ?? '').trim()
|
|
31
|
+
if (kind && !(LICENSE_KEY_CHOICE_KINDS as readonly string[]).includes(kind))
|
|
32
|
+
return response.json({ message: `kind must be one of ${LICENSE_KEY_CHOICE_KINDS.join(', ')}.` }, 422)
|
|
33
|
+
|
|
16
34
|
try {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
35
|
+
if (kind)
|
|
36
|
+
return { ...await searchLicenseKeyChoices(kind as LicenseKeyChoiceKind, query), limit: query.limit }
|
|
37
|
+
const [customers, products, orders] = await Promise.all(
|
|
38
|
+
LICENSE_KEY_CHOICE_KINDS.map(each => searchLicenseKeyChoices(each, query)),
|
|
39
|
+
)
|
|
22
40
|
return {
|
|
23
|
-
customers: customers
|
|
24
|
-
products: products
|
|
25
|
-
orders: orders
|
|
41
|
+
customers: customers!.choices,
|
|
42
|
+
products: products!.choices,
|
|
43
|
+
orders: orders!.choices,
|
|
44
|
+
totals: { customers: customers!.total, products: products!.total, orders: orders!.total },
|
|
26
45
|
}
|
|
27
46
|
}
|
|
28
47
|
catch (error) {
|
|
@@ -1,35 +1,35 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
1
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
2
|
-
import {
|
|
3
|
+
import { response } from '@stacksjs/router'
|
|
3
4
|
import { dashboardOperationalError } from '../dashboard-response'
|
|
4
|
-
import {
|
|
5
|
+
import { parseProductWaitlistListQuery, readProductWaitlistPage } from './commerce-product-waitlist-list'
|
|
5
6
|
|
|
7
|
+
/**
|
|
8
|
+
* `GET /api/dashboard/commerce/waitlist-products` - one page of the product
|
|
9
|
+
* waitlist, searched, filtered, sorted and counted by the database, with the
|
|
10
|
+
* summary of every entry (commerce-product-waitlist-list.ts,
|
|
11
|
+
* stacksjs/stacks#3218). The entry dialog searches its products and customers
|
|
12
|
+
* itself (commerce-choices.ts); this used to send the first 500 of each.
|
|
13
|
+
*/
|
|
6
14
|
export default new Action({
|
|
7
15
|
name: 'ProductWaitlistIndexAction',
|
|
8
|
-
description: 'Returns native product waitlist records for the dashboard.',
|
|
16
|
+
description: 'Returns one page of native product waitlist records for the dashboard.',
|
|
9
17
|
method: 'GET',
|
|
10
18
|
apiResponse: true,
|
|
11
19
|
|
|
12
|
-
async handle() {
|
|
20
|
+
async handle(request: RequestInstance) {
|
|
21
|
+
const query = parseProductWaitlistListQuery(key => request.get<unknown>(key, ''))
|
|
22
|
+
if ('error' in query)
|
|
23
|
+
return response.json({ message: query.error }, 422)
|
|
24
|
+
|
|
13
25
|
try {
|
|
14
|
-
const
|
|
15
|
-
WaitlistProduct.orderByDesc('id').limit(500).get(),
|
|
16
|
-
Product.orderBy('name').limit(500).get(),
|
|
17
|
-
Customer.orderBy('name').limit(500).get(),
|
|
18
|
-
])
|
|
19
|
-
const productOptions = products.map(normalizeProductWaitlistOption)
|
|
20
|
-
const customerOptions = customers.map(normalizeProductWaitlistCustomerOption)
|
|
21
|
-
const productIds = new Set(productOptions.map(product => product.id))
|
|
22
|
-
const customerIds = new Set(customerOptions.map(customer => customer.id))
|
|
23
|
-
const records = rows.map(row =>
|
|
24
|
-
normalizeProductWaitlistRecord(row, productIds, customerIds),
|
|
25
|
-
)
|
|
26
|
+
const entries = await readProductWaitlistPage(query)
|
|
26
27
|
return {
|
|
27
|
-
records,
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
},
|
|
28
|
+
records: entries.records,
|
|
29
|
+
total: entries.total,
|
|
30
|
+
page: entries.page,
|
|
31
|
+
perPage: query.perPage,
|
|
32
|
+
summary: entries.summary,
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
35
|
catch (error) {
|
|
@@ -1,30 +1,35 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
1
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
2
|
-
import {
|
|
3
|
+
import { response } from '@stacksjs/router'
|
|
3
4
|
import { dashboardOperationalError } from '../dashboard-response'
|
|
4
|
-
import {
|
|
5
|
+
import { parseRestaurantWaitlistListQuery, readRestaurantWaitlistPage } from './commerce-restaurant-waitlist-list'
|
|
5
6
|
|
|
7
|
+
/**
|
|
8
|
+
* `GET /api/dashboard/commerce/waitlist-restaurants` - one page of the
|
|
9
|
+
* restaurant waitlist, searched, filtered, sorted and counted by the database,
|
|
10
|
+
* with the summary of every party (commerce-restaurant-waitlist-list.ts,
|
|
11
|
+
* stacksjs/stacks#3218). The entry dialog searches its customers itself
|
|
12
|
+
* (commerce-choices.ts); this used to send the first 500.
|
|
13
|
+
*/
|
|
6
14
|
export default new Action({
|
|
7
15
|
name: 'RestaurantWaitlistIndexAction',
|
|
8
|
-
description: 'Return native restaurant waitlist records
|
|
16
|
+
description: 'Return one page of native restaurant waitlist records for the dashboard',
|
|
9
17
|
method: 'GET',
|
|
10
18
|
apiResponse: true,
|
|
11
19
|
|
|
12
|
-
async handle() {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
Customer.orderBy('name').limit(500).get(),
|
|
17
|
-
])
|
|
18
|
-
const customerOptions = customers.map(normalizeRestaurantWaitlistCustomerOption)
|
|
19
|
-
const customerIds = new Set(customerOptions.map(customer => customer.id))
|
|
20
|
-
const records = rows.map(row => normalizeRestaurantWaitlistRecord(row, customerIds))
|
|
20
|
+
async handle(request: RequestInstance) {
|
|
21
|
+
const query = parseRestaurantWaitlistListQuery(key => request.get<unknown>(key, ''))
|
|
22
|
+
if ('error' in query)
|
|
23
|
+
return response.json({ message: query.error }, 422)
|
|
21
24
|
|
|
25
|
+
try {
|
|
26
|
+
const parties = await readRestaurantWaitlistPage(query)
|
|
22
27
|
return {
|
|
23
|
-
records,
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
+
records: parties.records,
|
|
29
|
+
total: parties.total,
|
|
30
|
+
page: parties.page,
|
|
31
|
+
perPage: query.perPage,
|
|
32
|
+
summary: parties.summary,
|
|
28
33
|
}
|
|
29
34
|
}
|
|
30
35
|
catch (error) {
|
|
@@ -1,44 +1,35 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
1
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
2
|
-
import {
|
|
3
|
+
import { response } from '@stacksjs/router'
|
|
3
4
|
import { dashboardOperationalError } from '../dashboard-response'
|
|
4
|
-
import {
|
|
5
|
-
normalizeReviewCustomerContext,
|
|
6
|
-
normalizeReviewProductOption,
|
|
7
|
-
normalizeReviewRecord,
|
|
8
|
-
summarizeReviews,
|
|
9
|
-
} from './review-records'
|
|
5
|
+
import { parseReviewListQuery, readReviewPage } from './commerce-review-list'
|
|
10
6
|
|
|
7
|
+
/**
|
|
8
|
+
* `GET /api/dashboard/commerce/reviews` - one page of reviews, searched,
|
|
9
|
+
* filtered, sorted and counted by the database, with the summary of every
|
|
10
|
+
* review (commerce-review-list.ts, stacksjs/stacks#3218). It used to return
|
|
11
|
+
* the newest 500 for the browser to do all of that with.
|
|
12
|
+
*/
|
|
11
13
|
export default new Action({
|
|
12
14
|
name: 'ReviewIndexAction',
|
|
13
|
-
description: 'Returns persisted reviews with their product and customer context for dashboard moderation.',
|
|
15
|
+
description: 'Returns one page of persisted reviews with their product and customer context for dashboard moderation.',
|
|
14
16
|
method: 'GET',
|
|
15
17
|
apiResponse: true,
|
|
16
18
|
|
|
17
|
-
async handle() {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
Product.orderBy('name', 'asc').limit(500).get(),
|
|
22
|
-
Customer.orderBy('name', 'asc').limit(500).get(),
|
|
23
|
-
])
|
|
24
|
-
const productOptions = products
|
|
25
|
-
.map(normalizeReviewProductOption)
|
|
26
|
-
.sort((left, right) => left.label.localeCompare(right.label))
|
|
27
|
-
const productMap = new Map(productOptions.map(product => [
|
|
28
|
-
product.id,
|
|
29
|
-
{ name: product.label },
|
|
30
|
-
]))
|
|
31
|
-
const customerContexts = customers.map(normalizeReviewCustomerContext)
|
|
32
|
-
const customerMap = new Map(customerContexts.map(customer => [
|
|
33
|
-
customer.id,
|
|
34
|
-
customer.context,
|
|
35
|
-
]))
|
|
36
|
-
const records = reviews.map(review => normalizeReviewRecord(review, productMap, customerMap))
|
|
19
|
+
async handle(request: RequestInstance) {
|
|
20
|
+
const query = parseReviewListQuery(key => request.get<unknown>(key, ''))
|
|
21
|
+
if ('error' in query)
|
|
22
|
+
return response.json({ message: query.error }, 422)
|
|
37
23
|
|
|
24
|
+
try {
|
|
25
|
+
const reviews = await readReviewPage(query)
|
|
38
26
|
return {
|
|
39
|
-
records,
|
|
40
|
-
|
|
41
|
-
|
|
27
|
+
records: reviews.records,
|
|
28
|
+
total: reviews.total,
|
|
29
|
+
page: reviews.page,
|
|
30
|
+
perPage: query.perPage,
|
|
31
|
+
summary: reviews.summary,
|
|
32
|
+
products: reviews.products,
|
|
42
33
|
}
|
|
43
34
|
}
|
|
44
35
|
catch (error) {
|
|
@@ -15,7 +15,9 @@ export default new Action({
|
|
|
15
15
|
|
|
16
16
|
async handle() {
|
|
17
17
|
try {
|
|
18
|
-
|
|
18
|
+
// Read whole: store configuration, which the page searches in full. The
|
|
19
|
+
// first 500 left the rest unlisted and unsearchable (stacksjs/stacks#3218).
|
|
20
|
+
const methods = await ShippingMethod.orderBy('name', 'asc').get()
|
|
19
21
|
const methodIds = shippingMethodIds(methods)
|
|
20
22
|
const zones = methodIds.size
|
|
21
23
|
? await ShippingZone.whereIn('shipping_method_id', [...methodIds]).orderBy('name', 'asc').get()
|
|
@@ -15,7 +15,9 @@ export default new Action({
|
|
|
15
15
|
|
|
16
16
|
async handle() {
|
|
17
17
|
try {
|
|
18
|
-
|
|
18
|
+
// Read whole: store configuration, which the page searches in full. The
|
|
19
|
+
// first 500 left the rest unlisted and unsearchable (stacksjs/stacks#3218).
|
|
20
|
+
const rates = await ShippingRate.orderBy('weight_from', 'asc').get()
|
|
19
21
|
const methodIds = [...new Set(rates.map(rate => rate.get('shipping_method_id')).filter(Boolean))]
|
|
20
22
|
const zoneIds = [...new Set(rates.map(rate => rate.get('shipping_zone_id')).filter(Boolean))]
|
|
21
23
|
const [methods, zones] = await Promise.all([
|
|
@@ -14,7 +14,9 @@ export default new Action({
|
|
|
14
14
|
|
|
15
15
|
async handle() {
|
|
16
16
|
try {
|
|
17
|
-
|
|
17
|
+
// Read whole: store configuration, which the page searches in full. The
|
|
18
|
+
// first 500 left the rest unlisted and unsearchable (stacksjs/stacks#3218).
|
|
19
|
+
const zones = await ShippingZone.orderBy('name', 'asc').get()
|
|
18
20
|
const methodIds = [...new Set(zones.map(zone => zone.get('shipping_method_id')).filter(Boolean))]
|
|
19
21
|
const methods = methodIds.length
|
|
20
22
|
? await ShippingMethod.whereIn('id', methodIds).get()
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import { readCommerceCategories } from './commerce-category-list'
|
|
5
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The product categories against each dialect's real engine
|
|
9
|
+
* (stacksjs/stacks#3218), over 520 of them: the page used to read the first
|
|
10
|
+
* 500 by display order.
|
|
11
|
+
*/
|
|
12
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
13
|
+
|
|
14
|
+
const ROWS = 520
|
|
15
|
+
|
|
16
|
+
/** Category n shows in display order n, except 11, which ties with 10; 3's parent is the last one shown. */
|
|
17
|
+
const CATEGORIES = Array.from({ length: ROWS }, (_, index) => {
|
|
18
|
+
const id = index + 1
|
|
19
|
+
return {
|
|
20
|
+
id,
|
|
21
|
+
name: `Category ${String(id).padStart(3, '0')}`,
|
|
22
|
+
displayOrder: id === 11 ? 10 : id,
|
|
23
|
+
parentId: id === 3 ? 520 : id % 10 === 0 ? 1 : null,
|
|
24
|
+
active: id % 4 !== 0,
|
|
25
|
+
}
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
29
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
30
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
31
|
+
const bool = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
|
|
32
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
33
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
34
|
+
const columns = 7
|
|
35
|
+
await run(`CREATE TABLE categories (id ${pk}, name ${text}, description ${text} NULL, slug ${text}, image_url ${text} NULL, is_active ${bool}, parent_category_id INTEGER NULL, display_order INTEGER, created_at ${time})`)
|
|
36
|
+
await run(
|
|
37
|
+
`INSERT INTO categories (id, name, slug, is_active, parent_category_id, display_order, created_at) VALUES ${CATEGORIES.map((_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')}`,
|
|
38
|
+
CATEGORIES.flatMap(category => [
|
|
39
|
+
category.id, category.name, `category-${category.id}`, dialect === 'postgres' ? category.active : (category.active ? 1 : 0),
|
|
40
|
+
category.parentId, category.displayOrder, '2026-11-01 09:00:00',
|
|
41
|
+
]),
|
|
42
|
+
)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function exercise(runner: CommerceSqlRunner) {
|
|
46
|
+
const { records, summary } = await readCommerceCategories(runner)
|
|
47
|
+
|
|
48
|
+
// Every category, in display order, the id breaking the tie between 10 and 11.
|
|
49
|
+
expect(records.length).toBe(ROWS)
|
|
50
|
+
expect(records.map(record => record.id)).toEqual(
|
|
51
|
+
[...CATEGORIES].sort((a, b) => a.displayOrder - b.displayOrder || a.id - b.id).map(category => String(category.id)),
|
|
52
|
+
)
|
|
53
|
+
// A parent shown after the 500th is found.
|
|
54
|
+
expect(records.find(record => record.id === '3')?.parentCategoryId).toBe('520')
|
|
55
|
+
|
|
56
|
+
const roots = CATEGORIES.filter(category => !category.parentId).length
|
|
57
|
+
expect(summary).toMatchObject({
|
|
58
|
+
total: ROWS,
|
|
59
|
+
active: CATEGORIES.filter(category => category.active).length,
|
|
60
|
+
roots,
|
|
61
|
+
children: ROWS - roots,
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
describe('readCommerceCategories on SQLite', () => {
|
|
66
|
+
test('every category, in display order, with parents past the 500th', async () => {
|
|
67
|
+
const database = new Database(':memory:')
|
|
68
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
69
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) })
|
|
70
|
+
})
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
74
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
75
|
+
|
|
76
|
+
test.skipIf(!connection)(`readCommerceCategories on ${dialect}: every category, in display order, with parents past the 500th`, async () => {
|
|
77
|
+
const url = new URL(connection!)
|
|
78
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
79
|
+
throw new Error('Category list tests require a local disposable database server')
|
|
80
|
+
|
|
81
|
+
const name = `stacks_categories_${crypto.randomUUID().replaceAll('-', '')}`
|
|
82
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
83
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
84
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
85
|
+
const scoped = new URL(url.href)
|
|
86
|
+
scoped.pathname = `/${name}`
|
|
87
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
88
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
89
|
+
|
|
90
|
+
try {
|
|
91
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
92
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) })
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
await database.close()
|
|
96
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
97
|
+
finally { await admin.close() }
|
|
98
|
+
}
|
|
99
|
+
}, 60_000)
|
|
100
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
2
|
+
import { db } from '@stacksjs/database/runtime'
|
|
3
|
+
import type { CommerceCategoryRecord, CommerceCategorySummary } from './commerce-category-records'
|
|
4
|
+
import { normalizeCommerceCategoryRecord, summarizeCommerceCategories } from './commerce-category-records'
|
|
5
|
+
import { sqlRows } from './commerce-sql'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Every product category, in display order (stacksjs/stacks#3218).
|
|
9
|
+
*
|
|
10
|
+
* Categories are reference data the page needs whole: it draws them as a
|
|
11
|
+
* tree, offers them as parents in the dialog, and names each one's parent.
|
|
12
|
+
* It used to read the first 500 by display order, so a later category was
|
|
13
|
+
* missing from all of that, and one whose parent was past the 500th failed
|
|
14
|
+
* the whole page with "references missing Category".
|
|
15
|
+
*/
|
|
16
|
+
export async function readCommerceCategories(run: CommerceSqlRunner = db): Promise<{ records: CommerceCategoryRecord[], summary: CommerceCategorySummary }> {
|
|
17
|
+
// The id breaks display-order ties, so the order is the same on every load.
|
|
18
|
+
const rows = sqlRows(await run.unsafe('SELECT * FROM categories ORDER BY display_order ASC, id ASC').execute())
|
|
19
|
+
const records = rows.map(normalizeCommerceCategoryRecord)
|
|
20
|
+
const ids = new Set(records.map(record => record.id))
|
|
21
|
+
for (const record of records) {
|
|
22
|
+
if (record.parentCategoryId && !ids.has(record.parentCategoryId))
|
|
23
|
+
throw new TypeError(`Category ${record.id}.parent_category_id references missing Category ${record.parentCategoryId}.`)
|
|
24
|
+
}
|
|
25
|
+
return { records, summary: summarizeCommerceCategories(records) }
|
|
26
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import {
|
|
2
|
+
commerceEmail,
|
|
3
|
+
commerceIdentifier,
|
|
4
|
+
commerceNumber,
|
|
5
|
+
commerceOptionalString,
|
|
6
|
+
commerceRequiredString,
|
|
7
|
+
commerceValue,
|
|
8
|
+
} from './commerce-record'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The products and customers a commerce dialog offers, as the dialog shows
|
|
12
|
+
* them (stacksjs/stacks#3218). Kept apart from the search in
|
|
13
|
+
* commerce-choices.ts, which reads the database: the waitlist records modules
|
|
14
|
+
* re-export these, and dashboard components import values from those modules,
|
|
15
|
+
* so anything here ends up in a browser bundle.
|
|
16
|
+
*/
|
|
17
|
+
export interface ProductChoice {
|
|
18
|
+
id: string
|
|
19
|
+
label: string
|
|
20
|
+
detail: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface CustomerChoice extends ProductChoice {
|
|
24
|
+
email: string
|
|
25
|
+
phone: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function normalizeProductChoice(record: any): ProductChoice {
|
|
29
|
+
const id = commerceIdentifier(commerceValue(record, 'id', 'uuid'), 'Product')
|
|
30
|
+
const source = `Product ${id}`
|
|
31
|
+
const inventory = commerceNumber(
|
|
32
|
+
commerceValue(record, 'inventory_count', 'inventoryCount'),
|
|
33
|
+
source,
|
|
34
|
+
'inventory_count',
|
|
35
|
+
{ min: 0, integer: true },
|
|
36
|
+
)
|
|
37
|
+
return {
|
|
38
|
+
id,
|
|
39
|
+
label: commerceRequiredString(commerceValue(record, 'name'), source, 'name'),
|
|
40
|
+
detail: `${inventory} in inventory`,
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function normalizeCustomerChoice(record: any): CustomerChoice {
|
|
45
|
+
const id = commerceIdentifier(commerceValue(record, 'id', 'uuid'), 'Customer')
|
|
46
|
+
const source = `Customer ${id}`
|
|
47
|
+
const email = commerceEmail(commerceValue(record, 'email'), source)
|
|
48
|
+
const phone = commerceOptionalString(commerceValue(record, 'phone'), source, 'phone')
|
|
49
|
+
return {
|
|
50
|
+
id,
|
|
51
|
+
label: commerceRequiredString(commerceValue(record, 'name'), source, 'name'),
|
|
52
|
+
detail: email || phone,
|
|
53
|
+
email,
|
|
54
|
+
phone,
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import { searchCustomerChoices, searchProductChoices } from './commerce-choices'
|
|
5
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The commerce dialogs' product and customer searches against each dialect's
|
|
9
|
+
* real engine (stacksjs/stacks#3218), over 600 of each: the waitlist dialogs
|
|
10
|
+
* used to be handed the first 500.
|
|
11
|
+
*/
|
|
12
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
13
|
+
|
|
14
|
+
const ROWS = 600
|
|
15
|
+
const productName = (id: number) => id === 600 ? 'Zebra Tea' : id === 7 ? 'apple_50% off' : id === 8 ? 'apple 500 box' : `Product ${String(id).padStart(3, '0')}`
|
|
16
|
+
const customerName = (id: number) => id === 599 ? 'mia Late' : id === 3 ? 'Mia early' : `Customer ${String(id).padStart(3, '0')}`
|
|
17
|
+
|
|
18
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
19
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
20
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
21
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
22
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text}, inventory_count INTEGER)`)
|
|
23
|
+
await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text}, phone ${text} NULL)`)
|
|
24
|
+
const all = Array.from({ length: ROWS }, (_, i) => i + 1)
|
|
25
|
+
await run(`INSERT INTO products (id, name, inventory_count) VALUES ${all.map((_, i) => `(${p(3 * i + 1)}, ${p(3 * i + 2)}, ${p(3 * i + 3)})`).join(', ')}`, all.flatMap(id => [id, productName(id), id % 9]))
|
|
26
|
+
await run(`INSERT INTO customers (id, name, email, phone) VALUES ${all.map((_, i) => `(${p(4 * i + 1)}, ${p(4 * i + 2)}, ${p(4 * i + 3)}, ${p(4 * i + 4)})`).join(', ')}`, all.flatMap(id => [id, customerName(id), `buyer${id}@shop.test`, id === 444 ? '+1 555 0444' : null]))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
30
|
+
const products = (search: string, limit = 25) => searchProductChoices({ search, limit }, runner, dialect)
|
|
31
|
+
const customers = (search: string, limit = 25) => searchCustomerChoices({ search, limit }, runner, dialect)
|
|
32
|
+
|
|
33
|
+
// Unsearched: bounded, by name ignoring case, with how many there are.
|
|
34
|
+
const first = await products('')
|
|
35
|
+
expect(first.total).toBe(ROWS)
|
|
36
|
+
expect(first.choices.length).toBe(25)
|
|
37
|
+
expect(first.choices.slice(0, 2).map(choice => choice.label)).toEqual(['apple 500 box', 'apple_50% off'])
|
|
38
|
+
|
|
39
|
+
// The 600th of each can be found, and a literal % matches only itself.
|
|
40
|
+
expect(await products('zebra')).toEqual({ choices: [{ id: '600', label: 'Zebra Tea', detail: '6 in inventory' }], total: 1 })
|
|
41
|
+
expect((await products('50%')).choices.map(choice => choice.id)).toEqual(['7'])
|
|
42
|
+
expect((await products('600')).choices.map(choice => choice.id)).toEqual(['600'])
|
|
43
|
+
expect((await customers('MIA')).choices.map(choice => choice.label)).toEqual(['Mia early', 'mia Late'])
|
|
44
|
+
expect((await customers('buyer599@')).choices).toEqual([{ id: '599', label: 'mia Late', detail: 'buyer599@shop.test', email: 'buyer599@shop.test', phone: '' }])
|
|
45
|
+
expect((await customers('0444')).choices.map(choice => choice.id)).toEqual(['444'])
|
|
46
|
+
|
|
47
|
+
// The limit bounds the choices, not the count.
|
|
48
|
+
const bounded = await customers('customer', 5)
|
|
49
|
+
expect(bounded.choices.length).toBe(5)
|
|
50
|
+
expect(bounded.total).toBe(ROWS - 2)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
describe('commerce choices on SQLite', () => {
|
|
54
|
+
test('products and customers by name, email, phone and id', async () => {
|
|
55
|
+
const database = new Database(':memory:')
|
|
56
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
57
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
58
|
+
})
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
62
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
63
|
+
|
|
64
|
+
test.skipIf(!connection)(`commerce choices on ${dialect}: products and customers by name, email, phone and id`, async () => {
|
|
65
|
+
const url = new URL(connection!)
|
|
66
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
67
|
+
throw new Error('Commerce choice tests require a local disposable database server')
|
|
68
|
+
|
|
69
|
+
const name = `stacks_commerce_choices_${crypto.randomUUID().replaceAll('-', '')}`
|
|
70
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
71
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
72
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
73
|
+
const scoped = new URL(url.href)
|
|
74
|
+
scoped.pathname = `/${name}`
|
|
75
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
76
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
80
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
await database.close()
|
|
84
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
85
|
+
finally { await admin.close() }
|
|
86
|
+
}
|
|
87
|
+
}, 60_000)
|
|
88
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { db, getDatabaseDialect } from '@stacksjs/database/runtime'
|
|
3
|
+
import { containsPattern, countOf } from '../Content/content-list'
|
|
4
|
+
import type { NamedSearchQuery } from '../named-search'
|
|
5
|
+
import type { CustomerChoice, ProductChoice } from './commerce-choice-records'
|
|
6
|
+
import { normalizeCustomerChoice, normalizeProductChoice } from './commerce-choice-records'
|
|
7
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
8
|
+
import { asText, binder, sqlRows } from './commerce-sql'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The products and customers a commerce dialog offers, searched by the
|
|
12
|
+
* database (stacksjs/stacks#3218). The waitlist dialogs used to be handed the
|
|
13
|
+
* first 500 of each by name with every page, so an entry could not be made
|
|
14
|
+
* for a product or customer past the 500th.
|
|
15
|
+
*
|
|
16
|
+
* The query is the pickers' usual `q` and `limit` (`parseNamedSearchQuery`):
|
|
17
|
+
* case is ignored, `%` and `_` are characters to find, the answer is bounded,
|
|
18
|
+
* and `total` says how many matched. The choices themselves, and their
|
|
19
|
+
* normalizers, are in commerce-choice-records.ts.
|
|
20
|
+
*/
|
|
21
|
+
export type { CustomerChoice, ProductChoice } from './commerce-choice-records'
|
|
22
|
+
|
|
23
|
+
async function search<T>(
|
|
24
|
+
table: 'products' | 'customers',
|
|
25
|
+
columns: string,
|
|
26
|
+
searched: string[],
|
|
27
|
+
query: NamedSearchQuery,
|
|
28
|
+
normalize: (row: Record<string, unknown>) => T,
|
|
29
|
+
run: CommerceSqlRunner,
|
|
30
|
+
dialect: QueryBuilderDialect,
|
|
31
|
+
only: string[] = [],
|
|
32
|
+
): Promise<{ choices: T[], total: number }> {
|
|
33
|
+
const { bind, values } = binder(dialect)
|
|
34
|
+
const clauses = [...only]
|
|
35
|
+
if (query.search) {
|
|
36
|
+
const pattern = containsPattern(query.search)
|
|
37
|
+
clauses.push(`(${searched.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
38
|
+
}
|
|
39
|
+
const where = clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : ''
|
|
40
|
+
const [counted, found] = await Promise.all([
|
|
41
|
+
run.unsafe(`SELECT COUNT(*) AS total_count FROM ${table}${where}`, values).execute(),
|
|
42
|
+
// LOWER, so the order is the same on every dialect: each collates case its own way.
|
|
43
|
+
run.unsafe(`SELECT ${columns} FROM ${table}${where} ORDER BY LOWER(COALESCE(name, '')) ASC, id ASC LIMIT ${query.limit}`, values).execute(),
|
|
44
|
+
])
|
|
45
|
+
return { choices: sqlRows(found).map(normalize), total: countOf(sqlRows(counted)[0]?.total_count) }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Products by name or id. */
|
|
49
|
+
export function searchProductChoices(
|
|
50
|
+
query: NamedSearchQuery,
|
|
51
|
+
run: CommerceSqlRunner = db,
|
|
52
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
53
|
+
): Promise<{ choices: ProductChoice[], total: number }> {
|
|
54
|
+
return search('products', 'id, name, inventory_count', [`COALESCE(name, '')`, asText('id', dialect)], query, normalizeProductChoice, run, dialect)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Customers by name, email or phone. `activeOnly` keeps to customers whose
|
|
59
|
+
* status is Active, as the point of sale offers them.
|
|
60
|
+
*/
|
|
61
|
+
export function searchCustomerChoices(
|
|
62
|
+
query: NamedSearchQuery,
|
|
63
|
+
run: CommerceSqlRunner = db,
|
|
64
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
65
|
+
options: { activeOnly?: boolean } = {},
|
|
66
|
+
): Promise<{ choices: CustomerChoice[], total: number }> {
|
|
67
|
+
// A text comparison: PostgreSQL keeps the status as an enum.
|
|
68
|
+
const only = options.activeOnly ? [`${asText('status', dialect)} = 'Active'`] : []
|
|
69
|
+
return search('customers', 'id, name, email, phone', [`COALESCE(name, '')`, `COALESCE(email, '')`, `COALESCE(phone, '')`], query, normalizeCustomerChoice, run, dialect, only)
|
|
70
|
+
}
|