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