@stacksjs/defaults 0.75.618 → 0.75.621

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 (84) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-auth/SKILL.md +12 -1
  3. package/ai/skills/stacks-auto-imports/SKILL.md +1 -1
  4. package/ai/skills/stacks-commerce/SKILL.md +78 -4
  5. package/ai/skills/stacks-dashboard/SKILL.md +2 -2
  6. package/ai/skills/stacks-database/SKILL.md +1 -1
  7. package/ai/skills/stacks-migrations/SKILL.md +10 -2
  8. package/ai/skills/stacks-mobile/SKILL.md +21 -2
  9. package/ai/skills/stacks-models/SKILL.md +2 -2
  10. package/ai/skills/stacks-native/CATALOG.md +11 -11
  11. package/ai/skills/stacks-orm/SKILL.md +2 -2
  12. package/app/Actions/Dashboard/Commerce/CommerceDiscountDestroyAction.ts +27 -0
  13. package/app/Actions/Dashboard/Commerce/CommerceDiscountStoreAction.ts +28 -0
  14. package/app/Actions/Dashboard/Commerce/CommerceDiscountUpdateAction.ts +30 -0
  15. package/app/Actions/Dashboard/Commerce/CommerceDiscountsAction.ts +42 -0
  16. package/app/Actions/Dashboard/Commerce/CommerceUpsellDestroyAction.ts +31 -0
  17. package/app/Actions/Dashboard/Commerce/CommerceUpsellDetailAction.ts +28 -0
  18. package/app/Actions/Dashboard/Commerce/CommerceUpsellStoreAction.ts +26 -0
  19. package/app/Actions/Dashboard/Commerce/CommerceUpsellUpdateAction.ts +29 -0
  20. package/app/Actions/Dashboard/Commerce/CommerceUpsellsAction.ts +40 -0
  21. package/app/Actions/Dashboard/Commerce/commerce-discount-list.ts +204 -0
  22. package/app/Actions/Dashboard/Commerce/commerce-discount-write.ts +53 -0
  23. package/app/Actions/Dashboard/Commerce/commerce-discounts-upsells.test.ts +228 -0
  24. package/app/Actions/Dashboard/Commerce/commerce-upsell-list.ts +289 -0
  25. package/app/Actions/Dashboard/Commerce/discount-records.ts +392 -0
  26. package/app/Actions/Dashboard/Commerce/upsell-offer-records.ts +307 -0
  27. package/app/Actions/Dashboard/Models/ModelSaveAction.ts +6 -1
  28. package/app/Actions/Dashboard/Models/model-relations.ts +17 -7
  29. package/app/Actions/Dashboard/Models/model-row-writes.ts +9 -8
  30. package/app/Actions/Dashboard/Models/model-write.ts +51 -2
  31. package/app/Actions/Dashboard/Remote/RemoteCommandRunAction.ts +1 -2
  32. package/app/Actions/Dashboard/Remote/RemoteTerminalCloseAction.ts +1 -2
  33. package/app/Actions/Dashboard/Remote/RemoteTerminalInputAction.ts +1 -2
  34. package/app/Actions/Dashboard/Remote/RemoteTerminalOpenAction.ts +1 -2
  35. package/app/Actions/Dashboard/Remote/RemoteTerminalResizeAction.ts +1 -2
  36. package/app/Actions/Dashboard/Remote/RemoteTerminalStreamAction.ts +1 -2
  37. package/app/Actions/Dashboard/Remote/remote-commands.test.ts +2 -2
  38. package/app/Actions/Dashboard/Remote/remote-commands.ts +4 -4
  39. package/app/Actions/Dashboard/Remote/remote-terminal.test.ts +45 -25
  40. package/app/Actions/Dashboard/Remote/remote-terminal.ts +9 -9
  41. package/app/Actions/Storefront/AcceptOrderOfferAction.ts +68 -0
  42. package/app/Actions/Storefront/ApplyDiscountCodeAction.ts +83 -0
  43. package/app/Actions/Storefront/DeclineOrderOfferAction.ts +25 -0
  44. package/app/Actions/Storefront/PlaceOrderAction.ts +135 -72
  45. package/app/Gates.ts +4 -4
  46. package/app/Mail/OrderConfirmation.ts +7 -1
  47. package/app/Models/commerce/Cart.ts +14 -0
  48. package/app/Models/commerce/Discount.ts +255 -0
  49. package/app/Models/commerce/PostPurchaseOffer.ts +175 -0
  50. package/app/Models/commerce/PostPurchaseOfferResponse.ts +145 -0
  51. package/app/Policies/PostPolicy.ts +11 -11
  52. package/app/Storefront/DiscountCodeMessages.ts +12 -0
  53. package/app/Storefront/OrderKey.ts +29 -0
  54. package/app/Storefront/StorefrontPricing.ts +211 -0
  55. package/app/Storefront/UpsellCharge.ts +43 -0
  56. package/ide/vscode/package.json +1 -1
  57. package/package.json +7 -7
  58. package/resources/components/Dashboard/Commerce/CommerceDiscountBreakdown.stx +72 -0
  59. package/resources/components/Dashboard/Commerce/CommerceDiscountDeleteDialog.stx +19 -0
  60. package/resources/components/Dashboard/Commerce/CommerceDiscountDetailsDialog.stx +110 -0
  61. package/resources/components/Dashboard/Commerce/CommerceDiscountDialog.stx +353 -0
  62. package/resources/components/Dashboard/Commerce/CommerceDiscountsDashboard.stx +211 -0
  63. package/resources/components/Dashboard/Commerce/CommerceDiscountsTable.stx +105 -0
  64. package/resources/components/Dashboard/Commerce/CommerceProductPicker.stx +115 -0
  65. package/resources/components/Dashboard/Commerce/CommerceUpsellDeleteDialog.stx +21 -0
  66. package/resources/components/Dashboard/Commerce/CommerceUpsellDetailsDialog.stx +153 -0
  67. package/resources/components/Dashboard/Commerce/CommerceUpsellDialog.stx +191 -0
  68. package/resources/components/Dashboard/Commerce/CommerceUpsellsDashboard.stx +214 -0
  69. package/resources/components/Dashboard/Commerce/CommerceUpsellsTable.stx +91 -0
  70. package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +4 -19
  71. package/resources/components/Dashboard/Settings/SettingsDashboard.stx +5 -3
  72. package/resources/components/Dashboard/UI/SearchFilter.stx +7 -4
  73. package/resources/components/Storefront/OrderSummary.stx +17 -0
  74. package/resources/functions/dashboard/sidebar.ts +4 -1
  75. package/resources/views/cart.stx +50 -16
  76. package/resources/views/checkout/contact.stx +11 -5
  77. package/resources/views/checkout/payment.stx +11 -5
  78. package/resources/views/checkout/shipping.stx +11 -5
  79. package/resources/views/orders/[id].stx +227 -50
  80. package/routes/dashboard-api.ts +12 -0
  81. package/routes/dashboard.ts +2 -0
  82. package/routes/storefront.ts +8 -0
  83. package/views/dashboard/commerce/discounts/index.stx +10 -0
  84. package/views/dashboard/commerce/upsells/index.stx +10 -0
