@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.
Files changed (26) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +8 -0
  3. package/ai/skills/stacks-models/SKILL.md +11 -0
  4. package/ai/skills/stacks-native/CATALOG.md +2 -2
  5. package/app/Actions/Dashboard/Commerce/ProductUnitIndexAction.ts +23 -19
  6. package/app/Actions/Dashboard/Commerce/ProductVariantIndexAction.ts +25 -18
  7. package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.test.ts +146 -0
  8. package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.ts +178 -0
  9. package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.test.ts +165 -0
  10. package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.ts +209 -0
  11. package/app/Actions/Dashboard/Commerce/product-unit-records.test.ts +0 -13
  12. package/app/Actions/Dashboard/Commerce/product-unit-records.ts +0 -17
  13. package/app/Actions/Dashboard/Commerce/product-variant-records.test.ts +0 -13
  14. package/app/Actions/Dashboard/Commerce/product-variant-records.ts +0 -17
  15. package/functions/dashboard-list.test.ts +14 -0
  16. package/functions/dashboard-list.ts +21 -3
  17. package/ide/vscode/package.json +1 -1
  18. package/package.json +2 -2
  19. package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +63 -8
  20. package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +48 -60
  21. package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +29 -3
  22. package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +57 -3
  23. package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +59 -61
  24. package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +28 -2
  25. package/resources/functions/dashboard/sidebar.ts +50 -16
  26. package/views/dashboard/layouts/default.stx +2 -10
