@stacksjs/commerce 0.74.3 → 0.74.5

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,28 +1,28 @@
1
1
  // @bun
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
2
+ var Bm=Object.defineProperty;var Om=(t)=>t;function Um(t,e){this[t]=Om.bind(null,e)}var g=(t,e)=>{for(var r in e)Bm(t,r,{get:e[r],enumerable:!0,configurable:!0,set:Um.bind(e,r)})};var $m=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=import.meta.require;var Ws={};g(Ws,{canTransition:()=>He,emitForStatus:()=>Ye,emitOrderCancelled:()=>Fe,emitOrderCreated:()=>Qe,emitOrderDelivered:()=>Mt,emitOrderOutForDelivery:()=>$s,emitOrderPaid:()=>le,emitOrderRefunded:()=>ke,emitOrderShipped:()=>At});function He(t,e){if(t===e)return!0;return _p[t]?.includes(e)??!1}async function he(t,e){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let o=r.dispatch;if(typeof o!=="function")return;o(t,e)}catch{}}async function Qe(t){await he("order:created",{order:t})}async function le(t,e){await he("order:paid",{order:t,payment:e})}async function At(t){await he("order:shipped",{order:t})}async function $s(t){await he("order:out_for_delivery",{order:t})}async function Mt(t){await he("order:delivered",{order:t})}async function Fe(t,e){await he("order:cancelled",{order:t,reason:e})}async function ke(t,e){await he("order:refunded",{order:t,refundAmount:e})}async function Ye(t,e){switch(t){case"PROCESSING":return le(e);case"SHIPPED":return At(e);case"OUT_FOR_DELIVERY":return $s(e);case"DELIVERED":return Mt(e);case"CANCELLED":return Fe(e);case"REFUNDED":return ke(e);case"PENDING":default:}}var _p;var Te=$m(()=>{_p={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 lo={};g(lo,{DEFAULT_INCREMENT_LADDER:()=>H,auctionChannel:()=>bt,auctionTotals:()=>Yr,biddersFor:()=>$r,bids:()=>Zr,bidsByBidder:()=>Ur,bidsForAuction:()=>Or,bidsForItem:()=>Br,broadcastBid:()=>Lr,broadcastItemClosed:()=>zr,broadcastPledge:()=>jr,closeAuction:()=>ro,closeDueItems:()=>to,closeItem:()=>ze,closingSoon:()=>no,closingSoonNotification:()=>Gm,currencyFor:()=>Gr,determineWinner:()=>ve,effectiveCloseAt:()=>ue,engine:()=>Kr,extendedCloseAt:()=>$e,fetchAuction:()=>z,fetchAuctionForEvent:()=>Hr,fetchCatalogue:()=>Qr,fetchItems:()=>Y,fetchPledges:()=>uo,incrementFor:()=>O,leadingBid:()=>Ue,lots:()=>ao,makePledge:()=>Mn,nextMinimumBid:()=>Q,openAuction:()=>eo,outbidNotification:()=>jm,placeBid:()=>qr,pledgeLevels:()=>In,pledgeTotal:()=>io,pledges:()=>co,resolveBid:()=>We,rulesFor:()=>Le,settle:()=>je,settleAuction:()=>oo,winnerNotification:()=>zm});var Zr={};g(Zr,{biddersFor:()=>$r,bidsByBidder:()=>Ur,bidsForAuction:()=>Or,bidsForItem:()=>Br,leadingBid:()=>Ue,placeBid:()=>qr});import{db as K}from"@stacksjs/database";async function Ue(t){return await K.selectFrom("bids").selectAll().where("auction_item_id","=",t).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function Br(t){return await K.selectFrom("bids").selectAll().where("auction_item_id","=",t).orderBy("placed_at","desc").execute()??[]}async function Or(t){return await K.selectFrom("bids").selectAll().where("auction_id","=",t).orderBy("placed_at","asc").execute()??[]}async function Ur(t,e){return await K.selectFrom("bids").selectAll().where("auction_id","=",t).where("bidder_email","=",e.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function $r(t){let e=await K.selectFrom("bids").select(["bidder_name","bidder_email"]).where("auction_id","=",t).execute(),r=new Map;for(let o of e??[]){let n=o.bidder_email.toLowerCase();if(!r.has(n))r.set(n,{name:o.bidder_name,email:o.bidder_email})}return[...r.values()]}var{randomUUIDv7:Lm}=globalThis.Bun;import{db as Vr}from"@stacksjs/database";function $e(t,e,r,o){if(r.antiSnipeMinutes<=0||r.extendOnBidWindowMinutes<=0)return null;if(t.extension_count>=r.maxExtensions)return null;let n=e.getTime()-o.getTime();if(n<=0)return null;if(n>r.extendOnBidWindowMinutes*60000)return null;let a=new Date(o.getTime()+r.antiSnipeMinutes*60000);return a>e?a:null}function ue(t,e){return new Date(t.closes_at??e)}var H=[{upTo:5000,step:200},{upTo:1e4,step:500},{upTo:25000,step:1000},{upTo:50000,step:2500},{upTo:1e5,step:5000},{upTo:250000,step:1e4},{upTo:null,step:25000}];function O(t,e=H,r){if(r&&r>0)return r;for(let o of e)if(o.upTo===null||t<o.upTo)return o.step;return e[e.length-1]?.step??100}function Q(t,e,r=H){if(e===null||e<=0)return t.starting_bid;return e+O(e,r,t.min_increment)}function We(t,e,r,o=H){let n=Math.max(r.amount,r.maxAmount??0),a=Q(t,e?e.amount:null,o);if(r.maxAmount!=null&&r.maxAmount<r.amount)return{accepted:!1,reason:"max_below_amount",message:"Your maximum bid has to be at least as much as your bid.",nextMinimumBid:a};if(n<a)return{accepted:!1,reason:"below_minimum",message:`The next bid on this lot is ${a/100}.`,nextMinimumBid:a};if(t.buy_now_price&&n>=t.buy_now_price)return{accepted:!0,buyNow:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:t.buy_now_price,maxAmount:t.buy_now_price,isChallenger:!0},challengerAmount:t.buy_now_price,outbid:e?{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount}:void 0,nextMinimumBid:t.buy_now_price};if(!e){let m=Math.max(t.starting_bid,r.amount);return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:m,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:m,nextMinimumBid:m+O(m,o,t.min_increment)}}let s=Math.max(e.amount,e.max_amount??0);if(e.bidder_email.toLowerCase()===r.bidderEmail.toLowerCase()){if(n<=s)return{accepted:!1,reason:"already_leading",message:"You are already the leading bidder at or above that amount.",nextMinimumBid:a};return{accepted:!0,leader:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount,maxAmount:n,isChallenger:!1},challengerAmount:e.amount,nextMinimumBid:e.amount+O(e.amount,o,t.min_increment)}}if(n>s){let m=s+O(s,o,t.min_increment),p=Math.min(n,Math.max(m,a));return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:p,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:p,outbid:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount},nextMinimumBid:p+O(p,o,t.min_increment)}}let u=n+O(n,o,t.min_increment),c=Math.min(s,Math.max(u,n));return{accepted:!0,leader:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:c,maxAmount:e.max_amount??null,isChallenger:!1},challengerAmount:n,outbid:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:n},nextMinimumBid:c+O(c,o,t.min_increment)}}function bt(t){return`auction.${t}`}async function Wr(){try{return(await import("@stacksjs/realtime")).emit??null}catch{return null}}async function Lr(t){let e=await Wr();if(!e||!t.item||!t.leader)return;await e(bt(t.item.auction_id),"bid.placed",{itemId:t.item.id,lotNumber:t.item.lot_number,amount:t.leader.amount,nextMinimumBid:t.nextMinimumBid,leaderName:t.leader.bidderName,status:t.item.status,closesAt:t.item.closes_at,extended:Boolean(t.extendedTo),soldViaBuyNow:Boolean(t.buyNow)})}async function jr(t,e){let r=await Wr();if(!r)return;await r(bt(t.auction_id),"pledge.made",{donorName:t.donor_name,amount:t.amount,level:t.level??null,runningTotal:e})}async function zr(t,e,r){let o=await Wr();if(!o)return;await o(bt(t),"item.closed",{itemId:e,...r})}import{config as Wm}from"@stacksjs/config";function Cn(){return Wm.commerce??{}}function An(){return Cn().auction??{}}function Le(t){let e=An();return{increments:e.increments?.length?e.increments:H,antiSnipeMinutes:t?.anti_snipe_minutes??e.antiSnipeMinutes??2,extendOnBidWindowMinutes:t?.extend_on_bid_window_minutes??e.extendOnBidWindowMinutes??2,maxExtensions:t?.max_extensions??e.maxExtensions??20}}function Gr(t){return t?.currency??An().currency??Cn().currency??"USD"}function _t(t){return t.toISOString().slice(0,19).replace("T"," ")}async function qr(t){let e=t.now??new Date,r=await Vr.selectFrom("auction_items").selectAll().where("id","=",t.itemId).executeTakeFirst();if(!r)return{accepted:!1,reason:"item_not_found",message:"That lot is no longer available.",nextMinimumBid:0};let o=await Vr.selectFrom("auctions").selectAll().where("id","=",r.auction_id).executeTakeFirst(),n=Le(o),a=await Ue(r.id),s=Q(r,a?.amount??null,n.increments);if(!o||o.status!=="open"||new Date(o.opens_at)>e)return{accepted:!1,reason:"auction_not_open",message:"Bidding is not open yet.",nextMinimumBid:s,item:r};let i=ue(r,o.closes_at);if(r.status!=="open"||i<=e)return{accepted:!1,reason:"item_not_open",message:"Bidding on this lot has closed.",nextMinimumBid:s,item:r};let u=We(r,a,{bidderEmail:t.bidderEmail,bidderName:t.bidderName,amount:t.amount,maxAmount:t.maxAmount},n.increments);if(!u.accepted)return{...u,item:r};let c=u.buyNow?null:$e(r,i,n,e),m=u.leader&&!u.leader.isChallenger&&a&&a.bidder_email.toLowerCase()===t.bidderEmail.toLowerCase(),p=await Vr.transaction(async(y)=>{if(m&&a)return await y.updateTable("bids").set({max_amount:u.leader.maxAmount}).where("id","=",a.id).execute(),{...a,max_amount:u.leader.maxAmount};let b=u.leader?.isChallenger===!0,R=Lm();if(await y.insertInto("bids").values({uuid:R,auction_id:r.auction_id,auction_item_id:r.id,bidder_name:t.bidderName,bidder_email:t.bidderEmail.toLowerCase(),amount:u.challengerAmount??t.amount,max_amount:t.maxAmount??null,status:b?"leading":"outbid",placed_at:_t(e)}).execute(),a){if(b)await y.updateTable("bids").set({status:"outbid"}).where("id","=",a.id).execute();else if(u.leader&&u.leader.amount!==a.amount)await y.updateTable("bids").set({amount:u.leader.amount}).where("id","=",a.id).execute()}if(u.buyNow)await y.updateTable("auction_items").set({status:"sold",closes_at:_t(e)}).where("id","=",r.id).execute();else if(c)await y.updateTable("auction_items").set({closes_at:_t(c),extension_count:r.extension_count+1}).where("id","=",r.id).execute();return await y.selectFrom("bids").selectAll().where("uuid","=",R).executeTakeFirst()}),f={...u,bid:p,item:{...r,status:u.buyNow?"sold":r.status,closes_at:c?_t(c):r.closes_at,extension_count:c?r.extension_count+1:r.extension_count},extendedTo:c??void 0};return await Lr(f).catch(()=>{return}),f}var Kr={};g(Kr,{DEFAULT_INCREMENT_LADDER:()=>H,determineWinner:()=>ve,effectiveCloseAt:()=>ue,extendedCloseAt:()=>$e,incrementFor:()=>O,nextMinimumBid:()=>Q,resolveBid:()=>We,settle:()=>je});function ve(t,e){let r=e.filter((a)=>a.status!=="invalid");if(r.length===0)return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"passed",amount:0,passedReason:"no_bids"};let n=[...r].sort((a,s)=>{if(s.amount!==a.amount)return s.amount-a.amount;return new Date(a.placed_at).getTime()-new Date(s.placed_at).getTime()})[0];if(t.reserve_price&&n.amount<t.reserve_price)return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"passed",amount:n.amount,passedReason:"reserve_not_met"};return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"sold",winningBidId:n.id,winnerName:n.bidder_name,winnerEmail:n.bidder_email,amount:n.amount}}function je(t,e,r,o){let n=e.filter((p)=>p.status==="sold"),a=e.filter((p)=>p.status==="passed"),s=n.reduce((p,f)=>p+f.amount,0),i=r.filter((p)=>p.status==="confirmed").reduce((p,f)=>p+f.amount,0),u=new Map(t.map((p)=>[p.id,p.fair_market_value??null])),c=n.reduce((p,f)=>{let y=u.get(f.itemId);return y==null?p:p+(f.amount-y)},0),m=e.length;return{auctionId:o.auctionId,currency:o.currency,totalRaised:s+i,bidRevenue:s,pledgeRevenue:i,goalAmount:o.goalAmount??null,itemsSold:n.length,itemsPassed:a.length,sellThrough:m===0?0:n.length/m,valueDelta:c,outcomes:e}}var ao={};g(ao,{auctionTotals:()=>Yr,closeAuction:()=>ro,closeDueItems:()=>to,closeItem:()=>ze,closingSoon:()=>no,fetchAuction:()=>z,fetchAuctionForEvent:()=>Hr,fetchCatalogue:()=>Qr,fetchItems:()=>Y,openAuction:()=>eo,settleAuction:()=>oo});import{db as U}from"@stacksjs/database";async function z(t){return await U.selectFrom("auctions").selectAll().where("id","=",t).executeTakeFirst()??null}async function Hr(t){return await U.selectFrom("auctions").selectAll().where("event_id","=",t).executeTakeFirst()??null}async function Y(t){return await U.selectFrom("auction_items").selectAll().where("auction_id","=",t).orderBy("lot_number","asc").execute()??[]}async function Qr(t){let[e,r]=await Promise.all([z(t),Y(t)]),o=Le(e),n=await U.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",t).where("status","in",["leading","won"]).execute(),a=await U.selectFrom("bids").select(["auction_item_id"]).where("auction_id","=",t).where("status","!=","invalid").execute(),s=new Map((n??[]).map((u)=>[u.auction_item_id,u])),i=new Map;for(let u of a??[])i.set(u.auction_item_id,(i.get(u.auction_item_id)??0)+1);return r.map((u)=>{let c=s.get(u.id)??null;return{...u,currentBid:c?.amount??0,bidCount:i.get(u.id)??0,nextMinimumBid:Q(u,c?.amount??null,o.increments),leaderName:c?.bidder_name??null}})}async function Yr(t){let e=await z(t),r=await U.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",t).where("status","!=","invalid").execute(),o=await U.selectFrom("pledges").select(["amount"]).where("auction_id","=",t).where("status","=","confirmed").execute(),n=r??[],s=n.filter((c)=>c.status==="leading"||c.status==="won").reduce((c,m)=>c+m.amount,0),i=(o??[]).reduce((c,m)=>c+m.amount,0),u=await U.selectFrom("auction_items").where("auction_id","=",t).count();return{currentBidTotal:s,pledgeTotal:i,raised:s+i,goalAmount:e?.goal_amount??null,bidCount:n.length,bidderCount:new Set(n.map((c)=>c.bidder_email.toLowerCase())).size,lotsOffered:Number(u??0),lotsWithBids:new Set(n.map((c)=>c.auction_item_id)).size}}import{db as ce}from"@stacksjs/database";function Xr(t){return t.toISOString().slice(0,19).replace("T"," ")}async function eo(t,e=new Date){return await ce.updateTable("auctions").set({status:"open",opens_at:Xr(e)}).where("id","=",t).execute(),await ce.updateTable("auction_items").set({status:"open"}).where("auction_id","=",t).where("status","=","closed").execute(),z(t)}async function ze(t,e=new Date){if(t.status==="sold"||t.status==="passed")return null;let r=await ce.selectFrom("bids").selectAll().where("auction_item_id","=",t.id).execute(),o=ve(t,r??[]);return await ce.transaction(async(n)=>{if(await n.updateTable("auction_items").set({status:o.status,closes_at:Xr(e)}).where("id","=",t.id).execute(),o.winningBidId)await n.updateTable("bids").set({status:"won"}).where("id","=",o.winningBidId).execute();await n.updateTable("bids").set({status:"lost"}).where("auction_item_id","=",t.id).where("status","in",["leading","outbid"]).execute()}),await zr(t.auction_id,t.id,{status:o.status,amount:o.amount,winnerName:o.winnerName}).catch(()=>{return}),o}async function to(t,e=new Date){let r=await z(t);if(!r)return[];let o=await Y(t),n=[];for(let a of o){if(a.status!=="open")continue;if(ue(a,r.closes_at)>e)continue;let s=await ze(a,e);if(s)n.push(s)}return n}async function ro(t,e=new Date){let r=await Y(t),o=[];for(let n of r){let a=await ze(n,e);if(a)o.push(a)}return await ce.updateTable("auctions").set({status:"closed",closes_at:Xr(e)}).where("id","=",t).execute(),o}async function oo(t,e={}){let r=await z(t);if(!r)return null;let o=await Y(t),n=await ce.selectFrom("bids").selectAll().where("auction_id","=",t).execute(),a=await ce.selectFrom("pledges").selectAll().where("auction_id","=",t).execute(),s=new Map;for(let u of n??[]){let c=s.get(u.auction_item_id)??[];c.push(u),s.set(u.auction_item_id,c)}let i=o.map((u)=>{let c=ve(u,s.get(u.id)??[]);return u.status==="passed"?{...c,status:"passed"}:c});if(e.markSettled)await ce.updateTable("auctions").set({status:"settled"}).where("id","=",t).execute();return je(o,i,a??[],{auctionId:t,currency:Gr(r),goalAmount:r.goal_amount??null})}async function no(t,e,r=new Date){let o=await z(t);if(!o)return[];let n=new Date(r.getTime()+e*60000);return(await Y(t)).filter((a)=>{if(a.status!=="open")return!1;let s=ue(a,o.closes_at);return s>r&&s<=n})}function so(t,e="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0}).format(t/100)}function jm(t,e="USD"){if(!t.outbid||!t.item)return null;let r=t.item;return{to:{name:t.outbid.bidderName,email:t.outbid.bidderEmail},type:"outbid",subject:`You have been outbid on lot ${r.lot_number}: ${r.title}`,body:`Someone has bid higher on "${r.title}". The next bid is ${so(t.nextMinimumBid,e)}. Bidding closes ${new Date(r.closes_at??"").toLocaleString()}.`,data:{itemId:r.id,lotNumber:r.lot_number,title:r.title,nextMinimumBid:t.nextMinimumBid,closesAt:r.closes_at}}}function zm(t,e="USD"){if(t.status!=="sold"||!t.winnerEmail)return null;return{to:{name:t.winnerName??"Bidder",email:t.winnerEmail},type:"winner",subject:`You won lot ${t.lotNumber}: ${t.title}`,body:`Congratulations - you won "${t.title}" at ${so(t.amount,e)}. The school will be in touch with payment and pickup details.`,data:{itemId:t.itemId,lotNumber:t.lotNumber,title:t.title,amount:t.amount}}}function Gm(t,e,r,o="USD"){return{to:e,type:"closing_soon",subject:`Closing soon: lot ${t.lot_number}, ${t.title}`,body:`"${t.title}" closes at ${new Date(t.closes_at??"").toLocaleString()}. The current bid is ${so(r,o)}.`,data:{itemId:t.id,lotNumber:t.lot_number,title:t.title,currentBid:r,closesAt:t.closes_at}}}var co={};g(co,{fetchPledges:()=>uo,makePledge:()=>Mn,pledgeLevels:()=>In,pledgeTotal:()=>io});var{randomUUIDv7:Vm}=globalThis.Bun;import{db as Ge}from"@stacksjs/database";async function Mn(t){let e=Vm();await Ge.insertInto("pledges").values({uuid:e,auction_id:t.auctionId,donor_name:t.donorName,donor_email:t.donorEmail.toLowerCase(),amount:t.amount,level:t.level??null,status:t.status??"confirmed"}).execute();let r=await Ge.selectFrom("pledges").selectAll().where("uuid","=",e).executeTakeFirst();return await jr(r,await io(t.auctionId)).catch(()=>{return}),r}async function io(t){return(await Ge.selectFrom("pledges").select(["amount"]).where("auction_id","=",t).where("status","=","confirmed").execute()??[]).reduce((r,o)=>r+o.amount,0)}async function uo(t){return await Ge.selectFrom("pledges").selectAll().where("auction_id","=",t).orderBy("amount","desc").execute()??[]}async function In(t){let e=(await uo(t)).filter((o)=>o.status==="confirmed"),r=new Map;for(let o of e){let n=o.level??"other",a=r.get(n)??{amount:0,count:0};a.amount+=o.amount,a.count+=1,r.set(n,a)}return[...r.entries()].map(([o,n])=>({level:o,...n})).sort((o,n)=>n.amount-o.amount)}var mo={};g(mo,{bulkDestroy:()=>Bn,bulkStore:()=>zn,bulkUpdate:()=>Zn,destroy:()=>Jn,fetchAll:()=>$n,fetchById:()=>Un,store:()=>jn,update:()=>qn});import{db as Nn}from"@stacksjs/database";function l(t){if(typeof t==="number")return Number.isFinite(t)?t:0;if(typeof t==="bigint")return Number(t);if(!t||typeof t!=="object")return 0;let e=t;for(let r of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if(e[r]!==void 0&&e[r]!==null)return l(e[r]);if(Array.isArray(t))return t.reduce((r,o)=>r+l(o),0);return 0}async function Jn(t){try{let e=await Nn.deleteFrom("carts").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete cart: ${e.message}`);throw e}}async function Bn(t){if(!t.length)return 0;try{let e=await Nn.deleteFrom("carts").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete carts: ${e.message}`);throw e}}import{db as On}from"@stacksjs/database";function qm(t){return t.replace(/_([a-z0-9])/g,(e,r)=>r.toUpperCase())}function d(t){if(t===null||typeof t!=="object")return t;let e={...t};for(let[r,o]of Object.entries(e)){if(!r.includes("_"))continue;let n=qm(r);if(!(n in e))e[n]=o}return e}function w(t){return t.map((e)=>d(e))}async function Un(t){let e=await On.selectFrom("carts").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function $n(){return w(await On.selectFrom("carts").selectAll().execute())}var{randomUUIDv7:Wn}=globalThis.Bun;import{db as Ln}from"@stacksjs/database";async function jn(t){try{let e={...t,uuid:Wn()},r=await Ln.insertInto("carts").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create cart");return d(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create cart: ${e.message}`);throw e}}async function zn(t){if(!t.length)return 0;let e=0;try{return await Ln.transaction(async(r)=>{for(let o of t){let n={...o,uuid:Wn()};await r.insertInto("carts").values(n).execute(),e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create carts in bulk: ${r.message}`);throw r}}import{db as Gn}from"@stacksjs/database";import{formatDate as Vn}from"@stacksjs/orm";async function qn(t,e){try{let r=await Gn.updateTable("carts").set({...e,updated_at:Vn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update cart");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update cart: ${r.message}`);throw r}}async function Zn(t){if(!t.length)return 0;let e=0;try{return await Gn.transaction(async(r)=>{for(let o of t){if(!o.id)continue;let n=await r.updateTable("carts").set({...o,updated_at:Vn(new Date)}).where("id","=",o.id).executeTakeFirst();if(Number(n.numUpdatedRows)>0)e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update carts in bulk: ${r.message}`);throw r}}var po={};g(po,{deleteCoupon:()=>Kn,deleteCoupons:()=>Hn,deleteExpiredCoupons:()=>Qn,fetchActive:()=>ra,fetchAll:()=>ea,fetchByCode:()=>ta,fetchById:()=>ye,fetchConversionRate:()=>ca,fetchCouponCounts:()=>na,fetchCouponCountsByType:()=>aa,fetchRedemptionStats:()=>sa,fetchRedemptionTrend:()=>ua,fetchStats:()=>oa,fetchTopRedeemedCoupons:()=>ia,getActiveCouponsMoMChange:()=>da,redeem:()=>ga,store:()=>pa,update:()=>ha});import{db as Rt}from"@stacksjs/database";import{formatDate as Zm}from"@stacksjs/orm";async function Kn(t){let e=await Rt.deleteFrom("coupons").where("id","=",t).executeTakeFirst();return l(e)>0}async function Hn(t){if(!t.length)return 0;return await Rt.deleteFrom("coupons").where("id","in",t).execute()||0}async function Qn(){let t=Zm(new Date),e=await Rt.deleteFrom("coupons").where("end_date","<",t).executeTakeFirst();return l(e)}import{db as h}from"@stacksjs/database";import{extractDate as Yn,formatDate as Xn}from"@stacksjs/orm";import{camelCase as Km}from"@stacksjs/strings";function Dt(t){let e=Object.fromEntries(Object.entries(t).map(([r,o])=>[Km(r),o]));if(e.endDate)e.endDate=Yn(new Date(e.endDate));if(e.startDate)e.startDate=Yn(new Date(e.startDate));if(e.isActive!==void 0)e.isActive=Boolean(e.isActive);return e}async function ea(){let t=await h.selectFrom("coupons").selectAll().execute();return w(t).map(Dt)}async function ye(t){let e=await h.selectFrom("coupons").where("id","=",t).selectAll().executeTakeFirst();if(e)return Dt(d(e));return}async function ta(t){let e=await h.selectFrom("coupons").where("code","=",t).selectAll().executeTakeFirst();if(e)return Dt(d(e));return}async function ra(){let t=Xn(new Date),e=await h.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).selectAll().execute();return w(e).map(Dt)}async function oa(){let t=await h.selectFrom("coupons").select(h.fn.count("id").as("count")).executeTakeFirst(),e=Xn(new Date),r=await h.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(h.fn.count("id").as("count")).executeTakeFirst(),o=await h.selectFrom("coupons").select(["discount_type",h.fn.count("id").as("count")]).groupBy("discount_type").execute(),n=await h.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),a=await h.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",e).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(t?.count||0),active:Number(r?.count||0),by_type:o,most_used:n,upcoming:a}}async function na(){let t=new Date,e=new Date(t);e.setDate(t.getDate()-7);let r=new Date(t);r.setMonth(t.getMonth()-1);let o=new Date(t);o.setFullYear(t.getFullYear()-1);let n=await xt(null,null,t),a=await xt(e,null,t),s=await xt(r,null,t),i=await xt(o,null,t);return{week:a,month:s,year:i,all_time:n}}async function xt(t,e,r){let o=h.selectFrom("coupons");if(t)o=o.where("created_at",">=",t.toISOString());if(e)o=o.where("created_at","<=",e.toISOString());let n=await o.select(h.fn.count("id").as("count")).executeTakeFirst(),a=h.selectFrom("coupons");if(t)a=a.where("created_at",">=",t.toISOString());if(e)a=a.where("created_at","<=",e.toISOString());a=a.where("is_active","=",!0).where("start_date","<=",r).where("end_date",">=",r);let s=await a.select(h.fn.count("id").as("count")).executeTakeFirst(),i=Number(n?.count||0),u=Number(s?.count||0),c=i-u;return{total:i,active:u,inactive:c}}async function aa(){let t=new Date,e=await h.selectFrom("coupons").select("discount_type").distinct().execute(),r={};for(let{discount_type:o}of e){let n=await h.selectFrom("coupons").where("discount_type","=",o).select(h.fn.count("id").as("count")).executeTakeFirst(),a=await h.selectFrom("coupons").where("discount_type","=",o).where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(h.fn.count("id").as("count")).executeTakeFirst(),s=Number(n?.count||0),i=Number(a?.count||0);r[o]={total:s,active:i,inactive:s-i}}return r}async function sa(){let t=await h.selectFrom("coupons").select(h.fn.sum("usage_count").as("total")).executeTakeFirst(),e=new Date,r=new Date(e);r.setDate(e.getDate()-7);let o=new Date(e);o.setMonth(e.getMonth()-1);let n=new Date(e);n.setFullYear(e.getFullYear()-1);let a=await h.selectFrom("coupons").where("updated_at",">=",r.toISOString()).select(h.fn.sum("usage_count").as("total")).executeTakeFirst(),s=await h.selectFrom("coupons").where("updated_at",">=",o.toISOString()).select(h.fn.sum("usage_count").as("total")).executeTakeFirst(),i=await h.selectFrom("coupons").where("updated_at",">=",n.toISOString()).select(h.fn.sum("usage_count").as("total")).executeTakeFirst(),u=await h.selectFrom("coupons").select(["discount_type",h.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),c={};return u.forEach((m)=>{c[m.discount_type]=Number(m.total||0)}),{total:Number(t?.total||0),week:Number(a?.total||0),month:Number(s?.total||0),year:Number(i?.total||0),by_type:c}}async function ia(t=5){return await h.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(t).execute()}async function ua(t=30){let e=new Date().toISOString(),r=new Date;r.setDate(r.getDate()-t);let o=await h.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",r.toISOString()).where("updated_at","<=",e).where("usage_count",">",0).orderBy("updated_at","desc").execute(),n={};return o.forEach((a)=>{let s=a.updated_at?new Date(a.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!n[s])n[s]=0;n[s]+=a?.usage_count||0}),Object.entries(n).map(([a,s])=>({date:a,count:s}))}async function ca(){let t=new Date,e=await h.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(h.fn.count("id").as("count")).executeTakeFirst(),r=await h.selectFrom("coupons").where("usage_count",">",0).select(h.fn.count("id").as("count")).executeTakeFirst(),o=Number(e?.count||0),n=Number(r?.count||0);return{rate:o>0?n/o*100:0,total_active:o,total_redeemed:n}}async function da(){let t=new Date,e=new Date(t.getFullYear(),t.getMonth(),1),r=new Date(t.getFullYear(),t.getMonth()-1,1),o=new Date(t.getFullYear(),t.getMonth(),0),n=await h.selectFrom("coupons").select(h.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",e).executeTakeFirst(),a=await h.selectFrom("coupons").select(h.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",o).where("end_date",">=",r).executeTakeFirst(),s=Number(n?.count||0),i=Number(a?.count||0),u=s-i,c=i!==0?u/i*100:s>0?100:0;return{current_month:s,previous_month:i,difference:u,percentage_change:c}}var{randomUUIDv7:Hm}=globalThis.Bun;import{db as la}from"@stacksjs/database";import{HttpError as ma}from"@stacksjs/error-handling";import{isUniqueViolation as Qm}from"@stacksjs/orm";async function pa(t){try{let e=Hm();await la.insertInto("coupons").values({...t,uuid:e}).executeTakeFirst();let r=await la.selectFrom("coupons").where("uuid","=",e).selectAll().executeTakeFirst();return d(r,!0)}catch(e){if(e instanceof ma)throw e;if(Qm(e))throw new ma(409,"A coupon with this code already exists");if(e instanceof Error)throw Error(`Failed to create coupon: ${e.message}`);throw e}}import{db as wa,sqlHelpers as Ym}from"@stacksjs/database";import{env as Xm}from"@stacksjs/env";import{HttpError as fa}from"@stacksjs/error-handling";import{formatDate as ya,isUniqueViolation as ep}from"@stacksjs/orm";async function ha(t,e){if(!await ye(t))return;try{return await wa.updateTable("coupons").set({...e,updated_at:ya(new Date)}).where("id","=",t).execute(),await ye(t)}catch(o){if(o instanceof fa)throw o;if(ep(o))throw new fa(409,"A coupon with this code already exists");if(o instanceof Error)throw Error(`Failed to update coupon: ${o.message}`);throw o}}async function ga(t){let e=Ym(Xm.DB_CONNECTION||"sqlite"),r=e.param,o=ya(new Date),a=await wa.unsafe(`UPDATE coupons
3
3
  SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ${r(1)}
4
4
  WHERE id = ${r(2)}
5
5
  AND (max_uses IS NULL OR usage_count < max_uses)
6
- AND is_active = ${t.boolTrue}
6
+ AND is_active = ${e.boolTrue}
7
7
  AND (start_date IS NULL OR start_date <= ${r(3)})
8
- AND (end_date IS NULL OR end_date >= ${r(4)})`,[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)}
8
+ AND (end_date IS NULL OR end_date >= ${r(4)})`,[o,t,o,o]);if(Number(a?.changes??a?.numUpdatedRows??a?.affectedRows??0)>0){let m=await ye(t);if(m)return{ok:!0,coupon:m};return{ok:!1,reason:"not-found"}}let i=await ye(t);if(!i)return{ok:!1,reason:"not-found"};if(!i.isActive)return{ok:!1,reason:"inactive"};let u=!i.startDate||i.startDate<=o,c=!i.endDate||i.endDate>=o;if(!u||!c)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var wo={};g(wo,{bulkDestroy:()=>Ra,destroy:()=>_a,fetchAll:()=>Da,fetchById:()=>vt,store:()=>Pa,update:()=>ka});import{db as ba}from"@stacksjs/database";async function _a(t){try{let e=await ba.deleteFrom("customers").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete customer: ${e.message}`);throw e}}async function Ra(t){if(!t.length)return 0;try{let e=await ba.deleteFrom("customers").where("id","in",t).executeTakeFirst();return l(e)||0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${e.message}`);throw e}}import{db as xa}from"@stacksjs/database";async function vt(t){let e=await xa.selectFrom("customers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Da(){return w(await xa.selectFrom("customers").selectAll().execute())}import{db as tp}from"@stacksjs/database";import{HttpError as va}from"@stacksjs/error-handling";import{isUniqueViolation as rp}from"@stacksjs/orm";function X(t){if(typeof t==="bigint")return fo(t);if(typeof t==="number")return fo(t);if(!t||typeof t!=="object")return;if(Array.isArray(t)){for(let r of t){let o=X(r);if(o!==void 0)return o}return}let e=t;for(let r of["lastInsertRowid","insertId","lastInsertId"]){let o=e[r];if(o===void 0||o===null)continue;let n=fo(o);if(n!==void 0)return n}return}function fo(t){let e=typeof t==="bigint"?Number(t):Number(t);if(!Number.isSafeInteger(e)||e<=0)return;return e}async function Pa(t){try{let e={...t,avatar:t.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},r=await tp.insertInto("customers").values(e).executeTakeFirst();if(!r)throw Error("Failed to create customer");let o=X(r);if(o===void 0)throw Error("Failed to create customer: the database reported no insert id");return await vt(o)}catch(e){if(e instanceof va)throw e;if(rp(e))throw new va(409,"A customer with this email already exists");if(e instanceof Error)throw Error(`Failed to create customer: ${e.message}`);throw e}}import{db as op}from"@stacksjs/database";import{HttpError as Fa}from"@stacksjs/error-handling";import{formatDate as np,isUniqueViolation as ap}from"@stacksjs/orm";async function ka(t,e){try{if(!t)throw Error("Customer ID is required for update");let r=await op.updateTable("customers").set({...e,updated_at:np(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Fa)throw r;if(ap(r))throw new Fa(409,"A customer with this email already exists");if(r instanceof Error)throw Error(`Failed to update customer: ${r.message}`);throw r}}var _o={};g(_o,{bulkDestroy:()=>Sa,bulkStore:()=>ja,calculateErrorRate:()=>Ia,calculatePrinterHealth:()=>Ja,countAll:()=>Ca,countPrintsByDeviceId:()=>Ma,countTotalPrints:()=>Aa,destroy:()=>Ea,downloadPrintDevices:()=>Ua,exportPrintDevices:()=>Ft,fetchAll:()=>Pt,fetchById:()=>ee,fetchErrorsByDeviceId:()=>Na,getPrinterStatusCounts:()=>Ba,store:()=>La,storePrintDevicesExport:()=>$a,update:()=>za,updatePrintCount:()=>Va,updateStatus:()=>Ga});import{db as Ta}from"@stacksjs/database";async function Ea(t){try{let e=await Ta.deleteFrom("print_devices").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print device: ${e.message}`);throw e}}async function Sa(t){if(!t.length)return 0;try{let e=await Ta.deleteFrom("print_devices").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print devices: ${e.message}`);throw e}}import{createSpreadsheet as sp}from"ts-spreadsheets";import{db as A}from"@stacksjs/database";async function ee(t){let e=await A.selectFrom("print_devices").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Pt(){return w(await A.selectFrom("print_devices").selectAll().execute())}async function Ca(){let t=await A.selectFrom("print_devices").select(A.fn.count("id").as("count")).executeTakeFirst();return Number(t?.count||0)}async function Aa(){let t=await A.selectFrom("print_devices").select(A.fn.sum("print_count").as("total")).executeTakeFirst();return Number(t?.total||0)}async function Ma(t){let e=await A.selectFrom("print_devices").select("print_count").where("id","=",t).executeTakeFirst();return Number(e?.print_count??0)}async function Ia(){let t=await A.selectFrom("receipts").select([A.fn.count("id").as("total"),A.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!t?.total||t.total===0)return 0;return Number(Number(t?.failed_count??0)/Number(t?.total??0)*100)}async function Na(t){let e=await A.selectFrom("receipts").where("print_device_id","=",t).where("status","=","failed").selectAll().execute();return w(e)}async function Ja(){let t=await A.selectFrom("print_devices").select([A.fn.count("id").as("total"),A.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!t?.total||t.total===0)return 0;return Number(Number(t?.online_count??0)/Number(t?.total??0)*100)}async function Ba(){return(await A.selectFrom("print_devices").select(["status",A.fn.count("id").as("count")]).groupBy("status").execute()).reduce((e,r)=>(e[r.status]=Number(r.count||0),e),{})}function yo(t,e,r=e){let o=t;return o[String(e)]??o[r]}function ip(t){if(t instanceof Date)return t;if(typeof t==="number")return new Date(t);if(typeof t==="string")return new Date(/^\d+$/.test(t)?Number(t):t);return new Date(Number.NaN)}function Oa(t,e,r=e){let o=yo(t,e,r);if(typeof o==="number")return o;let n=Number(o);return Number.isFinite(n)?n:0}function Ve(t,e,r=e){let o=yo(t,e,r);return o==null?"":String(o)}async function Ft(t="csv"){let e=await Pt(),r=up(e);return sp(r,{type:t})}function up(t){let e=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],r=t.map((o)=>[Oa(o,"id"),Ve(o,"name"),Ve(o,"macAddress","mac_address"),Ve(o,"location"),Ve(o,"terminal"),Ve(o,"status"),ip(yo(o,"lastPing","last_ping")).toLocaleString(),Oa(o,"printCount","print_count")]);return{headings:e,data:r}}async function Ua(t="csv",e){let r=await Ft(t),o=`print_devices_export_${new Date().toISOString().split("T")[0]}.${t}`;return r.download(e||o)}async function $a(t="csv",e){let r=await Ft(t),o=`print_devices_export_${new Date().toISOString().split("T")[0]}.${t}`;r.store(e||o)}var{randomUUIDv7:Wa}=globalThis.Bun;import{db as ho}from"@stacksjs/database";async function La(t){try{let e=Wa(),r={last_ping:0,print_count:0,...t,uuid:e};await ho.insertInto("print_devices").values(r).executeTakeFirst();let o=await ho.selectFrom("print_devices").where("uuid","=",e).selectAll().executeTakeFirst();return d(o,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create print device: ${e.message}`);throw e}}async function ja(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={last_ping:0,print_count:0,...r,uuid:Wa()};await ho.insertInto("print_devices").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${r.message}`);throw r}}import{db as go}from"@stacksjs/database";import{formatDate as bo}from"@stacksjs/orm";async function za(t,e){if(!await ee(t))return;try{return await go.updateTable("print_devices").set({...e,updated_at:bo(new Date)}).where("id","=",t).execute(),await ee(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print device: ${o.message}`);throw o}}async function Ga(t,e){if(!await ee(t))throw Error(`Print device with ID ${t} not found`);try{return await go.updateTable("print_devices").set({status:e,updated_at:bo(new Date)}).where("id","=",t).execute(),await ee(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print device status: ${o.message}`);throw o}}async function Va(t,e){if(!await ee(t))throw Error(`Print device with ID ${t} not found`);try{return await go.updateTable("print_devices").set({print_count:e,updated_at:bo(new Date)}).where("id","=",t).execute(),await ee(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print count: ${o.message}`);throw o}}var Do={};g(Do,{bulkDestroy:()=>Za,bulkUpdateStatus:()=>rs,destroy:()=>qa,destroyGroup:()=>Ka,fetchAll:()=>Tt,fetchByGroup:()=>Ya,fetchById:()=>Ha,fetchGrouped:()=>Qa,fetchStats:()=>Xa,fetchTimeline:()=>es,ignoreGroup:()=>ns,resolveGroup:()=>os,unresolveGroup:()=>as,update:()=>ts});import{db as Ro}from"@stacksjs/database";import{log as xo}from"@stacksjs/logging";async function qa(t){try{return await Ro.deleteFrom("errors").where("id","=",t).execute(),!0}catch(e){return xo.error("[commerce/errors] destroy failed",{id:t,error:e}),!1}}async function Za(t){try{return await Ro.deleteFrom("errors").where("id","in",t).execute(),!0}catch(e){return xo.error("[commerce/errors] bulkDestroy failed",{count:t.length,error:e}),!1}}async function Ka(t,e){try{return await Ro.deleteFrom("errors").where("type","=",t).where("message","=",e).execute(),!0}catch(r){return xo.error("[commerce/errors] destroyGroup failed",{type:t,message:e,error:r}),!1}}import{db as kt}from"@stacksjs/database";async function Ha(t){return await kt.selectFrom("errors").where("id","=",t).selectAll().executeTakeFirst()}async function Tt(){return await kt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function Qa(){let t=await kt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),e=new Map;for(let o of t){let n=`${o.type}:${o.message}`;if(!e.has(n))e.set(n,{errors:[],firstSeen:new Date(o.created_at),lastSeen:new Date(o.created_at)});let a=e.get(n);a.errors.push(o);let s=new Date(o.created_at);if(s<a.firstSeen)a.firstSeen=s;if(s>a.lastSeen)a.lastSeen=s}let r=[];for(let[o,n]of e){let a=n.errors[0];if(!a)continue;let s=n.errors.find((u)=>u.status!==null)?.status,i="unresolved";if(s===1)i="resolved";else if(s===2)i="ignored";r.push({id:a.id,type:a.type,message:a.message,stack:a.stack,status:i,count:n.errors.length,first_seen:n.firstSeen.toISOString(),last_seen:n.lastSeen.toISOString(),error_ids:n.errors.map((u)=>u.id)})}return r.sort((o,n)=>new Date(n.last_seen).getTime()-new Date(o.last_seen).getTime()),r}async function Ya(t,e){return await kt.selectFrom("errors").where("type","=",t).where("message","=",e).selectAll().orderBy("created_at","desc").execute()}async function Xa(){let t=await Tt(),e=new Date,r=new Date(e.getTime()-86400000),o=new Date(e.getTime()-172800000),n=t.filter((i)=>new Date(i.created_at)>=r).length,a=t.filter((i)=>{let u=new Date(i.created_at);return u>=o&&u<r}).length,s=a===0?n>0?100:0:Math.round((n-a)/a*100);return{total:t.length,unresolved:t.filter((i)=>i.status===null||i.status===0).length,resolved:t.filter((i)=>i.status===1).length,ignored:t.filter((i)=>i.status===2).length,last_24h:n,trend:s}}async function es(){let t=await Tt(),e=new Date,r=[];for(let o=23;o>=0;o--){let n=new Date(e.getTime()-o*60*60*1000);n.setMinutes(0,0,0);let a=new Date(n.getTime()+3600000),s=t.filter((i)=>{let u=new Date(i.created_at);return u>=n&&u<a}).length;r.push({hour:n.toISOString(),count:s})}return r}import{db as qe}from"@stacksjs/database";import{sql as Ze}from"@stacksjs/database";import{log as Ke}from"@stacksjs/logging";async function ts(t,e){try{return await qe.updateTable("errors").set({...e,updated_at:Ze.raw("CURRENT_TIMESTAMP")}).where("id","=",t).execute(),!0}catch(r){return Ke.error("[commerce/errors] update failed",{id:t,error:r}),!1}}async function rs(t,e){try{return await qe.updateTable("errors").set({status:e,updated_at:Ze.raw("CURRENT_TIMESTAMP")}).where("id","in",t).execute(),!0}catch(r){return Ke.error("[commerce/errors] bulkUpdateStatus failed",{count:t.length,status:e,error:r}),!1}}async function os(t,e){try{return await qe.updateTable("errors").set({status:1,updated_at:Ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ke.error("[commerce/errors] resolveGroup failed",{type:t,message:e,error:r}),!1}}async function ns(t,e){try{return await qe.updateTable("errors").set({status:2,updated_at:Ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ke.error("[commerce/errors] ignoreGroup failed",{type:t,message:e,error:r}),!1}}async function as(t,e){try{return await qe.updateTable("errors").set({status:0,updated_at:Ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ke.error("[commerce/errors] unresolveGroup failed",{type:t,message:e,error:r}),!1}}var Fo={};g(Fo,{bulkDestroy:()=>ys,calculateGiftCardValues:()=>ls,checkBalance:()=>cs,compareActiveGiftCards:()=>ds,deactivate:()=>gs,destroy:()=>ws,destroyExpired:()=>hs,fetchActive:()=>is,fetchAll:()=>ss,fetchByCode:()=>vo,fetchById:()=>te,fetchStats:()=>us,fetchTotalCurrentBalance:()=>ps,fetchTotalValue:()=>ms,store:()=>_s,update:()=>vs,updateBalance:()=>Ps});import{db as Et}from"@stacksjs/database";import{formatDate as fs}from"@stacksjs/orm";import{db as P,sql as I}from"@stacksjs/database";import{formatDate as de,toTimestamp as Pe}from"@stacksjs/orm";import{aggregateFunctions as cp,db as dp}from"@stacksjs/database";async function J(t,e,r){let o=dp.selectFrom(t);if(r)o=r(o);o=o.select(Object.entries(e).map(([s,i])=>{let u=i.column??"id",c=cp[i.kind](u);if(i.filter)c=c.filterWhere(i.filter.column,i.filter.op,i.filter.value);return c.as(s)}));let n=await o.executeTakeFirst(),a={};for(let s of Object.keys(e)){let i=n?.[s];a[s]=typeof i==="number"?i:Number(i??0)||0}return a}async function ss(){let t=await P.selectFrom("gift_cards").selectAll().execute();return w(t)}async function te(t){let e=await P.selectFrom("gift_cards").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function vo(t){let e=await P.selectFrom("gift_cards").where("code","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function is(){let t=await P.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute();return w(t)}async function us(){let{count:t}=await J("gift_cards",{count:{kind:"count"}}),e=Pe(new Date),r=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(e)} OR expiry_date IS NULL)`).select(P.fn.count("id").as("count")).executeTakeFirst(),o=await P.selectFrom("gift_cards").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute(),{count:n}=await J("gift_cards",{count:{kind:"count"}},(m)=>m.whereRaw(I`current_balance / initial_balance < 0.25`)),{count:a}=await J("gift_cards",{count:{kind:"count"}},(m)=>m.whereRaw(I`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:s}=await J("gift_cards",{count:{kind:"count"}},(m)=>m.whereRaw(I`current_balance / initial_balance > 0.75`)),i=new Date;i.setDate(i.getDate()+30);let u=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",Pe(i)).where("expiry_date",">=",e).selectAll().limit(5).execute(),c=await P.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:t,active:Number(r?.count||0),by_status:o.map((m)=>({status:m.status,count:Number(m.count)})),by_balance:{low:n,medium:a,high:s},expiring_soon:w(u),recently_used:w(c)}}async function cs(t){let e=await vo(t);if(!e)return{valid:!1,message:"Gift card not found"};if(!e.isActive||e.status!=="ACTIVE")return{valid:!1,balance:e.currentBalance,currency:e.currency,message:`Gift card is ${e.status.toLowerCase()}`};if(e.expiryDate){if(new Date(e.expiryDate)<new Date)return{valid:!1,balance:e.currentBalance,currency:e.currency,message:"Gift card has expired"}}return{valid:!0,balance:e.currentBalance,currency:e.currency}}async function ds(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(Pe(e))} OR expiry_date IS NULL)`).where("created_at",">=",de(r)).where("created_at","<=",de(e)).executeTakeFirst(),s=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(Pe(n))} OR expiry_date IS NULL)`).where("created_at",">=",de(n)).where("created_at","<=",de(o)).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,m=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:m,days_range:t}}async function ls(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(Pe(e))} OR expiry_date IS NULL)`).where("created_at",">=",de(r)).where("created_at","<=",de(e)).executeTakeFirst(),s=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(Pe(n))} OR expiry_date IS NULL)`).where("created_at",">=",de(n)).where("created_at","<=",de(o)).executeTakeFirst(),i=Number(a?.total_initial||0),u=Number(a?.total_balance||0),c=Number(a?.card_count||0),m=Number(s?.total_initial||0),p=Number(s?.total_balance||0),f=Number(s?.card_count||0),y=i>0?(i-u)/i*100:0,b=m>0?(m-p)/m*100:0,R=c>0?i/c:0,v=c>0?u/c:0,V=i-m,fe=u-p,we=c-f,De=m!==0?V/m*100:i>0?100:0,q=p!==0?fe/p*100:u>0?100:0,Jm=f!==0?we/f*100:c>0?100:0;return{current_period:{total_initial_value:i,total_remaining_balance:u,utilization_rate:y,card_count:c,average_initial_value:R,average_remaining_balance:v},previous_period:{total_initial_value:m,total_remaining_balance:p,utilization_rate:b,card_count:f},comparison:{initial_value:{difference:V,percentage:Math.abs(De),is_increase:V>=0},balance:{difference:fe,percentage:Math.abs(q),is_increase:fe>=0},card_count:{difference:we,percentage:Math.abs(Jm),is_increase:we>=0}},days_range:t}}async function ms(){let{total_value:t}=await J("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:t}}async function ps(){let{total_balance:t}=await J("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:t}}async function ws(t){let e=await Et.deleteFrom("gift_cards").where("id","=",t).executeTakeFirst();return l(e)>0}async function ys(t){if(!t.length)return 0;let e=await Et.deleteFrom("gift_cards").where("id","in",t).executeTakeFirst();return l(e)}async function hs(){let t=fs(new Date),e=await Et.deleteFrom("gift_cards").where("expiry_date","<",t).executeTakeFirst();return l(e)}async function gs(t){if(!await te(t))throw Error(`Gift card with ID ${t} not found`);let r=await Et.updateTable("gift_cards").set({is_active:!1,status:"DEACTIVATED",updated_at:fs(new Date)}).where("id","=",t).executeTakeFirst();return l(r)>0}var{randomUUIDv7:lp}=globalThis.Bun;import{db as Po}from"@stacksjs/database";import{HttpError as bs}from"@stacksjs/error-handling";import{isUniqueViolation as mp}from"@stacksjs/orm";async function _s(t){let e=t,r={...t,current_balance:e.current_balance??e.initial_balance,status:t.status||"ACTIVE",is_active:e.is_active??!0,uuid:lp()};try{let o=await Po.insertInto("gift_cards").values(r).executeTakeFirst(),n=X(o);if(n!==void 0){let s=await Po.selectFrom("gift_cards").where("id","=",n).selectAll().executeTakeFirst();return d(s)}let a=await Po.selectFrom("gift_cards").where("uuid","=",r.uuid).selectAll().executeTakeFirst();return d(a,!0)}catch(o){if(o instanceof bs)throw o;if(mp(o))throw new bs(409,"A gift card with this code already exists");if(o instanceof Error)throw Error(`Failed to create gift card: ${o.message}`);throw o}}import{db as xs,sqlHelpers as pp}from"@stacksjs/database";import{env as fp}from"@stacksjs/env";import{HttpError as Rs}from"@stacksjs/error-handling";import{formatDate as Ds,isUniqueViolation as wp}from"@stacksjs/orm";async function vs(t,e){if(!await te(t))return;try{return await xs.updateTable("gift_cards").set({...e,updated_at:Ds(new Date)}).where("id","=",t).execute(),await te(t)}catch(o){if(o instanceof Rs)throw o;if(wp(o))throw new Rs(409,"A gift card with this code already exists");if(o instanceof Error)throw Error(`Failed to update gift card: ${o.message}`);throw o}}async function Ps(t,e){if(!Number.isFinite(e))throw Error(`Gift card balance adjustment must be a finite number, got ${e}`);let r=pp(fp.DB_CONNECTION||"sqlite"),o=r.param,n=Ds(new Date),a=e<0,s=e>0,i=s?`(status = 'ACTIVE' OR (status = 'USED' AND is_reloadable = ${r.boolTrue}))`:"status = 'ACTIVE'",u=[],c=(v)=>(u.push(v),o(u.length)),p=await xs.unsafe(`UPDATE gift_cards
9
+ SET current_balance = current_balance + ${c(e)},
10
+ ${a?`last_used_date = ${c(n)},
11
+ `:""}status = CASE WHEN current_balance + ${c(e)} = 0 THEN 'USED' ELSE 'ACTIVE' END,
12
+ updated_at = ${c(n)}
13
+ WHERE id = ${c(t)}
14
14
  AND is_active = ${r.boolTrue}
15
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
18
- SET inventory_count = inventory_count + ${o(1)},
19
- updated_at = ${o(2)}
20
- WHERE id = ${o(3)}
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
22
- SET refund_amount = COALESCE(refund_amount, 0) + ${n(1)},
23
- status = CASE WHEN COALESCE(refund_amount, 0) + ${n(2)} = amount
16
+ AND (expiry_date IS NULL OR expiry_date >= ${c(n)})
17
+ AND current_balance + ${c(e)} >= 0`,u);if(Number(p?.changes??p?.numUpdatedRows??p?.affectedRows??0)>0)return await te(t);let y=await te(t);if(!y)throw Error(`Gift card with ID ${t} not found`);let b=y;if(!b.is_active&&!b.isActive)throw Error("Gift card is not active");if(y.status==="USED"&&s&&!(b.is_reloadable??b.isReloadable))throw Error("Gift card is not reloadable");if(y.status!=="ACTIVE")throw Error("Gift card is not active");let R=b.expiry_date??b.expiryDate;if(R&&String(R)<n)throw Error("Gift card has expired");throw Error("Insufficient gift card balance")}var Bo={};g(Bo,{bulkDestroy:()=>Ts,bulkSoftDelete:()=>Es,calculateOrderMetrics:()=>Js,canTransition:()=>He,cleanupAbandonedCarts:()=>oi,compareOrdersByPeriod:()=>Ns,destroy:()=>Fs,downloadOrders:()=>Cs,emitForStatus:()=>Ye,emitOrderCancelled:()=>Fe,emitOrderCreated:()=>Qe,emitOrderDelivered:()=>Mt,emitOrderPaid:()=>le,emitOrderRefunded:()=>ke,emitOrderShipped:()=>At,exportOrders:()=>Ct,fetchAll:()=>ko,fetchById:()=>re,fetchDailyOrderTrends:()=>Bs,fetchRecent:()=>Ms,fetchStats:()=>Is,findOrderByIdempotencyKey:()=>Nt,handleChargeRefunded:()=>No,handlePaymentIntentFailed:()=>Io,handlePaymentIntentSucceeded:()=>Mo,placeOrder:()=>qs,recomputeOrderTotals:()=>ei,registerCommerceWebhookHandlers:()=>Ys,softDelete:()=>ks,store:()=>Us,storeOrdersExport:()=>As,update:()=>Zs,updateDeliveryInfo:()=>Hs,updateStatus:()=>Ks,validateCartQuantities:()=>ri,validateCouponStacking:()=>ti,validateQuantityBounds:()=>Jo});import{db as St}from"@stacksjs/database";async function Fs(t){try{let e=await St.deleteFrom("orders").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete order: ${e.message}`);throw e}}async function ks(t){try{let e=await St.updateTable("orders").set({status:"CANCELED"}).where("id","=",t).executeTakeFirst();return Number(e.numUpdatedRows)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete order: ${e.message}`);throw e}}async function Ts(t){if(!t.length)return 0;try{let e=await St.deleteFrom("orders").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete orders: ${e.message}`);throw e}}async function Es(t){if(!t.length)return 0;try{let e=await St.updateTable("orders").set({status:"CANCELED"}).where("id","in",t).executeTakeFirst();return Number(e.numUpdatedRows)}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete orders: ${e.message}`);throw e}}import{db as Ss}from"@stacksjs/database";import{createSpreadsheet as yp}from"ts-spreadsheets";async function Ct(t="csv"){let e=await hp(),r=gp(e);return yp(r,{type:t})}async function hp(){let t=await Ss.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),e=t.map((a)=>a.id);if(e.length===0)return[];let o=(await Ss.selectFrom("order_items").where("order_items.order_id","in",e).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((a,s)=>{if(!s.order_id)return a;if(!a[s.order_id])a[s.order_id]={totalItems:0,totalPrice:0};return a[s.order_id].totalItems+=s.quantity,a[s.order_id].totalPrice+=s.price*s.quantity,a},{});return t.map((a)=>{let s=o[a.id]||{totalItems:0,totalPrice:0};return{...a,totalItems:s.totalItems,totalPrice:s.totalPrice}})}function gp(t){let e=["Order ID","Customer","Date","Total","Status","Items"],r=t.map((o)=>{let n=o.order_items?.map((a)=>`${a.product?.name} (Qty: ${a.quantity}, Price: $${a.price})`).join(" | ")||"No Items";return[o.id,o.customer?.name||"N/A",o.created_at,o.total_amount,o.status,n]});return{headings:e,data:r}}async function Cs(t="csv",e){let r=await Ct(t),o=`orders_export_${new Date().toISOString().split("T")[0]}.${t}`;return r.download(e||o)}async function As(t="csv",e){let r=await Ct(t),o=`orders_export_${new Date().toISOString().split("T")[0]}.${t}`;r.store(e||o)}import{db as x}from"@stacksjs/database";async function ko(t){let e=x.selectFrom("orders").selectAll().orderBy("created_at","desc");if(t)e=e.limit(t);let r=w(await e.execute());return await Promise.all(r.map(async(o)=>{let n=await x.selectFrom("order_items").where("order_id","=",o.id).selectAll().execute();return{...o,items:n}}))}async function Ms(t=10){return ko(t)}async function re(t){let e=await x.selectFrom("orders").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Is(){let t=await x.selectFrom("orders").select(x.fn.count("id").as("count")).executeTakeFirst(),e=await x.selectFrom("orders").select(["status",x.fn.count("id").as("count")]).groupBy("status").execute(),r=await x.selectFrom("orders").select(["order_type",x.fn.count("id").as("count")]).groupBy("order_type").execute(),o=w(await x.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute()),n=await Promise.all(o.map(async(s)=>{let i=await x.selectFrom("order_items").where("order_id","=",s.id).selectAll().execute();return{...s,items:i}})),a=await x.selectFrom("orders").select(x.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(t?.count||0),by_status:e,by_type:r,recent:n,revenue:Number(a?.total||0)}}async function Ns(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await x.selectFrom("orders").select(x.fn.count("id").as("count")).where("created_at",">=",r.toISOString()).where("created_at","<=",e.toISOString()).executeTakeFirst(),s=await x.selectFrom("orders").select(x.fn.count("id").as("count")).where("created_at",">=",n.toISOString()).where("created_at","<=",o.toISOString()).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,m=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:m,days_range:t}}async function Js(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await x.selectFrom("orders").select([x.fn.count("id").as("total_orders"),x.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",r.toISOString()).where("created_at","<=",e.toISOString()).executeTakeFirst(),s=await x.selectFrom("orders").select([x.fn.count("id").as("total_orders"),x.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",n.toISOString()).where("created_at","<=",o.toISOString()).executeTakeFirst(),i=await x.selectFrom("orders").select(["status",x.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",e.toISOString()).groupBy("status").execute(),u=await x.selectFrom("orders").select(["order_type",x.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",e.toISOString()).groupBy("order_type").execute(),c=Number(a?.total_orders||0),m=Number(a?.total_revenue||0),p=c>0?m/c:0,f=Number(s?.total_orders||0),y=Number(s?.total_revenue||0),b=f>0?y/f:0,R=c-f,v=m-y,V=p-b,fe=f!==0?R/f*100:c>0?100:0,we=y!==0?v/y*100:m>0?100:0,De=b!==0?V/b*100:p>0?100:0;return{current_period:{total_orders:c,total_revenue:m,average_order_value:p,orders_by_status:i.map((q)=>({status:q.status,count:Number(q.count)})),orders_by_type:u.map((q)=>({order_type:q.order_type,count:Number(q.count)}))},previous_period:{total_orders:f,total_revenue:y,average_order_value:b},comparison:{orders:{difference:R,percentage:Math.abs(fe),is_increase:R>=0},revenue:{difference:v,percentage:Math.abs(we),is_increase:v>=0},average_order_value:{difference:V,percentage:Math.abs(De),is_increase:V>=0}},days_range:t}}async function Bs(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=await x.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",r.toISOString()).where("created_at","<=",e.toISOString()).orderBy("created_at","asc").execute(),n=new Map;for(let a of o){let s=(a.created_at||"").split("T")[0]||"unknown",i=n.get(s)||{order_count:0,revenue:0};i.order_count++,i.revenue+=Number(a.total_amount||0),n.set(s,i)}return Array.from(n.entries()).map(([a,s])=>({date:a,order_count:s.order_count,revenue:s.revenue}))}var{randomUUIDv7:bp}=globalThis.Bun;import{db as To}from"@stacksjs/database";import{formatDate as Os}from"@stacksjs/orm";async function Us(t){let e={...t,status:t.status||"PENDING",uuid:bp(),created_at:Os(new Date),updated_at:Os(new Date)};try{let r=await To.insertInto("orders").values(e).executeTakeFirst(),o=X(r);if(o!==void 0){let a=await To.selectFrom("orders").where("id","=",o).selectAll().executeTakeFirst();return d(a,!0)}let n=await To.selectFrom("orders").where("uuid","=",e.uuid).selectAll().executeTakeFirst();return d(n,!0)}catch(r){if(r instanceof Error)throw Error(`Failed to create order: ${r.message}`);throw r}}var{randomUUIDv7:js}=globalThis.Bun;import{db as It}from"@stacksjs/database";Te();import{formatDate as vp,isUniqueViolation as zs}from"@stacksjs/orm";import{sqlHelpers as Rp}from"@stacksjs/database";import{env as xp}from"@stacksjs/env";function Dp(t,e,r,o){let n=Rp(t).param;return{query:`UPDATE products
18
+ SET inventory_count = inventory_count + ${n(1)},
19
+ updated_at = ${n(2)}
20
+ WHERE id = ${n(3)}
21
+ AND inventory_count + ${n(4)} >= 0`,parameters:[r,o,e,r]}}async function Ls(t,e,r,o){let n=Dp(xp.DB_CONNECTION||"sqlite",e,r,o),a=await t.unsafe(n.query,n.parameters);return l(a)}var Gs=!1;function Vs(t){let e=t,r=e?.message??"";return e?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function Nt(t){try{let e=await It.selectFrom("order_idempotency").where("idempotency_key","=",t).selectAll().executeTakeFirst();if(!e)return null;return await It.selectFrom("orders").where("id","=",e.order_id).selectAll().executeTakeFirst()??null}catch(e){if(Vs(e)){if(!Gs)Gs=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw e}}async function qs(t){if(t.idempotencyKey){let e=await Nt(t.idempotencyKey);if(e)return{ok:!0,order:e}}try{let e=await It.transaction(async(r)=>{let o=vp(new Date),n=js(),a={...t.order,status:t.order.status||"PENDING",uuid:n,created_at:o,updated_at:o};await r.insertInto("orders").values(a).executeTakeFirst();let s=d(await r.selectFrom("orders").where("uuid","=",n).selectAll().executeTakeFirst(),!0),i=Number(s?.id);if(!Number.isSafeInteger(i)||i<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let u;if(t.items&&t.items.length>0){let p=t.items.map((f)=>{if(!Number.isInteger(f.productId)||f.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(f.quantity)||f.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(f.price)||f.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:i,product_id:f.productId,quantity:f.quantity,price:f.price,special_instructions:f.specialInstructions||null,created_at:o,updated_at:o}});await r.insertInto("order_items").values(p).execute(),u=w(await r.selectFrom("order_items").where("order_id","=",i).selectAll().execute())}let c;if(t.payment)try{let p=js();if(await r.insertInto("payments").values({...t.payment,order_id:i,uuid:p,created_at:o,updated_at:o}).executeTakeFirst(),c=d(await r.selectFrom("payments").where("uuid","=",p).selectAll().executeTakeFirst(),!0),!c)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(p){if(zs(p))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(p,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(t.inventory&&t.inventory.length>0)for(let p=0;p<t.inventory.length;p++){let{id:f,delta:y}=t.inventory[p];if(!Number.isFinite(y)||y===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await Ls(r,f,y,o))throw Object.assign(Error(`inventory adjust failed for product ${f}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(t.idempotencyKey)try{await r.insertInto("order_idempotency").values({idempotency_key:t.idempotencyKey,order_id:i,created_at:o}).execute()}catch(p){if(zs(p))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!Vs(p))throw p}let m=d(await r.selectFrom("orders").where("id","=",i).selectAll().executeTakeFirst(),!0);if(!m)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:m,items:u,payment:c}});if(Qe(e.order),e.payment)le(e.order,e.payment);return{ok:!0,order:e.order,items:e.items,payment:e.payment}}catch(e){if(e?.__placeFail){if(e.reason==="duplicate-idempotency-key"&&t.idempotencyKey){let r=await Nt(t.idempotencyKey);if(r)return{ok:!0,order:r}}return{ok:!1,reason:e.reason,failedAt:e.failedAt,error:e}}throw e}}Te();import{db as Eo}from"@stacksjs/database";import{formatDate as So}from"@stacksjs/orm";Te();async function Zs(t,e){if(!await re(t))return;try{return await Eo.updateTable("orders").set({...e,updated_at:So(new Date)}).where("id","=",t).execute(),await re(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update order: ${o.message}`);throw o}}async function Ks(t,e){let r=await re(t);if(!r)throw Error(`Order with ID ${t} not found`);let o=r.status??"PENDING";if(!He(o,e))throw Error(`[commerce/orders] illegal status transition ${o} \u2192 ${e}`);try{await Eo.updateTable("orders").set({status:e,updated_at:So(new Date)}).where("id","=",t).execute();let n=await re(t);if(n)Ye(e,n);return n}catch(n){if(n instanceof Error)throw TypeError(`Failed to update order status: ${n.message}`);throw n}}async function Hs(t,e,r){let o=await re(t);if(!o)throw Error(`Order with ID ${t} not found`);let n={updated_at:So(new Date)};if(e!==void 0)n.delivery_address=e;if(r!==void 0)n.estimated_delivery_time=r;if(Object.keys(n).length===1)return o;try{return await Eo.updateTable("orders").set(n).where("id","=",t).execute(),await re(t)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery information: ${a.message}`);throw a}}Te();import{db as Ee}from"@stacksjs/database";import{formatDate as Jt}from"@stacksjs/orm";async function Co(t){let e=await Ee.selectFrom("payments").where("transaction_id","=",t).selectAll().executeTakeFirst();if(!e)return null;return await Ee.selectFrom("orders").where("id","=",e.order_id).selectAll().executeTakeFirst()??null}var Qs=!1;function Pp(t){let e=t,r=e?.message??"";return e?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function Ao(t,e){try{return await e.insertInto("stripe_webhook_events").values({event_id:t,processed_at:Jt(new Date)}).execute(),!0}catch(r){if(r?.message?.includes("UNIQUE constraint")||r?.message?.includes("Duplicate entry"))return!1;if(Pp(r)){if(!Qs)Qs=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing - Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw r}}async function Mo(t){let r=t.data.object?.id;if(!r)return;await Ee.transaction(async(n)=>{if(!await Ao(t.id,n))return;let s=await n.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!s)return;let i=Jt(new Date);await n.updateTable("payments").set({status:"succeeded",updated_at:i}).where("id","=",s.id).execute();let u=await n.selectFrom("orders").where("id","=",s.order_id).selectAll().executeTakeFirst();if(u&&u.status==="PENDING")await n.updateTable("orders").set({status:"PROCESSING",updated_at:i}).where("id","=",u.id).execute()});let o=await Co(r);if(o)await le(o)}async function Io(t){let e=t.data.object,r=e?.id;if(!r)return;let n=e?.last_payment_error?.message??"payment failed";await Ee.transaction(async(s)=>{if(!await Ao(t.id,s))return;let u=await s.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!u)return;let c=Jt(new Date);await s.updateTable("payments").set({status:"failed",failure_reason:n,updated_at:c}).where("id","=",u.id).execute();let m=await s.selectFrom("orders").where("id","=",u.order_id).selectAll().executeTakeFirst();if(m&&m.status==="PENDING")await s.updateTable("orders").set({status:"CANCELLED",updated_at:c}).where("id","=",m.id).execute()});let a=await Co(r);if(a)await Fe(a,n)}async function No(t){let e=t.data.object,r=e?.payment_intent;if(!r)return;let o=e?.amount_refunded??0;await Ee.transaction(async(a)=>{if(!await Ao(t.id,a))return;let i=await a.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!i)return;let u=Jt(new Date);await a.updateTable("payments").set({status:"refunded",refund_amount:o,updated_at:u}).where("id","=",i.id).execute();let c=await a.selectFrom("orders").where("id","=",i.order_id).selectAll().executeTakeFirst();if(c&&c.status!=="REFUNDED")await a.updateTable("orders").set({status:"REFUNDED",updated_at:u}).where("id","=",c.id).execute()});let n=await Co(r);if(n)await ke(n,o)}async function Ys(){let t=await import("@stacksjs/payments").catch(()=>null);if(!t)return console.warn("[commerce/webhook] @stacksjs/payments not installed - Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:e,onCharge:r}=t;if(typeof e!=="function"||typeof r!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed - handlers NOT registered"),()=>{};return e({succeeded:Mo,failed:Io}),r({refunded:No}),()=>{}}import{db as Xs}from"@stacksjs/database";async function Fp(t){if(t.length===0)return new Map;let e=await Xs.selectFrom("products").where("id","in",t).select(["id","price"]).execute(),r=new Map;for(let o of e){let n=Number(o.price);if(Number.isFinite(n))r.set(o.id,Math.round(n))}return r}async function kp(t){try{let e=await Xs.selectFrom("tax_rates").where("id","=",t).select(["rate"]).executeTakeFirst(),r=Number(e?.rate??0);return Number.isFinite(r)?r:0}catch{return 0}}async function ei(t){let e=t.items.map((b)=>b.productId),r=await Fp(e),o=t.taxRateId!=null?await kp(t.taxRateId):0,n=0,a=[];for(let b of t.items){let R=b.unitPriceCents??r.get(b.productId)??0,v=Math.round(R*b.quantity);n+=v,a.push({productId:b.productId,quantity:b.quantity,unitPriceCents:R,lineCents:v})}let s=Math.max(0,t.discountCents??0),i=Math.max(0,n-s),u=Math.round(i*o),c=Math.max(0,t.shippingCents??0),m=n-s+u+c,p=t.maxDriftCents??5,f=!1,y=0;if(t.clientTotalCents!=null)y=Math.abs(m-t.clientTotalCents),f=y>p;return{subtotalCents:n,discountCents:s,taxCents:u,shippingCents:c,totalCents:m,resolvedItems:a,priceChanged:f,diffCents:y}}import{db as Bt,sqlHelpers as Tp}from"@stacksjs/database";import{env as Ep}from"@stacksjs/env";function ti(t,e={}){let r=t.length;if(r<=1)return{ok:!0,count:r};if(!e.allowMultiple)return{ok:!1,count:r,reason:"multiple-not-allowed"};let o=e.maxStacked??Number.POSITIVE_INFINITY;if(r>o)return{ok:!1,count:r,reason:"exceeds-max-stacked"};return{ok:!0,count:r}}async function Jo(t,e){if(!Number.isFinite(e)||e<=0)return{ok:!1,productId:t,quantity:e,reason:"non-positive"};let r;try{r=await Bt.selectFrom("products").where("id","=",t).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:t,quantity:e}}if(!r)return{ok:!1,productId:t,quantity:e,reason:"product-missing"};let o=r.min_order_qty??null,n=r.max_order_qty??null;if(o!=null&&e<o)return{ok:!1,productId:t,quantity:e,reason:"below-min",bound:o};if(n!=null&&e>n)return{ok:!1,productId:t,quantity:e,reason:"above-max",bound:n};return{ok:!0,productId:t,quantity:e}}async function ri(t){for(let r of t){let o=await Jo(r.productId,r.quantity);if(!o.ok)return o}let e=t[t.length-1]??{productId:0,quantity:0};return{ok:!0,productId:e.productId,quantity:e.quantity}}async function oi(t={}){let e=t.olderThanDays??30,r=t.limit??1000,n=new Date(Date.now()-e*24*60*60*1000).toISOString().slice(0,19).replace("T"," "),a=Tp(Ep.DB_CONNECTION||"sqlite").param;try{let i=await Bt.unsafe(`DELETE FROM carts WHERE updated_at < ${a(1)} AND id IN (SELECT id FROM carts WHERE updated_at < ${a(2)} LIMIT ${a(3)})`,[n,n,r]);return{deleted:Number(i?.changes??i?.numDeletedRows??i?.[0]?.numDeletedRows??i?.affectedRows??0),cutoffAt:n}}catch{try{let s=await Bt.selectFrom("carts").where("updated_at","<",n).select(["id"]).limit(r).execute();if(s.length===0)return{deleted:0,cutoffAt:n};let i=s.map((m)=>m.id),u=await Bt.deleteFrom("carts").where("id","in",i).execute();return{deleted:Number(u?.numDeletedRows??u?.[0]?.numDeletedRows??u?.affectedRows??s.length),cutoffAt:n}}catch{return{deleted:0,cutoffAt:n}}}}var Oo={};g(Oo,{bulkDestroy:()=>si,destroy:()=>ai,fetchAll:()=>ii,fetchById:()=>ge,fetchMonthlyPaymentTrends:()=>di,fetchPaymentStats:()=>ui,fetchPaymentStatsByMethod:()=>ci,recordRefund:()=>hi,store:()=>pi,update:()=>yi});import{db as ni}from"@stacksjs/database";async function ai(t){try{let e=await ni.deleteFrom("payments").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete payment: ${e.message}`);throw e}}async function si(t){if(!t.length)return 0;try{let e=await ni.deleteFrom("payments").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete payments: ${e.message}`);throw e}}import{db as S}from"@stacksjs/database";import{formatDate as W}from"@stacksjs/orm";async function ii(){let t=await S.selectFrom("payments").selectAll().execute();return w(t)}async function ge(t){let e=await S.selectFrom("payments").selectAll().where("id","=",t).executeTakeFirst();return d(e,!0)}async function ui(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await S.selectFrom("payments").select([S.fn.count("id").as("transaction_count"),S.fn.sum("amount").as("total_revenue")]).where("created_at",">=",W(r)).where("created_at","<=",W(e)).where("status","=","completed").executeTakeFirst(),s=await S.selectFrom("payments").select([S.fn.count("id").as("transaction_count"),S.fn.sum("amount").as("total_revenue")]).where("created_at",">=",W(n)).where("created_at","<=",W(o)).where("status","=","completed").executeTakeFirst(),i=await S.selectFrom("payments").select(S.fn.count("id").as("count")).where("created_at",">=",W(r)).where("created_at","<=",W(e)).executeTakeFirst(),u=Number(a?.transaction_count||0),c=Number(a?.total_revenue||0),m=u>0?c/u:0,p=Number(s?.transaction_count||0),f=Number(s?.total_revenue||0),y=p>0?f/p:0,b=u-p,R=c-f,v=m-y,V=p>0?b/p*100:u>0?100:0,fe=f>0?R/f*100:c>0?100:0,we=y>0?v/y*100:m>0?100:0,De=Number(i?.count||0),q=De>0?u/De*100:0;return{total_transactions:u,total_revenue:c,average_transaction:m,successful_rate:q,comparison:{transactions:{difference:b,percentage:Math.abs(V),is_increase:b>=0},revenue:{difference:R,percentage:Math.abs(fe),is_increase:R>=0},average:{difference:v,percentage:Math.abs(we),is_increase:v>=0}}}}async function ci(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=await S.selectFrom("payments").select([S.fn.count("id").as("total_count"),S.fn.sum("amount").as("total_revenue")]).where("created_at",">=",W(r)).where("created_at","<=",W(e)).where("status","=","completed").executeTakeFirst(),n=Number(o?.total_count||0),a=await S.selectFrom("payments").select(["method",S.fn.count("id").as("count"),S.fn.sum("amount").as("revenue")]).where("created_at",">=",W(r)).where("created_at","<=",W(e)).where("status","=","completed").groupBy("method").execute(),s={};return a.forEach((i)=>{let u=Number(i.count||0),c=Number(i.revenue||0),m=n>0?u/n*100:0;s[i.method]={count:u,revenue:c,percentage_of_total:m}}),s}async function di(){let t=new Date,e=new Date(t);e.setMonth(t.getMonth()-11),e.setDate(1);let r=await S.selectFrom("payments").selectAll().where("created_at",">=",W(e)).where("status","=","completed").execute(),o={};for(let a of r){let s=a.created_at?new Date(String(a.created_at)):new Date,i=s.getFullYear(),u=s.getMonth()+1,c=`${i}-${String(u).padStart(2,"0")}`;if(!o[c])o[c]={year:i,month:u,transactions:0,revenue:0};o[c].transactions++,o[c].revenue+=Number(a.amount||0)}return Object.keys(o).sort().map((a)=>{let s=o[a],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:Sp}=globalThis.Bun;import{db as li}from"@stacksjs/database";import{HttpError as mi}from"@stacksjs/error-handling";import{isUniqueViolation as Cp}from"@stacksjs/orm";async function pi(t){let e=Sp(),r={...t,status:t.status||"pending",currency:t.currency||"USD",uuid:e};try{await li.insertInto("payments").values(r).executeTakeFirst();let o=await li.selectFrom("payments").where("uuid","=",e).selectAll().executeTakeFirst();return d(o,!0)}catch(o){if(o instanceof mi)throw o;if(Cp(o))throw new mi(409,"A payment with this transaction ID already exists");if(o instanceof Error){if(o.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${o.message}`)}throw o}}import{db as fi,sqlHelpers as Ap}from"@stacksjs/database";import{env as Mp}from"@stacksjs/env";import{formatDate as wi}from"@stacksjs/orm";async function yi(t,e){if(!await ge(t))return;try{return await fi.updateTable("payments").set({...e,updated_at:wi(new Date)}).where("id","=",t).execute(),await ge(t)}catch(o){if(o instanceof Error){if(o.message.includes("Duplicate entry")&&o.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${o.message}`)}throw o}}var Ip=new Set(["completed","succeeded","partiallyRefunded"]);async function hi(t,e){if(!Number.isSafeInteger(t)||t<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger(e)||e<=0)throw TypeError("Refund amount must be a positive integer in minor units");let o=Ap(Mp.DB_CONNECTION||"sqlite").param,n=wi(new Date),s=await fi.unsafe(`UPDATE payments
22
+ SET refund_amount = COALESCE(refund_amount, 0) + ${o(1)},
23
+ status = CASE WHEN COALESCE(refund_amount, 0) + ${o(2)} = amount
24
24
  THEN 'refunded' ELSE 'partiallyRefunded' END,
25
- updated_at = ${n(3)}
26
- WHERE id = ${n(4)}
25
+ updated_at = ${o(3)}
26
+ WHERE id = ${o(4)}
27
27
  AND status IN ('completed', 'succeeded', 'partiallyRefunded')
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};
28
+ AND COALESCE(refund_amount, 0) + ${o(5)} <= amount`,[e,e,n,t,e]);if(Number(s?.numUpdatedRows??s?.[0]?.numUpdatedRows??s?.numAffectedRows??s?.affectedRows??s?.[0]?.affectedRows??s?.changes??0)>0){let f=await ge(t);if(f)return f;throw Error(`Payment with ID ${t} disappeared during refund`)}let u=await ge(t);if(!u)throw Error(`Payment with ID ${t} not found`);let c=String(u.status||"");if(!Ip.has(c))throw Error(`Payment status ${c||"unknown"} cannot be refunded`);let m=u,p=Number(u.amount||0)-Number(m.refundAmount??m.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${p} minor units`)}var Go={};g(Go,{categories:()=>$t,default:()=>Vp,items:()=>Wt,manufacturers:()=>Lt,reviews:()=>jt,units:()=>Vt,variants:()=>qt});var $t={};g($t,{bulkRemove:()=>ki,compareCategoryGrowth:()=>vi,deactivate:()=>Ei,deactivateChildCategories:()=>Si,fetchActive:()=>bi,fetchAll:()=>Uo,fetchByDisplayOrder:()=>xi,fetchById:()=>C,fetchByName:()=>gi,fetchCategoryTree:()=>Pi,fetchChildCategories:()=>Ri,fetchRootCategories:()=>_i,fetchStats:()=>Di,findOrCreateByName:()=>Ai,remove:()=>Fi,removeChildCategories:()=>Ti,store:()=>$o,update:()=>Mi,updateActiveStatus:()=>Ni,updateDisplayOrder:()=>Ii,updateParent:()=>Ji});import{db as Se}from"@stacksjs/database";import{db as F}from"@stacksjs/database";import{formatDate as Xe}from"@stacksjs/orm";async function Uo(){return await F.selectFrom("categories").selectAll().execute()}async function C(t){return await F.selectFrom("categories").where("id","=",t).selectAll().executeTakeFirst()}async function gi(t){return await F.selectFrom("categories").where("name","=",t).selectAll().executeTakeFirst()}async function bi(){return await F.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function _i(){return await F.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function Ri(t){return await F.selectFrom("categories").where("parent_category_id","=",t).where("is_active","=",!0).selectAll().execute()}async function xi(t=!0){let e=F.selectFrom("categories").where("is_active","=",!0).selectAll();if(t)return await e.orderBy("display_order","asc").execute();else return await e.orderBy("display_order","desc").execute()}async function Di(){let t=await F.selectFrom("categories").select(F.fn.count("id").as("count")).executeTakeFirst(),e=await F.selectFrom("categories").where("is_active","=",!0).select(F.fn.count("id").as("count")).executeTakeFirst(),r=await F.selectFrom("categories").whereNull("parent_category_id").select(F.fn.count("id").as("count")).executeTakeFirst(),o=await F.selectFrom("categories").whereNotNull("image_url").select(F.fn.count("id").as("count")).executeTakeFirst(),n=new Date;n.setDate(n.getDate()-30);let a=Xe(n),s=await F.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await F.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",F.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(t?.count||0),active:Number(e?.count||0),root_categories:Number(r?.count||0),child_categories:Number(t?.count||0)-Number(r?.count||0),with_images:Number(o?.count||0),recently_added:s,top_parent_categories:i.map((u)=>({id:String(u.parent_category_id||""),name:String(u.parent_name||""),child_count:Number(u.child_count)}))}}async function vi(t=30){let e=new Date,r=Xe(e),o=new Date;o.setDate(e.getDate()-t);let n=Xe(o),a=new Date(o);a.setDate(a.getDate()-1);let s=Xe(a),i=new Date(a);i.setDate(a.getDate()-t);let u=Xe(i),c=await F.selectFrom("categories").select(F.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",r).executeTakeFirst(),m=await F.selectFrom("categories").select(F.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),p=Number(c?.count||0),f=Number(m?.count||0),y=p-f,b=f!==0?y/f*100:p>0?100:0;return{current_period:p,previous_period:f,difference:y,percentage_change:b,days_range:t}}async function Pi(){let t=await Uo(),e=new Map;t.forEach((n)=>{e.set(n.id,{...n,children:[]})});let r=[];t.forEach((n)=>{let a=e.get(n.id);if(n.parent_category_id){let s=e.get(n.parent_category_id);if(s)s.children.push(a)}else r.push(a)}),r.sort((n,a)=>n.display_order-a.display_order);let o=(n)=>{n.sort((a,s)=>a.display_order-s.display_order),n.forEach((a)=>{if(a.children.length>0)o(a.children)})};return o(r),r}async function Fi(t){let e=await Se.deleteFrom("categories").where("id","=",t).executeTakeFirst();return l(e)>0}async function ki(t){if(!t.length)return 0;let e=await Se.deleteFrom("categories").where("id","in",t).executeTakeFirst();return l(e)}async function Ti(t){let e=await Se.deleteFrom("categories").where("parent_category_id","=",t).executeTakeFirst();return l(e)}async function Ei(t){if(!await C(t))throw Error(`Category with ID ${t} not found`);return!!await Se.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",t).executeTakeFirst()}async function Si(t){let e=await Se.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",t).execute();return Number(e)||0}var{randomUUIDv7:Np}=globalThis.Bun;import{db as Ci}from"@stacksjs/database";import{HttpError as Ot}from"@stacksjs/error-handling";import{isUniqueViolation as Jp}from"@stacksjs/orm";import{slug as Bp}from"@stacksjs/strings";async function $o(t){try{let e=t.parent_category_id?Number(t.parent_category_id):void 0;if(e!==void 0&&(!Number.isSafeInteger(e)||e<=0))throw new Ot(422,"Parent category ID must be a positive integer");if(e&&!await C(e))throw new Ot(422,`Parent category with ID ${t.parent_category_id} not found`);let r={...t,uuid:Np(),is_active:t.is_active??!0,parent_category_id:t.parent_category_id||null},o=await Ci.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create category");return o}catch(e){if(e instanceof Ot)throw e;if(Jp(e))throw new Ot(409,"A category with this name or slug already exists");if(e instanceof Error)throw Error(`Failed to create category: ${e.message}`);throw e}}async function Ai(t){if(!t.name)throw Error("Name is required");let e=await Ci.selectFrom("categories").selectAll().where("name","=",t.name).executeTakeFirst();if(e)return e;let r={name:t.name,slug:Bp(t.name),is_active:t.is_active??!0,display_order:0};return await $o(r)}import{db as et}from"@stacksjs/database";import{HttpError as Ce}from"@stacksjs/error-handling";import{formatDate as Ut,isUniqueViolation as Op}from"@stacksjs/orm";async function Mi(t,e){if(!await C(t))return;if(Object.hasOwn(e,"parent_category_id")){let o=e.parent_category_id?Number(e.parent_category_id):void 0;if(o!==void 0&&(!Number.isSafeInteger(o)||o<=0))throw new Ce(422,"Parent category ID must be a positive integer");if(o===t)throw new Ce(422,"A category cannot be its own parent");if(o&&!await C(o))throw new Ce(422,`Parent category with ID ${e.parent_category_id} not found`);if(o&&await Bi(t,String(o)))throw new Ce(422,"This operation would create a circular category hierarchy")}try{let o=Object.hasOwn(e,"parent_category_id")?{parent_category_id:e.parent_category_id||null}:{},n=await et.updateTable("categories").set({...e,...o,updated_at:Ut(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return n}catch(o){if(o instanceof Ce)throw o;if(Op(o))throw new Ce(409,"A category with this name or slug already exists");if(o instanceof Error)throw Error(`Failed to update category: ${o.message}`);throw o}}async function Ii(t,e){if(!await C(t))throw Error(`Category with ID ${t} not found`);try{return await et.updateTable("categories").set({display_order:e,updated_at:Ut(new Date)}).where("id","=",t).execute(),await C(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category display order: ${o.message}`);throw o}}async function Ni(t,e){if(!await C(t))throw Error(`Category with ID ${t} not found`);try{return await et.updateTable("categories").set({is_active:e,updated_at:Ut(new Date)}).where("id","=",t).execute(),await C(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category active status: ${o.message}`);throw o}}async function Ji(t,e){if(!await C(t))throw Error(`Category with ID ${t} not found`);if(e){let o=Number(e);if(o===t)throw Error("A category cannot be its own parent");if(!await C(o))throw Error(`Parent category with ID ${e} not found`);if(await Bi(t,e))throw Error("This operation would create a circular reference in the category hierarchy")}try{let o={updated_at:Ut(new Date)};if(e===null)await et.updateTable("categories").set({...o,parent_category_id:null}).where("id","=",t).execute();else await et.updateTable("categories").set({...o,parent_category_id:e}).where("id","=",t).execute();return await C(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category parent: ${o.message}`);throw o}}async function Bi(t,e){let r=Number(e),o=new Set;while(r){if(o.has(r))return!0;if(r===t)return!0;o.add(r);let n=await C(r),a=n?.parent_category_id;if(!n||!a)return!1;r=Number(a)}return!1}var Wt={};g(Wt,{bulkDestroy:()=>$i,bulkStore:()=>qi,destroy:()=>Ui,fetchAll:()=>Wi,fetchById:()=>ne,fetchTopProducts:()=>ji,store:()=>Vi,update:()=>Zi,updateAvailability:()=>Ki,updateInventory:()=>Hi});import{db as Oi}from"@stacksjs/database";async function Ui(t){try{let e=await Oi.deleteFrom("products").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product item: ${e.message}`);throw e}}async function $i(t){if(!t.length)return 0;try{let e=await Oi.deleteFrom("products").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product items: ${e.message}`);throw e}}import{db as oe,sql as Up}from"@stacksjs/database";async function ne(t){let e=await oe.selectFrom("products").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.manufacturer_id)r=await oe.selectFrom("manufacturers").where("id","=",e.manufacturer_id).selectAll().executeTakeFirst();if(e.category_id)o=await oe.selectFrom("categories").where("id","=",e.category_id).selectAll().executeTakeFirst();return{...e,manufacturer:r,category:o}}return}async function Wi(){let t=await oe.selectFrom("products").selectAll().execute(),e=t.map((c)=>c.manufacturer_id).filter((c)=>c!==null&&c!==void 0),r=t.map((c)=>c.category_id).filter((c)=>c!==null&&c!==void 0),o=oe.selectFrom("manufacturers"),n=oe.selectFrom("categories");if(e.length>0)o=o.where("id","in",e);if(r.length>0)n=n.where("id","in",r);let a=await o.selectAll().execute(),s=await n.selectAll().execute(),i=a.reduce((c,m)=>(c[m.id]=m,c),{}),u=s.reduce((c,m)=>(c[m.id]=m,c),{});return t.map((c)=>({...c,manufacturer:c.manufacturer_id?i[c.manufacturer_id]:null,category:c.category_id?u[c.category_id]:null}))}async function Li(t){try{let e=await oe.selectFrom("products").selectAll().where("uuid","=",t).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get product by UUID: ${e.message}`);throw e}}async function ji(t=5){try{return(await oe.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",oe.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(t).execute()).map((r)=>({id:Number(r.id),name:String(r.name??"Unnamed product"),units_sold:Number(r.units_sold??0),revenue:Number(r.revenue??0),inventory_count:Number(r.inventory_count??0)}))}catch(e){if(e instanceof Error)throw TypeError(`Failed to fetch top products: ${e.message}`);throw e}}var{randomUUIDv7:zi}=globalThis.Bun;import{db as Gi}from"@stacksjs/database";async function Vi(t){try{let e={...t,uuid:zi()},r=await Gi.insertInto("products").values(e).executeTakeFirst();if(!r)throw Error("Failed to create product item");let o=X(r),n=o!==void 0?await ne(o):await Li(e.uuid);if(!n)throw Error("Failed to create product item");return n}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product item: ${e.message}`);throw e}}async function qi(t){if(!t.length)return 0;let e=0;try{return await Gi.transaction(async(r)=>{for(let o of t){let n={...o,uuid:zi()};await r.insertInto("products").values(n).execute(),e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product items in bulk: ${r.message}`);throw r}}import{db as Wo}from"@stacksjs/database";import{formatDate as Lo}from"@stacksjs/orm";async function Zi(t,e){try{if(!t)throw Error("Product item ID is required for update");let r=await Wo.updateTable("products").set({...e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function Ki(t,e){if(!await ne(t))throw Error(`Product item with ID ${t} not found`);try{return await Wo.updateTable("products").set({is_available:e,updated_at:Lo(new Date)}).where("id","=",t).execute(),await ne(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update product item availability: ${o.message}`);throw o}}async function Hi(t,e){let r=await ne(t);if(!r)throw Error(`Product item with ID ${t} not found`);let o={updated_at:Lo(new Date)};if(e!==void 0)o.inventory_count=e;if(Object.keys(o).length===1)return r;try{return await Wo.updateTable("products").set(o).where("id","=",t).execute(),await ne(t)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update inventory information: ${n.message}`);throw n}}var Lt={};g(Lt,{bulkDestroy:()=>Xi,bulkStore:()=>du,destroy:()=>Yi,fetchAll:()=>eu,fetchByCountry:()=>nu,fetchById:()=>tu,fetchByUuid:()=>ru,fetchFeatured:()=>ou,fetchWithProductCount:()=>au,store:()=>cu,update:()=>mu,updateByUuid:()=>fu,updateFeaturedStatus:()=>pu});import{db as Qi}from"@stacksjs/database";async function Yi(t){try{let e=await Qi.deleteFrom("manufacturers").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete order: ${e.message}`);throw e}}async function Xi(t){if(!t.length)return 0;try{let e=await Qi.deleteFrom("manufacturers").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete orders: ${e.message}`);throw e}}import{db as ae}from"@stacksjs/database";async function eu(){return w(await ae.selectFrom("manufacturers").selectAll().execute())}async function tu(t){let e=await ae.selectFrom("manufacturers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ru(t){let e=await ae.selectFrom("manufacturers").where("uuid","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ou(t=10){let e=await ae.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(t).execute();return w(e)}async function nu(t,e={}){let r=e.page||1,o=e.limit||2,n=await ae.selectFrom("manufacturers").select(ae.fn.count("id").as("total")).where("country","=",t).executeTakeFirst(),a=Number(n?.total||0),s=await ae.selectFrom("manufacturers").selectAll().where("country","=",t).limit(o).offset((r-1)*o).execute(),i=Math.ceil(a/o);return{data:w(s),paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function au(t={}){let e=ae.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(t.country)e=e.where("m.country","=",t.country);if(t.featured!==void 0)e=e.where("m.featured","=",t.featured);return e=e.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",ae.fn.count("p.id").as("product_count")]).groupBy("m.id"),e.execute()}var{randomUUIDv7:iu}=globalThis.Bun;import{db as uu}from"@stacksjs/database";import{HttpError as su}from"@stacksjs/error-handling";import{isUniqueViolation as $p}from"@stacksjs/orm";async function cu(t){try{let e={...t,uuid:iu(),featured:t.featured??!1},r=await uu.insertInto("manufacturers").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return d(r)}catch(e){if(e instanceof su)throw e;if($p(e))throw new su(409,"A manufacturer with this name already exists");if(e instanceof Error)throw Error(`Failed to create manufacturer: ${e.message}`);throw e}}async function du(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:iu(),featured:r.featured??!1};await uu.insertInto("manufacturers").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${r.message}`);throw r}}import{db as jo}from"@stacksjs/database";import{HttpError as lu}from"@stacksjs/error-handling";import{formatDate as zo,isUniqueViolation as Wp}from"@stacksjs/orm";async function mu(t,e){try{if(!t)throw Error("Manufacturer ID is required for update");let r=await jo.updateTable("manufacturers").set({...e,updated_at:zo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof lu)throw r;if(Wp(r))throw new lu(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(t,e){try{let r=await jo.updateTable("manufacturers").set({featured:e,updated_at:zo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function fu(t,e){try{let r=await jo.updateTable("manufacturers").set({...e,updated_at:zo(new Date)}).where("uuid","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var jt={};g(jt,{bulkDestroy:()=>hu,destroy:()=>yu,fetchAll:()=>bu,fetchApprovedByProductId:()=>xu,fetchById:()=>gu,fetchByProductId:()=>_u,fetchByUserId:()=>Ru,fetchMostHelpfulByProductId:()=>Du,fetchStats:()=>ku,fetchStatsByProductIds:()=>Tu,store:()=>Eu,update:()=>Au,updateVotes:()=>Mu});import{db as wu}from"@stacksjs/database";async function yu(t){try{let e=await wu.deleteFrom("reviews").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete review: ${e.message}`);throw e}}async function hu(t){if(!t.length)return 0;try{let e=await wu.deleteFrom("reviews").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete reviews: ${e.message}`);throw e}}import{db as Ae}from"@stacksjs/database";async function gu(t){return d(await Ae.selectFrom("reviews").where("id","=",t).selectAll().executeTakeFirst(),!0)}async function bu(){return w(await Ae.selectFrom("reviews").selectAll().execute())}async function _u(t){return w(await Ae.selectFrom("reviews").where("product_id","=",t).selectAll().execute())}async function Ru(t){return w(await Ae.selectFrom("reviews").where("customer_id","=",t).selectAll().execute())}async function xu(t){return w(await Ae.selectFrom("reviews").where("product_id","=",t).where("is_approved","=",!0).selectAll().execute())}async function Du(t){return w(await Ae.selectFrom("reviews").where("product_id","=",t).orderBy("helpful_votes","desc").selectAll().execute())}import{db as vu}from"@stacksjs/database";function Pu(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function Fu(t){let e=Pu();e.total=t.length;let r=0;for(let o of t){if(o.rating===null||o.rating===void 0){e.commentsOnly++;continue}let n=Number(o.rating);if(Number.isNaN(n)){e.commentsOnly++;continue}e.rated++,r+=n;let a=Math.min(5,Math.max(1,Math.round(n)));e.distribution[a]++}if(e.rated>0)e.average=Math.round(r/e.rated*10)/10;return e}async function ku(t){let e=await vu.selectFrom("reviews").select(["rating"]).where("product_id","=",t).where("is_approved","=",!0).execute();return Fu(e)}async function Tu(t){let e=new Map;for(let n of t)e.set(n,Pu());if(t.length===0)return e;let r=await vu.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",t).where("is_approved","=",!0).execute(),o=new Map;for(let n of r){let a=o.get(n.product_id);if(a)a.push({rating:n.rating});else o.set(n.product_id,[{rating:n.rating}])}for(let[n,a]of o)e.set(n,Fu(a));return e}var{randomUUIDv7:Lp}=globalThis.Bun;import{db as jp}from"@stacksjs/database";function zp(t){let e=t.rating!==void 0&&t.rating!==null,r=typeof t.content==="string"&&t.content.trim().length>0,o=typeof t.title==="string"&&t.title.trim().length>0;return!e&&!r&&!o}async function Eu(t){try{if(zp(t))throw Error("A review needs a rating or something written: both were empty");let e={...t,uuid:Lp(),rating:t.rating??null,is_verified_purchase:t.is_verified_purchase??!1,is_approved:t.is_approved??!1,helpful_votes:t.helpful_votes??0,unhelpful_votes:t.unhelpful_votes??0,is_featured:t.is_featured??!1},r=await jp.insertInto("reviews").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return d(r)}catch(e){if(e instanceof Error){if(e.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${e.message}`)}throw e}}import{db as Su}from"@stacksjs/database";import{formatDate as Cu}from"@stacksjs/orm";async function Au(t,e){try{if(!t)throw Error("Review ID is required for update");let r=await Su.updateTable("reviews").set({...e,updated_at:Cu(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function Mu(t,e,r=!0){try{let o=e==="helpful"?"helpful_votes":"unhelpful_votes",n=r?`COALESCE("${o}", 0) + 1`:`MAX(COALESCE("${o}", 0) - 1, 0)`,a=await Su.unsafe(`UPDATE "reviews" SET "${o}" = ${n}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[Cu(new Date),t]).execute(),s=Array.isArray(a)?a[0]:a;if(!s)throw Error("Failed to update review votes");return d(s)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update review votes: ${o.message}`);throw o}}var Vt={};g(Vt,{bulkDestroy:()=>Ju,bulkStore:()=>Lu,bulkUpdate:()=>Vu,destroy:()=>Nu,fetchAll:()=>Uu,fetchById:()=>Ou,formatUnitOptions:()=>ju,getDefaultUnit:()=>zu,store:()=>Wu,update:()=>Gu,updateDefaultStatus:()=>qu});import{db as Iu}from"@stacksjs/database";async function Nu(t){try{let e=await Iu.deleteFrom("product_units").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product unit: ${e.message}`);throw e}}async function Ju(t){if(!t.length)return 0;try{let e=await Iu.deleteFrom("product_units").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product units: ${e.message}`);throw e}}import{db as Bu}from"@stacksjs/database";async function Ou(t){let e=await Bu.selectFrom("product_units").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Uu(){return w(await Bu.selectFrom("product_units").selectAll().execute())}var{randomUUIDv7:$u}=globalThis.Bun;import{db as tt}from"@stacksjs/database";async function Wu(t){try{return await tt.transaction(async(e)=>{let r={...t,uuid:$u()},o=await e.insertInto("product_units").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create product unit");if(r.is_default&&r.type)await e.updateTable("product_units").set({is_default:!1}).where("type","=",r.type).where("id","!=",o.id).execute();return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product unit: ${e.message}`);throw e}}async function Lu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:$u()},n=await tt.insertInto("product_units").values(o).returningAll().executeTakeFirst();if(o.is_default&&o.type&&n)await tt.updateTable("product_units").set({is_default:!1}).where("type","=",o.type).where("id","!=",n.id).execute();e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product units in bulk: ${r.message}`);throw r}}function ju(t){try{let e=tt.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(t)e=e.where("type","=",t);return e=e.orderBy("name"),e.execute().then((r)=>r.map((o)=>({id:String(o.id),name:o.name,abbreviation:o.abbreviation,is_default:o.is_default})))}catch(e){if(e instanceof Error)throw TypeError(`Failed to format unit options: ${e.message}`);throw e}}async function zu(t){try{let e=await tt.selectFrom("product_units").selectAll().where("type","=",t).where("is_default","=",!0).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get default unit: ${e.message}`);throw e}}import{db as zt}from"@stacksjs/database";import{formatDate as Gt}from"@stacksjs/orm";async function Gu(t,e){try{if(!t)throw Error("Product unit ID is required for update");return await zt.transaction(async(r)=>{let o=await r.selectFrom("product_units").select(["type","is_default"]).where("id","=",t).executeTakeFirst();if(!o)return;let n=e.type??o.type;if((e.is_default??Boolean(o.is_default))&&n)await r.updateTable("product_units").set({is_default:!1,updated_at:Gt(new Date)}).where("type","=",n).where("id","!=",t).execute();let s=await r.updateTable("product_units").set({...e,updated_at:Gt(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function Vu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o=r;if(!o.id)continue;let n=o.data&&typeof o.data==="object"?o.data:{...o};delete n.id;let a=await zt.updateTable("product_units").set({...n,updated_at:Gt(new Date)}).where("id","=",o.id).executeTakeFirst(),s=n;if(s.is_default===!0&&s.type)await zt.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",o.id).execute();if(Number(a.numUpdatedRows)>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product units in bulk: ${r.message}`);throw r}}async function qu(t,e){try{return await zt.transaction(async(r)=>{let o=await r.selectFrom("product_units").select("type").where("id","=",t).executeTakeFirst();if(!o)return!1;let n=Gt(new Date);if(e&&o.type)await r.updateTable("product_units").set({is_default:!1,updated_at:n}).where("type","=",o.type).where("id","!=",t).execute();return await r.updateTable("product_units").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit default status: ${r.message}`);throw r}}var qt={};g(qt,{bulkDestroy:()=>Hu,bulkStore:()=>oc,bulkUpdate:()=>cc,destroy:()=>Ku,fetchAll:()=>Xu,fetchById:()=>Yu,formatVariantOptions:()=>nc,generateVariantCombinations:()=>ac,store:()=>rc,update:()=>uc});import{db as Zu}from"@stacksjs/database";async function Ku(t){try{let e=await Zu.deleteFrom("product_variants").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variant: ${e.message}`);throw e}}async function Hu(t){if(!t.length)return 0;try{let e=await Zu.deleteFrom("product_variants").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variants: ${e.message}`);throw e}}import{db as Qu}from"@stacksjs/database";async function Yu(t){let e=await Qu.selectFrom("product_variants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Xu(){return w(await Qu.selectFrom("product_variants").selectAll().execute())}var{randomUUIDv7:ec}=globalThis.Bun;import{db as tc}from"@stacksjs/database";async function rc(t){try{let e={...t,uuid:ec()},r=await tc.insertInto("product_variants").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return d(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product variant: ${e.message}`);throw e}}async function oc(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:ec()};await tc.insertInto("product_variants").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${r.message}`);throw r}}function nc(t){if(!t||!t.length)return JSON.stringify([]);let e=t.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(e)}function ac(t){let e=Object.keys(t);if(!e.length)return[];function r(o,n){if(o===e.length)return[n];let a=e[o],s=t[a]??[],i=[];for(let u of s){let c={...n,[a]:u};i.push(...r(o+1,c))}return i}return r(0,{})}import{db as sc}from"@stacksjs/database";import{formatDate as ic}from"@stacksjs/orm";async function uc(t,e){try{let r=await sc.updateTable("product_variants").set({...e,updated_at:ic(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function cc(t){if(!t.length)return 0;let e=0;try{for(let r of t){if(!r.id)continue;let o=await sc.updateTable("product_variants").set({...r,updated_at:ic(new Date)}).where("id","=",r.id).executeTakeFirst();if(Number(o.numUpdatedRows)>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var Gp={categories:$t,items:Wt,manufacturers:Lt,reviews:jt,units:Vt,variants:qt},Vp=Gp;var Ho={};g(Ho,{bulkDestroy:()=>mc,bulkStore:()=>Rc,destroy:()=>lc,fetchAll:()=>pc,fetchById:()=>Me,fetchPageStats:()=>yc,fetchPrintJobStats:()=>fc,fetchPrintTimeStats:()=>hc,fetchPrintsPerHour:()=>gc,fetchSuccessRate:()=>wc,store:()=>_c,update:()=>xc,updatePrintJob:()=>vc,updateStatus:()=>Dc});import{db as dc}from"@stacksjs/database";async function lc(t){try{let e=await dc.deleteFrom("receipts").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print log: ${e.message}`);throw e}}async function mc(t){if(!t.length)return 0;try{let e=await dc.deleteFrom("receipts").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete receipts: ${e.message}`);throw e}}import{db as Vo}from"@stacksjs/database";import{formatDate as qp}from"@stacksjs/orm";function G(t){return qp(t)}function Zp(t){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t==="number"){let o=new Date(t<=2147483647?t*1000:t);return Number.isNaN(o.getTime())?null:o}let e=String(t||"").trim();if(!e)return null;if(/^\d{10}$/.test(e)){let o=new Date(Number(e)*1000);return Number.isNaN(o.getTime())?null:o}let r=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(r.getTime())?null:r}async function Me(t){let e=await Vo.selectFrom("receipts").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function pc(){return w(await Vo.selectFrom("receipts").selectAll().execute())}async function fc(t,e){let r=G(t),o=G(e),n=await J("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{total:n.total,success:n.success,failed:n.failed,warning:n.warning,averageSize:Math.round(n.averageSize),averagePages:Math.round(n.averagePages),averageDuration:Math.round(n.averageDuration)}}async function wc(t,e){let r=G(t),o=G(e),n=await J("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(s)=>s.where("timestamp",">=",r).where("timestamp","<=",o));return{successRate:n.total>0?Math.round(n.success/n.total*100):0,total:n.total,success:n.success,failed:n.failed,warning:n.warning}}async function yc(t,e){let r=G(t),o=G(e),n=await J("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{totalPages:n.totalPages,averagePagesPerReceipt:Math.round(n.averagePagesPerReceipt),totalReceipts:n.totalReceipts}}async function hc(t,e){let r=G(t),o=G(e),n=await J("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{averageDuration:Math.round(n.averageDuration),minDuration:n.minDuration,maxDuration:n.maxDuration,totalJobs:n.totalJobs}}async function gc(t,e){let r=typeof t==="number"?t:t.getTime(),o=typeof e==="number"?e:e.getTime(),n=G(t),a=G(e),s=await Vo.selectFrom("receipts").where("timestamp",">=",n).where("timestamp","<=",a).selectAll().execute(),i=s.length,u=Math.ceil((o-r)/3600000),c=u>0?Math.round(i/u):0,m=Array.from({length:24},(p,f)=>({hour:f,count:0}));return s.forEach((p)=>{let f=Zp(p.timestamp);if(!f)return;m[f.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:m}}var{randomUUIDv7:bc}=globalThis.Bun;import{db as Zt}from"@stacksjs/database";import{formatDate as qo}from"@stacksjs/orm";function rt(t){try{if(typeof t==="number")return qo(t<=2147483647?t*1000:t);if(typeof t==="string"&&/^\d{10}$/.test(t))return qo(Number(t)*1000);return qo(t)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function _c(t){try{let e=bc(),r={...t,timestamp:rt(t.timestamp),uuid:e};await Zt.insertInto("receipts").values(r).executeTakeFirst();let o=await Zt.selectFrom("receipts").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create receipt");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipt: ${e.message}`);throw e}}async function Rc(t){if(!t.length)return 0;try{let e=t.map((n)=>({...n,timestamp:rt(n.timestamp),uuid:bc()})),o=await Zt.insertInto("receipts").values(e).executeTakeFirst()??{};return Number(o.numInsertedOrUpdatedRows??o.numAffectedRows??o.affectedRows??o.changes??0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${e.message}`);throw e}}import{db as Zo}from"@stacksjs/database";import{formatDate as Ko}from"@stacksjs/orm";async function xc(t,e){try{if(!t)throw Error("Receipt ID is required for update");let r={...e,...e.timestamp===void 0?{}:{timestamp:rt(e.timestamp)},updated_at:Ko(new Date)};await Zo.updateTable("receipts").set(r).where("id","=",t).execute();let o=await Me(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function Dc(t,e){try{await Zo.updateTable("receipts").set({status:e,updated_at:Ko(new Date)}).where("id","=",t).execute();let r=await Me(t);if(!r)throw Error("Failed to update receipt status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function vc(t,e,r,o){try{let n={updated_at:Ko(new Date)};if(e!==void 0)n.size=e;if(r!==void 0)n.pages=r;if(o!==void 0)n.duration=o;await Zo.updateTable("receipts").set(n).where("id","=",t).execute();let a=await Me(t);if(!a)throw Error("Failed to update receipt job information");return d(a)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update receipt job information: ${n.message}`);throw n}}var Rn={};g(Rn,{couriers:()=>nr,default:()=>bf,digital:()=>rr,geocoding:()=>ur,licenses:()=>lr,methods:()=>wr,rates:()=>_r,routes:()=>er,tracking:()=>Tr,zones:()=>Ar});var er={};g(er,{DeliveryRouteInputError:()=>N,bulkDestroy:()=>kc,destroy:()=>Fc,fetchActive:()=>Ec,fetchAll:()=>Tc,fetchByCourier:()=>Sc,fetchById:()=>Ht,store:()=>Cc,update:()=>Mc,updateLastActive:()=>Ac,updateMetrics:()=>Nc,updateStops:()=>Ic,validateDeliveryRouteWrite:()=>Ie});import{db as Pc}from"@stacksjs/database";async function Fc(t){try{let e=await Pc.deleteFrom("delivery_routes").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery route: ${e.message}`);throw e}}async function kc(t){if(!t.length)return 0;try{let e=await Pc.deleteFrom("delivery_routes").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery routes: ${e.message}`);throw e}}import{db as Kt}from"@stacksjs/database";async function Ht(t){return await Kt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst()}async function Tc(){return await Kt.selectFrom("delivery_routes").selectAll().execute()}async function Ec(){return await Kt.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function Sc(t){return await Kt.selectFrom("delivery_routes").where("courier","=",t).selectAll().execute()}var{randomUUIDv7:Qp}=globalThis.Bun;import{db as Qo}from"@stacksjs/database";function be(t,e){let r={};for(let[o,n]of Object.entries(e))for(let a of n){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)continue;r[o]=t[a];break}return r}function ot(t){return be(t,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function se(t){return be(t,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function nt(t){return be(t,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function at(t){return be(t,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function st(t){return be(t,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function it(t){return be(t,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function Qt(t){return be(t,{courier:["courier"],courier_id:["courier_id","courierId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as Kp}from"@stacksjs/database";class N extends TypeError{constructor(t){super(t);this.name="DeliveryRouteInputError"}}function Yt(t,e,r){return Number(t[r]??e?.[r])}function Hp(t,e){let r=t.last_active??e?.last_active;if(r===void 0||r===null)return Date.now();if(r instanceof Date)return r.getTime();if(typeof r==="number")return r;if(typeof r==="string"&&/^\d{10,13}$/.test(r))return Number(r);return Number.NaN}async function Ie(t,e){let r=Yt(t,e,"courier_id"),o=Yt(t,e,"stops"),n=Yt(t,e,"delivery_time"),a=Yt(t,e,"total_distance"),s=Hp(t,e);if(!Number.isSafeInteger(r)||r<1)throw new N("Courier must be a positive integer.");if(!Number.isSafeInteger(o)||o<0)throw new N("Stops must be a non-negative integer.");if(!Number.isSafeInteger(n)||n<0)throw new N("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(a)||a<0)throw new N("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(s)||s<0)throw new N("Last active must be a valid Unix timestamp.");let i=await Kp.selectFrom("couriers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new N(`Courier ${r} was not found.`);return{...t,courier_id:Number(i.id),courier:i.name,vehicle:i.vehicle_number,last_active:s}}async function Cc(t){try{let e=Qp(),r=Qt(t),n={...await Ie(r),uuid:e};await Qo.insertInto("delivery_routes").values(n).executeTakeFirst();let a=await Qo.selectFrom("delivery_routes").where("uuid","=",e).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(e){if(e instanceof N)throw e;if(e instanceof Error)throw TypeError(`Failed to create delivery route: ${e.message}`);throw e}}async function Ac(t){try{await Qo.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",t).execute();let e=await Ht(t);if(!e)throw Error("Failed to update delivery route last active");return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update delivery route last active: ${e.message}`);throw e}}import{db as Xt}from"@stacksjs/database";import{formatDate as Yo}from"@stacksjs/orm";async function Mc(t,e){try{if(!t)throw Error("Delivery route ID is required for update");let r=await Xt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=Qt(e),n=await Ie(o,r),a=await Xt.updateTable("delivery_routes").set({...n,updated_at:Yo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof N)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function Ic(t,e){try{let r=await Xt.updateTable("delivery_routes").set({stops:e,updated_at:Yo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update delivery route stops");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update delivery route stops: ${r.message}`);throw r}}async function Nc(t,e,r){try{let o={updated_at:Yo(new Date)};if(e!==void 0)o.delivery_time=e;if(r!==void 0)o.total_distance=r;let n=await Xt.updateTable("delivery_routes").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update delivery metrics");return n}catch(o){if(o instanceof Error)throw TypeError(`Failed to update delivery metrics: ${o.message}`);throw o}}var rr={};g(rr,{bulkDestroy:()=>Oc,bulkSoftDelete:()=>Uc,bulkStore:()=>Gc,destroy:()=>Jc,fetchAll:()=>Lc,fetchById:()=>Wc,softDelete:()=>Bc,store:()=>zc,update:()=>Vc,updateDeliverySettings:()=>Zc,updateStatus:()=>qc});import{db as tr}from"@stacksjs/database";async function Jc(t){try{let e=await tr.deleteFrom("digital_deliveries").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital delivery: ${e.message}`);throw e}}async function Bc(t){try{let e=await tr.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${e.message}`);throw e}}async function Oc(t){if(!t.length)return 0;try{let e=await tr.deleteFrom("digital_deliveries").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${e.message}`);throw e}}async function Uc(t){if(!t.length)return 0;try{let e=await tr.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${e.message}`);throw e}}import{db as $c}from"@stacksjs/database";async function Wc(t){let e=await $c.selectFrom("digital_deliveries").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Lc(){return w(await $c.selectFrom("digital_deliveries").selectAll().execute())}var{randomUUIDv7:jc}=globalThis.Bun;import{db as Xo}from"@stacksjs/database";async function zc(t){try{let e=jc(),r={...at(t),uuid:e};await Xo.insertInto("digital_deliveries").values(r).executeTakeFirst();let o=await Xo.selectFrom("digital_deliveries").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created digital delivery");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital delivery: ${e.message}`);throw e}}async function Gc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...at(o),uuid:jc()})),r=await Xo.insertInto("digital_deliveries").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${e.message}`);throw e}}import{db as en}from"@stacksjs/database";import{formatDate as tn}from"@stacksjs/orm";async function Vc(t,e){try{if(!t)throw Error("Digital delivery ID is required for update");let r=await en.updateTable("digital_deliveries").set({...at(e),updated_at:tn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function qc(t,e){try{let r=await en.updateTable("digital_deliveries").set({status:e,updated_at:tn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function Zc(t,e,r,o,n){try{let a={updated_at:tn(new Date)};if(e!==void 0)a.download_limit=e;if(r!==void 0)a.expiry_days=r;if(o!==void 0)a.requires_login=o;if(n!==void 0)a.automatic_delivery=n;let s=await en.updateTable("digital_deliveries").set(a).where("id","=",t).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return d(s)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var nr={};g(nr,{bulkDestroy:()=>Xc,bulkStore:()=>rd,destroy:()=>Yc,fetchAll:()=>Hc,fetchById:()=>or,store:()=>td,update:()=>od,updateContact:()=>ad,updateStatus:()=>nd});import{db as Qc}from"@stacksjs/database";import{db as Kc}from"@stacksjs/database";async function or(t){let e=await Kc.selectFrom("couriers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Hc(){return w(await Kc.selectFrom("couriers").selectAll().execute())}async function Yc(t){try{let e=await Qc.deleteFrom("couriers").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete courier: ${e.message}`);throw e}}async function Xc(t){if(!t.length)return 0;let e=0;try{return await Qc.transaction(async(r)=>{for(let o of t)if(await or(o))await r.deleteFrom("couriers").where("id","=",o).execute(),e++}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to delete couriers in bulk: ${r.message}`);throw r}}var{randomUUIDv7:ed}=globalThis.Bun;import{db as rn}from"@stacksjs/database";async function td(t){try{let e=ed(),r={...it(t),uuid:e};await rn.insertInto("couriers").values(r).executeTakeFirst();let o=await rn.selectFrom("couriers").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created courier");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create courier: ${e.message}`);throw e}}async function rd(t){if(!t.length)return 0;try{let e=t.map((o)=>({...it(o),uuid:ed()})),r=await rn.insertInto("couriers").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create couriers in bulk: ${e.message}`);throw e}}import{db as on}from"@stacksjs/database";import{formatDate as nn}from"@stacksjs/orm";async function od(t,e){try{if(!t)throw Error("Courier ID is required for update");let r=await on.updateTable("couriers").set({...it(e),updated_at:nn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier: ${r.message}`);throw r}}async function nd(t,e){try{let r=await on.updateTable("couriers").set({status:e,updated_at:nn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update courier status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier status: ${r.message}`);throw r}}async function ad(t,e){try{let r={updated_at:nn(new Date)};if(e!==void 0)r.phone=e;let o=await on.updateTable("couriers").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update contact information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var ur={};g(ur,{PRECISION_RANK:()=>ct,checkCoverage:()=>of,formatQuery:()=>Ne,geocode:()=>rf,geocodingDriver:()=>ld,nominatimDriver:()=>ir,setGeocodingDriver:()=>tf});var _e=(t)=>t*Math.PI/180;function me(t,e){let r=_e(e.latitude-t.latitude),o=_e(e.longitude-t.longitude),n=_e(t.latitude),a=_e(e.latitude),s=Math.sin(r/2)**2+Math.sin(o/2)**2*Math.cos(n)*Math.cos(a);return 12742017.6*Math.asin(Math.sqrt(s))}function ar(t,e){let r=_e(t.latitude),o=_e(e.latitude),n=_e(e.longitude-t.longitude),a=Math.sin(n)*Math.cos(o),s=Math.cos(r)*Math.sin(o)-Math.sin(r)*Math.cos(o)*Math.cos(n);return(Math.atan2(a,s)*180/Math.PI+360)%360}function sr(t,e,r={}){let o=r.detourFactor??1.35,n=r.minimumSeconds??30;if(!Number.isFinite(e)||e<=0.5)return null;let a=t*o/e;return Math.max(n,Math.round(a))}function sd(t,e,r){return me(t,e)<=r}function ut(t){return typeof t?.latitude==="number"&&typeof t?.longitude==="number"&&Number.isFinite(t.latitude)&&Number.isFinite(t.longitude)}var ct={unknown:0,locality:1,postal:2,street:3,rooftop:4};function Ne(t){return[t.street,t.city,t.region,t.postalCode,t.country].map((e)=>String(e??"").trim()).filter(Boolean).join(", ")}var Yp="https://nominatim.openstreetmap.org/search",id=1000,ud=0,cd=Promise.resolve();async function Xp(t){let e=cd.then(async()=>{let r=Date.now()-ud;if(r<id)await Bun.sleep(id-r);return ud=Date.now(),t()});return cd=e.then(()=>{return},()=>{return}),e}function ef(t){let e=t.address??{},r=String(t.addresstype??""),o=String(t.type??""),n=String(t.category??t.class??"");if(e.house_number||o==="house"||o==="building"||r==="building")return"rooftop";if(e.road||n==="highway"||r==="road")return"street";if(r==="postcode"||e.postcode&&!e.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(r))return"locality";return"unknown"}function ir(t={}){let e=t.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,r=t.endpoint??Yp;return{name:"nominatim",async geocode(o){let n=Ne(o);if(!n)return null;let a=new URL(r);if(a.searchParams.set("q",n),a.searchParams.set("format","jsonv2"),a.searchParams.set("limit","1"),a.searchParams.set("addressdetails","1"),o.country)a.searchParams.set("countrycodes",o.country.toLowerCase());let s=await Xp(()=>fetch(a,{headers:{"user-agent":e,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!s.ok)throw Error(`Nominatim responded ${s.status}`);let u=(await s.json())?.[0];if(!u)return null;let c=Number(u.lat),m=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(m))return null;let p=ef(u);return{latitude:c,longitude:m,formatted:String(u.display_name??n),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[p],precision:p,provider:"nominatim"}}}}var dd=null;function tf(t){dd=t}function ld(){return dd??ir()}async function rf(t,e={}){let r=e.driver??ld(),o=e.minimumPrecision??"street",n=`geocode:${r.name}:${Ne(t).toLowerCase()}`,a=await nf(n);if(a!==void 0)return a;let s=await r.geocode(t),i=s&&ct[s.precision]>=ct[o]?s:null;return await af(n,i,i?e.cacheSeconds??2592000:600),i}function of(t,e,r){if(e.length===0)return null;let o=e[0],n=me(t,o);for(let a of e.slice(1)){let s=me(t,a);if(s<n)n=s,o=a}return{covered:n<=r,distanceMeters:Math.round(n),nearest:o}}async function nf(t){try{let r=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!r)return;let o=await r.get(t);if(o===null||o===void 0)return;return o==="null"?null:JSON.parse(String(o))}catch{return}}async function af(t,e,r){try{let n=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!n)return;await n.set(t,e===null?"null":JSON.stringify(e),r)}catch{}}var lr={};g(lr,{LicenseKeyInputError:()=>T,bulkDestroy:()=>fd,bulkSoftDelete:()=>wd,bulkStore:()=>Dd,destroy:()=>md,fetchAll:()=>gd,fetchById:()=>hd,softDelete:()=>pd,store:()=>xd,update:()=>vd,updateExpiration:()=>Fd,updateStatus:()=>Pd,validateLicenseKeyWrite:()=>Re});import{db as cr}from"@stacksjs/database";async function md(t){try{let e=await cr.deleteFrom("license_keys").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license key: ${e.message}`);throw e}}async function pd(t){try{let e=await cr.updateTable("license_keys").set({status:"inactive"}).where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license key: ${e.message}`);throw e}}async function fd(t){if(!t.length)return 0;try{let e=await cr.deleteFrom("license_keys").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license keys: ${e.message}`);throw e}}async function wd(t){if(!t.length)return 0;try{let e=await cr.updateTable("license_keys").set({status:"inactive"}).where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license keys: ${e.message}`);throw e}}import{db as yd}from"@stacksjs/database";async function hd(t){let e=await yd.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function gd(){return w(await yd.selectFrom("license_keys").selectAll().execute())}var{randomUUIDv7:Rd}=globalThis.Bun;import{db as un}from"@stacksjs/database";import{db as an}from"@stacksjs/database";var bd=["Standard License","Premium License","Enterprise License"],_d=["active","inactive","unassigned"];class T extends TypeError{constructor(t){super(t);this.name="LicenseKeyInputError"}}function dt(t,e,r){return t[r]!==void 0?t[r]:e?.[r]}function sn(t,e,r,o){let n=dt(t,e,r);if(n===void 0||n===null||n==="")return null;let a=Number(n);if(!Number.isSafeInteger(a)||a<1)throw new T(`${o} must be a positive integer or null.`);return a}function sf(t){if(typeof t==="number")return t>2147483647?Math.floor(t/1000):t;if(typeof t==="string"&&/^\d{10,13}$/.test(t))return t.length===13?Math.floor(Number(t)/1000):Number(t);if(typeof t==="string"){let e=/^\d{4}-\d{2}-\d{2} \d/.test(t)?`${t.replace(" ","T")}Z`:t;return Math.floor(new Date(e).getTime()/1000)}return Number.NaN}async function Re(t,e){let r=String(dt(t,e,"key")||"").trim().toUpperCase(),o=String(dt(t,e,"template")||""),n=String(dt(t,e,"status")||""),a=sf(dt(t,e,"expiry_date")),s=sn(t,e,"customer_id","Customer"),i=sn(t,e,"product_id","Product"),u=sn(t,e,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new T("License key must use five groups of four uppercase letters or numbers.");if(!bd.includes(o))throw new T(`Template must be one of: ${bd.join(", ")}.`);if(!_d.includes(n))throw new T(`Status must be one of: ${_d.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new T("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,m,p]=await Promise.all([s?an.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?an.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?an.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new T(`Customer ${s} was not found.`);if(i&&!m)throw new T(`Product ${i} was not found.`);if(u&&!p)throw new T(`Order ${u} was not found.`);if(s&&p?.customer_id&&Number(p.customer_id)!==s)throw new T(`Order ${u} belongs to Customer ${p.customer_id}, not Customer ${s}.`);return{...t,key:r,template:o,expiry_date:a,status:n,customer_id:s,product_id:i,order_id:u}}async function xd(t){try{let e=Rd(),r=st(t),o={...await Re(r),uuid:e};await un.insertInto("license_keys").values(o).executeTakeFirst();let n=await un.selectFrom("license_keys").where("uuid","=",e).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created license key");return d(n)}catch(e){if(e instanceof T)throw e;if(e instanceof Error){if(e.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${e.message}`)}throw e}}async function Dd(t){if(!t.length)return 0;try{let e=await Promise.all(t.map(async(o)=>({...await Re(st(o)),uuid:Rd()}))),r=await un.insertInto("license_keys").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof T)throw e;if(e instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${e.message}`);throw e}}import{db as dr}from"@stacksjs/database";import{formatDate as cn}from"@stacksjs/orm";async function vd(t,e){try{if(!t)throw Error("License key ID is required for update");let r=await dr.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=st(e),n=await Re(o,r),a=await dr.updateTable("license_keys").set({...n,updated_at:cn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return d(a)}catch(r){if(r instanceof T)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function Pd(t,e){try{let r=await dr.updateTable("license_keys").set({status:e,updated_at:cn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function Fd(t,e){try{let r={updated_at:cn(new Date)};if(e!==void 0)r.expiry_date=e;let o=await dr.updateTable("license_keys").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update expiration information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var wr={};g(wr,{bulkDestroy:()=>Ed,bulkSoftDelete:()=>Sd,bulkStore:()=>Id,destroy:()=>kd,fetchAll:()=>Cd,fetchById:()=>fr,formatShippingOptions:()=>Nd,getActiveShippingMethods:()=>Jd,softDelete:()=>Td,store:()=>Md,update:()=>Bd,updatePricing:()=>Ud,updateStatus:()=>Od});import{db as mr}from"@stacksjs/database";async function kd(t){try{let e=await mr.deleteFrom("shipping_methods").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping method: ${e.message}`);throw e}}async function Td(t){try{let e=await mr.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${e.message}`);throw e}}async function Ed(t){if(!t.length)return 0;try{let e=await mr.deleteFrom("shipping_methods").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping methods: ${e.message}`);throw e}}async function Sd(t){if(!t.length)return 0;try{let e=await mr.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${e.message}`);throw e}}import{db as pr}from"@stacksjs/database";async function fr(t){let e=await pr.selectFrom("shipping_methods").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=await pr.selectFrom("shipping_zones").where("shipping_method_id","=",t).selectAll().execute();return{...e,shippingZones:r}}return}async function Cd(){let t=await pr.selectFrom("shipping_methods").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((a)=>a.id))],n=(await pr.selectFrom("shipping_zones").where("shipping_method_id","in",e).selectAll().execute()).reduce((a,s)=>{let i=s.shipping_method_id;if(i!==null&&i!==void 0){if(!a[i])a[i]=[];a[i].push(s)}return a},{});return t.map((a)=>({...a,shipping_zones:n[a.id]||[]}))}var{randomUUIDv7:Ad}=globalThis.Bun;import{db as lt}from"@stacksjs/database";async function Md(t){try{let e=Ad(),r={...ot(t),uuid:e};await lt.insertInto("shipping_methods").values(r).executeTakeFirst();let o=await lt.selectFrom("shipping_methods").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping method");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping method: ${e.message}`);throw e}}async function Id(t){if(!t.length)return 0;try{let e=t.map((o)=>({...ot(o),uuid:Ad()})),r=await lt.insertInto("shipping_methods").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${e.message}`);throw e}}function Nd(){try{return lt.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping options: ${t.message}`);throw t}}async function Jd(){try{let t=await lt.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping methods: ${t.message}`);throw t}}import{db as dn}from"@stacksjs/database";import{formatDate as ln}from"@stacksjs/orm";async function Bd(t,e){try{if(!t)throw Error("Shipping method ID is required for update");let r=await dn.updateTable("shipping_methods").set({...ot(e),updated_at:ln(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function Od(t,e){try{let r=await dn.updateTable("shipping_methods").set({status:e,updated_at:ln(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function Ud(t,e,r){try{let o={updated_at:ln(new Date)};if(e!==void 0)o.base_rate=e;if(r!==void 0)o.free_shipping=r;let n=await dn.updateTable("shipping_methods").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update pricing information");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update pricing information: ${o.message}`);throw o}}var _r={};g(_r,{ShippingRateInputError:()=>M,bulkDestroy:()=>Wd,bulkStore:()=>nl,bulkUpdate:()=>sl,destroy:()=>$d,destroyByMethod:()=>jd,destroyByZone:()=>Ld,fetchAll:()=>Vd,fetchById:()=>Gd,formatShippingRateOptions:()=>Hd,getRateByWeightAndAddress:()=>Zd,getRateByWeightAndZone:()=>mn,getRatesByZone:()=>qd,getShippingRatesByMethod:()=>Qd,resolveZoneForAddress:()=>hr,store:()=>ol,update:()=>al,updateByMethod:()=>ul,updateByZone:()=>il,validateShippingRateWrite:()=>xe,validateZoneMatchesAddress:()=>Kd});import{db as yr}from"@stacksjs/database";async function $d(t){try{let e=await yr.deleteFrom("shipping_rates").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rate: ${e.message}`);throw e}}async function Wd(t){if(!t.length)return 0;try{let e=await yr.deleteFrom("shipping_rates").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates: ${e.message}`);throw e}}async function Ld(t){try{let e=await yr.deleteFrom("shipping_rates").where("shipping_zone_id","=",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${e.message}`);throw e}}async function jd(t){try{let e=await yr.deleteFrom("shipping_rates").where("shipping_method_id","=",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${e.message}`);throw e}}import{db as L}from"@stacksjs/database";async function Gd(t){let e=await L.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.shipping_zone_id)r=await L.selectFrom("shipping_zones").where("id","=",e.shipping_zone_id).selectAll().executeTakeFirst();if(e.shipping_method_id)o=await L.selectFrom("shipping_methods").where("id","=",e.shipping_method_id).selectAll().executeTakeFirst();return{...e,shipping_zone:r,shipping_method:o}}return}async function Vd(){let t=await L.selectFrom("shipping_rates").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((i)=>i.shipping_zone_id).filter((i)=>i!==null&&i!==void 0))],r=[...new Set(t.map((i)=>i.shipping_method_id).filter((i)=>i!==null&&i!==void 0))],[o,n]=await Promise.all([e.length?L.selectFrom("shipping_zones").where("id","in",e).selectAll().execute():[],r.length?L.selectFrom("shipping_methods").where("id","in",r).selectAll().execute():[]]),a=o.reduce((i,u)=>(i[u.id]=u,i),{}),s=n.reduce((i,u)=>(i[u.id]=u,i),{});return t.map((i)=>({...i,shipping_zone:i.shipping_zone_id?a[i.shipping_zone_id]:[],shipping_method:i.shipping_method_id?s[i.shipping_method_id]:[]}))}async function qd(t){try{let e=await L.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${e.message}`);throw e}}async function mn(t,e){try{let r=await L.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).where("weight_from","<=",t).where("weight_to",">=",t).executeTakeFirst();return d(r,!0)}catch(r){if(r instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${r.message}`);throw r}}async function hr(t){if(!t?.countryCode)return null;try{let e=await L.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t.countryCode}%`).where("status","=","active").execute();if(e.length===0)return null;let r=null;for(let o of e){let n=1;if(t.region&&o.regions&&zd(o.regions,t.region))n=2;if(t.postalCode&&o.postal_codes&&zd(o.postal_codes,t.postalCode))n=3;if(!r||n>r.score)r={id:o.id,score:n}}return r?.id??null}catch{return null}}async function Zd(t,e){let r=await hr(e);if(r==null)return;return mn(t,r)}async function Kd(t,e){return await hr(e)===t}function zd(t,e){if(!t||!e)return!1;let r=e.trim().toUpperCase();for(let o of t.split(/[,|;]/))if(o.trim().toUpperCase()===r)return!0;return!1}async function Hd(){try{return(await L.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((e)=>e.shipping_method_id!==null&&e.shipping_method_id!==void 0&&e.shipping_zone_id!==null&&e.shipping_zone_id!==void 0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping rate options: ${t.message}`);throw t}}async function Qd(t){try{let e=await L.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${e.message}`);throw e}}var{randomUUIDv7:rl}=globalThis.Bun;import{db as pn}from"@stacksjs/database";import{db as mt}from"@stacksjs/database";async function Yd(){return w(await mt.selectFrom("shipping_zones").selectAll().execute())}async function gr(t){let e=await mt.selectFrom("shipping_zones").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}function Xd(){try{return mt.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping zone options: ${t.message}`);throw t}}async function el(){try{let t=await mt.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping zones: ${t.message}`);throw t}}async function tl(t){try{let e=await mt.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t}%`).where("status","=","active").orderBy("name").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${e.message}`);throw e}}class M extends TypeError{constructor(t){super(t);this.name="ShippingRateInputError"}}function pt(t,e,r){return Number(t[r]??e?.[r])}async function xe(t,e){let r=pt(t,e,"shipping_method_id"),o=pt(t,e,"shipping_zone_id"),n=pt(t,e,"weight_from"),a=pt(t,e,"weight_to"),s=pt(t,e,"rate");if(!Number.isSafeInteger(r)||r<1)throw new M("Shipping method must be a positive integer.");if(!Number.isSafeInteger(o)||o<1)throw new M("Shipping zone must be a positive integer.");if(!Number.isFinite(n)||n<0)throw new M("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<n)throw new M("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new M("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([fr(r),gr(o)]);if(!i)throw new M(`Shipping method ${r} was not found.`);if(!u)throw new M(`Shipping zone ${o} was not found.`);if(Number(u.shipping_method_id)!==r)throw new M(`Shipping zone ${o} is not assigned to shipping method ${r}.`)}async function ol(t){try{let e=se(t),r=Number(e.shipping_method_id),o=Number(e.shipping_zone_id);await xe(e);let n=rl(),a={...e,shipping_method_id:r,shipping_zone_id:o,uuid:n};await pn.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await pn.selectFrom("shipping_rates").where("uuid","=",n).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return d(s)}catch(e){if(e instanceof M)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rate: ${e.message}`);throw e}}async function nl(t){if(!t.length)return 0;try{for(let o of t){let n=se(o);await xe(n)}let e=t.map((o)=>({...se(o),uuid:rl()})),r=await pn.insertInto("shipping_rates").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof M)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${e.message}`);throw e}}import{db as ft}from"@stacksjs/database";import{formatDate as br}from"@stacksjs/orm";async function al(t,e){try{if(!t)throw Error("Shipping rate ID is required for update");let r=await ft.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=se(e);await xe(o,r);let n=await ft.updateTable("shipping_rates").set({...o,updated_at:br(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return d(n)}catch(r){if(r instanceof M)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function sl(t){if(!t.length)return 0;try{let e=0;for(let{id:r,data:o}of t){let n=await ft.updateTable("shipping_rates").set({...se(o),updated_at:br(new Date)}).where("id","=",r).executeTakeFirst();if(l(n)>0)e++}return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${e.message}`);throw e}}async function il(t,e){try{let r=await ft.updateTable("shipping_rates").set({...se(e),updated_at:br(new Date)}).where("shipping_zone_id","=",t).executeTakeFirst();return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function ul(t,e){try{let r=await ft.updateTable("shipping_rates").set({...se(e),updated_at:br(new Date)}).where("shipping_method_id","=",t).executeTakeFirst();return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var Tr={};g(Tr,{ARRIVAL_RADIUS_METERS:()=>yn,NEARBY_RADIUS_METERS:()=>wn,assignStop:()=>dl,bearingInDegrees:()=>ar,broadcastToChannel:()=>ie,completeStop:()=>ml,distanceInMeters:()=>me,emitDeliveryArrived:()=>Pr,emitDeliveryAssigned:()=>xr,emitDeliveryCompleted:()=>Fr,emitDeliveryFailed:()=>kr,emitDeliveryNearby:()=>vr,emitDeliveryPosition:()=>Rr,emitDeliveryStarted:()=>Dr,estimateSecondsRemaining:()=>sr,failStop:()=>pl,hasCoordinates:()=>ut,isWithin:()=>sd,orderTrackingChannel:()=>pe,recordCourierPing:()=>cl,routeTrackingChannel:()=>fn,startRoute:()=>fl,startStop:()=>ll});function pe(t){return`order.${t}`}function fn(t){return`delivery-route.${t}`}async function Je(t,e){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let o=r.dispatch;if(typeof o!=="function")return;o(t,e)}catch{}}async function ie(t,e,r){try{let o=await import("@stacksjs/realtime").catch(()=>null);if(!o)return;let n=o.channel;if(typeof n!=="function")return;await n(t).broadcast(e,r,"private")}catch{}}async function Rr(t,e,r){await Promise.all([...t.map((o)=>ie(pe(o),"delivery:position",r)),e==null?Promise.resolve():ie(fn(e),"delivery:position",r)])}async function xr(t){if(await Je("delivery:assigned",{stop:t}),t.order_id!=null)await ie(pe(t.order_id),"delivery:assigned",{stop:t})}async function Dr(t){if(await Je("delivery:started",{stop:t}),t.order_id!=null)await ie(pe(t.order_id),"delivery:started",{stop:t})}async function vr(t,e,r){if(await Je("delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r}),t.order_id!=null)await ie(pe(t.order_id),"delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r})}async function Pr(t){if(await Je("delivery:arrived",{stop:t}),t.order_id!=null)await ie(pe(t.order_id),"delivery:arrived",{stop:t})}async function Fr(t){if(await Je("delivery:completed",{stop:t}),t.order_id!=null)await ie(pe(t.order_id),"delivery:completed",{stop:t})}async function kr(t,e){await Je("delivery:failed",{stop:t,reason:e})}var{randomUUIDv7:uf}=globalThis.Bun;import{db as j}from"@stacksjs/database";var wn=400,yn=60,cf=250;async function cl(t){let e=t.recordedAt??new Date().toISOString(),r=typeof t.accuracy!=="number"||t.accuracy<=cf,o=await j.selectFrom("couriers").where("id","=",t.courierId).select(["id","latitude","longitude"]).executeTakeFirst();if(!o)throw Error(`Unknown courier: ${t.courierId}`);let n=ut(o)?{latitude:o.latitude,longitude:o.longitude}:null,a=typeof t.heading==="number"?t.heading:n?ar(n,t):null,s=await df(t.courierId),i=s?await lf(s.id):null,u=null,c=null,m=!1,p=!1,f=i&&ut({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&f)u=Math.round(me(t,f)),c=sr(u,t.speed??0),p=u<=yn&&i.arrived_at==null,m=!p&&u<=wn&&i.status==="en_route"&&i.notified_nearby_at==null;let y=await mf({courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e});if(r)await j.updateTable("couriers").set({latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??0,last_ping_at:e}).where("id","=",t.courierId).execute();if(i&&(u!=null||c!=null))await j.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 Rr(i?.order_id==null?[]:[i.order_id],s?.id??null,{courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e,distanceToStopMeters:u,etaSeconds:c});if(m&&i)await j.updateTable("delivery_stops").set({notified_nearby_at:e}).where("id","=",i.id).execute(),await vr(i,u,c);if(p&&i)await j.updateTable("delivery_stops").set({status:"arrived",arrived_at:e}).where("id","=",i.id).execute(),await Pr({...i,status:"arrived",arrived_at:e});return{pingId:y,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:m,crossedArrival:p}}async function df(t){return await j.selectFrom("delivery_routes").where("courier_id","=",t).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function lf(t){let e=await j.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return e.find((r)=>r.status==="en_route")??e.find((r)=>r.status==="arrived")??e[0]??null}async function mf(t){let e=uf();return await j.insertInto("courier_pings").values({uuid:e,courier_id:t.courierId,delivery_route_id:t.routeId,latitude:t.latitude,longitude:t.longitude,heading:t.heading,speed:t.speed??0,accuracy:t.accuracy,recorded_at:t.recordedAt}).executeTakeFirst(),(await j.selectFrom("courier_pings").where("uuid","=",e).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:pf}=globalThis.Bun;import{db as E}from"@stacksjs/database";function hn(t){return t.type==="pickup"}async function dl(t){let e=pf(),r=t.sequence??await wf(t.deliveryRouteId);await E.insertInto("delivery_stops").values({uuid:e,delivery_route_id:t.deliveryRouteId,order_id:t.orderId??null,sequence:r,status:"pending",address:t.address,latitude:t.latitude??null,longitude:t.longitude??null,recipient_name:t.recipientName??null,recipient_phone:t.recipientPhone??null,eta_at:t.etaAt??null,type:t.type??"dropoff"}).executeTakeFirst();let o=await hf(e);if(o)await xr(o);return o??{}}async function ll(t){await E.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",t).execute();let e=await bn(t);if(!e)return null;if(e.order_id!=null&&!hn(e))await gn(e.order_id,"OUT_FOR_DELIVERY");return await Dr(e),e}async function ml(t,e){let r=new Date().toISOString();await E.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await yf(t)?{}:{arrived_at:r},...e?{notes:e}:{}}).where("id","=",t).execute();let o=await bn(t);if(!o)return null;if(o.order_id!=null)await gn(o.order_id,hn(o)?"OUT_FOR_DELIVERY":"DELIVERED");return await Fr(o),await wl(o.delivery_route_id),o}async function pl(t,e){await E.updateTable("delivery_stops").set({status:"failed",notes:e}).where("id","=",t).execute();let r=await bn(t);if(!r)return null;if(r.order_id!=null&&!hn(r))await gn(r.order_id,"SHIPPED");return await kr(r,e),await wl(r.delivery_route_id),r}async function fl(t){await E.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",t).execute()}async function wl(t){if(t==null)return;if(await E.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await E.selectFrom("delivery_routes").where("id","=",t).select(["courier_id"]).executeTakeFirst();if(await E.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",t).execute(),r?.courier_id!=null)await E.updateTable("couriers").set({status:"active"}).where("id","=",r.courier_id).execute()}async function gn(t,e){let r=await E.selectFrom("orders").where("id","=",t).select(["id","status"]).executeTakeFirst();if(!r)return;let o=await Promise.resolve().then(() => (Te(),Ws)),{canTransition:n,emitForStatus:a}=o,s=ff(r.status,e,n);if(s.length===0){let{log:i}=await import("@stacksjs/logging").catch(()=>({log:null}));i?.warn(`[delivery] refused to move order ${t} from ${r.status} to ${e}: no legal transition`);return}for(let i of s)await E.updateTable("orders").set({status:i}).where("id","=",t).execute(),await a(i,{...r,status:i})}function ff(t,e,r){if(t===e)return[];if(r(t,e))return[e];for(let o of["PROCESSING","SHIPPED"]){if(o===t||o===e)continue;if(r(t,o)&&r(o,e))return[o,e]}return[]}async function wf(t){return(await E.selectFrom("delivery_stops").where("delivery_route_id","=",t).select(["sequence"]).execute()).reduce((r,o)=>Math.max(r,o.sequence??0),0)+1}async function yf(t){return(await E.selectFrom("delivery_stops").where("id","=",t).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function bn(t){return await E.selectFrom("delivery_stops").where("id","=",t).selectAll().executeTakeFirst()??null}async function hf(t){return await E.selectFrom("delivery_stops").where("uuid","=",t).selectAll().executeTakeFirst()??null}var Ar={};g(Ar,{bulkDestroy:()=>gl,bulkSoftDelete:()=>bl,bulkStore:()=>xl,destroy:()=>yl,fetchAll:()=>Yd,fetchById:()=>gr,formatZoneOptions:()=>Xd,getActiveShippingZones:()=>el,getZonesByCountry:()=>tl,softDelete:()=>hl,store:()=>Rl,update:()=>Dl,updateCountries:()=>Pl,updateRegionsAndPostalCodes:()=>Fl,updateStatus:()=>vl});import{db as Er}from"@stacksjs/database";async function yl(t){try{let e=await Er.deleteFrom("shipping_zones").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zone: ${e.message}`);throw e}}async function hl(t){try{let e=await Er.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${e.message}`);throw e}}async function gl(t){if(!t.length)return 0;try{let e=await Er.deleteFrom("shipping_zones").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zones: ${e.message}`);throw e}}async function bl(t){if(!t.length)return 0;try{let e=await Er.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${e.message}`);throw e}}var{randomUUIDv7:_l}=globalThis.Bun;import{db as _n}from"@stacksjs/database";async function Rl(t){try{let e=_l(),r={...nt(t),uuid:e};await _n.insertInto("shipping_zones").values(r).executeTakeFirst();let o=await _n.selectFrom("shipping_zones").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping zone");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zone: ${e.message}`);throw e}}async function xl(t){if(!t.length)return 0;try{let e=t.map((o)=>({...nt(o),uuid:_l()})),r=await _n.insertInto("shipping_zones").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${e.message}`);throw e}}import{db as Sr}from"@stacksjs/database";import{formatDate as Cr}from"@stacksjs/orm";async function Dl(t,e){try{if(!t)throw Error("Shipping zone ID is required for update");let r=await Sr.updateTable("shipping_zones").set({...nt(e),updated_at:Cr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function vl(t,e){try{let r=await Sr.updateTable("shipping_zones").set({status:e,updated_at:Cr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function Pl(t,e){try{let r=await Sr.updateTable("shipping_zones").set({countries:e,updated_at:Cr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function Fl(t,e,r){try{let o={updated_at:Cr(new Date)};if(e!==void 0)o.regions=e;if(r!==void 0)o.postal_codes=r;let n=await Sr.updateTable("shipping_zones").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update regions and postal codes");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${o.message}`);throw o}}var gf={digital:rr,couriers:nr,geocoding:ur,licenses:lr,methods:wr,rates:_r,routes:er,tracking:Tr,zones:Ar},bf=gf;var vn={};g(vn,{activeTaxRates:()=>xn,breakdownFor:()=>Dn,bulkDestroy:()=>Sl,bulkStore:()=>Bl,destroy:()=>El,fetchAll:()=>Ml,fetchById:()=>Al,store:()=>Jl,taxFor:()=>kl,update:()=>Ol,updateDefaultStatus:()=>Wl,updateRate:()=>$l,updateStatus:()=>Ul});import{db as _f}from"@stacksjs/database";function Rf(t){let e=Number(t);return Number.isFinite(e)?e/100:0}async function xn(t={}){let e=_f.selectFrom("tax_rates").where("status","=","active").selectAll();if(t.country)e=e.where("country","=",t.country);let r=await e.execute();if(!t.codes?.length)return r;let o=new Set(t.codes);return r.filter((n)=>o.has(String(n.code??"")))}function Dn(t,e,r={}){let o=Math.max(0,Math.round(t)),n=[],a=0,s=0;for(let i of e){let u=Rf(i.rate),c=Math.round(o*u),m=Boolean(r.exempt&&i.exemptible);if(m)s+=c;else a+=c;n.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:m?0:c,exempted:m})}return{taxable:o,components:n,tax:a,exempted:s}}async function kl(t,e={}){return Dn(t,await xn(e),e)}import{db as Tl}from"@stacksjs/database";async function El(t){try{let e=await Tl.deleteFrom("tax_rates").where("id","=",t).executeTakeFirst();return l(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rate: ${e.message}`);throw e}}async function Sl(t){if(!t.length)return 0;try{let e=await Tl.deleteFrom("tax_rates").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rates: ${e.message}`);throw e}}import{db as Cl}from"@stacksjs/database";async function Al(t){let e=await Cl.selectFrom("tax_rates").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Ml(){return w(await Cl.selectFrom("tax_rates").selectAll().execute())}var{randomUUIDv7:Il}=globalThis.Bun;import{db as Nl}from"@stacksjs/database";async function Jl(t){try{return await Nl.transaction(async(e)=>{let r={...t,uuid:Il()};if(r.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();let o=await e.insertInto("tax_rates").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create tax rate");return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rate: ${e.message}`);throw e}}async function Bl(t){if(!t.length)return 0;try{return await Nl.transaction(async(e)=>{let r=0;for(let o of t){let n={...o,uuid:Il()};if(n.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();if(await e.insertInto("tax_rates").values(n).executeTakeFirst())r++}return r})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${e.message}`);throw e}}import{db as Mr}from"@stacksjs/database";import{formatDate as Ir}from"@stacksjs/orm";async function Ol(t,e){try{if(!t)throw Error("Tax rate ID is required for update");return await Mr.transaction(async(r)=>{let o=await r.selectFrom("tax_rates").select("is_default").where("id","=",t).executeTakeFirst();if(!o)return;let n=e.is_default??Boolean(o.is_default),a=Ir(new Date);if(n)await r.updateTable("tax_rates").set({is_default:!1,updated_at:a}).where("id","!=",t).execute();let s=await r.updateTable("tax_rates").set({...e,updated_at:a}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function Ul(t,e){try{let r=await Mr.updateTable("tax_rates").set({status:e,updated_at:Ir(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function $l(t,e){try{let r=await Mr.updateTable("tax_rates").set({rate:e,updated_at:Ir(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function Wl(t,e){try{return await Mr.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",t).executeTakeFirst())return!1;let n=Ir(new Date);if(e)await r.updateTable("tax_rates").set({is_default:!1,updated_at:n}).where("id","!=",t).execute();return await r.updateTable("tax_rates").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate default status: ${r.message}`);throw r}}var Sn={};g(Sn,{default:()=>Cf,products:()=>Jr,restaurant:()=>Oe});var Jr={};g(Jr,{bulkDestroy:()=>jl,bulkStore:()=>sm,destroy:()=>Ll,fetchAll:()=>zl,fetchById:()=>wt,fetchCancelledBetweenDates:()=>Ql,fetchConversionRates:()=>em,fetchCountBetweenDates:()=>tm,fetchCountByAllQuantities:()=>Zl,fetchCountByDate:()=>Vl,fetchCountByDateGrouped:()=>rm,fetchCountByQuantity:()=>ql,fetchCountBySource:()=>Gl,fetchCountByStatus:()=>Xl,fetchNotifiedBetweenDates:()=>Kl,fetchPurchasedBetweenDates:()=>Hl,fetchWaiting:()=>Yl,store:()=>am,update:()=>Nr,updatePartySize:()=>um,updateStatus:()=>im});import{db as Pn}from"@stacksjs/database";async function Ll(t){try{let e=await Pn.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await Pn.deleteFrom("waitlist_products").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist product: ${e.message}`);throw e}}async function jl(t){if(!t.length)return 0;try{let e=await Pn.deleteFrom("waitlist_products").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${e.message}`);throw e}}import{db as D}from"@stacksjs/database";import{formatDate as k}from"@stacksjs/orm";async function wt(t){let e=await D.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function zl(){return w(await D.selectFrom("waitlist_products").selectAll().execute())}async function Gl(t,e){let r=D.selectFrom("waitlist_products").select(["source",D.fn.count("id").as("count")]).groupBy("source");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{source:a,count:s})=>(n[a]=s,n),{})}async function Vl(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=k(e),n=k(r);return(await D.selectFrom("waitlist_products").select(D.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function ql(t){return(await D.selectFrom("waitlist_products").select(D.fn.count("id").as("count")).where("quantity","=",t).executeTakeFirst())?.count??0}async function Zl(t,e){let r=D.selectFrom("waitlist_products").select(["quantity",D.fn.count("id").as("count")]).groupBy("quantity");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{quantity:a,count:s})=>(n[a]=s,n),{})}async function Kl(t,e){let r=k(t),o=k(e),n=await D.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",o).whereNotNull("notified_at").execute();return w(n)}async function Hl(t,e){let r=k(t),o=k(e),n=await D.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",o).whereNotNull("purchased_at").execute();return w(n)}async function Ql(t,e){let r=k(t),o=k(e),n=await D.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",o).whereNotNull("cancelled_at").execute();return w(n)}async function Yl(){let t=await D.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute();return w(t)}async function Xl(t,e,r){let o=D.selectFrom("waitlist_products").select(D.fn.count("id").as("count")).where("status","=",t);if(e&&r){let a=k(e),s=k(r);o=o.where("created_at",">=",a).where("created_at","<=",s)}return(await o.executeTakeFirst())?.count??0}async function em(t,e){let r=D.selectFrom("waitlist_products").select(["status",D.fn.count("id").as("count")]).groupBy("status");if(t&&e){let u=k(t),c=k(e);r=r.where("created_at",">=",u).where("created_at","<=",c)}let o=await r.execute(),n=o.reduce((u,{count:c})=>u+c,0),a=Number(o.find((u)=>u.status==="purchased")?.count??0),s=n>0?a/n*100:0,i=o.reduce((u,{status:c,count:m})=>(u[c]={count:m,percentage:n>0?m/n*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function tm(t,e){let r=k(t),o=k(e);return(await D.selectFrom("waitlist_products").select(D.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",o).executeTakeFirst())?.count??0}async function rm(t,e){let r=D.selectFrom("waitlist_products").select(["created_at"]);if(t&&e){let a=k(t),s=k(e);r=r.where("created_at",">=",a).where("created_at","<=",s)}let n=(await r.execute()).reduce((a,{created_at:s})=>{let i=(s||"").split("T")[0]||"unknown";return a[i]=(a[i]||0)+1,a},{});return Object.entries(n).map(([a,s])=>({date:a,count:s})).sort((a,s)=>a.date.localeCompare(s.date))}var{randomUUIDv7:nm}=globalThis.Bun;import{db as Fn}from"@stacksjs/database";import{formatDate as om}from"@stacksjs/orm";var xf={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Df(t){return typeof t==="number"||t instanceof Date?om(t):t}function yt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));if(r.quantity===void 0&&r.party_size!==void 0)r.quantity=r.party_size;delete r.party_size;for(let n of["notified_at","purchased_at","cancelled_at"])if(r[n]!==void 0)r[n]=Df(r[n]);let o=xf[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=om(new Date);return r}async function am(t){try{let e=nm(),r={...yt(t),uuid:e,status:t.status||"waiting"};await Fn.insertInto("waitlist_products").values(r).executeTakeFirst();let o=await Fn.selectFrom("waitlist_products").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create waitlist product");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist product: ${e.message}`);throw e}}async function sm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...yt(o),status:o.status||"waiting",uuid:nm()})),r=await Fn.insertInto("waitlist_products").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${e.message}`);throw e}}import{db as vf}from"@stacksjs/database";import{formatDate as Pf}from"@stacksjs/orm";async function Nr(t,e){try{if(!t)throw Error("Waitlist product ID is required for update");let r=await wt(t);if(!r)return;await vf.updateTable("waitlist_products").set({...yt(e,r),updated_at:Pf(new Date)}).where("id","=",t).execute();let o=await wt(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function im(t,e){return await Nr(t,{status:e})}async function um(t,e){return await Nr(t,{quantity:e})}var Oe={};g(Oe,{bulkDestroy:()=>dm,bulkStore:()=>Cm,destroy:()=>cm,fetchAll:()=>lm,fetchAverageWaitTimes:()=>_m,fetchBetweenDates:()=>ym,fetchById:()=>ht,fetchConversionRates:()=>bm,fetchCountByAllPartySizes:()=>wm,fetchCountByDate:()=>pm,fetchCountByPartySize:()=>fm,fetchCountByTablePreference:()=>mm,fetchCurrentWaitTimes:()=>Fm,fetchNoShowStats:()=>Pm,fetchSeatedBetweenDates:()=>hm,fetchSeatedStats:()=>km,fetchSeatingRate:()=>vm,fetchTablesTurnedToday:()=>Dm,fetchTimeSeriesStats:()=>Tm,fetchWaiting:()=>gm,fetchWaitingWithPartySizes:()=>xm,fetchWaitingWithQuotedTimes:()=>Rm,store:()=>Sm,update:()=>Be,updatePartySize:()=>Mm,updateQueuePosition:()=>Nm,updateStatus:()=>Am,updateWaitTimes:()=>Im});import{db as kn}from"@stacksjs/database";async function cm(t){try{let e=await kn.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await kn.deleteFrom("waitlist_restaurants").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${e.message}`);throw e}}async function dm(t){if(!t.length)return 0;try{let e=await kn.deleteFrom("waitlist_restaurants").where("id","in",t).executeTakeFirst();return l(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as _}from"@stacksjs/database";import{formatDate as B}from"@stacksjs/orm";async function ht(t){let e=await _.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function lm(){return w(await _.selectFrom("waitlist_restaurants").selectAll().execute())}async function mm(){return(await _.selectFrom("waitlist_restaurants").select(["table_preference",_.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((e,{table_preference:r,count:o})=>(e[r]=o,e),{})}async function pm(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r);return(await _.selectFrom("waitlist_restaurants").select(_.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function fm(t){return(await _.selectFrom("waitlist_restaurants").select(_.fn.count("id").as("count")).where("party_size","=",t).executeTakeFirst())?.count??0}async function wm(){return(await _.selectFrom("waitlist_restaurants").select(["party_size",_.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((e,{party_size:r,count:o})=>(e[r]=o,e),{})}async function ym(t,e){let r=B(t),o=B(e),n=await _.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",o).execute();return w(n)}async function hm(t,e){let r=B(t),o=B(e),n=await _.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",o).where("status","=","seated").execute();return w(n)}async function gm(){let t=await _.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute();return w(t)}async function bm(){let t=await _.selectFrom("waitlist_restaurants").select(["status",_.fn.count("id").as("count")]).groupBy("status").execute(),e=t.reduce((a,{count:s})=>a+s,0),r=t.find((a)=>a.status==="seated")?.count??0,o=e>0?Number(r)/e*100:0,n=t.reduce((a,{status:s,count:i})=>(a[s]={count:i,percentage:e>0?i/e*100:0},a),{});return{totalConversionRate:o,statusBreakdown:n}}async function _m(){let t=await _.selectFrom("waitlist_restaurants").select([_.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),_.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:t?.avg_quoted_wait_time??0,averageActualWaitTime:t?.avg_actual_wait_time??0}}async function Rm(){let t=w(await _.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((o,n)=>o+(n.quoted_wait_time??0),0),r=t.length>0?e/t.length:0;return{entries:t,totalQuotedWaitTime:e,averageQuotedWaitTime:r}}async function xm(){let t=w(await _.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((n,a)=>n+a.party_size,0),r=t.length>0?e/t.length:0,o=t.reduce((n,a)=>(n[a.party_size]=(n[a.party_size]||0)+1,n),{});return{entries:t,totalPartySize:e,averagePartySize:r,partySizeBreakdown:o}}async function Dm(){let t=new Date,e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r),a=await _.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",o).where("check_in_time","<=",n).execute(),s=a.length,i=a.reduce((p,f)=>p+f.party_size,0),u=s>0?i/s:0,c=a.reduce((p,f)=>(p[f.table_preference]=(p[f.table_preference]||0)+1,p),{}),m=a.reduce((p,f)=>(p[f.party_size]=(p[f.party_size]||0)+1,p),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:m}}async function vm(t,e){let r=B(t),o=B(e),n=await _.selectFrom("waitlist_restaurants").select(["status",_.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",o).groupBy("status").execute(),a=n.reduce((c,{count:m})=>c+m,0),s=n.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=n.reduce((c,{status:m,count:p})=>(c[m]={count:p,percentage:a>0?p/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function Pm(t,e){let r=B(t),o=B(e),n=_.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",o),a=await _.selectFrom("waitlist_restaurants").select(_.fn.count("id").as("count")).where("check_in_time",">=",r).where("check_in_time","<=",o).executeTakeFirst(),s=await n.execute(),i=s.length,u=a?.count&&a.count>0?i/a.count*100:0,c=s.reduce((R,v)=>R+(v.quoted_wait_time??0),0),m=i>0?c/i:0,p=s.reduce((R,v)=>R+v.party_size,0),f=i>0?p/i:0,y=s.reduce((R,v)=>(R[v.table_preference]=(R[v.table_preference]||0)+1,R),{}),b=s.reduce((R,v)=>(R[v.party_size]=(R[v.party_size]||0)+1,R),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:m,averagePartySize:f,breakdownByTablePreference:y,breakdownByPartySize:b}}async function Fm(){let t=await _.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),e=t.reduce((n,a)=>n+(a.quoted_wait_time||0),0),r=t.reduce((n,a)=>n+(a.actual_wait_time||0),0),o=t.length;return{averageQuoted:o>0?e/o:0,averageActual:o>0?r/o:0}}async function km(){let t=Date.now()-86400000,e=await _.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",t).execute(),r=Array.from({length:24},(o,n)=>({hour:n,count:e.filter((a)=>a.seated_at===n).length}));return{total:e.length,byHour:r}}async function Tm(){return(await _.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((e,r)=>{let o=r.created_at;if(!e[o])e[o]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return e[o].total++,e[o][r.status]++,e},{})}var{randomUUIDv7:Em}=globalThis.Bun;import{db as En}from"@stacksjs/database";import{formatDate as Tn}from"@stacksjs/orm";var Ff={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function kf(t){if(typeof t==="number")return Tn(t<=2147483647?t*1000:t);if(t instanceof Date)return Tn(t);return t}function gt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));for(let n of["check_in_time","seated_at","no_show_at","cancelled_at"])if(r[n]!==void 0)r[n]=kf(r[n]);let o=Ff[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=Tn(new Date);return r}async function Sm(t){try{let e=Em(),r={...gt(t),status:t.status||"waiting",uuid:e};await En.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let o=await En.selectFrom("waitlist_restaurants").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create restaurant waitlist entry");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${e.message}`);throw e}}async function Cm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...gt(o),status:o.status||"waiting",uuid:Em()})),r=await En.insertInto("waitlist_restaurants").values(e).executeTakeFirst();return l(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as Tf}from"@stacksjs/database";import{formatDate as Ef}from"@stacksjs/orm";async function Be(t,e){try{if(!t)throw Error("Restaurant waitlist entry ID is required for update");let r=await ht(t);if(!r)return;await Tf.updateTable("waitlist_restaurants").set({...gt(e,r),updated_at:Ef(new Date)}).where("id","=",t).execute();let o=await ht(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function Am(t,e){return await Be(t,{status:e})}async function Mm(t,e){return await Be(t,{party_size:e})}async function Im(t,e,r){return await Be(t,{quoted_wait_time:e,...r===void 0?{}:{actual_wait_time:r}})}async function Nm(t,e){return await Be(t,{queue_position:e})}var Sf={products:Jr,restaurant:Oe},Cf=Sf;var Af={auctions:lo,carts:mo,coupons:po,customers:wo,devices:_o,errors:Do,giftCards:Fo,orders:Bo,payments:Oo,products:Go,receipts:Ho,restaurant:Oe,shippings:Rn,tax:vn,waitlists:Sn},zF=Af;export{lo as auctions,mo as carts,Af as commerce,po as coupons,wo as customers,zF as default,_o as devices,Do as errors,Fo as giftCards,Bo as orders,Oo as payments,Go as products,Ho as receipts,Oe as restaurant,Rn as shippings,vn as tax,Sn as waitlists};
@@ -0,0 +1,10 @@
1
+ /**
2
+ * One raw row as its model type.
3
+ *
4
+ * The returned object satisfies `T` at runtime rather than merely being cast to
5
+ * it: every underscored column gains its declared spelling first.
6
+ */
7
+ export declare function asModelRow<T>(row: unknown): T;
8
+ export declare function asModelRow<T>(row: unknown, allowUndefined: true): T | undefined;
9
+ /** Every row in a raw result set as its model type. */
10
+ export declare function asModelRows<T>(rows: unknown[]): T[];
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/commerce",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.74.3",
5
+ "version": "0.74.5",
6
6
  "description": "Stacks commerce utilities.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,17 +58,17 @@
58
58
  "prepublishOnly": "bun run build"
59
59
  },
60
60
  "dependencies": {
61
- "@stacksjs/cache": "0.74.3",
62
- "@stacksjs/config": "0.74.3",
63
- "@stacksjs/database": "0.74.3",
64
- "@stacksjs/env": "0.74.3",
65
- "@stacksjs/error-handling": "0.74.3",
66
- "@stacksjs/events": "0.74.3",
67
- "@stacksjs/logging": "0.74.3",
68
- "@stacksjs/orm": "0.74.3",
69
- "@stacksjs/payments": "0.74.3",
70
- "@stacksjs/realtime": "0.74.3",
71
- "@stacksjs/strings": "0.74.3",
61
+ "@stacksjs/cache": "0.74.5",
62
+ "@stacksjs/config": "0.74.5",
63
+ "@stacksjs/database": "0.74.5",
64
+ "@stacksjs/env": "0.74.5",
65
+ "@stacksjs/error-handling": "0.74.5",
66
+ "@stacksjs/events": "0.74.5",
67
+ "@stacksjs/logging": "0.74.5",
68
+ "@stacksjs/orm": "0.74.5",
69
+ "@stacksjs/payments": "0.74.5",
70
+ "@stacksjs/realtime": "0.74.5",
71
+ "@stacksjs/strings": "0.74.5",
72
72
  "ts-spreadsheets": "^0.2.0"
73
73
  },
74
74
  "devDependencies": {