@stacksjs/defaults 0.75.618 → 0.75.622

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 (94) 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-buddy/SKILL.md +70 -7
  5. package/ai/skills/stacks-commerce/SKILL.md +78 -4
  6. package/ai/skills/stacks-dashboard/SKILL.md +32 -2
  7. package/ai/skills/stacks-database/SKILL.md +1 -1
  8. package/ai/skills/stacks-development/SKILL.md +3 -0
  9. package/ai/skills/stacks-migrations/SKILL.md +10 -2
  10. package/ai/skills/stacks-mobile/SKILL.md +21 -2
  11. package/ai/skills/stacks-models/SKILL.md +2 -2
  12. package/ai/skills/stacks-native/CATALOG.md +21 -21
  13. package/ai/skills/stacks-orm/SKILL.md +2 -2
  14. package/ai/skills/stacks-utils/SKILL.md +8 -3
  15. package/app/Actions/Dashboard/Commerce/CommerceDiscountDestroyAction.ts +27 -0
  16. package/app/Actions/Dashboard/Commerce/CommerceDiscountStoreAction.ts +28 -0
  17. package/app/Actions/Dashboard/Commerce/CommerceDiscountUpdateAction.ts +30 -0
  18. package/app/Actions/Dashboard/Commerce/CommerceDiscountsAction.ts +42 -0
  19. package/app/Actions/Dashboard/Commerce/CommerceUpsellDestroyAction.ts +31 -0
  20. package/app/Actions/Dashboard/Commerce/CommerceUpsellDetailAction.ts +28 -0
  21. package/app/Actions/Dashboard/Commerce/CommerceUpsellStoreAction.ts +26 -0
  22. package/app/Actions/Dashboard/Commerce/CommerceUpsellUpdateAction.ts +29 -0
  23. package/app/Actions/Dashboard/Commerce/CommerceUpsellsAction.ts +40 -0
  24. package/app/Actions/Dashboard/Commerce/commerce-discount-list.ts +204 -0
  25. package/app/Actions/Dashboard/Commerce/commerce-discount-write.ts +53 -0
  26. package/app/Actions/Dashboard/Commerce/commerce-discounts-upsells.test.ts +228 -0
  27. package/app/Actions/Dashboard/Commerce/commerce-upsell-list.ts +289 -0
  28. package/app/Actions/Dashboard/Commerce/discount-records.ts +392 -0
  29. package/app/Actions/Dashboard/Commerce/upsell-offer-records.ts +307 -0
  30. package/app/Actions/Dashboard/Models/ModelSaveAction.ts +6 -1
  31. package/app/Actions/Dashboard/Models/model-relations.ts +17 -7
  32. package/app/Actions/Dashboard/Models/model-row-writes.ts +9 -8
  33. package/app/Actions/Dashboard/Models/model-write.ts +51 -2
  34. package/app/Actions/Dashboard/Remote/RemoteCommandRunAction.ts +1 -2
  35. package/app/Actions/Dashboard/Remote/RemoteTerminalCloseAction.ts +1 -2
  36. package/app/Actions/Dashboard/Remote/RemoteTerminalInputAction.ts +1 -2
  37. package/app/Actions/Dashboard/Remote/RemoteTerminalOpenAction.ts +1 -2
  38. package/app/Actions/Dashboard/Remote/RemoteTerminalResizeAction.ts +1 -2
  39. package/app/Actions/Dashboard/Remote/RemoteTerminalStreamAction.ts +1 -2
  40. package/app/Actions/Dashboard/Remote/remote-commands.test.ts +2 -2
  41. package/app/Actions/Dashboard/Remote/remote-commands.ts +4 -4
  42. package/app/Actions/Dashboard/Remote/remote-terminal.test.ts +45 -25
  43. package/app/Actions/Dashboard/Remote/remote-terminal.ts +9 -9
  44. package/app/Actions/Storefront/AcceptOrderOfferAction.ts +68 -0
  45. package/app/Actions/Storefront/ApplyDiscountCodeAction.ts +83 -0
  46. package/app/Actions/Storefront/DeclineOrderOfferAction.ts +25 -0
  47. package/app/Actions/Storefront/PlaceOrderAction.ts +135 -72
  48. package/app/Gates.ts +4 -4
  49. package/app/Mail/OrderConfirmation.ts +7 -1
  50. package/app/Models/commerce/Cart.ts +14 -0
  51. package/app/Models/commerce/Discount.ts +255 -0
  52. package/app/Models/commerce/PostPurchaseOffer.ts +175 -0
  53. package/app/Models/commerce/PostPurchaseOfferResponse.ts +145 -0
  54. package/app/Policies/PostPolicy.ts +11 -11
  55. package/app/Storefront/DiscountCodeMessages.ts +12 -0
  56. package/app/Storefront/OrderKey.ts +29 -0
  57. package/app/Storefront/StorefrontPricing.ts +211 -0
  58. package/app/Storefront/UpsellCharge.ts +43 -0
  59. package/functions/projects.test.ts +38 -0
  60. package/functions/projects.ts +99 -0
  61. package/ide/vscode/package.json +1 -1
  62. package/package.json +7 -7
  63. package/resources/components/Dashboard/Commerce/CommerceDiscountBreakdown.stx +72 -0
  64. package/resources/components/Dashboard/Commerce/CommerceDiscountDeleteDialog.stx +19 -0
  65. package/resources/components/Dashboard/Commerce/CommerceDiscountDetailsDialog.stx +110 -0
  66. package/resources/components/Dashboard/Commerce/CommerceDiscountDialog.stx +353 -0
  67. package/resources/components/Dashboard/Commerce/CommerceDiscountsDashboard.stx +211 -0
  68. package/resources/components/Dashboard/Commerce/CommerceDiscountsTable.stx +105 -0
  69. package/resources/components/Dashboard/Commerce/CommerceProductPicker.stx +115 -0
  70. package/resources/components/Dashboard/Commerce/CommerceUpsellDeleteDialog.stx +21 -0
  71. package/resources/components/Dashboard/Commerce/CommerceUpsellDetailsDialog.stx +153 -0
  72. package/resources/components/Dashboard/Commerce/CommerceUpsellDialog.stx +191 -0
  73. package/resources/components/Dashboard/Commerce/CommerceUpsellsDashboard.stx +214 -0
  74. package/resources/components/Dashboard/Commerce/CommerceUpsellsTable.stx +91 -0
  75. package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +4 -19
  76. package/resources/components/Dashboard/ProjectSwitcher.stx +302 -0
  77. package/resources/components/Dashboard/Settings/SettingsDashboard.stx +5 -3
  78. package/resources/components/Dashboard/UI/SearchFilter.stx +7 -4
  79. package/resources/components/Storefront/OrderSummary.stx +17 -0
  80. package/resources/functions/dashboard/project-switcher.test.ts +14 -0
  81. package/resources/functions/dashboard/project-switcher.ts +28 -0
  82. package/resources/functions/dashboard/sidebar.ts +4 -1
  83. package/resources/plugins/preloader.ts +33 -2
  84. package/resources/views/cart.stx +50 -16
  85. package/resources/views/checkout/contact.stx +11 -5
  86. package/resources/views/checkout/payment.stx +11 -5
  87. package/resources/views/checkout/shipping.stx +11 -5
  88. package/resources/views/orders/[id].stx +227 -50
  89. package/routes/dashboard-api.ts +12 -0
  90. package/routes/dashboard.ts +2 -0
  91. package/routes/storefront.ts +8 -0
  92. package/views/dashboard/commerce/discounts/index.stx +10 -0
  93. package/views/dashboard/commerce/upsells/index.stx +10 -0
  94. package/views/dashboard/layouts/default.stx +17 -0
