@stacksjs/defaults 0.75.489 → 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 (153) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +20 -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/ProductUnitIndexAction.ts +23 -19
  28. package/app/Actions/Dashboard/Commerce/ProductVariantIndexAction.ts +25 -18
  29. package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
  30. package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
  31. package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
  32. package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
  33. package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
  34. package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
  35. package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
  36. package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
  37. package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
  38. package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
  39. package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
  40. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
  41. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
  42. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
  43. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
  44. package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
  45. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
  46. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
  47. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
  48. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
  49. package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
  50. package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
  51. package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
  52. package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
  53. package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
  54. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
  55. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
  56. package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
  57. package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
  58. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
  59. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
  60. package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
  61. package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
  62. package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.test.ts +146 -0
  63. package/app/Actions/Dashboard/Commerce/commerce-product-unit-list.ts +178 -0
  64. package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.test.ts +165 -0
  65. package/app/Actions/Dashboard/Commerce/commerce-product-variant-list.ts +209 -0
  66. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
  67. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
  68. package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
  69. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
  70. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
  71. package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
  72. package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
  73. package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
  74. package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
  75. package/app/Actions/Dashboard/Commerce/product-unit-records.test.ts +0 -13
  76. package/app/Actions/Dashboard/Commerce/product-unit-records.ts +0 -17
  77. package/app/Actions/Dashboard/Commerce/product-variant-records.test.ts +0 -13
  78. package/app/Actions/Dashboard/Commerce/product-variant-records.ts +0 -17
  79. package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
  80. package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
  81. package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
  82. package/app/Actions/Dashboard/Content/content-list.ts +10 -0
  83. package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
  84. package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
  85. package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
  86. package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
  87. package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
  88. package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
  89. package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
  90. package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
  91. package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
  92. package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
  93. package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
  94. package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
  95. package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
  96. package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
  97. package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +5 -3
  98. package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
  99. package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
  100. package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
  101. package/app/Actions/Dashboard/named-search.test.ts +36 -0
  102. package/app/Actions/Dashboard/named-search.ts +80 -0
  103. package/app/Models/Request.ts +4 -2
  104. package/functions/commerce/shippings/dashboard-resource.ts +12 -1
  105. package/functions/commerce/shippings/delivery-routes.ts +1 -0
  106. package/functions/commerce/shippings/license-keys.ts +1 -0
  107. package/functions/dashboard-list.test.ts +146 -1
  108. package/functions/dashboard-list.ts +216 -1
  109. package/functions/queue.ts +2 -0
  110. package/ide/vscode/package.json +1 -1
  111. package/package.json +2 -2
  112. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
  113. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
  114. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
  115. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
  116. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
  117. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
  118. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
  119. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
  120. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
  121. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
  122. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
  123. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
  124. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
  125. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
  126. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
  127. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
  128. package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +63 -8
  129. package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +48 -60
  130. package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +29 -3
  131. package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +57 -3
  132. package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +59 -61
  133. package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +28 -2
  134. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
  135. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
  136. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
  137. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
  138. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
  139. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
  140. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
  141. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
  142. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
  143. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
  144. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
  145. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
  146. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
  147. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
  148. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
  149. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
  150. package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
  151. package/resources/components/Dashboard/Queue/QueueDashboard.stx +7 -1
  152. package/routes/dashboard-api.ts +11 -0
  153. package/views/dashboard/stores/kanban.ts +38 -6