@@ -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
+ })
@@ -0,0 +1,209 @@
1
+ import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
2
+ import { db, getDatabaseDialect } from '@stacksjs/database/runtime'
3
+ import type { QueryReader } from '../Content/content-list'
4
+ import { containsPattern, countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
5
+ import { commerceIdentifier, commerceRequiredString, commerceValue, referencedIds } from './commerce-record'
6
+ import type { CommerceSqlRunner } from './commerce-sql'
7
+ import { asText, binder, idPlaceholders, sqlRows } from './commerce-sql'
8
+ import type { ProductVariantRecord, ProductVariantSummary } from './product-variant-records'
9
+ import { normalizeProductVariantRecord } from './product-variant-records'
10
+
11
+ /**
12
+ * One page of product variants, searched, filtered, sorted and counted by the
13
+ * database, with the summary of every variant, every variant type, and every
14
+ * product that has a variant (stacksjs/stacks#3218).
15
+ *
16
+ * The Variants page used to read the newest 500 variants and do all of that
17
+ * in the browser, so an older variant could not be found, its cards counted
18
+ * those 500, and the type filter only knew those 500's types. It also read
19
+ * the first 500 products by name, for the product filter, the dialog's
20
+ * product select and to name each variant's product, so a variant of any
21
+ * later product failed the whole page.
22
+ */
23
+ export const PRODUCT_VARIANT_SORTS = ['variant', 'product', 'options', 'status', 'newest', 'created'] as const
24
+ export type ProductVariantSort = typeof PRODUCT_VARIANT_SORTS[number]
25
+
26
+ export const PRODUCT_VARIANT_STATUSES = ['active', 'inactive', 'draft'] as const
27
+
28
+ export interface ProductVariantListQuery {
29
+ search: string
30
+ /** '' for any. */
31
+ status: '' | typeof PRODUCT_VARIANT_STATUSES[number]
32
+ /** A variant type, or '' for any. */
33
+ type: string
34
+ /** A product id, or '' for any. */
35
+ product: string
36
+ sort: ProductVariantSort
37
+ direction: 'asc' | 'desc'
38
+ page: number
39
+ perPage: number
40
+ }
41
+
42
+ export function parseProductVariantListQuery(read: QueryReader): ProductVariantListQuery | { error: string } {
43
+ const pageText = queryText(read, 'page')
44
+ const page = pageText === '' ? 1 : Number(pageText)
45
+ if (!Number.isInteger(page) || page < 1)
46
+ return { error: 'page must be a whole number of 1 or more.' }
47
+
48
+ const sizeText = queryText(read, 'per_page')
49
+ const perPage = sizeText === '' ? 25 : Number(sizeText)
50
+ if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
51
+ return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
52
+
53
+ const sort = queryText(read, 'sort') || 'variant'
54
+ if (!(PRODUCT_VARIANT_SORTS as readonly string[]).includes(sort))
55
+ return { error: `sort must be one of ${PRODUCT_VARIANT_SORTS.join(', ')}.` }
56
+
57
+ const directionText = queryText(read, 'direction').toLowerCase()
58
+ const direction = directionText === '' ? (['options', 'newest', 'created'].includes(sort) ? 'desc' : 'asc') : directionText
59
+ if (direction !== 'asc' && direction !== 'desc')
60
+ return { error: 'direction must be asc or desc.' }
61
+
62
+ const search = queryText(read, 'q')
63
+ if (search.length > 200)
64
+ return { error: 'q must be 200 characters or fewer.' }
65
+
66
+ const status = queryText(read, 'status')
67
+ if (status && !(PRODUCT_VARIANT_STATUSES as readonly string[]).includes(status))
68
+ return { error: `status must be one of ${PRODUCT_VARIANT_STATUSES.join(', ')}.` }
69
+
70
+ const type = queryText(read, 'type')
71
+ if (type.length > 100)
72
+ return { error: 'type must be 100 characters or fewer.' }
73
+
74
+ const product = queryText(read, 'product')
75
+ if (product && !/^\d+$/.test(product))
76
+ return { error: 'product must be a product id.' }
77
+
78
+ return { search, status: status as ProductVariantListQuery['status'], type, product, sort: sort as ProductVariantSort, direction, page, perPage }
79
+ }
80
+
81
+ const FROM = ' FROM product_variants v LEFT JOIN products p ON p.id = v.product_id'
82
+
83
+ /**
84
+ * How many options a variant lists. `options` is text holding a JSON array
85
+ * or a list split by commas, bars, semicolons or new lines, as
86
+ * commerceStringList reads it; an array is measured by the dialect's JSON
87
+ * functions and a list by its separators. A list that repeats an option, which
88
+ * the page shows once, counts it each time.
89
+ */
90
+ function optionCount(dialect: QueryBuilderDialect): string {
91
+ const column = `COALESCE(TRIM(v.options), '')`
92
+ const json = dialect === 'postgres'
93
+ ? `json_array_length(CAST(v.options AS JSON))`
94
+ : dialect === 'sqlite' ? 'json_array_length(v.options)' : 'JSON_LENGTH(v.options)'
95
+ const newline = dialect === 'sqlite' ? 'char(10)' : dialect === 'postgres' ? 'chr(10)' : 'CHAR(10)'
96
+ const stripped = `REPLACE(REPLACE(REPLACE(REPLACE(${column}, ',', ''), '|', ''), ';', ''), ${newline}, '')`
97
+ return `CASE WHEN ${column} = '' THEN 0 WHEN ${column} LIKE '[%' THEN ${json} ELSE LENGTH(${column}) - LENGTH(${stripped}) + 1 END`
98
+ }
99
+
100
+ function sortExpression(sort: ProductVariantSort, dialect: QueryBuilderDialect): string {
101
+ switch (sort) {
102
+ case 'product': return `LOWER(COALESCE(p.name, ''))`
103
+ case 'options': return optionCount(dialect)
104
+ // As text: PostgreSQL and MySQL keep the status as an enum, which sorts by declaration order.
105
+ case 'status': return asText('v.status', dialect)
106
+ case 'newest': return 'v.id'
107
+ case 'created': return 'v.created_at'
108
+ default: return 'LOWER(v.variant)'
109
+ }
110
+ }
111
+
112
+ export function productVariantFilter(query: Pick<ProductVariantListQuery, 'search' | 'status' | 'type' | 'product'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
113
+ const { bind, values } = binder(dialect)
114
+ const clauses: string[] = []
115
+ if (query.status)
116
+ clauses.push(`${asText('v.status', dialect)} = ${bind(query.status)}`)
117
+ if (query.type)
118
+ clauses.push(`v.type = ${bind(query.type)}`)
119
+ if (query.product)
120
+ clauses.push(`v.product_id = ${bind(Number(query.product))}`)
121
+ if (query.search) {
122
+ const pattern = containsPattern(query.search)
123
+ const columns = ['v.variant', 'v.type', `COALESCE(v.description, '')`, `COALESCE(p.name, '')`, `COALESCE(v.options, '')`]
124
+ clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
125
+ }
126
+ return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
127
+ }
128
+
129
+ function orderBy(query: Pick<ProductVariantListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
130
+ const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
131
+ // Ties read by name, as the page sorted them; the id breaks every
132
+ // remaining tie, so pages never repeat or skip a variant.
133
+ if (query.sort === 'newest')
134
+ return ` ORDER BY v.id ${direction}`
135
+ const byName = query.sort === 'variant' ? '' : ', LOWER(v.variant) ASC'
136
+ return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}${byName}, v.id ${direction}`
137
+ }
138
+
139
+ function productNames(rows: unknown): Map<string, string> {
140
+ return new Map(sqlRows(rows).map((row) => {
141
+ const id = commerceIdentifier(commerceValue(row, 'id'), 'Product')
142
+ return [id, commerceRequiredString(commerceValue(row, 'name'), `Product ${id}`, 'name')]
143
+ }))
144
+ }
145
+
146
+ /** Variants turned into records, against exactly the products they reference. */
147
+ async function recordsFor(variants: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ProductVariantRecord[]> {
148
+ if (variants.length === 0)
149
+ return []
150
+ const productIds = referencedIds(variants, 'product_id')
151
+ const products = productIds.length > 0
152
+ ? await run.unsafe(`SELECT id, name FROM products WHERE id IN (${idPlaceholders(productIds, dialect)})`, productIds).execute()
153
+ : []
154
+ const names = productNames(products)
155
+ return variants.map(variant => normalizeProductVariantRecord(variant, names))
156
+ }
157
+
158
+ /** The summary cards, over every variant as before. */
159
+ async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ProductVariantSummary> {
160
+ const status = asText('status', dialect)
161
+ const row = sqlRows(await run.unsafe(
162
+ `SELECT COUNT(*) AS total_count, SUM(CASE WHEN ${status} = 'active' THEN 1 ELSE 0 END) AS active_count, SUM(CASE WHEN ${status} = 'draft' THEN 1 ELSE 0 END) AS draft_count, COUNT(DISTINCT product_id) AS product_count FROM product_variants`,
163
+ ).execute())[0] ?? {}
164
+ return {
165
+ total: countOf(row.total_count),
166
+ active: countOf(row.active_count),
167
+ draft: countOf(row.draft_count),
168
+ linkedProducts: countOf(row.product_count),
169
+ }
170
+ }
171
+
172
+ export interface ProductVariantPage {
173
+ records: ProductVariantRecord[]
174
+ total: number
175
+ page: number
176
+ summary: ProductVariantSummary
177
+ /** Every type any variant has, for the filter and the dialog's suggestions. */
178
+ types: string[]
179
+ /** Every product that has a variant, for the product filter, by name ignoring case. */
180
+ products: Array<{ id: string, name: string }>
181
+ }
182
+
183
+ export async function readProductVariantPage(
184
+ query: ProductVariantListQuery,
185
+ run: CommerceSqlRunner = db,
186
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
187
+ ): Promise<ProductVariantPage> {
188
+ const { where, values } = productVariantFilter(query, dialect)
189
+ const [counted, summary, typeRows, productRows] = await Promise.all([
190
+ run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
191
+ summarize(run, dialect),
192
+ run.unsafe(`SELECT DISTINCT type AS value FROM product_variants WHERE type IS NOT NULL AND type <> ''`).execute(),
193
+ run.unsafe('SELECT p.id, p.name FROM products p WHERE EXISTS (SELECT 1 FROM product_variants v WHERE v.product_id = p.id) ORDER BY LOWER(p.name) ASC, p.id ASC').execute(),
194
+ ])
195
+ const total = countOf(sqlRows(counted)[0]?.total_count)
196
+ const page = pageWithin(query.page, total, query.perPage)
197
+ const variants = await run.unsafe(
198
+ `SELECT v.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
199
+ values,
200
+ ).execute()
201
+ return {
202
+ records: await recordsFor(sqlRows(variants), run, dialect),
203
+ total,
204
+ page,
205
+ summary,
206
+ types: [...new Set(sqlRows(typeRows).map(row => String(row.value ?? '').trim()).filter(Boolean))].sort(),
207
+ products: [...productNames(productRows)].map(([id, name]) => ({ id, name })),
208
+ }
209
+ }
@@ -1,7 +1,6 @@
1
1
  import { describe, expect, it } from 'bun:test'
