@stacksjs/commerce 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.
@@ -0,0 +1,171 @@
1
+ /** The class a rule belongs to, from its effect, scope and target. */
2
+ export declare function discountClass(rule: Pick<DiscountRule, 'effect' | 'scope' | 'target'>): DiscountClass;
3
+ /** True when a rule can be used at `now`: active, started, not ended, not used up. */
4
+ export declare function isDiscountAvailable(rule: DiscountRule, now?: Date): boolean;
5
+ /** Whether a line falls inside a target. An empty target holds every line. */
6
+ export declare function matchesTarget(line: Pick<DiscountLineInput, 'productId' | 'variantId' | 'categoryId'>, target?: DiscountTarget | null): boolean;
7
+ /**
8
+ * Whether two discounts may apply to one order. Each has to accept the
9
+ * other's class; two discounts of one class both have to accept that class.
10
+ */
11
+ export declare function canCombine(a: DiscountRule, b: DiscountRule): boolean;
12
+ /**
13
+ * A short label for a discount, for a badge or a line under the item:
14
+ * `BUY 4, GET 4 FREE`, `20% OFF`, `5+ FOR 30% OFF`, `FREE SHIPPING`.
15
+ * `formatAmount` renders a fixed amount; without it the minor units show.
16
+ */
17
+ export declare function discountLabel(rule: Pick<DiscountRule, 'effect'>, formatAmount?: (minor: number) => string): string;
18
+ /** Price a basket: choose its discounts and spread them over its lines. */
19
+ export declare function applyDiscounts(input: ApplyDiscountsInput): DiscountResult;
20
+ /**
21
+ * Split `total` across `weights` in proportion, in whole minor units, by the
22
+ * largest-remainder method: the parts always add up to `total` exactly and no
23
+ * part exceeds its weight.
24
+ */
25
+ export declare function allocate(total: number, weights: readonly number[]): number[];
26
+ /** `percent` of an amount in minor units, rounded half up. */
27
+ export declare function percentOf(amount: number, percent: number): number;
28
+ /** Which lines a discount reaches. Leaving every list empty means every line. */
29
+ export declare interface DiscountTarget {
30
+ productIds?: readonly number[] | null
31
+ variantIds?: readonly number[] | null
32
+ categoryIds?: readonly number[] | null
33
+ }
34
+ export declare interface VolumeTier {
35
+ minQuantity: number
36
+ percent: number
37
+ }
38
+ export declare interface DiscountRule {
39
+ id: string | number
40
+ title: string
41
+ code?: string | null
42
+ effect: DiscountEffect
43
+ target?: DiscountTarget | null
44
+ scope?: 'product' | 'order' | null
45
+ minimumSubtotal?: number | null
46
+ minimumQuantity?: number | null
47
+ maxAmount?: number | null
48
+ combinesWith?: Partial<Record<DiscountClass, boolean>> | null
49
+ startsAt?: string | Date | null
50
+ endsAt?: string | Date | null
51
+ isActive?: boolean | null
52
+ usageLimit?: number | null
53
+ usageCount?: number | null
54
+ }
55
+ export declare interface DiscountLineInput {
56
+ id: string | number
57
+ productId: number
58
+ variantId?: number | null
59
+ categoryId?: number | null
60
+ quantity: number
61
+ unitPrice: number
62
+ compareAtPrice?: number | null
63
+ }
64
+ export declare interface ApplyDiscountsInput {
65
+ lines: readonly DiscountLineInput[]
66
+ rules: readonly DiscountRule[]
67
+ codes?: readonly string[]
68
+ shipping?: number
69
+ now?: Date
70
+ }
71
+ export declare interface DiscountAllocation {
72
+ ruleId: string | number
73
+ amount: number
74
+ }
75
+ export declare interface DiscountedLine {
76
+ id: string | number
77
+ quantity: number
78
+ unitPrice: number
79
+ subtotal: number
80
+ compareAtSubtotal: number
81
+ discount: number
82
+ total: number
83
+ allocations: DiscountAllocation[]
84
+ }
85
+ export declare interface AppliedDiscount {
86
+ ruleId: string | number
87
+ title: string
88
+ code: string | null
89
+ class: DiscountClass
90
+ amount: number
91
+ }
92
+ export declare interface RejectedCode {
93
+ code: string
94
+ reason: RejectedCodeReason
95
+ }
96
+ export declare interface DiscountResult {
97
+ lines: DiscountedLine[]
98
+ applied: AppliedDiscount[]
99
+ rejectedCodes: RejectedCode[]
100
+ subtotal: number
101
+ productDiscount: number
102
+ orderDiscount: number
103
+ shippingDiscount: number
104
+ discount: number
105
+ discountedSubtotal: number
106
+ shipping: number
107
+ shippingAfterDiscount: number
108
+ total: number
109
+ compareAtSavings: number
110
+ totalSavings: number
111
+ }
112
+ /**
113
+ * The discount engine: which discounts a cart earns and what each line pays.
114
+ *
115
+ * Pure and synchronous, so the cart page, the checkout and the order that is
116
+ * finally written all price a basket the same way, and a browser can bundle it
117
+ * (`@stacksjs/commerce/discounts/engine`). Every amount is integer minor units
118
+ * of one currency (1999 is $19.99), never a float.
119
+ *
120
+ * What it covers, in the terms a merchant uses:
121
+ *
122
+ * - **Automatic discounts** (no code) and **discount codes**, side by side.
123
+ * - **Amount off products**: a percentage or a fixed amount off chosen
124
+ * products, variants or categories, per item or once across them.
125
+ * - **Amount off order**: a percentage or fixed amount off the whole basket.
126
+ * - **Buy X get Y**: "buy 4, get 4 free", "buy 2, get 1 at 50% off". The
127
+ * cheapest qualifying units are the ones discounted.
128
+ * - **Volume tiers** (quantity breaks): "5+ pairs 20% off, 10+ pairs 30% off".
129
+ * - **Free shipping**, optionally only on rates up to a ceiling.
130
+ * - **Compare-at savings**: a sale price's "was" price counts toward the total
131
+ * a shopper is shown as saved, the way a storefront says "You saved $100".
132
+ *
133
+ * Combination follows the model shoppers already know from the big platforms:
134
+ * every discount has a class (product, order or shipping), and two discounts
135
+ * apply together only when each says it combines with the other's class. By
136
+ * default nothing combines. A line takes at most one product discount; order
137
+ * discounts apply to what is left after product discounts; shipping discounts
138
+ * apply to the shipping fee.
139
+ *
140
+ * When discounts conflict, the one worth most on this basket wins: candidates
141
+ * are evaluated alone, ranked by value, and taken greedily while they stay
142
+ * compatible with everything already taken. A code that loses that contest is
143
+ * reported in `rejectedCodes` with the reason, so a checkout can say why.
144
+ */
145
+ export type DiscountClass = 'product' | 'order' | 'shipping';
146
+ export type DiscountEffect = | { type: 'percentage', percent: number }
147
+ /** `perItem`: the amount comes off every targeted unit, not once across them. */
148
+ | { type: 'fixed_amount', amount: number, perItem?: boolean }
149
+ | {
150
+ type: 'buy_x_get_y'
151
+ buyQuantity: number
152
+ /** What has to be bought. Defaults to the rule's `target`. */
153
+ buyTarget?: DiscountTarget | null
154
+ getQuantity: number
155
+ /** What comes discounted. Defaults to `buyTarget`, then the rule's `target`. */
156
+ getTarget?: DiscountTarget | null
157
+ /** Percent off each "get" unit: 100 is free. */
158
+ getPercent: number
159
+ /** How many times one order may use it. Unlimited when left out. */
160
+ maxApplications?: number | null
161
+ }
162
+ | { type: 'volume', tiers: readonly VolumeTier[] }
163
+ /** Free shipping, only when the rate is at most `maxShipping` if one is set. */
164
+ | { type: 'free_shipping', maxShipping?: number | null }
165
+ export type RejectedCodeReason = | 'not-found'
166
+ | 'inactive'
167
+ | 'expired'
168
+ | 'exhausted'
169
+ | 'requirements-not-met'
170
+ | 'no-eligible-items'
171
+ | 'not-combinable';
@@ -0,0 +1 @@
1
+ const NO_COMBINATION={product:false,order:false,shipping:false};export function discountClass(rule){switch(rule.effect.type){case"free_shipping":return"shipping";case"buy_x_get_y":case"volume":return"product";default:if(rule.scope)return rule.scope;return hasTarget(rule.target)?"product":"order"}}export function isDiscountAvailable(rule,now=new Date){return availability(rule,now)==="ok"}function availability(rule,now){if(rule.isActive===false)return"inactive";const starts=toTime(rule.startsAt);const ends=toTime(rule.endsAt);if(starts!==null&&now.getTime()<starts)return"inactive";if(ends!==null&&now.getTime()>ends)return"expired";if(rule.usageLimit!=null&&Number(rule.usageCount??0)>=Number(rule.usageLimit))return"exhausted";return"ok"}export function matchesTarget(line,target){if(!hasTarget(target))return true;const t=target;if(t.variantIds?.length&&line.variantId!=null&&t.variantIds.includes(line.variantId))return true;if(t.productIds?.length&&t.productIds.includes(line.productId))return true;if(t.categoryIds?.length&&line.categoryId!=null&&t.categoryIds.includes(line.categoryId))return true;return false}export function canCombine(a,b){const aClass=discountClass(a);const bClass=discountClass(b);const aWith={...NO_COMBINATION,...a.combinesWith??{}};const bWith={...NO_COMBINATION,...b.combinesWith??{}};return Boolean(aWith[bClass])&&Boolean(bWith[aClass])}export function discountLabel(rule,formatAmount=String){const e=rule.effect;switch(e.type){case"percentage":return`${trimPercent(e.percent)}% OFF`;case"fixed_amount":return`${formatAmount(e.amount)} OFF${e.perItem?" EACH":""}`;case"buy_x_get_y":return`BUY ${e.buyQuantity}, GET ${e.getQuantity} ${e.getPercent>=100?"FREE":`${trimPercent(e.getPercent)}% OFF`}`;case"volume":{const tiers=[...e.tiers].sort((x,y)=>x.minQuantity-y.minQuantity);return tiers.map((t)=>`${t.minQuantity}+ FOR ${trimPercent(t.percent)}% OFF`).join(", ")}case"free_shipping":return"FREE SHIPPING"}}export function applyDiscounts(input){const now=input.now??new Date;const shipping=assertMinor(input.shipping??0,"shipping");const lines=input.lines.map((line,i)=>{assertLine(line,i);const subtotal=line.unitPrice*line.quantity;return{input:line,subtotal,remaining:subtotal,productDiscounted:false,allocations:[]}});for(const rule of input.rules)assertRule(rule);const rejectedCodes=[];const entered=dedupeCodes(input.codes??[]);const candidates=[];for(const rule of input.rules){if(!rule.code&&availability(rule,now)==="ok")candidates.push(rule)}for(const code of entered){const rule=input.rules.find((r)=>r.code&&normalizeCode(r.code)===normalizeCode(code));if(!rule){rejectedCodes.push({code,reason:"not-found"});continue}const state=availability(rule,now);if(state!=="ok"){rejectedCodes.push({code,reason:state});continue}candidates.push(rule)}const standalone=candidates.map((rule)=>{const evaluation=evaluate(rule,lines,shipping,0);return{rule,evaluation,value:sumEvaluation(evaluation)}});for(const{rule,evaluation,value}of standalone){if(value===0&&rule.code)rejectedCodes.push({code:rule.code,reason:evaluation.shortfall??"no-eligible-items"})}const ranked=standalone.filter((c)=>c.value>0).sort((a,b)=>b.value-a.value||Number(Boolean(a.rule.code))-Number(Boolean(b.rule.code)));const chosen=[];for(const{rule}of ranked){if(chosen.every((other)=>canCombine(rule,other)))chosen.push(rule);else if(rule.code)rejectedCodes.push({code:rule.code,reason:"not-combinable"})}const order={product:0,order:1,shipping:2};const valueOf=new Map(ranked.map((c)=>[c.rule,c.value]));chosen.sort((a,b)=>order[discountClass(a)]-order[discountClass(b)]||(valueOf.get(b)??0)-(valueOf.get(a)??0));const applied=[];let shippingDiscount=0;let productDiscount=0;let orderDiscount=0;const standaloneOf=new Map(standalone.map((c)=>[c.rule,c.evaluation]));const owner=new Map;for(const rule of chosen){if(discountClass(rule)!=="product")continue;for(const[index,take]of standaloneOf.get(rule)?.perLine??[]){const current=owner.get(index);const currentTake=current?standaloneOf.get(current)?.perLine.get(index)??0:0;if(take>currentTake)owner.set(index,rule)}}for(const rule of chosen){const cls=discountClass(rule);const view=cls==="product"?lines.map((l,i)=>({...l,productDiscounted:l.productDiscounted||owner.has(i)&&owner.get(i)!==rule})):lines;const evaluation=evaluate(rule,view,shipping,shippingDiscount);const amount=sumEvaluation(evaluation);if(amount===0){if(rule.code)rejectedCodes.push({code:rule.code,reason:"not-combinable"});continue}for(const[index,take]of evaluation.perLine){if(take<=0)continue;const line=lines[index];line.remaining-=take;line.allocations.push({ruleId:rule.id,amount:take});if(cls==="product")line.productDiscounted=true}shippingDiscount+=evaluation.shipping;if(cls==="product")productDiscount+=amount;else if(cls==="order")orderDiscount+=amount;applied.push({ruleId:rule.id,title:rule.title,code:rule.code??null,class:cls,amount})}const outLines=lines.map((line)=>{const discount=line.subtotal-line.remaining;const compareAt=line.input.compareAtPrice!=null&&line.input.compareAtPrice>line.input.unitPrice?line.input.compareAtPrice*line.input.quantity:line.subtotal;return{id:line.input.id,quantity:line.input.quantity,unitPrice:line.input.unitPrice,subtotal:line.subtotal,compareAtSubtotal:compareAt,discount,total:line.remaining,allocations:line.allocations}});const subtotal=outLines.reduce((s,l)=>s+l.subtotal,0);const discount=productDiscount+orderDiscount;const discountedSubtotal=subtotal-discount;const shippingAfterDiscount=shipping-shippingDiscount;const compareAtSavings=outLines.reduce((s,l)=>s+(l.compareAtSubtotal-l.subtotal),0);return{lines:outLines,applied,rejectedCodes,subtotal,productDiscount,orderDiscount,shippingDiscount,discount,discountedSubtotal,shipping,shippingAfterDiscount,total:discountedSubtotal+shippingAfterDiscount,compareAtSavings,totalSavings:compareAtSavings+discount+shippingDiscount}}function evaluate(rule,lines,shipping,shippingDiscounted){const cls=discountClass(rule);const perLine=new Map;if(cls==="shipping"){if(!meetsMinimums(rule,lines.map((_,i)=>i),lines))return{perLine,shipping:0,shortfall:"requirements-not-met"};const effect=rule.effect;const left=shipping-shippingDiscounted;if(left<=0||effect.maxShipping!=null&&shipping>effect.maxShipping)return{perLine,shipping:0,shortfall:"no-eligible-items"};return{perLine,shipping:capTotal(left,rule.maxAmount)}}if(cls==="order"){const all=lines.map((_,i)=>i);if(!meetsMinimums(rule,all,lines))return{perLine,shipping:0,shortfall:"requirements-not-met"};const base=lines.reduce((s,l)=>s+l.remaining,0);if(base<=0)return{perLine,shipping:0,shortfall:"no-eligible-items"};const effect=rule.effect;const total=capTotal(Math.min(base,effect.type==="percentage"?percentOf(base,effect.percent):effect.amount),rule.maxAmount);const shares=allocate(total,lines.map((l)=>l.remaining));shares.forEach((share,i)=>share>0&&perLine.set(i,share));return{perLine,shipping:0}}const eligible=lines.map((l,i)=>({l,i})).filter(({l})=>!l.productDiscounted&&l.remaining>0);const effect=rule.effect;if(effect.type==="buy_x_get_y")return buyXGetY(rule,effect,eligible,lines);const targeted=eligible.filter(({l})=>matchesTarget(l.input,rule.target));if(targeted.length===0)return{perLine,shipping:0,shortfall:"no-eligible-items"};if(!meetsMinimums(rule,targeted.map((t)=>t.i),lines))return{perLine,shipping:0,shortfall:"requirements-not-met"};if(effect.type==="percentage"){for(const{l,i}of targeted)perLine.set(i,Math.min(l.remaining,percentOf(l.remaining,effect.percent)))}else if(effect.type==="volume"){const units=targeted.reduce((s,t)=>s+t.l.input.quantity,0);const tier=[...effect.tiers].sort((a,b)=>b.minQuantity-a.minQuantity).find((t)=>units>=t.minQuantity);if(!tier)return{perLine,shipping:0,shortfall:"requirements-not-met"};for(const{l,i}of targeted)perLine.set(i,Math.min(l.remaining,percentOf(l.remaining,tier.percent)))}else if(effect.type==="fixed_amount"){if(effect.perItem){for(const{l,i}of targeted)perLine.set(i,Math.min(l.remaining,effect.amount*l.input.quantity))}else{const base=targeted.reduce((s,t)=>s+t.l.remaining,0);const shares=allocate(Math.min(base,effect.amount),targeted.map((t)=>t.l.remaining));targeted.forEach(({i},k)=>shares[k]>0&&perLine.set(i,shares[k]))}}return capEvaluation({perLine,shipping:0},rule.maxAmount,lines)}function buyXGetY(rule,effect,eligible,lines){const perLine=new Map;const buyTarget=effect.buyTarget??rule.target;const getTarget=effect.getTarget??buyTarget;const units=[];for(const{l,i}of eligible){const buy=matchesTarget(l.input,buyTarget);const get=matchesTarget(l.input,getTarget);if(!buy&&!get)continue;for(let n=0;n<l.input.quantity;n++)units.push({line:i,price:l.input.unitPrice,buy,get,used:false})}const buyLines=[...new Set(units.filter((u)=>u.buy).map((u)=>u.line))];if(buyLines.length===0)return{perLine,shipping:0,shortfall:"no-eligible-items"};if(!meetsMinimums(rule,buyLines,lines))return{perLine,shipping:0,shortfall:"requirements-not-met"};const byPriceDesc=[...units].sort((a,b)=>b.price-a.price);const byPriceAsc=[...units].sort((a,b)=>a.price-b.price);const limit=effect.maxApplications??Number.POSITIVE_INFINITY;let applications=0;while(applications<limit){const buys=byPriceDesc.filter((u)=>u.buy&&!u.used).slice(0,effect.buyQuantity);if(buys.length<effect.buyQuantity)break;for(const u of buys)u.used=true;const gets=byPriceAsc.filter((u)=>u.get&&!u.used).slice(0,effect.getQuantity);if(gets.length===0){for(const u of buys)u.used=false;break}for(const u of gets){u.used=true;perLine.set(u.line,(perLine.get(u.line)??0)+percentOf(u.price,effect.getPercent))}applications++}if(perLine.size===0)return{perLine,shipping:0,shortfall:"requirements-not-met"};for(const[i,take]of perLine)perLine.set(i,Math.min(take,lines[i].remaining));return capEvaluation({perLine,shipping:0},rule.maxAmount,lines)}function meetsMinimums(rule,indexes,lines){if(rule.minimumSubtotal!=null&&rule.minimumSubtotal>0){const subtotal=indexes.reduce((s,i)=>s+lines[i].subtotal,0);if(subtotal<rule.minimumSubtotal)return false}if(rule.minimumQuantity!=null&&rule.minimumQuantity>0){const quantity=indexes.reduce((s,i)=>s+lines[i].input.quantity,0);if(quantity<rule.minimumQuantity)return false}return true}function capEvaluation(evaluation,maxAmount,_lines){const total=sumEvaluation(evaluation);if(maxAmount==null||total<=maxAmount)return evaluation;const indexes=[...evaluation.perLine.keys()];const shares=allocate(maxAmount,indexes.map((i)=>evaluation.perLine.get(i)));const perLine=new Map;indexes.forEach((i,k)=>shares[k]>0&&perLine.set(i,shares[k]));return{perLine,shipping:evaluation.shipping}}function capTotal(amount,maxAmount){return maxAmount==null?amount:Math.min(amount,maxAmount)}function sumEvaluation(evaluation){let total=evaluation.shipping;for(const take of evaluation.perLine.values())total+=take;return total}export function allocate(total,weights){const sum=weights.reduce((s,w)=>s+Math.max(0,w),0);if(total<=0||sum<=0)return weights.map(()=>0);const amount=Math.min(total,sum);const raw=weights.map((w)=>Math.max(0,w)*amount/sum);const parts=raw.map(Math.floor);let left=amount-parts.reduce((s,p)=>s+p,0);const order=raw.map((r,i)=>({i,frac:r-Math.floor(r)})).sort((a,b)=>b.frac-a.frac||a.i-b.i);for(const{i}of order){if(left<=0)break;if(parts[i]<Math.max(0,weights[i])){parts[i]++;left--}}return parts}export function percentOf(amount,percent){return Math.round(amount*percent/100)}function hasTarget(target){return Boolean(target&&(target.productIds?.length||target.variantIds?.length||target.categoryIds?.length))}function toTime(value){if(value==null||value==="")return null;const time=value instanceof Date?value.getTime():Date.parse(asUtc(String(value)));return Number.isFinite(time)?time:null}function asUtc(value){const trimmed=value.trim();return/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/.test(trimmed)?`${trimmed.replace(" ","T")}Z`:trimmed}function normalizeCode(code){return code.trim().toUpperCase()}function dedupeCodes(codes){const seen=new Set;const out=[];for(const code of codes){const key=normalizeCode(String(code??""));if(key&&!seen.has(key)){seen.add(key);out.push(String(code).trim())}}return out}function trimPercent(percent){return Number.isInteger(percent)?String(percent):percent.toFixed(2).replace(/\.?0+$/,"")}function assertMinor(value,name){if(!Number.isSafeInteger(value)||value<0)throw new TypeError(`${name} must be a non-negative whole number of minor units, got ${value}.`);return value}function assertPercent(value,name){if(!Number.isFinite(value)||value<0||value>100)throw new TypeError(`${name} must be a percentage from 0 to 100, got ${value}.`)}function assertLine(line,index){if(!Number.isSafeInteger(line.quantity)||line.quantity<=0)throw new TypeError(`Line ${index} quantity must be a positive whole number, got ${line.quantity}.`);assertMinor(line.unitPrice,`Line ${index} unitPrice`);if(line.compareAtPrice!=null)assertMinor(line.compareAtPrice,`Line ${index} compareAtPrice`)}function assertRule(rule){const e=rule.effect;const name=`Discount ${String(rule.id)}`;switch(e.type){case"percentage":assertPercent(e.percent,`${name} percent`);break;case"fixed_amount":assertMinor(e.amount,`${name} amount`);break;case"buy_x_get_y":if(!Number.isSafeInteger(e.buyQuantity)||e.buyQuantity<1)throw new TypeError(`${name} buyQuantity must be a whole number of at least 1.`);if(!Number.isSafeInteger(e.getQuantity)||e.getQuantity<1)throw new TypeError(`${name} getQuantity must be a whole number of at least 1.`);assertPercent(e.getPercent,`${name} getPercent`);if(e.maxApplications!=null&&(!Number.isSafeInteger(e.maxApplications)||e.maxApplications<1))throw new TypeError(`${name} maxApplications must be a whole number of at least 1.`);break;case"volume":if(!e.tiers.length)throw new TypeError(`${name} needs at least one tier.`);for(const tier of e.tiers){if(!Number.isSafeInteger(tier.minQuantity)||tier.minQuantity<1)throw new TypeError(`${name} tier minQuantity must be a whole number of at least 1.`);assertPercent(tier.percent,`${name} tier percent`)}break;case"free_shipping":if(e.maxShipping!=null)assertMinor(e.maxShipping,`${name} maxShipping`);break;default:throw new TypeError(`${name} has an unknown effect type.`)}if(rule.maxAmount!=null)assertMinor(rule.maxAmount,`${name} maxAmount`)}
@@ -0,0 +1,68 @@
1
+ import type { ApplyDiscountsInput, AppliedDiscount, DiscountResult, DiscountRule, DiscountTarget, VolumeTier } from './engine';
2
+ import type { DiscountRow } from './rules';
3
+ /**
4
+ * The rules a basket could use: every active automatic discount, plus the
5
+ * discounts and coupons whose codes were entered. The engine still checks
6
+ * dates, limits and minimums; this only keeps the query small.
7
+ */
8
+ export declare function fetchRules(options?: FetchRulesOptions): Promise<DiscountRule[]>;
9
+ /** Price a basket against the store's discounts. */
10
+ export declare function price(input: PriceInput): Promise<DiscountResult>;
11
+ /**
12
+ * Count one use of every applied discount and coupon that came from the
13
+ * database. Each is a single conditional UPDATE that enforces `usage_limit`,
14
+ * so two checkouts racing for the last use cannot both get it; check the
15
+ * outcomes and refuse the order (or drop the discount) when one did not.
16
+ */
17
+ export declare function redeemApplied(applied: readonly Pick<AppliedDiscount, 'ruleId'>[]): Promise<RedeemOutcome[]>;
18
+ /** Count one use of a `discounts` row, refusing past its limit or outside its dates. */
19
+ export declare function redeemDiscount(id: number): Promise<boolean>;
20
+ /**
21
+ * Create a discount. The rule is validated through the engine first, so a
22
+ * discount that could not price a basket is refused here rather than at a
23
+ * shopper's checkout.
24
+ */
25
+ export declare function store(input: NewDiscount): Promise<DiscountRow>;
26
+ /** Every discount, newest first. */
27
+ export declare function fetchAll(): Promise<DiscountRow[]>;
28
+ /** One discount by id. */
29
+ export declare function fetchById(id: number): Promise<DiscountRow | undefined>;
30
+ /** Switch a discount off. Answers whether a row changed. */
31
+ export declare function deactivate(id: number): Promise<boolean>;
32
+ export declare interface FetchRulesOptions {
33
+ codes?: readonly string[]
34
+ includeCoupons?: boolean
35
+ }
36
+ export declare interface PriceInput extends Omit<ApplyDiscountsInput, 'rules'> {
37
+ rules?: readonly DiscountRule[]
38
+ includeCoupons?: boolean
39
+ }
40
+ export declare interface NewDiscount {
41
+ title: string
42
+ code?: string | null
43
+ type: 'percentage' | 'fixed_amount' | 'buy_x_get_y' | 'volume' | 'free_shipping'
44
+ value?: number
45
+ scope?: 'product' | 'order' | null
46
+ perItem?: boolean
47
+ target?: DiscountTarget | null
48
+ buyQuantity?: number | null
49
+ buyTarget?: DiscountTarget | null
50
+ getQuantity?: number | null
51
+ getTarget?: DiscountTarget | null
52
+ getPercent?: number | null
53
+ maxApplications?: number | null
54
+ tiers?: readonly VolumeTier[] | null
55
+ maxShipping?: number | null
56
+ minimumSubtotal?: number | null
57
+ minimumQuantity?: number | null
58
+ maxAmount?: number | null
59
+ combinesWith?: { product?: boolean, order?: boolean, shipping?: boolean }
60
+ usageLimit?: number | null
61
+ isActive?: boolean
62
+ startsAt?: string | null
63
+ endsAt?: string | null
64
+ }
65
+ export type RedeemOutcome = | { ruleId: string | number, ok: true }
66
+ | { ruleId: string | number, ok: false, reason: 'limit-reached' | 'not-found' | 'inactive' | 'expired' | 'not-stored' }
67
+ export * from './engine';
68
+ export * from './rules';
@@ -0,0 +1,7 @@
1
+ import{db,mutationCount,sqlHelpers}from"@stacksjs/database/runtime";import{env}from"@stacksjs/env";import{formatDate}from"@stacksjs/orm";import{applyDiscounts}from"./engine";import{COUPON_PREFIX,DISCOUNT_PREFIX,ruleFromCoupon,ruleFromDiscount,truthy}from"./rules";export*from"./engine";export*from"./rules";export async function fetchRules(options={}){const q=db;const codes=[...new Set((options.codes??[]).map((c)=>String(c).trim()).filter(Boolean))];const rules=[];const automatic=await q.selectFrom("discounts").where("code","is",null).selectAll().execute();for(const row of automatic){if(row.is_active==null||truthy(row.is_active))rules.push(ruleFromDiscount(row))}if(codes.length){const wanted=new Set(codes.map((c)=>c.toUpperCase()));const coded=await q.selectFrom("discounts").where("code","is not",null).selectAll().execute();for(const row of coded){if(row.code&&wanted.has(row.code.toUpperCase()))rules.push(ruleFromDiscount(row))}if(options.includeCoupons!==false){const coupons=await q.selectFrom("coupons").selectAll().execute();for(const row of coupons){if(row.code&&wanted.has(row.code.toUpperCase())&&!rules.some((r)=>r.code?.toUpperCase()===row.code.toUpperCase()))rules.push(ruleFromCoupon(row))}}}return rules}export async function price(input){const rules=input.rules??await fetchRules({codes:input.codes,includeCoupons:input.includeCoupons});return applyDiscounts({...input,rules})}export async function redeemApplied(applied){const outcomes=[];for(const{ruleId}of applied){const key=String(ruleId);if(key.startsWith(DISCOUNT_PREFIX)){const ok=await redeemDiscount(Number(key.slice(DISCOUNT_PREFIX.length)));outcomes.push(ok?{ruleId,ok:true}:{ruleId,ok:false,reason:"limit-reached"})}else if(key.startsWith(COUPON_PREFIX)){const{redeem}=await import("../coupons/update");const result=await redeem(Number(key.slice(COUPON_PREFIX.length)));outcomes.push(result.ok?{ruleId,ok:true}:{ruleId,ok:false,reason:result.reason})}else{outcomes.push({ruleId,ok:false,reason:"not-stored"})}}return outcomes}export async function redeemDiscount(id){const dialect=sqlHelpers(env.DB_CONNECTION||"sqlite");const p=dialect.param;const now=formatDate(new Date);const statement=await db.unsafe(`UPDATE discounts
2
+ SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ${p(1)}
3
+ WHERE id = ${p(2)}
4
+ AND (usage_limit IS NULL OR COALESCE(usage_count, 0) < usage_limit)
5
+ AND (is_active IS NULL OR is_active = ${dialect.boolTrue})
6
+ AND (starts_at IS NULL OR starts_at <= ${p(3)})
7
+ AND (ends_at IS NULL OR ends_at >= ${p(4)})`,[now,id,now,now]);return mutationCount(statement)>0}export async function store(input){const q=db;const{randomUUIDv7}=await import("bun");const now=formatDate(new Date);const uuid=randomUUIDv7();const values={uuid,title:input.title,code:input.code?.trim()||null,type:input.type,value:input.value??0,scope:input.scope??null,per_item:Boolean(input.perItem),target:input.target?JSON.stringify(input.target):null,buy_quantity:input.buyQuantity??null,buy_target:input.buyTarget?JSON.stringify(input.buyTarget):null,get_quantity:input.getQuantity??null,get_target:input.getTarget?JSON.stringify(input.getTarget):null,get_percent:input.getPercent??null,max_applications:input.maxApplications??null,tiers:input.tiers?JSON.stringify(input.tiers):null,max_shipping:input.maxShipping??null,minimum_subtotal:input.minimumSubtotal??null,minimum_quantity:input.minimumQuantity??null,max_amount:input.maxAmount??null,combines_with_product:Boolean(input.combinesWith?.product),combines_with_order:Boolean(input.combinesWith?.order),combines_with_shipping:Boolean(input.combinesWith?.shipping),usage_limit:input.usageLimit??null,usage_count:0,is_active:input.isActive??true,starts_at:input.startsAt??null,ends_at:input.endsAt??null,created_at:now,updated_at:now};applyDiscounts({lines:[],rules:[ruleFromDiscount({id:0,...values})]});await q.insertInto("discounts").values(values).execute();const row=await q.selectFrom("discounts").where("uuid","=",uuid).selectAll().executeTakeFirst();if(!row)throw new Error("Discount insert could not be read back.");return row}export async function fetchAll(){return await db.selectFrom("discounts").selectAll().orderBy("id","desc").execute()}export async function fetchById(id){return await db.selectFrom("discounts").where("id","=",id).selectAll().executeTakeFirst()}export async function deactivate(id){const result=await db.updateTable("discounts").set({is_active:false,updated_at:formatDate(new Date)}).where("id","=",id).executeTakeFirst();return mutationCount(result)>0}
@@ -0,0 +1,60 @@
1
+ import type { DiscountRule } from './engine';
2
+ /** A `discounts` row as an engine rule. Its id is `discount:<id>`. */
3
+ export declare function ruleFromDiscount(row: DiscountRow): DiscountRule;
4
+ /**
5
+ * A `coupons` row as an engine rule. Its id is `coupon:<id>`. A coupon tied to
6
+ * a product discounts that product; one with a free product gives one unit of
7
+ * it free once anything else is bought.
8
+ */
9
+ export declare function ruleFromCoupon(row: CouponRow): DiscountRule;
10
+ export declare function truthy(value: unknown): boolean;
11
+ /** Engine ids of stored rules: `discount:<id>` and `coupon:<id>`. */
12
+ export declare const DISCOUNT_PREFIX: 'discount:';
13
+ export declare const COUPON_PREFIX: 'coupon:';
14
+ /** A `discounts` row as the database returns it. */
15
+ export declare interface DiscountRow {
16
+ id: number
17
+ title: string
18
+ code?: string | null
19
+ type: string
20
+ value?: number | string | null
21
+ scope?: string | null
22
+ per_item?: number | boolean | null
23
+ target?: string | null
24
+ buy_quantity?: number | null
25
+ buy_target?: string | null
26
+ get_quantity?: number | null
27
+ get_target?: string | null
28
+ get_percent?: number | string | null
29
+ max_applications?: number | null
30
+ tiers?: string | null
31
+ max_shipping?: number | null
32
+ minimum_subtotal?: number | null
33
+ minimum_quantity?: number | null
34
+ max_amount?: number | null
35
+ combines_with_product?: number | boolean | null
36
+ combines_with_order?: number | boolean | null
37
+ combines_with_shipping?: number | boolean | null
38
+ usage_limit?: number | null
39
+ usage_count?: number | null
40
+ is_active?: number | boolean | null
41
+ starts_at?: string | null
42
+ ends_at?: string | null
43
+ }
44
+ /** A `coupons` row as the database returns it. */
45
+ export declare interface CouponRow {
46
+ id: number
47
+ code: string
48
+ description?: string | null
49
+ is_active?: number | boolean | null
50
+ discount_type: string
51
+ discount_value: number | string
52
+ min_order_amount?: number | string | null
53
+ max_discount_amount?: number | string | null
54
+ free_product_id?: number | string | null
55
+ product_id?: number | null
56
+ usage_limit?: number | string | null
57
+ usage_count?: number | string | null
58
+ start_date?: string | null
59
+ end_date?: string | null
60
+ }
@@ -0,0 +1 @@
1
+ export const DISCOUNT_PREFIX="discount:";export const COUPON_PREFIX="coupon:";export function ruleFromDiscount(row){const value=Number(row.value??0);const base={id:`${DISCOUNT_PREFIX}${row.id}`,title:row.title,code:row.code||null,target:parseTarget(row.target),scope:row.scope==="product"||row.scope==="order"?row.scope:null,minimumSubtotal:numberOrNull(row.minimum_subtotal),minimumQuantity:numberOrNull(row.minimum_quantity),maxAmount:numberOrNull(row.max_amount),combinesWith:{product:truthy(row.combines_with_product),order:truthy(row.combines_with_order),shipping:truthy(row.combines_with_shipping)},startsAt:row.starts_at??null,endsAt:row.ends_at??null,isActive:row.is_active==null?true:truthy(row.is_active),usageLimit:numberOrNull(row.usage_limit),usageCount:numberOrNull(row.usage_count)};switch(row.type){case"percentage":return{...base,effect:{type:"percentage",percent:value}};case"fixed_amount":return{...base,effect:{type:"fixed_amount",amount:Math.round(value),perItem:truthy(row.per_item)}};case"buy_x_get_y":return{...base,effect:{type:"buy_x_get_y",buyQuantity:Number(row.buy_quantity??1),buyTarget:parseTarget(row.buy_target),getQuantity:Number(row.get_quantity??1),getTarget:parseTarget(row.get_target),getPercent:Number(row.get_percent??100),maxApplications:numberOrNull(row.max_applications)}};case"volume":return{...base,effect:{type:"volume",tiers:parseTiers(row.tiers)}};case"free_shipping":return{...base,effect:{type:"free_shipping",maxShipping:numberOrNull(row.max_shipping)}};default:throw new TypeError(`Discount ${row.id} has unknown type "${row.type}".`)}}export function ruleFromCoupon(row){const value=Number(row.discount_value);const productId=numberOrNull(row.product_id);const freeProductId=numberOrNull(row.free_product_id);const base={id:`${COUPON_PREFIX}${row.id}`,title:row.description||row.code,code:row.code,target:productId?{productIds:[productId]}:null,minimumSubtotal:numberOrNull(row.min_order_amount),maxAmount:numberOrNull(row.max_discount_amount),startsAt:row.start_date??null,endsAt:row.end_date?endOfDay(row.end_date):null,isActive:row.is_active==null?true:truthy(row.is_active),usageLimit:numberOrNull(row.usage_limit),usageCount:numberOrNull(row.usage_count)};if(freeProductId){return{...base,target:null,effect:{type:"buy_x_get_y",buyQuantity:1,getQuantity:1,getTarget:{productIds:[freeProductId]},getPercent:100,maxApplications:1}}}return row.discount_type==="fixed_amount"?{...base,effect:{type:"fixed_amount",amount:Math.round(value)}}:{...base,effect:{type:"percentage",percent:value}}}function parseJson(raw){if(raw==null||raw==="")return null;try{return JSON.parse(raw)}catch{return null}}function parseTarget(raw){const parsed=parseJson(raw);if(!parsed||typeof parsed!=="object")return null;const ids=(list)=>Array.isArray(list)?list.map(Number).filter(Number.isSafeInteger):[];return{productIds:ids(parsed.productIds),variantIds:ids(parsed.variantIds),categoryIds:ids(parsed.categoryIds)}}function parseTiers(raw){const parsed=parseJson(raw);if(!Array.isArray(parsed))return[];return parsed.map((t)=>({minQuantity:Number(t.minQuantity),percent:Number(t.percent)})).filter((t)=>Number.isFinite(t.minQuantity)&&Number.isFinite(t.percent))}function numberOrNull(value){if(value==null||value==="")return null;const n=Number(value);return Number.isFinite(n)?n:null}export function truthy(value){return value===true||value===1||value==="1"||value==="true"}function endOfDay(date){return/^\d{4}-\d{2}-\d{2}$/.test(date)?`${date}T23:59:59.999Z`:date}
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ import * as catalogImport from './imports/index';
5
5
  import * as coupons from './coupons/index';
