@stacksjs/defaults 0.75.487 → 0.75.490

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +27 -2
  3. package/ai/skills/stacks-native/CATALOG.md +9 -9
  4. package/ai/skills/stacks-search-engine/SKILL.md +14 -0
  5. package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
  6. package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
  7. package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
  8. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
  9. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
  10. package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
  11. package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
  12. package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
  13. package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
  14. package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
  15. package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
  16. package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
  17. package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
  18. package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
  19. package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
  20. package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
  21. package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
  22. package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
  23. package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
  24. package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
  25. package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
  26. package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
  27. package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
  28. package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
  29. package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
  30. package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
  31. package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
  32. package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
  33. package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
  34. package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
  35. package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
  36. package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
  37. package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
  38. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
  39. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
  40. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
  41. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
  42. package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
  43. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
  44. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
  45. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
  46. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
  47. package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
  48. package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
  49. package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
  50. package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
  51. package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
  52. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
  53. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
  54. package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
  55. package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
  56. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
  57. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
  58. package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
  59. package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
  60. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
  61. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
  62. package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
  63. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
  64. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
  65. package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
  66. package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
  67. package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
  68. package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
  69. package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
  70. package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
  71. package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
  72. package/app/Actions/Dashboard/Content/content-list.ts +10 -0
  73. package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
  74. package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
  75. package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
  76. package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
  77. package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
  78. package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
  79. package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
  80. package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
  81. package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
  82. package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
  83. package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
  84. package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
  85. package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
  86. package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
  87. package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +9 -6
  88. package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
  89. package/app/Actions/Dashboard/Queue/queue-stats.ts +10 -0
  90. package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
  91. package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
  92. package/app/Actions/Dashboard/named-search.test.ts +36 -0
  93. package/app/Actions/Dashboard/named-search.ts +80 -0
  94. package/app/Models/QueueWorker.ts +1 -0
  95. package/app/Models/Request.ts +4 -2
  96. package/bootstrap.ts +6 -1
  97. package/functions/commerce/shippings/dashboard-resource.ts +12 -1
  98. package/functions/commerce/shippings/delivery-routes.ts +1 -0
  99. package/functions/commerce/shippings/license-keys.ts +1 -0
  100. package/functions/dashboard-list.test.ts +132 -1
  101. package/functions/dashboard-list.ts +198 -1
  102. package/functions/queue.ts +2 -0
  103. package/ide/vscode/package.json +1 -1
  104. package/package.json +2 -2
  105. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
  106. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
  107. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
  108. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
  109. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
  110. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
  111. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
  112. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
  113. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
  114. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
  115. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
  116. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
  117. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
  118. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
  119. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
  120. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
  121. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
  122. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
  123. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
  124. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
  125. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
  126. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
  127. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
  128. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
  129. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
  130. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
  131. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
  132. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
  133. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
  134. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
  135. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
  136. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
  137. package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
  138. package/resources/components/Dashboard/Queue/QueueDashboard.stx +8 -2
  139. package/resources/functions/dashboard/sidebar.ts +26 -1
  140. package/routes/dashboard-api.ts +11 -0
  141. package/views/dashboard/stores/kanban.ts +38 -6
@@ -1,5 +1,5 @@
1
1
  import type { Signal } from '@stacksjs/stx'
2
- import { state } from '@stacksjs/stx'
2
+ import { effect, state } from '@stacksjs/stx'
3
3
 
