@stacksjs/defaults 0.75.487 → 0.75.490

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +27 -2
  3. package/ai/skills/stacks-native/CATALOG.md +9 -9
  4. package/ai/skills/stacks-search-engine/SKILL.md +14 -0
  5. package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
  6. package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
  7. package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
  8. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
  9. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
  10. package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
  11. package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
  12. package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
  13. package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
  14. package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
  15. package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
  16. package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
  17. package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
  18. package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
  19. package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
  20. package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
  21. package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
  22. package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
  23. package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
  24. package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
  25. package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
  26. package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
  27. package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
  28. package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
  29. package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
  30. package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
  31. package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
  32. package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
  33. package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
  34. package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
  35. package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
  36. package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
  37. package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
  38. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
  39. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
  40. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
  41. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
  42. package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
  43. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
  44. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
  45. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
  46. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
  47. package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
  48. package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
  49. package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
  50. package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
  51. package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
  52. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
  53. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
  54. package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
  55. package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
  56. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
  57. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
  58. package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
  59. package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
  60. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
  61. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
  62. package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
  63. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
  64. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
  65. package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
  66. package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
  67. package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
  68. package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
  69. package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
  70. package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
  71. package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
  72. package/app/Actions/Dashboard/Content/content-list.ts +10 -0
  73. package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
  74. package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
  75. package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
  76. package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
  77. package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
  78. package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
  79. package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
  80. package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
  81. package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
  82. package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
  83. package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
  84. package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
  85. package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
  86. package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
  87. package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +9 -6
  88. package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
  89. package/app/Actions/Dashboard/Queue/queue-stats.ts +10 -0
  90. package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
  91. package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
  92. package/app/Actions/Dashboard/named-search.test.ts +36 -0
  93. package/app/Actions/Dashboard/named-search.ts +80 -0
  94. package/app/Models/QueueWorker.ts +1 -0
  95. package/app/Models/Request.ts +4 -2
  96. package/bootstrap.ts +6 -1
  97. package/functions/commerce/shippings/dashboard-resource.ts +12 -1
  98. package/functions/commerce/shippings/delivery-routes.ts +1 -0
  99. package/functions/commerce/shippings/license-keys.ts +1 -0
  100. package/functions/dashboard-list.test.ts +132 -1
  101. package/functions/dashboard-list.ts +198 -1
  102. package/functions/queue.ts +2 -0
  103. package/ide/vscode/package.json +1 -1
  104. package/package.json +2 -2
  105. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
  106. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
  107. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
  108. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
  109. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
  110. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
  111. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
  112. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
  113. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
  114. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
  115. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
  116. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
  117. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
  118. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
  119. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
  120. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
  121. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
  122. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
  123. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
  124. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
  125. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
  126. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
  127. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
  128. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
  129. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
  130. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
  131. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
  132. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
  133. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
  134. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
  135. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
  136. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
  137. package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
  138. package/resources/components/Dashboard/Queue/QueueDashboard.stx +8 -2
  139. package/resources/functions/dashboard/sidebar.ts +26 -1
  140. package/routes/dashboard-api.ts +11 -0
  141. package/views/dashboard/stores/kanban.ts +38 -6
@@ -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>
@@ -2,16 +2,17 @@
2
2
  import type {
3
3
  CommerceOrderRecord,
4
4
  CommerceOrderSummary,
5
- OrderCustomerOption,
6
5
  } from '../../../../app/Actions/Dashboard/Commerce/commerce-order-records'
7
6
  import { DashboardApiError, dashboardApi } from '../../../../functions/dashboard-api'
8
7
  import { pushToast } from '../../../../functions/toasts'
9
- import { formatCurrency, minorToInput } from '@stacksjs/commerce/money'
8
+ import { formatCurrency } from '@stacksjs/commerce/money'
10
9
 