@@ -0,0 +1,214 @@
1
+ <script client>
2
+ import type { UpsellOfferRecord, UpsellSummary } from '../../../../app/Actions/Dashboard/Commerce/upsell-offer-records'
3
+ import { formatCurrency } from '@stacksjs/commerce/money'
4
+ import { DashboardApiError, dashboardApi } from '../../../../functions/dashboard-api'
5
+ import { useServerList } from '../../../../functions/dashboard-list'
6
+ import { pushToast } from '../../../../functions/toasts'
7
+
8
+ interface UpsellIndexResponse {
9
+ records: UpsellOfferRecord[]
10
+ total: number
11
+ page: number
12
+ summary: UpsellSummary
13
+ currency: string
14
+ }
15
+
16
+ const emptySummary: UpsellSummary = { total: 0, running: 0, views: 0, accepted: 0, declined: 0, conversionRate: 0, revenue: 0, units: 0, top: [] }
17
+ const summary = state<UpsellSummary>({ ...emptySummary })
18
+ const currency = state('USD')
19
+ const stateFilter = state('all')
20
+ const sort = state('priority')
21
+ const dialogOpen = state(false)
22
+ const dialogMode = state<'add' | 'edit'>('add')
23
+ const editingRecord = state<UpsellOfferRecord | null>(null)
24
+ const detailsRecord = state<UpsellOfferRecord | null>(null)
25
+ const deletingRecord = state<UpsellOfferRecord | null>(null)
26
+ const saving = state(false)
27
+ const deleting = state(false)
28
+ const validationErrors = state<Record<string, string>>({})
29
+
30
+ const SELECT_SORTS: Record<string, { sort: string, direction: 'asc' | 'desc' }> = {
31
+ priority: { sort: 'priority', direction: 'desc' },
32
+ revenue: { sort: 'revenue', direction: 'desc' },
33
+ newest: { sort: 'newest', direction: 'desc' },
34
+ name: { sort: 'name', direction: 'asc' },
35
+ }
36
+
37
+ const {
38
+ records,
39
+ total,
40
+ page,
41
+ perPage,
42
+ search,
43
+ loading,
44
+ loadError,
45
+ load,
46
+ changePage,
47
+ changePageSize,
48
+ changeSort,
49
+ } = useServerList<UpsellOfferRecord>({
50
+ fetch: query => dashboardApi<UpsellIndexResponse>(`/api/dashboard/commerce/upsells?${query}`),
51
+ defaultSort: () => SELECT_SORTS[sort()] ?? SELECT_SORTS.priority!,
52
+ columnSorts: { name: 'name' },
53
+ filters: () => ({ state: stateFilter() }),
54
+ onLoad: (result) => {
55
+ const data = result as UpsellIndexResponse
56
+ summary.set(data.summary ?? { ...emptySummary })
57
+ currency.set(data.currency || 'USD')
58
+ },
59
+ onError: error => pushToast('error', 'Could not load offers', { detail: error instanceof Error ? error.message : String(error) }),
60
+ })
61
+
62
+ function money(value: number): string {
63
+ return formatCurrency(value, currency())
64
+ }
65
+
66
+ function percent(rate: number): string {
67
+ return `${(rate * 100).toFixed(rate > 0 && rate < 0.1 ? 1 : 0)}%`
68
+ }
69
+
70
+ function metricCards(): Array<{ label: string, value: string, detail: string }> {
71
+ const current = summary()
72
+ return [
73
+ { label: 'Running', value: String(current.running), detail: `of ${current.total} offers` },
74
+ { label: 'Shown', value: current.views.toLocaleString(), detail: 'Products shown after checkout' },
75
+ { label: 'Conversion', value: percent(current.conversionRate), detail: `${current.accepted.toLocaleString()} added, ${current.declined.toLocaleString()} declined` },
76
+ { label: 'Added to orders', value: money(current.revenue), detail: `${current.units.toLocaleString()} units` },
77
+ ]
78
+ }
79
+
80
+ function matchingLabel(): string {
81
+ const count = total()
82
+ return `${count.toLocaleString()} matching ${count === 1 ? 'offer' : 'offers'}`
83
+ }
84
+
85
+ function openAdd(): void {
86
+ dialogMode.set('add')
87
+ editingRecord.set(null)
88
+ validationErrors.set({})
89
+ dialogOpen.set(true)
90
+ }
91
+
92
+ function openEdit(record: UpsellOfferRecord): void {
93
+ dialogMode.set('edit')
94
+ editingRecord.set(record)
95
+ validationErrors.set({})
96
+ dialogOpen.set(true)
97
+ }
98
+
99
+ function closeDialog(): void {
100
+ if (saving())
101
+ return
102
+ dialogOpen.set(false)
103
+ editingRecord.set(null)
104
+ validationErrors.set({})
105
+ }
106
+
107
+ async function saveOffer(payload: Record<string, unknown>): Promise<void> {
108
+ const current = editingRecord()
109
+ const editing = dialogMode() === 'edit' && current !== null
110
+ saving.set(true)
111
+ validationErrors.set({})
112
+ try {
113
+ await dashboardApi(editing ? `/api/dashboard/commerce/upsells/${current.id}` : '/api/dashboard/commerce/upsells', {
114
+ method: editing ? 'PATCH' : 'POST',
115
+ body: payload,
116
+ })
117
+ dialogOpen.set(false)
118
+ editingRecord.set(null)
119
+ pushToast('success', editing ? 'Offer updated' : 'Offer added', { detail: String(payload.name ?? '') })
120
+ await load()
121
+ }
122
+ catch (error) {
123
+ if (error instanceof DashboardApiError)
124
+ validationErrors.set(error.fields ?? {})
125
+ pushToast('error', 'Could not save offer', { detail: error instanceof Error ? error.message : String(error) })
126
+ }
127
+ finally {
128
+ saving.set(false)
129
+ }
130
+ }
131
+
132
+ function openDetails(record: UpsellOfferRecord): void {
133
+ detailsRecord.set(record)
134
+ }
135
+
136
+ function closeDetails(): void {
137
+ detailsRecord.set(null)
138
+ }
139
+
140
+ function openDelete(record: UpsellOfferRecord): void {
141
+ deletingRecord.set(record)
142
+ }
143
+
144
+ function closeDelete(): void {
145
+ if (!deleting())
146
+ deletingRecord.set(null)
147
+ }
148
+
149
+ async function deleteOffer(): Promise<void> {
150
+ const current = deletingRecord()
151
+ if (!current)
152
+ return
153
+ deleting.set(true)
154
+ try {
155
+ await dashboardApi(`/api/dashboard/commerce/upsells/${current.id}`, { method: 'DELETE' })
156
+ deletingRecord.set(null)
157
+ detailsRecord.set(null)
158
+ pushToast('success', 'Offer deleted', { detail: current.name })
159
+ await load()
160
+ }
161
+ catch (error) {
162
+ pushToast('error', 'Could not delete offer', { detail: error instanceof Error ? error.message : String(error) })
163
+ }
164
+ finally {
165
+ deleting.set(false)
166
+ }
167
+ }
168
+
169
+ onMount(() => {
170
+ void load()
171
+ })
172
+ </script>
173
+
174
+ <div class="flex flex-col gap-6">
175
+ <PageHeader title="Upsells" description="One-time, discounted offers on the order confirmation page. Accepting adds the items to the order just placed, with no second checkout.">
176
+ <div class="flex flex-wrap gap-2">
177
+ <Button variant="secondary" :loading="loading()" @click="load()"><span :if="!loading()" class="h-4 w-4 i-hugeicons-refresh"></span>Refresh</Button>
178
+ <Button @click="openAdd()"><span class="h-4 w-4 i-hugeicons-add-01"></span>Add offer</Button>
179
+ </div>
180
+ </PageHeader>
181
+
182
+ <div :if="loadError()" class="p-4 text-red-700 text-sm dark:text-red-300 bg-red-50 dark:bg-red-950/30 border border-red-200 rounded-lg dark:border-red-900">{{ loadError() }}</div>
183
+
184
+ <MetricCards label="Upsell metrics" columns="grid-cols-2 lg:grid-cols-4" :items="metricCards()" />
185
+
186
+ <section :if="summary().top.length > 0" aria-label="Best offers" class="p-4 bg-white dark:bg-neutral-800 border border-gray-200 rounded-lg dark:border-neutral-700">
187
+ <h2 class="font-semibold text-gray-900 text-sm dark:text-white">Best offers</h2>
188
+ <ol class="grid gap-3 grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 mt-3">
189
+ <li :for="(entry, index) in summary().top" :key="entry.id" class="flex gap-3 items-baseline">
190
+ <span class="font-mono text-gray-400 text-xs">{{ index + 1 }}</span>
191
+ <div class="min-w-0">
192
+ <p class="text-gray-900 text-sm truncate dark:text-white">{{ entry.name }}</p>
193
+ <p class="tabular-nums text-gray-500 text-xs dark:text-neutral-400">{{ money(entry.revenue) }} · {{ percent(entry.conversionRate) }}</p>
194
+ </div>
195
+ </li>
196
+ </ol>
197
+ </section>
198
+
199
+ <section class="flex flex-col gap-3">
200
+ <div class="grid gap-3 grid-cols-1 sm:grid-cols-2 xl:grid-cols-4">
201
+ <div class="sm:col-span-2"><SearchFilter v-model:searchValue="search" placeholder="Search names, headlines or messages" ariaLabel="Search offers" /></div>
202
+ <Select v-model:value="stateFilter" ariaLabel="Offer status" placeholder="" :options="[{ value: 'all', label: 'Any status' }, { value: 'running', label: 'Running' }, { value: 'scheduled', label: 'Scheduled' }, { value: 'ended', label: 'Ended' }, { value: 'disabled', label: 'Disabled' }]" />
203
+ <Select v-model:value="sort" ariaLabel="Sort offers" placeholder="" :options="[{ value: 'priority', label: 'Priority' }, { value: 'revenue', label: 'Most revenue' }, { value: 'newest', label: 'Newest' }, { value: 'name', label: 'Name' }]" />
204
+ </div>
205
+
206
+ <p class="text-gray-500 text-sm dark:text-neutral-400">{{ matchingLabel() }}</p>
207
+
208
+ <CommerceUpsellsTable :sort-reset-key="sort()" :records="records()" :total="total()" :current-page="page()" :per-page="perPage()" :loading="loading()" :currency="currency()" @view="openDetails" @edit="openEdit" @delete="openDelete" @page-change="changePage" @page-size-change="changePageSize" @sort="changeSort" />
209
+ </section>
210
+ </div>
211
+
212
+ <CommerceUpsellDialog :open="dialogOpen()" :mode="dialogMode()" :record="editingRecord()" :currency="currency()" :busy="saving()" :errors="validationErrors()" @submit="saveOffer" @close="closeDialog()" />
213
+ <CommerceUpsellDetailsDialog :open="Boolean(detailsRecord())" :record="detailsRecord()" :currency="currency()" @edit="openEdit" @delete="openDelete" @close="closeDetails()" />
214
+ <CommerceUpsellDeleteDialog :open="Boolean(deletingRecord())" :record="deletingRecord()" :busy="deleting()" @confirm="deleteOffer()" @close="closeDelete()" />
@@ -0,0 +1,91 @@
1
+ @import('../UI/Table')
2
+
3
+ <script client>
4
+ import type { UpsellOfferRecord } from '../../../../app/Actions/Dashboard/Commerce/upsell-offer-records'
5
+
6
+ const records = useReactiveProp('records', [] as UpsellOfferRecord[])
7
+ const loading = useReactiveProp('loading', false)
8
+ const sortResetKey = useReactiveProp<unknown>('sortResetKey', '')
9
+ const currency = useReactiveProp('currency', 'USD')
10
+ const total = useReactiveProp('total', 0)
11
+ const currentPage = useReactiveProp('currentPage', 1)
12
+ const perPage = useReactiveProp('perPage', 25)
13
+ const emit = defineEmits(['view', 'edit', 'delete', 'page-change', 'page-size-change', 'sort'])
14
+
15
+ function percent(rate: number): string {
16
+ return `${(rate * 100).toFixed(rate > 0 && rate < 0.1 ? 1 : 0)}%`
17
+ }
18
+
19
+ const COLUMNS = derived(() => [
20
+ { key: 'name', label: 'Offer', sortable: true, subtitleKey: 'productsLabel', class: 'font-medium text-gray-900 dark:text-white' },
21
+ { key: 'dealLabel', label: 'Deal', subtitleKey: 'quantityLabel', searchable: false, class: 'font-semibold text-emerald-700 whitespace-nowrap dark:text-emerald-300' },
22
+ {
23
+ key: 'state',
24
+ label: 'Status',
25
+ type: 'badge' as const,
26
+ badgeClasses: {
27
+ running: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-300',
28
+ scheduled: 'bg-blue-100 text-blue-800 dark:bg-blue-950/50 dark:text-blue-300',
29
+ },
30
+ badgeLabels: { running: 'Running', scheduled: 'Scheduled', ended: 'Ended', disabled: 'Disabled' },
31
+ },
32
+ { key: 'shown', label: 'Shown', type: 'number' as const, align: 'right' as const, searchable: false },
33
+ { key: 'takenLabel', label: 'Taken', align: 'right' as const, subtitleKey: 'conversionLabel', searchable: false, class: 'font-mono whitespace-nowrap' },
34
+ { key: 'revenue', label: 'Added to orders', type: 'currency' as const, currency: currency(), align: 'right' as const, searchable: false, class: 'font-semibold whitespace-nowrap' },
35
+ { key: 'priority', label: 'Priority', type: 'number' as const, align: 'right' as const, searchable: false },
36
+ ])
37
+
38
+ const ROW_ACTIONS = [
39
+ { action: 'view', label: 'View results' },
40
+ { action: 'edit', label: 'Edit' },
41
+ { action: 'delete', label: 'Delete' },
42
+ ]
43
+
44
+ const rows = derived(() => records().map(record => ({
45
+ ...record,
46
+ productsLabel: record.products.map(product => product.label).join(', ') || 'No products',
47
+ dealLabel: record.discountPercent > 0 ? `${record.discountPercent}% off` : 'Full price',
48
+ quantityLabel: record.maxQuantity ? `${record.minQuantity} to ${record.maxQuantity} each` : `${record.minQuantity}+ each`,
49
+ shown: record.stats.views,
50
+ takenLabel: record.stats.accepted.toLocaleString(),
51
+ conversionLabel: `${percent(record.stats.conversionRate)} conversion`,
52
+ revenue: record.stats.revenue,
53
+ })))
54
+
55
+ function handleRowAction(payload: { action: string, row: UpsellOfferRecord }): void {
56
+ emit(payload.action, payload.row)
57
+ }
58
+
59
+ function changePage(page: number): void {
60
+ emit('page-change', page)
61
+ }
62
+
63
+ function changePageSize(size: number): void {
64
+ emit('page-size-change', size)
65
+ }
66
+
67
+ function changeSort(sort: { key: string, direction: string }): void {
68
+ emit('sort', sort)
69
+ }
70
+ </script>
71
+
72
+ <Table
73
+ :sort-reset-key="sortResetKey()"
74
+ :columns="COLUMNS()"
75
+ :data="rows()"
76
+ :loading="loading()"
77
+ :row-actions="ROW_ACTIONS"
78
+ action-label-key="name"
79
+ paginated
80
+ manual-pagination
81
+ manual-sort
82
+ :total="total()"
83
+ :current-page="currentPage()"
84
+ :page-size="perPage()"
85
+ empty-title="No post-purchase offers yet"
86
+ empty-description="Add an offer to show shoppers a one-time deal on their order confirmation page."
87
+ @row-action="handleRowAction"
88
+ @page-change="changePage"
89
+ @page-size-change="changePageSize"
90
+ @sort="changeSort"
91
+ />
@@ -1,7 +1,7 @@
1
1
  <template>
