@stacksjs/defaults 0.75.490 → 0.75.493
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 +8 -0
- package/ai/skills/stacks-models/SKILL.md +11 -0
- package/ai/skills/stacks-native/CATALOG.md +2 -2
- package/app/Actions/Dashboard/Commerce/ProductUnitIndexAction.ts +23 -19
- package/app/Actions/Dashboard/Commerce/ProductVariantIndexAction.ts +25 -18
- 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/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/functions/dashboard-list.test.ts +14 -0
- package/functions/dashboard-list.ts +21 -3
- package/ide/vscode/package.json +1 -1
- package/package.json +2 -2
- 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/functions/dashboard/sidebar.ts +50 -16
- package/views/dashboard/layouts/default.stx +2 -10
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: stacks-actions
|
|
3
|
-
description: Use when working with Stacks server actions - creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the
|
|
3
|
+
description: Use when working with Stacks server actions - creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 716 default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/app/Actions/.
|
|
4
4
|
license: MIT
|
|
5
5
|
compatibility: Bun >= 1.3.0, TypeScript
|
|
6
6
|
allowed-tools: Read Edit Write Bash Grep Glob
|
|
@@ -740,3 +740,11 @@ by itself: configure `createDatabaseErrorReporter()` from
|
|
|
740
740
|
`Error`, and migrate it. Reporting is bounded, buffered, identity-deduplicated
|
|
741
741
|
by `captureError`, and flushed by `flushErrorReporters`/the logger. The database
|
|
742
742
|
reporter stores allowlisted operational context and excludes bodies and headers.
|
|
743
|
+
|
|
744
|
+
### Pinned model rows
|
|
745
|
+
|
|
746
|
+
Declare `dashboard: { highlight: true }` on a model to pin its Data row, or use
|
|
747
|
+
numeric `highlight` values to order pinned rows. Other enabled Data models live
|
|
748
|
+
under the native Sidebar's collapsed More models disclosure. Labels, icons and
|
|
749
|
+
role gates apply to nested rows too. `enabled: false` omits navigation;
|
|
750
|
+
`access: false` excludes generic catalogs and reads as well.
|
|
@@ -519,3 +519,14 @@ commands, not a project's resolved models.
|
|
|
519
519
|
of a validator is not a promise that an arbitrary request body is safe.
|
|
520
520
|
- Dashboard-highlighted models (`dashboard: { highlight: true }`) appear
|
|
521
521
|
prominently in the admin UI.
|
|
522
|
+
|
|
523
|
+
### Bounded retention jobs
|
|
524
|
+
|
|
525
|
+
`pruneRetainedData({ models: { Request }, now, batchSize: 500, after })` scans at
|
|
526
|
+
most 500 candidates per model. Persist `result.next` in the next queue job and
|
|
527
|
+
reuse the same `now` until no cursors remain, even when a page changed zero rows.
|
|
528
|
+
This handles mixed SQL/ISO timestamps without skipping candidates. Each bounded
|
|
529
|
+
page commits its deletion/anonymization and retention audit together. A dry run
|
|
530
|
+
returns cursors without changing records. Omitting `batchSize` retains the CLI's
|
|
531
|
+
whole-run behavior. Declare the policy on `traits.gdpr.retention`, publish the
|
|
532
|
+
native `GdprRequest` audit model, and run cleanup through durable queue workers.
|
|
@@ -21,7 +21,7 @@ Browser runtime bindings are documented separately in `stacks-auto-imports`.
|
|
|
21
21
|
| `@stacksjs/auth` | [`stacks-auth`](../stacks-auth/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/auth/src/index.ts) | 131 |
|
|
22
22
|
| `@stacksjs/browser` | [`stacks-browser`](../stacks-browser/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/browser/src/index.ts) | 9 |
|
|
23
23
|
| `@stacksjs/browser-extension` | [`stacks-browser-extension`](../stacks-browser-extension/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/browser-extension/src/index.ts) | 9 |
|
|
24
|
-
| `@stacksjs/buddy` | [`stacks-buddy`](../stacks-buddy/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/src/index.ts) |
|
|
24
|
+
| `@stacksjs/buddy` | [`stacks-buddy`](../stacks-buddy/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/src/index.ts) | 183 |
|
|
25
25
|
| `@stacksjs/build` | [`stacks-build`](../stacks-build/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/build/src/index.ts) | 6 |
|
|
26
26
|
| `@stacksjs/cache` | [`stacks-cache`](../stacks-cache/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/cache/src/index.ts) | 24 |
|
|
27
27
|
| `@stacksjs/calendar-api` | [`stacks-calendar`](../stacks-calendar/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/calendar-api/src/index.ts) | 5 |
|
|
@@ -219,7 +219,7 @@ Read the entrypoint and package export map for re-exported or type-only surfaces
|
|
|
219
219
|
|
|
220
220
|
Local source modules: [src/commands/index.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/src/commands/index.ts).
|
|
221
221
|
|
|
222
|
-
Evidence directory: [
|
|
222
|
+
Evidence directory: [183 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
|
|
223
223
|
|
|
224
224
|
### @stacksjs/build
|
|
225
225
|
|
|
@@ -1,32 +1,36 @@
|
|
|
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
|
-
normalizeProductUnitRecord,
|
|
6
|
-
productUnitOptions,
|
|
7
|
-
summarizeProductUnits,
|
|
8
|
-
} from './product-unit-records'
|
|
5
|
+
import { parseProductUnitListQuery, readProductUnitPage } from './commerce-product-unit-list'
|
|
9
6
|
|
|
7
|
+
/**
|
|
8
|
+
* `GET /api/dashboard/commerce/units` - one page of product units, searched,
|
|
9
|
+
* filtered, sorted and counted by the database, with the summary of every
|
|
10
|
+
* unit and every unit type (commerce-product-unit-list.ts,
|
|
11
|
+
* stacksjs/stacks#3218). The dialog searches products through
|
|
12
|
+
* GET /commerce/product-choices; this used to send the first 500 of each.
|
|
13
|
+
*/
|
|
10
14
|
export default new Action({
|
|
11
15
|
name: 'ProductUnitIndexAction',
|
|
12
|
-
description: 'Returns persisted product units
|
|
16
|
+
description: 'Returns one page of persisted product units with their products.',
|
|
13
17
|
method: 'GET',
|
|
14
18
|
apiResponse: true,
|
|
15
19
|
|
|
16
|
-
async handle() {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
Product.orderBy('name').limit(500).get(),
|
|
21
|
-
])
|
|
22
|
-
const options = productUnitOptions(products)
|
|
23
|
-
const productNames = new Map(options.map(product => [product.id, product.name]))
|
|
24
|
-
const records = units.map(unit => normalizeProductUnitRecord(unit, productNames))
|
|
20
|
+
async handle(request: RequestInstance) {
|
|
21
|
+
const query = parseProductUnitListQuery(key => request.get<unknown>(key, ''))
|
|
22
|
+
if ('error' in query)
|
|
23
|
+
return response.json({ message: query.error }, 422)
|
|
25
24
|
|
|
25
|
+
try {
|
|
26
|
+
const units = await readProductUnitPage(query)
|
|
26
27
|
return {
|
|
27
|
-
records,
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
records: units.records,
|
|
29
|
+
total: units.total,
|
|
30
|
+
page: units.page,
|
|
31
|
+
perPage: query.perPage,
|
|
32
|
+
summary: units.summary,
|
|
33
|
+
types: units.types,
|
|
30
34
|
}
|
|
31
35
|
}
|
|
32
36
|
catch (error) {
|
|
@@ -1,31 +1,38 @@
|
|
|
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
|
-
normalizeProductVariantRecord,
|
|
6
|
-
productVariantOptions,
|
|
7
|
-
summarizeProductVariants,
|
|
8
|
-
} from './product-variant-records'
|
|
5
|
+
import { parseProductVariantListQuery, readProductVariantPage } from './commerce-product-variant-list'
|
|
9
6
|
|
|
7
|
+
/**
|
|
8
|
+
* `GET /api/dashboard/commerce/variants` - one page of product variants,
|
|
9
|
+
* searched, filtered, sorted and counted by the database, with the summary of
|
|
10
|
+
* every variant, every variant type and every product that has a variant
|
|
11
|
+
* (commerce-product-variant-list.ts, stacksjs/stacks#3218). The dialog
|
|
12
|
+
* searches products through GET /commerce/product-choices; this used to send
|
|
13
|
+
* the first 500 of each.
|
|
14
|
+
*/
|
|
10
15
|
export default new Action({
|
|
11
16
|
name: 'ProductVariantIndexAction',
|
|
12
|
-
description: 'Returns
|
|
17
|
+
description: 'Returns one page of persisted product variants with their products.',
|
|
13
18
|
method: 'GET',
|
|
14
19
|
apiResponse: true,
|
|
15
20
|
|
|
16
|
-
async handle() {
|
|
21
|
+
async handle(request: RequestInstance) {
|
|
22
|
+
const query = parseProductVariantListQuery(key => request.get<unknown>(key, ''))
|
|
23
|
+
if ('error' in query)
|
|
24
|
+
return response.json({ message: query.error }, 422)
|
|
25
|
+
|
|
17
26
|
try {
|
|
18
|
-
const
|
|
19
|
-
ProductVariant.orderByDesc('id').limit(500).get(),
|
|
20
|
-
Product.orderBy('name').limit(500).get(),
|
|
21
|
-
])
|
|
22
|
-
const productOptions = productVariantOptions(products)
|
|
23
|
-
const productNames = new Map(productOptions.map(product => [product.id, product.name]))
|
|
24
|
-
const records = variants.map(variant => normalizeProductVariantRecord(variant, productNames))
|
|
27
|
+
const variants = await readProductVariantPage(query)
|
|
25
28
|
return {
|
|
26
|
-
records,
|
|
27
|
-
|
|
28
|
-
|
|
29
|
+
records: variants.records,
|
|
30
|
+
total: variants.total,
|
|
31
|
+
page: variants.page,
|
|
32
|
+
perPage: query.perPage,
|
|
33
|
+
summary: variants.summary,
|
|
34
|
+
types: variants.types,
|
|
35
|
+
products: variants.products,
|
|
29
36
|
}
|
|
30
37
|
}
|
|
31
38
|
catch (error) {
|
|
@@ -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
|
+
}
|