@stacksjs/defaults 0.75.489 → 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 (137) 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/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 +5 -3
  88. package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
  89. package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
  90. package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
  91. package/app/Actions/Dashboard/named-search.test.ts +36 -0
  92. package/app/Actions/Dashboard/named-search.ts +80 -0
  93. package/app/Models/Request.ts +4 -2
  94. package/functions/commerce/shippings/dashboard-resource.ts +12 -1
  95. package/functions/commerce/shippings/delivery-routes.ts +1 -0
  96. package/functions/commerce/shippings/license-keys.ts +1 -0
  97. package/functions/dashboard-list.test.ts +132 -1
  98. package/functions/dashboard-list.ts +198 -1
  99. package/functions/queue.ts +2 -0
  100. package/ide/vscode/package.json +1 -1
  101. package/package.json +2 -2
  102. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
  103. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
  104. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
  105. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
  106. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
  107. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
  108. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
  109. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
  110. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
  111. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
  112. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
  113. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
  114. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
  115. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
  116. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
  117. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
  118. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
  119. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
  120. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
  121. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
  122. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
  123. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
  124. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
  125. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
  126. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
  127. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
  128. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
  129. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
  130. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
  131. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
  132. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
  133. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
  134. package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
  135. package/resources/components/Dashboard/Queue/QueueDashboard.stx +7 -1
  136. package/routes/dashboard-api.ts +11 -0
  137. package/views/dashboard/stores/kanban.ts +38 -6
@@ -7,10 +7,12 @@ import type {
7
7
  } from '../../../../app/Actions/Dashboard/Commerce/commerce-product-records'
8
8
  import { DashboardApiError, dashboardApi } from '../../../../functions/dashboard-api'
9
9
  import { pushToast } from '../../../../functions/toasts'
10
- import { minorToInput } from '@stacksjs/commerce/money'
11
10
 