11
10
  interface OrderIndexResponse {
12
11
  records: CommerceOrderRecord[]
12
+ total: number
13
+ page: number
14
+ perPage: number
13
15
  summary: CommerceOrderSummary
14
- customers: OrderCustomerOption[]
15
16
  statuses: string[]
16
17
  orderTypes: string[]
17
18
  defaultCurrency: string
@@ -44,7 +45,6 @@ const emptySummary: CommerceOrderSummary = {
44
45
  }
45
46
  const records = state<CommerceOrderRecord[]>([])
46
47
  const summary = state<CommerceOrderSummary>({ ...emptySummary })
47
- const customers = state<OrderCustomerOption[]>([])
48
48
  const statuses = state<string[]>([])
49
49
  const orderTypes = state<string[]>([])
50
50
  const defaultCurrency = state('USD')
@@ -52,6 +52,15 @@ const search = state('')
52
52
  const statusFilter = state('all')
53
53
  const typeFilter = state('all')
54
54
  const sort = state('newest')
55
+ // A column header's sort, which takes over from the select until it changes.
56
+ const headerSort = state<{ sort: string, direction: string } | null>(null)
57
+ // How many orders match the search and filters, across every page.
58
+ const matchingTotal = state(0)
59
+ const page = state(1)
60
+ const perPage = state(25)
61
+ const appliedSearch = state('')
62
+ let listRequest = 0
63
+ let searchTimer: ReturnType<typeof setTimeout> | null = null
55
64
  const loading = state(true)
56
65
  const loadError = state('')
57
66
  const dialogOpen = state(false)
@@ -63,16 +72,6 @@ const saving = state(false)
63
72
  const deleting = state(false)
64
73
  const validationErrors = state<Record<string, string>>({})
65
74
 
66
- function timestamp(value: string): number {
67
- if (!value)
68
- return 0
69
- const normalized = /^\d{4}-\d{2}-\d{2} \d/.test(value)
70
- ? `${value.replace(' ', 'T')}Z`
71
- : value
72
- const result = new Date(normalized).getTime()
73
- return Number.isFinite(result) ? result : 0
74
- }
75
-
76
75
  function formatMoney(value: number, currency: string): string {
77
76
  return formatCurrency(value, currency)
78
77
  }
@@ -81,39 +80,46 @@ function label(value: string): string {
81
80
  return value.replaceAll('_', ' ').toLowerCase().replace(/\b\w/g, letter => letter.toUpperCase())
82
81
  }
83
82
 
84
- function filteredRecords(): CommerceOrderRecord[] {
85
- const query = search().trim().toLowerCase()
86
- const selectedStatus = statusFilter()
87
- const selectedType = typeFilter()
88
- return [...records()]
89
- .filter((record) => {
90
- if (selectedStatus !== 'all' && record.status !== selectedStatus)
91
- return false
92
- if (selectedType !== 'all' && record.orderType !== selectedType)
93
- return false
94
- return !query || [
95
- record.id,
96
- record.customerName,
97
- record.customerEmail,
98
- record.status,
99
- record.orderType,
100
- record.deliveryAddress,
101
- ].some(value => value.toLowerCase().includes(query))
102
- })
103
- .sort((left, right) => {
104
- if (sort() === 'oldest')
105
- return timestamp(left.createdAt) - timestamp(right.createdAt)
106
- if (sort() === 'total-high')
107
- return right.totalAmount - left.totalAmount || timestamp(right.createdAt) - timestamp(left.createdAt)
108
- if (sort() === 'total-low')
109
- return left.totalAmount - right.totalAmount || timestamp(right.createdAt) - timestamp(left.createdAt)
110
- return timestamp(right.createdAt) - timestamp(left.createdAt) || Number(right.id) - Number(left.id)
111
- })
83
+ /** The select's four orders, as the server's sort and direction. */
84
+ const SELECT_SORTS: Record<string, { sort: string, direction: string }> = {
85
+ 'newest': { sort: 'created', direction: 'desc' },
86
+ 'oldest': { sort: 'created', direction: 'asc' },
87
+ 'total-high': { sort: 'total', direction: 'desc' },
88
+ 'total-low': { sort: 'total', direction: 'asc' },
89
+ }
90
+
91
+ /** The table's sortable columns, as the server's sort names. */
92
+ const COLUMN_SORTS: Record<string, string> = {
93
+ orderLabel: 'id',
94
+ customerLabel: 'customer',
95
+ totalAmount: 'total',
96
+ fulfillmentLabel: 'type',
97
+ statusTone: 'status',
98
+ createdAt: 'created',
99
+ }
100
+
101
+ /**
102
+ * The search, filters and order, as the query the server takes
103
+ * (stacksjs/stacks#3218): it searches, filters, sorts and pages every order,
104
+ * where this page used to do all of that with the newest 500.
105
+ */
106
+ function filterParams(): URLSearchParams {
107
+ const params = new URLSearchParams()
108
+ const order = headerSort() ?? SELECT_SORTS[sort()] ?? SELECT_SORTS.newest
109
+ params.set('sort', order.sort)
110
+ params.set('direction', order.direction)
111
+ if (appliedSearch())
112
+ params.set('q', appliedSearch())
113
+ if (statusFilter() !== 'all')
114
+ params.set('status', statusFilter())
115
+ if (typeFilter() !== 'all')
116
+ params.set('type', typeFilter())
117
+ return params
112
118
  }
113
119
 
114
120
  function matchingLabel(): string {
115
- const count = filteredRecords().length
116
- return `${count} matching ${count === 1 ? 'order' : 'orders'}`
121
+ const count = matchingTotal()
122
+ return `${count.toLocaleString()} matching ${count === 1 ? 'order' : 'orders'}`
117
123
  }
118
124
 
119
125
  function metricCards(): Array<{ label: string, value: string, detail: string }> {
@@ -127,62 +133,102 @@ function metricCards(): Array<{ label: string, value: string, detail: string }>
127
133
  ]
128
134
  }
129
135
 
136
+ /** Every matching order as CSV, built by the server, not just the page shown. */
130
137
  function exportHref(): string {
131
- const rows = filteredRecords().map(record => [
132
- record.id,
133
- record.customerName,
134
- record.customerEmail,
135
- record.status,
136
- record.orderType,
137
- String(record.itemCount),
138
- minorToInput(record.totalAmount, record.currency),
139
- record.currency,
140
- minorToInput(record.taxAmount, record.currency),
141
- minorToInput(record.discountAmount, record.currency),
142
- minorToInput(record.deliveryFee, record.currency),
143
- minorToInput(record.tipAmount, record.currency),
144
- record.deliveryAddress,
145
- record.createdAt,
146
- ])
147
- const escape = (value: string): string => `"${value.replaceAll('"', '""')}"`
148
- const csv = [
149
- ['Order ID', 'Customer', 'Customer email', 'Status', 'Order type', 'Items', 'Total', 'Currency', 'Tax', 'Discount', 'Delivery fee', 'Tip', 'Delivery address', 'Created at'],
150
- ...rows,
151
- ].map(row => row.map(escape).join(',')).join('\n')
152
- return `data:text/csv;charset=utf-8,${encodeURIComponent(`\uFEFF${csv}`)}`
153
- }
154
-
155
- /**
156
- * What the table is showing: a change returns it to the first page, as this
157
- * page's own pager did before the table took over paging.
158
- */
159
- function viewKey(): string {
160
- return JSON.stringify([search(), statusFilter(), typeFilter(), sort()])
138
+ return `/api/dashboard/commerce/orders/export?${filterParams()}`
161
139
  }
162
140
 
163
141
  async function loadOrders(): Promise<void> {
142
+ const request = ++listRequest
164
143
  loading.set(true)
165
144
  loadError.set('')
166
145
  try {
167
- const data = await dashboardApi<OrderIndexResponse>('/api/dashboard/commerce/orders')
146
+ const params = filterParams()
147
+ params.set('page', String(page()))
148
+ params.set('per_page', String(perPage()))
149
+ const data = await dashboardApi<OrderIndexResponse>(`/api/dashboard/commerce/orders?${params}`)
150
+ // Only the newest request lands: a slower answer to an older search does
151
+ // not overwrite the one for what is typed now.
152
+ if (request !== listRequest)
153
+ return
168
154
  records.set(Array.isArray(data.records) ? data.records : [])
155
+ matchingTotal.set(Number(data.total) || 0)
156
+ // The server moves back to the last page when a delete or a narrower
157
+ // filter leaves this one past the end.
158
+ page.set(Number(data.page) || 1)
169
159
  summary.set(data.summary ?? { ...emptySummary })
170
- customers.set(Array.isArray(data.customers) ? data.customers : [])
171
160
  statuses.set(Array.isArray(data.statuses) ? data.statuses : [])
172
161
  orderTypes.set(Array.isArray(data.orderTypes) ? data.orderTypes : [])
173
162
  defaultCurrency.set(data.defaultCurrency || 'USD')
174
163
  }
175
164
  catch (error) {
165
+ if (request !== listRequest)
166
+ return
176
167
  loadError.set('Order records could not be loaded.')
177
168
  pushToast('error', 'Could not load orders', {
178
169
  detail: error instanceof Error ? error.message : String(error),
179
170
  })
180
171
  }
181
172
  finally {
182
- loading.set(false)
173
+ if (request === listRequest)
174
+ loading.set(false)
183
175
  }
184
176
  }
185
177
 
178
+ function eventValue<T>(value: T | CustomEvent<T>): T {
179
+ return value instanceof CustomEvent ? value.detail : value
180
+ }
181
+
182
+ function changePage(value: number | CustomEvent<number>): void {
183
+ page.set(Number(eventValue(value)) || 1)
184
+ void loadOrders()
185
+ }
186
+
187
+ function changePageSize(value: number | CustomEvent<number>): void {
188
+ perPage.set(Number(eventValue(value)) || 25)
189
+ page.set(1)
190
+ void loadOrders()
191
+ }
192
+
193
+ function changeColumnSort(value: { key: string, direction: string } | CustomEvent<{ key: string, direction: string }>): void {
194
+ const column = eventValue(value)
195
+ const serverSort = COLUMN_SORTS[column.key]
196
+ headerSort.set(serverSort ? { sort: serverSort, direction: column.direction === 'asc' ? 'asc' : 'desc' } : null)
197
+ page.set(1)
198
+ void loadOrders()
199
+ }
200
+
201
+ // The filters and the select ask the server for page 1 when they change, and
202
+ // the search once typing pauses. A select change also hands the order back
203
+ // from a column header.
204
+ let shownFilters = JSON.stringify([statusFilter(), typeFilter(), sort()])
205
+ effect(() => {
206
+ const filters = JSON.stringify([statusFilter(), typeFilter(), sort()])
207
+ if (filters === shownFilters)
208
+ return
209
+ const sortChanged = JSON.parse(shownFilters)[2] !== sort()
210
+ shownFilters = filters
211
+ if (sortChanged)
212
+ headerSort.set(null)
213
+ page.set(1)
214
+ void loadOrders()
215
+ })
216
+
217
+ let shownSearch = search().trim()
218
+ effect(() => {
219
+ const term = search().trim()
220
+ if (term === shownSearch)
221
+ return
222
+ shownSearch = term
223
+ if (searchTimer)
224
+ clearTimeout(searchTimer)
225
+ searchTimer = setTimeout(() => {
226
+ appliedSearch.set(term)
227
+ page.set(1)
228
+ void loadOrders()
229
+ }, 250)
230
+ })
231
+
186
232
  function openAdd(): void {
187
233
  dialogMode.set('add')
188
234
  editingRecord.set(null)
@@ -281,7 +327,7 @@ onMount(() => {
281
327
  <PageHeader title="Orders" description="Manage native Order records, customer assignments, totals, and fulfillment state.">
282
328
  <div class="flex flex-wrap gap-2">
283
329
  <Button variant="secondary" :loading="loading()" @click="loadOrders()"><span :if="!loading()" class="h-4 w-4 i-hugeicons-refresh"></span>Refresh</Button>
284
- <Button tag="a" variant="secondary" :href="exportHref()" :download="'orders-' + new Date().toISOString().slice(0, 10) + '.csv'"><span class="h-4 w-4 i-hugeicons-download-04"></span>Export filtered</Button>
330
+ <Button tag="a" variant="secondary" :href="exportHref()" download><span class="h-4 w-4 i-hugeicons-download-04"></span>Export filtered</Button>
285
331
  <Button @click="openAdd()"><span class="h-4 w-4 i-hugeicons-add-01"></span>Add order</Button>
286
332
  </div>
287
333
  </PageHeader>
@@ -311,10 +357,10 @@ onMount(() => {
311
357
  <p class="text-gray-500 text-sm dark:text-neutral-400">{{ matchingLabel() }}</p>
312
358
  </div>
313
359
 
314
- <CommerceOrdersTable :sort-reset-key="sort()" :page-reset-key="viewKey()" :records="filteredRecords()" :loading="loading()" @view="openDetails" @edit="openEdit" @delete="openDelete" />
360
+ <CommerceOrdersTable :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" />
315
361
  </section>
316
362
  </div>
317
363
 
318
- <CommerceOrderDialog :open="dialogOpen()" :mode="dialogMode()" :record="editingRecord()" :customers="customers()" :statuses="statuses()" :order-types="orderTypes()" :default-currency="defaultCurrency()" :busy="saving()" :errors="validationErrors()" @submit="saveOrder" @close="closeDialog()" />
364
+ <CommerceOrderDialog :open="dialogOpen()" :mode="dialogMode()" :record="editingRecord()" :statuses="statuses()" :order-types="orderTypes()" :default-currency="defaultCurrency()" :busy="saving()" :errors="validationErrors()" @submit="saveOrder" @close="closeDialog()" />
319
365
  <CommerceOrderDetailsDialog :open="Boolean(detailsRecord())" :record="detailsRecord()" @edit="openEdit" @delete="openDelete" @close="closeDetails()" />
320
366
  <CommerceOrderDeleteDialog :open="Boolean(deletingRecord())" :record="deletingRecord()" :busy="deleting()" @confirm="deleteOrder()" @close="closeDelete()" />
@@ -9,7 +9,13 @@ const loading = useReactiveProp('loading', false)
9
9
  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
- const emit = defineEmits(['view', 'edit', 'delete'])
12
+ // One page the server chose (stacksjs/stacks#3218): it searches, filters, sorts
13
+ // and pages the orders, so this shows them as given and hands paging and
14
+ // column sorting back to the parent.
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'])
13
19
 
14
20
  function label(value: string): string {
15
21
  return value.replaceAll('_', ' ').toLowerCase().replace(/\b\w/g, letter => letter.toUpperCase())
@@ -71,11 +77,23 @@ const rows = derived(() => records().map(record => ({
71
77
  function handleRowAction(payload: { action: string, row: CommerceOrderRecord }): void {
72
78
  emit(payload.action, payload.row)
73
79
  }
80
+
81
+ function changePage(page: number): void {
82
+ emit('page-change', page)
83
+ }
84
+
85
+ function changePageSize(size: number): void {
86
+ emit('page-size-change', size)
87
+ }
88
+
89
+ function changeSort(sort: { key: string, direction: string }): void {
90
+ emit('sort', sort)
91
+ }
74
92
  </script>
75
93
 
76
94
  {{--
77
95
  No `searchable` or `filterable`: the parent dashboard owns the search box
78
- and the filter selects. Table pages the whole filtered list the parent passes.
96
+ and the filter selects, and the server pages and sorts what they match.
79
97
  --}}
80
98
  <Table
81
99
  :sort-reset-key="sortResetKey()"
@@ -86,8 +104,15 @@ function handleRowAction(payload: { action: string, row: CommerceOrderRecord }):
86
104
  :row-actions="ROW_ACTIONS"
87
105
  action-label-key="id"
88
106
  paginated
89
- :page-size="12"
107
+ manual-pagination
108
+ manual-sort
109
+ :total="total()"
110
+ :current-page="currentPage()"
111
+ :page-size="perPage()"
90
112
  empty-title="No orders found"
91
113
  empty-description="Adjust the filters or add a native Order record."
92
114
  @row-action="handleRowAction"
115
+ @page-change="changePage"
116
+ @page-size-change="changePageSize"
117
+ @sort="changeSort"
93
118
  />
@@ -1,8 +1,5 @@
1
1
  <script client>
2
- import type {
3
- PaymentRecord,
4
- } from '../../../../app/Actions/Dashboard/Commerce/payment-records'
5
- import { isSuccessfulPayment } from '../../../../app/Actions/Dashboard/Commerce/payment-records'
2
+ import type { PaymentBreakdown } from '../../../../app/Actions/Dashboard/Commerce/commerce-payment-list'
6
3
  import { formatCurrency } from '@stacksjs/commerce/money'
7
4
 
8
5
  interface CountRow {
@@ -17,38 +14,24 @@ interface CurrencyRow {
17
14
  refunded: number
18
15
  }
19
16
 
20
- const records = useReactiveProp('records', [] as PaymentRecord[])
17
+ // Counted by the server over every matching payment (stacksjs/stacks#3218);
18
+ // this used to count whichever of the newest 500 matched.
19
+ const breakdown = useReactiveProp('breakdown', { statuses: [], methods: [], currencies: [] } as PaymentBreakdown)
21
20
 
22
21
  function countRows(field: 'status' | 'method'): CountRow[] {
23
- const counts = new Map<string, number>()
24
- for (const record of records()) {
25
- const key = record[field] || 'unknown'
26
- counts.set(key, (counts.get(key) || 0) + 1)
27
- }
28
- const total = records().length
29
- return [...counts.entries()]
30
- .map(([key, count]) => ({
31
- key,
32
- count,
33
- percentage: total ? Math.round((count / total) * 1000) / 10 : 0,
22
+ const counts = field === 'status' ? breakdown().statuses : breakdown().methods
23
+ const total = counts.reduce((sum, row) => sum + row.count, 0)
24
+ return counts
25
+ .map(row => ({
26
+ key: row.key,
27
+ count: row.count,
28
+ percentage: total ? Math.round((row.count / total) * 1000) / 10 : 0,
34
29
  }))
35
30
  .sort((left, right) => right.count - left.count || left.key.localeCompare(right.key))
36
31
  }
37
32
 
38
33
  function currencyRows(): CurrencyRow[] {
39
- const currencies = new Map<string, CurrencyRow>()
40
- for (const record of records()) {
41
- const row = currencies.get(record.currency) ?? {
42
- currency: record.currency,
43
- captured: 0,
44
- refunded: 0,
45
- }
46
- if (isSuccessfulPayment(record))
47
- row.captured += record.amount
48
- row.refunded += record.refundAmount
49
- currencies.set(record.currency, row)
50
- }
51
- return [...currencies.values()].sort((left, right) => right.captured - left.captured)
34
+ return [...breakdown().currencies].sort((left, right) => right.captured - left.captured)
52
35
  }
53
36
 
54
37
  function label(value: string): string {