@stacksjs/commerce 0.74.46 → 0.74.47
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/dist/coupons/update.d.ts +3 -3
- package/dist/index.js +12 -12
- package/dist/payments/update.d.ts +7 -0
- package/dist/utils/mutation-count.d.ts +3 -1
- package/package.json +12 -12
package/dist/coupons/update.d.ts
CHANGED
|
@@ -11,14 +11,14 @@ export declare function update(id: number, data: Omit<CouponUpdate, 'id'>): Prom
|
|
|
11
11
|
* Atomically redeem a coupon (stacksjs/stacks#1879 Co-5).
|
|
12
12
|
*
|
|
13
13
|
* Pre-fix: callers fetched the coupon, checked `usage_count <
|
|
14
|
-
*
|
|
15
|
-
* redemption requests against a coupon with `
|
|
14
|
+
* usage_limit`, then bumped `usage_count` via `update()`. Two concurrent
|
|
15
|
+
* redemption requests against a coupon with `usage_limit=1` both saw
|
|
16
16
|
* `usage_count=0`, both incremented, both succeeded. The coupon
|
|
17
17
|
* was redeemed twice — direct revenue loss equal to `discount_value`
|
|
18
18
|
* times the over-redemption count.
|
|
19
19
|
*
|
|
20
20
|
* Post-fix: single conditional UPDATE that bumps `usage_count` and
|
|
21
|
-
* enforces `
|
|
21
|
+
* enforces `usage_limit` / `is_active` / expiry in the WHERE clause.
|
|
22
22
|
* The database guarantees only one writer wins the race. Returns a
|
|
23
23
|
* discriminated result so callers can surface a useful reason
|
|
24
24
|
* ("limit reached" vs "expired" vs "inactive") instead of a generic
|
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var Im=Object.defineProperty;var Nm=(t)=>t;function Jm(t,e){this[t]=Nm.bind(null,e)}var g=(t,e)=>{for(var r in e)Im(t,r,{get:e[r],enumerable:!0,configurable:!0,set:Jm.bind(e,r)})};var Bm=(t,e,r)=>()=>{if(t)try{e=t(t=0)}catch(o){r=[o]}if(r)throw r[0];return e};function ve(t,e){if(t===e)return!0;return hp[t]?.includes(e)??!1}async function fe(t,e){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let o=r.dispatch;if(typeof o!=="function")return;o(t,e)}catch{}}async function Et(t){await fe("order:created",{order:t})}async function we(t,e){await fe("order:paid",{order:t,payment:e})}async function vo(t){await fe("order:shipped",{order:t})}async function gp(t){await fe("order:out_for_delivery",{order:t})}async function Po(t){await fe("order:delivered",{order:t})}async function Ve(t,e){await fe("order:cancelled",{order:t,reason:e})}async function qe(t,e){await fe("order:refunded",{order:t,refundAmount:e})}async function Pe(t,e){switch(t){case"PROCESSING":return we(e);case"SHIPPED":return vo(e);case"OUT_FOR_DELIVERY":return gp(e);case"DELIVERED":return Po(e);case"CANCELLED":return Ve(e);case"REFUNDED":return qe(e);case"PENDING":default:}}var hp;var Fe=Bm(()=>{hp={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","OUT_FOR_DELIVERY","CANCELLED","REFUNDED"],SHIPPED:["OUT_FOR_DELIVERY","DELIVERED","REFUNDED"],OUT_FOR_DELIVERY:["DELIVERED","SHIPPED","CANCELLED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]}});var no={};g(no,{DEFAULT_INCREMENT_LADDER:()=>V,auctionChannel:()=>yt,auctionTotals:()=>Vr,biddersFor:()=>Ir,bids:()=>Lr,bidsByBidder:()=>Mr,bidsForAuction:()=>Ar,bidsForItem:()=>Cr,broadcastBid:()=>Jr,broadcastItemClosed:()=>Or,broadcastPledge:()=>Br,closeAuction:()=>Hr,closeDueItems:()=>Kr,closeItem:()=>We,closingSoon:()=>Yr,closingSoonNotification:()=>Lm,currencyFor:()=>Ur,determineWinner:()=>xe,effectiveCloseAt:()=>ae,engine:()=>jr,extendedCloseAt:()=>Be,fetchAuction:()=>L,fetchAuctionForEvent:()=>zr,fetchCatalogue:()=>Gr,fetchItems:()=>Z,fetchPledges:()=>ro,incrementFor:()=>O,leadingBid:()=>Je,lots:()=>Xr,makePledge:()=>An,nextMinimumBid:()=>q,openAuction:()=>Zr,outbidNotification:()=>$m,placeBid:()=>Wr,pledgeLevels:()=>Mn,pledgeTotal:()=>to,pledges:()=>oo,resolveBid:()=>Oe,rulesFor:()=>Ue,settle:()=>$e,settleAuction:()=>Qr,winnerNotification:()=>Wm});var Lr={};g(Lr,{biddersFor:()=>Ir,bidsByBidder:()=>Mr,bidsForAuction:()=>Ar,bidsForItem:()=>Cr,leadingBid:()=>Je,placeBid:()=>Wr});import{db as Ne}from"@stacksjs/database";async function Je(t){return await Ne.selectFrom("bids").selectAll().where("auction_item_id","=",t).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function Cr(t){return await Ne.selectFrom("bids").selectAll().where("auction_item_id","=",t).orderBy("placed_at","desc").execute()??[]}async function Ar(t){return await Ne.selectFrom("bids").selectAll().where("auction_id","=",t).orderBy("placed_at","asc").execute()??[]}async function Mr(t,e){return await Ne.selectFrom("bids").selectAll().where("auction_id","=",t).where("bidder_email","=",e.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function Ir(t){let e=await Ne.selectFrom("bids").select(["bidder_name","bidder_email"]).where("auction_id","=",t).execute(),r=new Map;for(let o of e??[]){let n=o.bidder_email.toLowerCase();if(!r.has(n))r.set(n,{name:o.bidder_name,email:o.bidder_email})}return[...r.values()]}var{randomUUIDv7:Um}=globalThis.Bun;import{db as $r}from"@stacksjs/database";function Be(t,e,r,o){if(r.antiSnipeMinutes<=0||r.extendOnBidWindowMinutes<=0)return null;if(t.extension_count>=r.maxExtensions)return null;let n=e.getTime()-o.getTime();if(n<=0)return null;if(n>r.extendOnBidWindowMinutes*60000)return null;let a=new Date(o.getTime()+r.antiSnipeMinutes*60000);return a>e?a:null}function ae(t,e){return new Date(t.closes_at??e)}var V=[{upTo:5000,step:200},{upTo:1e4,step:500},{upTo:25000,step:1000},{upTo:50000,step:2500},{upTo:1e5,step:5000},{upTo:250000,step:1e4},{upTo:null,step:25000}];function O(t,e=V,r){if(r&&r>0)return r;for(let o of e)if(o.upTo===null||t<o.upTo)return o.step;return e[e.length-1]?.step??100}function q(t,e,r=V){if(e===null||e<=0)return t.starting_bid;return e+O(e,r,t.min_increment)}function Oe(t,e,r,o=V){let n=Math.max(r.amount,r.maxAmount??0),a=q(t,e?e.amount:null,o);if(r.maxAmount!=null&&r.maxAmount<r.amount)return{accepted:!1,reason:"max_below_amount",message:"Your maximum bid has to be at least as much as your bid.",nextMinimumBid:a};if(n<a)return{accepted:!1,reason:"below_minimum",message:`The next bid on this lot is ${a/100}.`,nextMinimumBid:a};if(t.buy_now_price&&n>=t.buy_now_price)return{accepted:!0,buyNow:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:t.buy_now_price,maxAmount:t.buy_now_price,isChallenger:!0},challengerAmount:t.buy_now_price,outbid:e?{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount}:void 0,nextMinimumBid:t.buy_now_price};if(!e){let m=Math.max(t.starting_bid,r.amount);return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:m,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:m,nextMinimumBid:m+O(m,o,t.min_increment)}}let s=Math.max(e.amount,e.max_amount??0);if(e.bidder_email.toLowerCase()===r.bidderEmail.toLowerCase()){if(n<=s)return{accepted:!1,reason:"already_leading",message:"You are already the leading bidder at or above that amount.",nextMinimumBid:a};return{accepted:!0,leader:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount,maxAmount:n,isChallenger:!1},challengerAmount:e.amount,nextMinimumBid:e.amount+O(e.amount,o,t.min_increment)}}if(n>s){let m=s+O(s,o,t.min_increment),p=Math.min(n,Math.max(m,a));return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:p,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:p,outbid:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount},nextMinimumBid:p+O(p,o,t.min_increment)}}let u=n+O(n,o,t.min_increment),c=Math.min(s,Math.max(u,n));return{accepted:!0,leader:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:c,maxAmount:e.max_amount??null,isChallenger:!1},challengerAmount:n,outbid:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:n},nextMinimumBid:c+O(c,o,t.min_increment)}}function yt(t){return`auction.${t}`}async function Nr(){try{let t=await import("@stacksjs/realtime");return t.emit??null}catch{return null}}async function Jr(t){let e=await Nr();if(!e||!t.item||!t.leader)return;await e(yt(t.item.auction_id),"bid.placed",{itemId:t.item.id,lotNumber:t.item.lot_number,amount:t.leader.amount,nextMinimumBid:t.nextMinimumBid,leaderName:t.leader.bidderName,status:t.item.status,closesAt:t.item.closes_at,extended:Boolean(t.extendedTo),soldViaBuyNow:Boolean(t.buyNow)})}async function Br(t,e){let r=await Nr();if(!r)return;await r(yt(t.auction_id),"pledge.made",{donorName:t.donor_name,amount:t.amount,level:t.level??null,runningTotal:e})}async function Or(t,e,r){let o=await Nr();if(!o)return;await o(yt(t),"item.closed",{itemId:e,...r})}import{config as Om}from"@stacksjs/config";function Sn(){return Om.commerce??{}}function Cn(){return Sn().auction??{}}function Ue(t){let e=Cn();return{increments:e.increments?.length?e.increments:V,antiSnipeMinutes:t?.anti_snipe_minutes??e.antiSnipeMinutes??2,extendOnBidWindowMinutes:t?.extend_on_bid_window_minutes??e.extendOnBidWindowMinutes??2,maxExtensions:t?.max_extensions??e.maxExtensions??20}}function Ur(t){return t?.currency??Cn().currency??Sn().currency??"USD"}function ht(t){return t.toISOString().slice(0,19).replace("T"," ")}async function Wr(t){let e=t.now??new Date,r=await $r.selectFrom("auction_items").selectAll().where("id","=",t.itemId).executeTakeFirst();if(!r)return{accepted:!1,reason:"item_not_found",message:"That lot is no longer available.",nextMinimumBid:0};let o=await $r.selectFrom("auctions").selectAll().where("id","=",r.auction_id).executeTakeFirst(),n=Ue(o),a=await Je(r.id),s=q(r,a?.amount??null,n.increments);if(!o||o.status!=="open"||new Date(o.opens_at)>e)return{accepted:!1,reason:"auction_not_open",message:"Bidding is not open yet.",nextMinimumBid:s,item:r};let i=ae(r,o.closes_at);if(r.status!=="open"||i<=e)return{accepted:!1,reason:"item_not_open",message:"Bidding on this lot has closed.",nextMinimumBid:s,item:r};let u=Oe(r,a,{bidderEmail:t.bidderEmail,bidderName:t.bidderName,amount:t.amount,maxAmount:t.maxAmount},n.increments);if(!u.accepted)return{...u,item:r};let c=u.buyNow?null:Be(r,i,n,e),m=u.leader&&!u.leader.isChallenger&&a&&a.bidder_email.toLowerCase()===t.bidderEmail.toLowerCase(),p=await $r.transaction(async(y)=>{if(m&&a)return await y.updateTable("bids").set({max_amount:u.leader.maxAmount}).where("id","=",a.id).execute(),{...a,max_amount:u.leader.maxAmount};let b=u.leader?.isChallenger===!0,_=Um();if(await y.insertInto("bids").values({uuid:_,auction_id:r.auction_id,auction_item_id:r.id,bidder_name:t.bidderName,bidder_email:t.bidderEmail.toLowerCase(),amount:u.challengerAmount??t.amount,max_amount:t.maxAmount??null,status:b?"leading":"outbid",placed_at:ht(e)}).execute(),a){if(b)await y.updateTable("bids").set({status:"outbid"}).where("id","=",a.id).execute();else if(u.leader&&u.leader.amount!==a.amount)await y.updateTable("bids").set({amount:u.leader.amount}).where("id","=",a.id).execute()}if(u.buyNow)await y.updateTable("auction_items").set({status:"sold",closes_at:ht(e)}).where("id","=",r.id).execute();else if(c)await y.updateTable("auction_items").set({closes_at:ht(c),extension_count:r.extension_count+1}).where("id","=",r.id).execute();return await y.selectFrom("bids").selectAll().where("uuid","=",_).executeTakeFirst()}),f={...u,bid:p,item:{...r,status:u.buyNow?"sold":r.status,closes_at:c?ht(c):r.closes_at,extension_count:c?r.extension_count+1:r.extension_count},extendedTo:c??void 0};return await Jr(f).catch(()=>{return}),f}var jr={};g(jr,{DEFAULT_INCREMENT_LADDER:()=>V,determineWinner:()=>xe,effectiveCloseAt:()=>ae,extendedCloseAt:()=>Be,incrementFor:()=>O,nextMinimumBid:()=>q,resolveBid:()=>Oe,settle:()=>$e});function xe(t,e){let r=e.filter((a)=>a.status!=="invalid");if(r.length===0)return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"passed",amount:0,passedReason:"no_bids"};let n=[...r].sort((a,s)=>{if(s.amount!==a.amount)return s.amount-a.amount;return new Date(a.placed_at).getTime()-new Date(s.placed_at).getTime()})[0];if(t.reserve_price&&n.amount<t.reserve_price)return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"passed",amount:n.amount,passedReason:"reserve_not_met"};return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"sold",winningBidId:n.id,winnerName:n.bidder_name,winnerEmail:n.bidder_email,amount:n.amount}}function $e(t,e,r,o){let n=e.filter((p)=>p.status==="sold"),a=e.filter((p)=>p.status==="passed"),s=n.reduce((p,f)=>p+f.amount,0),i=r.filter((p)=>p.status==="confirmed").reduce((p,f)=>p+f.amount,0),u=new Map(t.map((p)=>[p.id,p.fair_market_value??null])),c=n.reduce((p,f)=>{let y=u.get(f.itemId);return y==null?p:p+(f.amount-y)},0),m=e.length;return{auctionId:o.auctionId,currency:o.currency,totalRaised:s+i,bidRevenue:s,pledgeRevenue:i,goalAmount:o.goalAmount??null,itemsSold:n.length,itemsPassed:a.length,sellThrough:m===0?0:n.length/m,valueDelta:c,outcomes:e}}var Xr={};g(Xr,{auctionTotals:()=>Vr,closeAuction:()=>Hr,closeDueItems:()=>Kr,closeItem:()=>We,closingSoon:()=>Yr,fetchAuction:()=>L,fetchAuctionForEvent:()=>zr,fetchCatalogue:()=>Gr,fetchItems:()=>Z,openAuction:()=>Zr,settleAuction:()=>Qr});import{db as se}from"@stacksjs/database";async function L(t){return await se.selectFrom("auctions").selectAll().where("id","=",t).executeTakeFirst()??null}async function zr(t){return await se.selectFrom("auctions").selectAll().where("event_id","=",t).executeTakeFirst()??null}async function Z(t){return await se.selectFrom("auction_items").selectAll().where("auction_id","=",t).orderBy("lot_number","asc").execute()??[]}async function Gr(t){let[e,r]=await Promise.all([L(t),Z(t)]),o=Ue(e),n=await se.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",t).where("status","in",["leading","won"]).execute(),a=await se.selectFrom("bids").select(["auction_item_id"]).where("auction_id","=",t).where("status","!=","invalid").execute(),s=new Map((n??[]).map((u)=>[u.auction_item_id,u])),i=new Map;for(let u of a??[])i.set(u.auction_item_id,(i.get(u.auction_item_id)??0)+1);return r.map((u)=>{let c=s.get(u.id)??null;return{...u,currentBid:c?.amount??0,bidCount:i.get(u.id)??0,nextMinimumBid:q(u,c?.amount??null,o.increments),leaderName:c?.bidder_name??null}})}async function Vr(t){let e=await L(t),r=await se.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",t).where("status","!=","invalid").execute(),o=await se.selectFrom("pledges").select(["amount"]).where("auction_id","=",t).where("status","=","confirmed").execute(),n=r??[],s=n.filter((c)=>c.status==="leading"||c.status==="won").reduce((c,m)=>c+m.amount,0),i=(o??[]).reduce((c,m)=>c+m.amount,0),u=await se.selectFrom("auction_items").where("auction_id","=",t).count();return{currentBidTotal:s,pledgeTotal:i,raised:s+i,goalAmount:e?.goal_amount??null,bidCount:n.length,bidderCount:new Set(n.map((c)=>c.bidder_email.toLowerCase())).size,lotsOffered:Number(u??0),lotsWithBids:new Set(n.map((c)=>c.auction_item_id)).size}}import{db as ie}from"@stacksjs/database";function qr(t){return t.toISOString().slice(0,19).replace("T"," ")}async function Zr(t,e=new Date){return await ie.updateTable("auctions").set({status:"open",opens_at:qr(e)}).where("id","=",t).execute(),await ie.updateTable("auction_items").set({status:"open"}).where("auction_id","=",t).where("status","=","closed").execute(),L(t)}async function We(t,e=new Date){if(t.status==="sold"||t.status==="passed")return null;let r=await ie.selectFrom("bids").selectAll().where("auction_item_id","=",t.id).execute(),o=xe(t,r??[]);return await ie.transaction(async(n)=>{if(await n.updateTable("auction_items").set({status:o.status,closes_at:qr(e)}).where("id","=",t.id).execute(),o.winningBidId)await n.updateTable("bids").set({status:"won"}).where("id","=",o.winningBidId).execute();await n.updateTable("bids").set({status:"lost"}).where("auction_item_id","=",t.id).where("status","in",["leading","outbid"]).execute()}),await Or(t.auction_id,t.id,{status:o.status,amount:o.amount,winnerName:o.winnerName}).catch(()=>{return}),o}async function Kr(t,e=new Date){let r=await L(t);if(!r)return[];let o=await Z(t),n=[];for(let a of o){if(a.status!=="open")continue;if(ae(a,r.closes_at)>e)continue;let s=await We(a,e);if(s)n.push(s)}return n}async function Hr(t,e=new Date){let r=await Z(t),o=[];for(let n of r){let a=await We(n,e);if(a)o.push(a)}return await ie.updateTable("auctions").set({status:"closed",closes_at:qr(e)}).where("id","=",t).execute(),o}async function Qr(t,e={}){let r=await L(t);if(!r)return null;let o=await Z(t),n=await ie.selectFrom("bids").selectAll().where("auction_id","=",t).execute(),a=await ie.selectFrom("pledges").selectAll().where("auction_id","=",t).execute(),s=new Map;for(let u of n??[]){let c=s.get(u.auction_item_id)??[];c.push(u),s.set(u.auction_item_id,c)}let i=o.map((u)=>{let c=xe(u,s.get(u.id)??[]);return u.status==="passed"?{...c,status:"passed"}:c});if(e.markSettled)await ie.updateTable("auctions").set({status:"settled"}).where("id","=",t).execute();return $e(o,i,a??[],{auctionId:t,currency:Ur(r),goalAmount:r.goal_amount??null})}async function Yr(t,e,r=new Date){let o=await L(t);if(!o)return[];let n=new Date(r.getTime()+e*60000);return(await Z(t)).filter((a)=>{if(a.status!=="open")return!1;let s=ae(a,o.closes_at);return s>r&&s<=n})}function eo(t,e="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0}).format(t/100)}function $m(t,e="USD"){if(!t.outbid||!t.item)return null;let r=t.item;return{to:{name:t.outbid.bidderName,email:t.outbid.bidderEmail},type:"outbid",subject:`You have been outbid on lot ${r.lot_number}: ${r.title}`,body:`Someone has bid higher on "${r.title}". The next bid is ${eo(t.nextMinimumBid,e)}. Bidding closes ${new Date(r.closes_at??"").toLocaleString()}.`,data:{itemId:r.id,lotNumber:r.lot_number,title:r.title,nextMinimumBid:t.nextMinimumBid,closesAt:r.closes_at}}}function Wm(t,e="USD"){if(t.status!=="sold"||!t.winnerEmail)return null;return{to:{name:t.winnerName??"Bidder",email:t.winnerEmail},type:"winner",subject:`You won lot ${t.lotNumber}: ${t.title}`,body:`Congratulations - you won "${t.title}" at ${eo(t.amount,e)}. The school will be in touch with payment and pickup details.`,data:{itemId:t.itemId,lotNumber:t.lotNumber,title:t.title,amount:t.amount}}}function Lm(t,e,r,o="USD"){return{to:e,type:"closing_soon",subject:`Closing soon: lot ${t.lot_number}, ${t.title}`,body:`"${t.title}" closes at ${new Date(t.closes_at??"").toLocaleString()}. The current bid is ${eo(r,o)}.`,data:{itemId:t.id,lotNumber:t.lot_number,title:t.title,currentBid:r,closesAt:t.closes_at}}}var oo={};g(oo,{fetchPledges:()=>ro,makePledge:()=>An,pledgeLevels:()=>Mn,pledgeTotal:()=>to});var{randomUUIDv7:jm}=globalThis.Bun;import{db as gt}from"@stacksjs/database";async function An(t){let e=jm();await gt.insertInto("pledges").values({uuid:e,auction_id:t.auctionId,donor_name:t.donorName,donor_email:t.donorEmail.toLowerCase(),amount:t.amount,level:t.level??null,status:t.status??"confirmed"}).execute();let r=await gt.selectFrom("pledges").selectAll().where("uuid","=",e).executeTakeFirst();return await Br(r,await to(t.auctionId)).catch(()=>{return}),r}async function to(t){return(await gt.selectFrom("pledges").select(["amount"]).where("auction_id","=",t).where("status","=","confirmed").execute()??[]).reduce((r,o)=>r+o.amount,0)}async function ro(t){return await gt.selectFrom("pledges").selectAll().where("auction_id","=",t).orderBy("amount","desc").execute()??[]}async function Mn(t){let e=(await ro(t)).filter((o)=>o.status==="confirmed"),r=new Map;for(let o of e){let n=o.level??"other",a=r.get(n)??{amount:0,count:0};a.amount+=o.amount,a.count+=1,r.set(n,a)}return[...r.entries()].map(([o,n])=>({level:o,...n})).sort((o,n)=>n.amount-o.amount)}var ao={};g(ao,{bulkDestroy:()=>Jn,bulkStore:()=>jn,bulkUpdate:()=>qn,destroy:()=>Nn,fetchAll:()=>Un,fetchById:()=>On,store:()=>Ln,update:()=>Vn});import{db as In}from"@stacksjs/database";function l(t){if(typeof t==="number")return Number.isFinite(t)?t:0;if(typeof t==="bigint")return Number(t);if(!t||typeof t!=="object")return 0;let e=t;for(let r of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if(e[r]!==void 0&&e[r]!==null)return l(e[r]);if(Array.isArray(t))return t.reduce((r,o)=>r+l(o),0);return 0}async function Nn(t){try{let e=await In.deleteFrom("carts").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete cart: ${e.message}`);throw e}}async function Jn(t){if(!t.length)return 0;try{let e=await In.deleteFrom("carts").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete carts: ${e.message}`);throw e}}import{db as Bn}from"@stacksjs/database";function zm(t){return t.replace(/_([a-z0-9])/g,(e,r)=>r.toUpperCase())}function d(t){if(t===null||typeof t!=="object")return t;let e={...t};for(let[r,o]of Object.entries(e)){if(!r.includes("_"))continue;let n=zm(r);if(!(n in e))e[n]=o}return e}function w(t){return t.map((e)=>d(e))}async function On(t){let e=await Bn.selectFrom("carts").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Un(){return w(await Bn.selectFrom("carts").selectAll().execute())}var{randomUUIDv7:$n}=globalThis.Bun;import{db as Wn}from"@stacksjs/database";async function Ln(t){try{let e={...t,uuid:$n()},r=await Wn.insertInto("carts").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create cart");return d(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create cart: ${e.message}`);throw e}}async function jn(t){if(!t.length)return 0;let e=0;try{return await Wn.transaction(async(r)=>{for(let o of t){let n={...o,uuid:$n()};await r.insertInto("carts").values(n).execute(),e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create carts in bulk: ${r.message}`);throw r}}import{db as zn}from"@stacksjs/database";import{formatDate as Gn}from"@stacksjs/orm";async function Vn(t,e){try{let r=await zn.updateTable("carts").set({...e,updated_at:Gn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update cart");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update cart: ${r.message}`);throw r}}async function qn(t){if(!t.length)return 0;let e=0;try{return await zn.transaction(async(r)=>{for(let o of t){if(!o.id)continue;let n=await r.updateTable("carts").set({...o,updated_at:Gn(new Date)}).where("id","=",o.id).executeTakeFirst();if(Number(n.numUpdatedRows)>0)e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update carts in bulk: ${r.message}`);throw r}}var io={};g(io,{deleteCoupon:()=>Zn,deleteCoupons:()=>Kn,deleteExpiredCoupons:()=>Hn,fetchActive:()=>ta,fetchAll:()=>Xn,fetchByCode:()=>ea,fetchById:()=>pe,fetchConversionRate:()=>ua,fetchCouponCounts:()=>oa,fetchCouponCountsByType:()=>na,fetchRedemptionStats:()=>aa,fetchRedemptionTrend:()=>ia,fetchStats:()=>ra,fetchTopRedeemedCoupons:()=>sa,getActiveCouponsMoMChange:()=>ca,redeem:()=>ha,store:()=>ma,update:()=>ya});import{db as so}from"@stacksjs/database";import{formatDate as Gm}from"@stacksjs/orm";async function Zn(t){let e=await so.deleteFrom("coupons").where("id","=",t).executeTakeFirst();return l(e)>0}async function Kn(t){if(!t.length)return 0;return await so.deleteFrom("coupons").where("id","in",t).execute()||0}async function Hn(){let t=Gm(new Date),e=await so.deleteFrom("coupons").where("end_date","<",t).executeTakeFirst();return l(e)}import{db as h}from"@stacksjs/database";import{extractDate as Qn,formatDate as Yn}from"@stacksjs/orm";import{camelCase as Vm}from"@stacksjs/strings";function _t(t){let e=Object.fromEntries(Object.entries(t).map(([r,o])=>[Vm(r),o]));if(e.endDate)e.endDate=Qn(new Date(e.endDate));if(e.startDate)e.startDate=Qn(new Date(e.startDate));if(e.isActive!==void 0)e.isActive=Boolean(e.isActive);return e}async function Xn(){let t=await h.selectFrom("coupons").selectAll().execute();return w(t).map(_t)}async function pe(t){let e=await h.selectFrom("coupons").where("id","=",t).selectAll().executeTakeFirst();if(e)return _t(d(e));return}async function ea(t){let e=await h.selectFrom("coupons").where("code","=",t).selectAll().executeTakeFirst();if(e)return _t(d(e));return}async function ta(){let t=Yn(new Date),e=await h.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).selectAll().execute();return w(e).map(_t)}async function ra(){let t=await h.selectFrom("coupons").select(h.fn.count("id").as("count")).executeTakeFirst(),e=Yn(new Date),r=await h.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(h.fn.count("id").as("count")).executeTakeFirst(),o=await h.selectFrom("coupons").select(["discount_type",h.fn.count("id").as("count")]).groupBy("discount_type").execute(),n=await h.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),a=await h.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",e).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(t?.count||0),active:Number(r?.count||0),by_type:o,most_used:n,upcoming:a}}async function oa(){let t=new Date,e=new Date(t);e.setDate(t.getDate()-7);let r=new Date(t);r.setMonth(t.getMonth()-1);let o=new Date(t);o.setFullYear(t.getFullYear()-1);let n=await bt(null,null,t),a=await bt(e,null,t),s=await bt(r,null,t),i=await bt(o,null,t);return{week:a,month:s,year:i,all_time:n}}async function bt(t,e,r){let o=h.selectFrom("coupons");if(t)o=o.where("created_at",">=",t.toISOString());if(e)o=o.where("created_at","<=",e.toISOString());let n=await o.select(h.fn.count("id").as("count")).executeTakeFirst(),a=h.selectFrom("coupons");if(t)a=a.where("created_at",">=",t.toISOString());if(e)a=a.where("created_at","<=",e.toISOString());a=a.where("is_active","=",!0).where("start_date","<=",r).where("end_date",">=",r);let s=await a.select(h.fn.count("id").as("count")).executeTakeFirst(),i=Number(n?.count||0),u=Number(s?.count||0),c=i-u;return{total:i,active:u,inactive:c}}async function na(){let t=new Date,e=await h.selectFrom("coupons").select("discount_type").distinct().execute(),r={};for(let{discount_type:o}of e){let n=await h.selectFrom("coupons").where("discount_type","=",o).select(h.fn.count("id").as("count")).executeTakeFirst(),a=await h.selectFrom("coupons").where("discount_type","=",o).where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(h.fn.count("id").as("count")).executeTakeFirst(),s=Number(n?.count||0),i=Number(a?.count||0);r[o]={total:s,active:i,inactive:s-i}}return r}async function aa(){let t=await h.selectFrom("coupons").select(h.fn.sum("usage_count").as("total")).executeTakeFirst(),e=new Date,r=new Date(e);r.setDate(e.getDate()-7);let o=new Date(e);o.setMonth(e.getMonth()-1);let n=new Date(e);n.setFullYear(e.getFullYear()-1);let a=await h.selectFrom("coupons").where("updated_at",">=",r.toISOString()).select(h.fn.sum("usage_count").as("total")).executeTakeFirst(),s=await h.selectFrom("coupons").where("updated_at",">=",o.toISOString()).select(h.fn.sum("usage_count").as("total")).executeTakeFirst(),i=await h.selectFrom("coupons").where("updated_at",">=",n.toISOString()).select(h.fn.sum("usage_count").as("total")).executeTakeFirst(),u=await h.selectFrom("coupons").select(["discount_type",h.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),c={};return u.forEach((m)=>{c[m.discount_type]=Number(m.total||0)}),{total:Number(t?.total||0),week:Number(a?.total||0),month:Number(s?.total||0),year:Number(i?.total||0),by_type:c}}async function sa(t=5){return await h.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(t).execute()}async function ia(t=30){let e=new Date().toISOString(),r=new Date;r.setDate(r.getDate()-t);let o=await h.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",r.toISOString()).where("updated_at","<=",e).where("usage_count",">",0).orderBy("updated_at","desc").execute(),n={};return o.forEach((a)=>{let s=a.updated_at?new Date(a.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!n[s])n[s]=0;n[s]+=a?.usage_count||0}),Object.entries(n).map(([a,s])=>({date:a,count:s}))}async function ua(){let t=new Date,e=await h.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(h.fn.count("id").as("count")).executeTakeFirst(),r=await h.selectFrom("coupons").where("usage_count",">",0).select(h.fn.count("id").as("count")).executeTakeFirst(),o=Number(e?.count||0),n=Number(r?.count||0);return{rate:o>0?n/o*100:0,total_active:o,total_redeemed:n}}async function ca(){let t=new Date,e=new Date(t.getFullYear(),t.getMonth(),1),r=new Date(t.getFullYear(),t.getMonth()-1,1),o=new Date(t.getFullYear(),t.getMonth(),0),n=await h.selectFrom("coupons").select(h.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",e).executeTakeFirst(),a=await h.selectFrom("coupons").select(h.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",o).where("end_date",">=",r).executeTakeFirst(),s=Number(n?.count||0),i=Number(a?.count||0),u=s-i,c=i!==0?u/i*100:s>0?100:0;return{current_month:s,previous_month:i,difference:u,percentage_change:c}}var{randomUUIDv7:qm}=globalThis.Bun;import{db as da}from"@stacksjs/database";import{HttpError as la}from"@stacksjs/error-handling";import{isUniqueViolation as Zm}from"@stacksjs/orm";async function ma(t){try{let e=qm();await da.insertInto("coupons").values({...t,uuid:e}).executeTakeFirst();let r=await da.selectFrom("coupons").where("uuid","=",e).selectAll().executeTakeFirst();return d(r,!0)}catch(e){if(e instanceof la)throw e;if(Zm(e))throw new la(409,"A coupon with this code already exists");if(e instanceof Error)throw Error(`Failed to create coupon: ${e.message}`);throw e}}import{db as fa,sqlHelpers as Km}from"@stacksjs/database";import{env as Hm}from"@stacksjs/env";import{HttpError as pa}from"@stacksjs/error-handling";import{formatDate as wa,isUniqueViolation as Qm}from"@stacksjs/orm";async function ya(t,e){if(!await pe(t))return;try{return await fa.updateTable("coupons").set({...e,updated_at:wa(new Date)}).where("id","=",t).execute(),await pe(t)}catch(o){if(o instanceof pa)throw o;if(Qm(o))throw new pa(409,"A coupon with this code already exists");if(o instanceof Error)throw Error(`Failed to update coupon: ${o.message}`);throw o}}async function ha(t){let e=Km(Hm.DB_CONNECTION||"sqlite"),r=e.param,o=wa(new Date),a=await fa.unsafe(`UPDATE coupons
|
|
2
|
+
var Lm=Object.defineProperty;var jm=(t)=>t;function zm(t,e){this[t]=jm.bind(null,e)}var g=(t,e)=>{for(var r in e)Lm(t,r,{get:e[r],enumerable:!0,configurable:!0,set:zm.bind(e,r)})};var Gm=(t,e,r)=>()=>{if(t)try{e=t(t=0)}catch(o){r=[o]}if(r)throw r[0];return e};function ve(t,e){if(t===e)return!0;return Ep[t]?.includes(e)??!1}async function fe(t,e){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let o=r.dispatch;if(typeof o!=="function")return;o(t,e)}catch{}}async function Et(t){await fe("order:created",{order:t})}async function we(t,e){await fe("order:paid",{order:t,payment:e})}async function vo(t){await fe("order:shipped",{order:t})}async function Sp(t){await fe("order:out_for_delivery",{order:t})}async function Po(t){await fe("order:delivered",{order:t})}async function qe(t,e){await fe("order:cancelled",{order:t,reason:e})}async function Ve(t,e){await fe("order:refunded",{order:t,refundAmount:e})}async function Pe(t,e){switch(t){case"PROCESSING":return we(e);case"SHIPPED":return vo(e);case"OUT_FOR_DELIVERY":return Sp(e);case"DELIVERED":return Po(e);case"CANCELLED":return qe(e);case"REFUNDED":return Ve(e);case"PENDING":default:}}var Ep;var Fe=Gm(()=>{Ep={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","OUT_FOR_DELIVERY","CANCELLED","REFUNDED"],SHIPPED:["OUT_FOR_DELIVERY","DELIVERED","REFUNDED"],OUT_FOR_DELIVERY:["DELIVERED","SHIPPED","CANCELLED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]}});var no={};g(no,{DEFAULT_INCREMENT_LADDER:()=>q,auctionChannel:()=>yt,auctionTotals:()=>qr,biddersFor:()=>Ir,bids:()=>Lr,bidsByBidder:()=>Mr,bidsForAuction:()=>Ar,bidsForItem:()=>Cr,broadcastBid:()=>Jr,broadcastItemClosed:()=>Or,broadcastPledge:()=>Br,closeAuction:()=>Kr,closeDueItems:()=>Hr,closeItem:()=>We,closingSoon:()=>Yr,closingSoonNotification:()=>Km,currencyFor:()=>Ur,determineWinner:()=>xe,effectiveCloseAt:()=>ae,engine:()=>jr,extendedCloseAt:()=>Be,fetchAuction:()=>L,fetchAuctionForEvent:()=>zr,fetchCatalogue:()=>Gr,fetchItems:()=>Z,fetchPledges:()=>ro,incrementFor:()=>O,leadingBid:()=>Je,lots:()=>Xr,makePledge:()=>Mn,nextMinimumBid:()=>V,openAuction:()=>Zr,outbidNotification:()=>Zm,placeBid:()=>Wr,pledgeLevels:()=>In,pledgeTotal:()=>to,pledges:()=>oo,resolveBid:()=>Oe,rulesFor:()=>Ue,settle:()=>$e,settleAuction:()=>Qr,winnerNotification:()=>Hm});var Lr={};g(Lr,{biddersFor:()=>Ir,bidsByBidder:()=>Mr,bidsForAuction:()=>Ar,bidsForItem:()=>Cr,leadingBid:()=>Je,placeBid:()=>Wr});import{db as Ne}from"@stacksjs/database";async function Je(t){return await Ne.selectFrom("bids").selectAll().where("auction_item_id","=",t).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function Cr(t){return await Ne.selectFrom("bids").selectAll().where("auction_item_id","=",t).orderBy("placed_at","desc").execute()??[]}async function Ar(t){return await Ne.selectFrom("bids").selectAll().where("auction_id","=",t).orderBy("placed_at","asc").execute()??[]}async function Mr(t,e){return await Ne.selectFrom("bids").selectAll().where("auction_id","=",t).where("bidder_email","=",e.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function Ir(t){let e=await Ne.selectFrom("bids").select(["bidder_name","bidder_email"]).where("auction_id","=",t).execute(),r=new Map;for(let o of e??[]){let n=o.bidder_email.toLowerCase();if(!r.has(n))r.set(n,{name:o.bidder_name,email:o.bidder_email})}return[...r.values()]}var{randomUUIDv7:Vm}=globalThis.Bun;import{db as $r}from"@stacksjs/database";function Be(t,e,r,o){if(r.antiSnipeMinutes<=0||r.extendOnBidWindowMinutes<=0)return null;if(t.extension_count>=r.maxExtensions)return null;let n=e.getTime()-o.getTime();if(n<=0)return null;if(n>r.extendOnBidWindowMinutes*60000)return null;let a=new Date(o.getTime()+r.antiSnipeMinutes*60000);return a>e?a:null}function ae(t,e){return new Date(t.closes_at??e)}var q=[{upTo:5000,step:200},{upTo:1e4,step:500},{upTo:25000,step:1000},{upTo:50000,step:2500},{upTo:1e5,step:5000},{upTo:250000,step:1e4},{upTo:null,step:25000}];function O(t,e=q,r){if(r&&r>0)return r;for(let o of e)if(o.upTo===null||t<o.upTo)return o.step;return e[e.length-1]?.step??100}function V(t,e,r=q){if(e===null||e<=0)return t.starting_bid;return e+O(e,r,t.min_increment)}function Oe(t,e,r,o=q){let n=Math.max(r.amount,r.maxAmount??0),a=V(t,e?e.amount:null,o);if(r.maxAmount!=null&&r.maxAmount<r.amount)return{accepted:!1,reason:"max_below_amount",message:"Your maximum bid has to be at least as much as your bid.",nextMinimumBid:a};if(n<a)return{accepted:!1,reason:"below_minimum",message:`The next bid on this lot is ${a/100}.`,nextMinimumBid:a};if(t.buy_now_price&&n>=t.buy_now_price)return{accepted:!0,buyNow:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:t.buy_now_price,maxAmount:t.buy_now_price,isChallenger:!0},challengerAmount:t.buy_now_price,outbid:e?{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount}:void 0,nextMinimumBid:t.buy_now_price};if(!e){let l=Math.max(t.starting_bid,r.amount);return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:l,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:l,nextMinimumBid:l+O(l,o,t.min_increment)}}let s=Math.max(e.amount,e.max_amount??0);if(e.bidder_email.toLowerCase()===r.bidderEmail.toLowerCase()){if(n<=s)return{accepted:!1,reason:"already_leading",message:"You are already the leading bidder at or above that amount.",nextMinimumBid:a};return{accepted:!0,leader:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount,maxAmount:n,isChallenger:!1},challengerAmount:e.amount,nextMinimumBid:e.amount+O(e.amount,o,t.min_increment)}}if(n>s){let l=s+O(s,o,t.min_increment),m=Math.min(n,Math.max(l,a));return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:m,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:m,outbid:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount},nextMinimumBid:m+O(m,o,t.min_increment)}}let u=n+O(n,o,t.min_increment),c=Math.min(s,Math.max(u,n));return{accepted:!0,leader:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:c,maxAmount:e.max_amount??null,isChallenger:!1},challengerAmount:n,outbid:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:n},nextMinimumBid:c+O(c,o,t.min_increment)}}function yt(t){return`auction.${t}`}async function Nr(){try{let t=await import("@stacksjs/realtime");return t.emit??null}catch{return null}}async function Jr(t){let e=await Nr();if(!e||!t.item||!t.leader)return;await e(yt(t.item.auction_id),"bid.placed",{itemId:t.item.id,lotNumber:t.item.lot_number,amount:t.leader.amount,nextMinimumBid:t.nextMinimumBid,leaderName:t.leader.bidderName,status:t.item.status,closesAt:t.item.closes_at,extended:Boolean(t.extendedTo),soldViaBuyNow:Boolean(t.buyNow)})}async function Br(t,e){let r=await Nr();if(!r)return;await r(yt(t.auction_id),"pledge.made",{donorName:t.donor_name,amount:t.amount,level:t.level??null,runningTotal:e})}async function Or(t,e,r){let o=await Nr();if(!o)return;await o(yt(t),"item.closed",{itemId:e,...r})}import{config as qm}from"@stacksjs/config";function Cn(){return qm.commerce??{}}function An(){return Cn().auction??{}}function Ue(t){let e=An();return{increments:e.increments?.length?e.increments:q,antiSnipeMinutes:t?.anti_snipe_minutes??e.antiSnipeMinutes??2,extendOnBidWindowMinutes:t?.extend_on_bid_window_minutes??e.extendOnBidWindowMinutes??2,maxExtensions:t?.max_extensions??e.maxExtensions??20}}function Ur(t){return t?.currency??An().currency??Cn().currency??"USD"}function ht(t){return t.toISOString().slice(0,19).replace("T"," ")}async function Wr(t){let e=t.now??new Date,r=await $r.selectFrom("auction_items").selectAll().where("id","=",t.itemId).executeTakeFirst();if(!r)return{accepted:!1,reason:"item_not_found",message:"That lot is no longer available.",nextMinimumBid:0};let o=await $r.selectFrom("auctions").selectAll().where("id","=",r.auction_id).executeTakeFirst(),n=Ue(o),a=await Je(r.id),s=V(r,a?.amount??null,n.increments);if(!o||o.status!=="open"||new Date(o.opens_at)>e)return{accepted:!1,reason:"auction_not_open",message:"Bidding is not open yet.",nextMinimumBid:s,item:r};let i=ae(r,o.closes_at);if(r.status!=="open"||i<=e)return{accepted:!1,reason:"item_not_open",message:"Bidding on this lot has closed.",nextMinimumBid:s,item:r};let u=Oe(r,a,{bidderEmail:t.bidderEmail,bidderName:t.bidderName,amount:t.amount,maxAmount:t.maxAmount},n.increments);if(!u.accepted)return{...u,item:r};let c=u.buyNow?null:Be(r,i,n,e),l=u.leader&&!u.leader.isChallenger&&a&&a.bidder_email.toLowerCase()===t.bidderEmail.toLowerCase(),m=await $r.transaction(async(h)=>{if(l&&a)return await h.updateTable("bids").set({max_amount:u.leader.maxAmount}).where("id","=",a.id).execute(),{...a,max_amount:u.leader.maxAmount};let b=u.leader?.isChallenger===!0,_=Vm();if(await h.insertInto("bids").values({uuid:_,auction_id:r.auction_id,auction_item_id:r.id,bidder_name:t.bidderName,bidder_email:t.bidderEmail.toLowerCase(),amount:u.challengerAmount??t.amount,max_amount:t.maxAmount??null,status:b?"leading":"outbid",placed_at:ht(e)}).execute(),a){if(b)await h.updateTable("bids").set({status:"outbid"}).where("id","=",a.id).execute();else if(u.leader&&u.leader.amount!==a.amount)await h.updateTable("bids").set({amount:u.leader.amount}).where("id","=",a.id).execute()}if(u.buyNow)await h.updateTable("auction_items").set({status:"sold",closes_at:ht(e)}).where("id","=",r.id).execute();else if(c)await h.updateTable("auction_items").set({closes_at:ht(c),extension_count:r.extension_count+1}).where("id","=",r.id).execute();return await h.selectFrom("bids").selectAll().where("uuid","=",_).executeTakeFirst()}),f={...u,bid:m,item:{...r,status:u.buyNow?"sold":r.status,closes_at:c?ht(c):r.closes_at,extension_count:c?r.extension_count+1:r.extension_count},extendedTo:c??void 0};return await Jr(f).catch(()=>{return}),f}var jr={};g(jr,{DEFAULT_INCREMENT_LADDER:()=>q,determineWinner:()=>xe,effectiveCloseAt:()=>ae,extendedCloseAt:()=>Be,incrementFor:()=>O,nextMinimumBid:()=>V,resolveBid:()=>Oe,settle:()=>$e});function xe(t,e){let r=e.filter((a)=>a.status!=="invalid");if(r.length===0)return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"passed",amount:0,passedReason:"no_bids"};let n=[...r].sort((a,s)=>{if(s.amount!==a.amount)return s.amount-a.amount;return new Date(a.placed_at).getTime()-new Date(s.placed_at).getTime()})[0];if(t.reserve_price&&n.amount<t.reserve_price)return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"passed",amount:n.amount,passedReason:"reserve_not_met"};return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"sold",winningBidId:n.id,winnerName:n.bidder_name,winnerEmail:n.bidder_email,amount:n.amount}}function $e(t,e,r,o){let n=e.filter((m)=>m.status==="sold"),a=e.filter((m)=>m.status==="passed"),s=n.reduce((m,f)=>m+f.amount,0),i=r.filter((m)=>m.status==="confirmed").reduce((m,f)=>m+f.amount,0),u=new Map(t.map((m)=>[m.id,m.fair_market_value??null])),c=n.reduce((m,f)=>{let h=u.get(f.itemId);return h==null?m:m+(f.amount-h)},0),l=e.length;return{auctionId:o.auctionId,currency:o.currency,totalRaised:s+i,bidRevenue:s,pledgeRevenue:i,goalAmount:o.goalAmount??null,itemsSold:n.length,itemsPassed:a.length,sellThrough:l===0?0:n.length/l,valueDelta:c,outcomes:e}}var Xr={};g(Xr,{auctionTotals:()=>qr,closeAuction:()=>Kr,closeDueItems:()=>Hr,closeItem:()=>We,closingSoon:()=>Yr,fetchAuction:()=>L,fetchAuctionForEvent:()=>zr,fetchCatalogue:()=>Gr,fetchItems:()=>Z,openAuction:()=>Zr,settleAuction:()=>Qr});import{db as se}from"@stacksjs/database";async function L(t){return await se.selectFrom("auctions").selectAll().where("id","=",t).executeTakeFirst()??null}async function zr(t){return await se.selectFrom("auctions").selectAll().where("event_id","=",t).executeTakeFirst()??null}async function Z(t){return await se.selectFrom("auction_items").selectAll().where("auction_id","=",t).orderBy("lot_number","asc").execute()??[]}async function Gr(t){let[e,r]=await Promise.all([L(t),Z(t)]),o=Ue(e),n=await se.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",t).where("status","in",["leading","won"]).execute(),a=await se.selectFrom("bids").select(["auction_item_id"]).where("auction_id","=",t).where("status","!=","invalid").execute(),s=new Map((n??[]).map((u)=>[u.auction_item_id,u])),i=new Map;for(let u of a??[])i.set(u.auction_item_id,(i.get(u.auction_item_id)??0)+1);return r.map((u)=>{let c=s.get(u.id)??null;return{...u,currentBid:c?.amount??0,bidCount:i.get(u.id)??0,nextMinimumBid:V(u,c?.amount??null,o.increments),leaderName:c?.bidder_name??null}})}async function qr(t){let e=await L(t),r=await se.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",t).where("status","!=","invalid").execute(),o=await se.selectFrom("pledges").select(["amount"]).where("auction_id","=",t).where("status","=","confirmed").execute(),n=r??[],s=n.filter((c)=>c.status==="leading"||c.status==="won").reduce((c,l)=>c+l.amount,0),i=(o??[]).reduce((c,l)=>c+l.amount,0),u=await se.selectFrom("auction_items").where("auction_id","=",t).count();return{currentBidTotal:s,pledgeTotal:i,raised:s+i,goalAmount:e?.goal_amount??null,bidCount:n.length,bidderCount:new Set(n.map((c)=>c.bidder_email.toLowerCase())).size,lotsOffered:Number(u??0),lotsWithBids:new Set(n.map((c)=>c.auction_item_id)).size}}import{db as ie}from"@stacksjs/database";function Vr(t){return t.toISOString().slice(0,19).replace("T"," ")}async function Zr(t,e=new Date){return await ie.updateTable("auctions").set({status:"open",opens_at:Vr(e)}).where("id","=",t).execute(),await ie.updateTable("auction_items").set({status:"open"}).where("auction_id","=",t).where("status","=","closed").execute(),L(t)}async function We(t,e=new Date){if(t.status==="sold"||t.status==="passed")return null;let r=await ie.selectFrom("bids").selectAll().where("auction_item_id","=",t.id).execute(),o=xe(t,r??[]);return await ie.transaction(async(n)=>{if(await n.updateTable("auction_items").set({status:o.status,closes_at:Vr(e)}).where("id","=",t.id).execute(),o.winningBidId)await n.updateTable("bids").set({status:"won"}).where("id","=",o.winningBidId).execute();await n.updateTable("bids").set({status:"lost"}).where("auction_item_id","=",t.id).where("status","in",["leading","outbid"]).execute()}),await Or(t.auction_id,t.id,{status:o.status,amount:o.amount,winnerName:o.winnerName}).catch(()=>{return}),o}async function Hr(t,e=new Date){let r=await L(t);if(!r)return[];let o=await Z(t),n=[];for(let a of o){if(a.status!=="open")continue;if(ae(a,r.closes_at)>e)continue;let s=await We(a,e);if(s)n.push(s)}return n}async function Kr(t,e=new Date){let r=await Z(t),o=[];for(let n of r){let a=await We(n,e);if(a)o.push(a)}return await ie.updateTable("auctions").set({status:"closed",closes_at:Vr(e)}).where("id","=",t).execute(),o}async function Qr(t,e={}){let r=await L(t);if(!r)return null;let o=await Z(t),n=await ie.selectFrom("bids").selectAll().where("auction_id","=",t).execute(),a=await ie.selectFrom("pledges").selectAll().where("auction_id","=",t).execute(),s=new Map;for(let u of n??[]){let c=s.get(u.auction_item_id)??[];c.push(u),s.set(u.auction_item_id,c)}let i=o.map((u)=>{let c=xe(u,s.get(u.id)??[]);return u.status==="passed"?{...c,status:"passed"}:c});if(e.markSettled)await ie.updateTable("auctions").set({status:"settled"}).where("id","=",t).execute();return $e(o,i,a??[],{auctionId:t,currency:Ur(r),goalAmount:r.goal_amount??null})}async function Yr(t,e,r=new Date){let o=await L(t);if(!o)return[];let n=new Date(r.getTime()+e*60000);return(await Z(t)).filter((a)=>{if(a.status!=="open")return!1;let s=ae(a,o.closes_at);return s>r&&s<=n})}function eo(t,e="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0}).format(t/100)}function Zm(t,e="USD"){if(!t.outbid||!t.item)return null;let r=t.item;return{to:{name:t.outbid.bidderName,email:t.outbid.bidderEmail},type:"outbid",subject:`You have been outbid on lot ${r.lot_number}: ${r.title}`,body:`Someone has bid higher on "${r.title}". The next bid is ${eo(t.nextMinimumBid,e)}. Bidding closes ${new Date(r.closes_at??"").toLocaleString()}.`,data:{itemId:r.id,lotNumber:r.lot_number,title:r.title,nextMinimumBid:t.nextMinimumBid,closesAt:r.closes_at}}}function Hm(t,e="USD"){if(t.status!=="sold"||!t.winnerEmail)return null;return{to:{name:t.winnerName??"Bidder",email:t.winnerEmail},type:"winner",subject:`You won lot ${t.lotNumber}: ${t.title}`,body:`Congratulations - you won "${t.title}" at ${eo(t.amount,e)}. The school will be in touch with payment and pickup details.`,data:{itemId:t.itemId,lotNumber:t.lotNumber,title:t.title,amount:t.amount}}}function Km(t,e,r,o="USD"){return{to:e,type:"closing_soon",subject:`Closing soon: lot ${t.lot_number}, ${t.title}`,body:`"${t.title}" closes at ${new Date(t.closes_at??"").toLocaleString()}. The current bid is ${eo(r,o)}.`,data:{itemId:t.id,lotNumber:t.lot_number,title:t.title,currentBid:r,closesAt:t.closes_at}}}var oo={};g(oo,{fetchPledges:()=>ro,makePledge:()=>Mn,pledgeLevels:()=>In,pledgeTotal:()=>to});var{randomUUIDv7:Qm}=globalThis.Bun;import{db as gt}from"@stacksjs/database";async function Mn(t){let e=Qm();await gt.insertInto("pledges").values({uuid:e,auction_id:t.auctionId,donor_name:t.donorName,donor_email:t.donorEmail.toLowerCase(),amount:t.amount,level:t.level??null,status:t.status??"confirmed"}).execute();let r=await gt.selectFrom("pledges").selectAll().where("uuid","=",e).executeTakeFirst();return await Br(r,await to(t.auctionId)).catch(()=>{return}),r}async function to(t){return(await gt.selectFrom("pledges").select(["amount"]).where("auction_id","=",t).where("status","=","confirmed").execute()??[]).reduce((r,o)=>r+o.amount,0)}async function ro(t){return await gt.selectFrom("pledges").selectAll().where("auction_id","=",t).orderBy("amount","desc").execute()??[]}async function In(t){let e=(await ro(t)).filter((o)=>o.status==="confirmed"),r=new Map;for(let o of e){let n=o.level??"other",a=r.get(n)??{amount:0,count:0};a.amount+=o.amount,a.count+=1,r.set(n,a)}return[...r.entries()].map(([o,n])=>({level:o,...n})).sort((o,n)=>n.amount-o.amount)}var ao={};g(ao,{bulkDestroy:()=>Bn,bulkStore:()=>zn,bulkUpdate:()=>Zn,destroy:()=>Jn,fetchAll:()=>$n,fetchById:()=>Un,store:()=>jn,update:()=>Vn});import{db as Nn}from"@stacksjs/database";import{mutationCount as p}from"@stacksjs/database";async function Jn(t){try{let e=await Nn.deleteFrom("carts").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete cart: ${e.message}`);throw e}}async function Bn(t){if(!t.length)return 0;try{let e=await Nn.deleteFrom("carts").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete carts: ${e.message}`);throw e}}import{db as On}from"@stacksjs/database";function Ym(t){return t.replace(/_([a-z0-9])/g,(e,r)=>r.toUpperCase())}function d(t){if(t===null||typeof t!=="object")return t;let e={...t};for(let[r,o]of Object.entries(e)){if(!r.includes("_"))continue;let n=Ym(r);if(!(n in e))e[n]=o}return e}function w(t){return t.map((e)=>d(e))}async function Un(t){let e=await On.selectFrom("carts").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function $n(){return w(await On.selectFrom("carts").selectAll().execute())}var{randomUUIDv7:Wn}=globalThis.Bun;import{db as Ln}from"@stacksjs/database";async function jn(t){try{let e={...t,uuid:Wn()},r=await Ln.insertInto("carts").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create cart");return d(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create cart: ${e.message}`);throw e}}async function zn(t){if(!t.length)return 0;let e=0;try{return await Ln.transaction(async(r)=>{for(let o of t){let n={...o,uuid:Wn()};await r.insertInto("carts").values(n).execute(),e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create carts in bulk: ${r.message}`);throw r}}import{db as Gn,matchedRows as Xm}from"@stacksjs/database";import{formatDate as qn}from"@stacksjs/orm";async function Vn(t,e){try{let r=await Gn.updateTable("carts").set({...e,updated_at:qn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update cart");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update cart: ${r.message}`);throw r}}async function Zn(t){if(!t.length)return 0;let e=0;try{return await Gn.transaction(async(r)=>{for(let o of t){if(!o.id)continue;if((await Xm(r.updateTable("carts").set({...o,updated_at:qn(new Date)}).where("id","=",o.id))).length>0)e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update carts in bulk: ${r.message}`);throw r}}var io={};g(io,{deleteCoupon:()=>Hn,deleteCoupons:()=>Kn,deleteExpiredCoupons:()=>Qn,fetchActive:()=>ra,fetchAll:()=>ea,fetchByCode:()=>ta,fetchById:()=>pe,fetchConversionRate:()=>ca,fetchCouponCounts:()=>na,fetchCouponCountsByType:()=>aa,fetchRedemptionStats:()=>sa,fetchRedemptionTrend:()=>ua,fetchStats:()=>oa,fetchTopRedeemedCoupons:()=>ia,getActiveCouponsMoMChange:()=>da,redeem:()=>ga,store:()=>pa,update:()=>ha});import{db as so}from"@stacksjs/database";import{formatDate as ep}from"@stacksjs/orm";async function Hn(t){let e=await so.deleteFrom("coupons").where("id","=",t).executeTakeFirst();return p(e)>0}async function Kn(t){if(!t.length)return 0;return await so.deleteFrom("coupons").where("id","in",t).execute()||0}async function Qn(){let t=ep(new Date),e=await so.deleteFrom("coupons").where("end_date","<",t).executeTakeFirst();return p(e)}import{db as y}from"@stacksjs/database";import{extractDate as Yn,formatDate as Xn}from"@stacksjs/orm";import{camelCase as tp}from"@stacksjs/strings";function _t(t){let e=Object.fromEntries(Object.entries(t).map(([r,o])=>[tp(r),o]));if(e.endDate)e.endDate=Yn(new Date(e.endDate));if(e.startDate)e.startDate=Yn(new Date(e.startDate));if(e.isActive!==void 0)e.isActive=Boolean(e.isActive);return e}async function ea(){let t=await y.selectFrom("coupons").selectAll().execute();return w(t).map(_t)}async function pe(t){let e=await y.selectFrom("coupons").where("id","=",t).selectAll().executeTakeFirst();if(e)return _t(d(e));return}async function ta(t){let e=await y.selectFrom("coupons").where("code","=",t).selectAll().executeTakeFirst();if(e)return _t(d(e));return}async function ra(){let t=Xn(new Date),e=await y.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).selectAll().execute();return w(e).map(_t)}async function oa(){let t=await y.selectFrom("coupons").select(y.fn.count("id").as("count")).executeTakeFirst(),e=Xn(new Date),r=await y.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(y.fn.count("id").as("count")).executeTakeFirst(),o=await y.selectFrom("coupons").select(["discount_type",y.fn.count("id").as("count")]).groupBy("discount_type").execute(),n=await y.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),a=await y.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",e).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(t?.count||0),active:Number(r?.count||0),by_type:o,most_used:n,upcoming:a}}async function na(){let t=new Date,e=new Date(t);e.setDate(t.getDate()-7);let r=new Date(t);r.setMonth(t.getMonth()-1);let o=new Date(t);o.setFullYear(t.getFullYear()-1);let n=await bt(null,null,t),a=await bt(e,null,t),s=await bt(r,null,t),i=await bt(o,null,t);return{week:a,month:s,year:i,all_time:n}}async function bt(t,e,r){let o=y.selectFrom("coupons");if(t)o=o.where("created_at",">=",t.toISOString());if(e)o=o.where("created_at","<=",e.toISOString());let n=await o.select(y.fn.count("id").as("count")).executeTakeFirst(),a=y.selectFrom("coupons");if(t)a=a.where("created_at",">=",t.toISOString());if(e)a=a.where("created_at","<=",e.toISOString());a=a.where("is_active","=",!0).where("start_date","<=",r).where("end_date",">=",r);let s=await a.select(y.fn.count("id").as("count")).executeTakeFirst(),i=Number(n?.count||0),u=Number(s?.count||0),c=i-u;return{total:i,active:u,inactive:c}}async function aa(){let t=new Date,e=await y.selectFrom("coupons").select("discount_type").distinct().execute(),r={};for(let{discount_type:o}of e){let n=await y.selectFrom("coupons").where("discount_type","=",o).select(y.fn.count("id").as("count")).executeTakeFirst(),a=await y.selectFrom("coupons").where("discount_type","=",o).where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(y.fn.count("id").as("count")).executeTakeFirst(),s=Number(n?.count||0),i=Number(a?.count||0);r[o]={total:s,active:i,inactive:s-i}}return r}async function sa(){let t=await y.selectFrom("coupons").select(y.fn.sum("usage_count").as("total")).executeTakeFirst(),e=new Date,r=new Date(e);r.setDate(e.getDate()-7);let o=new Date(e);o.setMonth(e.getMonth()-1);let n=new Date(e);n.setFullYear(e.getFullYear()-1);let a=await y.selectFrom("coupons").where("updated_at",">=",r.toISOString()).select(y.fn.sum("usage_count").as("total")).executeTakeFirst(),s=await y.selectFrom("coupons").where("updated_at",">=",o.toISOString()).select(y.fn.sum("usage_count").as("total")).executeTakeFirst(),i=await y.selectFrom("coupons").where("updated_at",">=",n.toISOString()).select(y.fn.sum("usage_count").as("total")).executeTakeFirst(),u=await y.selectFrom("coupons").select(["discount_type",y.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),c={};return u.forEach((l)=>{c[l.discount_type]=Number(l.total||0)}),{total:Number(t?.total||0),week:Number(a?.total||0),month:Number(s?.total||0),year:Number(i?.total||0),by_type:c}}async function ia(t=5){return await y.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(t).execute()}async function ua(t=30){let e=new Date().toISOString(),r=new Date;r.setDate(r.getDate()-t);let o=await y.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",r.toISOString()).where("updated_at","<=",e).where("usage_count",">",0).orderBy("updated_at","desc").execute(),n={};return o.forEach((a)=>{let s=a.updated_at?new Date(a.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!n[s])n[s]=0;n[s]+=a?.usage_count||0}),Object.entries(n).map(([a,s])=>({date:a,count:s}))}async function ca(){let t=new Date,e=await y.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(y.fn.count("id").as("count")).executeTakeFirst(),r=await y.selectFrom("coupons").where("usage_count",">",0).select(y.fn.count("id").as("count")).executeTakeFirst(),o=Number(e?.count||0),n=Number(r?.count||0);return{rate:o>0?n/o*100:0,total_active:o,total_redeemed:n}}async function da(){let t=new Date,e=new Date(t.getFullYear(),t.getMonth(),1),r=new Date(t.getFullYear(),t.getMonth()-1,1),o=new Date(t.getFullYear(),t.getMonth(),0),n=await y.selectFrom("coupons").select(y.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",e).executeTakeFirst(),a=await y.selectFrom("coupons").select(y.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",o).where("end_date",">=",r).executeTakeFirst(),s=Number(n?.count||0),i=Number(a?.count||0),u=s-i,c=i!==0?u/i*100:s>0?100:0;return{current_month:s,previous_month:i,difference:u,percentage_change:c}}var{randomUUIDv7:rp}=globalThis.Bun;import{db as la}from"@stacksjs/database";import{HttpError as ma}from"@stacksjs/error-handling";import{isUniqueViolation as op}from"@stacksjs/orm";async function pa(t){try{let e=rp();await la.insertInto("coupons").values({...t,uuid:e}).executeTakeFirst();let r=await la.selectFrom("coupons").where("uuid","=",e).selectAll().executeTakeFirst();return d(r,!0)}catch(e){if(e instanceof ma)throw e;if(op(e))throw new ma(409,"A coupon with this code already exists");if(e instanceof Error)throw Error(`Failed to create coupon: ${e.message}`);throw e}}import{db as wa,mutationCount as np,sqlHelpers as ap}from"@stacksjs/database";import{env as sp}from"@stacksjs/env";import{HttpError as fa}from"@stacksjs/error-handling";import{formatDate as ya,isUniqueViolation as ip}from"@stacksjs/orm";async function ha(t,e){if(!await pe(t))return;try{return await wa.updateTable("coupons").set({...e,updated_at:ya(new Date)}).where("id","=",t).execute(),await pe(t)}catch(o){if(o instanceof fa)throw o;if(ip(o))throw new fa(409,"A coupon with this code already exists");if(o instanceof Error)throw Error(`Failed to update coupon: ${o.message}`);throw o}}async function ga(t){let e=ap(sp.DB_CONNECTION||"sqlite"),r=e.param,o=ya(new Date),n=await wa.unsafe(`UPDATE coupons
|
|
3
3
|
SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ${r(1)}
|
|
4
4
|
WHERE id = ${r(2)}
|
|
5
|
-
AND (
|
|
5
|
+
AND (usage_limit IS NULL OR COALESCE(usage_count, 0) < usage_limit)
|
|
6
6
|
AND is_active = ${e.boolTrue}
|
|
7
7
|
AND (start_date IS NULL OR start_date <= ${r(3)})
|
|
8
|
-
AND (end_date IS NULL OR end_date >= ${r(4)})`,[o,t,o,o]);if(Number(a?.changes??a?.numUpdatedRows??a?.affectedRows??0)>0){let m=await pe(t);if(m)return{ok:!0,coupon:m};return{ok:!1,reason:"not-found"}}let i=await pe(t);if(!i)return{ok:!1,reason:"not-found"};if(!i.isActive)return{ok:!1,reason:"inactive"};let u=!i.startDate||i.startDate<=o,c=!i.endDate||i.endDate>=o;if(!u||!c)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var co={};g(co,{bulkDestroy:()=>_a,destroy:()=>ba,fetchAll:()=>xa,fetchById:()=>Rt,store:()=>va,update:()=>Fa});import{db as ga}from"@stacksjs/database";async function ba(t){try{let e=await ga.deleteFrom("customers").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete customer: ${e.message}`);throw e}}async function _a(t){if(!t.length)return 0;try{let e=await ga.deleteFrom("customers").where("id","in",t).executeTakeFirst();return l(e)||0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${e.message}`);throw e}}import{db as Ra}from"@stacksjs/database";async function Rt(t){let e=await Ra.selectFrom("customers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function xa(){return w(await Ra.selectFrom("customers").selectAll().execute())}import{db as Ym}from"@stacksjs/database";import{HttpError as Da}from"@stacksjs/error-handling";import{isUniqueViolation as Xm}from"@stacksjs/orm";function K(t){if(typeof t==="bigint")return uo(t);if(typeof t==="number")return uo(t);if(!t||typeof t!=="object")return;if(Array.isArray(t)){for(let r of t){let o=K(r);if(o!==void 0)return o}return}let e=t;for(let r of["lastInsertRowid","insertId","lastInsertId"]){let o=e[r];if(o===void 0||o===null)continue;let n=uo(o);if(n!==void 0)return n}return}function uo(t){let e=typeof t==="bigint"?Number(t):Number(t);if(!Number.isSafeInteger(e)||e<=0)return;return e}async function va(t){try{let e={...t,avatar:t.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},r=await Ym.insertInto("customers").values(e).executeTakeFirst();if(!r)throw Error("Failed to create customer");let o=K(r);if(o===void 0)throw Error("Failed to create customer: the database reported no insert id");return await Rt(o)}catch(e){if(e instanceof Da)throw e;if(Xm(e))throw new Da(409,"A customer with this email already exists");if(e instanceof Error)throw Error(`Failed to create customer: ${e.message}`);throw e}}import{db as ep}from"@stacksjs/database";import{HttpError as Pa}from"@stacksjs/error-handling";import{formatDate as tp,isUniqueViolation as rp}from"@stacksjs/orm";async function Fa(t,e){try{if(!t)throw Error("Customer ID is required for update");let r=await ep.updateTable("customers").set({...e,updated_at:tp(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Pa)throw r;if(rp(r))throw new Pa(409,"A customer with this email already exists");if(r instanceof Error)throw Error(`Failed to update customer: ${r.message}`);throw r}}var wo={};g(wo,{bulkDestroy:()=>Ea,bulkStore:()=>La,calculateErrorRate:()=>Ma,calculatePrinterHealth:()=>Na,countAll:()=>Sa,countPrintsByDeviceId:()=>Aa,countTotalPrints:()=>Ca,destroy:()=>Ta,downloadPrintDevices:()=>Oa,exportPrintDevices:()=>Dt,fetchAll:()=>xt,fetchById:()=>H,fetchErrorsByDeviceId:()=>Ia,getPrinterStatusCounts:()=>Ja,store:()=>Wa,storePrintDevicesExport:()=>Ua,update:()=>ja,updatePrintCount:()=>Ga,updateStatus:()=>za});import{db as ka}from"@stacksjs/database";async function Ta(t){try{let e=await ka.deleteFrom("print_devices").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print device: ${e.message}`);throw e}}async function Ea(t){if(!t.length)return 0;try{let e=await ka.deleteFrom("print_devices").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print devices: ${e.message}`);throw e}}import{createSpreadsheet as op}from"ts-spreadsheets";import{db as C}from"@stacksjs/database";async function H(t){let e=await C.selectFrom("print_devices").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function xt(){return w(await C.selectFrom("print_devices").selectAll().execute())}async function Sa(){let t=await C.selectFrom("print_devices").select(C.fn.count("id").as("count")).executeTakeFirst();return Number(t?.count||0)}async function Ca(){let t=await C.selectFrom("print_devices").select(C.fn.sum("print_count").as("total")).executeTakeFirst();return Number(t?.total||0)}async function Aa(t){let e=await C.selectFrom("print_devices").select("print_count").where("id","=",t).executeTakeFirst();return Number(e?.print_count??0)}async function Ma(){let t=await C.selectFrom("receipts").select([C.fn.count("id").as("total"),C.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!t?.total||t.total===0)return 0;return Number(Number(t?.failed_count??0)/Number(t?.total??0)*100)}async function Ia(t){let e=await C.selectFrom("receipts").where("print_device_id","=",t).where("status","=","failed").selectAll().execute();return w(e)}async function Na(){let t=await C.selectFrom("print_devices").select([C.fn.count("id").as("total"),C.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!t?.total||t.total===0)return 0;return Number(Number(t?.online_count??0)/Number(t?.total??0)*100)}async function Ja(){return(await C.selectFrom("print_devices").select(["status",C.fn.count("id").as("count")]).groupBy("status").execute()).reduce((e,r)=>(e[r.status]=Number(r.count||0),e),{})}function lo(t,e,r=e){let o=t;return o[String(e)]??o[r]}function np(t){if(t instanceof Date)return t;if(typeof t==="number")return new Date(t);if(typeof t==="string")return new Date(/^\d+$/.test(t)?Number(t):t);return new Date(Number.NaN)}function Ba(t,e,r=e){let o=lo(t,e,r);if(typeof o==="number")return o;let n=Number(o);return Number.isFinite(n)?n:0}function Le(t,e,r=e){let o=lo(t,e,r);return o==null?"":String(o)}async function Dt(t="csv"){let e=await xt(),r=ap(e);return op(r,{type:t})}function ap(t){let e=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],r=t.map((o)=>[Ba(o,"id"),Le(o,"name"),Le(o,"macAddress","mac_address"),Le(o,"location"),Le(o,"terminal"),Le(o,"status"),np(lo(o,"lastPing","last_ping")).toLocaleString(),Ba(o,"printCount","print_count")]);return{headings:e,data:r}}async function Oa(t="csv",e){let r=await Dt(t),o=`print_devices_export_${new Date().toISOString().split("T")[0]}.${t}`;return r.download(e||o)}async function Ua(t="csv",e){let r=await Dt(t),o=`print_devices_export_${new Date().toISOString().split("T")[0]}.${t}`;r.store(e||o)}var{randomUUIDv7:$a}=globalThis.Bun;import{db as mo}from"@stacksjs/database";async function Wa(t){try{let e=$a(),r={last_ping:0,print_count:0,...t,uuid:e};await mo.insertInto("print_devices").values(r).executeTakeFirst();let o=await mo.selectFrom("print_devices").where("uuid","=",e).selectAll().executeTakeFirst();return d(o,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create print device: ${e.message}`);throw e}}async function La(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={last_ping:0,print_count:0,...r,uuid:$a()};await mo.insertInto("print_devices").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${r.message}`);throw r}}import{db as po}from"@stacksjs/database";import{formatDate as fo}from"@stacksjs/orm";async function ja(t,e){if(!await H(t))return;try{return await po.updateTable("print_devices").set({...e,updated_at:fo(new Date)}).where("id","=",t).execute(),await H(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print device: ${o.message}`);throw o}}async function za(t,e){if(!await H(t))throw Error(`Print device with ID ${t} not found`);try{return await po.updateTable("print_devices").set({status:e,updated_at:fo(new Date)}).where("id","=",t).execute(),await H(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print device status: ${o.message}`);throw o}}async function Ga(t,e){if(!await H(t))throw Error(`Print device with ID ${t} not found`);try{return await po.updateTable("print_devices").set({print_count:e,updated_at:fo(new Date)}).where("id","=",t).execute(),await H(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print count: ${o.message}`);throw o}}var go={};g(go,{bulkDestroy:()=>qa,bulkUpdateStatus:()=>ts,destroy:()=>Va,destroyGroup:()=>Za,fetchAll:()=>Pt,fetchByGroup:()=>Qa,fetchById:()=>Ka,fetchGrouped:()=>Ha,fetchStats:()=>Ya,fetchTimeline:()=>Xa,ignoreGroup:()=>os,resolveGroup:()=>rs,unresolveGroup:()=>ns,update:()=>es});import{db as yo}from"@stacksjs/database";import{log as ho}from"@stacksjs/logging";async function Va(t){try{return await yo.deleteFrom("errors").where("id","=",t).execute(),!0}catch(e){return ho.error("[commerce/errors] destroy failed",{id:t,error:e}),!1}}async function qa(t){try{return await yo.deleteFrom("errors").where("id","in",t).execute(),!0}catch(e){return ho.error("[commerce/errors] bulkDestroy failed",{count:t.length,error:e}),!1}}async function Za(t,e){try{return await yo.deleteFrom("errors").where("type","=",t).where("message","=",e).execute(),!0}catch(r){return ho.error("[commerce/errors] destroyGroup failed",{type:t,message:e,error:r}),!1}}import{db as vt}from"@stacksjs/database";async function Ka(t){return await vt.selectFrom("errors").where("id","=",t).selectAll().executeTakeFirst()}async function Pt(){return await vt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function Ha(){let t=await vt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),e=new Map;for(let o of t){let n=`${o.type}:${o.message}`;if(!e.has(n))e.set(n,{errors:[],firstSeen:new Date(o.created_at),lastSeen:new Date(o.created_at)});let a=e.get(n);a.errors.push(o);let s=new Date(o.created_at);if(s<a.firstSeen)a.firstSeen=s;if(s>a.lastSeen)a.lastSeen=s}let r=[];for(let[o,n]of e){let a=n.errors[0];if(!a)continue;let s=n.errors.find((u)=>u.status!==null)?.status,i="unresolved";if(s===1)i="resolved";else if(s===2)i="ignored";r.push({id:a.id,type:a.type,message:a.message,stack:a.stack,status:i,count:n.errors.length,first_seen:n.firstSeen.toISOString(),last_seen:n.lastSeen.toISOString(),error_ids:n.errors.map((u)=>u.id)})}return r.sort((o,n)=>new Date(n.last_seen).getTime()-new Date(o.last_seen).getTime()),r}async function Qa(t,e){return await vt.selectFrom("errors").where("type","=",t).where("message","=",e).selectAll().orderBy("created_at","desc").execute()}async function Ya(){let t=await Pt(),e=new Date,r=new Date(e.getTime()-86400000),o=new Date(e.getTime()-172800000),n=t.filter((i)=>new Date(i.created_at)>=r).length,a=t.filter((i)=>{let u=new Date(i.created_at);return u>=o&&u<r}).length,s=a===0?n>0?100:0:Math.round((n-a)/a*100);return{total:t.length,unresolved:t.filter((i)=>i.status===null||i.status===0).length,resolved:t.filter((i)=>i.status===1).length,ignored:t.filter((i)=>i.status===2).length,last_24h:n,trend:s}}async function Xa(){let t=await Pt(),e=new Date,r=[];for(let o=23;o>=0;o--){let n=new Date(e.getTime()-o*60*60*1000);n.setMinutes(0,0,0);let a=new Date(n.getTime()+3600000),s=t.filter((i)=>{let u=new Date(i.created_at);return u>=n&&u<a}).length;r.push({hour:n.toISOString(),count:s})}return r}import{db as je}from"@stacksjs/database";import{sql as ze}from"@stacksjs/database";import{log as Ge}from"@stacksjs/logging";async function es(t,e){try{return await je.updateTable("errors").set({...e,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("id","=",t).execute(),!0}catch(r){return Ge.error("[commerce/errors] update failed",{id:t,error:r}),!1}}async function ts(t,e){try{return await je.updateTable("errors").set({status:e,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("id","in",t).execute(),!0}catch(r){return Ge.error("[commerce/errors] bulkUpdateStatus failed",{count:t.length,status:e,error:r}),!1}}async function rs(t,e){try{return await je.updateTable("errors").set({status:1,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ge.error("[commerce/errors] resolveGroup failed",{type:t,message:e,error:r}),!1}}async function os(t,e){try{return await je.updateTable("errors").set({status:2,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ge.error("[commerce/errors] ignoreGroup failed",{type:t,message:e,error:r}),!1}}async function ns(t,e){try{return await je.updateTable("errors").set({status:0,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ge.error("[commerce/errors] unresolveGroup failed",{type:t,message:e,error:r}),!1}}var Ro={};g(Ro,{bulkDestroy:()=>ws,calculateGiftCardValues:()=>ds,checkBalance:()=>us,compareActiveGiftCards:()=>cs,deactivate:()=>hs,destroy:()=>fs,destroyExpired:()=>ys,fetchActive:()=>ss,fetchAll:()=>as,fetchByCode:()=>bo,fetchById:()=>Q,fetchStats:()=>is,fetchTotalCurrentBalance:()=>ms,fetchTotalValue:()=>ls,store:()=>bs,update:()=>Ds,updateBalance:()=>vs});import{db as Ft}from"@stacksjs/database";import{formatDate as ps}from"@stacksjs/orm";import{db as v,sql as I}from"@stacksjs/database";import{formatDate as ue,toTimestamp as De}from"@stacksjs/orm";import{aggregateFunctions as sp,db as ip}from"@stacksjs/database";async function J(t,e,r){let o=ip.selectFrom(t);if(r)o=r(o);o=o.select(Object.entries(e).map(([s,i])=>{let u=i.column??"id",c=sp[i.kind](u);if(i.filter)c=c.filterWhere(i.filter.column,i.filter.op,i.filter.value);return c.as(s)}));let n=await o.executeTakeFirst(),a={};for(let s of Object.keys(e)){let i=n?.[s];a[s]=typeof i==="number"?i:Number(i??0)||0}return a}async function as(){let t=await v.selectFrom("gift_cards").selectAll().execute();return w(t)}async function Q(t){let e=await v.selectFrom("gift_cards").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function bo(t){let e=await v.selectFrom("gift_cards").where("code","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ss(){let t=await v.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute();return w(t)}async function is(){let{count:t}=await J("gift_cards",{count:{kind:"count"}}),e=De(new Date),r=await v.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(e)} OR expiry_date IS NULL)`).select(v.fn.count("id").as("count")).executeTakeFirst(),o=await v.selectFrom("gift_cards").select(["status",v.fn.count("id").as("count")]).groupBy("status").execute(),{count:n}=await J("gift_cards",{count:{kind:"count"}},(m)=>m.whereRaw(I`current_balance / initial_balance < 0.25`)),{count:a}=await J("gift_cards",{count:{kind:"count"}},(m)=>m.whereRaw(I`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:s}=await J("gift_cards",{count:{kind:"count"}},(m)=>m.whereRaw(I`current_balance / initial_balance > 0.75`)),i=new Date;i.setDate(i.getDate()+30);let u=await v.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",De(i)).where("expiry_date",">=",e).selectAll().limit(5).execute(),c=await v.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:t,active:Number(r?.count||0),by_status:o.map((m)=>({status:m.status,count:Number(m.count)})),by_balance:{low:n,medium:a,high:s},expiring_soon:w(u),recently_used:w(c)}}async function us(t){let e=await bo(t);if(!e)return{valid:!1,message:"Gift card not found"};if(!e.isActive||e.status!=="ACTIVE")return{valid:!1,balance:e.currentBalance,currency:e.currency,message:`Gift card is ${e.status.toLowerCase()}`};if(e.expiryDate){if(new Date(e.expiryDate)<new Date)return{valid:!1,balance:e.currentBalance,currency:e.currency,message:"Gift card has expired"}}return{valid:!0,balance:e.currentBalance,currency:e.currency}}async function cs(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await v.selectFrom("gift_cards").select(v.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(e))} OR expiry_date IS NULL)`).where("created_at",">=",ue(r)).where("created_at","<=",ue(e)).executeTakeFirst(),s=await v.selectFrom("gift_cards").select(v.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(n))} OR expiry_date IS NULL)`).where("created_at",">=",ue(n)).where("created_at","<=",ue(o)).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,m=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:m,days_range:t}}async function ds(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await v.selectFrom("gift_cards").select([v.fn.sum("initial_balance").as("total_initial"),v.fn.sum("current_balance").as("total_balance"),v.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(e))} OR expiry_date IS NULL)`).where("created_at",">=",ue(r)).where("created_at","<=",ue(e)).executeTakeFirst(),s=await v.selectFrom("gift_cards").select([v.fn.sum("initial_balance").as("total_initial"),v.fn.sum("current_balance").as("total_balance"),v.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(n))} OR expiry_date IS NULL)`).where("created_at",">=",ue(n)).where("created_at","<=",ue(o)).executeTakeFirst(),i=Number(a?.total_initial||0),u=Number(a?.total_balance||0),c=Number(a?.card_count||0),m=Number(s?.total_initial||0),p=Number(s?.total_balance||0),f=Number(s?.card_count||0),y=i>0?(i-u)/i*100:0,b=m>0?(m-p)/m*100:0,_=c>0?i/c:0,D=c>0?u/c:0,z=i-m,le=u-p,me=c-f,Re=m!==0?z/m*100:i>0?100:0,G=p!==0?le/p*100:u>0?100:0,Mm=f!==0?me/f*100:c>0?100:0;return{current_period:{total_initial_value:i,total_remaining_balance:u,utilization_rate:y,card_count:c,average_initial_value:_,average_remaining_balance:D},previous_period:{total_initial_value:m,total_remaining_balance:p,utilization_rate:b,card_count:f},comparison:{initial_value:{difference:z,percentage:Math.abs(Re),is_increase:z>=0},balance:{difference:le,percentage:Math.abs(G),is_increase:le>=0},card_count:{difference:me,percentage:Math.abs(Mm),is_increase:me>=0}},days_range:t}}async function ls(){let{total_value:t}=await J("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:t}}async function ms(){let{total_balance:t}=await J("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:t}}async function fs(t){let e=await Ft.deleteFrom("gift_cards").where("id","=",t).executeTakeFirst();return l(e)>0}async function ws(t){if(!t.length)return 0;let e=await Ft.deleteFrom("gift_cards").where("id","in",t).executeTakeFirst();return l(e)}async function ys(){let t=ps(new Date),e=await Ft.deleteFrom("gift_cards").where("expiry_date","<",t).executeTakeFirst();return l(e)}async function hs(t){if(!await Q(t))throw Error(`Gift card with ID ${t} not found`);let r=await Ft.updateTable("gift_cards").set({is_active:!1,status:"DEACTIVATED",updated_at:ps(new Date)}).where("id","=",t).executeTakeFirst();return l(r)>0}var{randomUUIDv7:up}=globalThis.Bun;import{db as _o}from"@stacksjs/database";import{HttpError as gs}from"@stacksjs/error-handling";import{isUniqueViolation as cp}from"@stacksjs/orm";async function bs(t){let e=t,r={...t,current_balance:e.current_balance??e.initial_balance,status:t.status||"ACTIVE",is_active:e.is_active??!0,uuid:up()};try{let o=await _o.insertInto("gift_cards").values(r).executeTakeFirst(),n=K(o);if(n!==void 0){let s=await _o.selectFrom("gift_cards").where("id","=",n).selectAll().executeTakeFirst();return d(s)}let a=await _o.selectFrom("gift_cards").where("uuid","=",r.uuid).selectAll().executeTakeFirst();return d(a,!0)}catch(o){if(o instanceof gs)throw o;if(cp(o))throw new gs(409,"A gift card with this code already exists");if(o instanceof Error)throw Error(`Failed to create gift card: ${o.message}`);throw o}}import{db as Rs,sqlHelpers as dp}from"@stacksjs/database";import{env as lp}from"@stacksjs/env";import{HttpError as _s}from"@stacksjs/error-handling";import{formatDate as xs,isUniqueViolation as mp}from"@stacksjs/orm";async function Ds(t,e){if(!await Q(t))return;try{return await Rs.updateTable("gift_cards").set({...e,updated_at:xs(new Date)}).where("id","=",t).execute(),await Q(t)}catch(o){if(o instanceof _s)throw o;if(mp(o))throw new _s(409,"A gift card with this code already exists");if(o instanceof Error)throw Error(`Failed to update gift card: ${o.message}`);throw o}}async function vs(t,e){if(!Number.isFinite(e))throw Error(`Gift card balance adjustment must be a finite number, got ${e}`);let r=dp(lp.DB_CONNECTION||"sqlite"),o=r.param,n=xs(new Date),a=e<0,s=e>0,i=s?`(status = 'ACTIVE' OR (status = 'USED' AND is_reloadable = ${r.boolTrue}))`:"status = 'ACTIVE'",u=[],c=(D)=>(u.push(D),o(u.length)),p=await Rs.unsafe(`UPDATE gift_cards
|
|
9
|
-
SET
|
|
8
|
+
AND (end_date IS NULL OR end_date >= ${r(4)})`,[o,t,o,o]);if(np(n)>0){let u=await pe(t);if(u)return{ok:!0,coupon:u};return{ok:!1,reason:"not-found"}}let a=await pe(t);if(!a)return{ok:!1,reason:"not-found"};if(!a.isActive)return{ok:!1,reason:"inactive"};let s=!a.startDate||a.startDate<=o,i=!a.endDate||a.endDate>=o;if(!s||!i)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var co={};g(co,{bulkDestroy:()=>Ra,destroy:()=>_a,fetchAll:()=>Da,fetchById:()=>Rt,store:()=>Pa,update:()=>ka});import{db as ba}from"@stacksjs/database";async function _a(t){try{let e=await ba.deleteFrom("customers").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete customer: ${e.message}`);throw e}}async function Ra(t){if(!t.length)return 0;try{let e=await ba.deleteFrom("customers").where("id","in",t).executeTakeFirst();return p(e)||0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${e.message}`);throw e}}import{db as xa}from"@stacksjs/database";async function Rt(t){let e=await xa.selectFrom("customers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Da(){return w(await xa.selectFrom("customers").selectAll().execute())}import{db as up}from"@stacksjs/database";import{HttpError as va}from"@stacksjs/error-handling";import{isUniqueViolation as cp}from"@stacksjs/orm";function H(t){if(typeof t==="bigint")return uo(t);if(typeof t==="number")return uo(t);if(!t||typeof t!=="object")return;if(Array.isArray(t)){for(let r of t){let o=H(r);if(o!==void 0)return o}return}let e=t;for(let r of["lastInsertRowid","insertId","lastInsertId"]){let o=e[r];if(o===void 0||o===null)continue;let n=uo(o);if(n!==void 0)return n}return}function uo(t){let e=typeof t==="bigint"?Number(t):Number(t);if(!Number.isSafeInteger(e)||e<=0)return;return e}async function Pa(t){try{let e={...t,avatar:t.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},r=await up.insertInto("customers").values(e).executeTakeFirst();if(!r)throw Error("Failed to create customer");let o=H(r);if(o===void 0)throw Error("Failed to create customer: the database reported no insert id");return await Rt(o)}catch(e){if(e instanceof va)throw e;if(cp(e))throw new va(409,"A customer with this email already exists");if(e instanceof Error)throw Error(`Failed to create customer: ${e.message}`);throw e}}import{db as dp}from"@stacksjs/database";import{HttpError as Fa}from"@stacksjs/error-handling";import{formatDate as lp,isUniqueViolation as mp}from"@stacksjs/orm";async function ka(t,e){try{if(!t)throw Error("Customer ID is required for update");let r=await dp.updateTable("customers").set({...e,updated_at:lp(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Fa)throw r;if(mp(r))throw new Fa(409,"A customer with this email already exists");if(r instanceof Error)throw Error(`Failed to update customer: ${r.message}`);throw r}}var wo={};g(wo,{bulkDestroy:()=>Sa,bulkStore:()=>ja,calculateErrorRate:()=>Ia,calculatePrinterHealth:()=>Ja,countAll:()=>Ca,countPrintsByDeviceId:()=>Ma,countTotalPrints:()=>Aa,destroy:()=>Ea,downloadPrintDevices:()=>Ua,exportPrintDevices:()=>Dt,fetchAll:()=>xt,fetchById:()=>K,fetchErrorsByDeviceId:()=>Na,getPrinterStatusCounts:()=>Ba,store:()=>La,storePrintDevicesExport:()=>$a,update:()=>za,updatePrintCount:()=>qa,updateStatus:()=>Ga});import{db as Ta}from"@stacksjs/database";async function Ea(t){try{let e=await Ta.deleteFrom("print_devices").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print device: ${e.message}`);throw e}}async function Sa(t){if(!t.length)return 0;try{let e=await Ta.deleteFrom("print_devices").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print devices: ${e.message}`);throw e}}import{createSpreadsheet as pp}from"ts-spreadsheets";import{db as C}from"@stacksjs/database";async function K(t){let e=await C.selectFrom("print_devices").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function xt(){return w(await C.selectFrom("print_devices").selectAll().execute())}async function Ca(){let t=await C.selectFrom("print_devices").select(C.fn.count("id").as("count")).executeTakeFirst();return Number(t?.count||0)}async function Aa(){let t=await C.selectFrom("print_devices").select(C.fn.sum("print_count").as("total")).executeTakeFirst();return Number(t?.total||0)}async function Ma(t){let e=await C.selectFrom("print_devices").select("print_count").where("id","=",t).executeTakeFirst();return Number(e?.print_count??0)}async function Ia(){let t=await C.selectFrom("receipts").select([C.fn.count("id").as("total"),C.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!t?.total||t.total===0)return 0;return Number(Number(t?.failed_count??0)/Number(t?.total??0)*100)}async function Na(t){let e=await C.selectFrom("receipts").where("print_device_id","=",t).where("status","=","failed").selectAll().execute();return w(e)}async function Ja(){let t=await C.selectFrom("print_devices").select([C.fn.count("id").as("total"),C.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!t?.total||t.total===0)return 0;return Number(Number(t?.online_count??0)/Number(t?.total??0)*100)}async function Ba(){return(await C.selectFrom("print_devices").select(["status",C.fn.count("id").as("count")]).groupBy("status").execute()).reduce((e,r)=>(e[r.status]=Number(r.count||0),e),{})}function lo(t,e,r=e){let o=t;return o[String(e)]??o[r]}function fp(t){if(t instanceof Date)return t;if(typeof t==="number")return new Date(t);if(typeof t==="string")return new Date(/^\d+$/.test(t)?Number(t):t);return new Date(Number.NaN)}function Oa(t,e,r=e){let o=lo(t,e,r);if(typeof o==="number")return o;let n=Number(o);return Number.isFinite(n)?n:0}function Le(t,e,r=e){let o=lo(t,e,r);return o==null?"":String(o)}async function Dt(t="csv"){let e=await xt(),r=wp(e);return pp(r,{type:t})}function wp(t){let e=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],r=t.map((o)=>[Oa(o,"id"),Le(o,"name"),Le(o,"macAddress","mac_address"),Le(o,"location"),Le(o,"terminal"),Le(o,"status"),fp(lo(o,"lastPing","last_ping")).toLocaleString(),Oa(o,"printCount","print_count")]);return{headings:e,data:r}}async function Ua(t="csv",e){let r=await Dt(t),o=`print_devices_export_${new Date().toISOString().split("T")[0]}.${t}`;return r.download(e||o)}async function $a(t="csv",e){let r=await Dt(t),o=`print_devices_export_${new Date().toISOString().split("T")[0]}.${t}`;r.store(e||o)}var{randomUUIDv7:Wa}=globalThis.Bun;import{db as mo}from"@stacksjs/database";async function La(t){try{let e=Wa(),r={last_ping:0,print_count:0,...t,uuid:e};await mo.insertInto("print_devices").values(r).executeTakeFirst();let o=await mo.selectFrom("print_devices").where("uuid","=",e).selectAll().executeTakeFirst();return d(o,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create print device: ${e.message}`);throw e}}async function ja(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={last_ping:0,print_count:0,...r,uuid:Wa()};await mo.insertInto("print_devices").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${r.message}`);throw r}}import{db as po}from"@stacksjs/database";import{formatDate as fo}from"@stacksjs/orm";async function za(t,e){if(!await K(t))return;try{return await po.updateTable("print_devices").set({...e,updated_at:fo(new Date)}).where("id","=",t).execute(),await K(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print device: ${o.message}`);throw o}}async function Ga(t,e){if(!await K(t))throw Error(`Print device with ID ${t} not found`);try{return await po.updateTable("print_devices").set({status:e,updated_at:fo(new Date)}).where("id","=",t).execute(),await K(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print device status: ${o.message}`);throw o}}async function qa(t,e){if(!await K(t))throw Error(`Print device with ID ${t} not found`);try{return await po.updateTable("print_devices").set({print_count:e,updated_at:fo(new Date)}).where("id","=",t).execute(),await K(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print count: ${o.message}`);throw o}}var go={};g(go,{bulkDestroy:()=>Za,bulkUpdateStatus:()=>rs,destroy:()=>Va,destroyGroup:()=>Ha,fetchAll:()=>Pt,fetchByGroup:()=>Ya,fetchById:()=>Ka,fetchGrouped:()=>Qa,fetchStats:()=>Xa,fetchTimeline:()=>es,ignoreGroup:()=>ns,resolveGroup:()=>os,unresolveGroup:()=>as,update:()=>ts});import{db as yo}from"@stacksjs/database";import{log as ho}from"@stacksjs/logging";async function Va(t){try{return await yo.deleteFrom("errors").where("id","=",t).execute(),!0}catch(e){return ho.error("[commerce/errors] destroy failed",{id:t,error:e}),!1}}async function Za(t){try{return await yo.deleteFrom("errors").where("id","in",t).execute(),!0}catch(e){return ho.error("[commerce/errors] bulkDestroy failed",{count:t.length,error:e}),!1}}async function Ha(t,e){try{return await yo.deleteFrom("errors").where("type","=",t).where("message","=",e).execute(),!0}catch(r){return ho.error("[commerce/errors] destroyGroup failed",{type:t,message:e,error:r}),!1}}import{db as vt}from"@stacksjs/database";async function Ka(t){return await vt.selectFrom("errors").where("id","=",t).selectAll().executeTakeFirst()}async function Pt(){return await vt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function Qa(){let t=await vt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),e=new Map;for(let o of t){let n=`${o.type}:${o.message}`;if(!e.has(n))e.set(n,{errors:[],firstSeen:new Date(o.created_at),lastSeen:new Date(o.created_at)});let a=e.get(n);a.errors.push(o);let s=new Date(o.created_at);if(s<a.firstSeen)a.firstSeen=s;if(s>a.lastSeen)a.lastSeen=s}let r=[];for(let[o,n]of e){let a=n.errors[0];if(!a)continue;let s=n.errors.find((u)=>u.status!==null)?.status,i="unresolved";if(s===1)i="resolved";else if(s===2)i="ignored";r.push({id:a.id,type:a.type,message:a.message,stack:a.stack,status:i,count:n.errors.length,first_seen:n.firstSeen.toISOString(),last_seen:n.lastSeen.toISOString(),error_ids:n.errors.map((u)=>u.id)})}return r.sort((o,n)=>new Date(n.last_seen).getTime()-new Date(o.last_seen).getTime()),r}async function Ya(t,e){return await vt.selectFrom("errors").where("type","=",t).where("message","=",e).selectAll().orderBy("created_at","desc").execute()}async function Xa(){let t=await Pt(),e=new Date,r=new Date(e.getTime()-86400000),o=new Date(e.getTime()-172800000),n=t.filter((i)=>new Date(i.created_at)>=r).length,a=t.filter((i)=>{let u=new Date(i.created_at);return u>=o&&u<r}).length,s=a===0?n>0?100:0:Math.round((n-a)/a*100);return{total:t.length,unresolved:t.filter((i)=>i.status===null||i.status===0).length,resolved:t.filter((i)=>i.status===1).length,ignored:t.filter((i)=>i.status===2).length,last_24h:n,trend:s}}async function es(){let t=await Pt(),e=new Date,r=[];for(let o=23;o>=0;o--){let n=new Date(e.getTime()-o*60*60*1000);n.setMinutes(0,0,0);let a=new Date(n.getTime()+3600000),s=t.filter((i)=>{let u=new Date(i.created_at);return u>=n&&u<a}).length;r.push({hour:n.toISOString(),count:s})}return r}import{db as je}from"@stacksjs/database";import{sql as ze}from"@stacksjs/database";import{log as Ge}from"@stacksjs/logging";async function ts(t,e){try{return await je.updateTable("errors").set({...e,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("id","=",t).execute(),!0}catch(r){return Ge.error("[commerce/errors] update failed",{id:t,error:r}),!1}}async function rs(t,e){try{return await je.updateTable("errors").set({status:e,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("id","in",t).execute(),!0}catch(r){return Ge.error("[commerce/errors] bulkUpdateStatus failed",{count:t.length,status:e,error:r}),!1}}async function os(t,e){try{return await je.updateTable("errors").set({status:1,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ge.error("[commerce/errors] resolveGroup failed",{type:t,message:e,error:r}),!1}}async function ns(t,e){try{return await je.updateTable("errors").set({status:2,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ge.error("[commerce/errors] ignoreGroup failed",{type:t,message:e,error:r}),!1}}async function as(t,e){try{return await je.updateTable("errors").set({status:0,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ge.error("[commerce/errors] unresolveGroup failed",{type:t,message:e,error:r}),!1}}var Ro={};g(Ro,{bulkDestroy:()=>ys,calculateGiftCardValues:()=>ls,checkBalance:()=>cs,compareActiveGiftCards:()=>ds,deactivate:()=>gs,destroy:()=>ws,destroyExpired:()=>hs,fetchActive:()=>is,fetchAll:()=>ss,fetchByCode:()=>bo,fetchById:()=>Q,fetchStats:()=>us,fetchTotalCurrentBalance:()=>ps,fetchTotalValue:()=>ms,store:()=>_s,update:()=>Ps,updateBalance:()=>Fs});import{db as Ft,matchedRows as gp}from"@stacksjs/database";import{formatDate as fs}from"@stacksjs/orm";import{db as v,sql as I}from"@stacksjs/database";import{formatDate as ue,toTimestamp as De}from"@stacksjs/orm";import{aggregateFunctions as yp,db as hp}from"@stacksjs/database";async function J(t,e,r){let o=hp.selectFrom(t);if(r)o=r(o);o=o.select(Object.entries(e).map(([s,i])=>{let u=i.column??"id",c=yp[i.kind](u);if(i.filter)c=c.filterWhere(i.filter.column,i.filter.op,i.filter.value);return c.as(s)}));let n=await o.executeTakeFirst(),a={};for(let s of Object.keys(e)){let i=n?.[s];a[s]=typeof i==="number"?i:Number(i??0)||0}return a}async function ss(){let t=await v.selectFrom("gift_cards").selectAll().execute();return w(t)}async function Q(t){let e=await v.selectFrom("gift_cards").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function bo(t){let e=await v.selectFrom("gift_cards").where("code","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function is(){let t=await v.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute();return w(t)}async function us(){let{count:t}=await J("gift_cards",{count:{kind:"count"}}),e=De(new Date),r=await v.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(e)} OR expiry_date IS NULL)`).select(v.fn.count("id").as("count")).executeTakeFirst(),o=await v.selectFrom("gift_cards").select(["status",v.fn.count("id").as("count")]).groupBy("status").execute(),{count:n}=await J("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(I`current_balance / initial_balance < 0.25`)),{count:a}=await J("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(I`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:s}=await J("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(I`current_balance / initial_balance > 0.75`)),i=new Date;i.setDate(i.getDate()+30);let u=await v.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",De(i)).where("expiry_date",">=",e).selectAll().limit(5).execute(),c=await v.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:t,active:Number(r?.count||0),by_status:o.map((l)=>({status:l.status,count:Number(l.count)})),by_balance:{low:n,medium:a,high:s},expiring_soon:w(u),recently_used:w(c)}}async function cs(t){let e=await bo(t);if(!e)return{valid:!1,message:"Gift card not found"};if(!e.isActive||e.status!=="ACTIVE")return{valid:!1,balance:e.currentBalance,currency:e.currency,message:`Gift card is ${e.status.toLowerCase()}`};if(e.expiryDate){if(new Date(e.expiryDate)<new Date)return{valid:!1,balance:e.currentBalance,currency:e.currency,message:"Gift card has expired"}}return{valid:!0,balance:e.currentBalance,currency:e.currency}}async function ds(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await v.selectFrom("gift_cards").select(v.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(e))} OR expiry_date IS NULL)`).where("created_at",">=",ue(r)).where("created_at","<=",ue(e)).executeTakeFirst(),s=await v.selectFrom("gift_cards").select(v.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(n))} OR expiry_date IS NULL)`).where("created_at",">=",ue(n)).where("created_at","<=",ue(o)).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,l=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:l,days_range:t}}async function ls(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await v.selectFrom("gift_cards").select([v.fn.sum("initial_balance").as("total_initial"),v.fn.sum("current_balance").as("total_balance"),v.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(e))} OR expiry_date IS NULL)`).where("created_at",">=",ue(r)).where("created_at","<=",ue(e)).executeTakeFirst(),s=await v.selectFrom("gift_cards").select([v.fn.sum("initial_balance").as("total_initial"),v.fn.sum("current_balance").as("total_balance"),v.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(n))} OR expiry_date IS NULL)`).where("created_at",">=",ue(n)).where("created_at","<=",ue(o)).executeTakeFirst(),i=Number(a?.total_initial||0),u=Number(a?.total_balance||0),c=Number(a?.card_count||0),l=Number(s?.total_initial||0),m=Number(s?.total_balance||0),f=Number(s?.card_count||0),h=i>0?(i-u)/i*100:0,b=l>0?(l-m)/l*100:0,_=c>0?i/c:0,D=c>0?u/c:0,z=i-l,le=u-m,me=c-f,Re=l!==0?z/l*100:i>0?100:0,G=m!==0?le/m*100:u>0?100:0,Wm=f!==0?me/f*100:c>0?100:0;return{current_period:{total_initial_value:i,total_remaining_balance:u,utilization_rate:h,card_count:c,average_initial_value:_,average_remaining_balance:D},previous_period:{total_initial_value:l,total_remaining_balance:m,utilization_rate:b,card_count:f},comparison:{initial_value:{difference:z,percentage:Math.abs(Re),is_increase:z>=0},balance:{difference:le,percentage:Math.abs(G),is_increase:le>=0},card_count:{difference:me,percentage:Math.abs(Wm),is_increase:me>=0}},days_range:t}}async function ms(){let{total_value:t}=await J("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:t}}async function ps(){let{total_balance:t}=await J("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:t}}async function ws(t){let e=await Ft.deleteFrom("gift_cards").where("id","=",t).executeTakeFirst();return p(e)>0}async function ys(t){if(!t.length)return 0;let e=await Ft.deleteFrom("gift_cards").where("id","in",t).executeTakeFirst();return p(e)}async function hs(){let t=fs(new Date),e=await Ft.deleteFrom("gift_cards").where("expiry_date","<",t).executeTakeFirst();return p(e)}async function gs(t){if(!await Q(t))throw Error(`Gift card with ID ${t} not found`);return(await gp(Ft.updateTable("gift_cards").set({is_active:!1,status:"DEACTIVATED",updated_at:fs(new Date)}).where("id","=",t))).length>0}var{randomUUIDv7:bp}=globalThis.Bun;import{db as _o}from"@stacksjs/database";import{HttpError as bs}from"@stacksjs/error-handling";import{isUniqueViolation as _p}from"@stacksjs/orm";async function _s(t){let e=t,r={...t,current_balance:e.current_balance??e.initial_balance,status:t.status||"ACTIVE",is_active:e.is_active??!0,uuid:bp()};try{let o=await _o.insertInto("gift_cards").values(r).executeTakeFirst(),n=H(o);if(n!==void 0){let s=await _o.selectFrom("gift_cards").where("id","=",n).selectAll().executeTakeFirst();return d(s)}let a=await _o.selectFrom("gift_cards").where("uuid","=",r.uuid).selectAll().executeTakeFirst();return d(a,!0)}catch(o){if(o instanceof bs)throw o;if(_p(o))throw new bs(409,"A gift card with this code already exists");if(o instanceof Error)throw Error(`Failed to create gift card: ${o.message}`);throw o}}import{db as Ds,mutationCount as Rp,parseSqlDateTime as Rs,sqlHelpers as xp}from"@stacksjs/database";import{env as Dp}from"@stacksjs/env";import{HttpError as xs}from"@stacksjs/error-handling";import{formatDate as vs,isUniqueViolation as vp}from"@stacksjs/orm";async function Ps(t,e){if(!await Q(t))return;try{return await Ds.updateTable("gift_cards").set({...e,updated_at:vs(new Date)}).where("id","=",t).execute(),await Q(t)}catch(o){if(o instanceof xs)throw o;if(vp(o))throw new xs(409,"A gift card with this code already exists");if(o instanceof Error)throw Error(`Failed to update gift card: ${o.message}`);throw o}}async function Fs(t,e){if(!Number.isFinite(e))throw Error(`Gift card balance adjustment must be a finite number, got ${e}`);let r=xp(Dp.DB_CONNECTION||"sqlite"),o=r.param,n=vs(new Date),a=e<0,s=e>0,i=s?`(status = 'ACTIVE' OR (status = 'USED' AND is_reloadable = ${r.boolTrue}))`:"status = 'ACTIVE'",u=[],c=(_)=>(u.push(_),o(u.length)),l=await Ds.unsafe(`UPDATE gift_cards
|
|
9
|
+
SET status = CASE WHEN current_balance + ${c(e)} = 0 THEN 'USED' WHEN 1 = 0 THEN status ELSE 'ACTIVE' END,
|
|
10
|
+
current_balance = current_balance + ${c(e)},
|
|
10
11
|
${a?`last_used_date = ${c(n)},
|
|
11
|
-
`:""}
|
|
12
|
-
updated_at = ${c(n)}
|
|
12
|
+
`:""}updated_at = ${c(n)}
|
|
13
13
|
WHERE id = ${c(t)}
|
|
14
14
|
AND is_active = ${r.boolTrue}
|
|
15
15
|
AND ${i}
|
|
16
16
|
AND (expiry_date IS NULL OR expiry_date >= ${c(n)})
|
|
17
|
-
AND current_balance + ${c(e)} >= 0`,u);if(
|
|
17
|
+
AND current_balance + ${c(e)} >= 0`,u);if(Rp(l)>0)return await Q(t);let m=await Q(t);if(!m)throw Error(`Gift card with ID ${t} not found`);let f=m;if(!f.is_active&&!f.isActive)throw Error("Gift card is not active");if(m.status==="USED"&&s&&!(f.is_reloadable??f.isReloadable))throw Error("Gift card is not reloadable");if(m.status!=="ACTIVE")throw Error("Gift card is not active");let h=Rs(f.expiry_date??f.expiryDate),b=Rs(n);if(h&&b&&h.getTime()<b.getTime())throw Error("Gift card has expired");if(e===0&&Number(f.current_balance??f.currentBalance)>=0)return m;throw Error("Insufficient gift card balance")}var No={};g(No,{bulkDestroy:()=>Ss,bulkSoftDelete:()=>Cs,calculateOrderMetrics:()=>Os,canTransition:()=>ve,cleanupAbandonedCarts:()=>oi,compareOrdersByPeriod:()=>Bs,destroy:()=>Ts,downloadOrders:()=>Ms,emitForStatus:()=>Pe,emitOrderCancelled:()=>qe,emitOrderCreated:()=>Et,emitOrderDelivered:()=>Po,emitOrderPaid:()=>we,emitOrderRefunded:()=>Ve,emitOrderShipped:()=>vo,exportOrders:()=>Tt,fetchAll:()=>xo,fetchById:()=>Y,fetchDailyOrderTrends:()=>Us,fetchRecent:()=>Ns,fetchStats:()=>Js,findOrderByIdempotencyKey:()=>St,handleChargeRefunded:()=>Mo,handlePaymentIntentFailed:()=>Ao,handlePaymentIntentSucceeded:()=>Co,placeOrder:()=>Vs,recomputeOrderTotals:()=>ei,registerCommerceWebhookHandlers:()=>Ys,softDelete:()=>Es,store:()=>Ws,storeOrdersExport:()=>Is,update:()=>Zs,updateDeliveryInfo:()=>Ks,updateStatus:()=>Hs,validateCartQuantities:()=>ri,validateCouponStacking:()=>ti,validateQuantityBounds:()=>Io});import{db as kt,matchedRows as ks}from"@stacksjs/database";async function Ts(t){try{let e=await kt.deleteFrom("orders").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete order: ${e.message}`);throw e}}async function Es(t){try{return(await ks(kt.updateTable("orders").set({status:"CANCELED"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete order: ${e.message}`);throw e}}async function Ss(t){if(!t.length)return 0;try{let e=await kt.deleteFrom("orders").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete orders: ${e.message}`);throw e}}async function Cs(t){if(!t.length)return 0;try{return(await ks(kt.updateTable("orders").set({status:"CANCELED"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete orders: ${e.message}`);throw e}}import{db as As}from"@stacksjs/database";import{createSpreadsheet as Pp}from"ts-spreadsheets";async function Tt(t="csv"){let e=await Fp(),r=kp(e);return Pp(r,{type:t})}async function Fp(){let t=await As.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),e=t.map((a)=>a.id);if(e.length===0)return[];let o=(await As.selectFrom("order_items").where("order_items.order_id","in",e).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((a,s)=>{if(!s.order_id)return a;if(!a[s.order_id])a[s.order_id]={totalItems:0,totalPrice:0};return a[s.order_id].totalItems+=s.quantity,a[s.order_id].totalPrice+=s.price*s.quantity,a},{});return t.map((a)=>{let s=o[a.id]||{totalItems:0,totalPrice:0};return{...a,totalItems:s.totalItems,totalPrice:s.totalPrice}})}function kp(t){let e=["Order ID","Customer","Date","Total","Status","Items"],r=t.map((o)=>{let n=o.order_items?.map((a)=>`${a.product?.name} (Qty: ${a.quantity}, Price: $${a.price})`).join(" | ")||"No Items";return[o.id,o.customer?.name||"N/A",o.created_at,o.total_amount,o.status,n]});return{headings:e,data:r}}async function Ms(t="csv",e){let r=await Tt(t),o=`orders_export_${new Date().toISOString().split("T")[0]}.${t}`;return r.download(e||o)}async function Is(t="csv",e){let r=await Tt(t),o=`orders_export_${new Date().toISOString().split("T")[0]}.${t}`;r.store(e||o)}import{db as x}from"@stacksjs/database";async function xo(t){let e=x.selectFrom("orders").selectAll().orderBy("created_at","desc");if(t)e=e.limit(t);let r=w(await e.execute());return await Promise.all(r.map(async(o)=>{let n=await x.selectFrom("order_items").where("order_id","=",o.id).selectAll().execute();return{...o,items:n}}))}async function Ns(t=10){return xo(t)}async function Y(t){let e=await x.selectFrom("orders").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Js(){let t=await x.selectFrom("orders").select(x.fn.count("id").as("count")).executeTakeFirst(),e=await x.selectFrom("orders").select(["status",x.fn.count("id").as("count")]).groupBy("status").execute(),r=await x.selectFrom("orders").select(["order_type",x.fn.count("id").as("count")]).groupBy("order_type").execute(),o=w(await x.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute()),n=await Promise.all(o.map(async(s)=>{let i=await x.selectFrom("order_items").where("order_id","=",s.id).selectAll().execute();return{...s,items:i}})),a=await x.selectFrom("orders").select(x.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(t?.count||0),by_status:e,by_type:r,recent:n,revenue:Number(a?.total||0)}}async function Bs(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await x.selectFrom("orders").select(x.fn.count("id").as("count")).where("created_at",">=",r.toISOString()).where("created_at","<=",e.toISOString()).executeTakeFirst(),s=await x.selectFrom("orders").select(x.fn.count("id").as("count")).where("created_at",">=",n.toISOString()).where("created_at","<=",o.toISOString()).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,l=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:l,days_range:t}}async function Os(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await x.selectFrom("orders").select([x.fn.count("id").as("total_orders"),x.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",r.toISOString()).where("created_at","<=",e.toISOString()).executeTakeFirst(),s=await x.selectFrom("orders").select([x.fn.count("id").as("total_orders"),x.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",n.toISOString()).where("created_at","<=",o.toISOString()).executeTakeFirst(),i=await x.selectFrom("orders").select(["status",x.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",e.toISOString()).groupBy("status").execute(),u=await x.selectFrom("orders").select(["order_type",x.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",e.toISOString()).groupBy("order_type").execute(),c=Number(a?.total_orders||0),l=Number(a?.total_revenue||0),m=c>0?l/c:0,f=Number(s?.total_orders||0),h=Number(s?.total_revenue||0),b=f>0?h/f:0,_=c-f,D=l-h,z=m-b,le=f!==0?_/f*100:c>0?100:0,me=h!==0?D/h*100:l>0?100:0,Re=b!==0?z/b*100:m>0?100:0;return{current_period:{total_orders:c,total_revenue:l,average_order_value:m,orders_by_status:i.map((G)=>({status:G.status,count:Number(G.count)})),orders_by_type:u.map((G)=>({order_type:G.order_type,count:Number(G.count)}))},previous_period:{total_orders:f,total_revenue:h,average_order_value:b},comparison:{orders:{difference:_,percentage:Math.abs(le),is_increase:_>=0},revenue:{difference:D,percentage:Math.abs(me),is_increase:D>=0},average_order_value:{difference:z,percentage:Math.abs(Re),is_increase:z>=0}},days_range:t}}async function Us(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=await x.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",r.toISOString()).where("created_at","<=",e.toISOString()).orderBy("created_at","asc").execute(),n=new Map;for(let a of o){let s=(a.created_at||"").split("T")[0]||"unknown",i=n.get(s)||{order_count:0,revenue:0};i.order_count++,i.revenue+=Number(a.total_amount||0),n.set(s,i)}return Array.from(n.entries()).map(([a,s])=>({date:a,order_count:s.order_count,revenue:s.revenue}))}var{randomUUIDv7:Tp}=globalThis.Bun;import{db as Do}from"@stacksjs/database";import{formatDate as $s}from"@stacksjs/orm";async function Ws(t){let e={...t,status:t.status||"PENDING",uuid:Tp(),created_at:$s(new Date),updated_at:$s(new Date)};try{let r=await Do.insertInto("orders").values(e).executeTakeFirst(),o=H(r);if(o!==void 0){let a=await Do.selectFrom("orders").where("id","=",o).selectAll().executeTakeFirst();return d(a,!0)}let n=await Do.selectFrom("orders").where("uuid","=",e.uuid).selectAll().executeTakeFirst();return d(n,!0)}catch(r){if(r instanceof Error)throw Error(`Failed to create order: ${r.message}`);throw r}}var{randomUUIDv7:js}=globalThis.Bun;import{db as Fo}from"@stacksjs/database";Fe();import{formatDate as Ip,isUniqueViolation as zs}from"@stacksjs/orm";import{sqlHelpers as Cp}from"@stacksjs/database";import{env as Ap}from"@stacksjs/env";function Mp(t,e,r,o){let n=Cp(t).param;return{query:`UPDATE products
|
|
18
18
|
SET inventory_count = inventory_count + ${n(1)},
|
|
19
19
|
updated_at = ${n(2)}
|
|
20
20
|
WHERE id = ${n(3)}
|
|
21
|
-
AND inventory_count + ${n(4)} >= 0`,parameters:[r,o,e,r]}}async function Us(t,e,r,o){let n=Rp(_p.DB_CONNECTION||"sqlite",e,r,o),a=await t.unsafe(n.query,n.parameters);return l(a)}var Ls=!1;function js(t){let e=t,r=e?.message??"";return e?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function St(t){try{let e=await Fo.selectFrom("order_idempotency").where("idempotency_key","=",t).selectAll().executeTakeFirst();if(!e)return null;return await Fo.selectFrom("orders").where("id","=",e.order_id).selectAll().executeTakeFirst()??null}catch(e){if(js(e)){if(!Ls)Ls=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw e}}async function zs(t){if(t.idempotencyKey){let e=await St(t.idempotencyKey);if(e)return{ok:!0,order:e}}try{let e=await Fo.transaction(async(r)=>{let o=xp(new Date),n=$s(),a={...t.order,status:t.order.status||"PENDING",uuid:n,created_at:o,updated_at:o};await r.insertInto("orders").values(a).executeTakeFirst();let s=d(await r.selectFrom("orders").where("uuid","=",n).selectAll().executeTakeFirst(),!0),i=Number(s?.id);if(!Number.isSafeInteger(i)||i<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let u;if(t.items&&t.items.length>0){let p=t.items.map((f)=>{if(!Number.isInteger(f.productId)||f.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(f.quantity)||f.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(f.price)||f.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:i,product_id:f.productId,quantity:f.quantity,price:f.price,special_instructions:f.specialInstructions||null,created_at:o,updated_at:o}});await r.insertInto("order_items").values(p).execute(),u=w(await r.selectFrom("order_items").where("order_id","=",i).selectAll().execute())}let c;if(t.payment)try{let p=$s();if(await r.insertInto("payments").values({...t.payment,order_id:i,uuid:p,created_at:o,updated_at:o}).executeTakeFirst(),c=d(await r.selectFrom("payments").where("uuid","=",p).selectAll().executeTakeFirst(),!0),!c)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(p){if(Ws(p))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(p,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(t.inventory&&t.inventory.length>0)for(let p=0;p<t.inventory.length;p++){let{id:f,delta:y}=t.inventory[p];if(!Number.isFinite(y)||y===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await Us(r,f,y,o))throw Object.assign(Error(`inventory adjust failed for product ${f}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(t.idempotencyKey)try{await r.insertInto("order_idempotency").values({idempotency_key:t.idempotencyKey,order_id:i,created_at:o}).execute()}catch(p){if(Ws(p))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!js(p))throw p}let m=d(await r.selectFrom("orders").where("id","=",i).selectAll().executeTakeFirst(),!0);if(!m)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:m,items:u,payment:c}});if(Et(e.order),e.payment)we(e.order,e.payment);return{ok:!0,order:e.order,items:e.items,payment:e.payment}}catch(e){if(e?.__placeFail){if(e.reason==="duplicate-idempotency-key"&&t.idempotencyKey){let r=await St(t.idempotencyKey);if(r)return{ok:!0,order:r}}return{ok:!1,reason:e.reason,failedAt:e.failedAt,error:e}}throw e}}Fe();import{db as ko}from"@stacksjs/database";import{formatDate as To}from"@stacksjs/orm";Fe();async function Gs(t,e){if(!await Y(t))return;try{return await ko.updateTable("orders").set({...e,updated_at:To(new Date)}).where("id","=",t).execute(),await Y(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update order: ${o.message}`);throw o}}async function Vs(t,e){let r=await Y(t);if(!r)throw Error(`Order with ID ${t} not found`);let o=r.status??"PENDING";if(!ve(o,e))throw Error(`[commerce/orders] illegal status transition ${o} \u2192 ${e}`);try{await ko.updateTable("orders").set({status:e,updated_at:To(new Date)}).where("id","=",t).execute();let n=await Y(t);if(n)Pe(e,n);return n}catch(n){if(n instanceof Error)throw TypeError(`Failed to update order status: ${n.message}`);throw n}}async function qs(t,e,r){let o=await Y(t);if(!o)throw Error(`Order with ID ${t} not found`);let n={updated_at:To(new Date)};if(e!==void 0)n.delivery_address=e;if(r!==void 0)n.estimated_delivery_time=r;if(Object.keys(n).length===1)return o;try{return await ko.updateTable("orders").set(n).where("id","=",t).execute(),await Y(t)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery information: ${a.message}`);throw a}}Fe();import{db as Ze}from"@stacksjs/database";import{formatDate as Ct}from"@stacksjs/orm";async function Eo(t){let e=await Ze.selectFrom("payments").where("transaction_id","=",t).selectAll().executeTakeFirst();if(!e)return null;return await Ze.selectFrom("orders").where("id","=",e.order_id).selectAll().executeTakeFirst()??null}var Zs=!1;function Dp(t){let e=t,r=e?.message??"";return e?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function So(t,e){try{return await e.insertInto("stripe_webhook_events").values({event_id:t,processed_at:Ct(new Date)}).execute(),!0}catch(r){if(r?.message?.includes("UNIQUE constraint")||r?.message?.includes("Duplicate entry"))return!1;if(Dp(r)){if(!Zs)Zs=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing - Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw r}}async function Co(t){let r=t.data.object?.id;if(!r)return;await Ze.transaction(async(n)=>{if(!await So(t.id,n))return;let s=await n.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!s)return;let i=Ct(new Date);await n.updateTable("payments").set({status:"succeeded",updated_at:i}).where("id","=",s.id).execute();let u=await n.selectFrom("orders").where("id","=",s.order_id).selectAll().executeTakeFirst();if(u&&u.status==="PENDING")await n.updateTable("orders").set({status:"PROCESSING",updated_at:i}).where("id","=",u.id).execute()});let o=await Eo(r);if(o)await we(o)}async function Ao(t){let e=t.data.object,r=e?.id;if(!r)return;let n=e?.last_payment_error?.message??"payment failed";await Ze.transaction(async(s)=>{if(!await So(t.id,s))return;let u=await s.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!u)return;let c=Ct(new Date);await s.updateTable("payments").set({status:"failed",failure_reason:n,updated_at:c}).where("id","=",u.id).execute();let m=await s.selectFrom("orders").where("id","=",u.order_id).selectAll().executeTakeFirst();if(m&&m.status==="PENDING")await s.updateTable("orders").set({status:"CANCELLED",updated_at:c}).where("id","=",m.id).execute()});let a=await Eo(r);if(a)await Ve(a,n)}async function Mo(t){let e=t.data.object,r=e?.payment_intent;if(!r)return;let o=e?.amount_refunded??0;await Ze.transaction(async(a)=>{if(!await So(t.id,a))return;let i=await a.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!i)return;let u=Ct(new Date);await a.updateTable("payments").set({status:"refunded",refund_amount:o,updated_at:u}).where("id","=",i.id).execute();let c=await a.selectFrom("orders").where("id","=",i.order_id).selectAll().executeTakeFirst();if(c&&c.status!=="REFUNDED")await a.updateTable("orders").set({status:"REFUNDED",updated_at:u}).where("id","=",c.id).execute()});let n=await Eo(r);if(n)await qe(n,o)}async function Ks(){let t=await import("@stacksjs/payments").catch(()=>null);if(!t)return console.warn("[commerce/webhook] @stacksjs/payments not installed - Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:e,onCharge:r}=t;if(typeof e!=="function"||typeof r!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed - handlers NOT registered"),()=>{};return e({succeeded:Co,failed:Ao}),r({refunded:Mo}),()=>{}}import{db as Hs}from"@stacksjs/database";async function vp(t){if(t.length===0)return new Map;let e=await Hs.selectFrom("products").where("id","in",t).select(["id","price"]).execute(),r=new Map;for(let o of e){let n=Number(o.price);if(Number.isFinite(n))r.set(o.id,Math.round(n))}return r}async function Pp(t){try{let e=await Hs.selectFrom("tax_rates").where("id","=",t).select(["rate"]).executeTakeFirst(),r=Number(e?.rate??0);return Number.isFinite(r)?r:0}catch{return 0}}async function Qs(t){let e=t.items.map((b)=>b.productId),r=await vp(e),o=t.taxRateId!=null?await Pp(t.taxRateId):0,n=0,a=[];for(let b of t.items){let _=b.unitPriceCents??r.get(b.productId)??0,D=Math.round(_*b.quantity);n+=D,a.push({productId:b.productId,quantity:b.quantity,unitPriceCents:_,lineCents:D})}let s=Math.max(0,t.discountCents??0),i=Math.max(0,n-s),u=Math.round(i*o),c=Math.max(0,t.shippingCents??0),m=n-s+u+c,p=t.maxDriftCents??5,f=!1,y=0;if(t.clientTotalCents!=null)y=Math.abs(m-t.clientTotalCents),f=y>p;return{subtotalCents:n,discountCents:s,taxCents:u,shippingCents:c,totalCents:m,resolvedItems:a,priceChanged:f,diffCents:y}}import{db as At,sqlHelpers as Fp}from"@stacksjs/database";import{env as kp}from"@stacksjs/env";function Ys(t,e={}){let r=t.length;if(r<=1)return{ok:!0,count:r};if(!e.allowMultiple)return{ok:!1,count:r,reason:"multiple-not-allowed"};let o=e.maxStacked??Number.POSITIVE_INFINITY;if(r>o)return{ok:!1,count:r,reason:"exceeds-max-stacked"};return{ok:!0,count:r}}async function Io(t,e){if(!Number.isFinite(e)||e<=0)return{ok:!1,productId:t,quantity:e,reason:"non-positive"};let r;try{r=await At.selectFrom("products").where("id","=",t).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:t,quantity:e}}if(!r)return{ok:!1,productId:t,quantity:e,reason:"product-missing"};let o=r.min_order_qty??null,n=r.max_order_qty??null;if(o!=null&&e<o)return{ok:!1,productId:t,quantity:e,reason:"below-min",bound:o};if(n!=null&&e>n)return{ok:!1,productId:t,quantity:e,reason:"above-max",bound:n};return{ok:!0,productId:t,quantity:e}}async function Xs(t){for(let r of t){let o=await Io(r.productId,r.quantity);if(!o.ok)return o}let e=t[t.length-1]??{productId:0,quantity:0};return{ok:!0,productId:e.productId,quantity:e.quantity}}async function ei(t={}){let e=t.olderThanDays??30,r=t.limit??1000,n=new Date(Date.now()-e*24*60*60*1000).toISOString().slice(0,19).replace("T"," "),a=Fp(kp.DB_CONNECTION||"sqlite").param;try{let i=await At.unsafe(`DELETE FROM carts WHERE updated_at < ${a(1)} AND id IN (SELECT id FROM carts WHERE updated_at < ${a(2)} LIMIT ${a(3)})`,[n,n,r]);return{deleted:Number(i?.changes??i?.numDeletedRows??i?.[0]?.numDeletedRows??i?.affectedRows??0),cutoffAt:n}}catch{try{let s=await At.selectFrom("carts").where("updated_at","<",n).select(["id"]).limit(r).execute();if(s.length===0)return{deleted:0,cutoffAt:n};let i=s.map((m)=>m.id),u=await At.deleteFrom("carts").where("id","in",i).execute();return{deleted:Number(u?.numDeletedRows??u?.[0]?.numDeletedRows??u?.affectedRows??s.length),cutoffAt:n}}catch{return{deleted:0,cutoffAt:n}}}}var Jo={};g(Jo,{bulkDestroy:()=>oi,destroy:()=>ri,fetchAll:()=>ni,fetchById:()=>ye,fetchMonthlyPaymentTrends:()=>ii,fetchPaymentStats:()=>ai,fetchPaymentStatsByMethod:()=>si,recordRefund:()=>fi,store:()=>di,update:()=>pi});import{db as ti}from"@stacksjs/database";async function ri(t){try{let e=await ti.deleteFrom("payments").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete payment: ${e.message}`);throw e}}async function oi(t){if(!t.length)return 0;try{let e=await ti.deleteFrom("payments").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete payments: ${e.message}`);throw e}}import{db as E}from"@stacksjs/database";import{formatDate as U}from"@stacksjs/orm";async function ni(){let t=await E.selectFrom("payments").selectAll().execute();return w(t)}async function ye(t){let e=await E.selectFrom("payments").selectAll().where("id","=",t).executeTakeFirst();return d(e,!0)}async function ai(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await E.selectFrom("payments").select([E.fn.count("id").as("transaction_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",U(r)).where("created_at","<=",U(e)).where("status","=","completed").executeTakeFirst(),s=await E.selectFrom("payments").select([E.fn.count("id").as("transaction_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",U(n)).where("created_at","<=",U(o)).where("status","=","completed").executeTakeFirst(),i=await E.selectFrom("payments").select(E.fn.count("id").as("count")).where("created_at",">=",U(r)).where("created_at","<=",U(e)).executeTakeFirst(),u=Number(a?.transaction_count||0),c=Number(a?.total_revenue||0),m=u>0?c/u:0,p=Number(s?.transaction_count||0),f=Number(s?.total_revenue||0),y=p>0?f/p:0,b=u-p,_=c-f,D=m-y,z=p>0?b/p*100:u>0?100:0,le=f>0?_/f*100:c>0?100:0,me=y>0?D/y*100:m>0?100:0,Re=Number(i?.count||0),G=Re>0?u/Re*100:0;return{total_transactions:u,total_revenue:c,average_transaction:m,successful_rate:G,comparison:{transactions:{difference:b,percentage:Math.abs(z),is_increase:b>=0},revenue:{difference:_,percentage:Math.abs(le),is_increase:_>=0},average:{difference:D,percentage:Math.abs(me),is_increase:D>=0}}}}async function si(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=await E.selectFrom("payments").select([E.fn.count("id").as("total_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",U(r)).where("created_at","<=",U(e)).where("status","=","completed").executeTakeFirst(),n=Number(o?.total_count||0),a=await E.selectFrom("payments").select(["method",E.fn.count("id").as("count"),E.fn.sum("amount").as("revenue")]).where("created_at",">=",U(r)).where("created_at","<=",U(e)).where("status","=","completed").groupBy("method").execute(),s={};return a.forEach((i)=>{let u=Number(i.count||0),c=Number(i.revenue||0),m=n>0?u/n*100:0;s[i.method]={count:u,revenue:c,percentage_of_total:m}}),s}async function ii(){let t=new Date,e=new Date(t);e.setMonth(t.getMonth()-11),e.setDate(1);let r=await E.selectFrom("payments").selectAll().where("created_at",">=",U(e)).where("status","=","completed").execute(),o={};for(let a of r){let s=a.created_at?new Date(String(a.created_at)):new Date,i=s.getFullYear(),u=s.getMonth()+1,c=`${i}-${String(u).padStart(2,"0")}`;if(!o[c])o[c]={year:i,month:u,transactions:0,revenue:0};o[c].transactions++,o[c].revenue+=Number(a.amount||0)}return Object.keys(o).sort().map((a)=>{let s=o[a],{transactions:i,revenue:u}=s,c=i>0?u/i:0;return{month:new Date(s.year,s.month-1,1).toLocaleString("default",{month:"short"}),year:s.year,transactions:i,revenue:u,average:c}})}var{randomUUIDv7:Tp}=globalThis.Bun;import{db as ui}from"@stacksjs/database";import{HttpError as ci}from"@stacksjs/error-handling";import{isUniqueViolation as Ep}from"@stacksjs/orm";async function di(t){let e=Tp(),r={...t,status:t.status||"pending",currency:t.currency||"USD",uuid:e};try{await ui.insertInto("payments").values(r).executeTakeFirst();let o=await ui.selectFrom("payments").where("uuid","=",e).selectAll().executeTakeFirst();return d(o,!0)}catch(o){if(o instanceof ci)throw o;if(Ep(o))throw new ci(409,"A payment with this transaction ID already exists");if(o instanceof Error){if(o.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${o.message}`)}throw o}}import{db as li,sqlHelpers as Sp}from"@stacksjs/database";import{env as Cp}from"@stacksjs/env";import{formatDate as mi}from"@stacksjs/orm";async function pi(t,e){if(!await ye(t))return;try{return await li.updateTable("payments").set({...e,updated_at:mi(new Date)}).where("id","=",t).execute(),await ye(t)}catch(o){if(o instanceof Error){if(o.message.includes("Duplicate entry")&&o.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${o.message}`)}throw o}}var Ap=new Set(["completed","succeeded","partiallyRefunded"]);async function fi(t,e){if(!Number.isSafeInteger(t)||t<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger(e)||e<=0)throw TypeError("Refund amount must be a positive integer in minor units");let o=Sp(Cp.DB_CONNECTION||"sqlite").param,n=mi(new Date),s=await li.unsafe(`UPDATE payments
|
|
22
|
-
SET
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
AND inventory_count + ${n(4)} >= 0`,parameters:[r,o,e,r]}}async function Ls(t,e,r,o){let n=Mp(Ap.DB_CONNECTION||"sqlite",e,r,o),a=await t.unsafe(n.query,n.parameters);return p(a)}var Gs=!1;function qs(t){let e=t,r=e?.message??"";return e?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function St(t){try{let e=await Fo.selectFrom("order_idempotency").where("idempotency_key","=",t).selectAll().executeTakeFirst();if(!e)return null;return await Fo.selectFrom("orders").where("id","=",e.order_id).selectAll().executeTakeFirst()??null}catch(e){if(qs(e)){if(!Gs)Gs=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw e}}async function Vs(t){if(t.idempotencyKey){let e=await St(t.idempotencyKey);if(e)return{ok:!0,order:e}}try{let e=await Fo.transaction(async(r)=>{let o=Ip(new Date),n=js(),a={...t.order,status:t.order.status||"PENDING",uuid:n,created_at:o,updated_at:o};await r.insertInto("orders").values(a).executeTakeFirst();let s=d(await r.selectFrom("orders").where("uuid","=",n).selectAll().executeTakeFirst(),!0),i=Number(s?.id);if(!Number.isSafeInteger(i)||i<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let u;if(t.items&&t.items.length>0){let m=t.items.map((f)=>{if(!Number.isInteger(f.productId)||f.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(f.quantity)||f.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(f.price)||f.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:i,product_id:f.productId,quantity:f.quantity,price:f.price,special_instructions:f.specialInstructions||null,created_at:o,updated_at:o}});await r.insertInto("order_items").values(m).execute(),u=w(await r.selectFrom("order_items").where("order_id","=",i).selectAll().execute())}let c;if(t.payment)try{let m=js();if(await r.insertInto("payments").values({...t.payment,order_id:i,uuid:m,created_at:o,updated_at:o}).executeTakeFirst(),c=d(await r.selectFrom("payments").where("uuid","=",m).selectAll().executeTakeFirst(),!0),!c)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(m){if(zs(m))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(m,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(t.inventory&&t.inventory.length>0)for(let m=0;m<t.inventory.length;m++){let{id:f,delta:h}=t.inventory[m];if(!Number.isFinite(h)||h===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await Ls(r,f,h,o))throw Object.assign(Error(`inventory adjust failed for product ${f}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(t.idempotencyKey)try{await r.insertInto("order_idempotency").values({idempotency_key:t.idempotencyKey,order_id:i,created_at:o}).execute()}catch(m){if(zs(m))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!qs(m))throw m}let l=d(await r.selectFrom("orders").where("id","=",i).selectAll().executeTakeFirst(),!0);if(!l)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:l,items:u,payment:c}});if(Et(e.order),e.payment)we(e.order,e.payment);return{ok:!0,order:e.order,items:e.items,payment:e.payment}}catch(e){if(e?.__placeFail){if(e.reason==="duplicate-idempotency-key"&&t.idempotencyKey){let r=await St(t.idempotencyKey);if(r)return{ok:!0,order:r}}return{ok:!1,reason:e.reason,failedAt:e.failedAt,error:e}}throw e}}Fe();import{db as ko}from"@stacksjs/database";import{formatDate as To}from"@stacksjs/orm";Fe();async function Zs(t,e){if(!await Y(t))return;try{return await ko.updateTable("orders").set({...e,updated_at:To(new Date)}).where("id","=",t).execute(),await Y(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update order: ${o.message}`);throw o}}async function Hs(t,e){let r=await Y(t);if(!r)throw Error(`Order with ID ${t} not found`);let o=r.status??"PENDING";if(!ve(o,e))throw Error(`[commerce/orders] illegal status transition ${o} \u2192 ${e}`);try{await ko.updateTable("orders").set({status:e,updated_at:To(new Date)}).where("id","=",t).execute();let n=await Y(t);if(n)Pe(e,n);return n}catch(n){if(n instanceof Error)throw TypeError(`Failed to update order status: ${n.message}`);throw n}}async function Ks(t,e,r){let o=await Y(t);if(!o)throw Error(`Order with ID ${t} not found`);let n={updated_at:To(new Date)};if(e!==void 0)n.delivery_address=e;if(r!==void 0)n.estimated_delivery_time=r;if(Object.keys(n).length===1)return o;try{return await ko.updateTable("orders").set(n).where("id","=",t).execute(),await Y(t)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery information: ${a.message}`);throw a}}Fe();import{db as Ze}from"@stacksjs/database";import{formatDate as Ct}from"@stacksjs/orm";async function Eo(t){let e=await Ze.selectFrom("payments").where("transaction_id","=",t).selectAll().executeTakeFirst();if(!e)return null;return await Ze.selectFrom("orders").where("id","=",e.order_id).selectAll().executeTakeFirst()??null}var Qs=!1;function Np(t){let e=t,r=e?.message??"";return e?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function So(t,e){try{return await e.insertInto("stripe_webhook_events").values({event_id:t,processed_at:Ct(new Date)}).execute(),!0}catch(r){if(r?.message?.includes("UNIQUE constraint")||r?.message?.includes("Duplicate entry"))return!1;if(Np(r)){if(!Qs)Qs=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing - Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw r}}async function Co(t){let r=t.data.object?.id;if(!r)return;await Ze.transaction(async(n)=>{if(!await So(t.id,n))return;let s=await n.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!s)return;let i=Ct(new Date);await n.updateTable("payments").set({status:"succeeded",updated_at:i}).where("id","=",s.id).execute();let u=await n.selectFrom("orders").where("id","=",s.order_id).selectAll().executeTakeFirst();if(u&&u.status==="PENDING")await n.updateTable("orders").set({status:"PROCESSING",updated_at:i}).where("id","=",u.id).execute()});let o=await Eo(r);if(o)await we(o)}async function Ao(t){let e=t.data.object,r=e?.id;if(!r)return;let n=e?.last_payment_error?.message??"payment failed";await Ze.transaction(async(s)=>{if(!await So(t.id,s))return;let u=await s.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!u)return;let c=Ct(new Date);await s.updateTable("payments").set({status:"failed",failure_reason:n,updated_at:c}).where("id","=",u.id).execute();let l=await s.selectFrom("orders").where("id","=",u.order_id).selectAll().executeTakeFirst();if(l&&l.status==="PENDING")await s.updateTable("orders").set({status:"CANCELLED",updated_at:c}).where("id","=",l.id).execute()});let a=await Eo(r);if(a)await qe(a,n)}async function Mo(t){let e=t.data.object,r=e?.payment_intent;if(!r)return;let o=e?.amount_refunded??0;await Ze.transaction(async(a)=>{if(!await So(t.id,a))return;let i=await a.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!i)return;let u=Ct(new Date);await a.updateTable("payments").set({status:"refunded",refund_amount:o,updated_at:u}).where("id","=",i.id).execute();let c=await a.selectFrom("orders").where("id","=",i.order_id).selectAll().executeTakeFirst();if(c&&c.status!=="REFUNDED")await a.updateTable("orders").set({status:"REFUNDED",updated_at:u}).where("id","=",c.id).execute()});let n=await Eo(r);if(n)await Ve(n,o)}async function Ys(){let t=await import("@stacksjs/payments").catch(()=>null);if(!t)return console.warn("[commerce/webhook] @stacksjs/payments not installed - Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:e,onCharge:r}=t;if(typeof e!=="function"||typeof r!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed - handlers NOT registered"),()=>{};return e({succeeded:Co,failed:Ao}),r({refunded:Mo}),()=>{}}import{db as Xs}from"@stacksjs/database";async function Jp(t){if(t.length===0)return new Map;let e=await Xs.selectFrom("products").where("id","in",t).select(["id","price"]).execute(),r=new Map;for(let o of e){let n=Number(o.price);if(Number.isFinite(n))r.set(o.id,Math.round(n))}return r}async function Bp(t){try{let e=await Xs.selectFrom("tax_rates").where("id","=",t).select(["rate"]).executeTakeFirst(),r=Number(e?.rate??0);return Number.isFinite(r)?r:0}catch{return 0}}async function ei(t){let e=t.items.map((b)=>b.productId),r=await Jp(e),o=t.taxRateId!=null?await Bp(t.taxRateId):0,n=0,a=[];for(let b of t.items){let _=b.unitPriceCents??r.get(b.productId)??0,D=Math.round(_*b.quantity);n+=D,a.push({productId:b.productId,quantity:b.quantity,unitPriceCents:_,lineCents:D})}let s=Math.max(0,t.discountCents??0),i=Math.max(0,n-s),u=Math.round(i*o),c=Math.max(0,t.shippingCents??0),l=n-s+u+c,m=t.maxDriftCents??5,f=!1,h=0;if(t.clientTotalCents!=null)h=Math.abs(l-t.clientTotalCents),f=h>m;return{subtotalCents:n,discountCents:s,taxCents:u,shippingCents:c,totalCents:l,resolvedItems:a,priceChanged:f,diffCents:h}}import{db as At,sqlHelpers as Op}from"@stacksjs/database";import{env as Up}from"@stacksjs/env";function ti(t,e={}){let r=t.length;if(r<=1)return{ok:!0,count:r};if(!e.allowMultiple)return{ok:!1,count:r,reason:"multiple-not-allowed"};let o=e.maxStacked??Number.POSITIVE_INFINITY;if(r>o)return{ok:!1,count:r,reason:"exceeds-max-stacked"};return{ok:!0,count:r}}async function Io(t,e){if(!Number.isFinite(e)||e<=0)return{ok:!1,productId:t,quantity:e,reason:"non-positive"};let r;try{r=await At.selectFrom("products").where("id","=",t).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:t,quantity:e}}if(!r)return{ok:!1,productId:t,quantity:e,reason:"product-missing"};let o=r.min_order_qty??null,n=r.max_order_qty??null;if(o!=null&&e<o)return{ok:!1,productId:t,quantity:e,reason:"below-min",bound:o};if(n!=null&&e>n)return{ok:!1,productId:t,quantity:e,reason:"above-max",bound:n};return{ok:!0,productId:t,quantity:e}}async function ri(t){for(let r of t){let o=await Io(r.productId,r.quantity);if(!o.ok)return o}let e=t[t.length-1]??{productId:0,quantity:0};return{ok:!0,productId:e.productId,quantity:e.quantity}}async function oi(t={}){let e=t.olderThanDays??30,r=t.limit??1000,n=new Date(Date.now()-e*24*60*60*1000).toISOString().slice(0,19).replace("T"," "),a=Op(Up.DB_CONNECTION||"sqlite").param;try{let s=await At.unsafe(`DELETE FROM carts WHERE updated_at < ${a(1)} AND id IN (SELECT id FROM carts WHERE updated_at < ${a(2)} LIMIT ${a(3)})`,[n,n,r]);return{deleted:p(s),cutoffAt:n}}catch{try{let s=await At.selectFrom("carts").where("updated_at","<",n).select(["id"]).limit(r).execute();if(s.length===0)return{deleted:0,cutoffAt:n};let i=s.map((c)=>c.id),u=await At.deleteFrom("carts").where("id","in",i).execute();return{deleted:p(u),cutoffAt:n}}catch{return{deleted:0,cutoffAt:n}}}}var Jo={};g(Jo,{bulkDestroy:()=>si,destroy:()=>ai,fetchAll:()=>ii,fetchById:()=>ye,fetchMonthlyPaymentTrends:()=>di,fetchPaymentStats:()=>ui,fetchPaymentStatsByMethod:()=>ci,recordRefund:()=>hi,store:()=>pi,update:()=>yi});import{db as ni}from"@stacksjs/database";async function ai(t){try{let e=await ni.deleteFrom("payments").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete payment: ${e.message}`);throw e}}async function si(t){if(!t.length)return 0;try{let e=await ni.deleteFrom("payments").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete payments: ${e.message}`);throw e}}import{db as E}from"@stacksjs/database";import{formatDate as U}from"@stacksjs/orm";async function ii(){let t=await E.selectFrom("payments").selectAll().execute();return w(t)}async function ye(t){let e=await E.selectFrom("payments").selectAll().where("id","=",t).executeTakeFirst();return d(e,!0)}async function ui(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await E.selectFrom("payments").select([E.fn.count("id").as("transaction_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",U(r)).where("created_at","<=",U(e)).where("status","=","completed").executeTakeFirst(),s=await E.selectFrom("payments").select([E.fn.count("id").as("transaction_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",U(n)).where("created_at","<=",U(o)).where("status","=","completed").executeTakeFirst(),i=await E.selectFrom("payments").select(E.fn.count("id").as("count")).where("created_at",">=",U(r)).where("created_at","<=",U(e)).executeTakeFirst(),u=Number(a?.transaction_count||0),c=Number(a?.total_revenue||0),l=u>0?c/u:0,m=Number(s?.transaction_count||0),f=Number(s?.total_revenue||0),h=m>0?f/m:0,b=u-m,_=c-f,D=l-h,z=m>0?b/m*100:u>0?100:0,le=f>0?_/f*100:c>0?100:0,me=h>0?D/h*100:l>0?100:0,Re=Number(i?.count||0),G=Re>0?u/Re*100:0;return{total_transactions:u,total_revenue:c,average_transaction:l,successful_rate:G,comparison:{transactions:{difference:b,percentage:Math.abs(z),is_increase:b>=0},revenue:{difference:_,percentage:Math.abs(le),is_increase:_>=0},average:{difference:D,percentage:Math.abs(me),is_increase:D>=0}}}}async function ci(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=await E.selectFrom("payments").select([E.fn.count("id").as("total_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",U(r)).where("created_at","<=",U(e)).where("status","=","completed").executeTakeFirst(),n=Number(o?.total_count||0),a=await E.selectFrom("payments").select(["method",E.fn.count("id").as("count"),E.fn.sum("amount").as("revenue")]).where("created_at",">=",U(r)).where("created_at","<=",U(e)).where("status","=","completed").groupBy("method").execute(),s={};return a.forEach((i)=>{let u=Number(i.count||0),c=Number(i.revenue||0),l=n>0?u/n*100:0;s[i.method]={count:u,revenue:c,percentage_of_total:l}}),s}async function di(){let t=new Date,e=new Date(t);e.setMonth(t.getMonth()-11),e.setDate(1);let r=await E.selectFrom("payments").selectAll().where("created_at",">=",U(e)).where("status","=","completed").execute(),o={};for(let a of r){let s=a.created_at?new Date(String(a.created_at)):new Date,i=s.getFullYear(),u=s.getMonth()+1,c=`${i}-${String(u).padStart(2,"0")}`;if(!o[c])o[c]={year:i,month:u,transactions:0,revenue:0};o[c].transactions++,o[c].revenue+=Number(a.amount||0)}return Object.keys(o).sort().map((a)=>{let s=o[a],{transactions:i,revenue:u}=s,c=i>0?u/i:0;return{month:new Date(s.year,s.month-1,1).toLocaleString("default",{month:"short"}),year:s.year,transactions:i,revenue:u,average:c}})}var{randomUUIDv7:$p}=globalThis.Bun;import{db as li}from"@stacksjs/database";import{HttpError as mi}from"@stacksjs/error-handling";import{isUniqueViolation as Wp}from"@stacksjs/orm";async function pi(t){let e=$p(),r={...t,status:t.status||"pending",currency:t.currency||"USD",uuid:e};try{await li.insertInto("payments").values(r).executeTakeFirst();let o=await li.selectFrom("payments").where("uuid","=",e).selectAll().executeTakeFirst();return d(o,!0)}catch(o){if(o instanceof mi)throw o;if(Wp(o))throw new mi(409,"A payment with this transaction ID already exists");if(o instanceof Error){if(o.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${o.message}`)}throw o}}import{db as fi,mutationCount as Lp,sqlHelpers as jp}from"@stacksjs/database";import{env as zp}from"@stacksjs/env";import{formatDate as wi}from"@stacksjs/orm";async function yi(t,e){if(!await ye(t))return;try{return await fi.updateTable("payments").set({...e,updated_at:wi(new Date)}).where("id","=",t).execute(),await ye(t)}catch(o){if(o instanceof Error){if(o.message.includes("Duplicate entry")&&o.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${o.message}`)}throw o}}var Gp=new Set(["completed","succeeded","partiallyRefunded"]);async function hi(t,e){if(!Number.isSafeInteger(t)||t<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger(e)||e<=0)throw TypeError("Refund amount must be a positive integer in minor units");let o=jp(zp.DB_CONNECTION||"sqlite").param,n=wi(new Date),a=await fi.unsafe(`UPDATE payments
|
|
22
|
+
SET status = CASE WHEN COALESCE(refund_amount, 0) + ${o(1)} = amount THEN 'refunded'
|
|
23
|
+
WHEN 1 = 0 THEN status ELSE 'partiallyRefunded' END,
|
|
24
|
+
refund_amount = COALESCE(refund_amount, 0) + ${o(2)},
|
|
25
25
|
updated_at = ${o(3)}
|
|
26
26
|
WHERE id = ${o(4)}
|
|
27
27
|
AND status IN ('completed', 'succeeded', 'partiallyRefunded')
|
|
28
|
-
AND COALESCE(refund_amount, 0) + ${o(5)} <= amount`,[e,e,n,t,e]);if(Number(s?.numUpdatedRows??s?.[0]?.numUpdatedRows??s?.numAffectedRows??s?.affectedRows??s?.[0]?.affectedRows??s?.changes??0)>0){let f=await ye(t);if(f)return f;throw Error(`Payment with ID ${t} disappeared during refund`)}let u=await ye(t);if(!u)throw Error(`Payment with ID ${t} not found`);let c=String(u.status||"");if(!Ap.has(c))throw Error(`Payment status ${c||"unknown"} cannot be refunded`);let m=u,p=Number(u.amount||0)-Number(m.refundAmount??m.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${p} minor units`)}var jo={};g(jo,{categories:()=>Nt,default:()=>zp,items:()=>Jt,manufacturers:()=>Bt,reviews:()=>Ot,units:()=>Wt,variants:()=>Lt});var Nt={};g(Nt,{bulkRemove:()=>vi,compareCategoryGrowth:()=>Ri,deactivate:()=>Fi,deactivateChildCategories:()=>ki,fetchActive:()=>yi,fetchAll:()=>Bo,fetchByDisplayOrder:()=>bi,fetchById:()=>S,fetchByName:()=>wi,fetchCategoryTree:()=>xi,fetchChildCategories:()=>gi,fetchRootCategories:()=>hi,fetchStats:()=>_i,findOrCreateByName:()=>Ei,remove:()=>Di,removeChildCategories:()=>Pi,store:()=>Oo,update:()=>Si,updateActiveStatus:()=>Ai,updateDisplayOrder:()=>Ci,updateParent:()=>Mi});import{db as He}from"@stacksjs/database";import{db as P}from"@stacksjs/database";import{formatDate as Ke}from"@stacksjs/orm";async function Bo(){return await P.selectFrom("categories").selectAll().execute()}async function S(t){return await P.selectFrom("categories").where("id","=",t).selectAll().executeTakeFirst()}async function wi(t){return await P.selectFrom("categories").where("name","=",t).selectAll().executeTakeFirst()}async function yi(){return await P.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function hi(){return await P.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function gi(t){return await P.selectFrom("categories").where("parent_category_id","=",t).where("is_active","=",!0).selectAll().execute()}async function bi(t=!0){let e=P.selectFrom("categories").where("is_active","=",!0).selectAll();if(t)return await e.orderBy("display_order","asc").execute();else return await e.orderBy("display_order","desc").execute()}async function _i(){let t=await P.selectFrom("categories").select(P.fn.count("id").as("count")).executeTakeFirst(),e=await P.selectFrom("categories").where("is_active","=",!0).select(P.fn.count("id").as("count")).executeTakeFirst(),r=await P.selectFrom("categories").whereNull("parent_category_id").select(P.fn.count("id").as("count")).executeTakeFirst(),o=await P.selectFrom("categories").whereNotNull("image_url").select(P.fn.count("id").as("count")).executeTakeFirst(),n=new Date;n.setDate(n.getDate()-30);let a=Ke(n),s=await P.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await P.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",P.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(t?.count||0),active:Number(e?.count||0),root_categories:Number(r?.count||0),child_categories:Number(t?.count||0)-Number(r?.count||0),with_images:Number(o?.count||0),recently_added:s,top_parent_categories:i.map((u)=>({id:String(u.parent_category_id||""),name:String(u.parent_name||""),child_count:Number(u.child_count)}))}}async function Ri(t=30){let e=new Date,r=Ke(e),o=new Date;o.setDate(e.getDate()-t);let n=Ke(o),a=new Date(o);a.setDate(a.getDate()-1);let s=Ke(a),i=new Date(a);i.setDate(a.getDate()-t);let u=Ke(i),c=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",r).executeTakeFirst(),m=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),p=Number(c?.count||0),f=Number(m?.count||0),y=p-f,b=f!==0?y/f*100:p>0?100:0;return{current_period:p,previous_period:f,difference:y,percentage_change:b,days_range:t}}async function xi(){let t=await Bo(),e=new Map;t.forEach((n)=>{e.set(n.id,{...n,children:[]})});let r=[];t.forEach((n)=>{let a=e.get(n.id);if(n.parent_category_id){let s=e.get(n.parent_category_id);if(s)s.children.push(a)}else r.push(a)}),r.sort((n,a)=>n.display_order-a.display_order);let o=(n)=>{n.sort((a,s)=>a.display_order-s.display_order),n.forEach((a)=>{if(a.children.length>0)o(a.children)})};return o(r),r}async function Di(t){let e=await He.deleteFrom("categories").where("id","=",t).executeTakeFirst();return l(e)>0}async function vi(t){if(!t.length)return 0;let e=await He.deleteFrom("categories").where("id","in",t).executeTakeFirst();return l(e)}async function Pi(t){let e=await He.deleteFrom("categories").where("parent_category_id","=",t).executeTakeFirst();return l(e)}async function Fi(t){if(!await S(t))throw Error(`Category with ID ${t} not found`);return!!await He.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",t).executeTakeFirst()}async function ki(t){let e=await He.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",t).execute();return Number(e)||0}var{randomUUIDv7:Mp}=globalThis.Bun;import{db as Ti}from"@stacksjs/database";import{HttpError as Mt}from"@stacksjs/error-handling";import{isUniqueViolation as Ip}from"@stacksjs/orm";import{slug as Np}from"@stacksjs/strings";async function Oo(t){try{let e=t.parent_category_id?Number(t.parent_category_id):void 0;if(e!==void 0&&(!Number.isSafeInteger(e)||e<=0))throw new Mt(422,"Parent category ID must be a positive integer");if(e&&!await S(e))throw new Mt(422,`Parent category with ID ${t.parent_category_id} not found`);let r={...t,uuid:Mp(),is_active:t.is_active??!0,parent_category_id:t.parent_category_id||null},o=await Ti.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create category");return o}catch(e){if(e instanceof Mt)throw e;if(Ip(e))throw new Mt(409,"A category with this name or slug already exists");if(e instanceof Error)throw Error(`Failed to create category: ${e.message}`);throw e}}async function Ei(t){if(!t.name)throw Error("Name is required");let e=await Ti.selectFrom("categories").selectAll().where("name","=",t.name).executeTakeFirst();if(e)return e;let r={name:t.name,slug:Np(t.name),is_active:t.is_active??!0,display_order:0};return await Oo(r)}import{db as Qe}from"@stacksjs/database";import{HttpError as ke}from"@stacksjs/error-handling";import{formatDate as It,isUniqueViolation as Jp}from"@stacksjs/orm";async function Si(t,e){if(!await S(t))return;if(Object.hasOwn(e,"parent_category_id")){let o=e.parent_category_id?Number(e.parent_category_id):void 0;if(o!==void 0&&(!Number.isSafeInteger(o)||o<=0))throw new ke(422,"Parent category ID must be a positive integer");if(o===t)throw new ke(422,"A category cannot be its own parent");if(o&&!await S(o))throw new ke(422,`Parent category with ID ${e.parent_category_id} not found`);if(o&&await Ii(t,String(o)))throw new ke(422,"This operation would create a circular category hierarchy")}try{let o=Object.hasOwn(e,"parent_category_id")?{parent_category_id:e.parent_category_id||null}:{},n=await Qe.updateTable("categories").set({...e,...o,updated_at:It(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return n}catch(o){if(o instanceof ke)throw o;if(Jp(o))throw new ke(409,"A category with this name or slug already exists");if(o instanceof Error)throw Error(`Failed to update category: ${o.message}`);throw o}}async function Ci(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);try{return await Qe.updateTable("categories").set({display_order:e,updated_at:It(new Date)}).where("id","=",t).execute(),await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category display order: ${o.message}`);throw o}}async function Ai(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);try{return await Qe.updateTable("categories").set({is_active:e,updated_at:It(new Date)}).where("id","=",t).execute(),await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category active status: ${o.message}`);throw o}}async function Mi(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);if(e){let o=Number(e);if(o===t)throw Error("A category cannot be its own parent");if(!await S(o))throw Error(`Parent category with ID ${e} not found`);if(await Ii(t,e))throw Error("This operation would create a circular reference in the category hierarchy")}try{let o={updated_at:It(new Date)};if(e===null)await Qe.updateTable("categories").set({...o,parent_category_id:null}).where("id","=",t).execute();else await Qe.updateTable("categories").set({...o,parent_category_id:e}).where("id","=",t).execute();return await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category parent: ${o.message}`);throw o}}async function Ii(t,e){let r=Number(e),o=new Set;while(r){if(o.has(r))return!0;if(r===t)return!0;o.add(r);let n=await S(r),a=n?.parent_category_id;if(!n||!a)return!1;r=Number(a)}return!1}var Jt={};g(Jt,{bulkDestroy:()=>Bi,bulkStore:()=>zi,destroy:()=>Ji,fetchAll:()=>Oi,fetchById:()=>ee,fetchTopProducts:()=>$i,store:()=>ji,update:()=>Gi,updateAvailability:()=>Vi,updateInventory:()=>qi});import{db as Ni}from"@stacksjs/database";async function Ji(t){try{let e=await Ni.deleteFrom("products").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product item: ${e.message}`);throw e}}async function Bi(t){if(!t.length)return 0;try{let e=await Ni.deleteFrom("products").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product items: ${e.message}`);throw e}}import{db as X,sql as Bp}from"@stacksjs/database";async function ee(t){let e=await X.selectFrom("products").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.manufacturer_id)r=await X.selectFrom("manufacturers").where("id","=",e.manufacturer_id).selectAll().executeTakeFirst();if(e.category_id)o=await X.selectFrom("categories").where("id","=",e.category_id).selectAll().executeTakeFirst();return{...e,manufacturer:r,category:o}}return}async function Oi(){let t=await X.selectFrom("products").selectAll().execute(),e=t.map((c)=>c.manufacturer_id).filter((c)=>c!==null&&c!==void 0),r=t.map((c)=>c.category_id).filter((c)=>c!==null&&c!==void 0),o=X.selectFrom("manufacturers"),n=X.selectFrom("categories");if(e.length>0)o=o.where("id","in",e);if(r.length>0)n=n.where("id","in",r);let a=await o.selectAll().execute(),s=await n.selectAll().execute(),i=a.reduce((c,m)=>(c[m.id]=m,c),{}),u=s.reduce((c,m)=>(c[m.id]=m,c),{});return t.map((c)=>({...c,manufacturer:c.manufacturer_id?i[c.manufacturer_id]:null,category:c.category_id?u[c.category_id]:null}))}async function Ui(t){try{let e=await X.selectFrom("products").selectAll().where("uuid","=",t).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get product by UUID: ${e.message}`);throw e}}async function $i(t=5){try{return(await X.selectFrom("order_items").innerJoin("products","products.id","=","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",X.fn.sum("order_items.quantity").as("units_sold"),Bp`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(t).execute()).map((r)=>({id:Number(r.id),name:String(r.name??"Unnamed product"),units_sold:Number(r.units_sold??0),revenue:Number(r.revenue??0),inventory_count:Number(r.inventory_count??0)}))}catch(e){if(e instanceof Error)throw TypeError(`Failed to fetch top products: ${e.message}`);throw e}}var{randomUUIDv7:Wi}=globalThis.Bun;import{db as Li}from"@stacksjs/database";async function ji(t){try{let e={...t,uuid:Wi()},r=await Li.insertInto("products").values(e).executeTakeFirst();if(!r)throw Error("Failed to create product item");let o=K(r),n=o!==void 0?await ee(o):await Ui(e.uuid);if(!n)throw Error("Failed to create product item");return n}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product item: ${e.message}`);throw e}}async function zi(t){if(!t.length)return 0;let e=0;try{return await Li.transaction(async(r)=>{for(let o of t){let n={...o,uuid:Wi()};await r.insertInto("products").values(n).execute(),e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product items in bulk: ${r.message}`);throw r}}import{db as Uo}from"@stacksjs/database";import{formatDate as $o}from"@stacksjs/orm";async function Gi(t,e){try{if(!t)throw Error("Product item ID is required for update");let r=await Uo.updateTable("products").set({...e,updated_at:$o(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function Vi(t,e){if(!await ee(t))throw Error(`Product item with ID ${t} not found`);try{return await Uo.updateTable("products").set({is_available:e,updated_at:$o(new Date)}).where("id","=",t).execute(),await ee(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update product item availability: ${o.message}`);throw o}}async function qi(t,e){let r=await ee(t);if(!r)throw Error(`Product item with ID ${t} not found`);let o={updated_at:$o(new Date)};if(e!==void 0)o.inventory_count=e;if(Object.keys(o).length===1)return r;try{return await Uo.updateTable("products").set(o).where("id","=",t).execute(),await ee(t)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update inventory information: ${n.message}`);throw n}}var Bt={};g(Bt,{bulkDestroy:()=>Hi,bulkStore:()=>iu,destroy:()=>Ki,fetchAll:()=>Qi,fetchByCountry:()=>tu,fetchById:()=>Yi,fetchByUuid:()=>Xi,fetchFeatured:()=>eu,fetchWithProductCount:()=>ru,store:()=>su,update:()=>cu,updateByUuid:()=>lu,updateFeaturedStatus:()=>du});import{db as Zi}from"@stacksjs/database";async function Ki(t){try{let e=await Zi.deleteFrom("manufacturers").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete order: ${e.message}`);throw e}}async function Hi(t){if(!t.length)return 0;try{let e=await Zi.deleteFrom("manufacturers").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete orders: ${e.message}`);throw e}}import{db as te}from"@stacksjs/database";async function Qi(){return w(await te.selectFrom("manufacturers").selectAll().execute())}async function Yi(t){let e=await te.selectFrom("manufacturers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Xi(t){let e=await te.selectFrom("manufacturers").where("uuid","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function eu(t=10){let e=await te.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(t).execute();return w(e)}async function tu(t,e={}){let r=e.page||1,o=e.limit||2,n=await te.selectFrom("manufacturers").select(te.fn.count("id").as("total")).where("country","=",t).executeTakeFirst(),a=Number(n?.total||0),s=await te.selectFrom("manufacturers").selectAll().where("country","=",t).limit(o).offset((r-1)*o).execute(),i=Math.ceil(a/o);return{data:w(s),paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function ru(t={}){let e=te.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(t.country)e=e.where("m.country","=",t.country);if(t.featured!==void 0)e=e.where("m.featured","=",t.featured);return e=e.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",te.fn.count("p.id").as("product_count")]).groupBy("m.id"),e.execute()}var{randomUUIDv7:nu}=globalThis.Bun;import{db as au}from"@stacksjs/database";import{HttpError as ou}from"@stacksjs/error-handling";import{isUniqueViolation as Op}from"@stacksjs/orm";async function su(t){try{let e={...t,uuid:nu(),featured:t.featured??!1},r=await au.insertInto("manufacturers").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return d(r)}catch(e){if(e instanceof ou)throw e;if(Op(e))throw new ou(409,"A manufacturer with this name already exists");if(e instanceof Error)throw Error(`Failed to create manufacturer: ${e.message}`);throw e}}async function iu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:nu(),featured:r.featured??!1};await au.insertInto("manufacturers").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${r.message}`);throw r}}import{db as Wo}from"@stacksjs/database";import{HttpError as uu}from"@stacksjs/error-handling";import{formatDate as Lo,isUniqueViolation as Up}from"@stacksjs/orm";async function cu(t,e){try{if(!t)throw Error("Manufacturer ID is required for update");let r=await Wo.updateTable("manufacturers").set({...e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof uu)throw r;if(Up(r))throw new uu(409,"A manufacturer with this name already exists");if(r instanceof Error)throw Error(`Failed to update manufacturer: ${r.message}`);throw r}}async function du(t,e){try{let r=await Wo.updateTable("manufacturers").set({featured:e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function lu(t,e){try{let r=await Wo.updateTable("manufacturers").set({...e,updated_at:Lo(new Date)}).where("uuid","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var Ot={};g(Ot,{bulkDestroy:()=>fu,destroy:()=>pu,fetchAll:()=>yu,fetchApprovedByProductId:()=>bu,fetchById:()=>wu,fetchByProductId:()=>hu,fetchByUserId:()=>gu,fetchMostHelpfulByProductId:()=>_u,fetchStats:()=>vu,fetchStatsByProductIds:()=>Pu,store:()=>Fu,update:()=>Eu,updateVotes:()=>Su});import{db as mu}from"@stacksjs/database";async function pu(t){try{let e=await mu.deleteFrom("reviews").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete review: ${e.message}`);throw e}}async function fu(t){if(!t.length)return 0;try{let e=await mu.deleteFrom("reviews").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete reviews: ${e.message}`);throw e}}import{db as Te}from"@stacksjs/database";async function wu(t){return d(await Te.selectFrom("reviews").where("id","=",t).selectAll().executeTakeFirst(),!0)}async function yu(){return w(await Te.selectFrom("reviews").selectAll().execute())}async function hu(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).selectAll().execute())}async function gu(t){return w(await Te.selectFrom("reviews").where("customer_id","=",t).selectAll().execute())}async function bu(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).where("is_approved","=",!0).selectAll().execute())}async function _u(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).orderBy("helpful_votes","desc").selectAll().execute())}import{db as Ru}from"@stacksjs/database";function xu(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function Du(t){let e=xu();e.total=t.length;let r=0;for(let o of t){if(o.rating===null||o.rating===void 0){e.commentsOnly++;continue}let n=Number(o.rating);if(Number.isNaN(n)){e.commentsOnly++;continue}e.rated++,r+=n;let a=Math.min(5,Math.max(1,Math.round(n)));e.distribution[a]++}if(e.rated>0)e.average=Math.round(r/e.rated*10)/10;return e}async function vu(t){let e=await Ru.selectFrom("reviews").select(["rating"]).where("product_id","=",t).where("is_approved","=",!0).execute();return Du(e)}async function Pu(t){let e=new Map;for(let n of t)e.set(n,xu());if(t.length===0)return e;let r=await Ru.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",t).where("is_approved","=",!0).execute(),o=new Map;for(let n of r){let a=o.get(n.product_id);if(a)a.push({rating:n.rating});else o.set(n.product_id,[{rating:n.rating}])}for(let[n,a]of o)e.set(n,Du(a));return e}var{randomUUIDv7:$p}=globalThis.Bun;import{db as Wp}from"@stacksjs/database";function Lp(t){let e=t.rating!==void 0&&t.rating!==null,r=typeof t.content==="string"&&t.content.trim().length>0,o=typeof t.title==="string"&&t.title.trim().length>0;return!e&&!r&&!o}async function Fu(t){try{if(Lp(t))throw Error("A review needs a rating or something written: both were empty");let e={...t,uuid:$p(),rating:t.rating??null,is_verified_purchase:t.is_verified_purchase??!1,is_approved:t.is_approved??!1,helpful_votes:t.helpful_votes??0,unhelpful_votes:t.unhelpful_votes??0,is_featured:t.is_featured??!1},r=await Wp.insertInto("reviews").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return d(r)}catch(e){if(e instanceof Error){if(e.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${e.message}`)}throw e}}import{db as ku}from"@stacksjs/database";import{formatDate as Tu}from"@stacksjs/orm";async function Eu(t,e){try{if(!t)throw Error("Review ID is required for update");let r=await ku.updateTable("reviews").set({...e,updated_at:Tu(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function Su(t,e,r=!0){try{let o=e==="helpful"?"helpful_votes":"unhelpful_votes",n=r?`COALESCE("${o}", 0) + 1`:`MAX(COALESCE("${o}", 0) - 1, 0)`,a=await ku.unsafe(`UPDATE "reviews" SET "${o}" = ${n}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[Tu(new Date),t]).execute(),s=Array.isArray(a)?a[0]:a;if(!s)throw Error("Failed to update review votes");return d(s)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update review votes: ${o.message}`);throw o}}var Wt={};g(Wt,{bulkDestroy:()=>Mu,bulkStore:()=>Uu,bulkUpdate:()=>ju,destroy:()=>Au,fetchAll:()=>Ju,fetchById:()=>Nu,formatUnitOptions:()=>$u,getDefaultUnit:()=>Wu,store:()=>Ou,update:()=>Lu,updateDefaultStatus:()=>zu});import{db as Cu}from"@stacksjs/database";async function Au(t){try{let e=await Cu.deleteFrom("product_units").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product unit: ${e.message}`);throw e}}async function Mu(t){if(!t.length)return 0;try{let e=await Cu.deleteFrom("product_units").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product units: ${e.message}`);throw e}}import{db as Iu}from"@stacksjs/database";async function Nu(t){let e=await Iu.selectFrom("product_units").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Ju(){return w(await Iu.selectFrom("product_units").selectAll().execute())}var{randomUUIDv7:Bu}=globalThis.Bun;import{db as Ye}from"@stacksjs/database";async function Ou(t){try{return await Ye.transaction(async(e)=>{let r={...t,uuid:Bu()},o=await e.insertInto("product_units").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create product unit");if(r.is_default&&r.type)await e.updateTable("product_units").set({is_default:!1}).where("type","=",r.type).where("id","!=",o.id).execute();return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product unit: ${e.message}`);throw e}}async function Uu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:Bu()},n=await Ye.insertInto("product_units").values(o).returningAll().executeTakeFirst();if(o.is_default&&o.type&&n)await Ye.updateTable("product_units").set({is_default:!1}).where("type","=",o.type).where("id","!=",n.id).execute();e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product units in bulk: ${r.message}`);throw r}}function $u(t){try{let e=Ye.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(t)e=e.where("type","=",t);return e=e.orderBy("name"),e.execute().then((r)=>r.map((o)=>({id:String(o.id),name:o.name,abbreviation:o.abbreviation,is_default:o.is_default})))}catch(e){if(e instanceof Error)throw TypeError(`Failed to format unit options: ${e.message}`);throw e}}async function Wu(t){try{let e=await Ye.selectFrom("product_units").selectAll().where("type","=",t).where("is_default","=",!0).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get default unit: ${e.message}`);throw e}}import{db as Ut}from"@stacksjs/database";import{formatDate as $t}from"@stacksjs/orm";async function Lu(t,e){try{if(!t)throw Error("Product unit ID is required for update");return await Ut.transaction(async(r)=>{let o=await r.selectFrom("product_units").select(["type","is_default"]).where("id","=",t).executeTakeFirst();if(!o)return;let n=e.type??o.type;if((e.is_default??Boolean(o.is_default))&&n)await r.updateTable("product_units").set({is_default:!1,updated_at:$t(new Date)}).where("type","=",n).where("id","!=",t).execute();let s=await r.updateTable("product_units").set({...e,updated_at:$t(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function ju(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o=r;if(!o.id)continue;let n=o.data&&typeof o.data==="object"?o.data:{...o};delete n.id;let a=await Ut.updateTable("product_units").set({...n,updated_at:$t(new Date)}).where("id","=",o.id).executeTakeFirst(),s=n;if(s.is_default===!0&&s.type)await Ut.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",o.id).execute();if(Number(a.numUpdatedRows)>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product units in bulk: ${r.message}`);throw r}}async function zu(t,e){try{return await Ut.transaction(async(r)=>{let o=await r.selectFrom("product_units").select("type").where("id","=",t).executeTakeFirst();if(!o)return!1;let n=$t(new Date);if(e&&o.type)await r.updateTable("product_units").set({is_default:!1,updated_at:n}).where("type","=",o.type).where("id","!=",t).execute();return await r.updateTable("product_units").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit default status: ${r.message}`);throw r}}var Lt={};g(Lt,{bulkDestroy:()=>qu,bulkStore:()=>ec,bulkUpdate:()=>sc,destroy:()=>Vu,fetchAll:()=>Hu,fetchById:()=>Ku,formatVariantOptions:()=>tc,generateVariantCombinations:()=>rc,store:()=>Xu,update:()=>ac});import{db as Gu}from"@stacksjs/database";async function Vu(t){try{let e=await Gu.deleteFrom("product_variants").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variant: ${e.message}`);throw e}}async function qu(t){if(!t.length)return 0;try{let e=await Gu.deleteFrom("product_variants").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variants: ${e.message}`);throw e}}import{db as Zu}from"@stacksjs/database";async function Ku(t){let e=await Zu.selectFrom("product_variants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Hu(){return w(await Zu.selectFrom("product_variants").selectAll().execute())}var{randomUUIDv7:Qu}=globalThis.Bun;import{db as Yu}from"@stacksjs/database";async function Xu(t){try{let e={...t,uuid:Qu()},r=await Yu.insertInto("product_variants").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return d(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product variant: ${e.message}`);throw e}}async function ec(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:Qu()};await Yu.insertInto("product_variants").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${r.message}`);throw r}}function tc(t){if(!t||!t.length)return JSON.stringify([]);let e=t.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(e)}function rc(t){let e=Object.keys(t);if(!e.length)return[];function r(o,n){if(o===e.length)return[n];let a=e[o],s=t[a]??[],i=[];for(let u of s){let c={...n,[a]:u};i.push(...r(o+1,c))}return i}return r(0,{})}import{db as oc}from"@stacksjs/database";import{formatDate as nc}from"@stacksjs/orm";async function ac(t,e){try{let r=await oc.updateTable("product_variants").set({...e,updated_at:nc(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function sc(t){if(!t.length)return 0;let e=0;try{for(let r of t){if(!r.id)continue;let o=await oc.updateTable("product_variants").set({...r,updated_at:nc(new Date)}).where("id","=",r.id).executeTakeFirst();if(Number(o.numUpdatedRows)>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var jp={categories:Nt,items:Jt,manufacturers:Bt,reviews:Ot,units:Wt,variants:Lt},zp=jp;var Ko={};g(Ko,{bulkDestroy:()=>cc,bulkStore:()=>gc,destroy:()=>uc,fetchAll:()=>dc,fetchById:()=>Ee,fetchPageStats:()=>pc,fetchPrintJobStats:()=>lc,fetchPrintTimeStats:()=>fc,fetchPrintsPerHour:()=>wc,fetchSuccessRate:()=>mc,store:()=>hc,update:()=>bc,updatePrintJob:()=>Rc,updateStatus:()=>_c});import{db as ic}from"@stacksjs/database";async function uc(t){try{let e=await ic.deleteFrom("receipts").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print log: ${e.message}`);throw e}}async function cc(t){if(!t.length)return 0;try{let e=await ic.deleteFrom("receipts").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete receipts: ${e.message}`);throw e}}import{db as zo}from"@stacksjs/database";import{formatDate as Gp}from"@stacksjs/orm";function j(t){return Gp(t)}function Vp(t){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t==="number"){let o=new Date(t<=2147483647?t*1000:t);return Number.isNaN(o.getTime())?null:o}let e=String(t||"").trim();if(!e)return null;if(/^\d{10}$/.test(e)){let o=new Date(Number(e)*1000);return Number.isNaN(o.getTime())?null:o}let r=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(r.getTime())?null:r}async function Ee(t){let e=await zo.selectFrom("receipts").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function dc(){return w(await zo.selectFrom("receipts").selectAll().execute())}async function lc(t,e){let r=j(t),o=j(e),n=await J("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{total:n.total,success:n.success,failed:n.failed,warning:n.warning,averageSize:Math.round(n.averageSize),averagePages:Math.round(n.averagePages),averageDuration:Math.round(n.averageDuration)}}async function mc(t,e){let r=j(t),o=j(e),n=await J("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(s)=>s.where("timestamp",">=",r).where("timestamp","<=",o));return{successRate:n.total>0?Math.round(n.success/n.total*100):0,total:n.total,success:n.success,failed:n.failed,warning:n.warning}}async function pc(t,e){let r=j(t),o=j(e),n=await J("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{totalPages:n.totalPages,averagePagesPerReceipt:Math.round(n.averagePagesPerReceipt),totalReceipts:n.totalReceipts}}async function fc(t,e){let r=j(t),o=j(e),n=await J("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{averageDuration:Math.round(n.averageDuration),minDuration:n.minDuration,maxDuration:n.maxDuration,totalJobs:n.totalJobs}}async function wc(t,e){let r=typeof t==="number"?t:t.getTime(),o=typeof e==="number"?e:e.getTime(),n=j(t),a=j(e),s=await zo.selectFrom("receipts").where("timestamp",">=",n).where("timestamp","<=",a).selectAll().execute(),i=s.length,u=Math.ceil((o-r)/3600000),c=u>0?Math.round(i/u):0,m=Array.from({length:24},(p,f)=>({hour:f,count:0}));return s.forEach((p)=>{let f=Vp(p.timestamp);if(!f)return;m[f.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:m}}var{randomUUIDv7:yc}=globalThis.Bun;import{db as Vo}from"@stacksjs/database";import{formatDate as Go}from"@stacksjs/orm";function Xe(t){try{if(typeof t==="number")return Go(t<=2147483647?t*1000:t);if(typeof t==="string"&&/^\d{10}$/.test(t))return Go(Number(t)*1000);return Go(t)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function hc(t){try{let e=yc(),r={...t,timestamp:Xe(t.timestamp),uuid:e};await Vo.insertInto("receipts").values(r).executeTakeFirst();let o=await Vo.selectFrom("receipts").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create receipt");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipt: ${e.message}`);throw e}}async function gc(t){if(!t.length)return 0;try{let e=t.map((n)=>({...n,timestamp:Xe(n.timestamp),uuid:yc()})),o=await Vo.insertInto("receipts").values(e).executeTakeFirst()??{};return Number(o.numInsertedOrUpdatedRows??o.numAffectedRows??o.affectedRows??o.changes??0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${e.message}`);throw e}}import{db as qo}from"@stacksjs/database";import{formatDate as Zo}from"@stacksjs/orm";async function bc(t,e){try{if(!t)throw Error("Receipt ID is required for update");let r={...e,...e.timestamp===void 0?{}:{timestamp:Xe(e.timestamp)},updated_at:Zo(new Date)};await qo.updateTable("receipts").set(r).where("id","=",t).execute();let o=await Ee(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function _c(t,e){try{await qo.updateTable("receipts").set({status:e,updated_at:Zo(new Date)}).where("id","=",t).execute();let r=await Ee(t);if(!r)throw Error("Failed to update receipt status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function Rc(t,e,r,o){try{let n={updated_at:Zo(new Date)};if(e!==void 0)n.size=e;if(r!==void 0)n.pages=r;if(o!==void 0)n.duration=o;await qo.updateTable("receipts").set(n).where("id","=",t).execute();let a=await Ee(t);if(!a)throw Error("Failed to update receipt job information");return d(a)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update receipt job information: ${n.message}`);throw n}}var _n={};g(_n,{couriers:()=>Yt,default:()=>hf,digital:()=>Ht,geocoding:()=>rr,licenses:()=>ar,methods:()=>cr,rates:()=>fr,routes:()=>Zt,tracking:()=>xr,zones:()=>Fr});var Zt={};g(Zt,{DeliveryRouteInputError:()=>N,bulkDestroy:()=>vc,destroy:()=>Dc,fetchActive:()=>Fc,fetchAll:()=>Pc,fetchByCourier:()=>kc,fetchById:()=>zt,store:()=>Tc,update:()=>Sc,updateLastActive:()=>Ec,updateMetrics:()=>Ac,updateStops:()=>Cc,validateDeliveryRouteWrite:()=>Se});import{db as xc}from"@stacksjs/database";async function Dc(t){try{let e=await xc.deleteFrom("delivery_routes").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery route: ${e.message}`);throw e}}async function vc(t){if(!t.length)return 0;try{let e=await xc.deleteFrom("delivery_routes").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery routes: ${e.message}`);throw e}}import{db as jt}from"@stacksjs/database";async function zt(t){return await jt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst()}async function Pc(){return await jt.selectFrom("delivery_routes").selectAll().execute()}async function Fc(){return await jt.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function kc(t){return await jt.selectFrom("delivery_routes").where("courier","=",t).selectAll().execute()}var{randomUUIDv7:Kp}=globalThis.Bun;import{db as Ho}from"@stacksjs/database";function he(t,e){let r={};for(let[o,n]of Object.entries(e))for(let a of n){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)continue;r[o]=t[a];break}return r}function et(t){return he(t,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function re(t){return he(t,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function tt(t){return he(t,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function rt(t){return he(t,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function ot(t){return he(t,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function nt(t){return he(t,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function Gt(t){return he(t,{courier:["courier"],courier_id:["courier_id","courierId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as qp}from"@stacksjs/database";class N extends TypeError{constructor(t){super(t);this.name="DeliveryRouteInputError"}}function Vt(t,e,r){return Number(t[r]??e?.[r])}function Zp(t,e){let r=t.last_active??e?.last_active;if(r===void 0||r===null)return Date.now();if(r instanceof Date)return r.getTime();if(typeof r==="number")return r;if(typeof r==="string"&&/^\d{10,13}$/.test(r))return Number(r);return Number.NaN}async function Se(t,e){let r=Vt(t,e,"courier_id"),o=Vt(t,e,"stops"),n=Vt(t,e,"delivery_time"),a=Vt(t,e,"total_distance"),s=Zp(t,e);if(!Number.isSafeInteger(r)||r<1)throw new N("Courier must be a positive integer.");if(!Number.isSafeInteger(o)||o<0)throw new N("Stops must be a non-negative integer.");if(!Number.isSafeInteger(n)||n<0)throw new N("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(a)||a<0)throw new N("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(s)||s<0)throw new N("Last active must be a valid Unix timestamp.");let i=await qp.selectFrom("couriers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new N(`Courier ${r} was not found.`);return{...t,courier_id:Number(i.id),courier:i.name,vehicle:i.vehicle_number,last_active:s}}async function Tc(t){try{let e=Kp(),r=Gt(t),n={...await Se(r),uuid:e};await Ho.insertInto("delivery_routes").values(n).executeTakeFirst();let a=await Ho.selectFrom("delivery_routes").where("uuid","=",e).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(e){if(e instanceof N)throw e;if(e instanceof Error)throw TypeError(`Failed to create delivery route: ${e.message}`);throw e}}async function Ec(t){try{await Ho.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",t).execute();let e=await zt(t);if(!e)throw Error("Failed to update delivery route last active");return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update delivery route last active: ${e.message}`);throw e}}import{db as qt}from"@stacksjs/database";import{formatDate as Qo}from"@stacksjs/orm";async function Sc(t,e){try{if(!t)throw Error("Delivery route ID is required for update");let r=await qt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=Gt(e),n=await Se(o,r),a=await qt.updateTable("delivery_routes").set({...n,updated_at:Qo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof N)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function Cc(t,e){try{let r=await qt.updateTable("delivery_routes").set({stops:e,updated_at:Qo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update delivery route stops");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update delivery route stops: ${r.message}`);throw r}}async function Ac(t,e,r){try{let o={updated_at:Qo(new Date)};if(e!==void 0)o.delivery_time=e;if(r!==void 0)o.total_distance=r;let n=await qt.updateTable("delivery_routes").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update delivery metrics");return n}catch(o){if(o instanceof Error)throw TypeError(`Failed to update delivery metrics: ${o.message}`);throw o}}var Ht={};g(Ht,{bulkDestroy:()=>Nc,bulkSoftDelete:()=>Jc,bulkStore:()=>Lc,destroy:()=>Mc,fetchAll:()=>Uc,fetchById:()=>Oc,softDelete:()=>Ic,store:()=>Wc,update:()=>jc,updateDeliverySettings:()=>Gc,updateStatus:()=>zc});import{db as Kt}from"@stacksjs/database";async function Mc(t){try{let e=await Kt.deleteFrom("digital_deliveries").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital delivery: ${e.message}`);throw e}}async function Ic(t){try{let e=await Kt.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${e.message}`);throw e}}async function Nc(t){if(!t.length)return 0;try{let e=await Kt.deleteFrom("digital_deliveries").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${e.message}`);throw e}}async function Jc(t){if(!t.length)return 0;try{let e=await Kt.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${e.message}`);throw e}}import{db as Bc}from"@stacksjs/database";async function Oc(t){let e=await Bc.selectFrom("digital_deliveries").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Uc(){return w(await Bc.selectFrom("digital_deliveries").selectAll().execute())}var{randomUUIDv7:$c}=globalThis.Bun;import{db as Yo}from"@stacksjs/database";async function Wc(t){try{let e=$c(),r={...rt(t),uuid:e};await Yo.insertInto("digital_deliveries").values(r).executeTakeFirst();let o=await Yo.selectFrom("digital_deliveries").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created digital delivery");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital delivery: ${e.message}`);throw e}}async function Lc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...rt(o),uuid:$c()})),r=await Yo.insertInto("digital_deliveries").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${e.message}`);throw e}}import{db as Xo}from"@stacksjs/database";import{formatDate as en}from"@stacksjs/orm";async function jc(t,e){try{if(!t)throw Error("Digital delivery ID is required for update");let r=await Xo.updateTable("digital_deliveries").set({...rt(e),updated_at:en(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function zc(t,e){try{let r=await Xo.updateTable("digital_deliveries").set({status:e,updated_at:en(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function Gc(t,e,r,o,n){try{let a={updated_at:en(new Date)};if(e!==void 0)a.download_limit=e;if(r!==void 0)a.expiry_days=r;if(o!==void 0)a.requires_login=o;if(n!==void 0)a.automatic_delivery=n;let s=await Xo.updateTable("digital_deliveries").set(a).where("id","=",t).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return d(s)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var Yt={};g(Yt,{bulkDestroy:()=>Hc,bulkStore:()=>Xc,destroy:()=>Kc,fetchAll:()=>qc,fetchById:()=>Qt,store:()=>Yc,update:()=>ed,updateContact:()=>rd,updateStatus:()=>td});import{db as Zc}from"@stacksjs/database";import{db as Vc}from"@stacksjs/database";async function Qt(t){let e=await Vc.selectFrom("couriers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function qc(){return w(await Vc.selectFrom("couriers").selectAll().execute())}async function Kc(t){try{let e=await Zc.deleteFrom("couriers").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete courier: ${e.message}`);throw e}}async function Hc(t){if(!t.length)return 0;let e=0;try{return await Zc.transaction(async(r)=>{for(let o of t)if(await Qt(o))await r.deleteFrom("couriers").where("id","=",o).execute(),e++}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to delete couriers in bulk: ${r.message}`);throw r}}var{randomUUIDv7:Qc}=globalThis.Bun;import{db as tn}from"@stacksjs/database";async function Yc(t){try{let e=Qc(),r={...nt(t),uuid:e};await tn.insertInto("couriers").values(r).executeTakeFirst();let o=await tn.selectFrom("couriers").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created courier");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create courier: ${e.message}`);throw e}}async function Xc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...nt(o),uuid:Qc()})),r=await tn.insertInto("couriers").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create couriers in bulk: ${e.message}`);throw e}}import{db as rn}from"@stacksjs/database";import{formatDate as on}from"@stacksjs/orm";async function ed(t,e){try{if(!t)throw Error("Courier ID is required for update");let r=await rn.updateTable("couriers").set({...nt(e),updated_at:on(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier: ${r.message}`);throw r}}async function td(t,e){try{let r=await rn.updateTable("couriers").set({status:e,updated_at:on(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update courier status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier status: ${r.message}`);throw r}}async function rd(t,e){try{let r={updated_at:on(new Date)};if(e!==void 0)r.phone=e;let o=await rn.updateTable("couriers").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update contact information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var rr={};g(rr,{PRECISION_RANK:()=>st,checkCoverage:()=>tf,formatQuery:()=>Ce,geocode:()=>ef,geocodingDriver:()=>ud,nominatimDriver:()=>tr,setGeocodingDriver:()=>Xp});var ge=(t)=>t*Math.PI/180;function ce(t,e){let r=ge(e.latitude-t.latitude),o=ge(e.longitude-t.longitude),n=ge(t.latitude),a=ge(e.latitude),s=Math.sin(r/2)**2+Math.sin(o/2)**2*Math.cos(n)*Math.cos(a);return 12742017.6*Math.asin(Math.sqrt(s))}function Xt(t,e){let r=ge(t.latitude),o=ge(e.latitude),n=ge(e.longitude-t.longitude),a=Math.sin(n)*Math.cos(o),s=Math.cos(r)*Math.sin(o)-Math.sin(r)*Math.cos(o)*Math.cos(n);return(Math.atan2(a,s)*180/Math.PI+360)%360}function er(t,e,r={}){let o=r.detourFactor??1.35,n=r.minimumSeconds??30;if(!Number.isFinite(e)||e<=0.5)return null;let a=t*o/e;return Math.max(n,Math.round(a))}function od(t,e,r){return ce(t,e)<=r}function at(t){return typeof t?.latitude==="number"&&typeof t?.longitude==="number"&&Number.isFinite(t.latitude)&&Number.isFinite(t.longitude)}var st={unknown:0,locality:1,postal:2,street:3,rooftop:4};function Ce(t){return[t.street,t.city,t.region,t.postalCode,t.country].map((e)=>String(e??"").trim()).filter(Boolean).join(", ")}var Hp="https://nominatim.openstreetmap.org/search",nd=1000,ad=0,sd=Promise.resolve();async function Qp(t){let e=sd.then(async()=>{let r=Date.now()-ad;if(r<nd)await Bun.sleep(nd-r);return ad=Date.now(),t()});return sd=e.then(()=>{return},()=>{return}),e}function Yp(t){let e=t.address??{},r=String(t.addresstype??""),o=String(t.type??""),n=String(t.category??t.class??"");if(e.house_number||o==="house"||o==="building"||r==="building")return"rooftop";if(e.road||n==="highway"||r==="road")return"street";if(r==="postcode"||e.postcode&&!e.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(r))return"locality";return"unknown"}function tr(t={}){let e=t.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,r=t.endpoint??Hp;return{name:"nominatim",async geocode(o){let n=Ce(o);if(!n)return null;let a=new URL(r);if(a.searchParams.set("q",n),a.searchParams.set("format","jsonv2"),a.searchParams.set("limit","1"),a.searchParams.set("addressdetails","1"),o.country)a.searchParams.set("countrycodes",o.country.toLowerCase());let s=await Qp(()=>fetch(a,{headers:{"user-agent":e,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!s.ok)throw Error(`Nominatim responded ${s.status}`);let u=(await s.json())?.[0];if(!u)return null;let c=Number(u.lat),m=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(m))return null;let p=Yp(u);return{latitude:c,longitude:m,formatted:String(u.display_name??n),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[p],precision:p,provider:"nominatim"}}}}var id=null;function Xp(t){id=t}function ud(){return id??tr()}async function ef(t,e={}){let r=e.driver??ud(),o=e.minimumPrecision??"street",n=`geocode:${r.name}:${Ce(t).toLowerCase()}`,a=await rf(n);if(a!==void 0)return a;let s=await r.geocode(t),i=s&&st[s.precision]>=st[o]?s:null;return await of(n,i,i?e.cacheSeconds??2592000:600),i}function tf(t,e,r){if(e.length===0)return null;let o=e[0],n=ce(t,o);for(let a of e.slice(1)){let s=ce(t,a);if(s<n)n=s,o=a}return{covered:n<=r,distanceMeters:Math.round(n),nearest:o}}async function rf(t){try{let r=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!r)return;let o=await r.get(t);if(o===null||o===void 0)return;return o==="null"?null:JSON.parse(String(o))}catch{return}}async function of(t,e,r){try{let n=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!n)return;await n.set(t,e===null?"null":JSON.stringify(e),r)}catch{}}var ar={};g(ar,{LicenseKeyInputError:()=>T,bulkDestroy:()=>ld,bulkSoftDelete:()=>md,bulkStore:()=>_d,destroy:()=>cd,fetchAll:()=>wd,fetchById:()=>fd,softDelete:()=>dd,store:()=>bd,update:()=>Rd,updateExpiration:()=>Dd,updateStatus:()=>xd,validateLicenseKeyWrite:()=>be});import{db as or}from"@stacksjs/database";async function cd(t){try{let e=await or.deleteFrom("license_keys").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license key: ${e.message}`);throw e}}async function dd(t){try{let e=await or.updateTable("license_keys").set({status:"inactive"}).where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license key: ${e.message}`);throw e}}async function ld(t){if(!t.length)return 0;try{let e=await or.deleteFrom("license_keys").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license keys: ${e.message}`);throw e}}async function md(t){if(!t.length)return 0;try{let e=await or.updateTable("license_keys").set({status:"inactive"}).where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license keys: ${e.message}`);throw e}}import{db as pd}from"@stacksjs/database";async function fd(t){let e=await pd.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function wd(){return w(await pd.selectFrom("license_keys").selectAll().execute())}var{randomUUIDv7:gd}=globalThis.Bun;import{db as sn}from"@stacksjs/database";import{db as nn}from"@stacksjs/database";var yd=["Standard License","Premium License","Enterprise License"],hd=["active","inactive","unassigned"];class T extends TypeError{constructor(t){super(t);this.name="LicenseKeyInputError"}}function it(t,e,r){return t[r]!==void 0?t[r]:e?.[r]}function an(t,e,r,o){let n=it(t,e,r);if(n===void 0||n===null||n==="")return null;let a=Number(n);if(!Number.isSafeInteger(a)||a<1)throw new T(`${o} must be a positive integer or null.`);return a}function nf(t){if(typeof t==="number")return t>2147483647?Math.floor(t/1000):t;if(typeof t==="string"&&/^\d{10,13}$/.test(t))return t.length===13?Math.floor(Number(t)/1000):Number(t);if(typeof t==="string"){let e=/^\d{4}-\d{2}-\d{2} \d/.test(t)?`${t.replace(" ","T")}Z`:t;return Math.floor(new Date(e).getTime()/1000)}return Number.NaN}async function be(t,e){let r=String(it(t,e,"key")||"").trim().toUpperCase(),o=String(it(t,e,"template")||""),n=String(it(t,e,"status")||""),a=nf(it(t,e,"expiry_date")),s=an(t,e,"customer_id","Customer"),i=an(t,e,"product_id","Product"),u=an(t,e,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new T("License key must use five groups of four uppercase letters or numbers.");if(!yd.includes(o))throw new T(`Template must be one of: ${yd.join(", ")}.`);if(!hd.includes(n))throw new T(`Status must be one of: ${hd.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new T("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,m,p]=await Promise.all([s?nn.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?nn.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?nn.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new T(`Customer ${s} was not found.`);if(i&&!m)throw new T(`Product ${i} was not found.`);if(u&&!p)throw new T(`Order ${u} was not found.`);if(s&&p?.customer_id&&Number(p.customer_id)!==s)throw new T(`Order ${u} belongs to Customer ${p.customer_id}, not Customer ${s}.`);return{...t,key:r,template:o,expiry_date:a,status:n,customer_id:s,product_id:i,order_id:u}}async function bd(t){try{let e=gd(),r=ot(t),o={...await be(r),uuid:e};await sn.insertInto("license_keys").values(o).executeTakeFirst();let n=await sn.selectFrom("license_keys").where("uuid","=",e).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created license key");return d(n)}catch(e){if(e instanceof T)throw e;if(e instanceof Error){if(e.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${e.message}`)}throw e}}async function _d(t){if(!t.length)return 0;try{let e=await Promise.all(t.map(async(o)=>({...await be(ot(o)),uuid:gd()}))),r=await sn.insertInto("license_keys").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof T)throw e;if(e instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${e.message}`);throw e}}import{db as nr}from"@stacksjs/database";import{formatDate as un}from"@stacksjs/orm";async function Rd(t,e){try{if(!t)throw Error("License key ID is required for update");let r=await nr.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=ot(e),n=await be(o,r),a=await nr.updateTable("license_keys").set({...n,updated_at:un(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return d(a)}catch(r){if(r instanceof T)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function xd(t,e){try{let r=await nr.updateTable("license_keys").set({status:e,updated_at:un(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function Dd(t,e){try{let r={updated_at:un(new Date)};if(e!==void 0)r.expiry_date=e;let o=await nr.updateTable("license_keys").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update expiration information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var cr={};g(cr,{bulkDestroy:()=>Fd,bulkSoftDelete:()=>kd,bulkStore:()=>Cd,destroy:()=>vd,fetchAll:()=>Td,fetchById:()=>ur,formatShippingOptions:()=>Ad,getActiveShippingMethods:()=>Md,softDelete:()=>Pd,store:()=>Sd,update:()=>Id,updatePricing:()=>Jd,updateStatus:()=>Nd});import{db as sr}from"@stacksjs/database";async function vd(t){try{let e=await sr.deleteFrom("shipping_methods").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping method: ${e.message}`);throw e}}async function Pd(t){try{let e=await sr.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${e.message}`);throw e}}async function Fd(t){if(!t.length)return 0;try{let e=await sr.deleteFrom("shipping_methods").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping methods: ${e.message}`);throw e}}async function kd(t){if(!t.length)return 0;try{let e=await sr.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${e.message}`);throw e}}import{db as ir}from"@stacksjs/database";async function ur(t){let e=await ir.selectFrom("shipping_methods").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=await ir.selectFrom("shipping_zones").where("shipping_method_id","=",t).selectAll().execute();return{...e,shippingZones:r}}return}async function Td(){let t=await ir.selectFrom("shipping_methods").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((a)=>a.id))],n=(await ir.selectFrom("shipping_zones").where("shipping_method_id","in",e).selectAll().execute()).reduce((a,s)=>{let i=s.shipping_method_id;if(i!==null&&i!==void 0){if(!a[i])a[i]=[];a[i].push(s)}return a},{});return t.map((a)=>({...a,shipping_zones:n[a.id]||[]}))}var{randomUUIDv7:Ed}=globalThis.Bun;import{db as ut}from"@stacksjs/database";async function Sd(t){try{let e=Ed(),r={...et(t),uuid:e};await ut.insertInto("shipping_methods").values(r).executeTakeFirst();let o=await ut.selectFrom("shipping_methods").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping method");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping method: ${e.message}`);throw e}}async function Cd(t){if(!t.length)return 0;try{let e=t.map((o)=>({...et(o),uuid:Ed()})),r=await ut.insertInto("shipping_methods").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${e.message}`);throw e}}function Ad(){try{return ut.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping options: ${t.message}`);throw t}}async function Md(){try{let t=await ut.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping methods: ${t.message}`);throw t}}import{db as cn}from"@stacksjs/database";import{formatDate as dn}from"@stacksjs/orm";async function Id(t,e){try{if(!t)throw Error("Shipping method ID is required for update");let r=await cn.updateTable("shipping_methods").set({...et(e),updated_at:dn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function Nd(t,e){try{let r=await cn.updateTable("shipping_methods").set({status:e,updated_at:dn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function Jd(t,e,r){try{let o={updated_at:dn(new Date)};if(e!==void 0)o.base_rate=e;if(r!==void 0)o.free_shipping=r;let n=await cn.updateTable("shipping_methods").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update pricing information");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update pricing information: ${o.message}`);throw o}}var fr={};g(fr,{ShippingRateInputError:()=>A,bulkDestroy:()=>Od,bulkStore:()=>tl,bulkUpdate:()=>ol,destroy:()=>Bd,destroyByMethod:()=>$d,destroyByZone:()=>Ud,fetchAll:()=>jd,fetchById:()=>Ld,formatShippingRateOptions:()=>qd,getRateByWeightAndAddress:()=>Gd,getRateByWeightAndZone:()=>ln,getRatesByZone:()=>zd,getShippingRatesByMethod:()=>Zd,resolveZoneForAddress:()=>lr,store:()=>el,update:()=>rl,updateByMethod:()=>al,updateByZone:()=>nl,validateShippingRateWrite:()=>_e,validateZoneMatchesAddress:()=>Vd});import{db as dr}from"@stacksjs/database";async function Bd(t){try{let e=await dr.deleteFrom("shipping_rates").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rate: ${e.message}`);throw e}}async function Od(t){if(!t.length)return 0;try{let e=await dr.deleteFrom("shipping_rates").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates: ${e.message}`);throw e}}async function Ud(t){try{let e=await dr.deleteFrom("shipping_rates").where("shipping_zone_id","=",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${e.message}`);throw e}}async function $d(t){try{let e=await dr.deleteFrom("shipping_rates").where("shipping_method_id","=",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${e.message}`);throw e}}import{db as W}from"@stacksjs/database";async function Ld(t){let e=await W.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.shipping_zone_id)r=await W.selectFrom("shipping_zones").where("id","=",e.shipping_zone_id).selectAll().executeTakeFirst();if(e.shipping_method_id)o=await W.selectFrom("shipping_methods").where("id","=",e.shipping_method_id).selectAll().executeTakeFirst();return{...e,shipping_zone:r,shipping_method:o}}return}async function jd(){let t=await W.selectFrom("shipping_rates").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((i)=>i.shipping_zone_id).filter((i)=>i!==null&&i!==void 0))],r=[...new Set(t.map((i)=>i.shipping_method_id).filter((i)=>i!==null&&i!==void 0))],[o,n]=await Promise.all([e.length?W.selectFrom("shipping_zones").where("id","in",e).selectAll().execute():[],r.length?W.selectFrom("shipping_methods").where("id","in",r).selectAll().execute():[]]),a=o.reduce((i,u)=>(i[u.id]=u,i),{}),s=n.reduce((i,u)=>(i[u.id]=u,i),{});return t.map((i)=>({...i,shipping_zone:i.shipping_zone_id?a[i.shipping_zone_id]:[],shipping_method:i.shipping_method_id?s[i.shipping_method_id]:[]}))}async function zd(t){try{let e=await W.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${e.message}`);throw e}}async function ln(t,e){try{let r=await W.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).where("weight_from","<=",t).where("weight_to",">=",t).executeTakeFirst();return d(r,!0)}catch(r){if(r instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${r.message}`);throw r}}async function lr(t){if(!t?.countryCode)return null;try{let e=await W.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t.countryCode}%`).where("status","=","active").execute();if(e.length===0)return null;let r=null;for(let o of e){let n=1;if(t.region&&o.regions&&Wd(o.regions,t.region))n=2;if(t.postalCode&&o.postal_codes&&Wd(o.postal_codes,t.postalCode))n=3;if(!r||n>r.score)r={id:o.id,score:n}}return r?.id??null}catch{return null}}async function Gd(t,e){let r=await lr(e);if(r==null)return;return ln(t,r)}async function Vd(t,e){return await lr(e)===t}function Wd(t,e){if(!t||!e)return!1;let r=e.trim().toUpperCase();for(let o of t.split(/[,|;]/))if(o.trim().toUpperCase()===r)return!0;return!1}async function qd(){try{return(await W.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((e)=>e.shipping_method_id!==null&&e.shipping_method_id!==void 0&&e.shipping_zone_id!==null&&e.shipping_zone_id!==void 0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping rate options: ${t.message}`);throw t}}async function Zd(t){try{let e=await W.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${e.message}`);throw e}}var{randomUUIDv7:Xd}=globalThis.Bun;import{db as mn}from"@stacksjs/database";import{db as ct}from"@stacksjs/database";async function Kd(){return w(await ct.selectFrom("shipping_zones").selectAll().execute())}async function mr(t){let e=await ct.selectFrom("shipping_zones").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}function Hd(){try{return ct.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping zone options: ${t.message}`);throw t}}async function Qd(){try{let t=await ct.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping zones: ${t.message}`);throw t}}async function Yd(t){try{let e=await ct.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t}%`).where("status","=","active").orderBy("name").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${e.message}`);throw e}}class A extends TypeError{constructor(t){super(t);this.name="ShippingRateInputError"}}function dt(t,e,r){return Number(t[r]??e?.[r])}async function _e(t,e){let r=dt(t,e,"shipping_method_id"),o=dt(t,e,"shipping_zone_id"),n=dt(t,e,"weight_from"),a=dt(t,e,"weight_to"),s=dt(t,e,"rate");if(!Number.isSafeInteger(r)||r<1)throw new A("Shipping method must be a positive integer.");if(!Number.isSafeInteger(o)||o<1)throw new A("Shipping zone must be a positive integer.");if(!Number.isFinite(n)||n<0)throw new A("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<n)throw new A("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new A("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([ur(r),mr(o)]);if(!i)throw new A(`Shipping method ${r} was not found.`);if(!u)throw new A(`Shipping zone ${o} was not found.`);if(Number(u.shipping_method_id)!==r)throw new A(`Shipping zone ${o} is not assigned to shipping method ${r}.`)}async function el(t){try{let e=re(t),r=Number(e.shipping_method_id),o=Number(e.shipping_zone_id);await _e(e);let n=Xd(),a={...e,shipping_method_id:r,shipping_zone_id:o,uuid:n};await mn.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await mn.selectFrom("shipping_rates").where("uuid","=",n).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return d(s)}catch(e){if(e instanceof A)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rate: ${e.message}`);throw e}}async function tl(t){if(!t.length)return 0;try{for(let o of t){let n=re(o);await _e(n)}let e=t.map((o)=>({...re(o),uuid:Xd()})),r=await mn.insertInto("shipping_rates").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof A)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${e.message}`);throw e}}import{db as lt}from"@stacksjs/database";import{formatDate as pr}from"@stacksjs/orm";async function rl(t,e){try{if(!t)throw Error("Shipping rate ID is required for update");let r=await lt.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=re(e);await _e(o,r);let n=await lt.updateTable("shipping_rates").set({...o,updated_at:pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return d(n)}catch(r){if(r instanceof A)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function ol(t){if(!t.length)return 0;try{let e=0;for(let{id:r,data:o}of t){let n=await lt.updateTable("shipping_rates").set({...re(o),updated_at:pr(new Date)}).where("id","=",r).executeTakeFirst();if(l(n)>0)e++}return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${e.message}`);throw e}}async function nl(t,e){try{let r=await lt.updateTable("shipping_rates").set({...re(e),updated_at:pr(new Date)}).where("shipping_zone_id","=",t).executeTakeFirst();return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function al(t,e){try{let r=await lt.updateTable("shipping_rates").set({...re(e),updated_at:pr(new Date)}).where("shipping_method_id","=",t).executeTakeFirst();return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var xr={};g(xr,{ARRIVAL_RADIUS_METERS:()=>wn,NEARBY_RADIUS_METERS:()=>fn,assignStop:()=>il,bearingInDegrees:()=>Xt,broadcastToChannel:()=>oe,completeStop:()=>cl,distanceInMeters:()=>ce,emitDeliveryArrived:()=>br,emitDeliveryAssigned:()=>yr,emitDeliveryCompleted:()=>_r,emitDeliveryFailed:()=>Rr,emitDeliveryNearby:()=>gr,emitDeliveryPosition:()=>wr,emitDeliveryStarted:()=>hr,estimateSecondsRemaining:()=>er,failStop:()=>dl,hasCoordinates:()=>at,isWithin:()=>od,orderTrackingChannel:()=>de,recordCourierPing:()=>sl,routeTrackingChannel:()=>pn,startRoute:()=>ll,startStop:()=>ul});function de(t){return`order.${t}`}function pn(t){return`delivery-route.${t}`}async function Ae(t,e){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let o=r.dispatch;if(typeof o!=="function")return;o(t,e)}catch{}}async function oe(t,e,r){try{let o=await import("@stacksjs/realtime").catch(()=>null);if(!o)return;let n=o.channel;if(typeof n!=="function")return;await n(t).broadcast(e,r,"private")}catch{}}async function wr(t,e,r){await Promise.all([...t.map((o)=>oe(de(o),"delivery:position",r)),e==null?Promise.resolve():oe(pn(e),"delivery:position",r)])}async function yr(t){if(await Ae("delivery:assigned",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:assigned",{stop:t})}async function hr(t){if(await Ae("delivery:started",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:started",{stop:t})}async function gr(t,e,r){if(await Ae("delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r}),t.order_id!=null)await oe(de(t.order_id),"delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r})}async function br(t){if(await Ae("delivery:arrived",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:arrived",{stop:t})}async function _r(t){if(await Ae("delivery:completed",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:completed",{stop:t})}async function Rr(t,e){await Ae("delivery:failed",{stop:t,reason:e})}var{randomUUIDv7:af}=globalThis.Bun;import{db as ne}from"@stacksjs/database";var fn=400,wn=60,sf=250;async function sl(t){let e=t.recordedAt??new Date().toISOString(),r=typeof t.accuracy!=="number"||t.accuracy<=sf,o=await ne.selectFrom("couriers").where("id","=",t.courierId).select(["id","latitude","longitude"]).executeTakeFirst();if(!o)throw Error(`Unknown courier: ${t.courierId}`);let n=at(o)?{latitude:o.latitude,longitude:o.longitude}:null,a=typeof t.heading==="number"?t.heading:n?Xt(n,t):null,s=await uf(t.courierId),i=s?await cf(s.id):null,u=null,c=null,m=!1,p=!1,f=i&&at({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&f)u=Math.round(ce(t,f)),c=er(u,t.speed??0),p=u<=wn&&i.arrived_at==null,m=!p&&u<=fn&&i.status==="en_route"&&i.notified_nearby_at==null;let y=await df({courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e});if(r)await ne.updateTable("couriers").set({latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??0,last_ping_at:e}).where("id","=",t.courierId).execute();if(i&&(u!=null||c!=null))await ne.updateTable("delivery_stops").set({eta_at:c==null?i.eta_at:new Date(Date.now()+c*1000).toISOString()}).where("id","=",i.id).execute();if(r)await wr(i?.order_id==null?[]:[i.order_id],s?.id??null,{courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e,distanceToStopMeters:u,etaSeconds:c});if(m&&i)await ne.updateTable("delivery_stops").set({notified_nearby_at:e}).where("id","=",i.id).execute(),await gr(i,u,c);if(p&&i)await ne.updateTable("delivery_stops").set({status:"arrived",arrived_at:e}).where("id","=",i.id).execute(),await br({...i,status:"arrived",arrived_at:e});return{pingId:y,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:m,crossedArrival:p}}async function uf(t){return await ne.selectFrom("delivery_routes").where("courier_id","=",t).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function cf(t){let e=await ne.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return e.find((r)=>r.status==="en_route")??e.find((r)=>r.status==="arrived")??e[0]??null}async function df(t){let e=af();return await ne.insertInto("courier_pings").values({uuid:e,courier_id:t.courierId,delivery_route_id:t.routeId,latitude:t.latitude,longitude:t.longitude,heading:t.heading,speed:t.speed??0,accuracy:t.accuracy,recorded_at:t.recordedAt}).executeTakeFirst(),(await ne.selectFrom("courier_pings").where("uuid","=",e).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:lf}=globalThis.Bun;import{db as M}from"@stacksjs/database";function yn(t){return t.type==="pickup"}async function il(t){let e=lf(),r=t.sequence??await pf(t.deliveryRouteId);await M.insertInto("delivery_stops").values({uuid:e,delivery_route_id:t.deliveryRouteId,order_id:t.orderId??null,sequence:r,status:"pending",address:t.address,latitude:t.latitude??null,longitude:t.longitude??null,recipient_name:t.recipientName??null,recipient_phone:t.recipientPhone??null,eta_at:t.etaAt??null,type:t.type??"dropoff"}).executeTakeFirst();let o=await wf(e);if(o)await yr(o);return o??{}}async function ul(t){await M.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",t).execute();let e=await gn(t);if(!e)return null;if(e.order_id!=null&&!yn(e))await hn(e.order_id,"OUT_FOR_DELIVERY");return await hr(e),e}async function cl(t,e){let r=new Date().toISOString();await M.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await ff(t)?{}:{arrived_at:r},...e?{notes:e}:{}}).where("id","=",t).execute();let o=await gn(t);if(!o)return null;if(o.order_id!=null)await hn(o.order_id,yn(o)?"OUT_FOR_DELIVERY":"DELIVERED");return await _r(o),await ml(o.delivery_route_id),o}async function dl(t,e){await M.updateTable("delivery_stops").set({status:"failed",notes:e}).where("id","=",t).execute();let r=await gn(t);if(!r)return null;if(r.order_id!=null&&!yn(r))await hn(r.order_id,"SHIPPED");return await Rr(r,e),await ml(r.delivery_route_id),r}async function ll(t){await M.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",t).execute()}async function ml(t){if(t==null)return;if(await M.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await M.selectFrom("delivery_routes").where("id","=",t).select(["courier_id"]).executeTakeFirst();if(await M.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",t).execute(),r?.courier_id!=null)await M.updateTable("couriers").set({status:"active"}).where("id","=",r.courier_id).execute()}async function hn(t,e){let r=await M.selectFrom("orders").where("id","=",t).select(["id","status"]).executeTakeFirst();if(!r)return;let o=await Promise.resolve().then(() => (Fe(),{}));let s=mf(r.status,e,ve);if(s.length===0){let{log:i}=await import("@stacksjs/logging").catch(()=>({log:null}));i?.warn(`[delivery] refused to move order ${t} from ${r.status} to ${e}: no legal transition`);return}for(let i of s)await M.updateTable("orders").set({status:i}).where("id","=",t).execute(),await Pe(i,{...r,status:i})}function mf(t,e,r){if(t===e)return[];if(r(t,e))return[e];for(let o of["PROCESSING","SHIPPED"]){if(o===t||o===e)continue;if(r(t,o)&&r(o,e))return[o,e]}return[]}async function pf(t){return(await M.selectFrom("delivery_stops").where("delivery_route_id","=",t).select(["sequence"]).execute()).reduce((r,o)=>Math.max(r,o.sequence??0),0)+1}async function ff(t){return(await M.selectFrom("delivery_stops").where("id","=",t).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function gn(t){return await M.selectFrom("delivery_stops").where("id","=",t).selectAll().executeTakeFirst()??null}async function wf(t){return await M.selectFrom("delivery_stops").where("uuid","=",t).selectAll().executeTakeFirst()??null}var Fr={};g(Fr,{bulkDestroy:()=>wl,bulkSoftDelete:()=>yl,bulkStore:()=>bl,destroy:()=>pl,fetchAll:()=>Kd,fetchById:()=>mr,formatZoneOptions:()=>Hd,getActiveShippingZones:()=>Qd,getZonesByCountry:()=>Yd,softDelete:()=>fl,store:()=>gl,update:()=>_l,updateCountries:()=>xl,updateRegionsAndPostalCodes:()=>Dl,updateStatus:()=>Rl});import{db as Dr}from"@stacksjs/database";async function pl(t){try{let e=await Dr.deleteFrom("shipping_zones").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zone: ${e.message}`);throw e}}async function fl(t){try{let e=await Dr.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${e.message}`);throw e}}async function wl(t){if(!t.length)return 0;try{let e=await Dr.deleteFrom("shipping_zones").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zones: ${e.message}`);throw e}}async function yl(t){if(!t.length)return 0;try{let e=await Dr.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${e.message}`);throw e}}var{randomUUIDv7:hl}=globalThis.Bun;import{db as bn}from"@stacksjs/database";async function gl(t){try{let e=hl(),r={...tt(t),uuid:e};await bn.insertInto("shipping_zones").values(r).executeTakeFirst();let o=await bn.selectFrom("shipping_zones").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping zone");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zone: ${e.message}`);throw e}}async function bl(t){if(!t.length)return 0;try{let e=t.map((o)=>({...tt(o),uuid:hl()})),r=await bn.insertInto("shipping_zones").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${e.message}`);throw e}}import{db as vr}from"@stacksjs/database";import{formatDate as Pr}from"@stacksjs/orm";async function _l(t,e){try{if(!t)throw Error("Shipping zone ID is required for update");let r=await vr.updateTable("shipping_zones").set({...tt(e),updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function Rl(t,e){try{let r=await vr.updateTable("shipping_zones").set({status:e,updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function xl(t,e){try{let r=await vr.updateTable("shipping_zones").set({countries:e,updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function Dl(t,e,r){try{let o={updated_at:Pr(new Date)};if(e!==void 0)o.regions=e;if(r!==void 0)o.postal_codes=r;let n=await vr.updateTable("shipping_zones").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update regions and postal codes");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${o.message}`);throw o}}var yf={digital:Ht,couriers:Yt,geocoding:rr,licenses:ar,methods:cr,rates:fr,routes:Zt,tracking:xr,zones:Fr},hf=yf;var Dn={};g(Dn,{activeTaxRates:()=>Rn,breakdownFor:()=>xn,bulkDestroy:()=>kl,bulkStore:()=>Il,destroy:()=>Fl,fetchAll:()=>Sl,fetchById:()=>El,store:()=>Ml,taxFor:()=>vl,update:()=>Nl,updateDefaultStatus:()=>Ol,updateRate:()=>Bl,updateStatus:()=>Jl});import{db as gf}from"@stacksjs/database";function bf(t){let e=Number(t);return Number.isFinite(e)?e/100:0}async function Rn(t={}){let e=gf.selectFrom("tax_rates").where("status","=","active").selectAll();if(t.country)e=e.where("country","=",t.country);let r=await e.execute();if(!t.codes?.length)return r;let o=new Set(t.codes);return r.filter((n)=>o.has(String(n.code??"")))}function xn(t,e,r={}){let o=Math.max(0,Math.round(t)),n=[],a=0,s=0;for(let i of e){let u=bf(i.rate),c=Math.round(o*u),m=Boolean(r.exempt&&i.exemptible);if(m)s+=c;else a+=c;n.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:m?0:c,exempted:m})}return{taxable:o,components:n,tax:a,exempted:s}}async function vl(t,e={}){return xn(t,await Rn(e),e)}import{db as Pl}from"@stacksjs/database";async function Fl(t){try{let e=await Pl.deleteFrom("tax_rates").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rate: ${e.message}`);throw e}}async function kl(t){if(!t.length)return 0;try{let e=await Pl.deleteFrom("tax_rates").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rates: ${e.message}`);throw e}}import{db as Tl}from"@stacksjs/database";async function El(t){let e=await Tl.selectFrom("tax_rates").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Sl(){return w(await Tl.selectFrom("tax_rates").selectAll().execute())}var{randomUUIDv7:Cl}=globalThis.Bun;import{db as Al}from"@stacksjs/database";async function Ml(t){try{return await Al.transaction(async(e)=>{let r={...t,uuid:Cl()};if(r.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();let o=await e.insertInto("tax_rates").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create tax rate");return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rate: ${e.message}`);throw e}}async function Il(t){if(!t.length)return 0;try{return await Al.transaction(async(e)=>{let r=0;for(let o of t){let n={...o,uuid:Cl()};if(n.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();if(await e.insertInto("tax_rates").values(n).executeTakeFirst())r++}return r})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${e.message}`);throw e}}import{db as kr}from"@stacksjs/database";import{formatDate as Tr}from"@stacksjs/orm";async function Nl(t,e){try{if(!t)throw Error("Tax rate ID is required for update");return await kr.transaction(async(r)=>{let o=await r.selectFrom("tax_rates").select("is_default").where("id","=",t).executeTakeFirst();if(!o)return;let n=e.is_default??Boolean(o.is_default),a=Tr(new Date);if(n)await r.updateTable("tax_rates").set({is_default:!1,updated_at:a}).where("id","!=",t).execute();let s=await r.updateTable("tax_rates").set({...e,updated_at:a}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function Jl(t,e){try{let r=await kr.updateTable("tax_rates").set({status:e,updated_at:Tr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function Bl(t,e){try{let r=await kr.updateTable("tax_rates").set({rate:e,updated_at:Tr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function Ol(t,e){try{return await kr.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",t).executeTakeFirst())return!1;let n=Tr(new Date);if(e)await r.updateTable("tax_rates").set({is_default:!1,updated_at:n}).where("id","!=",t).execute();return await r.updateTable("tax_rates").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate default status: ${r.message}`);throw r}}var En={};g(En,{default:()=>Ef,products:()=>Sr,restaurant:()=>Ie});var Sr={};g(Sr,{bulkDestroy:()=>$l,bulkStore:()=>om,destroy:()=>Ul,fetchAll:()=>Wl,fetchById:()=>mt,fetchCancelledBetweenDates:()=>Zl,fetchConversionRates:()=>Ql,fetchCountBetweenDates:()=>Yl,fetchCountByAllQuantities:()=>Gl,fetchCountByDate:()=>jl,fetchCountByDateGrouped:()=>Xl,fetchCountByQuantity:()=>zl,fetchCountBySource:()=>Ll,fetchCountByStatus:()=>Hl,fetchNotifiedBetweenDates:()=>Vl,fetchPurchasedBetweenDates:()=>ql,fetchWaiting:()=>Kl,store:()=>rm,update:()=>Er,updatePartySize:()=>am,updateStatus:()=>nm});import{db as vn}from"@stacksjs/database";async function Ul(t){try{let e=await vn.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await vn.deleteFrom("waitlist_products").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist product: ${e.message}`);throw e}}async function $l(t){if(!t.length)return 0;try{let e=await vn.deleteFrom("waitlist_products").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${e.message}`);throw e}}import{db as F}from"@stacksjs/database";import{formatDate as k}from"@stacksjs/orm";async function mt(t){let e=await F.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Wl(){return w(await F.selectFrom("waitlist_products").selectAll().execute())}async function Ll(t,e){let r=F.selectFrom("waitlist_products").select(["source",F.fn.count("id").as("count")]).groupBy("source");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{source:a,count:s})=>(n[a]=s,n),{})}async function jl(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=k(e),n=k(r);return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function zl(t){return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("quantity","=",t).executeTakeFirst())?.count??0}async function Gl(t,e){let r=F.selectFrom("waitlist_products").select(["quantity",F.fn.count("id").as("count")]).groupBy("quantity");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{quantity:a,count:s})=>(n[a]=s,n),{})}async function Vl(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",o).whereNotNull("notified_at").execute();return w(n)}async function ql(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",o).whereNotNull("purchased_at").execute();return w(n)}async function Zl(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",o).whereNotNull("cancelled_at").execute();return w(n)}async function Kl(){let t=await F.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute();return w(t)}async function Hl(t,e,r){let o=F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("status","=",t);if(e&&r){let a=k(e),s=k(r);o=o.where("created_at",">=",a).where("created_at","<=",s)}return(await o.executeTakeFirst())?.count??0}async function Ql(t,e){let r=F.selectFrom("waitlist_products").select(["status",F.fn.count("id").as("count")]).groupBy("status");if(t&&e){let u=k(t),c=k(e);r=r.where("created_at",">=",u).where("created_at","<=",c)}let o=await r.execute(),n=o.reduce((u,{count:c})=>u+c,0),a=Number(o.find((u)=>u.status==="purchased")?.count??0),s=n>0?a/n*100:0,i=o.reduce((u,{status:c,count:m})=>(u[c]={count:m,percentage:n>0?m/n*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function Yl(t,e){let r=k(t),o=k(e);return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",o).executeTakeFirst())?.count??0}async function Xl(t,e){let r=F.selectFrom("waitlist_products").select(["created_at"]);if(t&&e){let a=k(t),s=k(e);r=r.where("created_at",">=",a).where("created_at","<=",s)}let n=(await r.execute()).reduce((a,{created_at:s})=>{let i=(s||"").split("T")[0]||"unknown";return a[i]=(a[i]||0)+1,a},{});return Object.entries(n).map(([a,s])=>({date:a,count:s})).sort((a,s)=>a.date.localeCompare(s.date))}var{randomUUIDv7:tm}=globalThis.Bun;import{db as Pn}from"@stacksjs/database";import{formatDate as em}from"@stacksjs/orm";var _f={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Rf(t){return typeof t==="number"||t instanceof Date?em(t):t}function pt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));if(r.quantity===void 0&&r.party_size!==void 0)r.quantity=r.party_size;delete r.party_size;for(let n of["notified_at","purchased_at","cancelled_at"])if(r[n]!==void 0)r[n]=Rf(r[n]);let o=_f[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=em(new Date);return r}async function rm(t){try{let e=tm(),r={...pt(t),uuid:e,status:t.status||"waiting"};await Pn.insertInto("waitlist_products").values(r).executeTakeFirst();let o=await Pn.selectFrom("waitlist_products").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create waitlist product");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist product: ${e.message}`);throw e}}async function om(t){if(!t.length)return 0;try{let e=t.map((o)=>({...pt(o),status:o.status||"waiting",uuid:tm()})),r=await Pn.insertInto("waitlist_products").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${e.message}`);throw e}}import{db as xf}from"@stacksjs/database";import{formatDate as Df}from"@stacksjs/orm";async function Er(t,e){try{if(!t)throw Error("Waitlist product ID is required for update");let r=await mt(t);if(!r)return;await xf.updateTable("waitlist_products").set({...pt(e,r),updated_at:Df(new Date)}).where("id","=",t).execute();let o=await mt(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function nm(t,e){return await Er(t,{status:e})}async function am(t,e){return await Er(t,{quantity:e})}var Ie={};g(Ie,{bulkDestroy:()=>im,bulkStore:()=>Tm,destroy:()=>sm,fetchAll:()=>um,fetchAverageWaitTimes:()=>hm,fetchBetweenDates:()=>pm,fetchById:()=>ft,fetchConversionRates:()=>ym,fetchCountByAllPartySizes:()=>mm,fetchCountByDate:()=>dm,fetchCountByPartySize:()=>lm,fetchCountByTablePreference:()=>cm,fetchCurrentWaitTimes:()=>Dm,fetchNoShowStats:()=>xm,fetchSeatedBetweenDates:()=>fm,fetchSeatedStats:()=>vm,fetchSeatingRate:()=>Rm,fetchTablesTurnedToday:()=>_m,fetchTimeSeriesStats:()=>Pm,fetchWaiting:()=>wm,fetchWaitingWithPartySizes:()=>bm,fetchWaitingWithQuotedTimes:()=>gm,store:()=>km,update:()=>Me,updatePartySize:()=>Sm,updateQueuePosition:()=>Am,updateStatus:()=>Em,updateWaitTimes:()=>Cm});import{db as Fn}from"@stacksjs/database";async function sm(t){try{let e=await Fn.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await Fn.deleteFrom("waitlist_restaurants").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${e.message}`);throw e}}async function im(t){if(!t.length)return 0;try{let e=await Fn.deleteFrom("waitlist_restaurants").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as R}from"@stacksjs/database";import{formatDate as B}from"@stacksjs/orm";async function ft(t){let e=await R.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function um(){return w(await R.selectFrom("waitlist_restaurants").selectAll().execute())}async function cm(){return(await R.selectFrom("waitlist_restaurants").select(["table_preference",R.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((e,{table_preference:r,count:o})=>(e[r]=o,e),{})}async function dm(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r);return(await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function lm(t){return(await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("party_size","=",t).executeTakeFirst())?.count??0}async function mm(){return(await R.selectFrom("waitlist_restaurants").select(["party_size",R.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((e,{party_size:r,count:o})=>(e[r]=o,e),{})}async function pm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",o).execute();return w(n)}async function fm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",o).where("status","=","seated").execute();return w(n)}async function wm(){let t=await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute();return w(t)}async function ym(){let t=await R.selectFrom("waitlist_restaurants").select(["status",R.fn.count("id").as("count")]).groupBy("status").execute(),e=t.reduce((a,{count:s})=>a+s,0),r=t.find((a)=>a.status==="seated")?.count??0,o=e>0?Number(r)/e*100:0,n=t.reduce((a,{status:s,count:i})=>(a[s]={count:i,percentage:e>0?i/e*100:0},a),{});return{totalConversionRate:o,statusBreakdown:n}}async function hm(){let t=await R.selectFrom("waitlist_restaurants").select([R.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),R.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:t?.avg_quoted_wait_time??0,averageActualWaitTime:t?.avg_actual_wait_time??0}}async function gm(){let t=w(await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((o,n)=>o+(n.quoted_wait_time??0),0),r=t.length>0?e/t.length:0;return{entries:t,totalQuotedWaitTime:e,averageQuotedWaitTime:r}}async function bm(){let t=w(await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((n,a)=>n+a.party_size,0),r=t.length>0?e/t.length:0,o=t.reduce((n,a)=>(n[a.party_size]=(n[a.party_size]||0)+1,n),{});return{entries:t,totalPartySize:e,averagePartySize:r,partySizeBreakdown:o}}async function _m(){let t=new Date,e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r),a=await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",o).where("check_in_time","<=",n).execute(),s=a.length,i=a.reduce((p,f)=>p+f.party_size,0),u=s>0?i/s:0,c=a.reduce((p,f)=>(p[f.table_preference]=(p[f.table_preference]||0)+1,p),{}),m=a.reduce((p,f)=>(p[f.party_size]=(p[f.party_size]||0)+1,p),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:m}}async function Rm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").select(["status",R.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",o).groupBy("status").execute(),a=n.reduce((c,{count:m})=>c+m,0),s=n.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=n.reduce((c,{status:m,count:p})=>(c[m]={count:p,percentage:a>0?p/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function xm(t,e){let r=B(t),o=B(e),n=R.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",o),a=await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("check_in_time",">=",r).where("check_in_time","<=",o).executeTakeFirst(),s=await n.execute(),i=s.length,u=a?.count&&a.count>0?i/a.count*100:0,c=s.reduce((_,D)=>_+(D.quoted_wait_time??0),0),m=i>0?c/i:0,p=s.reduce((_,D)=>_+D.party_size,0),f=i>0?p/i:0,y=s.reduce((_,D)=>(_[D.table_preference]=(_[D.table_preference]||0)+1,_),{}),b=s.reduce((_,D)=>(_[D.party_size]=(_[D.party_size]||0)+1,_),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:m,averagePartySize:f,breakdownByTablePreference:y,breakdownByPartySize:b}}async function Dm(){let t=await R.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),e=t.reduce((n,a)=>n+(a.quoted_wait_time||0),0),r=t.reduce((n,a)=>n+(a.actual_wait_time||0),0),o=t.length;return{averageQuoted:o>0?e/o:0,averageActual:o>0?r/o:0}}async function vm(){let t=Date.now()-86400000,e=await R.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",t).execute(),r=Array.from({length:24},(o,n)=>({hour:n,count:e.filter((a)=>a.seated_at===n).length}));return{total:e.length,byHour:r}}async function Pm(){return(await R.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((e,r)=>{let o=r.created_at;if(!e[o])e[o]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return e[o].total++,e[o][r.status]++,e},{})}var{randomUUIDv7:Fm}=globalThis.Bun;import{db as Tn}from"@stacksjs/database";import{formatDate as kn}from"@stacksjs/orm";var vf={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function Pf(t){if(typeof t==="number")return kn(t<=2147483647?t*1000:t);if(t instanceof Date)return kn(t);return t}function wt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));for(let n of["check_in_time","seated_at","no_show_at","cancelled_at"])if(r[n]!==void 0)r[n]=Pf(r[n]);let o=vf[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=kn(new Date);return r}async function km(t){try{let e=Fm(),r={...wt(t),status:t.status||"waiting",uuid:e};await Tn.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let o=await Tn.selectFrom("waitlist_restaurants").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create restaurant waitlist entry");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${e.message}`);throw e}}async function Tm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...wt(o),status:o.status||"waiting",uuid:Fm()})),r=await Tn.insertInto("waitlist_restaurants").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as Ff}from"@stacksjs/database";import{formatDate as kf}from"@stacksjs/orm";async function Me(t,e){try{if(!t)throw Error("Restaurant waitlist entry ID is required for update");let r=await ft(t);if(!r)return;await Ff.updateTable("waitlist_restaurants").set({...wt(e,r),updated_at:kf(new Date)}).where("id","=",t).execute();let o=await ft(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function Em(t,e){return await Me(t,{status:e})}async function Sm(t,e){return await Me(t,{party_size:e})}async function Cm(t,e,r){return await Me(t,{quoted_wait_time:e,...r===void 0?{}:{actual_wait_time:r}})}async function Am(t,e){return await Me(t,{queue_position:e})}var Tf={products:Sr,restaurant:Ie},Ef=Tf;var Sf={auctions:no,carts:ao,coupons:io,customers:co,devices:wo,errors:go,giftCards:Ro,orders:No,payments:Jo,products:jo,receipts:Ko,restaurant:Ie,shippings:_n,tax:Dn,waitlists:En},jF=Sf;export{no as auctions,ao as carts,Sf as commerce,io as coupons,co as customers,jF as default,wo as devices,go as errors,Ro as giftCards,No as orders,Jo as payments,jo as products,Ko as receipts,Ie as restaurant,_n as shippings,Dn as tax,En as waitlists};
|
|
28
|
+
AND COALESCE(refund_amount, 0) + ${o(5)} <= amount`,[e,e,n,t,e]);if(Lp(a)>0){let l=await ye(t);if(l)return l;throw Error(`Payment with ID ${t} disappeared during refund`)}let s=await ye(t);if(!s)throw Error(`Payment with ID ${t} not found`);let i=String(s.status||"");if(!Gp.has(i))throw Error(`Payment status ${i||"unknown"} cannot be refunded`);let u=s,c=Number(s.amount||0)-Number(u.refundAmount??u.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${c} minor units`)}var jo={};g(jo,{categories:()=>Nt,default:()=>sf,items:()=>Jt,manufacturers:()=>Bt,reviews:()=>Ot,units:()=>Wt,variants:()=>Lt});var Nt={};g(Nt,{bulkRemove:()=>Ti,compareCategoryGrowth:()=>vi,deactivate:()=>Si,deactivateChildCategories:()=>Ci,fetchActive:()=>bi,fetchAll:()=>Bo,fetchByDisplayOrder:()=>xi,fetchById:()=>S,fetchByName:()=>gi,fetchCategoryTree:()=>Pi,fetchChildCategories:()=>Ri,fetchRootCategories:()=>_i,fetchStats:()=>Di,findOrCreateByName:()=>Mi,remove:()=>ki,removeChildCategories:()=>Ei,store:()=>Oo,update:()=>Ii,updateActiveStatus:()=>Ji,updateDisplayOrder:()=>Ni,updateParent:()=>Bi});import{db as Ke,matchedRows as qp}from"@stacksjs/database";import{formatDate as Fi}from"@stacksjs/orm";import{db as P}from"@stacksjs/database";import{formatDate as He}from"@stacksjs/orm";async function Bo(){return await P.selectFrom("categories").selectAll().execute()}async function S(t){return await P.selectFrom("categories").where("id","=",t).selectAll().executeTakeFirst()}async function gi(t){return await P.selectFrom("categories").where("name","=",t).selectAll().executeTakeFirst()}async function bi(){return await P.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function _i(){return await P.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function Ri(t){return await P.selectFrom("categories").where("parent_category_id","=",t).where("is_active","=",!0).selectAll().execute()}async function xi(t=!0){let e=P.selectFrom("categories").where("is_active","=",!0).selectAll();if(t)return await e.orderBy("display_order","asc").execute();else return await e.orderBy("display_order","desc").execute()}async function Di(){let t=await P.selectFrom("categories").select(P.fn.count("id").as("count")).executeTakeFirst(),e=await P.selectFrom("categories").where("is_active","=",!0).select(P.fn.count("id").as("count")).executeTakeFirst(),r=await P.selectFrom("categories").whereNull("parent_category_id").select(P.fn.count("id").as("count")).executeTakeFirst(),o=await P.selectFrom("categories").whereNotNull("image_url").select(P.fn.count("id").as("count")).executeTakeFirst(),n=new Date;n.setDate(n.getDate()-30);let a=He(n),s=await P.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await P.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",P.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(t?.count||0),active:Number(e?.count||0),root_categories:Number(r?.count||0),child_categories:Number(t?.count||0)-Number(r?.count||0),with_images:Number(o?.count||0),recently_added:s,top_parent_categories:i.map((u)=>({id:String(u.parent_category_id||""),name:String(u.parent_name||""),child_count:Number(u.child_count)}))}}async function vi(t=30){let e=new Date,r=He(e),o=new Date;o.setDate(e.getDate()-t);let n=He(o),a=new Date(o);a.setDate(a.getDate()-1);let s=He(a),i=new Date(a);i.setDate(a.getDate()-t);let u=He(i),c=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",r).executeTakeFirst(),l=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),m=Number(c?.count||0),f=Number(l?.count||0),h=m-f,b=f!==0?h/f*100:m>0?100:0;return{current_period:m,previous_period:f,difference:h,percentage_change:b,days_range:t}}async function Pi(){let t=await Bo(),e=new Map;t.forEach((n)=>{e.set(n.id,{...n,children:[]})});let r=[];t.forEach((n)=>{let a=e.get(n.id);if(n.parent_category_id){let s=e.get(n.parent_category_id);if(s)s.children.push(a)}else r.push(a)}),r.sort((n,a)=>n.display_order-a.display_order);let o=(n)=>{n.sort((a,s)=>a.display_order-s.display_order),n.forEach((a)=>{if(a.children.length>0)o(a.children)})};return o(r),r}async function ki(t){let e=await Ke.deleteFrom("categories").where("id","=",t).executeTakeFirst();return p(e)>0}async function Ti(t){if(!t.length)return 0;let e=await Ke.deleteFrom("categories").where("id","in",t).executeTakeFirst();return p(e)}async function Ei(t){let e=await Ke.deleteFrom("categories").where("parent_category_id","=",t).executeTakeFirst();return p(e)}async function Si(t){if(!await S(t))throw Error(`Category with ID ${t} not found`);let r=await Ke.updateTable("categories").set({is_active:!1,updated_at:Fi(new Date)}).where("id","=",t).returning("id").executeTakeFirst();return Boolean(r)}async function Ci(t){return(await qp(Ke.updateTable("categories").set({is_active:!1,updated_at:Fi(new Date)}).where("parent_category_id","=",t))).length}var{randomUUIDv7:Vp}=globalThis.Bun;import{db as Ai}from"@stacksjs/database";import{HttpError as Mt}from"@stacksjs/error-handling";import{isUniqueViolation as Zp}from"@stacksjs/orm";import{slug as Hp}from"@stacksjs/strings";async function Oo(t){try{let e=t.parent_category_id?Number(t.parent_category_id):void 0;if(e!==void 0&&(!Number.isSafeInteger(e)||e<=0))throw new Mt(422,"Parent category ID must be a positive integer");if(e&&!await S(e))throw new Mt(422,`Parent category with ID ${t.parent_category_id} not found`);let r={...t,uuid:Vp(),is_active:t.is_active??!0,parent_category_id:t.parent_category_id||null},o=await Ai.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create category");return o}catch(e){if(e instanceof Mt)throw e;if(Zp(e))throw new Mt(409,"A category with this name or slug already exists");if(e instanceof Error)throw Error(`Failed to create category: ${e.message}`);throw e}}async function Mi(t){if(!t.name)throw Error("Name is required");let e=await Ai.selectFrom("categories").selectAll().where("name","=",t.name).executeTakeFirst();if(e)return e;let r={name:t.name,slug:Hp(t.name),is_active:t.is_active??!0,display_order:0};return await Oo(r)}import{db as Qe}from"@stacksjs/database";import{HttpError as ke}from"@stacksjs/error-handling";import{formatDate as It,isUniqueViolation as Kp}from"@stacksjs/orm";async function Ii(t,e){if(!await S(t))return;if(Object.hasOwn(e,"parent_category_id")){let o=e.parent_category_id?Number(e.parent_category_id):void 0;if(o!==void 0&&(!Number.isSafeInteger(o)||o<=0))throw new ke(422,"Parent category ID must be a positive integer");if(o===t)throw new ke(422,"A category cannot be its own parent");if(o&&!await S(o))throw new ke(422,`Parent category with ID ${e.parent_category_id} not found`);if(o&&await Oi(t,String(o)))throw new ke(422,"This operation would create a circular category hierarchy")}try{let o=Object.hasOwn(e,"parent_category_id")?{parent_category_id:e.parent_category_id||null}:{},n=await Qe.updateTable("categories").set({...e,...o,updated_at:It(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return n}catch(o){if(o instanceof ke)throw o;if(Kp(o))throw new ke(409,"A category with this name or slug already exists");if(o instanceof Error)throw Error(`Failed to update category: ${o.message}`);throw o}}async function Ni(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);try{return await Qe.updateTable("categories").set({display_order:e,updated_at:It(new Date)}).where("id","=",t).execute(),await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category display order: ${o.message}`);throw o}}async function Ji(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);try{return await Qe.updateTable("categories").set({is_active:e,updated_at:It(new Date)}).where("id","=",t).execute(),await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category active status: ${o.message}`);throw o}}async function Bi(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);if(e){let o=Number(e);if(o===t)throw Error("A category cannot be its own parent");if(!await S(o))throw Error(`Parent category with ID ${e} not found`);if(await Oi(t,e))throw Error("This operation would create a circular reference in the category hierarchy")}try{let o={updated_at:It(new Date)};if(e===null)await Qe.updateTable("categories").set({...o,parent_category_id:null}).where("id","=",t).execute();else await Qe.updateTable("categories").set({...o,parent_category_id:e}).where("id","=",t).execute();return await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category parent: ${o.message}`);throw o}}async function Oi(t,e){let r=Number(e),o=new Set;while(r){if(o.has(r))return!0;if(r===t)return!0;o.add(r);let n=await S(r),a=n?.parent_category_id;if(!n||!a)return!1;r=Number(a)}return!1}var Jt={};g(Jt,{bulkDestroy:()=>Wi,bulkStore:()=>Zi,destroy:()=>$i,fetchAll:()=>Li,fetchById:()=>ee,fetchTopProducts:()=>zi,store:()=>Vi,update:()=>Hi,updateAvailability:()=>Ki,updateInventory:()=>Qi});import{db as Ui}from"@stacksjs/database";async function $i(t){try{let e=await Ui.deleteFrom("products").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product item: ${e.message}`);throw e}}async function Wi(t){if(!t.length)return 0;try{let e=await Ui.deleteFrom("products").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product items: ${e.message}`);throw e}}import{db as X,sql as Qp}from"@stacksjs/database";async function ee(t){let e=await X.selectFrom("products").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.manufacturer_id)r=await X.selectFrom("manufacturers").where("id","=",e.manufacturer_id).selectAll().executeTakeFirst();if(e.category_id)o=await X.selectFrom("categories").where("id","=",e.category_id).selectAll().executeTakeFirst();return{...e,manufacturer:r,category:o}}return}async function Li(){let t=await X.selectFrom("products").selectAll().execute(),e=t.map((c)=>c.manufacturer_id).filter((c)=>c!==null&&c!==void 0),r=t.map((c)=>c.category_id).filter((c)=>c!==null&&c!==void 0),o=X.selectFrom("manufacturers"),n=X.selectFrom("categories");if(e.length>0)o=o.where("id","in",e);if(r.length>0)n=n.where("id","in",r);let a=await o.selectAll().execute(),s=await n.selectAll().execute(),i=a.reduce((c,l)=>(c[l.id]=l,c),{}),u=s.reduce((c,l)=>(c[l.id]=l,c),{});return t.map((c)=>({...c,manufacturer:c.manufacturer_id?i[c.manufacturer_id]:null,category:c.category_id?u[c.category_id]:null}))}async function ji(t){try{let e=await X.selectFrom("products").selectAll().where("uuid","=",t).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get product by UUID: ${e.message}`);throw e}}async function zi(t=5){try{return(await X.selectFrom("order_items").innerJoin("products","products.id","=","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",X.fn.sum("order_items.quantity").as("units_sold"),Qp`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(t).execute()).map((r)=>({id:Number(r.id),name:String(r.name??"Unnamed product"),units_sold:Number(r.units_sold??0),revenue:Number(r.revenue??0),inventory_count:Number(r.inventory_count??0)}))}catch(e){if(e instanceof Error)throw TypeError(`Failed to fetch top products: ${e.message}`);throw e}}var{randomUUIDv7:Gi}=globalThis.Bun;import{db as qi}from"@stacksjs/database";async function Vi(t){try{let e={...t,uuid:Gi()},r=await qi.insertInto("products").values(e).executeTakeFirst();if(!r)throw Error("Failed to create product item");let o=H(r),n=o!==void 0?await ee(o):await ji(e.uuid);if(!n)throw Error("Failed to create product item");return n}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product item: ${e.message}`);throw e}}async function Zi(t){if(!t.length)return 0;let e=0;try{return await qi.transaction(async(r)=>{for(let o of t){let n={...o,uuid:Gi()};await r.insertInto("products").values(n).execute(),e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product items in bulk: ${r.message}`);throw r}}import{db as Uo,matchedRows as y_}from"@stacksjs/database";import{formatDate as $o}from"@stacksjs/orm";async function Hi(t,e){try{if(!t)throw Error("Product item ID is required for update");let r=await Uo.updateTable("products").set({...e,updated_at:$o(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function Ki(t,e){if(!await ee(t))throw Error(`Product item with ID ${t} not found`);try{return await Uo.updateTable("products").set({is_available:e,updated_at:$o(new Date)}).where("id","=",t).execute(),await ee(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update product item availability: ${o.message}`);throw o}}async function Qi(t,e){let r=await ee(t);if(!r)throw Error(`Product item with ID ${t} not found`);let o={updated_at:$o(new Date)};if(e!==void 0)o.inventory_count=e;if(Object.keys(o).length===1)return r;try{return await Uo.updateTable("products").set(o).where("id","=",t).execute(),await ee(t)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update inventory information: ${n.message}`);throw n}}var Bt={};g(Bt,{bulkDestroy:()=>eu,bulkStore:()=>lu,destroy:()=>Xi,fetchAll:()=>tu,fetchByCountry:()=>au,fetchById:()=>ru,fetchByUuid:()=>ou,fetchFeatured:()=>nu,fetchWithProductCount:()=>su,store:()=>du,update:()=>pu,updateByUuid:()=>wu,updateFeaturedStatus:()=>fu});import{db as Yi}from"@stacksjs/database";async function Xi(t){try{let e=await Yi.deleteFrom("manufacturers").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete order: ${e.message}`);throw e}}async function eu(t){if(!t.length)return 0;try{let e=await Yi.deleteFrom("manufacturers").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete orders: ${e.message}`);throw e}}import{db as te}from"@stacksjs/database";async function tu(){return w(await te.selectFrom("manufacturers").selectAll().execute())}async function ru(t){let e=await te.selectFrom("manufacturers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ou(t){let e=await te.selectFrom("manufacturers").where("uuid","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function nu(t=10){let e=await te.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(t).execute();return w(e)}async function au(t,e={}){let r=e.page||1,o=e.limit||2,n=await te.selectFrom("manufacturers").select(te.fn.count("id").as("total")).where("country","=",t).executeTakeFirst(),a=Number(n?.total||0),s=await te.selectFrom("manufacturers").selectAll().where("country","=",t).limit(o).offset((r-1)*o).execute(),i=Math.ceil(a/o);return{data:w(s),paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function su(t={}){let e=te.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(t.country)e=e.where("m.country","=",t.country);if(t.featured!==void 0)e=e.where("m.featured","=",t.featured);return e=e.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",te.fn.count("p.id").as("product_count")]).groupBy("m.id"),e.execute()}var{randomUUIDv7:uu}=globalThis.Bun;import{db as cu}from"@stacksjs/database";import{HttpError as iu}from"@stacksjs/error-handling";import{isUniqueViolation as Yp}from"@stacksjs/orm";async function du(t){try{let e={...t,uuid:uu(),featured:t.featured??!1},r=await cu.insertInto("manufacturers").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return d(r)}catch(e){if(e instanceof iu)throw e;if(Yp(e))throw new iu(409,"A manufacturer with this name already exists");if(e instanceof Error)throw Error(`Failed to create manufacturer: ${e.message}`);throw e}}async function lu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:uu(),featured:r.featured??!1};await cu.insertInto("manufacturers").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${r.message}`);throw r}}import{db as Wo}from"@stacksjs/database";import{HttpError as mu}from"@stacksjs/error-handling";import{formatDate as Lo,isUniqueViolation as Xp}from"@stacksjs/orm";async function pu(t,e){try{if(!t)throw Error("Manufacturer ID is required for update");let r=await Wo.updateTable("manufacturers").set({...e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof mu)throw r;if(Xp(r))throw new mu(409,"A manufacturer with this name already exists");if(r instanceof Error)throw Error(`Failed to update manufacturer: ${r.message}`);throw r}}async function fu(t,e){try{let r=await Wo.updateTable("manufacturers").set({featured:e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function wu(t,e){try{let r=await Wo.updateTable("manufacturers").set({...e,updated_at:Lo(new Date)}).where("uuid","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var Ot={};g(Ot,{bulkDestroy:()=>gu,destroy:()=>hu,fetchAll:()=>_u,fetchApprovedByProductId:()=>Du,fetchById:()=>bu,fetchByProductId:()=>Ru,fetchByUserId:()=>xu,fetchMostHelpfulByProductId:()=>vu,fetchStats:()=>Tu,fetchStatsByProductIds:()=>Eu,store:()=>Su,update:()=>Mu,updateVotes:()=>Iu});import{db as yu}from"@stacksjs/database";async function hu(t){try{let e=await yu.deleteFrom("reviews").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete review: ${e.message}`);throw e}}async function gu(t){if(!t.length)return 0;try{let e=await yu.deleteFrom("reviews").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete reviews: ${e.message}`);throw e}}import{db as Te}from"@stacksjs/database";async function bu(t){return d(await Te.selectFrom("reviews").where("id","=",t).selectAll().executeTakeFirst(),!0)}async function _u(){return w(await Te.selectFrom("reviews").selectAll().execute())}async function Ru(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).selectAll().execute())}async function xu(t){return w(await Te.selectFrom("reviews").where("customer_id","=",t).selectAll().execute())}async function Du(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).where("is_approved","=",!0).selectAll().execute())}async function vu(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).orderBy("helpful_votes","desc").selectAll().execute())}import{db as Pu}from"@stacksjs/database";function Fu(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function ku(t){let e=Fu();e.total=t.length;let r=0;for(let o of t){if(o.rating===null||o.rating===void 0){e.commentsOnly++;continue}let n=Number(o.rating);if(Number.isNaN(n)){e.commentsOnly++;continue}e.rated++,r+=n;let a=Math.min(5,Math.max(1,Math.round(n)));e.distribution[a]++}if(e.rated>0)e.average=Math.round(r/e.rated*10)/10;return e}async function Tu(t){let e=await Pu.selectFrom("reviews").select(["rating"]).where("product_id","=",t).where("is_approved","=",!0).execute();return ku(e)}async function Eu(t){let e=new Map;for(let n of t)e.set(n,Fu());if(t.length===0)return e;let r=await Pu.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",t).where("is_approved","=",!0).execute(),o=new Map;for(let n of r){let a=o.get(n.product_id);if(a)a.push({rating:n.rating});else o.set(n.product_id,[{rating:n.rating}])}for(let[n,a]of o)e.set(n,ku(a));return e}var{randomUUIDv7:ef}=globalThis.Bun;import{db as tf}from"@stacksjs/database";function rf(t){let e=t.rating!==void 0&&t.rating!==null,r=typeof t.content==="string"&&t.content.trim().length>0,o=typeof t.title==="string"&&t.title.trim().length>0;return!e&&!r&&!o}async function Su(t){try{if(rf(t))throw Error("A review needs a rating or something written: both were empty");let e={...t,uuid:ef(),rating:t.rating??null,is_verified_purchase:t.is_verified_purchase??!1,is_approved:t.is_approved??!1,helpful_votes:t.helpful_votes??0,unhelpful_votes:t.unhelpful_votes??0,is_featured:t.is_featured??!1},r=await tf.insertInto("reviews").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return d(r)}catch(e){if(e instanceof Error){if(e.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${e.message}`)}throw e}}import{db as Cu}from"@stacksjs/database";import{formatDate as Au}from"@stacksjs/orm";async function Mu(t,e){try{if(!t)throw Error("Review ID is required for update");let r=await Cu.updateTable("reviews").set({...e,updated_at:Au(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function Iu(t,e,r=!0){try{let o=e==="helpful"?"helpful_votes":"unhelpful_votes",n=r?`COALESCE("${o}", 0) + 1`:`MAX(COALESCE("${o}", 0) - 1, 0)`,a=await Cu.unsafe(`UPDATE "reviews" SET "${o}" = ${n}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[Au(new Date),t]).execute(),s=Array.isArray(a)?a[0]:a;if(!s)throw Error("Failed to update review votes");return d(s)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update review votes: ${o.message}`);throw o}}var Wt={};g(Wt,{bulkDestroy:()=>Bu,bulkStore:()=>ju,bulkUpdate:()=>Vu,destroy:()=>Ju,fetchAll:()=>$u,fetchById:()=>Uu,formatUnitOptions:()=>zu,getDefaultUnit:()=>Gu,store:()=>Lu,update:()=>qu,updateDefaultStatus:()=>Zu});import{db as Nu}from"@stacksjs/database";async function Ju(t){try{let e=await Nu.deleteFrom("product_units").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product unit: ${e.message}`);throw e}}async function Bu(t){if(!t.length)return 0;try{let e=await Nu.deleteFrom("product_units").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product units: ${e.message}`);throw e}}import{db as Ou}from"@stacksjs/database";async function Uu(t){let e=await Ou.selectFrom("product_units").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function $u(){return w(await Ou.selectFrom("product_units").selectAll().execute())}var{randomUUIDv7:Wu}=globalThis.Bun;import{db as Ye}from"@stacksjs/database";async function Lu(t){try{return await Ye.transaction(async(e)=>{let r={...t,uuid:Wu()},o=await e.insertInto("product_units").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create product unit");if(r.is_default&&r.type)await e.updateTable("product_units").set({is_default:!1}).where("type","=",r.type).where("id","!=",o.id).execute();return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product unit: ${e.message}`);throw e}}async function ju(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:Wu()},n=await Ye.insertInto("product_units").values(o).returningAll().executeTakeFirst();if(o.is_default&&o.type&&n)await Ye.updateTable("product_units").set({is_default:!1}).where("type","=",o.type).where("id","!=",n.id).execute();e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product units in bulk: ${r.message}`);throw r}}function zu(t){try{let e=Ye.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(t)e=e.where("type","=",t);return e=e.orderBy("name"),e.execute().then((r)=>r.map((o)=>({id:String(o.id),name:o.name,abbreviation:o.abbreviation,is_default:o.is_default})))}catch(e){if(e instanceof Error)throw TypeError(`Failed to format unit options: ${e.message}`);throw e}}async function Gu(t){try{let e=await Ye.selectFrom("product_units").selectAll().where("type","=",t).where("is_default","=",!0).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get default unit: ${e.message}`);throw e}}import{db as Ut,matchedRows as of}from"@stacksjs/database";import{formatDate as $t}from"@stacksjs/orm";async function qu(t,e){try{if(!t)throw Error("Product unit ID is required for update");return await Ut.transaction(async(r)=>{let o=await r.selectFrom("product_units").select(["type","is_default"]).where("id","=",t).executeTakeFirst();if(!o)return;let n=e.type??o.type;if((e.is_default??Boolean(o.is_default))&&n)await r.updateTable("product_units").set({is_default:!1,updated_at:$t(new Date)}).where("type","=",n).where("id","!=",t).execute();let s=await r.updateTable("product_units").set({...e,updated_at:$t(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function Vu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o=r;if(!o.id)continue;let n=o.data&&typeof o.data==="object"?o.data:{...o};delete n.id;let a=await of(Ut.updateTable("product_units").set({...n,updated_at:$t(new Date)}).where("id","=",o.id)),s=n;if(s.is_default===!0&&s.type)await Ut.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",o.id).execute();if(a.length>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product units in bulk: ${r.message}`);throw r}}async function Zu(t,e){try{return await Ut.transaction(async(r)=>{let o=await r.selectFrom("product_units").select("type").where("id","=",t).executeTakeFirst();if(!o)return!1;let n=$t(new Date);if(e&&o.type)await r.updateTable("product_units").set({is_default:!1,updated_at:n}).where("type","=",o.type).where("id","!=",t).execute();return await r.updateTable("product_units").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit default status: ${r.message}`);throw r}}var Lt={};g(Lt,{bulkDestroy:()=>Qu,bulkStore:()=>nc,bulkUpdate:()=>dc,destroy:()=>Ku,fetchAll:()=>ec,fetchById:()=>Xu,formatVariantOptions:()=>ac,generateVariantCombinations:()=>sc,store:()=>oc,update:()=>cc});import{db as Hu}from"@stacksjs/database";async function Ku(t){try{let e=await Hu.deleteFrom("product_variants").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variant: ${e.message}`);throw e}}async function Qu(t){if(!t.length)return 0;try{let e=await Hu.deleteFrom("product_variants").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variants: ${e.message}`);throw e}}import{db as Yu}from"@stacksjs/database";async function Xu(t){let e=await Yu.selectFrom("product_variants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ec(){return w(await Yu.selectFrom("product_variants").selectAll().execute())}var{randomUUIDv7:tc}=globalThis.Bun;import{db as rc}from"@stacksjs/database";async function oc(t){try{let e={...t,uuid:tc()},r=await rc.insertInto("product_variants").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return d(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product variant: ${e.message}`);throw e}}async function nc(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:tc()};await rc.insertInto("product_variants").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${r.message}`);throw r}}function ac(t){if(!t||!t.length)return JSON.stringify([]);let e=t.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(e)}function sc(t){let e=Object.keys(t);if(!e.length)return[];function r(o,n){if(o===e.length)return[n];let a=e[o],s=t[a]??[],i=[];for(let u of s){let c={...n,[a]:u};i.push(...r(o+1,c))}return i}return r(0,{})}import{db as ic,matchedRows as nf}from"@stacksjs/database";import{formatDate as uc}from"@stacksjs/orm";async function cc(t,e){try{let r=await ic.updateTable("product_variants").set({...e,updated_at:uc(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function dc(t){if(!t.length)return 0;let e=0;try{for(let r of t){if(!r.id)continue;if((await nf(ic.updateTable("product_variants").set({...r,updated_at:uc(new Date)}).where("id","=",r.id))).length>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var af={categories:Nt,items:Jt,manufacturers:Bt,reviews:Ot,units:Wt,variants:Lt},sf=af;var Ho={};g(Ho,{bulkDestroy:()=>pc,bulkStore:()=>xc,destroy:()=>mc,fetchAll:()=>fc,fetchById:()=>Ee,fetchPageStats:()=>hc,fetchPrintJobStats:()=>wc,fetchPrintTimeStats:()=>gc,fetchPrintsPerHour:()=>bc,fetchSuccessRate:()=>yc,store:()=>Rc,update:()=>Dc,updatePrintJob:()=>Pc,updateStatus:()=>vc});import{db as lc}from"@stacksjs/database";async function mc(t){try{let e=await lc.deleteFrom("receipts").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print log: ${e.message}`);throw e}}async function pc(t){if(!t.length)return 0;try{let e=await lc.deleteFrom("receipts").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete receipts: ${e.message}`);throw e}}import{db as zo}from"@stacksjs/database";import{formatDate as uf}from"@stacksjs/orm";function j(t){return uf(t)}function cf(t){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t==="number"){let o=new Date(t<=2147483647?t*1000:t);return Number.isNaN(o.getTime())?null:o}let e=String(t||"").trim();if(!e)return null;if(/^\d{10}$/.test(e)){let o=new Date(Number(e)*1000);return Number.isNaN(o.getTime())?null:o}let r=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(r.getTime())?null:r}async function Ee(t){let e=await zo.selectFrom("receipts").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function fc(){return w(await zo.selectFrom("receipts").selectAll().execute())}async function wc(t,e){let r=j(t),o=j(e),n=await J("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{total:n.total,success:n.success,failed:n.failed,warning:n.warning,averageSize:Math.round(n.averageSize),averagePages:Math.round(n.averagePages),averageDuration:Math.round(n.averageDuration)}}async function yc(t,e){let r=j(t),o=j(e),n=await J("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(s)=>s.where("timestamp",">=",r).where("timestamp","<=",o));return{successRate:n.total>0?Math.round(n.success/n.total*100):0,total:n.total,success:n.success,failed:n.failed,warning:n.warning}}async function hc(t,e){let r=j(t),o=j(e),n=await J("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{totalPages:n.totalPages,averagePagesPerReceipt:Math.round(n.averagePagesPerReceipt),totalReceipts:n.totalReceipts}}async function gc(t,e){let r=j(t),o=j(e),n=await J("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{averageDuration:Math.round(n.averageDuration),minDuration:n.minDuration,maxDuration:n.maxDuration,totalJobs:n.totalJobs}}async function bc(t,e){let r=typeof t==="number"?t:t.getTime(),o=typeof e==="number"?e:e.getTime(),n=j(t),a=j(e),s=await zo.selectFrom("receipts").where("timestamp",">=",n).where("timestamp","<=",a).selectAll().execute(),i=s.length,u=Math.ceil((o-r)/3600000),c=u>0?Math.round(i/u):0,l=Array.from({length:24},(m,f)=>({hour:f,count:0}));return s.forEach((m)=>{let f=cf(m.timestamp);if(!f)return;l[f.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:l}}var{randomUUIDv7:_c}=globalThis.Bun;import{db as qo}from"@stacksjs/database";import{formatDate as Go}from"@stacksjs/orm";function Xe(t){try{if(typeof t==="number")return Go(t<=2147483647?t*1000:t);if(typeof t==="string"&&/^\d{10}$/.test(t))return Go(Number(t)*1000);return Go(t)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function Rc(t){try{let e=_c(),r={...t,timestamp:Xe(t.timestamp),uuid:e};await qo.insertInto("receipts").values(r).executeTakeFirst();let o=await qo.selectFrom("receipts").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create receipt");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipt: ${e.message}`);throw e}}async function xc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...o,timestamp:Xe(o.timestamp),uuid:_c()})),r=await qo.insertInto("receipts").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${e.message}`);throw e}}import{db as Vo}from"@stacksjs/database";import{formatDate as Zo}from"@stacksjs/orm";async function Dc(t,e){try{if(!t)throw Error("Receipt ID is required for update");let r={...e,...e.timestamp===void 0?{}:{timestamp:Xe(e.timestamp)},updated_at:Zo(new Date)};await Vo.updateTable("receipts").set(r).where("id","=",t).execute();let o=await Ee(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function vc(t,e){try{await Vo.updateTable("receipts").set({status:e,updated_at:Zo(new Date)}).where("id","=",t).execute();let r=await Ee(t);if(!r)throw Error("Failed to update receipt status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function Pc(t,e,r,o){try{let n={updated_at:Zo(new Date)};if(e!==void 0)n.size=e;if(r!==void 0)n.pages=r;if(o!==void 0)n.duration=o;await Vo.updateTable("receipts").set(n).where("id","=",t).execute();let a=await Ee(t);if(!a)throw Error("Failed to update receipt job information");return d(a)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update receipt job information: ${n.message}`);throw n}}var Rn={};g(Rn,{couriers:()=>Yt,default:()=>Mf,digital:()=>Kt,geocoding:()=>rr,licenses:()=>ar,methods:()=>cr,rates:()=>fr,routes:()=>Zt,tracking:()=>xr,zones:()=>Fr});var Zt={};g(Zt,{DeliveryRouteInputError:()=>N,bulkDestroy:()=>Tc,destroy:()=>kc,fetchActive:()=>Sc,fetchAll:()=>Ec,fetchByCourier:()=>Cc,fetchById:()=>zt,store:()=>Ac,update:()=>Ic,updateLastActive:()=>Mc,updateMetrics:()=>Jc,updateStops:()=>Nc,validateDeliveryRouteWrite:()=>Se});import{db as Fc}from"@stacksjs/database";async function kc(t){try{let e=await Fc.deleteFrom("delivery_routes").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery route: ${e.message}`);throw e}}async function Tc(t){if(!t.length)return 0;try{let e=await Fc.deleteFrom("delivery_routes").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery routes: ${e.message}`);throw e}}import{db as jt}from"@stacksjs/database";async function zt(t){return await jt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst()}async function Ec(){return await jt.selectFrom("delivery_routes").selectAll().execute()}async function Sc(){return await jt.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function Cc(t){return await jt.selectFrom("delivery_routes").where("courier","=",t).selectAll().execute()}var{randomUUIDv7:mf}=globalThis.Bun;import{db as Ko}from"@stacksjs/database";function he(t,e){let r={};for(let[o,n]of Object.entries(e))for(let a of n){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)continue;r[o]=t[a];break}return r}function et(t){return he(t,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function re(t){return he(t,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function tt(t){return he(t,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function rt(t){return he(t,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function ot(t){return he(t,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function nt(t){return he(t,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function Gt(t){return he(t,{courier:["courier"],courier_id:["courier_id","courierId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as df}from"@stacksjs/database";class N extends TypeError{constructor(t){super(t);this.name="DeliveryRouteInputError"}}function qt(t,e,r){return Number(t[r]??e?.[r])}function lf(t,e){let r=t.last_active??e?.last_active;if(r===void 0||r===null)return Date.now();if(r instanceof Date)return r.getTime();if(typeof r==="number")return r;if(typeof r==="string"&&/^\d{10,13}$/.test(r))return Number(r);return Number.NaN}async function Se(t,e){let r=qt(t,e,"courier_id"),o=qt(t,e,"stops"),n=qt(t,e,"delivery_time"),a=qt(t,e,"total_distance"),s=lf(t,e);if(!Number.isSafeInteger(r)||r<1)throw new N("Courier must be a positive integer.");if(!Number.isSafeInteger(o)||o<0)throw new N("Stops must be a non-negative integer.");if(!Number.isSafeInteger(n)||n<0)throw new N("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(a)||a<0)throw new N("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(s)||s<0)throw new N("Last active must be a valid Unix timestamp.");let i=await df.selectFrom("couriers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new N(`Courier ${r} was not found.`);return{...t,courier_id:Number(i.id),courier:i.name,vehicle:i.vehicle_number,last_active:s}}async function Ac(t){try{let e=mf(),r=Gt(t),n={...await Se(r),uuid:e};await Ko.insertInto("delivery_routes").values(n).executeTakeFirst();let a=await Ko.selectFrom("delivery_routes").where("uuid","=",e).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(e){if(e instanceof N)throw e;if(e instanceof Error)throw TypeError(`Failed to create delivery route: ${e.message}`);throw e}}async function Mc(t){try{await Ko.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",t).execute();let e=await zt(t);if(!e)throw Error("Failed to update delivery route last active");return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update delivery route last active: ${e.message}`);throw e}}import{db as Vt}from"@stacksjs/database";import{formatDate as Qo}from"@stacksjs/orm";async function Ic(t,e){try{if(!t)throw Error("Delivery route ID is required for update");let r=await Vt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=Gt(e),n=await Se(o,r),a=await Vt.updateTable("delivery_routes").set({...n,updated_at:Qo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof N)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function Nc(t,e){try{let r=await Vt.updateTable("delivery_routes").set({stops:e,updated_at:Qo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update delivery route stops");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update delivery route stops: ${r.message}`);throw r}}async function Jc(t,e,r){try{let o={updated_at:Qo(new Date)};if(e!==void 0)o.delivery_time=e;if(r!==void 0)o.total_distance=r;let n=await Vt.updateTable("delivery_routes").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update delivery metrics");return n}catch(o){if(o instanceof Error)throw TypeError(`Failed to update delivery metrics: ${o.message}`);throw o}}var Kt={};g(Kt,{bulkDestroy:()=>$c,bulkSoftDelete:()=>Wc,bulkStore:()=>Vc,destroy:()=>Oc,fetchAll:()=>zc,fetchById:()=>jc,softDelete:()=>Uc,store:()=>qc,update:()=>Zc,updateDeliverySettings:()=>Kc,updateStatus:()=>Hc});import{db as Ht,matchedRows as Bc}from"@stacksjs/database";async function Oc(t){try{let e=await Ht.deleteFrom("digital_deliveries").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital delivery: ${e.message}`);throw e}}async function Uc(t){try{return(await Bc(Ht.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${e.message}`);throw e}}async function $c(t){if(!t.length)return 0;try{let e=await Ht.deleteFrom("digital_deliveries").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${e.message}`);throw e}}async function Wc(t){if(!t.length)return 0;try{return(await Bc(Ht.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${e.message}`);throw e}}import{db as Lc}from"@stacksjs/database";async function jc(t){let e=await Lc.selectFrom("digital_deliveries").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function zc(){return w(await Lc.selectFrom("digital_deliveries").selectAll().execute())}var{randomUUIDv7:Gc}=globalThis.Bun;import{db as Yo}from"@stacksjs/database";async function qc(t){try{let e=Gc(),r={...rt(t),uuid:e};await Yo.insertInto("digital_deliveries").values(r).executeTakeFirst();let o=await Yo.selectFrom("digital_deliveries").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created digital delivery");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital delivery: ${e.message}`);throw e}}async function Vc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...rt(o),uuid:Gc()})),r=await Yo.insertInto("digital_deliveries").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${e.message}`);throw e}}import{db as Xo}from"@stacksjs/database";import{formatDate as en}from"@stacksjs/orm";async function Zc(t,e){try{if(!t)throw Error("Digital delivery ID is required for update");let r=await Xo.updateTable("digital_deliveries").set({...rt(e),updated_at:en(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function Hc(t,e){try{let r=await Xo.updateTable("digital_deliveries").set({status:e,updated_at:en(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function Kc(t,e,r,o,n){try{let a={updated_at:en(new Date)};if(e!==void 0)a.download_limit=e;if(r!==void 0)a.expiry_days=r;if(o!==void 0)a.requires_login=o;if(n!==void 0)a.automatic_delivery=n;let s=await Xo.updateTable("digital_deliveries").set(a).where("id","=",t).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return d(s)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var Yt={};g(Yt,{bulkDestroy:()=>td,bulkStore:()=>nd,destroy:()=>ed,fetchAll:()=>Yc,fetchById:()=>Qt,store:()=>od,update:()=>ad,updateContact:()=>id,updateStatus:()=>sd});import{db as Xc}from"@stacksjs/database";import{db as Qc}from"@stacksjs/database";async function Qt(t){let e=await Qc.selectFrom("couriers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Yc(){return w(await Qc.selectFrom("couriers").selectAll().execute())}async function ed(t){try{let e=await Xc.deleteFrom("couriers").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete courier: ${e.message}`);throw e}}async function td(t){if(!t.length)return 0;let e=0;try{return await Xc.transaction(async(r)=>{for(let o of t)if(await Qt(o))await r.deleteFrom("couriers").where("id","=",o).execute(),e++}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to delete couriers in bulk: ${r.message}`);throw r}}var{randomUUIDv7:rd}=globalThis.Bun;import{db as tn}from"@stacksjs/database";async function od(t){try{let e=rd(),r={...nt(t),uuid:e};await tn.insertInto("couriers").values(r).executeTakeFirst();let o=await tn.selectFrom("couriers").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created courier");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create courier: ${e.message}`);throw e}}async function nd(t){if(!t.length)return 0;try{let e=t.map((o)=>({...nt(o),uuid:rd()})),r=await tn.insertInto("couriers").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create couriers in bulk: ${e.message}`);throw e}}import{db as rn}from"@stacksjs/database";import{formatDate as on}from"@stacksjs/orm";async function ad(t,e){try{if(!t)throw Error("Courier ID is required for update");let r=await rn.updateTable("couriers").set({...nt(e),updated_at:on(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier: ${r.message}`);throw r}}async function sd(t,e){try{let r=await rn.updateTable("couriers").set({status:e,updated_at:on(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update courier status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier status: ${r.message}`);throw r}}async function id(t,e){try{let r={updated_at:on(new Date)};if(e!==void 0)r.phone=e;let o=await rn.updateTable("couriers").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update contact information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var rr={};g(rr,{PRECISION_RANK:()=>st,checkCoverage:()=>gf,formatQuery:()=>Ce,geocode:()=>hf,geocodingDriver:()=>pd,nominatimDriver:()=>tr,setGeocodingDriver:()=>yf});var ge=(t)=>t*Math.PI/180;function ce(t,e){let r=ge(e.latitude-t.latitude),o=ge(e.longitude-t.longitude),n=ge(t.latitude),a=ge(e.latitude),s=Math.sin(r/2)**2+Math.sin(o/2)**2*Math.cos(n)*Math.cos(a);return 12742017.6*Math.asin(Math.sqrt(s))}function Xt(t,e){let r=ge(t.latitude),o=ge(e.latitude),n=ge(e.longitude-t.longitude),a=Math.sin(n)*Math.cos(o),s=Math.cos(r)*Math.sin(o)-Math.sin(r)*Math.cos(o)*Math.cos(n);return(Math.atan2(a,s)*180/Math.PI+360)%360}function er(t,e,r={}){let o=r.detourFactor??1.35,n=r.minimumSeconds??30;if(!Number.isFinite(e)||e<=0.5)return null;let a=t*o/e;return Math.max(n,Math.round(a))}function ud(t,e,r){return ce(t,e)<=r}function at(t){return typeof t?.latitude==="number"&&typeof t?.longitude==="number"&&Number.isFinite(t.latitude)&&Number.isFinite(t.longitude)}var st={unknown:0,locality:1,postal:2,street:3,rooftop:4};function Ce(t){return[t.street,t.city,t.region,t.postalCode,t.country].map((e)=>String(e??"").trim()).filter(Boolean).join(", ")}var pf="https://nominatim.openstreetmap.org/search",cd=1000,dd=0,ld=Promise.resolve();async function ff(t){let e=ld.then(async()=>{let r=Date.now()-dd;if(r<cd)await Bun.sleep(cd-r);return dd=Date.now(),t()});return ld=e.then(()=>{return},()=>{return}),e}function wf(t){let e=t.address??{},r=String(t.addresstype??""),o=String(t.type??""),n=String(t.category??t.class??"");if(e.house_number||o==="house"||o==="building"||r==="building")return"rooftop";if(e.road||n==="highway"||r==="road")return"street";if(r==="postcode"||e.postcode&&!e.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(r))return"locality";return"unknown"}function tr(t={}){let e=t.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,r=t.endpoint??pf;return{name:"nominatim",async geocode(o){let n=Ce(o);if(!n)return null;let a=new URL(r);if(a.searchParams.set("q",n),a.searchParams.set("format","jsonv2"),a.searchParams.set("limit","1"),a.searchParams.set("addressdetails","1"),o.country)a.searchParams.set("countrycodes",o.country.toLowerCase());let s=await ff(()=>fetch(a,{headers:{"user-agent":e,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!s.ok)throw Error(`Nominatim responded ${s.status}`);let u=(await s.json())?.[0];if(!u)return null;let c=Number(u.lat),l=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(l))return null;let m=wf(u);return{latitude:c,longitude:l,formatted:String(u.display_name??n),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[m],precision:m,provider:"nominatim"}}}}var md=null;function yf(t){md=t}function pd(){return md??tr()}async function hf(t,e={}){let r=e.driver??pd(),o=e.minimumPrecision??"street",n=`geocode:${r.name}:${Ce(t).toLowerCase()}`,a=await bf(n);if(a!==void 0)return a;let s=await r.geocode(t),i=s&&st[s.precision]>=st[o]?s:null;return await _f(n,i,i?e.cacheSeconds??2592000:600),i}function gf(t,e,r){if(e.length===0)return null;let o=e[0],n=ce(t,o);for(let a of e.slice(1)){let s=ce(t,a);if(s<n)n=s,o=a}return{covered:n<=r,distanceMeters:Math.round(n),nearest:o}}async function bf(t){try{let r=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!r)return;let o=await r.get(t);if(o===null||o===void 0)return;return o==="null"?null:JSON.parse(String(o))}catch{return}}async function _f(t,e,r){try{let n=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!n)return;await n.set(t,e===null?"null":JSON.stringify(e),r)}catch{}}var ar={};g(ar,{LicenseKeyInputError:()=>T,bulkDestroy:()=>hd,bulkSoftDelete:()=>gd,bulkStore:()=>Fd,destroy:()=>wd,fetchAll:()=>Rd,fetchById:()=>_d,softDelete:()=>yd,store:()=>Pd,update:()=>kd,updateExpiration:()=>Ed,updateStatus:()=>Td,validateLicenseKeyWrite:()=>be});import{db as or,matchedRows as fd}from"@stacksjs/database";async function wd(t){try{let e=await or.deleteFrom("license_keys").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license key: ${e.message}`);throw e}}async function yd(t){try{return(await fd(or.updateTable("license_keys").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license key: ${e.message}`);throw e}}async function hd(t){if(!t.length)return 0;try{let e=await or.deleteFrom("license_keys").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license keys: ${e.message}`);throw e}}async function gd(t){if(!t.length)return 0;try{return(await fd(or.updateTable("license_keys").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license keys: ${e.message}`);throw e}}import{db as bd}from"@stacksjs/database";async function _d(t){let e=await bd.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Rd(){return w(await bd.selectFrom("license_keys").selectAll().execute())}var{randomUUIDv7:vd}=globalThis.Bun;import{db as sn}from"@stacksjs/database";import{db as nn}from"@stacksjs/database";var xd=["Standard License","Premium License","Enterprise License"],Dd=["active","inactive","unassigned"];class T extends TypeError{constructor(t){super(t);this.name="LicenseKeyInputError"}}function it(t,e,r){return t[r]!==void 0?t[r]:e?.[r]}function an(t,e,r,o){let n=it(t,e,r);if(n===void 0||n===null||n==="")return null;let a=Number(n);if(!Number.isSafeInteger(a)||a<1)throw new T(`${o} must be a positive integer or null.`);return a}function Rf(t){if(typeof t==="number")return t>2147483647?Math.floor(t/1000):t;if(typeof t==="string"&&/^\d{10,13}$/.test(t))return t.length===13?Math.floor(Number(t)/1000):Number(t);if(typeof t==="string"){let e=/^\d{4}-\d{2}-\d{2} \d/.test(t)?`${t.replace(" ","T")}Z`:t;return Math.floor(new Date(e).getTime()/1000)}return Number.NaN}async function be(t,e){let r=String(it(t,e,"key")||"").trim().toUpperCase(),o=String(it(t,e,"template")||""),n=String(it(t,e,"status")||""),a=Rf(it(t,e,"expiry_date")),s=an(t,e,"customer_id","Customer"),i=an(t,e,"product_id","Product"),u=an(t,e,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new T("License key must use five groups of four uppercase letters or numbers.");if(!xd.includes(o))throw new T(`Template must be one of: ${xd.join(", ")}.`);if(!Dd.includes(n))throw new T(`Status must be one of: ${Dd.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new T("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,l,m]=await Promise.all([s?nn.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?nn.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?nn.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new T(`Customer ${s} was not found.`);if(i&&!l)throw new T(`Product ${i} was not found.`);if(u&&!m)throw new T(`Order ${u} was not found.`);if(s&&m?.customer_id&&Number(m.customer_id)!==s)throw new T(`Order ${u} belongs to Customer ${m.customer_id}, not Customer ${s}.`);return{...t,key:r,template:o,expiry_date:a,status:n,customer_id:s,product_id:i,order_id:u}}async function Pd(t){try{let e=vd(),r=ot(t),o={...await be(r),uuid:e};await sn.insertInto("license_keys").values(o).executeTakeFirst();let n=await sn.selectFrom("license_keys").where("uuid","=",e).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created license key");return d(n)}catch(e){if(e instanceof T)throw e;if(e instanceof Error){if(e.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${e.message}`)}throw e}}async function Fd(t){if(!t.length)return 0;try{let e=await Promise.all(t.map(async(o)=>({...await be(ot(o)),uuid:vd()}))),r=await sn.insertInto("license_keys").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof T)throw e;if(e instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${e.message}`);throw e}}import{db as nr}from"@stacksjs/database";import{formatDate as un}from"@stacksjs/orm";async function kd(t,e){try{if(!t)throw Error("License key ID is required for update");let r=await nr.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=ot(e),n=await be(o,r),a=await nr.updateTable("license_keys").set({...n,updated_at:un(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return d(a)}catch(r){if(r instanceof T)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function Td(t,e){try{let r=await nr.updateTable("license_keys").set({status:e,updated_at:un(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function Ed(t,e){try{let r={updated_at:un(new Date)};if(e!==void 0)r.expiry_date=e;let o=await nr.updateTable("license_keys").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update expiration information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var cr={};g(cr,{bulkDestroy:()=>Md,bulkSoftDelete:()=>Id,bulkStore:()=>Od,destroy:()=>Cd,fetchAll:()=>Nd,fetchById:()=>ur,formatShippingOptions:()=>Ud,getActiveShippingMethods:()=>$d,softDelete:()=>Ad,store:()=>Bd,update:()=>Wd,updatePricing:()=>jd,updateStatus:()=>Ld});import{db as sr,matchedRows as Sd}from"@stacksjs/database";async function Cd(t){try{let e=await sr.deleteFrom("shipping_methods").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping method: ${e.message}`);throw e}}async function Ad(t){try{return(await Sd(sr.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${e.message}`);throw e}}async function Md(t){if(!t.length)return 0;try{let e=await sr.deleteFrom("shipping_methods").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping methods: ${e.message}`);throw e}}async function Id(t){if(!t.length)return 0;try{return(await Sd(sr.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${e.message}`);throw e}}import{db as ir}from"@stacksjs/database";async function ur(t){let e=await ir.selectFrom("shipping_methods").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=await ir.selectFrom("shipping_zones").where("shipping_method_id","=",t).selectAll().execute();return{...e,shippingZones:r}}return}async function Nd(){let t=await ir.selectFrom("shipping_methods").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((a)=>a.id))],n=(await ir.selectFrom("shipping_zones").where("shipping_method_id","in",e).selectAll().execute()).reduce((a,s)=>{let i=s.shipping_method_id;if(i!==null&&i!==void 0){if(!a[i])a[i]=[];a[i].push(s)}return a},{});return t.map((a)=>({...a,shipping_zones:n[a.id]||[]}))}var{randomUUIDv7:Jd}=globalThis.Bun;import{db as ut}from"@stacksjs/database";async function Bd(t){try{let e=Jd(),r={...et(t),uuid:e};await ut.insertInto("shipping_methods").values(r).executeTakeFirst();let o=await ut.selectFrom("shipping_methods").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping method");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping method: ${e.message}`);throw e}}async function Od(t){if(!t.length)return 0;try{let e=t.map((o)=>({...et(o),uuid:Jd()})),r=await ut.insertInto("shipping_methods").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${e.message}`);throw e}}function Ud(){try{return ut.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping options: ${t.message}`);throw t}}async function $d(){try{let t=await ut.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping methods: ${t.message}`);throw t}}import{db as cn}from"@stacksjs/database";import{formatDate as dn}from"@stacksjs/orm";async function Wd(t,e){try{if(!t)throw Error("Shipping method ID is required for update");let r=await cn.updateTable("shipping_methods").set({...et(e),updated_at:dn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function Ld(t,e){try{let r=await cn.updateTable("shipping_methods").set({status:e,updated_at:dn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function jd(t,e,r){try{let o={updated_at:dn(new Date)};if(e!==void 0)o.base_rate=e;if(r!==void 0)o.free_shipping=r;let n=await cn.updateTable("shipping_methods").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update pricing information");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update pricing information: ${o.message}`);throw o}}var fr={};g(fr,{ShippingRateInputError:()=>A,bulkDestroy:()=>Gd,bulkStore:()=>ul,bulkUpdate:()=>dl,destroy:()=>zd,destroyByMethod:()=>Vd,destroyByZone:()=>qd,fetchAll:()=>Kd,fetchById:()=>Hd,formatShippingRateOptions:()=>el,getRateByWeightAndAddress:()=>Yd,getRateByWeightAndZone:()=>ln,getRatesByZone:()=>Qd,getShippingRatesByMethod:()=>tl,resolveZoneForAddress:()=>lr,store:()=>il,update:()=>cl,updateByMethod:()=>ml,updateByZone:()=>ll,validateShippingRateWrite:()=>_e,validateZoneMatchesAddress:()=>Xd});import{db as dr}from"@stacksjs/database";async function zd(t){try{let e=await dr.deleteFrom("shipping_rates").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rate: ${e.message}`);throw e}}async function Gd(t){if(!t.length)return 0;try{let e=await dr.deleteFrom("shipping_rates").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates: ${e.message}`);throw e}}async function qd(t){try{let e=await dr.deleteFrom("shipping_rates").where("shipping_zone_id","=",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${e.message}`);throw e}}async function Vd(t){try{let e=await dr.deleteFrom("shipping_rates").where("shipping_method_id","=",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${e.message}`);throw e}}import{db as W}from"@stacksjs/database";async function Hd(t){let e=await W.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.shipping_zone_id)r=await W.selectFrom("shipping_zones").where("id","=",e.shipping_zone_id).selectAll().executeTakeFirst();if(e.shipping_method_id)o=await W.selectFrom("shipping_methods").where("id","=",e.shipping_method_id).selectAll().executeTakeFirst();return{...e,shipping_zone:r,shipping_method:o}}return}async function Kd(){let t=await W.selectFrom("shipping_rates").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((i)=>i.shipping_zone_id).filter((i)=>i!==null&&i!==void 0))],r=[...new Set(t.map((i)=>i.shipping_method_id).filter((i)=>i!==null&&i!==void 0))],[o,n]=await Promise.all([e.length?W.selectFrom("shipping_zones").where("id","in",e).selectAll().execute():[],r.length?W.selectFrom("shipping_methods").where("id","in",r).selectAll().execute():[]]),a=o.reduce((i,u)=>(i[u.id]=u,i),{}),s=n.reduce((i,u)=>(i[u.id]=u,i),{});return t.map((i)=>({...i,shipping_zone:i.shipping_zone_id?a[i.shipping_zone_id]:[],shipping_method:i.shipping_method_id?s[i.shipping_method_id]:[]}))}async function Qd(t){try{let e=await W.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${e.message}`);throw e}}async function ln(t,e){try{let r=await W.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).where("weight_from","<=",t).where("weight_to",">=",t).executeTakeFirst();return d(r,!0)}catch(r){if(r instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${r.message}`);throw r}}async function lr(t){if(!t?.countryCode)return null;try{let e=await W.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t.countryCode}%`).where("status","=","active").execute();if(e.length===0)return null;let r=null;for(let o of e){let n=1;if(t.region&&o.regions&&Zd(o.regions,t.region))n=2;if(t.postalCode&&o.postal_codes&&Zd(o.postal_codes,t.postalCode))n=3;if(!r||n>r.score)r={id:o.id,score:n}}return r?.id??null}catch{return null}}async function Yd(t,e){let r=await lr(e);if(r==null)return;return ln(t,r)}async function Xd(t,e){return await lr(e)===t}function Zd(t,e){if(!t||!e)return!1;let r=e.trim().toUpperCase();for(let o of t.split(/[,|;]/))if(o.trim().toUpperCase()===r)return!0;return!1}async function el(){try{return(await W.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((e)=>e.shipping_method_id!==null&&e.shipping_method_id!==void 0&&e.shipping_zone_id!==null&&e.shipping_zone_id!==void 0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping rate options: ${t.message}`);throw t}}async function tl(t){try{let e=await W.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${e.message}`);throw e}}var{randomUUIDv7:sl}=globalThis.Bun;import{db as mn}from"@stacksjs/database";import{db as ct}from"@stacksjs/database";async function rl(){return w(await ct.selectFrom("shipping_zones").selectAll().execute())}async function mr(t){let e=await ct.selectFrom("shipping_zones").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}function ol(){try{return ct.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping zone options: ${t.message}`);throw t}}async function nl(){try{let t=await ct.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping zones: ${t.message}`);throw t}}async function al(t){try{let e=await ct.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t}%`).where("status","=","active").orderBy("name").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${e.message}`);throw e}}class A extends TypeError{constructor(t){super(t);this.name="ShippingRateInputError"}}function dt(t,e,r){return Number(t[r]??e?.[r])}async function _e(t,e){let r=dt(t,e,"shipping_method_id"),o=dt(t,e,"shipping_zone_id"),n=dt(t,e,"weight_from"),a=dt(t,e,"weight_to"),s=dt(t,e,"rate");if(!Number.isSafeInteger(r)||r<1)throw new A("Shipping method must be a positive integer.");if(!Number.isSafeInteger(o)||o<1)throw new A("Shipping zone must be a positive integer.");if(!Number.isFinite(n)||n<0)throw new A("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<n)throw new A("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new A("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([ur(r),mr(o)]);if(!i)throw new A(`Shipping method ${r} was not found.`);if(!u)throw new A(`Shipping zone ${o} was not found.`);if(Number(u.shipping_method_id)!==r)throw new A(`Shipping zone ${o} is not assigned to shipping method ${r}.`)}async function il(t){try{let e=re(t),r=Number(e.shipping_method_id),o=Number(e.shipping_zone_id);await _e(e);let n=sl(),a={...e,shipping_method_id:r,shipping_zone_id:o,uuid:n};await mn.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await mn.selectFrom("shipping_rates").where("uuid","=",n).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return d(s)}catch(e){if(e instanceof A)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rate: ${e.message}`);throw e}}async function ul(t){if(!t.length)return 0;try{for(let o of t){let n=re(o);await _e(n)}let e=t.map((o)=>({...re(o),uuid:sl()})),r=await mn.insertInto("shipping_rates").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof A)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${e.message}`);throw e}}import{db as lt,matchedRows as pn}from"@stacksjs/database";import{formatDate as pr}from"@stacksjs/orm";async function cl(t,e){try{if(!t)throw Error("Shipping rate ID is required for update");let r=await lt.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=re(e);await _e(o,r);let n=await lt.updateTable("shipping_rates").set({...o,updated_at:pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return d(n)}catch(r){if(r instanceof A)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function dl(t){if(!t.length)return 0;try{let e=0;for(let{id:r,data:o}of t)if((await pn(lt.updateTable("shipping_rates").set({...re(o),updated_at:pr(new Date)}).where("id","=",r))).length>0)e++;return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${e.message}`);throw e}}async function ll(t,e){try{return(await pn(lt.updateTable("shipping_rates").set({...re(e),updated_at:pr(new Date)}).where("shipping_zone_id","=",t))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function ml(t,e){try{return(await pn(lt.updateTable("shipping_rates").set({...re(e),updated_at:pr(new Date)}).where("shipping_method_id","=",t))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var xr={};g(xr,{ARRIVAL_RADIUS_METERS:()=>yn,NEARBY_RADIUS_METERS:()=>wn,assignStop:()=>fl,bearingInDegrees:()=>Xt,broadcastToChannel:()=>oe,completeStop:()=>yl,distanceInMeters:()=>ce,emitDeliveryArrived:()=>br,emitDeliveryAssigned:()=>yr,emitDeliveryCompleted:()=>_r,emitDeliveryFailed:()=>Rr,emitDeliveryNearby:()=>gr,emitDeliveryPosition:()=>wr,emitDeliveryStarted:()=>hr,estimateSecondsRemaining:()=>er,failStop:()=>hl,hasCoordinates:()=>at,isWithin:()=>ud,orderTrackingChannel:()=>de,recordCourierPing:()=>pl,routeTrackingChannel:()=>fn,startRoute:()=>gl,startStop:()=>wl});function de(t){return`order.${t}`}function fn(t){return`delivery-route.${t}`}async function Ae(t,e){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let o=r.dispatch;if(typeof o!=="function")return;o(t,e)}catch{}}async function oe(t,e,r){try{let o=await import("@stacksjs/realtime").catch(()=>null);if(!o)return;let n=o.channel;if(typeof n!=="function")return;await n(t).broadcast(e,r,"private")}catch{}}async function wr(t,e,r){await Promise.all([...t.map((o)=>oe(de(o),"delivery:position",r)),e==null?Promise.resolve():oe(fn(e),"delivery:position",r)])}async function yr(t){if(await Ae("delivery:assigned",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:assigned",{stop:t})}async function hr(t){if(await Ae("delivery:started",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:started",{stop:t})}async function gr(t,e,r){if(await Ae("delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r}),t.order_id!=null)await oe(de(t.order_id),"delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r})}async function br(t){if(await Ae("delivery:arrived",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:arrived",{stop:t})}async function _r(t){if(await Ae("delivery:completed",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:completed",{stop:t})}async function Rr(t,e){await Ae("delivery:failed",{stop:t,reason:e})}var{randomUUIDv7:xf}=globalThis.Bun;import{db as ne}from"@stacksjs/database";var wn=400,yn=60,Df=250;async function pl(t){let e=t.recordedAt??new Date().toISOString(),r=typeof t.accuracy!=="number"||t.accuracy<=Df,o=await ne.selectFrom("couriers").where("id","=",t.courierId).select(["id","latitude","longitude"]).executeTakeFirst();if(!o)throw Error(`Unknown courier: ${t.courierId}`);let n=at(o)?{latitude:o.latitude,longitude:o.longitude}:null,a=typeof t.heading==="number"?t.heading:n?Xt(n,t):null,s=await vf(t.courierId),i=s?await Pf(s.id):null,u=null,c=null,l=!1,m=!1,f=i&&at({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&f)u=Math.round(ce(t,f)),c=er(u,t.speed??0),m=u<=yn&&i.arrived_at==null,l=!m&&u<=wn&&i.status==="en_route"&&i.notified_nearby_at==null;let h=await Ff({courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e});if(r)await ne.updateTable("couriers").set({latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??0,last_ping_at:e}).where("id","=",t.courierId).execute();if(i&&(u!=null||c!=null))await ne.updateTable("delivery_stops").set({eta_at:c==null?i.eta_at:new Date(Date.now()+c*1000).toISOString()}).where("id","=",i.id).execute();if(r)await wr(i?.order_id==null?[]:[i.order_id],s?.id??null,{courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e,distanceToStopMeters:u,etaSeconds:c});if(l&&i)await ne.updateTable("delivery_stops").set({notified_nearby_at:e}).where("id","=",i.id).execute(),await gr(i,u,c);if(m&&i)await ne.updateTable("delivery_stops").set({status:"arrived",arrived_at:e}).where("id","=",i.id).execute(),await br({...i,status:"arrived",arrived_at:e});return{pingId:h,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:l,crossedArrival:m}}async function vf(t){return await ne.selectFrom("delivery_routes").where("courier_id","=",t).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function Pf(t){let e=await ne.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return e.find((r)=>r.status==="en_route")??e.find((r)=>r.status==="arrived")??e[0]??null}async function Ff(t){let e=xf();return await ne.insertInto("courier_pings").values({uuid:e,courier_id:t.courierId,delivery_route_id:t.routeId,latitude:t.latitude,longitude:t.longitude,heading:t.heading,speed:t.speed??0,accuracy:t.accuracy,recorded_at:t.recordedAt}).executeTakeFirst(),(await ne.selectFrom("courier_pings").where("uuid","=",e).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:kf}=globalThis.Bun;import{db as M}from"@stacksjs/database";function hn(t){return t.type==="pickup"}async function fl(t){let e=kf(),r=t.sequence??await Ef(t.deliveryRouteId);await M.insertInto("delivery_stops").values({uuid:e,delivery_route_id:t.deliveryRouteId,order_id:t.orderId??null,sequence:r,status:"pending",address:t.address,latitude:t.latitude??null,longitude:t.longitude??null,recipient_name:t.recipientName??null,recipient_phone:t.recipientPhone??null,eta_at:t.etaAt??null,type:t.type??"dropoff"}).executeTakeFirst();let o=await Cf(e);if(o)await yr(o);return o??{}}async function wl(t){await M.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",t).execute();let e=await bn(t);if(!e)return null;if(e.order_id!=null&&!hn(e))await gn(e.order_id,"OUT_FOR_DELIVERY");return await hr(e),e}async function yl(t,e){let r=new Date().toISOString();await M.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await Sf(t)?{}:{arrived_at:r},...e?{notes:e}:{}}).where("id","=",t).execute();let o=await bn(t);if(!o)return null;if(o.order_id!=null)await gn(o.order_id,hn(o)?"OUT_FOR_DELIVERY":"DELIVERED");return await _r(o),await bl(o.delivery_route_id),o}async function hl(t,e){await M.updateTable("delivery_stops").set({status:"failed",notes:e}).where("id","=",t).execute();let r=await bn(t);if(!r)return null;if(r.order_id!=null&&!hn(r))await gn(r.order_id,"SHIPPED");return await Rr(r,e),await bl(r.delivery_route_id),r}async function gl(t){await M.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",t).execute()}async function bl(t){if(t==null)return;if(await M.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await M.selectFrom("delivery_routes").where("id","=",t).select(["courier_id"]).executeTakeFirst();if(await M.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",t).execute(),r?.courier_id!=null)await M.updateTable("couriers").set({status:"active"}).where("id","=",r.courier_id).execute()}async function gn(t,e){let r=await M.selectFrom("orders").where("id","=",t).select(["id","status"]).executeTakeFirst();if(!r)return;let o=await Promise.resolve().then(() => (Fe(),{}));let s=Tf(r.status,e,ve);if(s.length===0){let{log:i}=await import("@stacksjs/logging").catch(()=>({log:null}));i?.warn(`[delivery] refused to move order ${t} from ${r.status} to ${e}: no legal transition`);return}for(let i of s)await M.updateTable("orders").set({status:i}).where("id","=",t).execute(),await Pe(i,{...r,status:i})}function Tf(t,e,r){if(t===e)return[];if(r(t,e))return[e];for(let o of["PROCESSING","SHIPPED"]){if(o===t||o===e)continue;if(r(t,o)&&r(o,e))return[o,e]}return[]}async function Ef(t){return(await M.selectFrom("delivery_stops").where("delivery_route_id","=",t).select(["sequence"]).execute()).reduce((r,o)=>Math.max(r,o.sequence??0),0)+1}async function Sf(t){return(await M.selectFrom("delivery_stops").where("id","=",t).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function bn(t){return await M.selectFrom("delivery_stops").where("id","=",t).selectAll().executeTakeFirst()??null}async function Cf(t){return await M.selectFrom("delivery_stops").where("uuid","=",t).selectAll().executeTakeFirst()??null}var Fr={};g(Fr,{bulkDestroy:()=>Dl,bulkSoftDelete:()=>vl,bulkStore:()=>kl,destroy:()=>Rl,fetchAll:()=>rl,fetchById:()=>mr,formatZoneOptions:()=>ol,getActiveShippingZones:()=>nl,getZonesByCountry:()=>al,softDelete:()=>xl,store:()=>Fl,update:()=>Tl,updateCountries:()=>Sl,updateRegionsAndPostalCodes:()=>Cl,updateStatus:()=>El});import{db as Dr,matchedRows as _l}from"@stacksjs/database";async function Rl(t){try{let e=await Dr.deleteFrom("shipping_zones").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zone: ${e.message}`);throw e}}async function xl(t){try{return(await _l(Dr.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${e.message}`);throw e}}async function Dl(t){if(!t.length)return 0;try{let e=await Dr.deleteFrom("shipping_zones").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zones: ${e.message}`);throw e}}async function vl(t){if(!t.length)return 0;try{return(await _l(Dr.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${e.message}`);throw e}}var{randomUUIDv7:Pl}=globalThis.Bun;import{db as _n}from"@stacksjs/database";async function Fl(t){try{let e=Pl(),r={...tt(t),uuid:e};await _n.insertInto("shipping_zones").values(r).executeTakeFirst();let o=await _n.selectFrom("shipping_zones").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping zone");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zone: ${e.message}`);throw e}}async function kl(t){if(!t.length)return 0;try{let e=t.map((o)=>({...tt(o),uuid:Pl()})),r=await _n.insertInto("shipping_zones").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${e.message}`);throw e}}import{db as vr}from"@stacksjs/database";import{formatDate as Pr}from"@stacksjs/orm";async function Tl(t,e){try{if(!t)throw Error("Shipping zone ID is required for update");let r=await vr.updateTable("shipping_zones").set({...tt(e),updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function El(t,e){try{let r=await vr.updateTable("shipping_zones").set({status:e,updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function Sl(t,e){try{let r=await vr.updateTable("shipping_zones").set({countries:e,updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function Cl(t,e,r){try{let o={updated_at:Pr(new Date)};if(e!==void 0)o.regions=e;if(r!==void 0)o.postal_codes=r;let n=await vr.updateTable("shipping_zones").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update regions and postal codes");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${o.message}`);throw o}}var Af={digital:Kt,couriers:Yt,geocoding:rr,licenses:ar,methods:cr,rates:fr,routes:Zt,tracking:xr,zones:Fr},Mf=Af;var vn={};g(vn,{activeTaxRates:()=>xn,breakdownFor:()=>Dn,bulkDestroy:()=>Nl,bulkStore:()=>Ll,destroy:()=>Il,fetchAll:()=>Ol,fetchById:()=>Bl,store:()=>Wl,taxFor:()=>Al,update:()=>jl,updateDefaultStatus:()=>ql,updateRate:()=>Gl,updateStatus:()=>zl});import{db as If}from"@stacksjs/database";function Nf(t){let e=Number(t);return Number.isFinite(e)?e/100:0}async function xn(t={}){let e=If.selectFrom("tax_rates").where("status","=","active").selectAll();if(t.country)e=e.where("country","=",t.country);let r=await e.execute();if(!t.codes?.length)return r;let o=new Set(t.codes);return r.filter((n)=>o.has(String(n.code??"")))}function Dn(t,e,r={}){let o=Math.max(0,Math.round(t)),n=[],a=0,s=0;for(let i of e){let u=Nf(i.rate),c=Math.round(o*u),l=Boolean(r.exempt&&i.exemptible);if(l)s+=c;else a+=c;n.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:l?0:c,exempted:l})}return{taxable:o,components:n,tax:a,exempted:s}}async function Al(t,e={}){return Dn(t,await xn(e),e)}import{db as Ml}from"@stacksjs/database";async function Il(t){try{let e=await Ml.deleteFrom("tax_rates").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rate: ${e.message}`);throw e}}async function Nl(t){if(!t.length)return 0;try{let e=await Ml.deleteFrom("tax_rates").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rates: ${e.message}`);throw e}}import{db as Jl}from"@stacksjs/database";async function Bl(t){let e=await Jl.selectFrom("tax_rates").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Ol(){return w(await Jl.selectFrom("tax_rates").selectAll().execute())}var{randomUUIDv7:Ul}=globalThis.Bun;import{db as $l}from"@stacksjs/database";async function Wl(t){try{return await $l.transaction(async(e)=>{let r={...t,uuid:Ul()};if(r.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();let o=await e.insertInto("tax_rates").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create tax rate");return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rate: ${e.message}`);throw e}}async function Ll(t){if(!t.length)return 0;try{return await $l.transaction(async(e)=>{let r=0;for(let o of t){let n={...o,uuid:Ul()};if(n.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();if(await e.insertInto("tax_rates").values(n).executeTakeFirst())r++}return r})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${e.message}`);throw e}}import{db as kr}from"@stacksjs/database";import{formatDate as Tr}from"@stacksjs/orm";async function jl(t,e){try{if(!t)throw Error("Tax rate ID is required for update");return await kr.transaction(async(r)=>{let o=await r.selectFrom("tax_rates").select("is_default").where("id","=",t).executeTakeFirst();if(!o)return;let n=e.is_default??Boolean(o.is_default),a=Tr(new Date);if(n)await r.updateTable("tax_rates").set({is_default:!1,updated_at:a}).where("id","!=",t).execute();let s=await r.updateTable("tax_rates").set({...e,updated_at:a}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function zl(t,e){try{let r=await kr.updateTable("tax_rates").set({status:e,updated_at:Tr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function Gl(t,e){try{let r=await kr.updateTable("tax_rates").set({rate:e,updated_at:Tr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function ql(t,e){try{return await kr.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",t).executeTakeFirst())return!1;let n=Tr(new Date);if(e)await r.updateTable("tax_rates").set({is_default:!1,updated_at:n}).where("id","!=",t).execute();return await r.updateTable("tax_rates").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate default status: ${r.message}`);throw r}}var Sn={};g(Sn,{default:()=>Gf,products:()=>Sr,restaurant:()=>Ie});var Sr={};g(Sr,{bulkDestroy:()=>Zl,bulkStore:()=>lm,destroy:()=>Vl,fetchAll:()=>Hl,fetchById:()=>mt,fetchCancelledBetweenDates:()=>rm,fetchConversionRates:()=>am,fetchCountBetweenDates:()=>sm,fetchCountByAllQuantities:()=>Xl,fetchCountByDate:()=>Ql,fetchCountByDateGrouped:()=>im,fetchCountByQuantity:()=>Yl,fetchCountBySource:()=>Kl,fetchCountByStatus:()=>nm,fetchNotifiedBetweenDates:()=>em,fetchPurchasedBetweenDates:()=>tm,fetchWaiting:()=>om,store:()=>dm,update:()=>Er,updatePartySize:()=>pm,updateStatus:()=>mm});import{db as Pn}from"@stacksjs/database";async function Vl(t){try{let e=await Pn.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await Pn.deleteFrom("waitlist_products").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist product: ${e.message}`);throw e}}async function Zl(t){if(!t.length)return 0;try{let e=await Pn.deleteFrom("waitlist_products").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${e.message}`);throw e}}import{db as F}from"@stacksjs/database";import{formatDate as k}from"@stacksjs/orm";async function mt(t){let e=await F.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Hl(){return w(await F.selectFrom("waitlist_products").selectAll().execute())}async function Kl(t,e){let r=F.selectFrom("waitlist_products").select(["source",F.fn.count("id").as("count")]).groupBy("source");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{source:a,count:s})=>(n[a]=s,n),{})}async function Ql(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=k(e),n=k(r);return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function Yl(t){return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("quantity","=",t).executeTakeFirst())?.count??0}async function Xl(t,e){let r=F.selectFrom("waitlist_products").select(["quantity",F.fn.count("id").as("count")]).groupBy("quantity");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{quantity:a,count:s})=>(n[a]=s,n),{})}async function em(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",o).whereNotNull("notified_at").execute();return w(n)}async function tm(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",o).whereNotNull("purchased_at").execute();return w(n)}async function rm(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",o).whereNotNull("cancelled_at").execute();return w(n)}async function om(){let t=await F.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute();return w(t)}async function nm(t,e,r){let o=F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("status","=",t);if(e&&r){let a=k(e),s=k(r);o=o.where("created_at",">=",a).where("created_at","<=",s)}return(await o.executeTakeFirst())?.count??0}async function am(t,e){let r=F.selectFrom("waitlist_products").select(["status",F.fn.count("id").as("count")]).groupBy("status");if(t&&e){let u=k(t),c=k(e);r=r.where("created_at",">=",u).where("created_at","<=",c)}let o=await r.execute(),n=o.reduce((u,{count:c})=>u+c,0),a=Number(o.find((u)=>u.status==="purchased")?.count??0),s=n>0?a/n*100:0,i=o.reduce((u,{status:c,count:l})=>(u[c]={count:l,percentage:n>0?l/n*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function sm(t,e){let r=k(t),o=k(e);return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",o).executeTakeFirst())?.count??0}async function im(t,e){let r=F.selectFrom("waitlist_products").select(["created_at"]);if(t&&e){let a=k(t),s=k(e);r=r.where("created_at",">=",a).where("created_at","<=",s)}let n=(await r.execute()).reduce((a,{created_at:s})=>{let i=(s||"").split("T")[0]||"unknown";return a[i]=(a[i]||0)+1,a},{});return Object.entries(n).map(([a,s])=>({date:a,count:s})).sort((a,s)=>a.date.localeCompare(s.date))}var{randomUUIDv7:cm}=globalThis.Bun;import{db as Fn}from"@stacksjs/database";import{formatDate as um}from"@stacksjs/orm";var Jf={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Bf(t){return typeof t==="number"||t instanceof Date?um(t):t}function pt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));if(r.quantity===void 0&&r.party_size!==void 0)r.quantity=r.party_size;delete r.party_size;for(let n of["notified_at","purchased_at","cancelled_at"])if(r[n]!==void 0)r[n]=Bf(r[n]);let o=Jf[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=um(new Date);return r}async function dm(t){try{let e=cm(),r={...pt(t),uuid:e,status:t.status||"waiting"};await Fn.insertInto("waitlist_products").values(r).executeTakeFirst();let o=await Fn.selectFrom("waitlist_products").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create waitlist product");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist product: ${e.message}`);throw e}}async function lm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...pt(o),status:o.status||"waiting",uuid:cm()})),r=await Fn.insertInto("waitlist_products").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${e.message}`);throw e}}import{db as Of}from"@stacksjs/database";import{formatDate as Uf}from"@stacksjs/orm";async function Er(t,e){try{if(!t)throw Error("Waitlist product ID is required for update");let r=await mt(t);if(!r)return;await Of.updateTable("waitlist_products").set({...pt(e,r),updated_at:Uf(new Date)}).where("id","=",t).execute();let o=await mt(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function mm(t,e){return await Er(t,{status:e})}async function pm(t,e){return await Er(t,{quantity:e})}var Ie={};g(Ie,{bulkDestroy:()=>wm,bulkStore:()=>Jm,destroy:()=>fm,fetchAll:()=>ym,fetchAverageWaitTimes:()=>Pm,fetchBetweenDates:()=>Rm,fetchById:()=>ft,fetchConversionRates:()=>vm,fetchCountByAllPartySizes:()=>_m,fetchCountByDate:()=>gm,fetchCountByPartySize:()=>bm,fetchCountByTablePreference:()=>hm,fetchCurrentWaitTimes:()=>Cm,fetchNoShowStats:()=>Sm,fetchSeatedBetweenDates:()=>xm,fetchSeatedStats:()=>Am,fetchSeatingRate:()=>Em,fetchTablesTurnedToday:()=>Tm,fetchTimeSeriesStats:()=>Mm,fetchWaiting:()=>Dm,fetchWaitingWithPartySizes:()=>km,fetchWaitingWithQuotedTimes:()=>Fm,store:()=>Nm,update:()=>Me,updatePartySize:()=>Om,updateQueuePosition:()=>$m,updateStatus:()=>Bm,updateWaitTimes:()=>Um});import{db as kn}from"@stacksjs/database";async function fm(t){try{let e=await kn.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await kn.deleteFrom("waitlist_restaurants").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${e.message}`);throw e}}async function wm(t){if(!t.length)return 0;try{let e=await kn.deleteFrom("waitlist_restaurants").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as R}from"@stacksjs/database";import{formatDate as B}from"@stacksjs/orm";async function ft(t){let e=await R.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ym(){return w(await R.selectFrom("waitlist_restaurants").selectAll().execute())}async function hm(){return(await R.selectFrom("waitlist_restaurants").select(["table_preference",R.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((e,{table_preference:r,count:o})=>(e[r]=o,e),{})}async function gm(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r);return(await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function bm(t){return(await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("party_size","=",t).executeTakeFirst())?.count??0}async function _m(){return(await R.selectFrom("waitlist_restaurants").select(["party_size",R.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((e,{party_size:r,count:o})=>(e[r]=o,e),{})}async function Rm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",o).execute();return w(n)}async function xm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",o).where("status","=","seated").execute();return w(n)}async function Dm(){let t=await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute();return w(t)}async function vm(){let t=await R.selectFrom("waitlist_restaurants").select(["status",R.fn.count("id").as("count")]).groupBy("status").execute(),e=t.reduce((a,{count:s})=>a+s,0),r=t.find((a)=>a.status==="seated")?.count??0,o=e>0?Number(r)/e*100:0,n=t.reduce((a,{status:s,count:i})=>(a[s]={count:i,percentage:e>0?i/e*100:0},a),{});return{totalConversionRate:o,statusBreakdown:n}}async function Pm(){let t=await R.selectFrom("waitlist_restaurants").select([R.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),R.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:t?.avg_quoted_wait_time??0,averageActualWaitTime:t?.avg_actual_wait_time??0}}async function Fm(){let t=w(await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((o,n)=>o+(n.quoted_wait_time??0),0),r=t.length>0?e/t.length:0;return{entries:t,totalQuotedWaitTime:e,averageQuotedWaitTime:r}}async function km(){let t=w(await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((n,a)=>n+a.party_size,0),r=t.length>0?e/t.length:0,o=t.reduce((n,a)=>(n[a.party_size]=(n[a.party_size]||0)+1,n),{});return{entries:t,totalPartySize:e,averagePartySize:r,partySizeBreakdown:o}}async function Tm(){let t=new Date,e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r),a=await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",o).where("check_in_time","<=",n).execute(),s=a.length,i=a.reduce((m,f)=>m+f.party_size,0),u=s>0?i/s:0,c=a.reduce((m,f)=>(m[f.table_preference]=(m[f.table_preference]||0)+1,m),{}),l=a.reduce((m,f)=>(m[f.party_size]=(m[f.party_size]||0)+1,m),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:l}}async function Em(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").select(["status",R.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",o).groupBy("status").execute(),a=n.reduce((c,{count:l})=>c+l,0),s=n.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=n.reduce((c,{status:l,count:m})=>(c[l]={count:m,percentage:a>0?m/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function Sm(t,e){let r=B(t),o=B(e),n=R.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",o),a=await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("check_in_time",">=",r).where("check_in_time","<=",o).executeTakeFirst(),s=await n.execute(),i=s.length,u=a?.count&&a.count>0?i/a.count*100:0,c=s.reduce((_,D)=>_+(D.quoted_wait_time??0),0),l=i>0?c/i:0,m=s.reduce((_,D)=>_+D.party_size,0),f=i>0?m/i:0,h=s.reduce((_,D)=>(_[D.table_preference]=(_[D.table_preference]||0)+1,_),{}),b=s.reduce((_,D)=>(_[D.party_size]=(_[D.party_size]||0)+1,_),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:l,averagePartySize:f,breakdownByTablePreference:h,breakdownByPartySize:b}}async function Cm(){let t=await R.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),e=t.reduce((n,a)=>n+(a.quoted_wait_time||0),0),r=t.reduce((n,a)=>n+(a.actual_wait_time||0),0),o=t.length;return{averageQuoted:o>0?e/o:0,averageActual:o>0?r/o:0}}async function Am(){let t=Date.now()-86400000,e=await R.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",t).execute(),r=Array.from({length:24},(o,n)=>({hour:n,count:e.filter((a)=>a.seated_at===n).length}));return{total:e.length,byHour:r}}async function Mm(){return(await R.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((e,r)=>{let o=r.created_at;if(!e[o])e[o]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return e[o].total++,e[o][r.status]++,e},{})}var{randomUUIDv7:Im}=globalThis.Bun;import{db as En}from"@stacksjs/database";import{formatDate as Tn}from"@stacksjs/orm";var $f={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function Wf(t){if(typeof t==="number")return Tn(t<=2147483647?t*1000:t);if(t instanceof Date)return Tn(t);return t}function wt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));for(let n of["check_in_time","seated_at","no_show_at","cancelled_at"])if(r[n]!==void 0)r[n]=Wf(r[n]);let o=$f[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=Tn(new Date);return r}async function Nm(t){try{let e=Im(),r={...wt(t),status:t.status||"waiting",uuid:e};await En.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let o=await En.selectFrom("waitlist_restaurants").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create restaurant waitlist entry");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${e.message}`);throw e}}async function Jm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...wt(o),status:o.status||"waiting",uuid:Im()})),r=await En.insertInto("waitlist_restaurants").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as Lf}from"@stacksjs/database";import{formatDate as jf}from"@stacksjs/orm";async function Me(t,e){try{if(!t)throw Error("Restaurant waitlist entry ID is required for update");let r=await ft(t);if(!r)return;await Lf.updateTable("waitlist_restaurants").set({...wt(e,r),updated_at:jf(new Date)}).where("id","=",t).execute();let o=await ft(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function Bm(t,e){return await Me(t,{status:e})}async function Om(t,e){return await Me(t,{party_size:e})}async function Um(t,e,r){return await Me(t,{quoted_wait_time:e,...r===void 0?{}:{actual_wait_time:r}})}async function $m(t,e){return await Me(t,{queue_position:e})}var zf={products:Sr,restaurant:Ie},Gf=zf;var qf={auctions:no,carts:ao,coupons:io,customers:co,devices:wo,errors:go,giftCards:Ro,orders:No,payments:Jo,products:jo,receipts:Ho,restaurant:Ie,shippings:Rn,tax:vn,waitlists:Sn},ck=qf;export{no as auctions,ao as carts,qf as commerce,io as coupons,co as customers,ck as default,wo as devices,go as errors,Ro as giftCards,No as orders,Jo as payments,jo as products,Ho as receipts,Ie as restaurant,Rn as shippings,vn as tax,Sn as waitlists};
|
|
@@ -21,6 +21,13 @@ export declare function update(id: number, data: Omit<PaymentUpdate, 'id'>): Pro
|
|
|
21
21
|
* Amounts are integer minor units. A single conditional update performs the
|
|
22
22
|
* increment and remaining-balance check atomically, so concurrent operators
|
|
23
23
|
* cannot record more than the captured amount.
|
|
24
|
+
*
|
|
25
|
+
* `status` is assigned before `refund_amount` because MySQL evaluates SET
|
|
26
|
+
* assignments left to right against values already updated, so a CASE placed
|
|
27
|
+
* after the increment recorded a full refund as `partiallyRefunded`. Its never-
|
|
28
|
+
* taken `WHEN 1 = 0 THEN status` branch types the CASE as the column: a CASE of
|
|
29
|
+
* bare literals is text, which PostgreSQL will not assign to the enum type
|
|
30
|
+
* `status` has there.
|
|
24
31
|
*/
|
|
25
32
|
export declare function recordRefund(id: number, amount: number): Promise<PaymentJsonResponse>;
|
|
26
33
|
declare type PaymentJsonResponse = ModelRow<typeof Payment>;
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/commerce",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.74.
|
|
5
|
+
"version": "0.74.47",
|
|
6
6
|
"description": "Stacks commerce utilities.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -58,17 +58,17 @@
|
|
|
58
58
|
"prepublishOnly": "bun run build"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@stacksjs/cache": "0.74.
|
|
62
|
-
"@stacksjs/config": "0.74.
|
|
63
|
-
"@stacksjs/database": "0.74.
|
|
64
|
-
"@stacksjs/env": "0.74.
|
|
65
|
-
"@stacksjs/error-handling": "0.74.
|
|
66
|
-
"@stacksjs/events": "0.74.
|
|
67
|
-
"@stacksjs/logging": "0.74.
|
|
68
|
-
"@stacksjs/orm": "0.74.
|
|
69
|
-
"@stacksjs/payments": "0.74.
|
|
70
|
-
"@stacksjs/realtime": "0.74.
|
|
71
|
-
"@stacksjs/strings": "0.74.
|
|
61
|
+
"@stacksjs/cache": "0.74.47",
|
|
62
|
+
"@stacksjs/config": "0.74.47",
|
|
63
|
+
"@stacksjs/database": "0.74.47",
|
|
64
|
+
"@stacksjs/env": "0.74.47",
|
|
65
|
+
"@stacksjs/error-handling": "0.74.47",
|
|
66
|
+
"@stacksjs/events": "0.74.47",
|
|
67
|
+
"@stacksjs/logging": "0.74.47",
|
|
68
|
+
"@stacksjs/orm": "0.74.47",
|
|
69
|
+
"@stacksjs/payments": "0.74.47",
|
|
70
|
+
"@stacksjs/realtime": "0.74.47",
|
|
71
|
+
"@stacksjs/strings": "0.74.47",
|
|
72
72
|
"ts-spreadsheets": "^0.2.0"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|