12
11
  interface ProductIndexResponse {
13
12
  records: CommerceProductRecord[]
13
+ total: number
14
+ page: number
15
+ perPage: number
14
16
  summary: CommerceProductSummary
15
17
  categories: ProductOption[]
16
18
  manufacturers: ProductOption[]
@@ -33,6 +35,16 @@ const search = state('')
33
35
  const categoryFilter = state('all')
34
36
  const availabilityFilter = state('all')
35
37
  const sort = state('newest')
38
+ // The server's answer for the current search and filters
39
+ // (stacksjs/stacks#3218): it searches, filters, sorts and pages every product,
40
+ // where this page used to do all of that with the newest 500.
41
+ const matchingTotal = state(0)
42
+ const page = state(1)
43
+ const perPage = state(25)
44
+ const appliedSearch = state('')
45
+ const headerSort = state<{ sort: string, direction: string } | null>(null)
46
+ let listRequest = 0
47
+ let searchTimer: ReturnType<typeof setTimeout> | null = null
36
48
  const loading = state(true)
37
49
  const loadError = state('')
38
50
  const dialogOpen = state(false)
@@ -43,56 +55,42 @@ const saving = state(false)
43
55
  const deleting = state(false)
44
56
  const validationErrors = state<Record<string, string>>({})
45
57
 
46
- function timestamp(value: string): number {
47
- if (!value)
48
- return 0
49
- const normalized = /^\d{4}-\d{2}-\d{2} \d/.test(value)
50
- ? `${value.replace(' ', 'T')}Z`
51
- : value
52
- const result = new Date(normalized).getTime()
53
- return Number.isFinite(result) ? result : 0
58
+ /** The select's orders, as the server's sort and direction. */
59
+ const SELECT_SORTS: Record<string, { sort: string, direction: string }> = {
60
+ 'newest': { sort: 'created', direction: 'desc' },
61
+ 'oldest': { sort: 'created', direction: 'asc' },
62
+ 'name': { sort: 'name', direction: 'asc' },
63
+ 'price-high': { sort: 'price', direction: 'desc' },
64
+ 'price-low': { sort: 'price', direction: 'asc' },
65
+ 'inventory-high': { sort: 'inventory', direction: 'desc' },
54
66
  }
55
67
 
56
- function filteredRecords(): CommerceProductRecord[] {
57
- const query = search().trim().toLowerCase()
58
- const selectedCategory = categoryFilter()
59
- const selectedAvailability = availabilityFilter()
60
- return [...records()]
61
- .filter((record) => {
62
- if (selectedCategory !== 'all' && record.categoryId !== selectedCategory)
63
- return false
64
- if (selectedAvailability === 'available' && !record.isAvailable)
65
- return false
66
- if (selectedAvailability === 'unavailable' && record.isAvailable)
67
- return false
68
- if (selectedAvailability === 'out-of-stock' && record.inventoryCount !== 0)
69
- return false
70
- return !query || [
71
- record.id,
72
- record.name,
73
- record.description,
74
- record.categoryName,
75
- record.manufacturerName,
76
- ...record.allergens,
77
- ].some(value => value.toLowerCase().includes(query))
78
- })
79
- .sort((left, right) => {
80
- if (sort() === 'oldest')
81
- return timestamp(left.createdAt) - timestamp(right.createdAt)
82
- if (sort() === 'name')
83
- return left.name.localeCompare(right.name)
84
- if (sort() === 'price-high')
85
- return right.price - left.price || left.name.localeCompare(right.name)
86
- if (sort() === 'price-low')
87
- return left.price - right.price || left.name.localeCompare(right.name)
88
- if (sort() === 'inventory-high')
89
- return right.inventoryCount - left.inventoryCount || left.name.localeCompare(right.name)
90
- return timestamp(right.createdAt) - timestamp(left.createdAt) || Number(right.id) - Number(left.id)
91
- })
68
+ /** The table's sortable columns, as the server's sort names. */
69
+ const COLUMN_SORTS: Record<string, string> = {
70
+ nameLabel: 'name',
71
+ categoryName: 'category',
72
+ price: 'price',
73
+ inventoryCount: 'inventory',
74
+ availability: 'available',
75
+ }
76
+
77
+ /** The search, filters and order, as the query the server takes. */
78
+ function filterParams(): URLSearchParams {
79
+ const params = new URLSearchParams()
80
+ const order = headerSort() ?? SELECT_SORTS[sort()] ?? SELECT_SORTS.newest
81
+ params.set('sort', order.sort)
82
+ params.set('direction', order.direction)
83
+ if (appliedSearch())
84
+ params.set('q', appliedSearch())
85
+ if (categoryFilter() !== 'all')
86
+ params.set('category', categoryFilter())
87
+ if (availabilityFilter() !== 'all')
88
+ params.set('availability', availabilityFilter())
89
+ return params
92
90
  }
93
91
 
94
92
  function matchingLabel(): string {
95
- const count = filteredRecords().length
93
+ const count = matchingTotal()
96
94
  return `${count} matching ${count === 1 ? 'product' : 'products'}`
97
95
  }
98
96
 
@@ -107,63 +105,99 @@ function metricCards(): Array<{ label: string, value: string, detail: string }>
107
105
  ]
108
106
  }
109
107
 
108
+ /** Every matching product as CSV, built by the server, not just the page shown. */
110
109
  function exportHref(): string {
111
- const rows = filteredRecords().map(record => [
112
- record.id,
113
- record.name,
114
- record.description,
115
- // Stored as integer minor units; the CSV carries the decimal a person reads.
116
- minorToInput(record.price, defaultCurrency()),
117
- defaultCurrency(),
118
- record.isAvailable ? 'Available' : 'Unavailable',
119
- String(record.inventoryCount),
120
- String(record.preparationTime),
121
- record.categoryName,
122
- record.manufacturerName,
123
- record.allergens.join('; '),
124
- String(record.variantCount),
125
- String(record.unitCount),
126
- String(record.reviewCount),
127
- record.createdAt,
128
- ])
129
- const escape = (value: string): string => `"${value.replaceAll('"', '""')}"`
130
- const csv = [
131
- ['Product ID', 'Name', 'Description', 'Price', 'Currency', 'Availability', 'Inventory', 'Preparation minutes', 'Category', 'Manufacturer', 'Allergens', 'Variants', 'Units', 'Reviews', 'Created at'],
132
- ...rows,
133
- ].map(row => row.map(escape).join(',')).join('\n')
134
- return `data:text/csv;charset=utf-8,${encodeURIComponent(`\uFEFF${csv}`)}`
135
- }
136
-
137
- /**
138
- * What the table is showing: a change returns it to the first page, as this
139
- * page's own pager did before the table took over paging.
140
- */
141
- function viewKey(): string {
142
- return JSON.stringify([search(), categoryFilter(), availabilityFilter(), sort()])
110
+ return `/api/dashboard/commerce/products/export?${filterParams()}`
143
111
  }
144
112
 
145
113
  async function loadProducts(): Promise<void> {
114
+ const request = ++listRequest
146
115
  loading.set(true)
147
116
  loadError.set('')
148
117
  try {
149
- const data = await dashboardApi<ProductIndexResponse>('/api/dashboard/commerce/products')
118
+ const params = filterParams()
119
+ params.set('page', String(page()))
120
+ params.set('per_page', String(perPage()))
121
+ const data = await dashboardApi<ProductIndexResponse>(`/api/dashboard/commerce/products?${params}`)
122
+ // Only the newest request lands.
123
+ if (request !== listRequest)
124
+ return
150
125
  records.set(Array.isArray(data.records) ? data.records : [])
126
+ matchingTotal.set(Number(data.total) || 0)
127
+ page.set(Number(data.page) || 1)
151
128
  summary.set(data.summary ?? { ...emptySummary })
152
129
  categories.set(Array.isArray(data.categories) ? data.categories : [])
153
130
  manufacturers.set(Array.isArray(data.manufacturers) ? data.manufacturers : [])
154
131
  defaultCurrency.set(data.defaultCurrency || 'USD')
155
132
  }
156
133
  catch (error) {
134
+ if (request !== listRequest)
135
+ return
157
136
  loadError.set('Product records could not be loaded.')
158
137
  pushToast('error', 'Could not load products', {
159
138
  detail: error instanceof Error ? error.message : String(error),
160
139
  })
161
140
  }
162
141
  finally {
163
- loading.set(false)
142
+ if (request === listRequest)
143
+ loading.set(false)
164
144
  }
165
145
  }
166
146
 
147
+ function eventValue<T>(value: T | CustomEvent<T>): T {
148
+ return value instanceof CustomEvent ? value.detail : value
149
+ }
150
+
151
+ function changePage(value: number | CustomEvent<number>): void {
152
+ page.set(Number(eventValue(value)) || 1)
153
+ void loadProducts()
154
+ }
155
+
156
+ function changePageSize(value: number | CustomEvent<number>): void {
157
+ perPage.set(Number(eventValue(value)) || 25)
158
+ page.set(1)
159
+ void loadProducts()
160
+ }
161
+
162
+ function changeColumnSort(value: { key: string, direction: string } | CustomEvent<{ key: string, direction: string }>): void {
163
+ const column = eventValue(value)
164
+ const serverSort = COLUMN_SORTS[column.key]
165
+ headerSort.set(serverSort ? { sort: serverSort, direction: column.direction === 'asc' ? 'asc' : 'desc' } : null)
166
+ page.set(1)
167
+ void loadProducts()
168
+ }
169
+
170
+ // The filters and the select ask the server for page 1 when they change, and
171
+ // the search once typing pauses. A select change hands the order back from a
172
+ // column header.
173
+ let shownFilters = JSON.stringify([categoryFilter(), availabilityFilter(), sort()])
174
+ effect(() => {
175
+ const filters = JSON.stringify([categoryFilter(), availabilityFilter(), sort()])
176
+ if (filters === shownFilters)
177
+ return
178
+ const sortChanged = JSON.parse(shownFilters)[2] !== sort()
179
+ shownFilters = filters
180
+ if (sortChanged)
181
+ headerSort.set(null)
182
+ page.set(1)
183
+ void loadProducts()
184
+ })
185
+
186
+ let shownSearch = search().trim()
187
+ effect(() => {
188
+ const term = search().trim()
189
+ if (term === shownSearch)
190
+ return
191
+ shownSearch = term
192
+ if (searchTimer)
193
+ clearTimeout(searchTimer)
194
+ searchTimer = setTimeout(() => {
195
+ appliedSearch.set(term)
196
+ page.set(1)
197
+ void loadProducts()
198
+ }, 250)
199
+ })
200
+
167
201
  function openAdd(): void {
168
202
  dialogMode.set('add')
169
203
  editingRecord.set(null)
@@ -256,7 +290,7 @@ onMount(() => {
256
290
  <PageHeader title="Products" description="Manage native Product records, commerce availability, inventory, and relationships.">
257
291
  <div class="flex flex-wrap gap-2">
258
292
  <Button variant="secondary" :loading="loading()" @click="loadProducts()"><span :if="!loading()" class="h-4 w-4 i-hugeicons-refresh"></span>Refresh</Button>
259
- <Button tag="a" variant="secondary" :href="exportHref()" :download="'products-' + new Date().toISOString().slice(0, 10) + '.csv'"><span class="h-4 w-4 i-hugeicons-download-04"></span>Export filtered</Button>
293
+ <Button tag="a" variant="secondary" :href="exportHref()" download><span class="h-4 w-4 i-hugeicons-download-04"></span>Export filtered</Button>
260
294
  <Button @click="openAdd()"><span class="h-4 w-4 i-hugeicons-add-01"></span>Add product</Button>
261
295
  </div>
262
296
  </PageHeader>
@@ -281,7 +315,7 @@ onMount(() => {
281
315
  <p class="text-gray-500 text-sm dark:text-neutral-400">{{ matchingLabel() }}</p>
282
316
  </div>
283
317
 
284
- <CommerceProductsTable :sort-reset-key="sort()" :page-reset-key="viewKey()" :records="filteredRecords()" :loading="loading()" :currency="defaultCurrency()" @view="viewProduct" @edit="openEdit" @delete="openDelete" />
318
+ <CommerceProductsTable :sort-reset-key="sort()" :records="records()" :total="matchingTotal()" :current-page="page()" :per-page="perPage()" :loading="loading()" :currency="defaultCurrency()" @view="viewProduct" @edit="openEdit" @delete="openDelete" @page-change="changePage" @page-size-change="changePageSize" @sort="changeColumnSort" />
285
319
  </section>
286
320
  </div>
287
321
 
@@ -10,7 +10,13 @@ const sortResetKey = useReactiveProp<unknown>('sortResetKey', '')
10
10
  /** The parent's search and filters: a change returns to the first page. */
11
11
  const pageResetKey = useReactiveProp<unknown>('pageResetKey', '')
12
12
  const currency = useReactiveProp('currency', 'USD')
13
- const emit = defineEmits(['view', 'edit', 'delete'])
13
+ // One page the server chose (stacksjs/stacks#3218): it searches, filters, sorts
14
+ // and pages the products, so this shows them as given and hands paging and
15
+ // column sorting back to the parent.
16
+ const total = useReactiveProp('total', 0)
17
+ const currentPage = useReactiveProp('currentPage', 1)
18
+ const perPage = useReactiveProp('perPage', 25)
19
+ const emit = defineEmits(['view', 'edit', 'delete', 'page-change', 'page-size-change', 'sort'])
14
20
 
15
21
  function initials(name: string): string {
16
22
  return name.split(/\s+/).filter(Boolean).slice(0, 2).map(part => part[0]?.toUpperCase() || '').join('') || 'PR'
@@ -59,25 +65,43 @@ const rows = derived(() => records().map(record => ({
59
65
  function handleRowAction(payload: { action: string, row: CommerceProductRecord }): void {
60
66
  emit(payload.action, payload.row)
61
67
  }
68
+
69
+ function changePage(page: number): void {
70
+ emit('page-change', page)
71
+ }
72
+
73
+ function changePageSize(size: number): void {
74
+ emit('page-size-change', size)
75
+ }
76
+
77
+ function changeSort(sort: { key: string, direction: string }): void {
78
+ emit('sort', sort)
79
+ }
62
80
  </script>
63
81
 
64
82
  {{--
65
83
  No `searchable` or `filterable`: the parent dashboard owns the search box
66
- and the filter selects. Table pages the whole filtered list the parent passes.
84
+ and the filter selects, and the server pages and sorts what they match.
67
85
  --}}
68
86
  <Table
69
87
  :sort-reset-key="sortResetKey()"
70
- :page-reset-key="pageResetKey()"
71
88
  :columns="COLUMNS"
72
89
  :data="rows()"
73
90
  :loading="loading()"
74
91
  :row-actions="ROW_ACTIONS"
75
92
  action-label-key="nameLabel"
76
93
  paginated
77
- :page-size="10"
94
+ manual-pagination
95
+ manual-sort
96
+ :total="total()"
97
+ :current-page="currentPage()"
98
+ :page-size="perPage()"
78
99
  empty-title="No products found"
79
100
  empty-description="Adjust the filters or add a native Product record."
80
101
  @row-action="handleRowAction"
102
+ @page-change="changePage"
103
+ @page-size-change="changePageSize"
104
+ @sort="changeSort"
81
105
  >
82
106
  <template #cell="{ row, column }">
83
107
  <template :if="column.key === 'nameLabel'">
@@ -9,6 +9,9 @@ import { pushToast } from '../../../../functions/toasts'
9
9
 
10
10
  interface ReviewIndexResponse {
11
11
  records: ReviewRecord[]
12
+ total: number
13
+ page: number
14
+ perPage: number
12
15
  summary: ReviewSummary
13
16
  products: ReviewProductOption[]
14
17
  }
@@ -43,6 +46,15 @@ const productFilter = state('all')
43
46
  const ratingFilter = state('all')
44
47
  const moderationFilter = state('all')
45
48
  const sort = state('newest')
49
+ // The server searches, filters, sorts and pages (stacksjs/stacks#3218), where
50
+ // this page used to do all of that with the newest 500.
51
+ const matchingTotal = state(0)
52
+ const page = state(1)
53
+ const perPage = state(25)
54
+ const appliedSearch = state('')
55
+ const headerSort = state<{ sort: string, direction: string } | null>(null)
56
+ let listRequest = 0
57
+ let searchTimer: ReturnType<typeof setTimeout> | null = null
46
58
  const loading = state(true)
47
59
  const loadError = state('')
48
60
  const editingReview = state<ReviewRecord | null>(null)
@@ -52,66 +64,42 @@ const deleting = state(false)
52
64
  const busyId = state('')
53
65
  const validationErrors = state<Record<string, string>>({})
54
66
 
55
- function timestamp(value: string): number {
56
- if (!value)
57
- return 0
58
- const numeric = /^\d{10,13}$/.test(value)
59
- ? Number(value) * (value.length === 10 ? 1000 : 1)
60
- : Number.NaN
61
- if (Number.isFinite(numeric))
62
- return numeric
63
- const normalized = /^\d{4}-\d{2}-\d{2} \d/.test(value)
64
- ? `${value.replace(' ', 'T')}Z`
65
- : value
66
- const result = new Date(normalized).getTime()
67
- return Number.isFinite(result) ? result : 0
67
+ const SELECT_SORTS: Record<string, { sort: string, direction: string }> = {
68
+ 'newest': { sort: 'created', direction: 'desc' },
69
+ 'oldest': { sort: 'created', direction: 'asc' },
70
+ 'rating-high': { sort: 'rating', direction: 'desc' },
71
+ 'rating-low': { sort: 'rating', direction: 'asc' },
72
+ 'helpful': { sort: 'helpful', direction: 'desc' },
68
73
  }
69
74
 
70
- /** Rated reviews in `direction` order, unrated ones last either way. */
71
- function byRating(left: ReviewRecord, right: ReviewRecord, direction: 1 | -1): number {
72
- if (left.rating === null || right.rating === null)
73
- return Number(left.rating === null) - Number(right.rating === null)
74
- return (left.rating - right.rating) * direction
75
+ /** The table's sortable columns, as the server's sort names. */
76
+ const COLUMN_SORTS: Record<string, string> = {
77
+ customerLabel: 'customer',
78
+ productLabel: 'product',
79
+ rating: 'rating',
80
+ moderation: 'approved',
75
81
  }
76
82
 
77
- function filteredRecords(): ReviewRecord[] {
78
- const query = search().trim().toLowerCase()
79
- const product = productFilter()
80
- const rating = ratingFilter()
81
- const moderation = moderationFilter()
82
- return [...records()]
83
- .filter((review) => {
84
- if (product !== 'all' && review.productId !== product)
85
- return false
86
- if (rating !== 'all' && String(review.rating ?? 'none') !== rating)
87
- return false
88
- if (moderation === 'approved' && !review.approved)
89
- return false
90
- if (moderation === 'pending' && review.approved)
91
- return false
92
- if (moderation === 'featured' && !review.featured)
93
- return false
94
- if (moderation === 'verified' && !review.verifiedPurchase)
95
- return false
96
- return !query || [
97
- review.customerName,
98
- review.customerEmail,
99
- review.productName,
100
- review.title,
101
- review.content,
102
- ].some(value => value.toLowerCase().includes(query))
103
- })
104
- .sort((left, right) => {
105
- if (sort() === 'oldest')
106
- return timestamp(left.createdAt) - timestamp(right.createdAt)
107
- if (sort() === 'rating-high')
108
- return byRating(left, right, -1) || timestamp(right.createdAt) - timestamp(left.createdAt)
109
- if (sort() === 'rating-low')
110
- return byRating(left, right, 1) || timestamp(right.createdAt) - timestamp(left.createdAt)
111
- if (sort() === 'helpful')
112
- return right.helpfulVotes - left.helpfulVotes || timestamp(right.createdAt) - timestamp(left.createdAt)
113
- return timestamp(right.createdAt) - timestamp(left.createdAt)
114
- })
83
+ /** The search, filters and order, as the query the server takes. */
84
+ function filterParams(): URLSearchParams {
85
+ const params = new URLSearchParams()
86
+ const order = headerSort() ?? SELECT_SORTS[sort()] ?? SELECT_SORTS.newest
87
+ params.set('sort', order.sort)
88
+ params.set('direction', order.direction)
89
+ if (appliedSearch())
90
+ params.set('q', appliedSearch())
91
+ if (productFilter() !== 'all')
92
+ params.set('product', productFilter())
93
+ if (ratingFilter() !== 'all')
94
+ params.set('rating', ratingFilter())
95
+ if (moderationFilter() !== 'all')
96
+ params.set('moderation', moderationFilter())
97
+ return params
98
+ }
99
+
100
+ function matchingLabel(): string {
101
+ const count = matchingTotal()
102
+ return `${count} matching ${count === 1 ? 'review' : 'reviews'}`
115
103
  }
116
104
 
117
105
  function metricCards(): Array<{ label: string, value: string }> {
@@ -124,34 +112,92 @@ function metricCards(): Array<{ label: string, value: string }> {
124
112
  ]
125
113
  }
126
114
 
127
- /**
128
- * What the table is showing: a change returns it to the first page, as this
129
- * page's own pager did before the table took over paging.
130
- */
131
- function viewKey(): string {
132
- return JSON.stringify([search(), productFilter(), ratingFilter(), moderationFilter(), sort()])
133
- }
134
-
135
115
  async function loadReviews(): Promise<void> {
116
+ const request = ++listRequest
136
117
  loading.set(true)
137
118
  loadError.set('')
138
119
  try {
139
- const data = await dashboardApi<ReviewIndexResponse>('/api/dashboard/commerce/reviews')
120
+ const params = filterParams()
121
+ params.set('page', String(page()))
122
+ params.set('per_page', String(perPage()))
123
+ const data = await dashboardApi<ReviewIndexResponse>(`/api/dashboard/commerce/reviews?${params}`)
124
+ // Only the newest request lands.
125
+ if (request !== listRequest)
126
+ return
140
127
  records.set(Array.isArray(data.records) ? data.records : [])
128
+ matchingTotal.set(Number(data.total) || 0)
129
+ page.set(Number(data.page) || 1)
141
130
  summary.set(data.summary ?? { ...emptySummary })
142
131
  products.set(Array.isArray(data.products) ? data.products : [])
143
132
  }
144
133
  catch (error) {
134
+ if (request !== listRequest)
135
+ return
145
136
  loadError.set('Review records could not be loaded.')
146
137
  pushToast('error', 'Could not load reviews', {
147
138
  detail: error instanceof Error ? error.message : String(error),
148
139
  })
149
140
  }
150
141
  finally {
151
- loading.set(false)
142
+ if (request === listRequest)
143
+ loading.set(false)
152
144
  }
153
145
  }
154
146
 
147
+ function eventValue<T>(value: T | CustomEvent<T>): T {
148
+ return value instanceof CustomEvent ? value.detail : value
149
+ }
150
+
151
+ function changePage(value: number | CustomEvent<number>): void {
152
+ page.set(Number(eventValue(value)) || 1)
153
+ void loadReviews()
154
+ }
155
+
156
+ function changePageSize(value: number | CustomEvent<number>): void {
157
+ perPage.set(Number(eventValue(value)) || 25)
158
+ page.set(1)
159
+ void loadReviews()
160
+ }
161
+
162
+ function changeColumnSort(value: { key: string, direction: string } | CustomEvent<{ key: string, direction: string }>): void {
163
+ const column = eventValue(value)
164
+ const serverSort = COLUMN_SORTS[column.key]
165
+ headerSort.set(serverSort ? { sort: serverSort, direction: column.direction === 'asc' ? 'asc' : 'desc' } : null)
166
+ page.set(1)
167
+ void loadReviews()
168
+ }
169
+
170
+ // The filters and the select ask the server for page 1 when they change, and
171
+ // the search once typing pauses. A select change hands the order back from a
172
+ // column header.
173
+ let shownFilters = JSON.stringify([productFilter(), ratingFilter(), moderationFilter(), sort()])
174
+ effect(() => {
175
+ const filters = JSON.stringify([productFilter(), ratingFilter(), moderationFilter(), sort()])
176
+ if (filters === shownFilters)
177
+ return
178
+ const sortChanged = JSON.parse(shownFilters)[3] !== sort()
179
+ shownFilters = filters
180
+ if (sortChanged)
181
+ headerSort.set(null)
182
+ page.set(1)
183
+ void loadReviews()
184
+ })
185
+
186
+ let shownSearch = search().trim()
187
+ effect(() => {
188
+ const term = search().trim()
189
+ if (term === shownSearch)
190
+ return
191
+ shownSearch = term
192
+ if (searchTimer)
193
+ clearTimeout(searchTimer)
194
+ searchTimer = setTimeout(() => {
195
+ appliedSearch.set(term)
196
+ page.set(1)
197
+ void loadReviews()
198
+ }, 250)
199
+ })
200
+
155
201
  async function patchReview(review: ReviewRecord, payload: Record<string, unknown>, successMessage: string): Promise<void> {
156
202
  busyId.set(review.id)
157
203
  try {
@@ -320,7 +366,7 @@ onMount(() => {
320
366
 
321
367
  <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
322
368
  <p class="text-gray-500 text-sm dark:text-neutral-400">
323
- {{ filteredRecords().length }} matching {{ filteredRecords().length === 1 ? 'review' : 'reviews' }}
369
+ {{ matchingLabel() }}
324
370
  </p>
325
371
  <label class="flex gap-2 items-center text-gray-500 text-sm dark:text-neutral-400">
326
372
  Sort
@@ -336,14 +382,19 @@ onMount(() => {
336
382
 
337
383
  <CommerceReviewsTable
338
384
  :sort-reset-key="sort()"
339
- :page-reset-key="viewKey()"
340
- :reviews="filteredRecords()"
385
+ :reviews="records()"
386
+ :total="matchingTotal()"
387
+ :current-page="page()"
388
+ :per-page="perPage()"
341
389
  :loading="loading()"
342
390
  :busy-id="busyId()"
343
391
  @approve="toggleApproval"
344
392
  @feature="toggleFeatured"
345
393
  @edit="openEdit"
346
394
  @delete="openDelete"
395
+ @page-change="changePage"
396
+ @page-size-change="changePageSize"
397
+ @sort="changeColumnSort"
347
398
  />
348
399
 
349
400
  </section>
@@ -9,9 +9,14 @@ const loading = useReactiveProp('loading', false)
9
9
  const busyId = useReactiveProp('busyId', '')
10
10
  /** The parent's sort select: a change hands the order back from a header sort. */
11
11
  const sortResetKey = useReactiveProp<unknown>('sortResetKey', '')
12
- /** The parent's search and filters: a change returns to the first page. */
13
- const pageResetKey = useReactiveProp<unknown>('pageResetKey', '')
14
- const emit = defineEmits(['approve', 'feature', 'edit', 'delete'])
12
+ /**
13
+ * The server pages and sorts what the parent's search and filters match
14
+ * (stacksjs/stacks#3218): how many reviews match, the page shown and its size.
15
+ */
16
+ const total = useReactiveProp('total', 0)
17
+ const currentPage = useReactiveProp('currentPage', 1)
18
+ const perPage = useReactiveProp('perPage', 25)
19
+ const emit = defineEmits(['approve', 'feature', 'edit', 'delete', 'page-change', 'page-size-change', 'sort'])
15
20
 
16
21
  /** Epoch seconds or milliseconds as well as stored timestamps, as the API sends either. */
17
22
  function formatDate(value: string): string {
@@ -76,15 +81,26 @@ const rows = derived(() => reviews().map(review => ({
76
81
  function handleRowAction(payload: { action: string, row: ReviewRecord }): void {
77
82
  emit(payload.action, payload.row)
78
83
  }
84
+
85
+ function changePage(page: number): void {
86
+ emit('page-change', page)
87
+ }
88
+
89
+ function changePageSize(size: number): void {
90
+ emit('page-size-change', size)
91
+ }
92
+
93
+ function changeSort(sort: { key: string, direction: string }): void {
94
+ emit('sort', sort)
95
+ }
79
96
  </script>
80
97
 
81
98
  {{--
82
99
  No `searchable` or `filterable`: the parent dashboard owns the search box
83
- and the filter selects. Table pages the whole filtered list the parent passes.
100
+ and the filter selects, and the server pages and sorts what they match.
84
101
  --}}
85
102
  <Table
86
103
  :sort-reset-key="sortResetKey()"
87
- :page-reset-key="pageResetKey()"
88
104
  :columns="COLUMNS"
89
105
  :data="rows()"
90
106
  :loading="loading()"
@@ -93,10 +109,17 @@ function handleRowAction(payload: { action: string, row: ReviewRecord }): void {
93
109
  busy-key="id"
94
110
  :busy-value="busyId()"
95
111
  paginated
96
- :page-size="12"
112
+ manual-pagination
113
+ manual-sort
114
+ :total="total()"
115
+ :current-page="currentPage()"
116
+ :page-size="perPage()"
97
117
  empty-title="No reviews found"
98
118
  empty-description="Adjust the current filters or wait for a customer review."
99
119
  @row-action="handleRowAction"
120
+ @page-change="changePage"
121
+ @page-size-change="changePageSize"
122
+ @sort="changeSort"
100
123
  >
101
124
  <template #cell="{ row, column }">
102
125
  <template :if="column.key === 'customerLabel'">