@@ -26,9 +26,14 @@ interface LicenseKeyRow {
26
26
 
27
27
  const licenseKeys = useReactiveProp('license-keys', [] as LicenseKeyRow[])
28
28
  const loading = useReactiveProp('loading', false)
29
- /** The parent's search: a change returns to the first page. */
30
- const pageResetKey = useReactiveProp<unknown>('pageResetKey', '')
31
- const emit = defineEmits(['edit', 'delete'])
29
+ /**
30
+ * The server pages and sorts what the parent's search matches
31
+ * (stacksjs/stacks#3218): how many keys match, the page shown and its size.
32
+ */
33
+ const total = useReactiveProp('total', 0)
34
+ const currentPage = useReactiveProp('currentPage', 1)
35
+ const perPage = useReactiveProp('perPage', 25)
36
+ const emit = defineEmits(['edit', 'delete', 'page-change', 'page-size-change', 'sort'])
32
37
 
33
38
  const COLUMNS = [
34
39
  { key: 'key', label: 'Key', sortable: true, class: 'font-medium font-mono text-stone-800 whitespace-nowrap dark:text-white' },
@@ -69,23 +74,41 @@ const rows = derived(() => licenseKeys().map(licenseKey => ({
69
74
  function handleRowAction(payload: { action: string, row: LicenseKeyRow }): void {
70
75
  emit(payload.action, payload.row)
71
76
  }
77
+
78
+ function changePage(page: number): void {
79
+ emit('page-change', page)
80
+ }
81
+
82
+ function changePageSize(size: number): void {
83
+ emit('page-size-change', size)
84
+ }
85
+
86
+ function changeSort(sort: { key: string, direction: string }): void {
87
+ emit('sort', sort)
88
+ }
72
89
  </script>
73
90
 
74
91
  {{--
75
- No `searchable` or `filterable`: the parent dashboard owns the search box.
76
- Table pages the whole filtered list the parent passes, and stays mounted
77
- while it loads.
92
+ No `searchable` or `filterable`: the parent dashboard owns the search box,
93
+ and the server pages and sorts what it matches. The table stays mounted
94
+ while a page loads.
78
95
  --}}
79
96
  <Table
80
- :page-reset-key="pageResetKey()"
81
97
  :columns="COLUMNS"
82
98
  :data="rows()"
83
99
  :loading="loading()"
84
100
  :row-actions="ROW_ACTIONS"
85
101
  action-label-key="actionName"
86
102
  paginated
87
- :page-size="10"
103
+ manual-pagination
104
+ manual-sort
105
+ :total="total()"
106
+ :current-page="currentPage()"
107
+ :page-size="perPage()"
88
108
  empty-title="No license keys found"
89
109
  empty-description="Add a license key, or adjust the search."
90
110
  @row-action="handleRowAction"
111
+ @page-change="changePage"
112
+ @page-size-change="changePageSize"
113
+ @sort="changeSort"
91
114
  />
@@ -1,6 +1,5 @@
1
1
  <script client>
2
- import type { PrintLogRecord } from '../../../../app/Actions/Dashboard/Commerce/print-log-records'
3
- import { printLogTimestamp } from '../../../../app/Actions/Dashboard/Commerce/print-log-records'
2
+ import type { PrintLogBreakdown } from '../../../../app/Actions/Dashboard/Commerce/commerce-print-log-list'
4
3
 
5
4
  interface CountRow {
6
5
  key: string
@@ -8,28 +7,33 @@ interface CountRow {
8
7
  percentage: number
9
8
  }
10
9
 
11
- const records = useReactiveProp('records', [] as PrintLogRecord[])
10
+ // Counted by the server over every log the search and filters match
11
+ // (stacksjs/stacks#3218); this used to count the twenty rows on the page.
12
+ const breakdown = useReactiveProp('breakdown', { printers: [], statuses: [], slots: [] } as PrintLogBreakdown)
12
13
 
13
14
  function countRows(field: 'printer' | 'status'): CountRow[] {
14
- const counts = new Map<string, number>()
15
- for (const record of records()) {
16
- const key = record[field] || 'Unknown'
17
- counts.set(key, (counts.get(key) || 0) + 1)
18
- }
19
- const total = records().length
20
- return [...counts.entries()]
21
- .map(([key, count]) => ({ key, count, percentage: total ? Math.round((count / total) * 1000) / 10 : 0 }))
22
- .sort((left, right) => right.count - left.count || left.key.localeCompare(right.key))
15
+ const counts = field === 'printer' ? breakdown().printers : breakdown().statuses
16
+ const total = counts.reduce((sum, row) => sum + row.count, 0)
17
+ return counts.map(row => ({
18
+ key: row.key,
19
+ count: row.count,
20
+ percentage: total ? Math.round((row.count / total) * 1000) / 10 : 0,
21
+ }))
23
22
  }
24
23
 
24
+ /**
25
+ * Logs by local hour of the day. Each slot is a UTC day and quarter hour, so
26
+ * its own instant says which local hour it falls in, with the offset that
27
+ * applied that day, daylight saving included.
28
+ */
25
29
  function hourlyRows(): CountRow[] {
26
30
  const counts = new Map<number, number>()
27
- for (const record of records()) {
28
- const timestamp = printLogTimestamp(record.timestamp)
29
- if (!timestamp)
31
+ for (const slot of breakdown().slots) {
32
+ const instant = Date.parse(`${slot.day}T00:00:00.000Z`) + slot.quarter * 15 * 60_000
33
+ if (!Number.isFinite(instant))
30
34
  continue
31
- const hour = new Date(timestamp).getHours()
32
- counts.set(hour, (counts.get(hour) || 0) + 1)
35
+ const hour = new Date(instant).getHours()
36
+ counts.set(hour, (counts.get(hour) || 0) + slot.count)
33
37
  }
34
38
  const max = Math.max(0, ...counts.values())
35
39
  return [...counts.entries()]
@@ -1,14 +1,13 @@
1
1
  <script client>
2
+ import type { PrintLogBreakdown } from '../../../../app/Actions/Dashboard/Commerce/commerce-print-log-list'
2
3
  import type { PrintLogRecord, PrintLogSummary } from '../../../../app/Actions/Dashboard/Commerce/print-log-records'
3
- import {
4
- printLogsToCsv,
5
- } from '../../../../app/Actions/Dashboard/Commerce/print-log-records'
6
4
  import { dashboardApi } from '../../../../functions/dashboard-api'
7
5
  import { pushToast } from '../../../../functions/toasts'
8
6
 
9
7
  interface PrintLogsResponse {
10
8
  records: PrintLogRecord[]
11
9
  summary: PrintLogSummary
10
+ breakdown: PrintLogBreakdown
12
11
  pagination: {
13
12
  page: number
14
13
  perPage: number
@@ -32,6 +31,7 @@ const summary = state<PrintLogSummary>({
32
31
  averagePages: 0,
33
32
  averageSuccessfulDuration: 0,
34
33
  })
34
+ const breakdown = state<PrintLogBreakdown>({ printers: [], statuses: [], slots: [] })
35
35
  const printerOptions = state<string[]>([])
36
36
  const statusOptions = state<string[]>([])
37
37
  const search = state('')
@@ -66,19 +66,28 @@ function metricCards(): Array<{ label: string, value: string, detail: string }>
66
66
  const current = summary()
67
67
  const warningLabel = current.warnings === 1 ? 'warning' : 'warnings'
68
68
  return [
69
- { label: 'Print jobs', value: String(current.total), detail: 'On the current page' },
69
+ { label: 'Print jobs', value: String(current.total), detail: 'Matching the current filters' },
70
70
  { label: 'Success rate', value: `${current.successRate}%`, detail: `${current.failed} failed, ${current.warnings} ${warningLabel}` },
71
71
  { label: 'Pages', value: String(current.totalPages), detail: `${current.averagePages} average per job` },
72
72
  { label: 'Successful duration', value: `${current.averageSuccessfulDuration}s`, detail: 'Average completed print time' },
73
73
  ]
74
74
  }
75
75
 
76
- function exportHref(): string {
77
- return `data:text/csv;charset=utf-8,${encodeURIComponent(`\uFEFF${printLogsToCsv(records())}`)}`
76
+ /** The search, filters and order as query parameters, without the page. */
77
+ function filterParams(): URLSearchParams {
78
+ const params = new URLSearchParams({ range: timeRange(), sort: sort() })
79
+ if (search().trim())
80
+ params.set('search', search().trim())
81
+ if (printerFilter() !== 'all')
82
+ params.set('printer', printerFilter())
83
+ if (statusFilter() !== 'all')
84
+ params.set('status', statusFilter())
85
+ return params
78
86
  }
79
87
 
80
- function exportFilename(): string {
81
- return `print-logs-${new Date().toISOString().slice(0, 10)}.csv`
88
+ /** Every matching log as CSV, built by the server, not just the page shown. */
89
+ function exportHref(): string {
90
+ return `/api/dashboard/commerce/print-logs/export?${filterParams()}`
82
91
  }
83
92
 
84
93
  function reloadFilters(): void {
@@ -91,24 +100,16 @@ async function loadPrintLogs(): Promise<void> {
91
100
  loading.set(true)
92
101
  loadError.set('')
93
102
  try {
94
- const params = new URLSearchParams({
95
- page: String(page()),
96
- per_page: String(pageSize),
97
- range: timeRange(),
98
- sort: sort(),
99
- })
100
- if (search().trim())
101
- params.set('search', search().trim())
102
- if (printerFilter() !== 'all')
103
- params.set('printer', printerFilter())
104
- if (statusFilter() !== 'all')
105
- params.set('status', statusFilter())
103
+ const params = filterParams()
104
+ params.set('page', String(page()))
105
+ params.set('per_page', String(pageSize))
106
106
 
107
107
  const data = await dashboardApi<PrintLogsResponse>(`/api/dashboard/commerce/print-logs?${params}`)
108
108
  if (sequence !== loadSequence)
109
109
  return
110
110
  records.set(Array.isArray(data.records) ? data.records : [])
111
111
  summary.set(data.summary)
112
+ breakdown.set(data.breakdown ?? { printers: [], statuses: [], slots: [] })
112
113
  printerOptions.set(Array.isArray(data.options?.printers) ? data.options.printers : [])
113
114
  statusOptions.set(Array.isArray(data.options?.statuses) ? data.options.statuses : [])
114
115
  total.set(Number(data.pagination?.total) || 0)
@@ -192,7 +193,7 @@ onMount(() => {
192
193
  <PageHeader title="Print logs" description="Inspect native Receipt records from configured print devices.">
193
194
  <div class="flex flex-wrap gap-2">
194
195
  <Button variant="secondary" :loading="loading()" @click="loadPrintLogs"><span :if="!loading()" class="h-4 w-4 i-hugeicons-refresh"></span>Refresh</Button>
195
- <Button tag="a" :href="exportHref()" :download="exportFilename()"><span class="h-4 w-4 i-hugeicons-download-04"></span>Export current page</Button>
196
+ <Button tag="a" :href="exportHref()" download><span class="h-4 w-4 i-hugeicons-download-04"></span>Export filtered</Button>
196
197
  </div>
197
198
  </PageHeader>
198
199
 
@@ -200,7 +201,7 @@ onMount(() => {
200
201
 
201
202
  <MetricCards label="Print log metrics" columns="grid-cols-2 lg:grid-cols-4" :items="metricCards()" />
202
203
 
203
- <PrintLogBreakdown :records="records()" />
204
+ <PrintLogBreakdown :breakdown="breakdown()" />
204
205
 
205
206
  <section class="space-y-3">
206
207
  <div class="grid gap-3 grid-cols-1 sm:grid-cols-2 xl:grid-cols-6">
@@ -1,19 +1,31 @@
1
1
  <script client>
2
- import type { ProductWaitlistOptions, ProductWaitlistRecord, ProductWaitlistSummary, ProductWaitlistWritePayload } from '../../../../app/Actions/Dashboard/Commerce/product-waitlist-records'
2
+ import type { ProductWaitlistRecord, ProductWaitlistSummary, ProductWaitlistWritePayload } from '../../../../app/Actions/Dashboard/Commerce/product-waitlist-records'
3
3
  import { DashboardApiError, dashboardApi } from '../../../../functions/dashboard-api'
4
4
  import { pushToast } from '../../../../functions/toasts'
5
5
 
6
6
  interface ProductWaitlistResponse {
7
7
  records: ProductWaitlistRecord[]
8
+ total: number
9
+ page: number
10
+ perPage: number
8
11
  summary: ProductWaitlistSummary
9
- options: ProductWaitlistOptions
10
12
  }
11
13
 
12
14
  const records = state<ProductWaitlistRecord[]>([])
13
15
  const summary = state<ProductWaitlistSummary>({ total: 0, waiting: 0, notified: 0, purchased: 0, conversionRate: 0 })
14
- const options = state<ProductWaitlistOptions>({ products: [], customers: [] })
16
+ /** Whether any product exists, so an entry can be added at all. */
17
+ const hasProducts = state(true)
15
18
  const search = state('')
16
19
  const status = state('all')
20
+ // The server searches, filters, sorts and pages (stacksjs/stacks#3218), where
21
+ // this page used to do all of that with the newest 500.
22
+ const matchingTotal = state(0)
23
+ const page = state(1)
24
+ const perPage = state(25)
25
+ const appliedSearch = state('')
26
+ const headerSort = state<{ sort: string, direction: string } | null>(null)
27
+ let listRequest = 0
28
+ let searchTimer: ReturnType<typeof setTimeout> | null = null
17
29
  const isLoading = state(true)
18
30
  const loadError = state('')
19
31
  const entryDialogOpen = state(false)
@@ -31,15 +43,19 @@ const metrics = derived(() => [
31
43
  { label: 'Conversion', value: `${summary().conversionRate}%` },
32
44
  ])
33
45
 
34
- function rows(): ProductWaitlistRecord[] {
35
- const query = search().trim().toLowerCase()
36
- return records().filter((record) => {
37
- if (status() !== 'all' && record.status !== status())
38
- return false
39
- const productName = options().products.find(option => option.id === record.productId)?.label || ''
40
- return !query || [record.name, record.email, record.phone, record.source, productName, record.productId]
41
- .some(value => value.toLowerCase().includes(query))
42
- })
46
+ /** The table's sortable columns, as the server's sort names. */
47
+ const COLUMN_SORTS: Record<string, string> = {
48
+ name: 'name',
49
+ productName: 'product',
50
+ quantity: 'quantity',
51
+ status: 'status',
52
+ notificationPreference: 'preference',
53
+ createdAt: 'created',
54
+ }
55
+
56
+ function matchingLabel(): string {
57
+ const count = matchingTotal()
58
+ return `${count} matching ${count === 1 ? 'entry' : 'entries'}`
43
59
  }
44
60
 
45
61
  function openAddDialog(): void {
@@ -74,25 +90,105 @@ function closeDeleteDialog(): void {
74
90
  }
75
91
 
76
92
  async function loadRecords(): Promise<void> {
93
+ const request = ++listRequest
77
94
  isLoading.set(true)
78
95
  loadError.set('')
79
96
  try {
80
- const result = await dashboardApi<ProductWaitlistResponse>('/api/dashboard/commerce/waitlist-products')
97
+ const params = new URLSearchParams()
98
+ const order = headerSort() ?? { sort: 'created', direction: 'desc' }
99
+ params.set('sort', order.sort)
100
+ params.set('direction', order.direction)
101
+ if (appliedSearch())
102
+ params.set('q', appliedSearch())
103
+ if (status() !== 'all')
104
+ params.set('status', status())
105
+ params.set('page', String(page()))
106
+ params.set('per_page', String(perPage()))
107
+ const result = await dashboardApi<ProductWaitlistResponse>(`/api/dashboard/commerce/waitlist-products?${params}`)
108
+ // Only the newest request lands.
109
+ if (request !== listRequest)
110
+ return
81
111
  records.set(Array.isArray(result.records) ? result.records : [])
112
+ matchingTotal.set(Number(result.total) || 0)
113
+ page.set(Number(result.page) || 1)
82
114
  summary.set(result.summary ?? { total: 0, waiting: 0, notified: 0, purchased: 0, conversionRate: 0 })
83
- options.set(result.options ?? { products: [], customers: [] })
84
115
  }
85
116
  catch (error) {
117
+ if (request !== listRequest)
118
+ return
86
119
  loadError.set('Product waitlist records could not be loaded.')
87
120
  pushToast('error', 'Could not load product waitlist', {
88
121
  detail: error instanceof Error ? error.message : String(error),
89
122
  })
90
123
  }
91
124
  finally {
92
- isLoading.set(false)
125
+ if (request === listRequest)
126
+ isLoading.set(false)
127
+ }
128
+ }
129
+
130
+ /** Whether there is any product to make an entry for: one choice is enough to know. */
131
+ async function loadHasProducts(): Promise<void> {
132
+ try {
133
+ const result = await dashboardApi<{ total?: number }>('/api/dashboard/commerce/product-choices?limit=1')
134
+ hasProducts.set(Number(result.total) > 0)
135
+ }
136
+ catch {
137
+ // Unknown: leave Add enabled, and the dialog says when nothing matches.
138
+ hasProducts.set(true)
93
139
  }
94
140
  }
95
141
 
142
+ function eventValue<T>(value: T | CustomEvent<T>): T {
143
+ return value instanceof CustomEvent ? value.detail : value
144
+ }
145
+
146
+ function changePage(value: number | CustomEvent<number>): void {
147
+ page.set(Number(eventValue(value)) || 1)
148
+ void loadRecords()
149
+ }
150
+
151
+ function changePageSize(value: number | CustomEvent<number>): void {
152
+ perPage.set(Number(eventValue(value)) || 25)
153
+ page.set(1)
154
+ void loadRecords()
155
+ }
156
+
157
+ function changeColumnSort(value: { key: string, direction: string } | CustomEvent<{ key: string, direction: string }>): void {
158
+ const column = eventValue(value)
159
+ const serverSort = COLUMN_SORTS[column.key]
160
+ headerSort.set(serverSort ? { sort: serverSort, direction: column.direction === 'asc' ? 'asc' : 'desc' } : null)
161
+ page.set(1)
162
+ void loadRecords()
163
+ }
164
+
165
+ // The status filter asks the server for page 1 when it changes, and the
166
+ // search once typing pauses.
167
+ let shownStatus = status()
168
+ effect(() => {
169
+ const current = status()
170
+ if (current === shownStatus)
171
+ return
172
+ shownStatus = current
173
+ page.set(1)
174
+ void loadRecords()
175
+ })
176
+
177
+ let shownSearch = search().trim()
178
+ effect(() => {
179
+ const term = search().trim()
180
+ if (term === shownSearch)
181
+ return
182
+ shownSearch = term
183
+ if (searchTimer)
184
+ clearTimeout(searchTimer)
185
+ searchTimer = setTimeout(() => {
186
+ appliedSearch.set(term)
187
+ page.set(1)
188
+ void loadRecords()
189
+ }, 250)
190
+ })
191
+
96
192
  async function saveRecord(payload: ProductWaitlistWritePayload): Promise<void> {
97
193
  const current = editingRecord()
98
194
  const isEditing = entryDialogMode() === 'edit' && current !== null
@@ -146,6 +242,7 @@ async function deleteSelectedRecord(): Promise<void> {
146
242
 
147
243
  onMount(() => {
148
244
  void loadRecords()
245
+ void loadHasProducts()
149
246
  })
150
247
  </script>
151
248
 
@@ -156,7 +253,7 @@ onMount(() => {
156
253
  <span :if="!isLoading()" class="h-4 w-4 i-hugeicons-refresh"></span>
157
254
  Refresh
158
255
  </Button>
159
- <Button :disabled="isLoading() || options().products.length === 0" @click="openAddDialog()">
256
+ <Button :disabled="isLoading() || !hasProducts()" @click="openAddDialog()">
160
257
  <span class="h-4 w-4 i-hugeicons-add-01"></span>
161
258
  Add entry
162
259
  </Button>
@@ -164,7 +261,7 @@ onMount(() => {
164
261
  </PageHeader>
165
262
 
166
263
  <div :if="loadError()" class="p-4 text-red-700 text-sm dark:text-red-300 bg-red-50 dark:bg-red-950/30 border border-red-200 rounded-lg dark:border-red-900">{{ loadError() }}</div>
167
- <div :if="!isLoading() && options().products.length === 0" class="p-4 text-amber-800 text-sm dark:text-amber-200 bg-amber-50 dark:bg-amber-950/30 border border-amber-200 rounded-lg dark:border-amber-900">
264
+ <div :if="!isLoading() && !hasProducts()" class="p-4 text-amber-800 text-sm dark:text-amber-200 bg-amber-50 dark:bg-amber-950/30 border border-amber-200 rounded-lg dark:border-amber-900">
168
265
  Add a product before creating a product waitlist entry.
169
266
  </div>
170
267
 
@@ -181,7 +278,7 @@ onMount(() => {
181
278
  <div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
182
279
  <div>
183
280
  <h2 class="font-semibold text-gray-900 dark:text-white">Waitlist entries</h2>
184
- <p class="mt-1 text-gray-500 text-sm dark:text-neutral-400">Up to 200 recent records from the application model.</p>
281
+ <p class="mt-1 text-gray-500 text-sm dark:text-neutral-400">{{ matchingLabel() }}</p>
185
282
  </div>
186
283
  <div class="flex gap-2">
187
284
  <label class="sr-only" for="waitlist-status">Status</label>
@@ -197,7 +294,7 @@ onMount(() => {
197
294
  </div>
198
295
  </div>
199
296
 
200
- <ProductWaitlistTable :records="rows()" :options="options()" :loading="isLoading()" @edit="openEditDialog" @delete="openDeleteDialog" />
297
+ <ProductWaitlistTable :records="records()" :total="matchingTotal()" :current-page="page()" :per-page="perPage()" :loading="isLoading()" @edit="openEditDialog" @delete="openDeleteDialog" @page-change="changePage" @page-size-change="changePageSize" @sort="changeColumnSort" />
201
298
  </section>
202
299
  </div>
203
300
 
@@ -205,7 +302,6 @@ onMount(() => {
205
302
  :open="entryDialogOpen()"
206
303
  :mode="entryDialogMode()"
207
304
  :record="editingRecord()"
208
- :options="options()"
209
305
  :busy="isSaving()"
210
306
  :errors="validationErrors()"
211
307
  @submit="saveRecord"
@@ -1,5 +1,7 @@
1
1
  <script client>
2
- import type { ProductWaitlistOptions, ProductWaitlistRecord, ProductWaitlistWritePayload } from '../../../../app/Actions/Dashboard/Commerce/product-waitlist-records'
2
+ import type { CustomerChoice, ProductChoice } from '../../../../app/Actions/Dashboard/Commerce/commerce-choice-records'
3
+ import type { ProductWaitlistRecord, ProductWaitlistWritePayload } from '../../../../app/Actions/Dashboard/Commerce/product-waitlist-records'
4
+ import { dashboardApi } from '../../../../functions/dashboard-api'
3
5
  import { formErrorMessages } from '../../../../functions/dashboard-form'
4
6
 
5
7
  type DialogMode = 'add' | 'edit'
@@ -7,10 +9,6 @@ type DialogMode = 'add' | 'edit'
7
9
  const open = useReactiveProp('open', false)
8
10
  const mode = useReactiveProp('mode', 'add' as DialogMode)
9
11
  const record = useReactiveProp('record', null as ProductWaitlistRecord | null)
10
- const options = useReactiveProp('options', {
11
- products: [],
12
- customers: [],
13
- } as ProductWaitlistOptions)
14
12
  const busy = useReactiveProp('busy', false)
15
13
  const errors = useReactiveProp('errors', {} as Record<string, string>)
16
14
  const emit = defineEmits(['submit', 'close'])
@@ -27,6 +25,84 @@ const notes = state('')
27
25
  const status = state<ProductWaitlistWritePayload['status']>('waiting')
28
26
  let lastSync = ''
29
27
 
28
+ // The product and customer choices are server searches (stacksjs/stacks#3218):
29
+ // this used to be handed the first 500 of each by name, so an entry could not
30
+ // be made for a product or customer past the 500th.
31
+ const productChoices = state<ProductChoice[]>([])
32
+ const productMatches = state(0)
33
+ const productQuery = state('')
34
+ const customerChoices = state<CustomerChoice[]>([])
35
+ const customerMatches = state(0)
36
+ const customerQuery = state('')
37
+ const requests = { products: 0, customers: 0 }
38
+ const timers: Record<'products' | 'customers', ReturnType<typeof setTimeout> | null> = { products: null, customers: null }
39
+
40
+ async function loadChoices(kind: 'products' | 'customers', term: string): Promise<void> {
41
+ const request = ++requests[kind]
42
+ const params = new URLSearchParams()
43
+ if (term)
44
+ params.set('q', term)
45
+ const path = kind === 'products' ? '/api/dashboard/commerce/product-choices' : '/api/dashboard/commerce/customer-choices'
46
+ try {
47
+ const data = await dashboardApi<{ choices?: Array<ProductChoice & Partial<CustomerChoice>>, total?: number }>(`${path}${term ? `?${params}` : ''}`)
48
+ if (request !== requests[kind])
49
+ return
50
+ const choices = Array.isArray(data.choices) ? data.choices : []
51
+ if (kind === 'products') {
52
+ productChoices.set(choices)
53
+ productMatches.set(data.total ?? choices.length)
54
+ }
55
+ else {
56
+ customerChoices.set(choices as CustomerChoice[])
57
+ customerMatches.set(data.total ?? choices.length)
58
+ }
59
+ }
60
+ catch {
61
+ // Soft-fail: the entry's own product and customer stay selectable.
62
+ if (request !== requests[kind])
63
+ return
64
+ if (kind === 'products') {
65
+ productChoices.set([])
66
+ productMatches.set(0)
67
+ }
68
+ else {
69
+ customerChoices.set([])
70
+ customerMatches.set(0)
71
+ }
72
+ }
73
+ }
74
+
75
+ function searchSoon(kind: 'products' | 'customers'): void {
76
+ const timer = timers[kind]
77
+ if (timer)
78
+ clearTimeout(timer)
79
+ timers[kind] = setTimeout(() => {
80
+ void loadChoices(kind, (kind === 'products' ? productQuery() : customerQuery()).trim())
81
+ }, 250)
82
+ }
83
+
84
+ /** The choices to show: the search results, with the entry's own product kept in. */
85
+ const products = derived((): ProductChoice[] => {
86
+ const found = productChoices()
87
+ const entry = record()
88
+ if (!entry?.productId || found.some(choice => choice.id === entry.productId))
89
+ return found
90
+ return [{ id: entry.productId, label: entry.productName || `Product ${entry.productId}`, detail: '' }, ...found]
91
+ })
92
+
93
+ /** The choices to show: the search results, with the entry's own customer kept in. */
94
+ const customers = derived((): CustomerChoice[] => {
95
+ const found = customerChoices()
96
+ const entry = record()
97
+ if (!entry?.customerId || found.some(choice => choice.id === entry.customerId))
98
+ return found
99
+ return [{ id: entry.customerId, label: entry.name || `Customer ${entry.customerId}`, detail: entry.email, email: entry.email, phone: entry.phone }, ...found]
100
+ })
101
+
102
+ function moreLabel(shown: number, total: number, noun: string): string {
103
+ return total > shown ? `Showing ${shown} of ${total.toLocaleString()} matching ${noun}. Search to narrow it down.` : ''
104
+ }
105
+
30
106
  function relationId(value: number | string): number | null {
31
107
  if (value === '')
32
108
  return null
@@ -60,11 +136,15 @@ effect(() => {
60
136
 
61
137
  lastSync = signature
62
138
  reset(entry)
139
+ productQuery.set('')
140
+ customerQuery.set('')
141
+ void loadChoices('products', '')
142
+ void loadChoices('customers', '')
63
143
  })
64
144
 
65
145
  function hydrateCustomer(event: Event): void {
66
146
  const selectedId = (event.target as HTMLSelectElement).value
67
- const customer = options().customers.find(option => option.id === selectedId)
147
+ const customer = customers().find(option => option.id === selectedId)
68
148
  if (!customer)
69
149
  return
70
150
  if (!name().trim())
@@ -115,19 +195,27 @@ function errorMessages(): string[] {
115
195
  <div class="grid gap-4 sm:grid-cols-2 mt-6">
116
196
  <label class="block sm:col-span-2">
117
197
  <span class="block font-medium text-gray-900 text-sm dark:text-neutral-200">Product</span>
118
- <select x-model="productId" required class="block mt-2 px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-700 border border-gray-300 rounded-md dark:border-neutral-600">
198
+ <input x-model="productQuery" @input="searchSoon('products')" type="search" name="product_search" aria-label="Search products by name or id" placeholder="Search products by name or id" class="block mt-2 px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-700 border border-gray-300 rounded-md dark:border-neutral-600" />
199
+ </label>
200
+ <div class="sm:col-span-2 -mt-2">
201
+ <select x-model="productId" required aria-label="Product" class="block px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-700 border border-gray-300 rounded-md dark:border-neutral-600">
119
202
  <option value="">Select a product</option>
120
- <option :for="option in options().products" :value="option.id">{{ option.label }}{{ option.detail ? ' · ' + option.detail : '' }}</option>
203
+ <template :for="option in products()" :key="option.id"><option :value="option.id" :selected="option.id === String(productId())">{{ option.label }}{{ option.detail ? ' · ' + option.detail : '' }}</option></template>
121
204
  </select>
122
- </label>
205
+ <p :if="moreLabel(productChoices().length, productMatches(), 'products')" class="mt-1 text-gray-500 text-xs dark:text-neutral-400" :text="moreLabel(productChoices().length, productMatches(), 'products')"></p>
206
+ </div>
123
207
 
124
208
  <label class="block sm:col-span-2">
125
209
  <span class="block font-medium text-gray-900 text-sm dark:text-neutral-200">Existing customer</span>
126
- <select x-model="customerId" class="block mt-2 px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-700 border border-gray-300 rounded-md dark:border-neutral-600" @change="hydrateCustomer($event)">
210
+ <input x-model="customerQuery" @input="searchSoon('customers')" type="search" name="customer_search" aria-label="Search customers by name, email or phone" placeholder="Search customers by name, email or phone" class="block mt-2 px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-700 border border-gray-300 rounded-md dark:border-neutral-600" />
211
+ </label>
212
+ <div class="sm:col-span-2 -mt-2">
213
+ <select x-model="customerId" aria-label="Existing customer" class="block px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-700 border border-gray-300 rounded-md dark:border-neutral-600" @change="hydrateCustomer($event)">
127
214
  <option value="">No linked customer</option>
128
- <option :for="option in options().customers" :value="option.id">{{ option.label }}{{ option.detail ? ' · ' + option.detail : '' }}</option>
215
+ <template :for="option in customers()" :key="option.id"><option :value="option.id" :selected="option.id === String(customerId())">{{ option.label }}{{ option.detail ? ' · ' + option.detail : '' }}</option></template>
129
216
  </select>
130
- </label>
217
+ <p :if="moreLabel(customerChoices().length, customerMatches(), 'customers')" class="mt-1 text-gray-500 text-xs dark:text-neutral-400" :text="moreLabel(customerChoices().length, customerMatches(), 'customers')"></p>
218
+ </div>
131
219
 
132
220
  <label class="block">
133
221
  <span class="block font-medium text-gray-900 text-sm dark:text-neutral-200">Name</span>