6
6
  import * as customers from './customers/index';
7
7
  import * as devices from './devices/index';
8
+ import * as discounts from './discounts/index';
8
9
  import * as errors from './errors/index';
9
10
  import * as giftCards from './gift-cards/index';
10
11
  import * as licensing from './licensing/index';
@@ -18,6 +19,7 @@ import * as releases from './releases';
18
19
  import * as restaurant from './waitlists/restaurant/index';
19
20
  import * as shippings from './shippings/index';
20
21
  import * as tax from './tax/index';
22
+ import * as upsells from './upsells/index';
21
23
  import * as waitlists from './waitlists/index';
22
24
  export type { MoneyInputOptions } from './money';
23
25
  export type { TaxRateRow } from './sales-tax';
@@ -40,6 +42,7 @@ export declare interface CommerceNamespace {
40
42
  catalog: CatalogModule
41
43
  coupons: CouponsModule
42
44
  customers: CustomersModule
45
+ discounts: DiscountsModule
43
46
  errors: ErrorsModule
44
47
  giftCards: GiftCardsModule
45
48
  licensing: LicensingModule
@@ -51,6 +54,7 @@ export declare interface CommerceNamespace {
51
54
  restaurant: RestaurantModule
52
55
  shippings: ShippingsModule
53
56
  tax: TaxModule
57
+ upsells: UpsellsModule
54
58
  waitlists: WaitlistsModule
55
59
  devices: DevicesModule
56
60
  receipts: ReceiptsModule
@@ -73,6 +77,8 @@ declare type RestaurantModule = typeof restaurant;
73
77
  declare type TaxModule = typeof tax;
74
78
  declare type WaitlistsModule = typeof waitlists;
75
79
  declare type DevicesModule = typeof devices;
80
+ declare type DiscountsModule = typeof discounts;
81
+ declare type UpsellsModule = typeof upsells;
76
82
  declare type ReceiptsModule = typeof receipts;
77
83
  // Catalog import (Shopify, WooCommerce) is a tool rather than a store module,
78
84
  // so it is exported beside the namespace rather than inside it.
@@ -84,6 +90,7 @@ export {
84
90
  coupons,
85
91
  customers,
86
92
  devices,
93
+ discounts,
87
94
  errors,
88
95
  giftCards,
89
96
  money,
@@ -96,6 +103,7 @@ export {
96
103
  restaurant,
97
104
  shippings,
98
105
  tax,
106
+ upsells,
99
107
  waitlists,
100
108
  };
101
109
  // Money conversion at the display and input boundary: stored amounts are
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import*as auctions from"./auctions";import*as carts from"./carts";import*as catalog from"./catalog";import*as catalogImport from"./imports";import*as coupons from"./coupons";import*as customers from"./customers";import*as devices from"./devices";import*as errors from"./errors";import*as giftCards from"./gift-cards";import*as licensing from"./licensing";import*as money from"./money";import*as orders from"./orders";import*as payments from"./payments";import*as products from"./products";import*as register from"./register";import*as releases from"./releases";import*as receipts from"./receipts";import*as shippings from"./shippings";import*as tax from"./tax";import*as waitlists from"./waitlists";import*as restaurant from"./waitlists/restaurant";export const commerce={auctions,carts,catalog,coupons,customers,devices,errors,giftCards,licensing,orders,payments,products,receipts,register,releases,restaurant,shippings,tax,waitlists};export default commerce;export{auctions,carts,catalog,catalogImport,coupons,customers,devices,errors,giftCards,money,orders,payments,products,receipts,register,releases,restaurant,shippings,tax,waitlists};export{currencyExponent,decimalToMinor,formatCurrency,formatMinor,minorToDecimal,minorToInput,minorToMajor,moneyInputError,moneyInputStep,parseMoneyInput,PriceFormatError}from"./money";export{breakdownFor,multiplierOf}from"./sales-tax";export{restockedQuantity}from"./inventory";export{receiptLinesText}from"./receipt-text";export{parseSalesTaxSetup,parseTaxRateWriteData}from"./tax-input";export{licensing};
1
+ import*as auctions from"./auctions";import*as carts from"./carts";import*as catalog from"./catalog";import*as catalogImport from"./imports";import*as coupons from"./coupons";import*as customers from"./customers";import*as devices from"./devices";import*as discounts from"./discounts";import*as errors from"./errors";import*as giftCards from"./gift-cards";import*as licensing from"./licensing";import*as money from"./money";import*as orders from"./orders";import*as payments from"./payments";import*as products from"./products";import*as register from"./register";import*as releases from"./releases";import*as receipts from"./receipts";import*as shippings from"./shippings";import*as tax from"./tax";import*as upsells from"./upsells";import*as waitlists from"./waitlists";import*as restaurant from"./waitlists/restaurant";export const commerce={auctions,carts,catalog,coupons,customers,devices,discounts,errors,giftCards,licensing,orders,payments,products,receipts,register,releases,restaurant,shippings,tax,upsells,waitlists};export default commerce;export{auctions,carts,catalog,catalogImport,coupons,customers,devices,discounts,errors,giftCards,money,orders,payments,products,receipts,register,releases,restaurant,shippings,tax,upsells,waitlists};export{currencyExponent,decimalToMinor,formatCurrency,formatMinor,minorToDecimal,minorToInput,minorToMajor,moneyInputError,moneyInputStep,parseMoneyInput,PriceFormatError}from"./money";export{breakdownFor,multiplierOf}from"./sales-tax";export{restockedQuantity}from"./inventory";export{receiptLinesText}from"./receipt-text";export{parseSalesTaxSetup,parseTaxRateWriteData}from"./tax-input";export{licensing};
@@ -1 +1 @@
1
- import{db}from"@stacksjs/database/runtime";import{formatDate}from"@stacksjs/orm";import{canTransition,emitOrderCancelled,emitOrderPaid,emitOrderRefunded}from"./events";import{handleLicensePaymentEvent}from"../licensing/service";async function findOrderByPaymentIntent(paymentIntentId){const payment=await db.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return null;const order=await db.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();return order??null}let warnedAboutMissingDedupTable=false;async function recordEventOrSkip(event,trx){try{const now=formatDate(new Date);await trx.insertInto("payment_webhook_events").values({provider:event.provider,event_id:event.id,processed_at:now,created_at:now}).execute();return true}catch(err){if(isUniqueViolation(err))return false;if(isMissingTableError(err)){if(!warnedAboutMissingDedupTable){warnedAboutMissingDedupTable=true;console.warn("[commerce/webhook] payment_webhook_events table missing - provider retries will be applied again. Run `buddy migrate` to enable dedup.")}return true}throw err}}function isMissingTableError(err){const e=err;const msg=e?.message??"";return e?.code==="42P01"||msg.includes("no such table")||msg.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(msg)}function isUniqueViolation(err){const e=err;const msg=e?.message??"";return e?.code==="23505"||msg.includes("UNIQUE constraint")||msg.includes("Duplicate entry")||/duplicate key value/i.test(msg)}async function handlePaymentSucceeded(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const now=formatDate(new Date);await trx.updateTable("payments").set({status:"succeeded",updated_at:now}).where("id","=",payment.id).execute();const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&order.status==="PENDING"){await trx.updateTable("orders").set({status:"PROCESSING",updated_at:now}).where("id","=",order.id).execute()}});const order=await findOrderByPaymentIntent(paymentIntentId);if(order)await emitOrderPaid(order)}async function handlePaymentFailed(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;const reason=event.reason??"payment failed";await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const now=formatDate(new Date);await trx.updateTable("payments").set({status:"failed",failure_reason:reason.slice(0,1000),updated_at:now}).where("id","=",payment.id).execute();const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&order.status==="PENDING"){await trx.updateTable("orders").set({status:"CANCELLED",updated_at:now}).where("id","=",order.id).execute()}});const order=await findOrderByPaymentIntent(paymentIntentId);if(order)await emitOrderCancelled(order,reason)}async function handleRefundSucceeded(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;const statedTotal=event.refundedTotal?.amount;const given=statedTotal??event.amount?.amount??0;if(!Number.isSafeInteger(given)||given<=0)return;let fullyRefunded=false;let applied=false;let refundAmount=0;await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const already=Number(payment.refund_amount??0);refundAmount=statedTotal===undefined?given:statedTotal-already;if(refundAmount<=0)return;const total=already+refundAmount;if(total>Number(payment.amount)){console.warn(`[commerce/webhook] ${event.provider} refunded ${refundAmount} of payment ${payment.id}, which has ${Number(payment.amount)-already} left to refund; not recorded.`);return}fullyRefunded=total===Number(payment.amount);const now=formatDate(new Date);await trx.updateTable("payments").set({status:fullyRefunded?"refunded":"partiallyRefunded",refund_amount:total,updated_at:now}).where("id","=",payment.id).execute();applied=true;if(!fullyRefunded)return;const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&canTransition(order.status,"REFUNDED")){await trx.updateTable("orders").set({status:"REFUNDED",updated_at:now}).where("id","=",order.id).execute()}});if(!applied)return;const order=await findOrderByPaymentIntent(paymentIntentId);if(order&&fullyRefunded)await emitOrderRefunded(order,refundAmount)}export async function handleCommercePaymentEvent(event){switch(event.type){case"payment.succeeded":await handlePaymentSucceeded(event);return true;case"payment.failed":await handlePaymentFailed(event);return true;case"refund.succeeded":await handleRefundSucceeded(event);return true;default:return false}}export async function receivePaymentWebhook(request,driver){const{paymentDriver,WebhookNotConfiguredError,WebhookSignatureError}=await import("@stacksjs/payments");const payments=driver??paymentDriver();let events;try{events=await payments.verifyWebhook({payload:await request.text(),headers:request.headers})}catch(error){if(error instanceof WebhookNotConfiguredError)return Response.json({ok:false,reason:"missing-config"},{status:401});if(error instanceof WebhookSignatureError)return Response.json({ok:false,reason:"invalid-signature"},{status:400});throw error}for(const event of events){await handleCommercePaymentEvent(event);await handleLicensePaymentEvent(event)}return payments.acknowledgeWebhook()}export{handlePaymentFailed,handlePaymentSucceeded,handleRefundSucceeded};
1
+ import{db}from"@stacksjs/database/runtime";import{formatDate}from"@stacksjs/orm";import{canTransition,emitOrderCancelled,emitOrderPaid,emitOrderRefunded}from"./events";import{handleLicensePaymentEvent}from"../licensing/service";import{completeUpsellPayment}from"../upsells";async function findOrderByPaymentIntent(paymentIntentId){const payment=await db.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return null;const order=await db.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();return order??null}let warnedAboutMissingDedupTable=false;async function recordEventOrSkip(event,trx){try{const now=formatDate(new Date);await trx.insertInto("payment_webhook_events").values({provider:event.provider,event_id:event.id,processed_at:now,created_at:now}).execute();return true}catch(err){if(isUniqueViolation(err))return false;if(isMissingTableError(err)){if(!warnedAboutMissingDedupTable){warnedAboutMissingDedupTable=true;console.warn("[commerce/webhook] payment_webhook_events table missing - provider retries will be applied again. Run `buddy migrate` to enable dedup.")}return true}throw err}}function isMissingTableError(err){const e=err;const msg=e?.message??"";return e?.code==="42P01"||msg.includes("no such table")||msg.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(msg)}function isUniqueViolation(err){const e=err;const msg=e?.message??"";return e?.code==="23505"||msg.includes("UNIQUE constraint")||msg.includes("Duplicate entry")||/duplicate key value/i.test(msg)}async function handlePaymentSucceeded(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const now=formatDate(new Date);await trx.updateTable("payments").set({status:"succeeded",updated_at:now}).where("id","=",payment.id).execute();const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&order.status==="PENDING"){await trx.updateTable("orders").set({status:"PROCESSING",updated_at:now}).where("id","=",order.id).execute()}});const order=await findOrderByPaymentIntent(paymentIntentId);if(order)await emitOrderPaid(order)}async function handlePaymentFailed(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;const reason=event.reason??"payment failed";await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const now=formatDate(new Date);await trx.updateTable("payments").set({status:"failed",failure_reason:reason.slice(0,1000),updated_at:now}).where("id","=",payment.id).execute();const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&order.status==="PENDING"){await trx.updateTable("orders").set({status:"CANCELLED",updated_at:now}).where("id","=",order.id).execute()}});const order=await findOrderByPaymentIntent(paymentIntentId);if(order)await emitOrderCancelled(order,reason)}async function handleRefundSucceeded(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;const statedTotal=event.refundedTotal?.amount;const given=statedTotal??event.amount?.amount??0;if(!Number.isSafeInteger(given)||given<=0)return;let fullyRefunded=false;let applied=false;let refundAmount=0;await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const already=Number(payment.refund_amount??0);refundAmount=statedTotal===undefined?given:statedTotal-already;if(refundAmount<=0)return;const total=already+refundAmount;if(total>Number(payment.amount)){console.warn(`[commerce/webhook] ${event.provider} refunded ${refundAmount} of payment ${payment.id}, which has ${Number(payment.amount)-already} left to refund; not recorded.`);return}fullyRefunded=total===Number(payment.amount);const now=formatDate(new Date);await trx.updateTable("payments").set({status:fullyRefunded?"refunded":"partiallyRefunded",refund_amount:total,updated_at:now}).where("id","=",payment.id).execute();applied=true;if(!fullyRefunded)return;const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&canTransition(order.status,"REFUNDED")){await trx.updateTable("orders").set({status:"REFUNDED",updated_at:now}).where("id","=",order.id).execute()}});if(!applied)return;const order=await findOrderByPaymentIntent(paymentIntentId);if(order&&fullyRefunded)await emitOrderRefunded(order,refundAmount)}export async function handleCommercePaymentEvent(event){switch(event.type){case"payment.succeeded":if(event.reference&&await completeUpsellPayment(event.reference,{succeeded:true,provider:event.provider}))return true;await handlePaymentSucceeded(event);return true;case"payment.failed":if(event.reference&&await completeUpsellPayment(event.reference,{succeeded:false,reason:event.reason,provider:event.provider}))return true;await handlePaymentFailed(event);return true;case"refund.succeeded":await handleRefundSucceeded(event);return true;default:return false}}export async function receivePaymentWebhook(request,driver){const{paymentDriver,WebhookNotConfiguredError,WebhookSignatureError}=await import("@stacksjs/payments");const payments=driver??paymentDriver();let events;try{events=await payments.verifyWebhook({payload:await request.text(),headers:request.headers})}catch(error){if(error instanceof WebhookNotConfiguredError)return Response.json({ok:false,reason:"missing-config"},{status:401});if(error instanceof WebhookSignatureError)return Response.json({ok:false,reason:"invalid-signature"},{status:400});throw error}for(const event of events){await handleCommercePaymentEvent(event);await handleLicensePaymentEvent(event)}return payments.acknowledgeWebhook()}export{handlePaymentFailed,handlePaymentSucceeded,handleRefundSucceeded};
@@ -0,0 +1,183 @@
1
+ import type { PaymentDriver, Payer } from '@stacksjs/payments';
2
+ /** The offers an order qualifies for right now, highest priority first. */
3
+ export declare function eligibleOffers(orderId: number, options?: { now?: Date }): Promise<OfferRow[]>;
4
+ /**
5
+ * The offers to show on an order's confirmation page, priced and with their
6
+ * variants and stock, recording a `viewed` response for each product shown so
7
+ * conversion can be measured. `limit` defaults to one offer, the way a
8
+ * post-purchase page shows a single proposition.
9
+ */
10
+ export declare function presentOffers(orderId: number, options?: { now?: Date, limit?: number, record?: boolean }): Promise<UpsellOfferView[]>;
11
+ /**
12
+ * Add an offered product to the order: claim, charge, finish. See the module
13
+ * comment for the order of operations.
14
+ */
15
+ export declare function acceptOffer(input: AcceptOfferInput): Promise<AcceptOfferResult>;
16
+ /**
17
+ * Finish a pending acceptance whose payment the provider has now settled.
18
+ * Called by the payment webhook with the payment's reference: `succeeded`
19
+ * adds the line to the order, anything else releases the stock. Answers
20
+ * whether a pending acceptance matched, so other payments pass through.
21
+ */
22
+ export declare function completeUpsellPayment(reference: string, outcome: { succeeded: boolean, reason?: string | null, provider?: string | null }, options?: { taxFor?: AcceptOfferInput['taxFor'] }): Promise<boolean>;
23
+ /**
24
+ * Fail acceptances left `pending` for longer than `olderThanMinutes` (default
25
+ * 60) and put their stock back: a 3-D Secure prompt the shopper walked away
26
+ * from would otherwise hold the items forever. Schedule it like the abandoned
27
+ * cart sweeper. A payment that settles after this still reaches the webhook,
28
+ * which finds nothing pending and leaves it for a person to refund.
29
+ */
30
+ export declare function releaseStalePending(options?: { olderThanMinutes?: number, now?: Date }): Promise<number>;
31
+ /**
32
+ * Turn an offer down for this order. Every product of it the shopper saw and
33
+ * had not taken is marked declined. Answers how many were.
34
+ */
35
+ export declare function declineOffer(orderId: number, offerId: number, options?: { now?: Date }): Promise<number>;
36
+ /** How an offer is doing, or every offer together without an id. */
37
+ export declare function offerStats(offerId?: number): Promise<OfferStats>;
38
+ /**
39
+ * A charger that takes the money through a `@stacksjs/payments` driver,
40
+ * off-session, on the payment method the original order was paid with.
41
+ */
42
+ export declare function chargeWith(driver: PaymentDriver, options: ChargeWithOptions): Exclude<UpsellCharger, 'collect-later'>;
43
+ /**
44
+ * A charger that takes the money from the payer's default saved payment
45
+ * method (or their only one) through a payments driver. Throws, which
46
+ * `acceptOffer` reports as a failed payment, when they have none on file.
47
+ */
48
+ export declare function chargeDefaultMethod(driver: PaymentDriver, payer: Payer): Exclude<UpsellCharger, 'collect-later'>;
49
+ /** The response rows an order has, for showing what it already did. */
50
+ export declare function responsesFor(orderId: number): Promise<ResponseRow[]>;
51
+ export declare interface OfferRow {
52
+ id: number
53
+ uuid?: string | null
54
+ name: string
55
+ headline?: string | null
56
+ message?: string | null
57
+ product_ids: string
58
+ discount_percent?: number | string | null
59
+ min_quantity?: number | null
60
+ default_quantity?: number | null
61
+ max_quantity?: number | null
62
+ trigger_product_ids?: string | null
63
+ min_order_total?: number | null
64
+ window_minutes?: number | null
65
+ priority?: number | null
66
+ is_active?: number | boolean | null
67
+ starts_at?: string | null
68
+ ends_at?: string | null
69
+ }
70
+ export declare interface ResponseRow {
71
+ id: number
72
+ post_purchase_offer_id: number
73
+ order_id: number
74
+ status: ResponseStatus
75
+ product_id: number
76
+ variant_id?: number | null
77
+ quantity?: number | null
78
+ unit_price?: number | null
79
+ compare_at_price?: number | null
80
+ amount?: number | null
81
+ currency?: string | null
82
+ payment_reference?: string | null
83
+ payment_provider?: string | null
84
+ failure_reason?: string | null
85
+ order_item_id?: number | null
86
+ responded_at?: string | null
87
+ }
88
+ export declare interface UpsellVariantView {
89
+ id: number
90
+ name: string
91
+ type: string | null
92
+ options: Record<string, unknown> | null
93
+ unitPrice: number
94
+ regularPrice: number
95
+ inventory: number | null
96
+ inStock: boolean
97
+ }
98
+ export declare interface UpsellProductView {
99
+ productId: number
100
+ name: string
101
+ slug: string | null
102
+ imageUrl: string | null
103
+ description: string | null
104
+ unitPrice: number
105
+ regularPrice: number
106
+ percentOff: number
107
+ variants: UpsellVariantView[]
108
+ inventory: number | null
109
+ inStock: boolean
110
+ status: ResponseStatus | null
111
+ }
112
+ export declare interface UpsellOfferView {
113
+ offerId: number
114
+ headline: string | null
115
+ message: string | null
116
+ discountPercent: number
117
+ minQuantity: number
118
+ defaultQuantity: number
119
+ maxQuantity: number | null
120
+ currency: string
121
+ expiresAt: string
122
+ products: UpsellProductView[]
123
+ }
124
+ export declare interface UpsellChargeRequest {
125
+ amount: number
126
+ currency: string
127
+ orderId: number
128
+ offerId: number
129
+ responseId: number
130
+ idempotencyKey: string
131
+ reference: string
132
+ description: string
133
+ }
134
+ export declare interface UpsellChargeResult {
135
+ status: 'succeeded' | 'processing' | 'requires_action' | 'requires_payment_method' | 'failed' | 'canceled'
136
+ reference?: string | null
137
+ provider?: string | null
138
+ failureReason?: string | null
139
+ clientConfirmation?: unknown
140
+ redirectUrl?: string | null
141
+ }
142
+ export declare interface AcceptOfferInput {
143
+ orderId: number
144
+ offerId: number
145
+ productId: number
146
+ variantId?: number | null
147
+ quantity: number
148
+ charge: UpsellCharger
149
+ taxFor?: (amount: number, order: Record<string, unknown>) => number
150
+ now?: Date
151
+ }
152
+ export declare interface OfferStats {
153
+ offerId: number | null
154
+ views: number
155
+ accepted: number
156
+ declined: number
157
+ pending: number
158
+ failed: number
159
+ conversionRate: number
160
+ revenue: number
161
+ units: number
162
+ }
163
+ export declare interface ChargeWithOptions {
164
+ payer: Payer
165
+ paymentMethod: string
166
+ }
167
+ export type ResponseStatus = 'viewed' | 'pending' | 'accepted' | 'declined' | 'failed';
168
+ /** Why an order does not qualify, or no longer does. */
169
+ export type IneligibleReason = 'order-not-found' | 'order-closed' | 'offer-not-found' | 'offer-inactive' | 'offer-expired' | 'not-eligible';
170
+ /**
171
+ * Takes the money for an accepted offer. `'collect-later'` adds the line
172
+ * without taking a payment, for stores that invoice, take cash on delivery or
173
+ * capture the whole order later; it is explicit so leaving the charge out can
174
+ * never give goods away by accident.
175
+ */
176
+ // eslint-disable-next-line pickier/no-unused-vars
177
+ export type UpsellCharger = ((request: UpsellChargeRequest) => Promise<UpsellChargeResult>) | 'collect-later';
178
+ export type AcceptOfferResult = | { ok: true, status: 'accepted', response: ResponseRow, orderItemId: number, order: Record<string, unknown> }
179
+ /** The provider has the payment but has not confirmed it; the webhook finishes it. */
180
+ | { ok: true, status: 'pending', response: ResponseRow }
181
+ | { ok: false, reason: 'payment-requires-action', response: ResponseRow, clientConfirmation?: unknown, redirectUrl?: string | null }
182
+ | { ok: false, reason: 'payment-failed', response: ResponseRow, message: string }
183
+ | { ok: false, reason: IneligibleReason | 'invalid-product' | 'invalid-variant' | 'invalid-quantity' | 'already-responded' | 'out-of-stock', message: string }
@@ -0,0 +1,5 @@
1
+ import{randomUUIDv7}from"bun";import{db,mutationCount,sqlHelpers}from"@stacksjs/database/runtime";import{env}from"@stacksjs/env";import{formatDate,isUniqueViolation}from"@stacksjs/orm";import{percentOf}from"../discounts/engine";const CLOSED_ORDER_STATUSES=new Set(["CANCELLED","CANCELED","REFUNDED","FAILED"]);const q=()=>db;export async function eligibleOffers(orderId,options={}){const now=options.now??new Date;const order=await loadOrder(orderId);if(!order||isOrderClosed(order))return[];const items=await loadOrderProductIds(orderId);const offers=await q().selectFrom("post_purchase_offers").selectAll().execute();const responses=await loadResponses(orderId);return offers.filter((offer)=>checkEligibility(offer,order,items,now)===null).filter((offer)=>{const productIds=parseIds(offer.product_ids);return productIds.some((pid)=>!responses.some((r)=>r.post_purchase_offer_id===offer.id&&r.product_id===pid&&(r.status==="accepted"||r.status==="declined")))}).sort((a,b)=>Number(b.priority??0)-Number(a.priority??0)||a.id-b.id)}export async function presentOffers(orderId,options={}){const now=options.now??new Date;const offers=(await eligibleOffers(orderId,{now})).slice(0,options.limit??1);if(offers.length===0)return[];const order=await loadOrder(orderId);const currency=String(order.currency||"USD").toUpperCase();const responses=await loadResponses(orderId);const views=[];for(const offer of offers){const percent=Number(offer.discount_percent??0);const products=[];for(const productId of parseIds(offer.product_ids)){const product=await q().selectFrom("products").where("id","=",productId).selectAll().executeTakeFirst();if(!product||product.is_available===0||product.is_available===false)continue;const variants=await loadVariants(productId);const base=Math.round(Number(product.price??0));const variantViews=variants.map((v)=>{const regular=v.price!=null?Math.round(Number(v.price)):base;const inventory=v.inventory_count==null?null:Number(v.inventory_count);return{id:Number(v.id),name:String(v.variant??""),type:v.type??null,options:parseObject(v.options),unitPrice:regular-percentOf(regular,percent),regularPrice:regular,inventory,inStock:inventory==null||inventory>0}});const inventory=product.inventory_count==null?null:Number(product.inventory_count);const lead=variantViews[0];const existing=responses.find((r)=>r.post_purchase_offer_id===offer.id&&r.product_id===productId);products.push({productId,name:String(product.name??""),slug:product.slug??null,imageUrl:product.image_url??null,description:product.description??null,unitPrice:lead?lead.unitPrice:base-percentOf(base,percent),regularPrice:lead?lead.regularPrice:base,percentOff:percent,variants:variantViews,inventory,inStock:variantViews.length?variantViews.some((v)=>v.inStock):inventory==null||inventory>0,status:existing?.status??null});if(options.record!==false&&!existing)await recordView(offer.id,orderId,productId)}if(products.length===0)continue;views.push({offerId:offer.id,headline:offer.headline??null,message:offer.message??null,discountPercent:percent,minQuantity:Number(offer.min_quantity??1),defaultQuantity:Math.max(Number(offer.default_quantity??1),Number(offer.min_quantity??1)),maxQuantity:offer.max_quantity==null?null:Number(offer.max_quantity),currency,expiresAt:new Date(offerClosesAt(offer,order)).toISOString(),products})}return views}export async function acceptOffer(input){const now=input.now??new Date;if(!Number.isSafeInteger(input.quantity)||input.quantity<1)return{ok:false,reason:"invalid-quantity",message:"Quantity must be a whole number of at least 1."};const order=await loadOrder(input.orderId);if(!order)return{ok:false,reason:"order-not-found",message:"That order does not exist."};const offer=await q().selectFrom("post_purchase_offers").where("id","=",input.offerId).selectAll().executeTakeFirst();if(!offer)return{ok:false,reason:"offer-not-found",message:"That offer does not exist."};const ineligible=isOrderClosed(order)?"order-closed":checkEligibility(offer,order,await loadOrderProductIds(input.orderId),now);if(ineligible)return{ok:false,reason:ineligible,message:INELIGIBLE_MESSAGES[ineligible]};if(!parseIds(offer.product_ids).includes(input.productId))return{ok:false,reason:"invalid-product",message:"That product is not part of this offer."};const minQuantity=Number(offer.min_quantity??1);const maxQuantity=offer.max_quantity==null?null:Number(offer.max_quantity);if(input.quantity<minQuantity||maxQuantity!=null&&input.quantity>maxQuantity){return{ok:false,reason:"invalid-quantity",message:maxQuantity==null?`This offer needs at least ${minQuantity}.`:`This offer takes ${minQuantity} to ${maxQuantity}.`}}const product=await q().selectFrom("products").where("id","=",input.productId).selectAll().executeTakeFirst();if(!product||product.is_available===0||product.is_available===false)return{ok:false,reason:"invalid-product",message:"That product is no longer available."};const variants=await loadVariants(input.productId);let variant;if(variants.length>0){variant=variants.find((v)=>Number(v.id)===Number(input.variantId));if(!variant)return{ok:false,reason:"invalid-variant",message:"Choose one of this product's options."}}else if(input.variantId!=null){return{ok:false,reason:"invalid-variant",message:"This product has no options to choose."}}const regular=variant?.price!=null?Math.round(Number(variant.price)):Math.round(Number(product.price??0));const unitPrice=regular-percentOf(regular,Number(offer.discount_percent??0));const amount=unitPrice*input.quantity;const currency=String(order.currency||"USD").toUpperCase();let response;try{response=await db.transaction(async(trx)=>{const stamp=formatDate(now);const snapshot={status:"pending",variant_id:variant?Number(variant.id):null,quantity:input.quantity,unit_price:unitPrice,compare_at_price:regular,amount,currency,payment_reference:null,payment_provider:null,failure_reason:null,responded_at:stamp,updated_at:stamp};const claimed=await claimResponse(trx,offer.id,input.orderId,input.productId,snapshot,stamp);if(!claimed)throw Object.assign(new Error("already responded"),{__upsell:"already-responded"});const reserved=await adjustStock(trx,input.productId,variant?Number(variant.id):null,-input.quantity,stamp);if(!reserved)throw Object.assign(new Error("out of stock"),{__upsell:"out-of-stock"});return await trx.selectFrom("post_purchase_offer_responses").where("id","=",claimed).selectAll().executeTakeFirst()})}catch(err){if(err?.__upsell==="already-responded")return{ok:false,reason:"already-responded",message:"This offer has already been used on this order."};if(err?.__upsell==="out-of-stock")return{ok:false,reason:"out-of-stock",message:"Sorry, there is not enough of that left."};throw err}if(input.charge==="collect-later")return await finishAccepted(response,{taxFor:input.taxFor});let charged;try{charged=await input.charge({amount,currency,orderId:input.orderId,offerId:offer.id,responseId:response.id,idempotencyKey:`upsell-${response.id}-${toTime(response.responded_at)??response.id}`,reference:`upsell-${response.id}`,description:`${product.name??"Item"} added to order #${input.orderId}`})}catch(error){const message=error instanceof Error?error.message:String(error);const failed=await failAcceptance(response.id,message);return{ok:false,reason:"payment-failed",response:failed??response,message}}if(charged.status==="succeeded")return await finishAccepted(response,{reference:charged.reference,provider:charged.provider,taxFor:input.taxFor});if(charged.status==="failed"||charged.status==="canceled"){const message=charged.failureReason||"The payment did not go through.";const failed=await failAcceptance(response.id,message);return{ok:false,reason:"payment-failed",response:failed??response,message}}const pending=await recordPendingPayment(response.id,charged.reference??null,charged.provider??null);if(charged.status==="processing")return{ok:true,status:"pending",response:pending??response};return{ok:false,reason:"payment-requires-action",response:pending??response,clientConfirmation:charged.clientConfirmation,redirectUrl:charged.redirectUrl??null}}export async function completeUpsellPayment(reference,outcome,options={}){if(!reference)return false;const response=await q().selectFrom("post_purchase_offer_responses").where("payment_reference","=",reference).selectAll().executeTakeFirst();if(!response||response.status!=="pending")return false;if(outcome.succeeded)await finishAccepted(response,{reference,provider:outcome.provider??response.payment_provider,taxFor:options.taxFor});else await failAcceptance(response.id,outcome.reason||"The payment did not go through.");return true}export async function releaseStalePending(options={}){const now=options.now??new Date;const cutoff=formatDate(new Date(now.getTime()-(options.olderThanMinutes??60)*60000));const stale=await q().selectFrom("post_purchase_offer_responses").where("status","=","pending").where("updated_at","<",cutoff).select(["id"]).execute();let released=0;for(const{id}of stale){const row=await failAcceptance(Number(id),"The payment was not completed in time.");if(row?.status==="failed")released++}return released}export async function declineOffer(orderId,offerId,options={}){const stamp=formatDate(options.now??new Date);const result=await q().updateTable("post_purchase_offer_responses").set({status:"declined",responded_at:stamp,updated_at:stamp}).where("order_id","=",orderId).where("post_purchase_offer_id","=",offerId).where("status","in",["viewed","failed"]).executeTakeFirst();return mutationCount(result)}export async function offerStats(offerId){let query=q().selectFrom("post_purchase_offer_responses").selectAll();if(offerId!=null)query=query.where("post_purchase_offer_id","=",offerId);const rows=await query.execute();const count=(status)=>rows.filter((r)=>r.status===status).length;const accepted=rows.filter((r)=>r.status==="accepted");return{offerId:offerId??null,views:rows.length,accepted:accepted.length,declined:count("declined"),pending:count("pending"),failed:count("failed"),conversionRate:rows.length?accepted.length/rows.length:0,revenue:accepted.reduce((s,r)=>s+Number(r.amount??0),0),units:accepted.reduce((s,r)=>s+Number(r.quantity??0),0)}}export function chargeWith(driver,options){return async(request)=>{const result=await driver.charge(options.payer,{amount:request.amount,currency:request.currency.toLowerCase()},options.paymentMethod,{idempotencyKey:request.idempotencyKey,reference:request.reference,description:request.description,metadata:{order_id:String(request.orderId),post_purchase_offer_id:String(request.offerId),post_purchase_offer_response_id:String(request.responseId)}});return{status:result.status,reference:result.id,provider:driver.name,failureReason:result.failureReason??null,clientConfirmation:result.clientConfirmation,redirectUrl:result.redirectUrl??null}}}export function chargeDefaultMethod(driver,payer){return async(request)=>{const methods=await driver.paymentMethods(payer);const method=methods.find((m)=>m.isDefault)??(methods.length===1?methods[0]:undefined);if(!method)throw new Error("There is no saved payment method to charge.");return await chargeWith(driver,{payer,paymentMethod:method.id})(request)}}export async function responsesFor(orderId){return await loadResponses(orderId)}const INELIGIBLE_MESSAGES={"order-not-found":"That order does not exist.","order-closed":"This order can no longer be added to.","offer-not-found":"That offer does not exist.","offer-inactive":"This offer is not running.","offer-expired":"This offer has ended.","not-eligible":"This order does not qualify for that offer."};function checkEligibility(offer,order,orderProductIds,now){if(offer.is_active===0||offer.is_active===false)return"offer-inactive";const starts=toTime(offer.starts_at);const ends=toTime(offer.ends_at);if(starts!==null&&now.getTime()<starts)return"offer-inactive";if(ends!==null&&now.getTime()>ends)return"offer-expired";if(now.getTime()>offerClosesAt(offer,order))return"offer-expired";if(offer.min_order_total!=null&&Number(order.total_amount??0)<Number(offer.min_order_total))return"not-eligible";const triggers=parseIds(offer.trigger_product_ids);if(triggers.length&&!triggers.some((id)=>orderProductIds.includes(id)))return"not-eligible";if(parseIds(offer.product_ids).length===0)return"not-eligible";return null}function offerClosesAt(offer,order){const placed=toTime(order.created_at)??Date.now();return placed+Number(offer.window_minutes??30)*60000}function isOrderClosed(order){return CLOSED_ORDER_STATUSES.has(String(order.status??"").toUpperCase())}async function claimResponse(trx,offerId,orderId,productId,snapshot,stamp){const where=(query)=>query.where("order_id","=",orderId).where("post_purchase_offer_id","=",offerId).where("product_id","=",productId);const existing=await where(trx.selectFrom("post_purchase_offer_responses").selectAll()).executeTakeFirst();if(!existing){try{await trx.insertInto("post_purchase_offer_responses").values({post_purchase_offer_id:offerId,order_id:orderId,product_id:productId,created_at:stamp,...snapshot}).execute();const row=await where(trx.selectFrom("post_purchase_offer_responses").selectAll()).executeTakeFirst();return row?Number(row.id):null}catch(err){if(!isUniqueViolation(err))throw err}}const result=await where(trx.updateTable("post_purchase_offer_responses").set(snapshot)).where("status","in",["viewed","failed"]).executeTakeFirst();if(mutationCount(result)===0)return null;const row=await where(trx.selectFrom("post_purchase_offer_responses").selectAll()).executeTakeFirst();return row?Number(row.id):null}async function adjustStock(trx,productId,variantId,delta,stamp){const p=sqlHelpers(env.DB_CONNECTION||"sqlite").param;const table=variantId!=null?"product_variants":"products";const id=variantId??productId;const statement=await trx.unsafe(`UPDATE ${table}
2
+ SET inventory_count = CASE WHEN inventory_count IS NULL THEN NULL ELSE inventory_count + ${p(1)} END,
3
+ updated_at = ${p(2)}
4
+ WHERE id = ${p(3)}
5
+ AND (inventory_count IS NULL OR inventory_count + ${p(4)} >= 0)`,[delta,stamp,id,delta]);return mutationCount(statement)>0}async function finishAccepted(response,payment){const now=formatDate(new Date);const outcome=await db.transaction(async(trx)=>{const order=await trx.selectFrom("orders").where("id","=",response.order_id).selectAll().executeTakeFirst();if(!order)throw new Error(`Order ${response.order_id} disappeared while finishing an upsell.`);const moved=await trx.updateTable("post_purchase_offer_responses").set({status:"accepted",payment_reference:payment.reference??response.payment_reference??null,payment_provider:payment.provider??response.payment_provider??null,updated_at:now}).where("id","=",response.id).where("status","=","pending").executeTakeFirst();if(mutationCount(moved)===0)return null;const amount=Number(response.amount??0);const tax=Math.max(0,Math.round(payment.taxFor?.(amount,order)??0));await trx.insertInto("order_items").values({order_id:response.order_id,product_id:response.product_id,quantity:Number(response.quantity),price:Number(response.unit_price),special_instructions:`Post-purchase offer #${response.post_purchase_offer_id}${response.variant_id?`, variant #${response.variant_id}`:""}`,created_at:now,updated_at:now}).execute();const item=await trx.selectFrom("order_items").where("order_id","=",response.order_id).where("product_id","=",response.product_id).orderBy("id","desc").selectAll().executeTakeFirst();await trx.updateTable("orders").set({total_amount:Number(order.total_amount??0)+amount+tax,tax_amount:Number(order.tax_amount??0)+tax,updated_at:now}).where("id","=",response.order_id).execute();if(payment.reference){await trx.insertInto("payments").values({uuid:randomUUIDv7(),order_id:response.order_id,customer_id:order.customer_id??null,amount:amount+tax,currency:response.currency??order.currency??"USD",method:"creditCard",status:"succeeded",transaction_id:payment.reference,payment_provider:payment.provider??null,reference_number:`upsell-${response.id}`,created_at:now,updated_at:now}).execute()}await trx.updateTable("post_purchase_offer_responses").set({order_item_id:item?.id??null}).where("id","=",response.id).execute();return{order:await trx.selectFrom("orders").where("id","=",response.order_id).selectAll().executeTakeFirst(),response:await trx.selectFrom("post_purchase_offer_responses").where("id","=",response.id).selectAll().executeTakeFirst(),orderItemId:Number(item?.id)}});if(!outcome){const current=await q().selectFrom("post_purchase_offer_responses").where("id","=",response.id).selectAll().executeTakeFirst();const order=await loadOrder(response.order_id);return{ok:true,status:"accepted",response:current,orderItemId:Number(current?.order_item_id),order:order??{}}}emitUpsellAccepted(outcome.order,outcome.response);return{ok:true,status:"accepted",response:outcome.response,orderItemId:outcome.orderItemId,order:outcome.order}}async function failAcceptance(responseId,reason){const stamp=formatDate(new Date);return await db.transaction(async(trx)=>{const response=await trx.selectFrom("post_purchase_offer_responses").where("id","=",responseId).selectAll().executeTakeFirst();if(!response)return;const moved=await trx.updateTable("post_purchase_offer_responses").set({status:"failed",failure_reason:reason.slice(0,1000),updated_at:stamp}).where("id","=",responseId).where("status","=","pending").executeTakeFirst();if(mutationCount(moved)>0&&response.quantity)await adjustStock(trx,response.product_id,response.variant_id??null,Number(response.quantity),stamp);return await trx.selectFrom("post_purchase_offer_responses").where("id","=",responseId).selectAll().executeTakeFirst()})}async function recordPendingPayment(responseId,reference,provider){await q().updateTable("post_purchase_offer_responses").set({payment_reference:reference,payment_provider:provider,updated_at:formatDate(new Date)}).where("id","=",responseId).where("status","=","pending").execute();return await q().selectFrom("post_purchase_offer_responses").where("id","=",responseId).selectAll().executeTakeFirst()}async function recordView(offerId,orderId,productId){const stamp=formatDate(new Date);try{await q().insertInto("post_purchase_offer_responses").values({post_purchase_offer_id:offerId,order_id:orderId,product_id:productId,status:"viewed",created_at:stamp,updated_at:stamp}).execute()}catch(err){if(!isUniqueViolation(err))throw err}}async function emitUpsellAccepted(order,response){try{const mod=await import("@stacksjs/events").catch(()=>null);const dispatch=mod?.dispatch;if(typeof dispatch==="function")dispatch("order:upsell-accepted",{order,response})}catch{}}async function loadOrder(orderId){return await q().selectFrom("orders").where("id","=",orderId).selectAll().executeTakeFirst()}async function loadOrderProductIds(orderId){const rows=await q().selectFrom("order_items").where("order_id","=",orderId).select(["product_id"]).execute();return rows.map((r)=>Number(r.product_id)).filter(Number.isSafeInteger)}async function loadResponses(orderId){return await q().selectFrom("post_purchase_offer_responses").where("order_id","=",orderId).selectAll().execute()}async function loadVariants(productId){const rows=await q().selectFrom("product_variants").where("product_id","=",productId).selectAll().orderBy("id","asc").execute();return rows.filter((v)=>v.status==null||!["inactive","archived","draft"].includes(String(v.status).toLowerCase()))}function parseIds(raw){if(!raw)return[];try{const parsed=JSON.parse(raw);return Array.isArray(parsed)?parsed.map(Number).filter((n)=>Number.isSafeInteger(n)&&n>0):[]}catch{return[]}}function parseObject(raw){if(raw==null||raw==="")return null;if(typeof raw==="object")return raw;try{const parsed=JSON.parse(String(raw));return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{return null}}function toTime(value){if(value==null||value==="")return null;const time=value instanceof Date?value.getTime():Date.parse(asUtc(String(value)));return Number.isFinite(time)?time:null}function asUtc(value){const trimmed=value.trim();return/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/.test(trimmed)?`${trimmed.replace(" ","T")}Z`:trimmed}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/commerce",
3
3
  "type": "module",
4
- "version": "0.75.618",
4
+ "version": "0.75.621",
5
5
  "description": "Stacks commerce utilities.",
6
6
  "author": "Chris Breuer",
7
7
  "contributors": [
@@ -57,19 +57,19 @@
57
57
  "prepublishOnly": "bun run build"
58
58
  },
59
59
  "dependencies": {
60
- "@stacksjs/cache": "0.75.618",
61
- "@stacksjs/config": "0.75.618",
62
- "@stacksjs/database": "0.75.618",
63
- "@stacksjs/env": "0.75.618",
64
- "@stacksjs/error-handling": "0.75.618",
65
- "@stacksjs/events": "0.75.618",
66
- "@stacksjs/logging": "0.75.618",
67
- "@stacksjs/orm": "0.75.618",
68
- "@stacksjs/payments": "0.75.618",
69
- "@stacksjs/realtime": "0.75.618",
70
- "@stacksjs/slug": "0.75.618",
71
- "@stacksjs/strings": "0.75.618",
72
- "@stacksjs/validation": "0.75.618",
60
+ "@stacksjs/cache": "0.75.621",
61
+ "@stacksjs/config": "0.75.621",
62
+ "@stacksjs/database": "0.75.621",
63
+ "@stacksjs/env": "0.75.621",
64
+ "@stacksjs/error-handling": "0.75.621",
65
+ "@stacksjs/events": "0.75.621",
66
+ "@stacksjs/logging": "0.75.621",
67
+ "@stacksjs/orm": "0.75.621",
68
+ "@stacksjs/payments": "0.75.621",
69
+ "@stacksjs/realtime": "0.75.621",
70
+ "@stacksjs/slug": "0.75.621",
71
+ "@stacksjs/strings": "0.75.621",
72
+ "@stacksjs/validation": "0.75.621",
73
73
  "ts-spreadsheets": "^0.2.0"
74
74
  },
75
75
  "devDependencies": {