4
4
  /**
5
5
  * Shared pieces of the dashboard's list screens.
@@ -255,3 +255,200 @@ export function useRecordsDashboard<T>(options: RecordsDashboardOptions<T>): Rec
255
255
  clampPage,
256
256
  }
257
257
  }
258
+
259
+ /** One page as a server-paged list endpoint answers it. */
260
+ export interface ServerListPage<T> {
261
+ records?: T[]
262
+ total?: number
263
+ page?: number
264
+ }
265
+
266
+ export interface ServerListOptions<T> {
267
+ /**
268
+ * Ask for one page. `params` carries `sort`, `direction`, `q`, the filters,
269
+ * `page` and `per_page`, as the commerce list endpoints read them.
270
+ */
271
+ fetch: (params: URLSearchParams) => Promise<ServerListPage<T>>
272
+ /** The order before any column header is clicked. */
273
+ defaultSort: { sort: string, direction: 'asc' | 'desc' }
274
+ /** The table's sortable column keys, as the server's sort names. A column not listed returns to `defaultSort`. */
275
+ columnSorts?: Record<string, string>
276
+ /** The filter values, read reactively: a change asks for page 1. `''` or `'all'` leaves a filter out. */
277
+ filters?: () => Record<string, string>
278
+ /** Rows per page. Default 25, the list endpoints' own default. */
279
+ perPage?: number
280
+ /** How long typing pauses before the search is sent. Default 250ms. */
281
+ searchDelay?: number
282
+ /** Called with whatever a load threw, after `loadError` is set. */
283
+ onError?: (error: unknown) => void
284
+ /** Called with each answer that lands, for anything else it carries (a summary, choices). */
285
+ onLoad?: (result: ServerListPage<T>) => void
286
+ }
287
+
288
+ export interface ServerList<T> {
289
+ records: Signal<T[]>
290
+ /** How many rows match, across every page. */
291
+ total: Signal<number>
292
+ page: Signal<number>
293
+ perPage: Signal<number>
294
+ /** What the search box holds; it is sent once typing pauses. */
295
+ search: Signal<string>
296
+ loading: Signal<boolean>
297
+ loadError: Signal<string>
298
+ /** The search, filters and order as query parameters, without the page: what an export link needs. */
299
+ params: () => URLSearchParams
300
+ /** Ask for the current page again, after a save or a delete. */
301
+ load: () => Promise<void>
302
+ changePage: (value: number | CustomEvent<number>) => void
303
+ changePageSize: (value: number | CustomEvent<number>) => void
304
+ changeSort: (value: { key: string, direction: string } | CustomEvent<{ key: string, direction: string }>) => void
305
+ }
306
+
307
+ function eventValue<V>(value: V | CustomEvent<V>): V {
308
+ return typeof CustomEvent !== 'undefined' && value instanceof CustomEvent ? value.detail : value as V
309
+ }
310
+
311
+ /**
312
+ * A list the server searches, filters, sorts and pages (stacksjs/stacks#3218).
313
+ *
314
+ * The Orders, Payments, Products, Gift Cards, Reviews and waitlist pages each
315
+ * wrote the same request counter, page, page size, header sort and search
316
+ * debounce. This is that, once: only the newest answer lands, a filter or
317
+ * search change asks for page 1, and a column header the server cannot sort
318
+ * by returns to the default order.
319
+ *
320
+ * The caller still owns when to load first (call `load()` in `onMount`), its
321
+ * toasts, and what its endpoint returns beyond the page (`onLoad`).
322
+ */
323
+ export function useServerList<T>(options: ServerListOptions<T>): ServerList<T> {
324
+ const records = state<T[]>([])
325
+ const total = state(0)
326
+ const page = state(1)
327
+ const perPage = state(options.perPage ?? 25)
328
+ const search = state('')
329
+ const loading = state(true)
330
+ const loadError = state('')
331
+ const appliedSearch = state('')
332
+ const headerSort = state<{ sort: string, direction: string } | null>(null)
333
+ let request = 0
334
+ let timer: ReturnType<typeof setTimeout> | null = null
335
+
336
+ const params = (): URLSearchParams => {
337
+ const query = new URLSearchParams()
338
+ const order = headerSort() ?? options.defaultSort
339
+ query.set('sort', order.sort)
340
+ query.set('direction', order.direction)
341
+ if (appliedSearch())
342
+ query.set('q', appliedSearch())
343
+ for (const [name, value] of Object.entries(options.filters?.() ?? {})) {
344
+ if (value !== '' && value !== 'all')
345
+ query.set(name, value)
346
+ }
347
+ return query
348
+ }
349
+
350
+ const load = async (): Promise<void> => {
351
+ const current = ++request
352
+ loading.set(true)
353
+ loadError.set('')
354
+ try {
355
+ const query = params()
356
+ query.set('page', String(page()))
357
+ query.set('per_page', String(perPage()))
358
+ const result = await options.fetch(query)
359
+ if (current !== request)
360
+ return
361
+ records.set(Array.isArray(result.records) ? result.records : [])
362
+ total.set(Number(result.total) || 0)
363
+ page.set(Number(result.page) || 1)
364
+ options.onLoad?.(result)
365
+ }
366
+ catch (error) {
367
+ if (current !== request)
368
+ return
369
+ loadError.set(error instanceof Error ? error.message : String(error))
370
+ options.onError?.(error)
371
+ }
372
+ finally {
373
+ if (current === request)
374
+ loading.set(false)
375
+ }
376
+ }
377
+
378
+ if (options.filters) {
379
+ let shown = JSON.stringify(options.filters())
380
+ effect(() => {
381
+ const filters = JSON.stringify(options.filters!())
382
+ if (filters === shown)
383
+ return
384
+ shown = filters
385
+ page.set(1)
386
+ void load()
387
+ })
388
+ }
389
+
390
+ let shownSearch = search().trim()
391
+ effect(() => {
392
+ const term = search().trim()
393
+ if (term === shownSearch)
394
+ return
395
+ shownSearch = term
396
+ if (timer)
397
+ clearTimeout(timer)
398
+ timer = setTimeout(() => {
399
+ appliedSearch.set(term)
400
+ page.set(1)
401
+ void load()
402
+ }, options.searchDelay ?? 250)
403
+ })
404
+
405
+ return {
406
+ records,
407
+ total,
408
+ page,
409
+ perPage,
410
+ search,
411
+ loading,
412
+ loadError,
413
+ params,
414
+ load,
415
+ changePage(value) {
416
+ page.set(Number(eventValue(value)) || 1)
417
+ void load()
418
+ },
419
+ changePageSize(value) {
420
+ perPage.set(Number(eventValue(value)) || (options.perPage ?? 25))
421
+ page.set(1)
422
+ void load()
423
+ },
424
+ changeSort(value) {
425
+ const column = eventValue(value)
426
+ const sort = options.columnSorts?.[column.key]
427
+ headerSort.set(sort ? { sort, direction: column.direction === 'asc' ? 'asc' : 'desc' } : null)
428
+ page.set(1)
429
+ void load()
430
+ },
431
+ }
432
+ }
433
+
434
+ /** The largest page the list endpoints serve. */
435
+ export const LARGEST_PAGE = 100
436
+
437
+ /**
438
+ * Every record a paged list endpoint holds, a page at a time: for a caller
439
+ * that does want all of them, such as a resource's `fetchAll`. Stops at the
440
+ * first short page, so a count that moved while it read cannot loop it.
441
+ */
442
+ export async function readEveryPage<T>(
443
+ get: (page: number, perPage: number) => Promise<{ records?: T[], total?: number }>,
444
+ ): Promise<T[]> {
445
+ const all: T[] = []
446
+ for (let page = 1; ; page++) {
447
+ const data = await get(page, LARGEST_PAGE)
448
+ if (!Array.isArray(data?.records))
449
+ throw new TypeError('Server returned a page without records')
450
+ all.push(...data.records)
451
+ if (data.records.length < LARGEST_PAGE || all.length >= Number(data.total))
452
+ return all
453
+ }
454
+ }
@@ -51,6 +51,8 @@ export interface QueueWorkersResponse {
51
51
  data: QueueWorker[]
52
52
  worker_running: boolean
53
53
  active_jobs: number
54
+ /** False when `queue_workers` has not been migrated: there is no worker telemetry to read yet. */
55
+ workers_migrated?: boolean
54
56
  }
