@stacksjs/defaults 0.75.490 → 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.
Files changed (22) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-native/CATALOG.md +2 -2
  3. package/app/Actions/Dashboard/Commerce/ProductUnitIndexAction.ts +23 -19
  4. package/app/Actions/Dashboard/Commerce/ProductVariantIndexAction.ts +25 -18
  5. package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.test.ts +146 -0
  6. package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.ts +178 -0
  7. package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.test.ts +165 -0
  8. package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.ts +209 -0
  9. package/app/Actions/Dashboard/Commerce/product-unit-records.test.ts +0 -13
  10. package/app/Actions/Dashboard/Commerce/product-unit-records.ts +0 -17
  11. package/app/Actions/Dashboard/Commerce/product-variant-records.test.ts +0 -13
  12. package/app/Actions/Dashboard/Commerce/product-variant-records.ts +0 -17
  13. package/functions/dashboard-list.test.ts +14 -0
  14. package/functions/dashboard-list.ts +21 -3
  15. package/ide/vscode/package.json +1 -1
  16. package/package.json +2 -2
  17. package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +63 -8
  18. package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +48 -60
  19. package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +29 -3
  20. package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +57 -3
  21. package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +59 -61
  22. package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +28 -2
@@ -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 714 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/.
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
@@ -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) | 182 |
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: [182 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.
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 { Product, ProductUnit } from '@stacksjs/orm'
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 and their product relationships for dashboard management.',
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
- try {
18
- const [units, products] = await Promise.all([
19
- ProductUnit.orderByDesc('id').limit(500).get(),
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
- products: options,
29
- summary: summarizeProductUnits(records),
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 { Product, ProductVariant } from '@stacksjs/orm'
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 persisted product variants and product relationships for dashboard management.',
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 [variants, products] = await Promise.all([
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
- products: productOptions,
28
- summary: summarizeProductVariants(records),
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
+ }
@@ -0,0 +1,165 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { SQL } from 'bun'
3
+ import { describe, expect, test } from 'bun:test'
4
+ import type { ProductVariantListQuery } from './commerce-product-variant-list'
5
+ import { parseProductVariantListQuery, readProductVariantPage } from './commerce-product-variant-list'
6
+ import type { CommerceSqlRunner } from './commerce-sql'
7
+
8
+ /**
9
+ * The Variants list against each dialect's real engine (stacksjs/stacks#3218),
10
+ * with status as a real enum, options as a JSON array or a delimited list,
11
+ * and products past the 500 the page used to read.
12
+ */
13
+ type Dialect = 'sqlite' | 'postgres' | 'mysql'
14
+
15
+ const PRODUCTS = 520
16
+ const STATUSES = ['active', 'inactive', 'draft'] as const
17
+ const TYPES = ['size', 'Color', 'material'] as const
18
+ const productName = (id: number) => id === 515 ? 'zebra Tea' : id === 2 ? 'Apron' : `Product ${String(id).padStart(3, '0')}`
19
+
20
+ /** How variant n stores its options: a JSON array, a comma, bar or newline list, or nothing. */
21
+ function optionsOf(id: number): { stored: string | null, count: number } {
22
+ const values = Array.from({ length: id % 5 }, (_, i) => `opt${i + 1}`)
23
+ if (values.length === 0)
24
+ return { stored: id % 2 === 0 ? null : '', count: 0 }
25
+ const stored = [JSON.stringify(values), values.join(', '), values.join('|'), values.join('\n')][id % 4]!
26
+ return { stored, count: values.length }
27
+ }
28
+
29
+ /** 30 variants, a third each status; a quarter belong to product 515 and a quarter to product 2. */
30
+ const VARIANTS = Array.from({ length: 30 }, (_, index) => {
31
+ const id = index + 1
32
+ return {
33
+ id,
34
+ variant: id === 9 ? 'Tall_100%' : id === 10 ? 'Tall 1000' : `${id % 2 === 0 ? 'variant' : 'Variant'} ${String(id).padStart(2, '0')}`,
35
+ type: TYPES[id % 3]!,
36
+ description: id === 17 ? 'Woven from RAFFIA' : null,
37
+ status: STATUSES[id % 3]!,
38
+ productId: id % 4 === 0 ? 515 : id % 4 === 1 ? 2 : null,
39
+ ...optionsOf(id),
40
+ }
41
+ })
42
+ type Variant = typeof VARIANTS[number]
43
+
44
+ const ids = (variants: Variant[]) => variants.map(variant => String(variant.id))
45
+ const byName = (a: Variant, b: Variant) => a.variant.toLowerCase().localeCompare(b.variant.toLowerCase()) || a.id - b.id
46
+
47
+ function query(overrides: Partial<ProductVariantListQuery> = {}): ProductVariantListQuery {
48
+ return { search: '', status: '', type: '', product: '', sort: 'variant', direction: 'asc', page: 1, perPage: 10, ...overrides }
49
+ }
50
+
51
+ async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
52
+ const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
53
+ const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
54
+ const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
55
+ const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
56
+ const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
57
+ let status = text
58
+ if (dialect === 'postgres') {
59
+ await run(`CREATE TYPE variant_status AS ENUM ('active', 'inactive', 'draft')`)
60
+ status = 'variant_status'
61
+ }
62
+ if (dialect === 'mysql')
63
+ status = `ENUM('active', 'inactive', 'draft')`
64
+ await run(`CREATE TABLE products (id ${pk}, name ${text})`)
65
+ await run(`CREATE TABLE product_variants (id ${pk}, variant ${text}, type ${text}, description ${text} NULL, options ${text} NULL, status ${status}, product_id INTEGER NULL, created_at ${time})`)
66
+ const all = Array.from({ length: PRODUCTS }, (_, i) => i + 1)
67
+ await run(`INSERT INTO products (id, name) VALUES ${rows(PRODUCTS, 2)}`, all.flatMap(id => [id, productName(id)]))
68
+ await run(
69
+ `INSERT INTO product_variants (id, variant, type, description, options, status, product_id, created_at) VALUES ${rows(VARIANTS.length, 8)}`,
70
+ VARIANTS.flatMap(variant => [variant.id, variant.variant, variant.type, variant.description, variant.stored, variant.status, variant.productId, `2026-10-${String(1 + variant.id % 28).padStart(2, '0')} 09:00:00`]),
71
+ )
72
+ }
73
+
74
+ async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
75
+ const read = (overrides: Partial<ProductVariantListQuery> = {}) => readProductVariantPage(query(overrides), runner, dialect)
76
+ const all = async (overrides: Partial<ProductVariantListQuery> = {}) => (await read({ perPage: 100, ...overrides })).records.map(record => record.id)
77
+ const matching = (keep: (variant: Variant) => boolean) => ids(VARIANTS.filter(keep).sort(byName))
78
+
79
+ // The summary and choices describe every variant, whatever the page is filtered to.
80
+ const filtered = await read({ status: 'inactive' })
81
+ expect(filtered.summary).toEqual({
82
+ total: VARIANTS.length,
83
+ active: VARIANTS.filter(variant => variant.status === 'active').length,
84
+ draft: VARIANTS.filter(variant => variant.status === 'draft').length,
85
+ linkedProducts: 2,
86
+ })
87
+ expect(filtered.types).toEqual(['Color', 'material', 'size'])
88
+ expect(filtered.products).toEqual([{ id: '2', name: 'Apron' }, { id: '515', name: 'zebra Tea' }])
89
+ expect(filtered.total).toBe(VARIANTS.filter(variant => variant.status === 'inactive').length)
90
+
91
+ // Filters and search: a literal %, the description, the product and the options text.
92
+ expect(await all({ product: '515' })).toEqual(matching(variant => variant.productId === 515))
93
+ expect(await all({ type: 'Color', status: 'draft' })).toEqual(matching(variant => variant.type === 'Color' && variant.status === 'draft'))
94
+ expect(await all({ search: '100%' })).toEqual(['9'])
95
+ expect(await all({ search: 'raffia' })).toEqual(['17'])
96
+ expect(await all({ search: 'ZEBRA' })).toEqual(matching(variant => variant.productId === 515))
97
+ expect(await all({ search: 'opt4' })).toEqual(matching(variant => variant.count >= 4))
98
+
99
+ // By name ignoring case, stable across pages.
100
+ const pages = [await read({ page: 1 }), await read({ page: 2 }), await read({ page: 3 })]
101
+ expect(pages.flatMap(result => result.records.map(record => record.id))).toEqual(ids([...VARIANTS].sort(byName)))
102
+
103
+ // Most options first, whatever the list is stored as; ties by name.
104
+ expect(await all({ sort: 'options', direction: 'desc' })).toEqual(ids([...VARIANTS].sort((a, b) => b.count - a.count || byName(a, b))))
105
+ const product = (variant: Variant) => variant.productId ? productName(variant.productId).toLowerCase() : ''
106
+ expect(await all({ sort: 'product' })).toEqual(ids([...VARIANTS].sort((a, b) => product(a).localeCompare(product(b)) || byName(a, b))))
107
+ expect(await all({ sort: 'status' })).toEqual(ids([...VARIANTS].sort((a, b) => a.status.localeCompare(b.status) || byName(a, b))))
108
+
109
+ // The records parse every stored form; a product past the 500th is named.
110
+ const records = (await read({ perPage: 100 })).records
111
+ for (const variant of VARIANTS)
112
+ expect(records.find(record => record.id === String(variant.id))?.options.length).toBe(variant.count)
113
+ expect(records.find(record => record.productId === '515')?.productName).toBe('zebra Tea')
114
+ }
115
+
116
+ describe('readProductVariantPage on SQLite', () => {
117
+ test('summary, choices, filters, search, sorts, pages and products', async () => {
118
+ const database = new Database(':memory:')
119
+ await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
120
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
121
+ })
122
+ })
123
+
124
+ for (const dialect of ['postgres', 'mysql'] as const) {
125
+ const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
126
+
127
+ test.skipIf(!connection)(`readProductVariantPage on ${dialect}: summary, choices, filters, search, sorts, pages and products`, async () => {
128
+ const url = new URL(connection!)
129
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
130
+ throw new Error('Product variant list tests require a local disposable database server')
131
+
132
+ const name = `stacks_product_variants_${crypto.randomUUID().replaceAll('-', '')}`
133
+ const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
134
+ const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
135
+ await admin.unsafe(`CREATE DATABASE ${quoted}`)
136
+ const scoped = new URL(url.href)
137
+ scoped.pathname = `/${name}`
138
+ const database = new SQL({ url: scoped.href, database: name })
139
+
140
+ try {
141
+ await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
142
+ await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
143
+ }
144
+ finally {
145
+ await database.close()
146
+ try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
147
+ finally { await admin.close() }
148
+ }
149
+ }, 60_000)
150
+ }
151
+
152
+ describe('parseProductVariantListQuery', () => {
153
+ const reader = (values: Record<string, unknown>) => (key: string) => values[key] ?? ''
154
+
155
+ test('defaults to every variant by name, 25 a page', () => {
156
+ expect(parseProductVariantListQuery(reader({}))).toEqual({ search: '', status: '', type: '', product: '', sort: 'variant', direction: 'asc', page: 1, perPage: 25 })
157
+ expect(parseProductVariantListQuery(reader({ sort: 'options' }))).toHaveProperty('direction', 'desc')
158
+ })
159
+
160
+ test('refuses values the page does not offer', () => {
161
+ expect(parseProductVariantListQuery(reader({ status: 'archived' }))).toHaveProperty('error')
162
+ expect(parseProductVariantListQuery(reader({ product: 'tea' }))).toHaveProperty('error')
163
+ expect(parseProductVariantListQuery(reader({ sort: 'sku' }))).toHaveProperty('error')
164
+ })
165
+ })