@stacksjs/commerce 0.75.90 → 0.75.91

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/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- var uy=Object.defineProperty;var cy=(e)=>e;function dy(e,t){this[e]=cy.bind(null,t)}var E=(e,t)=>{for(var r in t)uy(e,r,{get:t[r],enumerable:!0,configurable:!0,set:dy.bind(t,r)})};var ly=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};function Ue(e,t){if(e===t)return!0;return Hg[e]?.includes(t)??!1}async function Qe(e,t){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let n=r.dispatch;if(typeof n!=="function")return;n(e,t)}catch{}}async function vr(e){await Qe("order:created",{order:e})}async function Ye(e,t){await Qe("order:paid",{order:e,payment:t})}async function sa(e){await Qe("order:shipped",{order:e})}async function Kg(e){await Qe("order:out_for_delivery",{order:e})}async function ia(e){await Qe("order:delivered",{order:e})}async function Mt(e,t){await Qe("order:cancelled",{order:e,reason:t})}async function Nt(e,t){await Qe("order:refunded",{order:e,refundAmount:t})}async function ct(e,t){switch(e){case"PROCESSING":return Ye(t);case"SHIPPED":return sa(t);case"OUT_FOR_DELIVERY":return Kg(t);case"DELIVERED":return ia(t);case"CANCELLED":return Mt(t);case"REFUNDED":return Nt(t);case"PENDING":default:}}var Hg;var dt=ly(()=>{Hg={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 ro={};E(ro,{DEFAULT_INCREMENT_LADDER:()=>_e,auctionChannel:()=>or,auctionTotals:()=>zn,biddersFor:()=>Fn,bids:()=>Jn,bidsByBidder:()=>En,bidsForAuction:()=>An,bidsForItem:()=>Tn,broadcastBid:()=>Mn,broadcastItemClosed:()=>On,broadcastPledge:()=>Nn,closeAuction:()=>Hn,closeDueItems:()=>Vn,closeItem:()=>St,closingSoon:()=>Zn,closingSoonNotification:()=>yy,currencyFor:()=>$n,determineWinner:()=>ot,effectiveCloseAt:()=>Me,engine:()=>Wn,extendedCloseAt:()=>Rt,fetchAuction:()=>pe,fetchAuctionForEvent:()=>Ln,fetchCatalogue:()=>jn,fetchItems:()=>Re,fetchPledges:()=>eo,incrementFor:()=>de,leadingBid:()=>xt,lots:()=>Qn,makePledge:()=>bs,nextMinimumBid:()=>xe,openAuction:()=>qn,outbidNotification:()=>fy,placeBid:()=>Un,pledgeLevels:()=>_s,pledgeTotal:()=>Xn,pledges:()=>to,resolveBid:()=>Pt,rulesFor:()=>vt,settle:()=>Dt,settleAuction:()=>Kn,winnerNotification:()=>wy});var Jn={};E(Jn,{biddersFor:()=>Fn,bidsByBidder:()=>En,bidsForAuction:()=>An,bidsForItem:()=>Tn,leadingBid:()=>xt,placeBid:()=>Un});import{db as _t}from"@stacksjs/database/runtime";async function xt(e){return await _t.selectFrom("bids").selectAll().where("auction_item_id","=",e).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function Tn(e){return await _t.selectFrom("bids").selectAll().where("auction_item_id","=",e).orderBy("placed_at","desc").execute()??[]}async function An(e){return await _t.selectFrom("bids").selectAll().where("auction_id","=",e).orderBy("placed_at","asc").execute()??[]}async function En(e,t){return await _t.selectFrom("bids").selectAll().where("auction_id","=",e).where("bidder_email","=",t.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function Fn(e){let t=await _t.selectFrom("bids").select(["bidder_name","bidder_email"]).where("auction_id","=",e).execute(),r=new Map;for(let n of t??[]){let o=n.bidder_email.toLowerCase();if(!r.has(o))r.set(o,{name:n.bidder_name,email:n.bidder_email})}return[...r.values()]}var{randomUUIDv7:py}=globalThis.Bun;import{db as Bn}from"@stacksjs/database/runtime";function Rt(e,t,r,n){if(r.antiSnipeMinutes<=0||r.extendOnBidWindowMinutes<=0)return null;if(e.extension_count>=r.maxExtensions)return null;let o=t.getTime()-n.getTime();if(o<=0)return null;if(o>r.extendOnBidWindowMinutes*60000)return null;let a=new Date(n.getTime()+r.antiSnipeMinutes*60000);return a>t?a:null}function Me(e,t){return new Date(e.closes_at??t)}var _e=[{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 de(e,t=_e,r){if(r&&r>0)return r;for(let n of t)if(n.upTo===null||e<n.upTo)return n.step;return t[t.length-1]?.step??100}function xe(e,t,r=_e){if(t===null||t<=0)return e.starting_bid;return t+de(t,r,e.min_increment)}function Pt(e,t,r,n=_e){let o=Math.max(r.amount,r.maxAmount??0),a=xe(e,t?t.amount:null,n);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(o<a)return{accepted:!1,reason:"below_minimum",message:`The next bid on this lot is ${a/100}.`,nextMinimumBid:a};if(e.buy_now_price&&o>=e.buy_now_price)return{accepted:!0,buyNow:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:e.buy_now_price,maxAmount:e.buy_now_price,isChallenger:!0},challengerAmount:e.buy_now_price,outbid:t?{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:t.amount}:void 0,nextMinimumBid:e.buy_now_price};if(!t){let d=Math.max(e.starting_bid,r.amount);return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:d,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:d,nextMinimumBid:d+de(d,n,e.min_increment)}}let s=Math.max(t.amount,t.max_amount??0);if(t.bidder_email.toLowerCase()===r.bidderEmail.toLowerCase()){if(o<=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:t.bidder_email,bidderName:t.bidder_name,amount:t.amount,maxAmount:o,isChallenger:!1},challengerAmount:t.amount,nextMinimumBid:t.amount+de(t.amount,n,e.min_increment)}}if(o>s){let d=s+de(s,n,e.min_increment),m=Math.min(o,Math.max(d,a));return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:m,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:m,outbid:{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:t.amount},nextMinimumBid:m+de(m,n,e.min_increment)}}let u=o+de(o,n,e.min_increment),c=Math.min(s,Math.max(u,o));return{accepted:!0,leader:{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:c,maxAmount:t.max_amount??null,isChallenger:!1},challengerAmount:o,outbid:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:o},nextMinimumBid:c+de(c,n,e.min_increment)}}function or(e){return`auction.${e}`}async function In(){try{let e=await import("@stacksjs/realtime");return e.emit??null}catch{return null}}async function Mn(e){let t=await In();if(!t||!e.item||!e.leader)return;await t(or(e.item.auction_id),"bid.placed",{itemId:e.item.id,lotNumber:e.item.lot_number,amount:e.leader.amount,nextMinimumBid:e.nextMinimumBid,leaderName:e.leader.bidderName,status:e.item.status,closesAt:e.item.closes_at,extended:Boolean(e.extendedTo),soldViaBuyNow:Boolean(e.buyNow)})}async function Nn(e,t){let r=await In();if(!r)return;await r(or(e.auction_id),"pledge.made",{donorName:e.donor_name,amount:e.amount,level:e.level??null,runningTotal:t})}async function On(e,t,r){let n=await In();if(!n)return;await n(or(e),"item.closed",{itemId:t,...r})}import{config as my}from"@stacksjs/config";function gs(){return my.commerce??{}}function hs(){return gs().auction??{}}function vt(e){let t=hs();return{increments:t.increments?.length?t.increments:_e,antiSnipeMinutes:e?.anti_snipe_minutes??t.antiSnipeMinutes??2,extendOnBidWindowMinutes:e?.extend_on_bid_window_minutes??t.extendOnBidWindowMinutes??2,maxExtensions:e?.max_extensions??t.maxExtensions??20}}function $n(e){return e?.currency??hs().currency??gs().currency??"USD"}function ar(e){return e.toISOString().slice(0,19).replace("T"," ")}async function Un(e){let t=e.now??new Date,r=await Bn.selectFrom("auction_items").selectAll().where("id","=",e.itemId).executeTakeFirst();if(!r)return{accepted:!1,reason:"item_not_found",message:"That lot is no longer available.",nextMinimumBid:0};let n=await Bn.selectFrom("auctions").selectAll().where("id","=",r.auction_id).executeTakeFirst(),o=vt(n),a=await xt(r.id),s=xe(r,a?.amount??null,o.increments);if(!n||n.status!=="open"||new Date(n.opens_at)>t)return{accepted:!1,reason:"auction_not_open",message:"Bidding is not open yet.",nextMinimumBid:s,item:r};let i=Me(r,n.closes_at);if(r.status!=="open"||i<=t)return{accepted:!1,reason:"item_not_open",message:"Bidding on this lot has closed.",nextMinimumBid:s,item:r};let u=Pt(r,a,{bidderEmail:e.bidderEmail,bidderName:e.bidderName,amount:e.amount,maxAmount:e.maxAmount},o.increments);if(!u.accepted)return{...u,item:r};let c=u.buyNow?null:Rt(r,i,o,t),d=u.leader&&!u.leader.isChallenger&&a&&a.bidder_email.toLowerCase()===e.bidderEmail.toLowerCase(),m=await Bn.transaction(async(y)=>{if(d&&a)return await y.updateTable("bids").set({max_amount:u.leader.maxAmount}).where("id","=",a.id).execute(),{...a,max_amount:u.leader.maxAmount};let g=u.leader?.isChallenger===!0,p=py();if(await y.insertInto("bids").values({uuid:p,auction_id:r.auction_id,auction_item_id:r.id,bidder_name:e.bidderName,bidder_email:e.bidderEmail.toLowerCase(),amount:u.challengerAmount??e.amount,max_amount:e.maxAmount??null,status:g?"leading":"outbid",placed_at:ar(t)}).execute(),a){if(g)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:ar(t)}).where("id","=",r.id).execute();else if(c)await y.updateTable("auction_items").set({closes_at:ar(c),extension_count:r.extension_count+1}).where("id","=",r.id).execute();return await y.selectFrom("bids").selectAll().where("uuid","=",p).executeTakeFirst()}),l={...u,bid:m,item:{...r,status:u.buyNow?"sold":r.status,closes_at:c?ar(c):r.closes_at,extension_count:c?r.extension_count+1:r.extension_count},extendedTo:c??void 0};return await Mn(l).catch(()=>{return}),l}var Wn={};E(Wn,{DEFAULT_INCREMENT_LADDER:()=>_e,determineWinner:()=>ot,effectiveCloseAt:()=>Me,extendedCloseAt:()=>Rt,incrementFor:()=>de,nextMinimumBid:()=>xe,resolveBid:()=>Pt,settle:()=>Dt});function ot(e,t){let r=t.filter((a)=>a.status!=="invalid");if(r.length===0)return{itemId:e.id,lotNumber:e.lot_number,title:e.title,status:"passed",amount:0,passedReason:"no_bids"};let o=[...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(e.reserve_price&&o.amount<e.reserve_price)return{itemId:e.id,lotNumber:e.lot_number,title:e.title,status:"passed",amount:o.amount,passedReason:"reserve_not_met"};return{itemId:e.id,lotNumber:e.lot_number,title:e.title,status:"sold",winningBidId:o.id,winnerName:o.bidder_name,winnerEmail:o.bidder_email,amount:o.amount}}function Dt(e,t,r,n){let o=t.filter((m)=>m.status==="sold"),a=t.filter((m)=>m.status==="passed"),s=o.reduce((m,l)=>m+l.amount,0),i=r.filter((m)=>m.status==="confirmed").reduce((m,l)=>m+l.amount,0),u=new Map(e.map((m)=>[m.id,m.fair_market_value??null])),c=o.reduce((m,l)=>{let y=u.get(l.itemId);return y==null?m:m+(l.amount-y)},0),d=t.length;return{auctionId:n.auctionId,currency:n.currency,totalRaised:s+i,bidRevenue:s,pledgeRevenue:i,goalAmount:n.goalAmount??null,itemsSold:o.length,itemsPassed:a.length,sellThrough:d===0?0:o.length/d,valueDelta:c,outcomes:t}}var Qn={};E(Qn,{auctionTotals:()=>zn,closeAuction:()=>Hn,closeDueItems:()=>Vn,closeItem:()=>St,closingSoon:()=>Zn,fetchAuction:()=>pe,fetchAuctionForEvent:()=>Ln,fetchCatalogue:()=>jn,fetchItems:()=>Re,openAuction:()=>qn,settleAuction:()=>Kn});import{db as Ne}from"@stacksjs/database/runtime";async function pe(e){return await Ne.selectFrom("auctions").selectAll().where("id","=",e).executeTakeFirst()??null}async function Ln(e){return await Ne.selectFrom("auctions").selectAll().where("event_id","=",e).executeTakeFirst()??null}async function Re(e){return await Ne.selectFrom("auction_items").selectAll().where("auction_id","=",e).orderBy("lot_number","asc").execute()??[]}async function jn(e){let[t,r]=await Promise.all([pe(e),Re(e)]),n=vt(t),o=await Ne.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",e).where("status","in",["leading","won"]).execute(),a=await Ne.selectFrom("bids").select(["auction_item_id"]).where("auction_id","=",e).where("status","!=","invalid").execute(),s=new Map((o??[]).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:xe(u,c?.amount??null,n.increments),leaderName:c?.bidder_name??null}})}async function zn(e){let t=await pe(e),r=await Ne.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",e).where("status","!=","invalid").execute(),n=await Ne.selectFrom("pledges").select(["amount"]).where("auction_id","=",e).where("status","=","confirmed").execute(),o=r??[],s=o.filter((c)=>c.status==="leading"||c.status==="won").reduce((c,d)=>c+d.amount,0),i=(n??[]).reduce((c,d)=>c+d.amount,0),u=await Ne.selectFrom("auction_items").where("auction_id","=",e).count();return{currentBidTotal:s,pledgeTotal:i,raised:s+i,goalAmount:t?.goal_amount??null,bidCount:o.length,bidderCount:new Set(o.map((c)=>c.bidder_email.toLowerCase())).size,lotsOffered:Number(u??0),lotsWithBids:new Set(o.map((c)=>c.auction_item_id)).size}}import{db as Oe}from"@stacksjs/database/runtime";function Gn(e){return e.toISOString().slice(0,19).replace("T"," ")}async function qn(e,t=new Date){return await Oe.updateTable("auctions").set({status:"open",opens_at:Gn(t)}).where("id","=",e).execute(),await Oe.updateTable("auction_items").set({status:"open"}).where("auction_id","=",e).where("status","=","closed").execute(),pe(e)}async function St(e,t=new Date){if(e.status==="sold"||e.status==="passed")return null;let r=await Oe.selectFrom("bids").selectAll().where("auction_item_id","=",e.id).execute(),n=ot(e,r??[]);return await Oe.transaction(async(o)=>{if(await o.updateTable("auction_items").set({status:n.status,closes_at:Gn(t)}).where("id","=",e.id).execute(),n.winningBidId)await o.updateTable("bids").set({status:"won"}).where("id","=",n.winningBidId).execute();await o.updateTable("bids").set({status:"lost"}).where("auction_item_id","=",e.id).where("status","in",["leading","outbid"]).execute()}),await On(e.auction_id,e.id,{status:n.status,amount:n.amount,winnerName:n.winnerName}).catch(()=>{return}),n}async function Vn(e,t=new Date){let r=await pe(e);if(!r)return[];let n=await Re(e),o=[];for(let a of n){if(a.status!=="open")continue;if(Me(a,r.closes_at)>t)continue;let s=await St(a,t);if(s)o.push(s)}return o}async function Hn(e,t=new Date){let r=await Re(e),n=[];for(let o of r){let a=await St(o,t);if(a)n.push(a)}return await Oe.updateTable("auctions").set({status:"closed",closes_at:Gn(t)}).where("id","=",e).execute(),n}async function Kn(e,t={}){let r=await pe(e);if(!r)return null;let n=await Re(e),o=await Oe.selectFrom("bids").selectAll().where("auction_id","=",e).execute(),a=await Oe.selectFrom("pledges").selectAll().where("auction_id","=",e).execute(),s=new Map;for(let u of o??[]){let c=s.get(u.auction_item_id)??[];c.push(u),s.set(u.auction_item_id,c)}let i=n.map((u)=>{let c=ot(u,s.get(u.id)??[]);return u.status==="passed"?{...c,status:"passed"}:c});if(t.markSettled)await Oe.updateTable("auctions").set({status:"settled"}).where("id","=",e).execute();return Dt(n,i,a??[],{auctionId:e,currency:$n(r),goalAmount:r.goal_amount??null})}async function Zn(e,t,r=new Date){let n=await pe(e);if(!n)return[];let o=new Date(r.getTime()+t*60000);return(await Re(e)).filter((a)=>{if(a.status!=="open")return!1;let s=Me(a,n.closes_at);return s>r&&s<=o})}function Yn(e,t="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:t,minimumFractionDigits:0}).format(e/100)}function fy(e,t="USD"){if(!e.outbid||!e.item)return null;let r=e.item;return{to:{name:e.outbid.bidderName,email:e.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 ${Yn(e.nextMinimumBid,t)}. Bidding closes ${new Date(r.closes_at??"").toLocaleString()}.`,data:{itemId:r.id,lotNumber:r.lot_number,title:r.title,nextMinimumBid:e.nextMinimumBid,closesAt:r.closes_at}}}function wy(e,t="USD"){if(e.status!=="sold"||!e.winnerEmail)return null;return{to:{name:e.winnerName??"Bidder",email:e.winnerEmail},type:"winner",subject:`You won lot ${e.lotNumber}: ${e.title}`,body:`Congratulations - you won "${e.title}" at ${Yn(e.amount,t)}. The school will be in touch with payment and pickup details.`,data:{itemId:e.itemId,lotNumber:e.lotNumber,title:e.title,amount:e.amount}}}function yy(e,t,r,n="USD"){return{to:t,type:"closing_soon",subject:`Closing soon: lot ${e.lot_number}, ${e.title}`,body:`"${e.title}" closes at ${new Date(e.closes_at??"").toLocaleString()}. The current bid is ${Yn(r,n)}.`,data:{itemId:e.id,lotNumber:e.lot_number,title:e.title,currentBid:r,closesAt:e.closes_at}}}var to={};E(to,{fetchPledges:()=>eo,makePledge:()=>bs,pledgeLevels:()=>_s,pledgeTotal:()=>Xn});var{randomUUIDv7:gy}=globalThis.Bun;import{db as sr}from"@stacksjs/database/runtime";async function bs(e){let t=gy();await sr.insertInto("pledges").values({uuid:t,auction_id:e.auctionId,donor_name:e.donorName,donor_email:e.donorEmail.toLowerCase(),amount:e.amount,level:e.level??null,status:e.status??"confirmed"}).execute();let r=await sr.selectFrom("pledges").selectAll().where("uuid","=",t).executeTakeFirst();return await Nn(r,await Xn(e.auctionId)).catch(()=>{return}),r}async function Xn(e){return(await sr.selectFrom("pledges").select(["amount"]).where("auction_id","=",e).where("status","=","confirmed").execute()??[]).reduce((r,n)=>r+n.amount,0)}async function eo(e){return await sr.selectFrom("pledges").selectAll().where("auction_id","=",e).orderBy("amount","desc").execute()??[]}async function _s(e){let t=(await eo(e)).filter((n)=>n.status==="confirmed"),r=new Map;for(let n of t){let o=n.level??"other",a=r.get(o)??{amount:0,count:0};a.amount+=n.amount,a.count+=1,r.set(o,a)}return[...r.entries()].map(([n,o])=>({level:n,...o})).sort((n,o)=>o.amount-n.amount)}var no={};E(no,{bulkDestroy:()=>Ps,bulkStore:()=>As,bulkUpdate:()=>Ms,destroy:()=>Rs,fetchAll:()=>Ss,fetchById:()=>Ds,store:()=>Ts,update:()=>Is});import{db as xs}from"@stacksjs/database/runtime";import{mutationCount as _}from"@stacksjs/database/runtime";async function Rs(e){try{let t=await xs.deleteFrom("carts").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete cart: ${t.message}`);throw t}}async function Ps(e){if(!e.length)return 0;try{let t=await xs.deleteFrom("carts").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete carts: ${t.message}`);throw t}}import{db as vs}from"@stacksjs/database/runtime";function hy(e){return e.replace(/_([a-z0-9])/g,(t,r)=>r.toUpperCase())}function w(e){if(e===null||typeof e!=="object")return e;let t={...e};for(let[r,n]of Object.entries(t)){if(!r.includes("_"))continue;let o=hy(r);if(!(o in t))t[o]=n}return t}function P(e){return e.map((t)=>w(t))}async function Ds(e){let t=await vs.selectFrom("carts").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Ss(){return P(await vs.selectFrom("carts").selectAll().execute())}var{randomUUIDv7:ks}=globalThis.Bun;import{db as Cs}from"@stacksjs/database/runtime";async function Ts(e){try{let t={...e,uuid:ks()},r=await Cs.insertInto("carts").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create cart");return w(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create cart: ${t.message}`);throw t}}async function As(e){if(!e.length)return 0;let t=0;try{return await Cs.transaction(async(r)=>{for(let n of e){let o={...n,uuid:ks()};await r.insertInto("carts").values(o).execute(),t++}}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create carts in bulk: ${r.message}`);throw r}}import{db as Es,matchedRows as by}from"@stacksjs/database/runtime";import{formatDate as Fs}from"@stacksjs/orm";async function Is(e,t){try{let r=await Es.updateTable("carts").set({...t,updated_at:Fs(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update cart");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update cart: ${r.message}`);throw r}}async function Ms(e){if(!e.length)return 0;let t=0;try{return await Es.transaction(async(r)=>{for(let n of e){if(!n.id)continue;if((await by(r.updateTable("carts").set({...n,updated_at:Fs(new Date)}).where("id","=",n.id))).length>0)t++}}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update carts in bulk: ${r.message}`);throw r}}var so={};E(so,{SIZES:()=>Ns,categoryRank:()=>ao,compareCatalog:()=>_y,isLowStock:()=>Ry,matchesSearch:()=>xy,sizeOf:()=>oo});var Ns=["XXS","XS","S","M","L","XL","XXL","2XL","3XL","4XL"];function oo(e){let t=/^(.*?)\s*[\u2014\u2013\-/]\s*(XXS|XS|S|M|L|XL|XXL|2XL|3XL|4XL)$/i.exec(String(e).trim());if(!t)return{base:String(e).trim(),size:null,rank:-1};let r=t[2].toUpperCase();return{base:t[1],size:r,rank:Ns.indexOf(r)}}function ao(e,t=[]){let r=t.indexOf(String(e||""));if(r!==-1)return r;return e?t.length:t.length+1}function _y(e=[]){return(t,r)=>{let n=ao(t.category,e)-ao(r.category,e)||String(t.category||"").localeCompare(String(r.category||""));if(n)return n;let o=oo(String(t.name||"")),a=oo(String(r.name||""));return o.base.localeCompare(a.base)||o.rank-a.rank}}function xy(e,t){let r=String(t||"").toLowerCase().split(/\s+/).filter(Boolean);if(!r.length)return!0;let n=e.map((o)=>String(o??"")).join(" ").toLowerCase();return r.every((o)=>n.includes(o))}function Ry(e,t,r=5){if(e===null||e===void 0)return!1;return Number(e)<=(t===null||t===void 0?r:Number(t))}var pu={};E(pu,{ACCOUNT_CREDENTIAL_ENV:()=>mo,ACCOUNT_CREDENTIAL_HELP:()=>he,AdminCredentialError:()=>Ct,CATALOG_IMPORT_NAMESPACE:()=>Yi,CatalogFetchError:()=>T,MAX_RETRIES:()=>po,MissingCredentialsError:()=>it,PriceFormatError:()=>I,SHOPIFY_ADMIN_API_VERSION:()=>ri,SHOPWARE_ACCESS_KEY_HELP:()=>yo,SKU_MAX:()=>Bo,UNKNOWN_COUNTRY:()=>iu,accountAdapter:()=>bg,accountAdapters:()=>mu,addressLine:()=>je,adminRequest:()=>$e,amountOrZero:()=>ze,catalogAdapter:()=>hg,catalogAdapters:()=>lu,catalogUuid:()=>te,cleanName:()=>J,createDatabaseAccountRepository:()=>ou,createDatabaseRepository:()=>du,createMemoryAccountRepository:()=>dg,createMemoryRepository:()=>yg,createReadOnlyAccountRepository:()=>lg,createReadOnlyRepository:()=>gg,credentialSecrets:()=>qe,currencyCode:()=>ie,currencyExponent:()=>U,customerRow:()=>pr,customerUuid:()=>Ke,decimalToMinor:()=>ee,decodeHtmlEntities:()=>js,defaultSleep:()=>Ys,detectShopifyCurrency:()=>Ks,detectShopwareCurrency:()=>wi,fetchJson:()=>fe,formatMinor:()=>ne,gmtTimestamp:()=>ir,importCatalog:()=>wg,importCustomers:()=>ug,importOrders:()=>cg,isoTimestamp:()=>we,lineLabel:()=>Io,lowestPrice:()=>Wo,mapShopifyCustomer:()=>ni,mapShopifyOrder:()=>ai,mapShopifyProduct:()=>Hs,mapShopwareCustomer:()=>Pi,mapShopwareOrder:()=>Si,mapShopwareProduct:()=>mi,mapWooCustomer:()=>zi,mapWooOrder:()=>Gi,mapWooProduct:()=>$i,minorToDecimal:()=>Pe,missingAccessKeyMessage:()=>fi,nextPageInfo:()=>si,normalizeEmail:()=>oe,normalizeStoreUrl:()=>V,numberToDecimalString:()=>Ls,numberToMinor:()=>st,optionalString:()=>R,orderRow:()=>ru,personName:()=>H,phoneOf:()=>ye,productRow:()=>Uo,promotedCustomerUuid:()=>No,quantityOf:()=>Ge,readAccountCredentials:()=>Ay,redactSecrets:()=>Ve,rescaleMinor:()=>at,retryAfterSeconds:()=>Os,shopifyAccountAdapter:()=>fo,shopifyAdapter:()=>co,shopifyAdminBase:()=>ii,shopifyOrderStatus:()=>oi,shopwareAccessToken:()=>xo,shopwareAccountAdapter:()=>Ro,shopwareAdapter:()=>ho,shopwareAdminBase:()=>ki,shopwareBaseUrl:()=>pi,shopwareCustomerCriteria:()=>Ci,shopwareLineLabel:()=>Di,shopwareOrderCriteria:()=>Ti,shopwareOrderStatus:()=>vi,shopwareProductCriteria:()=>gi,shopwareVariantCriteria:()=>hi,signedMinor:()=>ge,storeHost:()=>kt,totalInventory:()=>uu,unitFromTotal:()=>lo,uuidV5:()=>Xi,variantRow:()=>Jo,variantSkus:()=>cu,wooAdminBase:()=>qi,wooAuthorization:()=>Vi,wooCommerceAccountAdapter:()=>To,wooCommerceAdapter:()=>ko,wooOrderStatus:()=>ji,wooPrices:()=>Ni,wooSlug:()=>Oi});import{slug as zs}from"@stacksjs/strings";class T extends Error{url;status;body;retryAfter;constructor(e,t,r,n,o){super(t);this.url=e;this.status=r;this.body=n;this.retryAfter=o;this.name="CatalogFetchError"}}var Py=2000,vy=30000;function V(e){let t=e.trim();if(!t)throw TypeError("A store URL is required, e.g. https://shop.example.com");let r=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`https://${t}`,n;try{n=new URL(r)}catch{throw TypeError(`"${e}" is not a valid store URL`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw TypeError(`"${e}" must be an http(s) URL`);let o=n.pathname.replace(/\/+$/,"");return`${n.protocol}//${n.host.toLowerCase()}${o}`}function kt(e){return new URL(e).host.toLowerCase()}function Os(e,t=Date.now){let r=e?.trim();if(!r)return;if(/^\d+(?:\.\d+)?$/.test(r))return Number(r);let n=Date.parse(r);return Number.isNaN(n)?void 0:Math.max(0,(n-t())/1000)}async function fe(e,t=fetch,r="",n={}){let o=r?` ${r}`:"",a={accept:"application/json",...n.headers};if(n.json!==void 0)a["content-type"]="application/json";let s;try{s=await t(e,{method:n.method??(n.json!==void 0?"POST":"GET"),headers:a,...n.json!==void 0?{body:JSON.stringify(n.json)}:{},signal:AbortSignal.timeout(vy)})}catch(u){let c=u instanceof Error?u.message:String(u);throw new T(e,`Could not reach ${e}: ${c}.${o}`)}if(!s.ok){let u=`${s.status}${s.statusText?` ${s.statusText}`:""}`,c=await s.text().catch(()=>"");throw new T(e,`${e} responded ${u}.${o}`,s.status,c?c.slice(0,Py):void 0,Os(s.headers.get("retry-after")))}let i=await s.text();try{return{data:JSON.parse(i),headers:s.headers}}catch{let u=s.headers.get("content-type")||"no content-type";throw new T(e,`${e} did not return JSON (${u}).${o}`,s.status)}}var Ws={};E(Ws,{PriceFormatError:()=>I,currencyExponent:()=>U,decimalToMinor:()=>ee,formatCurrency:()=>$s,formatMinor:()=>ne,minorToDecimal:()=>Pe,minorToInput:()=>Bs,minorToMajor:()=>io,moneyInputError:()=>uo,moneyInputStep:()=>Us,parseMoneyInput:()=>Js,rescaleMinor:()=>at});class I extends Error{value;constructor(e,t){super(`Unreadable price ${JSON.stringify(e)}: ${t}`);this.value=e;this.name="PriceFormatError"}}function U(e){if(!e)return 2;try{let t=new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits;return typeof t==="number"?t:2}catch{return 2}}function ee(e,t=2){if(e===null||e===void 0)return null;let r=String(e).trim();if(r==="")return null;let n=/^(\d*)(?:\.(\d*))?$/.exec(r);if(!n||!/\d/.test(r))throw new I(e,"expected a plain decimal such as 19.99");let o=n[1]||"0",a=n[2]??"",s;if(a.length<=t)s=BigInt(o+a.padEnd(t,"0"));else if(s=BigInt(o+a.slice(0,t)),a.charCodeAt(t)>=53)s+=1n;if(s>BigInt(Number.MAX_SAFE_INTEGER))throw new I(e,"too large to store exactly");return Number(s)}function Pe(e,t=2){let r=String(e).trim();if(!/^\d+$/.test(r))throw new I(e,"expected a non-negative integer amount in minor units");if(t===0)return r.replace(/^0+(?=\d)/,"");let n=r.padStart(t+1,"0");return`${n.slice(0,-t).replace(/^0+(?=\d)/,"")}.${n.slice(-t)}`}function at(e,t,r){if(e===null||e===void 0||String(e).trim()==="")return null;if(!Number.isInteger(t)||t<0)throw new I(e,`invalid source precision ${t}`);return ee(Pe(String(e),t),r)}function ne(e,t){let r=U(t),n=Math.round(Number(e)),o=Number.isSafeInteger(n)?`${n<0?"-":""}${Pe(Math.abs(n),r)}`:String(e);return t?`${o} ${t}`:o}function io(e,t){let r=Math.round(Number(e??0));if(!Number.isFinite(r))return 0;let n=Pe(Math.abs(r),U(t));return r<0?-Number(n):Number(n)}function $s(e,t,r){let n=(t||"USD").toUpperCase(),o=io(e,n);try{return new Intl.NumberFormat(r,{style:"currency",currency:n}).format(o)}catch{return ne(Math.round(Number(e??0))||0,n)}}function Bs(e,t){if(e===null||e===void 0||e==="")return"";let r=Math.round(Number(e));if(!Number.isFinite(r))return"";let n=Pe(Math.abs(r),U(t));return r<0?`-${n}`:n}function Us(e){let t=U(e);return t===0?"1":`0.${"1".padStart(t,"0")}`}function uo(e,t,r={}){let n=e===null||e===void 0?"":String(e).trim(),o=U(t),a=(t||"USD").toUpperCase();if(n==="")return r.required===!1?"":"Enter an amount.";let s=/^(\d*)(?:\.(\d*))?$/.exec(n);if(!s||!/\d/.test(n))return o===0?"Enter a whole number, for example 1999.":`Enter a plain amount, for example ${Pe(1999,o)}.`;if((s[2]??"").length>o)return o===0?`${a} amounts have no decimal places.`:`${a} amounts have at most ${o} decimal ${o===1?"place":"places"}.`;let u;try{u=ee(n,o)}catch{return"That amount is too large."}if(u===null)return"Enter an amount.";if(r.min!==void 0&&u<r.min)return`Enter at least ${ne(r.min,a)}.`;if(r.max!==void 0&&u>r.max)return`Enter at most ${ne(r.max,a)}.`;return""}function Js(e,t,r={}){let n=uo(e,t,r);if(n)throw new I(e,n);return ee(e,U(t))}function Ls(e){if(typeof e!=="number"||!Number.isFinite(e))throw new I(e,"expected a finite number");if(e<0)throw new I(e,"expected an amount of zero or more");let t=String(e),r=/^(\d+)(?:\.(\d+))?e([+-]\d+)$/.exec(t);if(!r)return t;let[,n,o="",a]=r,s=`${n}${o}`,i=n.length+Number(a);if(i<=0)return`0.${"0".repeat(-i)}${s}`;if(i>=s.length)return`${s}${"0".repeat(i-s.length)}`;return`${s.slice(0,i)}.${s.slice(i)}`}function st(e,t=2){if(e===null||e===void 0)return null;if(typeof e==="string")return ee(e,t);return ee(Ls(e),t)}var Dy={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",ndash:"\u2013",mdash:"\u2014",hellip:"\u2026",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",laquo:"\xAB",raquo:"\xBB",trade:"\u2122",reg:"\xAE",copy:"\xA9",deg:"\xB0",times:"\xD7",frac12:"\xBD",euro:"\u20AC",pound:"\xA3",yen:"\xA5",cent:"\xA2"};function js(e){return e.replace(/&(#x[0-9a-f]+|#\d+|[a-z][a-z0-9]*);/gi,(t,r)=>{if(r[0]==="#"){let n=r[1]==="x"||r[1]==="X"?Number.parseInt(r.slice(2),16):Number.parseInt(r.slice(1),10);return Number.isInteger(n)&&n>0&&n<=1114111?String.fromCodePoint(n):t}return Dy[r.toLowerCase()]??t})}function J(e){if(typeof e!=="string")return"";return js(e).replace(/\s+/g," ").trim()}function R(e){if(typeof e!=="string")return null;let t=e.trim();return t===""?null:t}var Gs=250,qs=400;function Sy(e){if(!e||e.length===0)return!0;if(e.length!==1)return!1;let[t]=e;return t?.name==="Title"&&(t.values?.length??0)<=1&&(t.values?.[0]??"Default Title")==="Default Title"}function ky(e){return(Array.isArray(e)?e:typeof e==="string"?e.split(","):[]).map((r)=>String(r).trim()).filter(Boolean)}function Vs(e,t,r,n,o){try{return ee(e,t)}catch(a){if(!(a instanceof I))throw a;return o.push({externalId:n,message:`${r}: ${a.message}; left unpriced`}),null}}function Hs(e,t){if(e?.id===void 0||e.id===null||e.id==="")throw TypeError("Shopify product has no id");let r=String(e.id),n=[],o=(R(e.title)??"").replace(/\s+/g," ");if(!o)throw TypeError(`Shopify product ${r} has no title`);let a=R(e.handle)??zs(o),s=U(t.currency),i=!Sy(e.options),u=i?(e.options??[]).map((l)=>R(l.name)??"").filter(Boolean):[],c=(e.variants??[]).map((l)=>{let y=String(l.id),g=Vs(l.compare_at_price,s,`variant ${y} compare-at price`,r,n);return{externalId:y,title:R(l.title)??o,sku:R(l.sku),priceMinor:Vs(l.price,s,`variant ${y} price`,r,n),compareAtMinor:g?g:null,available:l.available!==!1,inventory:typeof l.inventory_quantity==="number"?Math.max(0,Math.trunc(l.inventory_quantity)):null,optionValues:i?[l.option1,l.option2,l.option3].slice(0,u.length).map((p)=>R(p)??""):[]}});if(c.length===0)n.push({externalId:r,message:`"${o}" has no variants; imported without a price`});let d=[...e.images??[]].filter((l)=>R(l?.src)).sort((l,y)=>(l.position??0)-(y.position??0)).map((l)=>({src:R(l.src),alt:R(l.alt)})),m=R(e.product_type);return{product:{source:"shopify",externalId:r,name:o,handle:a,descriptionHtml:R(e.body_html),vendor:R(e.vendor),categories:m?[{name:m,slug:zs(m)}]:[],tags:ky(e.tags),currency:t.currency,images:d,optionNames:u,variants:c,hasOptions:i,url:`${t.storeUrl}/products/${a}`},warnings:n}}async function Ks(e,t=fetch){try{let{data:r}=await fe(`${e}/meta.json`,t),n=typeof r?.currency==="string"?r.currency.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(n)?n:null}catch{return null}}async function*Cy(e,t={}){let r=V(e),n=t.fetch??fetch,o=t.limit,a=o&&o>0?Math.min(Gs,o):Gs,s=[],i=t.currency?.toUpperCase()??null;if(!i){if(i=await Ks(r,n),!i)s.push({message:`${r}/meta.json did not report a currency; prices read as 2-decimal amounts. Pass --currency to be sure.`})}let u=new Set,c=0;for(let d=1;d<=qs;d++){let m=`${r}/products.json?limit=${a}&page=${d}`,{data:l}=await fe(m,n,"Is this a Shopify storefront, and is it public (no storefront password)?");if(!Array.isArray(l?.products))throw new T(m,`${m} did not return a "products" list. Is this a Shopify storefront?`);let y=l.products;if(y.length===0)return;let g=y.map((h)=>String(h?.id));if(d>1&&g.every((h)=>u.has(h)))throw new T(m,`${m} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);g.forEach((h)=>u.add(h));let p=[],b=d===1?s:[];for(let h of y){if(o&&c>=o)break;try{let f=Hs(h,{storeUrl:r,currency:i});p.push(f.product),b.push(...f.warnings),c++}catch(f){b.push({externalId:h?.id===void 0?void 0:String(h.id),message:`skipped: ${f.message}`})}}if(yield{url:m,products:p,warnings:b},o&&c>=o)return}throw new T(r,`Stopped after ${qs} pages of ${r}/products.json without reaching the end.`)}var co={name:"shopify",pages:Cy};var Ty=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function oe(e){if(typeof e!=="string")return null;let t=e.trim().toLowerCase();return Ty.test(t)?t:null}function we(e){if(typeof e!=="string"||e.trim()==="")return null;let t=new Date(e.trim());return Number.isNaN(t.getTime())?null:t.toISOString()}function ir(e){if(typeof e!=="string"||e.trim()==="")return null;let t=e.trim();return we(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(t)?t:`${t}Z`)}function H(...e){let t=e.map((r)=>J(r)).filter(Boolean).join(" ");return t===""?null:t}function ye(...e){for(let t of e){let r=R(typeof t==="number"?String(t):t);if(r)return r.slice(0,50)}return null}function je(...e){let t=e.map((r)=>J(r)).filter(Boolean).join(", ");return t===""?null:t}function ge(e,t){if(e===null||e===void 0||e==="")return null;if(typeof e==="number"){if(!Number.isFinite(e))throw new I(e,"expected a finite number");let a=st(Math.abs(e),t);return e<0?-a:a}if(typeof e!=="string")throw new I(e,"expected a decimal amount");let r=e.trim(),n=r.startsWith("-"),o=ee(n||r.startsWith("+")?r.slice(1):r,t);if(o===null)return null;return n?-o:o}function ze(e,t,r,n,o,a=0){let s;try{s=ge(e,t)}catch(i){if(!(i instanceof I))throw i;return o.push({externalId:n,message:`${r}: ${i.message}; recorded as ${a}`}),a}if(s===null)return a;if(s<0)return o.push({externalId:n,message:`${r} is negative (${String(e)}); recorded as ${a}`}),a;return s}function lo(e,t){if(t<=1)return e;return Math.floor((2*e+t)/(2*t))}function Ge(e){let t=typeof e==="string"?Number(e):e;return typeof t==="number"&&Number.isInteger(t)&&t>0?t:null}function ie(e){let t=typeof e==="string"?e.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(t)?t:null}var mo={shopify:["SHOPIFY_ADMIN_TOKEN"],woocommerce:["WOOCOMMERCE_CONSUMER_KEY","WOOCOMMERCE_CONSUMER_SECRET"],shopware:["SHOPWARE_CLIENT_ID","SHOPWARE_CLIENT_SECRET"]},he={shopify:"Create a custom app for the store (Shopify admin > Settings > Apps > Develop apps, or the Shopify Dev Dashboard), give it the Admin API scopes read_customers and read_orders (plus read_all_orders for orders older than 60 days), install it, and copy its Admin API access token (shpat_...).",woocommerce:"Create a key in WordPress admin > WooCommerce > Settings > Advanced > REST API > Add key, with Read permission, for a user who can manage WooCommerce. The key starts with ck_ and the secret with cs_.",shopware:"Create an integration in the Shopware Administration > Settings > System > Integrations, with a role that can read customers and orders. Its access key id (SWIA...) is the client id and its secret access key is the client secret."};class it extends Error{constructor(e){super(e);this.name="MissingCredentialsError"}}function Zs(e,t){let r=e[t]?.trim();return r?r:void 0}function Ay(e,t){let r=e.trim().toLowerCase(),n=mo[r];if(!n)throw new it(`Customers and orders can be imported from ${Object.keys(mo).join(", ")}; got "${e}".`);let o=n.filter((s)=>!Zs(t,s));if(o.length>0){let s=o.length===1?`${o[0]} is not set`:`${o.join(" and ")} are not set`;throw new it(`Importing customers or orders from ${r} needs Admin API credentials in the environment: ${s}. They are read from env (or .env) only, never from a flag, so they stay out of shell history. ${he[r]}`)}let a=n.map((s)=>Zs(t,s));for(let[s,i]of a.entries())if(/\s/.test(i))throw new it(`${n[s]} contains whitespace; paste the credential exactly as issued. ${he[r]}`);if(r==="shopify")return{source:"shopify",accessToken:a[0]};if(r==="woocommerce")return{source:"woocommerce",consumerKey:a[0],consumerSecret:a[1]};if(/^SWSC/i.test(a[0]))throw new it(`SHOPWARE_CLIENT_ID looks like a sales channel access key (SWSC...), which only reads the public catalog. ${he.shopware}`);return{source:"shopware",clientId:a[0],clientSecret:a[1]}}function qe(e){switch(e.source){case"shopify":return[e.accessToken];case"woocommerce":return[e.consumerKey,e.consumerSecret];case"shopware":return[e.clientId,e.clientSecret]}}function Ve(e,t){let r=e;for(let n of t)if(n.length>=4)r=r.split(n).join("[redacted]");return r}var po=5,Ey=2,Fy=60,Ys=(e)=>new Promise((t)=>setTimeout(t,e));class Ct extends T{constructor(e,t,r){super(e,t,r);this.name="AdminCredentialError"}}function Qs(e,t,r=""){let n=Ve(`${e.message}${r}`,t),o=e.body===void 0?void 0:Ve(e.body,t);return new T(Ve(e.url,t),n,e.status,o,e.retryAfter)}async function $e(e,t){let{fetch:r,secrets:n,credentialHelp:o,hint:a="",sleep:s,...i}=t,u=s??Ys;for(let c=0;;c++)try{return await fe(e,r,"",i)}catch(d){if(!(d instanceof T))throw d;if(d.status===429&&c<po){let m=d.retryAfter!==void 0&&d.retryAfter>=0?d.retryAfter:Ey;await u(Math.min(m,Fy)*1000);continue}if(d.status===401||d.status===403){let m=d.status===401?"The credentials were rejected.":"The credentials were accepted but lack permission to read this.";throw new Ct(Ve(e,n),Ve(`${e} responded ${d.status}. ${m} ${o}`,n),d.status)}if(d.status===429)throw Qs(d,n,` Still rate limited after ${po} retries; re-run later, the import resumes safely.`);throw Qs(d,n,a?` ${a}`:"")}}var ri="2026-10",Xs=250,ei=4000,Iy=["id","email","first_name","last_name","phone","state","total_spent","currency","created_at","default_address"],My=["id","name","order_number","email","contact_email","created_at","processed_at","cancelled_at","currency","total_price","total_tax","total_discounts","total_shipping_price_set","shipping_lines","total_tip_received","financial_status","fulfillment_status","customer","billing_address","shipping_address","line_items","note"],Ny=`Check SHOPIFY_ADMIN_TOKEN, and that the app is installed on this store with the read_customers and read_orders scopes. ${he.shopify}`;function ni(e){let t=e?.id===void 0||e.id===null?"":String(e.id),r=[],n=oe(e?.email);if(!t||!n)return r.push({externalId:t||void 0,message:"skipped: the customer has no valid email address, which Stacks customers are keyed by"}),{record:null,warnings:r};let o=ie(e.currency),a=null;try{a=ge(e.total_spent,U(o))}catch(s){if(!(s instanceof I))throw s;r.push({externalId:t,message:`total_spent: ${s.message}; not imported`})}return{record:{source:"shopify",externalId:t,email:n,name:H(e.first_name,e.last_name)??H(e.default_address?.first_name,e.default_address?.last_name)??n,phone:ye(e.phone,e.default_address?.phone),active:null,totalSpentMinor:a!==null&&a>=0?a:null,currency:o,lastOrderAt:null,avatarUrl:null,createdAt:we(e.created_at)},warnings:r}}function oi(e){let t=(e.financial_status??"").toLowerCase(),r=(e.fulfillment_status??"").toLowerCase();if(t==="refunded")return{status:"REFUNDED",mapped:!0};if(e.cancelled_at||t==="voided"||r==="restocked")return{status:"CANCELLED",mapped:!0};if(r==="fulfilled")return{status:"SHIPPED",mapped:!0};if(r==="partial")return{status:"PROCESSING",mapped:!0};if(["paid","partially_paid","partially_refunded","authorized"].includes(t))return{status:"PROCESSING",mapped:!0};if(t==="pending"||t==="expired"||t==="")return{status:"PENDING",mapped:!0};return{status:"PENDING",mapped:!1}}function Oy(e){if(!e)return null;return je(H(e.first_name,e.last_name)??e.name,e.address1,e.address2,e.city,[e.province_code??e.province,e.zip].map((t)=>J(t)).filter(Boolean).join(" "),e.country_code??e.country)}function ai(e,t={}){let r=e?.id===void 0||e.id===null?"":String(e.id),n=[];if(!r)return n.push({message:"skipped: a Shopify order has no id"}),{record:null,warnings:n};let o=ie(e.currency)??ie(t.currency);if(!o)return n.push({externalId:r,message:"skipped: the order names no currency; pass --currency"}),{record:null,warnings:n};let a=U(o),s=(p,b)=>ze(p,a,b,r,n),i=e.total_shipping_price_set?.shop_money?.amount,u=i!==void 0&&i!==null?s(i,"shipping"):(e.shipping_lines??[]).reduce((p,b)=>p+s(b?.price,"shipping line"),0),c=[];for(let p of e.line_items??[]){let b=p?.id===void 0||p.id===null?"":String(p.id),h=Ge(p?.quantity),f=R(p?.name)??H(p?.title,p?.variant_title)??`Line ${b}`;if(!b||h===null){n.push({externalId:r,message:`line "${f}" has no id or quantity; left out`});continue}c.push({externalId:b,productExternalId:p.product_id===void 0||p.product_id===null?null:String(p.product_id),variantExternalId:p.variant_id===void 0||p.variant_id===null?null:String(p.variant_id),name:f,sku:R(p.sku),quantity:h,unitPriceMinor:s(p.price,`line "${f}" price`)})}let{status:d,mapped:m}=oi(e),l=[e.financial_status??"no payment status",e.fulfillment_status??"unfulfilled",e.cancelled_at?"cancelled":null].filter(Boolean).join(", ");if(!m)n.push({externalId:r,message:`Shopify status "${l}" has no Stacks equivalent; imported as ${d}`});let y=oe(e.customer?.email)??oe(e.email)??oe(e.contact_email),g=e.customer?.id===void 0||e.customer?.id===null?null:String(e.customer.id);return{record:{source:"shopify",externalId:r,number:R(e.name)??(e.order_number?`#${e.order_number}`:null),currency:o,status:d,sourceStatus:l,totalMinor:s(e.total_price,"total"),taxMinor:s(e.total_tax,"tax"),discountMinor:s(e.total_discounts,"discounts"),shippingMinor:u,tipMinor:s(e.total_tip_received,"tip"),customer:y||g?{externalId:g,email:y,name:H(e.customer?.first_name,e.customer?.last_name)??H(e.billing_address?.first_name,e.billing_address?.last_name),phone:ye(e.customer?.phone,e.billing_address?.phone)}:null,shippingAddress:Oy(e.shipping_address),note:R(e.note),placedAt:we(e.processed_at)??we(e.created_at),lines:c},warnings:n}}function si(e){if(!e)return null;for(let t of e.split(",")){let r=/<([^>]+)>\s*;\s*rel="?next"?/i.exec(t);if(!r)continue;try{return new URL(r[1]).searchParams.get("page_info")}catch{return null}}return null}function ii(e,t){let r=V(t??e);if(!r.startsWith("https://"))throw TypeError(`${r} is not HTTPS. The Shopify Admin API is HTTPS only, and the access token must never travel in plain text.`);return r}async function*ti(e,t,r){if(t.credentials.source!=="shopify")throw TypeError("The Shopify importer needs Shopify credentials (SHOPIFY_ADMIN_TOKEN).");let n=ii(e,t.adminUrl),o=t.fetch??fetch,a=t.limit,s=a&&a>0?Math.min(Xs,a):Xs,i=`${n}/admin/api/${ri}/${r.resource}.json`,u=r.fields.join(","),c={fetch:o,headers:{"X-Shopify-Access-Token":t.credentials.accessToken},secrets:qe(t.credentials),credentialHelp:Ny,hint:`Is ${n} the store's Admin API address? For a custom domain, pass --admin-url https://<store>.myshopify.com.`,sleep:t.sleep},d=new Set,m=0,l=`${i}?limit=${s}&fields=${u}${r.firstQuery}`;for(let y=1;y<=ei;y++){let{data:g,headers:p}=await $e(l,c),b=g?.[r.resource];if(!Array.isArray(b))throw new T(l,`${l} did not return a "${r.resource}" list. Is this the Shopify Admin API?`);let h=b,f=h.map((F)=>String(F?.id));if(y>1&&f.length>0&&f.every((F)=>d.has(F)))throw new T(l,`${l} repeated ${r.resource} from an earlier page; stopping rather than looping.`);f.forEach((F)=>d.add(F));let x=[],D=[];for(let F of h){if(a&&m>=a)break;let k=r.map(F);if(D.push(...k.warnings),k.record)x.push(k.record),m++}yield{url:l,items:x,warnings:D};let v=si(p.get("link"));if(!v||h.length===0||a&&m>=a)return;l=`${i}?limit=${s}&fields=${u}&page_info=${encodeURIComponent(v)}`}throw new T(i,`Stopped after ${ei} pages of ${i} without reaching the end.`)}var fo={name:"shopify",customers:(e,t)=>ti(e,t,{resource:"customers",fields:Iy,firstQuery:"",map:ni}),orders:(e,t)=>ti(e,t,{resource:"orders",fields:My,firstQuery:"&status=any",map:(r)=>ai(r,{currency:t.currency})})};import{slug as li}from"@stacksjs/strings";var ur=100,cr=1000,dr="/store-api",wo="Is this a Shopware 6 store with the Store API reachable at /store-api?",yo='Find it in the Shopware Administration under Sales Channels: open the storefront or headless sales channel and copy the key from its "API access" card. A headless storefront also ships it in its page source.';function lr(e,t){if(!e)return null;let r=e,n=r.translated;return(n&&typeof n==="object"&&!Array.isArray(n)?R(n[t]):null)??R(r[t])}function He(e){return lr(e,"name")?.replace(/\s+/g," ")??null}function ui(e){let t=typeof e.availableStock==="number"?e.availableStock:e.stock;return typeof t==="number"&&Number.isFinite(t)?Math.max(0,Math.trunc(t)):null}function ci(e){return e.available!==!1&&e.active!==!1}function di(e,t,r,n,o){let a=U(n.currency),s=e.calculatedPrice?.unitPrice;if(s===null||s===void 0||s==="")return o.push({externalId:r,message:`${t} has no price in ${n.currency??"the sales channel currency"}; left unpriced`}),{priceMinor:null,compareAtMinor:null};try{let i=st(s,a),u=st(e.calculatedPrice?.listPrice?.price??null,a);return{priceMinor:i,compareAtMinor:u!==null&&i!==null&&u>i?u:null}}catch(i){if(!(i instanceof I))throw i;return o.push({externalId:r,message:`${t}: ${i.message}; left unpriced`}),{priceMinor:null,compareAtMinor:null}}}function $y(e){let t=[...e.media??[]].sort((o,a)=>(o?.position??0)-(a?.position??0));if(e.cover)t.unshift(e.cover);let r=new Set,n=[];for(let o of t){let a=R(o?.media?.url);if(!a||r.has(a))continue;r.add(a);let s=o.media;n.push({src:a,alt:lr(s,"alt")??lr(s,"title")})}return n}function By(e){let t=new Set,r=[];for(let n of[e.seoCategory,...e.categories??[]]){let o=He(n),a=o?li(o):"";if(!o||!a||t.has(a))continue;t.add(a),r.push({name:o,slug:a})}return r}function Uy(e){let t=new Map;for(let r of e)for(let n of r.options??[]){let o=He(n.group),a=R(n.groupId)??R(n.group?.id)??o;if(!a||!o||t.has(a))continue;t.set(a,{key:a,name:o,position:n.group?.position??0,order:t.size})}return[...t.values()].sort((r,n)=>r.position-n.position||r.order-n.order)}function Jy(e,t){return(e.options??[]).find((r)=>(R(r.groupId)??R(r.group?.id)??He(r.group))===t.key)}function mi(e,t){if(!R(e?.id))throw TypeError("Shopware product has no id");let r=e.id,n=[],o=He(e);if(!o)throw TypeError(`Shopware product ${r} has no name`);let a=t.children??[],s=typeof e.childCount==="number"?e.childCount:0,i=a.length>0,u,c=[];if(i){let d=Uy(a);c=d.map((l)=>l.name);let m=a.map((l)=>{let y=d.map((x)=>Jy(l,x)),g=y.map((x)=>He(x)??""),p=R(l.productNumber),b=`variant ${p??l.id}`,h=di(l,b,r,t,n);return{variant:{externalId:String(l.id),title:g.filter(Boolean).join(" / ")||He(l)||p||o,sku:p,priceMinor:h.priceMinor,compareAtMinor:h.compareAtMinor,available:ci(l),inventory:ui(l),optionValues:g},sortKey:y.map((x)=>x?.position??0),productNumber:p??""}});m.sort((l,y)=>{for(let g=0;g<l.sortKey.length;g++){let p=(l.sortKey[g]??0)-(y.sortKey[g]??0);if(p!==0)return p}return l.productNumber.localeCompare(y.productNumber)}),u=m.map((l)=>l.variant)}else if(s>0)n.push({externalId:r,message:`"${o}" has ${s} variant${s===1?"":"s"} in Shopware, none visible to this sales channel; imported without a price`}),u=[];else{let d=di(e,`"${o}"`,r,t,n);u=[{externalId:r,title:o,sku:R(e.productNumber),priceMinor:d.priceMinor,compareAtMinor:d.compareAtMinor,available:ci(e),inventory:ui(e),optionValues:[]}]}return{product:{source:"shopware",externalId:r,name:o,handle:li(o),descriptionHtml:lr(e,"description"),vendor:He(e.manufacturer),categories:By(e),tags:(e.tags??[]).map((d)=>R(d?.name)).filter((d)=>d!==null),currency:t.currency,images:$y(e),optionNames:c,variants:u,hasOptions:i,url:`${t.storeUrl}/detail/${r}`},warnings:n}}function pi(e){return V(e).replace(/\/store-api$/i,"")}function fi(){return`Shopware's Store API needs the sales channel access key: pass --access-key <key> or set SHOPWARE_ACCESS_KEY. It is public by design and not a secret. ${yo}`}function Wy(e){if(!e)return null;try{let r=JSON.parse(e)?.errors?.[0];return R(r?.detail)??R(r?.title)}catch{return null}}function Ly(e){let t=Wy(e.body),r=t?` Shopware said: "${t}"`:"";if(e.status===401||e.status===403||e.status===412)return new T(e.url,`${e.message}${r} The sales channel access key looks wrong: check --access-key or SHOPWARE_ACCESS_KEY. ${yo}`,e.status,e.body);return new T(e.url,`${e.message}${r} ${wo}`,e.status,e.body)}async function go(e,t,r,n){try{let{data:o}=await fe(e,r,"",{headers:{"sw-access-key":t},json:n});return o}catch(o){if(!(o instanceof T))throw o;throw Ly(o)}}function jy(e){return e instanceof T&&(e.status===401||e.status===403||e.status===412)}async function wi(e,t,r=fetch){try{let n=await go(`${e}${dr}/context`,t,r),o=typeof n?.currency?.isoCode==="string"?n.currency.isoCode.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(o)?o:null}catch(n){if(jy(n))throw n;return null}}var yi={product:["id","parentId","productNumber","name","description","translated","calculatedPrice","stock","availableStock","available","active","childCount","manufacturer","seoCategory","categories","tags","cover","media","options"],calculated_price:["unitPrice","quantity","listPrice"],cart_list_price:["price"],product_media:["position","media"],media:["url","alt","title","translated"],product_manufacturer:["name","translated"],category:["name","translated"],tag:["name"],property_group_option:["id","name","translated","position","groupId","group"],property_group:["id","name","translated","position"]};function gi(e,t){return{page:e,limit:t,"total-count-mode":"exact",filter:[{type:"equals",field:"parentId",value:null}],sort:[{field:"id",order:"ASC"}],associations:{cover:{},media:{associations:{media:{}}},manufacturer:{},categories:{},tags:{}},includes:yi}}function hi(e,t){return{page:t,limit:ur,"total-count-mode":"exact",filter:[{type:"equalsAny",field:"parentId",value:e}],sort:[{field:"id",order:"ASC"}],associations:{options:{associations:{group:{}}}},includes:yi}}function bi(e,t,r,n){if(n<r)return!0;let o=typeof e.total==="number"?e.total:Number.NaN;return Number.isInteger(o)&&t*r>=o}async function zy(e,t,r,n){let o=new Map;if(r.length===0)return o;let a=`${e}${dr}/product`;for(let s=1;s<=cr;s++){let i=await go(a,t,n,hi(r,s));if(!Array.isArray(i?.elements))throw new T(a,`${a} did not return a product list for the variants. ${wo}`);let u=i.elements;for(let c of u){let d=R(c?.parentId);if(!d)continue;let m=o.get(d)??[];m.push(c),o.set(d,m)}if(u.length===0||bi(i,s,ur,u.length))return o}throw new T(a,`Stopped after ${cr} pages of variants from ${a} without reaching the end.`)}async function*Gy(e,t={}){let r=t.accessKey?.trim();if(!r)throw TypeError(fi());let n=pi(e),o=t.fetch??fetch,a=t.limit,s=a&&a>0?Math.min(ur,a):ur,i=`${n}${dr}/product`,u=[],c=t.currency?.trim().toUpperCase()||null,d=await wi(n,r,o),m=d??c;if(d&&c&&d!==c)u.push({message:`--currency ${c} ignored: this sales channel prices in ${d}, and the Store API does not convert.`});if(!m)u.push({message:`${n}${dr}/context did not report a currency; prices read as 2-decimal amounts. Pass --currency to be sure.`});let l=new Set,y=0;for(let g=1;g<=cr;g++){let p=`${i} (page ${g})`,b;try{b=await go(i,r,o,gi(g,s))}catch(S){if(S instanceof T)throw new T(S.url,S.message.replace(S.url,p),S.status,S.body);throw S}if(!Array.isArray(b?.elements))throw new T(i,`${p} did not return a product list. ${wo}`);let h=b.elements;if(h.length===0)return;let f=h.map((S)=>String(S?.id));if(g>1&&f.every((S)=>l.has(S)))throw new T(i,`${p} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);f.forEach((S)=>l.add(S));let x=a?h.slice(0,Math.max(0,a-y)):h,D=g===1?u:[],v=x.filter((S)=>typeof S?.childCount==="number"&&S.childCount>0).map((S)=>String(S.id)),F=await zy(n,r,v,o),k=[];for(let S of x)try{let C=mi(S,{storeUrl:n,currency:m,children:F.get(String(S?.id))});k.push(C.product),D.push(...C.warnings),y++}catch(C){D.push({externalId:S?.id===void 0?void 0:String(S.id),message:`skipped: ${C.message}`})}if(yield{url:p,products:k,warnings:D},a&&y>=a)return;if(bi(b,g,s,h.length))return}throw new T(i,`Stopped after ${cr} pages of ${i} without reaching the end.`)}var ho={name:"shopware",pages:Gy};var _i=100,xi=1e4,qy=`Check SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET, and that the integration's role may read customers and orders. ${he.shopware}`,bo="Is this a Shopware 6 store with the Admin API reachable at /api?";function Pi(e,t={}){let r=R(e?.id)??"",n=[],o=oe(e?.email);if(!r||!o)return n.push({externalId:r||void 0,message:"skipped: the customer has no valid email address, which Stacks customers are keyed by"}),{record:null,warnings:n};let a=ie(t.currency),s=null;try{s=ge(e.orderTotalAmount??null,U(a))}catch(i){if(!(i instanceof I))throw i;n.push({externalId:r,message:`orderTotalAmount: ${i.message}; not imported`})}return{record:{source:"shopware",externalId:r,email:o,name:H(e.firstName,e.lastName)??R(e.company)??o,phone:ye(e.defaultBillingAddress?.phoneNumber),active:typeof e.active==="boolean"?e.active:null,totalSpentMinor:s!==null&&s>=0?s:null,currency:a,lastOrderAt:we(e.lastOrderDate),avatarUrl:null,createdAt:we(e.createdAt)},warnings:n}}function _o(e){return(e?.stateMachineState?.technicalName??"").toLowerCase()}function Vy(e){let t=[...e.transactions??[]].sort((r,n)=>String(r?.createdAt??"").localeCompare(String(n?.createdAt??"")));return _o(t.at(-1))}function vi(e){let t=_o(e),r=_o(e.deliveries?.[0]),n=Vy(e),o=`order ${t||"unknown"}, delivery ${r||"unknown"}, payment ${n||"unknown"}`,a=(s,i=!0)=>({status:s,mapped:i,sourceStatus:o});if(n==="refunded")return a("REFUNDED");if(t==="cancelled")return a("CANCELLED");if(t==="completed")return a("DELIVERED");if(t==="open"||t==="in_progress"){if(r==="shipped")return a("SHIPPED");if(t==="in_progress"||r==="shipped_partially"||["paid","paid_partially","authorized"].includes(n))return a("PROCESSING");return a("PENDING")}return a("PENDING",!1)}function Hy(e){if(!e||!R(e.street))return null;return je(H(e.firstName,e.lastName),e.company,e.street,e.additionalAddressLine1,[e.zipcode,e.city].map((t)=>J(t)).filter(Boolean).join(" "),e.country?.iso??e.country?.name)}function Ky(e){return e.payload&&typeof e.payload==="object"&&!Array.isArray(e.payload)?e.payload:{}}function Di(e,t){let r=Array.isArray(t)?t.map((n)=>J(n?.option)).filter(Boolean):[];return r.length>0&&!r.every((n)=>e.includes(n))?`${e} - ${r.join(", ")}`:e}function Si(e,t={}){let r=R(e?.id)??"",n=[];if(!r)return n.push({message:"skipped: a Shopware order has no id"}),{record:null,warnings:n};let o=ie(e.currency?.isoCode)??ie(t.currency);if(!o)return n.push({externalId:r,message:"skipped: the order names no currency; pass --currency"}),{record:null,warnings:n};let a=U(o),s=(f,x)=>ze(f,a,x,r,n),i=[],u=0;for(let f of e.lineItems??[]){if(R(f?.parentId))continue;let x=R(f?.id)??"",D=J(f?.label)||`Line ${x}`,v=(f?.type??"").toLowerCase(),F=null;try{F=ge(f?.totalPrice??null,a)}catch(M){if(!(M instanceof I))throw M;n.push({externalId:r,message:`line "${D}": ${M.message}; left out`});continue}if(v==="promotion"||v==="credit"||F!==null&&F<0){u+=Math.abs(F??0);continue}let k=Ge(f?.quantity);if(!x||k===null){n.push({externalId:r,message:`line "${D}" has no id or quantity; left out`});continue}let S=v==="product"&&f.productId===null,C=v==="product"&&!S?R(f.productId)??R(f.referencedId):null,O=Ky(f);i.push({externalId:x,productExternalId:R(O.parentId)??C,variantExternalId:C,name:Di(D,O.options),sku:R(O.productNumber),quantity:k,unitPriceMinor:s(f.unitPrice,`line "${D}" unit price`)})}let c=s(e.amountTotal,"total"),d=e.amountNet===null||e.amountNet===void 0?c:s(e.amountNet,"net total"),{status:m,mapped:l,sourceStatus:y}=vi(e);if(!l)n.push({externalId:r,message:`Shopware state "${y}" has no Stacks equivalent; imported as ${m}`});let g=(e.addresses??[]).find((f)=>f?.id&&f.id===e.billingAddressId),p=e.deliveries?.[0]?.shippingOrderAddress??(e.addresses??[]).find((f)=>f?.id&&f.id!==e.billingAddressId)??null,b=oe(e.orderCustomer?.email),h=R(e.orderCustomer?.customerId);return{record:{source:"shopware",externalId:r,number:R(e.orderNumber),currency:o,status:m,sourceStatus:y,totalMinor:c,taxMinor:Math.max(0,c-d),discountMinor:u,shippingMinor:s(e.shippingTotal,"shipping"),tipMinor:0,customer:b||h?{externalId:h,email:b,name:H(e.orderCustomer?.firstName,e.orderCustomer?.lastName),phone:ye(g?.phoneNumber)}:null,shippingAddress:Hy(p),note:R(e.customerComment),placedAt:we(e.orderDateTime),lines:i},warnings:n}}function ki(e,t){let r=V(t??e).replace(/\/(?:store-)?api$/i,""),{protocol:n,hostname:o}=new URL(r),a=o==="localhost"||o==="127.0.0.1"||o==="[::1]"||o.endsWith(".localhost");if(n!=="https:"&&!a)throw TypeError(`${r} is not HTTPS. The Shopware integration secret and bearer token must never travel in plain text.`);return r}function Ci(e,t){return{page:e,limit:t,"total-count-mode":1,sort:[{field:"id",order:"ASC"}],associations:{defaultBillingAddress:{}},includes:{customer:["id","customerNumber","email","firstName","lastName","company","active","guest","orderTotalAmount","lastOrderDate","createdAt","defaultBillingAddress"],customer_address:["phoneNumber"]}}}var Zy=["id","firstName","lastName","company","street","additionalAddressLine1","zipcode","city","phoneNumber","country"];function Ti(e,t){return{page:e,limit:t,"total-count-mode":1,sort:[{field:"id",order:"ASC"}],associations:{lineItems:{},addresses:{associations:{country:{}}},currency:{},stateMachineState:{},orderCustomer:{},deliveries:{associations:{stateMachineState:{},shippingOrderAddress:{associations:{country:{}}}}},transactions:{associations:{stateMachineState:{}}}},includes:{order:["id","orderNumber","orderDateTime","amountTotal","amountNet","shippingTotal","customerComment","billingAddressId","currency","stateMachineState","orderCustomer","lineItems","addresses","deliveries","transactions"],order_line_item:["id","parentId","productId","referencedId","label","quantity","unitPrice","totalPrice","type","payload"],order_customer:["customerId","email","firstName","lastName"],order_address:Zy,order_delivery:["shippingOrderAddress","stateMachineState"],order_transaction:["stateMachineState","createdAt"],currency:["isoCode"],country:["iso","name"],state_machine_state:["technicalName"]}}}async function xo(e,t,r,n){let o=`${e}/api/oauth/token`,{data:a}=await $e(o,{...n,json:{grant_type:"client_credentials",client_id:t,client_secret:r}}),s=typeof a?.access_token==="string"?a.access_token.trim():"";if(!s)throw new T(o,`${o} returned no access_token. ${bo}`);return s}async function*Ri(e,t,r,n,o){if(t.credentials.source!=="shopware")throw TypeError("The Shopware importer needs Shopware credentials (SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET).");let a=ki(e,t.adminUrl),{clientId:s,clientSecret:i}=t.credentials,u=qe(t.credentials),d={fetch:t.fetch??fetch,secrets:u,credentialHelp:qy,hint:bo,sleep:t.sleep},m=await xo(a,s,i,d),l=async(f,x)=>{let D=()=>$e(f,{...d,secrets:[...u,m],headers:{authorization:`Bearer ${m}`},json:x});try{return await D()}catch(v){if(!(v instanceof Ct)||v.status!==401)throw v;return m=await xo(a,s,i,d),await D()}},y=`${a}/api/search/${r}`,g=t.limit,p=g&&g>0?Math.min(_i,g):_i,b=new Set,h=0;for(let f=1;f<=xi;f++){let x=`${y} (page ${f})`,{data:D}=await l(y,n(f,p));if(!Array.isArray(D?.data))throw new T(y,`${x} did not return a "data" list. ${bo}`);let v=D.data;if(v.length===0)return;let F=v.map((O)=>String(O?.id));if(f>1&&F.every((O)=>b.has(O)))throw new T(y,`${x} repeated ${r}s from an earlier page; the store is not paginating.`);F.forEach((O)=>b.add(O));let k=[],S=[];for(let O of v){if(g&&h>=g)break;let M=o(O);if(S.push(...M.warnings),M.record)k.push(M.record),h++}if(yield{url:x,items:k,warnings:S},g&&h>=g)return;let C=typeof D.total==="number"?D.total:Number.NaN;if(v.length<p||Number.isInteger(C)&&f*p>=C)return}throw new T(y,`Stopped after ${xi} pages of ${y} without reaching the end.`)}var Ro={name:"shopware",customers:(e,t)=>Ri(e,t,"customer",Ci,(r)=>Pi(r,{currency:t.currency})),orders:(e,t)=>Ri(e,t,"order",Ti,(r)=>Si(r,{currency:t.currency}))};import{slug as Mi}from"@stacksjs/strings";var vo=100,Do=1000,So="/wp-json/wc/store/v1/products",Ai="Is WooCommerce 6+ installed with the Store API reachable at /wp-json?";function Ni(e){let t=R(e?.currency_code)?.toUpperCase()??null,r=Number(e?.currency_minor_unit),n=Number.isInteger(r)&&r>=0?r:2,o=U(t),a=at(e?.price,n,o),s=at(e?.regular_price,n,o);return{currency:t,priceMinor:a,compareAtMinor:s!==null&&a!==null&&s>a?s:null}}function Ei(e,t,r){try{return Ni(e.prices)}catch(n){if(!(n instanceof I))throw n;return r.push({externalId:t,message:`${n.message}; left unpriced`}),{currency:R(e.prices?.currency_code)?.toUpperCase()??null,priceMinor:null,compareAtMinor:null}}}function Po(e){return(e??[]).map((t)=>{let r=J(t?.name);return{name:r,slug:R(t?.slug)??Mi(r)}}).filter((t)=>t.name&&t.slug)}function Oi(e){let t=R(e);if(!t||!t.includes("%"))return t;try{return decodeURIComponent(t)}catch{return t}}function Fi(e){return typeof e.low_stock_remaining==="number"?Math.max(0,Math.trunc(e.low_stock_remaining)):null}function Ii(e){return e.is_in_stock!==!1&&e.is_purchasable!==!1}function $i(e,t={}){if(e?.id===void 0||e.id===null||e.id==="")throw TypeError("WooCommerce product has no id");let r=String(e.id),n=[],o=J(e.name);if(!o)throw TypeError(`WooCommerce product ${r} has no name`);let a=Ei(e,r,n),s=e.type==="variable"&&(e.variations?.length??0)>0,i=s?(e.attributes??[]).filter((l)=>l.has_variations!==!1):[],u=i.map((l)=>J(l.name)).filter(Boolean),c,d=a.currency;if(s)c=(e.variations??[]).map((l)=>{let y=String(l.id),g=i.map((h)=>{let f=J(h.name).toLowerCase(),x=(h.taxonomy??"").toLowerCase(),D=(l.attributes??[]).find((k)=>{let S=J(k.name).toLowerCase();return S===f||x!==""&&S===x}),v=R(D?.value);if(!v)return"Any";let F=(h.terms??[]).find((k)=>k.slug===v);return F?J(F.name):J(v)}),p=t.variations?.get(y);if(!p)return n.push({externalId:r,message:`variation ${y} could not be fetched; imported without a price`}),{externalId:y,title:g.join(" / ")||o,sku:null,priceMinor:null,compareAtMinor:null,available:!1,inventory:null,optionValues:g};let b=Ei(p,y,n);return d??=b.currency,{externalId:y,title:g.join(" / ")||J(p.name)||o,sku:R(p.sku),priceMinor:b.priceMinor,compareAtMinor:b.compareAtMinor,available:Ii(p),inventory:Fi(p),optionValues:g}});else c=[{externalId:r,title:o,sku:R(e.sku),priceMinor:a.priceMinor,compareAtMinor:a.compareAtMinor,available:Ii(e),inventory:Fi(e),optionValues:[]}];let m=Po(e.brands)[0];return{product:{source:"woocommerce",externalId:r,name:o,handle:Oi(e.slug)??Mi(o),descriptionHtml:R(e.description)??R(e.short_description),vendor:m?m.name:null,categories:Po(e.categories),tags:Po(e.tags).map((l)=>l.name),currency:d,images:(e.images??[]).filter((l)=>R(l?.src)).map((l)=>({src:R(l.src),alt:R(l.alt)})),optionNames:s?u:[],variants:c,hasOptions:s,url:R(e.permalink)},warnings:n}}async function Bi(e,t){let{data:r,headers:n}=await fe(e,t,Ai);if(!Array.isArray(r))throw new T(e,`${e} did not return a product list. ${Ai}`);let o=n.get("x-wp-totalpages")?.trim(),a=o?Number(o):Number.NaN;return{url:e,items:r,totalPages:Number.isInteger(a)&&a>=0?a:null}}async function Qy(e,t,r){let n=new Map;if(t.length===0)return n;for(let o=1;o<=Do;o++){let a=`${e}${So}?type=variation&parent=${t.join(",")}&per_page=${vo}&page=${o}`,s=await Bi(a,r);for(let i of s.items)n.set(String(i.id),i);if(s.items.length===0||s.totalPages!==null&&o>=s.totalPages)break}return n}async function*Yy(e,t={}){let r=V(e),n=t.fetch??fetch,o=t.limit,a=o&&o>0?Math.min(vo,o):vo,s=new Set,i=0;for(let u=1;u<=Do;u++){let c=`${r}${So}?per_page=${a}&page=${u}`,d=await Bi(c,n);if(d.items.length===0)return;let m=d.items.map((h)=>String(h?.id));if(u>1&&m.every((h)=>s.has(h)))throw new T(c,`${c} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);m.forEach((h)=>s.add(h));let l=o?d.items.slice(0,Math.max(0,o-i)):d.items,y=[],g=l.filter((h)=>h?.type==="variable"&&(h.variations?.length??0)>0).map((h)=>String(h.id)),p=new Map;try{p=await Qy(r,g,n)}catch(h){if(!(h instanceof T))throw h;y.push({message:`variations could not be fetched (${h.message}); variable products are imported without variant prices`})}let b=[];for(let h of l)try{let f=$i(h,{variations:p});b.push(f.product),y.push(...f.warnings),i++}catch(f){y.push({externalId:h?.id===void 0?void 0:String(h.id),message:`skipped: ${f.message}`})}if(yield{url:c,products:b,warnings:y},o&&i>=o)return;if(d.totalPages!==null&&u>=d.totalPages)return}throw new T(r,`Stopped after ${Do} pages of ${r}${So} without reaching the end.`)}var ko={name:"woocommerce",pages:Yy};var Ui=100,Ji=1e4,Co="/wp-json/wc/v3",Xy=`Check WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET, and that the key has Read permission. If the key is right and every request is a 401, the web server may be stripping the Authorization header (common with Apache and CGI PHP). ${he.woocommerce}`,Wi="Is WooCommerce installed with the REST API reachable at /wp-json/wc/v3, and pretty permalinks enabled?",eg={pending:"PENDING","on-hold":"PENDING",processing:"PROCESSING",completed:"DELIVERED",cancelled:"CANCELLED",failed:"CANCELLED",refunded:"REFUNDED"},tg=new Set(["checkout-draft","auto-draft","trash"]);function ji(e){let t=eg[(e??"").toLowerCase()];return t?{status:t,mapped:!0}:{status:"PENDING",mapped:!1}}function rg(e){let t=R(e);if(!t)return null;try{return new URL(t).protocol==="https:"?t:null}catch{return null}}function zi(e){let t=e?.id===void 0||e.id===null?"":String(e.id),r=[],n=oe(e?.email)??oe(e?.billing?.email);if(!t||!n)return r.push({externalId:t||void 0,message:"skipped: the customer has no valid email address, which Stacks customers are keyed by"}),{record:null,warnings:r};return{record:{source:"woocommerce",externalId:t,email:n,name:H(e.first_name,e.last_name)??H(e.billing?.first_name,e.billing?.last_name)??n,phone:ye(e.billing?.phone,e.shipping?.phone),active:null,totalSpentMinor:null,currency:null,lastOrderAt:null,avatarUrl:rg(e.avatar_url),createdAt:ir(e.date_created_gmt)},warnings:r}}function ng(e){if(!e||!R(e.address_1))return null;return je(H(e.first_name,e.last_name),e.company,e.address_1,e.address_2,e.city,[e.state,e.postcode].map((t)=>J(t)).filter(Boolean).join(" "),e.country)}function Gi(e,t={}){let r=e?.id===void 0||e.id===null?"":String(e.id),n=[];if(!r)return n.push({message:"skipped: a WooCommerce order has no id"}),{record:null,warnings:n};let o=(e.status??"").toLowerCase();if(tg.has(o))return n.push({externalId:r,message:`skipped: status "${o}" is not a placed order`}),{record:null,warnings:n};let a=ie(e.currency)??ie(t.currency);if(!a)return n.push({externalId:r,message:"skipped: the order names no currency; pass --currency"}),{record:null,warnings:n};let s=U(a),i=(p,b)=>ze(p,s,b,r,n),u=[];for(let p of e.line_items??[]){let b=p?.id===void 0||p.id===null?"":String(p.id),h=Ge(p?.quantity),f=J(p?.name)||`Line ${b}`;if(!b||h===null){n.push({externalId:r,message:`line "${f}" has no id or quantity; left out`});continue}let x=i(p.subtotal??p.total,`line "${f}" subtotal`);u.push({externalId:b,productExternalId:p.product_id?String(p.product_id):null,variantExternalId:p.variation_id?String(p.variation_id):null,name:f,sku:R(p.sku),quantity:h,unitPriceMinor:lo(x,h)})}let c=0;for(let p of e.fee_lines??[]){let b=J(p?.name)||"Fee",h=null;try{h=ge(p?.total,s)}catch(f){if(!(f instanceof I))throw f;n.push({externalId:r,message:`fee "${b}": ${f.message}; left out`})}if(h===null||h===0)continue;if(h<0){c+=-h;continue}u.push({externalId:`fee-${p?.id??u.length}`,productExternalId:null,variantExternalId:null,name:b,sku:null,quantity:1,unitPriceMinor:h})}let{status:d,mapped:m}=ji(o);if(!m)n.push({externalId:r,message:`WooCommerce status "${o||"none"}" has no Stacks equivalent; imported as ${d}`});let l=e.customer_id?String(e.customer_id):null,y=oe(e.billing?.email),g=0;for(let p of e.refunds??[])try{g+=Math.abs(ge(p?.total,s)??0)}catch(b){if(!(b instanceof I))throw b;n.push({externalId:r,message:`refund ${p?.id??""}: ${b.message}; not counted`})}return{record:{source:"woocommerce",externalId:r,number:R(e.number)?`#${R(e.number)}`:null,currency:a,status:d,sourceStatus:o||"none",totalMinor:i(e.total,"total"),taxMinor:i(e.total_tax,"tax"),discountMinor:i(e.discount_total,"discounts")+c,shippingMinor:i(e.shipping_total,"shipping"),tipMinor:0,customer:y||l?{externalId:l,email:y,name:H(e.billing?.first_name,e.billing?.last_name),phone:ye(e.billing?.phone)}:null,shippingAddress:ng(e.shipping),note:R(e.customer_note),placedAt:ir(e.date_created_gmt),lines:u,refundedMinor:g},warnings:n}}function qi(e,t){let r=V(t??e);if(!r.startsWith("https://"))throw TypeError(`${r} is not HTTPS. WooCommerce REST API keys are sent with HTTP Basic auth, which is only safe (and only accepted by WooCommerce) over HTTPS. Use the store's https:// address.`);return r}function Vi(e,t){return`Basic ${Buffer.from(`${e}:${t}`,"utf8").toString("base64")}`}async function*Li(e,t,r,n){if(t.credentials.source!=="woocommerce")throw TypeError("The WooCommerce importer needs WooCommerce credentials (WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET).");let o=qi(e,t.adminUrl),{consumerKey:a,consumerSecret:s}=t.credentials,i=Vi(a,s),u={fetch:t.fetch??fetch,headers:{authorization:i},secrets:[...qe(t.credentials),i.slice(6)],credentialHelp:Xy,hint:Wi,sleep:t.sleep},c=t.limit,d=c&&c>0?Math.min(Ui,c):Ui,m=new Set,l=0;for(let y=1;y<=Ji;y++){let g=`${o}${Co}/${r}?per_page=${d}&page=${y}&orderby=id&order=asc`,{data:p,headers:b}=await $e(g,u);if(!Array.isArray(p))throw new T(g,`${g} did not return a list of ${r}. ${Wi}`);let h=p;if(h.length===0)return;let f=h.map((k)=>String(k?.id));if(y>1&&f.every((k)=>m.has(k)))throw new T(g,`${g} repeated ${r} from an earlier page; the store is not paginating.`);f.forEach((k)=>m.add(k));let x=[],D=[];for(let k of h){if(c&&l>=c)break;let S=n(k);if(D.push(...S.warnings),S.record)x.push(S.record),l++}yield{url:g,items:x,warnings:D};let v=b.get("x-wp-totalpages")?.trim(),F=v?Number(v):Number.NaN;if(c&&l>=c)return;if(Number.isInteger(F)&&y>=F)return}throw new T(`${o}${Co}/${r}`,`Stopped after ${Ji} pages of ${o}${Co}/${r} without reaching the end.`)}var To={name:"woocommerce",customers:(e,t)=>Li(e,t,"customers",zi),orders:(e,t)=>Li(e,t,"orders",(r)=>Gi(r,{currency:t.currency}))};import{db as Fo,sqlHelpers as eu}from"@stacksjs/database/runtime";import{env as tu}from"@stacksjs/env";import{formatDate as Mo}from"@stacksjs/orm";import{db as og}from"@stacksjs/database/runtime";import{HttpError as Zi}from"@stacksjs/error-handling";import{isUniqueViolation as ag}from"@stacksjs/orm";function ve(e){if(typeof e==="bigint")return Ao(e);if(typeof e==="number")return Ao(e);if(!e||typeof e!=="object")return;if(Array.isArray(e)){for(let r of e){let n=ve(r);if(n!==void 0)return n}return}let t=e;for(let r of["lastInsertRowid","insertId","lastInsertId"]){let n=t[r];if(n===void 0||n===null)continue;let o=Ao(n);if(o!==void 0)return o}return}function Ao(e){let t=typeof e==="bigint"?Number(e):Number(e);if(!Number.isSafeInteger(t)||t<=0)return;return t}import{db as Hi}from"@stacksjs/database/runtime";async function mr(e){let t=await Hi.selectFrom("customers").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Ki(){return P(await Hi.selectFrom("customers").selectAll().execute())}var Eo="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60";async function Qi(e){try{let t={...e,avatar:e.avatar??Eo},r=await og.insertInto("customers").values(t).executeTakeFirst();if(!r)throw Error("Failed to create customer");let n=ve(r);if(n===void 0)throw Error("Failed to create customer: the database reported no insert id");return await mr(n)}catch(t){if(t instanceof Zi)throw t;if(ag(t))throw new Zi(409,"A customer with this email already exists");if(t instanceof Error)throw Error(`Failed to create customer: ${t.message}`);throw t}}import{createHash as sg}from"crypto";var Yi="5d0c8a3e-6f1b-4c2a-9e47-b18f3d2a6c90";function Xi(e,t=Yi){let r=t.replace(/-/g,"");if(!/^[0-9a-f]{32}$/i.test(r))throw TypeError(`Invalid namespace UUID "${t}"`);let n=sg("sha1").update(Buffer.from(r,"hex")).update(e,"utf8").digest().subarray(0,16);n[6]=n[6]&15|80,n[8]=n[8]&63|128;let o=n.toString("hex");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function te(e,t,r,n){return Xi(`${e}:${t.toLowerCase()}:${r}:${n}`)}var ig=255;function Ke(e,t,r,n){return te(e,t,"customer",r??`email:${n}`)}function No(e,t,r,n,o){if(!n)return null;if(r!==null&&r!==Ke(e,t,null,o))return null;return Ke(e,t,n,o)}function Tt(e){return e?Mo(new Date(e)):null}function pr(e,t,r,n){let o={name:e.name.slice(0,ig),updated_at:r};if(n==="create")return o.uuid=t,o.email=e.email,o.phone=e.phone,o.total_spent=e.totalSpentMinor??0,o.last_order=Tt(e.lastOrderAt),o.status=e.active===!1?"Inactive":"Active",o.avatar=e.avatarUrl??Eo,o.created_at=Tt(e.createdAt)??r,o;if(e.phone!==null)o.phone=e.phone;if(e.totalSpentMinor!==null)o.total_spent=e.totalSpentMinor;if(e.lastOrderAt!==null)o.last_order=Tt(e.lastOrderAt);if(e.active!==null)o.status=e.active?"Active":"Inactive";return o}function Io(e){return e.sku?`${e.name} (SKU ${e.sku})`:e.name}function ru(e,t,r,n){let o={uuid:te(e.source,t,"order",e.externalId),status:e.status,total_amount:e.totalMinor,currency:e.currency,tax_amount:e.taxMinor,discount_amount:e.discountMinor,delivery_fee:e.shippingMinor,tip_amount:e.tipMinor,order_type:e.shippingAddress?"DELIVERY":"TAKEOUT",delivery_address:e.shippingAddress,special_instructions:e.note,created_at:Tt(e.placedAt)??n,updated_at:n};if(r!==null)o.customer_id=r;return o}class Oo{byUuid=new Map;byEmail=new Map;uuidById=new Map;async load(e,t){let r=[...new Set(t.map((o)=>o.uuid).filter((o)=>o!==null&&!this.byUuid.has(o)))],n=[...new Set(t.map((o)=>o.email).filter((o)=>o!==null&&!this.byEmail.has(o)))];if(r.length===0&&n.length===0)return;for(let o of await e.findCustomers({uuids:r,emails:n}))this.remember(o.id,o.uuid,o.email)}remember(e,t,r){if(t){let n=this.uuidById.get(e);if(n&&n!==t)this.byUuid.delete(n);this.byUuid.set(t,e),this.uuidById.set(e,t)}if(r)this.byEmail.set(r.trim().toLowerCase(),e)}find(e,t){let r=e?this.byUuid.get(e):void 0;if(r!==void 0)return{id:r,matchedBy:"uuid"};let n=t?this.byEmail.get(t):void 0;return n!==void 0?{id:n,matchedBy:"email"}:null}uuidOf(e){return this.uuidById.get(e)??null}emailTakenByOther(e,t){let r=this.byEmail.get(e);return r!==void 0&&r!==t}}function nu(e){let t=V(e.storeUrl);return{storeUrl:t,host:kt(t),clock:e.now??(()=>new Date),fetchOptions:{credentials:e.credentials,limit:e.limit,fetch:e.fetch,currency:e.currency,adminUrl:e.adminUrl,sleep:e.sleep}}}async function ug(e){let{storeUrl:t,host:r,clock:n,fetchOptions:o}=nu(e),{adapter:a,repository:s}=e,i=new Oo,u=new Set,c={source:a.name,storeUrl:t,dryRun:e.dryRun===!0,pages:[],customers:[],counts:{customers:{created:0,updated:0},merged:0},warnings:[]};async function d(m,l){let y=Mo(n()),g=Ke(m.source,r,m.externalId,m.email),p=i.find(g,m.email);if(!p){let f=await l.createCustomer(pr(m,g,y,"create"));return i.remember(f,g,m.email),{action:"create",externalId:m.externalId,email:m.email,name:m.name,matchedBy:null}}let b=pr(m,g,y,"update");if(p.matchedBy==="uuid")if(i.emailTakenByOther(m.email,p.id))c.warnings.push({externalId:m.externalId??void 0,message:`email changed to ${m.email}, which another customer already has; kept the old address`});else b.email=m.email;let h=p.matchedBy==="email"?No(m.source,r,i.uuidOf(p.id),m.externalId,m.email):null;if(h)b.uuid=h;return await l.updateCustomer(p.id,b),i.remember(p.id,h,m.email),{action:"update",externalId:m.externalId,email:m.email,name:m.name,matchedBy:p.matchedBy}}for await(let m of a.customers(t,o)){c.pages.push(m.url),c.warnings.push(...m.warnings);let l=[];for(let y of m.items){if(u.has(y.email)){c.counts.merged++;continue}u.add(y.email),l.push(y)}await i.load(s,l.map((y)=>({uuid:Ke(y.source,r,y.externalId,y.email),email:y.email})));for(let y of l){let g=await d(y,s);c.counts.customers[g.action==="create"?"created":"updated"]++,c.customers.push(g),e.onCustomer?.(g)}}if(c.counts.merged>0)c.warnings.push({message:`${c.counts.merged} source customer${c.counts.merged===1?"":"s"} shared an email with another and ${c.counts.merged===1?"was":"were"} merged into one Stacks customer`});return c}async function cg(e){let{storeUrl:t,host:r,clock:n,fetchOptions:o}=nu(e),{adapter:a,repository:s}=e,i=new Oo,u=new Set,c=new Set,d=new Set,m=[],l={source:a.name,storeUrl:t,dryRun:e.dryRun===!0,pages:[],orders:[],counts:{orders:{created:0,updated:0},customers:{created:0,updated:0},lines:{linked:0,unlinked:0,productless:0},duplicates:0,partlyRefunded:0},currencies:[],warnings:[]},y=(f,x)=>te(f.source,r,"product",x),g=(f,x)=>te(f.source,r,"variant",x);function p(f){let x=f.customer;if(x?.externalId)return Ke(f.source,r,x.externalId,x.email??"");return x?.email?Ke(f.source,r,null,x.email):null}async function b(f,x,D){let v=f.customer;if(!v)return null;let F=p(f),k=i.find(F,v.email);if(k){let C=k.matchedBy==="email"&&v.email?No(f.source,r,i.uuidOf(k.id),v.externalId,v.email):null;if(C)await x.updateCustomer(k.id,{uuid:C,updated_at:D}),i.remember(k.id,C,v.email);return k.id}if(!v.email)return l.warnings.push({externalId:f.externalId,message:`order ${f.number??f.externalId} has no customer email; imported without a customer`}),null;let S=await x.createCustomer(pr({source:f.source,externalId:v.externalId,email:v.email,name:v.name??v.email,phone:v.phone,active:null,totalSpentMinor:null,currency:null,lastOrderAt:f.placedAt,avatarUrl:null,createdAt:f.placedAt},F,D,"create"));return i.remember(S,F,v.email),l.counts.customers.created++,S}async function h(f,x,D){let v=Mo(n()),F=await b(f,x,v),k=ru(f,r,F,v),S=D.orders.get(k.uuid),C;if(S===void 0)C=await x.createOrder(k);else{C=S;let q={...k};delete q.uuid,await x.updateOrder(C,q)}let O=0,M=0,re=f.lines.map((q)=>{let bt=(q.productExternalId?D.products.get(y(f,q.productExternalId)):void 0)??(q.variantExternalId?D.variants.get(g(f,q.variantExternalId)):void 0)??null;if(bt===null){if(!q.productExternalId&&!q.variantExternalId)M++;else if(O++,d.size<5)d.add(Io(q))}return{order_id:C,product_id:bt,quantity:q.quantity,price:q.unitPriceMinor,special_instructions:Io(q),created_at:v,updated_at:v}});return await x.replaceOrderItems(C,re),{action:S===void 0?"create":"update",externalId:f.externalId,number:f.number,status:f.status,sourceStatus:f.sourceStatus,totalMinor:f.totalMinor,currency:f.currency,lines:re.length,unlinkedLines:O,productlessLines:M,refundedMinor:f.refundedMinor??0,customerEmail:f.customer?.email??null,customerId:F}}for await(let f of a.orders(t,o)){l.pages.push(f.url),l.warnings.push(...f.warnings);let x=f.items.filter((C)=>{if(!u.has(C.externalId))return u.add(C.externalId),!0;return l.counts.duplicates++,!1}),D=x.map((C)=>te(C.source,r,"order",C.externalId)),v=[...new Set(x.flatMap((C)=>C.lines.flatMap((O)=>O.productExternalId?[y(C,O.productExternalId)]:[])))],F=[...new Set(x.flatMap((C)=>C.lines.flatMap((O)=>O.variantExternalId?[g(C,O.variantExternalId)]:[])))],k={orders:D.length>0?await s.findOrders(D):new Map,products:v.length>0?await s.findProducts(v):new Map,variants:F.length>0?await s.findVariantProducts(F):new Map};await i.load(s,x.map((C)=>({uuid:p(C),email:C.customer?.email??null})));let S=new Map;for(let C of x){c.add(C.currency);let{customerId:O,...M}=s.transaction?await s.transaction((q)=>h(C,q,k)):await h(C,s,k);if(l.counts.orders[M.action==="create"?"created":"updated"]++,l.counts.lines.linked+=M.lines-M.unlinkedLines-M.productlessLines,l.counts.lines.unlinked+=M.unlinkedLines,l.counts.lines.productless+=M.productlessLines,M.refundedMinor>0&&M.status!=="REFUNDED"){if(l.counts.partlyRefunded++,m.length<3)m.push(`${M.number??M.externalId}: ${ne(M.refundedMinor,M.currency)} of ${ne(M.totalMinor,M.currency)}`)}let re=Tt(C.placedAt);if(O!==null&&re&&re>(S.get(O)??""))S.set(O,re);l.orders.push(M),e.onOrder?.(M)}if(s.advanceLastOrder)for(let[C,O]of S)await s.advanceLastOrder(C,O)}if(l.currencies=[...c].sort(),l.counts.lines.unlinked>0){let f=[...d].map((D)=>`"${D}"`).join(", "),x=l.counts.lines.unlinked===1;l.warnings.push({message:`${l.counts.lines.unlinked} order line${x?" references a product":"s reference products"} not in Stacks (e.g. ${f}); kept with ${x?"its":"their"} label and price but no product link. Import the catalog (buddy commerce:import <url> --from ${a.name}), then re-run the order import to link ${x?"it":"them"}.`})}if(l.counts.partlyRefunded>0){let f=l.counts.partlyRefunded===1;l.warnings.push({message:`${l.counts.partlyRefunded} order${f?" was":"s were"} partly refunded at the source (${m.join("; ")}${f?"":", ..."}). Stacks orders have no refund column, so total_amount is what was charged.`})}return l}function ou(e=Fo){async function t(o,a){let s=await e.selectFrom(o).where("uuid","=",a).select("id").executeTakeFirst();if(!s)throw Error(`Inserted a row into ${o} but could not read it back (uuid ${a})`);return Number(s.id)}async function r(o,a){let s=[];for(let i=0;i<o.length;i+=500)s.push(...await a(o.slice(i,i+500)));return s}let n={async findCustomers({uuids:o,emails:a}){let s=await r(o,(c)=>e.selectFrom("customers").where("uuid","in",c).select(["id","uuid","email"]).execute()),i=eu(tu.DB_CONNECTION||"sqlite").param,u=await r(a.map((c)=>c.trim().toLowerCase()),async(c)=>{let d=c.map((l,y)=>i(y+1)).join(", "),m=await e.unsafe(`SELECT id, uuid, email FROM customers WHERE LOWER(email) IN (${d})`,c);return Array.isArray(m)?m:[]});return[...s,...u].map((c)=>({id:Number(c.id),uuid:c.uuid??null,email:String(c.email)}))},async createCustomer(o){return await e.insertInto("customers").values(o).execute(),t("customers",o.uuid)},async updateCustomer(o,a){await e.updateTable("customers").set(a).where("id","=",o).execute()},async advanceLastOrder(o,a){let s=eu(tu.DB_CONNECTION||"sqlite").param;await e.unsafe(`UPDATE customers SET last_order = ${s(1)} WHERE id = ${s(2)} AND (last_order IS NULL OR last_order < ${s(3)})`,[a,o,a])},async findOrders(o){let a=await r(o,(s)=>e.selectFrom("orders").where("uuid","in",s).select(["id","uuid"]).execute());return new Map(a.map((s)=>[String(s.uuid),Number(s.id)]))},async createOrder(o){return await e.insertInto("orders").values(o).execute(),t("orders",o.uuid)},async updateOrder(o,a){await e.updateTable("orders").set(a).where("id","=",o).execute()},async replaceOrderItems(o,a){if(await e.deleteFrom("order_items").where("order_id","=",o).execute(),a.length>0)await e.insertInto("order_items").values(a).execute()},async findProducts(o){let a=await r(o,(s)=>e.selectFrom("products").where("uuid","in",s).select(["id","uuid"]).execute());return new Map(a.map((s)=>[String(s.uuid),Number(s.id)]))},async findVariantProducts(o){let a=await r(o,(s)=>e.selectFrom("product_variants").where("uuid","in",s).select(["uuid","product_id"]).execute());return new Map(a.filter((s)=>s.product_id!==null&&s.product_id!==void 0).map((s)=>[String(s.uuid),Number(s.product_id)]))}};if(e===Fo)n.transaction=(o)=>Fo.transaction((a)=>o(ou(a)));return n}function dg(e={tables:{}}){let t=e.tables;for(let a of["customers","orders","order_items","products","product_variants"])t[a]??=[];function r(a,s){let i=t[a],u=i.reduce((c,d)=>Math.max(c,Number(d.id)),0)+1;return i.push({id:u,...s}),u}function n(a,s,i){let u=t[a].find((c)=>c.id===s);if(u)Object.assign(u,i)}let o=(a,s)=>new Map(t[a].filter((i)=>s.includes(i.uuid)).map((i)=>[i.uuid,i.id]));return{tables:t,findCustomers:async({uuids:a,emails:s})=>t.customers.filter((i)=>a.includes(i.uuid)||s.includes(String(i.email).trim().toLowerCase())).map((i)=>({id:i.id,uuid:i.uuid??null,email:i.email})),createCustomer:async(a)=>{if(t.customers.some((s)=>s.email===a.email))throw Error(`UNIQUE constraint failed: customers.email (${a.email})`);return r("customers",a)},updateCustomer:async(a,s)=>n("customers",a,s),advanceLastOrder:async(a,s)=>{let i=t.customers.find((u)=>u.id===a);if(i&&(i.last_order===null||i.last_order===void 0||String(i.last_order)<s))i.last_order=s},findOrders:async(a)=>o("orders",a),createOrder:async(a)=>r("orders",a),updateOrder:async(a,s)=>n("orders",a,s),replaceOrderItems:async(a,s)=>{t.order_items=t.order_items.filter((i)=>i.order_id!==a);for(let i of s)r("order_items",i)},findProducts:async(a)=>o("products",a),findVariantProducts:async(a)=>new Map(t.product_variants.filter((s)=>a.includes(s.uuid)).map((s)=>[s.uuid,s.product_id]))}}function lg(e){let t=-1,r=async()=>t--,n=[];return{async findCustomers(o){let a=await e.findCustomers(o),s=n.filter((i)=>i.uuid!==null&&o.uuids.includes(i.uuid)||o.emails.includes(i.email));return[...a,...s]},findOrders:e.findOrders,findProducts:e.findProducts,findVariantProducts:e.findVariantProducts,async createCustomer(o){let a=t--;return n.push({id:a,uuid:o.uuid??null,email:String(o.email??"").toLowerCase()}),a},createOrder:r,updateCustomer:async()=>{},advanceLastOrder:async()=>{},updateOrder:async()=>{},replaceOrderItems:async()=>{}}}var{randomUUIDv7:au}=globalThis.Bun;import{db as $o}from"@stacksjs/database/runtime";import{formatDate as mg}from"@stacksjs/orm";var iu="Unknown",pg=1,fg=50,Bo=100;function Wo(e){let t=e.map((r)=>r.priceMinor).filter((r)=>r!==null);return t.length>0?Math.min(...t):null}function uu(e){if(e.length===0||e.some((t)=>t.inventory===null))return null;return e.reduce((t,r)=>t+(r.inventory??0),0)}function cu(e){let t=new Map,r=[],n=new Set;for(let o of e.variants){let a=o.sku;if(a===null)t.set(o.externalId,null);else if(a.length>Bo)t.set(o.externalId,null),r.push({externalId:e.externalId,message:`"${e.name}" variant "${o.title}" has a SKU longer than ${Bo} characters; imported without it`});else if(n.has(a))t.set(o.externalId,null),r.push({externalId:e.externalId,message:`"${e.name}" variant "${o.title}" repeats SKU ${a}; imported without it`});else n.add(a),t.set(o.externalId,a)}return{skus:t,warnings:r}}function Uo(e,t,r,n,o){let a=uu(e.variants),s={uuid:te(e.source,t,"product",e.externalId),name:e.name,description:e.descriptionHtml,price:Wo(e.variants)??0,image_url:e.images[0]?.src??null,is_available:e.variants.some((i)=>i.available),updated_at:n};if(o==="create")s.inventory_count=a??0,s.preparation_time=pg,s.category_id=r.categoryId,s.manufacturer_id=r.manufacturerId,s.created_at=n;else{if(a!==null)s.inventory_count=a;if(r.categoryId!==null)s.category_id=r.categoryId;if(r.manufacturerId!==null)s.manufacturer_id=r.manufacturerId}return s}function Jo(e,t,r,n,o,a,s=t.sku){let i={uuid:te(e.source,r,"variant",t.externalId),product_id:n,variant:t.title,type:(e.optionNames.join(" / ")||"Option").slice(0,fg),options:JSON.stringify(t.optionValues),status:t.available?"active":"inactive",price:t.priceMinor,compare_at_price:t.compareAtMinor,updated_at:o};if(a==="create")i.sku=s,i.inventory_count=t.inventory,i.created_at=o;else{if(s!==null)i.sku=s;if(t.inventory!==null)i.inventory_count=t.inventory}return i}function su(e){let t={...e};return delete t.uuid,t}async function wg(e){let t=V(e.storeUrl),r=kt(t),n=e.now??(()=>new Date),{adapter:o,repository:a}=e,s={source:o.name,storeUrl:t,dryRun:e.dryRun===!0,pages:[],products:[],counts:{products:{created:0,updated:0},variants:{created:0,updated:0},categories:{created:0,updated:0},manufacturers:{created:0,updated:0},duplicates:0},currencies:[],warnings:[]},i=new Map,u=new Map,c=new Map,d=new Set;async function m(p,b,h){let f=p.categories[0];if(!f)return null;let x=i.get(f.slug);if(x!==void 0)return x;let D=await b.findCategory(f.slug,f.name);if(D===void 0)D=await b.createCategory({uuid:au(),name:f.name,slug:f.slug,description:null,image_url:null,is_active:!0,parent_category_id:null,display_order:i.size,created_at:h,updated_at:h}),s.counts.categories.created++;return i.set(f.slug,D),D}async function l(p,b,h){if(!p.vendor)return null;let f=u.get(p.vendor);if(f!==void 0)return f;let x=await b.findManufacturer(p.vendor);if(x===void 0)x=await b.createManufacturer({uuid:au(),manufacturer:p.vendor,description:null,country:iu,featured:!1,created_at:h,updated_at:h}),s.counts.manufacturers.created++;return u.set(p.vendor,x),x}async function y(p){let b=p.map((f)=>te(f.source,r,"product",f.externalId)),h=p.filter((f)=>f.hasOptions).flatMap((f)=>f.variants.map((x)=>te(f.source,r,"variant",x.externalId)));return{products:b.length>0?await a.findProducts(b):new Map,variants:h.length>0?await a.findVariants(h):new Map}}async function g(p,b,h){let f=mg(n()),x={categoryId:await m(p,b,f),manufacturerId:await l(p,b,f)},D=te(p.source,r,"product",p.externalId),v=h.products.get(D),F=v===void 0?"create":"update",k;if(v===void 0)k=await b.createProduct(Uo(p,r,x,f,"create"));else k=v,await b.updateProduct(k,su(Uo(p,r,x,f,"update")));let S={create:0,update:0};if(p.hasOptions){let{skus:C,warnings:O}=cu(p);s.warnings.push(...O);let M=[...C.values()].filter((re)=>re!==null);if(v!==void 0&&M.length>0)await b.releaseVariantSkus(k,M);for(let re of p.variants){let q=C.get(re.externalId)??null,bt=h.variants.get(te(p.source,r,"variant",re.externalId));if(bt===void 0)await b.createVariant(Jo(p,re,r,k,f,"create",q)),S.create++;else await b.updateVariant(bt,su(Jo(p,re,r,k,f,"update",q))),S.update++}}return{action:F,externalId:p.externalId,name:p.name,handle:p.handle,priceMinor:Wo(p.variants),currency:p.currency,variants:S,category:p.categories[0]?.name??null,vendor:p.vendor,imageCount:p.images.length}}for await(let p of o.pages(t,{limit:e.limit,fetch:e.fetch,currency:e.currency,accessKey:e.accessKey})){s.pages.push(p.url),s.warnings.push(...p.warnings);let b=[];for(let f of p.products){if(c.get(f.externalId)!==void 0){s.counts.duplicates++,s.warnings.push({externalId:f.externalId,message:`"${f.name}" appeared twice; imported once`});continue}c.set(f.externalId,f.handle),b.push(f)}let h=await y(b);for(let f of b){if(f.currency)d.add(f.currency);let x=a.transaction?await a.transaction((D)=>g(f,D,h)):await g(f,a,h);s.counts.products[x.action==="create"?"created":"updated"]++,s.counts.variants.created+=x.variants.create,s.counts.variants.updated+=x.variants.update,s.products.push(x),e.onProduct?.(x)}}if(s.currencies=[...d].sort(),s.currencies.length>1)s.warnings.push({message:`prices arrived in more than one currency (${s.currencies.join(", ")}); products.price has no currency column`});return s}function du(e=$o){async function t(a,s){let i=await e.selectFrom(a).where("uuid","=",s).select("id").executeTakeFirst();if(!i)throw Error(`Inserted a row into ${a} but could not read it back (uuid ${s})`);return Number(i.id)}async function r(a,s){let i=new Map;for(let u=0;u<s.length;u+=500){let c=await e.selectFrom(a).where("uuid","in",s.slice(u,u+500)).select(["id","uuid"]).execute();for(let d of c)i.set(d.uuid,Number(d.id))}return i}async function n(a){let s=await a.select("id").executeTakeFirst();return s?Number(s.id):void 0}let o={async findCategory(a,s){return await n(e.selectFrom("categories").where("slug","=",a))??await n(e.selectFrom("categories").where("name","=",s))},async createCategory(a){return await e.insertInto("categories").values(a).execute(),t("categories",a.uuid)},async findManufacturer(a){return n(e.selectFrom("manufacturers").where("manufacturer","=",a))},async createManufacturer(a){return await e.insertInto("manufacturers").values(a).execute(),t("manufacturers",a.uuid)},async findProducts(a){return r("products",a)},async createProduct(a){return await e.insertInto("products").values(a).execute(),t("products",a.uuid)},async updateProduct(a,s){await e.updateTable("products").set(s).where("id","=",a).execute()},async findVariants(a){return r("product_variants",a)},async createVariant(a){return await e.insertInto("product_variants").values(a).execute(),t("product_variants",a.uuid)},async updateVariant(a,s){await e.updateTable("product_variants").set(s).where("id","=",a).execute()},async releaseVariantSkus(a,s){for(let i=0;i<s.length;i+=500)await e.updateTable("product_variants").set({sku:null}).where("product_id","=",a).where("sku","in",s.slice(i,i+500)).execute()}};if(e===$o)o.transaction=(a)=>$o.transaction((s)=>a(du(s)));return o}function yg(){let e={categories:[],manufacturers:[],products:[],product_variants:[]};function t(a,s){let i=e[a].length+1;return e[a].push({id:i,...s}),i}function r(a,s,i){let u=e[a].find((c)=>c.id===s);if(u)Object.assign(u,i)}let n=(a,s)=>new Map(e[a].filter((i)=>s.includes(i.uuid)).map((i)=>[i.uuid,i.id])),o=(a,s)=>e[a].find(s)?.id;return{tables:e,findCategory:async(a,s)=>o("categories",(i)=>i.slug===a)??o("categories",(i)=>i.name===s),createCategory:async(a)=>t("categories",a),findManufacturer:async(a)=>o("manufacturers",(s)=>s.manufacturer===a),createManufacturer:async(a)=>t("manufacturers",a),findProducts:async(a)=>n("products",a),createProduct:async(a)=>t("products",a),updateProduct:async(a,s)=>r("products",a,s),findVariants:async(a)=>n("product_variants",a),createVariant:async(a)=>t("product_variants",a),updateVariant:async(a,s)=>r("product_variants",a,s),releaseVariantSkus:async(a,s)=>{for(let i of e.product_variants)if(i.product_id===a&&s.includes(i.sku))i.sku=null}}}function gg(e){let t=-1,r=async()=>t--;return{findCategory:e.findCategory,findManufacturer:e.findManufacturer,findProducts:e.findProducts,findVariants:e.findVariants,createCategory:r,createManufacturer:r,createProduct:r,createVariant:r,updateProduct:async()=>{},updateVariant:async()=>{},releaseVariantSkus:async()=>{}}}var lu={shopify:co,woocommerce:ko,shopware:ho};function hg(e){return lu[e.trim().toLowerCase()]}var mu={shopify:fo,woocommerce:To,shopware:Ro};function bg(e){return mu[e.trim().toLowerCase()]}var jo={};E(jo,{deleteCoupon:()=>fu,deleteCoupons:()=>wu,deleteExpiredCoupons:()=>yu,fetchActive:()=>xu,fetchAll:()=>bu,fetchByCode:()=>_u,fetchById:()=>Ze,fetchConversionRate:()=>Cu,fetchCouponCounts:()=>Pu,fetchCouponCountsByType:()=>vu,fetchRedemptionStats:()=>Du,fetchRedemptionTrend:()=>ku,fetchStats:()=>Ru,fetchTopRedeemedCoupons:()=>Su,getActiveCouponsMoMChange:()=>Tu,redeem:()=>$u,store:()=>Fu,update:()=>Ou});import{db as Lo}from"@stacksjs/database/runtime";import{formatDate as _g}from"@stacksjs/orm";async function fu(e){let t=await Lo.deleteFrom("coupons").where("id","=",e).executeTakeFirst();return _(t)>0}async function wu(e){if(!e.length)return 0;return await Lo.deleteFrom("coupons").where("id","in",e).execute()||0}async function yu(){let e=_g(new Date),t=await Lo.deleteFrom("coupons").where("end_date","<",e).executeTakeFirst();return _(t)}import{db as A}from"@stacksjs/database/runtime";import{extractDate as gu,formatDate as hu}from"@stacksjs/orm";import{camelCase as xg}from"@stacksjs/strings";function wr(e){let t=Object.fromEntries(Object.entries(e).map(([r,n])=>[xg(r),n]));if(t.endDate)t.endDate=gu(new Date(t.endDate));if(t.startDate)t.startDate=gu(new Date(t.startDate));if(t.isActive!==void 0)t.isActive=Boolean(t.isActive);return t}async function bu(){let e=await A.selectFrom("coupons").selectAll().execute();return P(e).map(wr)}async function Ze(e){let t=await A.selectFrom("coupons").where("id","=",e).selectAll().executeTakeFirst();if(t)return wr(w(t));return}async function _u(e){let t=await A.selectFrom("coupons").where("code","=",e).selectAll().executeTakeFirst();if(t)return wr(w(t));return}async function xu(){let e=hu(new Date),t=await A.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).selectAll().execute();return P(t).map(wr)}async function Ru(){let e=await A.selectFrom("coupons").select(A.fn.count("id").as("count")).executeTakeFirst(),t=hu(new Date),r=await A.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(A.fn.count("id").as("count")).executeTakeFirst(),n=await A.selectFrom("coupons").select(["discount_type",A.fn.count("id").as("count")]).groupBy("discount_type").execute(),o=await A.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),a=await A.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",t).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(e?.count||0),active:Number(r?.count||0),by_type:n,most_used:o,upcoming:a}}async function Pu(){let e=new Date,t=new Date(e);t.setDate(e.getDate()-7);let r=new Date(e);r.setMonth(e.getMonth()-1);let n=new Date(e);n.setFullYear(e.getFullYear()-1);let o=await fr(null,null,e),a=await fr(t,null,e),s=await fr(r,null,e),i=await fr(n,null,e);return{week:a,month:s,year:i,all_time:o}}async function fr(e,t,r){let n=A.selectFrom("coupons");if(e)n=n.where("created_at",">=",e.toISOString());if(t)n=n.where("created_at","<=",t.toISOString());let o=await n.select(A.fn.count("id").as("count")).executeTakeFirst(),a=A.selectFrom("coupons");if(e)a=a.where("created_at",">=",e.toISOString());if(t)a=a.where("created_at","<=",t.toISOString());a=a.where("is_active","=",!0).where("start_date","<=",r).where("end_date",">=",r);let s=await a.select(A.fn.count("id").as("count")).executeTakeFirst(),i=Number(o?.count||0),u=Number(s?.count||0),c=i-u;return{total:i,active:u,inactive:c}}async function vu(){let e=new Date,t=await A.selectFrom("coupons").select("discount_type").distinct().execute(),r={};for(let{discount_type:n}of t){let o=await A.selectFrom("coupons").where("discount_type","=",n).select(A.fn.count("id").as("count")).executeTakeFirst(),a=await A.selectFrom("coupons").where("discount_type","=",n).where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(A.fn.count("id").as("count")).executeTakeFirst(),s=Number(o?.count||0),i=Number(a?.count||0);r[n]={total:s,active:i,inactive:s-i}}return r}async function Du(){let e=await A.selectFrom("coupons").select(A.fn.sum("usage_count").as("total")).executeTakeFirst(),t=new Date,r=new Date(t);r.setDate(t.getDate()-7);let n=new Date(t);n.setMonth(t.getMonth()-1);let o=new Date(t);o.setFullYear(t.getFullYear()-1);let a=await A.selectFrom("coupons").where("updated_at",">=",r.toISOString()).select(A.fn.sum("usage_count").as("total")).executeTakeFirst(),s=await A.selectFrom("coupons").where("updated_at",">=",n.toISOString()).select(A.fn.sum("usage_count").as("total")).executeTakeFirst(),i=await A.selectFrom("coupons").where("updated_at",">=",o.toISOString()).select(A.fn.sum("usage_count").as("total")).executeTakeFirst(),u=await A.selectFrom("coupons").select(["discount_type",A.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),c={};return u.forEach((d)=>{c[d.discount_type]=Number(d.total||0)}),{total:Number(e?.total||0),week:Number(a?.total||0),month:Number(s?.total||0),year:Number(i?.total||0),by_type:c}}async function Su(e=5){return await A.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(e).execute()}async function ku(e=30){let t=new Date().toISOString(),r=new Date;r.setDate(r.getDate()-e);let n=await A.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",r.toISOString()).where("updated_at","<=",t).where("usage_count",">",0).orderBy("updated_at","desc").execute(),o={};return n.forEach((a)=>{let s=a.updated_at?new Date(a.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!o[s])o[s]=0;o[s]+=a?.usage_count||0}),Object.entries(o).map(([a,s])=>({date:a,count:s}))}async function Cu(){let e=new Date,t=await A.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(A.fn.count("id").as("count")).executeTakeFirst(),r=await A.selectFrom("coupons").where("usage_count",">",0).select(A.fn.count("id").as("count")).executeTakeFirst(),n=Number(t?.count||0),o=Number(r?.count||0);return{rate:n>0?o/n*100:0,total_active:n,total_redeemed:o}}async function Tu(){let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()-1,1),n=new Date(e.getFullYear(),e.getMonth(),0),o=await A.selectFrom("coupons").select(A.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",t).executeTakeFirst(),a=await A.selectFrom("coupons").select(A.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",n).where("end_date",">=",r).executeTakeFirst(),s=Number(o?.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:Rg}=globalThis.Bun;import{db as Au}from"@stacksjs/database/runtime";import{HttpError as Eu}from"@stacksjs/error-handling";import{isUniqueViolation as Pg}from"@stacksjs/orm";async function Fu(e){try{let t=Rg();await Au.insertInto("coupons").values({...e,uuid:t}).executeTakeFirst();let r=await Au.selectFrom("coupons").where("uuid","=",t).selectAll().executeTakeFirst();return w(r,!0)}catch(t){if(t instanceof Eu)throw t;if(Pg(t))throw new Eu(409,"A coupon with this code already exists");if(t instanceof Error)throw Error(`Failed to create coupon: ${t.message}`);throw t}}import{db as Mu,mutationCount as vg,sqlHelpers as Dg}from"@stacksjs/database/runtime";import{env as Sg}from"@stacksjs/env";import{HttpError as Iu}from"@stacksjs/error-handling";import{formatDate as Nu,isUniqueViolation as kg}from"@stacksjs/orm";async function Ou(e,t){if(!await Ze(e))return;try{return await Mu.updateTable("coupons").set({...t,updated_at:Nu(new Date)}).where("id","=",e).execute(),await Ze(e)}catch(n){if(n instanceof Iu)throw n;if(kg(n))throw new Iu(409,"A coupon with this code already exists");if(n instanceof Error)throw Error(`Failed to update coupon: ${n.message}`);throw n}}async function $u(e){let t=Dg(Sg.DB_CONNECTION||"sqlite"),r=t.param,n=Nu(new Date),o=await Mu.unsafe(`UPDATE coupons
2
+ var cy=Object.defineProperty;var dy=(e)=>e;function ly(e,t){this[e]=dy.bind(null,t)}var E=(e,t)=>{for(var r in t)cy(e,r,{get:t[r],enumerable:!0,configurable:!0,set:ly.bind(t,r)})};var my=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};function Je(e,t){if(e===t)return!0;return Kg[e]?.includes(t)??!1}async function Qe(e,t){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let n=r.dispatch;if(typeof n!=="function")return;n(e,t)}catch{}}async function Dr(e){await Qe("order:created",{order:e})}async function Ye(e,t){await Qe("order:paid",{order:e,payment:t})}async function ia(e){await Qe("order:shipped",{order:e})}async function Zg(e){await Qe("order:out_for_delivery",{order:e})}async function ua(e){await Qe("order:delivered",{order:e})}async function Nt(e,t){await Qe("order:cancelled",{order:e,reason:t})}async function Ot(e,t){await Qe("order:refunded",{order:e,refundAmount:t})}async function ct(e,t){switch(e){case"PROCESSING":return Ye(t);case"SHIPPED":return ia(t);case"OUT_FOR_DELIVERY":return Zg(t);case"DELIVERED":return ua(t);case"CANCELLED":return Nt(t);case"REFUNDED":return Ot(t);case"PENDING":default:}}var Kg;var dt=my(()=>{Kg={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={};E(no,{DEFAULT_INCREMENT_LADDER:()=>_e,auctionChannel:()=>ar,auctionTotals:()=>Gn,biddersFor:()=>In,bids:()=>Wn,bidsByBidder:()=>Fn,bidsForAuction:()=>En,bidsForItem:()=>An,broadcastBid:()=>Nn,broadcastItemClosed:()=>$n,broadcastPledge:()=>On,closeAuction:()=>Kn,closeDueItems:()=>Hn,closeItem:()=>kt,closingSoon:()=>Qn,closingSoonNotification:()=>gy,currencyFor:()=>Bn,determineWinner:()=>ot,effectiveCloseAt:()=>Ne,engine:()=>Ln,extendedCloseAt:()=>Pt,fetchAuction:()=>pe,fetchAuctionForEvent:()=>jn,fetchCatalogue:()=>zn,fetchItems:()=>Re,fetchPledges:()=>to,incrementFor:()=>de,leadingBid:()=>Rt,lots:()=>Yn,makePledge:()=>_s,nextMinimumBid:()=>xe,openAuction:()=>Vn,outbidNotification:()=>wy,placeBid:()=>Jn,pledgeLevels:()=>xs,pledgeTotal:()=>eo,pledges:()=>ro,resolveBid:()=>vt,rulesFor:()=>Dt,settle:()=>St,settleAuction:()=>Zn,winnerNotification:()=>yy});var Wn={};E(Wn,{biddersFor:()=>In,bidsByBidder:()=>Fn,bidsForAuction:()=>En,bidsForItem:()=>An,leadingBid:()=>Rt,placeBid:()=>Jn});import{db as xt}from"@stacksjs/database/runtime";async function Rt(e){return await xt.selectFrom("bids").selectAll().where("auction_item_id","=",e).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function An(e){return await xt.selectFrom("bids").selectAll().where("auction_item_id","=",e).orderBy("placed_at","desc").execute()??[]}async function En(e){return await xt.selectFrom("bids").selectAll().where("auction_id","=",e).orderBy("placed_at","asc").execute()??[]}async function Fn(e,t){return await xt.selectFrom("bids").selectAll().where("auction_id","=",e).where("bidder_email","=",t.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function In(e){let t=await xt.selectFrom("bids").select(["bidder_name","bidder_email"]).where("auction_id","=",e).execute(),r=new Map;for(let n of t??[]){let o=n.bidder_email.toLowerCase();if(!r.has(o))r.set(o,{name:n.bidder_name,email:n.bidder_email})}return[...r.values()]}var{randomUUIDv7:fy}=globalThis.Bun;import{db as Un}from"@stacksjs/database/runtime";function Pt(e,t,r,n){if(r.antiSnipeMinutes<=0||r.extendOnBidWindowMinutes<=0)return null;if(e.extension_count>=r.maxExtensions)return null;let o=t.getTime()-n.getTime();if(o<=0)return null;if(o>r.extendOnBidWindowMinutes*60000)return null;let a=new Date(n.getTime()+r.antiSnipeMinutes*60000);return a>t?a:null}function Ne(e,t){return new Date(e.closes_at??t)}var _e=[{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 de(e,t=_e,r){if(r&&r>0)return r;for(let n of t)if(n.upTo===null||e<n.upTo)return n.step;return t[t.length-1]?.step??100}function xe(e,t,r=_e){if(t===null||t<=0)return e.starting_bid;return t+de(t,r,e.min_increment)}function vt(e,t,r,n=_e){let o=Math.max(r.amount,r.maxAmount??0),a=xe(e,t?t.amount:null,n);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(o<a)return{accepted:!1,reason:"below_minimum",message:`The next bid on this lot is ${a/100}.`,nextMinimumBid:a};if(e.buy_now_price&&o>=e.buy_now_price)return{accepted:!0,buyNow:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:e.buy_now_price,maxAmount:e.buy_now_price,isChallenger:!0},challengerAmount:e.buy_now_price,outbid:t?{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:t.amount}:void 0,nextMinimumBid:e.buy_now_price};if(!t){let d=Math.max(e.starting_bid,r.amount);return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:d,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:d,nextMinimumBid:d+de(d,n,e.min_increment)}}let s=Math.max(t.amount,t.max_amount??0);if(t.bidder_email.toLowerCase()===r.bidderEmail.toLowerCase()){if(o<=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:t.bidder_email,bidderName:t.bidder_name,amount:t.amount,maxAmount:o,isChallenger:!1},challengerAmount:t.amount,nextMinimumBid:t.amount+de(t.amount,n,e.min_increment)}}if(o>s){let d=s+de(s,n,e.min_increment),m=Math.min(o,Math.max(d,a));return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:m,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:m,outbid:{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:t.amount},nextMinimumBid:m+de(m,n,e.min_increment)}}let u=o+de(o,n,e.min_increment),c=Math.min(s,Math.max(u,o));return{accepted:!0,leader:{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:c,maxAmount:t.max_amount??null,isChallenger:!1},challengerAmount:o,outbid:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:o},nextMinimumBid:c+de(c,n,e.min_increment)}}function ar(e){return`auction.${e}`}async function Mn(){try{let e=await import("@stacksjs/realtime");return e.emit??null}catch{return null}}async function Nn(e){let t=await Mn();if(!t||!e.item||!e.leader)return;await t(ar(e.item.auction_id),"bid.placed",{itemId:e.item.id,lotNumber:e.item.lot_number,amount:e.leader.amount,nextMinimumBid:e.nextMinimumBid,leaderName:e.leader.bidderName,status:e.item.status,closesAt:e.item.closes_at,extended:Boolean(e.extendedTo),soldViaBuyNow:Boolean(e.buyNow)})}async function On(e,t){let r=await Mn();if(!r)return;await r(ar(e.auction_id),"pledge.made",{donorName:e.donor_name,amount:e.amount,level:e.level??null,runningTotal:t})}async function $n(e,t,r){let n=await Mn();if(!n)return;await n(ar(e),"item.closed",{itemId:t,...r})}import{config as py}from"@stacksjs/config";function hs(){return py.commerce??{}}function bs(){return hs().auction??{}}function Dt(e){let t=bs();return{increments:t.increments?.length?t.increments:_e,antiSnipeMinutes:e?.anti_snipe_minutes??t.antiSnipeMinutes??2,extendOnBidWindowMinutes:e?.extend_on_bid_window_minutes??t.extendOnBidWindowMinutes??2,maxExtensions:e?.max_extensions??t.maxExtensions??20}}function Bn(e){return e?.currency??bs().currency??hs().currency??"USD"}function sr(e){return e.toISOString().slice(0,19).replace("T"," ")}async function Jn(e){let t=e.now??new Date,r=await Un.selectFrom("auction_items").selectAll().where("id","=",e.itemId).executeTakeFirst();if(!r)return{accepted:!1,reason:"item_not_found",message:"That lot is no longer available.",nextMinimumBid:0};let n=await Un.selectFrom("auctions").selectAll().where("id","=",r.auction_id).executeTakeFirst(),o=Dt(n),a=await Rt(r.id),s=xe(r,a?.amount??null,o.increments);if(!n||n.status!=="open"||new Date(n.opens_at)>t)return{accepted:!1,reason:"auction_not_open",message:"Bidding is not open yet.",nextMinimumBid:s,item:r};let i=Ne(r,n.closes_at);if(r.status!=="open"||i<=t)return{accepted:!1,reason:"item_not_open",message:"Bidding on this lot has closed.",nextMinimumBid:s,item:r};let u=vt(r,a,{bidderEmail:e.bidderEmail,bidderName:e.bidderName,amount:e.amount,maxAmount:e.maxAmount},o.increments);if(!u.accepted)return{...u,item:r};let c=u.buyNow?null:Pt(r,i,o,t),d=u.leader&&!u.leader.isChallenger&&a&&a.bidder_email.toLowerCase()===e.bidderEmail.toLowerCase(),m=await Un.transaction(async(y)=>{if(d&&a)return await y.updateTable("bids").set({max_amount:u.leader.maxAmount}).where("id","=",a.id).execute(),{...a,max_amount:u.leader.maxAmount};let g=u.leader?.isChallenger===!0,p=fy();if(await y.insertInto("bids").values({uuid:p,auction_id:r.auction_id,auction_item_id:r.id,bidder_name:e.bidderName,bidder_email:e.bidderEmail.toLowerCase(),amount:u.challengerAmount??e.amount,max_amount:e.maxAmount??null,status:g?"leading":"outbid",placed_at:sr(t)}).execute(),a){if(g)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:sr(t)}).where("id","=",r.id).execute();else if(c)await y.updateTable("auction_items").set({closes_at:sr(c),extension_count:r.extension_count+1}).where("id","=",r.id).execute();return await y.selectFrom("bids").selectAll().where("uuid","=",p).executeTakeFirst()}),l={...u,bid:m,item:{...r,status:u.buyNow?"sold":r.status,closes_at:c?sr(c):r.closes_at,extension_count:c?r.extension_count+1:r.extension_count},extendedTo:c??void 0};return await Nn(l).catch(()=>{return}),l}var Ln={};E(Ln,{DEFAULT_INCREMENT_LADDER:()=>_e,determineWinner:()=>ot,effectiveCloseAt:()=>Ne,extendedCloseAt:()=>Pt,incrementFor:()=>de,nextMinimumBid:()=>xe,resolveBid:()=>vt,settle:()=>St});function ot(e,t){let r=t.filter((a)=>a.status!=="invalid");if(r.length===0)return{itemId:e.id,lotNumber:e.lot_number,title:e.title,status:"passed",amount:0,passedReason:"no_bids"};let o=[...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(e.reserve_price&&o.amount<e.reserve_price)return{itemId:e.id,lotNumber:e.lot_number,title:e.title,status:"passed",amount:o.amount,passedReason:"reserve_not_met"};return{itemId:e.id,lotNumber:e.lot_number,title:e.title,status:"sold",winningBidId:o.id,winnerName:o.bidder_name,winnerEmail:o.bidder_email,amount:o.amount}}function St(e,t,r,n){let o=t.filter((m)=>m.status==="sold"),a=t.filter((m)=>m.status==="passed"),s=o.reduce((m,l)=>m+l.amount,0),i=r.filter((m)=>m.status==="confirmed").reduce((m,l)=>m+l.amount,0),u=new Map(e.map((m)=>[m.id,m.fair_market_value??null])),c=o.reduce((m,l)=>{let y=u.get(l.itemId);return y==null?m:m+(l.amount-y)},0),d=t.length;return{auctionId:n.auctionId,currency:n.currency,totalRaised:s+i,bidRevenue:s,pledgeRevenue:i,goalAmount:n.goalAmount??null,itemsSold:o.length,itemsPassed:a.length,sellThrough:d===0?0:o.length/d,valueDelta:c,outcomes:t}}var Yn={};E(Yn,{auctionTotals:()=>Gn,closeAuction:()=>Kn,closeDueItems:()=>Hn,closeItem:()=>kt,closingSoon:()=>Qn,fetchAuction:()=>pe,fetchAuctionForEvent:()=>jn,fetchCatalogue:()=>zn,fetchItems:()=>Re,openAuction:()=>Vn,settleAuction:()=>Zn});import{db as Oe}from"@stacksjs/database/runtime";async function pe(e){return await Oe.selectFrom("auctions").selectAll().where("id","=",e).executeTakeFirst()??null}async function jn(e){return await Oe.selectFrom("auctions").selectAll().where("event_id","=",e).executeTakeFirst()??null}async function Re(e){return await Oe.selectFrom("auction_items").selectAll().where("auction_id","=",e).orderBy("lot_number","asc").execute()??[]}async function zn(e){let[t,r]=await Promise.all([pe(e),Re(e)]),n=Dt(t),o=await Oe.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",e).where("status","in",["leading","won"]).execute(),a=await Oe.selectFrom("bids").select(["auction_item_id"]).where("auction_id","=",e).where("status","!=","invalid").execute(),s=new Map((o??[]).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:xe(u,c?.amount??null,n.increments),leaderName:c?.bidder_name??null}})}async function Gn(e){let t=await pe(e),r=await Oe.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",e).where("status","!=","invalid").execute(),n=await Oe.selectFrom("pledges").select(["amount"]).where("auction_id","=",e).where("status","=","confirmed").execute(),o=r??[],s=o.filter((c)=>c.status==="leading"||c.status==="won").reduce((c,d)=>c+d.amount,0),i=(n??[]).reduce((c,d)=>c+d.amount,0),u=await Oe.selectFrom("auction_items").where("auction_id","=",e).count();return{currentBidTotal:s,pledgeTotal:i,raised:s+i,goalAmount:t?.goal_amount??null,bidCount:o.length,bidderCount:new Set(o.map((c)=>c.bidder_email.toLowerCase())).size,lotsOffered:Number(u??0),lotsWithBids:new Set(o.map((c)=>c.auction_item_id)).size}}import{db as $e}from"@stacksjs/database/runtime";function qn(e){return e.toISOString().slice(0,19).replace("T"," ")}async function Vn(e,t=new Date){return await $e.updateTable("auctions").set({status:"open",opens_at:qn(t)}).where("id","=",e).execute(),await $e.updateTable("auction_items").set({status:"open"}).where("auction_id","=",e).where("status","=","closed").execute(),pe(e)}async function kt(e,t=new Date){if(e.status==="sold"||e.status==="passed")return null;let r=await $e.selectFrom("bids").selectAll().where("auction_item_id","=",e.id).execute(),n=ot(e,r??[]);return await $e.transaction(async(o)=>{if(await o.updateTable("auction_items").set({status:n.status,closes_at:qn(t)}).where("id","=",e.id).execute(),n.winningBidId)await o.updateTable("bids").set({status:"won"}).where("id","=",n.winningBidId).execute();await o.updateTable("bids").set({status:"lost"}).where("auction_item_id","=",e.id).where("status","in",["leading","outbid"]).execute()}),await $n(e.auction_id,e.id,{status:n.status,amount:n.amount,winnerName:n.winnerName}).catch(()=>{return}),n}async function Hn(e,t=new Date){let r=await pe(e);if(!r)return[];let n=await Re(e),o=[];for(let a of n){if(a.status!=="open")continue;if(Ne(a,r.closes_at)>t)continue;let s=await kt(a,t);if(s)o.push(s)}return o}async function Kn(e,t=new Date){let r=await Re(e),n=[];for(let o of r){let a=await kt(o,t);if(a)n.push(a)}return await $e.updateTable("auctions").set({status:"closed",closes_at:qn(t)}).where("id","=",e).execute(),n}async function Zn(e,t={}){let r=await pe(e);if(!r)return null;let n=await Re(e),o=await $e.selectFrom("bids").selectAll().where("auction_id","=",e).execute(),a=await $e.selectFrom("pledges").selectAll().where("auction_id","=",e).execute(),s=new Map;for(let u of o??[]){let c=s.get(u.auction_item_id)??[];c.push(u),s.set(u.auction_item_id,c)}let i=n.map((u)=>{let c=ot(u,s.get(u.id)??[]);return u.status==="passed"?{...c,status:"passed"}:c});if(t.markSettled)await $e.updateTable("auctions").set({status:"settled"}).where("id","=",e).execute();return St(n,i,a??[],{auctionId:e,currency:Bn(r),goalAmount:r.goal_amount??null})}async function Qn(e,t,r=new Date){let n=await pe(e);if(!n)return[];let o=new Date(r.getTime()+t*60000);return(await Re(e)).filter((a)=>{if(a.status!=="open")return!1;let s=Ne(a,n.closes_at);return s>r&&s<=o})}function Xn(e,t="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:t,minimumFractionDigits:0}).format(e/100)}function wy(e,t="USD"){if(!e.outbid||!e.item)return null;let r=e.item;return{to:{name:e.outbid.bidderName,email:e.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 ${Xn(e.nextMinimumBid,t)}. Bidding closes ${new Date(r.closes_at??"").toLocaleString()}.`,data:{itemId:r.id,lotNumber:r.lot_number,title:r.title,nextMinimumBid:e.nextMinimumBid,closesAt:r.closes_at}}}function yy(e,t="USD"){if(e.status!=="sold"||!e.winnerEmail)return null;return{to:{name:e.winnerName??"Bidder",email:e.winnerEmail},type:"winner",subject:`You won lot ${e.lotNumber}: ${e.title}`,body:`Congratulations - you won "${e.title}" at ${Xn(e.amount,t)}. The school will be in touch with payment and pickup details.`,data:{itemId:e.itemId,lotNumber:e.lotNumber,title:e.title,amount:e.amount}}}function gy(e,t,r,n="USD"){return{to:t,type:"closing_soon",subject:`Closing soon: lot ${e.lot_number}, ${e.title}`,body:`"${e.title}" closes at ${new Date(e.closes_at??"").toLocaleString()}. The current bid is ${Xn(r,n)}.`,data:{itemId:e.id,lotNumber:e.lot_number,title:e.title,currentBid:r,closesAt:e.closes_at}}}var ro={};E(ro,{fetchPledges:()=>to,makePledge:()=>_s,pledgeLevels:()=>xs,pledgeTotal:()=>eo});var{randomUUIDv7:hy}=globalThis.Bun;import{db as ir}from"@stacksjs/database/runtime";async function _s(e){let t=hy();await ir.insertInto("pledges").values({uuid:t,auction_id:e.auctionId,donor_name:e.donorName,donor_email:e.donorEmail.toLowerCase(),amount:e.amount,level:e.level??null,status:e.status??"confirmed"}).execute();let r=await ir.selectFrom("pledges").selectAll().where("uuid","=",t).executeTakeFirst();return await On(r,await eo(e.auctionId)).catch(()=>{return}),r}async function eo(e){return(await ir.selectFrom("pledges").select(["amount"]).where("auction_id","=",e).where("status","=","confirmed").execute()??[]).reduce((r,n)=>r+n.amount,0)}async function to(e){return await ir.selectFrom("pledges").selectAll().where("auction_id","=",e).orderBy("amount","desc").execute()??[]}async function xs(e){let t=(await to(e)).filter((n)=>n.status==="confirmed"),r=new Map;for(let n of t){let o=n.level??"other",a=r.get(o)??{amount:0,count:0};a.amount+=n.amount,a.count+=1,r.set(o,a)}return[...r.entries()].map(([n,o])=>({level:n,...o})).sort((n,o)=>o.amount-n.amount)}var oo={};E(oo,{bulkDestroy:()=>vs,bulkStore:()=>Es,bulkUpdate:()=>Ns,destroy:()=>Ps,fetchAll:()=>ks,fetchById:()=>Ss,store:()=>As,update:()=>Ms});import{db as Rs}from"@stacksjs/database/runtime";import{mutationCount as _}from"@stacksjs/database/runtime";async function Ps(e){try{let t=await Rs.deleteFrom("carts").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete cart: ${t.message}`);throw t}}async function vs(e){if(!e.length)return 0;try{let t=await Rs.deleteFrom("carts").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete carts: ${t.message}`);throw t}}import{db as Ds}from"@stacksjs/database/runtime";function by(e){return e.replace(/_([a-z0-9])/g,(t,r)=>r.toUpperCase())}function w(e){if(e===null||typeof e!=="object")return e;let t={...e};for(let[r,n]of Object.entries(t)){if(!r.includes("_"))continue;let o=by(r);if(!(o in t))t[o]=n}return t}function P(e){return e.map((t)=>w(t))}async function Ss(e){let t=await Ds.selectFrom("carts").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function ks(){return P(await Ds.selectFrom("carts").selectAll().execute())}var{randomUUIDv7:Cs}=globalThis.Bun;import{db as Ts}from"@stacksjs/database/runtime";async function As(e){try{let t={...e,uuid:Cs()},r=await Ts.insertInto("carts").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create cart");return w(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create cart: ${t.message}`);throw t}}async function Es(e){if(!e.length)return 0;let t=0;try{return await Ts.transaction(async(r)=>{for(let n of e){let o={...n,uuid:Cs()};await r.insertInto("carts").values(o).execute(),t++}}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create carts in bulk: ${r.message}`);throw r}}import{db as Fs,matchedRows as _y}from"@stacksjs/database/runtime";import{formatDate as Is}from"@stacksjs/orm";async function Ms(e,t){try{let r=await Fs.updateTable("carts").set({...t,updated_at:Is(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update cart");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update cart: ${r.message}`);throw r}}async function Ns(e){if(!e.length)return 0;let t=0;try{return await Fs.transaction(async(r)=>{for(let n of e){if(!n.id)continue;if((await _y(r.updateTable("carts").set({...n,updated_at:Is(new Date)}).where("id","=",n.id))).length>0)t++}}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update carts in bulk: ${r.message}`);throw r}}var io={};E(io,{SIZES:()=>Os,categoryRank:()=>so,compareCatalog:()=>xy,isLowStock:()=>Py,matchesSearch:()=>Ry,sizeOf:()=>ao});var Os=["XXS","XS","S","M","L","XL","XXL","2XL","3XL","4XL"];function ao(e){let t=/^(.*?)\s*[\u2014\u2013\-/]\s*(XXS|XS|S|M|L|XL|XXL|2XL|3XL|4XL)$/i.exec(String(e).trim());if(!t)return{base:String(e).trim(),size:null,rank:-1};let r=t[2].toUpperCase();return{base:t[1],size:r,rank:Os.indexOf(r)}}function so(e,t=[]){let r=t.indexOf(String(e||""));if(r!==-1)return r;return e?t.length:t.length+1}function xy(e=[]){return(t,r)=>{let n=so(t.category,e)-so(r.category,e)||String(t.category||"").localeCompare(String(r.category||""));if(n)return n;let o=ao(String(t.name||"")),a=ao(String(r.name||""));return o.base.localeCompare(a.base)||o.rank-a.rank}}function Ry(e,t){let r=String(t||"").toLowerCase().split(/\s+/).filter(Boolean);if(!r.length)return!0;let n=e.map((o)=>String(o??"")).join(" ").toLowerCase();return r.every((o)=>n.includes(o))}function Py(e,t,r=5){if(e===null||e===void 0)return!1;return Number(e)<=(t===null||t===void 0?r:Number(t))}var fu={};E(fu,{ACCOUNT_CREDENTIAL_ENV:()=>po,ACCOUNT_CREDENTIAL_HELP:()=>he,AdminCredentialError:()=>Tt,CATALOG_IMPORT_NAMESPACE:()=>Xi,CatalogFetchError:()=>T,MAX_RETRIES:()=>fo,MissingCredentialsError:()=>it,PriceFormatError:()=>I,SHOPIFY_ADMIN_API_VERSION:()=>ni,SHOPWARE_ACCESS_KEY_HELP:()=>go,SKU_MAX:()=>Uo,UNKNOWN_COUNTRY:()=>uu,accountAdapter:()=>_g,accountAdapters:()=>pu,addressLine:()=>je,adminRequest:()=>Be,amountOrZero:()=>ze,catalogAdapter:()=>bg,catalogAdapters:()=>mu,catalogUuid:()=>te,cleanName:()=>J,createDatabaseAccountRepository:()=>au,createDatabaseRepository:()=>lu,createMemoryAccountRepository:()=>lg,createMemoryRepository:()=>gg,createReadOnlyAccountRepository:()=>mg,createReadOnlyRepository:()=>hg,credentialSecrets:()=>qe,currencyCode:()=>ie,currencyExponent:()=>U,customerRow:()=>fr,customerUuid:()=>Ke,decimalToMinor:()=>ee,decodeHtmlEntities:()=>zs,defaultSleep:()=>Xs,detectShopifyCurrency:()=>Zs,detectShopwareCurrency:()=>yi,fetchJson:()=>fe,formatMinor:()=>ne,gmtTimestamp:()=>ur,importCatalog:()=>yg,importCustomers:()=>cg,importOrders:()=>dg,isoTimestamp:()=>we,lineLabel:()=>Mo,lowestPrice:()=>Lo,mapShopifyCustomer:()=>oi,mapShopifyOrder:()=>si,mapShopifyProduct:()=>Ks,mapShopwareCustomer:()=>vi,mapShopwareOrder:()=>ki,mapShopwareProduct:()=>pi,mapWooCustomer:()=>Gi,mapWooOrder:()=>qi,mapWooProduct:()=>Bi,minorToDecimal:()=>Pe,missingAccessKeyMessage:()=>wi,nextPageInfo:()=>ii,normalizeEmail:()=>oe,normalizeStoreUrl:()=>V,numberToDecimalString:()=>js,numberToMinor:()=>st,optionalString:()=>R,orderRow:()=>nu,personName:()=>H,phoneOf:()=>ye,productRow:()=>Jo,promotedCustomerUuid:()=>Oo,quantityOf:()=>Ge,readAccountCredentials:()=>Ey,redactSecrets:()=>Ve,rescaleMinor:()=>at,retryAfterSeconds:()=>$s,shopifyAccountAdapter:()=>wo,shopifyAdapter:()=>lo,shopifyAdminBase:()=>ui,shopifyOrderStatus:()=>ai,shopwareAccessToken:()=>Ro,shopwareAccountAdapter:()=>Po,shopwareAdapter:()=>bo,shopwareAdminBase:()=>Ci,shopwareBaseUrl:()=>fi,shopwareCustomerCriteria:()=>Ti,shopwareLineLabel:()=>Si,shopwareOrderCriteria:()=>Ai,shopwareOrderStatus:()=>Di,shopwareProductCriteria:()=>hi,shopwareVariantCriteria:()=>bi,signedMinor:()=>ge,storeHost:()=>Ct,totalInventory:()=>cu,unitFromTotal:()=>mo,uuidV5:()=>eu,variantRow:()=>Wo,variantSkus:()=>du,wooAdminBase:()=>Vi,wooAuthorization:()=>Hi,wooCommerceAccountAdapter:()=>Ao,wooCommerceAdapter:()=>Co,wooOrderStatus:()=>zi,wooPrices:()=>Oi,wooSlug:()=>$i});import{slug as Gs}from"@stacksjs/strings";class T extends Error{url;status;body;retryAfter;constructor(e,t,r,n,o){super(t);this.url=e;this.status=r;this.body=n;this.retryAfter=o;this.name="CatalogFetchError"}}var vy=2000,Dy=30000;function V(e){let t=e.trim();if(!t)throw TypeError("A store URL is required, e.g. https://shop.example.com");let r=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`https://${t}`,n;try{n=new URL(r)}catch{throw TypeError(`"${e}" is not a valid store URL`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw TypeError(`"${e}" must be an http(s) URL`);let o=n.pathname.replace(/\/+$/,"");return`${n.protocol}//${n.host.toLowerCase()}${o}`}function Ct(e){return new URL(e).host.toLowerCase()}function $s(e,t=Date.now){let r=e?.trim();if(!r)return;if(/^\d+(?:\.\d+)?$/.test(r))return Number(r);let n=Date.parse(r);return Number.isNaN(n)?void 0:Math.max(0,(n-t())/1000)}async function fe(e,t=fetch,r="",n={}){let o=r?` ${r}`:"",a={accept:"application/json",...n.headers};if(n.json!==void 0)a["content-type"]="application/json";let s;try{s=await t(e,{method:n.method??(n.json!==void 0?"POST":"GET"),headers:a,...n.json!==void 0?{body:JSON.stringify(n.json)}:{},signal:AbortSignal.timeout(Dy)})}catch(u){let c=u instanceof Error?u.message:String(u);throw new T(e,`Could not reach ${e}: ${c}.${o}`)}if(!s.ok){let u=`${s.status}${s.statusText?` ${s.statusText}`:""}`,c=await s.text().catch(()=>"");throw new T(e,`${e} responded ${u}.${o}`,s.status,c?c.slice(0,vy):void 0,$s(s.headers.get("retry-after")))}let i=await s.text();try{return{data:JSON.parse(i),headers:s.headers}}catch{let u=s.headers.get("content-type")||"no content-type";throw new T(e,`${e} did not return JSON (${u}).${o}`,s.status)}}var Ls={};E(Ls,{PriceFormatError:()=>I,currencyExponent:()=>U,decimalToMinor:()=>ee,formatCurrency:()=>Bs,formatMinor:()=>ne,minorToDecimal:()=>Pe,minorToInput:()=>Us,minorToMajor:()=>uo,moneyInputError:()=>co,moneyInputStep:()=>Js,parseMoneyInput:()=>Ws,rescaleMinor:()=>at});class I extends Error{value;constructor(e,t){super(`Unreadable price ${JSON.stringify(e)}: ${t}`);this.value=e;this.name="PriceFormatError"}}function U(e){if(!e)return 2;try{let t=new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits;return typeof t==="number"?t:2}catch{return 2}}function ee(e,t=2){if(e===null||e===void 0)return null;let r=String(e).trim();if(r==="")return null;let n=/^(\d*)(?:\.(\d*))?$/.exec(r);if(!n||!/\d/.test(r))throw new I(e,"expected a plain decimal such as 19.99");let o=n[1]||"0",a=n[2]??"",s;if(a.length<=t)s=BigInt(o+a.padEnd(t,"0"));else if(s=BigInt(o+a.slice(0,t)),a.charCodeAt(t)>=53)s+=1n;if(s>BigInt(Number.MAX_SAFE_INTEGER))throw new I(e,"too large to store exactly");return Number(s)}function Pe(e,t=2){let r=String(e).trim();if(!/^\d+$/.test(r))throw new I(e,"expected a non-negative integer amount in minor units");if(t===0)return r.replace(/^0+(?=\d)/,"");let n=r.padStart(t+1,"0");return`${n.slice(0,-t).replace(/^0+(?=\d)/,"")}.${n.slice(-t)}`}function at(e,t,r){if(e===null||e===void 0||String(e).trim()==="")return null;if(!Number.isInteger(t)||t<0)throw new I(e,`invalid source precision ${t}`);return ee(Pe(String(e),t),r)}function ne(e,t){let r=U(t),n=Math.round(Number(e)),o=Number.isSafeInteger(n)?`${n<0?"-":""}${Pe(Math.abs(n),r)}`:String(e);return t?`${o} ${t}`:o}function uo(e,t){let r=Math.round(Number(e??0));if(!Number.isFinite(r))return 0;let n=Pe(Math.abs(r),U(t));return r<0?-Number(n):Number(n)}function Bs(e,t,r){let n=(t||"USD").toUpperCase(),o=uo(e,n);try{return new Intl.NumberFormat(r,{style:"currency",currency:n}).format(o)}catch{return ne(Math.round(Number(e??0))||0,n)}}function Us(e,t){if(e===null||e===void 0||e==="")return"";let r=Math.round(Number(e));if(!Number.isFinite(r))return"";let n=Pe(Math.abs(r),U(t));return r<0?`-${n}`:n}function Js(e){let t=U(e);return t===0?"1":`0.${"1".padStart(t,"0")}`}function co(e,t,r={}){let n=e===null||e===void 0?"":String(e).trim(),o=U(t),a=(t||"USD").toUpperCase();if(n==="")return r.required===!1?"":"Enter an amount.";let s=/^(\d*)(?:\.(\d*))?$/.exec(n);if(!s||!/\d/.test(n))return o===0?"Enter a whole number, for example 1999.":`Enter a plain amount, for example ${Pe(1999,o)}.`;if((s[2]??"").length>o)return o===0?`${a} amounts have no decimal places.`:`${a} amounts have at most ${o} decimal ${o===1?"place":"places"}.`;let u;try{u=ee(n,o)}catch{return"That amount is too large."}if(u===null)return"Enter an amount.";if(r.min!==void 0&&u<r.min)return`Enter at least ${ne(r.min,a)}.`;if(r.max!==void 0&&u>r.max)return`Enter at most ${ne(r.max,a)}.`;return""}function Ws(e,t,r={}){let n=co(e,t,r);if(n)throw new I(e,n);return ee(e,U(t))}function js(e){if(typeof e!=="number"||!Number.isFinite(e))throw new I(e,"expected a finite number");if(e<0)throw new I(e,"expected an amount of zero or more");let t=String(e),r=/^(\d+)(?:\.(\d+))?e([+-]\d+)$/.exec(t);if(!r)return t;let[,n,o="",a]=r,s=`${n}${o}`,i=n.length+Number(a);if(i<=0)return`0.${"0".repeat(-i)}${s}`;if(i>=s.length)return`${s}${"0".repeat(i-s.length)}`;return`${s.slice(0,i)}.${s.slice(i)}`}function st(e,t=2){if(e===null||e===void 0)return null;if(typeof e==="string")return ee(e,t);return ee(js(e),t)}var Sy={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",ndash:"\u2013",mdash:"\u2014",hellip:"\u2026",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",laquo:"\xAB",raquo:"\xBB",trade:"\u2122",reg:"\xAE",copy:"\xA9",deg:"\xB0",times:"\xD7",frac12:"\xBD",euro:"\u20AC",pound:"\xA3",yen:"\xA5",cent:"\xA2"};function zs(e){return e.replace(/&(#x[0-9a-f]+|#\d+|[a-z][a-z0-9]*);/gi,(t,r)=>{if(r[0]==="#"){let n=r[1]==="x"||r[1]==="X"?Number.parseInt(r.slice(2),16):Number.parseInt(r.slice(1),10);return Number.isInteger(n)&&n>0&&n<=1114111?String.fromCodePoint(n):t}return Sy[r.toLowerCase()]??t})}function J(e){if(typeof e!=="string")return"";return zs(e).replace(/\s+/g," ").trim()}function R(e){if(typeof e!=="string")return null;let t=e.trim();return t===""?null:t}var qs=250,Vs=400;function ky(e){if(!e||e.length===0)return!0;if(e.length!==1)return!1;let[t]=e;return t?.name==="Title"&&(t.values?.length??0)<=1&&(t.values?.[0]??"Default Title")==="Default Title"}function Cy(e){return(Array.isArray(e)?e:typeof e==="string"?e.split(","):[]).map((r)=>String(r).trim()).filter(Boolean)}function Hs(e,t,r,n,o){try{return ee(e,t)}catch(a){if(!(a instanceof I))throw a;return o.push({externalId:n,message:`${r}: ${a.message}; left unpriced`}),null}}function Ks(e,t){if(e?.id===void 0||e.id===null||e.id==="")throw TypeError("Shopify product has no id");let r=String(e.id),n=[],o=(R(e.title)??"").replace(/\s+/g," ");if(!o)throw TypeError(`Shopify product ${r} has no title`);let a=R(e.handle)??Gs(o),s=U(t.currency),i=!ky(e.options),u=i?(e.options??[]).map((l)=>R(l.name)??"").filter(Boolean):[],c=(e.variants??[]).map((l)=>{let y=String(l.id),g=Hs(l.compare_at_price,s,`variant ${y} compare-at price`,r,n);return{externalId:y,title:R(l.title)??o,sku:R(l.sku),priceMinor:Hs(l.price,s,`variant ${y} price`,r,n),compareAtMinor:g?g:null,available:l.available!==!1,inventory:typeof l.inventory_quantity==="number"?Math.max(0,Math.trunc(l.inventory_quantity)):null,optionValues:i?[l.option1,l.option2,l.option3].slice(0,u.length).map((p)=>R(p)??""):[]}});if(c.length===0)n.push({externalId:r,message:`"${o}" has no variants; imported without a price`});let d=[...e.images??[]].filter((l)=>R(l?.src)).sort((l,y)=>(l.position??0)-(y.position??0)).map((l)=>({src:R(l.src),alt:R(l.alt)})),m=R(e.product_type);return{product:{source:"shopify",externalId:r,name:o,handle:a,descriptionHtml:R(e.body_html),vendor:R(e.vendor),categories:m?[{name:m,slug:Gs(m)}]:[],tags:Cy(e.tags),currency:t.currency,images:d,optionNames:u,variants:c,hasOptions:i,url:`${t.storeUrl}/products/${a}`},warnings:n}}async function Zs(e,t=fetch){try{let{data:r}=await fe(`${e}/meta.json`,t),n=typeof r?.currency==="string"?r.currency.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(n)?n:null}catch{return null}}async function*Ty(e,t={}){let r=V(e),n=t.fetch??fetch,o=t.limit,a=o&&o>0?Math.min(qs,o):qs,s=[],i=t.currency?.toUpperCase()??null;if(!i){if(i=await Zs(r,n),!i)s.push({message:`${r}/meta.json did not report a currency; prices read as 2-decimal amounts. Pass --currency to be sure.`})}let u=new Set,c=0;for(let d=1;d<=Vs;d++){let m=`${r}/products.json?limit=${a}&page=${d}`,{data:l}=await fe(m,n,"Is this a Shopify storefront, and is it public (no storefront password)?");if(!Array.isArray(l?.products))throw new T(m,`${m} did not return a "products" list. Is this a Shopify storefront?`);let y=l.products;if(y.length===0)return;let g=y.map((h)=>String(h?.id));if(d>1&&g.every((h)=>u.has(h)))throw new T(m,`${m} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);g.forEach((h)=>u.add(h));let p=[],b=d===1?s:[];for(let h of y){if(o&&c>=o)break;try{let f=Ks(h,{storeUrl:r,currency:i});p.push(f.product),b.push(...f.warnings),c++}catch(f){b.push({externalId:h?.id===void 0?void 0:String(h.id),message:`skipped: ${f.message}`})}}if(yield{url:m,products:p,warnings:b},o&&c>=o)return}throw new T(r,`Stopped after ${Vs} pages of ${r}/products.json without reaching the end.`)}var lo={name:"shopify",pages:Ty};var Ay=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function oe(e){if(typeof e!=="string")return null;let t=e.trim().toLowerCase();return Ay.test(t)?t:null}function we(e){if(typeof e!=="string"||e.trim()==="")return null;let t=new Date(e.trim());return Number.isNaN(t.getTime())?null:t.toISOString()}function ur(e){if(typeof e!=="string"||e.trim()==="")return null;let t=e.trim();return we(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(t)?t:`${t}Z`)}function H(...e){let t=e.map((r)=>J(r)).filter(Boolean).join(" ");return t===""?null:t}function ye(...e){for(let t of e){let r=R(typeof t==="number"?String(t):t);if(r)return r.slice(0,50)}return null}function je(...e){let t=e.map((r)=>J(r)).filter(Boolean).join(", ");return t===""?null:t}function ge(e,t){if(e===null||e===void 0||e==="")return null;if(typeof e==="number"){if(!Number.isFinite(e))throw new I(e,"expected a finite number");let a=st(Math.abs(e),t);return e<0?-a:a}if(typeof e!=="string")throw new I(e,"expected a decimal amount");let r=e.trim(),n=r.startsWith("-"),o=ee(n||r.startsWith("+")?r.slice(1):r,t);if(o===null)return null;return n?-o:o}function ze(e,t,r,n,o,a=0){let s;try{s=ge(e,t)}catch(i){if(!(i instanceof I))throw i;return o.push({externalId:n,message:`${r}: ${i.message}; recorded as ${a}`}),a}if(s===null)return a;if(s<0)return o.push({externalId:n,message:`${r} is negative (${String(e)}); recorded as ${a}`}),a;return s}function mo(e,t){if(t<=1)return e;return Math.floor((2*e+t)/(2*t))}function Ge(e){let t=typeof e==="string"?Number(e):e;return typeof t==="number"&&Number.isInteger(t)&&t>0?t:null}function ie(e){let t=typeof e==="string"?e.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(t)?t:null}var po={shopify:["SHOPIFY_ADMIN_TOKEN"],woocommerce:["WOOCOMMERCE_CONSUMER_KEY","WOOCOMMERCE_CONSUMER_SECRET"],shopware:["SHOPWARE_CLIENT_ID","SHOPWARE_CLIENT_SECRET"]},he={shopify:"Create a custom app for the store (Shopify admin > Settings > Apps > Develop apps, or the Shopify Dev Dashboard), give it the Admin API scopes read_customers and read_orders (plus read_all_orders for orders older than 60 days), install it, and copy its Admin API access token (shpat_...).",woocommerce:"Create a key in WordPress admin > WooCommerce > Settings > Advanced > REST API > Add key, with Read permission, for a user who can manage WooCommerce. The key starts with ck_ and the secret with cs_.",shopware:"Create an integration in the Shopware Administration > Settings > System > Integrations, with a role that can read customers and orders. Its access key id (SWIA...) is the client id and its secret access key is the client secret."};class it extends Error{constructor(e){super(e);this.name="MissingCredentialsError"}}function Qs(e,t){let r=e[t]?.trim();return r?r:void 0}function Ey(e,t){let r=e.trim().toLowerCase(),n=po[r];if(!n)throw new it(`Customers and orders can be imported from ${Object.keys(po).join(", ")}; got "${e}".`);let o=n.filter((s)=>!Qs(t,s));if(o.length>0){let s=o.length===1?`${o[0]} is not set`:`${o.join(" and ")} are not set`;throw new it(`Importing customers or orders from ${r} needs Admin API credentials in the environment: ${s}. They are read from env (or .env) only, never from a flag, so they stay out of shell history. ${he[r]}`)}let a=n.map((s)=>Qs(t,s));for(let[s,i]of a.entries())if(/\s/.test(i))throw new it(`${n[s]} contains whitespace; paste the credential exactly as issued. ${he[r]}`);if(r==="shopify")return{source:"shopify",accessToken:a[0]};if(r==="woocommerce")return{source:"woocommerce",consumerKey:a[0],consumerSecret:a[1]};if(/^SWSC/i.test(a[0]))throw new it(`SHOPWARE_CLIENT_ID looks like a sales channel access key (SWSC...), which only reads the public catalog. ${he.shopware}`);return{source:"shopware",clientId:a[0],clientSecret:a[1]}}function qe(e){switch(e.source){case"shopify":return[e.accessToken];case"woocommerce":return[e.consumerKey,e.consumerSecret];case"shopware":return[e.clientId,e.clientSecret]}}function Ve(e,t){let r=e;for(let n of t)if(n.length>=4)r=r.split(n).join("[redacted]");return r}var fo=5,Fy=2,Iy=60,Xs=(e)=>new Promise((t)=>setTimeout(t,e));class Tt extends T{constructor(e,t,r){super(e,t,r);this.name="AdminCredentialError"}}function Ys(e,t,r=""){let n=Ve(`${e.message}${r}`,t),o=e.body===void 0?void 0:Ve(e.body,t);return new T(Ve(e.url,t),n,e.status,o,e.retryAfter)}async function Be(e,t){let{fetch:r,secrets:n,credentialHelp:o,hint:a="",sleep:s,...i}=t,u=s??Xs;for(let c=0;;c++)try{return await fe(e,r,"",i)}catch(d){if(!(d instanceof T))throw d;if(d.status===429&&c<fo){let m=d.retryAfter!==void 0&&d.retryAfter>=0?d.retryAfter:Fy;await u(Math.min(m,Iy)*1000);continue}if(d.status===401||d.status===403){let m=d.status===401?"The credentials were rejected.":"The credentials were accepted but lack permission to read this.";throw new Tt(Ve(e,n),Ve(`${e} responded ${d.status}. ${m} ${o}`,n),d.status)}if(d.status===429)throw Ys(d,n,` Still rate limited after ${fo} retries; re-run later, the import resumes safely.`);throw Ys(d,n,a?` ${a}`:"")}}var ni="2026-10",ei=250,ti=4000,My=["id","email","first_name","last_name","phone","state","total_spent","currency","created_at","default_address"],Ny=["id","name","order_number","email","contact_email","created_at","processed_at","cancelled_at","currency","total_price","total_tax","total_discounts","total_shipping_price_set","shipping_lines","total_tip_received","financial_status","fulfillment_status","customer","billing_address","shipping_address","line_items","note"],Oy=`Check SHOPIFY_ADMIN_TOKEN, and that the app is installed on this store with the read_customers and read_orders scopes. ${he.shopify}`;function oi(e){let t=e?.id===void 0||e.id===null?"":String(e.id),r=[],n=oe(e?.email);if(!t||!n)return r.push({externalId:t||void 0,message:"skipped: the customer has no valid email address, which Stacks customers are keyed by"}),{record:null,warnings:r};let o=ie(e.currency),a=null;try{a=ge(e.total_spent,U(o))}catch(s){if(!(s instanceof I))throw s;r.push({externalId:t,message:`total_spent: ${s.message}; not imported`})}return{record:{source:"shopify",externalId:t,email:n,name:H(e.first_name,e.last_name)??H(e.default_address?.first_name,e.default_address?.last_name)??n,phone:ye(e.phone,e.default_address?.phone),active:null,totalSpentMinor:a!==null&&a>=0?a:null,currency:o,lastOrderAt:null,avatarUrl:null,createdAt:we(e.created_at)},warnings:r}}function ai(e){let t=(e.financial_status??"").toLowerCase(),r=(e.fulfillment_status??"").toLowerCase();if(t==="refunded")return{status:"REFUNDED",mapped:!0};if(e.cancelled_at||t==="voided"||r==="restocked")return{status:"CANCELLED",mapped:!0};if(r==="fulfilled")return{status:"SHIPPED",mapped:!0};if(r==="partial")return{status:"PROCESSING",mapped:!0};if(["paid","partially_paid","partially_refunded","authorized"].includes(t))return{status:"PROCESSING",mapped:!0};if(t==="pending"||t==="expired"||t==="")return{status:"PENDING",mapped:!0};return{status:"PENDING",mapped:!1}}function $y(e){if(!e)return null;return je(H(e.first_name,e.last_name)??e.name,e.address1,e.address2,e.city,[e.province_code??e.province,e.zip].map((t)=>J(t)).filter(Boolean).join(" "),e.country_code??e.country)}function si(e,t={}){let r=e?.id===void 0||e.id===null?"":String(e.id),n=[];if(!r)return n.push({message:"skipped: a Shopify order has no id"}),{record:null,warnings:n};let o=ie(e.currency)??ie(t.currency);if(!o)return n.push({externalId:r,message:"skipped: the order names no currency; pass --currency"}),{record:null,warnings:n};let a=U(o),s=(p,b)=>ze(p,a,b,r,n),i=e.total_shipping_price_set?.shop_money?.amount,u=i!==void 0&&i!==null?s(i,"shipping"):(e.shipping_lines??[]).reduce((p,b)=>p+s(b?.price,"shipping line"),0),c=[];for(let p of e.line_items??[]){let b=p?.id===void 0||p.id===null?"":String(p.id),h=Ge(p?.quantity),f=R(p?.name)??H(p?.title,p?.variant_title)??`Line ${b}`;if(!b||h===null){n.push({externalId:r,message:`line "${f}" has no id or quantity; left out`});continue}c.push({externalId:b,productExternalId:p.product_id===void 0||p.product_id===null?null:String(p.product_id),variantExternalId:p.variant_id===void 0||p.variant_id===null?null:String(p.variant_id),name:f,sku:R(p.sku),quantity:h,unitPriceMinor:s(p.price,`line "${f}" price`)})}let{status:d,mapped:m}=ai(e),l=[e.financial_status??"no payment status",e.fulfillment_status??"unfulfilled",e.cancelled_at?"cancelled":null].filter(Boolean).join(", ");if(!m)n.push({externalId:r,message:`Shopify status "${l}" has no Stacks equivalent; imported as ${d}`});let y=oe(e.customer?.email)??oe(e.email)??oe(e.contact_email),g=e.customer?.id===void 0||e.customer?.id===null?null:String(e.customer.id);return{record:{source:"shopify",externalId:r,number:R(e.name)??(e.order_number?`#${e.order_number}`:null),currency:o,status:d,sourceStatus:l,totalMinor:s(e.total_price,"total"),taxMinor:s(e.total_tax,"tax"),discountMinor:s(e.total_discounts,"discounts"),shippingMinor:u,tipMinor:s(e.total_tip_received,"tip"),customer:y||g?{externalId:g,email:y,name:H(e.customer?.first_name,e.customer?.last_name)??H(e.billing_address?.first_name,e.billing_address?.last_name),phone:ye(e.customer?.phone,e.billing_address?.phone)}:null,shippingAddress:$y(e.shipping_address),note:R(e.note),placedAt:we(e.processed_at)??we(e.created_at),lines:c},warnings:n}}function ii(e){if(!e)return null;for(let t of e.split(",")){let r=/<([^>]+)>\s*;\s*rel="?next"?/i.exec(t);if(!r)continue;try{return new URL(r[1]).searchParams.get("page_info")}catch{return null}}return null}function ui(e,t){let r=V(t??e);if(!r.startsWith("https://"))throw TypeError(`${r} is not HTTPS. The Shopify Admin API is HTTPS only, and the access token must never travel in plain text.`);return r}async function*ri(e,t,r){if(t.credentials.source!=="shopify")throw TypeError("The Shopify importer needs Shopify credentials (SHOPIFY_ADMIN_TOKEN).");let n=ui(e,t.adminUrl),o=t.fetch??fetch,a=t.limit,s=a&&a>0?Math.min(ei,a):ei,i=`${n}/admin/api/${ni}/${r.resource}.json`,u=r.fields.join(","),c={fetch:o,headers:{"X-Shopify-Access-Token":t.credentials.accessToken},secrets:qe(t.credentials),credentialHelp:Oy,hint:`Is ${n} the store's Admin API address? For a custom domain, pass --admin-url https://<store>.myshopify.com.`,sleep:t.sleep},d=new Set,m=0,l=`${i}?limit=${s}&fields=${u}${r.firstQuery}`;for(let y=1;y<=ti;y++){let{data:g,headers:p}=await Be(l,c),b=g?.[r.resource];if(!Array.isArray(b))throw new T(l,`${l} did not return a "${r.resource}" list. Is this the Shopify Admin API?`);let h=b,f=h.map((F)=>String(F?.id));if(y>1&&f.length>0&&f.every((F)=>d.has(F)))throw new T(l,`${l} repeated ${r.resource} from an earlier page; stopping rather than looping.`);f.forEach((F)=>d.add(F));let x=[],D=[];for(let F of h){if(a&&m>=a)break;let k=r.map(F);if(D.push(...k.warnings),k.record)x.push(k.record),m++}yield{url:l,items:x,warnings:D};let v=ii(p.get("link"));if(!v||h.length===0||a&&m>=a)return;l=`${i}?limit=${s}&fields=${u}&page_info=${encodeURIComponent(v)}`}throw new T(i,`Stopped after ${ti} pages of ${i} without reaching the end.`)}var wo={name:"shopify",customers:(e,t)=>ri(e,t,{resource:"customers",fields:My,firstQuery:"",map:oi}),orders:(e,t)=>ri(e,t,{resource:"orders",fields:Ny,firstQuery:"&status=any",map:(r)=>si(r,{currency:t.currency})})};import{slug as mi}from"@stacksjs/strings";var cr=100,dr=1000,lr="/store-api",yo="Is this a Shopware 6 store with the Store API reachable at /store-api?",go='Find it in the Shopware Administration under Sales Channels: open the storefront or headless sales channel and copy the key from its "API access" card. A headless storefront also ships it in its page source.';function mr(e,t){if(!e)return null;let r=e,n=r.translated;return(n&&typeof n==="object"&&!Array.isArray(n)?R(n[t]):null)??R(r[t])}function He(e){return mr(e,"name")?.replace(/\s+/g," ")??null}function ci(e){let t=typeof e.availableStock==="number"?e.availableStock:e.stock;return typeof t==="number"&&Number.isFinite(t)?Math.max(0,Math.trunc(t)):null}function di(e){return e.available!==!1&&e.active!==!1}function li(e,t,r,n,o){let a=U(n.currency),s=e.calculatedPrice?.unitPrice;if(s===null||s===void 0||s==="")return o.push({externalId:r,message:`${t} has no price in ${n.currency??"the sales channel currency"}; left unpriced`}),{priceMinor:null,compareAtMinor:null};try{let i=st(s,a),u=st(e.calculatedPrice?.listPrice?.price??null,a);return{priceMinor:i,compareAtMinor:u!==null&&i!==null&&u>i?u:null}}catch(i){if(!(i instanceof I))throw i;return o.push({externalId:r,message:`${t}: ${i.message}; left unpriced`}),{priceMinor:null,compareAtMinor:null}}}function By(e){let t=[...e.media??[]].sort((o,a)=>(o?.position??0)-(a?.position??0));if(e.cover)t.unshift(e.cover);let r=new Set,n=[];for(let o of t){let a=R(o?.media?.url);if(!a||r.has(a))continue;r.add(a);let s=o.media;n.push({src:a,alt:mr(s,"alt")??mr(s,"title")})}return n}function Uy(e){let t=new Set,r=[];for(let n of[e.seoCategory,...e.categories??[]]){let o=He(n),a=o?mi(o):"";if(!o||!a||t.has(a))continue;t.add(a),r.push({name:o,slug:a})}return r}function Jy(e){let t=new Map;for(let r of e)for(let n of r.options??[]){let o=He(n.group),a=R(n.groupId)??R(n.group?.id)??o;if(!a||!o||t.has(a))continue;t.set(a,{key:a,name:o,position:n.group?.position??0,order:t.size})}return[...t.values()].sort((r,n)=>r.position-n.position||r.order-n.order)}function Wy(e,t){return(e.options??[]).find((r)=>(R(r.groupId)??R(r.group?.id)??He(r.group))===t.key)}function pi(e,t){if(!R(e?.id))throw TypeError("Shopware product has no id");let r=e.id,n=[],o=He(e);if(!o)throw TypeError(`Shopware product ${r} has no name`);let a=t.children??[],s=typeof e.childCount==="number"?e.childCount:0,i=a.length>0,u,c=[];if(i){let d=Jy(a);c=d.map((l)=>l.name);let m=a.map((l)=>{let y=d.map((x)=>Wy(l,x)),g=y.map((x)=>He(x)??""),p=R(l.productNumber),b=`variant ${p??l.id}`,h=li(l,b,r,t,n);return{variant:{externalId:String(l.id),title:g.filter(Boolean).join(" / ")||He(l)||p||o,sku:p,priceMinor:h.priceMinor,compareAtMinor:h.compareAtMinor,available:di(l),inventory:ci(l),optionValues:g},sortKey:y.map((x)=>x?.position??0),productNumber:p??""}});m.sort((l,y)=>{for(let g=0;g<l.sortKey.length;g++){let p=(l.sortKey[g]??0)-(y.sortKey[g]??0);if(p!==0)return p}return l.productNumber.localeCompare(y.productNumber)}),u=m.map((l)=>l.variant)}else if(s>0)n.push({externalId:r,message:`"${o}" has ${s} variant${s===1?"":"s"} in Shopware, none visible to this sales channel; imported without a price`}),u=[];else{let d=li(e,`"${o}"`,r,t,n);u=[{externalId:r,title:o,sku:R(e.productNumber),priceMinor:d.priceMinor,compareAtMinor:d.compareAtMinor,available:di(e),inventory:ci(e),optionValues:[]}]}return{product:{source:"shopware",externalId:r,name:o,handle:mi(o),descriptionHtml:mr(e,"description"),vendor:He(e.manufacturer),categories:Uy(e),tags:(e.tags??[]).map((d)=>R(d?.name)).filter((d)=>d!==null),currency:t.currency,images:By(e),optionNames:c,variants:u,hasOptions:i,url:`${t.storeUrl}/detail/${r}`},warnings:n}}function fi(e){return V(e).replace(/\/store-api$/i,"")}function wi(){return`Shopware's Store API needs the sales channel access key: pass --access-key <key> or set SHOPWARE_ACCESS_KEY. It is public by design and not a secret. ${go}`}function Ly(e){if(!e)return null;try{let r=JSON.parse(e)?.errors?.[0];return R(r?.detail)??R(r?.title)}catch{return null}}function jy(e){let t=Ly(e.body),r=t?` Shopware said: "${t}"`:"";if(e.status===401||e.status===403||e.status===412)return new T(e.url,`${e.message}${r} The sales channel access key looks wrong: check --access-key or SHOPWARE_ACCESS_KEY. ${go}`,e.status,e.body);return new T(e.url,`${e.message}${r} ${yo}`,e.status,e.body)}async function ho(e,t,r,n){try{let{data:o}=await fe(e,r,"",{headers:{"sw-access-key":t},json:n});return o}catch(o){if(!(o instanceof T))throw o;throw jy(o)}}function zy(e){return e instanceof T&&(e.status===401||e.status===403||e.status===412)}async function yi(e,t,r=fetch){try{let n=await ho(`${e}${lr}/context`,t,r),o=typeof n?.currency?.isoCode==="string"?n.currency.isoCode.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(o)?o:null}catch(n){if(zy(n))throw n;return null}}var gi={product:["id","parentId","productNumber","name","description","translated","calculatedPrice","stock","availableStock","available","active","childCount","manufacturer","seoCategory","categories","tags","cover","media","options"],calculated_price:["unitPrice","quantity","listPrice"],cart_list_price:["price"],product_media:["position","media"],media:["url","alt","title","translated"],product_manufacturer:["name","translated"],category:["name","translated"],tag:["name"],property_group_option:["id","name","translated","position","groupId","group"],property_group:["id","name","translated","position"]};function hi(e,t){return{page:e,limit:t,"total-count-mode":"exact",filter:[{type:"equals",field:"parentId",value:null}],sort:[{field:"id",order:"ASC"}],associations:{cover:{},media:{associations:{media:{}}},manufacturer:{},categories:{},tags:{}},includes:gi}}function bi(e,t){return{page:t,limit:cr,"total-count-mode":"exact",filter:[{type:"equalsAny",field:"parentId",value:e}],sort:[{field:"id",order:"ASC"}],associations:{options:{associations:{group:{}}}},includes:gi}}function _i(e,t,r,n){if(n<r)return!0;let o=typeof e.total==="number"?e.total:Number.NaN;return Number.isInteger(o)&&t*r>=o}async function Gy(e,t,r,n){let o=new Map;if(r.length===0)return o;let a=`${e}${lr}/product`;for(let s=1;s<=dr;s++){let i=await ho(a,t,n,bi(r,s));if(!Array.isArray(i?.elements))throw new T(a,`${a} did not return a product list for the variants. ${yo}`);let u=i.elements;for(let c of u){let d=R(c?.parentId);if(!d)continue;let m=o.get(d)??[];m.push(c),o.set(d,m)}if(u.length===0||_i(i,s,cr,u.length))return o}throw new T(a,`Stopped after ${dr} pages of variants from ${a} without reaching the end.`)}async function*qy(e,t={}){let r=t.accessKey?.trim();if(!r)throw TypeError(wi());let n=fi(e),o=t.fetch??fetch,a=t.limit,s=a&&a>0?Math.min(cr,a):cr,i=`${n}${lr}/product`,u=[],c=t.currency?.trim().toUpperCase()||null,d=await yi(n,r,o),m=d??c;if(d&&c&&d!==c)u.push({message:`--currency ${c} ignored: this sales channel prices in ${d}, and the Store API does not convert.`});if(!m)u.push({message:`${n}${lr}/context did not report a currency; prices read as 2-decimal amounts. Pass --currency to be sure.`});let l=new Set,y=0;for(let g=1;g<=dr;g++){let p=`${i} (page ${g})`,b;try{b=await ho(i,r,o,hi(g,s))}catch(S){if(S instanceof T)throw new T(S.url,S.message.replace(S.url,p),S.status,S.body);throw S}if(!Array.isArray(b?.elements))throw new T(i,`${p} did not return a product list. ${yo}`);let h=b.elements;if(h.length===0)return;let f=h.map((S)=>String(S?.id));if(g>1&&f.every((S)=>l.has(S)))throw new T(i,`${p} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);f.forEach((S)=>l.add(S));let x=a?h.slice(0,Math.max(0,a-y)):h,D=g===1?u:[],v=x.filter((S)=>typeof S?.childCount==="number"&&S.childCount>0).map((S)=>String(S.id)),F=await Gy(n,r,v,o),k=[];for(let S of x)try{let C=pi(S,{storeUrl:n,currency:m,children:F.get(String(S?.id))});k.push(C.product),D.push(...C.warnings),y++}catch(C){D.push({externalId:S?.id===void 0?void 0:String(S.id),message:`skipped: ${C.message}`})}if(yield{url:p,products:k,warnings:D},a&&y>=a)return;if(_i(b,g,s,h.length))return}throw new T(i,`Stopped after ${dr} pages of ${i} without reaching the end.`)}var bo={name:"shopware",pages:qy};var xi=100,Ri=1e4,Vy=`Check SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET, and that the integration's role may read customers and orders. ${he.shopware}`,_o="Is this a Shopware 6 store with the Admin API reachable at /api?";function vi(e,t={}){let r=R(e?.id)??"",n=[],o=oe(e?.email);if(!r||!o)return n.push({externalId:r||void 0,message:"skipped: the customer has no valid email address, which Stacks customers are keyed by"}),{record:null,warnings:n};let a=ie(t.currency),s=null;try{s=ge(e.orderTotalAmount??null,U(a))}catch(i){if(!(i instanceof I))throw i;n.push({externalId:r,message:`orderTotalAmount: ${i.message}; not imported`})}return{record:{source:"shopware",externalId:r,email:o,name:H(e.firstName,e.lastName)??R(e.company)??o,phone:ye(e.defaultBillingAddress?.phoneNumber),active:typeof e.active==="boolean"?e.active:null,totalSpentMinor:s!==null&&s>=0?s:null,currency:a,lastOrderAt:we(e.lastOrderDate),avatarUrl:null,createdAt:we(e.createdAt)},warnings:n}}function xo(e){return(e?.stateMachineState?.technicalName??"").toLowerCase()}function Hy(e){let t=[...e.transactions??[]].sort((r,n)=>String(r?.createdAt??"").localeCompare(String(n?.createdAt??"")));return xo(t.at(-1))}function Di(e){let t=xo(e),r=xo(e.deliveries?.[0]),n=Hy(e),o=`order ${t||"unknown"}, delivery ${r||"unknown"}, payment ${n||"unknown"}`,a=(s,i=!0)=>({status:s,mapped:i,sourceStatus:o});if(n==="refunded")return a("REFUNDED");if(t==="cancelled")return a("CANCELLED");if(t==="completed")return a("DELIVERED");if(t==="open"||t==="in_progress"){if(r==="shipped")return a("SHIPPED");if(t==="in_progress"||r==="shipped_partially"||["paid","paid_partially","authorized"].includes(n))return a("PROCESSING");return a("PENDING")}return a("PENDING",!1)}function Ky(e){if(!e||!R(e.street))return null;return je(H(e.firstName,e.lastName),e.company,e.street,e.additionalAddressLine1,[e.zipcode,e.city].map((t)=>J(t)).filter(Boolean).join(" "),e.country?.iso??e.country?.name)}function Zy(e){return e.payload&&typeof e.payload==="object"&&!Array.isArray(e.payload)?e.payload:{}}function Si(e,t){let r=Array.isArray(t)?t.map((n)=>J(n?.option)).filter(Boolean):[];return r.length>0&&!r.every((n)=>e.includes(n))?`${e} - ${r.join(", ")}`:e}function ki(e,t={}){let r=R(e?.id)??"",n=[];if(!r)return n.push({message:"skipped: a Shopware order has no id"}),{record:null,warnings:n};let o=ie(e.currency?.isoCode)??ie(t.currency);if(!o)return n.push({externalId:r,message:"skipped: the order names no currency; pass --currency"}),{record:null,warnings:n};let a=U(o),s=(f,x)=>ze(f,a,x,r,n),i=[],u=0;for(let f of e.lineItems??[]){if(R(f?.parentId))continue;let x=R(f?.id)??"",D=J(f?.label)||`Line ${x}`,v=(f?.type??"").toLowerCase(),F=null;try{F=ge(f?.totalPrice??null,a)}catch(M){if(!(M instanceof I))throw M;n.push({externalId:r,message:`line "${D}": ${M.message}; left out`});continue}if(v==="promotion"||v==="credit"||F!==null&&F<0){u+=Math.abs(F??0);continue}let k=Ge(f?.quantity);if(!x||k===null){n.push({externalId:r,message:`line "${D}" has no id or quantity; left out`});continue}let S=v==="product"&&f.productId===null,C=v==="product"&&!S?R(f.productId)??R(f.referencedId):null,O=Zy(f);i.push({externalId:x,productExternalId:R(O.parentId)??C,variantExternalId:C,name:Si(D,O.options),sku:R(O.productNumber),quantity:k,unitPriceMinor:s(f.unitPrice,`line "${D}" unit price`)})}let c=s(e.amountTotal,"total"),d=e.amountNet===null||e.amountNet===void 0?c:s(e.amountNet,"net total"),{status:m,mapped:l,sourceStatus:y}=Di(e);if(!l)n.push({externalId:r,message:`Shopware state "${y}" has no Stacks equivalent; imported as ${m}`});let g=(e.addresses??[]).find((f)=>f?.id&&f.id===e.billingAddressId),p=e.deliveries?.[0]?.shippingOrderAddress??(e.addresses??[]).find((f)=>f?.id&&f.id!==e.billingAddressId)??null,b=oe(e.orderCustomer?.email),h=R(e.orderCustomer?.customerId);return{record:{source:"shopware",externalId:r,number:R(e.orderNumber),currency:o,status:m,sourceStatus:y,totalMinor:c,taxMinor:Math.max(0,c-d),discountMinor:u,shippingMinor:s(e.shippingTotal,"shipping"),tipMinor:0,customer:b||h?{externalId:h,email:b,name:H(e.orderCustomer?.firstName,e.orderCustomer?.lastName),phone:ye(g?.phoneNumber)}:null,shippingAddress:Ky(p),note:R(e.customerComment),placedAt:we(e.orderDateTime),lines:i},warnings:n}}function Ci(e,t){let r=V(t??e).replace(/\/(?:store-)?api$/i,""),{protocol:n,hostname:o}=new URL(r),a=o==="localhost"||o==="127.0.0.1"||o==="[::1]"||o.endsWith(".localhost");if(n!=="https:"&&!a)throw TypeError(`${r} is not HTTPS. The Shopware integration secret and bearer token must never travel in plain text.`);return r}function Ti(e,t){return{page:e,limit:t,"total-count-mode":1,sort:[{field:"id",order:"ASC"}],associations:{defaultBillingAddress:{}},includes:{customer:["id","customerNumber","email","firstName","lastName","company","active","guest","orderTotalAmount","lastOrderDate","createdAt","defaultBillingAddress"],customer_address:["phoneNumber"]}}}var Qy=["id","firstName","lastName","company","street","additionalAddressLine1","zipcode","city","phoneNumber","country"];function Ai(e,t){return{page:e,limit:t,"total-count-mode":1,sort:[{field:"id",order:"ASC"}],associations:{lineItems:{},addresses:{associations:{country:{}}},currency:{},stateMachineState:{},orderCustomer:{},deliveries:{associations:{stateMachineState:{},shippingOrderAddress:{associations:{country:{}}}}},transactions:{associations:{stateMachineState:{}}}},includes:{order:["id","orderNumber","orderDateTime","amountTotal","amountNet","shippingTotal","customerComment","billingAddressId","currency","stateMachineState","orderCustomer","lineItems","addresses","deliveries","transactions"],order_line_item:["id","parentId","productId","referencedId","label","quantity","unitPrice","totalPrice","type","payload"],order_customer:["customerId","email","firstName","lastName"],order_address:Qy,order_delivery:["shippingOrderAddress","stateMachineState"],order_transaction:["stateMachineState","createdAt"],currency:["isoCode"],country:["iso","name"],state_machine_state:["technicalName"]}}}async function Ro(e,t,r,n){let o=`${e}/api/oauth/token`,{data:a}=await Be(o,{...n,json:{grant_type:"client_credentials",client_id:t,client_secret:r}}),s=typeof a?.access_token==="string"?a.access_token.trim():"";if(!s)throw new T(o,`${o} returned no access_token. ${_o}`);return s}async function*Pi(e,t,r,n,o){if(t.credentials.source!=="shopware")throw TypeError("The Shopware importer needs Shopware credentials (SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET).");let a=Ci(e,t.adminUrl),{clientId:s,clientSecret:i}=t.credentials,u=qe(t.credentials),d={fetch:t.fetch??fetch,secrets:u,credentialHelp:Vy,hint:_o,sleep:t.sleep},m=await Ro(a,s,i,d),l=async(f,x)=>{let D=()=>Be(f,{...d,secrets:[...u,m],headers:{authorization:`Bearer ${m}`},json:x});try{return await D()}catch(v){if(!(v instanceof Tt)||v.status!==401)throw v;return m=await Ro(a,s,i,d),await D()}},y=`${a}/api/search/${r}`,g=t.limit,p=g&&g>0?Math.min(xi,g):xi,b=new Set,h=0;for(let f=1;f<=Ri;f++){let x=`${y} (page ${f})`,{data:D}=await l(y,n(f,p));if(!Array.isArray(D?.data))throw new T(y,`${x} did not return a "data" list. ${_o}`);let v=D.data;if(v.length===0)return;let F=v.map((O)=>String(O?.id));if(f>1&&F.every((O)=>b.has(O)))throw new T(y,`${x} repeated ${r}s from an earlier page; the store is not paginating.`);F.forEach((O)=>b.add(O));let k=[],S=[];for(let O of v){if(g&&h>=g)break;let M=o(O);if(S.push(...M.warnings),M.record)k.push(M.record),h++}if(yield{url:x,items:k,warnings:S},g&&h>=g)return;let C=typeof D.total==="number"?D.total:Number.NaN;if(v.length<p||Number.isInteger(C)&&f*p>=C)return}throw new T(y,`Stopped after ${Ri} pages of ${y} without reaching the end.`)}var Po={name:"shopware",customers:(e,t)=>Pi(e,t,"customer",Ti,(r)=>vi(r,{currency:t.currency})),orders:(e,t)=>Pi(e,t,"order",Ai,(r)=>ki(r,{currency:t.currency}))};import{slug as Ni}from"@stacksjs/strings";var Do=100,So=1000,ko="/wp-json/wc/store/v1/products",Ei="Is WooCommerce 6+ installed with the Store API reachable at /wp-json?";function Oi(e){let t=R(e?.currency_code)?.toUpperCase()??null,r=Number(e?.currency_minor_unit),n=Number.isInteger(r)&&r>=0?r:2,o=U(t),a=at(e?.price,n,o),s=at(e?.regular_price,n,o);return{currency:t,priceMinor:a,compareAtMinor:s!==null&&a!==null&&s>a?s:null}}function Fi(e,t,r){try{return Oi(e.prices)}catch(n){if(!(n instanceof I))throw n;return r.push({externalId:t,message:`${n.message}; left unpriced`}),{currency:R(e.prices?.currency_code)?.toUpperCase()??null,priceMinor:null,compareAtMinor:null}}}function vo(e){return(e??[]).map((t)=>{let r=J(t?.name);return{name:r,slug:R(t?.slug)??Ni(r)}}).filter((t)=>t.name&&t.slug)}function $i(e){let t=R(e);if(!t||!t.includes("%"))return t;try{return decodeURIComponent(t)}catch{return t}}function Ii(e){return typeof e.low_stock_remaining==="number"?Math.max(0,Math.trunc(e.low_stock_remaining)):null}function Mi(e){return e.is_in_stock!==!1&&e.is_purchasable!==!1}function Bi(e,t={}){if(e?.id===void 0||e.id===null||e.id==="")throw TypeError("WooCommerce product has no id");let r=String(e.id),n=[],o=J(e.name);if(!o)throw TypeError(`WooCommerce product ${r} has no name`);let a=Fi(e,r,n),s=e.type==="variable"&&(e.variations?.length??0)>0,i=s?(e.attributes??[]).filter((l)=>l.has_variations!==!1):[],u=i.map((l)=>J(l.name)).filter(Boolean),c,d=a.currency;if(s)c=(e.variations??[]).map((l)=>{let y=String(l.id),g=i.map((h)=>{let f=J(h.name).toLowerCase(),x=(h.taxonomy??"").toLowerCase(),D=(l.attributes??[]).find((k)=>{let S=J(k.name).toLowerCase();return S===f||x!==""&&S===x}),v=R(D?.value);if(!v)return"Any";let F=(h.terms??[]).find((k)=>k.slug===v);return F?J(F.name):J(v)}),p=t.variations?.get(y);if(!p)return n.push({externalId:r,message:`variation ${y} could not be fetched; imported without a price`}),{externalId:y,title:g.join(" / ")||o,sku:null,priceMinor:null,compareAtMinor:null,available:!1,inventory:null,optionValues:g};let b=Fi(p,y,n);return d??=b.currency,{externalId:y,title:g.join(" / ")||J(p.name)||o,sku:R(p.sku),priceMinor:b.priceMinor,compareAtMinor:b.compareAtMinor,available:Mi(p),inventory:Ii(p),optionValues:g}});else c=[{externalId:r,title:o,sku:R(e.sku),priceMinor:a.priceMinor,compareAtMinor:a.compareAtMinor,available:Mi(e),inventory:Ii(e),optionValues:[]}];let m=vo(e.brands)[0];return{product:{source:"woocommerce",externalId:r,name:o,handle:$i(e.slug)??Ni(o),descriptionHtml:R(e.description)??R(e.short_description),vendor:m?m.name:null,categories:vo(e.categories),tags:vo(e.tags).map((l)=>l.name),currency:d,images:(e.images??[]).filter((l)=>R(l?.src)).map((l)=>({src:R(l.src),alt:R(l.alt)})),optionNames:s?u:[],variants:c,hasOptions:s,url:R(e.permalink)},warnings:n}}async function Ui(e,t){let{data:r,headers:n}=await fe(e,t,Ei);if(!Array.isArray(r))throw new T(e,`${e} did not return a product list. ${Ei}`);let o=n.get("x-wp-totalpages")?.trim(),a=o?Number(o):Number.NaN;return{url:e,items:r,totalPages:Number.isInteger(a)&&a>=0?a:null}}async function Yy(e,t,r){let n=new Map;if(t.length===0)return n;for(let o=1;o<=So;o++){let a=`${e}${ko}?type=variation&parent=${t.join(",")}&per_page=${Do}&page=${o}`,s=await Ui(a,r);for(let i of s.items)n.set(String(i.id),i);if(s.items.length===0||s.totalPages!==null&&o>=s.totalPages)break}return n}async function*Xy(e,t={}){let r=V(e),n=t.fetch??fetch,o=t.limit,a=o&&o>0?Math.min(Do,o):Do,s=new Set,i=0;for(let u=1;u<=So;u++){let c=`${r}${ko}?per_page=${a}&page=${u}`,d=await Ui(c,n);if(d.items.length===0)return;let m=d.items.map((h)=>String(h?.id));if(u>1&&m.every((h)=>s.has(h)))throw new T(c,`${c} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);m.forEach((h)=>s.add(h));let l=o?d.items.slice(0,Math.max(0,o-i)):d.items,y=[],g=l.filter((h)=>h?.type==="variable"&&(h.variations?.length??0)>0).map((h)=>String(h.id)),p=new Map;try{p=await Yy(r,g,n)}catch(h){if(!(h instanceof T))throw h;y.push({message:`variations could not be fetched (${h.message}); variable products are imported without variant prices`})}let b=[];for(let h of l)try{let f=Bi(h,{variations:p});b.push(f.product),y.push(...f.warnings),i++}catch(f){y.push({externalId:h?.id===void 0?void 0:String(h.id),message:`skipped: ${f.message}`})}if(yield{url:c,products:b,warnings:y},o&&i>=o)return;if(d.totalPages!==null&&u>=d.totalPages)return}throw new T(r,`Stopped after ${So} pages of ${r}${ko} without reaching the end.`)}var Co={name:"woocommerce",pages:Xy};var Ji=100,Wi=1e4,To="/wp-json/wc/v3",eg=`Check WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET, and that the key has Read permission. If the key is right and every request is a 401, the web server may be stripping the Authorization header (common with Apache and CGI PHP). ${he.woocommerce}`,Li="Is WooCommerce installed with the REST API reachable at /wp-json/wc/v3, and pretty permalinks enabled?",tg={pending:"PENDING","on-hold":"PENDING",processing:"PROCESSING",completed:"DELIVERED",cancelled:"CANCELLED",failed:"CANCELLED",refunded:"REFUNDED"},rg=new Set(["checkout-draft","auto-draft","trash"]);function zi(e){let t=tg[(e??"").toLowerCase()];return t?{status:t,mapped:!0}:{status:"PENDING",mapped:!1}}function ng(e){let t=R(e);if(!t)return null;try{return new URL(t).protocol==="https:"?t:null}catch{return null}}function Gi(e){let t=e?.id===void 0||e.id===null?"":String(e.id),r=[],n=oe(e?.email)??oe(e?.billing?.email);if(!t||!n)return r.push({externalId:t||void 0,message:"skipped: the customer has no valid email address, which Stacks customers are keyed by"}),{record:null,warnings:r};return{record:{source:"woocommerce",externalId:t,email:n,name:H(e.first_name,e.last_name)??H(e.billing?.first_name,e.billing?.last_name)??n,phone:ye(e.billing?.phone,e.shipping?.phone),active:null,totalSpentMinor:null,currency:null,lastOrderAt:null,avatarUrl:ng(e.avatar_url),createdAt:ur(e.date_created_gmt)},warnings:r}}function og(e){if(!e||!R(e.address_1))return null;return je(H(e.first_name,e.last_name),e.company,e.address_1,e.address_2,e.city,[e.state,e.postcode].map((t)=>J(t)).filter(Boolean).join(" "),e.country)}function qi(e,t={}){let r=e?.id===void 0||e.id===null?"":String(e.id),n=[];if(!r)return n.push({message:"skipped: a WooCommerce order has no id"}),{record:null,warnings:n};let o=(e.status??"").toLowerCase();if(rg.has(o))return n.push({externalId:r,message:`skipped: status "${o}" is not a placed order`}),{record:null,warnings:n};let a=ie(e.currency)??ie(t.currency);if(!a)return n.push({externalId:r,message:"skipped: the order names no currency; pass --currency"}),{record:null,warnings:n};let s=U(a),i=(p,b)=>ze(p,s,b,r,n),u=[];for(let p of e.line_items??[]){let b=p?.id===void 0||p.id===null?"":String(p.id),h=Ge(p?.quantity),f=J(p?.name)||`Line ${b}`;if(!b||h===null){n.push({externalId:r,message:`line "${f}" has no id or quantity; left out`});continue}let x=i(p.subtotal??p.total,`line "${f}" subtotal`);u.push({externalId:b,productExternalId:p.product_id?String(p.product_id):null,variantExternalId:p.variation_id?String(p.variation_id):null,name:f,sku:R(p.sku),quantity:h,unitPriceMinor:mo(x,h)})}let c=0;for(let p of e.fee_lines??[]){let b=J(p?.name)||"Fee",h=null;try{h=ge(p?.total,s)}catch(f){if(!(f instanceof I))throw f;n.push({externalId:r,message:`fee "${b}": ${f.message}; left out`})}if(h===null||h===0)continue;if(h<0){c+=-h;continue}u.push({externalId:`fee-${p?.id??u.length}`,productExternalId:null,variantExternalId:null,name:b,sku:null,quantity:1,unitPriceMinor:h})}let{status:d,mapped:m}=zi(o);if(!m)n.push({externalId:r,message:`WooCommerce status "${o||"none"}" has no Stacks equivalent; imported as ${d}`});let l=e.customer_id?String(e.customer_id):null,y=oe(e.billing?.email),g=0;for(let p of e.refunds??[])try{g+=Math.abs(ge(p?.total,s)??0)}catch(b){if(!(b instanceof I))throw b;n.push({externalId:r,message:`refund ${p?.id??""}: ${b.message}; not counted`})}return{record:{source:"woocommerce",externalId:r,number:R(e.number)?`#${R(e.number)}`:null,currency:a,status:d,sourceStatus:o||"none",totalMinor:i(e.total,"total"),taxMinor:i(e.total_tax,"tax"),discountMinor:i(e.discount_total,"discounts")+c,shippingMinor:i(e.shipping_total,"shipping"),tipMinor:0,customer:y||l?{externalId:l,email:y,name:H(e.billing?.first_name,e.billing?.last_name),phone:ye(e.billing?.phone)}:null,shippingAddress:og(e.shipping),note:R(e.customer_note),placedAt:ur(e.date_created_gmt),lines:u,refundedMinor:g},warnings:n}}function Vi(e,t){let r=V(t??e);if(!r.startsWith("https://"))throw TypeError(`${r} is not HTTPS. WooCommerce REST API keys are sent with HTTP Basic auth, which is only safe (and only accepted by WooCommerce) over HTTPS. Use the store's https:// address.`);return r}function Hi(e,t){return`Basic ${Buffer.from(`${e}:${t}`,"utf8").toString("base64")}`}async function*ji(e,t,r,n){if(t.credentials.source!=="woocommerce")throw TypeError("The WooCommerce importer needs WooCommerce credentials (WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET).");let o=Vi(e,t.adminUrl),{consumerKey:a,consumerSecret:s}=t.credentials,i=Hi(a,s),u={fetch:t.fetch??fetch,headers:{authorization:i},secrets:[...qe(t.credentials),i.slice(6)],credentialHelp:eg,hint:Li,sleep:t.sleep},c=t.limit,d=c&&c>0?Math.min(Ji,c):Ji,m=new Set,l=0;for(let y=1;y<=Wi;y++){let g=`${o}${To}/${r}?per_page=${d}&page=${y}&orderby=id&order=asc`,{data:p,headers:b}=await Be(g,u);if(!Array.isArray(p))throw new T(g,`${g} did not return a list of ${r}. ${Li}`);let h=p;if(h.length===0)return;let f=h.map((k)=>String(k?.id));if(y>1&&f.every((k)=>m.has(k)))throw new T(g,`${g} repeated ${r} from an earlier page; the store is not paginating.`);f.forEach((k)=>m.add(k));let x=[],D=[];for(let k of h){if(c&&l>=c)break;let S=n(k);if(D.push(...S.warnings),S.record)x.push(S.record),l++}yield{url:g,items:x,warnings:D};let v=b.get("x-wp-totalpages")?.trim(),F=v?Number(v):Number.NaN;if(c&&l>=c)return;if(Number.isInteger(F)&&y>=F)return}throw new T(`${o}${To}/${r}`,`Stopped after ${Wi} pages of ${o}${To}/${r} without reaching the end.`)}var Ao={name:"woocommerce",customers:(e,t)=>ji(e,t,"customers",Gi),orders:(e,t)=>ji(e,t,"orders",(r)=>qi(r,{currency:t.currency}))};import{db as Io,sqlHelpers as tu}from"@stacksjs/database/runtime";import{env as ru}from"@stacksjs/env";import{formatDate as No}from"@stacksjs/orm";import{db as ag}from"@stacksjs/database/runtime";import{HttpError as Qi}from"@stacksjs/error-handling";import{isUniqueViolation as sg}from"@stacksjs/orm";function ve(e){if(typeof e==="bigint")return Eo(e);if(typeof e==="number")return Eo(e);if(!e||typeof e!=="object")return;if(Array.isArray(e)){for(let r of e){let n=ve(r);if(n!==void 0)return n}return}let t=e;for(let r of["lastInsertRowid","insertId","lastInsertId"]){let n=t[r];if(n===void 0||n===null)continue;let o=Eo(n);if(o!==void 0)return o}return}function Eo(e){let t=typeof e==="bigint"?Number(e):Number(e);if(!Number.isSafeInteger(t)||t<=0)return;return t}import{db as Ki}from"@stacksjs/database/runtime";async function pr(e){let t=await Ki.selectFrom("customers").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Zi(){return P(await Ki.selectFrom("customers").selectAll().execute())}var Fo="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60";async function Yi(e){try{let t={...e,avatar:e.avatar??Fo},r=await ag.insertInto("customers").values(t).executeTakeFirst();if(!r)throw Error("Failed to create customer");let n=ve(r);if(n===void 0)throw Error("Failed to create customer: the database reported no insert id");return await pr(n)}catch(t){if(t instanceof Qi)throw t;if(sg(t))throw new Qi(409,"A customer with this email already exists");if(t instanceof Error)throw Error(`Failed to create customer: ${t.message}`);throw t}}import{createHash as ig}from"crypto";var Xi="5d0c8a3e-6f1b-4c2a-9e47-b18f3d2a6c90";function eu(e,t=Xi){let r=t.replace(/-/g,"");if(!/^[0-9a-f]{32}$/i.test(r))throw TypeError(`Invalid namespace UUID "${t}"`);let n=ig("sha1").update(Buffer.from(r,"hex")).update(e,"utf8").digest().subarray(0,16);n[6]=n[6]&15|80,n[8]=n[8]&63|128;let o=n.toString("hex");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function te(e,t,r,n){return eu(`${e}:${t.toLowerCase()}:${r}:${n}`)}var ug=255;function Ke(e,t,r,n){return te(e,t,"customer",r??`email:${n}`)}function Oo(e,t,r,n,o){if(!n)return null;if(r!==null&&r!==Ke(e,t,null,o))return null;return Ke(e,t,n,o)}function At(e){return e?No(new Date(e)):null}function fr(e,t,r,n){let o={name:e.name.slice(0,ug),updated_at:r};if(n==="create")return o.uuid=t,o.email=e.email,o.phone=e.phone,o.total_spent=e.totalSpentMinor??0,o.last_order=At(e.lastOrderAt),o.status=e.active===!1?"Inactive":"Active",o.avatar=e.avatarUrl??Fo,o.created_at=At(e.createdAt)??r,o;if(e.phone!==null)o.phone=e.phone;if(e.totalSpentMinor!==null)o.total_spent=e.totalSpentMinor;if(e.lastOrderAt!==null)o.last_order=At(e.lastOrderAt);if(e.active!==null)o.status=e.active?"Active":"Inactive";return o}function Mo(e){return e.sku?`${e.name} (SKU ${e.sku})`:e.name}function nu(e,t,r,n){let o={uuid:te(e.source,t,"order",e.externalId),status:e.status,total_amount:e.totalMinor,currency:e.currency,tax_amount:e.taxMinor,discount_amount:e.discountMinor,delivery_fee:e.shippingMinor,tip_amount:e.tipMinor,order_type:e.shippingAddress?"DELIVERY":"TAKEOUT",delivery_address:e.shippingAddress,special_instructions:e.note,created_at:At(e.placedAt)??n,updated_at:n};if(r!==null)o.customer_id=r;return o}class $o{byUuid=new Map;byEmail=new Map;uuidById=new Map;async load(e,t){let r=[...new Set(t.map((o)=>o.uuid).filter((o)=>o!==null&&!this.byUuid.has(o)))],n=[...new Set(t.map((o)=>o.email).filter((o)=>o!==null&&!this.byEmail.has(o)))];if(r.length===0&&n.length===0)return;for(let o of await e.findCustomers({uuids:r,emails:n}))this.remember(o.id,o.uuid,o.email)}remember(e,t,r){if(t){let n=this.uuidById.get(e);if(n&&n!==t)this.byUuid.delete(n);this.byUuid.set(t,e),this.uuidById.set(e,t)}if(r)this.byEmail.set(r.trim().toLowerCase(),e)}find(e,t){let r=e?this.byUuid.get(e):void 0;if(r!==void 0)return{id:r,matchedBy:"uuid"};let n=t?this.byEmail.get(t):void 0;return n!==void 0?{id:n,matchedBy:"email"}:null}uuidOf(e){return this.uuidById.get(e)??null}emailTakenByOther(e,t){let r=this.byEmail.get(e);return r!==void 0&&r!==t}}function ou(e){let t=V(e.storeUrl);return{storeUrl:t,host:Ct(t),clock:e.now??(()=>new Date),fetchOptions:{credentials:e.credentials,limit:e.limit,fetch:e.fetch,currency:e.currency,adminUrl:e.adminUrl,sleep:e.sleep}}}async function cg(e){let{storeUrl:t,host:r,clock:n,fetchOptions:o}=ou(e),{adapter:a,repository:s}=e,i=new $o,u=new Set,c={source:a.name,storeUrl:t,dryRun:e.dryRun===!0,pages:[],customers:[],counts:{customers:{created:0,updated:0},merged:0},warnings:[]};async function d(m,l){let y=No(n()),g=Ke(m.source,r,m.externalId,m.email),p=i.find(g,m.email);if(!p){let f=await l.createCustomer(fr(m,g,y,"create"));return i.remember(f,g,m.email),{action:"create",externalId:m.externalId,email:m.email,name:m.name,matchedBy:null}}let b=fr(m,g,y,"update");if(p.matchedBy==="uuid")if(i.emailTakenByOther(m.email,p.id))c.warnings.push({externalId:m.externalId??void 0,message:`email changed to ${m.email}, which another customer already has; kept the old address`});else b.email=m.email;let h=p.matchedBy==="email"?Oo(m.source,r,i.uuidOf(p.id),m.externalId,m.email):null;if(h)b.uuid=h;return await l.updateCustomer(p.id,b),i.remember(p.id,h,m.email),{action:"update",externalId:m.externalId,email:m.email,name:m.name,matchedBy:p.matchedBy}}for await(let m of a.customers(t,o)){c.pages.push(m.url),c.warnings.push(...m.warnings);let l=[];for(let y of m.items){if(u.has(y.email)){c.counts.merged++;continue}u.add(y.email),l.push(y)}await i.load(s,l.map((y)=>({uuid:Ke(y.source,r,y.externalId,y.email),email:y.email})));for(let y of l){let g=await d(y,s);c.counts.customers[g.action==="create"?"created":"updated"]++,c.customers.push(g),e.onCustomer?.(g)}}if(c.counts.merged>0)c.warnings.push({message:`${c.counts.merged} source customer${c.counts.merged===1?"":"s"} shared an email with another and ${c.counts.merged===1?"was":"were"} merged into one Stacks customer`});return c}async function dg(e){let{storeUrl:t,host:r,clock:n,fetchOptions:o}=ou(e),{adapter:a,repository:s}=e,i=new $o,u=new Set,c=new Set,d=new Set,m=[],l={source:a.name,storeUrl:t,dryRun:e.dryRun===!0,pages:[],orders:[],counts:{orders:{created:0,updated:0},customers:{created:0,updated:0},lines:{linked:0,unlinked:0,productless:0},duplicates:0,partlyRefunded:0},currencies:[],warnings:[]},y=(f,x)=>te(f.source,r,"product",x),g=(f,x)=>te(f.source,r,"variant",x);function p(f){let x=f.customer;if(x?.externalId)return Ke(f.source,r,x.externalId,x.email??"");return x?.email?Ke(f.source,r,null,x.email):null}async function b(f,x,D){let v=f.customer;if(!v)return null;let F=p(f),k=i.find(F,v.email);if(k){let C=k.matchedBy==="email"&&v.email?Oo(f.source,r,i.uuidOf(k.id),v.externalId,v.email):null;if(C)await x.updateCustomer(k.id,{uuid:C,updated_at:D}),i.remember(k.id,C,v.email);return k.id}if(!v.email)return l.warnings.push({externalId:f.externalId,message:`order ${f.number??f.externalId} has no customer email; imported without a customer`}),null;let S=await x.createCustomer(fr({source:f.source,externalId:v.externalId,email:v.email,name:v.name??v.email,phone:v.phone,active:null,totalSpentMinor:null,currency:null,lastOrderAt:f.placedAt,avatarUrl:null,createdAt:f.placedAt},F,D,"create"));return i.remember(S,F,v.email),l.counts.customers.created++,S}async function h(f,x,D){let v=No(n()),F=await b(f,x,v),k=nu(f,r,F,v),S=D.orders.get(k.uuid),C;if(S===void 0)C=await x.createOrder(k);else{C=S;let q={...k};delete q.uuid,await x.updateOrder(C,q)}let O=0,M=0,re=f.lines.map((q)=>{let _t=(q.productExternalId?D.products.get(y(f,q.productExternalId)):void 0)??(q.variantExternalId?D.variants.get(g(f,q.variantExternalId)):void 0)??null;if(_t===null){if(!q.productExternalId&&!q.variantExternalId)M++;else if(O++,d.size<5)d.add(Mo(q))}return{order_id:C,product_id:_t,quantity:q.quantity,price:q.unitPriceMinor,special_instructions:Mo(q),created_at:v,updated_at:v}});return await x.replaceOrderItems(C,re),{action:S===void 0?"create":"update",externalId:f.externalId,number:f.number,status:f.status,sourceStatus:f.sourceStatus,totalMinor:f.totalMinor,currency:f.currency,lines:re.length,unlinkedLines:O,productlessLines:M,refundedMinor:f.refundedMinor??0,customerEmail:f.customer?.email??null,customerId:F}}for await(let f of a.orders(t,o)){l.pages.push(f.url),l.warnings.push(...f.warnings);let x=f.items.filter((C)=>{if(!u.has(C.externalId))return u.add(C.externalId),!0;return l.counts.duplicates++,!1}),D=x.map((C)=>te(C.source,r,"order",C.externalId)),v=[...new Set(x.flatMap((C)=>C.lines.flatMap((O)=>O.productExternalId?[y(C,O.productExternalId)]:[])))],F=[...new Set(x.flatMap((C)=>C.lines.flatMap((O)=>O.variantExternalId?[g(C,O.variantExternalId)]:[])))],k={orders:D.length>0?await s.findOrders(D):new Map,products:v.length>0?await s.findProducts(v):new Map,variants:F.length>0?await s.findVariantProducts(F):new Map};await i.load(s,x.map((C)=>({uuid:p(C),email:C.customer?.email??null})));let S=new Map;for(let C of x){c.add(C.currency);let{customerId:O,...M}=s.transaction?await s.transaction((q)=>h(C,q,k)):await h(C,s,k);if(l.counts.orders[M.action==="create"?"created":"updated"]++,l.counts.lines.linked+=M.lines-M.unlinkedLines-M.productlessLines,l.counts.lines.unlinked+=M.unlinkedLines,l.counts.lines.productless+=M.productlessLines,M.refundedMinor>0&&M.status!=="REFUNDED"){if(l.counts.partlyRefunded++,m.length<3)m.push(`${M.number??M.externalId}: ${ne(M.refundedMinor,M.currency)} of ${ne(M.totalMinor,M.currency)}`)}let re=At(C.placedAt);if(O!==null&&re&&re>(S.get(O)??""))S.set(O,re);l.orders.push(M),e.onOrder?.(M)}if(s.advanceLastOrder)for(let[C,O]of S)await s.advanceLastOrder(C,O)}if(l.currencies=[...c].sort(),l.counts.lines.unlinked>0){let f=[...d].map((D)=>`"${D}"`).join(", "),x=l.counts.lines.unlinked===1;l.warnings.push({message:`${l.counts.lines.unlinked} order line${x?" references a product":"s reference products"} not in Stacks (e.g. ${f}); kept with ${x?"its":"their"} label and price but no product link. Import the catalog (buddy commerce:import <url> --from ${a.name}), then re-run the order import to link ${x?"it":"them"}.`})}if(l.counts.partlyRefunded>0){let f=l.counts.partlyRefunded===1;l.warnings.push({message:`${l.counts.partlyRefunded} order${f?" was":"s were"} partly refunded at the source (${m.join("; ")}${f?"":", ..."}). Stacks orders have no refund column, so total_amount is what was charged.`})}return l}function au(e=Io){async function t(o,a){let s=await e.selectFrom(o).where("uuid","=",a).select("id").executeTakeFirst();if(!s)throw Error(`Inserted a row into ${o} but could not read it back (uuid ${a})`);return Number(s.id)}async function r(o,a){let s=[];for(let i=0;i<o.length;i+=500)s.push(...await a(o.slice(i,i+500)));return s}let n={async findCustomers({uuids:o,emails:a}){let s=await r(o,(c)=>e.selectFrom("customers").where("uuid","in",c).select(["id","uuid","email"]).execute()),i=tu(ru.DB_CONNECTION||"sqlite").param,u=await r(a.map((c)=>c.trim().toLowerCase()),async(c)=>{let d=c.map((l,y)=>i(y+1)).join(", "),m=await e.unsafe(`SELECT id, uuid, email FROM customers WHERE LOWER(email) IN (${d})`,c);return Array.isArray(m)?m:[]});return[...s,...u].map((c)=>({id:Number(c.id),uuid:c.uuid??null,email:String(c.email)}))},async createCustomer(o){return await e.insertInto("customers").values(o).execute(),t("customers",o.uuid)},async updateCustomer(o,a){await e.updateTable("customers").set(a).where("id","=",o).execute()},async advanceLastOrder(o,a){let s=tu(ru.DB_CONNECTION||"sqlite").param;await e.unsafe(`UPDATE customers SET last_order = ${s(1)} WHERE id = ${s(2)} AND (last_order IS NULL OR last_order < ${s(3)})`,[a,o,a])},async findOrders(o){let a=await r(o,(s)=>e.selectFrom("orders").where("uuid","in",s).select(["id","uuid"]).execute());return new Map(a.map((s)=>[String(s.uuid),Number(s.id)]))},async createOrder(o){return await e.insertInto("orders").values(o).execute(),t("orders",o.uuid)},async updateOrder(o,a){await e.updateTable("orders").set(a).where("id","=",o).execute()},async replaceOrderItems(o,a){if(await e.deleteFrom("order_items").where("order_id","=",o).execute(),a.length>0)await e.insertInto("order_items").values(a).execute()},async findProducts(o){let a=await r(o,(s)=>e.selectFrom("products").where("uuid","in",s).select(["id","uuid"]).execute());return new Map(a.map((s)=>[String(s.uuid),Number(s.id)]))},async findVariantProducts(o){let a=await r(o,(s)=>e.selectFrom("product_variants").where("uuid","in",s).select(["uuid","product_id"]).execute());return new Map(a.filter((s)=>s.product_id!==null&&s.product_id!==void 0).map((s)=>[String(s.uuid),Number(s.product_id)]))}};if(e===Io)n.transaction=(o)=>Io.transaction((a)=>o(au(a)));return n}function lg(e={tables:{}}){let t=e.tables;for(let a of["customers","orders","order_items","products","product_variants"])t[a]??=[];function r(a,s){let i=t[a],u=i.reduce((c,d)=>Math.max(c,Number(d.id)),0)+1;return i.push({id:u,...s}),u}function n(a,s,i){let u=t[a].find((c)=>c.id===s);if(u)Object.assign(u,i)}let o=(a,s)=>new Map(t[a].filter((i)=>s.includes(i.uuid)).map((i)=>[i.uuid,i.id]));return{tables:t,findCustomers:async({uuids:a,emails:s})=>t.customers.filter((i)=>a.includes(i.uuid)||s.includes(String(i.email).trim().toLowerCase())).map((i)=>({id:i.id,uuid:i.uuid??null,email:i.email})),createCustomer:async(a)=>{if(t.customers.some((s)=>s.email===a.email))throw Error(`UNIQUE constraint failed: customers.email (${a.email})`);return r("customers",a)},updateCustomer:async(a,s)=>n("customers",a,s),advanceLastOrder:async(a,s)=>{let i=t.customers.find((u)=>u.id===a);if(i&&(i.last_order===null||i.last_order===void 0||String(i.last_order)<s))i.last_order=s},findOrders:async(a)=>o("orders",a),createOrder:async(a)=>r("orders",a),updateOrder:async(a,s)=>n("orders",a,s),replaceOrderItems:async(a,s)=>{t.order_items=t.order_items.filter((i)=>i.order_id!==a);for(let i of s)r("order_items",i)},findProducts:async(a)=>o("products",a),findVariantProducts:async(a)=>new Map(t.product_variants.filter((s)=>a.includes(s.uuid)).map((s)=>[s.uuid,s.product_id]))}}function mg(e){let t=-1,r=async()=>t--,n=[];return{async findCustomers(o){let a=await e.findCustomers(o),s=n.filter((i)=>i.uuid!==null&&o.uuids.includes(i.uuid)||o.emails.includes(i.email));return[...a,...s]},findOrders:e.findOrders,findProducts:e.findProducts,findVariantProducts:e.findVariantProducts,async createCustomer(o){let a=t--;return n.push({id:a,uuid:o.uuid??null,email:String(o.email??"").toLowerCase()}),a},createOrder:r,updateCustomer:async()=>{},advanceLastOrder:async()=>{},updateOrder:async()=>{},replaceOrderItems:async()=>{}}}var{randomUUIDv7:su}=globalThis.Bun;import{db as Bo}from"@stacksjs/database/runtime";import{formatDate as pg}from"@stacksjs/orm";var uu="Unknown",fg=1,wg=50,Uo=100;function Lo(e){let t=e.map((r)=>r.priceMinor).filter((r)=>r!==null);return t.length>0?Math.min(...t):null}function cu(e){if(e.length===0||e.some((t)=>t.inventory===null))return null;return e.reduce((t,r)=>t+(r.inventory??0),0)}function du(e){let t=new Map,r=[],n=new Set;for(let o of e.variants){let a=o.sku;if(a===null)t.set(o.externalId,null);else if(a.length>Uo)t.set(o.externalId,null),r.push({externalId:e.externalId,message:`"${e.name}" variant "${o.title}" has a SKU longer than ${Uo} characters; imported without it`});else if(n.has(a))t.set(o.externalId,null),r.push({externalId:e.externalId,message:`"${e.name}" variant "${o.title}" repeats SKU ${a}; imported without it`});else n.add(a),t.set(o.externalId,a)}return{skus:t,warnings:r}}function Jo(e,t,r,n,o){let a=cu(e.variants),s={uuid:te(e.source,t,"product",e.externalId),name:e.name,description:e.descriptionHtml,price:Lo(e.variants)??0,image_url:e.images[0]?.src??null,is_available:e.variants.some((i)=>i.available),updated_at:n};if(o==="create")s.inventory_count=a??0,s.preparation_time=fg,s.category_id=r.categoryId,s.manufacturer_id=r.manufacturerId,s.created_at=n;else{if(a!==null)s.inventory_count=a;if(r.categoryId!==null)s.category_id=r.categoryId;if(r.manufacturerId!==null)s.manufacturer_id=r.manufacturerId}return s}function Wo(e,t,r,n,o,a,s=t.sku){let i={uuid:te(e.source,r,"variant",t.externalId),product_id:n,variant:t.title,type:(e.optionNames.join(" / ")||"Option").slice(0,wg),options:JSON.stringify(t.optionValues),status:t.available?"active":"inactive",price:t.priceMinor,compare_at_price:t.compareAtMinor,updated_at:o};if(a==="create")i.sku=s,i.inventory_count=t.inventory,i.created_at=o;else{if(s!==null)i.sku=s;if(t.inventory!==null)i.inventory_count=t.inventory}return i}function iu(e){let t={...e};return delete t.uuid,t}async function yg(e){let t=V(e.storeUrl),r=Ct(t),n=e.now??(()=>new Date),{adapter:o,repository:a}=e,s={source:o.name,storeUrl:t,dryRun:e.dryRun===!0,pages:[],products:[],counts:{products:{created:0,updated:0},variants:{created:0,updated:0},categories:{created:0,updated:0},manufacturers:{created:0,updated:0},duplicates:0},currencies:[],warnings:[]},i=new Map,u=new Map,c=new Map,d=new Set;async function m(p,b,h){let f=p.categories[0];if(!f)return null;let x=i.get(f.slug);if(x!==void 0)return x;let D=await b.findCategory(f.slug,f.name);if(D===void 0)D=await b.createCategory({uuid:su(),name:f.name,slug:f.slug,description:null,image_url:null,is_active:!0,parent_category_id:null,display_order:i.size,created_at:h,updated_at:h}),s.counts.categories.created++;return i.set(f.slug,D),D}async function l(p,b,h){if(!p.vendor)return null;let f=u.get(p.vendor);if(f!==void 0)return f;let x=await b.findManufacturer(p.vendor);if(x===void 0)x=await b.createManufacturer({uuid:su(),manufacturer:p.vendor,description:null,country:uu,featured:!1,created_at:h,updated_at:h}),s.counts.manufacturers.created++;return u.set(p.vendor,x),x}async function y(p){let b=p.map((f)=>te(f.source,r,"product",f.externalId)),h=p.filter((f)=>f.hasOptions).flatMap((f)=>f.variants.map((x)=>te(f.source,r,"variant",x.externalId)));return{products:b.length>0?await a.findProducts(b):new Map,variants:h.length>0?await a.findVariants(h):new Map}}async function g(p,b,h){let f=pg(n()),x={categoryId:await m(p,b,f),manufacturerId:await l(p,b,f)},D=te(p.source,r,"product",p.externalId),v=h.products.get(D),F=v===void 0?"create":"update",k;if(v===void 0)k=await b.createProduct(Jo(p,r,x,f,"create"));else k=v,await b.updateProduct(k,iu(Jo(p,r,x,f,"update")));let S={create:0,update:0};if(p.hasOptions){let{skus:C,warnings:O}=du(p);s.warnings.push(...O);let M=[...C.values()].filter((re)=>re!==null);if(v!==void 0&&M.length>0)await b.releaseVariantSkus(k,M);for(let re of p.variants){let q=C.get(re.externalId)??null,_t=h.variants.get(te(p.source,r,"variant",re.externalId));if(_t===void 0)await b.createVariant(Wo(p,re,r,k,f,"create",q)),S.create++;else await b.updateVariant(_t,iu(Wo(p,re,r,k,f,"update",q))),S.update++}}return{action:F,externalId:p.externalId,name:p.name,handle:p.handle,priceMinor:Lo(p.variants),currency:p.currency,variants:S,category:p.categories[0]?.name??null,vendor:p.vendor,imageCount:p.images.length}}for await(let p of o.pages(t,{limit:e.limit,fetch:e.fetch,currency:e.currency,accessKey:e.accessKey})){s.pages.push(p.url),s.warnings.push(...p.warnings);let b=[];for(let f of p.products){if(c.get(f.externalId)!==void 0){s.counts.duplicates++,s.warnings.push({externalId:f.externalId,message:`"${f.name}" appeared twice; imported once`});continue}c.set(f.externalId,f.handle),b.push(f)}let h=await y(b);for(let f of b){if(f.currency)d.add(f.currency);let x=a.transaction?await a.transaction((D)=>g(f,D,h)):await g(f,a,h);s.counts.products[x.action==="create"?"created":"updated"]++,s.counts.variants.created+=x.variants.create,s.counts.variants.updated+=x.variants.update,s.products.push(x),e.onProduct?.(x)}}if(s.currencies=[...d].sort(),s.currencies.length>1)s.warnings.push({message:`prices arrived in more than one currency (${s.currencies.join(", ")}); products.price has no currency column`});return s}function lu(e=Bo){async function t(a,s){let i=await e.selectFrom(a).where("uuid","=",s).select("id").executeTakeFirst();if(!i)throw Error(`Inserted a row into ${a} but could not read it back (uuid ${s})`);return Number(i.id)}async function r(a,s){let i=new Map;for(let u=0;u<s.length;u+=500){let c=await e.selectFrom(a).where("uuid","in",s.slice(u,u+500)).select(["id","uuid"]).execute();for(let d of c)i.set(d.uuid,Number(d.id))}return i}async function n(a){let s=await a.select("id").executeTakeFirst();return s?Number(s.id):void 0}let o={async findCategory(a,s){return await n(e.selectFrom("categories").where("slug","=",a))??await n(e.selectFrom("categories").where("name","=",s))},async createCategory(a){return await e.insertInto("categories").values(a).execute(),t("categories",a.uuid)},async findManufacturer(a){return n(e.selectFrom("manufacturers").where("manufacturer","=",a))},async createManufacturer(a){return await e.insertInto("manufacturers").values(a).execute(),t("manufacturers",a.uuid)},async findProducts(a){return r("products",a)},async createProduct(a){return await e.insertInto("products").values(a).execute(),t("products",a.uuid)},async updateProduct(a,s){await e.updateTable("products").set(s).where("id","=",a).execute()},async findVariants(a){return r("product_variants",a)},async createVariant(a){return await e.insertInto("product_variants").values(a).execute(),t("product_variants",a.uuid)},async updateVariant(a,s){await e.updateTable("product_variants").set(s).where("id","=",a).execute()},async releaseVariantSkus(a,s){for(let i=0;i<s.length;i+=500)await e.updateTable("product_variants").set({sku:null}).where("product_id","=",a).where("sku","in",s.slice(i,i+500)).execute()}};if(e===Bo)o.transaction=(a)=>Bo.transaction((s)=>a(lu(s)));return o}function gg(){let e={categories:[],manufacturers:[],products:[],product_variants:[]};function t(a,s){let i=e[a].length+1;return e[a].push({id:i,...s}),i}function r(a,s,i){let u=e[a].find((c)=>c.id===s);if(u)Object.assign(u,i)}let n=(a,s)=>new Map(e[a].filter((i)=>s.includes(i.uuid)).map((i)=>[i.uuid,i.id])),o=(a,s)=>e[a].find(s)?.id;return{tables:e,findCategory:async(a,s)=>o("categories",(i)=>i.slug===a)??o("categories",(i)=>i.name===s),createCategory:async(a)=>t("categories",a),findManufacturer:async(a)=>o("manufacturers",(s)=>s.manufacturer===a),createManufacturer:async(a)=>t("manufacturers",a),findProducts:async(a)=>n("products",a),createProduct:async(a)=>t("products",a),updateProduct:async(a,s)=>r("products",a,s),findVariants:async(a)=>n("product_variants",a),createVariant:async(a)=>t("product_variants",a),updateVariant:async(a,s)=>r("product_variants",a,s),releaseVariantSkus:async(a,s)=>{for(let i of e.product_variants)if(i.product_id===a&&s.includes(i.sku))i.sku=null}}}function hg(e){let t=-1,r=async()=>t--;return{findCategory:e.findCategory,findManufacturer:e.findManufacturer,findProducts:e.findProducts,findVariants:e.findVariants,createCategory:r,createManufacturer:r,createProduct:r,createVariant:r,updateProduct:async()=>{},updateVariant:async()=>{},releaseVariantSkus:async()=>{}}}var mu={shopify:lo,woocommerce:Co,shopware:bo};function bg(e){return mu[e.trim().toLowerCase()]}var pu={shopify:wo,woocommerce:Ao,shopware:Po};function _g(e){return pu[e.trim().toLowerCase()]}var zo={};E(zo,{deleteCoupon:()=>wu,deleteCoupons:()=>yu,deleteExpiredCoupons:()=>gu,fetchActive:()=>Ru,fetchAll:()=>_u,fetchByCode:()=>xu,fetchById:()=>Ze,fetchConversionRate:()=>Tu,fetchCouponCounts:()=>vu,fetchCouponCountsByType:()=>Du,fetchRedemptionStats:()=>Su,fetchRedemptionTrend:()=>Cu,fetchStats:()=>Pu,fetchTopRedeemedCoupons:()=>ku,getActiveCouponsMoMChange:()=>Au,redeem:()=>Bu,store:()=>Iu,update:()=>$u});import{db as jo}from"@stacksjs/database/runtime";import{formatDate as xg}from"@stacksjs/orm";async function wu(e){let t=await jo.deleteFrom("coupons").where("id","=",e).executeTakeFirst();return _(t)>0}async function yu(e){if(!e.length)return 0;return await jo.deleteFrom("coupons").where("id","in",e).execute()||0}async function gu(){let e=xg(new Date),t=await jo.deleteFrom("coupons").where("end_date","<",e).executeTakeFirst();return _(t)}import{db as A}from"@stacksjs/database/runtime";import{extractDate as hu,formatDate as bu}from"@stacksjs/orm";import{camelCase as Rg}from"@stacksjs/strings";function yr(e){let t=Object.fromEntries(Object.entries(e).map(([r,n])=>[Rg(r),n]));if(t.endDate)t.endDate=hu(new Date(t.endDate));if(t.startDate)t.startDate=hu(new Date(t.startDate));if(t.isActive!==void 0)t.isActive=Boolean(t.isActive);return t}async function _u(){let e=await A.selectFrom("coupons").selectAll().execute();return P(e).map(yr)}async function Ze(e){let t=await A.selectFrom("coupons").where("id","=",e).selectAll().executeTakeFirst();if(t)return yr(w(t));return}async function xu(e){let t=await A.selectFrom("coupons").where("code","=",e).selectAll().executeTakeFirst();if(t)return yr(w(t));return}async function Ru(){let e=bu(new Date),t=await A.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).selectAll().execute();return P(t).map(yr)}async function Pu(){let e=await A.selectFrom("coupons").select(A.fn.count("id").as("count")).executeTakeFirst(),t=bu(new Date),r=await A.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(A.fn.count("id").as("count")).executeTakeFirst(),n=await A.selectFrom("coupons").select(["discount_type",A.fn.count("id").as("count")]).groupBy("discount_type").execute(),o=await A.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),a=await A.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",t).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(e?.count||0),active:Number(r?.count||0),by_type:n,most_used:o,upcoming:a}}async function vu(){let e=new Date,t=new Date(e);t.setDate(e.getDate()-7);let r=new Date(e);r.setMonth(e.getMonth()-1);let n=new Date(e);n.setFullYear(e.getFullYear()-1);let o=await wr(null,null,e),a=await wr(t,null,e),s=await wr(r,null,e),i=await wr(n,null,e);return{week:a,month:s,year:i,all_time:o}}async function wr(e,t,r){let n=A.selectFrom("coupons");if(e)n=n.where("created_at",">=",e.toISOString());if(t)n=n.where("created_at","<=",t.toISOString());let o=await n.select(A.fn.count("id").as("count")).executeTakeFirst(),a=A.selectFrom("coupons");if(e)a=a.where("created_at",">=",e.toISOString());if(t)a=a.where("created_at","<=",t.toISOString());a=a.where("is_active","=",!0).where("start_date","<=",r).where("end_date",">=",r);let s=await a.select(A.fn.count("id").as("count")).executeTakeFirst(),i=Number(o?.count||0),u=Number(s?.count||0),c=i-u;return{total:i,active:u,inactive:c}}async function Du(){let e=new Date,t=await A.selectFrom("coupons").select("discount_type").distinct().execute(),r={};for(let{discount_type:n}of t){let o=await A.selectFrom("coupons").where("discount_type","=",n).select(A.fn.count("id").as("count")).executeTakeFirst(),a=await A.selectFrom("coupons").where("discount_type","=",n).where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(A.fn.count("id").as("count")).executeTakeFirst(),s=Number(o?.count||0),i=Number(a?.count||0);r[n]={total:s,active:i,inactive:s-i}}return r}async function Su(){let e=await A.selectFrom("coupons").select(A.fn.sum("usage_count").as("total")).executeTakeFirst(),t=new Date,r=new Date(t);r.setDate(t.getDate()-7);let n=new Date(t);n.setMonth(t.getMonth()-1);let o=new Date(t);o.setFullYear(t.getFullYear()-1);let a=await A.selectFrom("coupons").where("updated_at",">=",r.toISOString()).select(A.fn.sum("usage_count").as("total")).executeTakeFirst(),s=await A.selectFrom("coupons").where("updated_at",">=",n.toISOString()).select(A.fn.sum("usage_count").as("total")).executeTakeFirst(),i=await A.selectFrom("coupons").where("updated_at",">=",o.toISOString()).select(A.fn.sum("usage_count").as("total")).executeTakeFirst(),u=await A.selectFrom("coupons").select(["discount_type",A.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),c={};return u.forEach((d)=>{c[d.discount_type]=Number(d.total||0)}),{total:Number(e?.total||0),week:Number(a?.total||0),month:Number(s?.total||0),year:Number(i?.total||0),by_type:c}}async function ku(e=5){return await A.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(e).execute()}async function Cu(e=30){let t=new Date().toISOString(),r=new Date;r.setDate(r.getDate()-e);let n=await A.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",r.toISOString()).where("updated_at","<=",t).where("usage_count",">",0).orderBy("updated_at","desc").execute(),o={};return n.forEach((a)=>{let s=a.updated_at?new Date(a.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!o[s])o[s]=0;o[s]+=a?.usage_count||0}),Object.entries(o).map(([a,s])=>({date:a,count:s}))}async function Tu(){let e=new Date,t=await A.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(A.fn.count("id").as("count")).executeTakeFirst(),r=await A.selectFrom("coupons").where("usage_count",">",0).select(A.fn.count("id").as("count")).executeTakeFirst(),n=Number(t?.count||0),o=Number(r?.count||0);return{rate:n>0?o/n*100:0,total_active:n,total_redeemed:o}}async function Au(){let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()-1,1),n=new Date(e.getFullYear(),e.getMonth(),0),o=await A.selectFrom("coupons").select(A.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",t).executeTakeFirst(),a=await A.selectFrom("coupons").select(A.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",n).where("end_date",">=",r).executeTakeFirst(),s=Number(o?.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:Pg}=globalThis.Bun;import{db as Eu}from"@stacksjs/database/runtime";import{HttpError as Fu}from"@stacksjs/error-handling";import{isUniqueViolation as vg}from"@stacksjs/orm";async function Iu(e){try{let t=Pg();await Eu.insertInto("coupons").values({...e,uuid:t}).executeTakeFirst();let r=await Eu.selectFrom("coupons").where("uuid","=",t).selectAll().executeTakeFirst();return w(r,!0)}catch(t){if(t instanceof Fu)throw t;if(vg(t))throw new Fu(409,"A coupon with this code already exists");if(t instanceof Error)throw Error(`Failed to create coupon: ${t.message}`);throw t}}import{db as Nu,mutationCount as Dg,sqlHelpers as Sg}from"@stacksjs/database/runtime";import{env as kg}from"@stacksjs/env";import{HttpError as Mu}from"@stacksjs/error-handling";import{formatDate as Ou,isUniqueViolation as Cg}from"@stacksjs/orm";async function $u(e,t){if(!await Ze(e))return;try{return await Nu.updateTable("coupons").set({...t,updated_at:Ou(new Date)}).where("id","=",e).execute(),await Ze(e)}catch(n){if(n instanceof Mu)throw n;if(Cg(n))throw new Mu(409,"A coupon with this code already exists");if(n instanceof Error)throw Error(`Failed to update coupon: ${n.message}`);throw n}}async function Bu(e){let t=Sg(kg.DB_CONNECTION||"sqlite"),r=t.param,n=Ou(new Date),o=await Nu.unsafe(`UPDATE coupons
3
3
  SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ${r(1)}
4
4
  WHERE id = ${r(2)}
5
5
  AND (usage_limit IS NULL OR COALESCE(usage_count, 0) < usage_limit)
6
6
  AND is_active = ${t.boolTrue}
7
7
  AND (start_date IS NULL OR start_date <= ${r(3)})
8
- AND (end_date IS NULL OR end_date >= ${r(4)})`,[n,e,n,n]);if(vg(o)>0){let u=await Ze(e);if(u)return{ok:!0,coupon:u};return{ok:!1,reason:"not-found"}}let a=await Ze(e);if(!a)return{ok:!1,reason:"not-found"};if(!a.isActive)return{ok:!1,reason:"inactive"};let s=!a.startDate||a.startDate<=n,i=!a.endDate||a.endDate>=n;if(!s||!i)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var zo={};E(zo,{bulkDestroy:()=>Ju,destroy:()=>Uu,fetchAll:()=>Ki,fetchById:()=>mr,store:()=>Qi,update:()=>Lu});import{db as Bu}from"@stacksjs/database/runtime";async function Uu(e){try{let t=await Bu.deleteFrom("customers").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete customer: ${t.message}`);throw t}}async function Ju(e){if(!e.length)return 0;try{let t=await Bu.deleteFrom("customers").where("id","in",e).executeTakeFirst();return _(t)||0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${t.message}`);throw t}}import{db as Cg}from"@stacksjs/database/runtime";import{HttpError as Wu}from"@stacksjs/error-handling";import{formatDate as Tg,isUniqueViolation as Ag}from"@stacksjs/orm";async function Lu(e,t){try{if(!e)throw Error("Customer ID is required for update");let r=await Cg.updateTable("customers").set({...t,updated_at:Tg(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Wu)throw r;if(Ag(r))throw new Wu(409,"A customer with this email already exists");if(r instanceof Error)throw Error(`Failed to update customer: ${r.message}`);throw r}}var Ko={};E(Ko,{bulkDestroy:()=>Gu,bulkStore:()=>oc,calculateErrorRate:()=>Ku,calculatePrinterHealth:()=>Qu,countAll:()=>qu,countPrintsByDeviceId:()=>Hu,countTotalPrints:()=>Vu,destroy:()=>zu,downloadPrintDevices:()=>ec,exportPrintDevices:()=>gr,fetchAll:()=>yr,fetchById:()=>De,fetchErrorsByDeviceId:()=>Zu,getPrinterStatusCounts:()=>Yu,store:()=>nc,storePrintDevicesExport:()=>tc,update:()=>ac,updatePrintCount:()=>ic,updateStatus:()=>sc});import{db as ju}from"@stacksjs/database/runtime";async function zu(e){try{let t=await ju.deleteFrom("print_devices").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print device: ${t.message}`);throw t}}async function Gu(e){if(!e.length)return 0;try{let t=await ju.deleteFrom("print_devices").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print devices: ${t.message}`);throw t}}import{createSpreadsheet as Eg}from"ts-spreadsheets";import{db as Q}from"@stacksjs/database/runtime";async function De(e){let t=await Q.selectFrom("print_devices").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function yr(){return P(await Q.selectFrom("print_devices").selectAll().execute())}async function qu(){let e=await Q.selectFrom("print_devices").select(Q.fn.count("id").as("count")).executeTakeFirst();return Number(e?.count||0)}async function Vu(){let e=await Q.selectFrom("print_devices").select(Q.fn.sum("print_count").as("total")).executeTakeFirst();return Number(e?.total||0)}async function Hu(e){let t=await Q.selectFrom("print_devices").select("print_count").where("id","=",e).executeTakeFirst();return Number(t?.print_count??0)}async function Ku(){let e=await Q.selectFrom("receipts").select([Q.fn.count("id").as("total"),Q.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!e?.total||e.total===0)return 0;return Number(Number(e?.failed_count??0)/Number(e?.total??0)*100)}async function Zu(e){let t=await Q.selectFrom("receipts").where("print_device_id","=",e).where("status","=","failed").selectAll().execute();return P(t)}async function Qu(){let e=await Q.selectFrom("print_devices").select([Q.fn.count("id").as("total"),Q.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!e?.total||e.total===0)return 0;return Number(Number(e?.online_count??0)/Number(e?.total??0)*100)}async function Yu(){return(await Q.selectFrom("print_devices").select(["status",Q.fn.count("id").as("count")]).groupBy("status").execute()).reduce((t,r)=>(t[r.status]=Number(r.count||0),t),{})}function Go(e,t,r=t){let n=e;return n[String(t)]??n[r]}function Fg(e){if(e instanceof Date)return e;if(typeof e==="number")return new Date(e);if(typeof e==="string")return new Date(/^\d+$/.test(e)?Number(e):e);return new Date(Number.NaN)}function Xu(e,t,r=t){let n=Go(e,t,r);if(typeof n==="number")return n;let o=Number(n);return Number.isFinite(o)?o:0}function At(e,t,r=t){let n=Go(e,t,r);return n==null?"":String(n)}async function gr(e="csv"){let t=await yr(),r=Ig(t);return Eg(r,{type:e})}function Ig(e){let t=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],r=e.map((n)=>[Xu(n,"id"),At(n,"name"),At(n,"macAddress","mac_address"),At(n,"location"),At(n,"terminal"),At(n,"status"),Fg(Go(n,"lastPing","last_ping")).toLocaleString(),Xu(n,"printCount","print_count")]);return{headings:t,data:r}}async function ec(e="csv",t){let r=await gr(e),n=`print_devices_export_${new Date().toISOString().split("T")[0]}.${e}`;return r.download(t||n)}async function tc(e="csv",t){let r=await gr(e),n=`print_devices_export_${new Date().toISOString().split("T")[0]}.${e}`;r.store(t||n)}var{randomUUIDv7:rc}=globalThis.Bun;import{db as qo}from"@stacksjs/database/runtime";async function nc(e){try{let t=rc(),r={last_ping:0,print_count:0,...e,uuid:t};await qo.insertInto("print_devices").values(r).executeTakeFirst();let n=await qo.selectFrom("print_devices").where("uuid","=",t).selectAll().executeTakeFirst();return w(n,!0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create print device: ${t.message}`);throw t}}async function oc(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={last_ping:0,print_count:0,...r,uuid:rc()};await qo.insertInto("print_devices").values(n).execute(),t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${r.message}`);throw r}}import{db as Vo}from"@stacksjs/database/runtime";import{formatDate as Ho}from"@stacksjs/orm";async function ac(e,t){if(!await De(e))return;try{return await Vo.updateTable("print_devices").set({...t,updated_at:Ho(new Date)}).where("id","=",e).execute(),await De(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print device: ${n.message}`);throw n}}async function sc(e,t){if(!await De(e))throw Error(`Print device with ID ${e} not found`);try{return await Vo.updateTable("print_devices").set({status:t,updated_at:Ho(new Date)}).where("id","=",e).execute(),await De(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print device status: ${n.message}`);throw n}}async function ic(e,t){if(!await De(e))throw Error(`Print device with ID ${e} not found`);try{return await Vo.updateTable("print_devices").set({print_count:t,updated_at:Ho(new Date)}).where("id","=",e).execute(),await De(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print count: ${n.message}`);throw n}}var Yo={};E(Yo,{bulkDestroy:()=>cc,bulkUpdateStatus:()=>gc,destroy:()=>uc,destroyGroup:()=>dc,fetchAll:()=>br,fetchByGroup:()=>pc,fetchById:()=>lc,fetchGrouped:()=>mc,fetchStats:()=>fc,fetchTimeline:()=>wc,ignoreGroup:()=>bc,resolveGroup:()=>hc,unresolveGroup:()=>_c,update:()=>yc});import{db as Zo}from"@stacksjs/database/runtime";import{log as Qo}from"@stacksjs/logging";async function uc(e){try{return await Zo.deleteFrom("errors").where("id","=",e).execute(),!0}catch(t){return Qo.error("[commerce/errors] destroy failed",{id:e,error:t}),!1}}async function cc(e){try{return await Zo.deleteFrom("errors").where("id","in",e).execute(),!0}catch(t){return Qo.error("[commerce/errors] bulkDestroy failed",{count:e.length,error:t}),!1}}async function dc(e,t){try{return await Zo.deleteFrom("errors").where("type","=",e).where("message","=",t).execute(),!0}catch(r){return Qo.error("[commerce/errors] destroyGroup failed",{type:e,message:t,error:r}),!1}}import{db as hr}from"@stacksjs/database/runtime";async function lc(e){return await hr.selectFrom("errors").where("id","=",e).selectAll().executeTakeFirst()}async function br(){return await hr.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function mc(){let e=await hr.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),t=new Map;for(let n of e){let o=`${n.type}:${n.message}`;if(!t.has(o))t.set(o,{errors:[],firstSeen:new Date(n.created_at),lastSeen:new Date(n.created_at)});let a=t.get(o);a.errors.push(n);let s=new Date(n.created_at);if(s<a.firstSeen)a.firstSeen=s;if(s>a.lastSeen)a.lastSeen=s}let r=[];for(let[n,o]of t){let a=o.errors[0];if(!a)continue;let s=o.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:o.errors.length,first_seen:o.firstSeen.toISOString(),last_seen:o.lastSeen.toISOString(),error_ids:o.errors.map((u)=>u.id)})}return r.sort((n,o)=>new Date(o.last_seen).getTime()-new Date(n.last_seen).getTime()),r}async function pc(e,t){return await hr.selectFrom("errors").where("type","=",e).where("message","=",t).selectAll().orderBy("created_at","desc").execute()}async function fc(){let e=await br(),t=new Date,r=new Date(t.getTime()-86400000),n=new Date(t.getTime()-172800000),o=e.filter((i)=>new Date(i.created_at)>=r).length,a=e.filter((i)=>{let u=new Date(i.created_at);return u>=n&&u<r}).length,s=a===0?o>0?100:0:Math.round((o-a)/a*100);return{total:e.length,unresolved:e.filter((i)=>i.status===null||i.status===0).length,resolved:e.filter((i)=>i.status===1).length,ignored:e.filter((i)=>i.status===2).length,last_24h:o,trend:s}}async function wc(){let e=await br(),t=new Date,r=[];for(let n=23;n>=0;n--){let o=new Date(t.getTime()-n*60*60*1000);o.setMinutes(0,0,0);let a=new Date(o.getTime()+3600000),s=e.filter((i)=>{let u=new Date(i.created_at);return u>=o&&u<a}).length;r.push({hour:o.toISOString(),count:s})}return r}import{db as Et}from"@stacksjs/database/runtime";import{sql as Ft}from"@stacksjs/database/runtime";import{log as It}from"@stacksjs/logging";async function yc(e,t){try{return await Et.updateTable("errors").set({...t,updated_at:Ft.raw("CURRENT_TIMESTAMP")}).where("id","=",e).execute(),!0}catch(r){return It.error("[commerce/errors] update failed",{id:e,error:r}),!1}}async function gc(e,t){try{return await Et.updateTable("errors").set({status:t,updated_at:Ft.raw("CURRENT_TIMESTAMP")}).where("id","in",e).execute(),!0}catch(r){return It.error("[commerce/errors] bulkUpdateStatus failed",{count:e.length,status:t,error:r}),!1}}async function hc(e,t){try{return await Et.updateTable("errors").set({status:1,updated_at:Ft.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return It.error("[commerce/errors] resolveGroup failed",{type:e,message:t,error:r}),!1}}async function bc(e,t){try{return await Et.updateTable("errors").set({status:2,updated_at:Ft.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return It.error("[commerce/errors] ignoreGroup failed",{type:e,message:t,error:r}),!1}}async function _c(e,t){try{return await Et.updateTable("errors").set({status:0,updated_at:Ft.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return It.error("[commerce/errors] unresolveGroup failed",{type:e,message:t,error:r}),!1}}var ta={};E(ta,{bulkDestroy:()=>Ec,calculateGiftCardValues:()=>Sc,checkBalance:()=>vc,compareActiveGiftCards:()=>Dc,deactivate:()=>Ic,destroy:()=>Ac,destroyExpired:()=>Fc,fetchActive:()=>Rc,fetchAll:()=>xc,fetchByCode:()=>Xo,fetchById:()=>Se,fetchStats:()=>Pc,fetchTotalCurrentBalance:()=>Cc,fetchTotalValue:()=>kc,store:()=>Nc,update:()=>Jc,updateBalance:()=>Wc});import{db as _r,matchedRows as Og}from"@stacksjs/database/runtime";import{formatDate as Tc}from"@stacksjs/orm";import{db as W,sql as ae}from"@stacksjs/database/runtime";import{formatDate as Be,toTimestamp as ut}from"@stacksjs/orm";import{aggregateFunctions as Mg,db as Ng}from"@stacksjs/database/runtime";async function ue(e,t,r){let n=Ng.selectFrom(e);if(r)n=r(n);n=n.select(Object.entries(t).map(([s,i])=>{let u=i.column??"id",c=Mg[i.kind](u);if(i.filter)c=c.filterWhere(i.filter.column,i.filter.op,i.filter.value);return c.as(s)}));let o=await n.executeTakeFirst(),a={};for(let s of Object.keys(t)){let i=o?.[s];a[s]=typeof i==="number"?i:Number(i??0)||0}return a}async function xc(){let e=await W.selectFrom("gift_cards").selectAll().execute();return P(e)}async function Se(e){let t=await W.selectFrom("gift_cards").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Xo(e){let t=await W.selectFrom("gift_cards").where("code","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Rc(){let e=await W.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute();return P(e)}async function Pc(){let{count:e}=await ue("gift_cards",{count:{kind:"count"}}),t=ut(new Date),r=await W.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(ae`(expiry_date >= ${ae.literal(t)} OR expiry_date IS NULL)`).select(W.fn.count("id").as("count")).executeTakeFirst(),n=await W.selectFrom("gift_cards").select(["status",W.fn.count("id").as("count")]).groupBy("status").execute(),{count:o}=await ue("gift_cards",{count:{kind:"count"}},(d)=>d.whereRaw(ae`current_balance / initial_balance < 0.25`)),{count:a}=await ue("gift_cards",{count:{kind:"count"}},(d)=>d.whereRaw(ae`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:s}=await ue("gift_cards",{count:{kind:"count"}},(d)=>d.whereRaw(ae`current_balance / initial_balance > 0.75`)),i=new Date;i.setDate(i.getDate()+30);let u=await W.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",ut(i)).where("expiry_date",">=",t).selectAll().limit(5).execute(),c=await W.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:e,active:Number(r?.count||0),by_status:n.map((d)=>({status:d.status,count:Number(d.count)})),by_balance:{low:o,medium:a,high:s},expiring_soon:P(u),recently_used:P(c)}}async function vc(e){let t=await Xo(e);if(!t)return{valid:!1,message:"Gift card not found"};if(!t.isActive||t.status!=="ACTIVE")return{valid:!1,balance:t.currentBalance,currency:t.currency,message:`Gift card is ${t.status.toLowerCase()}`};if(t.expiryDate){if(new Date(t.expiryDate)<new Date)return{valid:!1,balance:t.currentBalance,currency:t.currency,message:"Gift card has expired"}}return{valid:!0,balance:t.currentBalance,currency:t.currency}}async function Dc(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await W.selectFrom("gift_cards").select(W.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(ae`(expiry_date >= ${ae.literal(ut(t))} OR expiry_date IS NULL)`).where("created_at",">=",Be(r)).where("created_at","<=",Be(t)).executeTakeFirst(),s=await W.selectFrom("gift_cards").select(W.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(ae`(expiry_date >= ${ae.literal(ut(o))} OR expiry_date IS NULL)`).where("created_at",">=",Be(o)).where("created_at","<=",Be(n)).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,d=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:d,days_range:e}}async function Sc(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await W.selectFrom("gift_cards").select([W.fn.sum("initial_balance").as("total_initial"),W.fn.sum("current_balance").as("total_balance"),W.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(ae`(expiry_date >= ${ae.literal(ut(t))} OR expiry_date IS NULL)`).where("created_at",">=",Be(r)).where("created_at","<=",Be(t)).executeTakeFirst(),s=await W.selectFrom("gift_cards").select([W.fn.sum("initial_balance").as("total_initial"),W.fn.sum("current_balance").as("total_balance"),W.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(ae`(expiry_date >= ${ae.literal(ut(o))} OR expiry_date IS NULL)`).where("created_at",">=",Be(o)).where("created_at","<=",Be(n)).executeTakeFirst(),i=Number(a?.total_initial||0),u=Number(a?.total_balance||0),c=Number(a?.card_count||0),d=Number(s?.total_initial||0),m=Number(s?.total_balance||0),l=Number(s?.card_count||0),y=i>0?(i-u)/i*100:0,g=d>0?(d-m)/d*100:0,p=c>0?i/c:0,b=c>0?u/c:0,h=i-d,f=u-m,x=c-l,D=d!==0?h/d*100:i>0?100:0,v=m!==0?f/m*100:u>0?100:0,F=l!==0?x/l*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:p,average_remaining_balance:b},previous_period:{total_initial_value:d,total_remaining_balance:m,utilization_rate:g,card_count:l},comparison:{initial_value:{difference:h,percentage:Math.abs(D),is_increase:h>=0},balance:{difference:f,percentage:Math.abs(v),is_increase:f>=0},card_count:{difference:x,percentage:Math.abs(F),is_increase:x>=0}},days_range:e}}async function kc(){let{total_value:e}=await ue("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:e}}async function Cc(){let{total_balance:e}=await ue("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:e}}async function Ac(e){let t=await _r.deleteFrom("gift_cards").where("id","=",e).executeTakeFirst();return _(t)>0}async function Ec(e){if(!e.length)return 0;let t=await _r.deleteFrom("gift_cards").where("id","in",e).executeTakeFirst();return _(t)}async function Fc(){let e=Tc(new Date),t=await _r.deleteFrom("gift_cards").where("expiry_date","<",e).executeTakeFirst();return _(t)}async function Ic(e){if(!await Se(e))throw Error(`Gift card with ID ${e} not found`);return(await Og(_r.updateTable("gift_cards").set({is_active:!1,status:"DEACTIVATED",updated_at:Tc(new Date)}).where("id","=",e))).length>0}var{randomUUIDv7:$g}=globalThis.Bun;import{db as ea}from"@stacksjs/database/runtime";import{HttpError as Mc}from"@stacksjs/error-handling";import{isUniqueViolation as Bg}from"@stacksjs/orm";async function Nc(e){let t=e,r={...e,current_balance:t.current_balance??t.initial_balance,status:e.status||"ACTIVE",is_active:t.is_active??!0,uuid:$g()};try{let n=await ea.insertInto("gift_cards").values(r).executeTakeFirst(),o=ve(n);if(o!==void 0){let s=await ea.selectFrom("gift_cards").where("id","=",o).selectAll().executeTakeFirst();return w(s)}let a=await ea.selectFrom("gift_cards").where("uuid","=",r.uuid).selectAll().executeTakeFirst();return w(a,!0)}catch(n){if(n instanceof Mc)throw n;if(Bg(n))throw new Mc(409,"A gift card with this code already exists");if(n instanceof Error)throw Error(`Failed to create gift card: ${n.message}`);throw n}}import{db as Bc,mutationCount as Ug,parseSqlDateTime as Oc,sqlHelpers as Jg}from"@stacksjs/database/runtime";import{env as Wg}from"@stacksjs/env";import{HttpError as $c}from"@stacksjs/error-handling";import{formatDate as Uc,isUniqueViolation as Lg}from"@stacksjs/orm";async function Jc(e,t){if(!await Se(e))return;try{return await Bc.updateTable("gift_cards").set({...t,updated_at:Uc(new Date)}).where("id","=",e).execute(),await Se(e)}catch(n){if(n instanceof $c)throw n;if(Lg(n))throw new $c(409,"A gift card with this code already exists");if(n instanceof Error)throw Error(`Failed to update gift card: ${n.message}`);throw n}}async function Wc(e,t){if(!Number.isFinite(t))throw Error(`Gift card balance adjustment must be a finite number, got ${t}`);let r=Jg(Wg.DB_CONNECTION||"sqlite"),n=r.param,o=Uc(new Date),a=t<0,s=t>0,i=s?`(status = 'ACTIVE' OR (status = 'USED' AND is_reloadable = ${r.boolTrue}))`:"status = 'ACTIVE'",u=[],c=(p)=>(u.push(p),n(u.length)),d=await Bc.unsafe(`UPDATE gift_cards
8
+ AND (end_date IS NULL OR end_date >= ${r(4)})`,[n,e,n,n]);if(Dg(o)>0){let u=await Ze(e);if(u)return{ok:!0,coupon:u};return{ok:!1,reason:"not-found"}}let a=await Ze(e);if(!a)return{ok:!1,reason:"not-found"};if(!a.isActive)return{ok:!1,reason:"inactive"};let s=!a.startDate||a.startDate<=n,i=!a.endDate||a.endDate>=n;if(!s||!i)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var Go={};E(Go,{bulkDestroy:()=>Wu,destroy:()=>Ju,fetchAll:()=>Zi,fetchById:()=>pr,store:()=>Yi,update:()=>ju});import{db as Uu}from"@stacksjs/database/runtime";async function Ju(e){try{let t=await Uu.deleteFrom("customers").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete customer: ${t.message}`);throw t}}async function Wu(e){if(!e.length)return 0;try{let t=await Uu.deleteFrom("customers").where("id","in",e).executeTakeFirst();return _(t)||0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${t.message}`);throw t}}import{db as Tg}from"@stacksjs/database/runtime";import{HttpError as Lu}from"@stacksjs/error-handling";import{formatDate as Ag,isUniqueViolation as Eg}from"@stacksjs/orm";async function ju(e,t){try{if(!e)throw Error("Customer ID is required for update");let r=await Tg.updateTable("customers").set({...t,updated_at:Ag(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Lu)throw r;if(Eg(r))throw new Lu(409,"A customer with this email already exists");if(r instanceof Error)throw Error(`Failed to update customer: ${r.message}`);throw r}}var Zo={};E(Zo,{bulkDestroy:()=>qu,bulkStore:()=>ac,calculateErrorRate:()=>Zu,calculatePrinterHealth:()=>Yu,countAll:()=>Vu,countPrintsByDeviceId:()=>Ku,countTotalPrints:()=>Hu,destroy:()=>Gu,downloadPrintDevices:()=>tc,exportPrintDevices:()=>hr,fetchAll:()=>gr,fetchById:()=>De,fetchErrorsByDeviceId:()=>Qu,getPrinterStatusCounts:()=>Xu,store:()=>oc,storePrintDevicesExport:()=>rc,update:()=>sc,updatePrintCount:()=>uc,updateStatus:()=>ic});import{db as zu}from"@stacksjs/database/runtime";async function Gu(e){try{let t=await zu.deleteFrom("print_devices").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print device: ${t.message}`);throw t}}async function qu(e){if(!e.length)return 0;try{let t=await zu.deleteFrom("print_devices").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print devices: ${t.message}`);throw t}}import{createSpreadsheet as Fg}from"ts-spreadsheets";import{db as Q}from"@stacksjs/database/runtime";async function De(e){let t=await Q.selectFrom("print_devices").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function gr(){return P(await Q.selectFrom("print_devices").selectAll().execute())}async function Vu(){let e=await Q.selectFrom("print_devices").select(Q.fn.count("id").as("count")).executeTakeFirst();return Number(e?.count||0)}async function Hu(){let e=await Q.selectFrom("print_devices").select(Q.fn.sum("print_count").as("total")).executeTakeFirst();return Number(e?.total||0)}async function Ku(e){let t=await Q.selectFrom("print_devices").select("print_count").where("id","=",e).executeTakeFirst();return Number(t?.print_count??0)}async function Zu(){let e=await Q.selectFrom("receipts").select([Q.fn.count("id").as("total"),Q.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!e?.total||e.total===0)return 0;return Number(Number(e?.failed_count??0)/Number(e?.total??0)*100)}async function Qu(e){let t=await Q.selectFrom("receipts").where("print_device_id","=",e).where("status","=","failed").selectAll().execute();return P(t)}async function Yu(){let e=await Q.selectFrom("print_devices").select([Q.fn.count("id").as("total"),Q.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!e?.total||e.total===0)return 0;return Number(Number(e?.online_count??0)/Number(e?.total??0)*100)}async function Xu(){return(await Q.selectFrom("print_devices").select(["status",Q.fn.count("id").as("count")]).groupBy("status").execute()).reduce((t,r)=>(t[r.status]=Number(r.count||0),t),{})}function qo(e,t,r=t){let n=e;return n[String(t)]??n[r]}function Ig(e){if(e instanceof Date)return e;if(typeof e==="number")return new Date(e);if(typeof e==="string")return new Date(/^\d+$/.test(e)?Number(e):e);return new Date(Number.NaN)}function ec(e,t,r=t){let n=qo(e,t,r);if(typeof n==="number")return n;let o=Number(n);return Number.isFinite(o)?o:0}function Et(e,t,r=t){let n=qo(e,t,r);return n==null?"":String(n)}async function hr(e="csv"){let t=await gr(),r=Mg(t);return Fg(r,{type:e})}function Mg(e){let t=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],r=e.map((n)=>[ec(n,"id"),Et(n,"name"),Et(n,"macAddress","mac_address"),Et(n,"location"),Et(n,"terminal"),Et(n,"status"),Ig(qo(n,"lastPing","last_ping")).toLocaleString(),ec(n,"printCount","print_count")]);return{headings:t,data:r}}async function tc(e="csv",t){let r=await hr(e),n=`print_devices_export_${new Date().toISOString().split("T")[0]}.${e}`;return r.download(t||n)}async function rc(e="csv",t){let r=await hr(e),n=`print_devices_export_${new Date().toISOString().split("T")[0]}.${e}`;r.store(t||n)}var{randomUUIDv7:nc}=globalThis.Bun;import{db as Vo}from"@stacksjs/database/runtime";async function oc(e){try{let t=nc(),r={last_ping:0,print_count:0,...e,uuid:t};await Vo.insertInto("print_devices").values(r).executeTakeFirst();let n=await Vo.selectFrom("print_devices").where("uuid","=",t).selectAll().executeTakeFirst();return w(n,!0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create print device: ${t.message}`);throw t}}async function ac(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={last_ping:0,print_count:0,...r,uuid:nc()};await Vo.insertInto("print_devices").values(n).execute(),t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${r.message}`);throw r}}import{db as Ho}from"@stacksjs/database/runtime";import{formatDate as Ko}from"@stacksjs/orm";async function sc(e,t){if(!await De(e))return;try{return await Ho.updateTable("print_devices").set({...t,updated_at:Ko(new Date)}).where("id","=",e).execute(),await De(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print device: ${n.message}`);throw n}}async function ic(e,t){if(!await De(e))throw Error(`Print device with ID ${e} not found`);try{return await Ho.updateTable("print_devices").set({status:t,updated_at:Ko(new Date)}).where("id","=",e).execute(),await De(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print device status: ${n.message}`);throw n}}async function uc(e,t){if(!await De(e))throw Error(`Print device with ID ${e} not found`);try{return await Ho.updateTable("print_devices").set({print_count:t,updated_at:Ko(new Date)}).where("id","=",e).execute(),await De(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print count: ${n.message}`);throw n}}var Xo={};E(Xo,{bulkDestroy:()=>dc,bulkUpdateStatus:()=>hc,destroy:()=>cc,destroyGroup:()=>lc,fetchAll:()=>_r,fetchByGroup:()=>fc,fetchById:()=>mc,fetchGrouped:()=>pc,fetchStats:()=>wc,fetchTimeline:()=>yc,ignoreGroup:()=>_c,resolveGroup:()=>bc,unresolveGroup:()=>xc,update:()=>gc});import{db as Qo}from"@stacksjs/database/runtime";import{log as Yo}from"@stacksjs/logging";async function cc(e){try{return await Qo.deleteFrom("errors").where("id","=",e).execute(),!0}catch(t){return Yo.error("[commerce/errors] destroy failed",{id:e,error:t}),!1}}async function dc(e){try{return await Qo.deleteFrom("errors").where("id","in",e).execute(),!0}catch(t){return Yo.error("[commerce/errors] bulkDestroy failed",{count:e.length,error:t}),!1}}async function lc(e,t){try{return await Qo.deleteFrom("errors").where("type","=",e).where("message","=",t).execute(),!0}catch(r){return Yo.error("[commerce/errors] destroyGroup failed",{type:e,message:t,error:r}),!1}}import{db as br}from"@stacksjs/database/runtime";async function mc(e){return await br.selectFrom("errors").where("id","=",e).selectAll().executeTakeFirst()}async function _r(){return await br.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function pc(){let e=await br.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),t=new Map;for(let n of e){let o=`${n.type}:${n.message}`;if(!t.has(o))t.set(o,{errors:[],firstSeen:new Date(n.created_at),lastSeen:new Date(n.created_at)});let a=t.get(o);a.errors.push(n);let s=new Date(n.created_at);if(s<a.firstSeen)a.firstSeen=s;if(s>a.lastSeen)a.lastSeen=s}let r=[];for(let[n,o]of t){let a=o.errors[0];if(!a)continue;let s=o.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:o.errors.length,first_seen:o.firstSeen.toISOString(),last_seen:o.lastSeen.toISOString(),error_ids:o.errors.map((u)=>u.id)})}return r.sort((n,o)=>new Date(o.last_seen).getTime()-new Date(n.last_seen).getTime()),r}async function fc(e,t){return await br.selectFrom("errors").where("type","=",e).where("message","=",t).selectAll().orderBy("created_at","desc").execute()}async function wc(){let e=await _r(),t=new Date,r=new Date(t.getTime()-86400000),n=new Date(t.getTime()-172800000),o=e.filter((i)=>new Date(i.created_at)>=r).length,a=e.filter((i)=>{let u=new Date(i.created_at);return u>=n&&u<r}).length,s=a===0?o>0?100:0:Math.round((o-a)/a*100);return{total:e.length,unresolved:e.filter((i)=>i.status===null||i.status===0).length,resolved:e.filter((i)=>i.status===1).length,ignored:e.filter((i)=>i.status===2).length,last_24h:o,trend:s}}async function yc(){let e=await _r(),t=new Date,r=[];for(let n=23;n>=0;n--){let o=new Date(t.getTime()-n*60*60*1000);o.setMinutes(0,0,0);let a=new Date(o.getTime()+3600000),s=e.filter((i)=>{let u=new Date(i.created_at);return u>=o&&u<a}).length;r.push({hour:o.toISOString(),count:s})}return r}import{db as Ft}from"@stacksjs/database/runtime";import{sql as It}from"@stacksjs/database/runtime";import{log as Mt}from"@stacksjs/logging";async function gc(e,t){try{return await Ft.updateTable("errors").set({...t,updated_at:It.raw("CURRENT_TIMESTAMP")}).where("id","=",e).execute(),!0}catch(r){return Mt.error("[commerce/errors] update failed",{id:e,error:r}),!1}}async function hc(e,t){try{return await Ft.updateTable("errors").set({status:t,updated_at:It.raw("CURRENT_TIMESTAMP")}).where("id","in",e).execute(),!0}catch(r){return Mt.error("[commerce/errors] bulkUpdateStatus failed",{count:e.length,status:t,error:r}),!1}}async function bc(e,t){try{return await Ft.updateTable("errors").set({status:1,updated_at:It.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return Mt.error("[commerce/errors] resolveGroup failed",{type:e,message:t,error:r}),!1}}async function _c(e,t){try{return await Ft.updateTable("errors").set({status:2,updated_at:It.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return Mt.error("[commerce/errors] ignoreGroup failed",{type:e,message:t,error:r}),!1}}async function xc(e,t){try{return await Ft.updateTable("errors").set({status:0,updated_at:It.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return Mt.error("[commerce/errors] unresolveGroup failed",{type:e,message:t,error:r}),!1}}var ra={};E(ra,{bulkDestroy:()=>Fc,calculateGiftCardValues:()=>kc,checkBalance:()=>Dc,compareActiveGiftCards:()=>Sc,deactivate:()=>Mc,destroy:()=>Ec,destroyExpired:()=>Ic,fetchActive:()=>Pc,fetchAll:()=>Rc,fetchByCode:()=>ea,fetchById:()=>Se,fetchStats:()=>vc,fetchTotalCurrentBalance:()=>Tc,fetchTotalValue:()=>Cc,store:()=>Oc,update:()=>Wc,updateBalance:()=>Lc});import{db as xr,matchedRows as $g}from"@stacksjs/database/runtime";import{formatDate as Ac}from"@stacksjs/orm";import{db as W,sql as ae}from"@stacksjs/database/runtime";import{formatDate as Ue,toTimestamp as ut}from"@stacksjs/orm";import{aggregateFunctions as Ng,db as Og}from"@stacksjs/database/runtime";async function ue(e,t,r){let n=Og.selectFrom(e);if(r)n=r(n);n=n.select(Object.entries(t).map(([s,i])=>{let u=i.column??"id",c=Ng[i.kind](u);if(i.filter)c=c.filterWhere(i.filter.column,i.filter.op,i.filter.value);return c.as(s)}));let o=await n.executeTakeFirst(),a={};for(let s of Object.keys(t)){let i=o?.[s];a[s]=typeof i==="number"?i:Number(i??0)||0}return a}async function Rc(){let e=await W.selectFrom("gift_cards").selectAll().execute();return P(e)}async function Se(e){let t=await W.selectFrom("gift_cards").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function ea(e){let t=await W.selectFrom("gift_cards").where("code","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Pc(){let e=await W.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute();return P(e)}async function vc(){let{count:e}=await ue("gift_cards",{count:{kind:"count"}}),t=ut(new Date),r=await W.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(ae`(expiry_date >= ${ae.literal(t)} OR expiry_date IS NULL)`).select(W.fn.count("id").as("count")).executeTakeFirst(),n=await W.selectFrom("gift_cards").select(["status",W.fn.count("id").as("count")]).groupBy("status").execute(),{count:o}=await ue("gift_cards",{count:{kind:"count"}},(d)=>d.whereRaw(ae`current_balance / initial_balance < 0.25`)),{count:a}=await ue("gift_cards",{count:{kind:"count"}},(d)=>d.whereRaw(ae`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:s}=await ue("gift_cards",{count:{kind:"count"}},(d)=>d.whereRaw(ae`current_balance / initial_balance > 0.75`)),i=new Date;i.setDate(i.getDate()+30);let u=await W.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",ut(i)).where("expiry_date",">=",t).selectAll().limit(5).execute(),c=await W.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:e,active:Number(r?.count||0),by_status:n.map((d)=>({status:d.status,count:Number(d.count)})),by_balance:{low:o,medium:a,high:s},expiring_soon:P(u),recently_used:P(c)}}async function Dc(e){let t=await ea(e);if(!t)return{valid:!1,message:"Gift card not found"};if(!t.isActive||t.status!=="ACTIVE")return{valid:!1,balance:t.currentBalance,currency:t.currency,message:`Gift card is ${t.status.toLowerCase()}`};if(t.expiryDate){if(new Date(t.expiryDate)<new Date)return{valid:!1,balance:t.currentBalance,currency:t.currency,message:"Gift card has expired"}}return{valid:!0,balance:t.currentBalance,currency:t.currency}}async function Sc(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await W.selectFrom("gift_cards").select(W.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(ae`(expiry_date >= ${ae.literal(ut(t))} OR expiry_date IS NULL)`).where("created_at",">=",Ue(r)).where("created_at","<=",Ue(t)).executeTakeFirst(),s=await W.selectFrom("gift_cards").select(W.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(ae`(expiry_date >= ${ae.literal(ut(o))} OR expiry_date IS NULL)`).where("created_at",">=",Ue(o)).where("created_at","<=",Ue(n)).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,d=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:d,days_range:e}}async function kc(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await W.selectFrom("gift_cards").select([W.fn.sum("initial_balance").as("total_initial"),W.fn.sum("current_balance").as("total_balance"),W.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(ae`(expiry_date >= ${ae.literal(ut(t))} OR expiry_date IS NULL)`).where("created_at",">=",Ue(r)).where("created_at","<=",Ue(t)).executeTakeFirst(),s=await W.selectFrom("gift_cards").select([W.fn.sum("initial_balance").as("total_initial"),W.fn.sum("current_balance").as("total_balance"),W.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(ae`(expiry_date >= ${ae.literal(ut(o))} OR expiry_date IS NULL)`).where("created_at",">=",Ue(o)).where("created_at","<=",Ue(n)).executeTakeFirst(),i=Number(a?.total_initial||0),u=Number(a?.total_balance||0),c=Number(a?.card_count||0),d=Number(s?.total_initial||0),m=Number(s?.total_balance||0),l=Number(s?.card_count||0),y=i>0?(i-u)/i*100:0,g=d>0?(d-m)/d*100:0,p=c>0?i/c:0,b=c>0?u/c:0,h=i-d,f=u-m,x=c-l,D=d!==0?h/d*100:i>0?100:0,v=m!==0?f/m*100:u>0?100:0,F=l!==0?x/l*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:p,average_remaining_balance:b},previous_period:{total_initial_value:d,total_remaining_balance:m,utilization_rate:g,card_count:l},comparison:{initial_value:{difference:h,percentage:Math.abs(D),is_increase:h>=0},balance:{difference:f,percentage:Math.abs(v),is_increase:f>=0},card_count:{difference:x,percentage:Math.abs(F),is_increase:x>=0}},days_range:e}}async function Cc(){let{total_value:e}=await ue("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:e}}async function Tc(){let{total_balance:e}=await ue("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:e}}async function Ec(e){let t=await xr.deleteFrom("gift_cards").where("id","=",e).executeTakeFirst();return _(t)>0}async function Fc(e){if(!e.length)return 0;let t=await xr.deleteFrom("gift_cards").where("id","in",e).executeTakeFirst();return _(t)}async function Ic(){let e=Ac(new Date),t=await xr.deleteFrom("gift_cards").where("expiry_date","<",e).executeTakeFirst();return _(t)}async function Mc(e){if(!await Se(e))throw Error(`Gift card with ID ${e} not found`);return(await $g(xr.updateTable("gift_cards").set({is_active:!1,status:"DEACTIVATED",updated_at:Ac(new Date)}).where("id","=",e))).length>0}var{randomUUIDv7:Bg}=globalThis.Bun;import{db as ta}from"@stacksjs/database/runtime";import{HttpError as Nc}from"@stacksjs/error-handling";import{isUniqueViolation as Ug}from"@stacksjs/orm";async function Oc(e){let t=e,r={...e,current_balance:t.current_balance??t.initial_balance,status:e.status||"ACTIVE",is_active:t.is_active??!0,uuid:Bg()};try{let n=await ta.insertInto("gift_cards").values(r).executeTakeFirst(),o=ve(n);if(o!==void 0){let s=await ta.selectFrom("gift_cards").where("id","=",o).selectAll().executeTakeFirst();return w(s)}let a=await ta.selectFrom("gift_cards").where("uuid","=",r.uuid).selectAll().executeTakeFirst();return w(a,!0)}catch(n){if(n instanceof Nc)throw n;if(Ug(n))throw new Nc(409,"A gift card with this code already exists");if(n instanceof Error)throw Error(`Failed to create gift card: ${n.message}`);throw n}}import{db as Uc,mutationCount as Jg,parseSqlDateTime as $c,sqlHelpers as Wg}from"@stacksjs/database/runtime";import{env as Lg}from"@stacksjs/env";import{HttpError as Bc}from"@stacksjs/error-handling";import{formatDate as Jc,isUniqueViolation as jg}from"@stacksjs/orm";async function Wc(e,t){if(!await Se(e))return;try{return await Uc.updateTable("gift_cards").set({...t,updated_at:Jc(new Date)}).where("id","=",e).execute(),await Se(e)}catch(n){if(n instanceof Bc)throw n;if(jg(n))throw new Bc(409,"A gift card with this code already exists");if(n instanceof Error)throw Error(`Failed to update gift card: ${n.message}`);throw n}}async function Lc(e,t){if(!Number.isFinite(t))throw Error(`Gift card balance adjustment must be a finite number, got ${t}`);let r=Wg(Lg.DB_CONNECTION||"sqlite"),n=r.param,o=Jc(new Date),a=t<0,s=t>0,i=s?`(status = 'ACTIVE' OR (status = 'USED' AND is_reloadable = ${r.boolTrue}))`:"status = 'ACTIVE'",u=[],c=(p)=>(u.push(p),n(u.length)),d=await Uc.unsafe(`UPDATE gift_cards
9
9
  SET status = CASE WHEN current_balance + ${c(t)} = 0 THEN 'USED' WHEN 1 = 0 THEN status ELSE 'ACTIVE' END,
10
10
  current_balance = current_balance + ${c(t)},
11
11
  ${a?`last_used_date = ${c(o)},
@@ -14,15 +14,15 @@ var uy=Object.defineProperty;var cy=(e)=>e;function dy(e,t){this[e]=cy.bind(null
14
14
  AND is_active = ${r.boolTrue}
15
15
  AND ${i}
16
16
  AND (expiry_date IS NULL OR expiry_date >= ${c(o)})
17
- AND current_balance + ${c(t)} >= 0`,u);if(Ug(d)>0)return await Se(e);let m=await Se(e);if(!m)throw Error(`Gift card with ID ${e} not found`);let l=m;if(!l.is_active&&!l.isActive)throw Error("Gift card is not active");if(m.status==="USED"&&s&&!(l.is_reloadable??l.isReloadable))throw Error("Gift card is not reloadable");if(m.status!=="ACTIVE")throw Error("Gift card is not active");let y=Oc(l.expiry_date??l.expiryDate),g=Oc(o);if(y&&g&&y.getTime()<g.getTime())throw Error("Gift card has expired");if(t===0&&Number(l.current_balance??l.currentBalance)>=0)return m;throw Error("Insufficient gift card balance")}var ba={};E(ba,{bulkDestroy:()=>Gc,bulkSoftDelete:()=>qc,calculateOrderMetrics:()=>Yc,canTransition:()=>Ue,cleanupAbandonedCarts:()=>yd,compareOrdersByPeriod:()=>Qc,destroy:()=>jc,downloadOrders:()=>Vc,emitForStatus:()=>ct,emitOrderCancelled:()=>Mt,emitOrderCreated:()=>vr,emitOrderDelivered:()=>ia,emitOrderPaid:()=>Ye,emitOrderRefunded:()=>Nt,emitOrderShipped:()=>sa,exportOrders:()=>Pr,fetchAll:()=>oa,fetchById:()=>ke,fetchDailyOrderTrends:()=>Xc,fetchRecent:()=>Kc,fetchStats:()=>Zc,findOrderByIdempotencyKey:()=>Dr,handleCommercePaymentEvent:()=>ga,handlePaymentFailed:()=>wa,handlePaymentSucceeded:()=>fa,handleRefundSucceeded:()=>ya,placeOrder:()=>sd,receivePaymentWebhook:()=>ld,recomputeOrderTotals:()=>pd,softDelete:()=>zc,store:()=>td,storeOrdersExport:()=>Hc,update:()=>id,updateDeliveryInfo:()=>cd,updateStatus:()=>ud,validateCartQuantities:()=>wd,validateCouponStacking:()=>fd,validateQuantityBounds:()=>ha});import{db as xr,matchedRows as Lc}from"@stacksjs/database/runtime";async function jc(e){try{let t=await xr.deleteFrom("orders").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete order: ${t.message}`);throw t}}async function zc(e){try{return(await Lc(xr.updateTable("orders").set({status:"CANCELED"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete order: ${t.message}`);throw t}}async function Gc(e){if(!e.length)return 0;try{let t=await xr.deleteFrom("orders").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete orders: ${t.message}`);throw t}}async function qc(e){if(!e.length)return 0;try{return(await Lc(xr.updateTable("orders").set({status:"CANCELED"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete orders: ${t.message}`);throw t}}import{db as Rr}from"@stacksjs/database/runtime";import{createSpreadsheet as jg}from"ts-spreadsheets";async function Pr(e="csv"){let t=await Gg(),r=qg(t);return jg(r,{type:e})}var zg=500;function ra(e,t=zg){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}function na(e){let t=new Set;for(let r of e){let n=Number(r);if(Number.isSafeInteger(n)&&n>0)t.add(n)}return[...t]}async function Gg(){let e=await Rr.selectFrom("orders").selectAll().orderBy("id","asc").execute();if(e.length===0)return[];let t=na(e.map((i)=>i.id)),r=na(e.map((i)=>i.customer_id)),n=new Map;for(let i of ra(r)){let u=await Rr.selectFrom("customers").where("id","in",i).select(["id","name","email"]).execute();for(let c of u)n.set(Number(c.id),c)}let o=[];for(let i of ra(t)){let u=await Rr.selectFrom("order_items").where("order_id","in",i).select(["id","order_id","product_id","quantity","price"]).orderBy("id","asc").execute();o.push(...u)}let a=new Map;for(let i of ra(na(o.map((u)=>u.product_id)))){let u=await Rr.selectFrom("products").where("id","in",i).select(["id","name"]).execute();for(let c of u)a.set(Number(c.id),c)}let s=new Map;for(let i of o){let u=Number(i.order_id),c={...i,product:a.get(Number(i.product_id))},d=s.get(u);if(d)d.push(c);else s.set(u,[c])}return e.map((i)=>{let u=s.get(Number(i.id))??[],c=n.get(Number(i.customer_id));return{...i,customer:c,customer_name:c?.name??null,customer_email:c?.email??null,order_items:u,totalItems:u.reduce((d,m)=>d+Number(m.quantity??0),0),totalPrice:u.reduce((d,m)=>d+Number(m.price??0)*Number(m.quantity??0),0)}})}function qg(e){let t=["Order ID","Customer","Date","Total","Status","Items"],r=e.map((n)=>{let o=typeof n.currency==="string"&&n.currency?n.currency:null,a=n.order_items?.map((s)=>`${s.product?.name||`Product #${s.product_id??"?"}`} (Qty: ${s.quantity}, Price: ${ne(Number(s.price??0),o)})`).join(" | ")||"No Items";return[n.id,n.customer?.name||n.customer_name||"N/A",n.created_at,ne(Number(n.total_amount??0),o),n.status,a]});return{headings:t,data:r}}async function Vc(e="csv",t){let r=await Pr(e),n=`orders_export_${new Date().toISOString().split("T")[0]}.${e}`;return r.download(t||n)}async function Hc(e="csv",t){let r=await Pr(e),n=`orders_export_${new Date().toISOString().split("T")[0]}.${e}`;r.store(t||n)}import{db as B}from"@stacksjs/database/runtime";async function oa(e){let t=B.selectFrom("orders").selectAll().orderBy("created_at","desc");if(e)t=t.limit(e);let r=P(await t.execute());return await Promise.all(r.map(async(n)=>{let o=await B.selectFrom("order_items").where("order_id","=",n.id).selectAll().execute();return{...n,items:o}}))}async function Kc(e=10){return oa(e)}async function ke(e){let t=await B.selectFrom("orders").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Zc(){let e=await B.selectFrom("orders").select(B.fn.count("id").as("count")).executeTakeFirst(),t=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).groupBy("status").execute(),r=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).groupBy("order_type").execute(),n=P(await B.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute()),o=await Promise.all(n.map(async(s)=>{let i=await B.selectFrom("order_items").where("order_id","=",s.id).selectAll().execute();return{...s,items:i}})),a=await B.selectFrom("orders").select(B.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(e?.count||0),by_status:t,by_type:r,recent:o,revenue:Number(a?.total||0)}}async function Qc(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).executeTakeFirst(),s=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",o.toISOString()).where("created_at","<=",n.toISOString()).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,d=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:d,days_range:e}}async function Yc(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).executeTakeFirst(),s=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",o.toISOString()).where("created_at","<=",n.toISOString()).executeTakeFirst(),i=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).groupBy("status").execute(),u=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).groupBy("order_type").execute(),c=Number(a?.total_orders||0),d=Number(a?.total_revenue||0),m=c>0?d/c:0,l=Number(s?.total_orders||0),y=Number(s?.total_revenue||0),g=l>0?y/l:0,p=c-l,b=d-y,h=m-g,f=l!==0?p/l*100:c>0?100:0,x=y!==0?b/y*100:d>0?100:0,D=g!==0?h/g*100:m>0?100:0;return{current_period:{total_orders:c,total_revenue:d,average_order_value:m,orders_by_status:i.map((v)=>({status:v.status,count:Number(v.count)})),orders_by_type:u.map((v)=>({order_type:v.order_type,count:Number(v.count)}))},previous_period:{total_orders:l,total_revenue:y,average_order_value:g},comparison:{orders:{difference:p,percentage:Math.abs(f),is_increase:p>=0},revenue:{difference:b,percentage:Math.abs(x),is_increase:b>=0},average_order_value:{difference:h,percentage:Math.abs(D),is_increase:h>=0}},days_range:e}}async function Xc(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=await B.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).orderBy("created_at","asc").execute(),o=new Map;for(let a of n){let s=(a.created_at||"").split("T")[0]||"unknown",i=o.get(s)||{order_count:0,revenue:0};i.order_count++,i.revenue+=Number(a.total_amount||0),o.set(s,i)}return Array.from(o.entries()).map(([a,s])=>({date:a,order_count:s.order_count,revenue:s.revenue}))}var{randomUUIDv7:Vg}=globalThis.Bun;import{db as aa}from"@stacksjs/database/runtime";import{formatDate as ed}from"@stacksjs/orm";async function td(e){let t={...e,status:e.status||"PENDING",uuid:Vg(),created_at:ed(new Date),updated_at:ed(new Date)};try{let r=await aa.insertInto("orders").values(t).executeTakeFirst(),n=ve(r);if(n!==void 0){let a=await aa.selectFrom("orders").where("id","=",n).selectAll().executeTakeFirst();return w(a,!0)}let o=await aa.selectFrom("orders").where("uuid","=",t.uuid).selectAll().executeTakeFirst();return w(o,!0)}catch(r){if(r instanceof Error)throw Error(`Failed to create order: ${r.message}`);throw r}}var{randomUUIDv7:rd}=globalThis.Bun;import{db as ca}from"@stacksjs/database/runtime";dt();import{formatDate as Xg,isUniqueViolation as nd}from"@stacksjs/orm";import{sqlHelpers as Zg}from"@stacksjs/database/runtime";import{env as Qg}from"@stacksjs/env";function Yg(e,t,r,n){let o=Zg(e).param;return{query:`UPDATE products
17
+ AND current_balance + ${c(t)} >= 0`,u);if(Jg(d)>0)return await Se(e);let m=await Se(e);if(!m)throw Error(`Gift card with ID ${e} not found`);let l=m;if(!l.is_active&&!l.isActive)throw Error("Gift card is not active");if(m.status==="USED"&&s&&!(l.is_reloadable??l.isReloadable))throw Error("Gift card is not reloadable");if(m.status!=="ACTIVE")throw Error("Gift card is not active");let y=$c(l.expiry_date??l.expiryDate),g=$c(o);if(y&&g&&y.getTime()<g.getTime())throw Error("Gift card has expired");if(t===0&&Number(l.current_balance??l.currentBalance)>=0)return m;throw Error("Insufficient gift card balance")}var _a={};E(_a,{bulkDestroy:()=>qc,bulkSoftDelete:()=>Vc,calculateOrderMetrics:()=>Xc,canTransition:()=>Je,cleanupAbandonedCarts:()=>gd,compareOrdersByPeriod:()=>Yc,destroy:()=>zc,downloadOrders:()=>Hc,emitForStatus:()=>ct,emitOrderCancelled:()=>Nt,emitOrderCreated:()=>Dr,emitOrderDelivered:()=>ua,emitOrderPaid:()=>Ye,emitOrderRefunded:()=>Ot,emitOrderShipped:()=>ia,exportOrders:()=>vr,fetchAll:()=>aa,fetchById:()=>ke,fetchDailyOrderTrends:()=>ed,fetchRecent:()=>Zc,fetchStats:()=>Qc,findOrderByIdempotencyKey:()=>Sr,handleCommercePaymentEvent:()=>ha,handlePaymentFailed:()=>ya,handlePaymentSucceeded:()=>wa,handleRefundSucceeded:()=>ga,placeOrder:()=>id,receivePaymentWebhook:()=>md,recomputeOrderTotals:()=>fd,softDelete:()=>Gc,store:()=>rd,storeOrdersExport:()=>Kc,update:()=>ud,updateDeliveryInfo:()=>dd,updateStatus:()=>cd,validateCartQuantities:()=>yd,validateCouponStacking:()=>wd,validateQuantityBounds:()=>ba});import{db as Rr,matchedRows as jc}from"@stacksjs/database/runtime";async function zc(e){try{let t=await Rr.deleteFrom("orders").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete order: ${t.message}`);throw t}}async function Gc(e){try{return(await jc(Rr.updateTable("orders").set({status:"CANCELED"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete order: ${t.message}`);throw t}}async function qc(e){if(!e.length)return 0;try{let t=await Rr.deleteFrom("orders").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete orders: ${t.message}`);throw t}}async function Vc(e){if(!e.length)return 0;try{return(await jc(Rr.updateTable("orders").set({status:"CANCELED"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete orders: ${t.message}`);throw t}}import{db as Pr}from"@stacksjs/database/runtime";import{createSpreadsheet as zg}from"ts-spreadsheets";async function vr(e="csv"){let t=await qg(),r=Vg(t);return zg(r,{type:e})}var Gg=500;function na(e,t=Gg){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}function oa(e){let t=new Set;for(let r of e){let n=Number(r);if(Number.isSafeInteger(n)&&n>0)t.add(n)}return[...t]}async function qg(){let e=await Pr.selectFrom("orders").selectAll().orderBy("id","asc").execute();if(e.length===0)return[];let t=oa(e.map((i)=>i.id)),r=oa(e.map((i)=>i.customer_id)),n=new Map;for(let i of na(r)){let u=await Pr.selectFrom("customers").where("id","in",i).select(["id","name","email"]).execute();for(let c of u)n.set(Number(c.id),c)}let o=[];for(let i of na(t)){let u=await Pr.selectFrom("order_items").where("order_id","in",i).select(["id","order_id","product_id","quantity","price"]).orderBy("id","asc").execute();o.push(...u)}let a=new Map;for(let i of na(oa(o.map((u)=>u.product_id)))){let u=await Pr.selectFrom("products").where("id","in",i).select(["id","name"]).execute();for(let c of u)a.set(Number(c.id),c)}let s=new Map;for(let i of o){let u=Number(i.order_id),c={...i,product:a.get(Number(i.product_id))},d=s.get(u);if(d)d.push(c);else s.set(u,[c])}return e.map((i)=>{let u=s.get(Number(i.id))??[],c=n.get(Number(i.customer_id));return{...i,customer:c,customer_name:c?.name??null,customer_email:c?.email??null,order_items:u,totalItems:u.reduce((d,m)=>d+Number(m.quantity??0),0),totalPrice:u.reduce((d,m)=>d+Number(m.price??0)*Number(m.quantity??0),0)}})}function Vg(e){let t=["Order ID","Customer","Date","Total","Status","Items"],r=e.map((n)=>{let o=typeof n.currency==="string"&&n.currency?n.currency:null,a=n.order_items?.map((s)=>`${s.product?.name||`Product #${s.product_id??"?"}`} (Qty: ${s.quantity}, Price: ${ne(Number(s.price??0),o)})`).join(" | ")||"No Items";return[n.id,n.customer?.name||n.customer_name||"N/A",n.created_at,ne(Number(n.total_amount??0),o),n.status,a]});return{headings:t,data:r}}async function Hc(e="csv",t){let r=await vr(e),n=`orders_export_${new Date().toISOString().split("T")[0]}.${e}`;return r.download(t||n)}async function Kc(e="csv",t){let r=await vr(e),n=`orders_export_${new Date().toISOString().split("T")[0]}.${e}`;r.store(t||n)}import{db as B}from"@stacksjs/database/runtime";async function aa(e){let t=B.selectFrom("orders").selectAll().orderBy("created_at","desc");if(e)t=t.limit(e);let r=P(await t.execute());return await Promise.all(r.map(async(n)=>{let o=await B.selectFrom("order_items").where("order_id","=",n.id).selectAll().execute();return{...n,items:o}}))}async function Zc(e=10){return aa(e)}async function ke(e){let t=await B.selectFrom("orders").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Qc(){let e=await B.selectFrom("orders").select(B.fn.count("id").as("count")).executeTakeFirst(),t=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).groupBy("status").execute(),r=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).groupBy("order_type").execute(),n=P(await B.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute()),o=await Promise.all(n.map(async(s)=>{let i=await B.selectFrom("order_items").where("order_id","=",s.id).selectAll().execute();return{...s,items:i}})),a=await B.selectFrom("orders").select(B.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(e?.count||0),by_status:t,by_type:r,recent:o,revenue:Number(a?.total||0)}}async function Yc(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).executeTakeFirst(),s=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",o.toISOString()).where("created_at","<=",n.toISOString()).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,d=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:d,days_range:e}}async function Xc(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).executeTakeFirst(),s=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",o.toISOString()).where("created_at","<=",n.toISOString()).executeTakeFirst(),i=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).groupBy("status").execute(),u=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).groupBy("order_type").execute(),c=Number(a?.total_orders||0),d=Number(a?.total_revenue||0),m=c>0?d/c:0,l=Number(s?.total_orders||0),y=Number(s?.total_revenue||0),g=l>0?y/l:0,p=c-l,b=d-y,h=m-g,f=l!==0?p/l*100:c>0?100:0,x=y!==0?b/y*100:d>0?100:0,D=g!==0?h/g*100:m>0?100:0;return{current_period:{total_orders:c,total_revenue:d,average_order_value:m,orders_by_status:i.map((v)=>({status:v.status,count:Number(v.count)})),orders_by_type:u.map((v)=>({order_type:v.order_type,count:Number(v.count)}))},previous_period:{total_orders:l,total_revenue:y,average_order_value:g},comparison:{orders:{difference:p,percentage:Math.abs(f),is_increase:p>=0},revenue:{difference:b,percentage:Math.abs(x),is_increase:b>=0},average_order_value:{difference:h,percentage:Math.abs(D),is_increase:h>=0}},days_range:e}}async function ed(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=await B.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).orderBy("created_at","asc").execute(),o=new Map;for(let a of n){let s=(a.created_at||"").split("T")[0]||"unknown",i=o.get(s)||{order_count:0,revenue:0};i.order_count++,i.revenue+=Number(a.total_amount||0),o.set(s,i)}return Array.from(o.entries()).map(([a,s])=>({date:a,order_count:s.order_count,revenue:s.revenue}))}var{randomUUIDv7:Hg}=globalThis.Bun;import{db as sa}from"@stacksjs/database/runtime";import{formatDate as td}from"@stacksjs/orm";async function rd(e){let t={...e,status:e.status||"PENDING",uuid:Hg(),created_at:td(new Date),updated_at:td(new Date)};try{let r=await sa.insertInto("orders").values(t).executeTakeFirst(),n=ve(r);if(n!==void 0){let a=await sa.selectFrom("orders").where("id","=",n).selectAll().executeTakeFirst();return w(a,!0)}let o=await sa.selectFrom("orders").where("uuid","=",t.uuid).selectAll().executeTakeFirst();return w(o,!0)}catch(r){if(r instanceof Error)throw Error(`Failed to create order: ${r.message}`);throw r}}var{randomUUIDv7:nd}=globalThis.Bun;import{db as da}from"@stacksjs/database/runtime";dt();import{formatDate as eh,isUniqueViolation as od}from"@stacksjs/orm";import{sqlHelpers as Qg}from"@stacksjs/database/runtime";import{env as Yg}from"@stacksjs/env";function Xg(e,t,r,n){let o=Qg(e).param;return{query:`UPDATE products
18
18
  SET inventory_count = inventory_count + ${o(1)},
19
19
  updated_at = ${o(2)}
20
20
  WHERE id = ${o(3)}
21
- AND inventory_count + ${o(4)} >= 0`,parameters:[r,n,t,r]}}async function ua(e,t,r,n){let o=Yg(Qg.DB_CONNECTION||"sqlite",t,r,n),a=await e.unsafe(o.query,o.parameters);return _(a)}var od=!1;function ad(e){let t=e,r=t?.message??"";return t?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function Dr(e){try{let t=await ca.selectFrom("order_idempotency").where("idempotency_key","=",e).selectAll().executeTakeFirst();if(!t)return null;return await ca.selectFrom("orders").where("id","=",t.order_id).selectAll().executeTakeFirst()??null}catch(t){if(ad(t)){if(!od)od=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw t}}async function sd(e){if(e.idempotencyKey){let t=await Dr(e.idempotencyKey);if(t)return{ok:!0,order:t}}try{let t=await ca.transaction(async(r)=>{let n=Xg(new Date),o=rd(),a={...e.order,status:e.order.status||"PENDING",uuid:o,created_at:n,updated_at:n};await r.insertInto("orders").values(a).executeTakeFirst();let s=w(await r.selectFrom("orders").where("uuid","=",o).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(e.items&&e.items.length>0){let m=e.items.map((l)=>{if(!Number.isInteger(l.productId)||l.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(l.quantity)||l.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(l.price)||l.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:l.productId,quantity:l.quantity,price:l.price,special_instructions:l.specialInstructions||null,created_at:n,updated_at:n}});await r.insertInto("order_items").values(m).execute(),u=P(await r.selectFrom("order_items").where("order_id","=",i).selectAll().execute())}let c;if(e.payment)try{let m=rd();if(await r.insertInto("payments").values({...e.payment,order_id:i,uuid:m,created_at:n,updated_at:n}).executeTakeFirst(),c=w(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(nd(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(e.inventory&&e.inventory.length>0)for(let m=0;m<e.inventory.length;m++){let{id:l,delta:y}=e.inventory[m];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 ua(r,l,y,n))throw Object.assign(Error(`inventory adjust failed for product ${l}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(e.idempotencyKey)try{await r.insertInto("order_idempotency").values({idempotency_key:e.idempotencyKey,order_id:i,created_at:n}).execute()}catch(m){if(nd(m))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!ad(m))throw m}let d=w(await r.selectFrom("orders").where("id","=",i).selectAll().executeTakeFirst(),!0);if(!d)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:d,items:u,payment:c}});if(vr(t.order),t.payment)Ye(t.order,t.payment);return{ok:!0,order:t.order,items:t.items,payment:t.payment}}catch(t){if(t?.__placeFail){if(t.reason==="duplicate-idempotency-key"&&e.idempotencyKey){let r=await Dr(e.idempotencyKey);if(r)return{ok:!0,order:r}}return{ok:!1,reason:t.reason,failedAt:t.failedAt,error:t}}throw t}}dt();import{db as da}from"@stacksjs/database/runtime";import{formatDate as la}from"@stacksjs/orm";dt();async function id(e,t){if(!await ke(e))return;try{return await da.updateTable("orders").set({...t,updated_at:la(new Date)}).where("id","=",e).execute(),await ke(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update order: ${n.message}`);throw n}}async function ud(e,t){let r=await ke(e);if(!r)throw Error(`Order with ID ${e} not found`);let n=r.status??"PENDING";if(!Ue(n,t))throw Error(`[commerce/orders] illegal status transition ${n} \u2192 ${t}`);try{await da.updateTable("orders").set({status:t,updated_at:la(new Date)}).where("id","=",e).execute();let o=await ke(e);if(o)ct(t,o);return o}catch(o){if(o instanceof Error)throw TypeError(`Failed to update order status: ${o.message}`);throw o}}async function cd(e,t,r){let n=await ke(e);if(!n)throw Error(`Order with ID ${e} not found`);let o={updated_at:la(new Date)};if(t!==void 0)o.delivery_address=t;if(r!==void 0)o.estimated_delivery_time=r;if(Object.keys(o).length===1)return n;try{return await da.updateTable("orders").set(o).where("id","=",e).execute(),await ke(e)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery information: ${a.message}`);throw a}}dt();import{db as Ot}from"@stacksjs/database/runtime";import{formatDate as Sr}from"@stacksjs/orm";async function ma(e){let t=await Ot.selectFrom("payments").where("transaction_id","=",e).selectAll().executeTakeFirst();if(!t)return null;return await Ot.selectFrom("orders").where("id","=",t.order_id).selectAll().executeTakeFirst()??null}var dd=!1;async function pa(e,t){try{let r=Sr(new Date);return await t.insertInto("payment_webhook_events").values({provider:e.provider,event_id:e.id,processed_at:r,created_at:r}).execute(),!0}catch(r){if(th(r))return!1;if(eh(r)){if(!dd)dd=!0,console.warn("[commerce/webhook] payment_webhook_events table missing - provider retries will be applied again. Run `buddy migrate` to enable dedup.");return!0}throw r}}function eh(e){let t=e,r=t?.message??"";return t?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}function th(e){let t=e,r=t?.message??"";return t?.code==="23505"||r.includes("UNIQUE constraint")||r.includes("Duplicate entry")||/duplicate key value/i.test(r)}async function fa(e){let t=e.reference;if(!t)return;await Ot.transaction(async(n)=>{if(!await pa(e,n))return;let a=await n.selectFrom("payments").where("transaction_id","=",t).selectAll().executeTakeFirst();if(!a)return;let s=Sr(new Date);await n.updateTable("payments").set({status:"succeeded",updated_at:s}).where("id","=",a.id).execute();let i=await n.selectFrom("orders").where("id","=",a.order_id).selectAll().executeTakeFirst();if(i&&i.status==="PENDING")await n.updateTable("orders").set({status:"PROCESSING",updated_at:s}).where("id","=",i.id).execute()});let r=await ma(t);if(r)await Ye(r)}async function wa(e){let t=e.reference;if(!t)return;let r=e.reason??"payment failed";await Ot.transaction(async(o)=>{if(!await pa(e,o))return;let s=await o.selectFrom("payments").where("transaction_id","=",t).selectAll().executeTakeFirst();if(!s)return;let i=Sr(new Date);await o.updateTable("payments").set({status:"failed",failure_reason:r.slice(0,1000),updated_at:i}).where("id","=",s.id).execute();let u=await o.selectFrom("orders").where("id","=",s.order_id).selectAll().executeTakeFirst();if(u&&u.status==="PENDING")await o.updateTable("orders").set({status:"CANCELLED",updated_at:i}).where("id","=",u.id).execute()});let n=await ma(t);if(n)await Mt(n,r)}async function ya(e){let t=e.reference;if(!t)return;let r=e.refundedTotal?.amount,n=r??e.amount?.amount??0;if(!Number.isSafeInteger(n)||n<=0)return;let o=!1,a=!1,s=0;if(await Ot.transaction(async(u)=>{if(!await pa(e,u))return;let d=await u.selectFrom("payments").where("transaction_id","=",t).selectAll().executeTakeFirst();if(!d)return;let m=Number(d.refund_amount??0);if(s=r===void 0?n:r-m,s<=0)return;let l=m+s;if(l>Number(d.amount)){console.warn(`[commerce/webhook] ${e.provider} refunded ${s} of payment ${d.id}, which has ${Number(d.amount)-m} left to refund; not recorded.`);return}o=l===Number(d.amount);let y=Sr(new Date);if(await u.updateTable("payments").set({status:o?"refunded":"partiallyRefunded",refund_amount:l,updated_at:y}).where("id","=",d.id).execute(),a=!0,!o)return;let g=await u.selectFrom("orders").where("id","=",d.order_id).selectAll().executeTakeFirst();if(g&&Ue(g.status,"REFUNDED"))await u.updateTable("orders").set({status:"REFUNDED",updated_at:y}).where("id","=",g.id).execute()}),!a)return;let i=await ma(t);if(i&&o)await Nt(i,s)}async function ga(e){switch(e.type){case"payment.succeeded":return await fa(e),!0;case"payment.failed":return await wa(e),!0;case"refund.succeeded":return await ya(e),!0;default:return!1}}async function ld(e,t){let{paymentDriver:r,WebhookNotConfiguredError:n,WebhookSignatureError:o}=await import("@stacksjs/payments"),a=t??r(),s;try{s=await a.verifyWebhook({payload:await e.text(),headers:e.headers})}catch(i){if(i instanceof n)return Response.json({ok:!1,reason:"missing-config"},{status:401});if(i instanceof o)return Response.json({ok:!1,reason:"invalid-signature"},{status:400});throw i}for(let i of s)await ga(i);return a.acknowledgeWebhook()}import{db as md}from"@stacksjs/database/runtime";async function rh(e){if(e.length===0)return new Map;let t=await md.selectFrom("products").where("id","in",e).select(["id","price"]).execute(),r=new Map;for(let n of t){let o=Number(n.price);if(Number.isFinite(o))r.set(n.id,Math.round(o))}return r}async function nh(e){try{let t=await md.selectFrom("tax_rates").where("id","=",e).select(["rate"]).executeTakeFirst(),r=Number(t?.rate??0);return Number.isFinite(r)?r:0}catch{return 0}}async function pd(e){let t=e.items.map((g)=>g.productId),r=await rh(t),n=e.taxRateId!=null?await nh(e.taxRateId):0,o=0,a=[];for(let g of e.items){let p=g.unitPriceCents??r.get(g.productId)??0,b=Math.round(p*g.quantity);o+=b,a.push({productId:g.productId,quantity:g.quantity,unitPriceCents:p,lineCents:b})}let s=Math.max(0,e.discountCents??0),i=Math.max(0,o-s),u=Math.round(i*n),c=Math.max(0,e.shippingCents??0),d=o-s+u+c,m=e.maxDriftCents??5,l=!1,y=0;if(e.clientTotalCents!=null)y=Math.abs(d-e.clientTotalCents),l=y>m;return{subtotalCents:o,discountCents:s,taxCents:u,shippingCents:c,totalCents:d,resolvedItems:a,priceChanged:l,diffCents:y}}import{db as kr,sqlHelpers as oh}from"@stacksjs/database/runtime";import{env as ah}from"@stacksjs/env";function fd(e,t={}){let r=e.length;if(r<=1)return{ok:!0,count:r};if(!t.allowMultiple)return{ok:!1,count:r,reason:"multiple-not-allowed"};let n=t.maxStacked??Number.POSITIVE_INFINITY;if(r>n)return{ok:!1,count:r,reason:"exceeds-max-stacked"};return{ok:!0,count:r}}async function ha(e,t){if(!Number.isFinite(t)||t<=0)return{ok:!1,productId:e,quantity:t,reason:"non-positive"};let r;try{r=await kr.selectFrom("products").where("id","=",e).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:e,quantity:t}}if(!r)return{ok:!1,productId:e,quantity:t,reason:"product-missing"};let n=r.min_order_qty??null,o=r.max_order_qty??null;if(n!=null&&t<n)return{ok:!1,productId:e,quantity:t,reason:"below-min",bound:n};if(o!=null&&t>o)return{ok:!1,productId:e,quantity:t,reason:"above-max",bound:o};return{ok:!0,productId:e,quantity:t}}async function wd(e){for(let r of e){let n=await ha(r.productId,r.quantity);if(!n.ok)return n}let t=e[e.length-1]??{productId:0,quantity:0};return{ok:!0,productId:t.productId,quantity:t.quantity}}async function yd(e={}){let t=e.olderThanDays??30,r=e.limit??1000,o=new Date(Date.now()-t*24*60*60*1000).toISOString().slice(0,19).replace("T"," "),a=oh(ah.DB_CONNECTION||"sqlite").param;try{let s=await kr.unsafe(`DELETE FROM carts WHERE updated_at < ${a(1)} AND id IN (SELECT id FROM carts WHERE updated_at < ${a(2)} LIMIT ${a(3)})`,[o,o,r]);return{deleted:_(s),cutoffAt:o}}catch{try{let s=await kr.selectFrom("carts").where("updated_at","<",o).select(["id"]).limit(r).execute();if(s.length===0)return{deleted:0,cutoffAt:o};let i=s.map((c)=>c.id),u=await kr.deleteFrom("carts").where("id","in",i).execute();return{deleted:_(u),cutoffAt:o}}catch{return{deleted:0,cutoffAt:o}}}}var _a={};E(_a,{bulkDestroy:()=>bd,destroy:()=>hd,fetchAll:()=>_d,fetchById:()=>Xe,fetchMonthlyPaymentTrends:()=>Pd,fetchPaymentStats:()=>xd,fetchPaymentStatsByMethod:()=>Rd,recordRefund:()=>Ad,store:()=>Sd,update:()=>Td});import{db as gd}from"@stacksjs/database/runtime";async function hd(e){try{let t=await gd.deleteFrom("payments").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete payment: ${t.message}`);throw t}}async function bd(e){if(!e.length)return 0;try{let t=await gd.deleteFrom("payments").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete payments: ${t.message}`);throw t}}import{db as K}from"@stacksjs/database/runtime";import{formatDate as le}from"@stacksjs/orm";async function _d(){let e=await K.selectFrom("payments").selectAll().execute();return P(e)}async function Xe(e){let t=await K.selectFrom("payments").selectAll().where("id","=",e).executeTakeFirst();return w(t,!0)}async function xd(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await K.selectFrom("payments").select([K.fn.count("id").as("transaction_count"),K.fn.sum("amount").as("total_revenue")]).where("created_at",">=",le(r)).where("created_at","<=",le(t)).where("status","=","completed").executeTakeFirst(),s=await K.selectFrom("payments").select([K.fn.count("id").as("transaction_count"),K.fn.sum("amount").as("total_revenue")]).where("created_at",">=",le(o)).where("created_at","<=",le(n)).where("status","=","completed").executeTakeFirst(),i=await K.selectFrom("payments").select(K.fn.count("id").as("count")).where("created_at",">=",le(r)).where("created_at","<=",le(t)).executeTakeFirst(),u=Number(a?.transaction_count||0),c=Number(a?.total_revenue||0),d=u>0?c/u:0,m=Number(s?.transaction_count||0),l=Number(s?.total_revenue||0),y=m>0?l/m:0,g=u-m,p=c-l,b=d-y,h=m>0?g/m*100:u>0?100:0,f=l>0?p/l*100:c>0?100:0,x=y>0?b/y*100:d>0?100:0,D=Number(i?.count||0),v=D>0?u/D*100:0;return{total_transactions:u,total_revenue:c,average_transaction:d,successful_rate:v,comparison:{transactions:{difference:g,percentage:Math.abs(h),is_increase:g>=0},revenue:{difference:p,percentage:Math.abs(f),is_increase:p>=0},average:{difference:b,percentage:Math.abs(x),is_increase:b>=0}}}}async function Rd(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=await K.selectFrom("payments").select([K.fn.count("id").as("total_count"),K.fn.sum("amount").as("total_revenue")]).where("created_at",">=",le(r)).where("created_at","<=",le(t)).where("status","=","completed").executeTakeFirst(),o=Number(n?.total_count||0),a=await K.selectFrom("payments").select(["method",K.fn.count("id").as("count"),K.fn.sum("amount").as("revenue")]).where("created_at",">=",le(r)).where("created_at","<=",le(t)).where("status","=","completed").groupBy("method").execute(),s={};return a.forEach((i)=>{let u=Number(i.count||0),c=Number(i.revenue||0),d=o>0?u/o*100:0;s[i.method]={count:u,revenue:c,percentage_of_total:d}}),s}async function Pd(){let e=new Date,t=new Date(e);t.setMonth(e.getMonth()-11),t.setDate(1);let r=await K.selectFrom("payments").selectAll().where("created_at",">=",le(t)).where("status","=","completed").execute(),n={};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(!n[c])n[c]={year:i,month:u,transactions:0,revenue:0};n[c].transactions++,n[c].revenue+=Number(a.amount||0)}return Object.keys(n).sort().map((a)=>{let s=n[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:sh}=globalThis.Bun;import{db as vd}from"@stacksjs/database/runtime";import{HttpError as Dd}from"@stacksjs/error-handling";import{isUniqueViolation as ih}from"@stacksjs/orm";async function Sd(e){let t=sh(),r={...e,status:e.status||"pending",currency:e.currency||"USD",uuid:t};try{await vd.insertInto("payments").values(r).executeTakeFirst();let n=await vd.selectFrom("payments").where("uuid","=",t).selectAll().executeTakeFirst();return w(n,!0)}catch(n){if(n instanceof Dd)throw n;if(ih(n))throw new Dd(409,"A payment with this transaction ID already exists");if(n instanceof Error){if(n.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${n.message}`)}throw n}}import{db as kd,mutationCount as uh,sqlHelpers as ch}from"@stacksjs/database/runtime";import{env as dh}from"@stacksjs/env";import{formatDate as Cd}from"@stacksjs/orm";async function Td(e,t){if(!await Xe(e))return;try{return await kd.updateTable("payments").set({...t,updated_at:Cd(new Date)}).where("id","=",e).execute(),await Xe(e)}catch(n){if(n instanceof Error){if(n.message.includes("Duplicate entry")&&n.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${n.message}`)}throw n}}var lh=new Set(["completed","succeeded","partiallyRefunded"]);async function Ad(e,t){if(!Number.isSafeInteger(e)||e<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger(t)||t<=0)throw TypeError("Refund amount must be a positive integer in minor units");let n=ch(dh.DB_CONNECTION||"sqlite").param,o=Cd(new Date),a=await kd.unsafe(`UPDATE payments
21
+ AND inventory_count + ${o(4)} >= 0`,parameters:[r,n,t,r]}}async function ca(e,t,r,n){let o=Xg(Yg.DB_CONNECTION||"sqlite",t,r,n),a=await e.unsafe(o.query,o.parameters);return _(a)}var ad=!1;function sd(e){let t=e,r=t?.message??"";return t?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function Sr(e){try{let t=await da.selectFrom("order_idempotency").where("idempotency_key","=",e).selectAll().executeTakeFirst();if(!t)return null;return await da.selectFrom("orders").where("id","=",t.order_id).selectAll().executeTakeFirst()??null}catch(t){if(sd(t)){if(!ad)ad=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw t}}async function id(e){if(e.idempotencyKey){let t=await Sr(e.idempotencyKey);if(t)return{ok:!0,order:t}}try{let t=await da.transaction(async(r)=>{let n=eh(new Date),o=nd(),a={...e.order,status:e.order.status||"PENDING",uuid:o,created_at:n,updated_at:n};await r.insertInto("orders").values(a).executeTakeFirst();let s=w(await r.selectFrom("orders").where("uuid","=",o).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(e.items&&e.items.length>0){let m=e.items.map((l)=>{if(!Number.isInteger(l.productId)||l.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(l.quantity)||l.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(l.price)||l.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:l.productId,quantity:l.quantity,price:l.price,special_instructions:l.specialInstructions||null,created_at:n,updated_at:n}});await r.insertInto("order_items").values(m).execute(),u=P(await r.selectFrom("order_items").where("order_id","=",i).selectAll().execute())}let c;if(e.payment)try{let m=nd();if(await r.insertInto("payments").values({...e.payment,order_id:i,uuid:m,created_at:n,updated_at:n}).executeTakeFirst(),c=w(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(od(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(e.inventory&&e.inventory.length>0)for(let m=0;m<e.inventory.length;m++){let{id:l,delta:y}=e.inventory[m];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 ca(r,l,y,n))throw Object.assign(Error(`inventory adjust failed for product ${l}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(e.idempotencyKey)try{await r.insertInto("order_idempotency").values({idempotency_key:e.idempotencyKey,order_id:i,created_at:n}).execute()}catch(m){if(od(m))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!sd(m))throw m}let d=w(await r.selectFrom("orders").where("id","=",i).selectAll().executeTakeFirst(),!0);if(!d)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:d,items:u,payment:c}});if(Dr(t.order),t.payment)Ye(t.order,t.payment);return{ok:!0,order:t.order,items:t.items,payment:t.payment}}catch(t){if(t?.__placeFail){if(t.reason==="duplicate-idempotency-key"&&e.idempotencyKey){let r=await Sr(e.idempotencyKey);if(r)return{ok:!0,order:r}}return{ok:!1,reason:t.reason,failedAt:t.failedAt,error:t}}throw t}}dt();import{db as la}from"@stacksjs/database/runtime";import{formatDate as ma}from"@stacksjs/orm";dt();async function ud(e,t){if(!await ke(e))return;try{return await la.updateTable("orders").set({...t,updated_at:ma(new Date)}).where("id","=",e).execute(),await ke(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update order: ${n.message}`);throw n}}async function cd(e,t){let r=await ke(e);if(!r)throw Error(`Order with ID ${e} not found`);let n=r.status??"PENDING";if(!Je(n,t))throw Error(`[commerce/orders] illegal status transition ${n} \u2192 ${t}`);try{await la.updateTable("orders").set({status:t,updated_at:ma(new Date)}).where("id","=",e).execute();let o=await ke(e);if(o)ct(t,o);return o}catch(o){if(o instanceof Error)throw TypeError(`Failed to update order status: ${o.message}`);throw o}}async function dd(e,t,r){let n=await ke(e);if(!n)throw Error(`Order with ID ${e} not found`);let o={updated_at:ma(new Date)};if(t!==void 0)o.delivery_address=t;if(r!==void 0)o.estimated_delivery_time=r;if(Object.keys(o).length===1)return n;try{return await la.updateTable("orders").set(o).where("id","=",e).execute(),await ke(e)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery information: ${a.message}`);throw a}}dt();import{db as $t}from"@stacksjs/database/runtime";import{formatDate as kr}from"@stacksjs/orm";async function pa(e){let t=await $t.selectFrom("payments").where("transaction_id","=",e).selectAll().executeTakeFirst();if(!t)return null;return await $t.selectFrom("orders").where("id","=",t.order_id).selectAll().executeTakeFirst()??null}var ld=!1;async function fa(e,t){try{let r=kr(new Date);return await t.insertInto("payment_webhook_events").values({provider:e.provider,event_id:e.id,processed_at:r,created_at:r}).execute(),!0}catch(r){if(rh(r))return!1;if(th(r)){if(!ld)ld=!0,console.warn("[commerce/webhook] payment_webhook_events table missing - provider retries will be applied again. Run `buddy migrate` to enable dedup.");return!0}throw r}}function th(e){let t=e,r=t?.message??"";return t?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}function rh(e){let t=e,r=t?.message??"";return t?.code==="23505"||r.includes("UNIQUE constraint")||r.includes("Duplicate entry")||/duplicate key value/i.test(r)}async function wa(e){let t=e.reference;if(!t)return;await $t.transaction(async(n)=>{if(!await fa(e,n))return;let a=await n.selectFrom("payments").where("transaction_id","=",t).selectAll().executeTakeFirst();if(!a)return;let s=kr(new Date);await n.updateTable("payments").set({status:"succeeded",updated_at:s}).where("id","=",a.id).execute();let i=await n.selectFrom("orders").where("id","=",a.order_id).selectAll().executeTakeFirst();if(i&&i.status==="PENDING")await n.updateTable("orders").set({status:"PROCESSING",updated_at:s}).where("id","=",i.id).execute()});let r=await pa(t);if(r)await Ye(r)}async function ya(e){let t=e.reference;if(!t)return;let r=e.reason??"payment failed";await $t.transaction(async(o)=>{if(!await fa(e,o))return;let s=await o.selectFrom("payments").where("transaction_id","=",t).selectAll().executeTakeFirst();if(!s)return;let i=kr(new Date);await o.updateTable("payments").set({status:"failed",failure_reason:r.slice(0,1000),updated_at:i}).where("id","=",s.id).execute();let u=await o.selectFrom("orders").where("id","=",s.order_id).selectAll().executeTakeFirst();if(u&&u.status==="PENDING")await o.updateTable("orders").set({status:"CANCELLED",updated_at:i}).where("id","=",u.id).execute()});let n=await pa(t);if(n)await Nt(n,r)}async function ga(e){let t=e.reference;if(!t)return;let r=e.refundedTotal?.amount,n=r??e.amount?.amount??0;if(!Number.isSafeInteger(n)||n<=0)return;let o=!1,a=!1,s=0;if(await $t.transaction(async(u)=>{if(!await fa(e,u))return;let d=await u.selectFrom("payments").where("transaction_id","=",t).selectAll().executeTakeFirst();if(!d)return;let m=Number(d.refund_amount??0);if(s=r===void 0?n:r-m,s<=0)return;let l=m+s;if(l>Number(d.amount)){console.warn(`[commerce/webhook] ${e.provider} refunded ${s} of payment ${d.id}, which has ${Number(d.amount)-m} left to refund; not recorded.`);return}o=l===Number(d.amount);let y=kr(new Date);if(await u.updateTable("payments").set({status:o?"refunded":"partiallyRefunded",refund_amount:l,updated_at:y}).where("id","=",d.id).execute(),a=!0,!o)return;let g=await u.selectFrom("orders").where("id","=",d.order_id).selectAll().executeTakeFirst();if(g&&Je(g.status,"REFUNDED"))await u.updateTable("orders").set({status:"REFUNDED",updated_at:y}).where("id","=",g.id).execute()}),!a)return;let i=await pa(t);if(i&&o)await Ot(i,s)}async function ha(e){switch(e.type){case"payment.succeeded":return await wa(e),!0;case"payment.failed":return await ya(e),!0;case"refund.succeeded":return await ga(e),!0;default:return!1}}async function md(e,t){let{paymentDriver:r,WebhookNotConfiguredError:n,WebhookSignatureError:o}=await import("@stacksjs/payments"),a=t??r(),s;try{s=await a.verifyWebhook({payload:await e.text(),headers:e.headers})}catch(i){if(i instanceof n)return Response.json({ok:!1,reason:"missing-config"},{status:401});if(i instanceof o)return Response.json({ok:!1,reason:"invalid-signature"},{status:400});throw i}for(let i of s)await ha(i);return a.acknowledgeWebhook()}import{db as pd}from"@stacksjs/database/runtime";async function nh(e){if(e.length===0)return new Map;let t=await pd.selectFrom("products").where("id","in",e).select(["id","price"]).execute(),r=new Map;for(let n of t){let o=Number(n.price);if(Number.isFinite(o))r.set(n.id,Math.round(o))}return r}async function oh(e){try{let t=await pd.selectFrom("tax_rates").where("id","=",e).select(["rate"]).executeTakeFirst(),r=Number(t?.rate??0);return Number.isFinite(r)?r:0}catch{return 0}}async function fd(e){let t=e.items.map((g)=>g.productId),r=await nh(t),n=e.taxRateId!=null?await oh(e.taxRateId):0,o=0,a=[];for(let g of e.items){let p=g.unitPriceCents??r.get(g.productId)??0,b=Math.round(p*g.quantity);o+=b,a.push({productId:g.productId,quantity:g.quantity,unitPriceCents:p,lineCents:b})}let s=Math.max(0,e.discountCents??0),i=Math.max(0,o-s),u=Math.round(i*n),c=Math.max(0,e.shippingCents??0),d=o-s+u+c,m=e.maxDriftCents??5,l=!1,y=0;if(e.clientTotalCents!=null)y=Math.abs(d-e.clientTotalCents),l=y>m;return{subtotalCents:o,discountCents:s,taxCents:u,shippingCents:c,totalCents:d,resolvedItems:a,priceChanged:l,diffCents:y}}import{db as Cr,sqlHelpers as ah}from"@stacksjs/database/runtime";import{env as sh}from"@stacksjs/env";function wd(e,t={}){let r=e.length;if(r<=1)return{ok:!0,count:r};if(!t.allowMultiple)return{ok:!1,count:r,reason:"multiple-not-allowed"};let n=t.maxStacked??Number.POSITIVE_INFINITY;if(r>n)return{ok:!1,count:r,reason:"exceeds-max-stacked"};return{ok:!0,count:r}}async function ba(e,t){if(!Number.isFinite(t)||t<=0)return{ok:!1,productId:e,quantity:t,reason:"non-positive"};let r;try{r=await Cr.selectFrom("products").where("id","=",e).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:e,quantity:t}}if(!r)return{ok:!1,productId:e,quantity:t,reason:"product-missing"};let n=r.min_order_qty??null,o=r.max_order_qty??null;if(n!=null&&t<n)return{ok:!1,productId:e,quantity:t,reason:"below-min",bound:n};if(o!=null&&t>o)return{ok:!1,productId:e,quantity:t,reason:"above-max",bound:o};return{ok:!0,productId:e,quantity:t}}async function yd(e){for(let r of e){let n=await ba(r.productId,r.quantity);if(!n.ok)return n}let t=e[e.length-1]??{productId:0,quantity:0};return{ok:!0,productId:t.productId,quantity:t.quantity}}async function gd(e={}){let t=e.olderThanDays??30,r=e.limit??1000,o=new Date(Date.now()-t*24*60*60*1000).toISOString().slice(0,19).replace("T"," "),a=ah(sh.DB_CONNECTION||"sqlite").param;try{let s=await Cr.unsafe(`DELETE FROM carts WHERE updated_at < ${a(1)} AND id IN (SELECT id FROM carts WHERE updated_at < ${a(2)} LIMIT ${a(3)})`,[o,o,r]);return{deleted:_(s),cutoffAt:o}}catch{try{let s=await Cr.selectFrom("carts").where("updated_at","<",o).select(["id"]).limit(r).execute();if(s.length===0)return{deleted:0,cutoffAt:o};let i=s.map((c)=>c.id),u=await Cr.deleteFrom("carts").where("id","in",i).execute();return{deleted:_(u),cutoffAt:o}}catch{return{deleted:0,cutoffAt:o}}}}var xa={};E(xa,{bulkDestroy:()=>_d,destroy:()=>bd,fetchAll:()=>xd,fetchById:()=>Xe,fetchMonthlyPaymentTrends:()=>vd,fetchPaymentStats:()=>Rd,fetchPaymentStatsByMethod:()=>Pd,recordRefund:()=>Ed,store:()=>kd,update:()=>Ad});import{db as hd}from"@stacksjs/database/runtime";async function bd(e){try{let t=await hd.deleteFrom("payments").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete payment: ${t.message}`);throw t}}async function _d(e){if(!e.length)return 0;try{let t=await hd.deleteFrom("payments").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete payments: ${t.message}`);throw t}}import{db as K}from"@stacksjs/database/runtime";import{formatDate as le}from"@stacksjs/orm";async function xd(){let e=await K.selectFrom("payments").selectAll().execute();return P(e)}async function Xe(e){let t=await K.selectFrom("payments").selectAll().where("id","=",e).executeTakeFirst();return w(t,!0)}async function Rd(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await K.selectFrom("payments").select([K.fn.count("id").as("transaction_count"),K.fn.sum("amount").as("total_revenue")]).where("created_at",">=",le(r)).where("created_at","<=",le(t)).where("status","=","completed").executeTakeFirst(),s=await K.selectFrom("payments").select([K.fn.count("id").as("transaction_count"),K.fn.sum("amount").as("total_revenue")]).where("created_at",">=",le(o)).where("created_at","<=",le(n)).where("status","=","completed").executeTakeFirst(),i=await K.selectFrom("payments").select(K.fn.count("id").as("count")).where("created_at",">=",le(r)).where("created_at","<=",le(t)).executeTakeFirst(),u=Number(a?.transaction_count||0),c=Number(a?.total_revenue||0),d=u>0?c/u:0,m=Number(s?.transaction_count||0),l=Number(s?.total_revenue||0),y=m>0?l/m:0,g=u-m,p=c-l,b=d-y,h=m>0?g/m*100:u>0?100:0,f=l>0?p/l*100:c>0?100:0,x=y>0?b/y*100:d>0?100:0,D=Number(i?.count||0),v=D>0?u/D*100:0;return{total_transactions:u,total_revenue:c,average_transaction:d,successful_rate:v,comparison:{transactions:{difference:g,percentage:Math.abs(h),is_increase:g>=0},revenue:{difference:p,percentage:Math.abs(f),is_increase:p>=0},average:{difference:b,percentage:Math.abs(x),is_increase:b>=0}}}}async function Pd(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=await K.selectFrom("payments").select([K.fn.count("id").as("total_count"),K.fn.sum("amount").as("total_revenue")]).where("created_at",">=",le(r)).where("created_at","<=",le(t)).where("status","=","completed").executeTakeFirst(),o=Number(n?.total_count||0),a=await K.selectFrom("payments").select(["method",K.fn.count("id").as("count"),K.fn.sum("amount").as("revenue")]).where("created_at",">=",le(r)).where("created_at","<=",le(t)).where("status","=","completed").groupBy("method").execute(),s={};return a.forEach((i)=>{let u=Number(i.count||0),c=Number(i.revenue||0),d=o>0?u/o*100:0;s[i.method]={count:u,revenue:c,percentage_of_total:d}}),s}async function vd(){let e=new Date,t=new Date(e);t.setMonth(e.getMonth()-11),t.setDate(1);let r=await K.selectFrom("payments").selectAll().where("created_at",">=",le(t)).where("status","=","completed").execute(),n={};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(!n[c])n[c]={year:i,month:u,transactions:0,revenue:0};n[c].transactions++,n[c].revenue+=Number(a.amount||0)}return Object.keys(n).sort().map((a)=>{let s=n[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:ih}=globalThis.Bun;import{db as Dd}from"@stacksjs/database/runtime";import{HttpError as Sd}from"@stacksjs/error-handling";import{isUniqueViolation as uh}from"@stacksjs/orm";async function kd(e){let t=ih(),r={...e,status:e.status||"pending",currency:e.currency||"USD",uuid:t};try{await Dd.insertInto("payments").values(r).executeTakeFirst();let n=await Dd.selectFrom("payments").where("uuid","=",t).selectAll().executeTakeFirst();return w(n,!0)}catch(n){if(n instanceof Sd)throw n;if(uh(n))throw new Sd(409,"A payment with this transaction ID already exists");if(n instanceof Error){if(n.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${n.message}`)}throw n}}import{db as Cd,mutationCount as ch,sqlHelpers as dh}from"@stacksjs/database/runtime";import{env as lh}from"@stacksjs/env";import{formatDate as Td}from"@stacksjs/orm";async function Ad(e,t){if(!await Xe(e))return;try{return await Cd.updateTable("payments").set({...t,updated_at:Td(new Date)}).where("id","=",e).execute(),await Xe(e)}catch(n){if(n instanceof Error){if(n.message.includes("Duplicate entry")&&n.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${n.message}`)}throw n}}var mh=new Set(["completed","succeeded","partiallyRefunded"]);async function Ed(e,t){if(!Number.isSafeInteger(e)||e<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger(t)||t<=0)throw TypeError("Refund amount must be a positive integer in minor units");let n=dh(lh.DB_CONNECTION||"sqlite").param,o=Td(new Date),a=await Cd.unsafe(`UPDATE payments
22
22
  SET status = CASE WHEN COALESCE(refund_amount, 0) + ${n(1)} = amount THEN 'refunded'
23
23
  WHEN 1 = 0 THEN status ELSE 'partiallyRefunded' END,
24
24
  refund_amount = COALESCE(refund_amount, 0) + ${n(2)},
25
25
  updated_at = ${n(3)}
26
26
  WHERE id = ${n(4)}
27
27
  AND status IN ('completed', 'succeeded', 'partiallyRefunded')
28
- AND COALESCE(refund_amount, 0) + ${n(5)} <= amount`,[t,t,o,e,t]);if(uh(a)>0){let d=await Xe(e);if(d)return d;throw Error(`Payment with ID ${e} disappeared during refund`)}let s=await Xe(e);if(!s)throw Error(`Payment with ID ${e} not found`);let i=String(s.status||"");if(!lh.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 ka={};E(ka,{categories:()=>Ar,default:()=>Ch,items:()=>Er,manufacturers:()=>Fr,reviews:()=>Ir,units:()=>Or,variants:()=>$r});var Ar={};E(Ar,{bulkRemove:()=>Wd,compareCategoryGrowth:()=>$d,deactivate:()=>jd,deactivateChildCategories:()=>zd,fetchActive:()=>Fd,fetchAll:()=>xa,fetchByDisplayOrder:()=>Nd,fetchById:()=>Z,fetchByName:()=>Ed,fetchCategoryTree:()=>Bd,fetchChildCategories:()=>Md,fetchRootCategories:()=>Id,fetchStats:()=>Od,findOrCreateByName:()=>qd,remove:()=>Jd,removeChildCategories:()=>Ld,store:()=>Ra,update:()=>Vd,updateActiveStatus:()=>Kd,updateDisplayOrder:()=>Hd,updateParent:()=>Zd});import{db as Bt,matchedRows as mh}from"@stacksjs/database/runtime";import{formatDate as Ud}from"@stacksjs/orm";import{db as L}from"@stacksjs/database/runtime";import{formatDate as $t}from"@stacksjs/orm";async function xa(){return await L.selectFrom("categories").selectAll().execute()}async function Z(e){return await L.selectFrom("categories").where("id","=",e).selectAll().executeTakeFirst()}async function Ed(e){return await L.selectFrom("categories").where("name","=",e).selectAll().executeTakeFirst()}async function Fd(){return await L.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function Id(){return await L.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function Md(e){return await L.selectFrom("categories").where("parent_category_id","=",e).where("is_active","=",!0).selectAll().execute()}async function Nd(e=!0){let t=L.selectFrom("categories").where("is_active","=",!0).selectAll();if(e)return await t.orderBy("display_order","asc").execute();else return await t.orderBy("display_order","desc").execute()}async function Od(){let e=await L.selectFrom("categories").select(L.fn.count("id").as("count")).executeTakeFirst(),t=await L.selectFrom("categories").where("is_active","=",!0).select(L.fn.count("id").as("count")).executeTakeFirst(),r=await L.selectFrom("categories").whereNull("parent_category_id").select(L.fn.count("id").as("count")).executeTakeFirst(),n=await L.selectFrom("categories").whereNotNull("image_url").select(L.fn.count("id").as("count")).executeTakeFirst(),o=new Date;o.setDate(o.getDate()-30);let a=$t(o),s=await L.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await L.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",L.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(e?.count||0),active:Number(t?.count||0),root_categories:Number(r?.count||0),child_categories:Number(e?.count||0)-Number(r?.count||0),with_images:Number(n?.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 $d(e=30){let t=new Date,r=$t(t),n=new Date;n.setDate(t.getDate()-e);let o=$t(n),a=new Date(n);a.setDate(a.getDate()-1);let s=$t(a),i=new Date(a);i.setDate(a.getDate()-e);let u=$t(i),c=await L.selectFrom("categories").select(L.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",r).executeTakeFirst(),d=await L.selectFrom("categories").select(L.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),m=Number(c?.count||0),l=Number(d?.count||0),y=m-l,g=l!==0?y/l*100:m>0?100:0;return{current_period:m,previous_period:l,difference:y,percentage_change:g,days_range:e}}async function Bd(){let e=await xa(),t=new Map;e.forEach((o)=>{t.set(o.id,{...o,children:[]})});let r=[];e.forEach((o)=>{let a=t.get(o.id);if(o.parent_category_id){let s=t.get(o.parent_category_id);if(s)s.children.push(a)}else r.push(a)}),r.sort((o,a)=>o.display_order-a.display_order);let n=(o)=>{o.sort((a,s)=>a.display_order-s.display_order),o.forEach((a)=>{if(a.children.length>0)n(a.children)})};return n(r),r}async function Jd(e){let t=await Bt.deleteFrom("categories").where("id","=",e).executeTakeFirst();return _(t)>0}async function Wd(e){if(!e.length)return 0;let t=await Bt.deleteFrom("categories").where("id","in",e).executeTakeFirst();return _(t)}async function Ld(e){let t=await Bt.deleteFrom("categories").where("parent_category_id","=",e).executeTakeFirst();return _(t)}async function jd(e){if(!await Z(e))throw Error(`Category with ID ${e} not found`);let r=await Bt.updateTable("categories").set({is_active:!1,updated_at:Ud(new Date)}).where("id","=",e).returning("id").executeTakeFirst();return Boolean(r)}async function zd(e){return(await mh(Bt.updateTable("categories").set({is_active:!1,updated_at:Ud(new Date)}).where("parent_category_id","=",e))).length}var{randomUUIDv7:ph}=globalThis.Bun;import{db as Gd}from"@stacksjs/database/runtime";import{HttpError as Cr}from"@stacksjs/error-handling";import{isUniqueViolation as fh}from"@stacksjs/orm";import{slug as wh}from"@stacksjs/strings";async function Ra(e){try{let t=e.parent_category_id?Number(e.parent_category_id):void 0;if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new Cr(422,"Parent category ID must be a positive integer");if(t&&!await Z(t))throw new Cr(422,`Parent category with ID ${e.parent_category_id} not found`);let r={...e,uuid:ph(),is_active:e.is_active??!0,parent_category_id:e.parent_category_id||null},n=await Gd.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create category");return n}catch(t){if(t instanceof Cr)throw t;if(fh(t))throw new Cr(409,"A category with this name or slug already exists");if(t instanceof Error)throw Error(`Failed to create category: ${t.message}`);throw t}}async function qd(e){if(!e.name)throw Error("Name is required");let t=await Gd.selectFrom("categories").selectAll().where("name","=",e.name).executeTakeFirst();if(t)return t;let r={name:e.name,slug:wh(e.name),is_active:e.is_active??!0,display_order:0};return await Ra(r)}import{db as Ut}from"@stacksjs/database/runtime";import{HttpError as lt}from"@stacksjs/error-handling";import{formatDate as Tr,isUniqueViolation as yh}from"@stacksjs/orm";async function Vd(e,t){if(!await Z(e))return;if(Object.hasOwn(t,"parent_category_id")){let n=t.parent_category_id?Number(t.parent_category_id):void 0;if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw new lt(422,"Parent category ID must be a positive integer");if(n===e)throw new lt(422,"A category cannot be its own parent");if(n&&!await Z(n))throw new lt(422,`Parent category with ID ${t.parent_category_id} not found`);if(n&&await Qd(e,String(n)))throw new lt(422,"This operation would create a circular category hierarchy")}try{let n=Object.hasOwn(t,"parent_category_id")?{parent_category_id:t.parent_category_id||null}:{},o=await Ut.updateTable("categories").set({...t,...n,updated_at:Tr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!o)return;return o}catch(n){if(n instanceof lt)throw n;if(yh(n))throw new lt(409,"A category with this name or slug already exists");if(n instanceof Error)throw Error(`Failed to update category: ${n.message}`);throw n}}async function Hd(e,t){if(!await Z(e))throw Error(`Category with ID ${e} not found`);try{return await Ut.updateTable("categories").set({display_order:t,updated_at:Tr(new Date)}).where("id","=",e).execute(),await Z(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category display order: ${n.message}`);throw n}}async function Kd(e,t){if(!await Z(e))throw Error(`Category with ID ${e} not found`);try{return await Ut.updateTable("categories").set({is_active:t,updated_at:Tr(new Date)}).where("id","=",e).execute(),await Z(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category active status: ${n.message}`);throw n}}async function Zd(e,t){if(!await Z(e))throw Error(`Category with ID ${e} not found`);if(t){let n=Number(t);if(n===e)throw Error("A category cannot be its own parent");if(!await Z(n))throw Error(`Parent category with ID ${t} not found`);if(await Qd(e,t))throw Error("This operation would create a circular reference in the category hierarchy")}try{let n={updated_at:Tr(new Date)};if(t===null)await Ut.updateTable("categories").set({...n,parent_category_id:null}).where("id","=",e).execute();else await Ut.updateTable("categories").set({...n,parent_category_id:t}).where("id","=",e).execute();return await Z(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category parent: ${n.message}`);throw n}}async function Qd(e,t){let r=Number(t),n=new Set;while(r){if(n.has(r))return!0;if(r===e)return!0;n.add(r);let o=await Z(r),a=o?.parent_category_id;if(!o||!a)return!1;r=Number(a)}return!1}var Er={};E(Er,{bulkDestroy:()=>el,bulkStore:()=>il,destroy:()=>Xd,fetchAll:()=>tl,fetchById:()=>Te,fetchTopProducts:()=>nl,store:()=>sl,update:()=>ul,updateAvailability:()=>cl,updateInventory:()=>dl});import{db as Yd}from"@stacksjs/database/runtime";async function Xd(e){try{let t=await Yd.deleteFrom("products").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product item: ${t.message}`);throw t}}async function el(e){if(!e.length)return 0;try{let t=await Yd.deleteFrom("products").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product items: ${t.message}`);throw t}}import{db as Ce,sql as gh}from"@stacksjs/database/runtime";async function Te(e){let t=await Ce.selectFrom("products").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=null,n=null;if(t.manufacturer_id)r=await Ce.selectFrom("manufacturers").where("id","=",t.manufacturer_id).selectAll().executeTakeFirst();if(t.category_id)n=await Ce.selectFrom("categories").where("id","=",t.category_id).selectAll().executeTakeFirst();return{...t,manufacturer:r,category:n}}return}async function tl(){let e=await Ce.selectFrom("products").selectAll().execute(),t=e.map((c)=>c.manufacturer_id).filter((c)=>c!==null&&c!==void 0),r=e.map((c)=>c.category_id).filter((c)=>c!==null&&c!==void 0),n=Ce.selectFrom("manufacturers"),o=Ce.selectFrom("categories");if(t.length>0)n=n.where("id","in",t);if(r.length>0)o=o.where("id","in",r);let a=await n.selectAll().execute(),s=await o.selectAll().execute(),i=a.reduce((c,d)=>(c[d.id]=d,c),{}),u=s.reduce((c,d)=>(c[d.id]=d,c),{});return e.map((c)=>({...c,manufacturer:c.manufacturer_id?i[c.manufacturer_id]:null,category:c.category_id?u[c.category_id]:null}))}async function rl(e){try{let t=await Ce.selectFrom("products").selectAll().where("uuid","=",e).executeTakeFirst();return w(t,!0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get product by UUID: ${t.message}`);throw t}}async function nl(e=5){try{return(await Ce.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",Ce.fn.sum("order_items.quantity").as("units_sold"),gh`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(e).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(t){if(t instanceof Error)throw TypeError(`Failed to fetch top products: ${t.message}`);throw t}}var{randomUUIDv7:ol}=globalThis.Bun;import{db as al}from"@stacksjs/database/runtime";async function sl(e){try{let t={...e,uuid:ol()},r=await al.insertInto("products").values(t).executeTakeFirst();if(!r)throw Error("Failed to create product item");let n=ve(r),o=n!==void 0?await Te(n):await rl(t.uuid);if(!o)throw Error("Failed to create product item");return o}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product item: ${t.message}`);throw t}}async function il(e){if(!e.length)return 0;let t=0;try{return await al.transaction(async(r)=>{for(let n of e){let o={...n,uuid:ol()};await r.insertInto("products").values(o).execute(),t++}}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product items in bulk: ${r.message}`);throw r}}import{db as Pa,matchedRows as SS}from"@stacksjs/database/runtime";import{formatDate as va}from"@stacksjs/orm";async function ul(e,t){try{if(!e)throw Error("Product item ID is required for update");let r=await Pa.updateTable("products").set({...t,updated_at:va(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function cl(e,t){if(!await Te(e))throw Error(`Product item with ID ${e} not found`);try{return await Pa.updateTable("products").set({is_available:t,updated_at:va(new Date)}).where("id","=",e).execute(),await Te(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update product item availability: ${n.message}`);throw n}}async function dl(e,t){let r=await Te(e);if(!r)throw Error(`Product item with ID ${e} not found`);let n={updated_at:va(new Date)};if(t!==void 0)n.inventory_count=t;if(Object.keys(n).length===1)return r;try{return await Pa.updateTable("products").set(n).where("id","=",e).execute(),await Te(e)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update inventory information: ${o.message}`);throw o}}var Fr={};E(Fr,{bulkDestroy:()=>pl,bulkStore:()=>vl,destroy:()=>ml,fetchAll:()=>fl,fetchByCountry:()=>hl,fetchById:()=>wl,fetchByUuid:()=>yl,fetchFeatured:()=>gl,fetchWithProductCount:()=>bl,store:()=>Pl,update:()=>Sl,updateByUuid:()=>Cl,updateFeaturedStatus:()=>kl});import{db as ll}from"@stacksjs/database/runtime";async function ml(e){try{let t=await ll.deleteFrom("manufacturers").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete order: ${t.message}`);throw t}}async function pl(e){if(!e.length)return 0;try{let t=await ll.deleteFrom("manufacturers").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete orders: ${t.message}`);throw t}}import{db as Ae}from"@stacksjs/database/runtime";async function fl(){return P(await Ae.selectFrom("manufacturers").selectAll().execute())}async function wl(e){let t=await Ae.selectFrom("manufacturers").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function yl(e){let t=await Ae.selectFrom("manufacturers").where("uuid","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function gl(e=10){let t=await Ae.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(e).execute();return P(t)}async function hl(e,t={}){let r=t.page||1,n=t.limit||2,o=await Ae.selectFrom("manufacturers").select(Ae.fn.count("id").as("total")).where("country","=",e).executeTakeFirst(),a=Number(o?.total||0),s=await Ae.selectFrom("manufacturers").selectAll().where("country","=",e).limit(n).offset((r-1)*n).execute(),i=Math.ceil(a/n);return{data:P(s),paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function bl(e={}){let t=Ae.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(e.country)t=t.where("m.country","=",e.country);if(e.featured!==void 0)t=t.where("m.featured","=",e.featured);return t=t.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",Ae.fn.count("p.id").as("product_count")]).groupBy("m.id"),t.execute()}var{randomUUIDv7:xl}=globalThis.Bun;import{db as Rl}from"@stacksjs/database/runtime";import{HttpError as _l}from"@stacksjs/error-handling";import{isUniqueViolation as hh}from"@stacksjs/orm";async function Pl(e){try{let t={...e,uuid:xl(),featured:e.featured??!1},r=await Rl.insertInto("manufacturers").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return w(r)}catch(t){if(t instanceof _l)throw t;if(hh(t))throw new _l(409,"A manufacturer with this name already exists");if(t instanceof Error)throw Error(`Failed to create manufacturer: ${t.message}`);throw t}}async function vl(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:xl(),featured:r.featured??!1};await Rl.insertInto("manufacturers").values(n).execute(),t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${r.message}`);throw r}}import{db as Da}from"@stacksjs/database/runtime";import{HttpError as Dl}from"@stacksjs/error-handling";import{formatDate as Sa,isUniqueViolation as bh}from"@stacksjs/orm";async function Sl(e,t){try{if(!e)throw Error("Manufacturer ID is required for update");let r=await Da.updateTable("manufacturers").set({...t,updated_at:Sa(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Dl)throw r;if(bh(r))throw new Dl(409,"A manufacturer with this name already exists");if(r instanceof Error)throw Error(`Failed to update manufacturer: ${r.message}`);throw r}}async function kl(e,t){try{let r=await Da.updateTable("manufacturers").set({featured:t,updated_at:Sa(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function Cl(e,t){try{let r=await Da.updateTable("manufacturers").set({...t,updated_at:Sa(new Date)}).where("uuid","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var Ir={};E(Ir,{bulkDestroy:()=>El,destroy:()=>Al,fetchAll:()=>Il,fetchApprovedByProductId:()=>Ol,fetchById:()=>Fl,fetchByProductId:()=>Ml,fetchByUserId:()=>Nl,fetchMostHelpfulByProductId:()=>$l,fetchStats:()=>Wl,fetchStatsByProductIds:()=>Ll,store:()=>jl,update:()=>ql,updateVotes:()=>Vl});import{db as Tl}from"@stacksjs/database/runtime";async function Al(e){try{let t=await Tl.deleteFrom("reviews").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete review: ${t.message}`);throw t}}async function El(e){if(!e.length)return 0;try{let t=await Tl.deleteFrom("reviews").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete reviews: ${t.message}`);throw t}}import{db as mt}from"@stacksjs/database/runtime";async function Fl(e){return w(await mt.selectFrom("reviews").where("id","=",e).selectAll().executeTakeFirst(),!0)}async function Il(){return P(await mt.selectFrom("reviews").selectAll().execute())}async function Ml(e){return P(await mt.selectFrom("reviews").where("product_id","=",e).selectAll().execute())}async function Nl(e){return P(await mt.selectFrom("reviews").where("customer_id","=",e).selectAll().execute())}async function Ol(e){return P(await mt.selectFrom("reviews").where("product_id","=",e).where("is_approved","=",!0).selectAll().execute())}async function $l(e){return P(await mt.selectFrom("reviews").where("product_id","=",e).orderBy("helpful_votes","desc").selectAll().execute())}import{db as Bl}from"@stacksjs/database/runtime";function Ul(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function Jl(e){let t=Ul();t.total=e.length;let r=0;for(let n of e){if(n.rating===null||n.rating===void 0){t.commentsOnly++;continue}let o=Number(n.rating);if(Number.isNaN(o)){t.commentsOnly++;continue}t.rated++,r+=o;let a=Math.min(5,Math.max(1,Math.round(o)));t.distribution[a]++}if(t.rated>0)t.average=Math.round(r/t.rated*10)/10;return t}async function Wl(e){let t=await Bl.selectFrom("reviews").select(["rating"]).where("product_id","=",e).where("is_approved","=",!0).execute();return Jl(t)}async function Ll(e){let t=new Map;for(let o of e)t.set(o,Ul());if(e.length===0)return t;let r=await Bl.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",e).where("is_approved","=",!0).execute(),n=new Map;for(let o of r){let a=n.get(o.product_id);if(a)a.push({rating:o.rating});else n.set(o.product_id,[{rating:o.rating}])}for(let[o,a]of n)t.set(o,Jl(a));return t}var{randomUUIDv7:_h}=globalThis.Bun;import{db as xh}from"@stacksjs/database/runtime";function Rh(e){let t=e.rating!==void 0&&e.rating!==null,r=typeof e.content==="string"&&e.content.trim().length>0,n=typeof e.title==="string"&&e.title.trim().length>0;return!t&&!r&&!n}async function jl(e){try{if(Rh(e))throw Error("A review needs a rating or something written: both were empty");let t={...e,uuid:_h(),rating:e.rating??null,is_verified_purchase:e.is_verified_purchase??!1,is_approved:e.is_approved??!1,helpful_votes:e.helpful_votes??0,unhelpful_votes:e.unhelpful_votes??0,is_featured:e.is_featured??!1},r=await xh.insertInto("reviews").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return w(r)}catch(t){if(t instanceof Error){if(t.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${t.message}`)}throw t}}import{db as zl,sqlHelpers as Ph}from"@stacksjs/database/runtime";import{env as vh}from"@stacksjs/env";import{formatDate as Gl}from"@stacksjs/orm";async function ql(e,t){try{if(!e)throw Error("Review ID is required for update");let r=await zl.updateTable("reviews").set({...t,updated_at:Gl(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function Vl(e,t,r=!0){try{let n=t==="helpful"?"helpful_votes":"unhelpful_votes",o=r?`COALESCE("${n}", 0) + 1`:`MAX(COALESCE("${n}", 0) - 1, 0)`,{param:a}=Ph(vh.DB_CONNECTION||"sqlite"),s=await zl.unsafe(`UPDATE "reviews" SET "${n}" = ${o}, "updated_at" = ${a(1)} WHERE "id" = ${a(2)} RETURNING *`,[Gl(new Date),e]).execute(),i=Array.isArray(s)?s[0]:s;if(!i)throw Error("Failed to update review votes");return w(i)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update review votes: ${n.message}`);throw n}}var Or={};E(Or,{bulkDestroy:()=>Zl,bulkStore:()=>rm,bulkUpdate:()=>sm,destroy:()=>Kl,fetchAll:()=>Xl,fetchById:()=>Yl,formatUnitOptions:()=>nm,getDefaultUnit:()=>om,store:()=>tm,update:()=>am,updateDefaultStatus:()=>im});import{db as Hl}from"@stacksjs/database/runtime";async function Kl(e){try{let t=await Hl.deleteFrom("product_units").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product unit: ${t.message}`);throw t}}async function Zl(e){if(!e.length)return 0;try{let t=await Hl.deleteFrom("product_units").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product units: ${t.message}`);throw t}}import{db as Ql}from"@stacksjs/database/runtime";async function Yl(e){let t=await Ql.selectFrom("product_units").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Xl(){return P(await Ql.selectFrom("product_units").selectAll().execute())}var{randomUUIDv7:em}=globalThis.Bun;import{db as Jt}from"@stacksjs/database/runtime";async function tm(e){try{return await Jt.transaction(async(t)=>{let r={...e,uuid:em()},n=await t.insertInto("product_units").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create product unit");if(r.is_default&&r.type)await t.updateTable("product_units").set({is_default:!1}).where("type","=",r.type).where("id","!=",n.id).execute();return w(n)})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product unit: ${t.message}`);throw t}}async function rm(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:em()},o=await Jt.insertInto("product_units").values(n).returningAll().executeTakeFirst();if(n.is_default&&n.type&&o)await Jt.updateTable("product_units").set({is_default:!1}).where("type","=",n.type).where("id","!=",o.id).execute();t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product units in bulk: ${r.message}`);throw r}}function nm(e){try{let t=Jt.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(e)t=t.where("type","=",e);return t=t.orderBy("name"),t.execute().then((r)=>r.map((n)=>({id:String(n.id),name:n.name,abbreviation:n.abbreviation,is_default:n.is_default})))}catch(t){if(t instanceof Error)throw TypeError(`Failed to format unit options: ${t.message}`);throw t}}async function om(e){try{let t=await Jt.selectFrom("product_units").selectAll().where("type","=",e).where("is_default","=",!0).executeTakeFirst();return w(t,!0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get default unit: ${t.message}`);throw t}}import{db as Mr,matchedRows as Dh}from"@stacksjs/database/runtime";import{formatDate as Nr}from"@stacksjs/orm";async function am(e,t){try{if(!e)throw Error("Product unit ID is required for update");return await Mr.transaction(async(r)=>{let n=await r.selectFrom("product_units").select(["type","is_default"]).where("id","=",e).executeTakeFirst();if(!n)return;let o=t.type??n.type;if((t.is_default??Boolean(n.is_default))&&o)await r.updateTable("product_units").set({is_default:!1,updated_at:Nr(new Date)}).where("type","=",o).where("id","!=",e).execute();let s=await r.updateTable("product_units").set({...t,updated_at:Nr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!s)return;return w(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function sm(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n=r;if(!n.id)continue;let o=n.data&&typeof n.data==="object"?n.data:{...n};delete o.id;let a=await Dh(Mr.updateTable("product_units").set({...o,updated_at:Nr(new Date)}).where("id","=",n.id)),s=o;if(s.is_default===!0&&s.type)await Mr.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",n.id).execute();if(a.length>0)t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product units in bulk: ${r.message}`);throw r}}async function im(e,t){try{return await Mr.transaction(async(r)=>{let n=await r.selectFrom("product_units").select("type").where("id","=",e).executeTakeFirst();if(!n)return!1;let o=Nr(new Date);if(t&&n.type)await r.updateTable("product_units").set({is_default:!1,updated_at:o}).where("type","=",n.type).where("id","!=",e).execute();return await r.updateTable("product_units").set({is_default:t,updated_at:o}).where("id","=",e).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit default status: ${r.message}`);throw r}}var $r={};E($r,{bulkDestroy:()=>dm,bulkStore:()=>gm,bulkUpdate:()=>Pm,destroy:()=>cm,fetchAll:()=>pm,fetchById:()=>mm,formatVariantOptions:()=>hm,generateVariantCombinations:()=>bm,store:()=>ym,update:()=>Rm});import{db as um}from"@stacksjs/database/runtime";async function cm(e){try{let t=await um.deleteFrom("product_variants").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product variant: ${t.message}`);throw t}}async function dm(e){if(!e.length)return 0;try{let t=await um.deleteFrom("product_variants").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product variants: ${t.message}`);throw t}}import{db as lm}from"@stacksjs/database/runtime";async function mm(e){let t=await lm.selectFrom("product_variants").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function pm(){return P(await lm.selectFrom("product_variants").selectAll().execute())}var{randomUUIDv7:fm}=globalThis.Bun;import{db as wm}from"@stacksjs/database/runtime";async function ym(e){try{let t={...e,uuid:fm()},r=await wm.insertInto("product_variants").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return w(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product variant: ${t.message}`);throw t}}async function gm(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:fm()};await wm.insertInto("product_variants").values(n).execute(),t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${r.message}`);throw r}}function hm(e){if(!e||!e.length)return JSON.stringify([]);let t=e.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(t)}function bm(e){let t=Object.keys(e);if(!t.length)return[];function r(n,o){if(n===t.length)return[o];let a=t[n],s=e[a]??[],i=[];for(let u of s){let c={...o,[a]:u};i.push(...r(n+1,c))}return i}return r(0,{})}import{db as _m,matchedRows as Sh}from"@stacksjs/database/runtime";import{formatDate as xm}from"@stacksjs/orm";async function Rm(e,t){try{let r=await _m.updateTable("product_variants").set({...t,updated_at:xm(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function Pm(e){if(!e.length)return 0;let t=0;try{for(let r of e){if(!r.id)continue;if((await Sh(_m.updateTable("product_variants").set({...r,updated_at:xm(new Date)}).where("id","=",r.id))).length>0)t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var kh={categories:Ar,items:Er,manufacturers:Fr,reviews:Ir,units:Or,variants:$r},Ch=kh;var Ta={};E(Ta,{CENTS_FIELDS:()=>Th,DEFAULT_FIELDS:()=>Je,addToBasket:()=>Ah,basketCount:()=>Ih,basketLines:()=>Sm,basketTotal:()=>Fh,canAdd:()=>Dm,groupsOf:()=>Nh,setQuantity:()=>Eh,shelfLeft:()=>Ca,stockLabel:()=>Mh});var Je={id:"id",price:"price",inventory:"inventory",lowStock:"low_stock_threshold"},Th={id:"id",price:"price_cents",inventory:"inventory_quantity",lowStock:"low_stock_threshold"};function Br(e,t){return Number(e[t.id])}function vm(e,t){let r=e[t.inventory];return r===null||r===void 0||r===""?null:Number(r)}function Ca(e,t,r=Je){let n=vm(e,r);if(n===null)return null;let o=t.find((a)=>a.productId===Br(e,r))?.quantity||0;return Math.max(0,n-o)}function Dm(e,t,r=Je){let n=Ca(e,t,r);return n===null||n>0}function Ah(e,t,r=Je){if(!Dm(t,e,r))return e;let n=Br(t,r);return e.some((o)=>o.productId===n)?e.map((o)=>o.productId===n?{...o,quantity:o.quantity+1}:o):[...e,{productId:n,quantity:1}]}function Eh(e,t,r,n=Je){let o=Br(t,n),a=vm(t,n),s=Math.min(Math.max(0,Math.floor(Number(r)||0)),a===null?Number.POSITIVE_INFINITY:a);if(s===0)return e.filter((i)=>i.productId!==o);return e.some((i)=>i.productId===o)?e.map((i)=>i.productId===o?{...i,quantity:s}:i):[...e,{productId:o,quantity:s}]}function Sm(e,t,r=Je){return e.map((n)=>({...n,product:t.find((o)=>Br(o,r)===n.productId)})).filter((n)=>!!n.product)}function Fh(e,t,r=Je){return Sm(e,t,r).reduce((n,o)=>n+Number(o.product[r.price]||0)*o.quantity,0)}function Ih(e){return e.reduce((t,r)=>t+r.quantity,0)}function Mh(e,t=[],r=Je,n=5){let o=Ca(e,t,r);if(o===null)return null;if(o===0)return{text:"Sold out",tone:"out"};let a=e[r.lowStock]===null||e[r.lowStock]===void 0?n:Number(e[r.lowStock]);return{text:`${o} left`,tone:o<=a?"low":"ok"}}function Nh(e,t){let r=[];for(let n of e){let o=t(n);if(!r.includes(o))r.push(o)}return r}var Aa={};E(Aa,{RELEASE_MODES:()=>Cm,describeRollout:()=>Uh,isReleaseMode:()=>Tm,releaseSchedule:()=>$h,rolloutFromProduct:()=>Oh,unlockAt:()=>Am,unlockedPrefix:()=>Bh});var Cm=["all_at_once","drip","scheduled"];function Tm(e){return typeof e==="string"&&Cm.includes(e)}function Oh(e){let t=Number(e.release_interval_days),r=Number(e.release_initial_count),n=Ur(e.release_starts_at);return{mode:Tm(e.release_mode)?e.release_mode:"all_at_once",intervalDays:Number.isInteger(t)&&t>0?t:7,initialCount:Number.isInteger(r)&&r>0?r:1,startsAt:n===null?null:new Date(n).toISOString()}}function Ur(e){if(e==null||e==="")return null;let t=new Date(String(e)).getTime();return Number.isFinite(t)?t:null}function km(e,t){return Math.max(0,t-(e.initialCount-1))}function Am(e,t,r,n={}){let o=Ur(e.startsAt),a=Math.max(r.getTime(),o??0);if(e.mode==="scheduled"){let s=Ur(n.releaseAt);if(s!==null)return new Date(s);let i=o??r.getTime();return new Date(i+km(e,t)*e.intervalDays*86400000)}if(e.mode==="drip"){let s=n.offsetDays;if(s!=null&&Number.isFinite(Number(s))&&Number(s)>=0)return new Date(a+Number(s)*86400000);return new Date(a+km(e,t)*e.intervalDays*86400000)}return new Date(a)}function $h(e,t,r,n,o=[]){let a=[];for(let s=0;s<t;s++){let i=Am(e,s,r,o[s]||{});a.push({index:s,unlock_at:i.toISOString(),unlocked:i.getTime()<=n.getTime()})}return a}function Bh(e){let t=0;for(let r of e){if(!r.unlocked)break;t++}return t}function Uh(e,t,r,n=new Date){let o=(m)=>`${m} ${r}${m===1?"":"s"}`,a=Ur(e.startsAt),s=a!==null&&a>n.getTime()?` from ${new Date(a).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"})}`:"";if(t<=0)return"";if(t===1)return`Available${s||" immediately"}.`;if(e.mode==="all_at_once"||t<=e.initialCount)return`All ${o(t)} available${s||" immediately"}.`;let i=e.intervalDays===1?"every day":e.intervalDays===7?"every week":`every ${e.intervalDays} days`,u=e.initialCount===1,c=u?`The first ${r}`:`The first ${o(e.initialCount)}`;if(e.mode==="drip")return`${c} ${u?"unlocks":"unlock"}${s||" on purchase"}, then one more ${i}.`;if(s)return`${c} ${u?"releases":"release"} on ${s.slice(6)}, then one more ${i}, on the same dates for everyone.`;return`Releasing on a shared schedule${a===null?"":` since ${new Date(a).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"})}`}, one more ${r} ${i}. Join now and everything already out is yours.`}var Oa={};E(Oa,{bulkDestroy:()=>Im,bulkStore:()=>Lm,destroy:()=>Fm,fetchAll:()=>Mm,fetchById:()=>pt,fetchPageStats:()=>$m,fetchPrintJobStats:()=>Nm,fetchPrintTimeStats:()=>Bm,fetchPrintsPerHour:()=>Um,fetchSuccessRate:()=>Om,store:()=>Wm,update:()=>jm,updatePrintJob:()=>Gm,updateStatus:()=>zm});import{db as Em}from"@stacksjs/database/runtime";async function Fm(e){try{let t=await Em.deleteFrom("receipts").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print log: ${t.message}`);throw t}}async function Im(e){if(!e.length)return 0;try{let t=await Em.deleteFrom("receipts").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete receipts: ${t.message}`);throw t}}import{db as Ea}from"@stacksjs/database/runtime";import{formatDate as Jh}from"@stacksjs/orm";function be(e){return Jh(e)}function Wh(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e==="number"){let n=new Date(e<=2147483647?e*1000:e);return Number.isNaN(n.getTime())?null:n}let t=String(e||"").trim();if(!t)return null;if(/^\d{10}$/.test(t)){let n=new Date(Number(t)*1000);return Number.isNaN(n.getTime())?null:n}let r=new Date(t.includes("T")?t:`${t.replace(" ","T")}Z`);return Number.isNaN(r.getTime())?null:r}async function pt(e){let t=await Ea.selectFrom("receipts").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Mm(){return P(await Ea.selectFrom("receipts").selectAll().execute())}async function Nm(e,t){let r=be(e),n=be(t),o=await ue("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","<=",n));return{total:o.total,success:o.success,failed:o.failed,warning:o.warning,averageSize:Math.round(o.averageSize),averagePages:Math.round(o.averagePages),averageDuration:Math.round(o.averageDuration)}}async function Om(e,t){let r=be(e),n=be(t),o=await ue("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","<=",n));return{successRate:o.total>0?Math.round(o.success/o.total*100):0,total:o.total,success:o.success,failed:o.failed,warning:o.warning}}async function $m(e,t){let r=be(e),n=be(t),o=await ue("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",n));return{totalPages:o.totalPages,averagePagesPerReceipt:Math.round(o.averagePagesPerReceipt),totalReceipts:o.totalReceipts}}async function Bm(e,t){let r=be(e),n=be(t),o=await ue("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","<=",n));return{averageDuration:Math.round(o.averageDuration),minDuration:o.minDuration,maxDuration:o.maxDuration,totalJobs:o.totalJobs}}async function Um(e,t){let r=typeof e==="number"?e:e.getTime(),n=typeof t==="number"?t:t.getTime(),o=be(e),a=be(t),s=await Ea.selectFrom("receipts").where("timestamp",">=",o).where("timestamp","<=",a).selectAll().execute(),i=s.length,u=Math.ceil((n-r)/3600000),c=u>0?Math.round(i/u):0,d=Array.from({length:24},(m,l)=>({hour:l,count:0}));return s.forEach((m)=>{let l=Wh(m.timestamp);if(!l)return;d[l.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:d}}var{randomUUIDv7:Jm}=globalThis.Bun;import{db as Ia}from"@stacksjs/database/runtime";import{formatDate as Fa}from"@stacksjs/orm";function Wt(e){try{if(typeof e==="number")return Fa(e<=2147483647?e*1000:e);if(typeof e==="string"&&/^\d{10}$/.test(e))return Fa(Number(e)*1000);return Fa(e)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function Wm(e){try{let t=Jm(),r={...e,timestamp:Wt(e.timestamp),uuid:t};await Ia.insertInto("receipts").values(r).executeTakeFirst();let n=await Ia.selectFrom("receipts").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create receipt");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create receipt: ${t.message}`);throw t}}async function Lm(e){if(!e.length)return 0;try{let t=e.map((n)=>({...n,timestamp:Wt(n.timestamp),uuid:Jm()})),r=await Ia.insertInto("receipts").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${t.message}`);throw t}}import{db as Ma}from"@stacksjs/database/runtime";import{formatDate as Na}from"@stacksjs/orm";async function jm(e,t){try{if(!e)throw Error("Receipt ID is required for update");let r={...t,...t.timestamp===void 0?{}:{timestamp:Wt(t.timestamp)},updated_at:Na(new Date)};await Ma.updateTable("receipts").set(r).where("id","=",e).execute();let n=await pt(e);if(!n)return;return w(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function zm(e,t){try{await Ma.updateTable("receipts").set({status:t,updated_at:Na(new Date)}).where("id","=",e).execute();let r=await pt(e);if(!r)throw Error("Failed to update receipt status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function Gm(e,t,r,n){try{let o={updated_at:Na(new Date)};if(t!==void 0)o.size=t;if(r!==void 0)o.pages=r;if(n!==void 0)o.duration=n;await Ma.updateTable("receipts").set(o).where("id","=",e).execute();let a=await pt(e);if(!a)throw Error("Failed to update receipt job information");return w(a)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update receipt job information: ${o.message}`);throw o}}var is={};E(is,{couriers:()=>Kr,default:()=>lb,digital:()=>Vr,geocoding:()=>Xr,licenses:()=>rn,methods:()=>sn,rates:()=>mn,routes:()=>Gr,tracking:()=>_n,zones:()=>vn});var Gr={};E(Gr,{DeliveryRouteInputError:()=>se,bulkDestroy:()=>Hm,destroy:()=>Vm,fetchActive:()=>Zm,fetchAll:()=>Km,fetchByCourier:()=>Qm,fetchById:()=>Wr,store:()=>Ym,update:()=>ep,updateLastActive:()=>Xm,updateMetrics:()=>rp,updateStops:()=>tp,validateDeliveryRouteWrite:()=>ft});import{db as qm}from"@stacksjs/database/runtime";async function Vm(e){try{let t=await qm.deleteFrom("delivery_routes").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete delivery route: ${t.message}`);throw t}}async function Hm(e){if(!e.length)return 0;try{let t=await qm.deleteFrom("delivery_routes").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete delivery routes: ${t.message}`);throw t}}import{db as Jr}from"@stacksjs/database/runtime";async function Wr(e){return await Jr.selectFrom("delivery_routes").where("id","=",e).selectAll().executeTakeFirst()}async function Km(){return await Jr.selectFrom("delivery_routes").selectAll().execute()}async function Zm(){return await Jr.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function Qm(e){return await Jr.selectFrom("delivery_routes").where("courier","=",e).selectAll().execute()}var{randomUUIDv7:zh}=globalThis.Bun;import{db as $a}from"@stacksjs/database/runtime";function et(e,t){let r={};for(let[n,o]of Object.entries(t))for(let a of o){if(!Object.prototype.hasOwnProperty.call(e,a)||e[a]===void 0)continue;r[n]=e[a];break}return r}function Lt(e){return et(e,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function Ee(e){return et(e,{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 jt(e){return et(e,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function zt(e){return et(e,{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 Gt(e){return et(e,{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 qt(e){return et(e,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function Lr(e){return et(e,{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 Lh}from"@stacksjs/database/runtime";class se extends TypeError{constructor(e){super(e);this.name="DeliveryRouteInputError"}}function jr(e,t,r){return Number(e[r]??t?.[r])}function jh(e,t){let r=e.last_active??t?.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 ft(e,t){let r=jr(e,t,"courier_id"),n=jr(e,t,"stops"),o=jr(e,t,"delivery_time"),a=jr(e,t,"total_distance"),s=jh(e,t);if(!Number.isSafeInteger(r)||r<1)throw new se("Courier must be a positive integer.");if(!Number.isSafeInteger(n)||n<0)throw new se("Stops must be a non-negative integer.");if(!Number.isSafeInteger(o)||o<0)throw new se("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(a)||a<0)throw new se("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(s)||s<0)throw new se("Last active must be a valid Unix timestamp.");let i=await Lh.selectFrom("couriers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new se(`Courier ${r} was not found.`);return{...e,courier_id:Number(i.id),courier:i.name,vehicle:i.vehicle_number,last_active:s}}async function Ym(e){try{let t=zh(),r=Lr(e),o={...await ft(r),uuid:t};await $a.insertInto("delivery_routes").values(o).executeTakeFirst();let a=await $a.selectFrom("delivery_routes").where("uuid","=",t).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(t){if(t instanceof se)throw t;if(t instanceof Error)throw TypeError(`Failed to create delivery route: ${t.message}`);throw t}}async function Xm(e){try{await $a.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",e).execute();let t=await Wr(e);if(!t)throw Error("Failed to update delivery route last active");return t}catch(t){if(t instanceof Error)throw TypeError(`Failed to update delivery route last active: ${t.message}`);throw t}}import{db as zr}from"@stacksjs/database/runtime";import{formatDate as Ba}from"@stacksjs/orm";async function ep(e,t){try{if(!e)throw Error("Delivery route ID is required for update");let r=await zr.selectFrom("delivery_routes").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=Lr(t),o=await ft(n,r),a=await zr.updateTable("delivery_routes").set({...o,updated_at:Ba(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof se)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function tp(e,t){try{let r=await zr.updateTable("delivery_routes").set({stops:t,updated_at:Ba(new Date)}).where("id","=",e).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 rp(e,t,r){try{let n={updated_at:Ba(new Date)};if(t!==void 0)n.delivery_time=t;if(r!==void 0)n.total_distance=r;let o=await zr.updateTable("delivery_routes").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update delivery metrics");return o}catch(n){if(n instanceof Error)throw TypeError(`Failed to update delivery metrics: ${n.message}`);throw n}}var Vr={};E(Vr,{bulkDestroy:()=>sp,bulkSoftDelete:()=>ip,bulkStore:()=>pp,destroy:()=>op,fetchAll:()=>dp,fetchById:()=>cp,softDelete:()=>ap,store:()=>mp,update:()=>fp,updateDeliverySettings:()=>yp,updateStatus:()=>wp});import{db as qr,matchedRows as np}from"@stacksjs/database/runtime";async function op(e){try{let t=await qr.deleteFrom("digital_deliveries").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete digital delivery: ${t.message}`);throw t}}async function ap(e){try{return(await np(qr.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${t.message}`);throw t}}async function sp(e){if(!e.length)return 0;try{let t=await qr.deleteFrom("digital_deliveries").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${t.message}`);throw t}}async function ip(e){if(!e.length)return 0;try{return(await np(qr.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${t.message}`);throw t}}import{db as up}from"@stacksjs/database/runtime";async function cp(e){let t=await up.selectFrom("digital_deliveries").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function dp(){return P(await up.selectFrom("digital_deliveries").selectAll().execute())}var{randomUUIDv7:lp}=globalThis.Bun;import{db as Ua}from"@stacksjs/database/runtime";async function mp(e){try{let t=lp(),r={...zt(e),uuid:t};await Ua.insertInto("digital_deliveries").values(r).executeTakeFirst();let n=await Ua.selectFrom("digital_deliveries").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created digital delivery");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create digital delivery: ${t.message}`);throw t}}async function pp(e){if(!e.length)return 0;try{let t=e.map((n)=>({...zt(n),uuid:lp()})),r=await Ua.insertInto("digital_deliveries").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${t.message}`);throw t}}import{db as Ja}from"@stacksjs/database/runtime";import{formatDate as Wa}from"@stacksjs/orm";async function fp(e,t){try{if(!e)throw Error("Digital delivery ID is required for update");let r=await Ja.updateTable("digital_deliveries").set({...zt(t),updated_at:Wa(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function wp(e,t){try{let r=await Ja.updateTable("digital_deliveries").set({status:t,updated_at:Wa(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function yp(e,t,r,n,o){try{let a={updated_at:Wa(new Date)};if(t!==void 0)a.download_limit=t;if(r!==void 0)a.expiry_days=r;if(n!==void 0)a.requires_login=n;if(o!==void 0)a.automatic_delivery=o;let s=await Ja.updateTable("digital_deliveries").set(a).where("id","=",e).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return w(s)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var Kr={};E(Kr,{bulkDestroy:()=>xp,bulkStore:()=>vp,destroy:()=>_p,fetchAll:()=>hp,fetchById:()=>Hr,store:()=>Pp,update:()=>Dp,updateContact:()=>kp,updateStatus:()=>Sp});import{db as bp}from"@stacksjs/database/runtime";import{db as gp}from"@stacksjs/database/runtime";async function Hr(e){let t=await gp.selectFrom("couriers").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function hp(){return P(await gp.selectFrom("couriers").selectAll().execute())}async function _p(e){try{let t=await bp.deleteFrom("couriers").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete courier: ${t.message}`);throw t}}async function xp(e){if(!e.length)return 0;let t=0;try{return await bp.transaction(async(r)=>{for(let n of e)if(await Hr(n))await r.deleteFrom("couriers").where("id","=",n).execute(),t++}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to delete couriers in bulk: ${r.message}`);throw r}}var{randomUUIDv7:Rp}=globalThis.Bun;import{db as La}from"@stacksjs/database/runtime";async function Pp(e){try{let t=Rp(),r={...qt(e),uuid:t};await La.insertInto("couriers").values(r).executeTakeFirst();let n=await La.selectFrom("couriers").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created courier");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create courier: ${t.message}`);throw t}}async function vp(e){if(!e.length)return 0;try{let t=e.map((n)=>({...qt(n),uuid:Rp()})),r=await La.insertInto("couriers").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create couriers in bulk: ${t.message}`);throw t}}import{db as ja}from"@stacksjs/database/runtime";import{formatDate as za}from"@stacksjs/orm";async function Dp(e,t){try{if(!e)throw Error("Courier ID is required for update");let r=await ja.updateTable("couriers").set({...qt(t),updated_at:za(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier: ${r.message}`);throw r}}async function Sp(e,t){try{let r=await ja.updateTable("couriers").set({status:t,updated_at:za(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update courier status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier status: ${r.message}`);throw r}}async function kp(e,t){try{let r={updated_at:za(new Date)};if(t!==void 0)r.phone=t;let n=await ja.updateTable("couriers").set(r).where("id","=",e).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update contact information");return w(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var Xr={};E(Xr,{PRECISION_RANK:()=>Ht,checkCoverage:()=>Zh,formatQuery:()=>wt,geocode:()=>Kh,geocodingDriver:()=>Ip,nominatimDriver:()=>Yr,setGeocodingDriver:()=>Hh});var tt=(e)=>e*Math.PI/180;function We(e,t){let r=tt(t.latitude-e.latitude),n=tt(t.longitude-e.longitude),o=tt(e.latitude),a=tt(t.latitude),s=Math.sin(r/2)**2+Math.sin(n/2)**2*Math.cos(o)*Math.cos(a);return 12742017.6*Math.asin(Math.sqrt(s))}function Zr(e,t){let r=tt(e.latitude),n=tt(t.latitude),o=tt(t.longitude-e.longitude),a=Math.sin(o)*Math.cos(n),s=Math.cos(r)*Math.sin(n)-Math.sin(r)*Math.cos(n)*Math.cos(o);return(Math.atan2(a,s)*180/Math.PI+360)%360}function Qr(e,t,r={}){let n=r.detourFactor??1.35,o=r.minimumSeconds??30;if(!Number.isFinite(t)||t<=0.5)return null;let a=e*n/t;return Math.max(o,Math.round(a))}function Cp(e,t,r){return We(e,t)<=r}function Vt(e){return typeof e?.latitude==="number"&&typeof e?.longitude==="number"&&Number.isFinite(e.latitude)&&Number.isFinite(e.longitude)}var Ht={unknown:0,locality:1,postal:2,street:3,rooftop:4};function wt(e){return[e.street,e.city,e.region,e.postalCode,e.country].map((t)=>String(t??"").trim()).filter(Boolean).join(", ")}var Gh="https://nominatim.openstreetmap.org/search",Tp=1000,Ap=0,Ep=Promise.resolve();async function qh(e){let t=Ep.then(async()=>{let r=Date.now()-Ap;if(r<Tp)await Bun.sleep(Tp-r);return Ap=Date.now(),e()});return Ep=t.then(()=>{return},()=>{return}),t}function Vh(e){let t=e.address??{},r=String(e.addresstype??""),n=String(e.type??""),o=String(e.category??e.class??"");if(t.house_number||n==="house"||n==="building"||r==="building")return"rooftop";if(t.road||o==="highway"||r==="road")return"street";if(r==="postcode"||t.postcode&&!t.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(r))return"locality";return"unknown"}function Yr(e={}){let t=e.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,r=e.endpoint??Gh;return{name:"nominatim",async geocode(n){let o=wt(n);if(!o)return null;let a=new URL(r);if(a.searchParams.set("q",o),a.searchParams.set("format","jsonv2"),a.searchParams.set("limit","1"),a.searchParams.set("addressdetails","1"),n.country)a.searchParams.set("countrycodes",n.country.toLowerCase());let s=await qh(()=>fetch(a,{headers:{"user-agent":t,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),d=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(d))return null;let m=Vh(u);return{latitude:c,longitude:d,formatted:String(u.display_name??o),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[m],precision:m,provider:"nominatim"}}}}var Fp=null;function Hh(e){Fp=e}function Ip(){return Fp??Yr()}async function Kh(e,t={}){let r=t.driver??Ip(),n=t.minimumPrecision??"street",o=`geocode:${r.name}:${wt(e).toLowerCase()}`,a=await Qh(o);if(a!==void 0)return a;let s=await r.geocode(e),i=s&&Ht[s.precision]>=Ht[n]?s:null;return await Yh(o,i,i?t.cacheSeconds??2592000:600),i}function Zh(e,t,r){if(t.length===0)return null;let n=t[0],o=We(e,n);for(let a of t.slice(1)){let s=We(e,a);if(s<o)o=s,n=a}return{covered:o<=r,distanceMeters:Math.round(o),nearest:n}}async function Qh(e){try{let r=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!r)return;let n=await r.get(e);if(n===null||n===void 0)return;return n==="null"?null:JSON.parse(String(n))}catch{return}}async function Yh(e,t,r){try{let o=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!o)return;await o.set(e,t===null?"null":JSON.stringify(t),r)}catch{}}var rn={};E(rn,{LicenseKeyInputError:()=>G,bulkDestroy:()=>$p,bulkSoftDelete:()=>Bp,bulkStore:()=>qp,destroy:()=>Np,fetchAll:()=>Wp,fetchById:()=>Jp,softDelete:()=>Op,store:()=>Gp,update:()=>Vp,updateExpiration:()=>Kp,updateStatus:()=>Hp,validateLicenseKeyWrite:()=>rt});import{db as en,matchedRows as Mp}from"@stacksjs/database/runtime";async function Np(e){try{let t=await en.deleteFrom("license_keys").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete license key: ${t.message}`);throw t}}async function Op(e){try{return(await Mp(en.updateTable("license_keys").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete license key: ${t.message}`);throw t}}async function $p(e){if(!e.length)return 0;try{let t=await en.deleteFrom("license_keys").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete license keys: ${t.message}`);throw t}}async function Bp(e){if(!e.length)return 0;try{return(await Mp(en.updateTable("license_keys").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete license keys: ${t.message}`);throw t}}import{db as Up}from"@stacksjs/database/runtime";async function Jp(e){let t=await Up.selectFrom("license_keys").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Wp(){return P(await Up.selectFrom("license_keys").selectAll().execute())}var{randomUUIDv7:zp}=globalThis.Bun;import{db as Va}from"@stacksjs/database/runtime";import{db as Ga}from"@stacksjs/database/runtime";var Lp=["Standard License","Premium License","Enterprise License"],jp=["active","inactive","unassigned"];class G extends TypeError{constructor(e){super(e);this.name="LicenseKeyInputError"}}function Kt(e,t,r){return e[r]!==void 0?e[r]:t?.[r]}function qa(e,t,r,n){let o=Kt(e,t,r);if(o===void 0||o===null||o==="")return null;let a=Number(o);if(!Number.isSafeInteger(a)||a<1)throw new G(`${n} must be a positive integer or null.`);return a}function Xh(e){if(typeof e==="number")return e>2147483647?Math.floor(e/1000):e;if(typeof e==="string"&&/^\d{10,13}$/.test(e))return e.length===13?Math.floor(Number(e)/1000):Number(e);if(typeof e==="string"){let t=/^\d{4}-\d{2}-\d{2} \d/.test(e)?`${e.replace(" ","T")}Z`:e;return Math.floor(new Date(t).getTime()/1000)}return Number.NaN}async function rt(e,t){let r=String(Kt(e,t,"key")||"").trim().toUpperCase(),n=String(Kt(e,t,"template")||""),o=String(Kt(e,t,"status")||""),a=Xh(Kt(e,t,"expiry_date")),s=qa(e,t,"customer_id","Customer"),i=qa(e,t,"product_id","Product"),u=qa(e,t,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new G("License key must use five groups of four uppercase letters or numbers.");if(!Lp.includes(n))throw new G(`Template must be one of: ${Lp.join(", ")}.`);if(!jp.includes(o))throw new G(`Status must be one of: ${jp.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new G("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,d,m]=await Promise.all([s?Ga.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?Ga.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?Ga.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new G(`Customer ${s} was not found.`);if(i&&!d)throw new G(`Product ${i} was not found.`);if(u&&!m)throw new G(`Order ${u} was not found.`);if(s&&m?.customer_id&&Number(m.customer_id)!==s)throw new G(`Order ${u} belongs to Customer ${m.customer_id}, not Customer ${s}.`);return{...e,key:r,template:n,expiry_date:a,status:o,customer_id:s,product_id:i,order_id:u}}async function Gp(e){try{let t=zp(),r=Gt(e),n={...await rt(r),uuid:t};await Va.insertInto("license_keys").values(n).executeTakeFirst();let o=await Va.selectFrom("license_keys").where("uuid","=",t).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created license key");return w(o)}catch(t){if(t instanceof G)throw t;if(t instanceof Error){if(t.message.includes("UNIQUE constraint failed: license_keys.key"))throw new G("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${t.message}`)}throw t}}async function qp(e){if(!e.length)return 0;try{let t=await Promise.all(e.map(async(n)=>({...await rt(Gt(n)),uuid:zp()}))),r=await Va.insertInto("license_keys").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof G)throw t;if(t instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${t.message}`);throw t}}import{db as tn}from"@stacksjs/database/runtime";import{formatDate as Ha}from"@stacksjs/orm";async function Vp(e,t){try{if(!e)throw Error("License key ID is required for update");let r=await tn.selectFrom("license_keys").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=Gt(t),o=await rt(n,r),a=await tn.updateTable("license_keys").set({...o,updated_at:Ha(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!a)return;return w(a)}catch(r){if(r instanceof G)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new G("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function Hp(e,t){try{let r=await tn.updateTable("license_keys").set({status:t,updated_at:Ha(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function Kp(e,t){try{let r={updated_at:Ha(new Date)};if(t!==void 0)r.expiry_date=t;let n=await tn.updateTable("license_keys").set(r).where("id","=",e).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update expiration information");return w(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var sn={};E(sn,{bulkDestroy:()=>Xp,bulkSoftDelete:()=>ef,bulkStore:()=>of,destroy:()=>Qp,fetchAll:()=>tf,fetchById:()=>an,formatShippingOptions:()=>af,getActiveShippingMethods:()=>sf,softDelete:()=>Yp,store:()=>nf,update:()=>uf,updatePricing:()=>df,updateStatus:()=>cf});import{db as nn,matchedRows as Zp}from"@stacksjs/database/runtime";async function Qp(e){try{let t=await nn.deleteFrom("shipping_methods").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping method: ${t.message}`);throw t}}async function Yp(e){try{return(await Zp(nn.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${t.message}`);throw t}}async function Xp(e){if(!e.length)return 0;try{let t=await nn.deleteFrom("shipping_methods").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping methods: ${t.message}`);throw t}}async function ef(e){if(!e.length)return 0;try{return(await Zp(nn.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${t.message}`);throw t}}import{db as on}from"@stacksjs/database/runtime";async function an(e){let t=await on.selectFrom("shipping_methods").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=await on.selectFrom("shipping_zones").where("shipping_method_id","=",e).selectAll().execute();return{...t,shippingZones:r}}return}async function tf(){let e=await on.selectFrom("shipping_methods").selectAll().execute();if(e.length===0)return[];let t=[...new Set(e.map((a)=>a.id))],o=(await on.selectFrom("shipping_zones").where("shipping_method_id","in",t).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 e.map((a)=>({...a,shipping_zones:o[a.id]||[]}))}var{randomUUIDv7:rf}=globalThis.Bun;import{db as Zt}from"@stacksjs/database/runtime";async function nf(e){try{let t=rf(),r={...Lt(e),uuid:t};await Zt.insertInto("shipping_methods").values(r).executeTakeFirst();let n=await Zt.selectFrom("shipping_methods").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created shipping method");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping method: ${t.message}`);throw t}}async function of(e){if(!e.length)return 0;try{let t=e.map((n)=>({...Lt(n),uuid:rf()})),r=await Zt.insertInto("shipping_methods").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${t.message}`);throw t}}function af(){try{return Zt.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(e){if(e instanceof Error)throw TypeError(`Failed to format shipping options: ${e.message}`);throw e}}async function sf(){try{let e=await Zt.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute();return P(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get active shipping methods: ${e.message}`);throw e}}import{db as Ka}from"@stacksjs/database/runtime";import{formatDate as Za}from"@stacksjs/orm";async function uf(e,t){try{if(!e)throw Error("Shipping method ID is required for update");let r=await Ka.updateTable("shipping_methods").set({...Lt(t),updated_at:Za(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function cf(e,t){try{let r=await Ka.updateTable("shipping_methods").set({status:t,updated_at:Za(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function df(e,t,r){try{let n={updated_at:Za(new Date)};if(t!==void 0)n.base_rate=t;if(r!==void 0)n.free_shipping=r;let o=await Ka.updateTable("shipping_methods").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update pricing information");return w(o)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update pricing information: ${n.message}`);throw n}}var mn={};E(mn,{ShippingRateInputError:()=>Y,bulkDestroy:()=>mf,bulkStore:()=>Tf,bulkUpdate:()=>Ef,destroy:()=>lf,destroyByMethod:()=>ff,destroyByZone:()=>pf,fetchAll:()=>gf,fetchById:()=>yf,formatShippingRateOptions:()=>xf,getRateByWeightAndAddress:()=>bf,getRateByWeightAndZone:()=>Qa,getRatesByZone:()=>hf,getShippingRatesByMethod:()=>Rf,resolveZoneForAddress:()=>cn,store:()=>Cf,update:()=>Af,updateByMethod:()=>If,updateByZone:()=>Ff,validateShippingRateWrite:()=>nt,validateZoneMatchesAddress:()=>_f});import{db as un}from"@stacksjs/database/runtime";async function lf(e){try{let t=await un.deleteFrom("shipping_rates").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rate: ${t.message}`);throw t}}async function mf(e){if(!e.length)return 0;try{let t=await un.deleteFrom("shipping_rates").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates: ${t.message}`);throw t}}async function pf(e){try{let t=await un.deleteFrom("shipping_rates").where("shipping_zone_id","=",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${t.message}`);throw t}}async function ff(e){try{let t=await un.deleteFrom("shipping_rates").where("shipping_method_id","=",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${t.message}`);throw t}}import{db as me}from"@stacksjs/database/runtime";async function yf(e){let t=await me.selectFrom("shipping_rates").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=null,n=null;if(t.shipping_zone_id)r=await me.selectFrom("shipping_zones").where("id","=",t.shipping_zone_id).selectAll().executeTakeFirst();if(t.shipping_method_id)n=await me.selectFrom("shipping_methods").where("id","=",t.shipping_method_id).selectAll().executeTakeFirst();return{...t,shipping_zone:r,shipping_method:n}}return}async function gf(){let e=await me.selectFrom("shipping_rates").selectAll().execute();if(e.length===0)return[];let t=[...new Set(e.map((i)=>i.shipping_zone_id).filter((i)=>i!==null&&i!==void 0))],r=[...new Set(e.map((i)=>i.shipping_method_id).filter((i)=>i!==null&&i!==void 0))],[n,o]=await Promise.all([t.length?me.selectFrom("shipping_zones").where("id","in",t).selectAll().execute():[],r.length?me.selectFrom("shipping_methods").where("id","in",r).selectAll().execute():[]]),a=n.reduce((i,u)=>(i[u.id]=u,i),{}),s=o.reduce((i,u)=>(i[u.id]=u,i),{});return e.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 hf(e){try{let t=await me.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).orderBy("weight_from").execute();return P(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${t.message}`);throw t}}async function Qa(e,t){try{let r=await me.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).where("weight_from","<=",e).where("weight_to",">=",e).executeTakeFirst();return w(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 cn(e){if(!e?.countryCode)return null;try{let t=await me.selectFrom("shipping_zones").selectAll().where("countries","like",`%${e.countryCode}%`).where("status","=","active").execute();if(t.length===0)return null;let r=null;for(let n of t){let o=1;if(e.region&&n.regions&&wf(n.regions,e.region))o=2;if(e.postalCode&&n.postal_codes&&wf(n.postal_codes,e.postalCode))o=3;if(!r||o>r.score)r={id:n.id,score:o}}return r?.id??null}catch{return null}}async function bf(e,t){let r=await cn(t);if(r==null)return;return Qa(e,r)}async function _f(e,t){return await cn(t)===e}function wf(e,t){if(!e||!t)return!1;let r=t.trim().toUpperCase();for(let n of e.split(/[,|;]/))if(n.trim().toUpperCase()===r)return!0;return!1}async function xf(){try{return(await me.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((t)=>t.shipping_method_id!==null&&t.shipping_method_id!==void 0&&t.shipping_zone_id!==null&&t.shipping_zone_id!==void 0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to format shipping rate options: ${e.message}`);throw e}}async function Rf(e){try{let t=await me.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",e).orderBy("weight_from").execute();return P(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${t.message}`);throw t}}var{randomUUIDv7:kf}=globalThis.Bun;import{db as Ya}from"@stacksjs/database/runtime";import{db as Qt}from"@stacksjs/database/runtime";async function Pf(){return P(await Qt.selectFrom("shipping_zones").selectAll().execute())}async function dn(e){let t=await Qt.selectFrom("shipping_zones").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}function vf(){try{return Qt.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(e){if(e instanceof Error)throw TypeError(`Failed to format shipping zone options: ${e.message}`);throw e}}async function Df(){try{let e=await Qt.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute();return P(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get active shipping zones: ${e.message}`);throw e}}async function Sf(e){try{let t=await Qt.selectFrom("shipping_zones").selectAll().where("countries","like",`%${e}%`).where("status","=","active").orderBy("name").execute();return P(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${t.message}`);throw t}}class Y extends TypeError{constructor(e){super(e);this.name="ShippingRateInputError"}}function Yt(e,t,r){return Number(e[r]??t?.[r])}async function nt(e,t){let r=Yt(e,t,"shipping_method_id"),n=Yt(e,t,"shipping_zone_id"),o=Yt(e,t,"weight_from"),a=Yt(e,t,"weight_to"),s=Yt(e,t,"rate");if(!Number.isSafeInteger(r)||r<1)throw new Y("Shipping method must be a positive integer.");if(!Number.isSafeInteger(n)||n<1)throw new Y("Shipping zone must be a positive integer.");if(!Number.isFinite(o)||o<0)throw new Y("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<o)throw new Y("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new Y("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([an(r),dn(n)]);if(!i)throw new Y(`Shipping method ${r} was not found.`);if(!u)throw new Y(`Shipping zone ${n} was not found.`);if(Number(u.shipping_method_id)!==r)throw new Y(`Shipping zone ${n} is not assigned to shipping method ${r}.`)}async function Cf(e){try{let t=Ee(e),r=Number(t.shipping_method_id),n=Number(t.shipping_zone_id);await nt(t);let o=kf(),a={...t,shipping_method_id:r,shipping_zone_id:n,uuid:o};await Ya.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await Ya.selectFrom("shipping_rates").where("uuid","=",o).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return w(s)}catch(t){if(t instanceof Y)throw t;if(t instanceof Error)throw TypeError(`Failed to create shipping rate: ${t.message}`);throw t}}async function Tf(e){if(!e.length)return 0;try{for(let n of e){let o=Ee(n);await nt(o)}let t=e.map((n)=>({...Ee(n),uuid:kf()})),r=await Ya.insertInto("shipping_rates").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Y)throw t;if(t instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${t.message}`);throw t}}import{db as Xt,matchedRows as Xa}from"@stacksjs/database/runtime";import{formatDate as ln}from"@stacksjs/orm";async function Af(e,t){try{if(!e)throw Error("Shipping rate ID is required for update");let r=await Xt.selectFrom("shipping_rates").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=Ee(t);await nt(n,r);let o=await Xt.updateTable("shipping_rates").set({...n,updated_at:ln(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!o)return;return w(o)}catch(r){if(r instanceof Y)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function Ef(e){if(!e.length)return 0;try{let t=0;for(let{id:r,data:n}of e)if((await Xa(Xt.updateTable("shipping_rates").set({...Ee(n),updated_at:ln(new Date)}).where("id","=",r))).length>0)t++;return t}catch(t){if(t instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${t.message}`);throw t}}async function Ff(e,t){try{return(await Xa(Xt.updateTable("shipping_rates").set({...Ee(t),updated_at:ln(new Date)}).where("shipping_zone_id","=",e))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function If(e,t){try{return(await Xa(Xt.updateTable("shipping_rates").set({...Ee(t),updated_at:ln(new Date)}).where("shipping_method_id","=",e))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var _n={};E(_n,{ARRIVAL_RADIUS_METERS:()=>rs,NEARBY_RADIUS_METERS:()=>ts,assignStop:()=>Nf,bearingInDegrees:()=>Zr,broadcastToChannel:()=>Fe,completeStop:()=>$f,distanceInMeters:()=>We,emitDeliveryArrived:()=>gn,emitDeliveryAssigned:()=>fn,emitDeliveryCompleted:()=>hn,emitDeliveryFailed:()=>bn,emitDeliveryNearby:()=>yn,emitDeliveryPosition:()=>pn,emitDeliveryStarted:()=>wn,estimateSecondsRemaining:()=>Qr,failStop:()=>Bf,hasCoordinates:()=>Vt,isWithin:()=>Cp,orderTrackingChannel:()=>Le,recordCourierPing:()=>Mf,routeTrackingChannel:()=>es,startRoute:()=>Uf,startStop:()=>Of});function Le(e){return`order.${e}`}function es(e){return`delivery-route.${e}`}async function yt(e,t){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let n=r.dispatch;if(typeof n!=="function")return;n(e,t)}catch{}}async function Fe(e,t,r){try{let n=await import("@stacksjs/realtime").catch(()=>null);if(!n)return;let o=n.channel;if(typeof o!=="function")return;await o(e).broadcast(t,r,"private")}catch{}}async function pn(e,t,r){await Promise.all([...e.map((n)=>Fe(Le(n),"delivery:position",r)),t==null?Promise.resolve():Fe(es(t),"delivery:position",r)])}async function fn(e){if(await yt("delivery:assigned",{stop:e}),e.order_id!=null)await Fe(Le(e.order_id),"delivery:assigned",{stop:e})}async function wn(e){if(await yt("delivery:started",{stop:e}),e.order_id!=null)await Fe(Le(e.order_id),"delivery:started",{stop:e})}async function yn(e,t,r){if(await yt("delivery:nearby",{stop:e,distanceMeters:t,etaSeconds:r}),e.order_id!=null)await Fe(Le(e.order_id),"delivery:nearby",{stop:e,distanceMeters:t,etaSeconds:r})}async function gn(e){if(await yt("delivery:arrived",{stop:e}),e.order_id!=null)await Fe(Le(e.order_id),"delivery:arrived",{stop:e})}async function hn(e){if(await yt("delivery:completed",{stop:e}),e.order_id!=null)await Fe(Le(e.order_id),"delivery:completed",{stop:e})}async function bn(e,t){await yt("delivery:failed",{stop:e,reason:t})}var{randomUUIDv7:eb}=globalThis.Bun;import{db as Ie}from"@stacksjs/database/runtime";var ts=400,rs=60,tb=250;async function Mf(e){let t=e.recordedAt??new Date().toISOString(),r=typeof e.accuracy!=="number"||e.accuracy<=tb,n=await Ie.selectFrom("couriers").where("id","=",e.courierId).select(["id","latitude","longitude"]).executeTakeFirst();if(!n)throw Error(`Unknown courier: ${e.courierId}`);let o=Vt(n)?{latitude:n.latitude,longitude:n.longitude}:null,a=typeof e.heading==="number"?e.heading:o?Zr(o,e):null,s=await rb(e.courierId),i=s?await nb(s.id):null,u=null,c=null,d=!1,m=!1,l=i&&Vt({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&l)u=Math.round(We(e,l)),c=Qr(u,e.speed??0),m=u<=rs&&i.arrived_at==null,d=!m&&u<=ts&&i.status==="en_route"&&i.notified_nearby_at==null;let y=await ob({courierId:e.courierId,routeId:s?.id??null,latitude:e.latitude,longitude:e.longitude,heading:a,speed:e.speed??null,accuracy:e.accuracy??null,recordedAt:t});if(r)await Ie.updateTable("couriers").set({latitude:e.latitude,longitude:e.longitude,heading:a,speed:e.speed??0,last_ping_at:t}).where("id","=",e.courierId).execute();if(i&&(u!=null||c!=null))await Ie.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 pn(i?.order_id==null?[]:[i.order_id],s?.id??null,{courierId:e.courierId,routeId:s?.id??null,latitude:e.latitude,longitude:e.longitude,heading:a,speed:e.speed??null,accuracy:e.accuracy??null,recordedAt:t,distanceToStopMeters:u,etaSeconds:c});if(d&&i)await Ie.updateTable("delivery_stops").set({notified_nearby_at:t}).where("id","=",i.id).execute(),await yn(i,u,c);if(m&&i)await Ie.updateTable("delivery_stops").set({status:"arrived",arrived_at:t}).where("id","=",i.id).execute(),await gn({...i,status:"arrived",arrived_at:t});return{pingId:y,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:d,crossedArrival:m}}async function rb(e){return await Ie.selectFrom("delivery_routes").where("courier_id","=",e).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function nb(e){let t=await Ie.selectFrom("delivery_stops").where("delivery_route_id","=",e).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 t.find((r)=>r.status==="en_route")??t.find((r)=>r.status==="arrived")??t[0]??null}async function ob(e){let t=eb();return await Ie.insertInto("courier_pings").values({uuid:t,courier_id:e.courierId,delivery_route_id:e.routeId,latitude:e.latitude,longitude:e.longitude,heading:e.heading,speed:e.speed??0,accuracy:e.accuracy,recorded_at:e.recordedAt}).executeTakeFirst(),(await Ie.selectFrom("courier_pings").where("uuid","=",t).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:ab}=globalThis.Bun;import{db as X}from"@stacksjs/database/runtime";function ns(e){return e.type==="pickup"}async function Nf(e){let t=ab(),r=e.sequence??await ib(e.deliveryRouteId);await X.insertInto("delivery_stops").values({uuid:t,delivery_route_id:e.deliveryRouteId,order_id:e.orderId??null,sequence:r,status:"pending",address:e.address,latitude:e.latitude??null,longitude:e.longitude??null,recipient_name:e.recipientName??null,recipient_phone:e.recipientPhone??null,eta_at:e.etaAt??null,type:e.type??"dropoff"}).executeTakeFirst();let n=await cb(t);if(n)await fn(n);return n??{}}async function Of(e){await X.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",e).execute();let t=await as(e);if(!t)return null;if(t.order_id!=null&&!ns(t))await os(t.order_id,"OUT_FOR_DELIVERY");return await wn(t),t}async function $f(e,t){let r=new Date().toISOString();await X.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await ub(e)?{}:{arrived_at:r},...t?{notes:t}:{}}).where("id","=",e).execute();let n=await as(e);if(!n)return null;if(n.order_id!=null)await os(n.order_id,ns(n)?"OUT_FOR_DELIVERY":"DELIVERED");return await hn(n),await Jf(n.delivery_route_id),n}async function Bf(e,t){await X.updateTable("delivery_stops").set({status:"failed",notes:t}).where("id","=",e).execute();let r=await as(e);if(!r)return null;if(r.order_id!=null&&!ns(r))await os(r.order_id,"SHIPPED");return await bn(r,t),await Jf(r.delivery_route_id),r}async function Uf(e){await X.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",e).execute()}async function Jf(e){if(e==null)return;if(await X.selectFrom("delivery_stops").where("delivery_route_id","=",e).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await X.selectFrom("delivery_routes").where("id","=",e).select(["courier_id"]).executeTakeFirst();if(await X.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",e).execute(),r?.courier_id!=null)await X.updateTable("couriers").set({status:"active"}).where("id","=",r.courier_id).execute()}async function os(e,t){let r=await X.selectFrom("orders").where("id","=",e).select(["id","status"]).executeTakeFirst();if(!r)return;let n=await Promise.resolve().then(() => (dt(),{}));let s=sb(r.status,t,Ue);if(s.length===0){let{log:i}=await import("@stacksjs/logging").catch(()=>({log:null}));i?.warn(`[delivery] refused to move order ${e} from ${r.status} to ${t}: no legal transition`);return}for(let i of s)await X.updateTable("orders").set({status:i}).where("id","=",e).execute(),await ct(i,{...r,status:i})}function sb(e,t,r){if(e===t)return[];if(r(e,t))return[t];for(let n of["PROCESSING","SHIPPED"]){if(n===e||n===t)continue;if(r(e,n)&&r(n,t))return[n,t]}return[]}async function ib(e){return(await X.selectFrom("delivery_stops").where("delivery_route_id","=",e).select(["sequence"]).execute()).reduce((r,n)=>Math.max(r,n.sequence??0),0)+1}async function ub(e){return(await X.selectFrom("delivery_stops").where("id","=",e).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function as(e){return await X.selectFrom("delivery_stops").where("id","=",e).selectAll().executeTakeFirst()??null}async function cb(e){return await X.selectFrom("delivery_stops").where("uuid","=",e).selectAll().executeTakeFirst()??null}var vn={};E(vn,{bulkDestroy:()=>zf,bulkSoftDelete:()=>Gf,bulkStore:()=>Hf,destroy:()=>Lf,fetchAll:()=>Pf,fetchById:()=>dn,formatZoneOptions:()=>vf,getActiveShippingZones:()=>Df,getZonesByCountry:()=>Sf,softDelete:()=>jf,store:()=>Vf,update:()=>Kf,updateCountries:()=>Qf,updateRegionsAndPostalCodes:()=>Yf,updateStatus:()=>Zf});import{db as xn,matchedRows as Wf}from"@stacksjs/database/runtime";async function Lf(e){try{let t=await xn.deleteFrom("shipping_zones").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping zone: ${t.message}`);throw t}}async function jf(e){try{return(await Wf(xn.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${t.message}`);throw t}}async function zf(e){if(!e.length)return 0;try{let t=await xn.deleteFrom("shipping_zones").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping zones: ${t.message}`);throw t}}async function Gf(e){if(!e.length)return 0;try{return(await Wf(xn.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${t.message}`);throw t}}var{randomUUIDv7:qf}=globalThis.Bun;import{db as ss}from"@stacksjs/database/runtime";async function Vf(e){try{let t=qf(),r={...jt(e),uuid:t};await ss.insertInto("shipping_zones").values(r).executeTakeFirst();let n=await ss.selectFrom("shipping_zones").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created shipping zone");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping zone: ${t.message}`);throw t}}async function Hf(e){if(!e.length)return 0;try{let t=e.map((n)=>({...jt(n),uuid:qf()})),r=await ss.insertInto("shipping_zones").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${t.message}`);throw t}}import{db as Rn}from"@stacksjs/database/runtime";import{formatDate as Pn}from"@stacksjs/orm";async function Kf(e,t){try{if(!e)throw Error("Shipping zone ID is required for update");let r=await Rn.updateTable("shipping_zones").set({...jt(t),updated_at:Pn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function Zf(e,t){try{let r=await Rn.updateTable("shipping_zones").set({status:t,updated_at:Pn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function Qf(e,t){try{let r=await Rn.updateTable("shipping_zones").set({countries:t,updated_at:Pn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function Yf(e,t,r){try{let n={updated_at:Pn(new Date)};if(t!==void 0)n.regions=t;if(r!==void 0)n.postal_codes=r;let o=await Rn.updateTable("shipping_zones").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update regions and postal codes");return w(o)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${n.message}`);throw n}}var db={digital:Vr,couriers:Kr,geocoding:Xr,licenses:rn,methods:sn,rates:mn,routes:Gr,tracking:_n,zones:vn},lb=db;var ds={};E(ds,{activeTaxRates:()=>us,breakdownFor:()=>cs,bulkDestroy:()=>rw,bulkStore:()=>cw,destroy:()=>tw,fetchAll:()=>aw,fetchById:()=>ow,store:()=>uw,taxFor:()=>Xf,update:()=>dw,updateDefaultStatus:()=>pw,updateRate:()=>mw,updateStatus:()=>lw});import{db as mb}from"@stacksjs/database/runtime";function pb(e){let t=Number(e);return Number.isFinite(t)?t/100:0}async function us(e={}){let t=mb.selectFrom("tax_rates").where("status","=","active").selectAll();if(e.country)t=t.where("country","=",e.country);let r=await t.execute();if(!e.codes?.length)return r;let n=new Set(e.codes);return r.filter((o)=>n.has(String(o.code??"")))}function cs(e,t,r={}){let n=Math.max(0,Math.round(e)),o=[],a=0,s=0;for(let i of t){let u=pb(i.rate),c=Math.round(n*u),d=Boolean(r.exempt&&i.exemptible);if(d)s+=c;else a+=c;o.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:d?0:c,exempted:d})}return{taxable:n,components:o,tax:a,exempted:s}}async function Xf(e,t={}){return cs(e,await us(t),t)}import{db as ew}from"@stacksjs/database/runtime";async function tw(e){try{let t=await ew.deleteFrom("tax_rates").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete tax rate: ${t.message}`);throw t}}async function rw(e){if(!e.length)return 0;try{let t=await ew.deleteFrom("tax_rates").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete tax rates: ${t.message}`);throw t}}import{db as nw}from"@stacksjs/database/runtime";async function ow(e){let t=await nw.selectFrom("tax_rates").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function aw(){return P(await nw.selectFrom("tax_rates").selectAll().execute())}var{randomUUIDv7:sw}=globalThis.Bun;import{db as iw}from"@stacksjs/database/runtime";async function uw(e){try{return await iw.transaction(async(t)=>{let r={...e,uuid:sw()};if(r.is_default)await t.updateTable("tax_rates").set({is_default:!1}).execute();let n=await t.insertInto("tax_rates").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create tax rate");return w(n)})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create tax rate: ${t.message}`);throw t}}async function cw(e){if(!e.length)return 0;try{return await iw.transaction(async(t)=>{let r=0;for(let n of e){let o={...n,uuid:sw()};if(o.is_default)await t.updateTable("tax_rates").set({is_default:!1}).execute();if(await t.insertInto("tax_rates").values(o).executeTakeFirst())r++}return r})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${t.message}`);throw t}}import{db as Dn}from"@stacksjs/database/runtime";import{formatDate as Sn}from"@stacksjs/orm";async function dw(e,t){try{if(!e)throw Error("Tax rate ID is required for update");return await Dn.transaction(async(r)=>{let n=await r.selectFrom("tax_rates").select("is_default").where("id","=",e).executeTakeFirst();if(!n)return;let o=t.is_default??Boolean(n.is_default),a=Sn(new Date);if(o)await r.updateTable("tax_rates").set({is_default:!1,updated_at:a}).where("id","!=",e).execute();let s=await r.updateTable("tax_rates").set({...t,updated_at:a}).where("id","=",e).returningAll().executeTakeFirst();if(!s)return;return w(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function lw(e,t){try{let r=await Dn.updateTable("tax_rates").set({status:t,updated_at:Sn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function mw(e,t){try{let r=await Dn.updateTable("tax_rates").set({rate:t,updated_at:Sn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function pw(e,t){try{return await Dn.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",e).executeTakeFirst())return!1;let o=Sn(new Date);if(t)await r.updateTable("tax_rates").set({is_default:!1,updated_at:o}).where("id","!=",e).execute();return await r.updateTable("tax_rates").set({is_default:t,updated_at:o}).where("id","=",e).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate default status: ${r.message}`);throw r}}var ys={};E(ys,{default:()=>Pb,products:()=>Cn,restaurant:()=>ht});var Cn={};E(Cn,{bulkDestroy:()=>ww,bulkStore:()=>Fw,destroy:()=>fw,fetchAll:()=>yw,fetchById:()=>er,fetchCancelledBetweenDates:()=>Pw,fetchConversionRates:()=>Sw,fetchCountBetweenDates:()=>kw,fetchCountByAllQuantities:()=>_w,fetchCountByDate:()=>hw,fetchCountByDateGrouped:()=>Cw,fetchCountByQuantity:()=>bw,fetchCountBySource:()=>gw,fetchCountByStatus:()=>Dw,fetchNotifiedBetweenDates:()=>xw,fetchPurchasedBetweenDates:()=>Rw,fetchWaiting:()=>vw,store:()=>Ew,update:()=>kn,updatePartySize:()=>Mw,updateStatus:()=>Iw});import{db as ls}from"@stacksjs/database/runtime";async function fw(e){try{let t=await ls.selectFrom("waitlist_products").where("id","=",e).selectAll().executeTakeFirst();if(!t)return;return await ls.deleteFrom("waitlist_products").where("id","=",e).execute(),w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete waitlist product: ${t.message}`);throw t}}async function ww(e){if(!e.length)return 0;try{let t=await ls.deleteFrom("waitlist_products").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${t.message}`);throw t}}import{db as j}from"@stacksjs/database/runtime";import{formatDate as z}from"@stacksjs/orm";async function er(e){let t=await j.selectFrom("waitlist_products").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function yw(){return P(await j.selectFrom("waitlist_products").selectAll().execute())}async function gw(e,t){let r=j.selectFrom("waitlist_products").select(["source",j.fn.count("id").as("count")]).groupBy("source");if(e&&t){let o=z(e),a=z(t);r=r.where("created_at",">=",o).where("created_at","<=",a)}return(await r.execute()).reduce((o,{source:a,count:s})=>(o[a]=s,o),{})}async function hw(e=new Date){let t=new Date(e);t.setHours(0,0,0,0);let r=new Date(e);r.setHours(23,59,59,999);let n=z(t),o=z(r);return(await j.selectFrom("waitlist_products").select(j.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",o).executeTakeFirst())?.count??0}async function bw(e){return(await j.selectFrom("waitlist_products").select(j.fn.count("id").as("count")).where("quantity","=",e).executeTakeFirst())?.count??0}async function _w(e,t){let r=j.selectFrom("waitlist_products").select(["quantity",j.fn.count("id").as("count")]).groupBy("quantity");if(e&&t){let o=z(e),a=z(t);r=r.where("created_at",">=",o).where("created_at","<=",a)}return(await r.execute()).reduce((o,{quantity:a,count:s})=>(o[a]=s,o),{})}async function xw(e,t){let r=z(e),n=z(t),o=await j.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",n).whereNotNull("notified_at").execute();return P(o)}async function Rw(e,t){let r=z(e),n=z(t),o=await j.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",n).whereNotNull("purchased_at").execute();return P(o)}async function Pw(e,t){let r=z(e),n=z(t),o=await j.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",n).whereNotNull("cancelled_at").execute();return P(o)}async function vw(){let e=await j.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute();return P(e)}async function Dw(e,t,r){let n=j.selectFrom("waitlist_products").select(j.fn.count("id").as("count")).where("status","=",e);if(t&&r){let a=z(t),s=z(r);n=n.where("created_at",">=",a).where("created_at","<=",s)}return(await n.executeTakeFirst())?.count??0}async function Sw(e,t){let r=j.selectFrom("waitlist_products").select(["status",j.fn.count("id").as("count")]).groupBy("status");if(e&&t){let u=z(e),c=z(t);r=r.where("created_at",">=",u).where("created_at","<=",c)}let n=await r.execute(),o=n.reduce((u,{count:c})=>u+c,0),a=Number(n.find((u)=>u.status==="purchased")?.count??0),s=o>0?a/o*100:0,i=n.reduce((u,{status:c,count:d})=>(u[c]={count:d,percentage:o>0?d/o*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function kw(e,t){let r=z(e),n=z(t);return(await j.selectFrom("waitlist_products").select(j.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",n).executeTakeFirst())?.count??0}async function Cw(e,t){let r=j.selectFrom("waitlist_products").select(["created_at"]);if(e&&t){let a=z(e),s=z(t);r=r.where("created_at",">=",a).where("created_at","<=",s)}let o=(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(o).map(([a,s])=>({date:a,count:s})).sort((a,s)=>a.date.localeCompare(s.date))}var{randomUUIDv7:Aw}=globalThis.Bun;import{db as ms}from"@stacksjs/database/runtime";import{formatDate as Tw}from"@stacksjs/orm";var fb={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function wb(e){return typeof e==="number"||e instanceof Date?Tw(e):e}function tr(e,t={}){let r=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0));if(r.quantity===void 0&&r.party_size!==void 0)r.quantity=r.party_size;delete r.party_size;for(let o of["notified_at","purchased_at","cancelled_at"])if(r[o]!==void 0)r[o]=wb(r[o]);let n=fb[r.status];if(n&&r[n]===void 0&&!t[n])r[n]=Tw(new Date);return r}async function Ew(e){try{let t=Aw(),r={...tr(e),uuid:t,status:e.status||"waiting"};await ms.insertInto("waitlist_products").values(r).executeTakeFirst();let n=await ms.selectFrom("waitlist_products").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create waitlist product");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create waitlist product: ${t.message}`);throw t}}async function Fw(e){if(!e.length)return 0;try{let t=e.map((n)=>({...tr(n),status:n.status||"waiting",uuid:Aw()})),r=await ms.insertInto("waitlist_products").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${t.message}`);throw t}}import{db as yb}from"@stacksjs/database/runtime";import{formatDate as gb}from"@stacksjs/orm";async function kn(e,t){try{if(!e)throw Error("Waitlist product ID is required for update");let r=await er(e);if(!r)return;await yb.updateTable("waitlist_products").set({...tr(t,r),updated_at:gb(new Date)}).where("id","=",e).execute();let n=await er(e);if(!n)return;return w(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function Iw(e,t){return await kn(e,{status:t})}async function Mw(e,t){return await kn(e,{quantity:t})}var ht={};E(ht,{bulkDestroy:()=>Ow,bulkStore:()=>ny,destroy:()=>Nw,fetchAll:()=>$w,fetchAverageWaitTimes:()=>qw,fetchBetweenDates:()=>Lw,fetchById:()=>rr,fetchConversionRates:()=>Gw,fetchCountByAllPartySizes:()=>Ww,fetchCountByDate:()=>Uw,fetchCountByPartySize:()=>Jw,fetchCountByTablePreference:()=>Bw,fetchCurrentWaitTimes:()=>Yw,fetchNoShowStats:()=>Qw,fetchSeatedBetweenDates:()=>jw,fetchSeatedStats:()=>Xw,fetchSeatingRate:()=>Zw,fetchTablesTurnedToday:()=>Kw,fetchTimeSeriesStats:()=>ey,fetchWaiting:()=>zw,fetchWaitingWithPartySizes:()=>Hw,fetchWaitingWithQuotedTimes:()=>Vw,store:()=>ry,update:()=>gt,updatePartySize:()=>ay,updateQueuePosition:()=>iy,updateStatus:()=>oy,updateWaitTimes:()=>sy});import{db as ps}from"@stacksjs/database/runtime";async function Nw(e){try{let t=await ps.selectFrom("waitlist_restaurants").where("id","=",e).selectAll().executeTakeFirst();if(!t)return;return await ps.deleteFrom("waitlist_restaurants").where("id","=",e).execute(),w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${t.message}`);throw t}}async function Ow(e){if(!e.length)return 0;try{let t=await ps.deleteFrom("waitlist_restaurants").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${t.message}`);throw t}}import{db as N}from"@stacksjs/database/runtime";import{formatDate as ce}from"@stacksjs/orm";async function rr(e){let t=await N.selectFrom("waitlist_restaurants").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function $w(){return P(await N.selectFrom("waitlist_restaurants").selectAll().execute())}async function Bw(){return(await N.selectFrom("waitlist_restaurants").select(["table_preference",N.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((t,{table_preference:r,count:n})=>(t[r]=n,t),{})}async function Uw(e=new Date){let t=new Date(e);t.setHours(0,0,0,0);let r=new Date(e);r.setHours(23,59,59,999);let n=ce(t),o=ce(r);return(await N.selectFrom("waitlist_restaurants").select(N.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",o).executeTakeFirst())?.count??0}async function Jw(e){return(await N.selectFrom("waitlist_restaurants").select(N.fn.count("id").as("count")).where("party_size","=",e).executeTakeFirst())?.count??0}async function Ww(){return(await N.selectFrom("waitlist_restaurants").select(["party_size",N.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((t,{party_size:r,count:n})=>(t[r]=n,t),{})}async function Lw(e,t){let r=ce(e),n=ce(t),o=await N.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",n).execute();return P(o)}async function jw(e,t){let r=ce(e),n=ce(t),o=await N.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",n).where("status","=","seated").execute();return P(o)}async function zw(){let e=await N.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute();return P(e)}async function Gw(){let e=await N.selectFrom("waitlist_restaurants").select(["status",N.fn.count("id").as("count")]).groupBy("status").execute(),t=e.reduce((a,{count:s})=>a+s,0),r=e.find((a)=>a.status==="seated")?.count??0,n=t>0?Number(r)/t*100:0,o=e.reduce((a,{status:s,count:i})=>(a[s]={count:i,percentage:t>0?i/t*100:0},a),{});return{totalConversionRate:n,statusBreakdown:o}}async function qw(){let e=await N.selectFrom("waitlist_restaurants").select([N.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),N.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:e?.avg_quoted_wait_time??0,averageActualWaitTime:e?.avg_actual_wait_time??0}}async function Vw(){let e=P(await N.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),t=e.reduce((n,o)=>n+(o.quoted_wait_time??0),0),r=e.length>0?t/e.length:0;return{entries:e,totalQuotedWaitTime:t,averageQuotedWaitTime:r}}async function Hw(){let e=P(await N.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),t=e.reduce((o,a)=>o+a.party_size,0),r=e.length>0?t/e.length:0,n=e.reduce((o,a)=>(o[a.party_size]=(o[a.party_size]||0)+1,o),{});return{entries:e,totalPartySize:t,averagePartySize:r,partySizeBreakdown:n}}async function Kw(){let e=new Date,t=new Date(e);t.setHours(0,0,0,0);let r=new Date(e);r.setHours(23,59,59,999);let n=ce(t),o=ce(r),a=await N.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",n).where("check_in_time","<=",o).execute(),s=a.length,i=a.reduce((m,l)=>m+l.party_size,0),u=s>0?i/s:0,c=a.reduce((m,l)=>(m[l.table_preference]=(m[l.table_preference]||0)+1,m),{}),d=a.reduce((m,l)=>(m[l.party_size]=(m[l.party_size]||0)+1,m),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:d}}async function Zw(e,t){let r=ce(e),n=ce(t),o=await N.selectFrom("waitlist_restaurants").select(["status",N.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",n).groupBy("status").execute(),a=o.reduce((c,{count:d})=>c+d,0),s=o.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=o.reduce((c,{status:d,count:m})=>(c[d]={count:m,percentage:a>0?m/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function Qw(e,t){let r=ce(e),n=ce(t),o=N.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",n),a=await N.selectFrom("waitlist_restaurants").select(N.fn.count("id").as("count")).where("check_in_time",">=",r).where("check_in_time","<=",n).executeTakeFirst(),s=await o.execute(),i=s.length,u=a?.count&&a.count>0?i/a.count*100:0,c=s.reduce((p,b)=>p+(b.quoted_wait_time??0),0),d=i>0?c/i:0,m=s.reduce((p,b)=>p+b.party_size,0),l=i>0?m/i:0,y=s.reduce((p,b)=>(p[b.table_preference]=(p[b.table_preference]||0)+1,p),{}),g=s.reduce((p,b)=>(p[b.party_size]=(p[b.party_size]||0)+1,p),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:d,averagePartySize:l,breakdownByTablePreference:y,breakdownByPartySize:g}}async function Yw(){let e=await N.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),t=e.reduce((o,a)=>o+(a.quoted_wait_time||0),0),r=e.reduce((o,a)=>o+(a.actual_wait_time||0),0),n=e.length;return{averageQuoted:n>0?t/n:0,averageActual:n>0?r/n:0}}async function Xw(){let e=Date.now()-86400000,t=await N.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",e).execute(),r=Array.from({length:24},(n,o)=>({hour:o,count:t.filter((a)=>a.seated_at===o).length}));return{total:t.length,byHour:r}}async function ey(){return(await N.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((t,r)=>{let n=r.created_at;if(!t[n])t[n]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return t[n].total++,t[n][r.status]++,t},{})}var{randomUUIDv7:ty}=globalThis.Bun;import{db as ws}from"@stacksjs/database/runtime";import{formatDate as fs}from"@stacksjs/orm";var hb={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function bb(e){if(typeof e==="number")return fs(e<=2147483647?e*1000:e);if(e instanceof Date)return fs(e);return e}function nr(e,t={}){let r=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0));for(let o of["check_in_time","seated_at","no_show_at","cancelled_at"])if(r[o]!==void 0)r[o]=bb(r[o]);let n=hb[r.status];if(n&&r[n]===void 0&&!t[n])r[n]=fs(new Date);return r}async function ry(e){try{let t=ty(),r={...nr(e),status:e.status||"waiting",uuid:t};await ws.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let n=await ws.selectFrom("waitlist_restaurants").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create restaurant waitlist entry");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${t.message}`);throw t}}async function ny(e){if(!e.length)return 0;try{let t=e.map((n)=>({...nr(n),status:n.status||"waiting",uuid:ty()})),r=await ws.insertInto("waitlist_restaurants").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${t.message}`);throw t}}import{db as _b}from"@stacksjs/database/runtime";import{formatDate as xb}from"@stacksjs/orm";async function gt(e,t){try{if(!e)throw Error("Restaurant waitlist entry ID is required for update");let r=await rr(e);if(!r)return;await _b.updateTable("waitlist_restaurants").set({...nr(t,r),updated_at:xb(new Date)}).where("id","=",e).execute();let n=await rr(e);if(!n)return;return w(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function oy(e,t){return await gt(e,{status:t})}async function ay(e,t){return await gt(e,{party_size:t})}async function sy(e,t,r){return await gt(e,{quoted_wait_time:t,...r===void 0?{}:{actual_wait_time:r}})}async function iy(e,t){return await gt(e,{queue_position:t})}var Rb={products:Cn,restaurant:ht},Pb=Rb;var vb={auctions:ro,carts:no,catalog:so,coupons:jo,customers:zo,devices:Ko,errors:Yo,giftCards:ta,orders:ba,payments:_a,products:ka,receipts:Oa,register:Ta,releases:Aa,restaurant:ht,shippings:is,tax:ds,waitlists:ys},xF=vb;export{I as PriceFormatError,ro as auctions,no as carts,so as catalog,pu as catalogImport,vb as commerce,jo as coupons,U as currencyExponent,zo as customers,ee as decimalToMinor,xF as default,Ko as devices,Yo as errors,$s as formatCurrency,ne as formatMinor,ta as giftCards,Pe as minorToDecimal,Bs as minorToInput,io as minorToMajor,Ws as money,uo as moneyInputError,Us as moneyInputStep,ba as orders,Js as parseMoneyInput,_a as payments,ka as products,Oa as receipts,Ta as register,Aa as releases,ht as restaurant,is as shippings,ds as tax,ys as waitlists};
28
+ AND COALESCE(refund_amount, 0) + ${n(5)} <= amount`,[t,t,o,e,t]);if(ch(a)>0){let d=await Xe(e);if(d)return d;throw Error(`Payment with ID ${e} disappeared during refund`)}let s=await Xe(e);if(!s)throw Error(`Payment with ID ${e} not found`);let i=String(s.status||"");if(!mh.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 Ca={};E(Ca,{categories:()=>Er,default:()=>Th,items:()=>Fr,manufacturers:()=>Ir,reviews:()=>Mr,units:()=>$r,variants:()=>Br});var Er={};E(Er,{bulkRemove:()=>Ld,compareCategoryGrowth:()=>Bd,deactivate:()=>zd,deactivateChildCategories:()=>Gd,fetchActive:()=>Id,fetchAll:()=>Ra,fetchByDisplayOrder:()=>Od,fetchById:()=>Z,fetchByName:()=>Fd,fetchCategoryTree:()=>Ud,fetchChildCategories:()=>Nd,fetchRootCategories:()=>Md,fetchStats:()=>$d,findOrCreateByName:()=>Vd,remove:()=>Wd,removeChildCategories:()=>jd,store:()=>Pa,update:()=>Hd,updateActiveStatus:()=>Zd,updateDisplayOrder:()=>Kd,updateParent:()=>Qd});import{db as Ut,matchedRows as ph}from"@stacksjs/database/runtime";import{formatDate as Jd}from"@stacksjs/orm";import{db as L}from"@stacksjs/database/runtime";import{formatDate as Bt}from"@stacksjs/orm";async function Ra(){return await L.selectFrom("categories").selectAll().execute()}async function Z(e){return await L.selectFrom("categories").where("id","=",e).selectAll().executeTakeFirst()}async function Fd(e){return await L.selectFrom("categories").where("name","=",e).selectAll().executeTakeFirst()}async function Id(){return await L.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function Md(){return await L.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function Nd(e){return await L.selectFrom("categories").where("parent_category_id","=",e).where("is_active","=",!0).selectAll().execute()}async function Od(e=!0){let t=L.selectFrom("categories").where("is_active","=",!0).selectAll();if(e)return await t.orderBy("display_order","asc").execute();else return await t.orderBy("display_order","desc").execute()}async function $d(){let e=await L.selectFrom("categories").select(L.fn.count("id").as("count")).executeTakeFirst(),t=await L.selectFrom("categories").where("is_active","=",!0).select(L.fn.count("id").as("count")).executeTakeFirst(),r=await L.selectFrom("categories").whereNull("parent_category_id").select(L.fn.count("id").as("count")).executeTakeFirst(),n=await L.selectFrom("categories").whereNotNull("image_url").select(L.fn.count("id").as("count")).executeTakeFirst(),o=new Date;o.setDate(o.getDate()-30);let a=Bt(o),s=await L.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await L.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",L.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(e?.count||0),active:Number(t?.count||0),root_categories:Number(r?.count||0),child_categories:Number(e?.count||0)-Number(r?.count||0),with_images:Number(n?.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 Bd(e=30){let t=new Date,r=Bt(t),n=new Date;n.setDate(t.getDate()-e);let o=Bt(n),a=new Date(n);a.setDate(a.getDate()-1);let s=Bt(a),i=new Date(a);i.setDate(a.getDate()-e);let u=Bt(i),c=await L.selectFrom("categories").select(L.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",r).executeTakeFirst(),d=await L.selectFrom("categories").select(L.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),m=Number(c?.count||0),l=Number(d?.count||0),y=m-l,g=l!==0?y/l*100:m>0?100:0;return{current_period:m,previous_period:l,difference:y,percentage_change:g,days_range:e}}async function Ud(){let e=await Ra(),t=new Map;e.forEach((o)=>{t.set(o.id,{...o,children:[]})});let r=[];e.forEach((o)=>{let a=t.get(o.id);if(o.parent_category_id){let s=t.get(o.parent_category_id);if(s)s.children.push(a)}else r.push(a)}),r.sort((o,a)=>o.display_order-a.display_order);let n=(o)=>{o.sort((a,s)=>a.display_order-s.display_order),o.forEach((a)=>{if(a.children.length>0)n(a.children)})};return n(r),r}async function Wd(e){let t=await Ut.deleteFrom("categories").where("id","=",e).executeTakeFirst();return _(t)>0}async function Ld(e){if(!e.length)return 0;let t=await Ut.deleteFrom("categories").where("id","in",e).executeTakeFirst();return _(t)}async function jd(e){let t=await Ut.deleteFrom("categories").where("parent_category_id","=",e).executeTakeFirst();return _(t)}async function zd(e){if(!await Z(e))throw Error(`Category with ID ${e} not found`);let r=await Ut.updateTable("categories").set({is_active:!1,updated_at:Jd(new Date)}).where("id","=",e).returning("id").executeTakeFirst();return Boolean(r)}async function Gd(e){return(await ph(Ut.updateTable("categories").set({is_active:!1,updated_at:Jd(new Date)}).where("parent_category_id","=",e))).length}var{randomUUIDv7:fh}=globalThis.Bun;import{db as qd}from"@stacksjs/database/runtime";import{HttpError as Tr}from"@stacksjs/error-handling";import{isUniqueViolation as wh}from"@stacksjs/orm";import{slug as yh}from"@stacksjs/strings";async function Pa(e){try{let t=e.parent_category_id?Number(e.parent_category_id):void 0;if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new Tr(422,"Parent category ID must be a positive integer");if(t&&!await Z(t))throw new Tr(422,`Parent category with ID ${e.parent_category_id} not found`);let r={...e,uuid:fh(),is_active:e.is_active??!0,parent_category_id:e.parent_category_id||null},n=await qd.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create category");return n}catch(t){if(t instanceof Tr)throw t;if(wh(t))throw new Tr(409,"A category with this name or slug already exists");if(t instanceof Error)throw Error(`Failed to create category: ${t.message}`);throw t}}async function Vd(e){if(!e.name)throw Error("Name is required");let t=await qd.selectFrom("categories").selectAll().where("name","=",e.name).executeTakeFirst();if(t)return t;let r={name:e.name,slug:yh(e.name),is_active:e.is_active??!0,display_order:0};return await Pa(r)}import{db as Jt}from"@stacksjs/database/runtime";import{HttpError as lt}from"@stacksjs/error-handling";import{formatDate as Ar,isUniqueViolation as gh}from"@stacksjs/orm";async function Hd(e,t){if(!await Z(e))return;if(Object.hasOwn(t,"parent_category_id")){let n=t.parent_category_id?Number(t.parent_category_id):void 0;if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw new lt(422,"Parent category ID must be a positive integer");if(n===e)throw new lt(422,"A category cannot be its own parent");if(n&&!await Z(n))throw new lt(422,`Parent category with ID ${t.parent_category_id} not found`);if(n&&await Yd(e,String(n)))throw new lt(422,"This operation would create a circular category hierarchy")}try{let n=Object.hasOwn(t,"parent_category_id")?{parent_category_id:t.parent_category_id||null}:{},o=await Jt.updateTable("categories").set({...t,...n,updated_at:Ar(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!o)return;return o}catch(n){if(n instanceof lt)throw n;if(gh(n))throw new lt(409,"A category with this name or slug already exists");if(n instanceof Error)throw Error(`Failed to update category: ${n.message}`);throw n}}async function Kd(e,t){if(!await Z(e))throw Error(`Category with ID ${e} not found`);try{return await Jt.updateTable("categories").set({display_order:t,updated_at:Ar(new Date)}).where("id","=",e).execute(),await Z(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category display order: ${n.message}`);throw n}}async function Zd(e,t){if(!await Z(e))throw Error(`Category with ID ${e} not found`);try{return await Jt.updateTable("categories").set({is_active:t,updated_at:Ar(new Date)}).where("id","=",e).execute(),await Z(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category active status: ${n.message}`);throw n}}async function Qd(e,t){if(!await Z(e))throw Error(`Category with ID ${e} not found`);if(t){let n=Number(t);if(n===e)throw Error("A category cannot be its own parent");if(!await Z(n))throw Error(`Parent category with ID ${t} not found`);if(await Yd(e,t))throw Error("This operation would create a circular reference in the category hierarchy")}try{let n={updated_at:Ar(new Date)};if(t===null)await Jt.updateTable("categories").set({...n,parent_category_id:null}).where("id","=",e).execute();else await Jt.updateTable("categories").set({...n,parent_category_id:t}).where("id","=",e).execute();return await Z(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category parent: ${n.message}`);throw n}}async function Yd(e,t){let r=Number(t),n=new Set;while(r){if(n.has(r))return!0;if(r===e)return!0;n.add(r);let o=await Z(r),a=o?.parent_category_id;if(!o||!a)return!1;r=Number(a)}return!1}var Fr={};E(Fr,{bulkDestroy:()=>tl,bulkStore:()=>ul,destroy:()=>el,fetchAll:()=>rl,fetchById:()=>Te,fetchTopProducts:()=>ol,store:()=>il,update:()=>cl,updateAvailability:()=>dl,updateInventory:()=>ll});import{db as Xd}from"@stacksjs/database/runtime";async function el(e){try{let t=await Xd.deleteFrom("products").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product item: ${t.message}`);throw t}}async function tl(e){if(!e.length)return 0;try{let t=await Xd.deleteFrom("products").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product items: ${t.message}`);throw t}}import{db as Ce,sql as hh}from"@stacksjs/database/runtime";async function Te(e){let t=await Ce.selectFrom("products").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=null,n=null;if(t.manufacturer_id)r=await Ce.selectFrom("manufacturers").where("id","=",t.manufacturer_id).selectAll().executeTakeFirst();if(t.category_id)n=await Ce.selectFrom("categories").where("id","=",t.category_id).selectAll().executeTakeFirst();return{...t,manufacturer:r,category:n}}return}async function rl(){let e=await Ce.selectFrom("products").selectAll().execute(),t=e.map((c)=>c.manufacturer_id).filter((c)=>c!==null&&c!==void 0),r=e.map((c)=>c.category_id).filter((c)=>c!==null&&c!==void 0),n=Ce.selectFrom("manufacturers"),o=Ce.selectFrom("categories");if(t.length>0)n=n.where("id","in",t);if(r.length>0)o=o.where("id","in",r);let a=await n.selectAll().execute(),s=await o.selectAll().execute(),i=a.reduce((c,d)=>(c[d.id]=d,c),{}),u=s.reduce((c,d)=>(c[d.id]=d,c),{});return e.map((c)=>({...c,manufacturer:c.manufacturer_id?i[c.manufacturer_id]:null,category:c.category_id?u[c.category_id]:null}))}async function nl(e){try{let t=await Ce.selectFrom("products").selectAll().where("uuid","=",e).executeTakeFirst();return w(t,!0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get product by UUID: ${t.message}`);throw t}}async function ol(e=5){try{return(await Ce.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",Ce.fn.sum("order_items.quantity").as("units_sold"),hh`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(e).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(t){if(t instanceof Error)throw TypeError(`Failed to fetch top products: ${t.message}`);throw t}}var{randomUUIDv7:al}=globalThis.Bun;import{db as sl}from"@stacksjs/database/runtime";async function il(e){try{let t={...e,uuid:al()},r=await sl.insertInto("products").values(t).executeTakeFirst();if(!r)throw Error("Failed to create product item");let n=ve(r),o=n!==void 0?await Te(n):await nl(t.uuid);if(!o)throw Error("Failed to create product item");return o}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product item: ${t.message}`);throw t}}async function ul(e){if(!e.length)return 0;let t=0;try{return await sl.transaction(async(r)=>{for(let n of e){let o={...n,uuid:al()};await r.insertInto("products").values(o).execute(),t++}}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product items in bulk: ${r.message}`);throw r}}import{db as va,matchedRows as kS}from"@stacksjs/database/runtime";import{formatDate as Da}from"@stacksjs/orm";async function cl(e,t){try{if(!e)throw Error("Product item ID is required for update");let r=await va.updateTable("products").set({...t,updated_at:Da(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function dl(e,t){if(!await Te(e))throw Error(`Product item with ID ${e} not found`);try{return await va.updateTable("products").set({is_available:t,updated_at:Da(new Date)}).where("id","=",e).execute(),await Te(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update product item availability: ${n.message}`);throw n}}async function ll(e,t){let r=await Te(e);if(!r)throw Error(`Product item with ID ${e} not found`);let n={updated_at:Da(new Date)};if(t!==void 0)n.inventory_count=t;if(Object.keys(n).length===1)return r;try{return await va.updateTable("products").set(n).where("id","=",e).execute(),await Te(e)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update inventory information: ${o.message}`);throw o}}var Ir={};E(Ir,{bulkDestroy:()=>fl,bulkStore:()=>Dl,destroy:()=>pl,fetchAll:()=>wl,fetchByCountry:()=>bl,fetchById:()=>yl,fetchByUuid:()=>gl,fetchFeatured:()=>hl,fetchWithProductCount:()=>_l,store:()=>vl,update:()=>kl,updateByUuid:()=>Tl,updateFeaturedStatus:()=>Cl});import{db as ml}from"@stacksjs/database/runtime";async function pl(e){try{let t=await ml.deleteFrom("manufacturers").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete order: ${t.message}`);throw t}}async function fl(e){if(!e.length)return 0;try{let t=await ml.deleteFrom("manufacturers").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete orders: ${t.message}`);throw t}}import{db as Ae}from"@stacksjs/database/runtime";async function wl(){return P(await Ae.selectFrom("manufacturers").selectAll().execute())}async function yl(e){let t=await Ae.selectFrom("manufacturers").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function gl(e){let t=await Ae.selectFrom("manufacturers").where("uuid","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function hl(e=10){let t=await Ae.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(e).execute();return P(t)}async function bl(e,t={}){let r=t.page||1,n=t.limit||2,o=await Ae.selectFrom("manufacturers").select(Ae.fn.count("id").as("total")).where("country","=",e).executeTakeFirst(),a=Number(o?.total||0),s=await Ae.selectFrom("manufacturers").selectAll().where("country","=",e).limit(n).offset((r-1)*n).execute(),i=Math.ceil(a/n);return{data:P(s),paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function _l(e={}){let t=Ae.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(e.country)t=t.where("m.country","=",e.country);if(e.featured!==void 0)t=t.where("m.featured","=",e.featured);return t=t.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",Ae.fn.count("p.id").as("product_count")]).groupBy("m.id"),t.execute()}var{randomUUIDv7:Rl}=globalThis.Bun;import{db as Pl}from"@stacksjs/database/runtime";import{HttpError as xl}from"@stacksjs/error-handling";import{isUniqueViolation as bh}from"@stacksjs/orm";async function vl(e){try{let t={...e,uuid:Rl(),featured:e.featured??!1},r=await Pl.insertInto("manufacturers").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return w(r)}catch(t){if(t instanceof xl)throw t;if(bh(t))throw new xl(409,"A manufacturer with this name already exists");if(t instanceof Error)throw Error(`Failed to create manufacturer: ${t.message}`);throw t}}async function Dl(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:Rl(),featured:r.featured??!1};await Pl.insertInto("manufacturers").values(n).execute(),t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${r.message}`);throw r}}import{db as Sa}from"@stacksjs/database/runtime";import{HttpError as Sl}from"@stacksjs/error-handling";import{formatDate as ka,isUniqueViolation as _h}from"@stacksjs/orm";async function kl(e,t){try{if(!e)throw Error("Manufacturer ID is required for update");let r=await Sa.updateTable("manufacturers").set({...t,updated_at:ka(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Sl)throw r;if(_h(r))throw new Sl(409,"A manufacturer with this name already exists");if(r instanceof Error)throw Error(`Failed to update manufacturer: ${r.message}`);throw r}}async function Cl(e,t){try{let r=await Sa.updateTable("manufacturers").set({featured:t,updated_at:ka(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function Tl(e,t){try{let r=await Sa.updateTable("manufacturers").set({...t,updated_at:ka(new Date)}).where("uuid","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var Mr={};E(Mr,{bulkDestroy:()=>Fl,destroy:()=>El,fetchAll:()=>Ml,fetchApprovedByProductId:()=>$l,fetchById:()=>Il,fetchByProductId:()=>Nl,fetchByUserId:()=>Ol,fetchMostHelpfulByProductId:()=>Bl,fetchStats:()=>Ll,fetchStatsByProductIds:()=>jl,store:()=>zl,update:()=>Vl,updateVotes:()=>Hl});import{db as Al}from"@stacksjs/database/runtime";async function El(e){try{let t=await Al.deleteFrom("reviews").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete review: ${t.message}`);throw t}}async function Fl(e){if(!e.length)return 0;try{let t=await Al.deleteFrom("reviews").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete reviews: ${t.message}`);throw t}}import{db as mt}from"@stacksjs/database/runtime";async function Il(e){return w(await mt.selectFrom("reviews").where("id","=",e).selectAll().executeTakeFirst(),!0)}async function Ml(){return P(await mt.selectFrom("reviews").selectAll().execute())}async function Nl(e){return P(await mt.selectFrom("reviews").where("product_id","=",e).selectAll().execute())}async function Ol(e){return P(await mt.selectFrom("reviews").where("customer_id","=",e).selectAll().execute())}async function $l(e){return P(await mt.selectFrom("reviews").where("product_id","=",e).where("is_approved","=",!0).selectAll().execute())}async function Bl(e){return P(await mt.selectFrom("reviews").where("product_id","=",e).orderBy("helpful_votes","desc").selectAll().execute())}import{db as Ul}from"@stacksjs/database/runtime";function Jl(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function Wl(e){let t=Jl();t.total=e.length;let r=0;for(let n of e){if(n.rating===null||n.rating===void 0){t.commentsOnly++;continue}let o=Number(n.rating);if(Number.isNaN(o)){t.commentsOnly++;continue}t.rated++,r+=o;let a=Math.min(5,Math.max(1,Math.round(o)));t.distribution[a]++}if(t.rated>0)t.average=Math.round(r/t.rated*10)/10;return t}async function Ll(e){let t=await Ul.selectFrom("reviews").select(["rating"]).where("product_id","=",e).where("is_approved","=",!0).execute();return Wl(t)}async function jl(e){let t=new Map;for(let o of e)t.set(o,Jl());if(e.length===0)return t;let r=await Ul.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",e).where("is_approved","=",!0).execute(),n=new Map;for(let o of r){let a=n.get(o.product_id);if(a)a.push({rating:o.rating});else n.set(o.product_id,[{rating:o.rating}])}for(let[o,a]of n)t.set(o,Wl(a));return t}var{randomUUIDv7:xh}=globalThis.Bun;import{db as Rh}from"@stacksjs/database/runtime";function Ph(e){let t=e.rating!==void 0&&e.rating!==null,r=typeof e.content==="string"&&e.content.trim().length>0,n=typeof e.title==="string"&&e.title.trim().length>0;return!t&&!r&&!n}async function zl(e){try{if(Ph(e))throw Error("A review needs a rating or something written: both were empty");let t={...e,uuid:xh(),rating:e.rating??null,is_verified_purchase:e.is_verified_purchase??!1,is_approved:e.is_approved??!1,helpful_votes:e.helpful_votes??0,unhelpful_votes:e.unhelpful_votes??0,is_featured:e.is_featured??!1},r=await Rh.insertInto("reviews").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return w(r)}catch(t){if(t instanceof Error){if(t.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${t.message}`)}throw t}}import{db as Gl,sqlHelpers as vh}from"@stacksjs/database/runtime";import{env as Dh}from"@stacksjs/env";import{formatDate as ql}from"@stacksjs/orm";async function Vl(e,t){try{if(!e)throw Error("Review ID is required for update");let r=await Gl.updateTable("reviews").set({...t,updated_at:ql(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function Hl(e,t,r=!0){try{let n=t==="helpful"?"helpful_votes":"unhelpful_votes",o=r?`COALESCE("${n}", 0) + 1`:`MAX(COALESCE("${n}", 0) - 1, 0)`,{param:a}=vh(Dh.DB_CONNECTION||"sqlite"),s=await Gl.unsafe(`UPDATE "reviews" SET "${n}" = ${o}, "updated_at" = ${a(1)} WHERE "id" = ${a(2)} RETURNING *`,[ql(new Date),e]).execute(),i=Array.isArray(s)?s[0]:s;if(!i)throw Error("Failed to update review votes");return w(i)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update review votes: ${n.message}`);throw n}}var $r={};E($r,{bulkDestroy:()=>Ql,bulkStore:()=>nm,bulkUpdate:()=>im,destroy:()=>Zl,fetchAll:()=>em,fetchById:()=>Xl,formatUnitOptions:()=>om,getDefaultUnit:()=>am,store:()=>rm,update:()=>sm,updateDefaultStatus:()=>um});import{db as Kl}from"@stacksjs/database/runtime";async function Zl(e){try{let t=await Kl.deleteFrom("product_units").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product unit: ${t.message}`);throw t}}async function Ql(e){if(!e.length)return 0;try{let t=await Kl.deleteFrom("product_units").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product units: ${t.message}`);throw t}}import{db as Yl}from"@stacksjs/database/runtime";async function Xl(e){let t=await Yl.selectFrom("product_units").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function em(){return P(await Yl.selectFrom("product_units").selectAll().execute())}var{randomUUIDv7:tm}=globalThis.Bun;import{db as Wt}from"@stacksjs/database/runtime";async function rm(e){try{return await Wt.transaction(async(t)=>{let r={...e,uuid:tm()},n=await t.insertInto("product_units").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create product unit");if(r.is_default&&r.type)await t.updateTable("product_units").set({is_default:!1}).where("type","=",r.type).where("id","!=",n.id).execute();return w(n)})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product unit: ${t.message}`);throw t}}async function nm(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:tm()},o=await Wt.insertInto("product_units").values(n).returningAll().executeTakeFirst();if(n.is_default&&n.type&&o)await Wt.updateTable("product_units").set({is_default:!1}).where("type","=",n.type).where("id","!=",o.id).execute();t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product units in bulk: ${r.message}`);throw r}}function om(e){try{let t=Wt.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(e)t=t.where("type","=",e);return t=t.orderBy("name"),t.execute().then((r)=>r.map((n)=>({id:String(n.id),name:n.name,abbreviation:n.abbreviation,is_default:n.is_default})))}catch(t){if(t instanceof Error)throw TypeError(`Failed to format unit options: ${t.message}`);throw t}}async function am(e){try{let t=await Wt.selectFrom("product_units").selectAll().where("type","=",e).where("is_default","=",!0).executeTakeFirst();return w(t,!0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get default unit: ${t.message}`);throw t}}import{db as Nr,matchedRows as Sh}from"@stacksjs/database/runtime";import{formatDate as Or}from"@stacksjs/orm";async function sm(e,t){try{if(!e)throw Error("Product unit ID is required for update");return await Nr.transaction(async(r)=>{let n=await r.selectFrom("product_units").select(["type","is_default"]).where("id","=",e).executeTakeFirst();if(!n)return;let o=t.type??n.type;if((t.is_default??Boolean(n.is_default))&&o)await r.updateTable("product_units").set({is_default:!1,updated_at:Or(new Date)}).where("type","=",o).where("id","!=",e).execute();let s=await r.updateTable("product_units").set({...t,updated_at:Or(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!s)return;return w(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function im(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n=r;if(!n.id)continue;let o=n.data&&typeof n.data==="object"?n.data:{...n};delete o.id;let a=await Sh(Nr.updateTable("product_units").set({...o,updated_at:Or(new Date)}).where("id","=",n.id)),s=o;if(s.is_default===!0&&s.type)await Nr.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",n.id).execute();if(a.length>0)t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product units in bulk: ${r.message}`);throw r}}async function um(e,t){try{return await Nr.transaction(async(r)=>{let n=await r.selectFrom("product_units").select("type").where("id","=",e).executeTakeFirst();if(!n)return!1;let o=Or(new Date);if(t&&n.type)await r.updateTable("product_units").set({is_default:!1,updated_at:o}).where("type","=",n.type).where("id","!=",e).execute();return await r.updateTable("product_units").set({is_default:t,updated_at:o}).where("id","=",e).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit default status: ${r.message}`);throw r}}var Br={};E(Br,{bulkDestroy:()=>lm,bulkStore:()=>hm,bulkUpdate:()=>vm,destroy:()=>dm,fetchAll:()=>fm,fetchById:()=>pm,formatVariantOptions:()=>bm,generateVariantCombinations:()=>_m,store:()=>gm,update:()=>Pm});import{db as cm}from"@stacksjs/database/runtime";async function dm(e){try{let t=await cm.deleteFrom("product_variants").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product variant: ${t.message}`);throw t}}async function lm(e){if(!e.length)return 0;try{let t=await cm.deleteFrom("product_variants").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product variants: ${t.message}`);throw t}}import{db as mm}from"@stacksjs/database/runtime";async function pm(e){let t=await mm.selectFrom("product_variants").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function fm(){return P(await mm.selectFrom("product_variants").selectAll().execute())}var{randomUUIDv7:wm}=globalThis.Bun;import{db as ym}from"@stacksjs/database/runtime";async function gm(e){try{let t={...e,uuid:wm()},r=await ym.insertInto("product_variants").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return w(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product variant: ${t.message}`);throw t}}async function hm(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:wm()};await ym.insertInto("product_variants").values(n).execute(),t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${r.message}`);throw r}}function bm(e){if(!e||!e.length)return JSON.stringify([]);let t=e.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(t)}function _m(e){let t=Object.keys(e);if(!t.length)return[];function r(n,o){if(n===t.length)return[o];let a=t[n],s=e[a]??[],i=[];for(let u of s){let c={...o,[a]:u};i.push(...r(n+1,c))}return i}return r(0,{})}import{db as xm,matchedRows as kh}from"@stacksjs/database/runtime";import{formatDate as Rm}from"@stacksjs/orm";async function Pm(e,t){try{let r=await xm.updateTable("product_variants").set({...t,updated_at:Rm(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function vm(e){if(!e.length)return 0;let t=0;try{for(let r of e){if(!r.id)continue;if((await kh(xm.updateTable("product_variants").set({...r,updated_at:Rm(new Date)}).where("id","=",r.id))).length>0)t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var Ch={categories:Er,items:Fr,manufacturers:Ir,reviews:Mr,units:$r,variants:Br},Th=Ch;var Ea={};E(Ea,{CENTS_FIELDS:()=>Ah,DEFAULT_FIELDS:()=>Ee,addToBasket:()=>Eh,basketCount:()=>Nh,basketLines:()=>Aa,basketTaxable:()=>Mh,basketTotal:()=>Ih,canAdd:()=>Sm,groupsOf:()=>$h,setQuantity:()=>Fh,shelfLeft:()=>Ta,stockLabel:()=>Oh});var Ee={id:"id",price:"price",inventory:"inventory",lowStock:"low_stock_threshold",taxable:"taxable"},Ah={id:"id",price:"price_cents",inventory:"inventory_quantity",lowStock:"low_stock_threshold",taxable:"taxable"};function Ur(e,t){return Number(e[t.id])}function Dm(e,t){let r=e[t.inventory];return r===null||r===void 0||r===""?null:Number(r)}function Ta(e,t,r=Ee){let n=Dm(e,r);if(n===null)return null;let o=t.find((a)=>a.productId===Ur(e,r))?.quantity||0;return Math.max(0,n-o)}function Sm(e,t,r=Ee){let n=Ta(e,t,r);return n===null||n>0}function Eh(e,t,r=Ee){if(!Sm(t,e,r))return e;let n=Ur(t,r);return e.some((o)=>o.productId===n)?e.map((o)=>o.productId===n?{...o,quantity:o.quantity+1}:o):[...e,{productId:n,quantity:1}]}function Fh(e,t,r,n=Ee){let o=Ur(t,n),a=Dm(t,n),s=Math.min(Math.max(0,Math.floor(Number(r)||0)),a===null?Number.POSITIVE_INFINITY:a);if(s===0)return e.filter((i)=>i.productId!==o);return e.some((i)=>i.productId===o)?e.map((i)=>i.productId===o?{...i,quantity:s}:i):[...e,{productId:o,quantity:s}]}function Aa(e,t,r=Ee){return e.map((n)=>({...n,product:t.find((o)=>Ur(o,r)===n.productId)})).filter((n)=>!!n.product)}function Ih(e,t,r=Ee){return Aa(e,t,r).reduce((n,o)=>n+Number(o.product[r.price]||0)*o.quantity,0)}function Mh(e,t,r=Ee){return Aa(e,t,r).filter((n)=>n.product[r.taxable]!==!1).reduce((n,o)=>n+Number(o.product[r.price]||0)*o.quantity,0)}function Nh(e){return e.reduce((t,r)=>t+r.quantity,0)}function Oh(e,t=[],r=Ee,n=5){let o=Ta(e,t,r);if(o===null)return null;if(o===0)return{text:"Sold out",tone:"out"};let a=e[r.lowStock]===null||e[r.lowStock]===void 0?n:Number(e[r.lowStock]);return{text:`${o} left`,tone:o<=a?"low":"ok"}}function $h(e,t){let r=[];for(let n of e){let o=t(n);if(!r.includes(o))r.push(o)}return r}var Fa={};E(Fa,{RELEASE_MODES:()=>Cm,describeRollout:()=>Wh,isReleaseMode:()=>Tm,releaseSchedule:()=>Uh,rolloutFromProduct:()=>Bh,unlockAt:()=>Am,unlockedPrefix:()=>Jh});var Cm=["all_at_once","drip","scheduled"];function Tm(e){return typeof e==="string"&&Cm.includes(e)}function Bh(e){let t=Number(e.release_interval_days),r=Number(e.release_initial_count),n=Jr(e.release_starts_at);return{mode:Tm(e.release_mode)?e.release_mode:"all_at_once",intervalDays:Number.isInteger(t)&&t>0?t:7,initialCount:Number.isInteger(r)&&r>0?r:1,startsAt:n===null?null:new Date(n).toISOString()}}function Jr(e){if(e==null||e==="")return null;let t=new Date(String(e)).getTime();return Number.isFinite(t)?t:null}function km(e,t){return Math.max(0,t-(e.initialCount-1))}function Am(e,t,r,n={}){let o=Jr(e.startsAt),a=Math.max(r.getTime(),o??0);if(e.mode==="scheduled"){let s=Jr(n.releaseAt);if(s!==null)return new Date(s);let i=o??r.getTime();return new Date(i+km(e,t)*e.intervalDays*86400000)}if(e.mode==="drip"){let s=n.offsetDays;if(s!=null&&Number.isFinite(Number(s))&&Number(s)>=0)return new Date(a+Number(s)*86400000);return new Date(a+km(e,t)*e.intervalDays*86400000)}return new Date(a)}function Uh(e,t,r,n,o=[]){let a=[];for(let s=0;s<t;s++){let i=Am(e,s,r,o[s]||{});a.push({index:s,unlock_at:i.toISOString(),unlocked:i.getTime()<=n.getTime()})}return a}function Jh(e){let t=0;for(let r of e){if(!r.unlocked)break;t++}return t}function Wh(e,t,r,n=new Date){let o=(m)=>`${m} ${r}${m===1?"":"s"}`,a=Jr(e.startsAt),s=a!==null&&a>n.getTime()?` from ${new Date(a).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"})}`:"";if(t<=0)return"";if(t===1)return`Available${s||" immediately"}.`;if(e.mode==="all_at_once"||t<=e.initialCount)return`All ${o(t)} available${s||" immediately"}.`;let i=e.intervalDays===1?"every day":e.intervalDays===7?"every week":`every ${e.intervalDays} days`,u=e.initialCount===1,c=u?`The first ${r}`:`The first ${o(e.initialCount)}`;if(e.mode==="drip")return`${c} ${u?"unlocks":"unlock"}${s||" on purchase"}, then one more ${i}.`;if(s)return`${c} ${u?"releases":"release"} on ${s.slice(6)}, then one more ${i}, on the same dates for everyone.`;return`Releasing on a shared schedule${a===null?"":` since ${new Date(a).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"})}`}, one more ${r} ${i}. Join now and everything already out is yours.`}var Ba={};E(Ba,{bulkDestroy:()=>Im,bulkStore:()=>Lm,destroy:()=>Fm,fetchAll:()=>Mm,fetchById:()=>pt,fetchPageStats:()=>$m,fetchPrintJobStats:()=>Nm,fetchPrintTimeStats:()=>Bm,fetchPrintsPerHour:()=>Um,fetchSuccessRate:()=>Om,store:()=>Wm,update:()=>jm,updatePrintJob:()=>Gm,updateStatus:()=>zm});import{db as Em}from"@stacksjs/database/runtime";async function Fm(e){try{let t=await Em.deleteFrom("receipts").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print log: ${t.message}`);throw t}}async function Im(e){if(!e.length)return 0;try{let t=await Em.deleteFrom("receipts").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete receipts: ${t.message}`);throw t}}import{db as Ia}from"@stacksjs/database/runtime";import{formatDate as Lh}from"@stacksjs/orm";function be(e){return Lh(e)}function jh(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e==="number"){let n=new Date(e<=2147483647?e*1000:e);return Number.isNaN(n.getTime())?null:n}let t=String(e||"").trim();if(!t)return null;if(/^\d{10}$/.test(t)){let n=new Date(Number(t)*1000);return Number.isNaN(n.getTime())?null:n}let r=new Date(t.includes("T")?t:`${t.replace(" ","T")}Z`);return Number.isNaN(r.getTime())?null:r}async function pt(e){let t=await Ia.selectFrom("receipts").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Mm(){return P(await Ia.selectFrom("receipts").selectAll().execute())}async function Nm(e,t){let r=be(e),n=be(t),o=await ue("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","<=",n));return{total:o.total,success:o.success,failed:o.failed,warning:o.warning,averageSize:Math.round(o.averageSize),averagePages:Math.round(o.averagePages),averageDuration:Math.round(o.averageDuration)}}async function Om(e,t){let r=be(e),n=be(t),o=await ue("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","<=",n));return{successRate:o.total>0?Math.round(o.success/o.total*100):0,total:o.total,success:o.success,failed:o.failed,warning:o.warning}}async function $m(e,t){let r=be(e),n=be(t),o=await ue("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",n));return{totalPages:o.totalPages,averagePagesPerReceipt:Math.round(o.averagePagesPerReceipt),totalReceipts:o.totalReceipts}}async function Bm(e,t){let r=be(e),n=be(t),o=await ue("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","<=",n));return{averageDuration:Math.round(o.averageDuration),minDuration:o.minDuration,maxDuration:o.maxDuration,totalJobs:o.totalJobs}}async function Um(e,t){let r=typeof e==="number"?e:e.getTime(),n=typeof t==="number"?t:t.getTime(),o=be(e),a=be(t),s=await Ia.selectFrom("receipts").where("timestamp",">=",o).where("timestamp","<=",a).selectAll().execute(),i=s.length,u=Math.ceil((n-r)/3600000),c=u>0?Math.round(i/u):0,d=Array.from({length:24},(m,l)=>({hour:l,count:0}));return s.forEach((m)=>{let l=jh(m.timestamp);if(!l)return;d[l.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:d}}var{randomUUIDv7:Jm}=globalThis.Bun;import{db as Na}from"@stacksjs/database/runtime";import{formatDate as Ma}from"@stacksjs/orm";function Lt(e){try{if(typeof e==="number")return Ma(e<=2147483647?e*1000:e);if(typeof e==="string"&&/^\d{10}$/.test(e))return Ma(Number(e)*1000);return Ma(e)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function Wm(e){try{let t=Jm(),r={...e,timestamp:Lt(e.timestamp),uuid:t};await Na.insertInto("receipts").values(r).executeTakeFirst();let n=await Na.selectFrom("receipts").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create receipt");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create receipt: ${t.message}`);throw t}}async function Lm(e){if(!e.length)return 0;try{let t=e.map((n)=>({...n,timestamp:Lt(n.timestamp),uuid:Jm()})),r=await Na.insertInto("receipts").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${t.message}`);throw t}}import{db as Oa}from"@stacksjs/database/runtime";import{formatDate as $a}from"@stacksjs/orm";async function jm(e,t){try{if(!e)throw Error("Receipt ID is required for update");let r={...t,...t.timestamp===void 0?{}:{timestamp:Lt(t.timestamp)},updated_at:$a(new Date)};await Oa.updateTable("receipts").set(r).where("id","=",e).execute();let n=await pt(e);if(!n)return;return w(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function zm(e,t){try{await Oa.updateTable("receipts").set({status:t,updated_at:$a(new Date)}).where("id","=",e).execute();let r=await pt(e);if(!r)throw Error("Failed to update receipt status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function Gm(e,t,r,n){try{let o={updated_at:$a(new Date)};if(t!==void 0)o.size=t;if(r!==void 0)o.pages=r;if(n!==void 0)o.duration=n;await Oa.updateTable("receipts").set(o).where("id","=",e).execute();let a=await pt(e);if(!a)throw Error("Failed to update receipt job information");return w(a)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update receipt job information: ${o.message}`);throw o}}var cs={};E(cs,{couriers:()=>Zr,default:()=>pb,digital:()=>Hr,geocoding:()=>en,licenses:()=>nn,methods:()=>un,rates:()=>pn,routes:()=>qr,tracking:()=>xn,zones:()=>Dn});var qr={};E(qr,{DeliveryRouteInputError:()=>se,bulkDestroy:()=>Hm,destroy:()=>Vm,fetchActive:()=>Zm,fetchAll:()=>Km,fetchByCourier:()=>Qm,fetchById:()=>Lr,store:()=>Ym,update:()=>ep,updateLastActive:()=>Xm,updateMetrics:()=>rp,updateStops:()=>tp,validateDeliveryRouteWrite:()=>ft});import{db as qm}from"@stacksjs/database/runtime";async function Vm(e){try{let t=await qm.deleteFrom("delivery_routes").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete delivery route: ${t.message}`);throw t}}async function Hm(e){if(!e.length)return 0;try{let t=await qm.deleteFrom("delivery_routes").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete delivery routes: ${t.message}`);throw t}}import{db as Wr}from"@stacksjs/database/runtime";async function Lr(e){return await Wr.selectFrom("delivery_routes").where("id","=",e).selectAll().executeTakeFirst()}async function Km(){return await Wr.selectFrom("delivery_routes").selectAll().execute()}async function Zm(){return await Wr.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function Qm(e){return await Wr.selectFrom("delivery_routes").where("courier","=",e).selectAll().execute()}var{randomUUIDv7:qh}=globalThis.Bun;import{db as Ua}from"@stacksjs/database/runtime";function et(e,t){let r={};for(let[n,o]of Object.entries(t))for(let a of o){if(!Object.prototype.hasOwnProperty.call(e,a)||e[a]===void 0)continue;r[n]=e[a];break}return r}function jt(e){return et(e,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function Fe(e){return et(e,{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 zt(e){return et(e,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function Gt(e){return et(e,{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 qt(e){return et(e,{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 Vt(e){return et(e,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function jr(e){return et(e,{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 zh}from"@stacksjs/database/runtime";class se extends TypeError{constructor(e){super(e);this.name="DeliveryRouteInputError"}}function zr(e,t,r){return Number(e[r]??t?.[r])}function Gh(e,t){let r=e.last_active??t?.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 ft(e,t){let r=zr(e,t,"courier_id"),n=zr(e,t,"stops"),o=zr(e,t,"delivery_time"),a=zr(e,t,"total_distance"),s=Gh(e,t);if(!Number.isSafeInteger(r)||r<1)throw new se("Courier must be a positive integer.");if(!Number.isSafeInteger(n)||n<0)throw new se("Stops must be a non-negative integer.");if(!Number.isSafeInteger(o)||o<0)throw new se("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(a)||a<0)throw new se("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(s)||s<0)throw new se("Last active must be a valid Unix timestamp.");let i=await zh.selectFrom("couriers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new se(`Courier ${r} was not found.`);return{...e,courier_id:Number(i.id),courier:i.name,vehicle:i.vehicle_number,last_active:s}}async function Ym(e){try{let t=qh(),r=jr(e),o={...await ft(r),uuid:t};await Ua.insertInto("delivery_routes").values(o).executeTakeFirst();let a=await Ua.selectFrom("delivery_routes").where("uuid","=",t).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(t){if(t instanceof se)throw t;if(t instanceof Error)throw TypeError(`Failed to create delivery route: ${t.message}`);throw t}}async function Xm(e){try{await Ua.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",e).execute();let t=await Lr(e);if(!t)throw Error("Failed to update delivery route last active");return t}catch(t){if(t instanceof Error)throw TypeError(`Failed to update delivery route last active: ${t.message}`);throw t}}import{db as Gr}from"@stacksjs/database/runtime";import{formatDate as Ja}from"@stacksjs/orm";async function ep(e,t){try{if(!e)throw Error("Delivery route ID is required for update");let r=await Gr.selectFrom("delivery_routes").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=jr(t),o=await ft(n,r),a=await Gr.updateTable("delivery_routes").set({...o,updated_at:Ja(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof se)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function tp(e,t){try{let r=await Gr.updateTable("delivery_routes").set({stops:t,updated_at:Ja(new Date)}).where("id","=",e).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 rp(e,t,r){try{let n={updated_at:Ja(new Date)};if(t!==void 0)n.delivery_time=t;if(r!==void 0)n.total_distance=r;let o=await Gr.updateTable("delivery_routes").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update delivery metrics");return o}catch(n){if(n instanceof Error)throw TypeError(`Failed to update delivery metrics: ${n.message}`);throw n}}var Hr={};E(Hr,{bulkDestroy:()=>sp,bulkSoftDelete:()=>ip,bulkStore:()=>pp,destroy:()=>op,fetchAll:()=>dp,fetchById:()=>cp,softDelete:()=>ap,store:()=>mp,update:()=>fp,updateDeliverySettings:()=>yp,updateStatus:()=>wp});import{db as Vr,matchedRows as np}from"@stacksjs/database/runtime";async function op(e){try{let t=await Vr.deleteFrom("digital_deliveries").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete digital delivery: ${t.message}`);throw t}}async function ap(e){try{return(await np(Vr.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${t.message}`);throw t}}async function sp(e){if(!e.length)return 0;try{let t=await Vr.deleteFrom("digital_deliveries").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${t.message}`);throw t}}async function ip(e){if(!e.length)return 0;try{return(await np(Vr.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${t.message}`);throw t}}import{db as up}from"@stacksjs/database/runtime";async function cp(e){let t=await up.selectFrom("digital_deliveries").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function dp(){return P(await up.selectFrom("digital_deliveries").selectAll().execute())}var{randomUUIDv7:lp}=globalThis.Bun;import{db as Wa}from"@stacksjs/database/runtime";async function mp(e){try{let t=lp(),r={...Gt(e),uuid:t};await Wa.insertInto("digital_deliveries").values(r).executeTakeFirst();let n=await Wa.selectFrom("digital_deliveries").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created digital delivery");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create digital delivery: ${t.message}`);throw t}}async function pp(e){if(!e.length)return 0;try{let t=e.map((n)=>({...Gt(n),uuid:lp()})),r=await Wa.insertInto("digital_deliveries").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${t.message}`);throw t}}import{db as La}from"@stacksjs/database/runtime";import{formatDate as ja}from"@stacksjs/orm";async function fp(e,t){try{if(!e)throw Error("Digital delivery ID is required for update");let r=await La.updateTable("digital_deliveries").set({...Gt(t),updated_at:ja(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function wp(e,t){try{let r=await La.updateTable("digital_deliveries").set({status:t,updated_at:ja(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function yp(e,t,r,n,o){try{let a={updated_at:ja(new Date)};if(t!==void 0)a.download_limit=t;if(r!==void 0)a.expiry_days=r;if(n!==void 0)a.requires_login=n;if(o!==void 0)a.automatic_delivery=o;let s=await La.updateTable("digital_deliveries").set(a).where("id","=",e).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return w(s)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var Zr={};E(Zr,{bulkDestroy:()=>xp,bulkStore:()=>vp,destroy:()=>_p,fetchAll:()=>hp,fetchById:()=>Kr,store:()=>Pp,update:()=>Dp,updateContact:()=>kp,updateStatus:()=>Sp});import{db as bp}from"@stacksjs/database/runtime";import{db as gp}from"@stacksjs/database/runtime";async function Kr(e){let t=await gp.selectFrom("couriers").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function hp(){return P(await gp.selectFrom("couriers").selectAll().execute())}async function _p(e){try{let t=await bp.deleteFrom("couriers").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete courier: ${t.message}`);throw t}}async function xp(e){if(!e.length)return 0;let t=0;try{return await bp.transaction(async(r)=>{for(let n of e)if(await Kr(n))await r.deleteFrom("couriers").where("id","=",n).execute(),t++}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to delete couriers in bulk: ${r.message}`);throw r}}var{randomUUIDv7:Rp}=globalThis.Bun;import{db as za}from"@stacksjs/database/runtime";async function Pp(e){try{let t=Rp(),r={...Vt(e),uuid:t};await za.insertInto("couriers").values(r).executeTakeFirst();let n=await za.selectFrom("couriers").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created courier");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create courier: ${t.message}`);throw t}}async function vp(e){if(!e.length)return 0;try{let t=e.map((n)=>({...Vt(n),uuid:Rp()})),r=await za.insertInto("couriers").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create couriers in bulk: ${t.message}`);throw t}}import{db as Ga}from"@stacksjs/database/runtime";import{formatDate as qa}from"@stacksjs/orm";async function Dp(e,t){try{if(!e)throw Error("Courier ID is required for update");let r=await Ga.updateTable("couriers").set({...Vt(t),updated_at:qa(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier: ${r.message}`);throw r}}async function Sp(e,t){try{let r=await Ga.updateTable("couriers").set({status:t,updated_at:qa(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update courier status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier status: ${r.message}`);throw r}}async function kp(e,t){try{let r={updated_at:qa(new Date)};if(t!==void 0)r.phone=t;let n=await Ga.updateTable("couriers").set(r).where("id","=",e).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update contact information");return w(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var en={};E(en,{PRECISION_RANK:()=>Kt,checkCoverage:()=>Yh,formatQuery:()=>wt,geocode:()=>Qh,geocodingDriver:()=>Ip,nominatimDriver:()=>Xr,setGeocodingDriver:()=>Zh});var tt=(e)=>e*Math.PI/180;function We(e,t){let r=tt(t.latitude-e.latitude),n=tt(t.longitude-e.longitude),o=tt(e.latitude),a=tt(t.latitude),s=Math.sin(r/2)**2+Math.sin(n/2)**2*Math.cos(o)*Math.cos(a);return 12742017.6*Math.asin(Math.sqrt(s))}function Qr(e,t){let r=tt(e.latitude),n=tt(t.latitude),o=tt(t.longitude-e.longitude),a=Math.sin(o)*Math.cos(n),s=Math.cos(r)*Math.sin(n)-Math.sin(r)*Math.cos(n)*Math.cos(o);return(Math.atan2(a,s)*180/Math.PI+360)%360}function Yr(e,t,r={}){let n=r.detourFactor??1.35,o=r.minimumSeconds??30;if(!Number.isFinite(t)||t<=0.5)return null;let a=e*n/t;return Math.max(o,Math.round(a))}function Cp(e,t,r){return We(e,t)<=r}function Ht(e){return typeof e?.latitude==="number"&&typeof e?.longitude==="number"&&Number.isFinite(e.latitude)&&Number.isFinite(e.longitude)}var Kt={unknown:0,locality:1,postal:2,street:3,rooftop:4};function wt(e){return[e.street,e.city,e.region,e.postalCode,e.country].map((t)=>String(t??"").trim()).filter(Boolean).join(", ")}var Vh="https://nominatim.openstreetmap.org/search",Tp=1000,Ap=0,Ep=Promise.resolve();async function Hh(e){let t=Ep.then(async()=>{let r=Date.now()-Ap;if(r<Tp)await Bun.sleep(Tp-r);return Ap=Date.now(),e()});return Ep=t.then(()=>{return},()=>{return}),t}function Kh(e){let t=e.address??{},r=String(e.addresstype??""),n=String(e.type??""),o=String(e.category??e.class??"");if(t.house_number||n==="house"||n==="building"||r==="building")return"rooftop";if(t.road||o==="highway"||r==="road")return"street";if(r==="postcode"||t.postcode&&!t.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(r))return"locality";return"unknown"}function Xr(e={}){let t=e.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,r=e.endpoint??Vh;return{name:"nominatim",async geocode(n){let o=wt(n);if(!o)return null;let a=new URL(r);if(a.searchParams.set("q",o),a.searchParams.set("format","jsonv2"),a.searchParams.set("limit","1"),a.searchParams.set("addressdetails","1"),n.country)a.searchParams.set("countrycodes",n.country.toLowerCase());let s=await Hh(()=>fetch(a,{headers:{"user-agent":t,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),d=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(d))return null;let m=Kh(u);return{latitude:c,longitude:d,formatted:String(u.display_name??o),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[m],precision:m,provider:"nominatim"}}}}var Fp=null;function Zh(e){Fp=e}function Ip(){return Fp??Xr()}async function Qh(e,t={}){let r=t.driver??Ip(),n=t.minimumPrecision??"street",o=`geocode:${r.name}:${wt(e).toLowerCase()}`,a=await Xh(o);if(a!==void 0)return a;let s=await r.geocode(e),i=s&&Kt[s.precision]>=Kt[n]?s:null;return await eb(o,i,i?t.cacheSeconds??2592000:600),i}function Yh(e,t,r){if(t.length===0)return null;let n=t[0],o=We(e,n);for(let a of t.slice(1)){let s=We(e,a);if(s<o)o=s,n=a}return{covered:o<=r,distanceMeters:Math.round(o),nearest:n}}async function Xh(e){try{let r=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!r)return;let n=await r.get(e);if(n===null||n===void 0)return;return n==="null"?null:JSON.parse(String(n))}catch{return}}async function eb(e,t,r){try{let o=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!o)return;await o.set(e,t===null?"null":JSON.stringify(t),r)}catch{}}var nn={};E(nn,{LicenseKeyInputError:()=>G,bulkDestroy:()=>$p,bulkSoftDelete:()=>Bp,bulkStore:()=>qp,destroy:()=>Np,fetchAll:()=>Wp,fetchById:()=>Jp,softDelete:()=>Op,store:()=>Gp,update:()=>Vp,updateExpiration:()=>Kp,updateStatus:()=>Hp,validateLicenseKeyWrite:()=>rt});import{db as tn,matchedRows as Mp}from"@stacksjs/database/runtime";async function Np(e){try{let t=await tn.deleteFrom("license_keys").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete license key: ${t.message}`);throw t}}async function Op(e){try{return(await Mp(tn.updateTable("license_keys").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete license key: ${t.message}`);throw t}}async function $p(e){if(!e.length)return 0;try{let t=await tn.deleteFrom("license_keys").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete license keys: ${t.message}`);throw t}}async function Bp(e){if(!e.length)return 0;try{return(await Mp(tn.updateTable("license_keys").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete license keys: ${t.message}`);throw t}}import{db as Up}from"@stacksjs/database/runtime";async function Jp(e){let t=await Up.selectFrom("license_keys").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Wp(){return P(await Up.selectFrom("license_keys").selectAll().execute())}var{randomUUIDv7:zp}=globalThis.Bun;import{db as Ka}from"@stacksjs/database/runtime";import{db as Va}from"@stacksjs/database/runtime";var Lp=["Standard License","Premium License","Enterprise License"],jp=["active","inactive","unassigned"];class G extends TypeError{constructor(e){super(e);this.name="LicenseKeyInputError"}}function Zt(e,t,r){return e[r]!==void 0?e[r]:t?.[r]}function Ha(e,t,r,n){let o=Zt(e,t,r);if(o===void 0||o===null||o==="")return null;let a=Number(o);if(!Number.isSafeInteger(a)||a<1)throw new G(`${n} must be a positive integer or null.`);return a}function tb(e){if(typeof e==="number")return e>2147483647?Math.floor(e/1000):e;if(typeof e==="string"&&/^\d{10,13}$/.test(e))return e.length===13?Math.floor(Number(e)/1000):Number(e);if(typeof e==="string"){let t=/^\d{4}-\d{2}-\d{2} \d/.test(e)?`${e.replace(" ","T")}Z`:e;return Math.floor(new Date(t).getTime()/1000)}return Number.NaN}async function rt(e,t){let r=String(Zt(e,t,"key")||"").trim().toUpperCase(),n=String(Zt(e,t,"template")||""),o=String(Zt(e,t,"status")||""),a=tb(Zt(e,t,"expiry_date")),s=Ha(e,t,"customer_id","Customer"),i=Ha(e,t,"product_id","Product"),u=Ha(e,t,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new G("License key must use five groups of four uppercase letters or numbers.");if(!Lp.includes(n))throw new G(`Template must be one of: ${Lp.join(", ")}.`);if(!jp.includes(o))throw new G(`Status must be one of: ${jp.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new G("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,d,m]=await Promise.all([s?Va.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?Va.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?Va.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new G(`Customer ${s} was not found.`);if(i&&!d)throw new G(`Product ${i} was not found.`);if(u&&!m)throw new G(`Order ${u} was not found.`);if(s&&m?.customer_id&&Number(m.customer_id)!==s)throw new G(`Order ${u} belongs to Customer ${m.customer_id}, not Customer ${s}.`);return{...e,key:r,template:n,expiry_date:a,status:o,customer_id:s,product_id:i,order_id:u}}async function Gp(e){try{let t=zp(),r=qt(e),n={...await rt(r),uuid:t};await Ka.insertInto("license_keys").values(n).executeTakeFirst();let o=await Ka.selectFrom("license_keys").where("uuid","=",t).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created license key");return w(o)}catch(t){if(t instanceof G)throw t;if(t instanceof Error){if(t.message.includes("UNIQUE constraint failed: license_keys.key"))throw new G("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${t.message}`)}throw t}}async function qp(e){if(!e.length)return 0;try{let t=await Promise.all(e.map(async(n)=>({...await rt(qt(n)),uuid:zp()}))),r=await Ka.insertInto("license_keys").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof G)throw t;if(t instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${t.message}`);throw t}}import{db as rn}from"@stacksjs/database/runtime";import{formatDate as Za}from"@stacksjs/orm";async function Vp(e,t){try{if(!e)throw Error("License key ID is required for update");let r=await rn.selectFrom("license_keys").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=qt(t),o=await rt(n,r),a=await rn.updateTable("license_keys").set({...o,updated_at:Za(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!a)return;return w(a)}catch(r){if(r instanceof G)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new G("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function Hp(e,t){try{let r=await rn.updateTable("license_keys").set({status:t,updated_at:Za(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function Kp(e,t){try{let r={updated_at:Za(new Date)};if(t!==void 0)r.expiry_date=t;let n=await rn.updateTable("license_keys").set(r).where("id","=",e).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update expiration information");return w(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var un={};E(un,{bulkDestroy:()=>Xp,bulkSoftDelete:()=>ef,bulkStore:()=>of,destroy:()=>Qp,fetchAll:()=>tf,fetchById:()=>sn,formatShippingOptions:()=>af,getActiveShippingMethods:()=>sf,softDelete:()=>Yp,store:()=>nf,update:()=>uf,updatePricing:()=>df,updateStatus:()=>cf});import{db as on,matchedRows as Zp}from"@stacksjs/database/runtime";async function Qp(e){try{let t=await on.deleteFrom("shipping_methods").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping method: ${t.message}`);throw t}}async function Yp(e){try{return(await Zp(on.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${t.message}`);throw t}}async function Xp(e){if(!e.length)return 0;try{let t=await on.deleteFrom("shipping_methods").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping methods: ${t.message}`);throw t}}async function ef(e){if(!e.length)return 0;try{return(await Zp(on.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${t.message}`);throw t}}import{db as an}from"@stacksjs/database/runtime";async function sn(e){let t=await an.selectFrom("shipping_methods").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=await an.selectFrom("shipping_zones").where("shipping_method_id","=",e).selectAll().execute();return{...t,shippingZones:r}}return}async function tf(){let e=await an.selectFrom("shipping_methods").selectAll().execute();if(e.length===0)return[];let t=[...new Set(e.map((a)=>a.id))],o=(await an.selectFrom("shipping_zones").where("shipping_method_id","in",t).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 e.map((a)=>({...a,shipping_zones:o[a.id]||[]}))}var{randomUUIDv7:rf}=globalThis.Bun;import{db as Qt}from"@stacksjs/database/runtime";async function nf(e){try{let t=rf(),r={...jt(e),uuid:t};await Qt.insertInto("shipping_methods").values(r).executeTakeFirst();let n=await Qt.selectFrom("shipping_methods").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created shipping method");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping method: ${t.message}`);throw t}}async function of(e){if(!e.length)return 0;try{let t=e.map((n)=>({...jt(n),uuid:rf()})),r=await Qt.insertInto("shipping_methods").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${t.message}`);throw t}}function af(){try{return Qt.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(e){if(e instanceof Error)throw TypeError(`Failed to format shipping options: ${e.message}`);throw e}}async function sf(){try{let e=await Qt.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute();return P(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get active shipping methods: ${e.message}`);throw e}}import{db as Qa}from"@stacksjs/database/runtime";import{formatDate as Ya}from"@stacksjs/orm";async function uf(e,t){try{if(!e)throw Error("Shipping method ID is required for update");let r=await Qa.updateTable("shipping_methods").set({...jt(t),updated_at:Ya(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function cf(e,t){try{let r=await Qa.updateTable("shipping_methods").set({status:t,updated_at:Ya(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function df(e,t,r){try{let n={updated_at:Ya(new Date)};if(t!==void 0)n.base_rate=t;if(r!==void 0)n.free_shipping=r;let o=await Qa.updateTable("shipping_methods").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update pricing information");return w(o)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update pricing information: ${n.message}`);throw n}}var pn={};E(pn,{ShippingRateInputError:()=>Y,bulkDestroy:()=>mf,bulkStore:()=>Tf,bulkUpdate:()=>Ef,destroy:()=>lf,destroyByMethod:()=>ff,destroyByZone:()=>pf,fetchAll:()=>gf,fetchById:()=>yf,formatShippingRateOptions:()=>xf,getRateByWeightAndAddress:()=>bf,getRateByWeightAndZone:()=>Xa,getRatesByZone:()=>hf,getShippingRatesByMethod:()=>Rf,resolveZoneForAddress:()=>dn,store:()=>Cf,update:()=>Af,updateByMethod:()=>If,updateByZone:()=>Ff,validateShippingRateWrite:()=>nt,validateZoneMatchesAddress:()=>_f});import{db as cn}from"@stacksjs/database/runtime";async function lf(e){try{let t=await cn.deleteFrom("shipping_rates").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rate: ${t.message}`);throw t}}async function mf(e){if(!e.length)return 0;try{let t=await cn.deleteFrom("shipping_rates").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates: ${t.message}`);throw t}}async function pf(e){try{let t=await cn.deleteFrom("shipping_rates").where("shipping_zone_id","=",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${t.message}`);throw t}}async function ff(e){try{let t=await cn.deleteFrom("shipping_rates").where("shipping_method_id","=",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${t.message}`);throw t}}import{db as me}from"@stacksjs/database/runtime";async function yf(e){let t=await me.selectFrom("shipping_rates").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=null,n=null;if(t.shipping_zone_id)r=await me.selectFrom("shipping_zones").where("id","=",t.shipping_zone_id).selectAll().executeTakeFirst();if(t.shipping_method_id)n=await me.selectFrom("shipping_methods").where("id","=",t.shipping_method_id).selectAll().executeTakeFirst();return{...t,shipping_zone:r,shipping_method:n}}return}async function gf(){let e=await me.selectFrom("shipping_rates").selectAll().execute();if(e.length===0)return[];let t=[...new Set(e.map((i)=>i.shipping_zone_id).filter((i)=>i!==null&&i!==void 0))],r=[...new Set(e.map((i)=>i.shipping_method_id).filter((i)=>i!==null&&i!==void 0))],[n,o]=await Promise.all([t.length?me.selectFrom("shipping_zones").where("id","in",t).selectAll().execute():[],r.length?me.selectFrom("shipping_methods").where("id","in",r).selectAll().execute():[]]),a=n.reduce((i,u)=>(i[u.id]=u,i),{}),s=o.reduce((i,u)=>(i[u.id]=u,i),{});return e.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 hf(e){try{let t=await me.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).orderBy("weight_from").execute();return P(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${t.message}`);throw t}}async function Xa(e,t){try{let r=await me.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).where("weight_from","<=",e).where("weight_to",">=",e).executeTakeFirst();return w(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 dn(e){if(!e?.countryCode)return null;try{let t=await me.selectFrom("shipping_zones").selectAll().where("countries","like",`%${e.countryCode}%`).where("status","=","active").execute();if(t.length===0)return null;let r=null;for(let n of t){let o=1;if(e.region&&n.regions&&wf(n.regions,e.region))o=2;if(e.postalCode&&n.postal_codes&&wf(n.postal_codes,e.postalCode))o=3;if(!r||o>r.score)r={id:n.id,score:o}}return r?.id??null}catch{return null}}async function bf(e,t){let r=await dn(t);if(r==null)return;return Xa(e,r)}async function _f(e,t){return await dn(t)===e}function wf(e,t){if(!e||!t)return!1;let r=t.trim().toUpperCase();for(let n of e.split(/[,|;]/))if(n.trim().toUpperCase()===r)return!0;return!1}async function xf(){try{return(await me.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((t)=>t.shipping_method_id!==null&&t.shipping_method_id!==void 0&&t.shipping_zone_id!==null&&t.shipping_zone_id!==void 0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to format shipping rate options: ${e.message}`);throw e}}async function Rf(e){try{let t=await me.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",e).orderBy("weight_from").execute();return P(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${t.message}`);throw t}}var{randomUUIDv7:kf}=globalThis.Bun;import{db as es}from"@stacksjs/database/runtime";import{db as Yt}from"@stacksjs/database/runtime";async function Pf(){return P(await Yt.selectFrom("shipping_zones").selectAll().execute())}async function ln(e){let t=await Yt.selectFrom("shipping_zones").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}function vf(){try{return Yt.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(e){if(e instanceof Error)throw TypeError(`Failed to format shipping zone options: ${e.message}`);throw e}}async function Df(){try{let e=await Yt.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute();return P(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get active shipping zones: ${e.message}`);throw e}}async function Sf(e){try{let t=await Yt.selectFrom("shipping_zones").selectAll().where("countries","like",`%${e}%`).where("status","=","active").orderBy("name").execute();return P(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${t.message}`);throw t}}class Y extends TypeError{constructor(e){super(e);this.name="ShippingRateInputError"}}function Xt(e,t,r){return Number(e[r]??t?.[r])}async function nt(e,t){let r=Xt(e,t,"shipping_method_id"),n=Xt(e,t,"shipping_zone_id"),o=Xt(e,t,"weight_from"),a=Xt(e,t,"weight_to"),s=Xt(e,t,"rate");if(!Number.isSafeInteger(r)||r<1)throw new Y("Shipping method must be a positive integer.");if(!Number.isSafeInteger(n)||n<1)throw new Y("Shipping zone must be a positive integer.");if(!Number.isFinite(o)||o<0)throw new Y("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<o)throw new Y("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new Y("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([sn(r),ln(n)]);if(!i)throw new Y(`Shipping method ${r} was not found.`);if(!u)throw new Y(`Shipping zone ${n} was not found.`);if(Number(u.shipping_method_id)!==r)throw new Y(`Shipping zone ${n} is not assigned to shipping method ${r}.`)}async function Cf(e){try{let t=Fe(e),r=Number(t.shipping_method_id),n=Number(t.shipping_zone_id);await nt(t);let o=kf(),a={...t,shipping_method_id:r,shipping_zone_id:n,uuid:o};await es.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await es.selectFrom("shipping_rates").where("uuid","=",o).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return w(s)}catch(t){if(t instanceof Y)throw t;if(t instanceof Error)throw TypeError(`Failed to create shipping rate: ${t.message}`);throw t}}async function Tf(e){if(!e.length)return 0;try{for(let n of e){let o=Fe(n);await nt(o)}let t=e.map((n)=>({...Fe(n),uuid:kf()})),r=await es.insertInto("shipping_rates").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Y)throw t;if(t instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${t.message}`);throw t}}import{db as er,matchedRows as ts}from"@stacksjs/database/runtime";import{formatDate as mn}from"@stacksjs/orm";async function Af(e,t){try{if(!e)throw Error("Shipping rate ID is required for update");let r=await er.selectFrom("shipping_rates").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=Fe(t);await nt(n,r);let o=await er.updateTable("shipping_rates").set({...n,updated_at:mn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!o)return;return w(o)}catch(r){if(r instanceof Y)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function Ef(e){if(!e.length)return 0;try{let t=0;for(let{id:r,data:n}of e)if((await ts(er.updateTable("shipping_rates").set({...Fe(n),updated_at:mn(new Date)}).where("id","=",r))).length>0)t++;return t}catch(t){if(t instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${t.message}`);throw t}}async function Ff(e,t){try{return(await ts(er.updateTable("shipping_rates").set({...Fe(t),updated_at:mn(new Date)}).where("shipping_zone_id","=",e))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function If(e,t){try{return(await ts(er.updateTable("shipping_rates").set({...Fe(t),updated_at:mn(new Date)}).where("shipping_method_id","=",e))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var xn={};E(xn,{ARRIVAL_RADIUS_METERS:()=>os,NEARBY_RADIUS_METERS:()=>ns,assignStop:()=>Nf,bearingInDegrees:()=>Qr,broadcastToChannel:()=>Ie,completeStop:()=>$f,distanceInMeters:()=>We,emitDeliveryArrived:()=>hn,emitDeliveryAssigned:()=>wn,emitDeliveryCompleted:()=>bn,emitDeliveryFailed:()=>_n,emitDeliveryNearby:()=>gn,emitDeliveryPosition:()=>fn,emitDeliveryStarted:()=>yn,estimateSecondsRemaining:()=>Yr,failStop:()=>Bf,hasCoordinates:()=>Ht,isWithin:()=>Cp,orderTrackingChannel:()=>Le,recordCourierPing:()=>Mf,routeTrackingChannel:()=>rs,startRoute:()=>Uf,startStop:()=>Of});function Le(e){return`order.${e}`}function rs(e){return`delivery-route.${e}`}async function yt(e,t){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let n=r.dispatch;if(typeof n!=="function")return;n(e,t)}catch{}}async function Ie(e,t,r){try{let n=await import("@stacksjs/realtime").catch(()=>null);if(!n)return;let o=n.channel;if(typeof o!=="function")return;await o(e).broadcast(t,r,"private")}catch{}}async function fn(e,t,r){await Promise.all([...e.map((n)=>Ie(Le(n),"delivery:position",r)),t==null?Promise.resolve():Ie(rs(t),"delivery:position",r)])}async function wn(e){if(await yt("delivery:assigned",{stop:e}),e.order_id!=null)await Ie(Le(e.order_id),"delivery:assigned",{stop:e})}async function yn(e){if(await yt("delivery:started",{stop:e}),e.order_id!=null)await Ie(Le(e.order_id),"delivery:started",{stop:e})}async function gn(e,t,r){if(await yt("delivery:nearby",{stop:e,distanceMeters:t,etaSeconds:r}),e.order_id!=null)await Ie(Le(e.order_id),"delivery:nearby",{stop:e,distanceMeters:t,etaSeconds:r})}async function hn(e){if(await yt("delivery:arrived",{stop:e}),e.order_id!=null)await Ie(Le(e.order_id),"delivery:arrived",{stop:e})}async function bn(e){if(await yt("delivery:completed",{stop:e}),e.order_id!=null)await Ie(Le(e.order_id),"delivery:completed",{stop:e})}async function _n(e,t){await yt("delivery:failed",{stop:e,reason:t})}var{randomUUIDv7:rb}=globalThis.Bun;import{db as Me}from"@stacksjs/database/runtime";var ns=400,os=60,nb=250;async function Mf(e){let t=e.recordedAt??new Date().toISOString(),r=typeof e.accuracy!=="number"||e.accuracy<=nb,n=await Me.selectFrom("couriers").where("id","=",e.courierId).select(["id","latitude","longitude"]).executeTakeFirst();if(!n)throw Error(`Unknown courier: ${e.courierId}`);let o=Ht(n)?{latitude:n.latitude,longitude:n.longitude}:null,a=typeof e.heading==="number"?e.heading:o?Qr(o,e):null,s=await ob(e.courierId),i=s?await ab(s.id):null,u=null,c=null,d=!1,m=!1,l=i&&Ht({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&l)u=Math.round(We(e,l)),c=Yr(u,e.speed??0),m=u<=os&&i.arrived_at==null,d=!m&&u<=ns&&i.status==="en_route"&&i.notified_nearby_at==null;let y=await sb({courierId:e.courierId,routeId:s?.id??null,latitude:e.latitude,longitude:e.longitude,heading:a,speed:e.speed??null,accuracy:e.accuracy??null,recordedAt:t});if(r)await Me.updateTable("couriers").set({latitude:e.latitude,longitude:e.longitude,heading:a,speed:e.speed??0,last_ping_at:t}).where("id","=",e.courierId).execute();if(i&&(u!=null||c!=null))await Me.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 fn(i?.order_id==null?[]:[i.order_id],s?.id??null,{courierId:e.courierId,routeId:s?.id??null,latitude:e.latitude,longitude:e.longitude,heading:a,speed:e.speed??null,accuracy:e.accuracy??null,recordedAt:t,distanceToStopMeters:u,etaSeconds:c});if(d&&i)await Me.updateTable("delivery_stops").set({notified_nearby_at:t}).where("id","=",i.id).execute(),await gn(i,u,c);if(m&&i)await Me.updateTable("delivery_stops").set({status:"arrived",arrived_at:t}).where("id","=",i.id).execute(),await hn({...i,status:"arrived",arrived_at:t});return{pingId:y,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:d,crossedArrival:m}}async function ob(e){return await Me.selectFrom("delivery_routes").where("courier_id","=",e).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function ab(e){let t=await Me.selectFrom("delivery_stops").where("delivery_route_id","=",e).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 t.find((r)=>r.status==="en_route")??t.find((r)=>r.status==="arrived")??t[0]??null}async function sb(e){let t=rb();return await Me.insertInto("courier_pings").values({uuid:t,courier_id:e.courierId,delivery_route_id:e.routeId,latitude:e.latitude,longitude:e.longitude,heading:e.heading,speed:e.speed??0,accuracy:e.accuracy,recorded_at:e.recordedAt}).executeTakeFirst(),(await Me.selectFrom("courier_pings").where("uuid","=",t).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:ib}=globalThis.Bun;import{db as X}from"@stacksjs/database/runtime";function as(e){return e.type==="pickup"}async function Nf(e){let t=ib(),r=e.sequence??await cb(e.deliveryRouteId);await X.insertInto("delivery_stops").values({uuid:t,delivery_route_id:e.deliveryRouteId,order_id:e.orderId??null,sequence:r,status:"pending",address:e.address,latitude:e.latitude??null,longitude:e.longitude??null,recipient_name:e.recipientName??null,recipient_phone:e.recipientPhone??null,eta_at:e.etaAt??null,type:e.type??"dropoff"}).executeTakeFirst();let n=await lb(t);if(n)await wn(n);return n??{}}async function Of(e){await X.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",e).execute();let t=await is(e);if(!t)return null;if(t.order_id!=null&&!as(t))await ss(t.order_id,"OUT_FOR_DELIVERY");return await yn(t),t}async function $f(e,t){let r=new Date().toISOString();await X.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await db(e)?{}:{arrived_at:r},...t?{notes:t}:{}}).where("id","=",e).execute();let n=await is(e);if(!n)return null;if(n.order_id!=null)await ss(n.order_id,as(n)?"OUT_FOR_DELIVERY":"DELIVERED");return await bn(n),await Jf(n.delivery_route_id),n}async function Bf(e,t){await X.updateTable("delivery_stops").set({status:"failed",notes:t}).where("id","=",e).execute();let r=await is(e);if(!r)return null;if(r.order_id!=null&&!as(r))await ss(r.order_id,"SHIPPED");return await _n(r,t),await Jf(r.delivery_route_id),r}async function Uf(e){await X.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",e).execute()}async function Jf(e){if(e==null)return;if(await X.selectFrom("delivery_stops").where("delivery_route_id","=",e).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await X.selectFrom("delivery_routes").where("id","=",e).select(["courier_id"]).executeTakeFirst();if(await X.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",e).execute(),r?.courier_id!=null)await X.updateTable("couriers").set({status:"active"}).where("id","=",r.courier_id).execute()}async function ss(e,t){let r=await X.selectFrom("orders").where("id","=",e).select(["id","status"]).executeTakeFirst();if(!r)return;let n=await Promise.resolve().then(() => (dt(),{}));let s=ub(r.status,t,Je);if(s.length===0){let{log:i}=await import("@stacksjs/logging").catch(()=>({log:null}));i?.warn(`[delivery] refused to move order ${e} from ${r.status} to ${t}: no legal transition`);return}for(let i of s)await X.updateTable("orders").set({status:i}).where("id","=",e).execute(),await ct(i,{...r,status:i})}function ub(e,t,r){if(e===t)return[];if(r(e,t))return[t];for(let n of["PROCESSING","SHIPPED"]){if(n===e||n===t)continue;if(r(e,n)&&r(n,t))return[n,t]}return[]}async function cb(e){return(await X.selectFrom("delivery_stops").where("delivery_route_id","=",e).select(["sequence"]).execute()).reduce((r,n)=>Math.max(r,n.sequence??0),0)+1}async function db(e){return(await X.selectFrom("delivery_stops").where("id","=",e).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function is(e){return await X.selectFrom("delivery_stops").where("id","=",e).selectAll().executeTakeFirst()??null}async function lb(e){return await X.selectFrom("delivery_stops").where("uuid","=",e).selectAll().executeTakeFirst()??null}var Dn={};E(Dn,{bulkDestroy:()=>zf,bulkSoftDelete:()=>Gf,bulkStore:()=>Hf,destroy:()=>Lf,fetchAll:()=>Pf,fetchById:()=>ln,formatZoneOptions:()=>vf,getActiveShippingZones:()=>Df,getZonesByCountry:()=>Sf,softDelete:()=>jf,store:()=>Vf,update:()=>Kf,updateCountries:()=>Qf,updateRegionsAndPostalCodes:()=>Yf,updateStatus:()=>Zf});import{db as Rn,matchedRows as Wf}from"@stacksjs/database/runtime";async function Lf(e){try{let t=await Rn.deleteFrom("shipping_zones").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping zone: ${t.message}`);throw t}}async function jf(e){try{return(await Wf(Rn.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${t.message}`);throw t}}async function zf(e){if(!e.length)return 0;try{let t=await Rn.deleteFrom("shipping_zones").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping zones: ${t.message}`);throw t}}async function Gf(e){if(!e.length)return 0;try{return(await Wf(Rn.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${t.message}`);throw t}}var{randomUUIDv7:qf}=globalThis.Bun;import{db as us}from"@stacksjs/database/runtime";async function Vf(e){try{let t=qf(),r={...zt(e),uuid:t};await us.insertInto("shipping_zones").values(r).executeTakeFirst();let n=await us.selectFrom("shipping_zones").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created shipping zone");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping zone: ${t.message}`);throw t}}async function Hf(e){if(!e.length)return 0;try{let t=e.map((n)=>({...zt(n),uuid:qf()})),r=await us.insertInto("shipping_zones").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${t.message}`);throw t}}import{db as Pn}from"@stacksjs/database/runtime";import{formatDate as vn}from"@stacksjs/orm";async function Kf(e,t){try{if(!e)throw Error("Shipping zone ID is required for update");let r=await Pn.updateTable("shipping_zones").set({...zt(t),updated_at:vn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function Zf(e,t){try{let r=await Pn.updateTable("shipping_zones").set({status:t,updated_at:vn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function Qf(e,t){try{let r=await Pn.updateTable("shipping_zones").set({countries:t,updated_at:vn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function Yf(e,t,r){try{let n={updated_at:vn(new Date)};if(t!==void 0)n.regions=t;if(r!==void 0)n.postal_codes=r;let o=await Pn.updateTable("shipping_zones").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update regions and postal codes");return w(o)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${n.message}`);throw n}}var mb={digital:Hr,couriers:Zr,geocoding:en,licenses:nn,methods:un,rates:pn,routes:qr,tracking:xn,zones:Dn},pb=mb;var ls={};E(ls,{activeTaxRates:()=>ds,breakdownFor:()=>gt,bulkDestroy:()=>nw,bulkStore:()=>dw,destroy:()=>rw,fetchAll:()=>sw,fetchById:()=>aw,store:()=>cw,taxFor:()=>ew,update:()=>lw,updateDefaultStatus:()=>fw,updateRate:()=>pw,updateStatus:()=>mw});import{db as fb}from"@stacksjs/database/runtime";function Xf(e){let t=Number(e);return Number.isFinite(t)?t/100:0}function gt(e,t,r={}){let n=Math.max(0,Math.round(e)),o=[],a=0,s=0;for(let i of t){let u=Xf(i.rate),c=Math.round(n*u),d=Boolean(r.exempt&&i.exemptible);if(d)s+=c;else a+=c;o.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:d?0:c,exempted:d})}return{taxable:n,components:o,tax:a,exempted:s}}async function ds(e={}){let t=fb.selectFrom("tax_rates").where("status","=","active").selectAll();if(e.country)t=t.where("country","=",e.country);let r=await t.execute();if(!e.codes?.length)return r;let n=new Set(e.codes);return r.filter((o)=>n.has(String(o.code??"")))}async function ew(e,t={}){return gt(e,await ds(t),t)}import{db as tw}from"@stacksjs/database/runtime";async function rw(e){try{let t=await tw.deleteFrom("tax_rates").where("id","=",e).executeTakeFirst();return _(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete tax rate: ${t.message}`);throw t}}async function nw(e){if(!e.length)return 0;try{let t=await tw.deleteFrom("tax_rates").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete tax rates: ${t.message}`);throw t}}import{db as ow}from"@stacksjs/database/runtime";async function aw(e){let t=await ow.selectFrom("tax_rates").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function sw(){return P(await ow.selectFrom("tax_rates").selectAll().execute())}var{randomUUIDv7:iw}=globalThis.Bun;import{db as uw}from"@stacksjs/database/runtime";async function cw(e){try{return await uw.transaction(async(t)=>{let r={...e,uuid:iw()};if(r.is_default)await t.updateTable("tax_rates").set({is_default:!1}).execute();let n=await t.insertInto("tax_rates").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create tax rate");return w(n)})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create tax rate: ${t.message}`);throw t}}async function dw(e){if(!e.length)return 0;try{return await uw.transaction(async(t)=>{let r=0;for(let n of e){let o={...n,uuid:iw()};if(o.is_default)await t.updateTable("tax_rates").set({is_default:!1}).execute();if(await t.insertInto("tax_rates").values(o).executeTakeFirst())r++}return r})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${t.message}`);throw t}}import{db as Sn}from"@stacksjs/database/runtime";import{formatDate as kn}from"@stacksjs/orm";async function lw(e,t){try{if(!e)throw Error("Tax rate ID is required for update");return await Sn.transaction(async(r)=>{let n=await r.selectFrom("tax_rates").select("is_default").where("id","=",e).executeTakeFirst();if(!n)return;let o=t.is_default??Boolean(n.is_default),a=kn(new Date);if(o)await r.updateTable("tax_rates").set({is_default:!1,updated_at:a}).where("id","!=",e).execute();let s=await r.updateTable("tax_rates").set({...t,updated_at:a}).where("id","=",e).returningAll().executeTakeFirst();if(!s)return;return w(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function mw(e,t){try{let r=await Sn.updateTable("tax_rates").set({status:t,updated_at:kn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function pw(e,t){try{let r=await Sn.updateTable("tax_rates").set({rate:t,updated_at:kn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return w(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function fw(e,t){try{return await Sn.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",e).executeTakeFirst())return!1;let o=kn(new Date);if(t)await r.updateTable("tax_rates").set({is_default:!1,updated_at:o}).where("id","!=",e).execute();return await r.updateTable("tax_rates").set({is_default:t,updated_at:o}).where("id","=",e).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate default status: ${r.message}`);throw r}}var gs={};E(gs,{default:()=>vb,products:()=>Tn,restaurant:()=>bt});var Tn={};E(Tn,{bulkDestroy:()=>yw,bulkStore:()=>Iw,destroy:()=>ww,fetchAll:()=>gw,fetchById:()=>tr,fetchCancelledBetweenDates:()=>vw,fetchConversionRates:()=>kw,fetchCountBetweenDates:()=>Cw,fetchCountByAllQuantities:()=>xw,fetchCountByDate:()=>bw,fetchCountByDateGrouped:()=>Tw,fetchCountByQuantity:()=>_w,fetchCountBySource:()=>hw,fetchCountByStatus:()=>Sw,fetchNotifiedBetweenDates:()=>Rw,fetchPurchasedBetweenDates:()=>Pw,fetchWaiting:()=>Dw,store:()=>Fw,update:()=>Cn,updatePartySize:()=>Nw,updateStatus:()=>Mw});import{db as ms}from"@stacksjs/database/runtime";async function ww(e){try{let t=await ms.selectFrom("waitlist_products").where("id","=",e).selectAll().executeTakeFirst();if(!t)return;return await ms.deleteFrom("waitlist_products").where("id","=",e).execute(),w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete waitlist product: ${t.message}`);throw t}}async function yw(e){if(!e.length)return 0;try{let t=await ms.deleteFrom("waitlist_products").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${t.message}`);throw t}}import{db as j}from"@stacksjs/database/runtime";import{formatDate as z}from"@stacksjs/orm";async function tr(e){let t=await j.selectFrom("waitlist_products").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function gw(){return P(await j.selectFrom("waitlist_products").selectAll().execute())}async function hw(e,t){let r=j.selectFrom("waitlist_products").select(["source",j.fn.count("id").as("count")]).groupBy("source");if(e&&t){let o=z(e),a=z(t);r=r.where("created_at",">=",o).where("created_at","<=",a)}return(await r.execute()).reduce((o,{source:a,count:s})=>(o[a]=s,o),{})}async function bw(e=new Date){let t=new Date(e);t.setHours(0,0,0,0);let r=new Date(e);r.setHours(23,59,59,999);let n=z(t),o=z(r);return(await j.selectFrom("waitlist_products").select(j.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",o).executeTakeFirst())?.count??0}async function _w(e){return(await j.selectFrom("waitlist_products").select(j.fn.count("id").as("count")).where("quantity","=",e).executeTakeFirst())?.count??0}async function xw(e,t){let r=j.selectFrom("waitlist_products").select(["quantity",j.fn.count("id").as("count")]).groupBy("quantity");if(e&&t){let o=z(e),a=z(t);r=r.where("created_at",">=",o).where("created_at","<=",a)}return(await r.execute()).reduce((o,{quantity:a,count:s})=>(o[a]=s,o),{})}async function Rw(e,t){let r=z(e),n=z(t),o=await j.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",n).whereNotNull("notified_at").execute();return P(o)}async function Pw(e,t){let r=z(e),n=z(t),o=await j.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",n).whereNotNull("purchased_at").execute();return P(o)}async function vw(e,t){let r=z(e),n=z(t),o=await j.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",n).whereNotNull("cancelled_at").execute();return P(o)}async function Dw(){let e=await j.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute();return P(e)}async function Sw(e,t,r){let n=j.selectFrom("waitlist_products").select(j.fn.count("id").as("count")).where("status","=",e);if(t&&r){let a=z(t),s=z(r);n=n.where("created_at",">=",a).where("created_at","<=",s)}return(await n.executeTakeFirst())?.count??0}async function kw(e,t){let r=j.selectFrom("waitlist_products").select(["status",j.fn.count("id").as("count")]).groupBy("status");if(e&&t){let u=z(e),c=z(t);r=r.where("created_at",">=",u).where("created_at","<=",c)}let n=await r.execute(),o=n.reduce((u,{count:c})=>u+c,0),a=Number(n.find((u)=>u.status==="purchased")?.count??0),s=o>0?a/o*100:0,i=n.reduce((u,{status:c,count:d})=>(u[c]={count:d,percentage:o>0?d/o*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function Cw(e,t){let r=z(e),n=z(t);return(await j.selectFrom("waitlist_products").select(j.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",n).executeTakeFirst())?.count??0}async function Tw(e,t){let r=j.selectFrom("waitlist_products").select(["created_at"]);if(e&&t){let a=z(e),s=z(t);r=r.where("created_at",">=",a).where("created_at","<=",s)}let o=(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(o).map(([a,s])=>({date:a,count:s})).sort((a,s)=>a.date.localeCompare(s.date))}var{randomUUIDv7:Ew}=globalThis.Bun;import{db as ps}from"@stacksjs/database/runtime";import{formatDate as Aw}from"@stacksjs/orm";var wb={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function yb(e){return typeof e==="number"||e instanceof Date?Aw(e):e}function rr(e,t={}){let r=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0));if(r.quantity===void 0&&r.party_size!==void 0)r.quantity=r.party_size;delete r.party_size;for(let o of["notified_at","purchased_at","cancelled_at"])if(r[o]!==void 0)r[o]=yb(r[o]);let n=wb[r.status];if(n&&r[n]===void 0&&!t[n])r[n]=Aw(new Date);return r}async function Fw(e){try{let t=Ew(),r={...rr(e),uuid:t,status:e.status||"waiting"};await ps.insertInto("waitlist_products").values(r).executeTakeFirst();let n=await ps.selectFrom("waitlist_products").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create waitlist product");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create waitlist product: ${t.message}`);throw t}}async function Iw(e){if(!e.length)return 0;try{let t=e.map((n)=>({...rr(n),status:n.status||"waiting",uuid:Ew()})),r=await ps.insertInto("waitlist_products").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${t.message}`);throw t}}import{db as gb}from"@stacksjs/database/runtime";import{formatDate as hb}from"@stacksjs/orm";async function Cn(e,t){try{if(!e)throw Error("Waitlist product ID is required for update");let r=await tr(e);if(!r)return;await gb.updateTable("waitlist_products").set({...rr(t,r),updated_at:hb(new Date)}).where("id","=",e).execute();let n=await tr(e);if(!n)return;return w(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function Mw(e,t){return await Cn(e,{status:t})}async function Nw(e,t){return await Cn(e,{quantity:t})}var bt={};E(bt,{bulkDestroy:()=>$w,bulkStore:()=>oy,destroy:()=>Ow,fetchAll:()=>Bw,fetchAverageWaitTimes:()=>Vw,fetchBetweenDates:()=>jw,fetchById:()=>nr,fetchConversionRates:()=>qw,fetchCountByAllPartySizes:()=>Lw,fetchCountByDate:()=>Jw,fetchCountByPartySize:()=>Ww,fetchCountByTablePreference:()=>Uw,fetchCurrentWaitTimes:()=>Xw,fetchNoShowStats:()=>Yw,fetchSeatedBetweenDates:()=>zw,fetchSeatedStats:()=>ey,fetchSeatingRate:()=>Qw,fetchTablesTurnedToday:()=>Zw,fetchTimeSeriesStats:()=>ty,fetchWaiting:()=>Gw,fetchWaitingWithPartySizes:()=>Kw,fetchWaitingWithQuotedTimes:()=>Hw,store:()=>ny,update:()=>ht,updatePartySize:()=>sy,updateQueuePosition:()=>uy,updateStatus:()=>ay,updateWaitTimes:()=>iy});import{db as fs}from"@stacksjs/database/runtime";async function Ow(e){try{let t=await fs.selectFrom("waitlist_restaurants").where("id","=",e).selectAll().executeTakeFirst();if(!t)return;return await fs.deleteFrom("waitlist_restaurants").where("id","=",e).execute(),w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${t.message}`);throw t}}async function $w(e){if(!e.length)return 0;try{let t=await fs.deleteFrom("waitlist_restaurants").where("id","in",e).executeTakeFirst();return _(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${t.message}`);throw t}}import{db as N}from"@stacksjs/database/runtime";import{formatDate as ce}from"@stacksjs/orm";async function nr(e){let t=await N.selectFrom("waitlist_restaurants").where("id","=",e).selectAll().executeTakeFirst();return w(t,!0)}async function Bw(){return P(await N.selectFrom("waitlist_restaurants").selectAll().execute())}async function Uw(){return(await N.selectFrom("waitlist_restaurants").select(["table_preference",N.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((t,{table_preference:r,count:n})=>(t[r]=n,t),{})}async function Jw(e=new Date){let t=new Date(e);t.setHours(0,0,0,0);let r=new Date(e);r.setHours(23,59,59,999);let n=ce(t),o=ce(r);return(await N.selectFrom("waitlist_restaurants").select(N.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",o).executeTakeFirst())?.count??0}async function Ww(e){return(await N.selectFrom("waitlist_restaurants").select(N.fn.count("id").as("count")).where("party_size","=",e).executeTakeFirst())?.count??0}async function Lw(){return(await N.selectFrom("waitlist_restaurants").select(["party_size",N.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((t,{party_size:r,count:n})=>(t[r]=n,t),{})}async function jw(e,t){let r=ce(e),n=ce(t),o=await N.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",n).execute();return P(o)}async function zw(e,t){let r=ce(e),n=ce(t),o=await N.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",n).where("status","=","seated").execute();return P(o)}async function Gw(){let e=await N.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute();return P(e)}async function qw(){let e=await N.selectFrom("waitlist_restaurants").select(["status",N.fn.count("id").as("count")]).groupBy("status").execute(),t=e.reduce((a,{count:s})=>a+s,0),r=e.find((a)=>a.status==="seated")?.count??0,n=t>0?Number(r)/t*100:0,o=e.reduce((a,{status:s,count:i})=>(a[s]={count:i,percentage:t>0?i/t*100:0},a),{});return{totalConversionRate:n,statusBreakdown:o}}async function Vw(){let e=await N.selectFrom("waitlist_restaurants").select([N.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),N.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:e?.avg_quoted_wait_time??0,averageActualWaitTime:e?.avg_actual_wait_time??0}}async function Hw(){let e=P(await N.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),t=e.reduce((n,o)=>n+(o.quoted_wait_time??0),0),r=e.length>0?t/e.length:0;return{entries:e,totalQuotedWaitTime:t,averageQuotedWaitTime:r}}async function Kw(){let e=P(await N.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),t=e.reduce((o,a)=>o+a.party_size,0),r=e.length>0?t/e.length:0,n=e.reduce((o,a)=>(o[a.party_size]=(o[a.party_size]||0)+1,o),{});return{entries:e,totalPartySize:t,averagePartySize:r,partySizeBreakdown:n}}async function Zw(){let e=new Date,t=new Date(e);t.setHours(0,0,0,0);let r=new Date(e);r.setHours(23,59,59,999);let n=ce(t),o=ce(r),a=await N.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",n).where("check_in_time","<=",o).execute(),s=a.length,i=a.reduce((m,l)=>m+l.party_size,0),u=s>0?i/s:0,c=a.reduce((m,l)=>(m[l.table_preference]=(m[l.table_preference]||0)+1,m),{}),d=a.reduce((m,l)=>(m[l.party_size]=(m[l.party_size]||0)+1,m),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:d}}async function Qw(e,t){let r=ce(e),n=ce(t),o=await N.selectFrom("waitlist_restaurants").select(["status",N.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",n).groupBy("status").execute(),a=o.reduce((c,{count:d})=>c+d,0),s=o.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=o.reduce((c,{status:d,count:m})=>(c[d]={count:m,percentage:a>0?m/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function Yw(e,t){let r=ce(e),n=ce(t),o=N.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",n),a=await N.selectFrom("waitlist_restaurants").select(N.fn.count("id").as("count")).where("check_in_time",">=",r).where("check_in_time","<=",n).executeTakeFirst(),s=await o.execute(),i=s.length,u=a?.count&&a.count>0?i/a.count*100:0,c=s.reduce((p,b)=>p+(b.quoted_wait_time??0),0),d=i>0?c/i:0,m=s.reduce((p,b)=>p+b.party_size,0),l=i>0?m/i:0,y=s.reduce((p,b)=>(p[b.table_preference]=(p[b.table_preference]||0)+1,p),{}),g=s.reduce((p,b)=>(p[b.party_size]=(p[b.party_size]||0)+1,p),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:d,averagePartySize:l,breakdownByTablePreference:y,breakdownByPartySize:g}}async function Xw(){let e=await N.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),t=e.reduce((o,a)=>o+(a.quoted_wait_time||0),0),r=e.reduce((o,a)=>o+(a.actual_wait_time||0),0),n=e.length;return{averageQuoted:n>0?t/n:0,averageActual:n>0?r/n:0}}async function ey(){let e=Date.now()-86400000,t=await N.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",e).execute(),r=Array.from({length:24},(n,o)=>({hour:o,count:t.filter((a)=>a.seated_at===o).length}));return{total:t.length,byHour:r}}async function ty(){return(await N.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((t,r)=>{let n=r.created_at;if(!t[n])t[n]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return t[n].total++,t[n][r.status]++,t},{})}var{randomUUIDv7:ry}=globalThis.Bun;import{db as ys}from"@stacksjs/database/runtime";import{formatDate as ws}from"@stacksjs/orm";var bb={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function _b(e){if(typeof e==="number")return ws(e<=2147483647?e*1000:e);if(e instanceof Date)return ws(e);return e}function or(e,t={}){let r=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0));for(let o of["check_in_time","seated_at","no_show_at","cancelled_at"])if(r[o]!==void 0)r[o]=_b(r[o]);let n=bb[r.status];if(n&&r[n]===void 0&&!t[n])r[n]=ws(new Date);return r}async function ny(e){try{let t=ry(),r={...or(e),status:e.status||"waiting",uuid:t};await ys.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let n=await ys.selectFrom("waitlist_restaurants").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create restaurant waitlist entry");return w(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${t.message}`);throw t}}async function oy(e){if(!e.length)return 0;try{let t=e.map((n)=>({...or(n),status:n.status||"waiting",uuid:ry()})),r=await ys.insertInto("waitlist_restaurants").values(t).executeTakeFirst();return _(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${t.message}`);throw t}}import{db as xb}from"@stacksjs/database/runtime";import{formatDate as Rb}from"@stacksjs/orm";async function ht(e,t){try{if(!e)throw Error("Restaurant waitlist entry ID is required for update");let r=await nr(e);if(!r)return;await xb.updateTable("waitlist_restaurants").set({...or(t,r),updated_at:Rb(new Date)}).where("id","=",e).execute();let n=await nr(e);if(!n)return;return w(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function ay(e,t){return await ht(e,{status:t})}async function sy(e,t){return await ht(e,{party_size:t})}async function iy(e,t,r){return await ht(e,{quoted_wait_time:t,...r===void 0?{}:{actual_wait_time:r}})}async function uy(e,t){return await ht(e,{queue_position:t})}var Pb={products:Tn,restaurant:bt},vb=Pb;var Db={auctions:no,carts:oo,catalog:io,coupons:zo,customers:Go,devices:Zo,errors:Xo,giftCards:ra,orders:_a,payments:xa,products:Ca,receipts:Ba,register:Ea,releases:Fa,restaurant:bt,shippings:cs,tax:ls,waitlists:gs},DF=Db;export{I as PriceFormatError,no as auctions,gt as breakdownFor,oo as carts,io as catalog,fu as catalogImport,Db as commerce,zo as coupons,U as currencyExponent,Go as customers,ee as decimalToMinor,DF as default,Zo as devices,Xo as errors,Bs as formatCurrency,ne as formatMinor,ra as giftCards,Pe as minorToDecimal,Us as minorToInput,uo as minorToMajor,Ls as money,co as moneyInputError,Js as moneyInputStep,Xf as multiplierOf,_a as orders,Ws as parseMoneyInput,xa as payments,Ca as products,Ba as receipts,Ea as register,Fa as releases,bt as restaurant,cs as shippings,ls as tax,gs as waitlists};