@stacksjs/defaults 0.75.617 → 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,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>
@@ -0,0 +1,191 @@
1
+ <script client>
2
+ import type { UpsellOfferRecord } from '../../../../app/Actions/Dashboard/Commerce/upsell-offer-records'
3
+ import { minorToInput, moneyInputError, moneyInputStep, parseMoneyInput } from '@stacksjs/commerce/money'
4
+ import { formErrorMessages } from '../../../../functions/dashboard-form'
5
+
6
+ /**
7
+ * Add or edit a post-purchase offer: what the confirmation page says, which
8
+ * products it offers and at what discount, which orders see it and for how
9
+ * long. A preview shows the banner the shopper will read.
10
+ */
11
+ interface PickedProduct { id: string, label: string }
12
+
13
+ const open = useReactiveProp('open', false)
14
+ const mode = useReactiveProp('mode', 'add')
15
+ const record = useReactiveProp('record', null as UpsellOfferRecord | null)
16
+ const currency = useReactiveProp('currency', 'USD')
17
+ const busy = useReactiveProp('busy', false)
18
+ const errors = useReactiveProp('errors', {} as Record<string, string>)
19
+ const emit = defineEmits(['submit', 'close'])
20
+
21
+ const offerName = state('')
22
+ const headlineText = state('')
23
+ const messageText = state('')
24
+ const products = state<PickedProduct[]>([])
25
+ const discountPercent = state('60')
26
+ const minQuantity = state('1')
27
+ const defaultQuantity = state('1')
28
+ const maxQuantity = state('')
29
+ const triggers = state<PickedProduct[]>([])
30
+ const minOrderTotal = state('')
31
+ const windowMinutes = state('30')
32
+ const priority = state('0')
33
+ const startsAt = state('')
34
+ const endsAt = state('')
35
+ const isActive = state(true)
36
+ let hydrationKey = ''
37
+
38
+ effect(() => {
39
+ if (!open()) {
40
+ hydrationKey = ''
41
+ return
42
+ }
43
+ const current = record()
44
+ const key = `${mode()}:${current?.id || 'new'}`
45
+ if (hydrationKey === key)
46
+ return
47
+ hydrationKey = key
48
+ offerName.set(current?.name || '')
49
+ headlineText.set(current?.headline || '')
50
+ messageText.set(current?.message || '')
51
+ products.set((current?.products ?? []).map(p => ({ id: p.id, label: p.label })))
52
+ discountPercent.set(String(current?.discountPercent ?? 60))
53
+ minQuantity.set(String(current?.minQuantity ?? 1))
54
+ defaultQuantity.set(String(current?.defaultQuantity ?? 1))
55
+ maxQuantity.set(current?.maxQuantity ? String(current.maxQuantity) : '')
56
+ triggers.set((current?.triggerProducts ?? []).map(p => ({ id: p.id, label: p.label })))
57
+ minOrderTotal.set(current?.minOrderTotal != null ? minorToInput(current.minOrderTotal, currency()) : '')
58
+ windowMinutes.set(String(current?.windowMinutes ?? 30))
59
+ priority.set(String(current?.priority ?? 0))
60
+ startsAt.set(current?.startsAt || '')
61
+ endsAt.set(current?.endsAt || '')
62
+ isActive.set(current?.isActive ?? true)
63
+ })
64
+
65
+ function setProducts(list: PickedProduct[]): void {
66
+ products.set(list)
67
+ }
68
+
69
+ function setTriggers(list: PickedProduct[]): void {
70
+ triggers.set(list)
71
+ }
72
+
73
+ function whole(text: string): number | undefined {
74
+ if (!text.trim())
75
+ return undefined
76
+ const n = Number(text)
77
+ return Number.isFinite(n) ? n : undefined
78
+ }
79
+
80
+ function quantitiesValid(): boolean {
81
+ const min = Number(minQuantity())
82
+ const start = Number(defaultQuantity())
83
+ const max = maxQuantity().trim() ? Number(maxQuantity()) : null
84
+ return Number.isInteger(min) && min >= 1
85
+ && Number.isInteger(start) && start >= min
86
+ && (max === null || (Number.isInteger(max) && max >= min && start <= max))
87
+ }
88
+
89
+ function valid(): boolean {
90
+ const percent = Number(discountPercent())
91
+ const window = Number(windowMinutes())
92
+ return Boolean(offerName().trim())
93
+ && products().length > 0
94
+ && Number.isInteger(percent) && percent >= 0 && percent <= 100
95
+ && quantitiesValid()
96
+ && Number.isInteger(window) && window >= 1
97
+ && !moneyInputError(minOrderTotal(), currency(), { required: false })
98
+ }
99
+
100
+ /** The banner as the confirmation page will show it. */
101
+ function previewHeadline(): string {
102
+ return headlineText().trim() || 'One-time offer'
103
+ }
104
+
105
+ function previewMessage(): string {
106
+ return messageText().trim() || `Add ${minQuantity()}+ and get ${discountPercent() || 0}% off, only on this page.`
107
+ }
108
+
109
+ function submit(): void {
110
+ if (!valid())
111
+ return
112
+ emit('submit', {
113
+ name: offerName().trim(),
114
+ headline: headlineText().trim(),
115
+ message: messageText().trim(),
116
+ productIds: products().map(p => p.id),
117
+ discountPercent: Number(discountPercent()),
118
+ minQuantity: Number(minQuantity()),
119
+ defaultQuantity: Number(defaultQuantity()),
120
+ maxQuantity: whole(maxQuantity()),
121
+ triggerProductIds: triggers().map(p => p.id),
122
+ minOrderTotal: parseMoneyInput(minOrderTotal(), currency(), { required: false }) ?? undefined,
123
+ windowMinutes: Number(windowMinutes()),
124
+ priority: whole(priority()) ?? 0,
125
+ startsAt: startsAt() || undefined,
126
+ endsAt: endsAt() || undefined,
127
+ isActive: isActive(),
128
+ })
129
+ }
130
+
131
+ function errorMessages(): string[] {
132
+ return formErrorMessages(errors())
133
+ }
134
+ </script>
135
+
136
+ <Modal
137
+ :isOpen="open()"
138
+ :title="mode() === 'edit' ? 'Edit post-purchase offer' : 'Add post-purchase offer'"
139
+ description="Shown once on the order confirmation page. Accepting adds the items to the order just placed, charged to the same payment method."
140
+ size="xl"
141
+ @close="emit('close')"
142
+ >
143
+ <form id="upsell-form" class="flex flex-col gap-6" @submit.prevent="submit">
144
+ <ul :if="errorMessages().length > 0" class="p-3 space-y-1 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">
145
+ <li :for="text in errorMessages()" :key="text">{{ text }}</li>
146
+ </ul>
147
+
148
+ <section class="grid gap-4 grid-cols-1 sm:grid-cols-2" aria-label="What the shopper sees">
149
+ <div class="sm:col-span-2"><Input v-model:value="offerName" label="Name" hint="For you: how this offer is listed here" :maxLength="255" :required="true" /></div>
150
+ <Input v-model:value="headlineText" label="Headline" placeholder="One-time offer" :maxLength="255" />
151
+ <div class="sm:row-span-2"><Textarea v-model:value="messageText" label="Message" :rows="4" placeholder="Thank you for your purchase! Grab 5+ pairs and get 60% off." /></div>
152
+ <div class="flex gap-3 items-start p-4 bg-gray-50 dark:bg-neutral-900/50 border border-gray-200 rounded-lg dark:border-neutral-700" aria-label="Preview">
153
+ <span class="flex-shrink-0 mt-0.5 h-5 w-5 text-gray-600 dark:text-neutral-300 i-hugeicons-gift"></span>
154
+ <div class="min-w-0">
155
+ <p class="font-semibold text-gray-900 text-sm dark:text-white">{{ previewHeadline() }}</p>
156
+ <p class="mt-1 text-gray-600 text-sm dark:text-neutral-300">{{ previewMessage() }}</p>
157
+ </div>
158
+ </div>
159
+ </section>
160
+
161
+ <section class="flex flex-col gap-4" aria-label="The offer">
162
+ <CommerceProductPicker label="Products offered" :selected="products()" :max="12" emptyLabel="Choose the products to offer, in the order they should appear" :error="errors().productIds || ''" @change="setProducts" />
163
+ <div class="grid gap-4 grid-cols-2 sm:grid-cols-4">
164
+ <Input v-model:value="discountPercent" label="Percent off" type="number" min="0" max="100" step="1" :required="true" />
165
+ <Input v-model:value="minQuantity" label="Minimum quantity" type="number" min="1" step="1" :required="true" />
166
+ <Input v-model:value="defaultQuantity" label="Default quantity" type="number" min="1" step="1" :required="true" />
167
+ <Input v-model:value="maxQuantity" label="Maximum quantity" type="number" min="1" step="1" placeholder="No limit" />
168
+ </div>
169
+ <p :if="!quantitiesValid()" class="text-amber-700 text-xs dark:text-amber-300">The default quantity has to sit between the minimum and the maximum.</p>
170
+ </section>
171
+
172
+ <section class="flex flex-col gap-4" aria-label="Who sees it">
173
+ <p class="font-semibold text-gray-900 text-sm dark:text-white">Who sees it</p>
174
+ <CommerceProductPicker label="Only orders containing" :selected="triggers()" emptyLabel="Every order" hint="Leave empty to show the offer after any order." @change="setTriggers" />
175
+ <div class="grid gap-4 grid-cols-1 sm:grid-cols-3">
176
+ <Input v-model:value="minOrderTotal" label="Minimum order total" type="number" min="0" :step="moneyInputStep(currency())" placeholder="Any total" />
177
+ <Input v-model:value="windowMinutes" label="Open for (minutes)" type="number" min="1" max="10080" step="1" hint="After the order is placed" :required="true" />
178
+ <Input v-model:value="priority" label="Priority" type="number" step="1" hint="Higher shows first" />
179
+ <Input v-model:value="startsAt" label="Starts" type="date" />
180
+ <Input v-model:value="endsAt" label="Ends" type="date" />
181
+ </div>
182
+ </section>
183
+
184
+ <div class="p-4 bg-gray-50 dark:bg-neutral-900/50 rounded-lg">
185
+ <Toggle v-model:checked="isActive" label="Running" description="Switched off, the offer is kept with its results but shown to nobody." labelPosition="left" />
186
+ </div>
187
+ </form>
188
+ <template #footer>
189
+ <div class="flex gap-2 justify-end w-full"><Button variant="secondary" :disabled="busy()" @click="emit('close')">Cancel</Button><Button type="submit" form="upsell-form" :loading="busy()" :disabled="!valid()">{{ mode() === 'edit' ? 'Save offer' : 'Add offer' }}</Button></div>
190
+ </template>
191
+ </Modal>