@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,353 @@
1
+ <script client>
2
+ import type { DiscountRecord, DiscountType } from '../../../../app/Actions/Dashboard/Commerce/discount-records'
3
+ import { discountLabel } from '@stacksjs/commerce/discounts/engine'
4
+ import { formatCurrency, minorToInput, moneyInputError, moneyInputStep, parseMoneyInput } from '@stacksjs/commerce/money'
5
+ import { formErrorMessages } from '../../../../functions/dashboard-form'
6
+
7
+ /**
8
+ * Add or edit a discount. The fields follow the type: a percentage or an
9
+ * amount off (the order, or chosen products), buy X get Y, volume tiers, or
10
+ * free shipping. A preview shows the badge the storefront will draw, and the
11
+ * server checks the rule through the discount engine before saving it.
12
+ *
13
+ * Money fields are typed as decimals of the store currency and sent as
14
+ * integer minor units, like every commerce dialog.
15
+ */
16
+ interface PickedProduct { id: string, label: string }
17
+ interface TierRow { minQuantity: string, percent: string }
18
+
19
+ const open = useReactiveProp('open', false)
20
+ const mode = useReactiveProp('mode', 'add')
21
+ const record = useReactiveProp('record', null as DiscountRecord | null)
22
+ const currency = useReactiveProp('currency', 'USD')
23
+ const busy = useReactiveProp('busy', false)
24
+ const errors = useReactiveProp('errors', {} as Record<string, string>)
25
+ const emit = defineEmits(['submit', 'close'])
26
+
27
+ const TYPE_OPTIONS: Array<{ value: DiscountType, label: string }> = [
28
+ { value: 'percentage', label: 'Percentage off' },
29
+ { value: 'fixed_amount', label: 'Amount off' },
30
+ { value: 'buy_x_get_y', label: 'Buy X, get Y' },
31
+ { value: 'volume', label: 'Volume tiers (buy more, save more)' },
32
+ { value: 'free_shipping', label: 'Free shipping' },
33
+ ]
34
+
35
+ const TYPE_HINTS: Record<DiscountType, string> = {
36
+ percentage: 'A percentage off the whole order, or off the products you choose.',
37
+ fixed_amount: 'An amount off the order, off the chosen products once, or off each chosen item.',
38
+ buy_x_get_y: 'Buy a number of items, get more at a discount. The cheapest qualifying items are the ones discounted.',
39
+ volume: 'The more of the chosen products a shopper buys together, the bigger the percentage off.',
40
+ free_shipping: 'Waives the shipping fee, optionally only up to a rate you set.',
41
+ }
42
+
43
+ const titleText = state('')
44
+ const method = state<'automatic' | 'code'>('automatic')
45
+ const code = state('')
46
+ const type = state<DiscountType>('percentage')
47
+ const value = state('10')
48
+ const scope = state<'order' | 'product'>('order')
49
+ const perItem = state(false)
50
+ const targetProducts = state<PickedProduct[]>([])
51
+ const buyQuantity = state('4')
52
+ const buyProducts = state<PickedProduct[]>([])
53
+ const getQuantity = state('4')
54
+ const getProducts = state<PickedProduct[]>([])
55
+ const getPercent = state('100')
56
+ const maxApplications = state('')
57
+ const tiers = state<TierRow[]>([{ minQuantity: '5', percent: '10' }])
58
+ const maxShipping = state('')
59
+ const minimumSubtotal = state('')
60
+ const minimumQuantity = state('')
61
+ const maxAmount = state('')
62
+ const combineProduct = state(false)
63
+ const combineOrder = state(false)
64
+ const combineShipping = state(false)
65
+ const usageLimit = state('')
66
+ const startsAt = state('')
67
+ const endsAt = state('')
68
+ const isActive = state(true)
69
+ /** Kept as they were: the dialog edits products, and must not drop variant or category targets. */
70
+ let keptTargets = { target: { variantIds: [] as string[], categoryIds: [] as string[] }, buy: { variantIds: [] as string[], categoryIds: [] as string[] }, get: { variantIds: [] as string[], categoryIds: [] as string[] } }
71
+ let hydrationKey = ''
72
+
73
+ function picked(ids: string[], labels: Record<string, string>): PickedProduct[] {
74
+ return ids.map(id => ({ id, label: labels[id] ?? `Product #${id}` }))
75
+ }
76
+
77
+ effect(() => {
78
+ if (!open()) {
79
+ hydrationKey = ''
80
+ return
81
+ }
82
+ const current = record()
83
+ const key = `${mode()}:${current?.id || 'new'}`
84
+ if (hydrationKey === key)
85
+ return
86
+ hydrationKey = key
87
+ const labels = current?.productLabels ?? {}
88
+ titleText.set(current?.title || '')
89
+ method.set(current?.method || 'automatic')
90
+ code.set(current?.code || '')
91
+ type.set(current?.type || 'percentage')
92
+ value.set(current
93
+ ? current.type === 'fixed_amount' ? minorToInput(current.value, currency()) : String(current.value || '')
94
+ : '10')
95
+ scope.set(current?.appliesTo === 'product' ? 'product' : 'order')
96
+ perItem.set(current?.perItem ?? false)
97
+ targetProducts.set(picked(current?.target.productIds ?? [], labels))
98
+ buyQuantity.set(String(current?.buyQuantity ?? 4))
99
+ buyProducts.set(picked(current?.buyTarget.productIds ?? [], labels))
100
+ getQuantity.set(String(current?.getQuantity ?? 4))
101
+ getProducts.set(picked(current?.getTarget.productIds ?? [], labels))
102
+ getPercent.set(String(current?.getPercent ?? 100))
103
+ maxApplications.set(current?.maxApplications ? String(current.maxApplications) : '')
104
+ tiers.set(current?.tiers.length ? current.tiers.map(t => ({ minQuantity: String(t.minQuantity), percent: String(t.percent) })) : [{ minQuantity: '5', percent: '10' }])
105
+ maxShipping.set(current?.maxShipping != null ? minorToInput(current.maxShipping, currency()) : '')
106
+ minimumSubtotal.set(current?.minimumSubtotal ? minorToInput(current.minimumSubtotal, currency()) : '')
107
+ minimumQuantity.set(current?.minimumQuantity ? String(current.minimumQuantity) : '')
108
+ maxAmount.set(current?.maxAmount ? minorToInput(current.maxAmount, currency()) : '')
109
+ combineProduct.set(current?.combinesWith.product ?? false)
110
+ combineOrder.set(current?.combinesWith.order ?? false)
111
+ combineShipping.set(current?.combinesWith.shipping ?? false)
112
+ usageLimit.set(current?.usageLimit ? String(current.usageLimit) : '')
113
+ startsAt.set(current?.startsAt || '')
114
+ endsAt.set(current?.endsAt || '')
115
+ isActive.set(current?.isActive ?? true)
116
+ keptTargets = {
117
+ target: { variantIds: current?.target.variantIds ?? [], categoryIds: current?.target.categoryIds ?? [] },
118
+ buy: { variantIds: current?.buyTarget.variantIds ?? [], categoryIds: current?.buyTarget.categoryIds ?? [] },
119
+ get: { variantIds: current?.getTarget.variantIds ?? [], categoryIds: current?.getTarget.categoryIds ?? [] },
120
+ }
121
+ })
122
+
123
+ function isType(...types: DiscountType[]): boolean {
124
+ return types.includes(type())
125
+ }
126
+
127
+ /** Whether the discount reaches chosen products rather than the order. */
128
+ function targetsProducts(): boolean {
129
+ return isType('volume') || (isType('percentage', 'fixed_amount') && scope() === 'product')
130
+ }
131
+
132
+ function optionalWhole(text: string): number | undefined {
133
+ if (!text.trim())
134
+ return undefined
135
+ const n = Number(text)
136
+ return Number.isFinite(n) ? n : undefined
137
+ }
138
+
139
+ function optionalMoney(text: string): number | undefined {
140
+ return parseMoneyInput(text, currency(), { required: false }) ?? undefined
141
+ }
142
+
143
+ function target(products: PickedProduct[], kept: { variantIds: string[], categoryIds: string[] }) {
144
+ return { productIds: products.map(p => p.id), variantIds: kept.variantIds, categoryIds: kept.categoryIds }
145
+ }
146
+
147
+ function setTargetProducts(products: PickedProduct[]): void {
148
+ targetProducts.set(products)
149
+ }
150
+
151
+ function setBuyProducts(products: PickedProduct[]): void {
152
+ buyProducts.set(products)
153
+ }
154
+
155
+ function setGetProducts(products: PickedProduct[]): void {
156
+ getProducts.set(products)
157
+ }
158
+
159
+ function addTier(): void {
160
+ const last = tiers()[tiers().length - 1]
161
+ const next = last ? Number(last.minQuantity) * 2 || 10 : 5
162
+ tiers.set([...tiers(), { minQuantity: String(next), percent: '' }])
163
+ }
164
+
165
+ function setTier(index: number, field: keyof TierRow, text: string): void {
166
+ tiers.set(tiers().map((tier, i) => i === index ? { ...tier, [field]: text } : tier))
167
+ }
168
+
169
+ function removeTier(index: number): void {
170
+ tiers.set(tiers().filter((_, i) => i !== index))
171
+ }
172
+
173
+ function valueValid(): boolean {
174
+ if (isType('fixed_amount'))
175
+ return !moneyInputError(value(), currency(), { min: 1 })
176
+ if (isType('percentage')) {
177
+ const n = Number(value())
178
+ return Number.isInteger(n) && n >= 1 && n <= 100
179
+ }
180
+ return true
181
+ }
182
+
183
+ function valid(): boolean {
184
+ if (!titleText().trim() || (method() === 'code' && !code().trim()) || !valueValid())
185
+ return false
186
+ if (targetsProducts() && isType('percentage', 'fixed_amount') && targetProducts().length === 0)
187
+ return false
188
+ if (isType('volume') && tiers().length === 0)
189
+ return false
190
+ return !moneyInputError(minimumSubtotal(), currency(), { required: false })
191
+ && !moneyInputError(maxAmount(), currency(), { required: false })
192
+ && !moneyInputError(maxShipping(), currency(), { required: false })
193
+ }
194
+
195
+ /** The badge the storefront will show for what is filled in so far. */
196
+ function preview(): string {
197
+ try {
198
+ const money = (minor: number) => formatCurrency(minor, currency())
199
+ switch (type()) {
200
+ case 'percentage': return discountLabel({ effect: { type: 'percentage', percent: Number(value()) || 0 } })
201
+ case 'fixed_amount': return discountLabel({ effect: { type: 'fixed_amount', amount: parseMoneyInput(value(), currency(), { required: false }) ?? 0, perItem: perItem() && scope() === 'product' } }, money)
202
+ case 'buy_x_get_y': return discountLabel({ effect: { type: 'buy_x_get_y', buyQuantity: Number(buyQuantity()) || 0, getQuantity: Number(getQuantity()) || 0, getPercent: Number(getPercent()) || 0 } })
203
+ case 'volume': return discountLabel({ effect: { type: 'volume', tiers: tiers().map(t => ({ minQuantity: Number(t.minQuantity) || 0, percent: Number(t.percent) || 0 })) } })
204
+ default: return discountLabel({ effect: { type: 'free_shipping' } })
205
+ }
206
+ }
207
+ catch {
208
+ return ''
209
+ }
210
+ }
211
+
212
+ function submit(): void {
213
+ if (!valid())
214
+ return
215
+ emit('submit', {
216
+ title: titleText().trim(),
217
+ method: method(),
218
+ code: method() === 'code' ? code().trim().toUpperCase() : '',
219
+ type: type(),
220
+ value: isType('fixed_amount') ? parseMoneyInput(value(), currency(), { min: 1 }) : isType('percentage') ? Number(value()) : 0,
221
+ scope: isType('percentage', 'fixed_amount') ? scope() : null,
222
+ perItem: isType('fixed_amount') && scope() === 'product' && perItem(),
223
+ target: targetsProducts() ? target(targetProducts(), keptTargets.target) : null,
224
+ buyQuantity: optionalWhole(buyQuantity()),
225
+ buyTarget: target(buyProducts(), keptTargets.buy),
226
+ getQuantity: optionalWhole(getQuantity()),
227
+ getTarget: target(getProducts(), keptTargets.get),
228
+ getPercent: optionalWhole(getPercent()),
229
+ maxApplications: optionalWhole(maxApplications()),
230
+ tiers: tiers().map(t => ({ minQuantity: Number(t.minQuantity), percent: Number(t.percent) })),
231
+ maxShipping: optionalMoney(maxShipping()),
232
+ minimumSubtotal: optionalMoney(minimumSubtotal()),
233
+ minimumQuantity: optionalWhole(minimumQuantity()),
234
+ maxAmount: optionalMoney(maxAmount()),
235
+ combinesWith: { product: combineProduct(), order: combineOrder(), shipping: combineShipping() },
236
+ usageLimit: optionalWhole(usageLimit()),
237
+ isActive: isActive(),
238
+ startsAt: startsAt() || undefined,
239
+ endsAt: endsAt() || undefined,
240
+ })
241
+ }
242
+
243
+ function errorMessages(): string[] {
244
+ return formErrorMessages(errors())
245
+ }
246
+ </script>
247
+
248
+ <Modal
249
+ :isOpen="open()"
250
+ :title="mode() === 'edit' ? 'Edit discount' : 'Add discount'"
251
+ description="Automatic discounts apply by themselves; a code applies when a shopper enters it."
252
+ size="xl"
253
+ @close="emit('close')"
254
+ >
255
+ <form id="discount-form" class="flex flex-col gap-6" @submit.prevent="submit">
256
+ <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">
257
+ <li :for="message in errorMessages()" :key="message">{{ message }}</li>
258
+ </ul>
259
+
260
+ <section class="grid gap-4 grid-cols-1 sm:grid-cols-2" aria-label="Discount">
261
+ <div class="sm:col-span-2"><Input v-model:value="titleText" label="Title" hint="What shoppers see beside the saving, e.g. BUY 4, GET 4 FREE | 50% OFF" :maxLength="255" :required="true" /></div>
262
+ <Select v-model:value="method" label="Method" placeholder="" :options="[{ value: 'automatic', label: 'Automatic: applies by itself' }, { value: 'code', label: 'Discount code: shopper enters it' }]" />
263
+ <div :if="method() === 'code'"><Input v-model:value="code" label="Code" :maxLength="64" :required="true" :spellcheck="false" :monospace="true" class="uppercase" placeholder="WELCOME10" /></div>
264
+ <div :else></div>
265
+ <div class="sm:col-span-2">
266
+ <Select v-model:value="type" label="Type" placeholder="" :options="TYPE_OPTIONS" />
267
+ <p class="mt-1 text-gray-500 text-xs dark:text-neutral-400">{{ TYPE_HINTS[type()] }}</p>
268
+ </div>
269
+ </section>
270
+
271
+ <section :if="isType('percentage', 'fixed_amount')" class="grid gap-4 grid-cols-1 sm:grid-cols-2" aria-label="Value">
272
+ <div :if="isType('percentage')"><Input v-model:value="value" label="Percent off" type="number" min="1" max="100" step="1" :required="true" /></div>
273
+ <div :else><Input v-model:value="value" label="Amount off" type="number" min="0" :step="moneyInputStep(currency())" :required="true" :hint="'In ' + currency()" /></div>
274
+ <Select v-model:value="scope" label="Applies to" placeholder="" :options="[{ value: 'order', label: 'The entire order' }, { value: 'product', label: 'Specific products' }]" />
275
+ <div :if="scope() === 'product'" class="flex flex-col gap-3 sm:col-span-2">
276
+ <CommerceProductPicker label="Products" :selected="targetProducts()" emptyLabel="Choose at least one product" :error="errors().target || ''" @change="setTargetProducts" />
277
+ <div :if="isType('fixed_amount')"><Toggle v-model:checked="perItem" label="Take the amount off each item" description="Off: the amount comes off once across the chosen products." labelPosition="left" /></div>
278
+ </div>
279
+ </section>
280
+
281
+ <section :if="isType('buy_x_get_y')" class="grid gap-4 grid-cols-1 sm:grid-cols-2" aria-label="Buy X get Y">
282
+ <div class="flex flex-col gap-3 p-4 border border-gray-200 rounded-lg dark:border-neutral-700">
283
+ <p class="font-semibold text-gray-900 text-sm dark:text-white">Customer buys</p>
284
+ <Input v-model:value="buyQuantity" label="Quantity" type="number" min="1" step="1" :required="true" />
285
+ <CommerceProductPicker label="Of these products" :selected="buyProducts()" emptyLabel="Any product" @change="setBuyProducts" />
286
+ </div>
287
+ <div class="flex flex-col gap-3 p-4 border border-gray-200 rounded-lg dark:border-neutral-700">
288
+ <p class="font-semibold text-gray-900 text-sm dark:text-white">Customer gets</p>
289
+ <div class="grid gap-3 grid-cols-2">
290
+ <Input v-model:value="getQuantity" label="Quantity" type="number" min="1" step="1" :required="true" />
291
+ <Input v-model:value="getPercent" label="Percent off" type="number" min="1" max="100" step="1" hint="100 is free" :required="true" />
292
+ </div>
293
+ <CommerceProductPicker label="Of these products" :selected="getProducts()" emptyLabel="The same products as the purchase" @change="setGetProducts" />
294
+ </div>
295
+ <Input v-model:value="maxApplications" label="Uses per order" type="number" min="1" step="1" placeholder="Unlimited" hint="How many times one order can get it" />
296
+ </section>
297
+
298
+ <section :if="isType('volume')" class="flex flex-col gap-3" aria-label="Volume tiers">
299
+ <div class="flex items-center justify-between">
300
+ <p class="font-semibold text-gray-900 text-sm dark:text-white">Tiers</p>
301
+ <Button size="sm" variant="secondary" @click="addTier()"><span class="h-4 w-4 i-hugeicons-add-01"></span>Add tier</Button>
302
+ </div>
303
+ <ol class="flex flex-col gap-2">
304
+ <li :for="(tier, index) in tiers()" :key="index" class="flex gap-3 items-end">
305
+ <Input :value="tier.minQuantity" label="Buy at least" type="number" min="1" step="1" @update:value="setTier(index, 'minQuantity', $event)" />
306
+ <Input :value="tier.percent" label="Percent off" type="number" min="1" max="100" step="1" @update:value="setTier(index, 'percent', $event)" />
307
+ <Button variant="secondary" :disabled="tiers().length === 1" ariaLabel="Remove tier" @click="removeTier(index)"><span class="h-4 w-4 i-hugeicons-delete-02"></span></Button>
308
+ </li>
309
+ </ol>
310
+ <p :if="errors().tiers" class="text-red-600 text-xs dark:text-red-400">{{ errors().tiers }}</p>
311
+ <CommerceProductPicker label="On these products" :selected="targetProducts()" emptyLabel="Every product counts toward the tiers" @change="setTargetProducts" />
312
+ </section>
313
+
314
+ <section :if="isType('free_shipping')" class="grid gap-4 grid-cols-1 sm:grid-cols-2" aria-label="Free shipping">
315
+ <Input v-model:value="maxShipping" label="Only for rates up to" type="number" min="0" :step="moneyInputStep(currency())" placeholder="Any rate" :hint="'In ' + currency()" />
316
+ </section>
317
+
318
+ <section class="flex flex-col gap-3" aria-label="Requirements">
319
+ <p class="font-semibold text-gray-900 text-sm dark:text-white">Requirements and limits</p>
320
+ <div class="grid gap-4 grid-cols-1 sm:grid-cols-3">
321
+ <Input v-model:value="minimumSubtotal" label="Minimum purchase" type="number" min="0" :step="moneyInputStep(currency())" placeholder="None" />
322
+ <Input v-model:value="minimumQuantity" label="Minimum items" type="number" min="0" step="1" placeholder="None" />
323
+ <div :if="!isType('free_shipping')"><Input v-model:value="maxAmount" label="Most it can take off" type="number" min="0" :step="moneyInputStep(currency())" placeholder="No cap" /></div>
324
+ <Input v-model:value="usageLimit" label="Total uses" type="number" min="1" step="1" placeholder="Unlimited" />
325
+ <Input v-model:value="startsAt" label="Starts" type="date" />
326
+ <Input v-model:value="endsAt" label="Ends" type="date" />
327
+ </div>
328
+ </section>
329
+
330
+ <section class="flex flex-col gap-3 p-4 border border-gray-200 rounded-lg dark:border-neutral-700" aria-label="Combinations">
331
+ <div>
332
+ <p class="font-semibold text-gray-900 text-sm dark:text-white">Combines with</p>
333
+ <p class="mt-0.5 text-gray-500 text-xs dark:text-neutral-400">Two discounts apply together only when both allow it. Otherwise the one worth more wins.</p>
334
+ </div>
335
+ <div class="grid gap-3 grid-cols-1 sm:grid-cols-3">
336
+ <Toggle v-model:checked="combineProduct" label="Product discounts" />
337
+ <Toggle v-model:checked="combineOrder" label="Order discounts" />
338
+ <Toggle v-model:checked="combineShipping" label="Shipping discounts" />
339
+ </div>
340
+ </section>
341
+
342
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between p-4 bg-gray-50 dark:bg-neutral-900/50 rounded-lg">
343
+ <Toggle v-model:checked="isActive" label="Enabled" description="A disabled discount is kept but never applied." labelPosition="left" />
344
+ <div :if="preview()" class="flex gap-2 items-center">
345
+ <span class="text-gray-500 text-xs dark:text-neutral-400">Storefront badge</span>
346
+ <span class="inline-flex gap-1.5 items-center px-2.5 py-1 font-semibold text-emerald-800 text-xs tracking-wide dark:text-emerald-300 bg-emerald-50 dark:bg-emerald-950/40 rounded-full"><span class="h-3.5 w-3.5 i-hugeicons-discount-tag-01"></span>{{ preview() }}</span>
347
+ </div>
348
+ </div>
349
+ </form>
350
+ <template #footer>
351
+ <div class="flex gap-2 justify-end w-full"><Button variant="secondary" :disabled="busy()" @click="emit('close')">Cancel</Button><Button type="submit" form="discount-form" :loading="busy()" :disabled="!valid()">{{ mode() === 'edit' ? 'Save discount' : 'Add discount' }}</Button></div>
352
+ </template>
353
+ </Modal>
@@ -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()" />