2
2
  import {
3
3
  normalizeProductUnitRecord,
4
- productUnitOptions,
5
4
  summarizeProductUnits,
6
5
  } from './product-unit-records'
7
6
 
@@ -75,16 +74,4 @@ describe('dashboard product unit records', () => {
75
74
 
76
75
  expect(summarizeProductUnits(records).defaultConflicts).toBe(1)
77
76
  })
78
-
79
- it('builds stable, validated product options from model rows', () => {
80
- expect(productUnitOptions([
81
- { id: 2, name: 'Tea' },
82
- { id: 1, name: 'Coffee' },
83
- ])).toEqual([
84
- { id: '1', name: 'Coffee' },
85
- { id: '2', name: 'Tea' },
86
- ])
87
- expect(() => productUnitOptions([{ id: 3, name: '' }]))
88
- .toThrow('Product 3.name must be a non-empty string')
89
- })
90
77
  })
@@ -20,11 +20,6 @@ export interface ProductUnitRecord {
20
20
  createdAt: string
21
21
  }
22
22
 
23
- export interface ProductUnitOption {
24
- id: string
25
- name: string
26
- }
27
-
28
23
  export interface ProductUnitSummary {
29
24
  total: number
30
25
  defaults: number
@@ -33,18 +28,6 @@ export interface ProductUnitSummary {
33
28
  defaultConflicts: number
34
29
  }
35
30
 
36
- export function productUnitOptions(products: any[]): ProductUnitOption[] {
37
- return products
38
- .map((product) => {
39
- const id = commerceIdentifier(commerceValue(product, 'id', 'uuid'), 'Product')
40
- return {
41
- id,
42
- name: commerceRequiredString(commerceValue(product, 'name'), `Product ${id}`, 'name'),
43
- }
44
- })
45
- .sort((left, right) => left.name.localeCompare(right.name))
46
- }
47
-
48
31
  export function normalizeProductUnitRecord(
49
32
  record: any,
50
33
  products = new Map<string, string>(),
@@ -2,7 +2,6 @@ import { describe, expect, it } from 'bun:test'
2
2
  import {
3
3
  normalizeProductVariantRecord,
4
4
  parseVariantOptions,
5
- productVariantOptions,
6
5
  summarizeProductVariants,
7
6
  } from './product-variant-records'
8
7
 
@@ -70,16 +69,4 @@ describe('dashboard product variant records', () => {
70
69
  linkedProducts: 2,
71
70
  })
72
71
  })