@@ -0,0 +1,211 @@
1
+ <script client>
2
+ import type { DiscountRecord, DiscountSummary } from '../../../../app/Actions/Dashboard/Commerce/discount-records'
3
+ import { DashboardApiError, dashboardApi } from '../../../../functions/dashboard-api'
4
+ import { useServerList } from '../../../../functions/dashboard-list'
5
+ import { pushToast } from '../../../../functions/toasts'
6
+
7
+ interface DiscountIndexResponse {
8
+ records: DiscountRecord[]
9
+ total: number
10
+ page: number
11
+ summary: DiscountSummary
12
+ currency: string
13
+ }
14
+
15
+ const emptySummary: DiscountSummary = {
16
+ total: 0,
17
+ automatic: 0,
18
+ code: 0,
19
+ active: 0,
20
+ scheduled: 0,
21
+ expired: 0,
22
+ exhausted: 0,
23
+ disabled: 0,
24
+ redemptions: 0,
25
+ byType: { percentage: 0, fixed_amount: 0, buy_x_get_y: 0, volume: 0, free_shipping: 0 },
26
+ mostUsed: [],
27
+ }
28
+ const summary = state<DiscountSummary>({ ...emptySummary })
29
+ /** The store currency: amounts are minor units of it. */
30
+ const currency = state('USD')
31
+ const methodFilter = state('all')
32
+ const typeFilter = state('all')
33
+ const stateFilter = state('all')
34
+ const sort = state('newest')
35
+ const dialogOpen = state(false)
36
+ const dialogMode = state<'add' | 'edit'>('add')
37
+ const editingRecord = state<DiscountRecord | null>(null)
38
+ const detailsRecord = state<DiscountRecord | null>(null)
39
+ const deletingRecord = state<DiscountRecord | null>(null)
40
+ const saving = state(false)
41
+ const deleting = state(false)
42
+ const validationErrors = state<Record<string, string>>({})
43
+
44
+ const SELECT_SORTS: Record<string, { sort: string, direction: 'asc' | 'desc' }> = {
45
+ newest: { sort: 'newest', direction: 'desc' },
46
+ title: { sort: 'title', direction: 'asc' },
47
+ usage: { sort: 'usage', direction: 'desc' },
48
+ ends: { sort: 'ends', direction: 'asc' },
49
+ }
50
+
51
+ const {
52
+ records,
53
+ total,
54
+ page,
55
+ perPage,
56
+ search,
57
+ loading,
58
+ loadError,
59
+ load,
60
+ changePage,
61
+ changePageSize,
62
+ changeSort,
63
+ } = useServerList<DiscountRecord>({
64
+ fetch: query => dashboardApi<DiscountIndexResponse>(`/api/dashboard/commerce/discounts?${query}`),
65
+ defaultSort: () => SELECT_SORTS[sort()] ?? SELECT_SORTS.newest!,
66
+ columnSorts: { title: 'title', startsAt: 'starts', endsAt: 'ends' },
67
+ filters: () => ({ method: methodFilter(), type: typeFilter(), state: stateFilter() }),
68
+ onLoad: (result) => {
69
+ const data = result as DiscountIndexResponse
70
+ summary.set(data.summary ?? { ...emptySummary })
71
+ currency.set(data.currency || 'USD')
72
+ },
73
+ onError: error => pushToast('error', 'Could not load discounts', { detail: error instanceof Error ? error.message : String(error) }),
74
+ })
75
+
76
+ function matchingLabel(): string {
77
+ const count = total()
78
+ return `${count.toLocaleString()} matching ${count === 1 ? 'discount' : 'discounts'}`
79
+ }
80
+
81
+ function metricCards(): Array<{ label: string, value: string, detail: string }> {
82
+ const current = summary()
83
+ return [
84
+ { label: 'Active now', value: String(current.active), detail: `of ${current.total} discounts` },
85
+ { label: 'Automatic', value: String(current.automatic), detail: `${current.code} by code` },
86
+ { label: 'Scheduled', value: String(current.scheduled), detail: `${current.expired} expired, ${current.exhausted} used up` },
87
+ { label: 'Uses', value: current.redemptions.toLocaleString(), detail: 'Orders that used a discount' },
88
+ ]
89
+ }
90
+
91
+ function openAdd(): void {
92
+ dialogMode.set('add')
93
+ editingRecord.set(null)
94
+ validationErrors.set({})
95
+ dialogOpen.set(true)
96
+ }
97
+
98
+ function openEdit(record: DiscountRecord): void {
99
+ dialogMode.set('edit')
100
+ editingRecord.set(record)
101
+ validationErrors.set({})
102
+ dialogOpen.set(true)
103
+ }
104
+
105
+ function closeDialog(): void {
106
+ if (saving())
107
+ return
108
+ dialogOpen.set(false)
109
+ editingRecord.set(null)
110
+ validationErrors.set({})
111
+ }
112
+
113
+ async function saveDiscount(payload: Record<string, unknown>): Promise<void> {
114
+ const current = editingRecord()
115
+ const editing = dialogMode() === 'edit' && current !== null
116
+ saving.set(true)
117
+ validationErrors.set({})
118
+ try {
119
+ await dashboardApi(editing ? `/api/dashboard/commerce/discounts/${current.id}` : '/api/dashboard/commerce/discounts', {
120
+ method: editing ? 'PATCH' : 'POST',
121
+ body: payload,
122
+ })
123
+ dialogOpen.set(false)
124
+ editingRecord.set(null)
125
+ pushToast('success', editing ? 'Discount updated' : 'Discount added', { detail: String(payload.title ?? '') })
126
+ await load()
127
+ }
128
+ catch (error) {
129
+ if (error instanceof DashboardApiError)
130
+ validationErrors.set(error.fields ?? {})
131
+ pushToast('error', 'Could not save discount', { detail: error instanceof Error ? error.message : String(error) })
132
+ }
133
+ finally {
134
+ saving.set(false)
135
+ }
136
+ }
137
+
138
+ function openDetails(record: DiscountRecord): void {
139
+ detailsRecord.set(record)
140
+ }
141
+
142
+ function closeDetails(): void {
143
+ detailsRecord.set(null)
144
+ }
145
+
146
+ function openDelete(record: DiscountRecord): void {
147
+ deletingRecord.set(record)
148
+ }
149
+
150
+ function closeDelete(): void {
151
+ if (!deleting())
152
+ deletingRecord.set(null)
153
+ }
154
+
155
+ async function deleteDiscount(): Promise<void> {
156
+ const current = deletingRecord()
157
+ if (!current)
158
+ return
159
+ deleting.set(true)
160
+ try {
161
+ await dashboardApi(`/api/dashboard/commerce/discounts/${current.id}`, { method: 'DELETE' })
162
+ deletingRecord.set(null)
163
+ detailsRecord.set(null)
164
+ pushToast('success', 'Discount deleted', { detail: current.title })
165
+ await load()
166
+ }
167
+ catch (error) {
168
+ pushToast('error', 'Could not delete discount', { detail: error instanceof Error ? error.message : String(error) })
169
+ }
170
+ finally {
171
+ deleting.set(false)
172
+ }
173
+ }
174
+
175
+ onMount(() => {
176
+ void load()
177
+ })
178
+ </script>
179
+
180
+ <div class="flex flex-col gap-6">
181
+ <PageHeader title="Discounts" description="Automatic discounts and discount codes: buy X get Y, volume tiers, amounts off and free shipping.">
182
+ <div class="flex flex-wrap gap-2">
183
+ <Button variant="secondary" :loading="loading()" @click="load()"><span :if="!loading()" class="h-4 w-4 i-hugeicons-refresh"></span>Refresh</Button>
184
+ <Button @click="openAdd()"><span class="h-4 w-4 i-hugeicons-add-01"></span>Add discount</Button>
185
+ </div>
186
+ </PageHeader>
187
+
188
+ <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>
189
+
190
+ <MetricCards label="Discount metrics" columns="grid-cols-2 lg:grid-cols-4" :items="metricCards()" />
191
+
192
+ <CommerceDiscountBreakdown :summary="summary()" />
193
+
194
+ <section class="flex flex-col gap-3">
195
+ <div class="grid gap-3 grid-cols-1 sm:grid-cols-2 xl:grid-cols-6">
196
+ <div class="sm:col-span-2"><SearchFilter v-model:searchValue="search" placeholder="Search titles or codes" ariaLabel="Search discounts" /></div>
197
+ <Select v-model:value="stateFilter" ariaLabel="Discount status" placeholder="" :options="[{ value: 'all', label: 'Any status' }, { value: 'active', label: 'Active' }, { value: 'scheduled', label: 'Scheduled' }, { value: 'exhausted', label: 'Used up' }, { value: 'expired', label: 'Expired' }, { value: 'disabled', label: 'Disabled' }]" />
198
+ <Select v-model:value="methodFilter" ariaLabel="Discount method" placeholder="" :options="[{ value: 'all', label: 'Automatic and codes' }, { value: 'automatic', label: 'Automatic' }, { value: 'code', label: 'Codes' }]" />
199
+ <Select v-model:value="typeFilter" ariaLabel="Discount type" placeholder="" :options="[{ value: 'all', label: 'All types' }, { value: 'percentage', label: 'Percentage' }, { value: 'fixed_amount', label: 'Amount off' }, { value: 'buy_x_get_y', label: 'Buy X get Y' }, { value: 'volume', label: 'Volume tiers' }, { value: 'free_shipping', label: 'Free shipping' }]" />
200
+ <Select v-model:value="sort" ariaLabel="Sort discounts" placeholder="" :options="[{ value: 'newest', label: 'Newest' }, { value: 'title', label: 'Title' }, { value: 'usage', label: 'Most used' }, { value: 'ends', label: 'Ending soonest' }]" />
201
+ </div>
202
+
203
+ <p class="text-gray-500 text-sm dark:text-neutral-400">{{ matchingLabel() }}</p>
204
+
205
+ <CommerceDiscountsTable :sort-reset-key="sort()" :records="records()" :total="total()" :current-page="page()" :per-page="perPage()" :loading="loading()" @view="openDetails" @edit="openEdit" @delete="openDelete" @page-change="changePage" @page-size-change="changePageSize" @sort="changeSort" />
206
+ </section>
207
+ </div>
208
+
209
+ <CommerceDiscountDialog :open="dialogOpen()" :mode="dialogMode()" :record="editingRecord()" :currency="currency()" :busy="saving()" :errors="validationErrors()" @submit="saveDiscount" @close="closeDialog()" />
210
+ <CommerceDiscountDetailsDialog :open="Boolean(detailsRecord())" :record="detailsRecord()" :currency="currency()" @edit="openEdit" @delete="openDelete" @close="closeDetails()" />
211
+ <CommerceDiscountDeleteDialog :open="Boolean(deletingRecord())" :record="deletingRecord()" :busy="deleting()" @confirm="deleteDiscount()" @close="closeDelete()" />
@@ -0,0 +1,105 @@
1
+ @import('../UI/Table')
2
+
3
+ <script client>
4
+ import type { DiscountRecord } from '../../../../app/Actions/Dashboard/Commerce/discount-records'
5
+
6
+ const records = useReactiveProp('records', [] as DiscountRecord[])
7
+ const loading = useReactiveProp('loading', false)
8
+ /** The parent's sort select: a change hands the order back from a header sort. */
9
+ const sortResetKey = useReactiveProp<unknown>('sortResetKey', '')
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
+ /** The kind of discount and what it comes off, in a few words. */
16
+ function kind(record: DiscountRecord): string {
17
+ switch (record.type) {
18
+ case 'percentage': return record.appliesTo === 'product' ? 'Percentage off products' : 'Percentage off the order'
19
+ case 'fixed_amount': return record.appliesTo === 'product' ? (record.perItem ? 'Amount off each item' : 'Amount off products') : 'Amount off the order'
20
+ case 'buy_x_get_y': return 'Buy X get Y'
21
+ case 'volume': return 'Volume tiers'
22
+ default: return 'Shipping'
23
+ }
24
+ }
25
+
26
+ const COLUMNS = [
27
+ { key: 'title', label: 'Discount', sortable: true, subtitleKey: 'methodLabel', class: 'font-medium text-gray-900 dark:text-white' },
28
+ {
29
+ key: 'label',
30
+ label: 'Offer',
31
+ subtitleKey: 'kind',
32
+ searchable: false,
33
+ class: 'font-semibold text-emerald-700 whitespace-nowrap dark:text-emerald-300 tracking-wide text-xs',
34
+ },
35
+ {
36
+ key: 'state',
37
+ label: 'Status',
38
+ type: 'badge' as const,
39
+ badgeClasses: {
40
+ active: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-300',
41
+ scheduled: 'bg-blue-100 text-blue-800 dark:bg-blue-950/50 dark:text-blue-300',
42
+ exhausted: 'bg-amber-100 text-amber-800 dark:bg-amber-950/50 dark:text-amber-300',
43
+ },
44
+ badgeLabels: { active: 'Active', scheduled: 'Scheduled', expired: 'Expired', exhausted: 'Used up', disabled: 'Disabled' },
45
+ },
46
+ { key: 'usageLabel', label: 'Used', align: 'right' as const, searchable: false, class: 'font-mono whitespace-nowrap' },
47
+ // Calendar days: parseDashboardDate reads them as that day in every zone.
48
+ { key: 'startsAt', label: 'Starts', type: 'date' as const, sortable: true, emptyText: 'Now', class: 'whitespace-nowrap' },
49
+ { key: 'endsAt', label: 'Ends', type: 'date' as const, sortable: true, emptyText: 'Never', class: 'whitespace-nowrap' },
50
+ ]
51
+
52
+ const ROW_ACTIONS = [
53
+ { action: 'view', label: 'View' },
54
+ { action: 'edit', label: 'Edit' },
55
+ { action: 'delete', label: 'Delete' },
56
+ ]
57
+
58
+ const rows = derived(() => records().map(record => ({
59
+ ...record,
60
+ methodLabel: record.method === 'code' ? `Code ${record.code}` : 'Automatic',
61
+ kind: kind(record),
62
+ usageLabel: `${record.usageCount.toLocaleString()} / ${record.usageLimit ? record.usageLimit.toLocaleString() : 'No limit'}`,
63
+ })))
64
+
65
+ function handleRowAction(payload: { action: string, row: DiscountRecord }): void {
66
+ emit(payload.action, payload.row)
67
+ }
68
+
69
+ function changePage(page: number): void {
70
+ emit('page-change', page)
71
+ }
72
+
73
+ function changePageSize(size: number): void {
74
+ emit('page-size-change', size)
75
+ }
76
+
77
+ function changeSort(sort: { key: string, direction: string }): void {
78
+ emit('sort', sort)
79
+ }
80
+ </script>
81
+
82
+ {{--
83
+ No `searchable` or `filterable`: the parent dashboard owns the search box
84
+ and the filter selects. The server pages and sorts what they match.
85
+ --}}
86
+ <Table
87
+ :sort-reset-key="sortResetKey()"
88
+ :columns="COLUMNS"
89
+ :data="rows()"
90
+ :loading="loading()"
91
+ :row-actions="ROW_ACTIONS"
92
+ action-label-key="title"
93
+ paginated
94
+ manual-pagination
95
+ manual-sort
96
+ :total="total()"
97
+ :current-page="currentPage()"
98
+ :page-size="perPage()"
99
+ empty-title="No discounts found"
100
+ empty-description="Add a discount, or adjust the filters."
101
+ @row-action="handleRowAction"
102
+ @page-change="changePage"
103
+ @page-size-change="changePageSize"
104
+ @sort="changeSort"
105
+ />
@@ -0,0 +1,115 @@
1
+ <script client>
2
+ import type { ProductChoice } from '../../../../app/Actions/Dashboard/Commerce/commerce-choice-records'
3
+ import { dashboardApi } from '../../../../functions/dashboard-api'
4
+
5
+ /**
6
+ * Several products, picked by searching: the chosen ones as removable chips,
7
+ * the matches under a search box. The products come from the server search
8
+ * the other commerce dialogs use (`/api/dashboard/commerce/product-choices`),
9
+ * so a store with thousands of products is searched, not listed.
10
+ *
11
+ * `selected` is `[{ id, label }]`; every change emits the whole new list.
12
+ */
13
+ interface PickedProduct { id: string, label: string }
14
+
15
+ const selected = useReactiveProp('selected', [] as PickedProduct[])
16
+ const label = useReactiveProp('label', 'Products')
17
+ const hint = useReactiveProp('hint', '')
18
+ const emptyLabel = useReactiveProp('emptyLabel', 'No products chosen')
19
+ const max = useReactiveProp('max', 0)
20
+ const error = useReactiveProp('error', '')
21
+ const emit = defineEmits(['change'])
22
+
23
+ // Not `query`: the render context has one of its own (the request's).
24
+ const searchTerm = state('')
25
+ const matches = state<ProductChoice[]>([])
26
+ const searching = state(false)
27
+ let request = 0
28
+ let timer: ReturnType<typeof setTimeout> | null = null
29
+
30
+ async function search(term: string): Promise<void> {
31
+ const current = ++request
32
+ if (!term) {
33
+ matches.set([])
34
+ searching.set(false)
35
+ return
36
+ }
37
+ searching.set(true)
38
+ let found: ProductChoice[] = []
39
+ try {
40
+ const data = await dashboardApi<{ choices?: ProductChoice[] }>(`/api/dashboard/commerce/product-choices?${new URLSearchParams({ q: term, limit: '8' })}`)
41
+ found = Array.isArray(data.choices) ? data.choices : []
42
+ }
43
+ catch {
44
+ // Soft-fail: what is already chosen stays chosen.
45
+ }
46
+ if (current !== request)
47
+ return
48
+ matches.set(found)
49
+ searching.set(false)
50
+ }
51
+
52
+ function searchSoon(): void {
53
+ if (timer)
54
+ clearTimeout(timer)
55
+ timer = setTimeout(() => { void search(searchTerm().trim()) }, 250)
56
+ }
57
+
58
+ function isChosen(id: string): boolean {
59
+ return selected().some(product => product.id === id)
60
+ }
61
+
62
+ function full(): boolean {
63
+ return max() > 0 && selected().length >= max()
64
+ }
65
+
66
+ /** Matches not chosen yet. */
67
+ function options(): ProductChoice[] {
68
+ return matches().filter(choice => !isChosen(choice.id))
69
+ }
70
+
71
+ function add(choice: ProductChoice): void {
72
+ if (isChosen(choice.id) || full())
73
+ return
74
+ emit('change', [...selected(), { id: choice.id, label: choice.label }])
75
+ searchTerm.set('')
76
+ matches.set([])
77
+ }
78
+
79
+ function remove(id: string): void {
80
+ emit('change', selected().filter(product => product.id !== id))
81
+ }
82
+ </script>
83
+
84
+ <div class="flex flex-col gap-2">
85
+ <div class="flex items-baseline justify-between">
86
+ <span class="font-medium text-gray-700 text-sm dark:text-neutral-200">{{ label() }}</span>
87
+ <span :if="max() > 0" class="tabular-nums text-gray-400 text-xs dark:text-neutral-500">{{ selected().length }} / {{ max() }}</span>
88
+ </div>
89
+
90
+ <ul :if="selected().length > 0" class="flex flex-wrap gap-1.5" aria-label="Chosen products">
91
+ <li :for="product in selected()" :key="product.id" class="inline-flex gap-1 items-center pl-2.5 pr-1 py-1 text-gray-800 text-xs dark:text-neutral-100 bg-gray-100 dark:bg-neutral-700 rounded-full">
92
+ <span class="max-w-[14rem] truncate">{{ product.label }}</span>
93
+ <button type="button" class="inline-flex items-center justify-center h-5 w-5 text-gray-500 hover:text-gray-900 dark:hover:text-white hover:bg-gray-200 dark:hover:bg-neutral-600 rounded-full transition-colors" :aria-label="'Remove ' + product.label" @click="remove(product.id)">
94
+ <span class="h-3 w-3 i-hugeicons-cancel-01" aria-hidden="true"></span>
95
+ </button>
96
+ </li>
97
+ </ul>
98
+ <p :else class="text-gray-500 text-xs dark:text-neutral-400">{{ emptyLabel() }}</p>
99
+
100
+ <div :if="!full()" class="relative">
101
+ <Input v-model:value="searchTerm" type="search" ariaLabel="Search products to add" placeholder="Search products by name or id" @input="searchSoon()" />
102
+ <ul :if="options().length > 0" class="absolute overflow-auto z-20 mt-1 py-1 max-h-56 w-full bg-white dark:bg-neutral-800 border border-gray-200 rounded-lg dark:border-neutral-700 shadow-lg" role="listbox">
103
+ <li :for="choice in options()" :key="choice.id" role="option">
104
+ <button type="button" class="flex gap-3 items-center justify-between px-3 py-2 w-full text-left text-sm hover:bg-gray-50 dark:hover:bg-neutral-700" @click="add(choice)">
105
+ <span class="text-gray-900 truncate dark:text-white">{{ choice.label }}</span>
106
+ <span class="flex-shrink-0 text-gray-400 text-xs">{{ choice.detail }}</span>
107
+ </button>
108
+ </li>
109
+ </ul>
110
+ <p :if="searching()" class="mt-1 text-gray-400 text-xs">Searching...</p>
111
+ </div>
112
+
113
+ <p :if="error()" class="text-red-600 text-xs dark:text-red-400">{{ error() }}</p>
114
+ <p :else-if="hint()" class="text-gray-500 text-xs dark:text-neutral-400">{{ hint() }}</p>
115
+ </div>
@@ -0,0 +1,21 @@
1
+ <script client>
2
+ import type { UpsellOfferRecord } from '../../../../app/Actions/Dashboard/Commerce/upsell-offer-records'
3
+
4
+ const open = useReactiveProp('open', false)
5
+ const record = useReactiveProp('record', null as UpsellOfferRecord | null)
6
+ const busy = useReactiveProp('busy', false)
7
+ const emit = defineEmits(['close', 'confirm'])
8
+ const description = derived(() => (record()?.stats.views ?? 0) > 0
9
+ ? `"${record()?.name}" has been shown to orders, and those responses are kept as the record of what was added. It cannot be deleted; edit it and switch it off instead.`
10
+ : `Delete "${record()?.name || 'this offer'}" permanently? It has not been shown to any order yet.`)
11
+ </script>
12
+
13
+ <ConfirmDialog
14
+ :isOpen="open()"
15
+ title="Delete offer"
16
+ :description="description()"
17
+ confirmLabel="Delete offer"
18
+ :busy="busy()"
19
+ @close="emit('close')"
20
+ @confirm="emit('confirm')"
21
+ />
@@ -0,0 +1,153 @@
1
+ <script client>
2
+ import type { UpsellOfferRecord, UpsellResponseRecord } from '../../../../app/Actions/Dashboard/Commerce/upsell-offer-records'
3
+ import { formatCurrency } from '@stacksjs/commerce/money'
4
+ import { dashboardApi } from '../../../../functions/dashboard-api'
5
+
6
+ /**
7
+ * An offer's results: the funnel from shown to taken, what it added to orders,
8
+ * and the latest responses, each with its order and outcome. The responses are
9
+ * read when the dialog opens.
10
+ */
11
+ const open = useReactiveProp('open', false)
12
+ const record = useReactiveProp('record', null as UpsellOfferRecord | null)
13
+ const currency = useReactiveProp('currency', 'USD')
14
+ const emit = defineEmits(['edit', 'close', 'delete'])
15
+
16
+ const responses = state<UpsellResponseRecord[]>([])
17
+ const loadingResponses = state(false)
18
+ const responsesError = state('')
19
+ let loadedFor = ''
20
+
21
+ const STATUS_LABELS: Record<string, string> = { viewed: 'Shown', pending: 'Confirming payment', accepted: 'Added', declined: 'Declined', failed: 'Payment failed' }
22
+ const STATUS_CLASSES: Record<string, string> = {
23
+ accepted: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-300',
24
+ failed: 'bg-red-100 text-red-800 dark:bg-red-950/50 dark:text-red-300',
25
+ pending: 'bg-amber-100 text-amber-800 dark:bg-amber-950/50 dark:text-amber-300',
26
+ declined: 'bg-gray-100 text-gray-700 dark:bg-neutral-700 dark:text-neutral-200',
27
+ viewed: 'bg-blue-50 text-blue-700 dark:bg-blue-950/40 dark:text-blue-300',
28
+ }
29
+
30
+ effect(() => {
31
+ const current = record()
32
+ if (!open() || !current) {
33
+ loadedFor = ''
34
+ return
35
+ }
36
+ if (loadedFor === current.id)
37
+ return
38
+ loadedFor = current.id
39
+ void loadResponses(current.id)
40
+ })
41
+
42
+ async function loadResponses(id: string): Promise<void> {
43
+ loadingResponses.set(true)
44
+ responsesError.set('')
45
+ try {
46
+ const data = await dashboardApi<{ responses?: UpsellResponseRecord[] }>(`/api/dashboard/commerce/upsells/${id}`)
47
+ if (loadedFor === id)
48
+ responses.set(Array.isArray(data.responses) ? data.responses : [])
49
+ }
50
+ catch (error) {
51
+ responsesError.set(error instanceof Error ? error.message : String(error))
52
+ }
53
+ finally {
54
+ loadingResponses.set(false)
55
+ }
56
+ }
57
+
58
+ function money(value: number | null | undefined): string {
59
+ return value == null ? '' : formatCurrency(value, currency())
60
+ }
61
+
62
+ function percent(rate: number): string {
63
+ return `${(rate * 100).toFixed(rate > 0 && rate < 0.1 ? 1 : 0)}%`
64
+ }
65
+
66
+ /** One bar per outcome, as a share of everything shown. */
67
+ function funnel(): Array<{ label: string, count: number, color: string, width: string }> {
68
+ const stats = record()?.stats
69
+ if (!stats)
70
+ return []
71
+ const share = (count: number) => `${stats.views ? Math.max(count ? 2 : 0, Math.round((count / stats.views) * 100)) : 0}%`
72
+ const answered = stats.accepted + stats.declined + stats.pending + stats.failed
73
+ return [
74
+ { label: 'Shown', count: stats.views, color: 'bg-blue-500', width: stats.views ? '100%' : '0%' },
75
+ { label: 'Added to order', count: stats.accepted, color: 'bg-emerald-500', width: share(stats.accepted) },
76
+ { label: 'Declined', count: stats.declined, color: 'bg-gray-400', width: share(stats.declined) },
77
+ { label: 'Payment failed', count: stats.failed, color: 'bg-red-400', width: share(stats.failed) },
78
+ { label: 'Confirming payment', count: stats.pending, color: 'bg-amber-400', width: share(stats.pending) },
79
+ { label: 'No answer yet', count: Math.max(0, stats.views - answered), color: 'bg-gray-200 dark:bg-neutral-600', width: share(Math.max(0, stats.views - answered)) },
80
+ ]
81
+ }
82
+
83
+ function responseLine(response: UpsellResponseRecord): string {
84
+ if (response.status === 'accepted' || response.status === 'pending' || response.status === 'failed')
85
+ return `${response.quantity ?? 0} × ${response.productLabel} at ${money(response.unitPrice)} each`
86
+ return response.productLabel
87
+ }
88
+
89
+ function editRecord(): void {
90
+ const current = record()
91
+ if (!current)
92
+ return
93
+ emit('edit', current)
94
+ emit('close')
95
+ }
96
+
97
+ function deleteRecord(): void {
98
+ const current = record()
99
+ if (!current)
100
+ return
101
+ emit('delete', current)
102
+ emit('close')
103
+ }
104
+ </script>
105
+
106
+ <Modal
107
+ :isOpen="open()"
108
+ :title="record()?.name || 'Offer'"
109
+ :description="(record()?.discountPercent || 0) + '% off ' + (record()?.products || []).map(p => p.label).join(', ')"
110
+ size="xl"
111
+ @close="emit('close')"
112
+ >
113
+ <div class="flex flex-col gap-6">
114
+ <dl class="grid gap-3 grid-cols-2 sm:grid-cols-4">
115
+ <div class="p-3 border border-gray-200 rounded-lg dark:border-neutral-700"><dt class="text-gray-500 text-xs dark:text-neutral-500">Shown</dt><dd class="mt-1 font-semibold tabular-nums text-gray-900 text-lg dark:text-white">{{ (record()?.stats.views || 0).toLocaleString() }}</dd></div>
116
+ <div class="p-3 border border-gray-200 rounded-lg dark:border-neutral-700"><dt class="text-gray-500 text-xs dark:text-neutral-500">Conversion</dt><dd class="mt-1 font-semibold tabular-nums text-gray-900 text-lg dark:text-white">{{ percent(record()?.stats.conversionRate || 0) }}</dd></div>
117
+ <div class="p-3 border border-gray-200 rounded-lg dark:border-neutral-700"><dt class="text-gray-500 text-xs dark:text-neutral-500">Added to orders</dt><dd class="mt-1 font-semibold tabular-nums text-gray-900 text-lg dark:text-white">{{ money(record()?.stats.revenue || 0) }}</dd></div>
118
+ <div class="p-3 border border-gray-200 rounded-lg dark:border-neutral-700"><dt class="text-gray-500 text-xs dark:text-neutral-500">Units</dt><dd class="mt-1 font-semibold tabular-nums text-gray-900 text-lg dark:text-white">{{ (record()?.stats.units || 0).toLocaleString() }}</dd></div>
119
+ </dl>
120
+
121
+ <section aria-label="Funnel">
122
+ <h3 class="font-semibold text-gray-900 text-sm dark:text-white">Funnel</h3>
123
+ <div class="mt-3 space-y-2.5">
124
+ <div :for="step in funnel()" :key="step.label">
125
+ <div class="flex justify-between text-xs"><span class="text-gray-500 dark:text-neutral-400">{{ step.label }}</span><span class="font-mono text-gray-700 dark:text-neutral-200">{{ step.count.toLocaleString() }}</span></div>
126
+ <div class="mt-1 h-2 bg-gray-100 dark:bg-neutral-700 rounded-full"><div :class="'h-full rounded-full transition-[width] duration-500 ' + step.color" :style="'width: ' + step.width"></div></div>
127
+ </div>
128
+ </div>
129
+ </section>
130
+
131
+ <section aria-label="Latest responses">
132
+ <h3 class="font-semibold text-gray-900 text-sm dark:text-white">Latest responses</h3>
133
+ <p :if="loadingResponses()" class="mt-3 text-gray-500 text-sm dark:text-neutral-400">Loading...</p>
134
+ <p :else-if="responsesError()" class="mt-3 text-red-600 text-sm dark:text-red-400">{{ responsesError() }}</p>
135
+ <p :else-if="responses().length === 0" class="mt-3 text-gray-500 text-sm dark:text-neutral-400">No order has seen this offer yet.</p>
136
+ <ul :else class="mt-3 divide-gray-100 divide-y dark:divide-neutral-700">
137
+ <li :for="response in responses()" :key="response.id" class="flex gap-3 items-center justify-between py-2.5">
138
+ <div class="min-w-0">
139
+ <p class="text-gray-900 text-sm truncate dark:text-white">{{ responseLine(response) }}</p>
140
+ <p class="text-gray-500 text-xs dark:text-neutral-400">Order #{{ response.orderId }}<span :if="response.failureReason"> · {{ response.failureReason }}</span></p>
141
+ </div>
142
+ <div class="flex flex-shrink-0 gap-3 items-center">
143
+ <span :if="response.status === 'accepted'" class="font-semibold tabular-nums text-gray-900 text-sm dark:text-white">{{ money(response.amount) }}</span>
144
+ <span :class="'px-2 py-0.5 rounded-full text-xs font-medium ' + (STATUS_CLASSES[response.status] || '')">{{ STATUS_LABELS[response.status] || response.status }}</span>
145
+ </div>
146
+ </li>
147
+ </ul>
148
+ </section>
149
+ </div>
150
+ <template #footer>
151
+ <div class="flex gap-2 justify-between w-full"><Button variant="danger" @click="deleteRecord()">Delete</Button><div class="flex gap-2"><Button variant="secondary" @click="emit('close')">Close</Button><Button @click="editRecord()">Edit offer</Button></div></div>
152
+ </template>
153
+ </Modal>