55
57
 
56
58
  export async function fetchQueueStats(): Promise<QueueStatsResponse> {
@@ -2,7 +2,7 @@
2
2
  "publisher": "Stacks",
3
3
  "name": "vscode-stacks",
4
4
  "displayName": "Stacks",
5
- "version": "0.75.487",
5
+ "version": "0.75.490",
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.487",
5
+ "version": "0.75.490",
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.487",
48
+ "@stacksjs/mobile": "0.75.490",
49
49
  "@stacksjs/sanitizer": "0.2.807",
50
50
  "@stacksjs/stx": "0.2.807",
51
51
  "@xterm/addon-fit": "^0.11.0",
@@ -1,8 +1,35 @@
1
1
  <script client>
2
- import type { GiftCardSummary } from '../../../../app/Actions/Dashboard/Commerce/gift-card-records'
2
+ import type { GiftCardCurrencySummary, GiftCardStatus, GiftCardSummary } from '../../../../app/Actions/Dashboard/Commerce/gift-card-records'
3
3
  import { formatCurrency } from '@stacksjs/commerce/money'
4
4
 
5
- const { summary } = defineProps<{ summary: GiftCardSummary }>()
5
+ // A reactive prop, as every other commerce breakdown reads its data: a
6
+ // destructured `defineProps` value is read once, before the page has loaded
7
+ // anything, so these panels used to render with no numbers at all.
8
+ const summary = useReactiveProp('summary', {
9
+ total: 0,
10
+ available: 0,
11
+ enabled: 0,
12
+ digital: 0,
13
+ reloadable: 0,
14
+ statuses: { ACTIVE: 0, USED: 0, EXPIRED: 0, DEACTIVATED: 0 },
15
+ currencies: [],
16
+ } as GiftCardSummary)
17
+
18
+ const STATUS_LABELS: Array<{ key: GiftCardStatus, label: string }> = [
19
+ { key: 'ACTIVE', label: 'Active' },
20
+ { key: 'USED', label: 'Used' },
21
+ { key: 'EXPIRED', label: 'Expired' },
22
+ { key: 'DEACTIVATED', label: 'Deactivated' },
23
+ ]
24
+
25
+ function statusRows(): Array<{ key: GiftCardStatus, label: string, count: number }> {
26
+ const counts = summary().statuses
27
+ return STATUS_LABELS.map(status => ({ ...status, count: counts?.[status.key] ?? 0 }))
28
+ }
29
+
30
+ function currencyRows(): GiftCardCurrencySummary[] {
31
+ return Array.isArray(summary().currencies) ? summary().currencies : []
32
+ }
6
33
 
7
34
  function money(value: number, currency: string): string {
8
35
  return formatCurrency(value, currency)
@@ -13,18 +40,17 @@ function money(value: number, currency: string): string {
13
40
  <article class="p-4 bg-white dark:bg-neutral-800 border border-gray-200 rounded-lg dark:border-neutral-700">
14
41
  <h2 class="font-semibold text-gray-900 text-sm dark:text-white">Status distribution</h2>
15
42
  <dl class="mt-4 space-y-3 text-sm">
16
- <div class="flex justify-between"><dt class="text-gray-500 dark:text-neutral-400">Active</dt><dd class="font-medium text-gray-900 dark:text-white">{{ summary.statuses.ACTIVE }}</dd></div>
17
- <div class="flex justify-between"><dt class="text-gray-500 dark:text-neutral-400">Used</dt><dd class="font-medium text-gray-900 dark:text-white">{{ summary.statuses.USED }}</dd></div>
18
- <div class="flex justify-between"><dt class="text-gray-500 dark:text-neutral-400">Expired</dt><dd class="font-medium text-gray-900 dark:text-white">{{ summary.statuses.EXPIRED }}</dd></div>
19
- <div class="flex justify-between"><dt class="text-gray-500 dark:text-neutral-400">Deactivated</dt><dd class="font-medium text-gray-900 dark:text-white">{{ summary.statuses.DEACTIVATED }}</dd></div>
43
+ <template :for="item in statusRows()" :key="item.key">
44
+ <div class="flex justify-between"><dt class="text-gray-500 dark:text-neutral-400">{{ item.label }}</dt><dd class="font-medium text-gray-900 dark:text-white">{{ item.count }}</dd></div>
45
+ </template>
20
46
  </dl>
21
47
  </article>
22
48
 
23
49
  <article class="p-4 bg-white dark:bg-neutral-800 border border-gray-200 rounded-lg dark:border-neutral-700">
24
50
  <h2 class="font-semibold text-gray-900 text-sm dark:text-white">Outstanding by currency</h2>
25
- <div :if="summary.currencies.length === 0" class="mt-4 text-gray-500 text-sm dark:text-neutral-400">No balances recorded.</div>
26
- <ul :if="summary.currencies.length > 0" class="mt-4 space-y-3">
27
- <template :for="item in summary.currencies" :key="item.currency">
51
+ <div :if="currencyRows().length === 0" class="mt-4 text-gray-500 text-sm dark:text-neutral-400">No balances recorded.</div>
52
+ <ul :if="currencyRows().length > 0" class="mt-4 space-y-3">
53
+ <template :for="item in currencyRows()" :key="item.currency">
28
54
  <li class="flex gap-4 justify-between text-sm">
29
55
  <span class="text-gray-500 dark:text-neutral-400">{{ item.currency }} <span class="text-gray-500 text-xs dark:text-neutral-500">({{ item.cards }})</span></span>
30
56
  <span class="font-medium text-gray-900 dark:text-white">{{ money(item.currentBalance, item.currency) }}</span>
@@ -35,9 +61,9 @@ function money(value: number, currency: string): string {
35
61
 
36
62
  <article class="p-4 bg-white dark:bg-neutral-800 border border-gray-200 rounded-lg dark:border-neutral-700">
37
63
  <h2 class="font-semibold text-gray-900 text-sm dark:text-white">Redeemed by currency</h2>
38
- <div :if="summary.currencies.length === 0" class="mt-4 text-gray-500 text-sm dark:text-neutral-400">No redemption value recorded.</div>
39
- <ul :if="summary.currencies.length > 0" class="mt-4 space-y-3">
40
- <template :for="item in summary.currencies" :key="item.currency">
64
+ <div :if="currencyRows().length === 0" class="mt-4 text-gray-500 text-sm dark:text-neutral-400">No redemption value recorded.</div>
65
+ <ul :if="currencyRows().length > 0" class="mt-4 space-y-3">
66
+ <template :for="item in currencyRows()" :key="item.currency">
41
67
  <li class="flex gap-4 justify-between text-sm">
42
68
  <span class="text-gray-500 dark:text-neutral-400">{{ item.currency }}</span>
43
69
  <span class="font-medium text-gray-900 dark:text-white">{{ money(item.redeemedBalance, item.currency) }}</span>
@@ -6,10 +6,12 @@ import type {
6
6
  } from '../../../../app/Actions/Dashboard/Commerce/gift-card-records'
7
7
  import { DashboardApiError, dashboardApi } from '../../../../functions/dashboard-api'
8
8
  import { pushToast } from '../../../../functions/toasts'
9
- import { minorToInput } from '@stacksjs/commerce/money'
10
9
 
11
10
  interface GiftCardIndexResponse {
12
11
  records: GiftCardRecord[]
12
+ total: number
13
+ page: number
14
+ perPage: number
13
15
  summary: GiftCardSummary
14
16
  }
15
17
 
@@ -48,6 +50,15 @@ const statusFilter = state('all')
48
50
  const enabledFilter = state('all')
49
51
  const deliveryFilter = state('all')
50
52
  const sort = state('newest')
53
+ // The server searches, filters, sorts and pages (stacksjs/stacks#3218), where
54
+ // this page used to do all of that with the newest 500.
55
+ const matchingTotal = state(0)
56
+ const page = state(1)
57
+ const perPage = state(25)
58
+ const appliedSearch = state('')
59
+ const headerSort = state<{ sort: string, direction: string } | null>(null)
60
+ let listRequest = 0
61
+ let searchTimer: ReturnType<typeof setTimeout> | null = null
51
62
  const loading = state(true)
52
63
  const loadError = state('')
53
64
  const dialogOpen = state(false)
@@ -59,40 +70,43 @@ const saving = state(false)
59
70
  const deleting = state(false)
60
71
  const validationErrors = state<Record<string, string>>({})
61
72
 
62
- function filteredRecords(): GiftCardRecord[] {
63
- const query = search().trim().toLowerCase()
64
- const selectedStatus = statusFilter()
65
- const selectedEnabled = enabledFilter()
66
- const selectedDelivery = deliveryFilter()
67
- return [...records()]
68
- .filter((record) => {
69
- if (selectedStatus !== 'all' && record.status !== selectedStatus)
70
- return false
71
- if (selectedEnabled === 'enabled' && !record.isActive)
72
- return false
73
- if (selectedEnabled === 'disabled' && record.isActive)
74
- return false
75
- if (selectedDelivery === 'digital' && !record.isDigital)
76
- return false
77
- if (selectedDelivery === 'physical' && record.isDigital)
78
- return false
79
- return !query || [
80
- record.code,
81
- record.recipientName,
82
- record.recipientEmail,
83
- record.purchaserId,
84
- record.currency,
85
- ].some(value => value.toLowerCase().includes(query))
86
- })
87
- .sort((left, right) => {
88
- if (sort() === 'code')
89
- return left.code.localeCompare(right.code)
90
- if (sort() === 'balance')
91
- return right.currentBalance - left.currentBalance || left.code.localeCompare(right.code)
92
- if (sort() === 'expiry')
93
- return left.expiryDate.localeCompare(right.expiryDate) || left.code.localeCompare(right.code)
94
- return Number(right.id) - Number(left.id)
95
- })
73
+ const SELECT_SORTS: Record<string, { sort: string, direction: string }> = {
74
+ newest: { sort: 'created', direction: 'desc' },
75
+ code: { sort: 'code', direction: 'asc' },
76
+ balance: { sort: 'balance', direction: 'desc' },
77
+ expiry: { sort: 'expiry', direction: 'asc' },
78
+ }
79
+
80
+ /** The table's sortable columns, as the server's sort names. */
81
+ const COLUMN_SORTS: Record<string, string> = {
82
+ code: 'code',
83
+ recipientLabel: 'recipient',
84
+ currentBalance: 'balance',
85
+ status: 'status',
86
+ deliveryLabel: 'delivery',
87
+ expiryDate: 'expiry',
88
+ }
89
+
90
+ /** The search, filters and order, as the query the server takes. */
91
+ function filterParams(): URLSearchParams {
92
+ const params = new URLSearchParams()
93
+ const order = headerSort() ?? SELECT_SORTS[sort()] ?? SELECT_SORTS.newest
94
+ params.set('sort', order.sort)
95
+ params.set('direction', order.direction)
96
+ if (appliedSearch())
97
+ params.set('q', appliedSearch())
98
+ if (statusFilter() !== 'all')
99
+ params.set('status', statusFilter())
100
+ if (enabledFilter() !== 'all')
101
+ params.set('enabled', enabledFilter())
102
+ if (deliveryFilter() !== 'all')
103
+ params.set('delivery', deliveryFilter())
104
+ return params
105
+ }
106
+
107
+ function matchingLabel(): string {
108
+ const count = matchingTotal()
109
+ return `${count} matching ${count === 1 ? 'gift card' : 'gift cards'}`
96
110
  }
97
111
 
98
112
  function metricCards(): Array<{ label: string, value: string, detail: string }> {
@@ -105,56 +119,96 @@ function metricCards(): Array<{ label: string, value: string, detail: string }>
105
119
  ]
106
120
  }
107
121
 
122
+ /** Every matching gift card as CSV, built by the server, not just the page shown. */
108
123
  function exportHref(): string {
109
- const rows = filteredRecords().map(record => [
110
- record.code,
111
- record.recipientName,
112
- record.recipientEmail,
113
- record.status,
114
- record.isActive ? 'Enabled' : 'Disabled',
115
- record.isDigital ? 'Digital' : 'Physical',
116
- record.isReloadable ? 'Reloadable' : 'Single use',
117
- record.currency,
118
- minorToInput(record.initialBalance, record.currency),
119
- minorToInput(record.currentBalance, record.currency),
120
- record.expiryDate,
121
- record.lastUsedDate,
122
- ])
123
- const escape = (value: string): string => `"${value.replaceAll('"', '""')}"`
124
- const csv = [
125
- ['Code', 'Recipient', 'Email', 'Status', 'Availability', 'Delivery', 'Reloading', 'Currency', 'Initial balance', 'Current balance', 'Expiry date', 'Last used date'],
126
- ...rows,
127
- ].map(row => row.map(escape).join(',')).join('\n')
128
- return `data:text/csv;charset=utf-8,${encodeURIComponent(`\uFEFF${csv}`)}`
129
- }
130
-
131
- /**
132
- * What the table is showing: a change returns it to the first page, as this
133
- * page's own pager did before the table took over paging.
134
- */
135
- function viewKey(): string {
136
- return JSON.stringify([search(), statusFilter(), enabledFilter(), deliveryFilter(), sort()])
124
+ return `/api/dashboard/commerce/gift-cards/export?${filterParams()}`
137
125
  }
138
126
 
139
127
  async function loadGiftCards(): Promise<void> {
128
+ const request = ++listRequest
140
129
  loading.set(true)
141
130
  loadError.set('')
142
131
  try {
143
- const data = await dashboardApi<GiftCardIndexResponse>('/api/dashboard/commerce/gift-cards')
132
+ const params = filterParams()
133
+ params.set('page', String(page()))
134
+ params.set('per_page', String(perPage()))
135
+ const data = await dashboardApi<GiftCardIndexResponse>(`/api/dashboard/commerce/gift-cards?${params}`)
136
+ // Only the newest request lands.
137
+ if (request !== listRequest)
138
+ return
144
139
  records.set(Array.isArray(data.records) ? data.records : [])
140
+ matchingTotal.set(Number(data.total) || 0)
141
+ page.set(Number(data.page) || 1)
145
142
  summary.set(data.summary ?? { ...emptySummary })
146
143
  }
147
144
  catch (error) {
145
+ if (request !== listRequest)
146
+ return
148
147
  loadError.set('Gift cards could not be loaded.')
149
148
  pushToast('error', 'Could not load gift cards', {
150
149
  detail: error instanceof Error ? error.message : String(error),
151
150
  })
152
151
  }
153
152
  finally {
154
- loading.set(false)
153
+ if (request === listRequest)
154
+ loading.set(false)
155
155
  }
156
156
  }
157
157
 
158
+ function eventValue<T>(value: T | CustomEvent<T>): T {
159
+ return value instanceof CustomEvent ? value.detail : value
160
+ }
161
+
162
+ function changePage(value: number | CustomEvent<number>): void {
163
+ page.set(Number(eventValue(value)) || 1)
164
+ void loadGiftCards()
165
+ }
166
+
167
+ function changePageSize(value: number | CustomEvent<number>): void {
168
+ perPage.set(Number(eventValue(value)) || 25)
169
+ page.set(1)
170
+ void loadGiftCards()
171
+ }
172
+
173
+ function changeColumnSort(value: { key: string, direction: string } | CustomEvent<{ key: string, direction: string }>): void {
174
+ const column = eventValue(value)
175
+ const serverSort = COLUMN_SORTS[column.key]
176
+ headerSort.set(serverSort ? { sort: serverSort, direction: column.direction === 'asc' ? 'asc' : 'desc' } : null)
177
+ page.set(1)
178
+ void loadGiftCards()
179
+ }
180
+
181
+ // The filters and the select ask the server for page 1 when they change, and
182
+ // the search once typing pauses. A select change hands the order back from a
183
+ // column header.
184
+ let shownFilters = JSON.stringify([statusFilter(), enabledFilter(), deliveryFilter(), sort()])
185
+ effect(() => {
186
+ const filters = JSON.stringify([statusFilter(), enabledFilter(), deliveryFilter(), sort()])
187
+ if (filters === shownFilters)
188
+ return
189
+ const sortChanged = JSON.parse(shownFilters)[3] !== sort()
190
+ shownFilters = filters
191
+ if (sortChanged)
192
+ headerSort.set(null)
193
+ page.set(1)
194
+ void loadGiftCards()
195
+ })
196
+
197
+ let shownSearch = search().trim()
198
+ effect(() => {
199
+ const term = search().trim()
200
+ if (term === shownSearch)
201
+ return
202
+ shownSearch = term
203
+ if (searchTimer)
204
+ clearTimeout(searchTimer)
205
+ searchTimer = setTimeout(() => {
206
+ appliedSearch.set(term)
207
+ page.set(1)
208
+ void loadGiftCards()
209
+ }, 250)
210
+ })
211
+
158
212
  function openAdd(): void {
159
213
  dialogMode.set('add')
160
214
  editingRecord.set(null)
@@ -253,7 +307,7 @@ onMount(() => {
253
307
  <PageHeader title="Gift Cards" description="Manage native GiftCard balances, recipients, delivery, and lifecycle state.">
254
308
  <div class="flex flex-wrap gap-2">
255
309
  <Button variant="secondary" :loading="loading()" @click="loadGiftCards()"><span :if="!loading()" class="h-4 w-4 i-hugeicons-refresh"></span>Refresh</Button>
256
- <Button tag="a" variant="secondary" :href="exportHref()" :download="'gift-cards-' + new Date().toISOString().slice(0, 10) + '.csv'"><span class="h-4 w-4 i-hugeicons-download-04"></span>Export filtered</Button>
310
+ <Button tag="a" variant="secondary" :href="exportHref()" download><span class="h-4 w-4 i-hugeicons-download-04"></span>Export filtered</Button>
257
311
  <Button @click="openAdd()"><span class="h-4 w-4 i-hugeicons-add-01"></span>Add gift card</Button>
258
312
  </div>
259
313
  </PageHeader>
@@ -278,10 +332,10 @@ onMount(() => {
278
332
  </div>
279
333
 
280
334
  <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
281
- <p class="text-gray-500 text-sm dark:text-neutral-400">{{ filteredRecords().length }} matching gift cards</p>
335
+ <p class="text-gray-500 text-sm dark:text-neutral-400">{{ matchingLabel() }}</p>
282
336
  </div>
283
337
 
284
- <CommerceGiftCardsTable :sort-reset-key="sort()" :page-reset-key="viewKey()" :records="filteredRecords()" :loading="loading()" @view="openDetails" @edit="openEdit" @delete="openDelete" />
338
+ <CommerceGiftCardsTable :sort-reset-key="sort()" :records="records()" :total="matchingTotal()" :current-page="page()" :per-page="perPage()" :loading="loading()" @view="openDetails" @edit="openEdit" @delete="openDelete" @page-change="changePage" @page-size-change="changePageSize" @sort="changeColumnSort" />
285
339
  </section>
286
340
  </div>
287
341
 
@@ -8,9 +8,14 @@ const records = useReactiveProp('records', [] as GiftCardRecord[])
8
8
  const loading = useReactiveProp('loading', false)
9
9
  /** The parent's sort select: a change hands the order back from a header sort. */
10
10
  const sortResetKey = useReactiveProp<unknown>('sortResetKey', '')
11
- /** The parent's search and filters: a change returns to the first page. */
12
- const pageResetKey = useReactiveProp<unknown>('pageResetKey', '')
13
- const emit = defineEmits(['view', 'edit', 'delete'])
11
+ /**
12
+ * The server pages and sorts what the parent's search and filters match
13
+ * (stacksjs/stacks#3218): how many cards match, the page shown and its size.
14
+ */
15
+ const total = useReactiveProp('total', 0)
16
+ const currentPage = useReactiveProp('currentPage', 1)
17
+ const perPage = useReactiveProp('perPage', 25)
18
+ const emit = defineEmits(['view', 'edit', 'delete', 'page-change', 'page-size-change', 'sort'])
14
19
 
15
20
  function statusLabel(status: GiftCardStatus): string {
16
21
  return status.charAt(0) + status.slice(1).toLowerCase()
@@ -62,23 +67,41 @@ const rows = derived(() => records().map(record => ({
62
67
  function handleRowAction(payload: { action: string, row: GiftCardRecord }): void {
63
68
  emit(payload.action, payload.row)
64
69
  }
70
+
71
+ function changePage(page: number): void {
72
+ emit('page-change', page)
73
+ }
74
+
75
+ function changePageSize(size: number): void {
76
+ emit('page-size-change', size)
77
+ }
78
+
79
+ function changeSort(sort: { key: string, direction: string }): void {
80
+ emit('sort', sort)
81
+ }
65
82
  </script>
66
83
 
67
84
  {{--
68
85
  No `searchable` or `filterable`: the parent dashboard owns the search box
69
- and the filter selects. Table pages the whole filtered list the parent passes.
86
+ and the filter selects, and the server pages and sorts what they match.
70
87
  --}}
71
88
  <Table
72
89
  :sort-reset-key="sortResetKey()"
73
- :page-reset-key="pageResetKey()"
74
90
  :columns="COLUMNS"
75
91
  :data="rows()"
76
92
  :loading="loading()"
77
93
  :row-actions="ROW_ACTIONS"
78
94
  action-label-key="code"
79
95
  paginated
80
- :page-size="20"
96
+ manual-pagination
97
+ manual-sort
98
+ :total="total()"
99
+ :current-page="currentPage()"
100
+ :page-size="perPage()"
81
101
  empty-title="No gift cards found"
82
102
  empty-description="Adjust the filters or add a native GiftCard record."
83
103
  @row-action="handleRowAction"
104
+ @page-change="changePage"
105
+ @page-size-change="changePageSize"
106
+ @sort="changeSort"
84
107
  />