73
-
74
- it('builds validated Product options', () => {
75
- expect(productVariantOptions([
76
- { id: 2, name: 'Tea' },
77
- { id: 1, name: 'Coffee' },
78
- ])).toEqual([
79
- { id: '1', name: 'Coffee' },
80
- { id: '2', name: 'Tea' },
81
- ])
82
- expect(() => productVariantOptions([{ id: 3, name: '' }]))
83
- .toThrow('Product 3.name must be a non-empty string')
84
- })
85
72
  })
@@ -21,11 +21,6 @@ export interface ProductVariantRecord {
21
21
  createdAt: string
22
22
  }
23
23
 
24
- export interface ProductVariantOption {
25
- id: string
26
- name: string
27
- }
28
-
29
24
  export interface ProductVariantSummary {
30
25
  total: number
31
26
  active: number
@@ -37,18 +32,6 @@ export function parseVariantOptions(input: unknown): string[] {
37
32
  return commerceStringList(input, 'ProductVariant', 'options')
38
33
  }
39
34
 
40
- export function productVariantOptions(products: any[]): ProductVariantOption[] {
41
- return products
42
- .map((product) => {
43
- const id = commerceIdentifier(commerceValue(product, 'id', 'uuid'), 'Product')
44
- return {
45
- id,
46
- name: commerceRequiredString(commerceValue(product, 'name'), `Product ${id}`, 'name'),
47
- }
48
- })
49
- .sort((left, right) => left.name.localeCompare(right.name))
50
- }
51
-
52
35
  export function normalizeProductVariantRecord(
53
36
  record: any,
54
37
  productNames = new Map<string, string>(),
@@ -302,6 +302,20 @@ describe('useServerList', () => {
302
302
  expect(api.asked[1]!.get('direction')).toBe('desc')
303
303
  })
304
304
 
305
+ it('follows a sort select, handing the order back from a header sort', () => {
306
+ const api = server()
307
+ const sort = state<{ sort: string, direction: 'asc' | 'desc' }>({ sort: 'name', direction: 'asc' })
308
+ const list = useServerList<string>({ fetch: api.fetch, defaultSort: () => sort(), columnSorts: { typeLabel: 'type' } })
309
+ list.changeSort({ key: 'typeLabel', direction: 'desc' })
310
+ expect(api.asked[0]!.get('sort')).toBe('type')
311
+ list.page.set(4)
312
+ sort.set({ sort: 'newest', direction: 'desc' })
313
+ expect(api.asked.length).toBe(2)
314
+ expect(api.asked[1]!.get('sort')).toBe('newest')
315
+ expect(api.asked[1]!.get('direction')).toBe('desc')
316
+ expect(api.asked[1]!.get('page')).toBe('1')
317
+ })
318
+
305
319
  it('reports a failed load, and ignores one that a newer load replaced', async () => {
306
320
  const errors: unknown[] = []
307
321
  let calls = 0
@@ -269,8 +269,12 @@ export interface ServerListOptions<T> {
269
269
  * `page` and `per_page`, as the commerce list endpoints read them.
270
270
  */
271
271
  fetch: (params: URLSearchParams) => Promise<ServerListPage<T>>
272
- /** The order before any column header is clicked. */
273
- defaultSort: { sort: string, direction: 'asc' | 'desc' }
272
+ /**
273
+ * The order before any column header is clicked. An accessor when the page
274
+ * has a sort select: changing it hands the order back from a header sort
275
+ * and asks for page 1.
276
+ */
277
+ defaultSort: { sort: string, direction: 'asc' | 'desc' } | (() => { sort: string, direction: 'asc' | 'desc' })
274
278
  /** The table's sortable column keys, as the server's sort names. A column not listed returns to `defaultSort`. */
275
279
  columnSorts?: Record<string, string>
276
280
  /** The filter values, read reactively: a change asks for page 1. `''` or `'all'` leaves a filter out. */
@@ -332,10 +336,11 @@ export function useServerList<T>(options: ServerListOptions<T>): ServerList<T> {
332
336
  const headerSort = state<{ sort: string, direction: string } | null>(null)
333
337
  let request = 0
334
338
  let timer: ReturnType<typeof setTimeout> | null = null
339
+ const defaultOrder = () => typeof options.defaultSort === 'function' ? options.defaultSort() : options.defaultSort
335
340
 
336
341
  const params = (): URLSearchParams => {
337
342
  const query = new URLSearchParams()
338
- const order = headerSort() ?? options.defaultSort
343
+ const order = headerSort() ?? defaultOrder()
339
344
  query.set('sort', order.sort)
340
345
  query.set('direction', order.direction)
341
346
  if (appliedSearch())
@@ -387,6 +392,19 @@ export function useServerList<T>(options: ServerListOptions<T>): ServerList<T> {
387
392
  })
388
393
  }
389
394
 
395
+ if (typeof options.defaultSort === 'function') {
396
+ let shownOrder = JSON.stringify(defaultOrder())
397
+ effect(() => {
398
+ const order = JSON.stringify(defaultOrder())
399
+ if (order === shownOrder)
400
+ return
401
+ shownOrder = order
402
+ headerSort.set(null)
403
+ page.set(1)
404
+ void load()
405
+ })
406
+ }
407
+
390
408
  let shownSearch = search().trim()
391
409
  effect(() => {
392
410
  const term = search().trim()
@@ -2,7 +2,7 @@
2
2
  "publisher": "Stacks",
3
3
  "name": "vscode-stacks",
4
4
  "displayName": "Stacks",
5
- "version": "0.75.490",
5
+ "version": "0.75.493",
6
6
  "description": "Stacks, built into VS Code: stx templates, pickier linting and formatting, encrypted env files, the dev server preview and every buddy command. No other extensions required.",
7
7
  "license": "MIT",
8
8
  "funding": "https://github.com/sponsors/chrisbbreuer",
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/defaults",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.490",
5
+ "version": "0.75.493",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/stacksjs/stacks.git",
@@ -45,7 +45,7 @@
45
45
  "dependencies": {
46
46
  "@iconify-json/f7": "^1.2.2",
47
47
  "@iconify-json/hugeicons": "^1.2.35",
48
- "@stacksjs/mobile": "0.75.490",
48
+ "@stacksjs/mobile": "0.75.493",
49
49
  "@stacksjs/sanitizer": "0.2.807",
50
50
  "@stacksjs/stx": "0.2.807",
51
51
  "@xterm/addon-fit": "^0.11.0",