@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.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-auth/SKILL.md +12 -1
- package/ai/skills/stacks-auto-imports/SKILL.md +1 -1
- package/ai/skills/stacks-buddy/SKILL.md +70 -7
- package/ai/skills/stacks-commerce/SKILL.md +78 -4
- package/ai/skills/stacks-dashboard/SKILL.md +32 -2
- package/ai/skills/stacks-database/SKILL.md +1 -1
- package/ai/skills/stacks-development/SKILL.md +3 -0
- package/ai/skills/stacks-migrations/SKILL.md +10 -2
- package/ai/skills/stacks-mobile/SKILL.md +21 -2
- package/ai/skills/stacks-models/SKILL.md +2 -2
- package/ai/skills/stacks-native/CATALOG.md +21 -21
- package/ai/skills/stacks-orm/SKILL.md +2 -2
- package/ai/skills/stacks-utils/SKILL.md +8 -3
- package/app/Actions/Dashboard/Commerce/CommerceDiscountDestroyAction.ts +27 -0
- package/app/Actions/Dashboard/Commerce/CommerceDiscountStoreAction.ts +28 -0
- package/app/Actions/Dashboard/Commerce/CommerceDiscountUpdateAction.ts +30 -0
- package/app/Actions/Dashboard/Commerce/CommerceDiscountsAction.ts +42 -0
- package/app/Actions/Dashboard/Commerce/CommerceUpsellDestroyAction.ts +31 -0
- package/app/Actions/Dashboard/Commerce/CommerceUpsellDetailAction.ts +28 -0
- package/app/Actions/Dashboard/Commerce/CommerceUpsellStoreAction.ts +26 -0
- package/app/Actions/Dashboard/Commerce/CommerceUpsellUpdateAction.ts +29 -0
- package/app/Actions/Dashboard/Commerce/CommerceUpsellsAction.ts +40 -0
- package/app/Actions/Dashboard/Commerce/commerce-discount-list.ts +204 -0
- package/app/Actions/Dashboard/Commerce/commerce-discount-write.ts +53 -0
- package/app/Actions/Dashboard/Commerce/commerce-discounts-upsells.test.ts +228 -0
- package/app/Actions/Dashboard/Commerce/commerce-upsell-list.ts +289 -0
- package/app/Actions/Dashboard/Commerce/discount-records.ts +392 -0
- package/app/Actions/Dashboard/Commerce/upsell-offer-records.ts +307 -0
- package/app/Actions/Dashboard/Models/ModelSaveAction.ts +6 -1
- package/app/Actions/Dashboard/Models/model-relations.ts +17 -7
- package/app/Actions/Dashboard/Models/model-row-writes.ts +9 -8
- package/app/Actions/Dashboard/Models/model-write.ts +51 -2
- package/app/Actions/Dashboard/Remote/RemoteCommandRunAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/RemoteTerminalCloseAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/RemoteTerminalInputAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/RemoteTerminalOpenAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/RemoteTerminalResizeAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/RemoteTerminalStreamAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/remote-commands.test.ts +2 -2
- package/app/Actions/Dashboard/Remote/remote-commands.ts +4 -4
- package/app/Actions/Dashboard/Remote/remote-terminal.test.ts +45 -25
- package/app/Actions/Dashboard/Remote/remote-terminal.ts +9 -9
- package/app/Actions/Storefront/AcceptOrderOfferAction.ts +68 -0
- package/app/Actions/Storefront/ApplyDiscountCodeAction.ts +83 -0
- package/app/Actions/Storefront/DeclineOrderOfferAction.ts +25 -0
- package/app/Actions/Storefront/PlaceOrderAction.ts +135 -72
- package/app/Gates.ts +4 -4
- package/app/Mail/OrderConfirmation.ts +7 -1
- package/app/Models/commerce/Cart.ts +14 -0
- package/app/Models/commerce/Discount.ts +255 -0
- package/app/Models/commerce/PostPurchaseOffer.ts +175 -0
- package/app/Models/commerce/PostPurchaseOfferResponse.ts +145 -0
- package/app/Policies/PostPolicy.ts +11 -11
- package/app/Storefront/DiscountCodeMessages.ts +12 -0
- package/app/Storefront/OrderKey.ts +29 -0
- package/app/Storefront/StorefrontPricing.ts +211 -0
- package/app/Storefront/UpsellCharge.ts +43 -0
- package/functions/projects.test.ts +38 -0
- package/functions/projects.ts +99 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +7 -7
- package/resources/components/Dashboard/Commerce/CommerceDiscountBreakdown.stx +72 -0
- package/resources/components/Dashboard/Commerce/CommerceDiscountDeleteDialog.stx +19 -0
- package/resources/components/Dashboard/Commerce/CommerceDiscountDetailsDialog.stx +110 -0
- package/resources/components/Dashboard/Commerce/CommerceDiscountDialog.stx +353 -0
- package/resources/components/Dashboard/Commerce/CommerceDiscountsDashboard.stx +211 -0
- package/resources/components/Dashboard/Commerce/CommerceDiscountsTable.stx +105 -0
- package/resources/components/Dashboard/Commerce/CommerceProductPicker.stx +115 -0
- package/resources/components/Dashboard/Commerce/CommerceUpsellDeleteDialog.stx +21 -0
- package/resources/components/Dashboard/Commerce/CommerceUpsellDetailsDialog.stx +153 -0
- package/resources/components/Dashboard/Commerce/CommerceUpsellDialog.stx +191 -0
- package/resources/components/Dashboard/Commerce/CommerceUpsellsDashboard.stx +214 -0
- package/resources/components/Dashboard/Commerce/CommerceUpsellsTable.stx +91 -0
- package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +4 -19
- package/resources/components/Dashboard/ProjectSwitcher.stx +302 -0
- package/resources/components/Dashboard/Settings/SettingsDashboard.stx +5 -3
- package/resources/components/Dashboard/UI/SearchFilter.stx +7 -4
- package/resources/components/Storefront/OrderSummary.stx +17 -0
- package/resources/functions/dashboard/project-switcher.test.ts +14 -0
- package/resources/functions/dashboard/project-switcher.ts +28 -0
- package/resources/functions/dashboard/sidebar.ts +4 -1
- package/resources/plugins/preloader.ts +33 -2
- package/resources/views/cart.stx +50 -16
- package/resources/views/checkout/contact.stx +11 -5
- package/resources/views/checkout/payment.stx +11 -5
- package/resources/views/checkout/shipping.stx +11 -5
- package/resources/views/orders/[id].stx +227 -50
- package/routes/dashboard-api.ts +12 -0
- package/routes/dashboard.ts +2 -0
- package/routes/storefront.ts +8 -0
- package/views/dashboard/commerce/discounts/index.stx +10 -0
- package/views/dashboard/commerce/upsells/index.stx +10 -0
- package/views/dashboard/layouts/default.stx +17 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
<script client>
|
|
2
|
+
import type { DiscountRecord, DiscountTargetRecord } from '../../../../app/Actions/Dashboard/Commerce/discount-records'
|
|
3
|
+
import { formatCurrency } from '@stacksjs/commerce/money'
|
|
4
|
+
|
|
5
|
+
const open = useReactiveProp('open', false)
|
|
6
|
+
const record = useReactiveProp('record', null as DiscountRecord | null)
|
|
7
|
+
const currency = useReactiveProp('currency', 'USD')
|
|
8
|
+
const emit = defineEmits(['edit', 'close', 'delete'])
|
|
9
|
+
|
|
10
|
+
const STATE_LABELS: Record<string, string> = { active: 'Active', scheduled: 'Scheduled', expired: 'Expired', exhausted: 'Used up', disabled: 'Disabled' }
|
|
11
|
+
|
|
12
|
+
function money(value: number | null | undefined): string {
|
|
13
|
+
return value == null ? '' : formatCurrency(value, currency())
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A target in words: product names, plus how many variants and categories it also names. */
|
|
17
|
+
function targetText(target: DiscountTargetRecord | undefined, empty: string): string {
|
|
18
|
+
const current = record()
|
|
19
|
+
if (!target || !current)
|
|
20
|
+
return empty
|
|
21
|
+
const parts: string[] = target.productIds.map(id => current.productLabels[id] ?? `Product #${id}`)
|
|
22
|
+
if (target.variantIds.length)
|
|
23
|
+
parts.push(`${target.variantIds.length} variant${target.variantIds.length === 1 ? '' : 's'}`)
|
|
24
|
+
if (target.categoryIds.length)
|
|
25
|
+
parts.push(`${target.categoryIds.length} categor${target.categoryIds.length === 1 ? 'y' : 'ies'}`)
|
|
26
|
+
return parts.length ? parts.join(', ') : empty
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** What it does, in a sentence. */
|
|
30
|
+
function summaryText(): string {
|
|
31
|
+
const current = record()
|
|
32
|
+
if (!current)
|
|
33
|
+
return ''
|
|
34
|
+
switch (current.type) {
|
|
35
|
+
case 'percentage':
|
|
36
|
+
return current.appliesTo === 'product' ? `${current.value}% off ${targetText(current.target, 'the chosen products')}` : `${current.value}% off the whole order`
|
|
37
|
+
case 'fixed_amount':
|
|
38
|
+
return current.appliesTo === 'product'
|
|
39
|
+
? `${money(current.value)} off ${current.perItem ? 'each of ' : ''}${targetText(current.target, 'the chosen products')}`
|
|
40
|
+
: `${money(current.value)} off the order`
|
|
41
|
+
case 'buy_x_get_y':
|
|
42
|
+
return `Buy ${current.buyQuantity} of ${targetText(current.buyTarget, 'any product')}, get ${current.getQuantity} of ${targetText(current.getTarget, 'the same products')} ${current.getPercent === 100 ? 'free' : `${current.getPercent}% off`}${current.maxApplications ? `, up to ${current.maxApplications} times per order` : ''}`
|
|
43
|
+
case 'volume':
|
|
44
|
+
return `${current.tiers.map(t => `${t.minQuantity}+ for ${t.percent}% off`).join(', ')} on ${targetText(current.target, 'every product')}`
|
|
45
|
+
default:
|
|
46
|
+
return current.maxShipping != null ? `Free shipping on rates up to ${money(current.maxShipping)}` : 'Free shipping on any rate'
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function combinations(): string {
|
|
51
|
+
const c = record()?.combinesWith
|
|
52
|
+
if (!c)
|
|
53
|
+
return 'Nothing'
|
|
54
|
+
const list = [c.product ? 'product' : '', c.order ? 'order' : '', c.shipping ? 'shipping' : ''].filter(Boolean)
|
|
55
|
+
return list.length ? `${list.join(', ')} discounts` : 'Nothing: the better discount wins'
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** When it runs, in words. */
|
|
59
|
+
function runs(): string {
|
|
60
|
+
const current = record()
|
|
61
|
+
if (!current?.startsAt && !current?.endsAt)
|
|
62
|
+
return 'Always'
|
|
63
|
+
if (current.startsAt && current.endsAt)
|
|
64
|
+
return `${current.startsAt} to ${current.endsAt}`
|
|
65
|
+
return current.startsAt ? `From ${current.startsAt}` : `Until ${current.endsAt}`
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function editRecord(): void {
|
|
69
|
+
const current = record()
|
|
70
|
+
if (!current)
|
|
71
|
+
return
|
|
72
|
+
emit('edit', current)
|
|
73
|
+
emit('close')
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function deleteRecord(): void {
|
|
77
|
+
const current = record()
|
|
78
|
+
if (!current)
|
|
79
|
+
return
|
|
80
|
+
emit('delete', current)
|
|
81
|
+
emit('close')
|
|
82
|
+
}
|
|
83
|
+
</script>
|
|
84
|
+
|
|
85
|
+
<Modal
|
|
86
|
+
:isOpen="open()"
|
|
87
|
+
:title="record()?.title || 'Discount'"
|
|
88
|
+
:description="summaryText()"
|
|
89
|
+
size="lg"
|
|
90
|
+
@close="emit('close')"
|
|
91
|
+
>
|
|
92
|
+
<template #header-trailing>
|
|
93
|
+
<span class="px-2 py-1 font-semibold text-gray-700 text-xs dark:text-neutral-200 bg-gray-100 dark:bg-neutral-700 rounded-full">{{ STATE_LABELS[record()?.state || ''] || 'Unknown' }}</span>
|
|
94
|
+
</template>
|
|
95
|
+
<div class="flex gap-2 items-center mb-5">
|
|
96
|
+
<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>{{ record()?.label }}</span>
|
|
97
|
+
<span class="text-gray-500 text-xs dark:text-neutral-400">{{ record()?.method === 'code' ? 'Code ' + record()?.code : 'Automatic' }}</span>
|
|
98
|
+
</div>
|
|
99
|
+
<dl class="grid gap-4 grid-cols-2">
|
|
100
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Used</dt><dd class="mt-1 font-mono text-gray-900 text-sm dark:text-white">{{ record()?.usageCount || 0 }} / {{ record()?.usageLimit || 'No limit' }}</dd></div>
|
|
101
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Combines with</dt><dd class="mt-1 text-gray-900 text-sm dark:text-white">{{ combinations() }}</dd></div>
|
|
102
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Minimum purchase</dt><dd class="mt-1 text-gray-900 text-sm dark:text-white">{{ record()?.minimumSubtotal ? money(record()?.minimumSubtotal) : 'None' }}</dd></div>
|
|
103
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Minimum items</dt><dd class="mt-1 text-gray-900 text-sm dark:text-white">{{ record()?.minimumQuantity || 'None' }}</dd></div>
|
|
104
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Most it takes off</dt><dd class="mt-1 text-gray-900 text-sm dark:text-white">{{ record()?.maxAmount ? money(record()?.maxAmount) : 'No cap' }}</dd></div>
|
|
105
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Runs</dt><dd class="mt-1 text-gray-900 text-sm dark:text-white">{{ runs() }}</dd></div>
|
|
106
|
+
</dl>
|
|
107
|
+
<template #footer>
|
|
108
|
+
<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 discount</Button></div></div>
|
|
109
|
+
</template>
|
|
110
|
+
</Modal>
|
|
@@ -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>
|