@stacksjs/commerce 0.72.103 → 0.73.1

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,27 +1,28 @@
1
1
  // @bun
2
- var pm=Object.defineProperty;var fm=(e)=>e;function wm(e,t){this[e]=fm.bind(null,t)}var y=(e,t)=>{for(var r in t)pm(e,r,{get:t[r],enumerable:!0,configurable:!0,set:wm.bind(t,r)})};var ym=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=import.meta.require;var gs={};y(gs,{canTransition:()=>qe,emitForStatus:()=>Ke,emitOrderCancelled:()=>ve,emitOrderCreated:()=>Ze,emitOrderDelivered:()=>Et,emitOrderOutForDelivery:()=>hs,emitOrderPaid:()=>se,emitOrderRefunded:()=>De,emitOrderShipped:()=>Tt});function qe(e,t){if(e===t)return!0;return Gm[e]?.includes(t)??!1}async function fe(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 Ze(e){await fe("order:created",{order:e})}async function se(e,t){await fe("order:paid",{order:e,payment:t})}async function Tt(e){await fe("order:shipped",{order:e})}async function hs(e){await fe("order:out_for_delivery",{order:e})}async function Et(e){await fe("order:delivered",{order:e})}async function ve(e,t){await fe("order:cancelled",{order:e,reason:t})}async function De(e,t){await fe("order:refunded",{order:e,refundAmount:t})}async function Ke(e,t){switch(e){case"PROCESSING":return se(t);case"SHIPPED":return Tt(t);case"OUT_FOR_DELIVERY":return hs(t);case"DELIVERED":return Et(t);case"CANCELLED":return ve(t);case"REFUNDED":return De(t);case"PENDING":default:}}var Gm;var Pe=ym(()=>{Gm={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 sn={};y(sn,{DEFAULT_INCREMENT_LADDER:()=>Z,auctionChannel:()=>yt,auctionTotals:()=>Zr,biddersFor:()=>Jr,bids:()=>jr,bidsByBidder:()=>Nr,bidsForAuction:()=>Mr,bidsForItem:()=>Ir,broadcastBid:()=>Or,broadcastItemClosed:()=>$r,broadcastPledge:()=>Ur,closeAuction:()=>Yr,closeDueItems:()=>Qr,closeItem:()=>We,closingSoon:()=>en,closingSoonNotification:()=>xm,currencyFor:()=>Wr,determineWinner:()=>xe,effectiveCloseAt:()=>ne,engine:()=>Gr,extendedCloseAt:()=>Be,fetchAuction:()=>L,fetchAuctionForEvent:()=>Vr,fetchCatalogue:()=>qr,fetchItems:()=>H,fetchPledges:()=>on,incrementFor:()=>J,leadingBid:()=>Je,lots:()=>tn,makePledge:()=>Do,nextMinimumBid:()=>K,openAuction:()=>Hr,outbidNotification:()=>bm,placeBid:()=>zr,pledgeLevels:()=>Po,pledgeTotal:()=>nn,pledges:()=>an,resolveBid:()=>Oe,rulesFor:()=>Ue,settle:()=>$e,settleAuction:()=>Xr,winnerNotification:()=>_m});var jr={};y(jr,{biddersFor:()=>Jr,bidsByBidder:()=>Nr,bidsForAuction:()=>Mr,bidsForItem:()=>Ir,leadingBid:()=>Je,placeBid:()=>zr});import{db as q}from"@stacksjs/database";async function Je(e){return await q.selectFrom("bids").selectAll().where("auction_item_id","=",e).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function Ir(e){return await q.selectFrom("bids").selectAll().where("auction_item_id","=",e).orderBy("placed_at","desc").execute()??[]}async function Mr(e){return await q.selectFrom("bids").selectAll().where("auction_id","=",e).orderBy("placed_at","asc").execute()??[]}async function Nr(e,t){return await q.selectFrom("bids").selectAll().where("auction_id","=",e).where("bidder_email","=",t.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function Jr(e){let t=await q.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:gm}=globalThis.Bun;import{db as Lr}from"@stacksjs/database";function Be(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 Z=[{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 J(e,t=Z,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 K(e,t,r=Z){if(t===null||t<=0)return e.starting_bid;return t+J(t,r,e.min_increment)}function Oe(e,t,r,n=Z){let o=Math.max(r.amount,r.maxAmount??0),a=K(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 l=Math.max(e.starting_bid,r.amount);return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:l,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:l,nextMinimumBid:l+J(l,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+J(t.amount,n,e.min_increment)}}if(o>s){let l=s+J(s,n,e.min_increment),m=Math.min(o,Math.max(l,a));return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:m,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:m,outbid:{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:t.amount},nextMinimumBid:m+J(m,n,e.min_increment)}}let u=o+J(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+J(c,n,e.min_increment)}}function yt(e){return`auction.${e}`}async function Br(){try{return(await import("@stacksjs/realtime")).emit??null}catch{return null}}async function Or(e){let t=await Br();if(!t||!e.item||!e.leader)return;await t(yt(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 Ur(e,t){let r=await Br();if(!r)return;await r(yt(e.auction_id),"pledge.made",{donorName:e.donor_name,amount:e.amount,level:e.level??null,runningTotal:t})}async function $r(e,t,r){let n=await Br();if(!n)return;await n(yt(e),"item.closed",{itemId:t,...r})}import{config as hm}from"@stacksjs/config";function Ro(){return hm.commerce??{}}function vo(){return Ro().auction??{}}function Ue(e){let t=vo();return{increments:t.increments?.length?t.increments:Z,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 Wr(e){return e?.currency??vo().currency??Ro().currency??"USD"}function ht(e){return e.toISOString().slice(0,19).replace("T"," ")}async function zr(e){let t=e.now??new Date,r=await Lr.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 Lr.selectFrom("auctions").selectAll().where("id","=",r.auction_id).executeTakeFirst(),o=Ue(n),a=await Je(r.id),s=K(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=Oe(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:Be(r,i,o,t),l=u.leader&&!u.leader.isChallenger&&a&&a.bidder_email.toLowerCase()===e.bidderEmail.toLowerCase(),m=await Lr.transaction(async(w)=>{if(l&&a)return await w.updateTable("bids").set({max_amount:u.leader.maxAmount}).where("id","=",a.id).execute(),{...a,max_amount:u.leader.maxAmount};let x=u.leader?.isChallenger===!0,b=gm();if(await w.insertInto("bids").values({uuid:b,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:x?"leading":"outbid",placed_at:ht(t)}).execute(),a){if(x)await w.updateTable("bids").set({status:"outbid"}).where("id","=",a.id).execute();else if(u.leader&&u.leader.amount!==a.amount)await w.updateTable("bids").set({amount:u.leader.amount}).where("id","=",a.id).execute()}if(u.buyNow)await w.updateTable("auction_items").set({status:"sold",closes_at:ht(t)}).where("id","=",r.id).execute();else if(c)await w.updateTable("auction_items").set({closes_at:ht(c),extension_count:r.extension_count+1}).where("id","=",r.id).execute();return await w.selectFrom("bids").selectAll().where("uuid","=",b).executeTakeFirst()}),p={...u,bid:m,item:{...r,status:u.buyNow?"sold":r.status,closes_at:c?ht(c):r.closes_at,extension_count:c?r.extension_count+1:r.extension_count},extendedTo:c??void 0};return await Or(p).catch(()=>{return}),p}var Gr={};y(Gr,{DEFAULT_INCREMENT_LADDER:()=>Z,determineWinner:()=>xe,effectiveCloseAt:()=>ne,extendedCloseAt:()=>Be,incrementFor:()=>J,nextMinimumBid:()=>K,resolveBid:()=>Oe,settle:()=>$e});function xe(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 $e(e,t,r,n){let o=t.filter((m)=>m.status==="sold"),a=t.filter((m)=>m.status==="passed"),s=o.reduce((m,p)=>m+p.amount,0),i=r.filter((m)=>m.status==="confirmed").reduce((m,p)=>m+p.amount,0),u=new Map(e.map((m)=>[m.id,m.fair_market_value??null])),c=o.reduce((m,p)=>{let w=u.get(p.itemId);return w==null?m:m+(p.amount-w)},0),l=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:l===0?0:o.length/l,valueDelta:c,outcomes:t}}var tn={};y(tn,{auctionTotals:()=>Zr,closeAuction:()=>Yr,closeDueItems:()=>Qr,closeItem:()=>We,closingSoon:()=>en,fetchAuction:()=>L,fetchAuctionForEvent:()=>Vr,fetchCatalogue:()=>qr,fetchItems:()=>H,openAuction:()=>Hr,settleAuction:()=>Xr});import{db as B}from"@stacksjs/database";async function L(e){return await B.selectFrom("auctions").selectAll().where("id","=",e).executeTakeFirst()??null}async function Vr(e){return await B.selectFrom("auctions").selectAll().where("event_id","=",e).executeTakeFirst()??null}async function H(e){return await B.selectFrom("auction_items").selectAll().where("auction_id","=",e).orderBy("lot_number","asc").execute()??[]}async function qr(e){let[t,r]=await Promise.all([L(e),H(e)]),n=Ue(t),o=await B.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",e).where("status","in",["leading","won"]).execute(),a=await B.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:K(u,c?.amount??null,n.increments),leaderName:c?.bidder_name??null}})}async function Zr(e){let t=await L(e),r=await B.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",e).where("status","!=","invalid").execute(),n=await B.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,l)=>c+l.amount,0),i=(n??[]).reduce((c,l)=>c+l.amount,0),u=await B.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";function Kr(e){return e.toISOString().slice(0,19).replace("T"," ")}async function Hr(e,t=new Date){return await oe.updateTable("auctions").set({status:"open",opens_at:Kr(t)}).where("id","=",e).execute(),await oe.updateTable("auction_items").set({status:"open"}).where("auction_id","=",e).where("status","=","closed").execute(),L(e)}async function We(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=xe(e,r??[]);return await oe.transaction(async(o)=>{if(await o.updateTable("auction_items").set({status:n.status,closes_at:Kr(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 $r(e.auction_id,e.id,{status:n.status,amount:n.amount,winnerName:n.winnerName}).catch(()=>{return}),n}async function Qr(e,t=new Date){let r=await L(e);if(!r)return[];let n=await H(e),o=[];for(let a of n){if(a.status!=="open")continue;if(ne(a,r.closes_at)>t)continue;let s=await We(a,t);if(s)o.push(s)}return o}async function Yr(e,t=new Date){let r=await H(e),n=[];for(let o of r){let a=await We(o,t);if(a)n.push(a)}return await oe.updateTable("auctions").set({status:"closed",closes_at:Kr(t)}).where("id","=",e).execute(),n}async function Xr(e,t={}){let r=await L(e);if(!r)return null;let n=await H(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=xe(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 $e(n,i,a??[],{auctionId:e,currency:Wr(r),goalAmount:r.goal_amount??null})}async function en(e,t,r=new Date){let n=await L(e);if(!n)return[];let o=new Date(r.getTime()+t*60000);return(await H(e)).filter((a)=>{if(a.status!=="open")return!1;let s=ne(a,n.closes_at);return s>r&&s<=o})}function rn(e,t="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:t,minimumFractionDigits:0}).format(e/100)}function bm(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 ${rn(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 _m(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 ${rn(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 xm(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 ${rn(r,n)}.`,data:{itemId:e.id,lotNumber:e.lot_number,title:e.title,currentBid:r,closesAt:e.closes_at}}}var an={};y(an,{fetchPledges:()=>on,makePledge:()=>Do,pledgeLevels:()=>Po,pledgeTotal:()=>nn});var{randomUUIDv7:Rm}=globalThis.Bun;import{db as Le}from"@stacksjs/database";async function Do(e){let t=Rm();await Le.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 Le.selectFrom("pledges").selectAll().where("uuid","=",t).executeTakeFirst();return await Ur(r,await nn(e.auctionId)).catch(()=>{return}),r}async function nn(e){return(await Le.selectFrom("pledges").select(["amount"]).where("auction_id","=",e).where("status","=","confirmed").execute()??[]).reduce((r,n)=>r+n.amount,0)}async function on(e){return await Le.selectFrom("pledges").selectAll().where("auction_id","=",e).orderBy("amount","desc").execute()??[]}async function Po(e){let t=(await on(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 un={};y(un,{deleteCoupon:()=>Fo,deleteCoupons:()=>ko,deleteExpiredCoupons:()=>To,fetchActive:()=>Io,fetchAll:()=>Co,fetchByCode:()=>Ao,fetchById:()=>me,fetchConversionRate:()=>$o,fetchCouponCounts:()=>No,fetchCouponCountsByType:()=>Jo,fetchRedemptionStats:()=>Bo,fetchRedemptionTrend:()=>Uo,fetchStats:()=>Mo,fetchTopRedeemedCoupons:()=>Oo,getActiveCouponsMoMChange:()=>Wo,redeem:()=>Ko,store:()=>jo,update:()=>Zo});import{db as gt}from"@stacksjs/database";import{formatDate as vm}from"@stacksjs/orm";function d(e){if(typeof e==="number")return Number.isFinite(e)?e:0;if(typeof e==="bigint")return Number(e);if(!e||typeof e!=="object")return 0;let t=e;for(let r of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if(t[r]!==void 0&&t[r]!==null)return d(t[r]);if(Array.isArray(e))return e.reduce((r,n)=>r+d(n),0);return 0}async function Fo(e){let t=await gt.deleteFrom("coupons").where("id","=",e).executeTakeFirst();return d(t)>0}async function ko(e){if(!e.length)return 0;return(await gt.deleteFrom("coupons").where("id","in",e).execute()).length||0}async function To(){let e=vm(new Date),t=await gt.deleteFrom("coupons").where("end_date","<",e).executeTakeFirst();return d(t)}import{db as f}from"@stacksjs/database";import{extractDate as Eo,formatDate as So}from"@stacksjs/orm";import{camelCase as Dm}from"@stacksjs/strings";function _t(e){let t=Object.fromEntries(Object.entries(e).map(([r,n])=>[Dm(r),n]));if(t.endDate)t.endDate=Eo(new Date(t.endDate));if(t.startDate)t.startDate=Eo(new Date(t.startDate));if(t.isActive!==void 0)t.isActive=Boolean(t.isActive);return t}async function Co(){return(await f.selectFrom("coupons").selectAll().execute()).map(_t)}async function me(e){let t=await f.selectFrom("coupons").where("id","=",e).selectAll().executeTakeFirst();if(t)return _t(t);return}async function Ao(e){let t=await f.selectFrom("coupons").where("code","=",e).selectAll().executeTakeFirst();if(t)return _t(t);return}async function Io(){let e=So(new Date);return(await f.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).selectAll().execute()).map(_t)}async function Mo(){let e=await f.selectFrom("coupons").select(f.fn.count("id").as("count")).executeTakeFirst(),t=So(new Date),r=await f.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(f.fn.count("id").as("count")).executeTakeFirst(),n=await f.selectFrom("coupons").select(["discount_type",f.fn.count("id").as("count")]).groupBy("discount_type").execute(),o=await f.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),a=await f.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 No(){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 bt(null,null,e),a=await bt(t,null,e),s=await bt(r,null,e),i=await bt(n,null,e);return{week:a,month:s,year:i,all_time:o}}async function bt(e,t,r){let n=f.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(f.fn.count("id").as("count")).executeTakeFirst(),a=f.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(f.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 Jo(){let e=new Date,t=await f.selectFrom("coupons").select("discount_type").distinct().execute(),r={};for(let{discount_type:n}of t){let o=await f.selectFrom("coupons").where("discount_type","=",n).select(f.fn.count("id").as("count")).executeTakeFirst(),a=await f.selectFrom("coupons").where("discount_type","=",n).where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(f.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 Bo(){let e=await f.selectFrom("coupons").select(f.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 f.selectFrom("coupons").where("updated_at",">=",r.toISOString()).select(f.fn.sum("usage_count").as("total")).executeTakeFirst(),s=await f.selectFrom("coupons").where("updated_at",">=",n.toISOString()).select(f.fn.sum("usage_count").as("total")).executeTakeFirst(),i=await f.selectFrom("coupons").where("updated_at",">=",o.toISOString()).select(f.fn.sum("usage_count").as("total")).executeTakeFirst(),u=await f.selectFrom("coupons").select(["discount_type",f.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),c={};return u.forEach((l)=>{c[l.discount_type]=Number(l.total||0)}),{total:Number(e?.total||0),week:Number(a?.total||0),month:Number(s?.total||0),year:Number(i?.total||0),by_type:c}}async function Oo(e=5){return await f.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 Uo(e=30){let t=new Date().toISOString(),r=new Date;r.setDate(r.getDate()-e);let n=await f.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 $o(){let e=new Date,t=await f.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(f.fn.count("id").as("count")).executeTakeFirst(),r=await f.selectFrom("coupons").where("usage_count",">",0).select(f.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 Wo(){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 f.selectFrom("coupons").select(f.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",t).executeTakeFirst(),a=await f.selectFrom("coupons").select(f.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:Pm}=globalThis.Bun;import{db as Lo}from"@stacksjs/database";import{HttpError as zo}from"@stacksjs/error-handling";import{isUniqueViolation as Fm}from"@stacksjs/orm";async function jo(e){try{let t=Pm();return await Lo.insertInto("coupons").values({...e,uuid:t}).executeTakeFirst(),await Lo.selectFrom("coupons").where("uuid","=",t).selectAll().executeTakeFirst()}catch(t){if(t instanceof zo)throw t;if(Fm(t))throw new zo(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 Vo}from"@stacksjs/database";import{HttpError as Go}from"@stacksjs/error-handling";import{formatDate as qo,isUniqueViolation as km}from"@stacksjs/orm";async function Zo(e,t){if(!await me(e))return;try{return await Vo.updateTable("coupons").set({...t,updated_at:qo(new Date)}).where("id","=",e).execute(),await me(e)}catch(n){if(n instanceof Go)throw n;if(km(n))throw new Go(409,"A coupon with this code already exists");if(n instanceof Error)throw Error(`Failed to update coupon: ${n.message}`);throw n}}async function Ko(e){let t=qo(new Date),r=await Vo.unsafe(`UPDATE coupons
3
- SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ?
4
- WHERE id = ?
2
+ var Jp=Object.defineProperty;var Bp=(e)=>e;function Op(e,t){this[e]=Bp.bind(null,t)}var y=(e,t)=>{for(var r in t)Jp(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Op.bind(t,r)})};var Up=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=import.meta.require;var $s={};y($s,{canTransition:()=>Ze,emitForStatus:()=>He,emitOrderCancelled:()=>ve,emitOrderCreated:()=>Ke,emitOrderDelivered:()=>Ct,emitOrderOutForDelivery:()=>Us,emitOrderPaid:()=>ce,emitOrderRefunded:()=>Pe,emitOrderShipped:()=>St});function Ze(e,t){if(e===t)return!0;return gm[e]?.includes(t)??!1}async function we(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 Ke(e){await we("order:created",{order:e})}async function ce(e,t){await we("order:paid",{order:e,payment:t})}async function St(e){await we("order:shipped",{order:e})}async function Us(e){await we("order:out_for_delivery",{order:e})}async function Ct(e){await we("order:delivered",{order:e})}async function ve(e,t){await we("order:cancelled",{order:e,reason:t})}async function Pe(e,t){await we("order:refunded",{order:e,refundAmount:t})}async function He(e,t){switch(e){case"PROCESSING":return ce(t);case"SHIPPED":return St(t);case"OUT_FOR_DELIVERY":return Us(t);case"DELIVERED":return Ct(t);case"CANCELLED":return ve(t);case"REFUNDED":return Pe(t);case"PENDING":default:}}var gm;var Fe=Up(()=>{gm={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 cn={};y(cn,{DEFAULT_INCREMENT_LADDER:()=>Z,auctionChannel:()=>ht,auctionTotals:()=>Hr,biddersFor:()=>Or,bids:()=>Vr,bidsByBidder:()=>Br,bidsForAuction:()=>Jr,bidsForItem:()=>Nr,broadcastBid:()=>$r,broadcastItemClosed:()=>Lr,broadcastPledge:()=>Wr,closeAuction:()=>en,closeDueItems:()=>Xr,closeItem:()=>Le,closingSoon:()=>rn,closingSoonNotification:()=>zp,currencyFor:()=>jr,determineWinner:()=>Re,effectiveCloseAt:()=>se,engine:()=>qr,extendedCloseAt:()=>Oe,fetchAuction:()=>L,fetchAuctionForEvent:()=>Zr,fetchCatalogue:()=>Kr,fetchItems:()=>H,fetchPledges:()=>sn,incrementFor:()=>J,leadingBid:()=>Be,lots:()=>nn,makePledge:()=>Co,nextMinimumBid:()=>K,openAuction:()=>Yr,outbidNotification:()=>Lp,placeBid:()=>Gr,pledgeLevels:()=>Ao,pledgeTotal:()=>an,pledges:()=>un,resolveBid:()=>Ue,rulesFor:()=>$e,settle:()=>We,settleAuction:()=>tn,winnerNotification:()=>jp});var Vr={};y(Vr,{biddersFor:()=>Or,bidsByBidder:()=>Br,bidsForAuction:()=>Jr,bidsForItem:()=>Nr,leadingBid:()=>Be,placeBid:()=>Gr});import{db as q}from"@stacksjs/database";async function Be(e){return await q.selectFrom("bids").selectAll().where("auction_item_id","=",e).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function Nr(e){return await q.selectFrom("bids").selectAll().where("auction_item_id","=",e).orderBy("placed_at","desc").execute()??[]}async function Jr(e){return await q.selectFrom("bids").selectAll().where("auction_id","=",e).orderBy("placed_at","asc").execute()??[]}async function Br(e,t){return await q.selectFrom("bids").selectAll().where("auction_id","=",e).where("bidder_email","=",t.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function Or(e){let t=await q.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:Wp}=globalThis.Bun;import{db as zr}from"@stacksjs/database";function Oe(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 se(e,t){return new Date(e.closes_at??t)}var Z=[{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 J(e,t=Z,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 K(e,t,r=Z){if(t===null||t<=0)return e.starting_bid;return t+J(t,r,e.min_increment)}function Ue(e,t,r,n=Z){let o=Math.max(r.amount,r.maxAmount??0),a=K(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 l=Math.max(e.starting_bid,r.amount);return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:l,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:l,nextMinimumBid:l+J(l,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+J(t.amount,n,e.min_increment)}}if(o>s){let l=s+J(s,n,e.min_increment),p=Math.min(o,Math.max(l,a));return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:p,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:p,outbid:{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:t.amount},nextMinimumBid:p+J(p,n,e.min_increment)}}let u=o+J(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+J(c,n,e.min_increment)}}function ht(e){return`auction.${e}`}async function Ur(){try{return(await import("@stacksjs/realtime")).emit??null}catch{return null}}async function $r(e){let t=await Ur();if(!t||!e.item||!e.leader)return;await t(ht(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 Wr(e,t){let r=await Ur();if(!r)return;await r(ht(e.auction_id),"pledge.made",{donorName:e.donor_name,amount:e.amount,level:e.level??null,runningTotal:t})}async function Lr(e,t,r){let n=await Ur();if(!n)return;await n(ht(e),"item.closed",{itemId:t,...r})}import{config as $p}from"@stacksjs/config";function Eo(){return $p.commerce??{}}function So(){return Eo().auction??{}}function $e(e){let t=So();return{increments:t.increments?.length?t.increments:Z,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 jr(e){return e?.currency??So().currency??Eo().currency??"USD"}function gt(e){return e.toISOString().slice(0,19).replace("T"," ")}async function Gr(e){let t=e.now??new Date,r=await zr.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 zr.selectFrom("auctions").selectAll().where("id","=",r.auction_id).executeTakeFirst(),o=$e(n),a=await Be(r.id),s=K(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=se(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=Ue(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:Oe(r,i,o,t),l=u.leader&&!u.leader.isChallenger&&a&&a.bidder_email.toLowerCase()===e.bidderEmail.toLowerCase(),p=await zr.transaction(async(f)=>{if(l&&a)return await f.updateTable("bids").set({max_amount:u.leader.maxAmount}).where("id","=",a.id).execute(),{...a,max_amount:u.leader.maxAmount};let h=u.leader?.isChallenger===!0,b=Wp();if(await f.insertInto("bids").values({uuid:b,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:h?"leading":"outbid",placed_at:gt(t)}).execute(),a){if(h)await f.updateTable("bids").set({status:"outbid"}).where("id","=",a.id).execute();else if(u.leader&&u.leader.amount!==a.amount)await f.updateTable("bids").set({amount:u.leader.amount}).where("id","=",a.id).execute()}if(u.buyNow)await f.updateTable("auction_items").set({status:"sold",closes_at:gt(t)}).where("id","=",r.id).execute();else if(c)await f.updateTable("auction_items").set({closes_at:gt(c),extension_count:r.extension_count+1}).where("id","=",r.id).execute();return await f.selectFrom("bids").selectAll().where("uuid","=",b).executeTakeFirst()}),m={...u,bid:p,item:{...r,status:u.buyNow?"sold":r.status,closes_at:c?gt(c):r.closes_at,extension_count:c?r.extension_count+1:r.extension_count},extendedTo:c??void 0};return await $r(m).catch(()=>{return}),m}var qr={};y(qr,{DEFAULT_INCREMENT_LADDER:()=>Z,determineWinner:()=>Re,effectiveCloseAt:()=>se,extendedCloseAt:()=>Oe,incrementFor:()=>J,nextMinimumBid:()=>K,resolveBid:()=>Ue,settle:()=>We});function Re(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 We(e,t,r,n){let o=t.filter((p)=>p.status==="sold"),a=t.filter((p)=>p.status==="passed"),s=o.reduce((p,m)=>p+m.amount,0),i=r.filter((p)=>p.status==="confirmed").reduce((p,m)=>p+m.amount,0),u=new Map(e.map((p)=>[p.id,p.fair_market_value??null])),c=o.reduce((p,m)=>{let f=u.get(m.itemId);return f==null?p:p+(m.amount-f)},0),l=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:l===0?0:o.length/l,valueDelta:c,outcomes:t}}var nn={};y(nn,{auctionTotals:()=>Hr,closeAuction:()=>en,closeDueItems:()=>Xr,closeItem:()=>Le,closingSoon:()=>rn,fetchAuction:()=>L,fetchAuctionForEvent:()=>Zr,fetchCatalogue:()=>Kr,fetchItems:()=>H,openAuction:()=>Yr,settleAuction:()=>tn});import{db as B}from"@stacksjs/database";async function L(e){return await B.selectFrom("auctions").selectAll().where("id","=",e).executeTakeFirst()??null}async function Zr(e){return await B.selectFrom("auctions").selectAll().where("event_id","=",e).executeTakeFirst()??null}async function H(e){return await B.selectFrom("auction_items").selectAll().where("auction_id","=",e).orderBy("lot_number","asc").execute()??[]}async function Kr(e){let[t,r]=await Promise.all([L(e),H(e)]),n=$e(t),o=await B.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",e).where("status","in",["leading","won"]).execute(),a=await B.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:K(u,c?.amount??null,n.increments),leaderName:c?.bidder_name??null}})}async function Hr(e){let t=await L(e),r=await B.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",e).where("status","!=","invalid").execute(),n=await B.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,l)=>c+l.amount,0),i=(n??[]).reduce((c,l)=>c+l.amount,0),u=await B.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 ie}from"@stacksjs/database";function Qr(e){return e.toISOString().slice(0,19).replace("T"," ")}async function Yr(e,t=new Date){return await ie.updateTable("auctions").set({status:"open",opens_at:Qr(t)}).where("id","=",e).execute(),await ie.updateTable("auction_items").set({status:"open"}).where("auction_id","=",e).where("status","=","closed").execute(),L(e)}async function Le(e,t=new Date){if(e.status==="sold"||e.status==="passed")return null;let r=await ie.selectFrom("bids").selectAll().where("auction_item_id","=",e.id).execute(),n=Re(e,r??[]);return await ie.transaction(async(o)=>{if(await o.updateTable("auction_items").set({status:n.status,closes_at:Qr(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 Lr(e.auction_id,e.id,{status:n.status,amount:n.amount,winnerName:n.winnerName}).catch(()=>{return}),n}async function Xr(e,t=new Date){let r=await L(e);if(!r)return[];let n=await H(e),o=[];for(let a of n){if(a.status!=="open")continue;if(se(a,r.closes_at)>t)continue;let s=await Le(a,t);if(s)o.push(s)}return o}async function en(e,t=new Date){let r=await H(e),n=[];for(let o of r){let a=await Le(o,t);if(a)n.push(a)}return await ie.updateTable("auctions").set({status:"closed",closes_at:Qr(t)}).where("id","=",e).execute(),n}async function tn(e,t={}){let r=await L(e);if(!r)return null;let n=await H(e),o=await ie.selectFrom("bids").selectAll().where("auction_id","=",e).execute(),a=await ie.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=Re(u,s.get(u.id)??[]);return u.status==="passed"?{...c,status:"passed"}:c});if(t.markSettled)await ie.updateTable("auctions").set({status:"settled"}).where("id","=",e).execute();return We(n,i,a??[],{auctionId:e,currency:jr(r),goalAmount:r.goal_amount??null})}async function rn(e,t,r=new Date){let n=await L(e);if(!n)return[];let o=new Date(r.getTime()+t*60000);return(await H(e)).filter((a)=>{if(a.status!=="open")return!1;let s=se(a,n.closes_at);return s>r&&s<=o})}function on(e,t="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:t,minimumFractionDigits:0}).format(e/100)}function Lp(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 ${on(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 jp(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 ${on(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 zp(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 ${on(r,n)}.`,data:{itemId:e.id,lotNumber:e.lot_number,title:e.title,currentBid:r,closesAt:e.closes_at}}}var un={};y(un,{fetchPledges:()=>sn,makePledge:()=>Co,pledgeLevels:()=>Ao,pledgeTotal:()=>an});var{randomUUIDv7:Gp}=globalThis.Bun;import{db as je}from"@stacksjs/database";async function Co(e){let t=Gp();await je.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 je.selectFrom("pledges").selectAll().where("uuid","=",t).executeTakeFirst();return await Wr(r,await an(e.auctionId)).catch(()=>{return}),r}async function an(e){return(await je.selectFrom("pledges").select(["amount"]).where("auction_id","=",e).where("status","=","confirmed").execute()??[]).reduce((r,n)=>r+n.amount,0)}async function sn(e){return await je.selectFrom("pledges").selectAll().where("auction_id","=",e).orderBy("amount","desc").execute()??[]}async function Ao(e){let t=(await sn(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 dn={};y(dn,{bulkDestroy:()=>No,bulkStore:()=>Lo,bulkUpdate:()=>Vo,destroy:()=>Mo,fetchAll:()=>Oo,fetchById:()=>Bo,store:()=>Wo,update:()=>Go});import{db as Io}from"@stacksjs/database";function d(e){if(typeof e==="number")return Number.isFinite(e)?e:0;if(typeof e==="bigint")return Number(e);if(!e||typeof e!=="object")return 0;let t=e;for(let r of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if(t[r]!==void 0&&t[r]!==null)return d(t[r]);if(Array.isArray(e))return e.reduce((r,n)=>r+d(n),0);return 0}async function Mo(e){try{let t=await Io.deleteFrom("carts").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete cart: ${t.message}`);throw t}}async function No(e){if(!e.length)return 0;try{let t=await Io.deleteFrom("carts").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete carts: ${t.message}`);throw t}}import{db as Jo}from"@stacksjs/database";async function Bo(e){return await Jo.selectFrom("carts").where("id","=",e).selectAll().executeTakeFirst()}async function Oo(){return await Jo.selectFrom("carts").selectAll().execute()}var{randomUUIDv7:Uo}=globalThis.Bun;import{db as $o}from"@stacksjs/database";async function Wo(e){try{let t={...e,uuid:Uo()},r=await $o.insertInto("carts").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create cart");return r}catch(t){if(t instanceof Error)throw TypeError(`Failed to create cart: ${t.message}`);throw t}}async function Lo(e){if(!e.length)return 0;let t=0;try{return await $o.transaction(async(r)=>{for(let n of e){let o={...n,uuid:Uo()};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 jo}from"@stacksjs/database";import{formatDate as zo}from"@stacksjs/orm";async function Go(e,t){try{let r=await jo.updateTable("carts").set({...t,updated_at:zo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update cart");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update cart: ${r.message}`);throw r}}async function Vo(e){if(!e.length)return 0;let t=0;try{return await jo.transaction(async(r)=>{for(let n of e){if(!n.id)continue;let o=await r.updateTable("carts").set({...n,updated_at:zo(new Date)}).where("id","=",n.id).executeTakeFirst();if(Number(o.numUpdatedRows)>0)t++}}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update carts in bulk: ${r.message}`);throw r}}var ln={};y(ln,{deleteCoupon:()=>qo,deleteCoupons:()=>Zo,deleteExpiredCoupons:()=>Ko,fetchActive:()=>ea,fetchAll:()=>Yo,fetchByCode:()=>Xo,fetchById:()=>fe,fetchConversionRate:()=>ia,fetchCouponCounts:()=>ra,fetchCouponCountsByType:()=>na,fetchRedemptionStats:()=>oa,fetchRedemptionTrend:()=>sa,fetchStats:()=>ta,fetchTopRedeemedCoupons:()=>aa,getActiveCouponsMoMChange:()=>ua,redeem:()=>ya,store:()=>la,update:()=>wa});import{db as bt}from"@stacksjs/database";import{formatDate as Vp}from"@stacksjs/orm";async function qo(e){let t=await bt.deleteFrom("coupons").where("id","=",e).executeTakeFirst();return d(t)>0}async function Zo(e){if(!e.length)return 0;return await bt.deleteFrom("coupons").where("id","in",e).execute()||0}async function Ko(){let e=Vp(new Date),t=await bt.deleteFrom("coupons").where("end_date","<",e).executeTakeFirst();return d(t)}import{db as w}from"@stacksjs/database";import{extractDate as Ho,formatDate as Qo}from"@stacksjs/orm";import{camelCase as qp}from"@stacksjs/strings";function xt(e){let t=Object.fromEntries(Object.entries(e).map(([r,n])=>[qp(r),n]));if(t.endDate)t.endDate=Ho(new Date(t.endDate));if(t.startDate)t.startDate=Ho(new Date(t.startDate));if(t.isActive!==void 0)t.isActive=Boolean(t.isActive);return t}async function Yo(){return(await w.selectFrom("coupons").selectAll().execute()).map(xt)}async function fe(e){let t=await w.selectFrom("coupons").where("id","=",e).selectAll().executeTakeFirst();if(t)return xt(t);return}async function Xo(e){let t=await w.selectFrom("coupons").where("code","=",e).selectAll().executeTakeFirst();if(t)return xt(t);return}async function ea(){let e=Qo(new Date);return(await w.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).selectAll().execute()).map(xt)}async function ta(){let e=await w.selectFrom("coupons").select(w.fn.count("id").as("count")).executeTakeFirst(),t=Qo(new Date),r=await w.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(w.fn.count("id").as("count")).executeTakeFirst(),n=await w.selectFrom("coupons").select(["discount_type",w.fn.count("id").as("count")]).groupBy("discount_type").execute(),o=await w.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),a=await w.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 ra(){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 _t(null,null,e),a=await _t(t,null,e),s=await _t(r,null,e),i=await _t(n,null,e);return{week:a,month:s,year:i,all_time:o}}async function _t(e,t,r){let n=w.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(w.fn.count("id").as("count")).executeTakeFirst(),a=w.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(w.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 na(){let e=new Date,t=await w.selectFrom("coupons").select("discount_type").distinct().execute(),r={};for(let{discount_type:n}of t){let o=await w.selectFrom("coupons").where("discount_type","=",n).select(w.fn.count("id").as("count")).executeTakeFirst(),a=await w.selectFrom("coupons").where("discount_type","=",n).where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(w.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 oa(){let e=await w.selectFrom("coupons").select(w.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 w.selectFrom("coupons").where("updated_at",">=",r.toISOString()).select(w.fn.sum("usage_count").as("total")).executeTakeFirst(),s=await w.selectFrom("coupons").where("updated_at",">=",n.toISOString()).select(w.fn.sum("usage_count").as("total")).executeTakeFirst(),i=await w.selectFrom("coupons").where("updated_at",">=",o.toISOString()).select(w.fn.sum("usage_count").as("total")).executeTakeFirst(),u=await w.selectFrom("coupons").select(["discount_type",w.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),c={};return u.forEach((l)=>{c[l.discount_type]=Number(l.total||0)}),{total:Number(e?.total||0),week:Number(a?.total||0),month:Number(s?.total||0),year:Number(i?.total||0),by_type:c}}async function aa(e=5){return await w.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 sa(e=30){let t=new Date().toISOString(),r=new Date;r.setDate(r.getDate()-e);let n=await w.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 ia(){let e=new Date,t=await w.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(w.fn.count("id").as("count")).executeTakeFirst(),r=await w.selectFrom("coupons").where("usage_count",">",0).select(w.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 ua(){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 w.selectFrom("coupons").select(w.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",t).executeTakeFirst(),a=await w.selectFrom("coupons").select(w.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:Zp}=globalThis.Bun;import{db as ca}from"@stacksjs/database";import{HttpError as da}from"@stacksjs/error-handling";import{isUniqueViolation as Kp}from"@stacksjs/orm";async function la(e){try{let t=Zp();return await ca.insertInto("coupons").values({...e,uuid:t}).executeTakeFirst(),await ca.selectFrom("coupons").where("uuid","=",t).selectAll().executeTakeFirst()}catch(t){if(t instanceof da)throw t;if(Kp(t))throw new da(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 ma,sqlHelpers as Hp}from"@stacksjs/database";import{env as Qp}from"@stacksjs/env";import{HttpError as pa}from"@stacksjs/error-handling";import{formatDate as fa,isUniqueViolation as Yp}from"@stacksjs/orm";async function wa(e,t){if(!await fe(e))return;try{return await ma.updateTable("coupons").set({...t,updated_at:fa(new Date)}).where("id","=",e).execute(),await fe(e)}catch(n){if(n instanceof pa)throw n;if(Yp(n))throw new pa(409,"A coupon with this code already exists");if(n instanceof Error)throw Error(`Failed to update coupon: ${n.message}`);throw n}}async function ya(e){let t=Hp(Qp.DB_CONNECTION||"sqlite"),r=t.param,n=fa(new Date),a=await ma.unsafe(`UPDATE coupons
3
+ SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ${r(1)}
4
+ WHERE id = ${r(2)}
5
5
  AND (max_uses IS NULL OR usage_count < max_uses)
6
- AND is_active = 1
7
- AND (start_date IS NULL OR start_date <= ?)
8
- AND (end_date IS NULL OR end_date >= ?)`,[t,e,t,t]),n=typeof r?.execute==="function"?await r.execute():r;if(Number(n?.changes??n?.numUpdatedRows??n?.affectedRows??0)>0){let u=await me(e);if(u)return{ok:!0,coupon:u};return{ok:!1,reason:"not-found"}}let a=await me(e);if(!a)return{ok:!1,reason:"not-found"};if(!a.isActive)return{ok:!1,reason:"inactive"};let s=!a.startDate||a.startDate<=t,i=!a.endDate||a.endDate>=t;if(!s||!i)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var cn={};y(cn,{bulkDestroy:()=>Yo,destroy:()=>Qo,fetchAll:()=>ea,fetchById:()=>xt,store:()=>ra,update:()=>oa});import{db as Ho}from"@stacksjs/database";async function Qo(e){try{let t=await Ho.deleteFrom("customers").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete customer: ${t.message}`);throw t}}async function Yo(e){if(!e.length)return 0;try{let t=await Ho.deleteFrom("customers").where("id","in",e).executeTakeFirst();return d(t)||0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${t.message}`);throw t}}import{db as Xo}from"@stacksjs/database";async function xt(e){return await Xo.selectFrom("customers").where("id","=",e).selectAll().executeTakeFirst()}async function ea(){return await Xo.selectFrom("customers").selectAll().execute()}import{db as Tm}from"@stacksjs/database";import{HttpError as ta}from"@stacksjs/error-handling";import{isUniqueViolation as Em}from"@stacksjs/orm";async function ra(e){try{let t={...e,avatar:e.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},r=await Tm.insertInto("customers").values(t).executeTakeFirst();if(!r)throw Error("Failed to create customer");let n=r.insertId||Number(r.numInsertedOrUpdatedRows);return await xt(Number(n))}catch(t){if(t instanceof ta)throw t;if(Em(t))throw new ta(409,"A customer with this email already exists");if(t instanceof Error)throw Error(`Failed to create customer: ${t.message}`);throw t}}import{db as Sm}from"@stacksjs/database";import{HttpError as na}from"@stacksjs/error-handling";import{formatDate as Cm,isUniqueViolation as Am}from"@stacksjs/orm";async function oa(e,t){try{if(!e)throw Error("Customer ID is required for update");let r=await Sm.updateTable("customers").set({...t,updated_at:Cm(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof na)throw r;if(Am(r))throw new na(409,"A customer with this email already exists");if(r instanceof Error)throw Error(`Failed to update customer: ${r.message}`);throw r}}var fn={};y(fn,{bulkDestroy:()=>ia,bulkStore:()=>_a,calculateErrorRate:()=>la,calculatePrinterHealth:()=>pa,countAll:()=>ua,countPrintsByDeviceId:()=>da,countTotalPrints:()=>ca,destroy:()=>sa,downloadPrintDevices:()=>ya,exportPrintDevices:()=>vt,fetchAll:()=>Rt,fetchById:()=>Q,fetchErrorsByDeviceId:()=>ma,getPrinterStatusCounts:()=>fa,store:()=>ba,storePrintDevicesExport:()=>ha,update:()=>xa,updatePrintCount:()=>va,updateStatus:()=>Ra});import{db as aa}from"@stacksjs/database";async function sa(e){try{let t=await aa.deleteFrom("print_devices").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print device: ${t.message}`);throw t}}async function ia(e){if(!e.length)return 0;try{let t=await aa.deleteFrom("print_devices").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print devices: ${t.message}`);throw t}}import{createSpreadsheet as Im}from"ts-spreadsheets";import{db as T}from"@stacksjs/database";async function Q(e){return await T.selectFrom("print_devices").where("id","=",e).selectAll().executeTakeFirst()}async function Rt(){return await T.selectFrom("print_devices").selectAll().execute()}async function ua(){let e=await T.selectFrom("print_devices").select(T.fn.count("id").as("count")).executeTakeFirst();return Number(e?.count||0)}async function ca(){let e=await T.selectFrom("print_devices").select(T.fn.sum("print_count").as("total")).executeTakeFirst();return Number(e?.total||0)}async function da(e){return(await T.selectFrom("print_devices").select("print_count").where("id","=",e).executeTakeFirst())?.print_count??0}async function la(){let e=await T.selectFrom("receipts").select([T.fn.count("id").as("total"),T.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!e?.total||e.total===0)return 0;return Number((e.failed_count??0)/e.total*100)}async function ma(e){return await T.selectFrom("receipts").where("print_device_id","=",e).where("status","=","failed").selectAll().execute()}async function pa(){let e=await T.selectFrom("print_devices").select([T.fn.count("id").as("total"),T.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!e?.total||e.total===0)return 0;return Number((e.online_count??0)/e.total*100)}async function fa(){return(await T.selectFrom("print_devices").select(["status",T.fn.count("id").as("count")]).groupBy("status").execute()).reduce((t,r)=>(t[r.status]=Number(r.count||0),t),{})}function dn(e,t,r=t){let n=e;return n[String(t)]??n[r]}function Mm(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 wa(e,t,r=t){let n=dn(e,t,r);if(typeof n==="number")return n;let o=Number(n);return Number.isFinite(o)?o:0}function ze(e,t,r=t){let n=dn(e,t,r);return n==null?"":String(n)}async function vt(e="csv"){let t=await Rt(),r=Nm(t);return Im(r,{type:e})}function Nm(e){let t=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],r=e.map((n)=>[wa(n,"id"),ze(n,"name"),ze(n,"macAddress","mac_address"),ze(n,"location"),ze(n,"terminal"),ze(n,"status"),Mm(dn(n,"lastPing","last_ping")).toLocaleString(),wa(n,"printCount","print_count")]);return{headings:t,data:r}}async function ya(e="csv",t){let r=await vt(e),n=`print_devices_export_${new Date().toISOString().split("T")[0]}.${e}`;return r.download(t||n)}async function ha(e="csv",t){let r=await vt(e),n=`print_devices_export_${new Date().toISOString().split("T")[0]}.${e}`;r.store(t||n)}var{randomUUIDv7:ga}=globalThis.Bun;import{db as ln}from"@stacksjs/database";async function ba(e){try{let t=ga(),r={last_ping:0,print_count:0,...e,uuid:t};return await ln.insertInto("print_devices").values(r).executeTakeFirst(),await ln.selectFrom("print_devices").where("uuid","=",t).selectAll().executeTakeFirst()}catch(t){if(t instanceof Error)throw TypeError(`Failed to create print device: ${t.message}`);throw t}}async function _a(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:ga()};await ln.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 mn}from"@stacksjs/database";import{formatDate as pn}from"@stacksjs/orm";async function xa(e,t){if(!await Q(e))return;try{return await mn.updateTable("print_devices").set({...t,updated_at:pn(new Date)}).where("id","=",e).execute(),await Q(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print device: ${n.message}`);throw n}}async function Ra(e,t){if(!await Q(e))throw Error(`Print device with ID ${e} not found`);try{return await mn.updateTable("print_devices").set({status:t,updated_at:pn(new Date)}).where("id","=",e).execute(),await Q(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print device status: ${n.message}`);throw n}}async function va(e,t){if(!await Q(e))throw Error(`Print device with ID ${e} not found`);try{return await mn.updateTable("print_devices").set({print_count:t,updated_at:pn(new Date)}).where("id","=",e).execute(),await Q(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print count: ${n.message}`);throw n}}var hn={};y(hn,{bulkDestroy:()=>Pa,bulkUpdateStatus:()=>Ia,destroy:()=>Da,destroyGroup:()=>Fa,fetchAll:()=>Pt,fetchByGroup:()=>Ea,fetchById:()=>ka,fetchGrouped:()=>Ta,fetchStats:()=>Sa,fetchTimeline:()=>Ca,ignoreGroup:()=>Na,resolveGroup:()=>Ma,unresolveGroup:()=>Ja,update:()=>Aa});import{db as wn}from"@stacksjs/database";import{log as yn}from"@stacksjs/logging";async function Da(e){try{return await wn.deleteFrom("errors").where("id","=",e).execute(),!0}catch(t){return yn.error("[commerce/errors] destroy failed",{id:e,error:t}),!1}}async function Pa(e){try{return await wn.deleteFrom("errors").where("id","in",e).execute(),!0}catch(t){return yn.error("[commerce/errors] bulkDestroy failed",{count:e.length,error:t}),!1}}async function Fa(e,t){try{return await wn.deleteFrom("errors").where("type","=",e).where("message","=",t).execute(),!0}catch(r){return yn.error("[commerce/errors] destroyGroup failed",{type:e,message:t,error:r}),!1}}import{db as Dt}from"@stacksjs/database";async function ka(e){return await Dt.selectFrom("errors").where("id","=",e).selectAll().executeTakeFirst()}async function Pt(){return await Dt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function Ta(){let e=await Dt.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 Ea(e,t){return await Dt.selectFrom("errors").where("type","=",e).where("message","=",t).selectAll().orderBy("created_at","desc").execute()}async function Sa(){let e=await Pt(),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 Ca(){let e=await Pt(),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 je}from"@stacksjs/database";import{sql as Ge}from"@stacksjs/database";import{log as Ve}from"@stacksjs/logging";async function Aa(e,t){try{return await je.updateTable("errors").set({...t,updated_at:Ge.raw("CURRENT_TIMESTAMP")}).where("id","=",e).execute(),!0}catch(r){return Ve.error("[commerce/errors] update failed",{id:e,error:r}),!1}}async function Ia(e,t){try{return await je.updateTable("errors").set({status:t,updated_at:Ge.raw("CURRENT_TIMESTAMP")}).where("id","in",e).execute(),!0}catch(r){return Ve.error("[commerce/errors] bulkUpdateStatus failed",{count:e.length,status:t,error:r}),!1}}async function Ma(e,t){try{return await je.updateTable("errors").set({status:1,updated_at:Ge.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return Ve.error("[commerce/errors] resolveGroup failed",{type:e,message:t,error:r}),!1}}async function Na(e,t){try{return await je.updateTable("errors").set({status:2,updated_at:Ge.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return Ve.error("[commerce/errors] ignoreGroup failed",{type:e,message:t,error:r}),!1}}async function Ja(e,t){try{return await je.updateTable("errors").set({status:0,updated_at:Ge.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return Ve.error("[commerce/errors] unresolveGroup failed",{type:e,message:t,error:r}),!1}}var _n={};y(_n,{bulkDestroy:()=>qa,calculateGiftCardValues:()=>La,checkBalance:()=>$a,compareActiveGiftCards:()=>Wa,destroy:()=>Va,fetchActive:()=>Oa,fetchAll:()=>Ba,fetchByCode:()=>gn,fetchById:()=>pe,fetchStats:()=>Ua,fetchTotalCurrentBalance:()=>ja,fetchTotalValue:()=>za,store:()=>Ka,update:()=>Xa,updateBalance:()=>es});import{db as Ga}from"@stacksjs/database";import{formatDate as Sy}from"@stacksjs/orm";import{db as v,sql as A}from"@stacksjs/database";import{formatDate as ae,toTimestamp as Re}from"@stacksjs/orm";import{aggregateFunctions as Jm,db as Bm}from"@stacksjs/database";async function M(e,t,r){let n=Bm.selectFrom(e);if(r)n=r(n);n=n.select(Object.entries(t).map(([s,i])=>{let u=i.column??"id",c=Jm[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 Ba(){return await v.selectFrom("gift_cards").selectAll().execute()}async function pe(e){return await v.selectFrom("gift_cards").where("id","=",e).selectAll().executeTakeFirst()}async function gn(e){return await v.selectFrom("gift_cards").where("code","=",e).selectAll().executeTakeFirst()}async function Oa(){return await v.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function Ua(){let{count:e}=await M("gift_cards",{count:{kind:"count"}}),t=Re(new Date),r=await v.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(A`(expiry_date >= ${A.literal(t)} OR expiry_date IS NULL)`).select(v.fn.count("id").as("count")).executeTakeFirst(),n=await v.selectFrom("gift_cards").select(["status",v.fn.count("id").as("count")]).groupBy("status").execute(),{count:o}=await M("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(A`current_balance / initial_balance < 0.25`)),{count:a}=await M("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(A`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:s}=await M("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(A`current_balance / initial_balance > 0.75`)),i=new Date;i.setDate(i.getDate()+30);let u=await v.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",Re(i)).where("expiry_date",">=",t).selectAll().limit(5).execute(),c=await v.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:e,active:Number(r?.count||0),by_status:n.map((l)=>({status:l.status,count:Number(l.count)})),by_balance:{low:o,medium:a,high:s},expiring_soon:u,recently_used:c}}async function $a(e){let t=await gn(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 Wa(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 v.selectFrom("gift_cards").select(v.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(A`(expiry_date >= ${A.literal(Re(t))} OR expiry_date IS NULL)`).where("created_at",">=",ae(r)).where("created_at","<=",ae(t)).executeTakeFirst(),s=await v.selectFrom("gift_cards").select(v.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(A`(expiry_date >= ${A.literal(Re(o))} OR expiry_date IS NULL)`).where("created_at",">=",ae(o)).where("created_at","<=",ae(n)).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,l=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:l,days_range:e}}async function La(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 v.selectFrom("gift_cards").select([v.fn.sum("initial_balance").as("total_initial"),v.fn.sum("current_balance").as("total_balance"),v.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(A`(expiry_date >= ${A.literal(Re(t))} OR expiry_date IS NULL)`).where("created_at",">=",ae(r)).where("created_at","<=",ae(t)).executeTakeFirst(),s=await v.selectFrom("gift_cards").select([v.fn.sum("initial_balance").as("total_initial"),v.fn.sum("current_balance").as("total_balance"),v.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(A`(expiry_date >= ${A.literal(Re(o))} OR expiry_date IS NULL)`).where("created_at",">=",ae(o)).where("created_at","<=",ae(n)).executeTakeFirst(),i=Number(a?.total_initial||0),u=Number(a?.total_balance||0),c=Number(a?.card_count||0),l=Number(s?.total_initial||0),m=Number(s?.total_balance||0),p=Number(s?.card_count||0),w=i>0?(i-u)/i*100:0,x=l>0?(l-m)/l*100:0,b=c>0?i/c:0,R=c>0?u/c:0,j=i-l,de=u-m,le=c-p,_e=l!==0?j/l*100:i>0?100:0,G=m!==0?de/m*100:u>0?100:0,mm=p!==0?le/p*100:c>0?100:0;return{current_period:{total_initial_value:i,total_remaining_balance:u,utilization_rate:w,card_count:c,average_initial_value:b,average_remaining_balance:R},previous_period:{total_initial_value:l,total_remaining_balance:m,utilization_rate:x,card_count:p},comparison:{initial_value:{difference:j,percentage:Math.abs(_e),is_increase:j>=0},balance:{difference:de,percentage:Math.abs(G),is_increase:de>=0},card_count:{difference:le,percentage:Math.abs(mm),is_increase:le>=0}},days_range:e}}async function za(){let{total_value:e}=await M("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:e}}async function ja(){let{total_balance:e}=await M("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:e}}async function Va(e){let t=await Ga.deleteFrom("gift_cards").where("id","=",e).executeTakeFirst();return d(t)>0}async function qa(e){if(!e.length)return 0;let t=await Ga.deleteFrom("gift_cards").where("id","in",e).executeTakeFirst();return d(t)}var{randomUUIDv7:Om}=globalThis.Bun;import{db as bn}from"@stacksjs/database";import{HttpError as Za}from"@stacksjs/error-handling";import{isUniqueViolation as Um}from"@stacksjs/orm";async function Ka(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:Om()};try{let o=await bn.insertInto("gift_cards").values(r).executeTakeFirst()??{},a=Number(o.insertId??0)||Number(o.numInsertedOrUpdatedRows??0);if(a)return await bn.selectFrom("gift_cards").where("id","=",a).selectAll().executeTakeFirst();return}catch(n){if(n instanceof Za)throw n;if(Um(n))throw new Za(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 Qa}from"@stacksjs/database";import{HttpError as Ha}from"@stacksjs/error-handling";import{formatDate as Ya,isUniqueViolation as $m}from"@stacksjs/orm";async function Xa(e,t){if(!await pe(e))return;try{return await Qa.updateTable("gift_cards").set({...t,updated_at:Ya(new Date)}).where("id","=",e).execute(),await pe(e)}catch(n){if(n instanceof Ha)throw n;if($m(n))throw new Ha(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 es(e,t){if(!Number.isFinite(t))throw Error(`Gift card balance adjustment must be a finite number, got ${t}`);let r=Ya(new Date),n=await Qa.unsafe(`UPDATE gift_cards
9
- SET current_balance = current_balance + ?,
10
- last_used_date = ?,
11
- status = CASE WHEN current_balance + ? = 0 THEN 'USED' ELSE 'ACTIVE' END,
12
- updated_at = ?
13
- WHERE id = ?
14
- AND is_active = 1
15
- AND status = 'ACTIVE'
16
- AND current_balance + ? >= 0`,[t,r,t,r,e,t]),o=typeof n?.execute==="function"?await n.execute():n;if(Number(o?.changes??o?.numUpdatedRows??o?.affectedRows??0)>0)return await pe(e);let s=await pe(e);if(!s)throw Error(`Gift card with ID ${e} not found`);if(!s.is_active||s.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var En={};y(En,{bulkDestroy:()=>ns,bulkSoftDelete:()=>os,calculateOrderMetrics:()=>ms,canTransition:()=>qe,cleanupAbandonedCarts:()=>Ms,compareOrdersByPeriod:()=>ls,destroy:()=>ts,downloadOrders:()=>ss,emitForStatus:()=>Ke,emitOrderCancelled:()=>ve,emitOrderCreated:()=>Ze,emitOrderDelivered:()=>Et,emitOrderPaid:()=>se,emitOrderRefunded:()=>De,emitOrderShipped:()=>Tt,exportOrders:()=>kt,fetchAll:()=>cs,fetchById:()=>Y,fetchDailyOrderTrends:()=>ps,fetchStats:()=>ds,findOrderByIdempotencyKey:()=>Ct,handleChargeRefunded:()=>kn,handlePaymentIntentFailed:()=>Fn,handlePaymentIntentSucceeded:()=>Pn,placeOrder:()=>Ds,recomputeOrderTotals:()=>Cs,registerCommerceWebhookHandlers:()=>Es,softDelete:()=>rs,store:()=>ys,storeOrdersExport:()=>is,update:()=>Ps,updateDeliveryInfo:()=>ks,updateStatus:()=>Fs,validateCartQuantities:()=>Is,validateCouponStacking:()=>As,validateQuantityBounds:()=>Tn});import{db as Ft}from"@stacksjs/database";async function ts(e){try{let t=await Ft.deleteFrom("orders").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete order: ${t.message}`);throw t}}async function rs(e){try{let t=await Ft.updateTable("orders").set({status:"CANCELED"}).where("id","=",e).executeTakeFirst();return Number(t.numUpdatedRows)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete order: ${t.message}`);throw t}}async function ns(e){if(!e.length)return 0;try{let t=await Ft.deleteFrom("orders").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete orders: ${t.message}`);throw t}}async function os(e){if(!e.length)return 0;try{let t=await Ft.updateTable("orders").set({status:"CANCELED"}).where("id","in",e).executeTakeFirst();return Number(t.numUpdatedRows)}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete orders: ${t.message}`);throw t}}import{db as as}from"@stacksjs/database";import{createSpreadsheet as Wm}from"ts-spreadsheets";async function kt(e="csv"){let t=await Lm(),r=zm(t);return Wm(r,{type:e})}async function Lm(){let e=await as.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),t=e.map((a)=>a.id);if(t.length===0)return[];let n=(await as.selectFrom("order_items").where("order_items.order_id","in",t).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((a,s)=>{if(!s.order_id)return a;if(!a[s.order_id])a[s.order_id]={totalItems:0,totalPrice:0};return a[s.order_id].totalItems+=s.quantity,a[s.order_id].totalPrice+=s.price*s.quantity,a},{});return e.map((a)=>{let s=n[a.id]||{totalItems:0,totalPrice:0};return{...a,totalItems:s.totalItems,totalPrice:s.totalPrice}})}function zm(e){let t=["Order ID","Customer","Date","Total","Status","Items"],r=e.map((n)=>{let o=n.order_items?.map((a)=>`${a.product?.name} (Qty: ${a.quantity}, Price: $${a.price})`).join(" | ")||"No Items";return[n.id,n.customer?.name||"N/A",n.created_at,n.total_amount,n.status,o]});return{headings:t,data:r}}async function ss(e="csv",t){let r=await kt(e),n=`orders_export_${new Date().toISOString().split("T")[0]}.${e}`;return r.download(t||n)}async function is(e="csv",t){let r=await kt(e),n=`orders_export_${new Date().toISOString().split("T")[0]}.${e}`;r.store(t||n)}import{asRows as us,db as g}from"@stacksjs/database";async function cs(e){let t=g.selectFrom("orders").selectAll().orderBy("created_at","desc");if(e)t=t.limit(e);let r=us(await t.execute());return await Promise.all(r.map(async(n)=>{let o=await g.selectFrom("order_items").where("order_id","=",n.id).selectAll().execute();return{...n,items:o}}))}async function Y(e){return await g.selectFrom("orders").where("id","=",e).selectAll().executeTakeFirst()}async function ds(){let e=await g.selectFrom("orders").select(g.fn.count("id").as("count")).executeTakeFirst(),t=await g.selectFrom("orders").select(["status",g.fn.count("id").as("count")]).groupBy("status").execute(),r=await g.selectFrom("orders").select(["order_type",g.fn.count("id").as("count")]).groupBy("order_type").execute(),n=us(await g.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute()),o=await Promise.all(n.map(async(s)=>{let i=await g.selectFrom("order_items").where("order_id","=",s.id).selectAll().execute();return{...s,items:i}})),a=await g.selectFrom("orders").select(g.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 ls(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 g.selectFrom("orders").select(g.fn.count("id").as("count")).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).executeTakeFirst(),s=await g.selectFrom("orders").select(g.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,l=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:l,days_range:e}}async function ms(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 g.selectFrom("orders").select([g.fn.count("id").as("total_orders"),g.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).executeTakeFirst(),s=await g.selectFrom("orders").select([g.fn.count("id").as("total_orders"),g.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",o.toISOString()).where("created_at","<=",n.toISOString()).executeTakeFirst(),i=await g.selectFrom("orders").select(["status",g.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).groupBy("status").execute(),u=await g.selectFrom("orders").select(["order_type",g.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),l=Number(a?.total_revenue||0),m=c>0?l/c:0,p=Number(s?.total_orders||0),w=Number(s?.total_revenue||0),x=p>0?w/p:0,b=c-p,R=l-w,j=m-x,de=p!==0?b/p*100:c>0?100:0,le=w!==0?R/w*100:l>0?100:0,_e=x!==0?j/x*100:m>0?100:0;return{current_period:{total_orders:c,total_revenue:l,average_order_value:m,orders_by_status:i.map((G)=>({status:G.status,count:Number(G.count)})),orders_by_type:u.map((G)=>({order_type:G.order_type,count:Number(G.count)}))},previous_period:{total_orders:p,total_revenue:w,average_order_value:x},comparison:{orders:{difference:b,percentage:Math.abs(de),is_increase:b>=0},revenue:{difference:R,percentage:Math.abs(le),is_increase:R>=0},average_order_value:{difference:j,percentage:Math.abs(_e),is_increase:j>=0}},days_range:e}}async function ps(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=await g.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:jm}=globalThis.Bun;import{db as fs}from"@stacksjs/database";import{formatDate as ws}from"@stacksjs/orm";async function ys(e){let t={...e,status:e.status||"PENDING",uuid:jm(),created_at:ws(new Date),updated_at:ws(new Date)};try{let r=await fs.insertInto("orders").values(t).executeTakeFirst(),n=Number(r?.insertId)||Number(r?.numInsertedOrUpdatedRows);if(n)return await fs.selectFrom("orders").where("id","=",n).selectAll().executeTakeFirst();return}catch(r){if(r instanceof Error)throw Error(`Failed to create order: ${r.message}`);throw r}}Pe();var{randomUUIDv7:_s}=globalThis.Bun;import{db as St}from"@stacksjs/database";import{formatDate as Km,isUniqueViolation as xs}from"@stacksjs/orm";import{sqlHelpers as Vm}from"@stacksjs/database";import{env as qm}from"@stacksjs/env";function Zm(e,t,r,n){let o=Vm(e).param;return{query:`UPDATE products
6
+ AND is_active = ${t.boolTrue}
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(Number(a?.changes??a?.numUpdatedRows??a?.affectedRows??0)>0){let l=await fe(e);if(l)return{ok:!0,coupon:l};return{ok:!1,reason:"not-found"}}let i=await fe(e);if(!i)return{ok:!1,reason:"not-found"};if(!i.isActive)return{ok:!1,reason:"inactive"};let u=!i.startDate||i.startDate<=n,c=!i.endDate||i.endDate>=n;if(!u||!c)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var mn={};y(mn,{bulkDestroy:()=>ba,destroy:()=>ga,fetchAll:()=>xa,fetchById:()=>Rt,store:()=>Da,update:()=>Pa});import{db as ha}from"@stacksjs/database";async function ga(e){try{let t=await ha.deleteFrom("customers").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete customer: ${t.message}`);throw t}}async function ba(e){if(!e.length)return 0;try{let t=await ha.deleteFrom("customers").where("id","in",e).executeTakeFirst();return d(t)||0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${t.message}`);throw t}}import{db as _a}from"@stacksjs/database";async function Rt(e){return await _a.selectFrom("customers").where("id","=",e).selectAll().executeTakeFirst()}async function xa(){return await _a.selectFrom("customers").selectAll().execute()}import{db as Xp}from"@stacksjs/database";import{HttpError as Ra}from"@stacksjs/error-handling";import{isUniqueViolation as em}from"@stacksjs/orm";function Q(e){if(typeof e==="bigint")return pn(e);if(typeof e==="number")return pn(e);if(!e||typeof e!=="object")return;if(Array.isArray(e)){for(let r of e){let n=Q(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=pn(n);if(o!==void 0)return o}return}function pn(e){let t=typeof e==="bigint"?Number(e):Number(e);if(!Number.isSafeInteger(t)||t<=0)return;return t}async function Da(e){try{let t={...e,avatar:e.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},r=await Xp.insertInto("customers").values(t).executeTakeFirst();if(!r)throw Error("Failed to create customer");let n=Q(r);if(n===void 0)throw Error("Failed to create customer: the database reported no insert id");return await Rt(n)}catch(t){if(t instanceof Ra)throw t;if(em(t))throw new Ra(409,"A customer with this email already exists");if(t instanceof Error)throw Error(`Failed to create customer: ${t.message}`);throw t}}import{db as tm}from"@stacksjs/database";import{HttpError as va}from"@stacksjs/error-handling";import{formatDate as rm,isUniqueViolation as nm}from"@stacksjs/orm";async function Pa(e,t){try{if(!e)throw Error("Customer ID is required for update");let r=await tm.updateTable("customers").set({...t,updated_at:rm(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof va)throw r;if(nm(r))throw new va(409,"A customer with this email already exists");if(r instanceof Error)throw Error(`Failed to update customer: ${r.message}`);throw r}}var gn={};y(gn,{bulkDestroy:()=>Ta,bulkStore:()=>Wa,calculateErrorRate:()=>Aa,calculatePrinterHealth:()=>Ma,countAll:()=>Ea,countPrintsByDeviceId:()=>Ca,countTotalPrints:()=>Sa,destroy:()=>ka,downloadPrintDevices:()=>Ba,exportPrintDevices:()=>vt,fetchAll:()=>Dt,fetchById:()=>Y,fetchErrorsByDeviceId:()=>Ia,getPrinterStatusCounts:()=>Na,store:()=>$a,storePrintDevicesExport:()=>Oa,update:()=>La,updatePrintCount:()=>za,updateStatus:()=>ja});import{db as Fa}from"@stacksjs/database";async function ka(e){try{let t=await Fa.deleteFrom("print_devices").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print device: ${t.message}`);throw t}}async function Ta(e){if(!e.length)return 0;try{let t=await Fa.deleteFrom("print_devices").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print devices: ${t.message}`);throw t}}import{createSpreadsheet as om}from"ts-spreadsheets";import{db as S}from"@stacksjs/database";async function Y(e){return await S.selectFrom("print_devices").where("id","=",e).selectAll().executeTakeFirst()}async function Dt(){return await S.selectFrom("print_devices").selectAll().execute()}async function Ea(){let e=await S.selectFrom("print_devices").select(S.fn.count("id").as("count")).executeTakeFirst();return Number(e?.count||0)}async function Sa(){let e=await S.selectFrom("print_devices").select(S.fn.sum("print_count").as("total")).executeTakeFirst();return Number(e?.total||0)}async function Ca(e){let t=await S.selectFrom("print_devices").select("print_count").where("id","=",e).executeTakeFirst();return Number(t?.print_count??0)}async function Aa(){let e=await S.selectFrom("receipts").select([S.fn.count("id").as("total"),S.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 Ia(e){return await S.selectFrom("receipts").where("print_device_id","=",e).where("status","=","failed").selectAll().execute()}async function Ma(){let e=await S.selectFrom("print_devices").select([S.fn.count("id").as("total"),S.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 Na(){return(await S.selectFrom("print_devices").select(["status",S.fn.count("id").as("count")]).groupBy("status").execute()).reduce((t,r)=>(t[r.status]=Number(r.count||0),t),{})}function fn(e,t,r=t){let n=e;return n[String(t)]??n[r]}function am(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 Ja(e,t,r=t){let n=fn(e,t,r);if(typeof n==="number")return n;let o=Number(n);return Number.isFinite(o)?o:0}function ze(e,t,r=t){let n=fn(e,t,r);return n==null?"":String(n)}async function vt(e="csv"){let t=await Dt(),r=sm(t);return om(r,{type:e})}function sm(e){let t=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],r=e.map((n)=>[Ja(n,"id"),ze(n,"name"),ze(n,"macAddress","mac_address"),ze(n,"location"),ze(n,"terminal"),ze(n,"status"),am(fn(n,"lastPing","last_ping")).toLocaleString(),Ja(n,"printCount","print_count")]);return{headings:t,data:r}}async function Ba(e="csv",t){let r=await vt(e),n=`print_devices_export_${new Date().toISOString().split("T")[0]}.${e}`;return r.download(t||n)}async function Oa(e="csv",t){let r=await vt(e),n=`print_devices_export_${new Date().toISOString().split("T")[0]}.${e}`;r.store(t||n)}var{randomUUIDv7:Ua}=globalThis.Bun;import{db as wn}from"@stacksjs/database";async function $a(e){try{let t=Ua(),r={last_ping:0,print_count:0,...e,uuid:t};return await wn.insertInto("print_devices").values(r).executeTakeFirst(),await wn.selectFrom("print_devices").where("uuid","=",t).selectAll().executeTakeFirst()}catch(t){if(t instanceof Error)throw TypeError(`Failed to create print device: ${t.message}`);throw t}}async function Wa(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:Ua()};await wn.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 yn}from"@stacksjs/database";import{formatDate as hn}from"@stacksjs/orm";async function La(e,t){if(!await Y(e))return;try{return await yn.updateTable("print_devices").set({...t,updated_at:hn(new Date)}).where("id","=",e).execute(),await Y(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print device: ${n.message}`);throw n}}async function ja(e,t){if(!await Y(e))throw Error(`Print device with ID ${e} not found`);try{return await yn.updateTable("print_devices").set({status:t,updated_at:hn(new Date)}).where("id","=",e).execute(),await Y(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print device status: ${n.message}`);throw n}}async function za(e,t){if(!await Y(e))throw Error(`Print device with ID ${e} not found`);try{return await yn.updateTable("print_devices").set({print_count:t,updated_at:hn(new Date)}).where("id","=",e).execute(),await Y(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print count: ${n.message}`);throw n}}var xn={};y(xn,{bulkDestroy:()=>Va,bulkUpdateStatus:()=>es,destroy:()=>Ga,destroyGroup:()=>qa,fetchAll:()=>Ft,fetchByGroup:()=>Ha,fetchById:()=>Za,fetchGrouped:()=>Ka,fetchStats:()=>Qa,fetchTimeline:()=>Ya,ignoreGroup:()=>rs,resolveGroup:()=>ts,unresolveGroup:()=>ns,update:()=>Xa});import{db as bn}from"@stacksjs/database";import{log as _n}from"@stacksjs/logging";async function Ga(e){try{return await bn.deleteFrom("errors").where("id","=",e).execute(),!0}catch(t){return _n.error("[commerce/errors] destroy failed",{id:e,error:t}),!1}}async function Va(e){try{return await bn.deleteFrom("errors").where("id","in",e).execute(),!0}catch(t){return _n.error("[commerce/errors] bulkDestroy failed",{count:e.length,error:t}),!1}}async function qa(e,t){try{return await bn.deleteFrom("errors").where("type","=",e).where("message","=",t).execute(),!0}catch(r){return _n.error("[commerce/errors] destroyGroup failed",{type:e,message:t,error:r}),!1}}import{db as Pt}from"@stacksjs/database";async function Za(e){return await Pt.selectFrom("errors").where("id","=",e).selectAll().executeTakeFirst()}async function Ft(){return await Pt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function Ka(){let e=await Pt.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 Ha(e,t){return await Pt.selectFrom("errors").where("type","=",e).where("message","=",t).selectAll().orderBy("created_at","desc").execute()}async function Qa(){let e=await Ft(),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 Ya(){let e=await Ft(),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 Ge}from"@stacksjs/database";import{sql as Ve}from"@stacksjs/database";import{log as qe}from"@stacksjs/logging";async function Xa(e,t){try{return await Ge.updateTable("errors").set({...t,updated_at:Ve.raw("CURRENT_TIMESTAMP")}).where("id","=",e).execute(),!0}catch(r){return qe.error("[commerce/errors] update failed",{id:e,error:r}),!1}}async function es(e,t){try{return await Ge.updateTable("errors").set({status:t,updated_at:Ve.raw("CURRENT_TIMESTAMP")}).where("id","in",e).execute(),!0}catch(r){return qe.error("[commerce/errors] bulkUpdateStatus failed",{count:e.length,status:t,error:r}),!1}}async function ts(e,t){try{return await Ge.updateTable("errors").set({status:1,updated_at:Ve.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return qe.error("[commerce/errors] resolveGroup failed",{type:e,message:t,error:r}),!1}}async function rs(e,t){try{return await Ge.updateTable("errors").set({status:2,updated_at:Ve.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return qe.error("[commerce/errors] ignoreGroup failed",{type:e,message:t,error:r}),!1}}async function ns(e,t){try{return await Ge.updateTable("errors").set({status:0,updated_at:Ve.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return qe.error("[commerce/errors] unresolveGroup failed",{type:e,message:t,error:r}),!1}}var vn={};y(vn,{bulkDestroy:()=>fs,calculateGiftCardValues:()=>cs,checkBalance:()=>is,compareActiveGiftCards:()=>us,deactivate:()=>ys,destroy:()=>ms,destroyExpired:()=>ws,fetchActive:()=>as,fetchAll:()=>os,fetchByCode:()=>Rn,fetchById:()=>X,fetchStats:()=>ss,fetchTotalCurrentBalance:()=>ls,fetchTotalValue:()=>ds,store:()=>gs,update:()=>Rs,updateBalance:()=>Ds});import{db as kt}from"@stacksjs/database";import{formatDate as ps}from"@stacksjs/orm";import{db as D,sql as A}from"@stacksjs/database";import{formatDate as ue,toTimestamp as De}from"@stacksjs/orm";import{aggregateFunctions as im,db as um}from"@stacksjs/database";async function M(e,t,r){let n=um.selectFrom(e);if(r)n=r(n);n=n.select(Object.entries(t).map(([s,i])=>{let u=i.column??"id",c=im[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 os(){return await D.selectFrom("gift_cards").selectAll().execute()}async function X(e){return await D.selectFrom("gift_cards").where("id","=",e).selectAll().executeTakeFirst()}async function Rn(e){return await D.selectFrom("gift_cards").where("code","=",e).selectAll().executeTakeFirst()}async function as(){return await D.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function ss(){let{count:e}=await M("gift_cards",{count:{kind:"count"}}),t=De(new Date),r=await D.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(A`(expiry_date >= ${A.literal(t)} OR expiry_date IS NULL)`).select(D.fn.count("id").as("count")).executeTakeFirst(),n=await D.selectFrom("gift_cards").select(["status",D.fn.count("id").as("count")]).groupBy("status").execute(),{count:o}=await M("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(A`current_balance / initial_balance < 0.25`)),{count:a}=await M("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(A`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:s}=await M("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(A`current_balance / initial_balance > 0.75`)),i=new Date;i.setDate(i.getDate()+30);let u=await D.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",De(i)).where("expiry_date",">=",t).selectAll().limit(5).execute(),c=await D.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:e,active:Number(r?.count||0),by_status:n.map((l)=>({status:l.status,count:Number(l.count)})),by_balance:{low:o,medium:a,high:s},expiring_soon:u,recently_used:c}}async function is(e){let t=await Rn(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 us(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 D.selectFrom("gift_cards").select(D.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(A`(expiry_date >= ${A.literal(De(t))} OR expiry_date IS NULL)`).where("created_at",">=",ue(r)).where("created_at","<=",ue(t)).executeTakeFirst(),s=await D.selectFrom("gift_cards").select(D.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(A`(expiry_date >= ${A.literal(De(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,l=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:l,days_range:e}}async function cs(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 D.selectFrom("gift_cards").select([D.fn.sum("initial_balance").as("total_initial"),D.fn.sum("current_balance").as("total_balance"),D.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(A`(expiry_date >= ${A.literal(De(t))} OR expiry_date IS NULL)`).where("created_at",">=",ue(r)).where("created_at","<=",ue(t)).executeTakeFirst(),s=await D.selectFrom("gift_cards").select([D.fn.sum("initial_balance").as("total_initial"),D.fn.sum("current_balance").as("total_balance"),D.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(A`(expiry_date >= ${A.literal(De(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),l=Number(s?.total_initial||0),p=Number(s?.total_balance||0),m=Number(s?.card_count||0),f=i>0?(i-u)/i*100:0,h=l>0?(l-p)/l*100:0,b=c>0?i/c:0,R=c>0?u/c:0,z=i-l,pe=u-p,me=c-m,xe=l!==0?z/l*100:i>0?100:0,G=p!==0?pe/p*100:u>0?100:0,Np=m!==0?me/m*100:c>0?100:0;return{current_period:{total_initial_value:i,total_remaining_balance:u,utilization_rate:f,card_count:c,average_initial_value:b,average_remaining_balance:R},previous_period:{total_initial_value:l,total_remaining_balance:p,utilization_rate:h,card_count:m},comparison:{initial_value:{difference:z,percentage:Math.abs(xe),is_increase:z>=0},balance:{difference:pe,percentage:Math.abs(G),is_increase:pe>=0},card_count:{difference:me,percentage:Math.abs(Np),is_increase:me>=0}},days_range:e}}async function ds(){let{total_value:e}=await M("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:e}}async function ls(){let{total_balance:e}=await M("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:e}}async function ms(e){let t=await kt.deleteFrom("gift_cards").where("id","=",e).executeTakeFirst();return d(t)>0}async function fs(e){if(!e.length)return 0;let t=await kt.deleteFrom("gift_cards").where("id","in",e).executeTakeFirst();return d(t)}async function ws(){let e=ps(new Date),t=await kt.deleteFrom("gift_cards").where("expiry_date","<",e).executeTakeFirst();return d(t)}async function ys(e){if(!await X(e))throw Error(`Gift card with ID ${e} not found`);let r=await kt.updateTable("gift_cards").set({is_active:!1,status:"DEACTIVATED",updated_at:ps(new Date)}).where("id","=",e).executeTakeFirst();return d(r)>0}var{randomUUIDv7:cm}=globalThis.Bun;import{db as Dn}from"@stacksjs/database";import{HttpError as hs}from"@stacksjs/error-handling";import{isUniqueViolation as dm}from"@stacksjs/orm";async function gs(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:cm()};try{let n=await Dn.insertInto("gift_cards").values(r).executeTakeFirst(),o=Q(n);if(o!==void 0)return await Dn.selectFrom("gift_cards").where("id","=",o).selectAll().executeTakeFirst();return await Dn.selectFrom("gift_cards").where("uuid","=",r.uuid).selectAll().executeTakeFirst()}catch(n){if(n instanceof hs)throw n;if(dm(n))throw new hs(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 _s,sqlHelpers as lm}from"@stacksjs/database";import{env as pm}from"@stacksjs/env";import{HttpError as bs}from"@stacksjs/error-handling";import{formatDate as xs,isUniqueViolation as mm}from"@stacksjs/orm";async function Rs(e,t){if(!await X(e))return;try{return await _s.updateTable("gift_cards").set({...t,updated_at:xs(new Date)}).where("id","=",e).execute(),await X(e)}catch(n){if(n instanceof bs)throw n;if(mm(n))throw new bs(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 Ds(e,t){if(!Number.isFinite(t))throw Error(`Gift card balance adjustment must be a finite number, got ${t}`);let r=lm(pm.DB_CONNECTION||"sqlite"),n=r.param,o=xs(new Date),a=t<0,s=t>0,i=s?`(status = 'ACTIVE' OR (status = 'USED' AND is_reloadable = ${r.boolTrue}))`:"status = 'ACTIVE'",u=[],c=(R)=>(u.push(R),n(u.length)),p=await _s.unsafe(`UPDATE gift_cards
9
+ SET current_balance = current_balance + ${c(t)},
10
+ ${a?`last_used_date = ${c(o)},
11
+ `:""}status = CASE WHEN current_balance + ${c(t)} = 0 THEN 'USED' ELSE 'ACTIVE' END,
12
+ updated_at = ${c(o)}
13
+ WHERE id = ${c(e)}
14
+ AND is_active = ${r.boolTrue}
15
+ AND ${i}
16
+ AND (expiry_date IS NULL OR expiry_date >= ${c(o)})
17
+ AND current_balance + ${c(t)} >= 0`,u);if(Number(p?.changes??p?.numUpdatedRows??p?.affectedRows??0)>0)return await X(e);let f=await X(e);if(!f)throw Error(`Gift card with ID ${e} not found`);let h=f;if(!h.is_active&&!h.isActive)throw Error("Gift card is not active");if(f.status==="USED"&&s&&!(h.is_reloadable??h.isReloadable))throw Error("Gift card is not reloadable");if(f.status!=="ACTIVE")throw Error("Gift card is not active");let b=h.expiry_date??h.expiryDate;if(b&&String(b)<o)throw Error("Gift card has expired");throw Error("Insufficient gift card balance")}var Nn={};y(Nn,{bulkDestroy:()=>Fs,bulkSoftDelete:()=>ks,calculateOrderMetrics:()=>Ns,canTransition:()=>Ze,cleanupAbandonedCarts:()=>ri,compareOrdersByPeriod:()=>Ms,destroy:()=>vs,downloadOrders:()=>Es,emitForStatus:()=>He,emitOrderCancelled:()=>ve,emitOrderCreated:()=>Ke,emitOrderDelivered:()=>Ct,emitOrderPaid:()=>ce,emitOrderRefunded:()=>Pe,emitOrderShipped:()=>St,exportOrders:()=>Et,fetchAll:()=>Pn,fetchById:()=>ee,fetchDailyOrderTrends:()=>Js,fetchRecent:()=>As,fetchStats:()=>Is,findOrderByIdempotencyKey:()=>It,handleChargeRefunded:()=>In,handlePaymentIntentFailed:()=>An,handlePaymentIntentSucceeded:()=>Cn,placeOrder:()=>Vs,recomputeOrderTotals:()=>Xs,registerCommerceWebhookHandlers:()=>Qs,softDelete:()=>Ps,store:()=>Os,storeOrdersExport:()=>Ss,update:()=>qs,updateDeliveryInfo:()=>Ks,updateStatus:()=>Zs,validateCartQuantities:()=>ti,validateCouponStacking:()=>ei,validateQuantityBounds:()=>Mn});import{db as Tt}from"@stacksjs/database";async function vs(e){try{let t=await Tt.deleteFrom("orders").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete order: ${t.message}`);throw t}}async function Ps(e){try{let t=await Tt.updateTable("orders").set({status:"CANCELED"}).where("id","=",e).executeTakeFirst();return Number(t.numUpdatedRows)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete order: ${t.message}`);throw t}}async function Fs(e){if(!e.length)return 0;try{let t=await Tt.deleteFrom("orders").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete orders: ${t.message}`);throw t}}async function ks(e){if(!e.length)return 0;try{let t=await Tt.updateTable("orders").set({status:"CANCELED"}).where("id","in",e).executeTakeFirst();return Number(t.numUpdatedRows)}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete orders: ${t.message}`);throw t}}import{db as Ts}from"@stacksjs/database";import{createSpreadsheet as fm}from"ts-spreadsheets";async function Et(e="csv"){let t=await wm(),r=ym(t);return fm(r,{type:e})}async function wm(){let e=await Ts.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),t=e.map((a)=>a.id);if(t.length===0)return[];let n=(await Ts.selectFrom("order_items").where("order_items.order_id","in",t).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((a,s)=>{if(!s.order_id)return a;if(!a[s.order_id])a[s.order_id]={totalItems:0,totalPrice:0};return a[s.order_id].totalItems+=s.quantity,a[s.order_id].totalPrice+=s.price*s.quantity,a},{});return e.map((a)=>{let s=n[a.id]||{totalItems:0,totalPrice:0};return{...a,totalItems:s.totalItems,totalPrice:s.totalPrice}})}function ym(e){let t=["Order ID","Customer","Date","Total","Status","Items"],r=e.map((n)=>{let o=n.order_items?.map((a)=>`${a.product?.name} (Qty: ${a.quantity}, Price: $${a.price})`).join(" | ")||"No Items";return[n.id,n.customer?.name||"N/A",n.created_at,n.total_amount,n.status,o]});return{headings:t,data:r}}async function Es(e="csv",t){let r=await Et(e),n=`orders_export_${new Date().toISOString().split("T")[0]}.${e}`;return r.download(t||n)}async function Ss(e="csv",t){let r=await Et(e),n=`orders_export_${new Date().toISOString().split("T")[0]}.${e}`;r.store(t||n)}import{asRows as Cs,db as _}from"@stacksjs/database";async function Pn(e){let t=_.selectFrom("orders").selectAll().orderBy("created_at","desc");if(e)t=t.limit(e);let r=Cs(await t.execute());return await Promise.all(r.map(async(n)=>{let o=await _.selectFrom("order_items").where("order_id","=",n.id).selectAll().execute();return{...n,items:o}}))}async function As(e=10){return Pn(e)}async function ee(e){return await _.selectFrom("orders").where("id","=",e).selectAll().executeTakeFirst()}async function Is(){let e=await _.selectFrom("orders").select(_.fn.count("id").as("count")).executeTakeFirst(),t=await _.selectFrom("orders").select(["status",_.fn.count("id").as("count")]).groupBy("status").execute(),r=await _.selectFrom("orders").select(["order_type",_.fn.count("id").as("count")]).groupBy("order_type").execute(),n=Cs(await _.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute()),o=await Promise.all(n.map(async(s)=>{let i=await _.selectFrom("order_items").where("order_id","=",s.id).selectAll().execute();return{...s,items:i}})),a=await _.selectFrom("orders").select(_.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 Ms(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 _.selectFrom("orders").select(_.fn.count("id").as("count")).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).executeTakeFirst(),s=await _.selectFrom("orders").select(_.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,l=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:l,days_range:e}}async function Ns(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 _.selectFrom("orders").select([_.fn.count("id").as("total_orders"),_.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).executeTakeFirst(),s=await _.selectFrom("orders").select([_.fn.count("id").as("total_orders"),_.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",o.toISOString()).where("created_at","<=",n.toISOString()).executeTakeFirst(),i=await _.selectFrom("orders").select(["status",_.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).groupBy("status").execute(),u=await _.selectFrom("orders").select(["order_type",_.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),l=Number(a?.total_revenue||0),p=c>0?l/c:0,m=Number(s?.total_orders||0),f=Number(s?.total_revenue||0),h=m>0?f/m:0,b=c-m,R=l-f,z=p-h,pe=m!==0?b/m*100:c>0?100:0,me=f!==0?R/f*100:l>0?100:0,xe=h!==0?z/h*100:p>0?100:0;return{current_period:{total_orders:c,total_revenue:l,average_order_value:p,orders_by_status:i.map((G)=>({status:G.status,count:Number(G.count)})),orders_by_type:u.map((G)=>({order_type:G.order_type,count:Number(G.count)}))},previous_period:{total_orders:m,total_revenue:f,average_order_value:h},comparison:{orders:{difference:b,percentage:Math.abs(pe),is_increase:b>=0},revenue:{difference:R,percentage:Math.abs(me),is_increase:R>=0},average_order_value:{difference:z,percentage:Math.abs(xe),is_increase:z>=0}},days_range:e}}async function Js(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=await _.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:hm}=globalThis.Bun;import{db as Fn}from"@stacksjs/database";import{formatDate as Bs}from"@stacksjs/orm";async function Os(e){let t={...e,status:e.status||"PENDING",uuid:hm(),created_at:Bs(new Date),updated_at:Bs(new Date)};try{let r=await Fn.insertInto("orders").values(t).executeTakeFirst(),n=Q(r);if(n!==void 0)return await Fn.selectFrom("orders").where("id","=",n).selectAll().executeTakeFirst();return await Fn.selectFrom("orders").where("uuid","=",t.uuid).selectAll().executeTakeFirst()}catch(r){if(r instanceof Error)throw Error(`Failed to create order: ${r.message}`);throw r}}Fe();var{randomUUIDv7:Ls}=globalThis.Bun;import{db as At}from"@stacksjs/database";import{formatDate as Rm,isUniqueViolation as js}from"@stacksjs/orm";import{sqlHelpers as bm}from"@stacksjs/database";import{env as _m}from"@stacksjs/env";function xm(e,t,r,n){let o=bm(e).param;return{query:`UPDATE products
17
18
  SET inventory_count = inventory_count + ${o(1)},
18
19
  updated_at = ${o(2)}
19
20
  WHERE id = ${o(3)}
20
- AND inventory_count + ${o(4)} >= 0`,parameters:[r,n,t,r]}}async function bs(e,t,r,n){let o=Zm(qm.DB_CONNECTION||"sqlite",t,r,n),a=await e.unsafe(o.query,o.parameters),s=typeof a?.execute==="function"?await a.execute():a;return d(s)}var Rs=!1;function vs(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 Ct(e){try{let t=await St.selectFrom("order_idempotency").where("idempotency_key","=",e).selectAll().executeTakeFirst();if(!t)return null;return await St.selectFrom("orders").where("id","=",t.order_id).selectAll().executeTakeFirst()??null}catch(t){if(vs(t)){if(!Rs)Rs=!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 Ds(e){if(e.idempotencyKey){let t=await Ct(e.idempotencyKey);if(t)return{ok:!0,order:t}}try{let t=await St.transaction(async(r)=>{let n=Km(new Date),o=_s(),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=await r.selectFrom("orders").where("uuid","=",o).selectAll().executeTakeFirst(),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((p)=>{if(!Number.isInteger(p.productId)||p.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(p.quantity)||p.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(p.price)||p.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:p.productId,quantity:p.quantity,price:p.price,special_instructions:p.specialInstructions||null,created_at:n,updated_at:n}});await r.insertInto("order_items").values(m).execute(),u=await r.selectFrom("order_items").where("order_id","=",i).selectAll().execute()}let c;if(e.payment)try{let m=_s();if(await r.insertInto("payments").values({...e.payment,order_id:i,uuid:m,created_at:n,updated_at:n}).executeTakeFirst(),c=await r.selectFrom("payments").where("uuid","=",m).selectAll().executeTakeFirst(),!c)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(m){if(xs(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:p,delta:w}=e.inventory[m];if(!Number.isFinite(w)||w===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await bs(r,p,w,n))throw Object.assign(Error(`inventory adjust failed for product ${p}`),{__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(xs(m))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!vs(m))throw m}let l=await r.selectFrom("orders").where("id","=",i).selectAll().executeTakeFirst();if(!l)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:l,items:u,payment:c}});if(Ze(t.order),t.payment)se(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 Ct(e.idempotencyKey);if(r)return{ok:!0,order:r}}return{ok:!1,reason:t.reason,failedAt:t.failedAt,error:t}}throw t}}Pe();import{db as xn}from"@stacksjs/database";import{formatDate as Rn}from"@stacksjs/orm";Pe();async function Ps(e,t){if(!await Y(e))return;try{return await xn.updateTable("orders").set({...t,updated_at:Rn(new Date)}).where("id","=",e).execute(),await Y(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update order: ${n.message}`);throw n}}async function Fs(e,t){let r=await Y(e);if(!r)throw Error(`Order with ID ${e} not found`);let n=r.status??"PENDING";if(!qe(n,t))throw Error(`[commerce/orders] illegal status transition ${n} \u2192 ${t}`);try{await xn.updateTable("orders").set({status:t,updated_at:Rn(new Date)}).where("id","=",e).execute();let o=await Y(e);if(o)Ke(t,o);return o}catch(o){if(o instanceof Error)throw TypeError(`Failed to update order status: ${o.message}`);throw o}}async function ks(e,t,r){let n=await Y(e);if(!n)throw Error(`Order with ID ${e} not found`);let o={updated_at:Rn(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 xn.updateTable("orders").set(o).where("id","=",e).execute(),await Y(e)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery information: ${a.message}`);throw a}}Pe();import{db as Fe}from"@stacksjs/database";import{formatDate as At}from"@stacksjs/orm";async function vn(e){let t=await Fe.selectFrom("payments").where("transaction_id","=",e).selectAll().executeTakeFirst();if(!t)return null;return await Fe.selectFrom("orders").where("id","=",t.order_id).selectAll().executeTakeFirst()??null}var Ts=!1;function Hm(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 Dn(e,t){try{return await t.insertInto("stripe_webhook_events").values({event_id:e,processed_at:At(new Date)}).execute(),!0}catch(r){if(r?.message?.includes("UNIQUE constraint")||r?.message?.includes("Duplicate entry"))return!1;if(Hm(r)){if(!Ts)Ts=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing - Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw r}}async function Pn(e){let r=e.data.object?.id;if(!r)return;await Fe.transaction(async(o)=>{if(!await Dn(e.id,o))return;let s=await o.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!s)return;let i=At(new Date);await o.updateTable("payments").set({status:"succeeded",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:"PROCESSING",updated_at:i}).where("id","=",u.id).execute()});let n=await vn(r);if(n)await se(n)}async function Fn(e){let t=e.data.object,r=t?.id;if(!r)return;let o=t?.last_payment_error?.message??"payment failed";await Fe.transaction(async(s)=>{if(!await Dn(e.id,s))return;let u=await s.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!u)return;let c=At(new Date);await s.updateTable("payments").set({status:"failed",failure_reason:o,updated_at:c}).where("id","=",u.id).execute();let l=await s.selectFrom("orders").where("id","=",u.order_id).selectAll().executeTakeFirst();if(l&&l.status==="PENDING")await s.updateTable("orders").set({status:"CANCELLED",updated_at:c}).where("id","=",l.id).execute()});let a=await vn(r);if(a)await ve(a,o)}async function kn(e){let t=e.data.object,r=t?.payment_intent;if(!r)return;let n=t?.amount_refunded??0;await Fe.transaction(async(a)=>{if(!await Dn(e.id,a))return;let i=await a.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!i)return;let u=At(new Date);await a.updateTable("payments").set({status:"refunded",refund_amount:n,updated_at:u}).where("id","=",i.id).execute();let c=await a.selectFrom("orders").where("id","=",i.order_id).selectAll().executeTakeFirst();if(c&&c.status!=="REFUNDED")await a.updateTable("orders").set({status:"REFUNDED",updated_at:u}).where("id","=",c.id).execute()});let o=await vn(r);if(o)await De(o,n)}async function Es(){let e=await import("@stacksjs/payments").catch(()=>null);if(!e)return console.warn("[commerce/webhook] @stacksjs/payments not installed - Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:t,onCharge:r}=e;if(typeof t!=="function"||typeof r!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed - handlers NOT registered"),()=>{};return t({succeeded:Pn,failed:Fn}),r({refunded:kn}),()=>{}}import{db as Ss}from"@stacksjs/database";async function Qm(e){if(e.length===0)return new Map;let t=await Ss.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 Ym(e){try{let t=await Ss.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 Cs(e){let t=e.items.map((x)=>x.productId),r=await Qm(t),n=e.taxRateId!=null?await Ym(e.taxRateId):0,o=0,a=[];for(let x of e.items){let b=x.unitPriceCents??r.get(x.productId)??0,R=Math.round(b*x.quantity);o+=R,a.push({productId:x.productId,quantity:x.quantity,unitPriceCents:b,lineCents:R})}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),l=o-s+u+c,m=e.maxDriftCents??5,p=!1,w=0;if(e.clientTotalCents!=null)w=Math.abs(l-e.clientTotalCents),p=w>m;return{subtotalCents:o,discountCents:s,taxCents:u,shippingCents:c,totalCents:l,resolvedItems:a,priceChanged:p,diffCents:w}}import{db as It}from"@stacksjs/database";function As(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 Tn(e,t){if(!Number.isFinite(t)||t<=0)return{ok:!1,productId:e,quantity:t,reason:"non-positive"};let r;try{r=await It.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 Is(e){for(let r of e){let n=await Tn(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 Ms(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"," ");try{let a=await It.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[o,o,r]),s=typeof a?.execute==="function"?await a.execute():a;return{deleted:Number(s?.changes??s?.numDeletedRows??s?.[0]?.numDeletedRows??s?.affectedRows??0),cutoffAt:o}}catch{try{let a=await It.selectFrom("carts").where("updated_at","<",o).select(["id"]).limit(r).execute();if(a.length===0)return{deleted:0,cutoffAt:o};let s=a.map((c)=>c.id),i=await It.deleteFrom("carts").where("id","in",s).execute();return{deleted:Number(i?.numDeletedRows??i?.[0]?.numDeletedRows??i?.affectedRows??a.length),cutoffAt:o}}catch{return{deleted:0,cutoffAt:o}}}}var Sn={};y(Sn,{bulkDestroy:()=>Bs,destroy:()=>Js,fetchAll:()=>Os,fetchById:()=>we,fetchMonthlyPaymentTrends:()=>Ws,fetchPaymentStats:()=>Us,fetchPaymentStatsByMethod:()=>$s,recordRefund:()=>Zs,store:()=>js,update:()=>qs});import{db as Ns}from"@stacksjs/database";async function Js(e){try{let t=await Ns.deleteFrom("payments").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete payment: ${t.message}`);throw t}}async function Bs(e){if(!e.length)return 0;try{let t=await Ns.deleteFrom("payments").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete payments: ${t.message}`);throw t}}import{db as E}from"@stacksjs/database";import{formatDate as O}from"@stacksjs/orm";async function Os(){return await E.selectFrom("payments").selectAll().execute()}async function we(e){return await E.selectFrom("payments").selectAll().where("id","=",e).executeTakeFirst()}async function Us(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 E.selectFrom("payments").select([E.fn.count("id").as("transaction_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",O(r)).where("created_at","<=",O(t)).where("status","=","completed").executeTakeFirst(),s=await E.selectFrom("payments").select([E.fn.count("id").as("transaction_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",O(o)).where("created_at","<=",O(n)).where("status","=","completed").executeTakeFirst(),i=await E.selectFrom("payments").select(E.fn.count("id").as("count")).where("created_at",">=",O(r)).where("created_at","<=",O(t)).executeTakeFirst(),u=Number(a?.transaction_count||0),c=Number(a?.total_revenue||0),l=u>0?c/u:0,m=Number(s?.transaction_count||0),p=Number(s?.total_revenue||0),w=m>0?p/m:0,x=u-m,b=c-p,R=l-w,j=m>0?x/m*100:u>0?100:0,de=p>0?b/p*100:c>0?100:0,le=w>0?R/w*100:l>0?100:0,_e=Number(i?.count||0),G=_e>0?u/_e*100:0;return{total_transactions:u,total_revenue:c,average_transaction:l,successful_rate:G,comparison:{transactions:{difference:x,percentage:Math.abs(j),is_increase:x>=0},revenue:{difference:b,percentage:Math.abs(de),is_increase:b>=0},average:{difference:R,percentage:Math.abs(le),is_increase:R>=0}}}}async function $s(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=await E.selectFrom("payments").select([E.fn.count("id").as("total_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",O(r)).where("created_at","<=",O(t)).where("status","=","completed").executeTakeFirst(),o=Number(n?.total_count||0),a=await E.selectFrom("payments").select(["method",E.fn.count("id").as("count"),E.fn.sum("amount").as("revenue")]).where("created_at",">=",O(r)).where("created_at","<=",O(t)).where("status","=","completed").groupBy("method").execute(),s={};return a.forEach((i)=>{let u=Number(i.count||0),c=Number(i.revenue||0),l=o>0?u/o*100:0;s[i.method]={count:u,revenue:c,percentage_of_total:l}}),s}async function Ws(){let e=new Date,t=new Date(e);t.setMonth(e.getMonth()-11),t.setDate(1);let r=await E.selectFrom("payments").selectAll().where("created_at",">=",O(t)).where("status","=","completed").execute(),n={};for(let a of r){let s=a.created_at?new Date(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],i=s.transactions,u=s.revenue,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:Xm}=globalThis.Bun;import{db as Ls}from"@stacksjs/database";import{HttpError as zs}from"@stacksjs/error-handling";import{isUniqueViolation as ep}from"@stacksjs/orm";async function js(e){let t=Xm(),r={...e,status:e.status||"pending",currency:e.currency||"USD",uuid:t};try{return await Ls.insertInto("payments").values(r).executeTakeFirst(),await Ls.selectFrom("payments").where("uuid","=",t).selectAll().executeTakeFirst()}catch(n){if(n instanceof zs)throw n;if(ep(n))throw new zs(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 Gs,sqlHelpers as tp}from"@stacksjs/database";import{env as rp}from"@stacksjs/env";import{formatDate as Vs}from"@stacksjs/orm";async function qs(e,t){if(!await we(e))return;try{return await Gs.updateTable("payments").set({...t,updated_at:Vs(new Date)}).where("id","=",e).execute(),await we(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 np=new Set(["completed","succeeded","partiallyRefunded"]);async function Zs(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=tp(rp.DB_CONNECTION||"sqlite").param,o=Vs(new Date),a=await Gs.unsafe(`UPDATE payments
21
+ AND inventory_count + ${o(4)} >= 0`,parameters:[r,n,t,r]}}async function Ws(e,t,r,n){let o=xm(_m.DB_CONNECTION||"sqlite",t,r,n),a=await e.unsafe(o.query,o.parameters);return d(a)}var zs=!1;function Gs(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 It(e){try{let t=await At.selectFrom("order_idempotency").where("idempotency_key","=",e).selectAll().executeTakeFirst();if(!t)return null;return await At.selectFrom("orders").where("id","=",t.order_id).selectAll().executeTakeFirst()??null}catch(t){if(Gs(t)){if(!zs)zs=!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 Vs(e){if(e.idempotencyKey){let t=await It(e.idempotencyKey);if(t)return{ok:!0,order:t}}try{let t=await At.transaction(async(r)=>{let n=Rm(new Date),o=Ls(),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=await r.selectFrom("orders").where("uuid","=",o).selectAll().executeTakeFirst(),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 p=e.items.map((m)=>{if(!Number.isInteger(m.productId)||m.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(m.quantity)||m.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(m.price)||m.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:m.productId,quantity:m.quantity,price:m.price,special_instructions:m.specialInstructions||null,created_at:n,updated_at:n}});await r.insertInto("order_items").values(p).execute(),u=await r.selectFrom("order_items").where("order_id","=",i).selectAll().execute()}let c;if(e.payment)try{let p=Ls();if(await r.insertInto("payments").values({...e.payment,order_id:i,uuid:p,created_at:n,updated_at:n}).executeTakeFirst(),c=await r.selectFrom("payments").where("uuid","=",p).selectAll().executeTakeFirst(),!c)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(p){if(js(p))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(p,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(e.inventory&&e.inventory.length>0)for(let p=0;p<e.inventory.length;p++){let{id:m,delta:f}=e.inventory[p];if(!Number.isFinite(f)||f===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await Ws(r,m,f,n))throw Object.assign(Error(`inventory adjust failed for product ${m}`),{__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(p){if(js(p))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!Gs(p))throw p}let l=await r.selectFrom("orders").where("id","=",i).selectAll().executeTakeFirst();if(!l)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:l,items:u,payment:c}});if(Ke(t.order),t.payment)ce(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 It(e.idempotencyKey);if(r)return{ok:!0,order:r}}return{ok:!1,reason:t.reason,failedAt:t.failedAt,error:t}}throw t}}Fe();import{db as kn}from"@stacksjs/database";import{formatDate as Tn}from"@stacksjs/orm";Fe();async function qs(e,t){if(!await ee(e))return;try{return await kn.updateTable("orders").set({...t,updated_at:Tn(new Date)}).where("id","=",e).execute(),await ee(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update order: ${n.message}`);throw n}}async function Zs(e,t){let r=await ee(e);if(!r)throw Error(`Order with ID ${e} not found`);let n=r.status??"PENDING";if(!Ze(n,t))throw Error(`[commerce/orders] illegal status transition ${n} \u2192 ${t}`);try{await kn.updateTable("orders").set({status:t,updated_at:Tn(new Date)}).where("id","=",e).execute();let o=await ee(e);if(o)He(t,o);return o}catch(o){if(o instanceof Error)throw TypeError(`Failed to update order status: ${o.message}`);throw o}}async function Ks(e,t,r){let n=await ee(e);if(!n)throw Error(`Order with ID ${e} not found`);let o={updated_at:Tn(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 kn.updateTable("orders").set(o).where("id","=",e).execute(),await ee(e)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery information: ${a.message}`);throw a}}Fe();import{db as ke}from"@stacksjs/database";import{formatDate as Mt}from"@stacksjs/orm";async function En(e){let t=await ke.selectFrom("payments").where("transaction_id","=",e).selectAll().executeTakeFirst();if(!t)return null;return await ke.selectFrom("orders").where("id","=",t.order_id).selectAll().executeTakeFirst()??null}var Hs=!1;function Dm(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 Sn(e,t){try{return await t.insertInto("stripe_webhook_events").values({event_id:e,processed_at:Mt(new Date)}).execute(),!0}catch(r){if(r?.message?.includes("UNIQUE constraint")||r?.message?.includes("Duplicate entry"))return!1;if(Dm(r)){if(!Hs)Hs=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing - Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw r}}async function Cn(e){let r=e.data.object?.id;if(!r)return;await ke.transaction(async(o)=>{if(!await Sn(e.id,o))return;let s=await o.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!s)return;let i=Mt(new Date);await o.updateTable("payments").set({status:"succeeded",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:"PROCESSING",updated_at:i}).where("id","=",u.id).execute()});let n=await En(r);if(n)await ce(n)}async function An(e){let t=e.data.object,r=t?.id;if(!r)return;let o=t?.last_payment_error?.message??"payment failed";await ke.transaction(async(s)=>{if(!await Sn(e.id,s))return;let u=await s.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!u)return;let c=Mt(new Date);await s.updateTable("payments").set({status:"failed",failure_reason:o,updated_at:c}).where("id","=",u.id).execute();let l=await s.selectFrom("orders").where("id","=",u.order_id).selectAll().executeTakeFirst();if(l&&l.status==="PENDING")await s.updateTable("orders").set({status:"CANCELLED",updated_at:c}).where("id","=",l.id).execute()});let a=await En(r);if(a)await ve(a,o)}async function In(e){let t=e.data.object,r=t?.payment_intent;if(!r)return;let n=t?.amount_refunded??0;await ke.transaction(async(a)=>{if(!await Sn(e.id,a))return;let i=await a.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!i)return;let u=Mt(new Date);await a.updateTable("payments").set({status:"refunded",refund_amount:n,updated_at:u}).where("id","=",i.id).execute();let c=await a.selectFrom("orders").where("id","=",i.order_id).selectAll().executeTakeFirst();if(c&&c.status!=="REFUNDED")await a.updateTable("orders").set({status:"REFUNDED",updated_at:u}).where("id","=",c.id).execute()});let o=await En(r);if(o)await Pe(o,n)}async function Qs(){let e=await import("@stacksjs/payments").catch(()=>null);if(!e)return console.warn("[commerce/webhook] @stacksjs/payments not installed - Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:t,onCharge:r}=e;if(typeof t!=="function"||typeof r!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed - handlers NOT registered"),()=>{};return t({succeeded:Cn,failed:An}),r({refunded:In}),()=>{}}import{db as Ys}from"@stacksjs/database";async function vm(e){if(e.length===0)return new Map;let t=await Ys.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 Pm(e){try{let t=await Ys.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 Xs(e){let t=e.items.map((h)=>h.productId),r=await vm(t),n=e.taxRateId!=null?await Pm(e.taxRateId):0,o=0,a=[];for(let h of e.items){let b=h.unitPriceCents??r.get(h.productId)??0,R=Math.round(b*h.quantity);o+=R,a.push({productId:h.productId,quantity:h.quantity,unitPriceCents:b,lineCents:R})}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),l=o-s+u+c,p=e.maxDriftCents??5,m=!1,f=0;if(e.clientTotalCents!=null)f=Math.abs(l-e.clientTotalCents),m=f>p;return{subtotalCents:o,discountCents:s,taxCents:u,shippingCents:c,totalCents:l,resolvedItems:a,priceChanged:m,diffCents:f}}import{db as Nt,sqlHelpers as Fm}from"@stacksjs/database";import{env as km}from"@stacksjs/env";function ei(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 Mn(e,t){if(!Number.isFinite(t)||t<=0)return{ok:!1,productId:e,quantity:t,reason:"non-positive"};let r;try{r=await Nt.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 ti(e){for(let r of e){let n=await Mn(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 ri(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=Fm(km.DB_CONNECTION||"sqlite").param;try{let i=await Nt.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:Number(i?.changes??i?.numDeletedRows??i?.[0]?.numDeletedRows??i?.affectedRows??0),cutoffAt:o}}catch{try{let s=await Nt.selectFrom("carts").where("updated_at","<",o).select(["id"]).limit(r).execute();if(s.length===0)return{deleted:0,cutoffAt:o};let i=s.map((l)=>l.id),u=await Nt.deleteFrom("carts").where("id","in",i).execute();return{deleted:Number(u?.numDeletedRows??u?.[0]?.numDeletedRows??u?.affectedRows??s.length),cutoffAt:o}}catch{return{deleted:0,cutoffAt:o}}}}var Jn={};y(Jn,{bulkDestroy:()=>ai,destroy:()=>oi,fetchAll:()=>si,fetchById:()=>ye,fetchMonthlyPaymentTrends:()=>ci,fetchPaymentStats:()=>ii,fetchPaymentStatsByMethod:()=>ui,recordRefund:()=>yi,store:()=>pi,update:()=>wi});import{db as ni}from"@stacksjs/database";async function oi(e){try{let t=await ni.deleteFrom("payments").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete payment: ${t.message}`);throw t}}async function ai(e){if(!e.length)return 0;try{let t=await ni.deleteFrom("payments").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete payments: ${t.message}`);throw t}}import{db as T}from"@stacksjs/database";import{formatDate as O}from"@stacksjs/orm";async function si(){return await T.selectFrom("payments").selectAll().execute()}async function ye(e){return await T.selectFrom("payments").selectAll().where("id","=",e).executeTakeFirst()}async function ii(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 T.selectFrom("payments").select([T.fn.count("id").as("transaction_count"),T.fn.sum("amount").as("total_revenue")]).where("created_at",">=",O(r)).where("created_at","<=",O(t)).where("status","=","completed").executeTakeFirst(),s=await T.selectFrom("payments").select([T.fn.count("id").as("transaction_count"),T.fn.sum("amount").as("total_revenue")]).where("created_at",">=",O(o)).where("created_at","<=",O(n)).where("status","=","completed").executeTakeFirst(),i=await T.selectFrom("payments").select(T.fn.count("id").as("count")).where("created_at",">=",O(r)).where("created_at","<=",O(t)).executeTakeFirst(),u=Number(a?.transaction_count||0),c=Number(a?.total_revenue||0),l=u>0?c/u:0,p=Number(s?.transaction_count||0),m=Number(s?.total_revenue||0),f=p>0?m/p:0,h=u-p,b=c-m,R=l-f,z=p>0?h/p*100:u>0?100:0,pe=m>0?b/m*100:c>0?100:0,me=f>0?R/f*100:l>0?100:0,xe=Number(i?.count||0),G=xe>0?u/xe*100:0;return{total_transactions:u,total_revenue:c,average_transaction:l,successful_rate:G,comparison:{transactions:{difference:h,percentage:Math.abs(z),is_increase:h>=0},revenue:{difference:b,percentage:Math.abs(pe),is_increase:b>=0},average:{difference:R,percentage:Math.abs(me),is_increase:R>=0}}}}async function ui(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=await T.selectFrom("payments").select([T.fn.count("id").as("total_count"),T.fn.sum("amount").as("total_revenue")]).where("created_at",">=",O(r)).where("created_at","<=",O(t)).where("status","=","completed").executeTakeFirst(),o=Number(n?.total_count||0),a=await T.selectFrom("payments").select(["method",T.fn.count("id").as("count"),T.fn.sum("amount").as("revenue")]).where("created_at",">=",O(r)).where("created_at","<=",O(t)).where("status","=","completed").groupBy("method").execute(),s={};return a.forEach((i)=>{let u=Number(i.count||0),c=Number(i.revenue||0),l=o>0?u/o*100:0;s[i.method]={count:u,revenue:c,percentage_of_total:l}}),s}async function ci(){let e=new Date,t=new Date(e);t.setMonth(e.getMonth()-11),t.setDate(1);let r=await T.selectFrom("payments").selectAll().where("created_at",">=",O(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],i=s.transactions,u=s.revenue,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:Tm}=globalThis.Bun;import{db as di}from"@stacksjs/database";import{HttpError as li}from"@stacksjs/error-handling";import{isUniqueViolation as Em}from"@stacksjs/orm";async function pi(e){let t=Tm(),r={...e,status:e.status||"pending",currency:e.currency||"USD",uuid:t};try{return await di.insertInto("payments").values(r).executeTakeFirst(),await di.selectFrom("payments").where("uuid","=",t).selectAll().executeTakeFirst()}catch(n){if(n instanceof li)throw n;if(Em(n))throw new li(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 mi,sqlHelpers as Sm}from"@stacksjs/database";import{env as Cm}from"@stacksjs/env";import{formatDate as fi}from"@stacksjs/orm";async function wi(e,t){if(!await ye(e))return;try{return await mi.updateTable("payments").set({...t,updated_at:fi(new Date)}).where("id","=",e).execute(),await ye(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 Am=new Set(["completed","succeeded","partiallyRefunded"]);async function yi(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=Sm(Cm.DB_CONNECTION||"sqlite").param,o=fi(new Date),s=await mi.unsafe(`UPDATE payments
21
22
  SET refund_amount = COALESCE(refund_amount, 0) + ${n(1)},
22
23
  status = CASE WHEN COALESCE(refund_amount, 0) + ${n(2)} = amount
23
24
  THEN 'refunded' ELSE 'partiallyRefunded' END,
24
25
  updated_at = ${n(3)}
25
26
  WHERE id = ${n(4)}
26
27
  AND status IN ('completed', 'succeeded', 'partiallyRefunded')
27
- AND COALESCE(refund_amount, 0) + ${n(5)} <= amount`,[t,t,o,e,t]),s=typeof a?.execute==="function"?await a.execute():a;if(Number(s?.numUpdatedRows??s?.[0]?.numUpdatedRows??s?.numAffectedRows??s?.affectedRows??s?.[0]?.affectedRows??s?.changes??0)>0){let p=await we(e);if(p)return p;throw Error(`Payment with ID ${e} disappeared during refund`)}let u=await we(e);if(!u)throw Error(`Payment with ID ${e} not found`);let c=String(u.status||"");if(!np.has(c))throw Error(`Payment status ${c||"unknown"} cannot be refunded`);let l=u,m=Number(u.amount||0)-Number(l.refundAmount??l.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${m} minor units`)}var Bn={};y(Bn,{categories:()=>Jt,default:()=>yp,items:()=>Bt,manufacturers:()=>Ot,reviews:()=>Ut,units:()=>Lt,variants:()=>zt});var Jt={};y(Jt,{bulkRemove:()=>oi,compareCategoryGrowth:()=>ti,deactivate:()=>si,deactivateChildCategories:()=>ii,fetchActive:()=>Hs,fetchAll:()=>Cn,fetchByDisplayOrder:()=>Xs,fetchById:()=>S,fetchByName:()=>Ks,fetchCategoryTree:()=>ri,fetchChildCategories:()=>Ys,fetchRootCategories:()=>Qs,fetchStats:()=>ei,findOrCreateByName:()=>ci,remove:()=>ni,removeChildCategories:()=>ai,store:()=>An,update:()=>di,updateActiveStatus:()=>mi,updateDisplayOrder:()=>li,updateParent:()=>pi});import{db as ke}from"@stacksjs/database";import{db as D}from"@stacksjs/database";import{formatDate as He}from"@stacksjs/orm";async function Cn(){return await D.selectFrom("categories").selectAll().execute()}async function S(e){return await D.selectFrom("categories").where("id","=",e).selectAll().executeTakeFirst()}async function Ks(e){return await D.selectFrom("categories").where("name","=",e).selectAll().executeTakeFirst()}async function Hs(){return await D.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function Qs(){return await D.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function Ys(e){return await D.selectFrom("categories").where("parent_category_id","=",e).where("is_active","=",!0).selectAll().execute()}async function Xs(e=!0){let t=D.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 ei(){let e=await D.selectFrom("categories").select(D.fn.count("id").as("count")).executeTakeFirst(),t=await D.selectFrom("categories").where("is_active","=",!0).select(D.fn.count("id").as("count")).executeTakeFirst(),r=await D.selectFrom("categories").whereNull("parent_category_id").select(D.fn.count("id").as("count")).executeTakeFirst(),n=await D.selectFrom("categories").whereNotNull("image_url").select(D.fn.count("id").as("count")).executeTakeFirst(),o=new Date;o.setDate(o.getDate()-30);let a=He(o),s=await D.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await D.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",D.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 ti(e=30){let t=new Date,r=He(t),n=new Date;n.setDate(t.getDate()-e);let o=He(n),a=new Date(n);a.setDate(a.getDate()-1);let s=He(a),i=new Date(a);i.setDate(a.getDate()-e);let u=He(i),c=await D.selectFrom("categories").select(D.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",r).executeTakeFirst(),l=await D.selectFrom("categories").select(D.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),m=Number(c?.count||0),p=Number(l?.count||0),w=m-p,x=p!==0?w/p*100:m>0?100:0;return{current_period:m,previous_period:p,difference:w,percentage_change:x,days_range:e}}async function ri(){let e=await Cn(),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 ni(e){let t=await ke.deleteFrom("categories").where("id","=",e).executeTakeFirst();return d(t)>0}async function oi(e){if(!e.length)return 0;let t=await ke.deleteFrom("categories").where("id","in",e).executeTakeFirst();return d(t)}async function ai(e){let t=await ke.deleteFrom("categories").where("parent_category_id","=",e).executeTakeFirst();return d(t)}async function si(e){if(!await S(e))throw Error(`Category with ID ${e} not found`);return!!await ke.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",e).executeTakeFirst()}async function ii(e){let t=await ke.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",e).execute();return Number(t.length)||0}var{randomUUIDv7:op}=globalThis.Bun;import{db as ui}from"@stacksjs/database";import{HttpError as Mt}from"@stacksjs/error-handling";import{isUniqueViolation as ap}from"@stacksjs/orm";import{slug as sp}from"@stacksjs/strings";async function An(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 Mt(422,"Parent category ID must be a positive integer");if(t&&!await S(t))throw new Mt(422,`Parent category with ID ${e.parent_category_id} not found`);let r={...e,uuid:op(),is_active:e.is_active??!0,parent_category_id:e.parent_category_id||null},n=await ui.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create category");return n}catch(t){if(t instanceof Mt)throw t;if(ap(t))throw new Mt(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 ci(e){if(!e.name)throw Error("Name is required");let t=await ui.selectFrom("categories").selectAll().where("name","=",e.name).executeTakeFirst();if(t)return t;let r={name:e.name,slug:sp(e.name),is_active:e.is_active??!0,display_order:0};return await An(r)}import{db as Qe}from"@stacksjs/database";import{HttpError as Te}from"@stacksjs/error-handling";import{formatDate as Nt,isUniqueViolation as ip}from"@stacksjs/orm";async function di(e,t){if(!await S(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 Te(422,"Parent category ID must be a positive integer");if(n===e)throw new Te(422,"A category cannot be its own parent");if(n&&!await S(n))throw new Te(422,`Parent category with ID ${t.parent_category_id} not found`);if(n&&await fi(e,String(n)))throw new Te(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 Qe.updateTable("categories").set({...t,...n,updated_at:Nt(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!o)return;return o}catch(n){if(n instanceof Te)throw n;if(ip(n))throw new Te(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 li(e,t){if(!await S(e))throw Error(`Category with ID ${e} not found`);try{return await Qe.updateTable("categories").set({display_order:t,updated_at:Nt(new Date)}).where("id","=",e).execute(),await S(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category display order: ${n.message}`);throw n}}async function mi(e,t){if(!await S(e))throw Error(`Category with ID ${e} not found`);try{return await Qe.updateTable("categories").set({is_active:t,updated_at:Nt(new Date)}).where("id","=",e).execute(),await S(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category active status: ${n.message}`);throw n}}async function pi(e,t){if(!await S(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 S(n))throw Error(`Parent category with ID ${t} not found`);if(await fi(e,t))throw Error("This operation would create a circular reference in the category hierarchy")}try{let n={updated_at:Nt(new Date)};if(t===null)await Qe.updateTable("categories").set({...n,parent_category_id:null}).where("id","=",e).execute();else await Qe.updateTable("categories").set({...n,parent_category_id:t}).where("id","=",e).execute();return await S(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category parent: ${n.message}`);throw n}}async function fi(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 S(r),a=o?.parent_category_id??o?.parentCategoryId;if(!o||!a)return!1;r=Number(a)}return!1}var Bt={};y(Bt,{bulkDestroy:()=>hi,bulkStore:()=>vi,destroy:()=>yi,fetchAll:()=>gi,fetchById:()=>X,fetchTopProducts:()=>bi,store:()=>Ri,update:()=>Di,updateAvailability:()=>Pi,updateInventory:()=>Fi});import{db as wi}from"@stacksjs/database";async function yi(e){try{let t=await wi.deleteFrom("products").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product item: ${t.message}`);throw t}}async function hi(e){if(!e.length)return 0;try{let t=await wi.deleteFrom("products").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product items: ${t.message}`);throw t}}import{db as ie,sql as up}from"@stacksjs/database";async function X(e){let t=await ie.selectFrom("products").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=null,n=null;if(t.manufacturer_id)r=await ie.selectFrom("manufacturers").where("id","=",t.manufacturer_id).selectAll().executeTakeFirst();if(t.category_id)n=await ie.selectFrom("categories").where("id","=",t.category_id).selectAll().executeTakeFirst();return{...t,manufacturer:r,category:n}}return}async function gi(){let e=await ie.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=ie.selectFrom("manufacturers"),o=ie.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,l)=>(c[l.id]=l,c),{}),u=s.reduce((c,l)=>(c[l.id]=l,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 bi(e=5){try{return(await ie.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",ie.fn.sum("order_items.quantity").as("units_sold"),up`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:_i}=globalThis.Bun;import{db as xi}from"@stacksjs/database";async function Ri(e){try{let t={...e,uuid:_i()},r=await xi.insertInto("products").values(t).executeTakeFirst();if(!r)throw Error("Failed to create product item");let n=Number(r.insertId)||Number(r.numInsertedOrUpdatedRows),o=await X(n);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 vi(e){if(!e.length)return 0;let t=0;try{return await xi.transaction().execute(async(r)=>{for(let n of e){let o={...n,uuid:_i()};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 In}from"@stacksjs/database";import{formatDate as Mn}from"@stacksjs/orm";async function Di(e,t){try{if(!e)throw Error("Product item ID is required for update");let r=await In.updateTable("products").set({...t,updated_at:Mn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function Pi(e,t){if(!await X(e))throw Error(`Product item with ID ${e} not found`);try{return await In.updateTable("products").set({is_available:t,updated_at:Mn(new Date)}).where("id","=",e).execute(),await X(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update product item availability: ${n.message}`);throw n}}async function Fi(e,t){let r=await X(e);if(!r)throw Error(`Product item with ID ${e} not found`);let n={updated_at:Mn(new Date)};if(t!==void 0)n.inventory_count=t;if(Object.keys(n).length===1)return r;try{return await In.updateTable("products").set(n).where("id","=",e).execute(),await X(e)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update inventory information: ${o.message}`);throw o}}var Ot={};y(Ot,{bulkDestroy:()=>Ei,bulkStore:()=>$i,destroy:()=>Ti,fetchAll:()=>Si,fetchByCountry:()=>Mi,fetchById:()=>Ci,fetchByUuid:()=>Ai,fetchFeatured:()=>Ii,fetchWithProductCount:()=>Ni,store:()=>Ui,update:()=>Li,updateByUuid:()=>ji,updateFeaturedStatus:()=>zi});import{db as ki}from"@stacksjs/database";async function Ti(e){try{let t=await ki.deleteFrom("manufacturers").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete order: ${t.message}`);throw t}}async function Ei(e){if(!e.length)return 0;try{let t=await ki.deleteFrom("manufacturers").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete orders: ${t.message}`);throw t}}import{db as ee}from"@stacksjs/database";function Si(){return ee.selectFrom("manufacturers").selectAll().execute()}async function Ci(e){return await ee.selectFrom("manufacturers").where("id","=",e).selectAll().executeTakeFirst()}async function Ai(e){return await ee.selectFrom("manufacturers").where("uuid","=",e).selectAll().executeTakeFirst()}async function Ii(e=10){return await ee.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(e).execute()}async function Mi(e,t={}){let r=t.page||1,n=t.limit||2,o=await ee.selectFrom("manufacturers").select(ee.fn.count("id").as("total")).where("country","=",e).executeTakeFirst(),a=Number(o?.total||0),s=await ee.selectFrom("manufacturers").selectAll().where("country","=",e).limit(n).offset((r-1)*n).execute(),i=Math.ceil(a/n);return{data:s,paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function Ni(e={}){let t=ee.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",ee.fn.count("p.id").as("product_count")]).groupBy("m.id"),t.execute()}var{randomUUIDv7:Bi}=globalThis.Bun;import{db as Oi}from"@stacksjs/database";import{HttpError as Ji}from"@stacksjs/error-handling";import{isUniqueViolation as cp}from"@stacksjs/orm";async function Ui(e){try{let t={...e,uuid:Bi(),featured:e.featured??!1},r=await Oi.insertInto("manufacturers").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return r}catch(t){if(t instanceof Ji)throw t;if(cp(t))throw new Ji(409,"A manufacturer with this name already exists");if(t instanceof Error)throw Error(`Failed to create manufacturer: ${t.message}`);throw t}}async function $i(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:Bi(),featured:r.featured??!1};await Oi.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 Nn}from"@stacksjs/database";import{HttpError as Wi}from"@stacksjs/error-handling";import{formatDate as Jn,isUniqueViolation as dp}from"@stacksjs/orm";async function Li(e,t){try{if(!e)throw Error("Manufacturer ID is required for update");let r=await Nn.updateTable("manufacturers").set({...t,updated_at:Jn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Wi)throw r;if(dp(r))throw new Wi(409,"A manufacturer with this name already exists");if(r instanceof Error)throw Error(`Failed to update manufacturer: ${r.message}`);throw r}}async function zi(e,t){try{let r=await Nn.updateTable("manufacturers").set({featured:t,updated_at:Jn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function ji(e,t){try{let r=await Nn.updateTable("manufacturers").set({...t,updated_at:Jn(new Date)}).where("uuid","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var Ut={};y(Ut,{bulkDestroy:()=>qi,destroy:()=>Vi,fetchAll:()=>Ki,fetchApprovedByProductId:()=>Yi,fetchById:()=>Zi,fetchByProductId:()=>Hi,fetchByUserId:()=>Qi,fetchMostHelpfulByProductId:()=>Xi,fetchStats:()=>nu,fetchStatsByProductIds:()=>ou,store:()=>au,update:()=>uu,updateVotes:()=>cu});import{db as Gi}from"@stacksjs/database";async function Vi(e){try{let t=await Gi.deleteFrom("reviews").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete review: ${t.message}`);throw t}}async function qi(e){if(!e.length)return 0;try{let t=await Gi.deleteFrom("reviews").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete reviews: ${t.message}`);throw t}}import{db as Ee}from"@stacksjs/database";async function Zi(e){return await Ee.selectFrom("reviews").where("id","=",e).selectAll().executeTakeFirst()}async function Ki(){return await Ee.selectFrom("reviews").selectAll().execute()}async function Hi(e){return await Ee.selectFrom("reviews").where("product_id","=",e).selectAll().execute()}async function Qi(e){return await Ee.selectFrom("reviews").where("customer_id","=",e).selectAll().execute()}async function Yi(e){return await Ee.selectFrom("reviews").where("product_id","=",e).where("is_approved","=",!0).selectAll().execute()}async function Xi(e){return await Ee.selectFrom("reviews").where("product_id","=",e).orderBy("helpful_votes","desc").selectAll().execute()}import{db as eu}from"@stacksjs/database";function tu(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function ru(e){let t=tu();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 nu(e){let t=await eu.selectFrom("reviews").select(["rating"]).where("product_id","=",e).where("is_approved","=",!0).execute();return ru(t)}async function ou(e){let t=new Map;for(let o of e)t.set(o,tu());if(e.length===0)return t;let r=await eu.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,ru(a));return t}var{randomUUIDv7:lp}=globalThis.Bun;import{db as mp}from"@stacksjs/database";function pp(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 au(e){try{if(pp(e))throw Error("A review needs a rating or something written: both were empty");let t={...e,uuid:lp(),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 mp.insertInto("reviews").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return 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{asRow as fp,db as su}from"@stacksjs/database";import{formatDate as iu}from"@stacksjs/orm";async function uu(e,t){try{if(!e)throw Error("Review ID is required for update");let r=await su.updateTable("reviews").set({...t,updated_at:iu(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function cu(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)`,a=await su.unsafe(`UPDATE "reviews" SET "${n}" = ${o}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[iu(new Date),e]).execute(),s=Array.isArray(a)?a[0]:a;if(!s)throw Error("Failed to update review votes");return fp(s)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update review votes: ${n.message}`);throw n}}var Lt={};y(Lt,{bulkDestroy:()=>mu,bulkStore:()=>gu,bulkUpdate:()=>Ru,destroy:()=>lu,fetchAll:()=>wu,fetchById:()=>fu,formatUnitOptions:()=>bu,getDefaultUnit:()=>_u,store:()=>hu,update:()=>xu,updateDefaultStatus:()=>vu});import{db as du}from"@stacksjs/database";async function lu(e){try{let t=await du.deleteFrom("product_units").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product unit: ${t.message}`);throw t}}async function mu(e){if(!e.length)return 0;try{let t=await du.deleteFrom("product_units").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product units: ${t.message}`);throw t}}import{db as pu}from"@stacksjs/database";async function fu(e){return await pu.selectFrom("product_units").where("id","=",e).selectAll().executeTakeFirst()}async function wu(){return await pu.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:yu}=globalThis.Bun;import{db as Ye}from"@stacksjs/database";async function hu(e){try{return await Ye.transaction(async(t)=>{let r={...e,uuid:yu()},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 n})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product unit: ${t.message}`);throw t}}async function gu(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:yu()},o=await Ye.insertInto("product_units").values(n).returningAll().executeTakeFirst();if(n.is_default&&n.type&&o)await Ye.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 bu(e){try{let t=Ye.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 _u(e){try{return await Ye.selectFrom("product_units").selectAll().where("type","=",e).where("is_default","=",!0).executeTakeFirst()}catch(t){if(t instanceof Error)throw TypeError(`Failed to get default unit: ${t.message}`);throw t}}import{db as $t}from"@stacksjs/database";import{formatDate as Wt}from"@stacksjs/orm";async function xu(e,t){try{if(!e)throw Error("Product unit ID is required for update");return await $t.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:Wt(new Date)}).where("type","=",o).where("id","!=",e).execute();let s=await r.updateTable("product_units").set({...t,updated_at:Wt(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!s)return;return s})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function Ru(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 $t.updateTable("product_units").set({...o,updated_at:Wt(new Date)}).where("id","=",n.id).executeTakeFirst(),s=o;if(s.is_default===!0&&s.type)await $t.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",n.id).execute();if(Number(a.numUpdatedRows)>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 vu(e,t){try{return await $t.transaction(async(r)=>{let n=await r.selectFrom("product_units").select("type").where("id","=",e).executeTakeFirst();if(!n)return!1;let o=Wt(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 zt={};y(zt,{bulkDestroy:()=>Fu,bulkStore:()=>Iu,bulkUpdate:()=>Uu,destroy:()=>Pu,fetchAll:()=>Eu,fetchById:()=>Tu,formatVariantOptions:()=>Mu,generateVariantCombinations:()=>Nu,store:()=>Au,update:()=>Ou});import{db as Du}from"@stacksjs/database";async function Pu(e){try{let t=await Du.deleteFrom("product_variants").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product variant: ${t.message}`);throw t}}async function Fu(e){if(!e.length)return 0;try{let t=await Du.deleteFrom("product_variants").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product variants: ${t.message}`);throw t}}import{db as ku}from"@stacksjs/database";async function Tu(e){return await ku.selectFrom("product_variants").where("id","=",e).selectAll().executeTakeFirst()}async function Eu(){return await ku.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:Su}=globalThis.Bun;import{db as Cu}from"@stacksjs/database";async function Au(e){try{let t={...e,uuid:Su()},r=await Cu.insertInto("product_variants").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return r}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product variant: ${t.message}`);throw t}}async function Iu(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:Su()};await Cu.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 Mu(e){if(!e||!e.length)return JSON.stringify([]);let t=e.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(t)}function Nu(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 Ju}from"@stacksjs/database";import{formatDate as Bu}from"@stacksjs/orm";async function Ou(e,t){try{let r=await Ju.updateTable("product_variants").set({...t,updated_at:Bu(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function Uu(e){if(!e.length)return 0;let t=0;try{for(let r of e){if(!r.id)continue;let n=await Ju.updateTable("product_variants").set({...r,updated_at:Bu(new Date)}).where("id","=",r.id).executeTakeFirst();if(Number(n.numUpdatedRows)>0)t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var wp={categories:Jt,items:Bt,manufacturers:Ot,reviews:Ut,units:Lt,variants:zt},yp=wp;var Ln={};y(Ln,{bulkDestroy:()=>Lu,bulkStore:()=>Qu,destroy:()=>Wu,fetchAll:()=>zu,fetchById:()=>Se,fetchPageStats:()=>Vu,fetchPrintJobStats:()=>ju,fetchPrintTimeStats:()=>qu,fetchPrintsPerHour:()=>Zu,fetchSuccessRate:()=>Gu,store:()=>Hu,update:()=>Yu,updatePrintJob:()=>ec,updateStatus:()=>Xu});import{db as $u}from"@stacksjs/database";async function Wu(e){try{let t=await $u.deleteFrom("receipts").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print log: ${t.message}`);throw t}}async function Lu(e){if(!e.length)return 0;try{let t=await $u.deleteFrom("receipts").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete receipts: ${t.message}`);throw t}}import{db as On}from"@stacksjs/database";import{formatDate as hp}from"@stacksjs/orm";function z(e){return hp(e)}function gp(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 Se(e){return await On.selectFrom("receipts").where("id","=",e).selectAll().executeTakeFirst()}async function zu(){return await On.selectFrom("receipts").selectAll().execute()}async function ju(e,t){let r=z(e),n=z(t),o=await M("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 Gu(e,t){let r=z(e),n=z(t),o=await M("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 Vu(e,t){let r=z(e),n=z(t),o=await M("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 qu(e,t){let r=z(e),n=z(t),o=await M("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 Zu(e,t){let r=typeof e==="number"?e:e.getTime(),n=typeof t==="number"?t:t.getTime(),o=z(e),a=z(t),s=await On.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,l=Array.from({length:24},(m,p)=>({hour:p,count:0}));return s.forEach((m)=>{let p=gp(m.timestamp);if(!p)return;l[p.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:l}}var{randomUUIDv7:Ku}=globalThis.Bun;import{db as jt}from"@stacksjs/database";import{formatDate as Un}from"@stacksjs/orm";function Xe(e){try{if(typeof e==="number")return Un(e<=2147483647?e*1000:e);if(typeof e==="string"&&/^\d{10}$/.test(e))return Un(Number(e)*1000);return Un(e)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function Hu(e){try{let t=Ku(),r={...e,timestamp:Xe(e.timestamp),uuid:t};await jt.insertInto("receipts").values(r).executeTakeFirst();let n=await jt.selectFrom("receipts").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create receipt");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create receipt: ${t.message}`);throw t}}async function Qu(e){if(!e.length)return 0;try{let t=e.map((o)=>({...o,timestamp:Xe(o.timestamp),uuid:Ku()})),n=await jt.insertInto("receipts").values(t).executeTakeFirst()??{};return Number(n.numInsertedOrUpdatedRows??n.numAffectedRows??n.affectedRows??n.changes??0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${t.message}`);throw t}}import{db as $n}from"@stacksjs/database";import{formatDate as Wn}from"@stacksjs/orm";async function Yu(e,t){try{if(!e)throw Error("Receipt ID is required for update");let r={...t,...t.timestamp===void 0?{}:{timestamp:Xe(t.timestamp)},updated_at:Wn(new Date)};await $n.updateTable("receipts").set(r).where("id","=",e).execute();let n=await Se(e);if(!n)return;return n}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function Xu(e,t){try{await $n.updateTable("receipts").set({status:t,updated_at:Wn(new Date)}).where("id","=",e).execute();let r=await Se(e);if(!r)throw Error("Failed to update receipt status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function ec(e,t,r,n){try{let o={updated_at:Wn(new Date)};if(t!==void 0)o.size=t;if(r!==void 0)o.pages=r;if(n!==void 0)o.duration=n;await $n.updateTable("receipts").set(o).where("id","=",e).execute();let a=await Se(e);if(!a)throw Error("Failed to update receipt job information");return a}catch(o){if(o instanceof Error)throw TypeError(`Failed to update receipt job information: ${o.message}`);throw o}}var mo={};y(mo,{default:()=>jp,digital:()=>Yt,drivers:()=>er,geocoding:()=>or,licenses:()=>ir,methods:()=>lr,rates:()=>yr,routes:()=>Ht,tracking:()=>Dr,zones:()=>Tr});var Ht={};y(Ht,{DeliveryRouteInputError:()=>I,bulkDestroy:()=>nc,destroy:()=>rc,fetchActive:()=>ac,fetchAll:()=>oc,fetchByDriver:()=>sc,fetchById:()=>Vt,store:()=>ic,update:()=>cc,updateLastActive:()=>uc,updateMetrics:()=>lc,updateStops:()=>dc,validateDeliveryRouteWrite:()=>Ce});import{db as tc}from"@stacksjs/database";async function rc(e){try{let t=await tc.deleteFrom("delivery_routes").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete delivery route: ${t.message}`);throw t}}async function nc(e){if(!e.length)return 0;try{let t=await tc.deleteFrom("delivery_routes").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete delivery routes: ${t.message}`);throw t}}import{db as Gt}from"@stacksjs/database";async function Vt(e){return await Gt.selectFrom("delivery_routes").where("id","=",e).selectAll().executeTakeFirst()}async function oc(){return await Gt.selectFrom("delivery_routes").selectAll().execute()}async function ac(){return await Gt.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function sc(e){return await Gt.selectFrom("delivery_routes").where("driver","=",e).selectAll().execute()}var{randomUUIDv7:xp}=globalThis.Bun;import{db as zn}from"@stacksjs/database";function ye(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 et(e){return ye(e,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function te(e){return ye(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 tt(e){return ye(e,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function rt(e){return ye(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 nt(e){return ye(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 ot(e){return ye(e,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function qt(e){return ye(e,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as bp}from"@stacksjs/database";class I extends TypeError{constructor(e){super(e);this.name="DeliveryRouteInputError"}}function Zt(e,t,r){return Number(e[r]??t?.[r])}function _p(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 Ce(e,t){let r=Zt(e,t,"driver_id"),n=Zt(e,t,"stops"),o=Zt(e,t,"delivery_time"),a=Zt(e,t,"total_distance"),s=_p(e,t);if(!Number.isSafeInteger(r)||r<1)throw new I("Driver must be a positive integer.");if(!Number.isSafeInteger(n)||n<0)throw new I("Stops must be a non-negative integer.");if(!Number.isSafeInteger(o)||o<0)throw new I("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(a)||a<0)throw new I("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(s)||s<0)throw new I("Last active must be a valid Unix timestamp.");let i=await bp.selectFrom("drivers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new I(`Driver ${r} was not found.`);return{...e,driver_id:Number(i.id),driver:i.name,vehicle:i.vehicle_number,last_active:s}}async function ic(e){try{let t=xp(),r=qt(e),o={...await Ce(r),uuid:t};await zn.insertInto("delivery_routes").values(o).executeTakeFirst();let a=await zn.selectFrom("delivery_routes").where("uuid","=",t).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(t){if(t instanceof I)throw t;if(t instanceof Error)throw TypeError(`Failed to create delivery route: ${t.message}`);throw t}}async function uc(e){try{await zn.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",e).execute();let t=await Vt(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 Kt}from"@stacksjs/database";import{formatDate as jn}from"@stacksjs/orm";async function cc(e,t){try{if(!e)throw Error("Delivery route ID is required for update");let r=await Kt.selectFrom("delivery_routes").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=qt(t),o=await Ce(n,r),a=await Kt.updateTable("delivery_routes").set({...o,updated_at:jn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof I)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function dc(e,t){try{let r=await Kt.updateTable("delivery_routes").set({stops:t,updated_at:jn(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 lc(e,t,r){try{let n={updated_at:jn(new Date)};if(t!==void 0)n.delivery_time=t;if(r!==void 0)n.total_distance=r;let o=await Kt.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 Yt={};y(Yt,{bulkDestroy:()=>fc,bulkSoftDelete:()=>wc,bulkStore:()=>xc,destroy:()=>mc,fetchAll:()=>gc,fetchById:()=>hc,softDelete:()=>pc,store:()=>_c,update:()=>Rc,updateDeliverySettings:()=>Dc,updateStatus:()=>vc});import{db as Qt}from"@stacksjs/database";async function mc(e){try{let t=await Qt.deleteFrom("digital_deliveries").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete digital delivery: ${t.message}`);throw t}}async function pc(e){try{let t=await Qt.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${t.message}`);throw t}}async function fc(e){if(!e.length)return 0;try{let t=await Qt.deleteFrom("digital_deliveries").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${t.message}`);throw t}}async function wc(e){if(!e.length)return 0;try{let t=await Qt.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${t.message}`);throw t}}import{db as yc}from"@stacksjs/database";async function hc(e){return await yc.selectFrom("digital_deliveries").where("id","=",e).selectAll().executeTakeFirst()}async function gc(){return await yc.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:bc}=globalThis.Bun;import{asRow as Rp,db as Gn}from"@stacksjs/database";async function _c(e){try{let t=bc(),r={...rt(e),uuid:t};await Gn.insertInto("digital_deliveries").values(r).executeTakeFirst();let n=await Gn.selectFrom("digital_deliveries").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created digital delivery");return Rp(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create digital delivery: ${t.message}`);throw t}}async function xc(e){if(!e.length)return 0;try{let t=e.map((n)=>({...rt(n),uuid:bc()})),r=await Gn.insertInto("digital_deliveries").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${t.message}`);throw t}}import{db as Vn}from"@stacksjs/database";import{formatDate as qn}from"@stacksjs/orm";async function Rc(e,t){try{if(!e)throw Error("Digital delivery ID is required for update");let r=await Vn.updateTable("digital_deliveries").set({...rt(t),updated_at:qn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function vc(e,t){try{let r=await Vn.updateTable("digital_deliveries").set({status:t,updated_at:qn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function Dc(e,t,r,n,o){try{let a={updated_at:qn(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 Vn.updateTable("digital_deliveries").set(a).where("id","=",e).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return s}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var er={};y(er,{bulkDestroy:()=>Ec,bulkStore:()=>Ac,destroy:()=>Tc,fetchAll:()=>Fc,fetchById:()=>Xt,store:()=>Cc,update:()=>Ic,updateContact:()=>Nc,updateStatus:()=>Mc});import{db as kc}from"@stacksjs/database";import{db as Pc}from"@stacksjs/database";async function Xt(e){return await Pc.selectFrom("drivers").where("id","=",e).selectAll().executeTakeFirst()}async function Fc(){return await Pc.selectFrom("drivers").selectAll().execute()}async function Tc(e){try{let t=await kc.deleteFrom("drivers").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete driver: ${t.message}`);throw t}}async function Ec(e){if(!e.length)return 0;let t=0;try{return await kc.transaction().execute(async(r)=>{for(let n of e)if(await Xt(n))await r.deleteFrom("drivers").where("id","=",n).execute(),t++}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${r.message}`);throw r}}var{randomUUIDv7:Sc}=globalThis.Bun;import{db as Zn}from"@stacksjs/database";async function Cc(e){try{let t=Sc(),r={...ot(e),uuid:t};await Zn.insertInto("drivers").values(r).executeTakeFirst();let n=await Zn.selectFrom("drivers").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created driver");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create driver: ${t.message}`);throw t}}async function Ac(e){if(!e.length)return 0;try{let t=e.map((n)=>({...ot(n),uuid:Sc()})),r=await Zn.insertInto("drivers").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${t.message}`);throw t}}import{db as Kn}from"@stacksjs/database";import{formatDate as Hn}from"@stacksjs/orm";async function Ic(e,t){try{if(!e)throw Error("Driver ID is required for update");let r=await Kn.updateTable("drivers").set({...ot(t),updated_at:Hn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update driver: ${r.message}`);throw r}}async function Mc(e,t){try{let r=await Kn.updateTable("drivers").set({status:t,updated_at:Hn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update driver status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update driver status: ${r.message}`);throw r}}async function Nc(e,t){try{let r={updated_at:Hn(new Date)};if(t!==void 0)r.phone=t;let n=await Kn.updateTable("drivers").set(r).where("id","=",e).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update contact information");return n}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var or={};y(or,{PRECISION_RANK:()=>st,checkCoverage:()=>Tp,formatQuery:()=>Ae,geocode:()=>kp,geocodingDriver:()=>Wc,nominatimDriver:()=>nr,setGeocodingDriver:()=>Fp});var he=(e)=>e*Math.PI/180;function ue(e,t){let r=he(t.latitude-e.latitude),n=he(t.longitude-e.longitude),o=he(e.latitude),a=he(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 tr(e,t){let r=he(e.latitude),n=he(t.latitude),o=he(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 rr(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 Jc(e,t,r){return ue(e,t)<=r}function at(e){return typeof e?.latitude==="number"&&typeof e?.longitude==="number"&&Number.isFinite(e.latitude)&&Number.isFinite(e.longitude)}var st={unknown:0,locality:1,postal:2,street:3,rooftop:4};function Ae(e){return[e.street,e.city,e.region,e.postalCode,e.country].map((t)=>String(t??"").trim()).filter(Boolean).join(", ")}var vp="https://nominatim.openstreetmap.org/search",Bc=1000,Oc=0,Uc=Promise.resolve();async function Dp(e){let t=Uc.then(async()=>{let r=Date.now()-Oc;if(r<Bc)await Bun.sleep(Bc-r);return Oc=Date.now(),e()});return Uc=t.then(()=>{return},()=>{return}),t}function Pp(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 nr(e={}){let t=e.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,r=e.endpoint??vp;return{name:"nominatim",async geocode(n){let o=Ae(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 Dp(()=>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),l=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(l))return null;let m=Pp(u);return{latitude:c,longitude:l,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 $c=null;function Fp(e){$c=e}function Wc(){return $c??nr()}async function kp(e,t={}){let r=t.driver??Wc(),n=t.minimumPrecision??"street",o=`geocode:${r.name}:${Ae(e).toLowerCase()}`,a=await Ep(o);if(a!==void 0)return a;let s=await r.geocode(e),i=s&&st[s.precision]>=st[n]?s:null;return await Sp(o,i,i?t.cacheSeconds??2592000:600),i}function Tp(e,t,r){if(t.length===0)return null;let n=t[0],o=ue(e,n);for(let a of t.slice(1)){let s=ue(e,a);if(s<o)o=s,n=a}return{covered:o<=r,distanceMeters:Math.round(o),nearest:n}}async function Ep(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 Sp(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 ir={};y(ir,{LicenseKeyInputError:()=>F,bulkDestroy:()=>jc,bulkSoftDelete:()=>Gc,bulkStore:()=>Xc,destroy:()=>Lc,fetchAll:()=>Zc,fetchById:()=>qc,softDelete:()=>zc,store:()=>Yc,update:()=>ed,updateExpiration:()=>rd,updateStatus:()=>td,validateLicenseKeyWrite:()=>ge});import{db as ar}from"@stacksjs/database";async function Lc(e){try{let t=await ar.deleteFrom("license_keys").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete license key: ${t.message}`);throw t}}async function zc(e){try{let t=await ar.updateTable("license_keys").set({status:"inactive"}).where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete license key: ${t.message}`);throw t}}async function jc(e){if(!e.length)return 0;try{let t=await ar.deleteFrom("license_keys").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete license keys: ${t.message}`);throw t}}async function Gc(e){if(!e.length)return 0;try{let t=await ar.updateTable("license_keys").set({status:"inactive"}).where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete license keys: ${t.message}`);throw t}}import{db as Vc}from"@stacksjs/database";async function qc(e){return await Vc.selectFrom("license_keys").where("id","=",e).selectAll().executeTakeFirst()}async function Zc(){return await Vc.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:Qc}=globalThis.Bun;import{asRow as Ap,db as Xn}from"@stacksjs/database";import{db as Qn}from"@stacksjs/database";var Kc=["Standard License","Premium License","Enterprise License"],Hc=["active","inactive","unassigned"];class F extends TypeError{constructor(e){super(e);this.name="LicenseKeyInputError"}}function it(e,t,r){return e[r]!==void 0?e[r]:t?.[r]}function Yn(e,t,r,n){let o=it(e,t,r);if(o===void 0||o===null||o==="")return null;let a=Number(o);if(!Number.isSafeInteger(a)||a<1)throw new F(`${n} must be a positive integer or null.`);return a}function Cp(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 ge(e,t){let r=String(it(e,t,"key")||"").trim().toUpperCase(),n=String(it(e,t,"template")||""),o=String(it(e,t,"status")||""),a=Cp(it(e,t,"expiry_date")),s=Yn(e,t,"customer_id","Customer"),i=Yn(e,t,"product_id","Product"),u=Yn(e,t,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new F("License key must use five groups of four uppercase letters or numbers.");if(!Kc.includes(n))throw new F(`Template must be one of: ${Kc.join(", ")}.`);if(!Hc.includes(o))throw new F(`Status must be one of: ${Hc.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new F("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,l,m]=await Promise.all([s?Qn.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?Qn.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?Qn.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new F(`Customer ${s} was not found.`);if(i&&!l)throw new F(`Product ${i} was not found.`);if(u&&!m)throw new F(`Order ${u} was not found.`);if(s&&m?.customer_id&&Number(m.customer_id)!==s)throw new F(`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 Yc(e){try{let t=Qc(),r=nt(e),n={...await ge(r),uuid:t};await Xn.insertInto("license_keys").values(n).executeTakeFirst();let o=await Xn.selectFrom("license_keys").where("uuid","=",t).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created license key");return Ap(o)}catch(t){if(t instanceof F)throw t;if(t instanceof Error){if(t.message.includes("UNIQUE constraint failed: license_keys.key"))throw new F("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${t.message}`)}throw t}}async function Xc(e){if(!e.length)return 0;try{let t=await Promise.all(e.map(async(n)=>({...await ge(nt(n)),uuid:Qc()}))),r=await Xn.insertInto("license_keys").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof F)throw t;if(t instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${t.message}`);throw t}}import{db as sr}from"@stacksjs/database";import{formatDate as eo}from"@stacksjs/orm";async function ed(e,t){try{if(!e)throw Error("License key ID is required for update");let r=await sr.selectFrom("license_keys").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=nt(t),o=await ge(n,r),a=await sr.updateTable("license_keys").set({...o,updated_at:eo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof F)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new F("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function td(e,t){try{let r=await sr.updateTable("license_keys").set({status:t,updated_at:eo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function rd(e,t){try{let r={updated_at:eo(new Date)};if(t!==void 0)r.expiry_date=t;let n=await sr.updateTable("license_keys").set(r).where("id","=",e).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update expiration information");return n}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var lr={};y(lr,{bulkDestroy:()=>ad,bulkSoftDelete:()=>sd,bulkStore:()=>dd,destroy:()=>nd,fetchAll:()=>id,fetchById:()=>dr,formatShippingOptions:()=>ld,getActiveShippingMethods:()=>md,softDelete:()=>od,store:()=>cd,update:()=>pd,updatePricing:()=>wd,updateStatus:()=>fd});import{db as ur}from"@stacksjs/database";async function nd(e){try{let t=await ur.deleteFrom("shipping_methods").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping method: ${t.message}`);throw t}}async function od(e){try{let t=await ur.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${t.message}`);throw t}}async function ad(e){if(!e.length)return 0;try{let t=await ur.deleteFrom("shipping_methods").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping methods: ${t.message}`);throw t}}async function sd(e){if(!e.length)return 0;try{let t=await ur.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${t.message}`);throw t}}import{db as cr}from"@stacksjs/database";async function dr(e){let t=await cr.selectFrom("shipping_methods").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=await cr.selectFrom("shipping_zones").where("shipping_method_id","=",e).selectAll().execute();return{...t,shippingZones:r}}return}async function id(){let e=await cr.selectFrom("shipping_methods").selectAll().execute();if(e.length===0)return[];let t=[...new Set(e.map((a)=>a.id))],o=(await cr.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:ud}=globalThis.Bun;import{db as ut}from"@stacksjs/database";async function cd(e){try{let t=ud(),r={...et(e),uuid:t};await ut.insertInto("shipping_methods").values(r).executeTakeFirst();let n=await ut.selectFrom("shipping_methods").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created shipping method");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping method: ${t.message}`);throw t}}async function dd(e){if(!e.length)return 0;try{let t=e.map((n)=>({...et(n),uuid:ud()})),r=await ut.insertInto("shipping_methods").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${t.message}`);throw t}}function ld(){try{return ut.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 md(){try{return await ut.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(e){if(e instanceof Error)throw TypeError(`Failed to get active shipping methods: ${e.message}`);throw e}}import{db as to}from"@stacksjs/database";import{formatDate as ro}from"@stacksjs/orm";async function pd(e,t){try{if(!e)throw Error("Shipping method ID is required for update");let r=await to.updateTable("shipping_methods").set({...et(t),updated_at:ro(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function fd(e,t){try{let r=await to.updateTable("shipping_methods").set({status:t,updated_at:ro(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function wd(e,t,r){try{let n={updated_at:ro(new Date)};if(t!==void 0)n.base_rate=t;if(r!==void 0)n.free_shipping=r;let o=await to.updateTable("shipping_methods").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update pricing information");return o}catch(n){if(n instanceof Error)throw TypeError(`Failed to update pricing information: ${n.message}`);throw n}}var yr={};y(yr,{ShippingRateInputError:()=>C,bulkDestroy:()=>hd,bulkStore:()=>Md,bulkUpdate:()=>Jd,destroy:()=>yd,destroyByMethod:()=>bd,destroyByZone:()=>gd,fetchAll:()=>Rd,fetchById:()=>xd,formatShippingRateOptions:()=>Fd,getRateByWeightAndAddress:()=>Dd,getRateByWeightAndZone:()=>no,getRatesByZone:()=>vd,getShippingRatesByMethod:()=>kd,resolveZoneForAddress:()=>pr,store:()=>Id,update:()=>Nd,updateByMethod:()=>Od,updateByZone:()=>Bd,validateShippingRateWrite:()=>be,validateZoneMatchesAddress:()=>Pd});import{db as mr}from"@stacksjs/database";async function yd(e){try{let t=await mr.deleteFrom("shipping_rates").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rate: ${t.message}`);throw t}}async function hd(e){if(!e.length)return 0;try{let t=await mr.deleteFrom("shipping_rates").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates: ${t.message}`);throw t}}async function gd(e){try{let t=await mr.deleteFrom("shipping_rates").where("shipping_zone_id","=",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${t.message}`);throw t}}async function bd(e){try{let t=await mr.deleteFrom("shipping_rates").where("shipping_method_id","=",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${t.message}`);throw t}}import{db as U}from"@stacksjs/database";async function xd(e){let t=await U.selectFrom("shipping_rates").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=null,n=null;if(t.shipping_zone_id)r=await U.selectFrom("shipping_zones").where("id","=",t.shipping_zone_id).selectAll().executeTakeFirst();if(t.shipping_method_id)n=await U.selectFrom("shipping_methods").where("id","=",t.shipping_method_id).selectAll().executeTakeFirst();return{...t,shipping_zone:r,shipping_method:n}}return}async function Rd(){let e=await U.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?U.selectFrom("shipping_zones").where("id","in",t).selectAll().execute():[],r.length?U.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 vd(e){try{return await U.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).orderBy("weight_from").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${t.message}`);throw t}}async function no(e,t){try{return await U.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).where("weight_from","<=",e).where("weight_to",">=",e).executeTakeFirst()}catch(r){if(r instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${r.message}`);throw r}}async function pr(e){if(!e?.countryCode)return null;try{let t=await U.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&&_d(n.regions,e.region))o=2;if(e.postalCode&&n.postal_codes&&_d(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 Dd(e,t){let r=await pr(t);if(r==null)return;return no(e,r)}async function Pd(e,t){return await pr(t)===e}function _d(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 Fd(){try{return(await U.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 kd(e){try{return await U.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",e).orderBy("weight_from").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${t.message}`);throw t}}var{randomUUIDv7:Ad}=globalThis.Bun;import{db as oo}from"@stacksjs/database";import{db as ct}from"@stacksjs/database";async function Td(){return await ct.selectFrom("shipping_zones").selectAll().execute()}async function fr(e){return await ct.selectFrom("shipping_zones").where("id","=",e).selectAll().executeTakeFirst()}function Ed(){try{return ct.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 Sd(){try{return await ct.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(e){if(e instanceof Error)throw TypeError(`Failed to get active shipping zones: ${e.message}`);throw e}}async function Cd(e){try{return await ct.selectFrom("shipping_zones").selectAll().where("countries","like",`%${e}%`).where("status","=","active").orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${t.message}`);throw t}}class C extends TypeError{constructor(e){super(e);this.name="ShippingRateInputError"}}function dt(e,t,r){return Number(e[r]??t?.[r])}async function be(e,t){let r=dt(e,t,"shipping_method_id"),n=dt(e,t,"shipping_zone_id"),o=dt(e,t,"weight_from"),a=dt(e,t,"weight_to"),s=dt(e,t,"rate");if(!Number.isSafeInteger(r)||r<1)throw new C("Shipping method must be a positive integer.");if(!Number.isSafeInteger(n)||n<1)throw new C("Shipping zone must be a positive integer.");if(!Number.isFinite(o)||o<0)throw new C("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<o)throw new C("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new C("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([dr(r),fr(n)]);if(!i)throw new C(`Shipping method ${r} was not found.`);if(!u)throw new C(`Shipping zone ${n} was not found.`);if(Number(u.shipping_method_id)!==r)throw new C(`Shipping zone ${n} is not assigned to shipping method ${r}.`)}async function Id(e){try{let t=te(e),r=Number(t.shipping_method_id),n=Number(t.shipping_zone_id);await be(t);let o=Ad(),a={...t,shipping_method_id:r,shipping_zone_id:n,uuid:o};await oo.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await oo.selectFrom("shipping_rates").where("uuid","=",o).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return s}catch(t){if(t instanceof C)throw t;if(t instanceof Error)throw TypeError(`Failed to create shipping rate: ${t.message}`);throw t}}async function Md(e){if(!e.length)return 0;try{for(let n of e){let o=te(n);await be(o)}let t=e.map((n)=>({...te(n),uuid:Ad()})),r=await oo.insertInto("shipping_rates").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof C)throw t;if(t instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${t.message}`);throw t}}import{db as lt}from"@stacksjs/database";import{formatDate as wr}from"@stacksjs/orm";async function Nd(e,t){try{if(!e)throw Error("Shipping rate ID is required for update");let r=await lt.selectFrom("shipping_rates").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=te(t);await be(n,r);let o=await lt.updateTable("shipping_rates").set({...n,updated_at:wr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!o)return;return o}catch(r){if(r instanceof C)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function Jd(e){if(!e.length)return 0;try{let t=0;for(let{id:r,data:n}of e){let o=await lt.updateTable("shipping_rates").set({...te(n),updated_at:wr(new Date)}).where("id","=",r).executeTakeFirst();if(d(o)>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 Bd(e,t){try{let r=await lt.updateTable("shipping_rates").set({...te(t),updated_at:wr(new Date)}).where("shipping_zone_id","=",e).executeTakeFirst();return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function Od(e,t){try{let r=await lt.updateTable("shipping_rates").set({...te(t),updated_at:wr(new Date)}).where("shipping_method_id","=",e).executeTakeFirst();return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var Dr={};y(Dr,{ARRIVAL_RADIUS_METERS:()=>io,NEARBY_RADIUS_METERS:()=>so,assignStop:()=>$d,bearingInDegrees:()=>tr,broadcastToChannel:()=>re,completeStop:()=>Ld,distanceInMeters:()=>ue,emitDeliveryArrived:()=>xr,emitDeliveryAssigned:()=>gr,emitDeliveryCompleted:()=>Rr,emitDeliveryFailed:()=>vr,emitDeliveryNearby:()=>_r,emitDeliveryPosition:()=>hr,emitDeliveryStarted:()=>br,estimateSecondsRemaining:()=>rr,failStop:()=>zd,hasCoordinates:()=>at,isWithin:()=>Jc,orderTrackingChannel:()=>ce,recordDriverPing:()=>Ud,routeTrackingChannel:()=>ao,startRoute:()=>jd,startStop:()=>Wd});function ce(e){return`order.${e}`}function ao(e){return`delivery-route.${e}`}async function Ie(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 re(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 hr(e,t,r){await Promise.all([...e.map((n)=>re(ce(n),"delivery:position",r)),t==null?Promise.resolve():re(ao(t),"delivery:position",r)])}async function gr(e){if(await Ie("delivery:assigned",{stop:e}),e.order_id!=null)await re(ce(e.order_id),"delivery:assigned",{stop:e})}async function br(e){if(await Ie("delivery:started",{stop:e}),e.order_id!=null)await re(ce(e.order_id),"delivery:started",{stop:e})}async function _r(e,t,r){if(await Ie("delivery:nearby",{stop:e,distanceMeters:t,etaSeconds:r}),e.order_id!=null)await re(ce(e.order_id),"delivery:nearby",{stop:e,distanceMeters:t,etaSeconds:r})}async function xr(e){if(await Ie("delivery:arrived",{stop:e}),e.order_id!=null)await re(ce(e.order_id),"delivery:arrived",{stop:e})}async function Rr(e){if(await Ie("delivery:completed",{stop:e}),e.order_id!=null)await re(ce(e.order_id),"delivery:completed",{stop:e})}async function vr(e,t){await Ie("delivery:failed",{stop:e,reason:t})}var{randomUUIDv7:Ip}=globalThis.Bun;import{db as W}from"@stacksjs/database";var so=400,io=60,Mp=250;async function Ud(e){let t=e.recordedAt??new Date().toISOString(),r=typeof e.accuracy!=="number"||e.accuracy<=Mp,n=await W.selectFrom("drivers").where("id","=",e.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!n)throw Error(`Unknown driver: ${e.driverId}`);let o=at(n)?{latitude:n.latitude,longitude:n.longitude}:null,a=typeof e.heading==="number"?e.heading:o?tr(o,e):null,s=await Np(e.driverId),i=s?await Jp(s.id):null,u=null,c=null,l=!1,m=!1,p=i&&at({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&p)u=Math.round(ue(e,p)),c=rr(u,e.speed??0),m=u<=io&&i.arrived_at==null,l=!m&&u<=so&&i.status==="en_route"&&i.notified_nearby_at==null;let w=await Bp({driverId:e.driverId,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 W.updateTable("drivers").set({latitude:e.latitude,longitude:e.longitude,heading:a,speed:e.speed??0,last_ping_at:t}).where("id","=",e.driverId).execute();if(i&&(u!=null||c!=null))await W.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 hr(i?.order_id==null?[]:[i.order_id],s?.id??null,{driverId:e.driverId,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(l&&i)await W.updateTable("delivery_stops").set({notified_nearby_at:t}).where("id","=",i.id).execute(),await _r(i,u,c);if(m&&i)await W.updateTable("delivery_stops").set({status:"arrived",arrived_at:t}).where("id","=",i.id).execute(),await xr({...i,status:"arrived",arrived_at:t});return{pingId:w,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:l,crossedArrival:m}}async function Np(e){return await W.selectFrom("delivery_routes").where("driver_id","=",e).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function Jp(e){let t=await W.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 Bp(e){let t=Ip();return await W.insertInto("driver_pings").values({uuid:t,driver_id:e.driverId,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 W.selectFrom("driver_pings").where("uuid","=",t).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:Op}=globalThis.Bun;import{db as k}from"@stacksjs/database";async function $d(e){let t=Op(),r=e.sequence??await $p(e.deliveryRouteId);await k.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}).executeTakeFirst();let n=await Lp(t);if(n)await gr(n);return n??{}}async function Wd(e){await k.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",e).execute();let t=await co(e);if(!t)return null;if(t.order_id!=null)await uo(t.order_id,"OUT_FOR_DELIVERY");return await br(t),t}async function Ld(e,t){let r=new Date().toISOString();await k.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await Wp(e)?{}:{arrived_at:r},...t?{notes:t}:{}}).where("id","=",e).execute();let n=await co(e);if(!n)return null;if(n.order_id!=null)await uo(n.order_id,"DELIVERED");return await Rr(n),await Gd(n.delivery_route_id),n}async function zd(e,t){await k.updateTable("delivery_stops").set({status:"failed",notes:t}).where("id","=",e).execute();let r=await co(e);if(!r)return null;if(r.order_id!=null)await uo(r.order_id,"SHIPPED");return await vr(r,t),await Gd(r.delivery_route_id),r}async function jd(e){await k.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",e).execute()}async function Gd(e){if(e==null)return;if(await k.selectFrom("delivery_stops").where("delivery_route_id","=",e).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await k.selectFrom("delivery_routes").where("id","=",e).select(["driver_id"]).executeTakeFirst();if(await k.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",e).execute(),r?.driver_id!=null)await k.updateTable("drivers").set({status:"active"}).where("id","=",r.driver_id).execute()}async function uo(e,t){let r=await k.selectFrom("orders").where("id","=",e).select(["id","status"]).executeTakeFirst();if(!r)return;let n=await Promise.resolve().then(() => (Pe(),gs)),{canTransition:o,emitForStatus:a}=n,s=Up(r.status,t,o);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 k.updateTable("orders").set({status:i}).where("id","=",e).execute(),await a(i,{...r,status:i})}function Up(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 $p(e){return(await k.selectFrom("delivery_stops").where("delivery_route_id","=",e).select(["sequence"]).execute()).reduce((r,n)=>Math.max(r,n.sequence??0),0)+1}async function Wp(e){return(await k.selectFrom("delivery_stops").where("id","=",e).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function co(e){return await k.selectFrom("delivery_stops").where("id","=",e).selectAll().executeTakeFirst()??null}async function Lp(e){return await k.selectFrom("delivery_stops").where("uuid","=",e).selectAll().executeTakeFirst()??null}var Tr={};y(Tr,{bulkDestroy:()=>Zd,bulkSoftDelete:()=>Kd,bulkStore:()=>Yd,destroy:()=>Vd,fetchAll:()=>Td,fetchById:()=>fr,formatZoneOptions:()=>Ed,getActiveShippingZones:()=>Sd,getZonesByCountry:()=>Cd,softDelete:()=>qd,store:()=>Qd,update:()=>Xd,updateCountries:()=>tl,updateRegionsAndPostalCodes:()=>rl,updateStatus:()=>el});import{db as Pr}from"@stacksjs/database";async function Vd(e){try{let t=await Pr.deleteFrom("shipping_zones").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping zone: ${t.message}`);throw t}}async function qd(e){try{let t=await Pr.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${t.message}`);throw t}}async function Zd(e){if(!e.length)return 0;try{let t=await Pr.deleteFrom("shipping_zones").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping zones: ${t.message}`);throw t}}async function Kd(e){if(!e.length)return 0;try{let t=await Pr.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${t.message}`);throw t}}var{randomUUIDv7:Hd}=globalThis.Bun;import{db as lo}from"@stacksjs/database";async function Qd(e){try{let t=Hd(),r={...tt(e),uuid:t};await lo.insertInto("shipping_zones").values(r).executeTakeFirst();let n=await lo.selectFrom("shipping_zones").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created shipping zone");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping zone: ${t.message}`);throw t}}async function Yd(e){if(!e.length)return 0;try{let t=e.map((n)=>({...tt(n),uuid:Hd()})),r=await lo.insertInto("shipping_zones").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${t.message}`);throw t}}import{db as Fr}from"@stacksjs/database";import{formatDate as kr}from"@stacksjs/orm";async function Xd(e,t){try{if(!e)throw Error("Shipping zone ID is required for update");let r=await Fr.updateTable("shipping_zones").set({...tt(t),updated_at:kr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function el(e,t){try{let r=await Fr.updateTable("shipping_zones").set({status:t,updated_at:kr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function tl(e,t){try{let r=await Fr.updateTable("shipping_zones").set({countries:t,updated_at:kr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function rl(e,t,r){try{let n={updated_at:kr(new Date)};if(t!==void 0)n.regions=t;if(r!==void 0)n.postal_codes=r;let o=await Fr.updateTable("shipping_zones").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update regions and postal codes");return o}catch(n){if(n instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${n.message}`);throw n}}var zp={digital:Yt,drivers:er,geocoding:or,licenses:ir,methods:lr,rates:yr,routes:Ht,tracking:Dr,zones:Tr},jp=zp;var wo={};y(wo,{activeTaxRates:()=>po,breakdownFor:()=>fo,bulkDestroy:()=>sl,bulkStore:()=>pl,destroy:()=>al,fetchAll:()=>cl,fetchById:()=>ul,store:()=>ml,taxFor:()=>nl,update:()=>fl,updateDefaultStatus:()=>hl,updateRate:()=>yl,updateStatus:()=>wl});import{db as Gp}from"@stacksjs/database";function Vp(e){let t=Number(e);return Number.isFinite(t)?t/100:0}async function po(e={}){let t=Gp.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 fo(e,t,r={}){let n=Math.max(0,Math.round(e)),o=[],a=0,s=0;for(let i of t){let u=Vp(i.rate),c=Math.round(n*u),l=Boolean(r.exempt&&i.exemptible);if(l)s+=c;else a+=c;o.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:l?0:c,exempted:l})}return{taxable:n,components:o,tax:a,exempted:s}}async function nl(e,t={}){return fo(e,await po(t),t)}import{db as ol}from"@stacksjs/database";async function al(e){try{let t=await ol.deleteFrom("tax_rates").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete tax rate: ${t.message}`);throw t}}async function sl(e){if(!e.length)return 0;try{let t=await ol.deleteFrom("tax_rates").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete tax rates: ${t.message}`);throw t}}import{db as il}from"@stacksjs/database";async function ul(e){return await il.selectFrom("tax_rates").where("id","=",e).selectAll().executeTakeFirst()}async function cl(){return await il.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:dl}=globalThis.Bun;import{db as ll}from"@stacksjs/database";async function ml(e){try{return await ll.transaction(async(t)=>{let r={...e,uuid:dl()};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 n})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create tax rate: ${t.message}`);throw t}}async function pl(e){if(!e.length)return 0;try{return await ll.transaction(async(t)=>{let r=0;for(let n of e){let o={...n,uuid:dl()};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 Er}from"@stacksjs/database";import{formatDate as Sr}from"@stacksjs/orm";async function fl(e,t){try{if(!e)throw Error("Tax rate ID is required for update");return await Er.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=Sr(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 s})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function wl(e,t){try{let r=await Er.updateTable("tax_rates").set({status:t,updated_at:Sr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function yl(e,t){try{let r=await Er.updateTable("tax_rates").set({rate:t,updated_at:Sr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function hl(e,t){try{return await Er.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",e).executeTakeFirst())return!1;let o=Sr(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 xo={};y(xo,{default:()=>rf,products:()=>Ar,restaurant:()=>Ne});var Ar={};y(Ar,{bulkDestroy:()=>bl,bulkStore:()=>Jl,destroy:()=>gl,fetchAll:()=>_l,fetchById:()=>mt,fetchCancelledBetweenDates:()=>kl,fetchConversionRates:()=>Sl,fetchCountBetweenDates:()=>Cl,fetchCountByAllQuantities:()=>Dl,fetchCountByDate:()=>Rl,fetchCountByDateGrouped:()=>Al,fetchCountByQuantity:()=>vl,fetchCountBySource:()=>xl,fetchCountByStatus:()=>El,fetchNotifiedBetweenDates:()=>Pl,fetchPurchasedBetweenDates:()=>Fl,fetchWaiting:()=>Tl,store:()=>Nl,update:()=>Cr,updatePartySize:()=>Ol,updateStatus:()=>Bl});import{db as yo}from"@stacksjs/database";async function gl(e){try{let t=await yo.selectFrom("waitlist_products").where("id","=",e).selectAll().executeTakeFirst();if(!t)return;return await yo.deleteFrom("waitlist_products").where("id","=",e).execute(),t}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete waitlist product: ${t.message}`);throw t}}async function bl(e){if(!e.length)return 0;try{let t=await yo.deleteFrom("waitlist_products").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${t.message}`);throw t}}import{db as _}from"@stacksjs/database";import{formatDate as P}from"@stacksjs/orm";async function mt(e){return await _.selectFrom("waitlist_products").where("id","=",e).selectAll().executeTakeFirst()}async function _l(){return await _.selectFrom("waitlist_products").selectAll().execute()}async function xl(e,t){let r=_.selectFrom("waitlist_products").select(["source",_.fn.count("id").as("count")]).groupBy("source");if(e&&t){let o=P(e),a=P(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 Rl(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=P(t),o=P(r);return(await _.selectFrom("waitlist_products").select(_.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",o).executeTakeFirst())?.count??0}async function vl(e){return(await _.selectFrom("waitlist_products").select(_.fn.count("id").as("count")).where("quantity","=",e).executeTakeFirst())?.count??0}async function Dl(e,t){let r=_.selectFrom("waitlist_products").select(["quantity",_.fn.count("id").as("count")]).groupBy("quantity");if(e&&t){let o=P(e),a=P(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 Pl(e,t){let r=P(e),n=P(t);return await _.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",n).whereNotNull("notified_at").execute()}async function Fl(e,t){let r=P(e),n=P(t);return await _.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",n).whereNotNull("purchased_at").execute()}async function kl(e,t){let r=P(e),n=P(t);return await _.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",n).whereNotNull("cancelled_at").execute()}async function Tl(){return await _.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function El(e,t,r){let n=_.selectFrom("waitlist_products").select(_.fn.count("id").as("count")).where("status","=",e);if(t&&r){let a=P(t),s=P(r);n=n.where("created_at",">=",a).where("created_at","<=",s)}return(await n.executeTakeFirst())?.count??0}async function Sl(e,t){let r=_.selectFrom("waitlist_products").select(["status",_.fn.count("id").as("count")]).groupBy("status");if(e&&t){let u=P(e),c=P(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=n.find((u)=>u.status==="purchased")?.count??0,s=o>0?a/o*100:0,i=n.reduce((u,{status:c,count:l})=>(u[c]={count:l,percentage:o>0?l/o*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function Cl(e,t){let r=P(e),n=P(t);return(await _.selectFrom("waitlist_products").select(_.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",n).executeTakeFirst())?.count??0}async function Al(e,t){let r=_.selectFrom("waitlist_products").select(["created_at"]);if(e&&t){let a=P(e),s=P(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:Ml}=globalThis.Bun;import{db as ho}from"@stacksjs/database";import{formatDate as Il}from"@stacksjs/orm";var qp={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Zp(e){return typeof e==="number"||e instanceof Date?Il(e):e}function pt(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]=Zp(r[o]);let n=qp[r.status];if(n&&r[n]===void 0&&!t[n])r[n]=Il(new Date);return r}async function Nl(e){try{let t=Ml(),r={...pt(e),uuid:t,status:e.status||"waiting"};await ho.insertInto("waitlist_products").values(r).executeTakeFirst();let n=await ho.selectFrom("waitlist_products").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create waitlist product");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create waitlist product: ${t.message}`);throw t}}async function Jl(e){if(!e.length)return 0;try{let t=e.map((n)=>({...pt(n),status:n.status||"waiting",uuid:Ml()})),r=await ho.insertInto("waitlist_products").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${t.message}`);throw t}}import{db as Kp}from"@stacksjs/database";import{formatDate as Hp}from"@stacksjs/orm";async function Cr(e,t){try{if(!e)throw Error("Waitlist product ID is required for update");let r=await mt(e);if(!r)return;await Kp.updateTable("waitlist_products").set({...pt(t,r),updated_at:Hp(new Date)}).where("id","=",e).execute();let n=await mt(e);if(!n)return;return n}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function Bl(e,t){return await Cr(e,{status:t})}async function Ol(e,t){return await Cr(e,{quantity:t})}var Ne={};y(Ne,{bulkDestroy:()=>$l,bulkStore:()=>im,destroy:()=>Ul,fetchAll:()=>Wl,fetchAverageWaitTimes:()=>Hl,fetchBetweenDates:()=>Vl,fetchById:()=>ft,fetchConversionRates:()=>Kl,fetchCountByAllPartySizes:()=>Gl,fetchCountByDate:()=>zl,fetchCountByPartySize:()=>jl,fetchCountByTablePreference:()=>Ll,fetchCurrentWaitTimes:()=>rm,fetchNoShowStats:()=>tm,fetchSeatedBetweenDates:()=>ql,fetchSeatedStats:()=>nm,fetchSeatingRate:()=>em,fetchTablesTurnedToday:()=>Xl,fetchTimeSeriesStats:()=>om,fetchWaiting:()=>Zl,fetchWaitingWithPartySizes:()=>Yl,fetchWaitingWithQuotedTimes:()=>Ql,store:()=>sm,update:()=>Me,updatePartySize:()=>cm,updateQueuePosition:()=>lm,updateStatus:()=>um,updateWaitTimes:()=>dm});import{db as go}from"@stacksjs/database";async function Ul(e){try{let t=await go.selectFrom("waitlist_restaurants").where("id","=",e).selectAll().executeTakeFirst();if(!t)return;return await go.deleteFrom("waitlist_restaurants").where("id","=",e).execute(),t}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${t.message}`);throw t}}async function $l(e){if(!e.length)return 0;try{let t=await go.deleteFrom("waitlist_restaurants").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${t.message}`);throw t}}import{db as h}from"@stacksjs/database";import{formatDate as N}from"@stacksjs/orm";async function ft(e){return await h.selectFrom("waitlist_restaurants").where("id","=",e).selectAll().executeTakeFirst()}async function Wl(){return await h.selectFrom("waitlist_restaurants").selectAll().execute()}async function Ll(){return(await h.selectFrom("waitlist_restaurants").select(["table_preference",h.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((t,{table_preference:r,count:n})=>(t[r]=n,t),{})}async function zl(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=N(t),o=N(r);return(await h.selectFrom("waitlist_restaurants").select(h.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",o).executeTakeFirst())?.count??0}async function jl(e){return(await h.selectFrom("waitlist_restaurants").select(h.fn.count("id").as("count")).where("party_size","=",e).executeTakeFirst())?.count??0}async function Gl(){return(await h.selectFrom("waitlist_restaurants").select(["party_size",h.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((t,{party_size:r,count:n})=>(t[r]=n,t),{})}async function Vl(e,t){let r=N(e),n=N(t);return await h.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",n).execute()}async function ql(e,t){let r=N(e),n=N(t);return await h.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",n).where("status","=","seated").execute()}async function Zl(){return await h.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function Kl(){let e=await h.selectFrom("waitlist_restaurants").select(["status",h.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 Hl(){let e=await h.selectFrom("waitlist_restaurants").select([h.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),h.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 Ql(){let e=await h.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 Yl(){let e=await h.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 Xl(){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=N(t),o=N(r),a=await h.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,p)=>m+p.party_size,0),u=s>0?i/s:0,c=a.reduce((m,p)=>(m[p.table_preference]=(m[p.table_preference]||0)+1,m),{}),l=a.reduce((m,p)=>(m[p.party_size]=(m[p.party_size]||0)+1,m),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:l}}async function em(e,t){let r=N(e),n=N(t),o=await h.selectFrom("waitlist_restaurants").select(["status",h.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",n).groupBy("status").execute(),a=o.reduce((c,{count:l})=>c+l,0),s=o.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=o.reduce((c,{status:l,count:m})=>(c[l]={count:m,percentage:a>0?m/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function tm(e,t){let r=N(e),n=N(t),o=h.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",n),a=await h.selectFrom("waitlist_restaurants").select(h.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((b,R)=>b+(R.quoted_wait_time??0),0),l=i>0?c/i:0,m=s.reduce((b,R)=>b+R.party_size,0),p=i>0?m/i:0,w=s.reduce((b,R)=>(b[R.table_preference]=(b[R.table_preference]||0)+1,b),{}),x=s.reduce((b,R)=>(b[R.party_size]=(b[R.party_size]||0)+1,b),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:l,averagePartySize:p,breakdownByTablePreference:w,breakdownByPartySize:x}}async function rm(){let e=await h.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 nm(){let e=Date.now()-86400000,t=await h.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 om(){return(await h.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:am}=globalThis.Bun;import{db as _o}from"@stacksjs/database";import{formatDate as bo}from"@stacksjs/orm";var Qp={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function Yp(e){if(typeof e==="number")return bo(e<=2147483647?e*1000:e);if(e instanceof Date)return bo(e);return e}function wt(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]=Yp(r[o]);let n=Qp[r.status];if(n&&r[n]===void 0&&!t[n])r[n]=bo(new Date);return r}async function sm(e){try{let t=am(),r={...wt(e),status:e.status||"waiting",uuid:t};await _o.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let n=await _o.selectFrom("waitlist_restaurants").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create restaurant waitlist entry");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${t.message}`);throw t}}async function im(e){if(!e.length)return 0;try{let t=e.map((n)=>({...wt(n),status:n.status||"waiting",uuid:am()})),r=await _o.insertInto("waitlist_restaurants").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${t.message}`);throw t}}import{db as Xp}from"@stacksjs/database";import{formatDate as ef}from"@stacksjs/orm";async function Me(e,t){try{if(!e)throw Error("Restaurant waitlist entry ID is required for update");let r=await ft(e);if(!r)return;await Xp.updateTable("waitlist_restaurants").set({...wt(t,r),updated_at:ef(new Date)}).where("id","=",e).execute();let n=await ft(e);if(!n)return;return n}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function um(e,t){return await Me(e,{status:t})}async function cm(e,t){return await Me(e,{party_size:t})}async function dm(e,t,r){return await Me(e,{quoted_wait_time:t,...r===void 0?{}:{actual_wait_time:r}})}async function lm(e,t){return await Me(e,{queue_position:t})}var tf={products:Ar,restaurant:Ne},rf=tf;var nf={auctions:sn,coupons:un,customers:cn,devices:fn,errors:hn,giftCards:_n,orders:En,payments:Sn,products:Bn,receipts:Ln,restaurant:Ne,shippings:mo,tax:wo,waitlists:xo},UD=nf;export{sn as auctions,nf as commerce,un as coupons,cn as customers,UD as default,fn as devices,hn as errors,_n as giftCards,En as orders,Sn as payments,Bn as products,Ln as receipts,Ne as restaurant,mo as shippings,wo as tax,xo as waitlists};
28
+ AND COALESCE(refund_amount, 0) + ${n(5)} <= amount`,[t,t,o,e,t]);if(Number(s?.numUpdatedRows??s?.[0]?.numUpdatedRows??s?.numAffectedRows??s?.affectedRows??s?.[0]?.affectedRows??s?.changes??0)>0){let m=await ye(e);if(m)return m;throw Error(`Payment with ID ${e} disappeared during refund`)}let u=await ye(e);if(!u)throw Error(`Payment with ID ${e} not found`);let c=String(u.status||"");if(!Am.has(c))throw Error(`Payment status ${c||"unknown"} cannot be refunded`);let l=u,p=Number(u.amount||0)-Number(l.refundAmount??l.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${p} minor units`)}var jn={};y(jn,{categories:()=>Ot,default:()=>Gm,items:()=>Ut,manufacturers:()=>$t,reviews:()=>Wt,units:()=>zt,variants:()=>Gt});var Ot={};y(Ot,{bulkRemove:()=>Fi,compareCategoryGrowth:()=>Di,deactivate:()=>Ti,deactivateChildCategories:()=>Ei,fetchActive:()=>gi,fetchAll:()=>Bn,fetchByDisplayOrder:()=>xi,fetchById:()=>E,fetchByName:()=>hi,fetchCategoryTree:()=>vi,fetchChildCategories:()=>_i,fetchRootCategories:()=>bi,fetchStats:()=>Ri,findOrCreateByName:()=>Ci,remove:()=>Pi,removeChildCategories:()=>ki,store:()=>On,update:()=>Ai,updateActiveStatus:()=>Mi,updateDisplayOrder:()=>Ii,updateParent:()=>Ni});import{db as Te}from"@stacksjs/database";import{db as v}from"@stacksjs/database";import{formatDate as Qe}from"@stacksjs/orm";async function Bn(){return await v.selectFrom("categories").selectAll().execute()}async function E(e){return await v.selectFrom("categories").where("id","=",e).selectAll().executeTakeFirst()}async function hi(e){return await v.selectFrom("categories").where("name","=",e).selectAll().executeTakeFirst()}async function gi(){return await v.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function bi(){return await v.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function _i(e){return await v.selectFrom("categories").where("parent_category_id","=",e).where("is_active","=",!0).selectAll().execute()}async function xi(e=!0){let t=v.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 Ri(){let e=await v.selectFrom("categories").select(v.fn.count("id").as("count")).executeTakeFirst(),t=await v.selectFrom("categories").where("is_active","=",!0).select(v.fn.count("id").as("count")).executeTakeFirst(),r=await v.selectFrom("categories").whereNull("parent_category_id").select(v.fn.count("id").as("count")).executeTakeFirst(),n=await v.selectFrom("categories").whereNotNull("image_url").select(v.fn.count("id").as("count")).executeTakeFirst(),o=new Date;o.setDate(o.getDate()-30);let a=Qe(o),s=await v.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await v.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",v.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 Di(e=30){let t=new Date,r=Qe(t),n=new Date;n.setDate(t.getDate()-e);let o=Qe(n),a=new Date(n);a.setDate(a.getDate()-1);let s=Qe(a),i=new Date(a);i.setDate(a.getDate()-e);let u=Qe(i),c=await v.selectFrom("categories").select(v.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",r).executeTakeFirst(),l=await v.selectFrom("categories").select(v.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),p=Number(c?.count||0),m=Number(l?.count||0),f=p-m,h=m!==0?f/m*100:p>0?100:0;return{current_period:p,previous_period:m,difference:f,percentage_change:h,days_range:e}}async function vi(){let e=await Bn(),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 Pi(e){let t=await Te.deleteFrom("categories").where("id","=",e).executeTakeFirst();return d(t)>0}async function Fi(e){if(!e.length)return 0;let t=await Te.deleteFrom("categories").where("id","in",e).executeTakeFirst();return d(t)}async function ki(e){let t=await Te.deleteFrom("categories").where("parent_category_id","=",e).executeTakeFirst();return d(t)}async function Ti(e){if(!await E(e))throw Error(`Category with ID ${e} not found`);return!!await Te.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",e).executeTakeFirst()}async function Ei(e){let t=await Te.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",e).execute();return Number(t)||0}var{randomUUIDv7:Im}=globalThis.Bun;import{db as Si}from"@stacksjs/database";import{HttpError as Jt}from"@stacksjs/error-handling";import{isUniqueViolation as Mm}from"@stacksjs/orm";import{slug as Nm}from"@stacksjs/strings";async function On(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 Jt(422,"Parent category ID must be a positive integer");if(t&&!await E(t))throw new Jt(422,`Parent category with ID ${e.parent_category_id} not found`);let r={...e,uuid:Im(),is_active:e.is_active??!0,parent_category_id:e.parent_category_id||null},n=await Si.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create category");return n}catch(t){if(t instanceof Jt)throw t;if(Mm(t))throw new Jt(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 Ci(e){if(!e.name)throw Error("Name is required");let t=await Si.selectFrom("categories").selectAll().where("name","=",e.name).executeTakeFirst();if(t)return t;let r={name:e.name,slug:Nm(e.name),is_active:e.is_active??!0,display_order:0};return await On(r)}import{db as Ye}from"@stacksjs/database";import{HttpError as Ee}from"@stacksjs/error-handling";import{formatDate as Bt,isUniqueViolation as Jm}from"@stacksjs/orm";async function Ai(e,t){if(!await E(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 Ee(422,"Parent category ID must be a positive integer");if(n===e)throw new Ee(422,"A category cannot be its own parent");if(n&&!await E(n))throw new Ee(422,`Parent category with ID ${t.parent_category_id} not found`);if(n&&await Ji(e,String(n)))throw new Ee(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 Ye.updateTable("categories").set({...t,...n,updated_at:Bt(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!o)return;return o}catch(n){if(n instanceof Ee)throw n;if(Jm(n))throw new Ee(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 Ii(e,t){if(!await E(e))throw Error(`Category with ID ${e} not found`);try{return await Ye.updateTable("categories").set({display_order:t,updated_at:Bt(new Date)}).where("id","=",e).execute(),await E(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category display order: ${n.message}`);throw n}}async function Mi(e,t){if(!await E(e))throw Error(`Category with ID ${e} not found`);try{return await Ye.updateTable("categories").set({is_active:t,updated_at:Bt(new Date)}).where("id","=",e).execute(),await E(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category active status: ${n.message}`);throw n}}async function Ni(e,t){if(!await E(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 E(n))throw Error(`Parent category with ID ${t} not found`);if(await Ji(e,t))throw Error("This operation would create a circular reference in the category hierarchy")}try{let n={updated_at:Bt(new Date)};if(t===null)await Ye.updateTable("categories").set({...n,parent_category_id:null}).where("id","=",e).execute();else await Ye.updateTable("categories").set({...n,parent_category_id:t}).where("id","=",e).execute();return await E(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category parent: ${n.message}`);throw n}}async function Ji(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 E(r),a=o?.parent_category_id??o?.parentCategoryId;if(!o||!a)return!1;r=Number(a)}return!1}var Ut={};y(Ut,{bulkDestroy:()=>Ui,bulkStore:()=>Vi,destroy:()=>Oi,fetchAll:()=>$i,fetchById:()=>re,fetchTopProducts:()=>Li,store:()=>Gi,update:()=>qi,updateAvailability:()=>Zi,updateInventory:()=>Ki});import{db as Bi}from"@stacksjs/database";async function Oi(e){try{let t=await Bi.deleteFrom("products").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product item: ${t.message}`);throw t}}async function Ui(e){if(!e.length)return 0;try{let t=await Bi.deleteFrom("products").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product items: ${t.message}`);throw t}}import{db as te,sql as Bm}from"@stacksjs/database";async function re(e){let t=await te.selectFrom("products").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=null,n=null;if(t.manufacturer_id)r=await te.selectFrom("manufacturers").where("id","=",t.manufacturer_id).selectAll().executeTakeFirst();if(t.category_id)n=await te.selectFrom("categories").where("id","=",t.category_id).selectAll().executeTakeFirst();return{...t,manufacturer:r,category:n}}return}async function $i(){let e=await te.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=te.selectFrom("manufacturers"),o=te.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,l)=>(c[l.id]=l,c),{}),u=s.reduce((c,l)=>(c[l.id]=l,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 Wi(e){try{return await te.selectFrom("products").selectAll().where("uuid","=",e).executeTakeFirst()}catch(t){if(t instanceof Error)throw TypeError(`Failed to get product by UUID: ${t.message}`);throw t}}async function Li(e=5){try{return(await te.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",te.fn.sum("order_items.quantity").as("units_sold"),Bm`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:ji}=globalThis.Bun;import{db as zi}from"@stacksjs/database";async function Gi(e){try{let t={...e,uuid:ji()},r=await zi.insertInto("products").values(t).executeTakeFirst();if(!r)throw Error("Failed to create product item");let n=Q(r),o=n!==void 0?await re(n):await Wi(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 Vi(e){if(!e.length)return 0;let t=0;try{return await zi.transaction(async(r)=>{for(let n of e){let o={...n,uuid:ji()};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 Un}from"@stacksjs/database";import{formatDate as $n}from"@stacksjs/orm";async function qi(e,t){try{if(!e)throw Error("Product item ID is required for update");let r=await Un.updateTable("products").set({...t,updated_at:$n(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function Zi(e,t){if(!await re(e))throw Error(`Product item with ID ${e} not found`);try{return await Un.updateTable("products").set({is_available:t,updated_at:$n(new Date)}).where("id","=",e).execute(),await re(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update product item availability: ${n.message}`);throw n}}async function Ki(e,t){let r=await re(e);if(!r)throw Error(`Product item with ID ${e} not found`);let n={updated_at:$n(new Date)};if(t!==void 0)n.inventory_count=t;if(Object.keys(n).length===1)return r;try{return await Un.updateTable("products").set(n).where("id","=",e).execute(),await re(e)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update inventory information: ${o.message}`);throw o}}var $t={};y($t,{bulkDestroy:()=>Yi,bulkStore:()=>cu,destroy:()=>Qi,fetchAll:()=>Xi,fetchByCountry:()=>nu,fetchById:()=>eu,fetchByUuid:()=>tu,fetchFeatured:()=>ru,fetchWithProductCount:()=>ou,store:()=>uu,update:()=>lu,updateByUuid:()=>mu,updateFeaturedStatus:()=>pu});import{db as Hi}from"@stacksjs/database";async function Qi(e){try{let t=await Hi.deleteFrom("manufacturers").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete order: ${t.message}`);throw t}}async function Yi(e){if(!e.length)return 0;try{let t=await Hi.deleteFrom("manufacturers").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete orders: ${t.message}`);throw t}}import{db as ne}from"@stacksjs/database";function Xi(){return ne.selectFrom("manufacturers").selectAll().execute()}async function eu(e){return await ne.selectFrom("manufacturers").where("id","=",e).selectAll().executeTakeFirst()}async function tu(e){return await ne.selectFrom("manufacturers").where("uuid","=",e).selectAll().executeTakeFirst()}async function ru(e=10){return await ne.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(e).execute()}async function nu(e,t={}){let r=t.page||1,n=t.limit||2,o=await ne.selectFrom("manufacturers").select(ne.fn.count("id").as("total")).where("country","=",e).executeTakeFirst(),a=Number(o?.total||0),s=await ne.selectFrom("manufacturers").selectAll().where("country","=",e).limit(n).offset((r-1)*n).execute(),i=Math.ceil(a/n);return{data:s,paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function ou(e={}){let t=ne.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",ne.fn.count("p.id").as("product_count")]).groupBy("m.id"),t.execute()}var{randomUUIDv7:su}=globalThis.Bun;import{db as iu}from"@stacksjs/database";import{HttpError as au}from"@stacksjs/error-handling";import{isUniqueViolation as Om}from"@stacksjs/orm";async function uu(e){try{let t={...e,uuid:su(),featured:e.featured??!1},r=await iu.insertInto("manufacturers").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return r}catch(t){if(t instanceof au)throw t;if(Om(t))throw new au(409,"A manufacturer with this name already exists");if(t instanceof Error)throw Error(`Failed to create manufacturer: ${t.message}`);throw t}}async function cu(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:su(),featured:r.featured??!1};await iu.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 Wn}from"@stacksjs/database";import{HttpError as du}from"@stacksjs/error-handling";import{formatDate as Ln,isUniqueViolation as Um}from"@stacksjs/orm";async function lu(e,t){try{if(!e)throw Error("Manufacturer ID is required for update");let r=await Wn.updateTable("manufacturers").set({...t,updated_at:Ln(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof du)throw r;if(Um(r))throw new du(409,"A manufacturer with this name already exists");if(r instanceof Error)throw Error(`Failed to update manufacturer: ${r.message}`);throw r}}async function pu(e,t){try{let r=await Wn.updateTable("manufacturers").set({featured:t,updated_at:Ln(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function mu(e,t){try{let r=await Wn.updateTable("manufacturers").set({...t,updated_at:Ln(new Date)}).where("uuid","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var Wt={};y(Wt,{bulkDestroy:()=>yu,destroy:()=>wu,fetchAll:()=>gu,fetchApprovedByProductId:()=>xu,fetchById:()=>hu,fetchByProductId:()=>bu,fetchByUserId:()=>_u,fetchMostHelpfulByProductId:()=>Ru,fetchStats:()=>Fu,fetchStatsByProductIds:()=>ku,store:()=>Tu,update:()=>Cu,updateVotes:()=>Au});import{db as fu}from"@stacksjs/database";async function wu(e){try{let t=await fu.deleteFrom("reviews").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete review: ${t.message}`);throw t}}async function yu(e){if(!e.length)return 0;try{let t=await fu.deleteFrom("reviews").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete reviews: ${t.message}`);throw t}}import{db as Se}from"@stacksjs/database";async function hu(e){return await Se.selectFrom("reviews").where("id","=",e).selectAll().executeTakeFirst()}async function gu(){return await Se.selectFrom("reviews").selectAll().execute()}async function bu(e){return await Se.selectFrom("reviews").where("product_id","=",e).selectAll().execute()}async function _u(e){return await Se.selectFrom("reviews").where("customer_id","=",e).selectAll().execute()}async function xu(e){return await Se.selectFrom("reviews").where("product_id","=",e).where("is_approved","=",!0).selectAll().execute()}async function Ru(e){return await Se.selectFrom("reviews").where("product_id","=",e).orderBy("helpful_votes","desc").selectAll().execute()}import{db as Du}from"@stacksjs/database";function vu(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function Pu(e){let t=vu();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 Fu(e){let t=await Du.selectFrom("reviews").select(["rating"]).where("product_id","=",e).where("is_approved","=",!0).execute();return Pu(t)}async function ku(e){let t=new Map;for(let o of e)t.set(o,vu());if(e.length===0)return t;let r=await Du.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,Pu(a));return t}var{randomUUIDv7:$m}=globalThis.Bun;import{db as Wm}from"@stacksjs/database";function Lm(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 Tu(e){try{if(Lm(e))throw Error("A review needs a rating or something written: both were empty");let t={...e,uuid:$m(),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 Wm.insertInto("reviews").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return 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{asRow as jm,db as Eu}from"@stacksjs/database";import{formatDate as Su}from"@stacksjs/orm";async function Cu(e,t){try{if(!e)throw Error("Review ID is required for update");let r=await Eu.updateTable("reviews").set({...t,updated_at:Su(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function Au(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)`,a=await Eu.unsafe(`UPDATE "reviews" SET "${n}" = ${o}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[Su(new Date),e]).execute(),s=Array.isArray(a)?a[0]:a;if(!s)throw Error("Failed to update review votes");return jm(s)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update review votes: ${n.message}`);throw n}}var zt={};y(zt,{bulkDestroy:()=>Nu,bulkStore:()=>Wu,bulkUpdate:()=>Gu,destroy:()=>Mu,fetchAll:()=>Ou,fetchById:()=>Bu,formatUnitOptions:()=>Lu,getDefaultUnit:()=>ju,store:()=>$u,update:()=>zu,updateDefaultStatus:()=>Vu});import{db as Iu}from"@stacksjs/database";async function Mu(e){try{let t=await Iu.deleteFrom("product_units").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product unit: ${t.message}`);throw t}}async function Nu(e){if(!e.length)return 0;try{let t=await Iu.deleteFrom("product_units").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product units: ${t.message}`);throw t}}import{db as Ju}from"@stacksjs/database";async function Bu(e){return await Ju.selectFrom("product_units").where("id","=",e).selectAll().executeTakeFirst()}async function Ou(){return await Ju.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:Uu}=globalThis.Bun;import{db as Xe}from"@stacksjs/database";async function $u(e){try{return await Xe.transaction(async(t)=>{let r={...e,uuid:Uu()},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 n})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product unit: ${t.message}`);throw t}}async function Wu(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:Uu()},o=await Xe.insertInto("product_units").values(n).returningAll().executeTakeFirst();if(n.is_default&&n.type&&o)await Xe.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 Lu(e){try{let t=Xe.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 ju(e){try{return await Xe.selectFrom("product_units").selectAll().where("type","=",e).where("is_default","=",!0).executeTakeFirst()}catch(t){if(t instanceof Error)throw TypeError(`Failed to get default unit: ${t.message}`);throw t}}import{db as Lt}from"@stacksjs/database";import{formatDate as jt}from"@stacksjs/orm";async function zu(e,t){try{if(!e)throw Error("Product unit ID is required for update");return await Lt.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:jt(new Date)}).where("type","=",o).where("id","!=",e).execute();let s=await r.updateTable("product_units").set({...t,updated_at:jt(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!s)return;return s})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function Gu(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 Lt.updateTable("product_units").set({...o,updated_at:jt(new Date)}).where("id","=",n.id).executeTakeFirst(),s=o;if(s.is_default===!0&&s.type)await Lt.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",n.id).execute();if(Number(a.numUpdatedRows)>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 Vu(e,t){try{return await Lt.transaction(async(r)=>{let n=await r.selectFrom("product_units").select("type").where("id","=",e).executeTakeFirst();if(!n)return!1;let o=jt(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 Gt={};y(Gt,{bulkDestroy:()=>Ku,bulkStore:()=>rc,bulkUpdate:()=>uc,destroy:()=>Zu,fetchAll:()=>Yu,fetchById:()=>Qu,formatVariantOptions:()=>nc,generateVariantCombinations:()=>oc,store:()=>tc,update:()=>ic});import{db as qu}from"@stacksjs/database";async function Zu(e){try{let t=await qu.deleteFrom("product_variants").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product variant: ${t.message}`);throw t}}async function Ku(e){if(!e.length)return 0;try{let t=await qu.deleteFrom("product_variants").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product variants: ${t.message}`);throw t}}import{db as Hu}from"@stacksjs/database";async function Qu(e){return await Hu.selectFrom("product_variants").where("id","=",e).selectAll().executeTakeFirst()}async function Yu(){return await Hu.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:Xu}=globalThis.Bun;import{db as ec}from"@stacksjs/database";async function tc(e){try{let t={...e,uuid:Xu()},r=await ec.insertInto("product_variants").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return r}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product variant: ${t.message}`);throw t}}async function rc(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:Xu()};await ec.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 nc(e){if(!e||!e.length)return JSON.stringify([]);let t=e.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(t)}function oc(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 ac}from"@stacksjs/database";import{formatDate as sc}from"@stacksjs/orm";async function ic(e,t){try{let r=await ac.updateTable("product_variants").set({...t,updated_at:sc(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function uc(e){if(!e.length)return 0;let t=0;try{for(let r of e){if(!r.id)continue;let n=await ac.updateTable("product_variants").set({...r,updated_at:sc(new Date)}).where("id","=",r.id).executeTakeFirst();if(Number(n.numUpdatedRows)>0)t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var zm={categories:Ot,items:Ut,manufacturers:$t,reviews:Wt,units:zt,variants:Gt},Gm=zm;var Zn={};y(Zn,{bulkDestroy:()=>lc,bulkStore:()=>_c,destroy:()=>dc,fetchAll:()=>pc,fetchById:()=>Ce,fetchPageStats:()=>wc,fetchPrintJobStats:()=>mc,fetchPrintTimeStats:()=>yc,fetchPrintsPerHour:()=>hc,fetchSuccessRate:()=>fc,store:()=>bc,update:()=>xc,updatePrintJob:()=>Dc,updateStatus:()=>Rc});import{db as cc}from"@stacksjs/database";async function dc(e){try{let t=await cc.deleteFrom("receipts").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print log: ${t.message}`);throw t}}async function lc(e){if(!e.length)return 0;try{let t=await cc.deleteFrom("receipts").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete receipts: ${t.message}`);throw t}}import{db as zn}from"@stacksjs/database";import{formatDate as Vm}from"@stacksjs/orm";function j(e){return Vm(e)}function qm(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 Ce(e){return await zn.selectFrom("receipts").where("id","=",e).selectAll().executeTakeFirst()}async function pc(){return await zn.selectFrom("receipts").selectAll().execute()}async function mc(e,t){let r=j(e),n=j(t),o=await M("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 fc(e,t){let r=j(e),n=j(t),o=await M("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 wc(e,t){let r=j(e),n=j(t),o=await M("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 yc(e,t){let r=j(e),n=j(t),o=await M("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 hc(e,t){let r=typeof e==="number"?e:e.getTime(),n=typeof t==="number"?t:t.getTime(),o=j(e),a=j(t),s=await zn.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,l=Array.from({length:24},(p,m)=>({hour:m,count:0}));return s.forEach((p)=>{let m=qm(p.timestamp);if(!m)return;l[m.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:l}}var{randomUUIDv7:gc}=globalThis.Bun;import{db as Vt}from"@stacksjs/database";import{formatDate as Gn}from"@stacksjs/orm";function et(e){try{if(typeof e==="number")return Gn(e<=2147483647?e*1000:e);if(typeof e==="string"&&/^\d{10}$/.test(e))return Gn(Number(e)*1000);return Gn(e)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function bc(e){try{let t=gc(),r={...e,timestamp:et(e.timestamp),uuid:t};await Vt.insertInto("receipts").values(r).executeTakeFirst();let n=await Vt.selectFrom("receipts").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create receipt");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create receipt: ${t.message}`);throw t}}async function _c(e){if(!e.length)return 0;try{let t=e.map((o)=>({...o,timestamp:et(o.timestamp),uuid:gc()})),n=await Vt.insertInto("receipts").values(t).executeTakeFirst()??{};return Number(n.numInsertedOrUpdatedRows??n.numAffectedRows??n.affectedRows??n.changes??0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${t.message}`);throw t}}import{db as Vn}from"@stacksjs/database";import{formatDate as qn}from"@stacksjs/orm";async function xc(e,t){try{if(!e)throw Error("Receipt ID is required for update");let r={...t,...t.timestamp===void 0?{}:{timestamp:et(t.timestamp)},updated_at:qn(new Date)};await Vn.updateTable("receipts").set(r).where("id","=",e).execute();let n=await Ce(e);if(!n)return;return n}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function Rc(e,t){try{await Vn.updateTable("receipts").set({status:t,updated_at:qn(new Date)}).where("id","=",e).execute();let r=await Ce(e);if(!r)throw Error("Failed to update receipt status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function Dc(e,t,r,n){try{let o={updated_at:qn(new Date)};if(t!==void 0)o.size=t;if(r!==void 0)o.pages=r;if(n!==void 0)o.duration=n;await Vn.updateTable("receipts").set(o).where("id","=",e).execute();let a=await Ce(e);if(!a)throw Error("Failed to update receipt job information");return a}catch(o){if(o instanceof Error)throw TypeError(`Failed to update receipt job information: ${o.message}`);throw o}}var bo={};y(bo,{couriers:()=>rr,default:()=>_f,digital:()=>er,geocoding:()=>sr,licenses:()=>cr,methods:()=>mr,rates:()=>gr,routes:()=>Yt,tracking:()=>Fr,zones:()=>Sr});var Yt={};y(Yt,{DeliveryRouteInputError:()=>I,bulkDestroy:()=>Fc,destroy:()=>Pc,fetchActive:()=>Tc,fetchAll:()=>kc,fetchByCourier:()=>Ec,fetchById:()=>Zt,store:()=>Sc,update:()=>Ac,updateLastActive:()=>Cc,updateMetrics:()=>Mc,updateStops:()=>Ic,validateDeliveryRouteWrite:()=>Ae});import{db as vc}from"@stacksjs/database";async function Pc(e){try{let t=await vc.deleteFrom("delivery_routes").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete delivery route: ${t.message}`);throw t}}async function Fc(e){if(!e.length)return 0;try{let t=await vc.deleteFrom("delivery_routes").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete delivery routes: ${t.message}`);throw t}}import{db as qt}from"@stacksjs/database";async function Zt(e){return await qt.selectFrom("delivery_routes").where("id","=",e).selectAll().executeTakeFirst()}async function kc(){return await qt.selectFrom("delivery_routes").selectAll().execute()}async function Tc(){return await qt.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function Ec(e){return await qt.selectFrom("delivery_routes").where("courier","=",e).selectAll().execute()}var{randomUUIDv7:Hm}=globalThis.Bun;import{db as Kn}from"@stacksjs/database";function he(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 tt(e){return he(e,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function oe(e){return he(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 rt(e){return he(e,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function nt(e){return he(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 ot(e){return he(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 at(e){return he(e,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function Kt(e){return he(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 Zm}from"@stacksjs/database";class I extends TypeError{constructor(e){super(e);this.name="DeliveryRouteInputError"}}function Ht(e,t,r){return Number(e[r]??t?.[r])}function Km(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 Ae(e,t){let r=Ht(e,t,"courier_id"),n=Ht(e,t,"stops"),o=Ht(e,t,"delivery_time"),a=Ht(e,t,"total_distance"),s=Km(e,t);if(!Number.isSafeInteger(r)||r<1)throw new I("Courier must be a positive integer.");if(!Number.isSafeInteger(n)||n<0)throw new I("Stops must be a non-negative integer.");if(!Number.isSafeInteger(o)||o<0)throw new I("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(a)||a<0)throw new I("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(s)||s<0)throw new I("Last active must be a valid Unix timestamp.");let i=await Zm.selectFrom("couriers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new I(`Courier ${r} was not found.`);return{...e,courier_id:Number(i.id),courier:i.name,vehicle:i.vehicle_number,last_active:s}}async function Sc(e){try{let t=Hm(),r=Kt(e),o={...await Ae(r),uuid:t};await Kn.insertInto("delivery_routes").values(o).executeTakeFirst();let a=await Kn.selectFrom("delivery_routes").where("uuid","=",t).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(t){if(t instanceof I)throw t;if(t instanceof Error)throw TypeError(`Failed to create delivery route: ${t.message}`);throw t}}async function Cc(e){try{await Kn.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",e).execute();let t=await Zt(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 Qt}from"@stacksjs/database";import{formatDate as Hn}from"@stacksjs/orm";async function Ac(e,t){try{if(!e)throw Error("Delivery route ID is required for update");let r=await Qt.selectFrom("delivery_routes").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=Kt(t),o=await Ae(n,r),a=await Qt.updateTable("delivery_routes").set({...o,updated_at:Hn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof I)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function Ic(e,t){try{let r=await Qt.updateTable("delivery_routes").set({stops:t,updated_at:Hn(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 Mc(e,t,r){try{let n={updated_at:Hn(new Date)};if(t!==void 0)n.delivery_time=t;if(r!==void 0)n.total_distance=r;let o=await Qt.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 er={};y(er,{bulkDestroy:()=>Bc,bulkSoftDelete:()=>Oc,bulkStore:()=>zc,destroy:()=>Nc,fetchAll:()=>Wc,fetchById:()=>$c,softDelete:()=>Jc,store:()=>jc,update:()=>Gc,updateDeliverySettings:()=>qc,updateStatus:()=>Vc});import{db as Xt}from"@stacksjs/database";async function Nc(e){try{let t=await Xt.deleteFrom("digital_deliveries").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete digital delivery: ${t.message}`);throw t}}async function Jc(e){try{let t=await Xt.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${t.message}`);throw t}}async function Bc(e){if(!e.length)return 0;try{let t=await Xt.deleteFrom("digital_deliveries").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${t.message}`);throw t}}async function Oc(e){if(!e.length)return 0;try{let t=await Xt.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${t.message}`);throw t}}import{db as Uc}from"@stacksjs/database";async function $c(e){return await Uc.selectFrom("digital_deliveries").where("id","=",e).selectAll().executeTakeFirst()}async function Wc(){return await Uc.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:Lc}=globalThis.Bun;import{asRow as Qm,db as Qn}from"@stacksjs/database";async function jc(e){try{let t=Lc(),r={...nt(e),uuid:t};await Qn.insertInto("digital_deliveries").values(r).executeTakeFirst();let n=await Qn.selectFrom("digital_deliveries").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created digital delivery");return Qm(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create digital delivery: ${t.message}`);throw t}}async function zc(e){if(!e.length)return 0;try{let t=e.map((n)=>({...nt(n),uuid:Lc()})),r=await Qn.insertInto("digital_deliveries").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${t.message}`);throw t}}import{db as Yn}from"@stacksjs/database";import{formatDate as Xn}from"@stacksjs/orm";async function Gc(e,t){try{if(!e)throw Error("Digital delivery ID is required for update");let r=await Yn.updateTable("digital_deliveries").set({...nt(t),updated_at:Xn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function Vc(e,t){try{let r=await Yn.updateTable("digital_deliveries").set({status:t,updated_at:Xn(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function qc(e,t,r,n,o){try{let a={updated_at:Xn(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 Yn.updateTable("digital_deliveries").set(a).where("id","=",e).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return s}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var rr={};y(rr,{bulkDestroy:()=>Yc,bulkStore:()=>td,destroy:()=>Qc,fetchAll:()=>Kc,fetchById:()=>tr,store:()=>ed,update:()=>rd,updateContact:()=>od,updateStatus:()=>nd});import{db as Hc}from"@stacksjs/database";import{db as Zc}from"@stacksjs/database";async function tr(e){return await Zc.selectFrom("couriers").where("id","=",e).selectAll().executeTakeFirst()}async function Kc(){return await Zc.selectFrom("couriers").selectAll().execute()}async function Qc(e){try{let t=await Hc.deleteFrom("couriers").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete courier: ${t.message}`);throw t}}async function Yc(e){if(!e.length)return 0;let t=0;try{return await Hc.transaction(async(r)=>{for(let n of e)if(await tr(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:Xc}=globalThis.Bun;import{db as eo}from"@stacksjs/database";async function ed(e){try{let t=Xc(),r={...at(e),uuid:t};await eo.insertInto("couriers").values(r).executeTakeFirst();let n=await eo.selectFrom("couriers").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created courier");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create courier: ${t.message}`);throw t}}async function td(e){if(!e.length)return 0;try{let t=e.map((n)=>({...at(n),uuid:Xc()})),r=await eo.insertInto("couriers").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create couriers in bulk: ${t.message}`);throw t}}import{db as to}from"@stacksjs/database";import{formatDate as ro}from"@stacksjs/orm";async function rd(e,t){try{if(!e)throw Error("Courier ID is required for update");let r=await to.updateTable("couriers").set({...at(t),updated_at:ro(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier: ${r.message}`);throw r}}async function nd(e,t){try{let r=await to.updateTable("couriers").set({status:t,updated_at:ro(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update courier status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier status: ${r.message}`);throw r}}async function od(e,t){try{let r={updated_at:ro(new Date)};if(t!==void 0)r.phone=t;let n=await to.updateTable("couriers").set(r).where("id","=",e).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update contact information");return n}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var sr={};y(sr,{PRECISION_RANK:()=>it,checkCoverage:()=>nf,formatQuery:()=>Ie,geocode:()=>rf,geocodingDriver:()=>dd,nominatimDriver:()=>ar,setGeocodingDriver:()=>tf});var ge=(e)=>e*Math.PI/180;function de(e,t){let r=ge(t.latitude-e.latitude),n=ge(t.longitude-e.longitude),o=ge(e.latitude),a=ge(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 nr(e,t){let r=ge(e.latitude),n=ge(t.latitude),o=ge(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 or(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 ad(e,t,r){return de(e,t)<=r}function st(e){return typeof e?.latitude==="number"&&typeof e?.longitude==="number"&&Number.isFinite(e.latitude)&&Number.isFinite(e.longitude)}var it={unknown:0,locality:1,postal:2,street:3,rooftop:4};function Ie(e){return[e.street,e.city,e.region,e.postalCode,e.country].map((t)=>String(t??"").trim()).filter(Boolean).join(", ")}var Ym="https://nominatim.openstreetmap.org/search",sd=1000,id=0,ud=Promise.resolve();async function Xm(e){let t=ud.then(async()=>{let r=Date.now()-id;if(r<sd)await Bun.sleep(sd-r);return id=Date.now(),e()});return ud=t.then(()=>{return},()=>{return}),t}function ef(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 ar(e={}){let t=e.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,r=e.endpoint??Ym;return{name:"nominatim",async geocode(n){let o=Ie(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 Xm(()=>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),l=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(l))return null;let p=ef(u);return{latitude:c,longitude:l,formatted:String(u.display_name??o),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[p],precision:p,provider:"nominatim"}}}}var cd=null;function tf(e){cd=e}function dd(){return cd??ar()}async function rf(e,t={}){let r=t.driver??dd(),n=t.minimumPrecision??"street",o=`geocode:${r.name}:${Ie(e).toLowerCase()}`,a=await of(o);if(a!==void 0)return a;let s=await r.geocode(e),i=s&&it[s.precision]>=it[n]?s:null;return await af(o,i,i?t.cacheSeconds??2592000:600),i}function nf(e,t,r){if(t.length===0)return null;let n=t[0],o=de(e,n);for(let a of t.slice(1)){let s=de(e,a);if(s<o)o=s,n=a}return{covered:o<=r,distanceMeters:Math.round(o),nearest:n}}async function of(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 af(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 cr={};y(cr,{LicenseKeyInputError:()=>F,bulkDestroy:()=>md,bulkSoftDelete:()=>fd,bulkStore:()=>Rd,destroy:()=>ld,fetchAll:()=>hd,fetchById:()=>yd,softDelete:()=>pd,store:()=>xd,update:()=>Dd,updateExpiration:()=>Pd,updateStatus:()=>vd,validateLicenseKeyWrite:()=>be});import{db as ir}from"@stacksjs/database";async function ld(e){try{let t=await ir.deleteFrom("license_keys").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete license key: ${t.message}`);throw t}}async function pd(e){try{let t=await ir.updateTable("license_keys").set({status:"inactive"}).where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete license key: ${t.message}`);throw t}}async function md(e){if(!e.length)return 0;try{let t=await ir.deleteFrom("license_keys").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete license keys: ${t.message}`);throw t}}async function fd(e){if(!e.length)return 0;try{let t=await ir.updateTable("license_keys").set({status:"inactive"}).where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete license keys: ${t.message}`);throw t}}import{db as wd}from"@stacksjs/database";async function yd(e){return await wd.selectFrom("license_keys").where("id","=",e).selectAll().executeTakeFirst()}async function hd(){return await wd.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:_d}=globalThis.Bun;import{asRow as uf,db as ao}from"@stacksjs/database";import{db as no}from"@stacksjs/database";var gd=["Standard License","Premium License","Enterprise License"],bd=["active","inactive","unassigned"];class F extends TypeError{constructor(e){super(e);this.name="LicenseKeyInputError"}}function ut(e,t,r){return e[r]!==void 0?e[r]:t?.[r]}function oo(e,t,r,n){let o=ut(e,t,r);if(o===void 0||o===null||o==="")return null;let a=Number(o);if(!Number.isSafeInteger(a)||a<1)throw new F(`${n} must be a positive integer or null.`);return a}function sf(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 be(e,t){let r=String(ut(e,t,"key")||"").trim().toUpperCase(),n=String(ut(e,t,"template")||""),o=String(ut(e,t,"status")||""),a=sf(ut(e,t,"expiry_date")),s=oo(e,t,"customer_id","Customer"),i=oo(e,t,"product_id","Product"),u=oo(e,t,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new F("License key must use five groups of four uppercase letters or numbers.");if(!gd.includes(n))throw new F(`Template must be one of: ${gd.join(", ")}.`);if(!bd.includes(o))throw new F(`Status must be one of: ${bd.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new F("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,l,p]=await Promise.all([s?no.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?no.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?no.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new F(`Customer ${s} was not found.`);if(i&&!l)throw new F(`Product ${i} was not found.`);if(u&&!p)throw new F(`Order ${u} was not found.`);if(s&&p?.customer_id&&Number(p.customer_id)!==s)throw new F(`Order ${u} belongs to Customer ${p.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 xd(e){try{let t=_d(),r=ot(e),n={...await be(r),uuid:t};await ao.insertInto("license_keys").values(n).executeTakeFirst();let o=await ao.selectFrom("license_keys").where("uuid","=",t).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created license key");return uf(o)}catch(t){if(t instanceof F)throw t;if(t instanceof Error){if(t.message.includes("UNIQUE constraint failed: license_keys.key"))throw new F("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${t.message}`)}throw t}}async function Rd(e){if(!e.length)return 0;try{let t=await Promise.all(e.map(async(n)=>({...await be(ot(n)),uuid:_d()}))),r=await ao.insertInto("license_keys").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof F)throw t;if(t instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${t.message}`);throw t}}import{db as ur}from"@stacksjs/database";import{formatDate as so}from"@stacksjs/orm";async function Dd(e,t){try{if(!e)throw Error("License key ID is required for update");let r=await ur.selectFrom("license_keys").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=ot(t),o=await be(n,r),a=await ur.updateTable("license_keys").set({...o,updated_at:so(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof F)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new F("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function vd(e,t){try{let r=await ur.updateTable("license_keys").set({status:t,updated_at:so(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function Pd(e,t){try{let r={updated_at:so(new Date)};if(t!==void 0)r.expiry_date=t;let n=await ur.updateTable("license_keys").set(r).where("id","=",e).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update expiration information");return n}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var mr={};y(mr,{bulkDestroy:()=>Td,bulkSoftDelete:()=>Ed,bulkStore:()=>Id,destroy:()=>Fd,fetchAll:()=>Sd,fetchById:()=>pr,formatShippingOptions:()=>Md,getActiveShippingMethods:()=>Nd,softDelete:()=>kd,store:()=>Ad,update:()=>Jd,updatePricing:()=>Od,updateStatus:()=>Bd});import{db as dr}from"@stacksjs/database";async function Fd(e){try{let t=await dr.deleteFrom("shipping_methods").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping method: ${t.message}`);throw t}}async function kd(e){try{let t=await dr.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${t.message}`);throw t}}async function Td(e){if(!e.length)return 0;try{let t=await dr.deleteFrom("shipping_methods").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping methods: ${t.message}`);throw t}}async function Ed(e){if(!e.length)return 0;try{let t=await dr.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${t.message}`);throw t}}import{db as lr}from"@stacksjs/database";async function pr(e){let t=await lr.selectFrom("shipping_methods").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=await lr.selectFrom("shipping_zones").where("shipping_method_id","=",e).selectAll().execute();return{...t,shippingZones:r}}return}async function Sd(){let e=await lr.selectFrom("shipping_methods").selectAll().execute();if(e.length===0)return[];let t=[...new Set(e.map((a)=>a.id))],o=(await lr.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:Cd}=globalThis.Bun;import{db as ct}from"@stacksjs/database";async function Ad(e){try{let t=Cd(),r={...tt(e),uuid:t};await ct.insertInto("shipping_methods").values(r).executeTakeFirst();let n=await ct.selectFrom("shipping_methods").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created shipping method");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping method: ${t.message}`);throw t}}async function Id(e){if(!e.length)return 0;try{let t=e.map((n)=>({...tt(n),uuid:Cd()})),r=await ct.insertInto("shipping_methods").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${t.message}`);throw t}}function Md(){try{return ct.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 Nd(){try{return await ct.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(e){if(e instanceof Error)throw TypeError(`Failed to get active shipping methods: ${e.message}`);throw e}}import{db as io}from"@stacksjs/database";import{formatDate as uo}from"@stacksjs/orm";async function Jd(e,t){try{if(!e)throw Error("Shipping method ID is required for update");let r=await io.updateTable("shipping_methods").set({...tt(t),updated_at:uo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function Bd(e,t){try{let r=await io.updateTable("shipping_methods").set({status:t,updated_at:uo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function Od(e,t,r){try{let n={updated_at:uo(new Date)};if(t!==void 0)n.base_rate=t;if(r!==void 0)n.free_shipping=r;let o=await io.updateTable("shipping_methods").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update pricing information");return o}catch(n){if(n instanceof Error)throw TypeError(`Failed to update pricing information: ${n.message}`);throw n}}var gr={};y(gr,{ShippingRateInputError:()=>C,bulkDestroy:()=>$d,bulkStore:()=>nl,bulkUpdate:()=>al,destroy:()=>Ud,destroyByMethod:()=>Ld,destroyByZone:()=>Wd,fetchAll:()=>Gd,fetchById:()=>zd,formatShippingRateOptions:()=>Kd,getRateByWeightAndAddress:()=>qd,getRateByWeightAndZone:()=>co,getRatesByZone:()=>Vd,getShippingRatesByMethod:()=>Hd,resolveZoneForAddress:()=>wr,store:()=>rl,update:()=>ol,updateByMethod:()=>il,updateByZone:()=>sl,validateShippingRateWrite:()=>_e,validateZoneMatchesAddress:()=>Zd});import{db as fr}from"@stacksjs/database";async function Ud(e){try{let t=await fr.deleteFrom("shipping_rates").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rate: ${t.message}`);throw t}}async function $d(e){if(!e.length)return 0;try{let t=await fr.deleteFrom("shipping_rates").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates: ${t.message}`);throw t}}async function Wd(e){try{let t=await fr.deleteFrom("shipping_rates").where("shipping_zone_id","=",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${t.message}`);throw t}}async function Ld(e){try{let t=await fr.deleteFrom("shipping_rates").where("shipping_method_id","=",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${t.message}`);throw t}}import{db as U}from"@stacksjs/database";async function zd(e){let t=await U.selectFrom("shipping_rates").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=null,n=null;if(t.shipping_zone_id)r=await U.selectFrom("shipping_zones").where("id","=",t.shipping_zone_id).selectAll().executeTakeFirst();if(t.shipping_method_id)n=await U.selectFrom("shipping_methods").where("id","=",t.shipping_method_id).selectAll().executeTakeFirst();return{...t,shipping_zone:r,shipping_method:n}}return}async function Gd(){let e=await U.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?U.selectFrom("shipping_zones").where("id","in",t).selectAll().execute():[],r.length?U.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 Vd(e){try{return await U.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).orderBy("weight_from").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${t.message}`);throw t}}async function co(e,t){try{return await U.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).where("weight_from","<=",e).where("weight_to",">=",e).executeTakeFirst()}catch(r){if(r instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${r.message}`);throw r}}async function wr(e){if(!e?.countryCode)return null;try{let t=await U.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&&jd(n.regions,e.region))o=2;if(e.postalCode&&n.postal_codes&&jd(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 qd(e,t){let r=await wr(t);if(r==null)return;return co(e,r)}async function Zd(e,t){return await wr(t)===e}function jd(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 Kd(){try{return(await U.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 Hd(e){try{return await U.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",e).orderBy("weight_from").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${t.message}`);throw t}}var{randomUUIDv7:tl}=globalThis.Bun;import{db as lo}from"@stacksjs/database";import{db as dt}from"@stacksjs/database";async function Qd(){return await dt.selectFrom("shipping_zones").selectAll().execute()}async function yr(e){return await dt.selectFrom("shipping_zones").where("id","=",e).selectAll().executeTakeFirst()}function Yd(){try{return dt.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 Xd(){try{return await dt.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(e){if(e instanceof Error)throw TypeError(`Failed to get active shipping zones: ${e.message}`);throw e}}async function el(e){try{return await dt.selectFrom("shipping_zones").selectAll().where("countries","like",`%${e}%`).where("status","=","active").orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${t.message}`);throw t}}class C extends TypeError{constructor(e){super(e);this.name="ShippingRateInputError"}}function lt(e,t,r){return Number(e[r]??t?.[r])}async function _e(e,t){let r=lt(e,t,"shipping_method_id"),n=lt(e,t,"shipping_zone_id"),o=lt(e,t,"weight_from"),a=lt(e,t,"weight_to"),s=lt(e,t,"rate");if(!Number.isSafeInteger(r)||r<1)throw new C("Shipping method must be a positive integer.");if(!Number.isSafeInteger(n)||n<1)throw new C("Shipping zone must be a positive integer.");if(!Number.isFinite(o)||o<0)throw new C("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<o)throw new C("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new C("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([pr(r),yr(n)]);if(!i)throw new C(`Shipping method ${r} was not found.`);if(!u)throw new C(`Shipping zone ${n} was not found.`);if(Number(u.shipping_method_id)!==r)throw new C(`Shipping zone ${n} is not assigned to shipping method ${r}.`)}async function rl(e){try{let t=oe(e),r=Number(t.shipping_method_id),n=Number(t.shipping_zone_id);await _e(t);let o=tl(),a={...t,shipping_method_id:r,shipping_zone_id:n,uuid:o};await lo.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await lo.selectFrom("shipping_rates").where("uuid","=",o).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return s}catch(t){if(t instanceof C)throw t;if(t instanceof Error)throw TypeError(`Failed to create shipping rate: ${t.message}`);throw t}}async function nl(e){if(!e.length)return 0;try{for(let n of e){let o=oe(n);await _e(o)}let t=e.map((n)=>({...oe(n),uuid:tl()})),r=await lo.insertInto("shipping_rates").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof C)throw t;if(t instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${t.message}`);throw t}}import{db as pt}from"@stacksjs/database";import{formatDate as hr}from"@stacksjs/orm";async function ol(e,t){try{if(!e)throw Error("Shipping rate ID is required for update");let r=await pt.selectFrom("shipping_rates").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=oe(t);await _e(n,r);let o=await pt.updateTable("shipping_rates").set({...n,updated_at:hr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!o)return;return o}catch(r){if(r instanceof C)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function al(e){if(!e.length)return 0;try{let t=0;for(let{id:r,data:n}of e){let o=await pt.updateTable("shipping_rates").set({...oe(n),updated_at:hr(new Date)}).where("id","=",r).executeTakeFirst();if(d(o)>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 sl(e,t){try{let r=await pt.updateTable("shipping_rates").set({...oe(t),updated_at:hr(new Date)}).where("shipping_zone_id","=",e).executeTakeFirst();return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function il(e,t){try{let r=await pt.updateTable("shipping_rates").set({...oe(t),updated_at:hr(new Date)}).where("shipping_method_id","=",e).executeTakeFirst();return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var Fr={};y(Fr,{ARRIVAL_RADIUS_METERS:()=>fo,NEARBY_RADIUS_METERS:()=>mo,assignStop:()=>cl,bearingInDegrees:()=>nr,broadcastToChannel:()=>ae,completeStop:()=>ll,distanceInMeters:()=>de,emitDeliveryArrived:()=>Dr,emitDeliveryAssigned:()=>_r,emitDeliveryCompleted:()=>vr,emitDeliveryFailed:()=>Pr,emitDeliveryNearby:()=>Rr,emitDeliveryPosition:()=>br,emitDeliveryStarted:()=>xr,estimateSecondsRemaining:()=>or,failStop:()=>pl,hasCoordinates:()=>st,isWithin:()=>ad,orderTrackingChannel:()=>le,recordCourierPing:()=>ul,routeTrackingChannel:()=>po,startRoute:()=>ml,startStop:()=>dl});function le(e){return`order.${e}`}function po(e){return`delivery-route.${e}`}async function Me(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 ae(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 br(e,t,r){await Promise.all([...e.map((n)=>ae(le(n),"delivery:position",r)),t==null?Promise.resolve():ae(po(t),"delivery:position",r)])}async function _r(e){if(await Me("delivery:assigned",{stop:e}),e.order_id!=null)await ae(le(e.order_id),"delivery:assigned",{stop:e})}async function xr(e){if(await Me("delivery:started",{stop:e}),e.order_id!=null)await ae(le(e.order_id),"delivery:started",{stop:e})}async function Rr(e,t,r){if(await Me("delivery:nearby",{stop:e,distanceMeters:t,etaSeconds:r}),e.order_id!=null)await ae(le(e.order_id),"delivery:nearby",{stop:e,distanceMeters:t,etaSeconds:r})}async function Dr(e){if(await Me("delivery:arrived",{stop:e}),e.order_id!=null)await ae(le(e.order_id),"delivery:arrived",{stop:e})}async function vr(e){if(await Me("delivery:completed",{stop:e}),e.order_id!=null)await ae(le(e.order_id),"delivery:completed",{stop:e})}async function Pr(e,t){await Me("delivery:failed",{stop:e,reason:t})}var{randomUUIDv7:cf}=globalThis.Bun;import{db as W}from"@stacksjs/database";var mo=400,fo=60,df=250;async function ul(e){let t=e.recordedAt??new Date().toISOString(),r=typeof e.accuracy!=="number"||e.accuracy<=df,n=await W.selectFrom("couriers").where("id","=",e.courierId).select(["id","latitude","longitude"]).executeTakeFirst();if(!n)throw Error(`Unknown courier: ${e.courierId}`);let o=st(n)?{latitude:n.latitude,longitude:n.longitude}:null,a=typeof e.heading==="number"?e.heading:o?nr(o,e):null,s=await lf(e.courierId),i=s?await pf(s.id):null,u=null,c=null,l=!1,p=!1,m=i&&st({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&m)u=Math.round(de(e,m)),c=or(u,e.speed??0),p=u<=fo&&i.arrived_at==null,l=!p&&u<=mo&&i.status==="en_route"&&i.notified_nearby_at==null;let f=await mf({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 W.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 W.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 br(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(l&&i)await W.updateTable("delivery_stops").set({notified_nearby_at:t}).where("id","=",i.id).execute(),await Rr(i,u,c);if(p&&i)await W.updateTable("delivery_stops").set({status:"arrived",arrived_at:t}).where("id","=",i.id).execute(),await Dr({...i,status:"arrived",arrived_at:t});return{pingId:f,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:l,crossedArrival:p}}async function lf(e){return await W.selectFrom("delivery_routes").where("courier_id","=",e).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function pf(e){let t=await W.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 mf(e){let t=cf();return await W.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 W.selectFrom("courier_pings").where("uuid","=",t).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:ff}=globalThis.Bun;import{db as k}from"@stacksjs/database";function wo(e){return e.type==="pickup"}async function cl(e){let t=ff(),r=e.sequence??await yf(e.deliveryRouteId);await k.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 gf(t);if(n)await _r(n);return n??{}}async function dl(e){await k.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",e).execute();let t=await ho(e);if(!t)return null;if(t.order_id!=null&&!wo(t))await yo(t.order_id,"OUT_FOR_DELIVERY");return await xr(t),t}async function ll(e,t){let r=new Date().toISOString();await k.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await hf(e)?{}:{arrived_at:r},...t?{notes:t}:{}}).where("id","=",e).execute();let n=await ho(e);if(!n)return null;if(n.order_id!=null)await yo(n.order_id,wo(n)?"OUT_FOR_DELIVERY":"DELIVERED");return await vr(n),await fl(n.delivery_route_id),n}async function pl(e,t){await k.updateTable("delivery_stops").set({status:"failed",notes:t}).where("id","=",e).execute();let r=await ho(e);if(!r)return null;if(r.order_id!=null&&!wo(r))await yo(r.order_id,"SHIPPED");return await Pr(r,t),await fl(r.delivery_route_id),r}async function ml(e){await k.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",e).execute()}async function fl(e){if(e==null)return;if(await k.selectFrom("delivery_stops").where("delivery_route_id","=",e).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await k.selectFrom("delivery_routes").where("id","=",e).select(["courier_id"]).executeTakeFirst();if(await k.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",e).execute(),r?.courier_id!=null)await k.updateTable("couriers").set({status:"active"}).where("id","=",r.courier_id).execute()}async function yo(e,t){let r=await k.selectFrom("orders").where("id","=",e).select(["id","status"]).executeTakeFirst();if(!r)return;let n=await Promise.resolve().then(() => (Fe(),$s)),{canTransition:o,emitForStatus:a}=n,s=wf(r.status,t,o);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 k.updateTable("orders").set({status:i}).where("id","=",e).execute(),await a(i,{...r,status:i})}function wf(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 yf(e){return(await k.selectFrom("delivery_stops").where("delivery_route_id","=",e).select(["sequence"]).execute()).reduce((r,n)=>Math.max(r,n.sequence??0),0)+1}async function hf(e){return(await k.selectFrom("delivery_stops").where("id","=",e).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function ho(e){return await k.selectFrom("delivery_stops").where("id","=",e).selectAll().executeTakeFirst()??null}async function gf(e){return await k.selectFrom("delivery_stops").where("uuid","=",e).selectAll().executeTakeFirst()??null}var Sr={};y(Sr,{bulkDestroy:()=>hl,bulkSoftDelete:()=>gl,bulkStore:()=>xl,destroy:()=>wl,fetchAll:()=>Qd,fetchById:()=>yr,formatZoneOptions:()=>Yd,getActiveShippingZones:()=>Xd,getZonesByCountry:()=>el,softDelete:()=>yl,store:()=>_l,update:()=>Rl,updateCountries:()=>vl,updateRegionsAndPostalCodes:()=>Pl,updateStatus:()=>Dl});import{db as kr}from"@stacksjs/database";async function wl(e){try{let t=await kr.deleteFrom("shipping_zones").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping zone: ${t.message}`);throw t}}async function yl(e){try{let t=await kr.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${t.message}`);throw t}}async function hl(e){if(!e.length)return 0;try{let t=await kr.deleteFrom("shipping_zones").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping zones: ${t.message}`);throw t}}async function gl(e){if(!e.length)return 0;try{let t=await kr.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${t.message}`);throw t}}var{randomUUIDv7:bl}=globalThis.Bun;import{db as go}from"@stacksjs/database";async function _l(e){try{let t=bl(),r={...rt(e),uuid:t};await go.insertInto("shipping_zones").values(r).executeTakeFirst();let n=await go.selectFrom("shipping_zones").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created shipping zone");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping zone: ${t.message}`);throw t}}async function xl(e){if(!e.length)return 0;try{let t=e.map((n)=>({...rt(n),uuid:bl()})),r=await go.insertInto("shipping_zones").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${t.message}`);throw t}}import{db as Tr}from"@stacksjs/database";import{formatDate as Er}from"@stacksjs/orm";async function Rl(e,t){try{if(!e)throw Error("Shipping zone ID is required for update");let r=await Tr.updateTable("shipping_zones").set({...rt(t),updated_at:Er(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function Dl(e,t){try{let r=await Tr.updateTable("shipping_zones").set({status:t,updated_at:Er(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function vl(e,t){try{let r=await Tr.updateTable("shipping_zones").set({countries:t,updated_at:Er(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function Pl(e,t,r){try{let n={updated_at:Er(new Date)};if(t!==void 0)n.regions=t;if(r!==void 0)n.postal_codes=r;let o=await Tr.updateTable("shipping_zones").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update regions and postal codes");return o}catch(n){if(n instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${n.message}`);throw n}}var bf={digital:er,couriers:rr,geocoding:sr,licenses:cr,methods:mr,rates:gr,routes:Yt,tracking:Fr,zones:Sr},_f=bf;var Ro={};y(Ro,{activeTaxRates:()=>_o,breakdownFor:()=>xo,bulkDestroy:()=>El,bulkStore:()=>Jl,destroy:()=>Tl,fetchAll:()=>Al,fetchById:()=>Cl,store:()=>Nl,taxFor:()=>Fl,update:()=>Bl,updateDefaultStatus:()=>$l,updateRate:()=>Ul,updateStatus:()=>Ol});import{db as xf}from"@stacksjs/database";function Rf(e){let t=Number(e);return Number.isFinite(t)?t/100:0}async function _o(e={}){let t=xf.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 xo(e,t,r={}){let n=Math.max(0,Math.round(e)),o=[],a=0,s=0;for(let i of t){let u=Rf(i.rate),c=Math.round(n*u),l=Boolean(r.exempt&&i.exemptible);if(l)s+=c;else a+=c;o.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:l?0:c,exempted:l})}return{taxable:n,components:o,tax:a,exempted:s}}async function Fl(e,t={}){return xo(e,await _o(t),t)}import{db as kl}from"@stacksjs/database";async function Tl(e){try{let t=await kl.deleteFrom("tax_rates").where("id","=",e).executeTakeFirst();return d(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete tax rate: ${t.message}`);throw t}}async function El(e){if(!e.length)return 0;try{let t=await kl.deleteFrom("tax_rates").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete tax rates: ${t.message}`);throw t}}import{db as Sl}from"@stacksjs/database";async function Cl(e){return await Sl.selectFrom("tax_rates").where("id","=",e).selectAll().executeTakeFirst()}async function Al(){return await Sl.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:Il}=globalThis.Bun;import{db as Ml}from"@stacksjs/database";async function Nl(e){try{return await Ml.transaction(async(t)=>{let r={...e,uuid:Il()};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 n})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create tax rate: ${t.message}`);throw t}}async function Jl(e){if(!e.length)return 0;try{return await Ml.transaction(async(t)=>{let r=0;for(let n of e){let o={...n,uuid:Il()};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 Cr}from"@stacksjs/database";import{formatDate as Ar}from"@stacksjs/orm";async function Bl(e,t){try{if(!e)throw Error("Tax rate ID is required for update");return await Cr.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=Ar(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 s})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function Ol(e,t){try{let r=await Cr.updateTable("tax_rates").set({status:t,updated_at:Ar(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function Ul(e,t){try{let r=await Cr.updateTable("tax_rates").set({rate:t,updated_at:Ar(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function $l(e,t){try{return await Cr.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",e).executeTakeFirst())return!1;let o=Ar(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 To={};y(To,{default:()=>Af,products:()=>Mr,restaurant:()=>Je});var Mr={};y(Mr,{bulkDestroy:()=>Ll,bulkStore:()=>ap,destroy:()=>Wl,fetchAll:()=>jl,fetchById:()=>mt,fetchCancelledBetweenDates:()=>Hl,fetchConversionRates:()=>Xl,fetchCountBetweenDates:()=>ep,fetchCountByAllQuantities:()=>ql,fetchCountByDate:()=>Gl,fetchCountByDateGrouped:()=>tp,fetchCountByQuantity:()=>Vl,fetchCountBySource:()=>zl,fetchCountByStatus:()=>Yl,fetchNotifiedBetweenDates:()=>Zl,fetchPurchasedBetweenDates:()=>Kl,fetchWaiting:()=>Ql,store:()=>op,update:()=>Ir,updatePartySize:()=>ip,updateStatus:()=>sp});import{db as Do}from"@stacksjs/database";async function Wl(e){try{let t=await Do.selectFrom("waitlist_products").where("id","=",e).selectAll().executeTakeFirst();if(!t)return;return await Do.deleteFrom("waitlist_products").where("id","=",e).execute(),t}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete waitlist product: ${t.message}`);throw t}}async function Ll(e){if(!e.length)return 0;try{let t=await Do.deleteFrom("waitlist_products").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${t.message}`);throw t}}import{db as x}from"@stacksjs/database";import{formatDate as P}from"@stacksjs/orm";async function mt(e){return await x.selectFrom("waitlist_products").where("id","=",e).selectAll().executeTakeFirst()}async function jl(){return await x.selectFrom("waitlist_products").selectAll().execute()}async function zl(e,t){let r=x.selectFrom("waitlist_products").select(["source",x.fn.count("id").as("count")]).groupBy("source");if(e&&t){let o=P(e),a=P(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 Gl(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=P(t),o=P(r);return(await x.selectFrom("waitlist_products").select(x.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",o).executeTakeFirst())?.count??0}async function Vl(e){return(await x.selectFrom("waitlist_products").select(x.fn.count("id").as("count")).where("quantity","=",e).executeTakeFirst())?.count??0}async function ql(e,t){let r=x.selectFrom("waitlist_products").select(["quantity",x.fn.count("id").as("count")]).groupBy("quantity");if(e&&t){let o=P(e),a=P(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 Zl(e,t){let r=P(e),n=P(t);return await x.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",n).whereNotNull("notified_at").execute()}async function Kl(e,t){let r=P(e),n=P(t);return await x.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",n).whereNotNull("purchased_at").execute()}async function Hl(e,t){let r=P(e),n=P(t);return await x.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",n).whereNotNull("cancelled_at").execute()}async function Ql(){return await x.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function Yl(e,t,r){let n=x.selectFrom("waitlist_products").select(x.fn.count("id").as("count")).where("status","=",e);if(t&&r){let a=P(t),s=P(r);n=n.where("created_at",">=",a).where("created_at","<=",s)}return(await n.executeTakeFirst())?.count??0}async function Xl(e,t){let r=x.selectFrom("waitlist_products").select(["status",x.fn.count("id").as("count")]).groupBy("status");if(e&&t){let u=P(e),c=P(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:l})=>(u[c]={count:l,percentage:o>0?l/o*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function ep(e,t){let r=P(e),n=P(t);return(await x.selectFrom("waitlist_products").select(x.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",n).executeTakeFirst())?.count??0}async function tp(e,t){let r=x.selectFrom("waitlist_products").select(["created_at"]);if(e&&t){let a=P(e),s=P(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:np}=globalThis.Bun;import{db as vo}from"@stacksjs/database";import{formatDate as rp}from"@stacksjs/orm";var Df={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function vf(e){return typeof e==="number"||e instanceof Date?rp(e):e}function ft(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]=vf(r[o]);let n=Df[r.status];if(n&&r[n]===void 0&&!t[n])r[n]=rp(new Date);return r}async function op(e){try{let t=np(),r={...ft(e),uuid:t,status:e.status||"waiting"};await vo.insertInto("waitlist_products").values(r).executeTakeFirst();let n=await vo.selectFrom("waitlist_products").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create waitlist product");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create waitlist product: ${t.message}`);throw t}}async function ap(e){if(!e.length)return 0;try{let t=e.map((n)=>({...ft(n),status:n.status||"waiting",uuid:np()})),r=await vo.insertInto("waitlist_products").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${t.message}`);throw t}}import{db as Pf}from"@stacksjs/database";import{formatDate as Ff}from"@stacksjs/orm";async function Ir(e,t){try{if(!e)throw Error("Waitlist product ID is required for update");let r=await mt(e);if(!r)return;await Pf.updateTable("waitlist_products").set({...ft(t,r),updated_at:Ff(new Date)}).where("id","=",e).execute();let n=await mt(e);if(!n)return;return n}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function sp(e,t){return await Ir(e,{status:t})}async function ip(e,t){return await Ir(e,{quantity:t})}var Je={};y(Je,{bulkDestroy:()=>cp,bulkStore:()=>Sp,destroy:()=>up,fetchAll:()=>dp,fetchAverageWaitTimes:()=>bp,fetchBetweenDates:()=>wp,fetchById:()=>wt,fetchConversionRates:()=>gp,fetchCountByAllPartySizes:()=>fp,fetchCountByDate:()=>pp,fetchCountByPartySize:()=>mp,fetchCountByTablePreference:()=>lp,fetchCurrentWaitTimes:()=>Pp,fetchNoShowStats:()=>vp,fetchSeatedBetweenDates:()=>yp,fetchSeatedStats:()=>Fp,fetchSeatingRate:()=>Dp,fetchTablesTurnedToday:()=>Rp,fetchTimeSeriesStats:()=>kp,fetchWaiting:()=>hp,fetchWaitingWithPartySizes:()=>xp,fetchWaitingWithQuotedTimes:()=>_p,store:()=>Ep,update:()=>Ne,updatePartySize:()=>Ap,updateQueuePosition:()=>Mp,updateStatus:()=>Cp,updateWaitTimes:()=>Ip});import{db as Po}from"@stacksjs/database";async function up(e){try{let t=await Po.selectFrom("waitlist_restaurants").where("id","=",e).selectAll().executeTakeFirst();if(!t)return;return await Po.deleteFrom("waitlist_restaurants").where("id","=",e).execute(),t}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${t.message}`);throw t}}async function cp(e){if(!e.length)return 0;try{let t=await Po.deleteFrom("waitlist_restaurants").where("id","in",e).executeTakeFirst();return d(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${t.message}`);throw t}}import{db as g}from"@stacksjs/database";import{formatDate as N}from"@stacksjs/orm";async function wt(e){return await g.selectFrom("waitlist_restaurants").where("id","=",e).selectAll().executeTakeFirst()}async function dp(){return await g.selectFrom("waitlist_restaurants").selectAll().execute()}async function lp(){return(await g.selectFrom("waitlist_restaurants").select(["table_preference",g.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((t,{table_preference:r,count:n})=>(t[r]=n,t),{})}async function pp(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=N(t),o=N(r);return(await g.selectFrom("waitlist_restaurants").select(g.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",o).executeTakeFirst())?.count??0}async function mp(e){return(await g.selectFrom("waitlist_restaurants").select(g.fn.count("id").as("count")).where("party_size","=",e).executeTakeFirst())?.count??0}async function fp(){return(await g.selectFrom("waitlist_restaurants").select(["party_size",g.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((t,{party_size:r,count:n})=>(t[r]=n,t),{})}async function wp(e,t){let r=N(e),n=N(t);return await g.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",n).execute()}async function yp(e,t){let r=N(e),n=N(t);return await g.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",n).where("status","=","seated").execute()}async function hp(){return await g.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function gp(){let e=await g.selectFrom("waitlist_restaurants").select(["status",g.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 bp(){let e=await g.selectFrom("waitlist_restaurants").select([g.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),g.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 _p(){let e=await g.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 xp(){let e=await g.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 Rp(){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=N(t),o=N(r),a=await g.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",n).where("check_in_time","<=",o).execute(),s=a.length,i=a.reduce((p,m)=>p+m.party_size,0),u=s>0?i/s:0,c=a.reduce((p,m)=>(p[m.table_preference]=(p[m.table_preference]||0)+1,p),{}),l=a.reduce((p,m)=>(p[m.party_size]=(p[m.party_size]||0)+1,p),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:l}}async function Dp(e,t){let r=N(e),n=N(t),o=await g.selectFrom("waitlist_restaurants").select(["status",g.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",n).groupBy("status").execute(),a=o.reduce((c,{count:l})=>c+l,0),s=o.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=o.reduce((c,{status:l,count:p})=>(c[l]={count:p,percentage:a>0?p/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function vp(e,t){let r=N(e),n=N(t),o=g.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",n),a=await g.selectFrom("waitlist_restaurants").select(g.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((b,R)=>b+(R.quoted_wait_time??0),0),l=i>0?c/i:0,p=s.reduce((b,R)=>b+R.party_size,0),m=i>0?p/i:0,f=s.reduce((b,R)=>(b[R.table_preference]=(b[R.table_preference]||0)+1,b),{}),h=s.reduce((b,R)=>(b[R.party_size]=(b[R.party_size]||0)+1,b),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:l,averagePartySize:m,breakdownByTablePreference:f,breakdownByPartySize:h}}async function Pp(){let e=await g.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 Fp(){let e=Date.now()-86400000,t=await g.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 kp(){return(await g.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:Tp}=globalThis.Bun;import{db as ko}from"@stacksjs/database";import{formatDate as Fo}from"@stacksjs/orm";var kf={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function Tf(e){if(typeof e==="number")return Fo(e<=2147483647?e*1000:e);if(e instanceof Date)return Fo(e);return e}function yt(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]=Tf(r[o]);let n=kf[r.status];if(n&&r[n]===void 0&&!t[n])r[n]=Fo(new Date);return r}async function Ep(e){try{let t=Tp(),r={...yt(e),status:e.status||"waiting",uuid:t};await ko.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let n=await ko.selectFrom("waitlist_restaurants").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create restaurant waitlist entry");return n}catch(t){if(t instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${t.message}`);throw t}}async function Sp(e){if(!e.length)return 0;try{let t=e.map((n)=>({...yt(n),status:n.status||"waiting",uuid:Tp()})),r=await ko.insertInto("waitlist_restaurants").values(t).executeTakeFirst();return d(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${t.message}`);throw t}}import{db as Ef}from"@stacksjs/database";import{formatDate as Sf}from"@stacksjs/orm";async function Ne(e,t){try{if(!e)throw Error("Restaurant waitlist entry ID is required for update");let r=await wt(e);if(!r)return;await Ef.updateTable("waitlist_restaurants").set({...yt(t,r),updated_at:Sf(new Date)}).where("id","=",e).execute();let n=await wt(e);if(!n)return;return n}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function Cp(e,t){return await Ne(e,{status:t})}async function Ap(e,t){return await Ne(e,{party_size:t})}async function Ip(e,t,r){return await Ne(e,{quoted_wait_time:t,...r===void 0?{}:{actual_wait_time:r}})}async function Mp(e,t){return await Ne(e,{queue_position:t})}var Cf={products:Mr,restaurant:Je},Af=Cf;var If={auctions:cn,carts:dn,coupons:ln,customers:mn,devices:gn,errors:xn,giftCards:vn,orders:Nn,payments:Jn,products:jn,receipts:Zn,restaurant:Je,shippings:bo,tax:Ro,waitlists:To},BP=If;export{cn as auctions,dn as carts,If as commerce,ln as coupons,mn as customers,BP as default,gn as devices,xn as errors,vn as giftCards,Nn as orders,Jn as payments,jn as products,Zn as receipts,Je as restaurant,bo as shippings,Ro as tax,To as waitlists};