2
2
  <div class="min-h-screen dark:bg-neutral-800">
3
3
  <div class="flex h-screen">
4
- <EmailSidebar :activeFolder="activeFolder" :folders="folders" :unreadCounts="unreadCounts" :mailbox="mailbox" @update:active-folder="handleFolderChange" @compose="handleCompose" />
4
+ <EmailSidebar :activeFolder="activeFolder" :folders="folders" :mailbox="mailbox" @update:active-folder="handleFolderChange" @compose="handleCompose" />
5
5
 
6
6
  <div class="flex overflow-hidden flex-1 flex-col">
7
7
  <div class="px-6 py-4 bg-white dark:bg-neutral-700 border-b border-gray-200 dark:border-neutral-600">
@@ -245,7 +245,6 @@ import type {
245
245
  NotificationSound,
246
246
  ReplyBehavior,
247
247
  } from '@stacksjs/defaults/functions/mail-preferences'
248
- import { fetchInboxActivity } from '@stacksjs/defaults/functions/inbox'
249
248
  import { fetchMailPreference, saveMailPreference } from '@stacksjs/defaults/functions/mail-preferences'
250
249
 
251
250
  interface SettingsSection {
@@ -264,15 +263,6 @@ const folders = [
264
263
  { id: 'trash', name: 'Trash', icon: 'waste' },
265
264
  ]
266
265
 
267
- const unreadCounts = state({
268
- inbox: 0,
269
- starred: 0,
270
- sent: 0,
271
- drafts: 0,
272
- archive: 0,
273
- spam: 0,
274
- trash: 0,
275
- })
276
266
  const mailbox = state('')
277
267
 
278
268
  const settingsSections: SettingsSection[] = [
@@ -431,14 +421,9 @@ async function saveSettings(): Promise<void> {
431
421
 
432
422
  onMount(async () => {
433
423
  try {
434
- const activity = await fetchInboxActivity('year')
435
- if (activity) {
436
- unreadCounts.set(activity.folder_counts)
437
- mailbox.set(activity.mailbox)
438
- accountEmail.set(activity.mailbox)
439
- }
440
-
441
- const preference = await fetchMailPreference(activity?.mailbox)
424
+ // Settings come from the configured mailbox's persisted preferences.
425
+ // Reading them must not require an available inbound storage provider.
426
+ const preference = await fetchMailPreference()
442
427
  if (preference)
443
428
  applyPreference(preference)
444
429
  }
@@ -43,14 +43,16 @@ const fields = state<ConfigField[]>([])
43
43
  const drafts = reactive<Record<string, string | number | boolean>>({})
44
44
  const selected = state('')
45
45
  const pendingSelection = state('')
46
- const query = state('')
46
+ // Not `query`: the render context has one of its own (the request's query
47
+ // string), and a component binding resolved to it.
48
+ const configQuery = state('')
47
49
  const loading = state(true)
48
50
  const saving = state(false)
49
51
  const message = state('')
50
52
  const error = state('')
51
53
 
52
54
  const filteredFiles = derived(() => {
53
- const needle = query().trim().toLowerCase()
55
+ const needle = configQuery().trim().toLowerCase()
54
56
  if (!needle)
55
57
  return files()
56
58
 
@@ -198,7 +200,7 @@ void loadFiles()
198
200
  <div class="grid gap-6 lg:grid-cols-[17rem_minmax(0,1fr)]">
199
201
  <Card variant="default" padding="none">
200
202
  <div class="p-4 border-b border-neutral-200/60 dark:border-white/5">
201
- <SearchFilter v-model:searchValue="query" placeholder="Search config" ariaLabel="Search configuration" />
203
+ <SearchFilter v-model:searchValue="configQuery" placeholder="Search config" ariaLabel="Search configuration" />
202
204
  </div>
203
205
 
204
206
  <nav class="overflow-y-auto p-2 max-h-[68vh]" aria-label="Configuration files">
@@ -18,7 +18,10 @@ const placeholder = useReactiveProp('placeholder', 'Search...')
18
18
  // bar names the list it searches ("Search coupons").
19
19
  const ariaLabel = useReactiveProp('ariaLabel', '')
20
20
  const requested = useReactiveProp('searchValue', '')
21
- const query = state(requested())
21
+ // Not `query`: a render's context has a `query` of its own (the request's
22
+ // query-string object), and the binding below resolved to that, filling
23
+ // every dashboard search box with "[object Object]".
24
+ const term = state(requested())
22
25
  const emit = defineEmits(['update:searchValue', 'search'])
23
26
  // What the box last showed that the parent already knows: the value it was
24
27
  // seeded with, or the last search reported. Only a change the person makes is
@@ -29,11 +32,11 @@ let known = requested()
29
32
  effect(() => {
30
33
  const next = requested()
31
34
  known = next
32
- query.set(next)
35
+ term.set(next)
33
36
  })
34
37
 
35
38
  effect(() => {
36
- const value = query()
39
+ const value = term()
37
40
  if (value === known)
38
41
  return
39
42
  known = value
@@ -48,7 +51,7 @@ effect(() => {
48
51
  The box is the root, so a caller's `class` (a width) sizes the whole field.
49
52
  -->
50
53
  <div>
51
- <Input v-model:value="query" type="search" name="search" :placeholder="placeholder()" :ariaLabel="ariaLabel() || placeholder()" autocomplete="off" :spellcheck="false">
54
+ <Input v-model:value="term" type="search" name="search" :placeholder="placeholder()" :ariaLabel="ariaLabel() || placeholder()" autocomplete="off" :spellcheck="false">
52
55
  <template #iconLeft>
53
56
  <span aria-hidden="true" class="h-4 w-4 i-hugeicons-search-01"></span>
54
57
  </template>
@@ -21,6 +21,10 @@ interface OrderSummaryProps {
21
21
  /** Optional, pre-formatted "Add $X.XX more for free shipping." nudge.
22
22
  * When empty/omitted the nudge is hidden — let the caller decide. */
23
23
  freeShippingNote?: string
24
+ /** Optional, pre-formatted discount ("-$10.00"); the row is hidden when empty. */
25
+ discountLabel?: string
26
+ /** What the discount is, shown under the row: "BUY 4, GET 4 FREE". */
27
+ discountTitle?: string
24
28
  showItems?: boolean
25
29
  ctaHref?: string
26
30
  ctaLabel?: string
@@ -38,6 +42,8 @@ const {
38
42
  shippingLabel,
39
43
  totalLabel,
40
44
  freeShippingNote = '',
45
+ discountLabel = '',
46
+ discountTitle = '',
41
47
  showItems = false,
42
48
  ctaHref = '',
43
49
  ctaLabel = '',
@@ -64,6 +70,17 @@ const {
64
70
 
65
71
  <dl class="space-y-3 text-sm {{ showItems ? '' : 'mt-4' }}">
66
72
  <div class="flex justify-between"><dt class="text-stone-600">Subtotal</dt><dd class="font-semibold text-stone-900">{{ subtotalLabel }}</dd></div>
73
+ @if (discountLabel)
74
+ <div class="flex gap-3 justify-between">
75
+ <dt class="text-stone-600">
76
+ Discount
77
+ @if (discountTitle)
78
+ <span class="block font-medium text-emerald-700 text-xs tracking-wide uppercase">{{ discountTitle }}</span>
79
+ @endif
80
+ </dt>
81
+ <dd class="font-semibold text-emerald-700">{{ discountLabel }}</dd>
82
+ </div>
83
+ @endif
67
84
  <div class="flex justify-between"><dt class="text-stone-600">Shipping</dt><dd class="font-semibold text-stone-900">{{ shippingLabel }}</dd></div>
68
85
  @if (taxLabel)
69
86
  <div class="flex justify-between"><dt class="text-stone-600">Tax</dt><dd class="font-semibold text-stone-900">{{ taxLabel }}</dd></div>
@@ -482,6 +482,8 @@ export function buildNavSections(
482
482
  { to: '/commerce/variants', icon: 'puzzle', text: 'Variants' },
483
483
  { to: '/commerce/reviews', icon: 'star', text: 'Reviews' },
484
484
  { to: '/commerce/coupons', icon: 'coupon', text: 'Coupons' },
485
+ { to: '/commerce/discounts', icon: 'sale-tag', text: 'Discounts' },
486
+ { to: '/commerce/upsells', icon: 'zap', text: 'Upsells' },
485
487
  { to: '/commerce/gift-cards', icon: 'gift', text: 'Gift Cards' },
486
488
  { to: '/commerce/payments', icon: 'invoice', text: 'Payments' },
487
489
  { to: '/commerce/taxes', icon: 'percent', text: 'Taxes' },
@@ -491,7 +493,8 @@ export function buildNavSections(
491
493
  { to: '/commerce/waitlist/restaurant', icon: 'clock', text: 'Restaurant Waitlist' },
492
494
  ...categoryNavItems(discoveredModels, 'commerce', new Set([
493
495
  'customer', 'order', 'product', 'product-variant', 'product-unit',
494
- 'manufacturer', 'review', 'coupon', 'gift-card', 'payment', 'category',
496
+ 'manufacturer', 'review', 'coupon', 'discount', 'post-purchase-offer', 'post-purchase-offer-response',
497
+ 'gift-card', 'payment', 'category',
495
498
  'cart', 'cart-item', 'order-item', 'tax-rate',
496
499
  'shipping-method', 'shipping-rate', 'shipping-zone',
497
500
  'delivery-route', 'courier', 'license-key', 'digital-delivery',
@@ -19,6 +19,7 @@ interface CartItemRow {
19
19
  interface CartRow {
20
20
  id: number
21
21
  currency: string | null
22
+ discount_code?: string | null
22
23
  }
23
24
 
24
25
  interface StorefrontLineItem { lineTotal: number }
@@ -26,16 +27,17 @@ interface StorefrontLineItem { lineTotal: number }
26
27
  const { verifyCartCookie } = require('../../app/Storefront/CartCookie')
27
28
  const { readStorefront } = require('../../app/Storefront/StorefrontDatabase')
28
29
  const { storefrontCurrency, storefrontMoney, storefrontSummary } = require('../../app/Storefront/StorefrontMoney')
30
+ const { storefrontCartSummary } = require('../../app/Storefront/StorefrontPricing')
29
31
 
30
32
  // Signed by the storefront actions as the token, a dot and its HMAC. An
31
33
  // unsigned or tampered cookie is no cart, and is never looked up.
32
34
  const token = verifyCartCookie(requestContext.cookie('stacks_cart'))
33
35
 
34
36
  const found = token
35
- ? readStorefront('views/cart.stx', { cart: null, items: [] }, (db: import('bun:sqlite').Database) => {
37
+ ? readStorefront('views/cart.stx', { cart: null, items: [], summary: null }, (db: import('bun:sqlite').Database) => {
36
38
  const row = db.query<CartRow, [string]>(`SELECT * FROM carts WHERE session_token = ?1 AND status = 'active' LIMIT 1`).get(token)
37
39
  if (!row)
38
- return { cart: null, items: [] }
40
+ return { cart: null, items: [], summary: null }
39
41
 
40
42
  // Every amount below is integer minor units of the cart's currency.
41
43
  const currency = storefrontCurrency(row.currency)
@@ -63,9 +65,10 @@ const found = token
63
65
  }
64
66
  })
65
67
 
66
- return { cart: row, items: lines }
68
+ // Priced with the store's automatic discounts, exactly as PlaceOrderAction charges.
69
+ return { cart: row, items: lines, summary: storefrontCartSummary(db, row.id, currency) }
67
70
  })
68
- : { cart: null, items: [] }
71
+ : { cart: null, items: [], summary: null }
69
72
 
70
73
  const cart = found.cart
71
74
  const items = found.items
@@ -78,7 +81,9 @@ const subtotal = items.reduce((sum: number, i: StorefrontLineItem) => sum + i.li
78
81
  // Pre-format every amount so the OrderSummary component template doesn't
79
82
  // have to format a defineProps local — STX's SSR pass doesn't reliably
80
83
  // expose those locals, so callers do the formatting.
81
- const summary = storefrontSummary(subtotal, storefrontCurrency(cart?.currency))
84
+ const summary = found.summary ?? { ...storefrontSummary(subtotal, storefrontCurrency(cart?.currency)), discountLabel: '', discountTitle: '' }
85
+ const discountLabel = summary.discountLabel
86
+ const discountTitle = summary.discountTitle
82
87
  const subtotalLabel = summary.subtotalLabel
83
88
  const shippingLabel = summary.shippingLabel
84
89
  const totalLabel = summary.totalLabel
@@ -89,6 +94,10 @@ const cartNotice = requestContext.notice()
89
94
  // Why the form this page posted was refused, when it was not about one field
90
95
  // ("Your cart is empty."). Shown once (stacksjs/stacks#3311).
91
96
  const formError = requestContext.formError()
97
+ // The discount code field: what is applied, or what was typed and refused.
98
+ const discountCode = String(cart?.discount_code ?? '')
99
+ const codeError = requestContext.error('code')
100
+ const codeValue = requestContext.old('code', '')
92
101
  </script>
93
102
 
94
103
  @section('content')
@@ -165,17 +174,42 @@ const formError = requestContext.formError()
165
174
  @endforeach
166
175
  </div>
167
176
 
168
- <OrderSummary
169
- subtotalLabel="{{ subtotalLabel }}"
170
- shippingLabel="{{ shippingLabel }}"
171
- totalLabel="{{ totalLabel }}"
172
- freeShippingNote="{{ freeShippingNote }}"
173
- ctaHref="/checkout/contact"
174
- ctaLabel="Checkout"
175
- secondaryHref="/products"
176
- secondaryLabel="Keep shopping"
177
- :sticky="true"
178
- />
177
+ <div class="space-y-4 lg:sticky lg:top-28">
178
+ <OrderSummary
179
+ subtotalLabel="{{ subtotalLabel }}"
180
+ shippingLabel="{{ shippingLabel }}"
181
+ totalLabel="{{ totalLabel }}"
182
+ freeShippingNote="{{ freeShippingNote }}"
183
+ discountLabel="{{ discountLabel }}"
184
+ discountTitle="{{ discountTitle }}"
185
+ ctaHref="/checkout/contact"
186
+ ctaLabel="Checkout"
187
+ secondaryHref="/products"
188
+ secondaryLabel="Keep shopping"
189
+ />
190
+
191
+ <form action="/api/cart/discount" method="POST" class="p-4 border border-stone-200 rounded-2xl">
192
+ @if (discountCode)
193
+ <p class="font-semibold text-stone-500 text-xs tracking-wider uppercase">Discount code</p>
194
+ <div class="flex gap-3 items-center justify-between mt-2">
195
+ <span class="inline-flex gap-2 items-center px-3 py-1.5 font-semibold text-emerald-800 text-sm bg-emerald-50 rounded-full">
196
+ <span class="i-hugeicons-discount-tag-01 h-4 w-4" aria-hidden="true"></span>
197
+ {{ discountCode }}
198
+ </span>
199
+ <button type="submit" name="remove" value="1" class="font-medium text-stone-500 text-xs underline-offset-4 hover:text-stone-900 hover:underline focus-visible:outline-none focus-visible:underline">Remove</button>
200
+ </div>
201
+ @else
202
+ <label for="discount-code" class="font-semibold text-stone-500 text-xs tracking-wider uppercase">Discount code</label>
203
+ <div class="flex gap-2 mt-2">
204
+ <input id="discount-code" name="code" type="text" autocomplete="off" autocapitalize="characters" maxlength="64" value="{{ codeValue }}" placeholder="Enter code" class="flex-1 min-w-0 px-3 py-2 text-sm text-stone-900 border border-stone-300 rounded-xl focus:border-stone-900 focus:outline-none" aria-describedby="discount-code-error">
205
+ <button type="submit" class="px-4 py-2 font-semibold text-sm text-stone-900 border border-stone-300 hover:border-stone-900 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-stone-900 transition-colors">Apply</button>
206
+ </div>
207
+ @if (codeError)
208
+ <p id="discount-code-error" role="alert" class="mt-2 text-red-700 text-xs">{{ codeError }}</p>
209
+ @endif
210
+ @endif
211
+ </form>
212
+ </div>
179
213
 
180
214
  </div>
181
215
  @endif
@@ -23,16 +23,17 @@ interface StorefrontLineItem { lineTotal: number }
23
23
  const { verifyCartCookie } = require('../../../app/Storefront/CartCookie')
24
24
  const { readStorefront } = require('../../../app/Storefront/StorefrontDatabase')
25
25
  const { storefrontCurrency, storefrontMoney, storefrontSummary } = require('../../../app/Storefront/StorefrontMoney')
26
+ const { storefrontCartSummary } = require('../../../app/Storefront/StorefrontPricing')
26
27
 
27
28
  // Signed by the storefront actions as the token, a dot and its HMAC. An
28
29
  // unsigned or tampered cookie is no cart, and is never looked up.
29
30
  const token = verifyCartCookie(requestContext.cookie('stacks_cart'))
30
31
 
31
32
  const found = token
32
- ? readStorefront('views/checkout/contact.stx', { cart: null, items: [] }, (db: import('bun:sqlite').Database) => {
33
+ ? readStorefront('views/checkout/contact.stx', { cart: null, items: [], summary: null }, (db: import('bun:sqlite').Database) => {
33
34
  const row = db.query<CartRow, [string]>(`SELECT * FROM carts WHERE session_token = ?1 AND status = 'active' LIMIT 1`).get(token)
34
35
  if (!row)
35
- return { cart: null, items: [] }
36
+ return { cart: null, items: [], summary: null }
36
37
 
37
38
  // Every amount below is integer minor units of the cart's currency.
38
39
  const currency = storefrontCurrency(row.currency)
@@ -50,9 +51,10 @@ const found = token
50
51
  }
51
52
  })
52
53
 
53
- return { cart: row, items: lines }
54
+ // Priced with the store's automatic discounts, exactly as PlaceOrderAction charges.
55
+ return { cart: row, items: lines, summary: storefrontCartSummary(db, row.id, currency) }
54
56
  })
55
- : { cart: null, items: [] }
57
+ : { cart: null, items: [], summary: null }
56
58
 
57
59
  const cart = found.cart
58
60
  const items = found.items
@@ -61,7 +63,9 @@ const items = found.items
61
63
  // (app/Actions/Storefront/_shipping.ts), in minor units, so the running
62
64
  // totals on every checkout step match what gets charged.
63
65
  const subtotal = items.reduce((s: number, i: StorefrontLineItem) => s + i.lineTotal, 0)
64
- const summary = storefrontSummary(subtotal, storefrontCurrency(cart?.currency))
66
+ const summary = found.summary ?? { ...storefrontSummary(subtotal, storefrontCurrency(cart?.currency)), discountLabel: '', discountTitle: '' }
67
+ const discountLabel = summary.discountLabel
68
+ const discountTitle = summary.discountTitle
65
69
  const subtotalLabel = summary.subtotalLabel
66
70
  const shippingLabel = summary.shippingLabel
67
71
  const totalLabel = summary.totalLabel
@@ -126,6 +130,8 @@ const formError = requestContext.formError()
126
130
  shippingLabel="{{ shippingLabel }}"
127
131
  totalLabel="{{ totalLabel }}"
128
132
  freeShippingNote="{{ freeShippingNote }}"
133
+ discountLabel="{{ discountLabel }}"
134
+ discountTitle="{{ discountTitle }}"
129
135
  :showItems="true"
130
136
  />
131
137
  </div>