@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
@@ -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
  />
@@ -4,12 +4,20 @@ import type {
4
4
  OrderCustomerOption,
5
5
  } from '../../../../app/Actions/Dashboard/Commerce/commerce-order-records'
6
6
  import { minorToInput, moneyInputError, moneyInputStep, parseMoneyInput } from '@stacksjs/commerce/money'
7
+ import { dashboardApi } from '../../../../functions/dashboard-api'
7
8
  import { formErrorMessages } from '../../../../functions/dashboard-form'
8
9
 
9
10
  const open = useReactiveProp('open', false)
10
11
  const mode = useReactiveProp('mode', 'add')
11
12
  const record = useReactiveProp('record', null as CommerceOrderRecord | null)
12
- const customers = useReactiveProp('customers', [] as OrderCustomerOption[])
13
+ // The customer choices are a server search (stacksjs/stacks#3218): this used
14
+ // to be handed the first 500 customers by name, so nobody past the 500th could
15
+ // be chosen.
16
+ const customerOptions = state<OrderCustomerOption[]>([])
17
+ const customerMatches = state(0)
18
+ const customerQuery = state('')
19
+ let customerRequest = 0
20
+ let customerTimer: ReturnType<typeof setTimeout> | null = null
13
21
  const statuses = useReactiveProp('statuses', [] as string[])
14
22
  const orderTypes = useReactiveProp('orderTypes', [] as string[])
15
23
  const defaultCurrency = useReactiveProp('defaultCurrency', 'USD')
@@ -42,6 +50,8 @@ effect(() => {
42
50
  if (hydrationKey === key)
43
51
  return
44
52
  hydrationKey = key
53
+ customerQuery.set('')
54
+ void loadCustomers('')
45
55
  customerId.set(current?.customerId || '')
46
56
  couponId.set(current?.couponId || '')
47
57
  status.set(current?.status || statuses()[0] || 'PENDING')
@@ -60,6 +70,49 @@ effect(() => {
60
70
  appliedCouponId.set(current?.appliedCouponId || '')
61
71
  })
62
72
 
73
+ /** The choices to show: the search results, with the order's own customer kept in. */
74
+ const customers = derived(() => {
75
+ const options = customerOptions()
76
+ const current = record()
77
+ if (!current?.customerId || options.some(option => option.id === current.customerId))
78
+ return options
79
+ return [{ id: current.customerId, label: current.customerName || `Customer ${current.customerId}` }, ...options]
80
+ })
81
+
82
+ const moreCustomersLabel = derived(() => {
83
+ const shown = customerOptions().length
84
+ const total = customerMatches()
85
+ return total > shown ? `Showing ${shown} of ${total.toLocaleString()} matching customers. Search to narrow it down.` : ''
86
+ })
87
+
88
+ async function loadCustomers(term: string): Promise<void> {
89
+ const request = ++customerRequest
90
+ try {
91
+ const params = new URLSearchParams()
92
+ if (term)
93
+ params.set('q', term)
94
+ const suffix = params.toString()
95
+ const data = await dashboardApi<{ customers?: OrderCustomerOption[], total?: number }>(`/api/dashboard/commerce/orders/customers${suffix ? `?${suffix}` : ''}`)
96
+ if (request !== customerRequest)
97
+ return
98
+ customerOptions.set(data.customers ?? [])
99
+ customerMatches.set(data.total ?? (data.customers?.length ?? 0))
100
+ }
101
+ catch {
102
+ // Soft-fail: the order's own customer stays selectable, and Unassigned.
103
+ if (request === customerRequest) {
104
+ customerOptions.set([])
105
+ customerMatches.set(0)
106
+ }
107
+ }
108
+ }
109
+
110
+ function searchCustomersSoon(): void {
111
+ if (customerTimer)
112
+ clearTimeout(customerTimer)
113
+ customerTimer = setTimeout(() => { void loadCustomers(customerQuery().trim()) }, 250)
114
+ }
115
+
63
116
  function label(value: string): string {
64
117
  return value.replaceAll('_', ' ').toLowerCase().replace(/\b\w/g, letter => letter.toUpperCase())
65
118
  }
@@ -125,7 +178,11 @@ function errorMessages(): string[] {
125
178
  <template :for="message in errorMessages()" :key="message"><li>{{ message }}</li></template>
126
179
  </ul>
127
180
  <div class="grid gap-4 grid-cols-1 sm:grid-cols-2">
128
- <label class="block"><span class="font-medium text-gray-700 text-sm dark:text-neutral-200">Customer</span><select x-model="customerId" class="mt-1 px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-900 border border-gray-300 rounded-md dark:border-neutral-700"><option value="">Unassigned customer</option><template :for="option in customers()" :key="option.id"><option :value="option.id">{{ option.label }}</option></template></select></label>
181
+ <div class="block">
182
+ <label class="block"><span class="font-medium text-gray-700 text-sm dark:text-neutral-200">Customer</span><input x-model="customerQuery" @input="searchCustomersSoon()" type="search" name="customer_search" aria-label="Search customers by name or email" placeholder="Search by name or email" class="mt-1 px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-900 border border-gray-300 rounded-md dark:border-neutral-700" /></label>
183
+ <select x-model="customerId" aria-label="Customer" class="mt-2 px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-900 border border-gray-300 rounded-md dark:border-neutral-700"><option value="">Unassigned customer</option><template :for="option in customers()" :key="option.id"><option :value="option.id" :selected="option.id === customerId()">{{ option.label }}</option></template></select>
184
+ <p :if="moreCustomersLabel()" class="mt-1 text-gray-500 text-xs dark:text-neutral-400" :text="moreCustomersLabel()"></p>
185
+ </div>
129
186
  <label class="block"><span class="font-medium text-gray-700 text-sm dark:text-neutral-200">Status</span><select x-model="status" required class="mt-1 px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-900 border border-gray-300 rounded-md dark:border-neutral-700"><template :for="option in statuses()" :key="option"><option :value="option">{{ label(option) }}</option></template></select></label>
130
187
  <label class="block"><span class="font-medium text-gray-700 text-sm dark:text-neutral-200">Order type</span><select x-model="orderType" required class="mt-1 px-3 py-2 w-full text-gray-900 text-sm dark:text-white bg-white dark:bg-neutral-900 border border-gray-300 rounded-md dark:border-neutral-700"><template :for="option in orderTypes()" :key="option"><option :value="option">{{ label(option) }}</option></template></select></label>
131
188
  <label class="block"><span class="font-medium text-gray-700 text-sm dark:text-neutral-200">Currency</span><input x-model="currency" type="text" minlength="3" maxlength="3" required spellcheck="false" class="mt-1 px-3 py-2 w-full font-mono text-gray-900 text-sm uppercase dark:text-white bg-white dark:bg-neutral-900 border border-gray-300 rounded-md dark:border-neutral-700" /></label>