@stacksjs/commerce 0.75.38 → 0.75.40
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/imports/http.d.ts +36 -0
- package/dist/imports/identity.d.ts +22 -0
- package/dist/imports/index.d.ts +37 -0
- package/dist/imports/money.d.ts +40 -0
- package/dist/imports/shopify.d.ts +40 -0
- package/dist/imports/shopware.d.ts +80 -0
- package/dist/imports/text.d.ts +6 -0
- package/dist/imports/types.d.ts +79 -0
- package/dist/imports/woocommerce.d.ts +62 -0
- package/dist/imports/writer.d.ts +202 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +19 -19
- package/dist/money.d.ts +107 -0
- package/dist/money.js +2 -0
- package/dist/orders/export.d.ts +25 -1
- package/package.json +12 -13
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var Lm=Object.defineProperty;var jm=(t)=>t;function zm(t,e){this[t]=jm.bind(null,e)}var g=(t,e)=>{for(var r in e)Lm(t,r,{get:e[r],enumerable:!0,configurable:!0,set:zm.bind(e,r)})};var Gm=(t,e,r)=>()=>{if(t)try{e=t(t=0)}catch(o){r=[o]}if(r)throw r[0];return e};function ve(t,e){if(t===e)return!0;return Ep[t]?.includes(e)??!1}async function fe(t,e){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let o=r.dispatch;if(typeof o!=="function")return;o(t,e)}catch{}}async function Et(t){await fe("order:created",{order:t})}async function we(t,e){await fe("order:paid",{order:t,payment:e})}async function vo(t){await fe("order:shipped",{order:t})}async function Sp(t){await fe("order:out_for_delivery",{order:t})}async function Po(t){await fe("order:delivered",{order:t})}async function qe(t,e){await fe("order:cancelled",{order:t,reason:e})}async function Ve(t,e){await fe("order:refunded",{order:t,refundAmount:e})}async function Pe(t,e){switch(t){case"PROCESSING":return we(e);case"SHIPPED":return vo(e);case"OUT_FOR_DELIVERY":return Sp(e);case"DELIVERED":return Po(e);case"CANCELLED":return qe(e);case"REFUNDED":return Ve(e);case"PENDING":default:}}var Ep;var Fe=Gm(()=>{Ep={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","OUT_FOR_DELIVERY","CANCELLED","REFUNDED"],SHIPPED:["OUT_FOR_DELIVERY","DELIVERED","REFUNDED"],OUT_FOR_DELIVERY:["DELIVERED","SHIPPED","CANCELLED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]}});var no={};g(no,{DEFAULT_INCREMENT_LADDER:()=>q,auctionChannel:()=>yt,auctionTotals:()=>qr,biddersFor:()=>Ir,bids:()=>Lr,bidsByBidder:()=>Mr,bidsForAuction:()=>Ar,bidsForItem:()=>Cr,broadcastBid:()=>Jr,broadcastItemClosed:()=>Or,broadcastPledge:()=>Br,closeAuction:()=>Kr,closeDueItems:()=>Hr,closeItem:()=>We,closingSoon:()=>Yr,closingSoonNotification:()=>Km,currencyFor:()=>Ur,determineWinner:()=>xe,effectiveCloseAt:()=>ae,engine:()=>jr,extendedCloseAt:()=>Be,fetchAuction:()=>L,fetchAuctionForEvent:()=>zr,fetchCatalogue:()=>Gr,fetchItems:()=>Z,fetchPledges:()=>ro,incrementFor:()=>O,leadingBid:()=>Je,lots:()=>Xr,makePledge:()=>Mn,nextMinimumBid:()=>V,openAuction:()=>Zr,outbidNotification:()=>Zm,placeBid:()=>Wr,pledgeLevels:()=>In,pledgeTotal:()=>to,pledges:()=>oo,resolveBid:()=>Oe,rulesFor:()=>Ue,settle:()=>$e,settleAuction:()=>Qr,winnerNotification:()=>Hm});var Lr={};g(Lr,{biddersFor:()=>Ir,bidsByBidder:()=>Mr,bidsForAuction:()=>Ar,bidsForItem:()=>Cr,leadingBid:()=>Je,placeBid:()=>Wr});import{db as Ne}from"@stacksjs/database/runtime";async function Je(t){return await Ne.selectFrom("bids").selectAll().where("auction_item_id","=",t).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function Cr(t){return await Ne.selectFrom("bids").selectAll().where("auction_item_id","=",t).orderBy("placed_at","desc").execute()??[]}async function Ar(t){return await Ne.selectFrom("bids").selectAll().where("auction_id","=",t).orderBy("placed_at","asc").execute()??[]}async function Mr(t,e){return await Ne.selectFrom("bids").selectAll().where("auction_id","=",t).where("bidder_email","=",e.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function Ir(t){let e=await Ne.selectFrom("bids").select(["bidder_name","bidder_email"]).where("auction_id","=",t).execute(),r=new Map;for(let o of e??[]){let n=o.bidder_email.toLowerCase();if(!r.has(n))r.set(n,{name:o.bidder_name,email:o.bidder_email})}return[...r.values()]}var{randomUUIDv7:Vm}=globalThis.Bun;import{db as $r}from"@stacksjs/database/runtime";function Be(t,e,r,o){if(r.antiSnipeMinutes<=0||r.extendOnBidWindowMinutes<=0)return null;if(t.extension_count>=r.maxExtensions)return null;let n=e.getTime()-o.getTime();if(n<=0)return null;if(n>r.extendOnBidWindowMinutes*60000)return null;let a=new Date(o.getTime()+r.antiSnipeMinutes*60000);return a>e?a:null}function ae(t,e){return new Date(t.closes_at??e)}var q=[{upTo:5000,step:200},{upTo:1e4,step:500},{upTo:25000,step:1000},{upTo:50000,step:2500},{upTo:1e5,step:5000},{upTo:250000,step:1e4},{upTo:null,step:25000}];function O(t,e=q,r){if(r&&r>0)return r;for(let o of e)if(o.upTo===null||t<o.upTo)return o.step;return e[e.length-1]?.step??100}function V(t,e,r=q){if(e===null||e<=0)return t.starting_bid;return e+O(e,r,t.min_increment)}function Oe(t,e,r,o=q){let n=Math.max(r.amount,r.maxAmount??0),a=V(t,e?e.amount:null,o);if(r.maxAmount!=null&&r.maxAmount<r.amount)return{accepted:!1,reason:"max_below_amount",message:"Your maximum bid has to be at least as much as your bid.",nextMinimumBid:a};if(n<a)return{accepted:!1,reason:"below_minimum",message:`The next bid on this lot is ${a/100}.`,nextMinimumBid:a};if(t.buy_now_price&&n>=t.buy_now_price)return{accepted:!0,buyNow:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:t.buy_now_price,maxAmount:t.buy_now_price,isChallenger:!0},challengerAmount:t.buy_now_price,outbid:e?{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount}:void 0,nextMinimumBid:t.buy_now_price};if(!e){let l=Math.max(t.starting_bid,r.amount);return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:l,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:l,nextMinimumBid:l+O(l,o,t.min_increment)}}let s=Math.max(e.amount,e.max_amount??0);if(e.bidder_email.toLowerCase()===r.bidderEmail.toLowerCase()){if(n<=s)return{accepted:!1,reason:"already_leading",message:"You are already the leading bidder at or above that amount.",nextMinimumBid:a};return{accepted:!0,leader:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount,maxAmount:n,isChallenger:!1},challengerAmount:e.amount,nextMinimumBid:e.amount+O(e.amount,o,t.min_increment)}}if(n>s){let l=s+O(s,o,t.min_increment),m=Math.min(n,Math.max(l,a));return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:m,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:m,outbid:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:e.amount},nextMinimumBid:m+O(m,o,t.min_increment)}}let u=n+O(n,o,t.min_increment),c=Math.min(s,Math.max(u,n));return{accepted:!0,leader:{bidderEmail:e.bidder_email,bidderName:e.bidder_name,amount:c,maxAmount:e.max_amount??null,isChallenger:!1},challengerAmount:n,outbid:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:n},nextMinimumBid:c+O(c,o,t.min_increment)}}function yt(t){return`auction.${t}`}async function Nr(){try{let t=await import("@stacksjs/realtime");return t.emit??null}catch{return null}}async function Jr(t){let e=await Nr();if(!e||!t.item||!t.leader)return;await e(yt(t.item.auction_id),"bid.placed",{itemId:t.item.id,lotNumber:t.item.lot_number,amount:t.leader.amount,nextMinimumBid:t.nextMinimumBid,leaderName:t.leader.bidderName,status:t.item.status,closesAt:t.item.closes_at,extended:Boolean(t.extendedTo),soldViaBuyNow:Boolean(t.buyNow)})}async function Br(t,e){let r=await Nr();if(!r)return;await r(yt(t.auction_id),"pledge.made",{donorName:t.donor_name,amount:t.amount,level:t.level??null,runningTotal:e})}async function Or(t,e,r){let o=await Nr();if(!o)return;await o(yt(t),"item.closed",{itemId:e,...r})}import{config as qm}from"@stacksjs/config";function Cn(){return qm.commerce??{}}function An(){return Cn().auction??{}}function Ue(t){let e=An();return{increments:e.increments?.length?e.increments:q,antiSnipeMinutes:t?.anti_snipe_minutes??e.antiSnipeMinutes??2,extendOnBidWindowMinutes:t?.extend_on_bid_window_minutes??e.extendOnBidWindowMinutes??2,maxExtensions:t?.max_extensions??e.maxExtensions??20}}function Ur(t){return t?.currency??An().currency??Cn().currency??"USD"}function ht(t){return t.toISOString().slice(0,19).replace("T"," ")}async function Wr(t){let e=t.now??new Date,r=await $r.selectFrom("auction_items").selectAll().where("id","=",t.itemId).executeTakeFirst();if(!r)return{accepted:!1,reason:"item_not_found",message:"That lot is no longer available.",nextMinimumBid:0};let o=await $r.selectFrom("auctions").selectAll().where("id","=",r.auction_id).executeTakeFirst(),n=Ue(o),a=await Je(r.id),s=V(r,a?.amount??null,n.increments);if(!o||o.status!=="open"||new Date(o.opens_at)>e)return{accepted:!1,reason:"auction_not_open",message:"Bidding is not open yet.",nextMinimumBid:s,item:r};let i=ae(r,o.closes_at);if(r.status!=="open"||i<=e)return{accepted:!1,reason:"item_not_open",message:"Bidding on this lot has closed.",nextMinimumBid:s,item:r};let u=Oe(r,a,{bidderEmail:t.bidderEmail,bidderName:t.bidderName,amount:t.amount,maxAmount:t.maxAmount},n.increments);if(!u.accepted)return{...u,item:r};let c=u.buyNow?null:Be(r,i,n,e),l=u.leader&&!u.leader.isChallenger&&a&&a.bidder_email.toLowerCase()===t.bidderEmail.toLowerCase(),m=await $r.transaction(async(h)=>{if(l&&a)return await h.updateTable("bids").set({max_amount:u.leader.maxAmount}).where("id","=",a.id).execute(),{...a,max_amount:u.leader.maxAmount};let b=u.leader?.isChallenger===!0,_=Vm();if(await h.insertInto("bids").values({uuid:_,auction_id:r.auction_id,auction_item_id:r.id,bidder_name:t.bidderName,bidder_email:t.bidderEmail.toLowerCase(),amount:u.challengerAmount??t.amount,max_amount:t.maxAmount??null,status:b?"leading":"outbid",placed_at:ht(e)}).execute(),a){if(b)await h.updateTable("bids").set({status:"outbid"}).where("id","=",a.id).execute();else if(u.leader&&u.leader.amount!==a.amount)await h.updateTable("bids").set({amount:u.leader.amount}).where("id","=",a.id).execute()}if(u.buyNow)await h.updateTable("auction_items").set({status:"sold",closes_at:ht(e)}).where("id","=",r.id).execute();else if(c)await h.updateTable("auction_items").set({closes_at:ht(c),extension_count:r.extension_count+1}).where("id","=",r.id).execute();return await h.selectFrom("bids").selectAll().where("uuid","=",_).executeTakeFirst()}),f={...u,bid:m,item:{...r,status:u.buyNow?"sold":r.status,closes_at:c?ht(c):r.closes_at,extension_count:c?r.extension_count+1:r.extension_count},extendedTo:c??void 0};return await Jr(f).catch(()=>{return}),f}var jr={};g(jr,{DEFAULT_INCREMENT_LADDER:()=>q,determineWinner:()=>xe,effectiveCloseAt:()=>ae,extendedCloseAt:()=>Be,incrementFor:()=>O,nextMinimumBid:()=>V,resolveBid:()=>Oe,settle:()=>$e});function xe(t,e){let r=e.filter((a)=>a.status!=="invalid");if(r.length===0)return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"passed",amount:0,passedReason:"no_bids"};let n=[...r].sort((a,s)=>{if(s.amount!==a.amount)return s.amount-a.amount;return new Date(a.placed_at).getTime()-new Date(s.placed_at).getTime()})[0];if(t.reserve_price&&n.amount<t.reserve_price)return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"passed",amount:n.amount,passedReason:"reserve_not_met"};return{itemId:t.id,lotNumber:t.lot_number,title:t.title,status:"sold",winningBidId:n.id,winnerName:n.bidder_name,winnerEmail:n.bidder_email,amount:n.amount}}function $e(t,e,r,o){let n=e.filter((m)=>m.status==="sold"),a=e.filter((m)=>m.status==="passed"),s=n.reduce((m,f)=>m+f.amount,0),i=r.filter((m)=>m.status==="confirmed").reduce((m,f)=>m+f.amount,0),u=new Map(t.map((m)=>[m.id,m.fair_market_value??null])),c=n.reduce((m,f)=>{let h=u.get(f.itemId);return h==null?m:m+(f.amount-h)},0),l=e.length;return{auctionId:o.auctionId,currency:o.currency,totalRaised:s+i,bidRevenue:s,pledgeRevenue:i,goalAmount:o.goalAmount??null,itemsSold:n.length,itemsPassed:a.length,sellThrough:l===0?0:n.length/l,valueDelta:c,outcomes:e}}var Xr={};g(Xr,{auctionTotals:()=>qr,closeAuction:()=>Kr,closeDueItems:()=>Hr,closeItem:()=>We,closingSoon:()=>Yr,fetchAuction:()=>L,fetchAuctionForEvent:()=>zr,fetchCatalogue:()=>Gr,fetchItems:()=>Z,openAuction:()=>Zr,settleAuction:()=>Qr});import{db as se}from"@stacksjs/database/runtime";async function L(t){return await se.selectFrom("auctions").selectAll().where("id","=",t).executeTakeFirst()??null}async function zr(t){return await se.selectFrom("auctions").selectAll().where("event_id","=",t).executeTakeFirst()??null}async function Z(t){return await se.selectFrom("auction_items").selectAll().where("auction_id","=",t).orderBy("lot_number","asc").execute()??[]}async function Gr(t){let[e,r]=await Promise.all([L(t),Z(t)]),o=Ue(e),n=await se.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",t).where("status","in",["leading","won"]).execute(),a=await se.selectFrom("bids").select(["auction_item_id"]).where("auction_id","=",t).where("status","!=","invalid").execute(),s=new Map((n??[]).map((u)=>[u.auction_item_id,u])),i=new Map;for(let u of a??[])i.set(u.auction_item_id,(i.get(u.auction_item_id)??0)+1);return r.map((u)=>{let c=s.get(u.id)??null;return{...u,currentBid:c?.amount??0,bidCount:i.get(u.id)??0,nextMinimumBid:V(u,c?.amount??null,o.increments),leaderName:c?.bidder_name??null}})}async function qr(t){let e=await L(t),r=await se.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",t).where("status","!=","invalid").execute(),o=await se.selectFrom("pledges").select(["amount"]).where("auction_id","=",t).where("status","=","confirmed").execute(),n=r??[],s=n.filter((c)=>c.status==="leading"||c.status==="won").reduce((c,l)=>c+l.amount,0),i=(o??[]).reduce((c,l)=>c+l.amount,0),u=await se.selectFrom("auction_items").where("auction_id","=",t).count();return{currentBidTotal:s,pledgeTotal:i,raised:s+i,goalAmount:e?.goal_amount??null,bidCount:n.length,bidderCount:new Set(n.map((c)=>c.bidder_email.toLowerCase())).size,lotsOffered:Number(u??0),lotsWithBids:new Set(n.map((c)=>c.auction_item_id)).size}}import{db as ie}from"@stacksjs/database/runtime";function Vr(t){return t.toISOString().slice(0,19).replace("T"," ")}async function Zr(t,e=new Date){return await ie.updateTable("auctions").set({status:"open",opens_at:Vr(e)}).where("id","=",t).execute(),await ie.updateTable("auction_items").set({status:"open"}).where("auction_id","=",t).where("status","=","closed").execute(),L(t)}async function We(t,e=new Date){if(t.status==="sold"||t.status==="passed")return null;let r=await ie.selectFrom("bids").selectAll().where("auction_item_id","=",t.id).execute(),o=xe(t,r??[]);return await ie.transaction(async(n)=>{if(await n.updateTable("auction_items").set({status:o.status,closes_at:Vr(e)}).where("id","=",t.id).execute(),o.winningBidId)await n.updateTable("bids").set({status:"won"}).where("id","=",o.winningBidId).execute();await n.updateTable("bids").set({status:"lost"}).where("auction_item_id","=",t.id).where("status","in",["leading","outbid"]).execute()}),await Or(t.auction_id,t.id,{status:o.status,amount:o.amount,winnerName:o.winnerName}).catch(()=>{return}),o}async function Hr(t,e=new Date){let r=await L(t);if(!r)return[];let o=await Z(t),n=[];for(let a of o){if(a.status!=="open")continue;if(ae(a,r.closes_at)>e)continue;let s=await We(a,e);if(s)n.push(s)}return n}async function Kr(t,e=new Date){let r=await Z(t),o=[];for(let n of r){let a=await We(n,e);if(a)o.push(a)}return await ie.updateTable("auctions").set({status:"closed",closes_at:Vr(e)}).where("id","=",t).execute(),o}async function Qr(t,e={}){let r=await L(t);if(!r)return null;let o=await Z(t),n=await ie.selectFrom("bids").selectAll().where("auction_id","=",t).execute(),a=await ie.selectFrom("pledges").selectAll().where("auction_id","=",t).execute(),s=new Map;for(let u of n??[]){let c=s.get(u.auction_item_id)??[];c.push(u),s.set(u.auction_item_id,c)}let i=o.map((u)=>{let c=xe(u,s.get(u.id)??[]);return u.status==="passed"?{...c,status:"passed"}:c});if(e.markSettled)await ie.updateTable("auctions").set({status:"settled"}).where("id","=",t).execute();return $e(o,i,a??[],{auctionId:t,currency:Ur(r),goalAmount:r.goal_amount??null})}async function Yr(t,e,r=new Date){let o=await L(t);if(!o)return[];let n=new Date(r.getTime()+e*60000);return(await Z(t)).filter((a)=>{if(a.status!=="open")return!1;let s=ae(a,o.closes_at);return s>r&&s<=n})}function eo(t,e="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0}).format(t/100)}function Zm(t,e="USD"){if(!t.outbid||!t.item)return null;let r=t.item;return{to:{name:t.outbid.bidderName,email:t.outbid.bidderEmail},type:"outbid",subject:`You have been outbid on lot ${r.lot_number}: ${r.title}`,body:`Someone has bid higher on "${r.title}". The next bid is ${eo(t.nextMinimumBid,e)}. Bidding closes ${new Date(r.closes_at??"").toLocaleString()}.`,data:{itemId:r.id,lotNumber:r.lot_number,title:r.title,nextMinimumBid:t.nextMinimumBid,closesAt:r.closes_at}}}function Hm(t,e="USD"){if(t.status!=="sold"||!t.winnerEmail)return null;return{to:{name:t.winnerName??"Bidder",email:t.winnerEmail},type:"winner",subject:`You won lot ${t.lotNumber}: ${t.title}`,body:`Congratulations - you won "${t.title}" at ${eo(t.amount,e)}. The school will be in touch with payment and pickup details.`,data:{itemId:t.itemId,lotNumber:t.lotNumber,title:t.title,amount:t.amount}}}function Km(t,e,r,o="USD"){return{to:e,type:"closing_soon",subject:`Closing soon: lot ${t.lot_number}, ${t.title}`,body:`"${t.title}" closes at ${new Date(t.closes_at??"").toLocaleString()}. The current bid is ${eo(r,o)}.`,data:{itemId:t.id,lotNumber:t.lot_number,title:t.title,currentBid:r,closesAt:t.closes_at}}}var oo={};g(oo,{fetchPledges:()=>ro,makePledge:()=>Mn,pledgeLevels:()=>In,pledgeTotal:()=>to});var{randomUUIDv7:Qm}=globalThis.Bun;import{db as gt}from"@stacksjs/database/runtime";async function Mn(t){let e=Qm();await gt.insertInto("pledges").values({uuid:e,auction_id:t.auctionId,donor_name:t.donorName,donor_email:t.donorEmail.toLowerCase(),amount:t.amount,level:t.level??null,status:t.status??"confirmed"}).execute();let r=await gt.selectFrom("pledges").selectAll().where("uuid","=",e).executeTakeFirst();return await Br(r,await to(t.auctionId)).catch(()=>{return}),r}async function to(t){return(await gt.selectFrom("pledges").select(["amount"]).where("auction_id","=",t).where("status","=","confirmed").execute()??[]).reduce((r,o)=>r+o.amount,0)}async function ro(t){return await gt.selectFrom("pledges").selectAll().where("auction_id","=",t).orderBy("amount","desc").execute()??[]}async function In(t){let e=(await ro(t)).filter((o)=>o.status==="confirmed"),r=new Map;for(let o of e){let n=o.level??"other",a=r.get(n)??{amount:0,count:0};a.amount+=o.amount,a.count+=1,r.set(n,a)}return[...r.entries()].map(([o,n])=>({level:o,...n})).sort((o,n)=>n.amount-o.amount)}var ao={};g(ao,{bulkDestroy:()=>Bn,bulkStore:()=>zn,bulkUpdate:()=>Zn,destroy:()=>Jn,fetchAll:()=>$n,fetchById:()=>Un,store:()=>jn,update:()=>Vn});import{db as Nn}from"@stacksjs/database/runtime";import{mutationCount as p}from"@stacksjs/database/runtime";async function Jn(t){try{let e=await Nn.deleteFrom("carts").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete cart: ${e.message}`);throw e}}async function Bn(t){if(!t.length)return 0;try{let e=await Nn.deleteFrom("carts").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete carts: ${e.message}`);throw e}}import{db as On}from"@stacksjs/database/runtime";function Ym(t){return t.replace(/_([a-z0-9])/g,(e,r)=>r.toUpperCase())}function d(t){if(t===null||typeof t!=="object")return t;let e={...t};for(let[r,o]of Object.entries(e)){if(!r.includes("_"))continue;let n=Ym(r);if(!(n in e))e[n]=o}return e}function w(t){return t.map((e)=>d(e))}async function Un(t){let e=await On.selectFrom("carts").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function $n(){return w(await On.selectFrom("carts").selectAll().execute())}var{randomUUIDv7:Wn}=globalThis.Bun;import{db as Ln}from"@stacksjs/database/runtime";async function jn(t){try{let e={...t,uuid:Wn()},r=await Ln.insertInto("carts").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create cart");return d(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create cart: ${e.message}`);throw e}}async function zn(t){if(!t.length)return 0;let e=0;try{return await Ln.transaction(async(r)=>{for(let o of t){let n={...o,uuid:Wn()};await r.insertInto("carts").values(n).execute(),e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create carts in bulk: ${r.message}`);throw r}}import{db as Gn,matchedRows as Xm}from"@stacksjs/database/runtime";import{formatDate as qn}from"@stacksjs/orm";async function Vn(t,e){try{let r=await Gn.updateTable("carts").set({...e,updated_at:qn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update cart");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update cart: ${r.message}`);throw r}}async function Zn(t){if(!t.length)return 0;let e=0;try{return await Gn.transaction(async(r)=>{for(let o of t){if(!o.id)continue;if((await Xm(r.updateTable("carts").set({...o,updated_at:qn(new Date)}).where("id","=",o.id))).length>0)e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update carts in bulk: ${r.message}`);throw r}}var io={};g(io,{deleteCoupon:()=>Hn,deleteCoupons:()=>Kn,deleteExpiredCoupons:()=>Qn,fetchActive:()=>ra,fetchAll:()=>ea,fetchByCode:()=>ta,fetchById:()=>pe,fetchConversionRate:()=>ca,fetchCouponCounts:()=>na,fetchCouponCountsByType:()=>aa,fetchRedemptionStats:()=>sa,fetchRedemptionTrend:()=>ua,fetchStats:()=>oa,fetchTopRedeemedCoupons:()=>ia,getActiveCouponsMoMChange:()=>da,redeem:()=>ga,store:()=>pa,update:()=>ha});import{db as so}from"@stacksjs/database/runtime";import{formatDate as ep}from"@stacksjs/orm";async function Hn(t){let e=await so.deleteFrom("coupons").where("id","=",t).executeTakeFirst();return p(e)>0}async function Kn(t){if(!t.length)return 0;return await so.deleteFrom("coupons").where("id","in",t).execute()||0}async function Qn(){let t=ep(new Date),e=await so.deleteFrom("coupons").where("end_date","<",t).executeTakeFirst();return p(e)}import{db as y}from"@stacksjs/database/runtime";import{extractDate as Yn,formatDate as Xn}from"@stacksjs/orm";import{camelCase as tp}from"@stacksjs/strings";function _t(t){let e=Object.fromEntries(Object.entries(t).map(([r,o])=>[tp(r),o]));if(e.endDate)e.endDate=Yn(new Date(e.endDate));if(e.startDate)e.startDate=Yn(new Date(e.startDate));if(e.isActive!==void 0)e.isActive=Boolean(e.isActive);return e}async function ea(){let t=await y.selectFrom("coupons").selectAll().execute();return w(t).map(_t)}async function pe(t){let e=await y.selectFrom("coupons").where("id","=",t).selectAll().executeTakeFirst();if(e)return _t(d(e));return}async function ta(t){let e=await y.selectFrom("coupons").where("code","=",t).selectAll().executeTakeFirst();if(e)return _t(d(e));return}async function ra(){let t=Xn(new Date),e=await y.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).selectAll().execute();return w(e).map(_t)}async function oa(){let t=await y.selectFrom("coupons").select(y.fn.count("id").as("count")).executeTakeFirst(),e=Xn(new Date),r=await y.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(y.fn.count("id").as("count")).executeTakeFirst(),o=await y.selectFrom("coupons").select(["discount_type",y.fn.count("id").as("count")]).groupBy("discount_type").execute(),n=await y.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),a=await y.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",e).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(t?.count||0),active:Number(r?.count||0),by_type:o,most_used:n,upcoming:a}}async function na(){let t=new Date,e=new Date(t);e.setDate(t.getDate()-7);let r=new Date(t);r.setMonth(t.getMonth()-1);let o=new Date(t);o.setFullYear(t.getFullYear()-1);let n=await bt(null,null,t),a=await bt(e,null,t),s=await bt(r,null,t),i=await bt(o,null,t);return{week:a,month:s,year:i,all_time:n}}async function bt(t,e,r){let o=y.selectFrom("coupons");if(t)o=o.where("created_at",">=",t.toISOString());if(e)o=o.where("created_at","<=",e.toISOString());let n=await o.select(y.fn.count("id").as("count")).executeTakeFirst(),a=y.selectFrom("coupons");if(t)a=a.where("created_at",">=",t.toISOString());if(e)a=a.where("created_at","<=",e.toISOString());a=a.where("is_active","=",!0).where("start_date","<=",r).where("end_date",">=",r);let s=await a.select(y.fn.count("id").as("count")).executeTakeFirst(),i=Number(n?.count||0),u=Number(s?.count||0),c=i-u;return{total:i,active:u,inactive:c}}async function aa(){let t=new Date,e=await y.selectFrom("coupons").select("discount_type").distinct().execute(),r={};for(let{discount_type:o}of e){let n=await y.selectFrom("coupons").where("discount_type","=",o).select(y.fn.count("id").as("count")).executeTakeFirst(),a=await y.selectFrom("coupons").where("discount_type","=",o).where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(y.fn.count("id").as("count")).executeTakeFirst(),s=Number(n?.count||0),i=Number(a?.count||0);r[o]={total:s,active:i,inactive:s-i}}return r}async function sa(){let t=await y.selectFrom("coupons").select(y.fn.sum("usage_count").as("total")).executeTakeFirst(),e=new Date,r=new Date(e);r.setDate(e.getDate()-7);let o=new Date(e);o.setMonth(e.getMonth()-1);let n=new Date(e);n.setFullYear(e.getFullYear()-1);let a=await y.selectFrom("coupons").where("updated_at",">=",r.toISOString()).select(y.fn.sum("usage_count").as("total")).executeTakeFirst(),s=await y.selectFrom("coupons").where("updated_at",">=",o.toISOString()).select(y.fn.sum("usage_count").as("total")).executeTakeFirst(),i=await y.selectFrom("coupons").where("updated_at",">=",n.toISOString()).select(y.fn.sum("usage_count").as("total")).executeTakeFirst(),u=await y.selectFrom("coupons").select(["discount_type",y.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),c={};return u.forEach((l)=>{c[l.discount_type]=Number(l.total||0)}),{total:Number(t?.total||0),week:Number(a?.total||0),month:Number(s?.total||0),year:Number(i?.total||0),by_type:c}}async function ia(t=5){return await y.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(t).execute()}async function ua(t=30){let e=new Date().toISOString(),r=new Date;r.setDate(r.getDate()-t);let o=await y.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",r.toISOString()).where("updated_at","<=",e).where("usage_count",">",0).orderBy("updated_at","desc").execute(),n={};return o.forEach((a)=>{let s=a.updated_at?new Date(a.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!n[s])n[s]=0;n[s]+=a?.usage_count||0}),Object.entries(n).map(([a,s])=>({date:a,count:s}))}async function ca(){let t=new Date,e=await y.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(y.fn.count("id").as("count")).executeTakeFirst(),r=await y.selectFrom("coupons").where("usage_count",">",0).select(y.fn.count("id").as("count")).executeTakeFirst(),o=Number(e?.count||0),n=Number(r?.count||0);return{rate:o>0?n/o*100:0,total_active:o,total_redeemed:n}}async function da(){let t=new Date,e=new Date(t.getFullYear(),t.getMonth(),1),r=new Date(t.getFullYear(),t.getMonth()-1,1),o=new Date(t.getFullYear(),t.getMonth(),0),n=await y.selectFrom("coupons").select(y.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",e).executeTakeFirst(),a=await y.selectFrom("coupons").select(y.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",o).where("end_date",">=",r).executeTakeFirst(),s=Number(n?.count||0),i=Number(a?.count||0),u=s-i,c=i!==0?u/i*100:s>0?100:0;return{current_month:s,previous_month:i,difference:u,percentage_change:c}}var{randomUUIDv7:rp}=globalThis.Bun;import{db as la}from"@stacksjs/database/runtime";import{HttpError as ma}from"@stacksjs/error-handling";import{isUniqueViolation as op}from"@stacksjs/orm";async function pa(t){try{let e=rp();await la.insertInto("coupons").values({...t,uuid:e}).executeTakeFirst();let r=await la.selectFrom("coupons").where("uuid","=",e).selectAll().executeTakeFirst();return d(r,!0)}catch(e){if(e instanceof ma)throw e;if(op(e))throw new ma(409,"A coupon with this code already exists");if(e instanceof Error)throw Error(`Failed to create coupon: ${e.message}`);throw e}}import{db as wa,mutationCount as np,sqlHelpers as ap}from"@stacksjs/database/runtime";import{env as sp}from"@stacksjs/env";import{HttpError as fa}from"@stacksjs/error-handling";import{formatDate as ya,isUniqueViolation as ip}from"@stacksjs/orm";async function ha(t,e){if(!await pe(t))return;try{return await wa.updateTable("coupons").set({...e,updated_at:ya(new Date)}).where("id","=",t).execute(),await pe(t)}catch(o){if(o instanceof fa)throw o;if(ip(o))throw new fa(409,"A coupon with this code already exists");if(o instanceof Error)throw Error(`Failed to update coupon: ${o.message}`);throw o}}async function ga(t){let e=ap(sp.DB_CONNECTION||"sqlite"),r=e.param,o=ya(new Date),n=await wa.unsafe(`UPDATE coupons
|
|
2
|
+
var vf=Object.defineProperty;var Df=(e)=>e;function kf(e,t){this[e]=Df.bind(null,t)}var D=(e,t)=>{for(var r in t)vf(e,r,{get:t[r],enumerable:!0,configurable:!0,set:kf.bind(t,r)})};var Ff=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};function Le(e,t){if(e===t)return!0;return Ow[e]?.includes(t)??!1}async function Ee(e,t){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let n=r.dispatch;if(typeof n!=="function")return;n(e,t)}catch{}}async function Xt(e){await Ee("order:created",{order:e})}async function Ae(e,t){await Ee("order:paid",{order:e,payment:t})}async function wo(e){await Ee("order:shipped",{order:e})}async function Jw(e){await Ee("order:out_for_delivery",{order:e})}async function yo(e){await Ee("order:delivered",{order:e})}async function dt(e,t){await Ee("order:cancelled",{order:e,reason:t})}async function lt(e,t){await Ee("order:refunded",{order:e,refundAmount:t})}async function je(e,t){switch(e){case"PROCESSING":return Ae(t);case"SHIPPED":return wo(t);case"OUT_FOR_DELIVERY":return Jw(t);case"DELIVERED":return yo(t);case"CANCELLED":return dt(t);case"REFUNDED":return lt(t);case"PENDING":default:}}var Ow;var ze=Ff(()=>{Ow={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","OUT_FOR_DELIVERY","CANCELLED","REFUNDED"],SHIPPED:["OUT_FOR_DELIVERY","DELIVERED","REFUNDED"],OUT_FOR_DELIVERY:["DELIVERED","SHIPPED","CANCELLED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]}});var Sn={};D(Sn,{DEFAULT_INCREMENT_LADDER:()=>oe,auctionChannel:()=>It,auctionTotals:()=>gn,biddersFor:()=>on,bids:()=>mn,bidsByBidder:()=>nn,bidsForAuction:()=>rn,bidsForItem:()=>tn,broadcastBid:()=>sn,broadcastItemClosed:()=>cn,broadcastPledge:()=>un,closeAuction:()=>xn,closeDueItems:()=>_n,closeItem:()=>at,closingSoon:()=>Pn,closingSoonNotification:()=>Af,currencyFor:()=>dn,determineWinner:()=>Be,effectiveCloseAt:()=>_e,engine:()=>fn,extendedCloseAt:()=>tt,fetchAuction:()=>ee,fetchAuctionForEvent:()=>wn,fetchCatalogue:()=>yn,fetchItems:()=>se,fetchPledges:()=>Fn,incrementFor:()=>Q,leadingBid:()=>et,lots:()=>vn,makePledge:()=>Fa,nextMinimumBid:()=>ae,openAuction:()=>bn,outbidNotification:()=>Cf,placeBid:()=>pn,pledgeLevels:()=>Ta,pledgeTotal:()=>kn,pledges:()=>Tn,resolveBid:()=>rt,rulesFor:()=>nt,settle:()=>ot,settleAuction:()=>Rn,winnerNotification:()=>Ef});var mn={};D(mn,{biddersFor:()=>on,bidsByBidder:()=>nn,bidsForAuction:()=>rn,bidsForItem:()=>tn,leadingBid:()=>et,placeBid:()=>pn});import{db as Xe}from"@stacksjs/database/runtime";async function et(e){return await Xe.selectFrom("bids").selectAll().where("auction_item_id","=",e).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function tn(e){return await Xe.selectFrom("bids").selectAll().where("auction_item_id","=",e).orderBy("placed_at","desc").execute()??[]}async function rn(e){return await Xe.selectFrom("bids").selectAll().where("auction_id","=",e).orderBy("placed_at","asc").execute()??[]}async function nn(e,t){return await Xe.selectFrom("bids").selectAll().where("auction_id","=",e).where("bidder_email","=",t.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function on(e){let t=await Xe.selectFrom("bids").select(["bidder_name","bidder_email"]).where("auction_id","=",e).execute(),r=new Map;for(let n of t??[]){let o=n.bidder_email.toLowerCase();if(!r.has(o))r.set(o,{name:n.bidder_name,email:n.bidder_email})}return[...r.values()]}var{randomUUIDv7:Sf}=globalThis.Bun;import{db as ln}from"@stacksjs/database/runtime";function tt(e,t,r,n){if(r.antiSnipeMinutes<=0||r.extendOnBidWindowMinutes<=0)return null;if(e.extension_count>=r.maxExtensions)return null;let o=t.getTime()-n.getTime();if(o<=0)return null;if(o>r.extendOnBidWindowMinutes*60000)return null;let a=new Date(n.getTime()+r.antiSnipeMinutes*60000);return a>t?a:null}function _e(e,t){return new Date(e.closes_at??t)}var oe=[{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 Q(e,t=oe,r){if(r&&r>0)return r;for(let n of t)if(n.upTo===null||e<n.upTo)return n.step;return t[t.length-1]?.step??100}function ae(e,t,r=oe){if(t===null||t<=0)return e.starting_bid;return t+Q(t,r,e.min_increment)}function rt(e,t,r,n=oe){let o=Math.max(r.amount,r.maxAmount??0),a=ae(e,t?t.amount:null,n);if(r.maxAmount!=null&&r.maxAmount<r.amount)return{accepted:!1,reason:"max_below_amount",message:"Your maximum bid has to be at least as much as your bid.",nextMinimumBid:a};if(o<a)return{accepted:!1,reason:"below_minimum",message:`The next bid on this lot is ${a/100}.`,nextMinimumBid:a};if(e.buy_now_price&&o>=e.buy_now_price)return{accepted:!0,buyNow:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:e.buy_now_price,maxAmount:e.buy_now_price,isChallenger:!0},challengerAmount:e.buy_now_price,outbid:t?{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:t.amount}:void 0,nextMinimumBid:e.buy_now_price};if(!t){let d=Math.max(e.starting_bid,r.amount);return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:d,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:d,nextMinimumBid:d+Q(d,n,e.min_increment)}}let s=Math.max(t.amount,t.max_amount??0);if(t.bidder_email.toLowerCase()===r.bidderEmail.toLowerCase()){if(o<=s)return{accepted:!1,reason:"already_leading",message:"You are already the leading bidder at or above that amount.",nextMinimumBid:a};return{accepted:!0,leader:{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:t.amount,maxAmount:o,isChallenger:!1},challengerAmount:t.amount,nextMinimumBid:t.amount+Q(t.amount,n,e.min_increment)}}if(o>s){let d=s+Q(s,n,e.min_increment),m=Math.min(o,Math.max(d,a));return{accepted:!0,leader:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:m,maxAmount:r.maxAmount??null,isChallenger:!0},challengerAmount:m,outbid:{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:t.amount},nextMinimumBid:m+Q(m,n,e.min_increment)}}let u=o+Q(o,n,e.min_increment),c=Math.min(s,Math.max(u,o));return{accepted:!0,leader:{bidderEmail:t.bidder_email,bidderName:t.bidder_name,amount:c,maxAmount:t.max_amount??null,isChallenger:!1},challengerAmount:o,outbid:{bidderEmail:r.bidderEmail,bidderName:r.bidderName,amount:o},nextMinimumBid:c+Q(c,n,e.min_increment)}}function It(e){return`auction.${e}`}async function an(){try{let e=await import("@stacksjs/realtime");return e.emit??null}catch{return null}}async function sn(e){let t=await an();if(!t||!e.item||!e.leader)return;await t(It(e.item.auction_id),"bid.placed",{itemId:e.item.id,lotNumber:e.item.lot_number,amount:e.leader.amount,nextMinimumBid:e.nextMinimumBid,leaderName:e.leader.bidderName,status:e.item.status,closesAt:e.item.closes_at,extended:Boolean(e.extendedTo),soldViaBuyNow:Boolean(e.buyNow)})}async function un(e,t){let r=await an();if(!r)return;await r(It(e.auction_id),"pledge.made",{donorName:e.donor_name,amount:e.amount,level:e.level??null,runningTotal:t})}async function cn(e,t,r){let n=await an();if(!n)return;await n(It(e),"item.closed",{itemId:t,...r})}import{config as Tf}from"@stacksjs/config";function Da(){return Tf.commerce??{}}function ka(){return Da().auction??{}}function nt(e){let t=ka();return{increments:t.increments?.length?t.increments:oe,antiSnipeMinutes:e?.anti_snipe_minutes??t.antiSnipeMinutes??2,extendOnBidWindowMinutes:e?.extend_on_bid_window_minutes??t.extendOnBidWindowMinutes??2,maxExtensions:e?.max_extensions??t.maxExtensions??20}}function dn(e){return e?.currency??ka().currency??Da().currency??"USD"}function Nt(e){return e.toISOString().slice(0,19).replace("T"," ")}async function pn(e){let t=e.now??new Date,r=await ln.selectFrom("auction_items").selectAll().where("id","=",e.itemId).executeTakeFirst();if(!r)return{accepted:!1,reason:"item_not_found",message:"That lot is no longer available.",nextMinimumBid:0};let n=await ln.selectFrom("auctions").selectAll().where("id","=",r.auction_id).executeTakeFirst(),o=nt(n),a=await et(r.id),s=ae(r,a?.amount??null,o.increments);if(!n||n.status!=="open"||new Date(n.opens_at)>t)return{accepted:!1,reason:"auction_not_open",message:"Bidding is not open yet.",nextMinimumBid:s,item:r};let i=_e(r,n.closes_at);if(r.status!=="open"||i<=t)return{accepted:!1,reason:"item_not_open",message:"Bidding on this lot has closed.",nextMinimumBid:s,item:r};let u=rt(r,a,{bidderEmail:e.bidderEmail,bidderName:e.bidderName,amount:e.amount,maxAmount:e.maxAmount},o.increments);if(!u.accepted)return{...u,item:r};let c=u.buyNow?null:tt(r,i,o,t),d=u.leader&&!u.leader.isChallenger&&a&&a.bidder_email.toLowerCase()===e.bidderEmail.toLowerCase(),m=await ln.transaction(async(y)=>{if(d&&a)return await y.updateTable("bids").set({max_amount:u.leader.maxAmount}).where("id","=",a.id).execute(),{...a,max_amount:u.leader.maxAmount};let _=u.leader?.isChallenger===!0,w=Sf();if(await y.insertInto("bids").values({uuid:w,auction_id:r.auction_id,auction_item_id:r.id,bidder_name:e.bidderName,bidder_email:e.bidderEmail.toLowerCase(),amount:u.challengerAmount??e.amount,max_amount:e.maxAmount??null,status:_?"leading":"outbid",placed_at:Nt(t)}).execute(),a){if(_)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:Nt(t)}).where("id","=",r.id).execute();else if(c)await y.updateTable("auction_items").set({closes_at:Nt(c),extension_count:r.extension_count+1}).where("id","=",r.id).execute();return await y.selectFrom("bids").selectAll().where("uuid","=",w).executeTakeFirst()}),p={...u,bid:m,item:{...r,status:u.buyNow?"sold":r.status,closes_at:c?Nt(c):r.closes_at,extension_count:c?r.extension_count+1:r.extension_count},extendedTo:c??void 0};return await sn(p).catch(()=>{return}),p}var fn={};D(fn,{DEFAULT_INCREMENT_LADDER:()=>oe,determineWinner:()=>Be,effectiveCloseAt:()=>_e,extendedCloseAt:()=>tt,incrementFor:()=>Q,nextMinimumBid:()=>ae,resolveBid:()=>rt,settle:()=>ot});function Be(e,t){let r=t.filter((a)=>a.status!=="invalid");if(r.length===0)return{itemId:e.id,lotNumber:e.lot_number,title:e.title,status:"passed",amount:0,passedReason:"no_bids"};let o=[...r].sort((a,s)=>{if(s.amount!==a.amount)return s.amount-a.amount;return new Date(a.placed_at).getTime()-new Date(s.placed_at).getTime()})[0];if(e.reserve_price&&o.amount<e.reserve_price)return{itemId:e.id,lotNumber:e.lot_number,title:e.title,status:"passed",amount:o.amount,passedReason:"reserve_not_met"};return{itemId:e.id,lotNumber:e.lot_number,title:e.title,status:"sold",winningBidId:o.id,winnerName:o.bidder_name,winnerEmail:o.bidder_email,amount:o.amount}}function ot(e,t,r,n){let o=t.filter((m)=>m.status==="sold"),a=t.filter((m)=>m.status==="passed"),s=o.reduce((m,p)=>m+p.amount,0),i=r.filter((m)=>m.status==="confirmed").reduce((m,p)=>m+p.amount,0),u=new Map(e.map((m)=>[m.id,m.fair_market_value??null])),c=o.reduce((m,p)=>{let y=u.get(p.itemId);return y==null?m:m+(p.amount-y)},0),d=t.length;return{auctionId:n.auctionId,currency:n.currency,totalRaised:s+i,bidRevenue:s,pledgeRevenue:i,goalAmount:n.goalAmount??null,itemsSold:o.length,itemsPassed:a.length,sellThrough:d===0?0:o.length/d,valueDelta:c,outcomes:t}}var vn={};D(vn,{auctionTotals:()=>gn,closeAuction:()=>xn,closeDueItems:()=>_n,closeItem:()=>at,closingSoon:()=>Pn,fetchAuction:()=>ee,fetchAuctionForEvent:()=>wn,fetchCatalogue:()=>yn,fetchItems:()=>se,openAuction:()=>bn,settleAuction:()=>Rn});import{db as xe}from"@stacksjs/database/runtime";async function ee(e){return await xe.selectFrom("auctions").selectAll().where("id","=",e).executeTakeFirst()??null}async function wn(e){return await xe.selectFrom("auctions").selectAll().where("event_id","=",e).executeTakeFirst()??null}async function se(e){return await xe.selectFrom("auction_items").selectAll().where("auction_id","=",e).orderBy("lot_number","asc").execute()??[]}async function yn(e){let[t,r]=await Promise.all([ee(e),se(e)]),n=nt(t),o=await xe.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",e).where("status","in",["leading","won"]).execute(),a=await xe.selectFrom("bids").select(["auction_item_id"]).where("auction_id","=",e).where("status","!=","invalid").execute(),s=new Map((o??[]).map((u)=>[u.auction_item_id,u])),i=new Map;for(let u of a??[])i.set(u.auction_item_id,(i.get(u.auction_item_id)??0)+1);return r.map((u)=>{let c=s.get(u.id)??null;return{...u,currentBid:c?.amount??0,bidCount:i.get(u.id)??0,nextMinimumBid:ae(u,c?.amount??null,n.increments),leaderName:c?.bidder_name??null}})}async function gn(e){let t=await ee(e),r=await xe.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",e).where("status","!=","invalid").execute(),n=await xe.selectFrom("pledges").select(["amount"]).where("auction_id","=",e).where("status","=","confirmed").execute(),o=r??[],s=o.filter((c)=>c.status==="leading"||c.status==="won").reduce((c,d)=>c+d.amount,0),i=(n??[]).reduce((c,d)=>c+d.amount,0),u=await xe.selectFrom("auction_items").where("auction_id","=",e).count();return{currentBidTotal:s,pledgeTotal:i,raised:s+i,goalAmount:t?.goal_amount??null,bidCount:o.length,bidderCount:new Set(o.map((c)=>c.bidder_email.toLowerCase())).size,lotsOffered:Number(u??0),lotsWithBids:new Set(o.map((c)=>c.auction_item_id)).size}}import{db as Re}from"@stacksjs/database/runtime";function hn(e){return e.toISOString().slice(0,19).replace("T"," ")}async function bn(e,t=new Date){return await Re.updateTable("auctions").set({status:"open",opens_at:hn(t)}).where("id","=",e).execute(),await Re.updateTable("auction_items").set({status:"open"}).where("auction_id","=",e).where("status","=","closed").execute(),ee(e)}async function at(e,t=new Date){if(e.status==="sold"||e.status==="passed")return null;let r=await Re.selectFrom("bids").selectAll().where("auction_item_id","=",e.id).execute(),n=Be(e,r??[]);return await Re.transaction(async(o)=>{if(await o.updateTable("auction_items").set({status:n.status,closes_at:hn(t)}).where("id","=",e.id).execute(),n.winningBidId)await o.updateTable("bids").set({status:"won"}).where("id","=",n.winningBidId).execute();await o.updateTable("bids").set({status:"lost"}).where("auction_item_id","=",e.id).where("status","in",["leading","outbid"]).execute()}),await cn(e.auction_id,e.id,{status:n.status,amount:n.amount,winnerName:n.winnerName}).catch(()=>{return}),n}async function _n(e,t=new Date){let r=await ee(e);if(!r)return[];let n=await se(e),o=[];for(let a of n){if(a.status!=="open")continue;if(_e(a,r.closes_at)>t)continue;let s=await at(a,t);if(s)o.push(s)}return o}async function xn(e,t=new Date){let r=await se(e),n=[];for(let o of r){let a=await at(o,t);if(a)n.push(a)}return await Re.updateTable("auctions").set({status:"closed",closes_at:hn(t)}).where("id","=",e).execute(),n}async function Rn(e,t={}){let r=await ee(e);if(!r)return null;let n=await se(e),o=await Re.selectFrom("bids").selectAll().where("auction_id","=",e).execute(),a=await Re.selectFrom("pledges").selectAll().where("auction_id","=",e).execute(),s=new Map;for(let u of o??[]){let c=s.get(u.auction_item_id)??[];c.push(u),s.set(u.auction_item_id,c)}let i=n.map((u)=>{let c=Be(u,s.get(u.id)??[]);return u.status==="passed"?{...c,status:"passed"}:c});if(t.markSettled)await Re.updateTable("auctions").set({status:"settled"}).where("id","=",e).execute();return ot(n,i,a??[],{auctionId:e,currency:dn(r),goalAmount:r.goal_amount??null})}async function Pn(e,t,r=new Date){let n=await ee(e);if(!n)return[];let o=new Date(r.getTime()+t*60000);return(await se(e)).filter((a)=>{if(a.status!=="open")return!1;let s=_e(a,n.closes_at);return s>r&&s<=o})}function Dn(e,t="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:t,minimumFractionDigits:0}).format(e/100)}function Cf(e,t="USD"){if(!e.outbid||!e.item)return null;let r=e.item;return{to:{name:e.outbid.bidderName,email:e.outbid.bidderEmail},type:"outbid",subject:`You have been outbid on lot ${r.lot_number}: ${r.title}`,body:`Someone has bid higher on "${r.title}". The next bid is ${Dn(e.nextMinimumBid,t)}. Bidding closes ${new Date(r.closes_at??"").toLocaleString()}.`,data:{itemId:r.id,lotNumber:r.lot_number,title:r.title,nextMinimumBid:e.nextMinimumBid,closesAt:r.closes_at}}}function Ef(e,t="USD"){if(e.status!=="sold"||!e.winnerEmail)return null;return{to:{name:e.winnerName??"Bidder",email:e.winnerEmail},type:"winner",subject:`You won lot ${e.lotNumber}: ${e.title}`,body:`Congratulations - you won "${e.title}" at ${Dn(e.amount,t)}. The school will be in touch with payment and pickup details.`,data:{itemId:e.itemId,lotNumber:e.lotNumber,title:e.title,amount:e.amount}}}function Af(e,t,r,n="USD"){return{to:t,type:"closing_soon",subject:`Closing soon: lot ${e.lot_number}, ${e.title}`,body:`"${e.title}" closes at ${new Date(e.closes_at??"").toLocaleString()}. The current bid is ${Dn(r,n)}.`,data:{itemId:e.id,lotNumber:e.lot_number,title:e.title,currentBid:r,closesAt:e.closes_at}}}var Tn={};D(Tn,{fetchPledges:()=>Fn,makePledge:()=>Fa,pledgeLevels:()=>Ta,pledgeTotal:()=>kn});var{randomUUIDv7:Mf}=globalThis.Bun;import{db as $t}from"@stacksjs/database/runtime";async function Fa(e){let t=Mf();await $t.insertInto("pledges").values({uuid:t,auction_id:e.auctionId,donor_name:e.donorName,donor_email:e.donorEmail.toLowerCase(),amount:e.amount,level:e.level??null,status:e.status??"confirmed"}).execute();let r=await $t.selectFrom("pledges").selectAll().where("uuid","=",t).executeTakeFirst();return await un(r,await kn(e.auctionId)).catch(()=>{return}),r}async function kn(e){return(await $t.selectFrom("pledges").select(["amount"]).where("auction_id","=",e).where("status","=","confirmed").execute()??[]).reduce((r,n)=>r+n.amount,0)}async function Fn(e){return await $t.selectFrom("pledges").selectAll().where("auction_id","=",e).orderBy("amount","desc").execute()??[]}async function Ta(e){let t=(await Fn(e)).filter((n)=>n.status==="confirmed"),r=new Map;for(let n of t){let o=n.level??"other",a=r.get(o)??{amount:0,count:0};a.amount+=n.amount,a.count+=1,r.set(o,a)}return[...r.entries()].map(([n,o])=>({level:n,...o})).sort((n,o)=>o.amount-n.amount)}var Cn={};D(Cn,{bulkDestroy:()=>Ea,bulkStore:()=>Ja,bulkUpdate:()=>La,destroy:()=>Ca,fetchAll:()=>Ia,fetchById:()=>Ma,store:()=>Oa,update:()=>Wa});import{db as Sa}from"@stacksjs/database/runtime";import{mutationCount as f}from"@stacksjs/database/runtime";async function Ca(e){try{let t=await Sa.deleteFrom("carts").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete cart: ${t.message}`);throw t}}async function Ea(e){if(!e.length)return 0;try{let t=await Sa.deleteFrom("carts").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete carts: ${t.message}`);throw t}}import{db as Aa}from"@stacksjs/database/runtime";function If(e){return e.replace(/_([a-z0-9])/g,(t,r)=>r.toUpperCase())}function l(e){if(e===null||typeof e!=="object")return e;let t={...e};for(let[r,n]of Object.entries(t)){if(!r.includes("_"))continue;let o=If(r);if(!(o in t))t[o]=n}return t}function g(e){return e.map((t)=>l(t))}async function Ma(e){let t=await Aa.selectFrom("carts").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function Ia(){return g(await Aa.selectFrom("carts").selectAll().execute())}var{randomUUIDv7:Na}=globalThis.Bun;import{db as $a}from"@stacksjs/database/runtime";async function Oa(e){try{let t={...e,uuid:Na()},r=await $a.insertInto("carts").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create cart");return l(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create cart: ${t.message}`);throw t}}async function Ja(e){if(!e.length)return 0;let t=0;try{return await $a.transaction(async(r)=>{for(let n of e){let o={...n,uuid:Na()};await r.insertInto("carts").values(o).execute(),t++}}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create carts in bulk: ${r.message}`);throw r}}import{db as Ba,matchedRows as Nf}from"@stacksjs/database/runtime";import{formatDate as Ua}from"@stacksjs/orm";async function Wa(e,t){try{let r=await Ba.updateTable("carts").set({...t,updated_at:Ua(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update cart");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update cart: ${r.message}`);throw r}}async function La(e){if(!e.length)return 0;let t=0;try{return await Ba.transaction(async(r)=>{for(let n of e){if(!n.id)continue;if((await Nf(r.updateTable("carts").set({...n,updated_at:Ua(new Date)}).where("id","=",n.id))).length>0)t++}}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update carts in bulk: ${r.message}`);throw r}}var Es={};D(Es,{CATALOG_IMPORT_NAMESPACE:()=>Rs,CatalogFetchError:()=>S,PriceFormatError:()=>O,SHOPWARE_ACCESS_KEY_HELP:()=>$n,SKU_MAX:()=>Gn,UNKNOWN_COUNTRY:()=>ks,catalogAdapter:()=>sw,catalogAdapters:()=>Cs,catalogUuid:()=>ve,cleanName:()=>re,createDatabaseRepository:()=>Ss,createMemoryRepository:()=>ow,createReadOnlyRepository:()=>aw,currencyExponent:()=>W,decimalToMinor:()=>H,decodeHtmlEntities:()=>Ka,detectShopifyCurrency:()=>ts,detectShopwareCurrency:()=>cs,fetchJson:()=>Pe,formatMinor:()=>te,importCatalog:()=>nw,lowestPrice:()=>Hn,mapShopifyProduct:()=>es,mapShopwareProduct:()=>ss,mapWooProduct:()=>_s,minorToDecimal:()=>ue,missingAccessKeyMessage:()=>us,normalizeStoreUrl:()=>ie,numberToDecimalString:()=>Ha,numberToMinor:()=>Ot,optionalString:()=>R,productRow:()=>Vn,rescaleMinor:()=>Ue,shopifyAdapter:()=>In,shopwareAdapter:()=>Jn,shopwareBaseUrl:()=>is,shopwareProductCriteria:()=>ls,shopwareVariantCriteria:()=>ps,storeHost:()=>En,totalInventory:()=>Fs,uuidV5:()=>Ps,variantRow:()=>qn,variantSkus:()=>Ts,wooCommerceAdapter:()=>jn,wooPrices:()=>bs});import{slug as Za}from"@stacksjs/strings";class S extends Error{url;status;body;constructor(e,t,r,n){super(t);this.url=e;this.status=r;this.body=n;this.name="CatalogFetchError"}}var $f=2000,Of=30000;function ie(e){let t=e.trim();if(!t)throw TypeError("A store URL is required, e.g. https://shop.example.com");let r=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`https://${t}`,n;try{n=new URL(r)}catch{throw TypeError(`"${e}" is not a valid store URL`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw TypeError(`"${e}" must be an http(s) URL`);let o=n.pathname.replace(/\/+$/,"");return`${n.protocol}//${n.host.toLowerCase()}${o}`}function En(e){return new URL(e).host.toLowerCase()}async function Pe(e,t=fetch,r="",n={}){let o=r?` ${r}`:"",a={accept:"application/json",...n.headers};if(n.json!==void 0)a["content-type"]="application/json";let s;try{s=await t(e,{method:n.method??(n.json!==void 0?"POST":"GET"),headers:a,...n.json!==void 0?{body:JSON.stringify(n.json)}:{},signal:AbortSignal.timeout(Of)})}catch(u){let c=u instanceof Error?u.message:String(u);throw new S(e,`Could not reach ${e}: ${c}.${o}`)}if(!s.ok){let u=`${s.status}${s.statusText?` ${s.statusText}`:""}`,c=await s.text().catch(()=>"");throw new S(e,`${e} responded ${u}.${o}`,s.status,c?c.slice(0,$f):void 0)}let i=await s.text();try{return{data:JSON.parse(i),headers:s.headers}}catch{let u=s.headers.get("content-type")||"no content-type";throw new S(e,`${e} did not return JSON (${u}).${o}`,s.status)}}var qa={};D(qa,{PriceFormatError:()=>O,currencyExponent:()=>W,decimalToMinor:()=>H,formatCurrency:()=>ja,formatMinor:()=>te,minorToDecimal:()=>ue,minorToInput:()=>za,minorToMajor:()=>An,moneyInputError:()=>Mn,moneyInputStep:()=>Ga,parseMoneyInput:()=>Va,rescaleMinor:()=>Ue});class O extends Error{value;constructor(e,t){super(`Unreadable price ${JSON.stringify(e)}: ${t}`);this.value=e;this.name="PriceFormatError"}}function W(e){if(!e)return 2;try{let t=new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits;return typeof t==="number"?t:2}catch{return 2}}function H(e,t=2){if(e===null||e===void 0)return null;let r=String(e).trim();if(r==="")return null;let n=/^(\d*)(?:\.(\d*))?$/.exec(r);if(!n||!/\d/.test(r))throw new O(e,"expected a plain decimal such as 19.99");let o=n[1]||"0",a=n[2]??"",s;if(a.length<=t)s=BigInt(o+a.padEnd(t,"0"));else if(s=BigInt(o+a.slice(0,t)),a.charCodeAt(t)>=53)s+=1n;if(s>BigInt(Number.MAX_SAFE_INTEGER))throw new O(e,"too large to store exactly");return Number(s)}function ue(e,t=2){let r=String(e).trim();if(!/^\d+$/.test(r))throw new O(e,"expected a non-negative integer amount in minor units");if(t===0)return r.replace(/^0+(?=\d)/,"");let n=r.padStart(t+1,"0");return`${n.slice(0,-t).replace(/^0+(?=\d)/,"")}.${n.slice(-t)}`}function Ue(e,t,r){if(e===null||e===void 0||String(e).trim()==="")return null;if(!Number.isInteger(t)||t<0)throw new O(e,`invalid source precision ${t}`);return H(ue(String(e),t),r)}function te(e,t){let r=W(t),n=Math.round(Number(e)),o=Number.isSafeInteger(n)?`${n<0?"-":""}${ue(Math.abs(n),r)}`:String(e);return t?`${o} ${t}`:o}function An(e,t){let r=Math.round(Number(e??0));if(!Number.isFinite(r))return 0;let n=ue(Math.abs(r),W(t));return r<0?-Number(n):Number(n)}function ja(e,t,r){let n=(t||"USD").toUpperCase(),o=An(e,n);try{return new Intl.NumberFormat(r,{style:"currency",currency:n}).format(o)}catch{return te(Math.round(Number(e??0))||0,n)}}function za(e,t){if(e===null||e===void 0||e==="")return"";let r=Math.round(Number(e));if(!Number.isFinite(r))return"";let n=ue(Math.abs(r),W(t));return r<0?`-${n}`:n}function Ga(e){let t=W(e);return t===0?"1":`0.${"1".padStart(t,"0")}`}function Mn(e,t,r={}){let n=e===null||e===void 0?"":String(e).trim(),o=W(t),a=(t||"USD").toUpperCase();if(n==="")return r.required===!1?"":"Enter an amount.";let s=/^(\d*)(?:\.(\d*))?$/.exec(n);if(!s||!/\d/.test(n))return o===0?"Enter a whole number, for example 1999.":`Enter a plain amount, for example ${ue(1999,o)}.`;if((s[2]??"").length>o)return o===0?`${a} amounts have no decimal places.`:`${a} amounts have at most ${o} decimal ${o===1?"place":"places"}.`;let u;try{u=H(n,o)}catch{return"That amount is too large."}if(u===null)return"Enter an amount.";if(r.min!==void 0&&u<r.min)return`Enter at least ${te(r.min,a)}.`;if(r.max!==void 0&&u>r.max)return`Enter at most ${te(r.max,a)}.`;return""}function Va(e,t,r={}){let n=Mn(e,t,r);if(n)throw new O(e,n);return H(e,W(t))}function Ha(e){if(typeof e!=="number"||!Number.isFinite(e))throw new O(e,"expected a finite number");if(e<0)throw new O(e,"expected an amount of zero or more");let t=String(e),r=/^(\d+)(?:\.(\d+))?e([+-]\d+)$/.exec(t);if(!r)return t;let[,n,o="",a]=r,s=`${n}${o}`,i=n.length+Number(a);if(i<=0)return`0.${"0".repeat(-i)}${s}`;if(i>=s.length)return`${s}${"0".repeat(i-s.length)}`;return`${s.slice(0,i)}.${s.slice(i)}`}function Ot(e,t=2){if(e===null||e===void 0)return null;if(typeof e==="string")return H(e,t);return H(Ha(e),t)}var Jf={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",ndash:"\u2013",mdash:"\u2014",hellip:"\u2026",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",laquo:"\xAB",raquo:"\xBB",trade:"\u2122",reg:"\xAE",copy:"\xA9",deg:"\xB0",times:"\xD7",frac12:"\xBD",euro:"\u20AC",pound:"\xA3",yen:"\xA5",cent:"\xA2"};function Ka(e){return e.replace(/&(#x[0-9a-f]+|#\d+|[a-z][a-z0-9]*);/gi,(t,r)=>{if(r[0]==="#"){let n=r[1]==="x"||r[1]==="X"?Number.parseInt(r.slice(2),16):Number.parseInt(r.slice(1),10);return Number.isInteger(n)&&n>0&&n<=1114111?String.fromCodePoint(n):t}return Jf[r.toLowerCase()]??t})}function re(e){if(typeof e!=="string")return"";return Ka(e).replace(/\s+/g," ").trim()}function R(e){if(typeof e!=="string")return null;let t=e.trim();return t===""?null:t}var Qa=250,Ya=400;function Bf(e){if(!e||e.length===0)return!0;if(e.length!==1)return!1;let[t]=e;return t?.name==="Title"&&(t.values?.length??0)<=1&&(t.values?.[0]??"Default Title")==="Default Title"}function Uf(e){return(Array.isArray(e)?e:typeof e==="string"?e.split(","):[]).map((r)=>String(r).trim()).filter(Boolean)}function Xa(e,t,r,n,o){try{return H(e,t)}catch(a){if(!(a instanceof O))throw a;return o.push({externalId:n,message:`${r}: ${a.message}; left unpriced`}),null}}function es(e,t){if(e?.id===void 0||e.id===null||e.id==="")throw TypeError("Shopify product has no id");let r=String(e.id),n=[],o=(R(e.title)??"").replace(/\s+/g," ");if(!o)throw TypeError(`Shopify product ${r} has no title`);let a=R(e.handle)??Za(o),s=W(t.currency),i=!Bf(e.options),u=i?(e.options??[]).map((p)=>R(p.name)??"").filter(Boolean):[],c=(e.variants??[]).map((p)=>{let y=String(p.id),_=Xa(p.compare_at_price,s,`variant ${y} compare-at price`,r,n);return{externalId:y,title:R(p.title)??o,sku:R(p.sku),priceMinor:Xa(p.price,s,`variant ${y} price`,r,n),compareAtMinor:_?_:null,available:p.available!==!1,inventory:typeof p.inventory_quantity==="number"?Math.max(0,Math.trunc(p.inventory_quantity)):null,optionValues:i?[p.option1,p.option2,p.option3].slice(0,u.length).map((w)=>R(w)??""):[]}});if(c.length===0)n.push({externalId:r,message:`"${o}" has no variants; imported without a price`});let d=[...e.images??[]].filter((p)=>R(p?.src)).sort((p,y)=>(p.position??0)-(y.position??0)).map((p)=>({src:R(p.src),alt:R(p.alt)})),m=R(e.product_type);return{product:{source:"shopify",externalId:r,name:o,handle:a,descriptionHtml:R(e.body_html),vendor:R(e.vendor),categories:m?[{name:m,slug:Za(m)}]:[],tags:Uf(e.tags),currency:t.currency,images:d,optionNames:u,variants:c,hasOptions:i,url:`${t.storeUrl}/products/${a}`},warnings:n}}async function ts(e,t=fetch){try{let{data:r}=await Pe(`${e}/meta.json`,t),n=typeof r?.currency==="string"?r.currency.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(n)?n:null}catch{return null}}async function*Wf(e,t={}){let r=ie(e),n=t.fetch??fetch,o=t.limit,a=o&&o>0?Math.min(Qa,o):Qa,s=[],i=t.currency?.toUpperCase()??null;if(!i){if(i=await ts(r,n),!i)s.push({message:`${r}/meta.json did not report a currency; prices read as 2-decimal amounts. Pass --currency to be sure.`})}let u=new Set,c=0;for(let d=1;d<=Ya;d++){let m=`${r}/products.json?limit=${a}&page=${d}`,{data:p}=await Pe(m,n,"Is this a Shopify storefront, and is it public (no storefront password)?");if(!Array.isArray(p?.products))throw new S(m,`${m} did not return a "products" list. Is this a Shopify storefront?`);let y=p.products;if(y.length===0)return;let _=y.map((h)=>String(h?.id));if(d>1&&_.every((h)=>u.has(h)))throw new S(m,`${m} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);_.forEach((h)=>u.add(h));let w=[],b=d===1?s:[];for(let h of y){if(o&&c>=o)break;try{let x=es(h,{storeUrl:r,currency:i});w.push(x.product),b.push(...x.warnings),c++}catch(x){b.push({externalId:h?.id===void 0?void 0:String(h.id),message:`skipped: ${x.message}`})}}if(yield{url:m,products:w,warnings:b},o&&c>=o)return}throw new S(r,`Stopped after ${Ya} pages of ${r}/products.json without reaching the end.`)}var In={name:"shopify",pages:Wf};import{slug as as}from"@stacksjs/strings";var Jt=100,Bt=1000,Ut="/store-api",Nn="Is this a Shopware 6 store with the Store API reachable at /store-api?",$n='Find it in the Shopware Administration under Sales Channels: open the storefront or headless sales channel and copy the key from its "API access" card. A headless storefront also ships it in its page source.';function Wt(e,t){if(!e)return null;let r=e,n=r.translated;return(n&&typeof n==="object"&&!Array.isArray(n)?R(n[t]):null)??R(r[t])}function Se(e){return Wt(e,"name")?.replace(/\s+/g," ")??null}function rs(e){let t=typeof e.availableStock==="number"?e.availableStock:e.stock;return typeof t==="number"&&Number.isFinite(t)?Math.max(0,Math.trunc(t)):null}function ns(e){return e.available!==!1&&e.active!==!1}function os(e,t,r,n,o){let a=W(n.currency),s=e.calculatedPrice?.unitPrice;if(s===null||s===void 0||s==="")return o.push({externalId:r,message:`${t} has no price in ${n.currency??"the sales channel currency"}; left unpriced`}),{priceMinor:null,compareAtMinor:null};try{let i=Ot(s,a),u=Ot(e.calculatedPrice?.listPrice?.price??null,a);return{priceMinor:i,compareAtMinor:u!==null&&i!==null&&u>i?u:null}}catch(i){if(!(i instanceof O))throw i;return o.push({externalId:r,message:`${t}: ${i.message}; left unpriced`}),{priceMinor:null,compareAtMinor:null}}}function Lf(e){let t=[...e.media??[]].sort((o,a)=>(o?.position??0)-(a?.position??0));if(e.cover)t.unshift(e.cover);let r=new Set,n=[];for(let o of t){let a=R(o?.media?.url);if(!a||r.has(a))continue;r.add(a);let s=o.media;n.push({src:a,alt:Wt(s,"alt")??Wt(s,"title")})}return n}function jf(e){let t=new Set,r=[];for(let n of[e.seoCategory,...e.categories??[]]){let o=Se(n),a=o?as(o):"";if(!o||!a||t.has(a))continue;t.add(a),r.push({name:o,slug:a})}return r}function zf(e){let t=new Map;for(let r of e)for(let n of r.options??[]){let o=Se(n.group),a=R(n.groupId)??R(n.group?.id)??o;if(!a||!o||t.has(a))continue;t.set(a,{key:a,name:o,position:n.group?.position??0,order:t.size})}return[...t.values()].sort((r,n)=>r.position-n.position||r.order-n.order)}function Gf(e,t){return(e.options??[]).find((r)=>(R(r.groupId)??R(r.group?.id)??Se(r.group))===t.key)}function ss(e,t){if(!R(e?.id))throw TypeError("Shopware product has no id");let r=e.id,n=[],o=Se(e);if(!o)throw TypeError(`Shopware product ${r} has no name`);let a=t.children??[],s=typeof e.childCount==="number"?e.childCount:0,i=a.length>0,u,c=[];if(i){let d=zf(a);c=d.map((p)=>p.name);let m=a.map((p)=>{let y=d.map((v)=>Gf(p,v)),_=y.map((v)=>Se(v)??""),w=R(p.productNumber),b=`variant ${w??p.id}`,h=os(p,b,r,t,n);return{variant:{externalId:String(p.id),title:_.filter(Boolean).join(" / ")||Se(p)||w||o,sku:w,priceMinor:h.priceMinor,compareAtMinor:h.compareAtMinor,available:ns(p),inventory:rs(p),optionValues:_},sortKey:y.map((v)=>v?.position??0),productNumber:w??""}});m.sort((p,y)=>{for(let _=0;_<p.sortKey.length;_++){let w=(p.sortKey[_]??0)-(y.sortKey[_]??0);if(w!==0)return w}return p.productNumber.localeCompare(y.productNumber)}),u=m.map((p)=>p.variant)}else if(s>0)n.push({externalId:r,message:`"${o}" has ${s} variant${s===1?"":"s"} in Shopware, none visible to this sales channel; imported without a price`}),u=[];else{let d=os(e,`"${o}"`,r,t,n);u=[{externalId:r,title:o,sku:R(e.productNumber),priceMinor:d.priceMinor,compareAtMinor:d.compareAtMinor,available:ns(e),inventory:rs(e),optionValues:[]}]}return{product:{source:"shopware",externalId:r,name:o,handle:as(o),descriptionHtml:Wt(e,"description"),vendor:Se(e.manufacturer),categories:jf(e),tags:(e.tags??[]).map((d)=>R(d?.name)).filter((d)=>d!==null),currency:t.currency,images:Lf(e),optionNames:c,variants:u,hasOptions:i,url:`${t.storeUrl}/detail/${r}`},warnings:n}}function is(e){return ie(e).replace(/\/store-api$/i,"")}function us(){return`Shopware's Store API needs the sales channel access key: pass --access-key <key> or set SHOPWARE_ACCESS_KEY. It is public by design and not a secret. ${$n}`}function Vf(e){if(!e)return null;try{let r=JSON.parse(e)?.errors?.[0];return R(r?.detail)??R(r?.title)}catch{return null}}function qf(e){let t=Vf(e.body),r=t?` Shopware said: "${t}"`:"";if(e.status===401||e.status===403||e.status===412)return new S(e.url,`${e.message}${r} The sales channel access key looks wrong: check --access-key or SHOPWARE_ACCESS_KEY. ${$n}`,e.status,e.body);return new S(e.url,`${e.message}${r} ${Nn}`,e.status,e.body)}async function On(e,t,r,n){try{let{data:o}=await Pe(e,r,"",{headers:{"sw-access-key":t},json:n});return o}catch(o){if(!(o instanceof S))throw o;throw qf(o)}}function Hf(e){return e instanceof S&&(e.status===401||e.status===403||e.status===412)}async function cs(e,t,r=fetch){try{let n=await On(`${e}${Ut}/context`,t,r),o=typeof n?.currency?.isoCode==="string"?n.currency.isoCode.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(o)?o:null}catch(n){if(Hf(n))throw n;return null}}var ds={product:["id","parentId","productNumber","name","description","translated","calculatedPrice","stock","availableStock","available","active","childCount","manufacturer","seoCategory","categories","tags","cover","media","options"],calculated_price:["unitPrice","quantity","listPrice"],cart_list_price:["price"],product_media:["position","media"],media:["url","alt","title","translated"],product_manufacturer:["name","translated"],category:["name","translated"],tag:["name"],property_group_option:["id","name","translated","position","groupId","group"],property_group:["id","name","translated","position"]};function ls(e,t){return{page:e,limit:t,"total-count-mode":"exact",filter:[{type:"equals",field:"parentId",value:null}],sort:[{field:"id",order:"ASC"}],associations:{cover:{},media:{associations:{media:{}}},manufacturer:{},categories:{},tags:{}},includes:ds}}function ps(e,t){return{page:t,limit:Jt,"total-count-mode":"exact",filter:[{type:"equalsAny",field:"parentId",value:e}],sort:[{field:"id",order:"ASC"}],associations:{options:{associations:{group:{}}}},includes:ds}}function ms(e,t,r,n){if(n<r)return!0;let o=typeof e.total==="number"?e.total:Number.NaN;return Number.isInteger(o)&&t*r>=o}async function Kf(e,t,r,n){let o=new Map;if(r.length===0)return o;let a=`${e}${Ut}/product`;for(let s=1;s<=Bt;s++){let i=await On(a,t,n,ps(r,s));if(!Array.isArray(i?.elements))throw new S(a,`${a} did not return a product list for the variants. ${Nn}`);let u=i.elements;for(let c of u){let d=R(c?.parentId);if(!d)continue;let m=o.get(d)??[];m.push(c),o.set(d,m)}if(u.length===0||ms(i,s,Jt,u.length))return o}throw new S(a,`Stopped after ${Bt} pages of variants from ${a} without reaching the end.`)}async function*Zf(e,t={}){let r=t.accessKey?.trim();if(!r)throw TypeError(us());let n=is(e),o=t.fetch??fetch,a=t.limit,s=a&&a>0?Math.min(Jt,a):Jt,i=`${n}${Ut}/product`,u=[],c=t.currency?.trim().toUpperCase()||null,d=await cs(n,r,o),m=d??c;if(d&&c&&d!==c)u.push({message:`--currency ${c} ignored: this sales channel prices in ${d}, and the Store API does not convert.`});if(!m)u.push({message:`${n}${Ut}/context did not report a currency; prices read as 2-decimal amounts. Pass --currency to be sure.`});let p=new Set,y=0;for(let _=1;_<=Bt;_++){let w=`${i} (page ${_})`,b;try{b=await On(i,r,o,ls(_,s))}catch(k){if(k instanceof S)throw new S(k.url,k.message.replace(k.url,w),k.status,k.body);throw k}if(!Array.isArray(b?.elements))throw new S(i,`${w} did not return a product list. ${Nn}`);let h=b.elements;if(h.length===0)return;let x=h.map((k)=>String(k?.id));if(_>1&&x.every((k)=>p.has(k)))throw new S(i,`${w} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);x.forEach((k)=>p.add(k));let v=a?h.slice(0,Math.max(0,a-y)):h,A=_===1?u:[],I=v.filter((k)=>typeof k?.childCount==="number"&&k.childCount>0).map((k)=>String(k.id)),be=await Kf(n,r,I,o),G=[];for(let k of v)try{let Te=ss(k,{storeUrl:n,currency:m,children:be.get(String(k?.id))});G.push(Te.product),A.push(...Te.warnings),y++}catch(Te){A.push({externalId:k?.id===void 0?void 0:String(k.id),message:`skipped: ${Te.message}`})}if(yield{url:w,products:G,warnings:A},a&&y>=a)return;if(ms(b,_,s,h.length))return}throw new S(i,`Stopped after ${Bt} pages of ${i} without reaching the end.`)}var Jn={name:"shopware",pages:Zf};import{slug as hs}from"@stacksjs/strings";var Un=100,Wn=1000,Ln="/wp-json/wc/store/v1/products",fs="Is WooCommerce 6+ installed with the Store API reachable at /wp-json?";function bs(e){let t=R(e?.currency_code)?.toUpperCase()??null,r=Number(e?.currency_minor_unit),n=Number.isInteger(r)&&r>=0?r:2,o=W(t),a=Ue(e?.price,n,o),s=Ue(e?.regular_price,n,o);return{currency:t,priceMinor:a,compareAtMinor:s!==null&&a!==null&&s>a?s:null}}function ws(e,t,r){try{return bs(e.prices)}catch(n){if(!(n instanceof O))throw n;return r.push({externalId:t,message:`${n.message}; left unpriced`}),{currency:R(e.prices?.currency_code)?.toUpperCase()??null,priceMinor:null,compareAtMinor:null}}}function Bn(e){return(e??[]).map((t)=>{let r=re(t?.name);return{name:r,slug:R(t?.slug)??hs(r)}}).filter((t)=>t.name&&t.slug)}function ys(e){return typeof e.low_stock_remaining==="number"?Math.max(0,Math.trunc(e.low_stock_remaining)):null}function gs(e){return e.is_in_stock!==!1&&e.is_purchasable!==!1}function _s(e,t={}){if(e?.id===void 0||e.id===null||e.id==="")throw TypeError("WooCommerce product has no id");let r=String(e.id),n=[],o=re(e.name);if(!o)throw TypeError(`WooCommerce product ${r} has no name`);let a=ws(e,r,n),s=e.type==="variable"&&(e.variations?.length??0)>0,i=s?(e.attributes??[]).filter((p)=>p.has_variations!==!1):[],u=i.map((p)=>re(p.name)).filter(Boolean),c,d=a.currency;if(s)c=(e.variations??[]).map((p)=>{let y=String(p.id),_=i.map((h)=>{let x=re(h.name).toLowerCase(),v=(h.taxonomy??"").toLowerCase(),A=(p.attributes??[]).find((G)=>{let k=re(G.name).toLowerCase();return k===x||v!==""&&k===v}),I=R(A?.value);if(!I)return"Any";let be=(h.terms??[]).find((G)=>G.slug===I);return be?re(be.name):re(I)}),w=t.variations?.get(y);if(!w)return n.push({externalId:r,message:`variation ${y} could not be fetched; imported without a price`}),{externalId:y,title:_.join(" / ")||o,sku:null,priceMinor:null,compareAtMinor:null,available:!1,inventory:null,optionValues:_};let b=ws(w,y,n);return d??=b.currency,{externalId:y,title:_.join(" / ")||re(w.name)||o,sku:R(w.sku),priceMinor:b.priceMinor,compareAtMinor:b.compareAtMinor,available:gs(w),inventory:ys(w),optionValues:_}});else c=[{externalId:r,title:o,sku:R(e.sku),priceMinor:a.priceMinor,compareAtMinor:a.compareAtMinor,available:gs(e),inventory:ys(e),optionValues:[]}];let m=Bn(e.brands)[0];return{product:{source:"woocommerce",externalId:r,name:o,handle:R(e.slug)??hs(o),descriptionHtml:R(e.description)??R(e.short_description),vendor:m?m.name:null,categories:Bn(e.categories),tags:Bn(e.tags).map((p)=>p.name),currency:d,images:(e.images??[]).filter((p)=>R(p?.src)).map((p)=>({src:R(p.src),alt:R(p.alt)})),optionNames:s?u:[],variants:c,hasOptions:s,url:R(e.permalink)},warnings:n}}async function xs(e,t){let{data:r,headers:n}=await Pe(e,t,fs);if(!Array.isArray(r))throw new S(e,`${e} did not return a product list. ${fs}`);let o=n.get("x-wp-totalpages")?.trim(),a=o?Number(o):Number.NaN;return{url:e,items:r,totalPages:Number.isInteger(a)&&a>=0?a:null}}async function Qf(e,t,r){let n=new Map;if(t.length===0)return n;for(let o=1;o<=Wn;o++){let a=`${e}${Ln}?type=variation&parent=${t.join(",")}&per_page=${Un}&page=${o}`,s=await xs(a,r);for(let i of s.items)n.set(String(i.id),i);if(s.items.length===0||s.totalPages!==null&&o>=s.totalPages)break}return n}async function*Yf(e,t={}){let r=ie(e),n=t.fetch??fetch,o=t.limit,a=o&&o>0?Math.min(Un,o):Un,s=new Set,i=0;for(let u=1;u<=Wn;u++){let c=`${r}${Ln}?per_page=${a}&page=${u}`,d=await xs(c,n);if(d.items.length===0)return;let m=d.items.map((h)=>String(h?.id));if(u>1&&m.every((h)=>s.has(h)))throw new S(c,`${c} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);m.forEach((h)=>s.add(h));let p=o?d.items.slice(0,Math.max(0,o-i)):d.items,y=[],_=p.filter((h)=>h?.type==="variable"&&(h.variations?.length??0)>0).map((h)=>String(h.id)),w=new Map;try{w=await Qf(r,_,n)}catch(h){if(!(h instanceof S))throw h;y.push({message:`variations could not be fetched (${h.message}); variable products are imported without variant prices`})}let b=[];for(let h of p)try{let x=_s(h,{variations:w});b.push(x.product),y.push(...x.warnings),i++}catch(x){y.push({externalId:h?.id===void 0?void 0:String(h.id),message:`skipped: ${x.message}`})}if(yield{url:c,products:b,warnings:y},o&&i>=o)return;if(d.totalPages!==null&&u>=d.totalPages)return}throw new S(r,`Stopped after ${Wn} pages of ${r}${Ln} without reaching the end.`)}var jn={name:"woocommerce",pages:Yf};import{createHash as Xf}from"crypto";var Rs="5d0c8a3e-6f1b-4c2a-9e47-b18f3d2a6c90";function Ps(e,t=Rs){let r=t.replace(/-/g,"");if(!/^[0-9a-f]{32}$/i.test(r))throw TypeError(`Invalid namespace UUID "${t}"`);let n=Xf("sha1").update(Buffer.from(r,"hex")).update(e,"utf8").digest().subarray(0,16);n[6]=n[6]&15|80,n[8]=n[8]&63|128;let o=n.toString("hex");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function ve(e,t,r,n){return Ps(`${e}:${t.toLowerCase()}:${r}:${n}`)}var{randomUUIDv7:vs}=globalThis.Bun;import{db as zn}from"@stacksjs/database/runtime";import{formatDate as ew}from"@stacksjs/orm";var ks="Unknown",tw=1,rw=50,Gn=100;function Hn(e){let t=e.map((r)=>r.priceMinor).filter((r)=>r!==null);return t.length>0?Math.min(...t):null}function Fs(e){if(e.length===0||e.some((t)=>t.inventory===null))return null;return e.reduce((t,r)=>t+(r.inventory??0),0)}function Ts(e){let t=new Map,r=[],n=new Set;for(let o of e.variants){let a=o.sku;if(a===null)t.set(o.externalId,null);else if(a.length>Gn)t.set(o.externalId,null),r.push({externalId:e.externalId,message:`"${e.name}" variant "${o.title}" has a SKU longer than ${Gn} characters; imported without it`});else if(n.has(a))t.set(o.externalId,null),r.push({externalId:e.externalId,message:`"${e.name}" variant "${o.title}" repeats SKU ${a}; imported without it`});else n.add(a),t.set(o.externalId,a)}return{skus:t,warnings:r}}function Vn(e,t,r,n,o){let a=Fs(e.variants),s={uuid:ve(e.source,t,"product",e.externalId),name:e.name,description:e.descriptionHtml,price:Hn(e.variants)??0,image_url:e.images[0]?.src??null,is_available:e.variants.some((i)=>i.available),updated_at:n};if(o==="create")s.inventory_count=a??0,s.preparation_time=tw,s.category_id=r.categoryId,s.manufacturer_id=r.manufacturerId,s.created_at=n;else{if(a!==null)s.inventory_count=a;if(r.categoryId!==null)s.category_id=r.categoryId;if(r.manufacturerId!==null)s.manufacturer_id=r.manufacturerId}return s}function qn(e,t,r,n,o,a,s=t.sku){let i={uuid:ve(e.source,r,"variant",t.externalId),product_id:n,variant:t.title,type:(e.optionNames.join(" / ")||"Option").slice(0,rw),options:JSON.stringify(t.optionValues),status:t.available?"active":"inactive",price:t.priceMinor,compare_at_price:t.compareAtMinor,updated_at:o};if(a==="create")i.sku=s,i.inventory_count=t.inventory,i.created_at=o;else{if(s!==null)i.sku=s;if(t.inventory!==null)i.inventory_count=t.inventory}return i}function Ds(e){let t={...e};return delete t.uuid,t}async function nw(e){let t=ie(e.storeUrl),r=En(t),n=e.now??(()=>new Date),{adapter:o,repository:a}=e,s={source:o.name,storeUrl:t,dryRun:e.dryRun===!0,pages:[],products:[],counts:{products:{created:0,updated:0},variants:{created:0,updated:0},categories:{created:0,updated:0},manufacturers:{created:0,updated:0},duplicates:0},currencies:[],warnings:[]},i=new Map,u=new Map,c=new Map,d=new Set;async function m(w,b,h){let x=w.categories[0];if(!x)return null;let v=i.get(x.slug);if(v!==void 0)return v;let A=await b.findCategory(x.slug,x.name);if(A===void 0)A=await b.createCategory({uuid:vs(),name:x.name,slug:x.slug,description:null,image_url:null,is_active:!0,parent_category_id:null,display_order:i.size,created_at:h,updated_at:h}),s.counts.categories.created++;return i.set(x.slug,A),A}async function p(w,b,h){if(!w.vendor)return null;let x=u.get(w.vendor);if(x!==void 0)return x;let v=await b.findManufacturer(w.vendor);if(v===void 0)v=await b.createManufacturer({uuid:vs(),manufacturer:w.vendor,description:null,country:ks,featured:!1,created_at:h,updated_at:h}),s.counts.manufacturers.created++;return u.set(w.vendor,v),v}async function y(w){let b=w.map((x)=>ve(x.source,r,"product",x.externalId)),h=w.filter((x)=>x.hasOptions).flatMap((x)=>x.variants.map((v)=>ve(x.source,r,"variant",v.externalId)));return{products:b.length>0?await a.findProducts(b):new Map,variants:h.length>0?await a.findVariants(h):new Map}}async function _(w,b,h){let x=ew(n()),v={categoryId:await m(w,b,x),manufacturerId:await p(w,b,x)},A=ve(w.source,r,"product",w.externalId),I=h.products.get(A),be=I===void 0?"create":"update",G;if(I===void 0)G=await b.createProduct(Vn(w,r,v,x,"create"));else G=I,await b.updateProduct(G,Ds(Vn(w,r,v,x,"update")));let k={create:0,update:0};if(w.hasOptions){let{skus:Te,warnings:Pf}=Ts(w);s.warnings.push(...Pf);let Ra=[...Te.values()].filter((Je)=>Je!==null);if(I!==void 0&&Ra.length>0)await b.releaseVariantSkus(G,Ra);for(let Je of w.variants){let Pa=Te.get(Je.externalId)??null,va=h.variants.get(ve(w.source,r,"variant",Je.externalId));if(va===void 0)await b.createVariant(qn(w,Je,r,G,x,"create",Pa)),k.create++;else await b.updateVariant(va,Ds(qn(w,Je,r,G,x,"update",Pa))),k.update++}}return{action:be,externalId:w.externalId,name:w.name,handle:w.handle,priceMinor:Hn(w.variants),currency:w.currency,variants:k,category:w.categories[0]?.name??null,vendor:w.vendor,imageCount:w.images.length}}for await(let w of o.pages(t,{limit:e.limit,fetch:e.fetch,currency:e.currency,accessKey:e.accessKey})){s.pages.push(w.url),s.warnings.push(...w.warnings);let b=[];for(let x of w.products){if(c.get(x.externalId)!==void 0){s.counts.duplicates++,s.warnings.push({externalId:x.externalId,message:`"${x.name}" appeared twice; imported once`});continue}c.set(x.externalId,x.handle),b.push(x)}let h=await y(b);for(let x of b){if(x.currency)d.add(x.currency);let v=a.transaction?await a.transaction((A)=>_(x,A,h)):await _(x,a,h);s.counts.products[v.action==="create"?"created":"updated"]++,s.counts.variants.created+=v.variants.create,s.counts.variants.updated+=v.variants.update,s.products.push(v),e.onProduct?.(v)}}if(s.currencies=[...d].sort(),s.currencies.length>1)s.warnings.push({message:`prices arrived in more than one currency (${s.currencies.join(", ")}); products.price has no currency column`});return s}function Ss(e=zn){async function t(a,s){let i=await e.selectFrom(a).where("uuid","=",s).select("id").executeTakeFirst();if(!i)throw Error(`Inserted a row into ${a} but could not read it back (uuid ${s})`);return Number(i.id)}async function r(a,s){let i=new Map;for(let u=0;u<s.length;u+=500){let c=await e.selectFrom(a).where("uuid","in",s.slice(u,u+500)).select(["id","uuid"]).execute();for(let d of c)i.set(d.uuid,Number(d.id))}return i}async function n(a){let s=await a.select("id").executeTakeFirst();return s?Number(s.id):void 0}let o={async findCategory(a,s){return await n(e.selectFrom("categories").where("slug","=",a))??await n(e.selectFrom("categories").where("name","=",s))},async createCategory(a){return await e.insertInto("categories").values(a).execute(),t("categories",a.uuid)},async findManufacturer(a){return n(e.selectFrom("manufacturers").where("manufacturer","=",a))},async createManufacturer(a){return await e.insertInto("manufacturers").values(a).execute(),t("manufacturers",a.uuid)},async findProducts(a){return r("products",a)},async createProduct(a){return await e.insertInto("products").values(a).execute(),t("products",a.uuid)},async updateProduct(a,s){await e.updateTable("products").set(s).where("id","=",a).execute()},async findVariants(a){return r("product_variants",a)},async createVariant(a){return await e.insertInto("product_variants").values(a).execute(),t("product_variants",a.uuid)},async updateVariant(a,s){await e.updateTable("product_variants").set(s).where("id","=",a).execute()},async releaseVariantSkus(a,s){for(let i=0;i<s.length;i+=500)await e.updateTable("product_variants").set({sku:null}).where("product_id","=",a).where("sku","in",s.slice(i,i+500)).execute()}};if(e===zn)o.transaction=(a)=>zn.transaction((s)=>a(Ss(s)));return o}function ow(){let e={categories:[],manufacturers:[],products:[],product_variants:[]};function t(a,s){let i=e[a].length+1;return e[a].push({id:i,...s}),i}function r(a,s,i){let u=e[a].find((c)=>c.id===s);if(u)Object.assign(u,i)}let n=(a,s)=>new Map(e[a].filter((i)=>s.includes(i.uuid)).map((i)=>[i.uuid,i.id])),o=(a,s)=>e[a].find(s)?.id;return{tables:e,findCategory:async(a,s)=>o("categories",(i)=>i.slug===a)??o("categories",(i)=>i.name===s),createCategory:async(a)=>t("categories",a),findManufacturer:async(a)=>o("manufacturers",(s)=>s.manufacturer===a),createManufacturer:async(a)=>t("manufacturers",a),findProducts:async(a)=>n("products",a),createProduct:async(a)=>t("products",a),updateProduct:async(a,s)=>r("products",a,s),findVariants:async(a)=>n("product_variants",a),createVariant:async(a)=>t("product_variants",a),updateVariant:async(a,s)=>r("product_variants",a,s),releaseVariantSkus:async(a,s)=>{for(let i of e.product_variants)if(i.product_id===a&&s.includes(i.sku))i.sku=null}}}function aw(e){let t=-1,r=async()=>t--;return{findCategory:e.findCategory,findManufacturer:e.findManufacturer,findProducts:e.findProducts,findVariants:e.findVariants,createCategory:r,createManufacturer:r,createProduct:r,createVariant:r,updateProduct:async()=>{},updateVariant:async()=>{},releaseVariantSkus:async()=>{}}}var Cs={shopify:In,woocommerce:jn,shopware:Jn};function sw(e){return Cs[e.trim().toLowerCase()]}var Zn={};D(Zn,{deleteCoupon:()=>As,deleteCoupons:()=>Ms,deleteExpiredCoupons:()=>Is,fetchActive:()=>Bs,fetchAll:()=>Os,fetchByCode:()=>Js,fetchById:()=>Ce,fetchConversionRate:()=>Vs,fetchCouponCounts:()=>Ws,fetchCouponCountsByType:()=>Ls,fetchRedemptionStats:()=>js,fetchRedemptionTrend:()=>Gs,fetchStats:()=>Us,fetchTopRedeemedCoupons:()=>zs,getActiveCouponsMoMChange:()=>qs,redeem:()=>ti,store:()=>Zs,update:()=>ei});import{db as Kn}from"@stacksjs/database/runtime";import{formatDate as iw}from"@stacksjs/orm";async function As(e){let t=await Kn.deleteFrom("coupons").where("id","=",e).executeTakeFirst();return f(t)>0}async function Ms(e){if(!e.length)return 0;return await Kn.deleteFrom("coupons").where("id","in",e).execute()||0}async function Is(){let e=iw(new Date),t=await Kn.deleteFrom("coupons").where("end_date","<",e).executeTakeFirst();return f(t)}import{db as P}from"@stacksjs/database/runtime";import{extractDate as Ns,formatDate as $s}from"@stacksjs/orm";import{camelCase as uw}from"@stacksjs/strings";function jt(e){let t=Object.fromEntries(Object.entries(e).map(([r,n])=>[uw(r),n]));if(t.endDate)t.endDate=Ns(new Date(t.endDate));if(t.startDate)t.startDate=Ns(new Date(t.startDate));if(t.isActive!==void 0)t.isActive=Boolean(t.isActive);return t}async function Os(){let e=await P.selectFrom("coupons").selectAll().execute();return g(e).map(jt)}async function Ce(e){let t=await P.selectFrom("coupons").where("id","=",e).selectAll().executeTakeFirst();if(t)return jt(l(t));return}async function Js(e){let t=await P.selectFrom("coupons").where("code","=",e).selectAll().executeTakeFirst();if(t)return jt(l(t));return}async function Bs(){let e=$s(new Date),t=await P.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).selectAll().execute();return g(t).map(jt)}async function Us(){let e=await P.selectFrom("coupons").select(P.fn.count("id").as("count")).executeTakeFirst(),t=$s(new Date),r=await P.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",t).where("end_date",">=",t).select(P.fn.count("id").as("count")).executeTakeFirst(),n=await P.selectFrom("coupons").select(["discount_type",P.fn.count("id").as("count")]).groupBy("discount_type").execute(),o=await P.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),a=await P.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",t).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(e?.count||0),active:Number(r?.count||0),by_type:n,most_used:o,upcoming:a}}async function Ws(){let e=new Date,t=new Date(e);t.setDate(e.getDate()-7);let r=new Date(e);r.setMonth(e.getMonth()-1);let n=new Date(e);n.setFullYear(e.getFullYear()-1);let o=await Lt(null,null,e),a=await Lt(t,null,e),s=await Lt(r,null,e),i=await Lt(n,null,e);return{week:a,month:s,year:i,all_time:o}}async function Lt(e,t,r){let n=P.selectFrom("coupons");if(e)n=n.where("created_at",">=",e.toISOString());if(t)n=n.where("created_at","<=",t.toISOString());let o=await n.select(P.fn.count("id").as("count")).executeTakeFirst(),a=P.selectFrom("coupons");if(e)a=a.where("created_at",">=",e.toISOString());if(t)a=a.where("created_at","<=",t.toISOString());a=a.where("is_active","=",!0).where("start_date","<=",r).where("end_date",">=",r);let s=await a.select(P.fn.count("id").as("count")).executeTakeFirst(),i=Number(o?.count||0),u=Number(s?.count||0),c=i-u;return{total:i,active:u,inactive:c}}async function Ls(){let e=new Date,t=await P.selectFrom("coupons").select("discount_type").distinct().execute(),r={};for(let{discount_type:n}of t){let o=await P.selectFrom("coupons").where("discount_type","=",n).select(P.fn.count("id").as("count")).executeTakeFirst(),a=await P.selectFrom("coupons").where("discount_type","=",n).where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(P.fn.count("id").as("count")).executeTakeFirst(),s=Number(o?.count||0),i=Number(a?.count||0);r[n]={total:s,active:i,inactive:s-i}}return r}async function js(){let e=await P.selectFrom("coupons").select(P.fn.sum("usage_count").as("total")).executeTakeFirst(),t=new Date,r=new Date(t);r.setDate(t.getDate()-7);let n=new Date(t);n.setMonth(t.getMonth()-1);let o=new Date(t);o.setFullYear(t.getFullYear()-1);let a=await P.selectFrom("coupons").where("updated_at",">=",r.toISOString()).select(P.fn.sum("usage_count").as("total")).executeTakeFirst(),s=await P.selectFrom("coupons").where("updated_at",">=",n.toISOString()).select(P.fn.sum("usage_count").as("total")).executeTakeFirst(),i=await P.selectFrom("coupons").where("updated_at",">=",o.toISOString()).select(P.fn.sum("usage_count").as("total")).executeTakeFirst(),u=await P.selectFrom("coupons").select(["discount_type",P.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),c={};return u.forEach((d)=>{c[d.discount_type]=Number(d.total||0)}),{total:Number(e?.total||0),week:Number(a?.total||0),month:Number(s?.total||0),year:Number(i?.total||0),by_type:c}}async function zs(e=5){return await P.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(e).execute()}async function Gs(e=30){let t=new Date().toISOString(),r=new Date;r.setDate(r.getDate()-e);let n=await P.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",r.toISOString()).where("updated_at","<=",t).where("usage_count",">",0).orderBy("updated_at","desc").execute(),o={};return n.forEach((a)=>{let s=a.updated_at?new Date(a.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!o[s])o[s]=0;o[s]+=a?.usage_count||0}),Object.entries(o).map(([a,s])=>({date:a,count:s}))}async function Vs(){let e=new Date,t=await P.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",e).select(P.fn.count("id").as("count")).executeTakeFirst(),r=await P.selectFrom("coupons").where("usage_count",">",0).select(P.fn.count("id").as("count")).executeTakeFirst(),n=Number(t?.count||0),o=Number(r?.count||0);return{rate:n>0?o/n*100:0,total_active:n,total_redeemed:o}}async function qs(){let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()-1,1),n=new Date(e.getFullYear(),e.getMonth(),0),o=await P.selectFrom("coupons").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",e).where("end_date",">=",t).executeTakeFirst(),a=await P.selectFrom("coupons").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",n).where("end_date",">=",r).executeTakeFirst(),s=Number(o?.count||0),i=Number(a?.count||0),u=s-i,c=i!==0?u/i*100:s>0?100:0;return{current_month:s,previous_month:i,difference:u,percentage_change:c}}var{randomUUIDv7:cw}=globalThis.Bun;import{db as Hs}from"@stacksjs/database/runtime";import{HttpError as Ks}from"@stacksjs/error-handling";import{isUniqueViolation as dw}from"@stacksjs/orm";async function Zs(e){try{let t=cw();await Hs.insertInto("coupons").values({...e,uuid:t}).executeTakeFirst();let r=await Hs.selectFrom("coupons").where("uuid","=",t).selectAll().executeTakeFirst();return l(r,!0)}catch(t){if(t instanceof Ks)throw t;if(dw(t))throw new Ks(409,"A coupon with this code already exists");if(t instanceof Error)throw Error(`Failed to create coupon: ${t.message}`);throw t}}import{db as Ys,mutationCount as lw,sqlHelpers as pw}from"@stacksjs/database/runtime";import{env as mw}from"@stacksjs/env";import{HttpError as Qs}from"@stacksjs/error-handling";import{formatDate as Xs,isUniqueViolation as fw}from"@stacksjs/orm";async function ei(e,t){if(!await Ce(e))return;try{return await Ys.updateTable("coupons").set({...t,updated_at:Xs(new Date)}).where("id","=",e).execute(),await Ce(e)}catch(n){if(n instanceof Qs)throw n;if(fw(n))throw new Qs(409,"A coupon with this code already exists");if(n instanceof Error)throw Error(`Failed to update coupon: ${n.message}`);throw n}}async function ti(e){let t=pw(mw.DB_CONNECTION||"sqlite"),r=t.param,n=Xs(new Date),o=await Ys.unsafe(`UPDATE coupons
|
|
3
3
|
SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ${r(1)}
|
|
4
4
|
WHERE id = ${r(2)}
|
|
5
5
|
AND (usage_limit IS NULL OR COALESCE(usage_count, 0) < usage_limit)
|
|
6
|
-
AND is_active = ${
|
|
6
|
+
AND is_active = ${t.boolTrue}
|
|
7
7
|
AND (start_date IS NULL OR start_date <= ${r(3)})
|
|
8
|
-
AND (end_date IS NULL OR end_date >= ${r(4)})`,[o,t,o,o]);if(np(n)>0){let u=await pe(t);if(u)return{ok:!0,coupon:u};return{ok:!1,reason:"not-found"}}let a=await pe(t);if(!a)return{ok:!1,reason:"not-found"};if(!a.isActive)return{ok:!1,reason:"inactive"};let s=!a.startDate||a.startDate<=o,i=!a.endDate||a.endDate>=o;if(!s||!i)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var co={};g(co,{bulkDestroy:()=>Ra,destroy:()=>_a,fetchAll:()=>Da,fetchById:()=>Rt,store:()=>Pa,update:()=>ka});import{db as ba}from"@stacksjs/database/runtime";async function _a(t){try{let e=await ba.deleteFrom("customers").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete customer: ${e.message}`);throw e}}async function Ra(t){if(!t.length)return 0;try{let e=await ba.deleteFrom("customers").where("id","in",t).executeTakeFirst();return p(e)||0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${e.message}`);throw e}}import{db as xa}from"@stacksjs/database/runtime";async function Rt(t){let e=await xa.selectFrom("customers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Da(){return w(await xa.selectFrom("customers").selectAll().execute())}import{db as up}from"@stacksjs/database/runtime";import{HttpError as va}from"@stacksjs/error-handling";import{isUniqueViolation as cp}from"@stacksjs/orm";function H(t){if(typeof t==="bigint")return uo(t);if(typeof t==="number")return uo(t);if(!t||typeof t!=="object")return;if(Array.isArray(t)){for(let r of t){let o=H(r);if(o!==void 0)return o}return}let e=t;for(let r of["lastInsertRowid","insertId","lastInsertId"]){let o=e[r];if(o===void 0||o===null)continue;let n=uo(o);if(n!==void 0)return n}return}function uo(t){let e=typeof t==="bigint"?Number(t):Number(t);if(!Number.isSafeInteger(e)||e<=0)return;return e}async function Pa(t){try{let e={...t,avatar:t.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},r=await up.insertInto("customers").values(e).executeTakeFirst();if(!r)throw Error("Failed to create customer");let o=H(r);if(o===void 0)throw Error("Failed to create customer: the database reported no insert id");return await Rt(o)}catch(e){if(e instanceof va)throw e;if(cp(e))throw new va(409,"A customer with this email already exists");if(e instanceof Error)throw Error(`Failed to create customer: ${e.message}`);throw e}}import{db as dp}from"@stacksjs/database/runtime";import{HttpError as Fa}from"@stacksjs/error-handling";import{formatDate as lp,isUniqueViolation as mp}from"@stacksjs/orm";async function ka(t,e){try{if(!t)throw Error("Customer ID is required for update");let r=await dp.updateTable("customers").set({...e,updated_at:lp(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Fa)throw r;if(mp(r))throw new Fa(409,"A customer with this email already exists");if(r instanceof Error)throw Error(`Failed to update customer: ${r.message}`);throw r}}var wo={};g(wo,{bulkDestroy:()=>Sa,bulkStore:()=>ja,calculateErrorRate:()=>Ia,calculatePrinterHealth:()=>Ja,countAll:()=>Ca,countPrintsByDeviceId:()=>Ma,countTotalPrints:()=>Aa,destroy:()=>Ea,downloadPrintDevices:()=>Ua,exportPrintDevices:()=>Dt,fetchAll:()=>xt,fetchById:()=>K,fetchErrorsByDeviceId:()=>Na,getPrinterStatusCounts:()=>Ba,store:()=>La,storePrintDevicesExport:()=>$a,update:()=>za,updatePrintCount:()=>qa,updateStatus:()=>Ga});import{db as Ta}from"@stacksjs/database/runtime";async function Ea(t){try{let e=await Ta.deleteFrom("print_devices").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print device: ${e.message}`);throw e}}async function Sa(t){if(!t.length)return 0;try{let e=await Ta.deleteFrom("print_devices").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print devices: ${e.message}`);throw e}}import{createSpreadsheet as pp}from"ts-spreadsheets";import{db as C}from"@stacksjs/database/runtime";async function K(t){let e=await C.selectFrom("print_devices").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function xt(){return w(await C.selectFrom("print_devices").selectAll().execute())}async function Ca(){let t=await C.selectFrom("print_devices").select(C.fn.count("id").as("count")).executeTakeFirst();return Number(t?.count||0)}async function Aa(){let t=await C.selectFrom("print_devices").select(C.fn.sum("print_count").as("total")).executeTakeFirst();return Number(t?.total||0)}async function Ma(t){let e=await C.selectFrom("print_devices").select("print_count").where("id","=",t).executeTakeFirst();return Number(e?.print_count??0)}async function Ia(){let t=await C.selectFrom("receipts").select([C.fn.count("id").as("total"),C.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!t?.total||t.total===0)return 0;return Number(Number(t?.failed_count??0)/Number(t?.total??0)*100)}async function Na(t){let e=await C.selectFrom("receipts").where("print_device_id","=",t).where("status","=","failed").selectAll().execute();return w(e)}async function Ja(){let t=await C.selectFrom("print_devices").select([C.fn.count("id").as("total"),C.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!t?.total||t.total===0)return 0;return Number(Number(t?.online_count??0)/Number(t?.total??0)*100)}async function Ba(){return(await C.selectFrom("print_devices").select(["status",C.fn.count("id").as("count")]).groupBy("status").execute()).reduce((e,r)=>(e[r.status]=Number(r.count||0),e),{})}function lo(t,e,r=e){let o=t;return o[String(e)]??o[r]}function fp(t){if(t instanceof Date)return t;if(typeof t==="number")return new Date(t);if(typeof t==="string")return new Date(/^\d+$/.test(t)?Number(t):t);return new Date(Number.NaN)}function Oa(t,e,r=e){let o=lo(t,e,r);if(typeof o==="number")return o;let n=Number(o);return Number.isFinite(n)?n:0}function Le(t,e,r=e){let o=lo(t,e,r);return o==null?"":String(o)}async function Dt(t="csv"){let e=await xt(),r=wp(e);return pp(r,{type:t})}function wp(t){let e=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],r=t.map((o)=>[Oa(o,"id"),Le(o,"name"),Le(o,"macAddress","mac_address"),Le(o,"location"),Le(o,"terminal"),Le(o,"status"),fp(lo(o,"lastPing","last_ping")).toLocaleString(),Oa(o,"printCount","print_count")]);return{headings:e,data:r}}async function Ua(t="csv",e){let r=await Dt(t),o=`print_devices_export_${new Date().toISOString().split("T")[0]}.${t}`;return r.download(e||o)}async function $a(t="csv",e){let r=await Dt(t),o=`print_devices_export_${new Date().toISOString().split("T")[0]}.${t}`;r.store(e||o)}var{randomUUIDv7:Wa}=globalThis.Bun;import{db as mo}from"@stacksjs/database/runtime";async function La(t){try{let e=Wa(),r={last_ping:0,print_count:0,...t,uuid:e};await mo.insertInto("print_devices").values(r).executeTakeFirst();let o=await mo.selectFrom("print_devices").where("uuid","=",e).selectAll().executeTakeFirst();return d(o,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create print device: ${e.message}`);throw e}}async function ja(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={last_ping:0,print_count:0,...r,uuid:Wa()};await mo.insertInto("print_devices").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${r.message}`);throw r}}import{db as po}from"@stacksjs/database/runtime";import{formatDate as fo}from"@stacksjs/orm";async function za(t,e){if(!await K(t))return;try{return await po.updateTable("print_devices").set({...e,updated_at:fo(new Date)}).where("id","=",t).execute(),await K(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print device: ${o.message}`);throw o}}async function Ga(t,e){if(!await K(t))throw Error(`Print device with ID ${t} not found`);try{return await po.updateTable("print_devices").set({status:e,updated_at:fo(new Date)}).where("id","=",t).execute(),await K(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print device status: ${o.message}`);throw o}}async function qa(t,e){if(!await K(t))throw Error(`Print device with ID ${t} not found`);try{return await po.updateTable("print_devices").set({print_count:e,updated_at:fo(new Date)}).where("id","=",t).execute(),await K(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update print count: ${o.message}`);throw o}}var go={};g(go,{bulkDestroy:()=>Za,bulkUpdateStatus:()=>rs,destroy:()=>Va,destroyGroup:()=>Ha,fetchAll:()=>Pt,fetchByGroup:()=>Ya,fetchById:()=>Ka,fetchGrouped:()=>Qa,fetchStats:()=>Xa,fetchTimeline:()=>es,ignoreGroup:()=>ns,resolveGroup:()=>os,unresolveGroup:()=>as,update:()=>ts});import{db as yo}from"@stacksjs/database/runtime";import{log as ho}from"@stacksjs/logging";async function Va(t){try{return await yo.deleteFrom("errors").where("id","=",t).execute(),!0}catch(e){return ho.error("[commerce/errors] destroy failed",{id:t,error:e}),!1}}async function Za(t){try{return await yo.deleteFrom("errors").where("id","in",t).execute(),!0}catch(e){return ho.error("[commerce/errors] bulkDestroy failed",{count:t.length,error:e}),!1}}async function Ha(t,e){try{return await yo.deleteFrom("errors").where("type","=",t).where("message","=",e).execute(),!0}catch(r){return ho.error("[commerce/errors] destroyGroup failed",{type:t,message:e,error:r}),!1}}import{db as vt}from"@stacksjs/database/runtime";async function Ka(t){return await vt.selectFrom("errors").where("id","=",t).selectAll().executeTakeFirst()}async function Pt(){return await vt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function Qa(){let t=await vt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),e=new Map;for(let o of t){let n=`${o.type}:${o.message}`;if(!e.has(n))e.set(n,{errors:[],firstSeen:new Date(o.created_at),lastSeen:new Date(o.created_at)});let a=e.get(n);a.errors.push(o);let s=new Date(o.created_at);if(s<a.firstSeen)a.firstSeen=s;if(s>a.lastSeen)a.lastSeen=s}let r=[];for(let[o,n]of e){let a=n.errors[0];if(!a)continue;let s=n.errors.find((u)=>u.status!==null)?.status,i="unresolved";if(s===1)i="resolved";else if(s===2)i="ignored";r.push({id:a.id,type:a.type,message:a.message,stack:a.stack,status:i,count:n.errors.length,first_seen:n.firstSeen.toISOString(),last_seen:n.lastSeen.toISOString(),error_ids:n.errors.map((u)=>u.id)})}return r.sort((o,n)=>new Date(n.last_seen).getTime()-new Date(o.last_seen).getTime()),r}async function Ya(t,e){return await vt.selectFrom("errors").where("type","=",t).where("message","=",e).selectAll().orderBy("created_at","desc").execute()}async function Xa(){let t=await Pt(),e=new Date,r=new Date(e.getTime()-86400000),o=new Date(e.getTime()-172800000),n=t.filter((i)=>new Date(i.created_at)>=r).length,a=t.filter((i)=>{let u=new Date(i.created_at);return u>=o&&u<r}).length,s=a===0?n>0?100:0:Math.round((n-a)/a*100);return{total:t.length,unresolved:t.filter((i)=>i.status===null||i.status===0).length,resolved:t.filter((i)=>i.status===1).length,ignored:t.filter((i)=>i.status===2).length,last_24h:n,trend:s}}async function es(){let t=await Pt(),e=new Date,r=[];for(let o=23;o>=0;o--){let n=new Date(e.getTime()-o*60*60*1000);n.setMinutes(0,0,0);let a=new Date(n.getTime()+3600000),s=t.filter((i)=>{let u=new Date(i.created_at);return u>=n&&u<a}).length;r.push({hour:n.toISOString(),count:s})}return r}import{db as je}from"@stacksjs/database/runtime";import{sql as ze}from"@stacksjs/database/runtime";import{log as Ge}from"@stacksjs/logging";async function ts(t,e){try{return await je.updateTable("errors").set({...e,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("id","=",t).execute(),!0}catch(r){return Ge.error("[commerce/errors] update failed",{id:t,error:r}),!1}}async function rs(t,e){try{return await je.updateTable("errors").set({status:e,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("id","in",t).execute(),!0}catch(r){return Ge.error("[commerce/errors] bulkUpdateStatus failed",{count:t.length,status:e,error:r}),!1}}async function os(t,e){try{return await je.updateTable("errors").set({status:1,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ge.error("[commerce/errors] resolveGroup failed",{type:t,message:e,error:r}),!1}}async function ns(t,e){try{return await je.updateTable("errors").set({status:2,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ge.error("[commerce/errors] ignoreGroup failed",{type:t,message:e,error:r}),!1}}async function as(t,e){try{return await je.updateTable("errors").set({status:0,updated_at:ze.raw("CURRENT_TIMESTAMP")}).where("type","=",t).where("message","=",e).execute(),!0}catch(r){return Ge.error("[commerce/errors] unresolveGroup failed",{type:t,message:e,error:r}),!1}}var Ro={};g(Ro,{bulkDestroy:()=>ys,calculateGiftCardValues:()=>ls,checkBalance:()=>cs,compareActiveGiftCards:()=>ds,deactivate:()=>gs,destroy:()=>ws,destroyExpired:()=>hs,fetchActive:()=>is,fetchAll:()=>ss,fetchByCode:()=>bo,fetchById:()=>Q,fetchStats:()=>us,fetchTotalCurrentBalance:()=>ps,fetchTotalValue:()=>ms,store:()=>_s,update:()=>Ps,updateBalance:()=>Fs});import{db as Ft,matchedRows as gp}from"@stacksjs/database/runtime";import{formatDate as fs}from"@stacksjs/orm";import{db as v,sql as I}from"@stacksjs/database/runtime";import{formatDate as ue,toTimestamp as De}from"@stacksjs/orm";import{aggregateFunctions as yp,db as hp}from"@stacksjs/database/runtime";async function J(t,e,r){let o=hp.selectFrom(t);if(r)o=r(o);o=o.select(Object.entries(e).map(([s,i])=>{let u=i.column??"id",c=yp[i.kind](u);if(i.filter)c=c.filterWhere(i.filter.column,i.filter.op,i.filter.value);return c.as(s)}));let n=await o.executeTakeFirst(),a={};for(let s of Object.keys(e)){let i=n?.[s];a[s]=typeof i==="number"?i:Number(i??0)||0}return a}async function ss(){let t=await v.selectFrom("gift_cards").selectAll().execute();return w(t)}async function Q(t){let e=await v.selectFrom("gift_cards").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function bo(t){let e=await v.selectFrom("gift_cards").where("code","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function is(){let t=await v.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute();return w(t)}async function us(){let{count:t}=await J("gift_cards",{count:{kind:"count"}}),e=De(new Date),r=await v.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(e)} OR expiry_date IS NULL)`).select(v.fn.count("id").as("count")).executeTakeFirst(),o=await v.selectFrom("gift_cards").select(["status",v.fn.count("id").as("count")]).groupBy("status").execute(),{count:n}=await J("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(I`current_balance / initial_balance < 0.25`)),{count:a}=await J("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(I`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:s}=await J("gift_cards",{count:{kind:"count"}},(l)=>l.whereRaw(I`current_balance / initial_balance > 0.75`)),i=new Date;i.setDate(i.getDate()+30);let u=await v.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",De(i)).where("expiry_date",">=",e).selectAll().limit(5).execute(),c=await v.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:t,active:Number(r?.count||0),by_status:o.map((l)=>({status:l.status,count:Number(l.count)})),by_balance:{low:n,medium:a,high:s},expiring_soon:w(u),recently_used:w(c)}}async function cs(t){let e=await bo(t);if(!e)return{valid:!1,message:"Gift card not found"};if(!e.isActive||e.status!=="ACTIVE")return{valid:!1,balance:e.currentBalance,currency:e.currency,message:`Gift card is ${e.status.toLowerCase()}`};if(e.expiryDate){if(new Date(e.expiryDate)<new Date)return{valid:!1,balance:e.currentBalance,currency:e.currency,message:"Gift card has expired"}}return{valid:!0,balance:e.currentBalance,currency:e.currency}}async function ds(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await v.selectFrom("gift_cards").select(v.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(e))} OR expiry_date IS NULL)`).where("created_at",">=",ue(r)).where("created_at","<=",ue(e)).executeTakeFirst(),s=await v.selectFrom("gift_cards").select(v.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(n))} OR expiry_date IS NULL)`).where("created_at",">=",ue(n)).where("created_at","<=",ue(o)).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,l=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:l,days_range:t}}async function ls(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await v.selectFrom("gift_cards").select([v.fn.sum("initial_balance").as("total_initial"),v.fn.sum("current_balance").as("total_balance"),v.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(e))} OR expiry_date IS NULL)`).where("created_at",">=",ue(r)).where("created_at","<=",ue(e)).executeTakeFirst(),s=await v.selectFrom("gift_cards").select([v.fn.sum("initial_balance").as("total_initial"),v.fn.sum("current_balance").as("total_balance"),v.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(I`(expiry_date >= ${I.literal(De(n))} OR expiry_date IS NULL)`).where("created_at",">=",ue(n)).where("created_at","<=",ue(o)).executeTakeFirst(),i=Number(a?.total_initial||0),u=Number(a?.total_balance||0),c=Number(a?.card_count||0),l=Number(s?.total_initial||0),m=Number(s?.total_balance||0),f=Number(s?.card_count||0),h=i>0?(i-u)/i*100:0,b=l>0?(l-m)/l*100:0,_=c>0?i/c:0,D=c>0?u/c:0,z=i-l,le=u-m,me=c-f,Re=l!==0?z/l*100:i>0?100:0,G=m!==0?le/m*100:u>0?100:0,Wm=f!==0?me/f*100:c>0?100:0;return{current_period:{total_initial_value:i,total_remaining_balance:u,utilization_rate:h,card_count:c,average_initial_value:_,average_remaining_balance:D},previous_period:{total_initial_value:l,total_remaining_balance:m,utilization_rate:b,card_count:f},comparison:{initial_value:{difference:z,percentage:Math.abs(Re),is_increase:z>=0},balance:{difference:le,percentage:Math.abs(G),is_increase:le>=0},card_count:{difference:me,percentage:Math.abs(Wm),is_increase:me>=0}},days_range:t}}async function ms(){let{total_value:t}=await J("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:t}}async function ps(){let{total_balance:t}=await J("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:t}}async function ws(t){let e=await Ft.deleteFrom("gift_cards").where("id","=",t).executeTakeFirst();return p(e)>0}async function ys(t){if(!t.length)return 0;let e=await Ft.deleteFrom("gift_cards").where("id","in",t).executeTakeFirst();return p(e)}async function hs(){let t=fs(new Date),e=await Ft.deleteFrom("gift_cards").where("expiry_date","<",t).executeTakeFirst();return p(e)}async function gs(t){if(!await Q(t))throw Error(`Gift card with ID ${t} not found`);return(await gp(Ft.updateTable("gift_cards").set({is_active:!1,status:"DEACTIVATED",updated_at:fs(new Date)}).where("id","=",t))).length>0}var{randomUUIDv7:bp}=globalThis.Bun;import{db as _o}from"@stacksjs/database/runtime";import{HttpError as bs}from"@stacksjs/error-handling";import{isUniqueViolation as _p}from"@stacksjs/orm";async function _s(t){let e=t,r={...t,current_balance:e.current_balance??e.initial_balance,status:t.status||"ACTIVE",is_active:e.is_active??!0,uuid:bp()};try{let o=await _o.insertInto("gift_cards").values(r).executeTakeFirst(),n=H(o);if(n!==void 0){let s=await _o.selectFrom("gift_cards").where("id","=",n).selectAll().executeTakeFirst();return d(s)}let a=await _o.selectFrom("gift_cards").where("uuid","=",r.uuid).selectAll().executeTakeFirst();return d(a,!0)}catch(o){if(o instanceof bs)throw o;if(_p(o))throw new bs(409,"A gift card with this code already exists");if(o instanceof Error)throw Error(`Failed to create gift card: ${o.message}`);throw o}}import{db as Ds,mutationCount as Rp,parseSqlDateTime as Rs,sqlHelpers as xp}from"@stacksjs/database/runtime";import{env as Dp}from"@stacksjs/env";import{HttpError as xs}from"@stacksjs/error-handling";import{formatDate as vs,isUniqueViolation as vp}from"@stacksjs/orm";async function Ps(t,e){if(!await Q(t))return;try{return await Ds.updateTable("gift_cards").set({...e,updated_at:vs(new Date)}).where("id","=",t).execute(),await Q(t)}catch(o){if(o instanceof xs)throw o;if(vp(o))throw new xs(409,"A gift card with this code already exists");if(o instanceof Error)throw Error(`Failed to update gift card: ${o.message}`);throw o}}async function Fs(t,e){if(!Number.isFinite(e))throw Error(`Gift card balance adjustment must be a finite number, got ${e}`);let r=xp(Dp.DB_CONNECTION||"sqlite"),o=r.param,n=vs(new Date),a=e<0,s=e>0,i=s?`(status = 'ACTIVE' OR (status = 'USED' AND is_reloadable = ${r.boolTrue}))`:"status = 'ACTIVE'",u=[],c=(_)=>(u.push(_),o(u.length)),l=await Ds.unsafe(`UPDATE gift_cards
|
|
9
|
-
SET status = CASE WHEN current_balance + ${c(
|
|
10
|
-
current_balance = current_balance + ${c(
|
|
11
|
-
${a?`last_used_date = ${c(
|
|
12
|
-
`:""}updated_at = ${c(
|
|
13
|
-
WHERE id = ${c(
|
|
8
|
+
AND (end_date IS NULL OR end_date >= ${r(4)})`,[n,e,n,n]);if(lw(o)>0){let u=await Ce(e);if(u)return{ok:!0,coupon:u};return{ok:!1,reason:"not-found"}}let a=await Ce(e);if(!a)return{ok:!1,reason:"not-found"};if(!a.isActive)return{ok:!1,reason:"inactive"};let s=!a.startDate||a.startDate<=n,i=!a.endDate||a.endDate>=n;if(!s||!i)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var Yn={};D(Yn,{bulkDestroy:()=>oi,destroy:()=>ni,fetchAll:()=>si,fetchById:()=>zt,store:()=>ui,update:()=>di});import{db as ri}from"@stacksjs/database/runtime";async function ni(e){try{let t=await ri.deleteFrom("customers").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete customer: ${t.message}`);throw t}}async function oi(e){if(!e.length)return 0;try{let t=await ri.deleteFrom("customers").where("id","in",e).executeTakeFirst();return f(t)||0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${t.message}`);throw t}}import{db as ai}from"@stacksjs/database/runtime";async function zt(e){let t=await ai.selectFrom("customers").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function si(){return g(await ai.selectFrom("customers").selectAll().execute())}import{db as ww}from"@stacksjs/database/runtime";import{HttpError as ii}from"@stacksjs/error-handling";import{isUniqueViolation as yw}from"@stacksjs/orm";function ce(e){if(typeof e==="bigint")return Qn(e);if(typeof e==="number")return Qn(e);if(!e||typeof e!=="object")return;if(Array.isArray(e)){for(let r of e){let n=ce(r);if(n!==void 0)return n}return}let t=e;for(let r of["lastInsertRowid","insertId","lastInsertId"]){let n=t[r];if(n===void 0||n===null)continue;let o=Qn(n);if(o!==void 0)return o}return}function Qn(e){let t=typeof e==="bigint"?Number(e):Number(e);if(!Number.isSafeInteger(t)||t<=0)return;return t}async function ui(e){try{let t={...e,avatar:e.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},r=await ww.insertInto("customers").values(t).executeTakeFirst();if(!r)throw Error("Failed to create customer");let n=ce(r);if(n===void 0)throw Error("Failed to create customer: the database reported no insert id");return await zt(n)}catch(t){if(t instanceof ii)throw t;if(yw(t))throw new ii(409,"A customer with this email already exists");if(t instanceof Error)throw Error(`Failed to create customer: ${t.message}`);throw t}}import{db as gw}from"@stacksjs/database/runtime";import{HttpError as ci}from"@stacksjs/error-handling";import{formatDate as hw,isUniqueViolation as bw}from"@stacksjs/orm";async function di(e,t){try{if(!e)throw Error("Customer ID is required for update");let r=await gw.updateTable("customers").set({...t,updated_at:hw(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return l(r)}catch(r){if(r instanceof ci)throw r;if(bw(r))throw new ci(409,"A customer with this email already exists");if(r instanceof Error)throw Error(`Failed to update customer: ${r.message}`);throw r}}var no={};D(no,{bulkDestroy:()=>mi,bulkStore:()=>ki,calculateErrorRate:()=>gi,calculatePrinterHealth:()=>bi,countAll:()=>fi,countPrintsByDeviceId:()=>yi,countTotalPrints:()=>wi,destroy:()=>pi,downloadPrintDevices:()=>Ri,exportPrintDevices:()=>Vt,fetchAll:()=>Gt,fetchById:()=>de,fetchErrorsByDeviceId:()=>hi,getPrinterStatusCounts:()=>_i,store:()=>Di,storePrintDevicesExport:()=>Pi,update:()=>Fi,updatePrintCount:()=>Si,updateStatus:()=>Ti});import{db as li}from"@stacksjs/database/runtime";async function pi(e){try{let t=await li.deleteFrom("print_devices").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print device: ${t.message}`);throw t}}async function mi(e){if(!e.length)return 0;try{let t=await li.deleteFrom("print_devices").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print devices: ${t.message}`);throw t}}import{createSpreadsheet as _w}from"ts-spreadsheets";import{db as L}from"@stacksjs/database/runtime";async function de(e){let t=await L.selectFrom("print_devices").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function Gt(){return g(await L.selectFrom("print_devices").selectAll().execute())}async function fi(){let e=await L.selectFrom("print_devices").select(L.fn.count("id").as("count")).executeTakeFirst();return Number(e?.count||0)}async function wi(){let e=await L.selectFrom("print_devices").select(L.fn.sum("print_count").as("total")).executeTakeFirst();return Number(e?.total||0)}async function yi(e){let t=await L.selectFrom("print_devices").select("print_count").where("id","=",e).executeTakeFirst();return Number(t?.print_count??0)}async function gi(){let e=await L.selectFrom("receipts").select([L.fn.count("id").as("total"),L.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!e?.total||e.total===0)return 0;return Number(Number(e?.failed_count??0)/Number(e?.total??0)*100)}async function hi(e){let t=await L.selectFrom("receipts").where("print_device_id","=",e).where("status","=","failed").selectAll().execute();return g(t)}async function bi(){let e=await L.selectFrom("print_devices").select([L.fn.count("id").as("total"),L.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!e?.total||e.total===0)return 0;return Number(Number(e?.online_count??0)/Number(e?.total??0)*100)}async function _i(){return(await L.selectFrom("print_devices").select(["status",L.fn.count("id").as("count")]).groupBy("status").execute()).reduce((t,r)=>(t[r.status]=Number(r.count||0),t),{})}function Xn(e,t,r=t){let n=e;return n[String(t)]??n[r]}function xw(e){if(e instanceof Date)return e;if(typeof e==="number")return new Date(e);if(typeof e==="string")return new Date(/^\d+$/.test(e)?Number(e):e);return new Date(Number.NaN)}function xi(e,t,r=t){let n=Xn(e,t,r);if(typeof n==="number")return n;let o=Number(n);return Number.isFinite(o)?o:0}function st(e,t,r=t){let n=Xn(e,t,r);return n==null?"":String(n)}async function Vt(e="csv"){let t=await Gt(),r=Rw(t);return _w(r,{type:e})}function Rw(e){let t=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],r=e.map((n)=>[xi(n,"id"),st(n,"name"),st(n,"macAddress","mac_address"),st(n,"location"),st(n,"terminal"),st(n,"status"),xw(Xn(n,"lastPing","last_ping")).toLocaleString(),xi(n,"printCount","print_count")]);return{headings:t,data:r}}async function Ri(e="csv",t){let r=await Vt(e),n=`print_devices_export_${new Date().toISOString().split("T")[0]}.${e}`;return r.download(t||n)}async function Pi(e="csv",t){let r=await Vt(e),n=`print_devices_export_${new Date().toISOString().split("T")[0]}.${e}`;r.store(t||n)}var{randomUUIDv7:vi}=globalThis.Bun;import{db as eo}from"@stacksjs/database/runtime";async function Di(e){try{let t=vi(),r={last_ping:0,print_count:0,...e,uuid:t};await eo.insertInto("print_devices").values(r).executeTakeFirst();let n=await eo.selectFrom("print_devices").where("uuid","=",t).selectAll().executeTakeFirst();return l(n,!0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create print device: ${t.message}`);throw t}}async function ki(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={last_ping:0,print_count:0,...r,uuid:vi()};await eo.insertInto("print_devices").values(n).execute(),t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${r.message}`);throw r}}import{db as to}from"@stacksjs/database/runtime";import{formatDate as ro}from"@stacksjs/orm";async function Fi(e,t){if(!await de(e))return;try{return await to.updateTable("print_devices").set({...t,updated_at:ro(new Date)}).where("id","=",e).execute(),await de(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print device: ${n.message}`);throw n}}async function Ti(e,t){if(!await de(e))throw Error(`Print device with ID ${e} not found`);try{return await to.updateTable("print_devices").set({status:t,updated_at:ro(new Date)}).where("id","=",e).execute(),await de(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print device status: ${n.message}`);throw n}}async function Si(e,t){if(!await de(e))throw Error(`Print device with ID ${e} not found`);try{return await to.updateTable("print_devices").set({print_count:t,updated_at:ro(new Date)}).where("id","=",e).execute(),await de(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update print count: ${n.message}`);throw n}}var so={};D(so,{bulkDestroy:()=>Ei,bulkUpdateStatus:()=>Bi,destroy:()=>Ci,destroyGroup:()=>Ai,fetchAll:()=>Ht,fetchByGroup:()=>Ni,fetchById:()=>Mi,fetchGrouped:()=>Ii,fetchStats:()=>$i,fetchTimeline:()=>Oi,ignoreGroup:()=>Wi,resolveGroup:()=>Ui,unresolveGroup:()=>Li,update:()=>Ji});import{db as oo}from"@stacksjs/database/runtime";import{log as ao}from"@stacksjs/logging";async function Ci(e){try{return await oo.deleteFrom("errors").where("id","=",e).execute(),!0}catch(t){return ao.error("[commerce/errors] destroy failed",{id:e,error:t}),!1}}async function Ei(e){try{return await oo.deleteFrom("errors").where("id","in",e).execute(),!0}catch(t){return ao.error("[commerce/errors] bulkDestroy failed",{count:e.length,error:t}),!1}}async function Ai(e,t){try{return await oo.deleteFrom("errors").where("type","=",e).where("message","=",t).execute(),!0}catch(r){return ao.error("[commerce/errors] destroyGroup failed",{type:e,message:t,error:r}),!1}}import{db as qt}from"@stacksjs/database/runtime";async function Mi(e){return await qt.selectFrom("errors").where("id","=",e).selectAll().executeTakeFirst()}async function Ht(){return await qt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function Ii(){let e=await qt.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),t=new Map;for(let n of e){let o=`${n.type}:${n.message}`;if(!t.has(o))t.set(o,{errors:[],firstSeen:new Date(n.created_at),lastSeen:new Date(n.created_at)});let a=t.get(o);a.errors.push(n);let s=new Date(n.created_at);if(s<a.firstSeen)a.firstSeen=s;if(s>a.lastSeen)a.lastSeen=s}let r=[];for(let[n,o]of t){let a=o.errors[0];if(!a)continue;let s=o.errors.find((u)=>u.status!==null)?.status,i="unresolved";if(s===1)i="resolved";else if(s===2)i="ignored";r.push({id:a.id,type:a.type,message:a.message,stack:a.stack,status:i,count:o.errors.length,first_seen:o.firstSeen.toISOString(),last_seen:o.lastSeen.toISOString(),error_ids:o.errors.map((u)=>u.id)})}return r.sort((n,o)=>new Date(o.last_seen).getTime()-new Date(n.last_seen).getTime()),r}async function Ni(e,t){return await qt.selectFrom("errors").where("type","=",e).where("message","=",t).selectAll().orderBy("created_at","desc").execute()}async function $i(){let e=await Ht(),t=new Date,r=new Date(t.getTime()-86400000),n=new Date(t.getTime()-172800000),o=e.filter((i)=>new Date(i.created_at)>=r).length,a=e.filter((i)=>{let u=new Date(i.created_at);return u>=n&&u<r}).length,s=a===0?o>0?100:0:Math.round((o-a)/a*100);return{total:e.length,unresolved:e.filter((i)=>i.status===null||i.status===0).length,resolved:e.filter((i)=>i.status===1).length,ignored:e.filter((i)=>i.status===2).length,last_24h:o,trend:s}}async function Oi(){let e=await Ht(),t=new Date,r=[];for(let n=23;n>=0;n--){let o=new Date(t.getTime()-n*60*60*1000);o.setMinutes(0,0,0);let a=new Date(o.getTime()+3600000),s=e.filter((i)=>{let u=new Date(i.created_at);return u>=o&&u<a}).length;r.push({hour:o.toISOString(),count:s})}return r}import{db as it}from"@stacksjs/database/runtime";import{sql as ut}from"@stacksjs/database/runtime";import{log as ct}from"@stacksjs/logging";async function Ji(e,t){try{return await it.updateTable("errors").set({...t,updated_at:ut.raw("CURRENT_TIMESTAMP")}).where("id","=",e).execute(),!0}catch(r){return ct.error("[commerce/errors] update failed",{id:e,error:r}),!1}}async function Bi(e,t){try{return await it.updateTable("errors").set({status:t,updated_at:ut.raw("CURRENT_TIMESTAMP")}).where("id","in",e).execute(),!0}catch(r){return ct.error("[commerce/errors] bulkUpdateStatus failed",{count:e.length,status:t,error:r}),!1}}async function Ui(e,t){try{return await it.updateTable("errors").set({status:1,updated_at:ut.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return ct.error("[commerce/errors] resolveGroup failed",{type:e,message:t,error:r}),!1}}async function Wi(e,t){try{return await it.updateTable("errors").set({status:2,updated_at:ut.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return ct.error("[commerce/errors] ignoreGroup failed",{type:e,message:t,error:r}),!1}}async function Li(e,t){try{return await it.updateTable("errors").set({status:0,updated_at:ut.raw("CURRENT_TIMESTAMP")}).where("type","=",e).where("message","=",t).execute(),!0}catch(r){return ct.error("[commerce/errors] unresolveGroup failed",{type:e,message:t,error:r}),!1}}var co={};D(co,{bulkDestroy:()=>Xi,calculateGiftCardValues:()=>Hi,checkBalance:()=>Vi,compareActiveGiftCards:()=>qi,deactivate:()=>tu,destroy:()=>Yi,destroyExpired:()=>eu,fetchActive:()=>zi,fetchAll:()=>ji,fetchByCode:()=>io,fetchById:()=>le,fetchStats:()=>Gi,fetchTotalCurrentBalance:()=>Zi,fetchTotalValue:()=>Ki,store:()=>nu,update:()=>uu,updateBalance:()=>cu});import{db as Kt,matchedRows as Dw}from"@stacksjs/database/runtime";import{formatDate as Qi}from"@stacksjs/orm";import{db as C,sql as V}from"@stacksjs/database/runtime";import{formatDate as De,toTimestamp as We}from"@stacksjs/orm";import{aggregateFunctions as Pw,db as vw}from"@stacksjs/database/runtime";async function K(e,t,r){let n=vw.selectFrom(e);if(r)n=r(n);n=n.select(Object.entries(t).map(([s,i])=>{let u=i.column??"id",c=Pw[i.kind](u);if(i.filter)c=c.filterWhere(i.filter.column,i.filter.op,i.filter.value);return c.as(s)}));let o=await n.executeTakeFirst(),a={};for(let s of Object.keys(t)){let i=o?.[s];a[s]=typeof i==="number"?i:Number(i??0)||0}return a}async function ji(){let e=await C.selectFrom("gift_cards").selectAll().execute();return g(e)}async function le(e){let t=await C.selectFrom("gift_cards").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function io(e){let t=await C.selectFrom("gift_cards").where("code","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function zi(){let e=await C.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute();return g(e)}async function Gi(){let{count:e}=await K("gift_cards",{count:{kind:"count"}}),t=We(new Date),r=await C.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(V`(expiry_date >= ${V.literal(t)} OR expiry_date IS NULL)`).select(C.fn.count("id").as("count")).executeTakeFirst(),n=await C.selectFrom("gift_cards").select(["status",C.fn.count("id").as("count")]).groupBy("status").execute(),{count:o}=await K("gift_cards",{count:{kind:"count"}},(d)=>d.whereRaw(V`current_balance / initial_balance < 0.25`)),{count:a}=await K("gift_cards",{count:{kind:"count"}},(d)=>d.whereRaw(V`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:s}=await K("gift_cards",{count:{kind:"count"}},(d)=>d.whereRaw(V`current_balance / initial_balance > 0.75`)),i=new Date;i.setDate(i.getDate()+30);let u=await C.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",We(i)).where("expiry_date",">=",t).selectAll().limit(5).execute(),c=await C.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:e,active:Number(r?.count||0),by_status:n.map((d)=>({status:d.status,count:Number(d.count)})),by_balance:{low:o,medium:a,high:s},expiring_soon:g(u),recently_used:g(c)}}async function Vi(e){let t=await io(e);if(!t)return{valid:!1,message:"Gift card not found"};if(!t.isActive||t.status!=="ACTIVE")return{valid:!1,balance:t.currentBalance,currency:t.currency,message:`Gift card is ${t.status.toLowerCase()}`};if(t.expiryDate){if(new Date(t.expiryDate)<new Date)return{valid:!1,balance:t.currentBalance,currency:t.currency,message:"Gift card has expired"}}return{valid:!0,balance:t.currentBalance,currency:t.currency}}async function qi(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await C.selectFrom("gift_cards").select(C.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(V`(expiry_date >= ${V.literal(We(t))} OR expiry_date IS NULL)`).where("created_at",">=",De(r)).where("created_at","<=",De(t)).executeTakeFirst(),s=await C.selectFrom("gift_cards").select(C.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(V`(expiry_date >= ${V.literal(We(o))} OR expiry_date IS NULL)`).where("created_at",">=",De(o)).where("created_at","<=",De(n)).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,d=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:d,days_range:e}}async function Hi(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await C.selectFrom("gift_cards").select([C.fn.sum("initial_balance").as("total_initial"),C.fn.sum("current_balance").as("total_balance"),C.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(V`(expiry_date >= ${V.literal(We(t))} OR expiry_date IS NULL)`).where("created_at",">=",De(r)).where("created_at","<=",De(t)).executeTakeFirst(),s=await C.selectFrom("gift_cards").select([C.fn.sum("initial_balance").as("total_initial"),C.fn.sum("current_balance").as("total_balance"),C.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(V`(expiry_date >= ${V.literal(We(o))} OR expiry_date IS NULL)`).where("created_at",">=",De(o)).where("created_at","<=",De(n)).executeTakeFirst(),i=Number(a?.total_initial||0),u=Number(a?.total_balance||0),c=Number(a?.card_count||0),d=Number(s?.total_initial||0),m=Number(s?.total_balance||0),p=Number(s?.card_count||0),y=i>0?(i-u)/i*100:0,_=d>0?(d-m)/d*100:0,w=c>0?i/c:0,b=c>0?u/c:0,h=i-d,x=u-m,v=c-p,A=d!==0?h/d*100:i>0?100:0,I=m!==0?x/m*100:u>0?100:0,be=p!==0?v/p*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:w,average_remaining_balance:b},previous_period:{total_initial_value:d,total_remaining_balance:m,utilization_rate:_,card_count:p},comparison:{initial_value:{difference:h,percentage:Math.abs(A),is_increase:h>=0},balance:{difference:x,percentage:Math.abs(I),is_increase:x>=0},card_count:{difference:v,percentage:Math.abs(be),is_increase:v>=0}},days_range:e}}async function Ki(){let{total_value:e}=await K("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:e}}async function Zi(){let{total_balance:e}=await K("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:e}}async function Yi(e){let t=await Kt.deleteFrom("gift_cards").where("id","=",e).executeTakeFirst();return f(t)>0}async function Xi(e){if(!e.length)return 0;let t=await Kt.deleteFrom("gift_cards").where("id","in",e).executeTakeFirst();return f(t)}async function eu(){let e=Qi(new Date),t=await Kt.deleteFrom("gift_cards").where("expiry_date","<",e).executeTakeFirst();return f(t)}async function tu(e){if(!await le(e))throw Error(`Gift card with ID ${e} not found`);return(await Dw(Kt.updateTable("gift_cards").set({is_active:!1,status:"DEACTIVATED",updated_at:Qi(new Date)}).where("id","=",e))).length>0}var{randomUUIDv7:kw}=globalThis.Bun;import{db as uo}from"@stacksjs/database/runtime";import{HttpError as ru}from"@stacksjs/error-handling";import{isUniqueViolation as Fw}from"@stacksjs/orm";async function nu(e){let t=e,r={...e,current_balance:t.current_balance??t.initial_balance,status:e.status||"ACTIVE",is_active:t.is_active??!0,uuid:kw()};try{let n=await uo.insertInto("gift_cards").values(r).executeTakeFirst(),o=ce(n);if(o!==void 0){let s=await uo.selectFrom("gift_cards").where("id","=",o).selectAll().executeTakeFirst();return l(s)}let a=await uo.selectFrom("gift_cards").where("uuid","=",r.uuid).selectAll().executeTakeFirst();return l(a,!0)}catch(n){if(n instanceof ru)throw n;if(Fw(n))throw new ru(409,"A gift card with this code already exists");if(n instanceof Error)throw Error(`Failed to create gift card: ${n.message}`);throw n}}import{db as su,mutationCount as Tw,parseSqlDateTime as ou,sqlHelpers as Sw}from"@stacksjs/database/runtime";import{env as Cw}from"@stacksjs/env";import{HttpError as au}from"@stacksjs/error-handling";import{formatDate as iu,isUniqueViolation as Ew}from"@stacksjs/orm";async function uu(e,t){if(!await le(e))return;try{return await su.updateTable("gift_cards").set({...t,updated_at:iu(new Date)}).where("id","=",e).execute(),await le(e)}catch(n){if(n instanceof au)throw n;if(Ew(n))throw new au(409,"A gift card with this code already exists");if(n instanceof Error)throw Error(`Failed to update gift card: ${n.message}`);throw n}}async function cu(e,t){if(!Number.isFinite(t))throw Error(`Gift card balance adjustment must be a finite number, got ${t}`);let r=Sw(Cw.DB_CONNECTION||"sqlite"),n=r.param,o=iu(new Date),a=t<0,s=t>0,i=s?`(status = 'ACTIVE' OR (status = 'USED' AND is_reloadable = ${r.boolTrue}))`:"status = 'ACTIVE'",u=[],c=(w)=>(u.push(w),n(u.length)),d=await su.unsafe(`UPDATE gift_cards
|
|
9
|
+
SET status = CASE WHEN current_balance + ${c(t)} = 0 THEN 'USED' WHEN 1 = 0 THEN status ELSE 'ACTIVE' END,
|
|
10
|
+
current_balance = current_balance + ${c(t)},
|
|
11
|
+
${a?`last_used_date = ${c(o)},
|
|
12
|
+
`:""}updated_at = ${c(o)}
|
|
13
|
+
WHERE id = ${c(e)}
|
|
14
14
|
AND is_active = ${r.boolTrue}
|
|
15
15
|
AND ${i}
|
|
16
|
-
AND (expiry_date IS NULL OR expiry_date >= ${c(
|
|
17
|
-
AND current_balance + ${c(
|
|
18
|
-
SET inventory_count = inventory_count + ${
|
|
19
|
-
updated_at = ${
|
|
20
|
-
WHERE id = ${
|
|
21
|
-
AND inventory_count + ${n(4)} >= 0`,parameters:[r,o,e,r]}}async function Ls(t,e,r,o){let n=Mp(Ap.DB_CONNECTION||"sqlite",e,r,o),a=await t.unsafe(n.query,n.parameters);return p(a)}var Gs=!1;function qs(t){let e=t,r=e?.message??"";return e?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function St(t){try{let e=await Fo.selectFrom("order_idempotency").where("idempotency_key","=",t).selectAll().executeTakeFirst();if(!e)return null;return await Fo.selectFrom("orders").where("id","=",e.order_id).selectAll().executeTakeFirst()??null}catch(e){if(qs(e)){if(!Gs)Gs=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw e}}async function Vs(t){if(t.idempotencyKey){let e=await St(t.idempotencyKey);if(e)return{ok:!0,order:e}}try{let e=await Fo.transaction(async(r)=>{let o=Ip(new Date),n=js(),a={...t.order,status:t.order.status||"PENDING",uuid:n,created_at:o,updated_at:o};await r.insertInto("orders").values(a).executeTakeFirst();let s=d(await r.selectFrom("orders").where("uuid","=",n).selectAll().executeTakeFirst(),!0),i=Number(s?.id);if(!Number.isSafeInteger(i)||i<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let u;if(t.items&&t.items.length>0){let m=t.items.map((f)=>{if(!Number.isInteger(f.productId)||f.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(f.quantity)||f.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(f.price)||f.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:i,product_id:f.productId,quantity:f.quantity,price:f.price,special_instructions:f.specialInstructions||null,created_at:o,updated_at:o}});await r.insertInto("order_items").values(m).execute(),u=w(await r.selectFrom("order_items").where("order_id","=",i).selectAll().execute())}let c;if(t.payment)try{let m=js();if(await r.insertInto("payments").values({...t.payment,order_id:i,uuid:m,created_at:o,updated_at:o}).executeTakeFirst(),c=d(await r.selectFrom("payments").where("uuid","=",m).selectAll().executeTakeFirst(),!0),!c)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(m){if(zs(m))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(m,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(t.inventory&&t.inventory.length>0)for(let m=0;m<t.inventory.length;m++){let{id:f,delta:h}=t.inventory[m];if(!Number.isFinite(h)||h===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await Ls(r,f,h,o))throw Object.assign(Error(`inventory adjust failed for product ${f}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(t.idempotencyKey)try{await r.insertInto("order_idempotency").values({idempotency_key:t.idempotencyKey,order_id:i,created_at:o}).execute()}catch(m){if(zs(m))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!qs(m))throw m}let l=d(await r.selectFrom("orders").where("id","=",i).selectAll().executeTakeFirst(),!0);if(!l)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:l,items:u,payment:c}});if(Et(e.order),e.payment)we(e.order,e.payment);return{ok:!0,order:e.order,items:e.items,payment:e.payment}}catch(e){if(e?.__placeFail){if(e.reason==="duplicate-idempotency-key"&&t.idempotencyKey){let r=await St(t.idempotencyKey);if(r)return{ok:!0,order:r}}return{ok:!1,reason:e.reason,failedAt:e.failedAt,error:e}}throw e}}Fe();import{db as ko}from"@stacksjs/database/runtime";import{formatDate as To}from"@stacksjs/orm";Fe();async function Zs(t,e){if(!await Y(t))return;try{return await ko.updateTable("orders").set({...e,updated_at:To(new Date)}).where("id","=",t).execute(),await Y(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update order: ${o.message}`);throw o}}async function Hs(t,e){let r=await Y(t);if(!r)throw Error(`Order with ID ${t} not found`);let o=r.status??"PENDING";if(!ve(o,e))throw Error(`[commerce/orders] illegal status transition ${o} \u2192 ${e}`);try{await ko.updateTable("orders").set({status:e,updated_at:To(new Date)}).where("id","=",t).execute();let n=await Y(t);if(n)Pe(e,n);return n}catch(n){if(n instanceof Error)throw TypeError(`Failed to update order status: ${n.message}`);throw n}}async function Ks(t,e,r){let o=await Y(t);if(!o)throw Error(`Order with ID ${t} not found`);let n={updated_at:To(new Date)};if(e!==void 0)n.delivery_address=e;if(r!==void 0)n.estimated_delivery_time=r;if(Object.keys(n).length===1)return o;try{return await ko.updateTable("orders").set(n).where("id","=",t).execute(),await Y(t)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery information: ${a.message}`);throw a}}Fe();import{db as Ze}from"@stacksjs/database/runtime";import{formatDate as Ct}from"@stacksjs/orm";async function Eo(t){let e=await Ze.selectFrom("payments").where("transaction_id","=",t).selectAll().executeTakeFirst();if(!e)return null;return await Ze.selectFrom("orders").where("id","=",e.order_id).selectAll().executeTakeFirst()??null}var Qs=!1;function Np(t){let e=t,r=e?.message??"";return e?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function So(t,e){try{return await e.insertInto("stripe_webhook_events").values({event_id:t,processed_at:Ct(new Date)}).execute(),!0}catch(r){if(r?.message?.includes("UNIQUE constraint")||r?.message?.includes("Duplicate entry"))return!1;if(Np(r)){if(!Qs)Qs=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing - Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw r}}async function Co(t){let r=t.data.object?.id;if(!r)return;await Ze.transaction(async(n)=>{if(!await So(t.id,n))return;let s=await n.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!s)return;let i=Ct(new Date);await n.updateTable("payments").set({status:"succeeded",updated_at:i}).where("id","=",s.id).execute();let u=await n.selectFrom("orders").where("id","=",s.order_id).selectAll().executeTakeFirst();if(u&&u.status==="PENDING")await n.updateTable("orders").set({status:"PROCESSING",updated_at:i}).where("id","=",u.id).execute()});let o=await Eo(r);if(o)await we(o)}async function Ao(t){let e=t.data.object,r=e?.id;if(!r)return;let n=e?.last_payment_error?.message??"payment failed";await Ze.transaction(async(s)=>{if(!await So(t.id,s))return;let u=await s.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!u)return;let c=Ct(new Date);await s.updateTable("payments").set({status:"failed",failure_reason:n,updated_at:c}).where("id","=",u.id).execute();let l=await s.selectFrom("orders").where("id","=",u.order_id).selectAll().executeTakeFirst();if(l&&l.status==="PENDING")await s.updateTable("orders").set({status:"CANCELLED",updated_at:c}).where("id","=",l.id).execute()});let a=await Eo(r);if(a)await qe(a,n)}async function Mo(t){let e=t.data.object,r=e?.payment_intent;if(!r)return;let o=e?.amount_refunded??0;await Ze.transaction(async(a)=>{if(!await So(t.id,a))return;let i=await a.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!i)return;let u=Ct(new Date);await a.updateTable("payments").set({status:"refunded",refund_amount:o,updated_at:u}).where("id","=",i.id).execute();let c=await a.selectFrom("orders").where("id","=",i.order_id).selectAll().executeTakeFirst();if(c&&c.status!=="REFUNDED")await a.updateTable("orders").set({status:"REFUNDED",updated_at:u}).where("id","=",c.id).execute()});let n=await Eo(r);if(n)await Ve(n,o)}async function Ys(){let t=await import("@stacksjs/payments").catch(()=>null);if(!t)return console.warn("[commerce/webhook] @stacksjs/payments not installed - Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:e,onCharge:r}=t;if(typeof e!=="function"||typeof r!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed - handlers NOT registered"),()=>{};return e({succeeded:Co,failed:Ao}),r({refunded:Mo}),()=>{}}import{db as Xs}from"@stacksjs/database/runtime";async function Jp(t){if(t.length===0)return new Map;let e=await Xs.selectFrom("products").where("id","in",t).select(["id","price"]).execute(),r=new Map;for(let o of e){let n=Number(o.price);if(Number.isFinite(n))r.set(o.id,Math.round(n))}return r}async function Bp(t){try{let e=await Xs.selectFrom("tax_rates").where("id","=",t).select(["rate"]).executeTakeFirst(),r=Number(e?.rate??0);return Number.isFinite(r)?r:0}catch{return 0}}async function ei(t){let e=t.items.map((b)=>b.productId),r=await Jp(e),o=t.taxRateId!=null?await Bp(t.taxRateId):0,n=0,a=[];for(let b of t.items){let _=b.unitPriceCents??r.get(b.productId)??0,D=Math.round(_*b.quantity);n+=D,a.push({productId:b.productId,quantity:b.quantity,unitPriceCents:_,lineCents:D})}let s=Math.max(0,t.discountCents??0),i=Math.max(0,n-s),u=Math.round(i*o),c=Math.max(0,t.shippingCents??0),l=n-s+u+c,m=t.maxDriftCents??5,f=!1,h=0;if(t.clientTotalCents!=null)h=Math.abs(l-t.clientTotalCents),f=h>m;return{subtotalCents:n,discountCents:s,taxCents:u,shippingCents:c,totalCents:l,resolvedItems:a,priceChanged:f,diffCents:h}}import{db as At,sqlHelpers as Op}from"@stacksjs/database/runtime";import{env as Up}from"@stacksjs/env";function ti(t,e={}){let r=t.length;if(r<=1)return{ok:!0,count:r};if(!e.allowMultiple)return{ok:!1,count:r,reason:"multiple-not-allowed"};let o=e.maxStacked??Number.POSITIVE_INFINITY;if(r>o)return{ok:!1,count:r,reason:"exceeds-max-stacked"};return{ok:!0,count:r}}async function Io(t,e){if(!Number.isFinite(e)||e<=0)return{ok:!1,productId:t,quantity:e,reason:"non-positive"};let r;try{r=await At.selectFrom("products").where("id","=",t).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:t,quantity:e}}if(!r)return{ok:!1,productId:t,quantity:e,reason:"product-missing"};let o=r.min_order_qty??null,n=r.max_order_qty??null;if(o!=null&&e<o)return{ok:!1,productId:t,quantity:e,reason:"below-min",bound:o};if(n!=null&&e>n)return{ok:!1,productId:t,quantity:e,reason:"above-max",bound:n};return{ok:!0,productId:t,quantity:e}}async function ri(t){for(let r of t){let o=await Io(r.productId,r.quantity);if(!o.ok)return o}let e=t[t.length-1]??{productId:0,quantity:0};return{ok:!0,productId:e.productId,quantity:e.quantity}}async function oi(t={}){let e=t.olderThanDays??30,r=t.limit??1000,n=new Date(Date.now()-e*24*60*60*1000).toISOString().slice(0,19).replace("T"," "),a=Op(Up.DB_CONNECTION||"sqlite").param;try{let s=await At.unsafe(`DELETE FROM carts WHERE updated_at < ${a(1)} AND id IN (SELECT id FROM carts WHERE updated_at < ${a(2)} LIMIT ${a(3)})`,[n,n,r]);return{deleted:p(s),cutoffAt:n}}catch{try{let s=await At.selectFrom("carts").where("updated_at","<",n).select(["id"]).limit(r).execute();if(s.length===0)return{deleted:0,cutoffAt:n};let i=s.map((c)=>c.id),u=await At.deleteFrom("carts").where("id","in",i).execute();return{deleted:p(u),cutoffAt:n}}catch{return{deleted:0,cutoffAt:n}}}}var Jo={};g(Jo,{bulkDestroy:()=>si,destroy:()=>ai,fetchAll:()=>ii,fetchById:()=>ye,fetchMonthlyPaymentTrends:()=>di,fetchPaymentStats:()=>ui,fetchPaymentStatsByMethod:()=>ci,recordRefund:()=>hi,store:()=>pi,update:()=>yi});import{db as ni}from"@stacksjs/database/runtime";async function ai(t){try{let e=await ni.deleteFrom("payments").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete payment: ${e.message}`);throw e}}async function si(t){if(!t.length)return 0;try{let e=await ni.deleteFrom("payments").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete payments: ${e.message}`);throw e}}import{db as E}from"@stacksjs/database/runtime";import{formatDate as U}from"@stacksjs/orm";async function ii(){let t=await E.selectFrom("payments").selectAll().execute();return w(t)}async function ye(t){let e=await E.selectFrom("payments").selectAll().where("id","=",t).executeTakeFirst();return d(e,!0)}async function ui(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=new Date(r);o.setDate(o.getDate()-1);let n=new Date(o);n.setDate(o.getDate()-t);let a=await E.selectFrom("payments").select([E.fn.count("id").as("transaction_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",U(r)).where("created_at","<=",U(e)).where("status","=","completed").executeTakeFirst(),s=await E.selectFrom("payments").select([E.fn.count("id").as("transaction_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",U(n)).where("created_at","<=",U(o)).where("status","=","completed").executeTakeFirst(),i=await E.selectFrom("payments").select(E.fn.count("id").as("count")).where("created_at",">=",U(r)).where("created_at","<=",U(e)).executeTakeFirst(),u=Number(a?.transaction_count||0),c=Number(a?.total_revenue||0),l=u>0?c/u:0,m=Number(s?.transaction_count||0),f=Number(s?.total_revenue||0),h=m>0?f/m:0,b=u-m,_=c-f,D=l-h,z=m>0?b/m*100:u>0?100:0,le=f>0?_/f*100:c>0?100:0,me=h>0?D/h*100:l>0?100:0,Re=Number(i?.count||0),G=Re>0?u/Re*100:0;return{total_transactions:u,total_revenue:c,average_transaction:l,successful_rate:G,comparison:{transactions:{difference:b,percentage:Math.abs(z),is_increase:b>=0},revenue:{difference:_,percentage:Math.abs(le),is_increase:_>=0},average:{difference:D,percentage:Math.abs(me),is_increase:D>=0}}}}async function ci(t=30){let e=new Date,r=new Date(e);r.setDate(e.getDate()-t);let o=await E.selectFrom("payments").select([E.fn.count("id").as("total_count"),E.fn.sum("amount").as("total_revenue")]).where("created_at",">=",U(r)).where("created_at","<=",U(e)).where("status","=","completed").executeTakeFirst(),n=Number(o?.total_count||0),a=await E.selectFrom("payments").select(["method",E.fn.count("id").as("count"),E.fn.sum("amount").as("revenue")]).where("created_at",">=",U(r)).where("created_at","<=",U(e)).where("status","=","completed").groupBy("method").execute(),s={};return a.forEach((i)=>{let u=Number(i.count||0),c=Number(i.revenue||0),l=n>0?u/n*100:0;s[i.method]={count:u,revenue:c,percentage_of_total:l}}),s}async function di(){let t=new Date,e=new Date(t);e.setMonth(t.getMonth()-11),e.setDate(1);let r=await E.selectFrom("payments").selectAll().where("created_at",">=",U(e)).where("status","=","completed").execute(),o={};for(let a of r){let s=a.created_at?new Date(String(a.created_at)):new Date,i=s.getFullYear(),u=s.getMonth()+1,c=`${i}-${String(u).padStart(2,"0")}`;if(!o[c])o[c]={year:i,month:u,transactions:0,revenue:0};o[c].transactions++,o[c].revenue+=Number(a.amount||0)}return Object.keys(o).sort().map((a)=>{let s=o[a],{transactions:i,revenue:u}=s,c=i>0?u/i:0;return{month:new Date(s.year,s.month-1,1).toLocaleString("default",{month:"short"}),year:s.year,transactions:i,revenue:u,average:c}})}var{randomUUIDv7:$p}=globalThis.Bun;import{db as li}from"@stacksjs/database/runtime";import{HttpError as mi}from"@stacksjs/error-handling";import{isUniqueViolation as Wp}from"@stacksjs/orm";async function pi(t){let e=$p(),r={...t,status:t.status||"pending",currency:t.currency||"USD",uuid:e};try{await li.insertInto("payments").values(r).executeTakeFirst();let o=await li.selectFrom("payments").where("uuid","=",e).selectAll().executeTakeFirst();return d(o,!0)}catch(o){if(o instanceof mi)throw o;if(Wp(o))throw new mi(409,"A payment with this transaction ID already exists");if(o instanceof Error){if(o.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${o.message}`)}throw o}}import{db as fi,mutationCount as Lp,sqlHelpers as jp}from"@stacksjs/database/runtime";import{env as zp}from"@stacksjs/env";import{formatDate as wi}from"@stacksjs/orm";async function yi(t,e){if(!await ye(t))return;try{return await fi.updateTable("payments").set({...e,updated_at:wi(new Date)}).where("id","=",t).execute(),await ye(t)}catch(o){if(o instanceof Error){if(o.message.includes("Duplicate entry")&&o.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${o.message}`)}throw o}}var Gp=new Set(["completed","succeeded","partiallyRefunded"]);async function hi(t,e){if(!Number.isSafeInteger(t)||t<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger(e)||e<=0)throw TypeError("Refund amount must be a positive integer in minor units");let o=jp(zp.DB_CONNECTION||"sqlite").param,n=wi(new Date),a=await fi.unsafe(`UPDATE payments
|
|
22
|
-
SET status = CASE WHEN COALESCE(refund_amount, 0) + ${
|
|
16
|
+
AND (expiry_date IS NULL OR expiry_date >= ${c(o)})
|
|
17
|
+
AND current_balance + ${c(t)} >= 0`,u);if(Tw(d)>0)return await le(e);let m=await le(e);if(!m)throw Error(`Gift card with ID ${e} not found`);let p=m;if(!p.is_active&&!p.isActive)throw Error("Gift card is not active");if(m.status==="USED"&&s&&!(p.is_reloadable??p.isReloadable))throw Error("Gift card is not reloadable");if(m.status!=="ACTIVE")throw Error("Gift card is not active");let y=ou(p.expiry_date??p.expiryDate),_=ou(o);if(y&&_&&y.getTime()<_.getTime())throw Error("Gift card has expired");if(t===0&&Number(p.current_balance??p.currentBalance)>=0)return m;throw Error("Insufficient gift card balance")}var Fo={};D(Fo,{bulkDestroy:()=>mu,bulkSoftDelete:()=>fu,calculateOrderMetrics:()=>_u,canTransition:()=>Le,cleanupAbandonedCarts:()=>Ju,compareOrdersByPeriod:()=>bu,destroy:()=>lu,downloadOrders:()=>wu,emitForStatus:()=>je,emitOrderCancelled:()=>dt,emitOrderCreated:()=>Xt,emitOrderDelivered:()=>yo,emitOrderPaid:()=>Ae,emitOrderRefunded:()=>lt,emitOrderShipped:()=>wo,exportOrders:()=>Yt,fetchAll:()=>mo,fetchById:()=>pe,fetchDailyOrderTrends:()=>xu,fetchRecent:()=>gu,fetchStats:()=>hu,findOrderByIdempotencyKey:()=>er,handleChargeRefunded:()=>Do,handlePaymentIntentFailed:()=>vo,handlePaymentIntentSucceeded:()=>Po,placeOrder:()=>Tu,recomputeOrderTotals:()=>Nu,registerCommerceWebhookHandlers:()=>Mu,softDelete:()=>pu,store:()=>Pu,storeOrdersExport:()=>yu,update:()=>Su,updateDeliveryInfo:()=>Eu,updateStatus:()=>Cu,validateCartQuantities:()=>Ou,validateCouponStacking:()=>$u,validateQuantityBounds:()=>ko});import{db as Zt,matchedRows as du}from"@stacksjs/database/runtime";async function lu(e){try{let t=await Zt.deleteFrom("orders").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete order: ${t.message}`);throw t}}async function pu(e){try{return(await du(Zt.updateTable("orders").set({status:"CANCELED"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete order: ${t.message}`);throw t}}async function mu(e){if(!e.length)return 0;try{let t=await Zt.deleteFrom("orders").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete orders: ${t.message}`);throw t}}async function fu(e){if(!e.length)return 0;try{return(await du(Zt.updateTable("orders").set({status:"CANCELED"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete orders: ${t.message}`);throw t}}import{db as Qt}from"@stacksjs/database/runtime";import{createSpreadsheet as Aw}from"ts-spreadsheets";async function Yt(e="csv"){let t=await Iw(),r=Nw(t);return Aw(r,{type:e})}var Mw=500;function lo(e,t=Mw){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}function po(e){let t=new Set;for(let r of e){let n=Number(r);if(Number.isSafeInteger(n)&&n>0)t.add(n)}return[...t]}async function Iw(){let e=await Qt.selectFrom("orders").selectAll().orderBy("id","asc").execute();if(e.length===0)return[];let t=po(e.map((i)=>i.id)),r=po(e.map((i)=>i.customer_id)),n=new Map;for(let i of lo(r)){let u=await Qt.selectFrom("customers").where("id","in",i).select(["id","name","email"]).execute();for(let c of u)n.set(Number(c.id),c)}let o=[];for(let i of lo(t)){let u=await Qt.selectFrom("order_items").where("order_id","in",i).select(["id","order_id","product_id","quantity","price"]).orderBy("id","asc").execute();o.push(...u)}let a=new Map;for(let i of lo(po(o.map((u)=>u.product_id)))){let u=await Qt.selectFrom("products").where("id","in",i).select(["id","name"]).execute();for(let c of u)a.set(Number(c.id),c)}let s=new Map;for(let i of o){let u=Number(i.order_id),c={...i,product:a.get(Number(i.product_id))},d=s.get(u);if(d)d.push(c);else s.set(u,[c])}return e.map((i)=>{let u=s.get(Number(i.id))??[],c=n.get(Number(i.customer_id));return{...i,customer:c,customer_name:c?.name??null,customer_email:c?.email??null,order_items:u,totalItems:u.reduce((d,m)=>d+Number(m.quantity??0),0),totalPrice:u.reduce((d,m)=>d+Number(m.price??0)*Number(m.quantity??0),0)}})}function Nw(e){let t=["Order ID","Customer","Date","Total","Status","Items"],r=e.map((n)=>{let o=typeof n.currency==="string"&&n.currency?n.currency:null,a=n.order_items?.map((s)=>`${s.product?.name||`Product #${s.product_id??"?"}`} (Qty: ${s.quantity}, Price: ${te(Number(s.price??0),o)})`).join(" | ")||"No Items";return[n.id,n.customer?.name||n.customer_name||"N/A",n.created_at,te(Number(n.total_amount??0),o),n.status,a]});return{headings:t,data:r}}async function wu(e="csv",t){let r=await Yt(e),n=`orders_export_${new Date().toISOString().split("T")[0]}.${e}`;return r.download(t||n)}async function yu(e="csv",t){let r=await Yt(e),n=`orders_export_${new Date().toISOString().split("T")[0]}.${e}`;r.store(t||n)}import{db as T}from"@stacksjs/database/runtime";async function mo(e){let t=T.selectFrom("orders").selectAll().orderBy("created_at","desc");if(e)t=t.limit(e);let r=g(await t.execute());return await Promise.all(r.map(async(n)=>{let o=await T.selectFrom("order_items").where("order_id","=",n.id).selectAll().execute();return{...n,items:o}}))}async function gu(e=10){return mo(e)}async function pe(e){let t=await T.selectFrom("orders").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function hu(){let e=await T.selectFrom("orders").select(T.fn.count("id").as("count")).executeTakeFirst(),t=await T.selectFrom("orders").select(["status",T.fn.count("id").as("count")]).groupBy("status").execute(),r=await T.selectFrom("orders").select(["order_type",T.fn.count("id").as("count")]).groupBy("order_type").execute(),n=g(await T.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute()),o=await Promise.all(n.map(async(s)=>{let i=await T.selectFrom("order_items").where("order_id","=",s.id).selectAll().execute();return{...s,items:i}})),a=await T.selectFrom("orders").select(T.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(e?.count||0),by_status:t,by_type:r,recent:o,revenue:Number(a?.total||0)}}async function bu(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await T.selectFrom("orders").select(T.fn.count("id").as("count")).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).executeTakeFirst(),s=await T.selectFrom("orders").select(T.fn.count("id").as("count")).where("created_at",">=",o.toISOString()).where("created_at","<=",n.toISOString()).executeTakeFirst(),i=Number(a?.count||0),u=Number(s?.count||0),c=i-u,d=u!==0?c/u*100:i>0?100:0;return{current_period:i,previous_period:u,difference:c,percentage_change:d,days_range:e}}async function _u(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await T.selectFrom("orders").select([T.fn.count("id").as("total_orders"),T.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).executeTakeFirst(),s=await T.selectFrom("orders").select([T.fn.count("id").as("total_orders"),T.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",o.toISOString()).where("created_at","<=",n.toISOString()).executeTakeFirst(),i=await T.selectFrom("orders").select(["status",T.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).groupBy("status").execute(),u=await T.selectFrom("orders").select(["order_type",T.fn.count("id").as("count")]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).groupBy("order_type").execute(),c=Number(a?.total_orders||0),d=Number(a?.total_revenue||0),m=c>0?d/c:0,p=Number(s?.total_orders||0),y=Number(s?.total_revenue||0),_=p>0?y/p:0,w=c-p,b=d-y,h=m-_,x=p!==0?w/p*100:c>0?100:0,v=y!==0?b/y*100:d>0?100:0,A=_!==0?h/_*100:m>0?100:0;return{current_period:{total_orders:c,total_revenue:d,average_order_value:m,orders_by_status:i.map((I)=>({status:I.status,count:Number(I.count)})),orders_by_type:u.map((I)=>({order_type:I.order_type,count:Number(I.count)}))},previous_period:{total_orders:p,total_revenue:y,average_order_value:_},comparison:{orders:{difference:w,percentage:Math.abs(x),is_increase:w>=0},revenue:{difference:b,percentage:Math.abs(v),is_increase:b>=0},average_order_value:{difference:h,percentage:Math.abs(A),is_increase:h>=0}},days_range:e}}async function xu(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=await T.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",r.toISOString()).where("created_at","<=",t.toISOString()).orderBy("created_at","asc").execute(),o=new Map;for(let a of n){let s=(a.created_at||"").split("T")[0]||"unknown",i=o.get(s)||{order_count:0,revenue:0};i.order_count++,i.revenue+=Number(a.total_amount||0),o.set(s,i)}return Array.from(o.entries()).map(([a,s])=>({date:a,order_count:s.order_count,revenue:s.revenue}))}var{randomUUIDv7:$w}=globalThis.Bun;import{db as fo}from"@stacksjs/database/runtime";import{formatDate as Ru}from"@stacksjs/orm";async function Pu(e){let t={...e,status:e.status||"PENDING",uuid:$w(),created_at:Ru(new Date),updated_at:Ru(new Date)};try{let r=await fo.insertInto("orders").values(t).executeTakeFirst(),n=ce(r);if(n!==void 0){let a=await fo.selectFrom("orders").where("id","=",n).selectAll().executeTakeFirst();return l(a,!0)}let o=await fo.selectFrom("orders").where("uuid","=",t.uuid).selectAll().executeTakeFirst();return l(o,!0)}catch(r){if(r instanceof Error)throw Error(`Failed to create order: ${r.message}`);throw r}}var{randomUUIDv7:vu}=globalThis.Bun;import{db as ho}from"@stacksjs/database/runtime";ze();import{formatDate as Lw,isUniqueViolation as Du}from"@stacksjs/orm";import{sqlHelpers as Bw}from"@stacksjs/database/runtime";import{env as Uw}from"@stacksjs/env";function Ww(e,t,r,n){let o=Bw(e).param;return{query:`UPDATE products
|
|
18
|
+
SET inventory_count = inventory_count + ${o(1)},
|
|
19
|
+
updated_at = ${o(2)}
|
|
20
|
+
WHERE id = ${o(3)}
|
|
21
|
+
AND inventory_count + ${o(4)} >= 0`,parameters:[r,n,t,r]}}async function go(e,t,r,n){let o=Ww(Uw.DB_CONNECTION||"sqlite",t,r,n),a=await e.unsafe(o.query,o.parameters);return f(a)}var ku=!1;function Fu(e){let t=e,r=t?.message??"";return t?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function er(e){try{let t=await ho.selectFrom("order_idempotency").where("idempotency_key","=",e).selectAll().executeTakeFirst();if(!t)return null;return await ho.selectFrom("orders").where("id","=",t.order_id).selectAll().executeTakeFirst()??null}catch(t){if(Fu(t)){if(!ku)ku=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw t}}async function Tu(e){if(e.idempotencyKey){let t=await er(e.idempotencyKey);if(t)return{ok:!0,order:t}}try{let t=await ho.transaction(async(r)=>{let n=Lw(new Date),o=vu(),a={...e.order,status:e.order.status||"PENDING",uuid:o,created_at:n,updated_at:n};await r.insertInto("orders").values(a).executeTakeFirst();let s=l(await r.selectFrom("orders").where("uuid","=",o).selectAll().executeTakeFirst(),!0),i=Number(s?.id);if(!Number.isSafeInteger(i)||i<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let u;if(e.items&&e.items.length>0){let m=e.items.map((p)=>{if(!Number.isInteger(p.productId)||p.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(p.quantity)||p.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(p.price)||p.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:i,product_id:p.productId,quantity:p.quantity,price:p.price,special_instructions:p.specialInstructions||null,created_at:n,updated_at:n}});await r.insertInto("order_items").values(m).execute(),u=g(await r.selectFrom("order_items").where("order_id","=",i).selectAll().execute())}let c;if(e.payment)try{let m=vu();if(await r.insertInto("payments").values({...e.payment,order_id:i,uuid:m,created_at:n,updated_at:n}).executeTakeFirst(),c=l(await r.selectFrom("payments").where("uuid","=",m).selectAll().executeTakeFirst(),!0),!c)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(m){if(Du(m))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(m,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(e.inventory&&e.inventory.length>0)for(let m=0;m<e.inventory.length;m++){let{id:p,delta:y}=e.inventory[m];if(!Number.isFinite(y)||y===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await go(r,p,y,n))throw Object.assign(Error(`inventory adjust failed for product ${p}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(e.idempotencyKey)try{await r.insertInto("order_idempotency").values({idempotency_key:e.idempotencyKey,order_id:i,created_at:n}).execute()}catch(m){if(Du(m))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!Fu(m))throw m}let d=l(await r.selectFrom("orders").where("id","=",i).selectAll().executeTakeFirst(),!0);if(!d)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:d,items:u,payment:c}});if(Xt(t.order),t.payment)Ae(t.order,t.payment);return{ok:!0,order:t.order,items:t.items,payment:t.payment}}catch(t){if(t?.__placeFail){if(t.reason==="duplicate-idempotency-key"&&e.idempotencyKey){let r=await er(e.idempotencyKey);if(r)return{ok:!0,order:r}}return{ok:!1,reason:t.reason,failedAt:t.failedAt,error:t}}throw t}}ze();import{db as bo}from"@stacksjs/database/runtime";import{formatDate as _o}from"@stacksjs/orm";ze();async function Su(e,t){if(!await pe(e))return;try{return await bo.updateTable("orders").set({...t,updated_at:_o(new Date)}).where("id","=",e).execute(),await pe(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update order: ${n.message}`);throw n}}async function Cu(e,t){let r=await pe(e);if(!r)throw Error(`Order with ID ${e} not found`);let n=r.status??"PENDING";if(!Le(n,t))throw Error(`[commerce/orders] illegal status transition ${n} \u2192 ${t}`);try{await bo.updateTable("orders").set({status:t,updated_at:_o(new Date)}).where("id","=",e).execute();let o=await pe(e);if(o)je(t,o);return o}catch(o){if(o instanceof Error)throw TypeError(`Failed to update order status: ${o.message}`);throw o}}async function Eu(e,t,r){let n=await pe(e);if(!n)throw Error(`Order with ID ${e} not found`);let o={updated_at:_o(new Date)};if(t!==void 0)o.delivery_address=t;if(r!==void 0)o.estimated_delivery_time=r;if(Object.keys(o).length===1)return n;try{return await bo.updateTable("orders").set(o).where("id","=",e).execute(),await pe(e)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery information: ${a.message}`);throw a}}ze();import{db as pt}from"@stacksjs/database/runtime";import{formatDate as tr}from"@stacksjs/orm";async function xo(e){let t=await pt.selectFrom("payments").where("transaction_id","=",e).selectAll().executeTakeFirst();if(!t)return null;return await pt.selectFrom("orders").where("id","=",t.order_id).selectAll().executeTakeFirst()??null}var Au=!1;function jw(e){let t=e,r=t?.message??"";return t?.code==="42P01"||r.includes("no such table")||r.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(r)}async function Ro(e,t){try{return await t.insertInto("stripe_webhook_events").values({event_id:e,processed_at:tr(new Date)}).execute(),!0}catch(r){if(r?.message?.includes("UNIQUE constraint")||r?.message?.includes("Duplicate entry"))return!1;if(jw(r)){if(!Au)Au=!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 Po(e){let r=e.data.object?.id;if(!r)return;await pt.transaction(async(o)=>{if(!await Ro(e.id,o))return;let s=await o.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!s)return;let i=tr(new Date);await o.updateTable("payments").set({status:"succeeded",updated_at:i}).where("id","=",s.id).execute();let u=await o.selectFrom("orders").where("id","=",s.order_id).selectAll().executeTakeFirst();if(u&&u.status==="PENDING")await o.updateTable("orders").set({status:"PROCESSING",updated_at:i}).where("id","=",u.id).execute()});let n=await xo(r);if(n)await Ae(n)}async function vo(e){let t=e.data.object,r=t?.id;if(!r)return;let o=t?.last_payment_error?.message??"payment failed";await pt.transaction(async(s)=>{if(!await Ro(e.id,s))return;let u=await s.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!u)return;let c=tr(new Date);await s.updateTable("payments").set({status:"failed",failure_reason:o,updated_at:c}).where("id","=",u.id).execute();let d=await s.selectFrom("orders").where("id","=",u.order_id).selectAll().executeTakeFirst();if(d&&d.status==="PENDING")await s.updateTable("orders").set({status:"CANCELLED",updated_at:c}).where("id","=",d.id).execute()});let a=await xo(r);if(a)await dt(a,o)}async function Do(e){let t=e.data.object,r=t?.payment_intent;if(!r)return;let n=t?.amount_refunded??0;await pt.transaction(async(a)=>{if(!await Ro(e.id,a))return;let i=await a.selectFrom("payments").where("transaction_id","=",r).selectAll().executeTakeFirst();if(!i)return;let u=tr(new Date);await a.updateTable("payments").set({status:"refunded",refund_amount:n,updated_at:u}).where("id","=",i.id).execute();let c=await a.selectFrom("orders").where("id","=",i.order_id).selectAll().executeTakeFirst();if(c&&c.status!=="REFUNDED")await a.updateTable("orders").set({status:"REFUNDED",updated_at:u}).where("id","=",c.id).execute()});let o=await xo(r);if(o)await lt(o,n)}async function Mu(){let e=await import("@stacksjs/payments").catch(()=>null);if(!e)return console.warn("[commerce/webhook] @stacksjs/payments not installed - Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:t,onCharge:r}=e;if(typeof t!=="function"||typeof r!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed - handlers NOT registered"),()=>{};return t({succeeded:Po,failed:vo}),r({refunded:Do}),()=>{}}import{db as Iu}from"@stacksjs/database/runtime";async function zw(e){if(e.length===0)return new Map;let t=await Iu.selectFrom("products").where("id","in",e).select(["id","price"]).execute(),r=new Map;for(let n of t){let o=Number(n.price);if(Number.isFinite(o))r.set(n.id,Math.round(o))}return r}async function Gw(e){try{let t=await Iu.selectFrom("tax_rates").where("id","=",e).select(["rate"]).executeTakeFirst(),r=Number(t?.rate??0);return Number.isFinite(r)?r:0}catch{return 0}}async function Nu(e){let t=e.items.map((_)=>_.productId),r=await zw(t),n=e.taxRateId!=null?await Gw(e.taxRateId):0,o=0,a=[];for(let _ of e.items){let w=_.unitPriceCents??r.get(_.productId)??0,b=Math.round(w*_.quantity);o+=b,a.push({productId:_.productId,quantity:_.quantity,unitPriceCents:w,lineCents:b})}let s=Math.max(0,e.discountCents??0),i=Math.max(0,o-s),u=Math.round(i*n),c=Math.max(0,e.shippingCents??0),d=o-s+u+c,m=e.maxDriftCents??5,p=!1,y=0;if(e.clientTotalCents!=null)y=Math.abs(d-e.clientTotalCents),p=y>m;return{subtotalCents:o,discountCents:s,taxCents:u,shippingCents:c,totalCents:d,resolvedItems:a,priceChanged:p,diffCents:y}}import{db as rr,sqlHelpers as Vw}from"@stacksjs/database/runtime";import{env as qw}from"@stacksjs/env";function $u(e,t={}){let r=e.length;if(r<=1)return{ok:!0,count:r};if(!t.allowMultiple)return{ok:!1,count:r,reason:"multiple-not-allowed"};let n=t.maxStacked??Number.POSITIVE_INFINITY;if(r>n)return{ok:!1,count:r,reason:"exceeds-max-stacked"};return{ok:!0,count:r}}async function ko(e,t){if(!Number.isFinite(t)||t<=0)return{ok:!1,productId:e,quantity:t,reason:"non-positive"};let r;try{r=await rr.selectFrom("products").where("id","=",e).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:e,quantity:t}}if(!r)return{ok:!1,productId:e,quantity:t,reason:"product-missing"};let n=r.min_order_qty??null,o=r.max_order_qty??null;if(n!=null&&t<n)return{ok:!1,productId:e,quantity:t,reason:"below-min",bound:n};if(o!=null&&t>o)return{ok:!1,productId:e,quantity:t,reason:"above-max",bound:o};return{ok:!0,productId:e,quantity:t}}async function Ou(e){for(let r of e){let n=await ko(r.productId,r.quantity);if(!n.ok)return n}let t=e[e.length-1]??{productId:0,quantity:0};return{ok:!0,productId:t.productId,quantity:t.quantity}}async function Ju(e={}){let t=e.olderThanDays??30,r=e.limit??1000,o=new Date(Date.now()-t*24*60*60*1000).toISOString().slice(0,19).replace("T"," "),a=Vw(qw.DB_CONNECTION||"sqlite").param;try{let s=await rr.unsafe(`DELETE FROM carts WHERE updated_at < ${a(1)} AND id IN (SELECT id FROM carts WHERE updated_at < ${a(2)} LIMIT ${a(3)})`,[o,o,r]);return{deleted:f(s),cutoffAt:o}}catch{try{let s=await rr.selectFrom("carts").where("updated_at","<",o).select(["id"]).limit(r).execute();if(s.length===0)return{deleted:0,cutoffAt:o};let i=s.map((c)=>c.id),u=await rr.deleteFrom("carts").where("id","in",i).execute();return{deleted:f(u),cutoffAt:o}}catch{return{deleted:0,cutoffAt:o}}}}var To={};D(To,{bulkDestroy:()=>Wu,destroy:()=>Uu,fetchAll:()=>Lu,fetchById:()=>Me,fetchMonthlyPaymentTrends:()=>Gu,fetchPaymentStats:()=>ju,fetchPaymentStatsByMethod:()=>zu,recordRefund:()=>Yu,store:()=>Hu,update:()=>Qu});import{db as Bu}from"@stacksjs/database/runtime";async function Uu(e){try{let t=await Bu.deleteFrom("payments").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete payment: ${t.message}`);throw t}}async function Wu(e){if(!e.length)return 0;try{let t=await Bu.deleteFrom("payments").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete payments: ${t.message}`);throw t}}import{db as B}from"@stacksjs/database/runtime";import{formatDate as Y}from"@stacksjs/orm";async function Lu(){let e=await B.selectFrom("payments").selectAll().execute();return g(e)}async function Me(e){let t=await B.selectFrom("payments").selectAll().where("id","=",e).executeTakeFirst();return l(t,!0)}async function ju(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=new Date(r);n.setDate(n.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-e);let a=await B.selectFrom("payments").select([B.fn.count("id").as("transaction_count"),B.fn.sum("amount").as("total_revenue")]).where("created_at",">=",Y(r)).where("created_at","<=",Y(t)).where("status","=","completed").executeTakeFirst(),s=await B.selectFrom("payments").select([B.fn.count("id").as("transaction_count"),B.fn.sum("amount").as("total_revenue")]).where("created_at",">=",Y(o)).where("created_at","<=",Y(n)).where("status","=","completed").executeTakeFirst(),i=await B.selectFrom("payments").select(B.fn.count("id").as("count")).where("created_at",">=",Y(r)).where("created_at","<=",Y(t)).executeTakeFirst(),u=Number(a?.transaction_count||0),c=Number(a?.total_revenue||0),d=u>0?c/u:0,m=Number(s?.transaction_count||0),p=Number(s?.total_revenue||0),y=m>0?p/m:0,_=u-m,w=c-p,b=d-y,h=m>0?_/m*100:u>0?100:0,x=p>0?w/p*100:c>0?100:0,v=y>0?b/y*100:d>0?100:0,A=Number(i?.count||0),I=A>0?u/A*100:0;return{total_transactions:u,total_revenue:c,average_transaction:d,successful_rate:I,comparison:{transactions:{difference:_,percentage:Math.abs(h),is_increase:_>=0},revenue:{difference:w,percentage:Math.abs(x),is_increase:w>=0},average:{difference:b,percentage:Math.abs(v),is_increase:b>=0}}}}async function zu(e=30){let t=new Date,r=new Date(t);r.setDate(t.getDate()-e);let n=await B.selectFrom("payments").select([B.fn.count("id").as("total_count"),B.fn.sum("amount").as("total_revenue")]).where("created_at",">=",Y(r)).where("created_at","<=",Y(t)).where("status","=","completed").executeTakeFirst(),o=Number(n?.total_count||0),a=await B.selectFrom("payments").select(["method",B.fn.count("id").as("count"),B.fn.sum("amount").as("revenue")]).where("created_at",">=",Y(r)).where("created_at","<=",Y(t)).where("status","=","completed").groupBy("method").execute(),s={};return a.forEach((i)=>{let u=Number(i.count||0),c=Number(i.revenue||0),d=o>0?u/o*100:0;s[i.method]={count:u,revenue:c,percentage_of_total:d}}),s}async function Gu(){let e=new Date,t=new Date(e);t.setMonth(e.getMonth()-11),t.setDate(1);let r=await B.selectFrom("payments").selectAll().where("created_at",">=",Y(t)).where("status","=","completed").execute(),n={};for(let a of r){let s=a.created_at?new Date(String(a.created_at)):new Date,i=s.getFullYear(),u=s.getMonth()+1,c=`${i}-${String(u).padStart(2,"0")}`;if(!n[c])n[c]={year:i,month:u,transactions:0,revenue:0};n[c].transactions++,n[c].revenue+=Number(a.amount||0)}return Object.keys(n).sort().map((a)=>{let s=n[a],{transactions:i,revenue:u}=s,c=i>0?u/i:0;return{month:new Date(s.year,s.month-1,1).toLocaleString("default",{month:"short"}),year:s.year,transactions:i,revenue:u,average:c}})}var{randomUUIDv7:Hw}=globalThis.Bun;import{db as Vu}from"@stacksjs/database/runtime";import{HttpError as qu}from"@stacksjs/error-handling";import{isUniqueViolation as Kw}from"@stacksjs/orm";async function Hu(e){let t=Hw(),r={...e,status:e.status||"pending",currency:e.currency||"USD",uuid:t};try{await Vu.insertInto("payments").values(r).executeTakeFirst();let n=await Vu.selectFrom("payments").where("uuid","=",t).selectAll().executeTakeFirst();return l(n,!0)}catch(n){if(n instanceof qu)throw n;if(Kw(n))throw new qu(409,"A payment with this transaction ID already exists");if(n instanceof Error){if(n.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${n.message}`)}throw n}}import{db as Ku,mutationCount as Zw,sqlHelpers as Qw}from"@stacksjs/database/runtime";import{env as Yw}from"@stacksjs/env";import{formatDate as Zu}from"@stacksjs/orm";async function Qu(e,t){if(!await Me(e))return;try{return await Ku.updateTable("payments").set({...t,updated_at:Zu(new Date)}).where("id","=",e).execute(),await Me(e)}catch(n){if(n instanceof Error){if(n.message.includes("Duplicate entry")&&n.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${n.message}`)}throw n}}var Xw=new Set(["completed","succeeded","partiallyRefunded"]);async function Yu(e,t){if(!Number.isSafeInteger(e)||e<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger(t)||t<=0)throw TypeError("Refund amount must be a positive integer in minor units");let n=Qw(Yw.DB_CONNECTION||"sqlite").param,o=Zu(new Date),a=await Ku.unsafe(`UPDATE payments
|
|
22
|
+
SET status = CASE WHEN COALESCE(refund_amount, 0) + ${n(1)} = amount THEN 'refunded'
|
|
23
23
|
WHEN 1 = 0 THEN status ELSE 'partiallyRefunded' END,
|
|
24
|
-
refund_amount = COALESCE(refund_amount, 0) + ${
|
|
25
|
-
updated_at = ${
|
|
26
|
-
WHERE id = ${
|
|
24
|
+
refund_amount = COALESCE(refund_amount, 0) + ${n(2)},
|
|
25
|
+
updated_at = ${n(3)}
|
|
26
|
+
WHERE id = ${n(4)}
|
|
27
27
|
AND status IN ('completed', 'succeeded', 'partiallyRefunded')
|
|
28
|
-
AND COALESCE(refund_amount, 0) + ${o(5)} <= amount`,[e,e,n,t,e]);if(Lp(a)>0){let l=await ye(t);if(l)return l;throw Error(`Payment with ID ${t} disappeared during refund`)}let s=await ye(t);if(!s)throw Error(`Payment with ID ${t} not found`);let i=String(s.status||"");if(!Gp.has(i))throw Error(`Payment status ${i||"unknown"} cannot be refunded`);let u=s,c=Number(s.amount||0)-Number(u.refundAmount??u.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${c} minor units`)}var jo={};g(jo,{categories:()=>Nt,default:()=>cf,items:()=>Jt,manufacturers:()=>Bt,reviews:()=>Ot,units:()=>Wt,variants:()=>Lt});var Nt={};g(Nt,{bulkRemove:()=>Ti,compareCategoryGrowth:()=>vi,deactivate:()=>Si,deactivateChildCategories:()=>Ci,fetchActive:()=>bi,fetchAll:()=>Bo,fetchByDisplayOrder:()=>xi,fetchById:()=>S,fetchByName:()=>gi,fetchCategoryTree:()=>Pi,fetchChildCategories:()=>Ri,fetchRootCategories:()=>_i,fetchStats:()=>Di,findOrCreateByName:()=>Mi,remove:()=>ki,removeChildCategories:()=>Ei,store:()=>Oo,update:()=>Ii,updateActiveStatus:()=>Ji,updateDisplayOrder:()=>Ni,updateParent:()=>Bi});import{db as Ke,matchedRows as qp}from"@stacksjs/database/runtime";import{formatDate as Fi}from"@stacksjs/orm";import{db as P}from"@stacksjs/database/runtime";import{formatDate as He}from"@stacksjs/orm";async function Bo(){return await P.selectFrom("categories").selectAll().execute()}async function S(t){return await P.selectFrom("categories").where("id","=",t).selectAll().executeTakeFirst()}async function gi(t){return await P.selectFrom("categories").where("name","=",t).selectAll().executeTakeFirst()}async function bi(){return await P.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function _i(){return await P.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function Ri(t){return await P.selectFrom("categories").where("parent_category_id","=",t).where("is_active","=",!0).selectAll().execute()}async function xi(t=!0){let e=P.selectFrom("categories").where("is_active","=",!0).selectAll();if(t)return await e.orderBy("display_order","asc").execute();else return await e.orderBy("display_order","desc").execute()}async function Di(){let t=await P.selectFrom("categories").select(P.fn.count("id").as("count")).executeTakeFirst(),e=await P.selectFrom("categories").where("is_active","=",!0).select(P.fn.count("id").as("count")).executeTakeFirst(),r=await P.selectFrom("categories").whereNull("parent_category_id").select(P.fn.count("id").as("count")).executeTakeFirst(),o=await P.selectFrom("categories").whereNotNull("image_url").select(P.fn.count("id").as("count")).executeTakeFirst(),n=new Date;n.setDate(n.getDate()-30);let a=He(n),s=await P.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await P.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",P.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(t?.count||0),active:Number(e?.count||0),root_categories:Number(r?.count||0),child_categories:Number(t?.count||0)-Number(r?.count||0),with_images:Number(o?.count||0),recently_added:s,top_parent_categories:i.map((u)=>({id:String(u.parent_category_id||""),name:String(u.parent_name||""),child_count:Number(u.child_count)}))}}async function vi(t=30){let e=new Date,r=He(e),o=new Date;o.setDate(e.getDate()-t);let n=He(o),a=new Date(o);a.setDate(a.getDate()-1);let s=He(a),i=new Date(a);i.setDate(a.getDate()-t);let u=He(i),c=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",r).executeTakeFirst(),l=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),m=Number(c?.count||0),f=Number(l?.count||0),h=m-f,b=f!==0?h/f*100:m>0?100:0;return{current_period:m,previous_period:f,difference:h,percentage_change:b,days_range:t}}async function Pi(){let t=await Bo(),e=new Map;t.forEach((n)=>{e.set(n.id,{...n,children:[]})});let r=[];t.forEach((n)=>{let a=e.get(n.id);if(n.parent_category_id){let s=e.get(n.parent_category_id);if(s)s.children.push(a)}else r.push(a)}),r.sort((n,a)=>n.display_order-a.display_order);let o=(n)=>{n.sort((a,s)=>a.display_order-s.display_order),n.forEach((a)=>{if(a.children.length>0)o(a.children)})};return o(r),r}async function ki(t){let e=await Ke.deleteFrom("categories").where("id","=",t).executeTakeFirst();return p(e)>0}async function Ti(t){if(!t.length)return 0;let e=await Ke.deleteFrom("categories").where("id","in",t).executeTakeFirst();return p(e)}async function Ei(t){let e=await Ke.deleteFrom("categories").where("parent_category_id","=",t).executeTakeFirst();return p(e)}async function Si(t){if(!await S(t))throw Error(`Category with ID ${t} not found`);let r=await Ke.updateTable("categories").set({is_active:!1,updated_at:Fi(new Date)}).where("id","=",t).returning("id").executeTakeFirst();return Boolean(r)}async function Ci(t){return(await qp(Ke.updateTable("categories").set({is_active:!1,updated_at:Fi(new Date)}).where("parent_category_id","=",t))).length}var{randomUUIDv7:Vp}=globalThis.Bun;import{db as Ai}from"@stacksjs/database/runtime";import{HttpError as Mt}from"@stacksjs/error-handling";import{isUniqueViolation as Zp}from"@stacksjs/orm";import{slug as Hp}from"@stacksjs/strings";async function Oo(t){try{let e=t.parent_category_id?Number(t.parent_category_id):void 0;if(e!==void 0&&(!Number.isSafeInteger(e)||e<=0))throw new Mt(422,"Parent category ID must be a positive integer");if(e&&!await S(e))throw new Mt(422,`Parent category with ID ${t.parent_category_id} not found`);let r={...t,uuid:Vp(),is_active:t.is_active??!0,parent_category_id:t.parent_category_id||null},o=await Ai.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create category");return o}catch(e){if(e instanceof Mt)throw e;if(Zp(e))throw new Mt(409,"A category with this name or slug already exists");if(e instanceof Error)throw Error(`Failed to create category: ${e.message}`);throw e}}async function Mi(t){if(!t.name)throw Error("Name is required");let e=await Ai.selectFrom("categories").selectAll().where("name","=",t.name).executeTakeFirst();if(e)return e;let r={name:t.name,slug:Hp(t.name),is_active:t.is_active??!0,display_order:0};return await Oo(r)}import{db as Qe}from"@stacksjs/database/runtime";import{HttpError as ke}from"@stacksjs/error-handling";import{formatDate as It,isUniqueViolation as Kp}from"@stacksjs/orm";async function Ii(t,e){if(!await S(t))return;if(Object.hasOwn(e,"parent_category_id")){let o=e.parent_category_id?Number(e.parent_category_id):void 0;if(o!==void 0&&(!Number.isSafeInteger(o)||o<=0))throw new ke(422,"Parent category ID must be a positive integer");if(o===t)throw new ke(422,"A category cannot be its own parent");if(o&&!await S(o))throw new ke(422,`Parent category with ID ${e.parent_category_id} not found`);if(o&&await Oi(t,String(o)))throw new ke(422,"This operation would create a circular category hierarchy")}try{let o=Object.hasOwn(e,"parent_category_id")?{parent_category_id:e.parent_category_id||null}:{},n=await Qe.updateTable("categories").set({...e,...o,updated_at:It(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return n}catch(o){if(o instanceof ke)throw o;if(Kp(o))throw new ke(409,"A category with this name or slug already exists");if(o instanceof Error)throw Error(`Failed to update category: ${o.message}`);throw o}}async function Ni(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);try{return await Qe.updateTable("categories").set({display_order:e,updated_at:It(new Date)}).where("id","=",t).execute(),await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category display order: ${o.message}`);throw o}}async function Ji(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);try{return await Qe.updateTable("categories").set({is_active:e,updated_at:It(new Date)}).where("id","=",t).execute(),await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category active status: ${o.message}`);throw o}}async function Bi(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);if(e){let o=Number(e);if(o===t)throw Error("A category cannot be its own parent");if(!await S(o))throw Error(`Parent category with ID ${e} not found`);if(await Oi(t,e))throw Error("This operation would create a circular reference in the category hierarchy")}try{let o={updated_at:It(new Date)};if(e===null)await Qe.updateTable("categories").set({...o,parent_category_id:null}).where("id","=",t).execute();else await Qe.updateTable("categories").set({...o,parent_category_id:e}).where("id","=",t).execute();return await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category parent: ${o.message}`);throw o}}async function Oi(t,e){let r=Number(e),o=new Set;while(r){if(o.has(r))return!0;if(r===t)return!0;o.add(r);let n=await S(r),a=n?.parent_category_id;if(!n||!a)return!1;r=Number(a)}return!1}var Jt={};g(Jt,{bulkDestroy:()=>Wi,bulkStore:()=>Zi,destroy:()=>$i,fetchAll:()=>Li,fetchById:()=>ee,fetchTopProducts:()=>zi,store:()=>Vi,update:()=>Hi,updateAvailability:()=>Ki,updateInventory:()=>Qi});import{db as Ui}from"@stacksjs/database/runtime";async function $i(t){try{let e=await Ui.deleteFrom("products").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product item: ${e.message}`);throw e}}async function Wi(t){if(!t.length)return 0;try{let e=await Ui.deleteFrom("products").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product items: ${e.message}`);throw e}}import{db as X,sql as Qp}from"@stacksjs/database/runtime";async function ee(t){let e=await X.selectFrom("products").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.manufacturer_id)r=await X.selectFrom("manufacturers").where("id","=",e.manufacturer_id).selectAll().executeTakeFirst();if(e.category_id)o=await X.selectFrom("categories").where("id","=",e.category_id).selectAll().executeTakeFirst();return{...e,manufacturer:r,category:o}}return}async function Li(){let t=await X.selectFrom("products").selectAll().execute(),e=t.map((c)=>c.manufacturer_id).filter((c)=>c!==null&&c!==void 0),r=t.map((c)=>c.category_id).filter((c)=>c!==null&&c!==void 0),o=X.selectFrom("manufacturers"),n=X.selectFrom("categories");if(e.length>0)o=o.where("id","in",e);if(r.length>0)n=n.where("id","in",r);let a=await o.selectAll().execute(),s=await n.selectAll().execute(),i=a.reduce((c,l)=>(c[l.id]=l,c),{}),u=s.reduce((c,l)=>(c[l.id]=l,c),{});return t.map((c)=>({...c,manufacturer:c.manufacturer_id?i[c.manufacturer_id]:null,category:c.category_id?u[c.category_id]:null}))}async function ji(t){try{let e=await X.selectFrom("products").selectAll().where("uuid","=",t).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get product by UUID: ${e.message}`);throw e}}async function zi(t=5){try{return(await X.selectFrom("order_items").innerJoin("products","products.id","=","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",X.fn.sum("order_items.quantity").as("units_sold"),Qp`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(t).execute()).map((r)=>({id:Number(r.id),name:String(r.name??"Unnamed product"),units_sold:Number(r.units_sold??0),revenue:Number(r.revenue??0),inventory_count:Number(r.inventory_count??0)}))}catch(e){if(e instanceof Error)throw TypeError(`Failed to fetch top products: ${e.message}`);throw e}}var{randomUUIDv7:Gi}=globalThis.Bun;import{db as qi}from"@stacksjs/database/runtime";async function Vi(t){try{let e={...t,uuid:Gi()},r=await qi.insertInto("products").values(e).executeTakeFirst();if(!r)throw Error("Failed to create product item");let o=H(r),n=o!==void 0?await ee(o):await ji(e.uuid);if(!n)throw Error("Failed to create product item");return n}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product item: ${e.message}`);throw e}}async function Zi(t){if(!t.length)return 0;let e=0;try{return await qi.transaction(async(r)=>{for(let o of t){let n={...o,uuid:Gi()};await r.insertInto("products").values(n).execute(),e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product items in bulk: ${r.message}`);throw r}}import{db as Uo,matchedRows as g_}from"@stacksjs/database/runtime";import{formatDate as $o}from"@stacksjs/orm";async function Hi(t,e){try{if(!t)throw Error("Product item ID is required for update");let r=await Uo.updateTable("products").set({...e,updated_at:$o(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function Ki(t,e){if(!await ee(t))throw Error(`Product item with ID ${t} not found`);try{return await Uo.updateTable("products").set({is_available:e,updated_at:$o(new Date)}).where("id","=",t).execute(),await ee(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update product item availability: ${o.message}`);throw o}}async function Qi(t,e){let r=await ee(t);if(!r)throw Error(`Product item with ID ${t} not found`);let o={updated_at:$o(new Date)};if(e!==void 0)o.inventory_count=e;if(Object.keys(o).length===1)return r;try{return await Uo.updateTable("products").set(o).where("id","=",t).execute(),await ee(t)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update inventory information: ${n.message}`);throw n}}var Bt={};g(Bt,{bulkDestroy:()=>eu,bulkStore:()=>lu,destroy:()=>Xi,fetchAll:()=>tu,fetchByCountry:()=>au,fetchById:()=>ru,fetchByUuid:()=>ou,fetchFeatured:()=>nu,fetchWithProductCount:()=>su,store:()=>du,update:()=>pu,updateByUuid:()=>wu,updateFeaturedStatus:()=>fu});import{db as Yi}from"@stacksjs/database/runtime";async function Xi(t){try{let e=await Yi.deleteFrom("manufacturers").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete order: ${e.message}`);throw e}}async function eu(t){if(!t.length)return 0;try{let e=await Yi.deleteFrom("manufacturers").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete orders: ${e.message}`);throw e}}import{db as te}from"@stacksjs/database/runtime";async function tu(){return w(await te.selectFrom("manufacturers").selectAll().execute())}async function ru(t){let e=await te.selectFrom("manufacturers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ou(t){let e=await te.selectFrom("manufacturers").where("uuid","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function nu(t=10){let e=await te.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(t).execute();return w(e)}async function au(t,e={}){let r=e.page||1,o=e.limit||2,n=await te.selectFrom("manufacturers").select(te.fn.count("id").as("total")).where("country","=",t).executeTakeFirst(),a=Number(n?.total||0),s=await te.selectFrom("manufacturers").selectAll().where("country","=",t).limit(o).offset((r-1)*o).execute(),i=Math.ceil(a/o);return{data:w(s),paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function su(t={}){let e=te.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(t.country)e=e.where("m.country","=",t.country);if(t.featured!==void 0)e=e.where("m.featured","=",t.featured);return e=e.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",te.fn.count("p.id").as("product_count")]).groupBy("m.id"),e.execute()}var{randomUUIDv7:uu}=globalThis.Bun;import{db as cu}from"@stacksjs/database/runtime";import{HttpError as iu}from"@stacksjs/error-handling";import{isUniqueViolation as Yp}from"@stacksjs/orm";async function du(t){try{let e={...t,uuid:uu(),featured:t.featured??!1},r=await cu.insertInto("manufacturers").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return d(r)}catch(e){if(e instanceof iu)throw e;if(Yp(e))throw new iu(409,"A manufacturer with this name already exists");if(e instanceof Error)throw Error(`Failed to create manufacturer: ${e.message}`);throw e}}async function lu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:uu(),featured:r.featured??!1};await cu.insertInto("manufacturers").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${r.message}`);throw r}}import{db as Wo}from"@stacksjs/database/runtime";import{HttpError as mu}from"@stacksjs/error-handling";import{formatDate as Lo,isUniqueViolation as Xp}from"@stacksjs/orm";async function pu(t,e){try{if(!t)throw Error("Manufacturer ID is required for update");let r=await Wo.updateTable("manufacturers").set({...e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof mu)throw r;if(Xp(r))throw new mu(409,"A manufacturer with this name already exists");if(r instanceof Error)throw Error(`Failed to update manufacturer: ${r.message}`);throw r}}async function fu(t,e){try{let r=await Wo.updateTable("manufacturers").set({featured:e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function wu(t,e){try{let r=await Wo.updateTable("manufacturers").set({...e,updated_at:Lo(new Date)}).where("uuid","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var Ot={};g(Ot,{bulkDestroy:()=>gu,destroy:()=>hu,fetchAll:()=>_u,fetchApprovedByProductId:()=>Du,fetchById:()=>bu,fetchByProductId:()=>Ru,fetchByUserId:()=>xu,fetchMostHelpfulByProductId:()=>vu,fetchStats:()=>Tu,fetchStatsByProductIds:()=>Eu,store:()=>Su,update:()=>Mu,updateVotes:()=>Iu});import{db as yu}from"@stacksjs/database/runtime";async function hu(t){try{let e=await yu.deleteFrom("reviews").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete review: ${e.message}`);throw e}}async function gu(t){if(!t.length)return 0;try{let e=await yu.deleteFrom("reviews").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete reviews: ${e.message}`);throw e}}import{db as Te}from"@stacksjs/database/runtime";async function bu(t){return d(await Te.selectFrom("reviews").where("id","=",t).selectAll().executeTakeFirst(),!0)}async function _u(){return w(await Te.selectFrom("reviews").selectAll().execute())}async function Ru(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).selectAll().execute())}async function xu(t){return w(await Te.selectFrom("reviews").where("customer_id","=",t).selectAll().execute())}async function Du(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).where("is_approved","=",!0).selectAll().execute())}async function vu(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).orderBy("helpful_votes","desc").selectAll().execute())}import{db as Pu}from"@stacksjs/database/runtime";function Fu(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function ku(t){let e=Fu();e.total=t.length;let r=0;for(let o of t){if(o.rating===null||o.rating===void 0){e.commentsOnly++;continue}let n=Number(o.rating);if(Number.isNaN(n)){e.commentsOnly++;continue}e.rated++,r+=n;let a=Math.min(5,Math.max(1,Math.round(n)));e.distribution[a]++}if(e.rated>0)e.average=Math.round(r/e.rated*10)/10;return e}async function Tu(t){let e=await Pu.selectFrom("reviews").select(["rating"]).where("product_id","=",t).where("is_approved","=",!0).execute();return ku(e)}async function Eu(t){let e=new Map;for(let n of t)e.set(n,Fu());if(t.length===0)return e;let r=await Pu.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",t).where("is_approved","=",!0).execute(),o=new Map;for(let n of r){let a=o.get(n.product_id);if(a)a.push({rating:n.rating});else o.set(n.product_id,[{rating:n.rating}])}for(let[n,a]of o)e.set(n,ku(a));return e}var{randomUUIDv7:ef}=globalThis.Bun;import{db as tf}from"@stacksjs/database/runtime";function rf(t){let e=t.rating!==void 0&&t.rating!==null,r=typeof t.content==="string"&&t.content.trim().length>0,o=typeof t.title==="string"&&t.title.trim().length>0;return!e&&!r&&!o}async function Su(t){try{if(rf(t))throw Error("A review needs a rating or something written: both were empty");let e={...t,uuid:ef(),rating:t.rating??null,is_verified_purchase:t.is_verified_purchase??!1,is_approved:t.is_approved??!1,helpful_votes:t.helpful_votes??0,unhelpful_votes:t.unhelpful_votes??0,is_featured:t.is_featured??!1},r=await tf.insertInto("reviews").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return d(r)}catch(e){if(e instanceof Error){if(e.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${e.message}`)}throw e}}import{db as Cu,sqlHelpers as of}from"@stacksjs/database/runtime";import{env as nf}from"@stacksjs/env";import{formatDate as Au}from"@stacksjs/orm";async function Mu(t,e){try{if(!t)throw Error("Review ID is required for update");let r=await Cu.updateTable("reviews").set({...e,updated_at:Au(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function Iu(t,e,r=!0){try{let o=e==="helpful"?"helpful_votes":"unhelpful_votes",n=r?`COALESCE("${o}", 0) + 1`:`MAX(COALESCE("${o}", 0) - 1, 0)`,{param:a}=of(nf.DB_CONNECTION||"sqlite"),s=await Cu.unsafe(`UPDATE "reviews" SET "${o}" = ${n}, "updated_at" = ${a(1)} WHERE "id" = ${a(2)} RETURNING *`,[Au(new Date),t]).execute(),i=Array.isArray(s)?s[0]:s;if(!i)throw Error("Failed to update review votes");return d(i)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update review votes: ${o.message}`);throw o}}var Wt={};g(Wt,{bulkDestroy:()=>Bu,bulkStore:()=>ju,bulkUpdate:()=>Vu,destroy:()=>Ju,fetchAll:()=>$u,fetchById:()=>Uu,formatUnitOptions:()=>zu,getDefaultUnit:()=>Gu,store:()=>Lu,update:()=>qu,updateDefaultStatus:()=>Zu});import{db as Nu}from"@stacksjs/database/runtime";async function Ju(t){try{let e=await Nu.deleteFrom("product_units").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product unit: ${e.message}`);throw e}}async function Bu(t){if(!t.length)return 0;try{let e=await Nu.deleteFrom("product_units").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product units: ${e.message}`);throw e}}import{db as Ou}from"@stacksjs/database/runtime";async function Uu(t){let e=await Ou.selectFrom("product_units").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function $u(){return w(await Ou.selectFrom("product_units").selectAll().execute())}var{randomUUIDv7:Wu}=globalThis.Bun;import{db as Ye}from"@stacksjs/database/runtime";async function Lu(t){try{return await Ye.transaction(async(e)=>{let r={...t,uuid:Wu()},o=await e.insertInto("product_units").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create product unit");if(r.is_default&&r.type)await e.updateTable("product_units").set({is_default:!1}).where("type","=",r.type).where("id","!=",o.id).execute();return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product unit: ${e.message}`);throw e}}async function ju(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:Wu()},n=await Ye.insertInto("product_units").values(o).returningAll().executeTakeFirst();if(o.is_default&&o.type&&n)await Ye.updateTable("product_units").set({is_default:!1}).where("type","=",o.type).where("id","!=",n.id).execute();e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product units in bulk: ${r.message}`);throw r}}function zu(t){try{let e=Ye.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(t)e=e.where("type","=",t);return e=e.orderBy("name"),e.execute().then((r)=>r.map((o)=>({id:String(o.id),name:o.name,abbreviation:o.abbreviation,is_default:o.is_default})))}catch(e){if(e instanceof Error)throw TypeError(`Failed to format unit options: ${e.message}`);throw e}}async function Gu(t){try{let e=await Ye.selectFrom("product_units").selectAll().where("type","=",t).where("is_default","=",!0).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get default unit: ${e.message}`);throw e}}import{db as Ut,matchedRows as af}from"@stacksjs/database/runtime";import{formatDate as $t}from"@stacksjs/orm";async function qu(t,e){try{if(!t)throw Error("Product unit ID is required for update");return await Ut.transaction(async(r)=>{let o=await r.selectFrom("product_units").select(["type","is_default"]).where("id","=",t).executeTakeFirst();if(!o)return;let n=e.type??o.type;if((e.is_default??Boolean(o.is_default))&&n)await r.updateTable("product_units").set({is_default:!1,updated_at:$t(new Date)}).where("type","=",n).where("id","!=",t).execute();let s=await r.updateTable("product_units").set({...e,updated_at:$t(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function Vu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o=r;if(!o.id)continue;let n=o.data&&typeof o.data==="object"?o.data:{...o};delete n.id;let a=await af(Ut.updateTable("product_units").set({...n,updated_at:$t(new Date)}).where("id","=",o.id)),s=n;if(s.is_default===!0&&s.type)await Ut.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",o.id).execute();if(a.length>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product units in bulk: ${r.message}`);throw r}}async function Zu(t,e){try{return await Ut.transaction(async(r)=>{let o=await r.selectFrom("product_units").select("type").where("id","=",t).executeTakeFirst();if(!o)return!1;let n=$t(new Date);if(e&&o.type)await r.updateTable("product_units").set({is_default:!1,updated_at:n}).where("type","=",o.type).where("id","!=",t).execute();return await r.updateTable("product_units").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit default status: ${r.message}`);throw r}}var Lt={};g(Lt,{bulkDestroy:()=>Qu,bulkStore:()=>nc,bulkUpdate:()=>dc,destroy:()=>Ku,fetchAll:()=>ec,fetchById:()=>Xu,formatVariantOptions:()=>ac,generateVariantCombinations:()=>sc,store:()=>oc,update:()=>cc});import{db as Hu}from"@stacksjs/database/runtime";async function Ku(t){try{let e=await Hu.deleteFrom("product_variants").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variant: ${e.message}`);throw e}}async function Qu(t){if(!t.length)return 0;try{let e=await Hu.deleteFrom("product_variants").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variants: ${e.message}`);throw e}}import{db as Yu}from"@stacksjs/database/runtime";async function Xu(t){let e=await Yu.selectFrom("product_variants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ec(){return w(await Yu.selectFrom("product_variants").selectAll().execute())}var{randomUUIDv7:tc}=globalThis.Bun;import{db as rc}from"@stacksjs/database/runtime";async function oc(t){try{let e={...t,uuid:tc()},r=await rc.insertInto("product_variants").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return d(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product variant: ${e.message}`);throw e}}async function nc(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:tc()};await rc.insertInto("product_variants").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${r.message}`);throw r}}function ac(t){if(!t||!t.length)return JSON.stringify([]);let e=t.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(e)}function sc(t){let e=Object.keys(t);if(!e.length)return[];function r(o,n){if(o===e.length)return[n];let a=e[o],s=t[a]??[],i=[];for(let u of s){let c={...n,[a]:u};i.push(...r(o+1,c))}return i}return r(0,{})}import{db as ic,matchedRows as sf}from"@stacksjs/database/runtime";import{formatDate as uc}from"@stacksjs/orm";async function cc(t,e){try{let r=await ic.updateTable("product_variants").set({...e,updated_at:uc(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function dc(t){if(!t.length)return 0;let e=0;try{for(let r of t){if(!r.id)continue;if((await sf(ic.updateTable("product_variants").set({...r,updated_at:uc(new Date)}).where("id","=",r.id))).length>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var uf={categories:Nt,items:Jt,manufacturers:Bt,reviews:Ot,units:Wt,variants:Lt},cf=uf;var Ho={};g(Ho,{bulkDestroy:()=>pc,bulkStore:()=>xc,destroy:()=>mc,fetchAll:()=>fc,fetchById:()=>Ee,fetchPageStats:()=>hc,fetchPrintJobStats:()=>wc,fetchPrintTimeStats:()=>gc,fetchPrintsPerHour:()=>bc,fetchSuccessRate:()=>yc,store:()=>Rc,update:()=>Dc,updatePrintJob:()=>Pc,updateStatus:()=>vc});import{db as lc}from"@stacksjs/database/runtime";async function mc(t){try{let e=await lc.deleteFrom("receipts").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print log: ${e.message}`);throw e}}async function pc(t){if(!t.length)return 0;try{let e=await lc.deleteFrom("receipts").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete receipts: ${e.message}`);throw e}}import{db as zo}from"@stacksjs/database/runtime";import{formatDate as df}from"@stacksjs/orm";function j(t){return df(t)}function lf(t){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t==="number"){let o=new Date(t<=2147483647?t*1000:t);return Number.isNaN(o.getTime())?null:o}let e=String(t||"").trim();if(!e)return null;if(/^\d{10}$/.test(e)){let o=new Date(Number(e)*1000);return Number.isNaN(o.getTime())?null:o}let r=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(r.getTime())?null:r}async function Ee(t){let e=await zo.selectFrom("receipts").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function fc(){return w(await zo.selectFrom("receipts").selectAll().execute())}async function wc(t,e){let r=j(t),o=j(e),n=await J("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{total:n.total,success:n.success,failed:n.failed,warning:n.warning,averageSize:Math.round(n.averageSize),averagePages:Math.round(n.averagePages),averageDuration:Math.round(n.averageDuration)}}async function yc(t,e){let r=j(t),o=j(e),n=await J("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(s)=>s.where("timestamp",">=",r).where("timestamp","<=",o));return{successRate:n.total>0?Math.round(n.success/n.total*100):0,total:n.total,success:n.success,failed:n.failed,warning:n.warning}}async function hc(t,e){let r=j(t),o=j(e),n=await J("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{totalPages:n.totalPages,averagePagesPerReceipt:Math.round(n.averagePagesPerReceipt),totalReceipts:n.totalReceipts}}async function gc(t,e){let r=j(t),o=j(e),n=await J("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{averageDuration:Math.round(n.averageDuration),minDuration:n.minDuration,maxDuration:n.maxDuration,totalJobs:n.totalJobs}}async function bc(t,e){let r=typeof t==="number"?t:t.getTime(),o=typeof e==="number"?e:e.getTime(),n=j(t),a=j(e),s=await zo.selectFrom("receipts").where("timestamp",">=",n).where("timestamp","<=",a).selectAll().execute(),i=s.length,u=Math.ceil((o-r)/3600000),c=u>0?Math.round(i/u):0,l=Array.from({length:24},(m,f)=>({hour:f,count:0}));return s.forEach((m)=>{let f=lf(m.timestamp);if(!f)return;l[f.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:l}}var{randomUUIDv7:_c}=globalThis.Bun;import{db as qo}from"@stacksjs/database/runtime";import{formatDate as Go}from"@stacksjs/orm";function Xe(t){try{if(typeof t==="number")return Go(t<=2147483647?t*1000:t);if(typeof t==="string"&&/^\d{10}$/.test(t))return Go(Number(t)*1000);return Go(t)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function Rc(t){try{let e=_c(),r={...t,timestamp:Xe(t.timestamp),uuid:e};await qo.insertInto("receipts").values(r).executeTakeFirst();let o=await qo.selectFrom("receipts").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create receipt");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipt: ${e.message}`);throw e}}async function xc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...o,timestamp:Xe(o.timestamp),uuid:_c()})),r=await qo.insertInto("receipts").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${e.message}`);throw e}}import{db as Vo}from"@stacksjs/database/runtime";import{formatDate as Zo}from"@stacksjs/orm";async function Dc(t,e){try{if(!t)throw Error("Receipt ID is required for update");let r={...e,...e.timestamp===void 0?{}:{timestamp:Xe(e.timestamp)},updated_at:Zo(new Date)};await Vo.updateTable("receipts").set(r).where("id","=",t).execute();let o=await Ee(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function vc(t,e){try{await Vo.updateTable("receipts").set({status:e,updated_at:Zo(new Date)}).where("id","=",t).execute();let r=await Ee(t);if(!r)throw Error("Failed to update receipt status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function Pc(t,e,r,o){try{let n={updated_at:Zo(new Date)};if(e!==void 0)n.size=e;if(r!==void 0)n.pages=r;if(o!==void 0)n.duration=o;await Vo.updateTable("receipts").set(n).where("id","=",t).execute();let a=await Ee(t);if(!a)throw Error("Failed to update receipt job information");return d(a)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update receipt job information: ${n.message}`);throw n}}var Rn={};g(Rn,{couriers:()=>Yt,default:()=>Nf,digital:()=>Kt,geocoding:()=>rr,licenses:()=>ar,methods:()=>cr,rates:()=>fr,routes:()=>Zt,tracking:()=>xr,zones:()=>Fr});var Zt={};g(Zt,{DeliveryRouteInputError:()=>N,bulkDestroy:()=>Tc,destroy:()=>kc,fetchActive:()=>Sc,fetchAll:()=>Ec,fetchByCourier:()=>Cc,fetchById:()=>zt,store:()=>Ac,update:()=>Ic,updateLastActive:()=>Mc,updateMetrics:()=>Jc,updateStops:()=>Nc,validateDeliveryRouteWrite:()=>Se});import{db as Fc}from"@stacksjs/database/runtime";async function kc(t){try{let e=await Fc.deleteFrom("delivery_routes").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery route: ${e.message}`);throw e}}async function Tc(t){if(!t.length)return 0;try{let e=await Fc.deleteFrom("delivery_routes").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery routes: ${e.message}`);throw e}}import{db as jt}from"@stacksjs/database/runtime";async function zt(t){return await jt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst()}async function Ec(){return await jt.selectFrom("delivery_routes").selectAll().execute()}async function Sc(){return await jt.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function Cc(t){return await jt.selectFrom("delivery_routes").where("courier","=",t).selectAll().execute()}var{randomUUIDv7:ff}=globalThis.Bun;import{db as Ko}from"@stacksjs/database/runtime";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 mf}from"@stacksjs/database/runtime";class N extends TypeError{constructor(t){super(t);this.name="DeliveryRouteInputError"}}function qt(t,e,r){return Number(t[r]??e?.[r])}function pf(t,e){let r=t.last_active??e?.last_active;if(r===void 0||r===null)return Date.now();if(r instanceof Date)return r.getTime();if(typeof r==="number")return r;if(typeof r==="string"&&/^\d{10,13}$/.test(r))return Number(r);return Number.NaN}async function Se(t,e){let r=qt(t,e,"courier_id"),o=qt(t,e,"stops"),n=qt(t,e,"delivery_time"),a=qt(t,e,"total_distance"),s=pf(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 mf.selectFrom("couriers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new N(`Courier ${r} was not found.`);return{...t,courier_id:Number(i.id),courier:i.name,vehicle:i.vehicle_number,last_active:s}}async function Ac(t){try{let e=ff(),r=Gt(t),n={...await Se(r),uuid:e};await Ko.insertInto("delivery_routes").values(n).executeTakeFirst();let a=await Ko.selectFrom("delivery_routes").where("uuid","=",e).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(e){if(e instanceof N)throw e;if(e instanceof Error)throw TypeError(`Failed to create delivery route: ${e.message}`);throw e}}async function Mc(t){try{await Ko.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",t).execute();let e=await zt(t);if(!e)throw Error("Failed to update delivery route last active");return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update delivery route last active: ${e.message}`);throw e}}import{db as Vt}from"@stacksjs/database/runtime";import{formatDate as Qo}from"@stacksjs/orm";async function Ic(t,e){try{if(!t)throw Error("Delivery route ID is required for update");let r=await Vt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=Gt(e),n=await Se(o,r),a=await Vt.updateTable("delivery_routes").set({...n,updated_at:Qo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof N)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function Nc(t,e){try{let r=await Vt.updateTable("delivery_routes").set({stops:e,updated_at:Qo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update delivery route stops");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update delivery route stops: ${r.message}`);throw r}}async function Jc(t,e,r){try{let o={updated_at:Qo(new Date)};if(e!==void 0)o.delivery_time=e;if(r!==void 0)o.total_distance=r;let n=await Vt.updateTable("delivery_routes").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update delivery metrics");return n}catch(o){if(o instanceof Error)throw TypeError(`Failed to update delivery metrics: ${o.message}`);throw o}}var Kt={};g(Kt,{bulkDestroy:()=>$c,bulkSoftDelete:()=>Wc,bulkStore:()=>Vc,destroy:()=>Oc,fetchAll:()=>zc,fetchById:()=>jc,softDelete:()=>Uc,store:()=>qc,update:()=>Zc,updateDeliverySettings:()=>Kc,updateStatus:()=>Hc});import{db as Ht,matchedRows as Bc}from"@stacksjs/database/runtime";async function Oc(t){try{let e=await Ht.deleteFrom("digital_deliveries").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital delivery: ${e.message}`);throw e}}async function Uc(t){try{return(await Bc(Ht.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${e.message}`);throw e}}async function $c(t){if(!t.length)return 0;try{let e=await Ht.deleteFrom("digital_deliveries").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${e.message}`);throw e}}async function Wc(t){if(!t.length)return 0;try{return(await Bc(Ht.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${e.message}`);throw e}}import{db as Lc}from"@stacksjs/database/runtime";async function jc(t){let e=await Lc.selectFrom("digital_deliveries").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function zc(){return w(await Lc.selectFrom("digital_deliveries").selectAll().execute())}var{randomUUIDv7:Gc}=globalThis.Bun;import{db as Yo}from"@stacksjs/database/runtime";async function qc(t){try{let e=Gc(),r={...rt(t),uuid:e};await Yo.insertInto("digital_deliveries").values(r).executeTakeFirst();let o=await Yo.selectFrom("digital_deliveries").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created digital delivery");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital delivery: ${e.message}`);throw e}}async function Vc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...rt(o),uuid:Gc()})),r=await Yo.insertInto("digital_deliveries").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${e.message}`);throw e}}import{db as Xo}from"@stacksjs/database/runtime";import{formatDate as en}from"@stacksjs/orm";async function Zc(t,e){try{if(!t)throw Error("Digital delivery ID is required for update");let r=await Xo.updateTable("digital_deliveries").set({...rt(e),updated_at:en(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function Hc(t,e){try{let r=await Xo.updateTable("digital_deliveries").set({status:e,updated_at:en(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function Kc(t,e,r,o,n){try{let a={updated_at:en(new Date)};if(e!==void 0)a.download_limit=e;if(r!==void 0)a.expiry_days=r;if(o!==void 0)a.requires_login=o;if(n!==void 0)a.automatic_delivery=n;let s=await Xo.updateTable("digital_deliveries").set(a).where("id","=",t).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return d(s)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var Yt={};g(Yt,{bulkDestroy:()=>td,bulkStore:()=>nd,destroy:()=>ed,fetchAll:()=>Yc,fetchById:()=>Qt,store:()=>od,update:()=>ad,updateContact:()=>id,updateStatus:()=>sd});import{db as Xc}from"@stacksjs/database/runtime";import{db as Qc}from"@stacksjs/database/runtime";async function Qt(t){let e=await Qc.selectFrom("couriers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Yc(){return w(await Qc.selectFrom("couriers").selectAll().execute())}async function ed(t){try{let e=await Xc.deleteFrom("couriers").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete courier: ${e.message}`);throw e}}async function td(t){if(!t.length)return 0;let e=0;try{return await Xc.transaction(async(r)=>{for(let o of t)if(await Qt(o))await r.deleteFrom("couriers").where("id","=",o).execute(),e++}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to delete couriers in bulk: ${r.message}`);throw r}}var{randomUUIDv7:rd}=globalThis.Bun;import{db as tn}from"@stacksjs/database/runtime";async function od(t){try{let e=rd(),r={...nt(t),uuid:e};await tn.insertInto("couriers").values(r).executeTakeFirst();let o=await tn.selectFrom("couriers").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created courier");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create courier: ${e.message}`);throw e}}async function nd(t){if(!t.length)return 0;try{let e=t.map((o)=>({...nt(o),uuid:rd()})),r=await tn.insertInto("couriers").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create couriers in bulk: ${e.message}`);throw e}}import{db as rn}from"@stacksjs/database/runtime";import{formatDate as on}from"@stacksjs/orm";async function ad(t,e){try{if(!t)throw Error("Courier ID is required for update");let r=await rn.updateTable("couriers").set({...nt(e),updated_at:on(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier: ${r.message}`);throw r}}async function sd(t,e){try{let r=await rn.updateTable("couriers").set({status:e,updated_at:on(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update courier status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier status: ${r.message}`);throw r}}async function id(t,e){try{let r={updated_at:on(new Date)};if(e!==void 0)r.phone=e;let o=await rn.updateTable("couriers").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update contact information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var rr={};g(rr,{PRECISION_RANK:()=>st,checkCoverage:()=>_f,formatQuery:()=>Ce,geocode:()=>bf,geocodingDriver:()=>pd,nominatimDriver:()=>tr,setGeocodingDriver:()=>gf});var ge=(t)=>t*Math.PI/180;function ce(t,e){let r=ge(e.latitude-t.latitude),o=ge(e.longitude-t.longitude),n=ge(t.latitude),a=ge(e.latitude),s=Math.sin(r/2)**2+Math.sin(o/2)**2*Math.cos(n)*Math.cos(a);return 12742017.6*Math.asin(Math.sqrt(s))}function Xt(t,e){let r=ge(t.latitude),o=ge(e.latitude),n=ge(e.longitude-t.longitude),a=Math.sin(n)*Math.cos(o),s=Math.cos(r)*Math.sin(o)-Math.sin(r)*Math.cos(o)*Math.cos(n);return(Math.atan2(a,s)*180/Math.PI+360)%360}function er(t,e,r={}){let o=r.detourFactor??1.35,n=r.minimumSeconds??30;if(!Number.isFinite(e)||e<=0.5)return null;let a=t*o/e;return Math.max(n,Math.round(a))}function ud(t,e,r){return ce(t,e)<=r}function at(t){return typeof t?.latitude==="number"&&typeof t?.longitude==="number"&&Number.isFinite(t.latitude)&&Number.isFinite(t.longitude)}var st={unknown:0,locality:1,postal:2,street:3,rooftop:4};function Ce(t){return[t.street,t.city,t.region,t.postalCode,t.country].map((e)=>String(e??"").trim()).filter(Boolean).join(", ")}var wf="https://nominatim.openstreetmap.org/search",cd=1000,dd=0,ld=Promise.resolve();async function yf(t){let e=ld.then(async()=>{let r=Date.now()-dd;if(r<cd)await Bun.sleep(cd-r);return dd=Date.now(),t()});return ld=e.then(()=>{return},()=>{return}),e}function hf(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??wf;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 yf(()=>fetch(a,{headers:{"user-agent":e,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!s.ok)throw Error(`Nominatim responded ${s.status}`);let u=(await s.json())?.[0];if(!u)return null;let c=Number(u.lat),l=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(l))return null;let m=hf(u);return{latitude:c,longitude:l,formatted:String(u.display_name??n),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[m],precision:m,provider:"nominatim"}}}}var md=null;function gf(t){md=t}function pd(){return md??tr()}async function bf(t,e={}){let r=e.driver??pd(),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 xf(n,i,i?e.cacheSeconds??2592000:600),i}function _f(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 xf(t,e,r){try{let n=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!n)return;await n.set(t,e===null?"null":JSON.stringify(e),r)}catch{}}var ar={};g(ar,{LicenseKeyInputError:()=>T,bulkDestroy:()=>hd,bulkSoftDelete:()=>gd,bulkStore:()=>Fd,destroy:()=>wd,fetchAll:()=>Rd,fetchById:()=>_d,softDelete:()=>yd,store:()=>Pd,update:()=>kd,updateExpiration:()=>Ed,updateStatus:()=>Td,validateLicenseKeyWrite:()=>be});import{db as or,matchedRows as fd}from"@stacksjs/database/runtime";async function wd(t){try{let e=await or.deleteFrom("license_keys").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license key: ${e.message}`);throw e}}async function yd(t){try{return(await fd(or.updateTable("license_keys").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license key: ${e.message}`);throw e}}async function hd(t){if(!t.length)return 0;try{let e=await or.deleteFrom("license_keys").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license keys: ${e.message}`);throw e}}async function gd(t){if(!t.length)return 0;try{return(await fd(or.updateTable("license_keys").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license keys: ${e.message}`);throw e}}import{db as bd}from"@stacksjs/database/runtime";async function _d(t){let e=await bd.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Rd(){return w(await bd.selectFrom("license_keys").selectAll().execute())}var{randomUUIDv7:vd}=globalThis.Bun;import{db as sn}from"@stacksjs/database/runtime";import{db as nn}from"@stacksjs/database/runtime";var xd=["Standard License","Premium License","Enterprise License"],Dd=["active","inactive","unassigned"];class T extends TypeError{constructor(t){super(t);this.name="LicenseKeyInputError"}}function it(t,e,r){return t[r]!==void 0?t[r]:e?.[r]}function an(t,e,r,o){let n=it(t,e,r);if(n===void 0||n===null||n==="")return null;let a=Number(n);if(!Number.isSafeInteger(a)||a<1)throw new T(`${o} must be a positive integer or null.`);return a}function Df(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=Df(it(t,e,"expiry_date")),s=an(t,e,"customer_id","Customer"),i=an(t,e,"product_id","Product"),u=an(t,e,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new T("License key must use five groups of four uppercase letters or numbers.");if(!xd.includes(o))throw new T(`Template must be one of: ${xd.join(", ")}.`);if(!Dd.includes(n))throw new T(`Status must be one of: ${Dd.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new T("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,l,m]=await Promise.all([s?nn.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?nn.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?nn.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new T(`Customer ${s} was not found.`);if(i&&!l)throw new T(`Product ${i} was not found.`);if(u&&!m)throw new T(`Order ${u} was not found.`);if(s&&m?.customer_id&&Number(m.customer_id)!==s)throw new T(`Order ${u} belongs to Customer ${m.customer_id}, not Customer ${s}.`);return{...t,key:r,template:o,expiry_date:a,status:n,customer_id:s,product_id:i,order_id:u}}async function Pd(t){try{let e=vd(),r=ot(t),o={...await be(r),uuid:e};await sn.insertInto("license_keys").values(o).executeTakeFirst();let n=await sn.selectFrom("license_keys").where("uuid","=",e).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created license key");return d(n)}catch(e){if(e instanceof T)throw e;if(e instanceof Error){if(e.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${e.message}`)}throw e}}async function Fd(t){if(!t.length)return 0;try{let e=await Promise.all(t.map(async(o)=>({...await be(ot(o)),uuid:vd()}))),r=await sn.insertInto("license_keys").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof T)throw e;if(e instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${e.message}`);throw e}}import{db as nr}from"@stacksjs/database/runtime";import{formatDate as un}from"@stacksjs/orm";async function kd(t,e){try{if(!t)throw Error("License key ID is required for update");let r=await nr.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=ot(e),n=await be(o,r),a=await nr.updateTable("license_keys").set({...n,updated_at:un(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return d(a)}catch(r){if(r instanceof T)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function Td(t,e){try{let r=await nr.updateTable("license_keys").set({status:e,updated_at:un(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function Ed(t,e){try{let r={updated_at:un(new Date)};if(e!==void 0)r.expiry_date=e;let o=await nr.updateTable("license_keys").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update expiration information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var cr={};g(cr,{bulkDestroy:()=>Md,bulkSoftDelete:()=>Id,bulkStore:()=>Od,destroy:()=>Cd,fetchAll:()=>Nd,fetchById:()=>ur,formatShippingOptions:()=>Ud,getActiveShippingMethods:()=>$d,softDelete:()=>Ad,store:()=>Bd,update:()=>Wd,updatePricing:()=>jd,updateStatus:()=>Ld});import{db as sr,matchedRows as Sd}from"@stacksjs/database/runtime";async function Cd(t){try{let e=await sr.deleteFrom("shipping_methods").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping method: ${e.message}`);throw e}}async function Ad(t){try{return(await Sd(sr.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${e.message}`);throw e}}async function Md(t){if(!t.length)return 0;try{let e=await sr.deleteFrom("shipping_methods").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping methods: ${e.message}`);throw e}}async function Id(t){if(!t.length)return 0;try{return(await Sd(sr.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${e.message}`);throw e}}import{db as ir}from"@stacksjs/database/runtime";async function ur(t){let e=await ir.selectFrom("shipping_methods").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=await ir.selectFrom("shipping_zones").where("shipping_method_id","=",t).selectAll().execute();return{...e,shippingZones:r}}return}async function Nd(){let t=await ir.selectFrom("shipping_methods").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((a)=>a.id))],n=(await ir.selectFrom("shipping_zones").where("shipping_method_id","in",e).selectAll().execute()).reduce((a,s)=>{let i=s.shipping_method_id;if(i!==null&&i!==void 0){if(!a[i])a[i]=[];a[i].push(s)}return a},{});return t.map((a)=>({...a,shipping_zones:n[a.id]||[]}))}var{randomUUIDv7:Jd}=globalThis.Bun;import{db as ut}from"@stacksjs/database/runtime";async function Bd(t){try{let e=Jd(),r={...et(t),uuid:e};await ut.insertInto("shipping_methods").values(r).executeTakeFirst();let o=await ut.selectFrom("shipping_methods").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping method");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping method: ${e.message}`);throw e}}async function Od(t){if(!t.length)return 0;try{let e=t.map((o)=>({...et(o),uuid:Jd()})),r=await ut.insertInto("shipping_methods").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${e.message}`);throw e}}function Ud(){try{return ut.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping options: ${t.message}`);throw t}}async function $d(){try{let t=await ut.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping methods: ${t.message}`);throw t}}import{db as cn}from"@stacksjs/database/runtime";import{formatDate as dn}from"@stacksjs/orm";async function Wd(t,e){try{if(!t)throw Error("Shipping method ID is required for update");let r=await cn.updateTable("shipping_methods").set({...et(e),updated_at:dn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function Ld(t,e){try{let r=await cn.updateTable("shipping_methods").set({status:e,updated_at:dn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function jd(t,e,r){try{let o={updated_at:dn(new Date)};if(e!==void 0)o.base_rate=e;if(r!==void 0)o.free_shipping=r;let n=await cn.updateTable("shipping_methods").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update pricing information");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update pricing information: ${o.message}`);throw o}}var fr={};g(fr,{ShippingRateInputError:()=>A,bulkDestroy:()=>Gd,bulkStore:()=>ul,bulkUpdate:()=>dl,destroy:()=>zd,destroyByMethod:()=>Vd,destroyByZone:()=>qd,fetchAll:()=>Kd,fetchById:()=>Hd,formatShippingRateOptions:()=>el,getRateByWeightAndAddress:()=>Yd,getRateByWeightAndZone:()=>ln,getRatesByZone:()=>Qd,getShippingRatesByMethod:()=>tl,resolveZoneForAddress:()=>lr,store:()=>il,update:()=>cl,updateByMethod:()=>ml,updateByZone:()=>ll,validateShippingRateWrite:()=>_e,validateZoneMatchesAddress:()=>Xd});import{db as dr}from"@stacksjs/database/runtime";async function zd(t){try{let e=await dr.deleteFrom("shipping_rates").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rate: ${e.message}`);throw e}}async function Gd(t){if(!t.length)return 0;try{let e=await dr.deleteFrom("shipping_rates").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates: ${e.message}`);throw e}}async function qd(t){try{let e=await dr.deleteFrom("shipping_rates").where("shipping_zone_id","=",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${e.message}`);throw e}}async function Vd(t){try{let e=await dr.deleteFrom("shipping_rates").where("shipping_method_id","=",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${e.message}`);throw e}}import{db as W}from"@stacksjs/database/runtime";async function Hd(t){let e=await W.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.shipping_zone_id)r=await W.selectFrom("shipping_zones").where("id","=",e.shipping_zone_id).selectAll().executeTakeFirst();if(e.shipping_method_id)o=await W.selectFrom("shipping_methods").where("id","=",e.shipping_method_id).selectAll().executeTakeFirst();return{...e,shipping_zone:r,shipping_method:o}}return}async function Kd(){let t=await W.selectFrom("shipping_rates").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((i)=>i.shipping_zone_id).filter((i)=>i!==null&&i!==void 0))],r=[...new Set(t.map((i)=>i.shipping_method_id).filter((i)=>i!==null&&i!==void 0))],[o,n]=await Promise.all([e.length?W.selectFrom("shipping_zones").where("id","in",e).selectAll().execute():[],r.length?W.selectFrom("shipping_methods").where("id","in",r).selectAll().execute():[]]),a=o.reduce((i,u)=>(i[u.id]=u,i),{}),s=n.reduce((i,u)=>(i[u.id]=u,i),{});return t.map((i)=>({...i,shipping_zone:i.shipping_zone_id?a[i.shipping_zone_id]:[],shipping_method:i.shipping_method_id?s[i.shipping_method_id]:[]}))}async function Qd(t){try{let e=await W.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${e.message}`);throw e}}async function ln(t,e){try{let r=await W.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).where("weight_from","<=",t).where("weight_to",">=",t).executeTakeFirst();return d(r,!0)}catch(r){if(r instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${r.message}`);throw r}}async function lr(t){if(!t?.countryCode)return null;try{let e=await W.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t.countryCode}%`).where("status","=","active").execute();if(e.length===0)return null;let r=null;for(let o of e){let n=1;if(t.region&&o.regions&&Zd(o.regions,t.region))n=2;if(t.postalCode&&o.postal_codes&&Zd(o.postal_codes,t.postalCode))n=3;if(!r||n>r.score)r={id:o.id,score:n}}return r?.id??null}catch{return null}}async function Yd(t,e){let r=await lr(e);if(r==null)return;return ln(t,r)}async function Xd(t,e){return await lr(e)===t}function Zd(t,e){if(!t||!e)return!1;let r=e.trim().toUpperCase();for(let o of t.split(/[,|;]/))if(o.trim().toUpperCase()===r)return!0;return!1}async function el(){try{return(await W.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((e)=>e.shipping_method_id!==null&&e.shipping_method_id!==void 0&&e.shipping_zone_id!==null&&e.shipping_zone_id!==void 0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping rate options: ${t.message}`);throw t}}async function tl(t){try{let e=await W.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${e.message}`);throw e}}var{randomUUIDv7:sl}=globalThis.Bun;import{db as mn}from"@stacksjs/database/runtime";import{db as ct}from"@stacksjs/database/runtime";async function rl(){return w(await ct.selectFrom("shipping_zones").selectAll().execute())}async function mr(t){let e=await ct.selectFrom("shipping_zones").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}function ol(){try{return ct.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping zone options: ${t.message}`);throw t}}async function nl(){try{let t=await ct.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping zones: ${t.message}`);throw t}}async function al(t){try{let e=await ct.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t}%`).where("status","=","active").orderBy("name").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${e.message}`);throw e}}class A extends TypeError{constructor(t){super(t);this.name="ShippingRateInputError"}}function dt(t,e,r){return Number(t[r]??e?.[r])}async function _e(t,e){let r=dt(t,e,"shipping_method_id"),o=dt(t,e,"shipping_zone_id"),n=dt(t,e,"weight_from"),a=dt(t,e,"weight_to"),s=dt(t,e,"rate");if(!Number.isSafeInteger(r)||r<1)throw new A("Shipping method must be a positive integer.");if(!Number.isSafeInteger(o)||o<1)throw new A("Shipping zone must be a positive integer.");if(!Number.isFinite(n)||n<0)throw new A("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<n)throw new A("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new A("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([ur(r),mr(o)]);if(!i)throw new A(`Shipping method ${r} was not found.`);if(!u)throw new A(`Shipping zone ${o} was not found.`);if(Number(u.shipping_method_id)!==r)throw new A(`Shipping zone ${o} is not assigned to shipping method ${r}.`)}async function il(t){try{let e=re(t),r=Number(e.shipping_method_id),o=Number(e.shipping_zone_id);await _e(e);let n=sl(),a={...e,shipping_method_id:r,shipping_zone_id:o,uuid:n};await mn.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await mn.selectFrom("shipping_rates").where("uuid","=",n).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return d(s)}catch(e){if(e instanceof A)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rate: ${e.message}`);throw e}}async function ul(t){if(!t.length)return 0;try{for(let o of t){let n=re(o);await _e(n)}let e=t.map((o)=>({...re(o),uuid:sl()})),r=await mn.insertInto("shipping_rates").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof A)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${e.message}`);throw e}}import{db as lt,matchedRows as pn}from"@stacksjs/database/runtime";import{formatDate as pr}from"@stacksjs/orm";async function cl(t,e){try{if(!t)throw Error("Shipping rate ID is required for update");let r=await lt.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=re(e);await _e(o,r);let n=await lt.updateTable("shipping_rates").set({...o,updated_at:pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return d(n)}catch(r){if(r instanceof A)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function dl(t){if(!t.length)return 0;try{let e=0;for(let{id:r,data:o}of t)if((await pn(lt.updateTable("shipping_rates").set({...re(o),updated_at:pr(new Date)}).where("id","=",r))).length>0)e++;return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${e.message}`);throw e}}async function ll(t,e){try{return(await pn(lt.updateTable("shipping_rates").set({...re(e),updated_at:pr(new Date)}).where("shipping_zone_id","=",t))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function ml(t,e){try{return(await pn(lt.updateTable("shipping_rates").set({...re(e),updated_at:pr(new Date)}).where("shipping_method_id","=",t))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var xr={};g(xr,{ARRIVAL_RADIUS_METERS:()=>yn,NEARBY_RADIUS_METERS:()=>wn,assignStop:()=>fl,bearingInDegrees:()=>Xt,broadcastToChannel:()=>oe,completeStop:()=>yl,distanceInMeters:()=>ce,emitDeliveryArrived:()=>br,emitDeliveryAssigned:()=>yr,emitDeliveryCompleted:()=>_r,emitDeliveryFailed:()=>Rr,emitDeliveryNearby:()=>gr,emitDeliveryPosition:()=>wr,emitDeliveryStarted:()=>hr,estimateSecondsRemaining:()=>er,failStop:()=>hl,hasCoordinates:()=>at,isWithin:()=>ud,orderTrackingChannel:()=>de,recordCourierPing:()=>pl,routeTrackingChannel:()=>fn,startRoute:()=>gl,startStop:()=>wl});function de(t){return`order.${t}`}function fn(t){return`delivery-route.${t}`}async function Ae(t,e){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let o=r.dispatch;if(typeof o!=="function")return;o(t,e)}catch{}}async function oe(t,e,r){try{let o=await import("@stacksjs/realtime").catch(()=>null);if(!o)return;let n=o.channel;if(typeof n!=="function")return;await n(t).broadcast(e,r,"private")}catch{}}async function wr(t,e,r){await Promise.all([...t.map((o)=>oe(de(o),"delivery:position",r)),e==null?Promise.resolve():oe(fn(e),"delivery:position",r)])}async function yr(t){if(await Ae("delivery:assigned",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:assigned",{stop:t})}async function hr(t){if(await Ae("delivery:started",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:started",{stop:t})}async function gr(t,e,r){if(await Ae("delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r}),t.order_id!=null)await oe(de(t.order_id),"delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r})}async function br(t){if(await Ae("delivery:arrived",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:arrived",{stop:t})}async function _r(t){if(await Ae("delivery:completed",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:completed",{stop:t})}async function Rr(t,e){await Ae("delivery:failed",{stop:t,reason:e})}var{randomUUIDv7:vf}=globalThis.Bun;import{db as ne}from"@stacksjs/database/runtime";var wn=400,yn=60,Pf=250;async function pl(t){let e=t.recordedAt??new Date().toISOString(),r=typeof t.accuracy!=="number"||t.accuracy<=Pf,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 Ff(t.courierId),i=s?await kf(s.id):null,u=null,c=null,l=!1,m=!1,f=i&&at({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&f)u=Math.round(ce(t,f)),c=er(u,t.speed??0),m=u<=yn&&i.arrived_at==null,l=!m&&u<=wn&&i.status==="en_route"&&i.notified_nearby_at==null;let h=await Tf({courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e});if(r)await ne.updateTable("couriers").set({latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??0,last_ping_at:e}).where("id","=",t.courierId).execute();if(i&&(u!=null||c!=null))await ne.updateTable("delivery_stops").set({eta_at:c==null?i.eta_at:new Date(Date.now()+c*1000).toISOString()}).where("id","=",i.id).execute();if(r)await wr(i?.order_id==null?[]:[i.order_id],s?.id??null,{courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e,distanceToStopMeters:u,etaSeconds:c});if(l&&i)await ne.updateTable("delivery_stops").set({notified_nearby_at:e}).where("id","=",i.id).execute(),await gr(i,u,c);if(m&&i)await ne.updateTable("delivery_stops").set({status:"arrived",arrived_at:e}).where("id","=",i.id).execute(),await br({...i,status:"arrived",arrived_at:e});return{pingId:h,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:l,crossedArrival:m}}async function Ff(t){return await ne.selectFrom("delivery_routes").where("courier_id","=",t).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function kf(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 Tf(t){let e=vf();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:Ef}=globalThis.Bun;import{db as M}from"@stacksjs/database/runtime";function hn(t){return t.type==="pickup"}async function fl(t){let e=Ef(),r=t.sequence??await Cf(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 Mf(e);if(o)await yr(o);return o??{}}async function wl(t){await M.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",t).execute();let e=await bn(t);if(!e)return null;if(e.order_id!=null&&!hn(e))await gn(e.order_id,"OUT_FOR_DELIVERY");return await hr(e),e}async function yl(t,e){let r=new Date().toISOString();await M.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await Af(t)?{}:{arrived_at:r},...e?{notes:e}:{}}).where("id","=",t).execute();let o=await bn(t);if(!o)return null;if(o.order_id!=null)await gn(o.order_id,hn(o)?"OUT_FOR_DELIVERY":"DELIVERED");return await _r(o),await bl(o.delivery_route_id),o}async function hl(t,e){await M.updateTable("delivery_stops").set({status:"failed",notes:e}).where("id","=",t).execute();let r=await bn(t);if(!r)return null;if(r.order_id!=null&&!hn(r))await gn(r.order_id,"SHIPPED");return await Rr(r,e),await bl(r.delivery_route_id),r}async function gl(t){await M.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",t).execute()}async function bl(t){if(t==null)return;if(await M.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await M.selectFrom("delivery_routes").where("id","=",t).select(["courier_id"]).executeTakeFirst();if(await M.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",t).execute(),r?.courier_id!=null)await M.updateTable("couriers").set({status:"active"}).where("id","=",r.courier_id).execute()}async function gn(t,e){let r=await M.selectFrom("orders").where("id","=",t).select(["id","status"]).executeTakeFirst();if(!r)return;let o=await Promise.resolve().then(() => (Fe(),{}));let s=Sf(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 Sf(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 Cf(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 Af(t){return(await M.selectFrom("delivery_stops").where("id","=",t).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function bn(t){return await M.selectFrom("delivery_stops").where("id","=",t).selectAll().executeTakeFirst()??null}async function Mf(t){return await M.selectFrom("delivery_stops").where("uuid","=",t).selectAll().executeTakeFirst()??null}var Fr={};g(Fr,{bulkDestroy:()=>Dl,bulkSoftDelete:()=>vl,bulkStore:()=>kl,destroy:()=>Rl,fetchAll:()=>rl,fetchById:()=>mr,formatZoneOptions:()=>ol,getActiveShippingZones:()=>nl,getZonesByCountry:()=>al,softDelete:()=>xl,store:()=>Fl,update:()=>Tl,updateCountries:()=>Sl,updateRegionsAndPostalCodes:()=>Cl,updateStatus:()=>El});import{db as Dr,matchedRows as _l}from"@stacksjs/database/runtime";async function Rl(t){try{let e=await Dr.deleteFrom("shipping_zones").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zone: ${e.message}`);throw e}}async function xl(t){try{return(await _l(Dr.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${e.message}`);throw e}}async function Dl(t){if(!t.length)return 0;try{let e=await Dr.deleteFrom("shipping_zones").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zones: ${e.message}`);throw e}}async function vl(t){if(!t.length)return 0;try{return(await _l(Dr.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${e.message}`);throw e}}var{randomUUIDv7:Pl}=globalThis.Bun;import{db as _n}from"@stacksjs/database/runtime";async function Fl(t){try{let e=Pl(),r={...tt(t),uuid:e};await _n.insertInto("shipping_zones").values(r).executeTakeFirst();let o=await _n.selectFrom("shipping_zones").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping zone");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zone: ${e.message}`);throw e}}async function kl(t){if(!t.length)return 0;try{let e=t.map((o)=>({...tt(o),uuid:Pl()})),r=await _n.insertInto("shipping_zones").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${e.message}`);throw e}}import{db as vr}from"@stacksjs/database/runtime";import{formatDate as Pr}from"@stacksjs/orm";async function Tl(t,e){try{if(!t)throw Error("Shipping zone ID is required for update");let r=await vr.updateTable("shipping_zones").set({...tt(e),updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function El(t,e){try{let r=await vr.updateTable("shipping_zones").set({status:e,updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function Sl(t,e){try{let r=await vr.updateTable("shipping_zones").set({countries:e,updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function Cl(t,e,r){try{let o={updated_at:Pr(new Date)};if(e!==void 0)o.regions=e;if(r!==void 0)o.postal_codes=r;let n=await vr.updateTable("shipping_zones").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update regions and postal codes");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${o.message}`);throw o}}var If={digital:Kt,couriers:Yt,geocoding:rr,licenses:ar,methods:cr,rates:fr,routes:Zt,tracking:xr,zones:Fr},Nf=If;var vn={};g(vn,{activeTaxRates:()=>xn,breakdownFor:()=>Dn,bulkDestroy:()=>Nl,bulkStore:()=>Ll,destroy:()=>Il,fetchAll:()=>Ol,fetchById:()=>Bl,store:()=>Wl,taxFor:()=>Al,update:()=>jl,updateDefaultStatus:()=>ql,updateRate:()=>Gl,updateStatus:()=>zl});import{db as Jf}from"@stacksjs/database/runtime";function Bf(t){let e=Number(t);return Number.isFinite(e)?e/100:0}async function xn(t={}){let e=Jf.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=Bf(i.rate),c=Math.round(o*u),l=Boolean(r.exempt&&i.exemptible);if(l)s+=c;else a+=c;n.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:l?0:c,exempted:l})}return{taxable:o,components:n,tax:a,exempted:s}}async function Al(t,e={}){return Dn(t,await xn(e),e)}import{db as Ml}from"@stacksjs/database/runtime";async function Il(t){try{let e=await Ml.deleteFrom("tax_rates").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rate: ${e.message}`);throw e}}async function Nl(t){if(!t.length)return 0;try{let e=await Ml.deleteFrom("tax_rates").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rates: ${e.message}`);throw e}}import{db as Jl}from"@stacksjs/database/runtime";async function Bl(t){let e=await Jl.selectFrom("tax_rates").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Ol(){return w(await Jl.selectFrom("tax_rates").selectAll().execute())}var{randomUUIDv7:Ul}=globalThis.Bun;import{db as $l}from"@stacksjs/database/runtime";async function Wl(t){try{return await $l.transaction(async(e)=>{let r={...t,uuid:Ul()};if(r.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();let o=await e.insertInto("tax_rates").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create tax rate");return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rate: ${e.message}`);throw e}}async function Ll(t){if(!t.length)return 0;try{return await $l.transaction(async(e)=>{let r=0;for(let o of t){let n={...o,uuid:Ul()};if(n.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();if(await e.insertInto("tax_rates").values(n).executeTakeFirst())r++}return r})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${e.message}`);throw e}}import{db as kr}from"@stacksjs/database/runtime";import{formatDate as Tr}from"@stacksjs/orm";async function jl(t,e){try{if(!t)throw Error("Tax rate ID is required for update");return await kr.transaction(async(r)=>{let o=await r.selectFrom("tax_rates").select("is_default").where("id","=",t).executeTakeFirst();if(!o)return;let n=e.is_default??Boolean(o.is_default),a=Tr(new Date);if(n)await r.updateTable("tax_rates").set({is_default:!1,updated_at:a}).where("id","!=",t).execute();let s=await r.updateTable("tax_rates").set({...e,updated_at:a}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function zl(t,e){try{let r=await kr.updateTable("tax_rates").set({status:e,updated_at:Tr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function Gl(t,e){try{let r=await kr.updateTable("tax_rates").set({rate:e,updated_at:Tr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function ql(t,e){try{return await kr.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",t).executeTakeFirst())return!1;let n=Tr(new Date);if(e)await r.updateTable("tax_rates").set({is_default:!1,updated_at:n}).where("id","!=",t).execute();return await r.updateTable("tax_rates").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate default status: ${r.message}`);throw r}}var Sn={};g(Sn,{default:()=>Vf,products:()=>Sr,restaurant:()=>Ie});var Sr={};g(Sr,{bulkDestroy:()=>Zl,bulkStore:()=>lm,destroy:()=>Vl,fetchAll:()=>Hl,fetchById:()=>mt,fetchCancelledBetweenDates:()=>rm,fetchConversionRates:()=>am,fetchCountBetweenDates:()=>sm,fetchCountByAllQuantities:()=>Xl,fetchCountByDate:()=>Ql,fetchCountByDateGrouped:()=>im,fetchCountByQuantity:()=>Yl,fetchCountBySource:()=>Kl,fetchCountByStatus:()=>nm,fetchNotifiedBetweenDates:()=>em,fetchPurchasedBetweenDates:()=>tm,fetchWaiting:()=>om,store:()=>dm,update:()=>Er,updatePartySize:()=>pm,updateStatus:()=>mm});import{db as Pn}from"@stacksjs/database/runtime";async function Vl(t){try{let e=await Pn.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await Pn.deleteFrom("waitlist_products").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist product: ${e.message}`);throw e}}async function Zl(t){if(!t.length)return 0;try{let e=await Pn.deleteFrom("waitlist_products").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${e.message}`);throw e}}import{db as F}from"@stacksjs/database/runtime";import{formatDate as k}from"@stacksjs/orm";async function mt(t){let e=await F.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Hl(){return w(await F.selectFrom("waitlist_products").selectAll().execute())}async function Kl(t,e){let r=F.selectFrom("waitlist_products").select(["source",F.fn.count("id").as("count")]).groupBy("source");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{source:a,count:s})=>(n[a]=s,n),{})}async function Ql(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=k(e),n=k(r);return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function Yl(t){return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("quantity","=",t).executeTakeFirst())?.count??0}async function Xl(t,e){let r=F.selectFrom("waitlist_products").select(["quantity",F.fn.count("id").as("count")]).groupBy("quantity");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{quantity:a,count:s})=>(n[a]=s,n),{})}async function em(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",o).whereNotNull("notified_at").execute();return w(n)}async function tm(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",o).whereNotNull("purchased_at").execute();return w(n)}async function rm(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",o).whereNotNull("cancelled_at").execute();return w(n)}async function om(){let t=await F.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute();return w(t)}async function nm(t,e,r){let o=F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("status","=",t);if(e&&r){let a=k(e),s=k(r);o=o.where("created_at",">=",a).where("created_at","<=",s)}return(await o.executeTakeFirst())?.count??0}async function am(t,e){let r=F.selectFrom("waitlist_products").select(["status",F.fn.count("id").as("count")]).groupBy("status");if(t&&e){let u=k(t),c=k(e);r=r.where("created_at",">=",u).where("created_at","<=",c)}let o=await r.execute(),n=o.reduce((u,{count:c})=>u+c,0),a=Number(o.find((u)=>u.status==="purchased")?.count??0),s=n>0?a/n*100:0,i=o.reduce((u,{status:c,count:l})=>(u[c]={count:l,percentage:n>0?l/n*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function sm(t,e){let r=k(t),o=k(e);return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",o).executeTakeFirst())?.count??0}async function im(t,e){let r=F.selectFrom("waitlist_products").select(["created_at"]);if(t&&e){let a=k(t),s=k(e);r=r.where("created_at",">=",a).where("created_at","<=",s)}let n=(await r.execute()).reduce((a,{created_at:s})=>{let i=(s||"").split("T")[0]||"unknown";return a[i]=(a[i]||0)+1,a},{});return Object.entries(n).map(([a,s])=>({date:a,count:s})).sort((a,s)=>a.date.localeCompare(s.date))}var{randomUUIDv7:cm}=globalThis.Bun;import{db as Fn}from"@stacksjs/database/runtime";import{formatDate as um}from"@stacksjs/orm";var Of={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Uf(t){return typeof t==="number"||t instanceof Date?um(t):t}function pt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));if(r.quantity===void 0&&r.party_size!==void 0)r.quantity=r.party_size;delete r.party_size;for(let n of["notified_at","purchased_at","cancelled_at"])if(r[n]!==void 0)r[n]=Uf(r[n]);let o=Of[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=um(new Date);return r}async function dm(t){try{let e=cm(),r={...pt(t),uuid:e,status:t.status||"waiting"};await Fn.insertInto("waitlist_products").values(r).executeTakeFirst();let o=await Fn.selectFrom("waitlist_products").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create waitlist product");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist product: ${e.message}`);throw e}}async function lm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...pt(o),status:o.status||"waiting",uuid:cm()})),r=await Fn.insertInto("waitlist_products").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${e.message}`);throw e}}import{db as $f}from"@stacksjs/database/runtime";import{formatDate as Wf}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 $f.updateTable("waitlist_products").set({...pt(e,r),updated_at:Wf(new Date)}).where("id","=",t).execute();let o=await mt(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function mm(t,e){return await Er(t,{status:e})}async function pm(t,e){return await Er(t,{quantity:e})}var Ie={};g(Ie,{bulkDestroy:()=>wm,bulkStore:()=>Jm,destroy:()=>fm,fetchAll:()=>ym,fetchAverageWaitTimes:()=>Pm,fetchBetweenDates:()=>Rm,fetchById:()=>ft,fetchConversionRates:()=>vm,fetchCountByAllPartySizes:()=>_m,fetchCountByDate:()=>gm,fetchCountByPartySize:()=>bm,fetchCountByTablePreference:()=>hm,fetchCurrentWaitTimes:()=>Cm,fetchNoShowStats:()=>Sm,fetchSeatedBetweenDates:()=>xm,fetchSeatedStats:()=>Am,fetchSeatingRate:()=>Em,fetchTablesTurnedToday:()=>Tm,fetchTimeSeriesStats:()=>Mm,fetchWaiting:()=>Dm,fetchWaitingWithPartySizes:()=>km,fetchWaitingWithQuotedTimes:()=>Fm,store:()=>Nm,update:()=>Me,updatePartySize:()=>Om,updateQueuePosition:()=>$m,updateStatus:()=>Bm,updateWaitTimes:()=>Um});import{db as kn}from"@stacksjs/database/runtime";async function fm(t){try{let e=await kn.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await kn.deleteFrom("waitlist_restaurants").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${e.message}`);throw e}}async function wm(t){if(!t.length)return 0;try{let e=await kn.deleteFrom("waitlist_restaurants").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as R}from"@stacksjs/database/runtime";import{formatDate as B}from"@stacksjs/orm";async function ft(t){let e=await R.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ym(){return w(await R.selectFrom("waitlist_restaurants").selectAll().execute())}async function hm(){return(await R.selectFrom("waitlist_restaurants").select(["table_preference",R.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((e,{table_preference:r,count:o})=>(e[r]=o,e),{})}async function gm(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r);return(await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function bm(t){return(await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("party_size","=",t).executeTakeFirst())?.count??0}async function _m(){return(await R.selectFrom("waitlist_restaurants").select(["party_size",R.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((e,{party_size:r,count:o})=>(e[r]=o,e),{})}async function Rm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",o).execute();return w(n)}async function xm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",o).where("status","=","seated").execute();return w(n)}async function Dm(){let t=await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute();return w(t)}async function vm(){let t=await R.selectFrom("waitlist_restaurants").select(["status",R.fn.count("id").as("count")]).groupBy("status").execute(),e=t.reduce((a,{count:s})=>a+s,0),r=t.find((a)=>a.status==="seated")?.count??0,o=e>0?Number(r)/e*100:0,n=t.reduce((a,{status:s,count:i})=>(a[s]={count:i,percentage:e>0?i/e*100:0},a),{});return{totalConversionRate:o,statusBreakdown:n}}async function Pm(){let t=await R.selectFrom("waitlist_restaurants").select([R.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),R.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:t?.avg_quoted_wait_time??0,averageActualWaitTime:t?.avg_actual_wait_time??0}}async function Fm(){let t=w(await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((o,n)=>o+(n.quoted_wait_time??0),0),r=t.length>0?e/t.length:0;return{entries:t,totalQuotedWaitTime:e,averageQuotedWaitTime:r}}async function km(){let t=w(await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((n,a)=>n+a.party_size,0),r=t.length>0?e/t.length:0,o=t.reduce((n,a)=>(n[a.party_size]=(n[a.party_size]||0)+1,n),{});return{entries:t,totalPartySize:e,averagePartySize:r,partySizeBreakdown:o}}async function Tm(){let t=new Date,e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r),a=await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",o).where("check_in_time","<=",n).execute(),s=a.length,i=a.reduce((m,f)=>m+f.party_size,0),u=s>0?i/s:0,c=a.reduce((m,f)=>(m[f.table_preference]=(m[f.table_preference]||0)+1,m),{}),l=a.reduce((m,f)=>(m[f.party_size]=(m[f.party_size]||0)+1,m),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:l}}async function Em(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").select(["status",R.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",o).groupBy("status").execute(),a=n.reduce((c,{count:l})=>c+l,0),s=n.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=n.reduce((c,{status:l,count:m})=>(c[l]={count:m,percentage:a>0?m/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function Sm(t,e){let r=B(t),o=B(e),n=R.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",o),a=await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("check_in_time",">=",r).where("check_in_time","<=",o).executeTakeFirst(),s=await n.execute(),i=s.length,u=a?.count&&a.count>0?i/a.count*100:0,c=s.reduce((_,D)=>_+(D.quoted_wait_time??0),0),l=i>0?c/i:0,m=s.reduce((_,D)=>_+D.party_size,0),f=i>0?m/i:0,h=s.reduce((_,D)=>(_[D.table_preference]=(_[D.table_preference]||0)+1,_),{}),b=s.reduce((_,D)=>(_[D.party_size]=(_[D.party_size]||0)+1,_),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:l,averagePartySize:f,breakdownByTablePreference:h,breakdownByPartySize:b}}async function Cm(){let t=await R.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),e=t.reduce((n,a)=>n+(a.quoted_wait_time||0),0),r=t.reduce((n,a)=>n+(a.actual_wait_time||0),0),o=t.length;return{averageQuoted:o>0?e/o:0,averageActual:o>0?r/o:0}}async function Am(){let t=Date.now()-86400000,e=await R.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",t).execute(),r=Array.from({length:24},(o,n)=>({hour:n,count:e.filter((a)=>a.seated_at===n).length}));return{total:e.length,byHour:r}}async function Mm(){return(await R.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((e,r)=>{let o=r.created_at;if(!e[o])e[o]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return e[o].total++,e[o][r.status]++,e},{})}var{randomUUIDv7:Im}=globalThis.Bun;import{db as En}from"@stacksjs/database/runtime";import{formatDate as Tn}from"@stacksjs/orm";var Lf={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function jf(t){if(typeof t==="number")return Tn(t<=2147483647?t*1000:t);if(t instanceof Date)return Tn(t);return t}function wt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));for(let n of["check_in_time","seated_at","no_show_at","cancelled_at"])if(r[n]!==void 0)r[n]=jf(r[n]);let o=Lf[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=Tn(new Date);return r}async function Nm(t){try{let e=Im(),r={...wt(t),status:t.status||"waiting",uuid:e};await En.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let o=await En.selectFrom("waitlist_restaurants").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create restaurant waitlist entry");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${e.message}`);throw e}}async function Jm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...wt(o),status:o.status||"waiting",uuid:Im()})),r=await En.insertInto("waitlist_restaurants").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as zf}from"@stacksjs/database/runtime";import{formatDate as Gf}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 zf.updateTable("waitlist_restaurants").set({...wt(e,r),updated_at:Gf(new Date)}).where("id","=",t).execute();let o=await ft(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function Bm(t,e){return await Me(t,{status:e})}async function Om(t,e){return await Me(t,{party_size:e})}async function Um(t,e,r){return await Me(t,{quoted_wait_time:e,...r===void 0?{}:{actual_wait_time:r}})}async function $m(t,e){return await Me(t,{queue_position:e})}var qf={products:Sr,restaurant:Ie},Vf=qf;var Zf={auctions:no,carts:ao,coupons:io,customers:co,devices:wo,errors:go,giftCards:Ro,orders:No,payments:Jo,products:jo,receipts:Ho,restaurant:Ie,shippings:Rn,tax:vn,waitlists:Sn},mk=Zf;export{no as auctions,ao as carts,Zf as commerce,io as coupons,co as customers,mk as default,wo as devices,go as errors,Ro as giftCards,No as orders,Jo as payments,jo as products,Ho as receipts,Ie as restaurant,Rn as shippings,vn as tax,Sn as waitlists};
|
|
28
|
+
AND COALESCE(refund_amount, 0) + ${n(5)} <= amount`,[t,t,o,e,t]);if(Zw(a)>0){let d=await Me(e);if(d)return d;throw Error(`Payment with ID ${e} disappeared during refund`)}let s=await Me(e);if(!s)throw Error(`Payment with ID ${e} not found`);let i=String(s.status||"");if(!Xw.has(i))throw Error(`Payment status ${i||"unknown"} cannot be refunded`);let u=s,c=Number(s.amount||0)-Number(u.refundAmount??u.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${c} minor units`)}var No={};D(No,{categories:()=>ar,default:()=>yy,items:()=>sr,manufacturers:()=>ir,reviews:()=>ur,units:()=>lr,variants:()=>pr});var ar={};D(ar,{bulkRemove:()=>cc,compareCategoryGrowth:()=>ac,deactivate:()=>lc,deactivateChildCategories:()=>pc,fetchActive:()=>ec,fetchAll:()=>So,fetchByDisplayOrder:()=>nc,fetchById:()=>U,fetchByName:()=>Xu,fetchCategoryTree:()=>sc,fetchChildCategories:()=>rc,fetchRootCategories:()=>tc,fetchStats:()=>oc,findOrCreateByName:()=>fc,remove:()=>uc,removeChildCategories:()=>dc,store:()=>Co,update:()=>wc,updateActiveStatus:()=>gc,updateDisplayOrder:()=>yc,updateParent:()=>hc});import{db as ft,matchedRows as ey}from"@stacksjs/database/runtime";import{formatDate as ic}from"@stacksjs/orm";import{db as E}from"@stacksjs/database/runtime";import{formatDate as mt}from"@stacksjs/orm";async function So(){return await E.selectFrom("categories").selectAll().execute()}async function U(e){return await E.selectFrom("categories").where("id","=",e).selectAll().executeTakeFirst()}async function Xu(e){return await E.selectFrom("categories").where("name","=",e).selectAll().executeTakeFirst()}async function ec(){return await E.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function tc(){return await E.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function rc(e){return await E.selectFrom("categories").where("parent_category_id","=",e).where("is_active","=",!0).selectAll().execute()}async function nc(e=!0){let t=E.selectFrom("categories").where("is_active","=",!0).selectAll();if(e)return await t.orderBy("display_order","asc").execute();else return await t.orderBy("display_order","desc").execute()}async function oc(){let e=await E.selectFrom("categories").select(E.fn.count("id").as("count")).executeTakeFirst(),t=await E.selectFrom("categories").where("is_active","=",!0).select(E.fn.count("id").as("count")).executeTakeFirst(),r=await E.selectFrom("categories").whereNull("parent_category_id").select(E.fn.count("id").as("count")).executeTakeFirst(),n=await E.selectFrom("categories").whereNotNull("image_url").select(E.fn.count("id").as("count")).executeTakeFirst(),o=new Date;o.setDate(o.getDate()-30);let a=mt(o),s=await E.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await E.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",E.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(e?.count||0),active:Number(t?.count||0),root_categories:Number(r?.count||0),child_categories:Number(e?.count||0)-Number(r?.count||0),with_images:Number(n?.count||0),recently_added:s,top_parent_categories:i.map((u)=>({id:String(u.parent_category_id||""),name:String(u.parent_name||""),child_count:Number(u.child_count)}))}}async function ac(e=30){let t=new Date,r=mt(t),n=new Date;n.setDate(t.getDate()-e);let o=mt(n),a=new Date(n);a.setDate(a.getDate()-1);let s=mt(a),i=new Date(a);i.setDate(a.getDate()-e);let u=mt(i),c=await E.selectFrom("categories").select(E.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",r).executeTakeFirst(),d=await E.selectFrom("categories").select(E.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),m=Number(c?.count||0),p=Number(d?.count||0),y=m-p,_=p!==0?y/p*100:m>0?100:0;return{current_period:m,previous_period:p,difference:y,percentage_change:_,days_range:e}}async function sc(){let e=await So(),t=new Map;e.forEach((o)=>{t.set(o.id,{...o,children:[]})});let r=[];e.forEach((o)=>{let a=t.get(o.id);if(o.parent_category_id){let s=t.get(o.parent_category_id);if(s)s.children.push(a)}else r.push(a)}),r.sort((o,a)=>o.display_order-a.display_order);let n=(o)=>{o.sort((a,s)=>a.display_order-s.display_order),o.forEach((a)=>{if(a.children.length>0)n(a.children)})};return n(r),r}async function uc(e){let t=await ft.deleteFrom("categories").where("id","=",e).executeTakeFirst();return f(t)>0}async function cc(e){if(!e.length)return 0;let t=await ft.deleteFrom("categories").where("id","in",e).executeTakeFirst();return f(t)}async function dc(e){let t=await ft.deleteFrom("categories").where("parent_category_id","=",e).executeTakeFirst();return f(t)}async function lc(e){if(!await U(e))throw Error(`Category with ID ${e} not found`);let r=await ft.updateTable("categories").set({is_active:!1,updated_at:ic(new Date)}).where("id","=",e).returning("id").executeTakeFirst();return Boolean(r)}async function pc(e){return(await ey(ft.updateTable("categories").set({is_active:!1,updated_at:ic(new Date)}).where("parent_category_id","=",e))).length}var{randomUUIDv7:ty}=globalThis.Bun;import{db as mc}from"@stacksjs/database/runtime";import{HttpError as nr}from"@stacksjs/error-handling";import{isUniqueViolation as ry}from"@stacksjs/orm";import{slug as ny}from"@stacksjs/strings";async function Co(e){try{let t=e.parent_category_id?Number(e.parent_category_id):void 0;if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new nr(422,"Parent category ID must be a positive integer");if(t&&!await U(t))throw new nr(422,`Parent category with ID ${e.parent_category_id} not found`);let r={...e,uuid:ty(),is_active:e.is_active??!0,parent_category_id:e.parent_category_id||null},n=await mc.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create category");return n}catch(t){if(t instanceof nr)throw t;if(ry(t))throw new nr(409,"A category with this name or slug already exists");if(t instanceof Error)throw Error(`Failed to create category: ${t.message}`);throw t}}async function fc(e){if(!e.name)throw Error("Name is required");let t=await mc.selectFrom("categories").selectAll().where("name","=",e.name).executeTakeFirst();if(t)return t;let r={name:e.name,slug:ny(e.name),is_active:e.is_active??!0,display_order:0};return await Co(r)}import{db as wt}from"@stacksjs/database/runtime";import{HttpError as Ge}from"@stacksjs/error-handling";import{formatDate as or,isUniqueViolation as oy}from"@stacksjs/orm";async function wc(e,t){if(!await U(e))return;if(Object.hasOwn(t,"parent_category_id")){let n=t.parent_category_id?Number(t.parent_category_id):void 0;if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw new Ge(422,"Parent category ID must be a positive integer");if(n===e)throw new Ge(422,"A category cannot be its own parent");if(n&&!await U(n))throw new Ge(422,`Parent category with ID ${t.parent_category_id} not found`);if(n&&await bc(e,String(n)))throw new Ge(422,"This operation would create a circular category hierarchy")}try{let n=Object.hasOwn(t,"parent_category_id")?{parent_category_id:t.parent_category_id||null}:{},o=await wt.updateTable("categories").set({...t,...n,updated_at:or(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!o)return;return o}catch(n){if(n instanceof Ge)throw n;if(oy(n))throw new Ge(409,"A category with this name or slug already exists");if(n instanceof Error)throw Error(`Failed to update category: ${n.message}`);throw n}}async function yc(e,t){if(!await U(e))throw Error(`Category with ID ${e} not found`);try{return await wt.updateTable("categories").set({display_order:t,updated_at:or(new Date)}).where("id","=",e).execute(),await U(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category display order: ${n.message}`);throw n}}async function gc(e,t){if(!await U(e))throw Error(`Category with ID ${e} not found`);try{return await wt.updateTable("categories").set({is_active:t,updated_at:or(new Date)}).where("id","=",e).execute(),await U(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category active status: ${n.message}`);throw n}}async function hc(e,t){if(!await U(e))throw Error(`Category with ID ${e} not found`);if(t){let n=Number(t);if(n===e)throw Error("A category cannot be its own parent");if(!await U(n))throw Error(`Parent category with ID ${t} not found`);if(await bc(e,t))throw Error("This operation would create a circular reference in the category hierarchy")}try{let n={updated_at:or(new Date)};if(t===null)await wt.updateTable("categories").set({...n,parent_category_id:null}).where("id","=",e).execute();else await wt.updateTable("categories").set({...n,parent_category_id:t}).where("id","=",e).execute();return await U(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update category parent: ${n.message}`);throw n}}async function bc(e,t){let r=Number(t),n=new Set;while(r){if(n.has(r))return!0;if(r===e)return!0;n.add(r);let o=await U(r),a=o?.parent_category_id;if(!o||!a)return!1;r=Number(a)}return!1}var sr={};D(sr,{bulkDestroy:()=>Rc,bulkStore:()=>Sc,destroy:()=>xc,fetchAll:()=>Pc,fetchById:()=>fe,fetchTopProducts:()=>Dc,store:()=>Tc,update:()=>Cc,updateAvailability:()=>Ec,updateInventory:()=>Ac});import{db as _c}from"@stacksjs/database/runtime";async function xc(e){try{let t=await _c.deleteFrom("products").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product item: ${t.message}`);throw t}}async function Rc(e){if(!e.length)return 0;try{let t=await _c.deleteFrom("products").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product items: ${t.message}`);throw t}}import{db as me,sql as ay}from"@stacksjs/database/runtime";async function fe(e){let t=await me.selectFrom("products").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=null,n=null;if(t.manufacturer_id)r=await me.selectFrom("manufacturers").where("id","=",t.manufacturer_id).selectAll().executeTakeFirst();if(t.category_id)n=await me.selectFrom("categories").where("id","=",t.category_id).selectAll().executeTakeFirst();return{...t,manufacturer:r,category:n}}return}async function Pc(){let e=await me.selectFrom("products").selectAll().execute(),t=e.map((c)=>c.manufacturer_id).filter((c)=>c!==null&&c!==void 0),r=e.map((c)=>c.category_id).filter((c)=>c!==null&&c!==void 0),n=me.selectFrom("manufacturers"),o=me.selectFrom("categories");if(t.length>0)n=n.where("id","in",t);if(r.length>0)o=o.where("id","in",r);let a=await n.selectAll().execute(),s=await o.selectAll().execute(),i=a.reduce((c,d)=>(c[d.id]=d,c),{}),u=s.reduce((c,d)=>(c[d.id]=d,c),{});return e.map((c)=>({...c,manufacturer:c.manufacturer_id?i[c.manufacturer_id]:null,category:c.category_id?u[c.category_id]:null}))}async function vc(e){try{let t=await me.selectFrom("products").selectAll().where("uuid","=",e).executeTakeFirst();return l(t,!0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get product by UUID: ${t.message}`);throw t}}async function Dc(e=5){try{return(await me.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",me.fn.sum("order_items.quantity").as("units_sold"),ay`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(e).execute()).map((r)=>({id:Number(r.id),name:String(r.name??"Unnamed product"),units_sold:Number(r.units_sold??0),revenue:Number(r.revenue??0),inventory_count:Number(r.inventory_count??0)}))}catch(t){if(t instanceof Error)throw TypeError(`Failed to fetch top products: ${t.message}`);throw t}}var{randomUUIDv7:kc}=globalThis.Bun;import{db as Fc}from"@stacksjs/database/runtime";async function Tc(e){try{let t={...e,uuid:kc()},r=await Fc.insertInto("products").values(t).executeTakeFirst();if(!r)throw Error("Failed to create product item");let n=ce(r),o=n!==void 0?await fe(n):await vc(t.uuid);if(!o)throw Error("Failed to create product item");return o}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product item: ${t.message}`);throw t}}async function Sc(e){if(!e.length)return 0;let t=0;try{return await Fc.transaction(async(r)=>{for(let n of e){let o={...n,uuid:kc()};await r.insertInto("products").values(o).execute(),t++}}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product items in bulk: ${r.message}`);throw r}}import{db as Eo,matchedRows as lP}from"@stacksjs/database/runtime";import{formatDate as Ao}from"@stacksjs/orm";async function Cc(e,t){try{if(!e)throw Error("Product item ID is required for update");let r=await Eo.updateTable("products").set({...t,updated_at:Ao(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function Ec(e,t){if(!await fe(e))throw Error(`Product item with ID ${e} not found`);try{return await Eo.updateTable("products").set({is_available:t,updated_at:Ao(new Date)}).where("id","=",e).execute(),await fe(e)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update product item availability: ${n.message}`);throw n}}async function Ac(e,t){let r=await fe(e);if(!r)throw Error(`Product item with ID ${e} not found`);let n={updated_at:Ao(new Date)};if(t!==void 0)n.inventory_count=t;if(Object.keys(n).length===1)return r;try{return await Eo.updateTable("products").set(n).where("id","=",e).execute(),await fe(e)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update inventory information: ${o.message}`);throw o}}var ir={};D(ir,{bulkDestroy:()=>Nc,bulkStore:()=>Vc,destroy:()=>Ic,fetchAll:()=>$c,fetchByCountry:()=>Uc,fetchById:()=>Oc,fetchByUuid:()=>Jc,fetchFeatured:()=>Bc,fetchWithProductCount:()=>Wc,store:()=>Gc,update:()=>Hc,updateByUuid:()=>Zc,updateFeaturedStatus:()=>Kc});import{db as Mc}from"@stacksjs/database/runtime";async function Ic(e){try{let t=await Mc.deleteFrom("manufacturers").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete order: ${t.message}`);throw t}}async function Nc(e){if(!e.length)return 0;try{let t=await Mc.deleteFrom("manufacturers").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete orders: ${t.message}`);throw t}}import{db as we}from"@stacksjs/database/runtime";async function $c(){return g(await we.selectFrom("manufacturers").selectAll().execute())}async function Oc(e){let t=await we.selectFrom("manufacturers").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function Jc(e){let t=await we.selectFrom("manufacturers").where("uuid","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function Bc(e=10){let t=await we.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(e).execute();return g(t)}async function Uc(e,t={}){let r=t.page||1,n=t.limit||2,o=await we.selectFrom("manufacturers").select(we.fn.count("id").as("total")).where("country","=",e).executeTakeFirst(),a=Number(o?.total||0),s=await we.selectFrom("manufacturers").selectAll().where("country","=",e).limit(n).offset((r-1)*n).execute(),i=Math.ceil(a/n);return{data:g(s),paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function Wc(e={}){let t=we.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(e.country)t=t.where("m.country","=",e.country);if(e.featured!==void 0)t=t.where("m.featured","=",e.featured);return t=t.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",we.fn.count("p.id").as("product_count")]).groupBy("m.id"),t.execute()}var{randomUUIDv7:jc}=globalThis.Bun;import{db as zc}from"@stacksjs/database/runtime";import{HttpError as Lc}from"@stacksjs/error-handling";import{isUniqueViolation as sy}from"@stacksjs/orm";async function Gc(e){try{let t={...e,uuid:jc(),featured:e.featured??!1},r=await zc.insertInto("manufacturers").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return l(r)}catch(t){if(t instanceof Lc)throw t;if(sy(t))throw new Lc(409,"A manufacturer with this name already exists");if(t instanceof Error)throw Error(`Failed to create manufacturer: ${t.message}`);throw t}}async function Vc(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:jc(),featured:r.featured??!1};await zc.insertInto("manufacturers").values(n).execute(),t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${r.message}`);throw r}}import{db as Mo}from"@stacksjs/database/runtime";import{HttpError as qc}from"@stacksjs/error-handling";import{formatDate as Io,isUniqueViolation as iy}from"@stacksjs/orm";async function Hc(e,t){try{if(!e)throw Error("Manufacturer ID is required for update");let r=await Mo.updateTable("manufacturers").set({...t,updated_at:Io(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return l(r)}catch(r){if(r instanceof qc)throw r;if(iy(r))throw new qc(409,"A manufacturer with this name already exists");if(r instanceof Error)throw Error(`Failed to update manufacturer: ${r.message}`);throw r}}async function Kc(e,t){try{let r=await Mo.updateTable("manufacturers").set({featured:t,updated_at:Io(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function Zc(e,t){try{let r=await Mo.updateTable("manufacturers").set({...t,updated_at:Io(new Date)}).where("uuid","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var ur={};D(ur,{bulkDestroy:()=>Xc,destroy:()=>Yc,fetchAll:()=>td,fetchApprovedByProductId:()=>od,fetchById:()=>ed,fetchByProductId:()=>rd,fetchByUserId:()=>nd,fetchMostHelpfulByProductId:()=>ad,fetchStats:()=>cd,fetchStatsByProductIds:()=>dd,store:()=>ld,update:()=>fd,updateVotes:()=>wd});import{db as Qc}from"@stacksjs/database/runtime";async function Yc(e){try{let t=await Qc.deleteFrom("reviews").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete review: ${t.message}`);throw t}}async function Xc(e){if(!e.length)return 0;try{let t=await Qc.deleteFrom("reviews").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete reviews: ${t.message}`);throw t}}import{db as Ve}from"@stacksjs/database/runtime";async function ed(e){return l(await Ve.selectFrom("reviews").where("id","=",e).selectAll().executeTakeFirst(),!0)}async function td(){return g(await Ve.selectFrom("reviews").selectAll().execute())}async function rd(e){return g(await Ve.selectFrom("reviews").where("product_id","=",e).selectAll().execute())}async function nd(e){return g(await Ve.selectFrom("reviews").where("customer_id","=",e).selectAll().execute())}async function od(e){return g(await Ve.selectFrom("reviews").where("product_id","=",e).where("is_approved","=",!0).selectAll().execute())}async function ad(e){return g(await Ve.selectFrom("reviews").where("product_id","=",e).orderBy("helpful_votes","desc").selectAll().execute())}import{db as sd}from"@stacksjs/database/runtime";function id(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function ud(e){let t=id();t.total=e.length;let r=0;for(let n of e){if(n.rating===null||n.rating===void 0){t.commentsOnly++;continue}let o=Number(n.rating);if(Number.isNaN(o)){t.commentsOnly++;continue}t.rated++,r+=o;let a=Math.min(5,Math.max(1,Math.round(o)));t.distribution[a]++}if(t.rated>0)t.average=Math.round(r/t.rated*10)/10;return t}async function cd(e){let t=await sd.selectFrom("reviews").select(["rating"]).where("product_id","=",e).where("is_approved","=",!0).execute();return ud(t)}async function dd(e){let t=new Map;for(let o of e)t.set(o,id());if(e.length===0)return t;let r=await sd.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",e).where("is_approved","=",!0).execute(),n=new Map;for(let o of r){let a=n.get(o.product_id);if(a)a.push({rating:o.rating});else n.set(o.product_id,[{rating:o.rating}])}for(let[o,a]of n)t.set(o,ud(a));return t}var{randomUUIDv7:uy}=globalThis.Bun;import{db as cy}from"@stacksjs/database/runtime";function dy(e){let t=e.rating!==void 0&&e.rating!==null,r=typeof e.content==="string"&&e.content.trim().length>0,n=typeof e.title==="string"&&e.title.trim().length>0;return!t&&!r&&!n}async function ld(e){try{if(dy(e))throw Error("A review needs a rating or something written: both were empty");let t={...e,uuid:uy(),rating:e.rating??null,is_verified_purchase:e.is_verified_purchase??!1,is_approved:e.is_approved??!1,helpful_votes:e.helpful_votes??0,unhelpful_votes:e.unhelpful_votes??0,is_featured:e.is_featured??!1},r=await cy.insertInto("reviews").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return l(r)}catch(t){if(t instanceof Error){if(t.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${t.message}`)}throw t}}import{db as pd,sqlHelpers as ly}from"@stacksjs/database/runtime";import{env as py}from"@stacksjs/env";import{formatDate as md}from"@stacksjs/orm";async function fd(e,t){try{if(!e)throw Error("Review ID is required for update");let r=await pd.updateTable("reviews").set({...t,updated_at:md(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function wd(e,t,r=!0){try{let n=t==="helpful"?"helpful_votes":"unhelpful_votes",o=r?`COALESCE("${n}", 0) + 1`:`MAX(COALESCE("${n}", 0) - 1, 0)`,{param:a}=ly(py.DB_CONNECTION||"sqlite"),s=await pd.unsafe(`UPDATE "reviews" SET "${n}" = ${o}, "updated_at" = ${a(1)} WHERE "id" = ${a(2)} RETURNING *`,[md(new Date),e]).execute(),i=Array.isArray(s)?s[0]:s;if(!i)throw Error("Failed to update review votes");return l(i)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update review votes: ${n.message}`);throw n}}var lr={};D(lr,{bulkDestroy:()=>hd,bulkStore:()=>vd,bulkUpdate:()=>Td,destroy:()=>gd,fetchAll:()=>xd,fetchById:()=>_d,formatUnitOptions:()=>Dd,getDefaultUnit:()=>kd,store:()=>Pd,update:()=>Fd,updateDefaultStatus:()=>Sd});import{db as yd}from"@stacksjs/database/runtime";async function gd(e){try{let t=await yd.deleteFrom("product_units").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product unit: ${t.message}`);throw t}}async function hd(e){if(!e.length)return 0;try{let t=await yd.deleteFrom("product_units").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product units: ${t.message}`);throw t}}import{db as bd}from"@stacksjs/database/runtime";async function _d(e){let t=await bd.selectFrom("product_units").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function xd(){return g(await bd.selectFrom("product_units").selectAll().execute())}var{randomUUIDv7:Rd}=globalThis.Bun;import{db as yt}from"@stacksjs/database/runtime";async function Pd(e){try{return await yt.transaction(async(t)=>{let r={...e,uuid:Rd()},n=await t.insertInto("product_units").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create product unit");if(r.is_default&&r.type)await t.updateTable("product_units").set({is_default:!1}).where("type","=",r.type).where("id","!=",n.id).execute();return l(n)})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product unit: ${t.message}`);throw t}}async function vd(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:Rd()},o=await yt.insertInto("product_units").values(n).returningAll().executeTakeFirst();if(n.is_default&&n.type&&o)await yt.updateTable("product_units").set({is_default:!1}).where("type","=",n.type).where("id","!=",o.id).execute();t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product units in bulk: ${r.message}`);throw r}}function Dd(e){try{let t=yt.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(e)t=t.where("type","=",e);return t=t.orderBy("name"),t.execute().then((r)=>r.map((n)=>({id:String(n.id),name:n.name,abbreviation:n.abbreviation,is_default:n.is_default})))}catch(t){if(t instanceof Error)throw TypeError(`Failed to format unit options: ${t.message}`);throw t}}async function kd(e){try{let t=await yt.selectFrom("product_units").selectAll().where("type","=",e).where("is_default","=",!0).executeTakeFirst();return l(t,!0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get default unit: ${t.message}`);throw t}}import{db as cr,matchedRows as my}from"@stacksjs/database/runtime";import{formatDate as dr}from"@stacksjs/orm";async function Fd(e,t){try{if(!e)throw Error("Product unit ID is required for update");return await cr.transaction(async(r)=>{let n=await r.selectFrom("product_units").select(["type","is_default"]).where("id","=",e).executeTakeFirst();if(!n)return;let o=t.type??n.type;if((t.is_default??Boolean(n.is_default))&&o)await r.updateTable("product_units").set({is_default:!1,updated_at:dr(new Date)}).where("type","=",o).where("id","!=",e).execute();let s=await r.updateTable("product_units").set({...t,updated_at:dr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!s)return;return l(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function Td(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n=r;if(!n.id)continue;let o=n.data&&typeof n.data==="object"?n.data:{...n};delete o.id;let a=await my(cr.updateTable("product_units").set({...o,updated_at:dr(new Date)}).where("id","=",n.id)),s=o;if(s.is_default===!0&&s.type)await cr.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",n.id).execute();if(a.length>0)t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product units in bulk: ${r.message}`);throw r}}async function Sd(e,t){try{return await cr.transaction(async(r)=>{let n=await r.selectFrom("product_units").select("type").where("id","=",e).executeTakeFirst();if(!n)return!1;let o=dr(new Date);if(t&&n.type)await r.updateTable("product_units").set({is_default:!1,updated_at:o}).where("type","=",n.type).where("id","!=",e).execute();return await r.updateTable("product_units").set({is_default:t,updated_at:o}).where("id","=",e).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit default status: ${r.message}`);throw r}}var pr={};D(pr,{bulkDestroy:()=>Ad,bulkStore:()=>Bd,bulkUpdate:()=>Gd,destroy:()=>Ed,fetchAll:()=>Nd,fetchById:()=>Id,formatVariantOptions:()=>Ud,generateVariantCombinations:()=>Wd,store:()=>Jd,update:()=>zd});import{db as Cd}from"@stacksjs/database/runtime";async function Ed(e){try{let t=await Cd.deleteFrom("product_variants").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product variant: ${t.message}`);throw t}}async function Ad(e){if(!e.length)return 0;try{let t=await Cd.deleteFrom("product_variants").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete product variants: ${t.message}`);throw t}}import{db as Md}from"@stacksjs/database/runtime";async function Id(e){let t=await Md.selectFrom("product_variants").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function Nd(){return g(await Md.selectFrom("product_variants").selectAll().execute())}var{randomUUIDv7:$d}=globalThis.Bun;import{db as Od}from"@stacksjs/database/runtime";async function Jd(e){try{let t={...e,uuid:$d()},r=await Od.insertInto("product_variants").values(t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return l(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create product variant: ${t.message}`);throw t}}async function Bd(e){if(!e.length)return 0;let t=0;try{for(let r of e){let n={...r,uuid:$d()};await Od.insertInto("product_variants").values(n).execute(),t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${r.message}`);throw r}}function Ud(e){if(!e||!e.length)return JSON.stringify([]);let t=e.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(t)}function Wd(e){let t=Object.keys(e);if(!t.length)return[];function r(n,o){if(n===t.length)return[o];let a=t[n],s=e[a]??[],i=[];for(let u of s){let c={...o,[a]:u};i.push(...r(n+1,c))}return i}return r(0,{})}import{db as Ld,matchedRows as fy}from"@stacksjs/database/runtime";import{formatDate as jd}from"@stacksjs/orm";async function zd(e,t){try{let r=await Ld.updateTable("product_variants").set({...t,updated_at:jd(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function Gd(e){if(!e.length)return 0;let t=0;try{for(let r of e){if(!r.id)continue;if((await fy(Ld.updateTable("product_variants").set({...r,updated_at:jd(new Date)}).where("id","=",r.id))).length>0)t++}return t}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var wy={categories:ar,items:sr,manufacturers:ir,reviews:ur,units:lr,variants:pr},yy=wy;var Wo={};D(Wo,{bulkDestroy:()=>Hd,bulkStore:()=>nl,destroy:()=>qd,fetchAll:()=>Kd,fetchById:()=>qe,fetchPageStats:()=>Yd,fetchPrintJobStats:()=>Zd,fetchPrintTimeStats:()=>Xd,fetchPrintsPerHour:()=>el,fetchSuccessRate:()=>Qd,store:()=>rl,update:()=>ol,updatePrintJob:()=>sl,updateStatus:()=>al});import{db as Vd}from"@stacksjs/database/runtime";async function qd(e){try{let t=await Vd.deleteFrom("receipts").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete print log: ${t.message}`);throw t}}async function Hd(e){if(!e.length)return 0;try{let t=await Vd.deleteFrom("receipts").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete receipts: ${t.message}`);throw t}}import{db as $o}from"@stacksjs/database/runtime";import{formatDate as gy}from"@stacksjs/orm";function ne(e){return gy(e)}function hy(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e==="number"){let n=new Date(e<=2147483647?e*1000:e);return Number.isNaN(n.getTime())?null:n}let t=String(e||"").trim();if(!t)return null;if(/^\d{10}$/.test(t)){let n=new Date(Number(t)*1000);return Number.isNaN(n.getTime())?null:n}let r=new Date(t.includes("T")?t:`${t.replace(" ","T")}Z`);return Number.isNaN(r.getTime())?null:r}async function qe(e){let t=await $o.selectFrom("receipts").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function Kd(){return g(await $o.selectFrom("receipts").selectAll().execute())}async function Zd(e,t){let r=ne(e),n=ne(t),o=await K("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",n));return{total:o.total,success:o.success,failed:o.failed,warning:o.warning,averageSize:Math.round(o.averageSize),averagePages:Math.round(o.averagePages),averageDuration:Math.round(o.averageDuration)}}async function Qd(e,t){let r=ne(e),n=ne(t),o=await K("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(s)=>s.where("timestamp",">=",r).where("timestamp","<=",n));return{successRate:o.total>0?Math.round(o.success/o.total*100):0,total:o.total,success:o.success,failed:o.failed,warning:o.warning}}async function Yd(e,t){let r=ne(e),n=ne(t),o=await K("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",n));return{totalPages:o.totalPages,averagePagesPerReceipt:Math.round(o.averagePagesPerReceipt),totalReceipts:o.totalReceipts}}async function Xd(e,t){let r=ne(e),n=ne(t),o=await K("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",n));return{averageDuration:Math.round(o.averageDuration),minDuration:o.minDuration,maxDuration:o.maxDuration,totalJobs:o.totalJobs}}async function el(e,t){let r=typeof e==="number"?e:e.getTime(),n=typeof t==="number"?t:t.getTime(),o=ne(e),a=ne(t),s=await $o.selectFrom("receipts").where("timestamp",">=",o).where("timestamp","<=",a).selectAll().execute(),i=s.length,u=Math.ceil((n-r)/3600000),c=u>0?Math.round(i/u):0,d=Array.from({length:24},(m,p)=>({hour:p,count:0}));return s.forEach((m)=>{let p=hy(m.timestamp);if(!p)return;d[p.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:d}}var{randomUUIDv7:tl}=globalThis.Bun;import{db as Jo}from"@stacksjs/database/runtime";import{formatDate as Oo}from"@stacksjs/orm";function gt(e){try{if(typeof e==="number")return Oo(e<=2147483647?e*1000:e);if(typeof e==="string"&&/^\d{10}$/.test(e))return Oo(Number(e)*1000);return Oo(e)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function rl(e){try{let t=tl(),r={...e,timestamp:gt(e.timestamp),uuid:t};await Jo.insertInto("receipts").values(r).executeTakeFirst();let n=await Jo.selectFrom("receipts").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create receipt");return l(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create receipt: ${t.message}`);throw t}}async function nl(e){if(!e.length)return 0;try{let t=e.map((n)=>({...n,timestamp:gt(n.timestamp),uuid:tl()})),r=await Jo.insertInto("receipts").values(t).executeTakeFirst();return f(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${t.message}`);throw t}}import{db as Bo}from"@stacksjs/database/runtime";import{formatDate as Uo}from"@stacksjs/orm";async function ol(e,t){try{if(!e)throw Error("Receipt ID is required for update");let r={...t,...t.timestamp===void 0?{}:{timestamp:gt(t.timestamp)},updated_at:Uo(new Date)};await Bo.updateTable("receipts").set(r).where("id","=",e).execute();let n=await qe(e);if(!n)return;return l(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function al(e,t){try{await Bo.updateTable("receipts").set({status:t,updated_at:Uo(new Date)}).where("id","=",e).execute();let r=await qe(e);if(!r)throw Error("Failed to update receipt status");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function sl(e,t,r,n){try{let o={updated_at:Uo(new Date)};if(t!==void 0)o.size=t;if(r!==void 0)o.pages=r;if(n!==void 0)o.duration=n;await Bo.updateTable("receipts").set(o).where("id","=",e).execute();let a=await qe(e);if(!a)throw Error("Failed to update receipt job information");return l(a)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update receipt job information: ${o.message}`);throw o}}var pa={};D(pa,{couriers:()=>Rr,default:()=>Ly,digital:()=>_r,geocoding:()=>kr,licenses:()=>Sr,methods:()=>Mr,rates:()=>Jr,routes:()=>hr,tracking:()=>Vr,zones:()=>Zr});var hr={};D(hr,{DeliveryRouteInputError:()=>q,bulkDestroy:()=>cl,destroy:()=>ul,fetchActive:()=>ll,fetchAll:()=>dl,fetchByCourier:()=>pl,fetchById:()=>fr,store:()=>ml,update:()=>wl,updateLastActive:()=>fl,updateMetrics:()=>gl,updateStops:()=>yl,validateDeliveryRouteWrite:()=>He});import{db as il}from"@stacksjs/database/runtime";async function ul(e){try{let t=await il.deleteFrom("delivery_routes").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete delivery route: ${t.message}`);throw t}}async function cl(e){if(!e.length)return 0;try{let t=await il.deleteFrom("delivery_routes").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete delivery routes: ${t.message}`);throw t}}import{db as mr}from"@stacksjs/database/runtime";async function fr(e){return await mr.selectFrom("delivery_routes").where("id","=",e).selectAll().executeTakeFirst()}async function dl(){return await mr.selectFrom("delivery_routes").selectAll().execute()}async function ll(){return await mr.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function pl(e){return await mr.selectFrom("delivery_routes").where("courier","=",e).selectAll().execute()}var{randomUUIDv7:xy}=globalThis.Bun;import{db as Lo}from"@stacksjs/database/runtime";function Ie(e,t){let r={};for(let[n,o]of Object.entries(t))for(let a of o){if(!Object.prototype.hasOwnProperty.call(e,a)||e[a]===void 0)continue;r[n]=e[a];break}return r}function ht(e){return Ie(e,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function ye(e){return Ie(e,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function bt(e){return Ie(e,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function _t(e){return Ie(e,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function xt(e){return Ie(e,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function Rt(e){return Ie(e,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function wr(e){return Ie(e,{courier:["courier"],courier_id:["courier_id","courierId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as by}from"@stacksjs/database/runtime";class q extends TypeError{constructor(e){super(e);this.name="DeliveryRouteInputError"}}function yr(e,t,r){return Number(e[r]??t?.[r])}function _y(e,t){let r=e.last_active??t?.last_active;if(r===void 0||r===null)return Date.now();if(r instanceof Date)return r.getTime();if(typeof r==="number")return r;if(typeof r==="string"&&/^\d{10,13}$/.test(r))return Number(r);return Number.NaN}async function He(e,t){let r=yr(e,t,"courier_id"),n=yr(e,t,"stops"),o=yr(e,t,"delivery_time"),a=yr(e,t,"total_distance"),s=_y(e,t);if(!Number.isSafeInteger(r)||r<1)throw new q("Courier must be a positive integer.");if(!Number.isSafeInteger(n)||n<0)throw new q("Stops must be a non-negative integer.");if(!Number.isSafeInteger(o)||o<0)throw new q("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(a)||a<0)throw new q("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(s)||s<0)throw new q("Last active must be a valid Unix timestamp.");let i=await by.selectFrom("couriers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new q(`Courier ${r} was not found.`);return{...e,courier_id:Number(i.id),courier:i.name,vehicle:i.vehicle_number,last_active:s}}async function ml(e){try{let t=xy(),r=wr(e),o={...await He(r),uuid:t};await Lo.insertInto("delivery_routes").values(o).executeTakeFirst();let a=await Lo.selectFrom("delivery_routes").where("uuid","=",t).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(t){if(t instanceof q)throw t;if(t instanceof Error)throw TypeError(`Failed to create delivery route: ${t.message}`);throw t}}async function fl(e){try{await Lo.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",e).execute();let t=await fr(e);if(!t)throw Error("Failed to update delivery route last active");return t}catch(t){if(t instanceof Error)throw TypeError(`Failed to update delivery route last active: ${t.message}`);throw t}}import{db as gr}from"@stacksjs/database/runtime";import{formatDate as jo}from"@stacksjs/orm";async function wl(e,t){try{if(!e)throw Error("Delivery route ID is required for update");let r=await gr.selectFrom("delivery_routes").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=wr(t),o=await He(n,r),a=await gr.updateTable("delivery_routes").set({...o,updated_at:jo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof q)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function yl(e,t){try{let r=await gr.updateTable("delivery_routes").set({stops:t,updated_at:jo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update delivery route stops");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update delivery route stops: ${r.message}`);throw r}}async function gl(e,t,r){try{let n={updated_at:jo(new Date)};if(t!==void 0)n.delivery_time=t;if(r!==void 0)n.total_distance=r;let o=await gr.updateTable("delivery_routes").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update delivery metrics");return o}catch(n){if(n instanceof Error)throw TypeError(`Failed to update delivery metrics: ${n.message}`);throw n}}var _r={};D(_r,{bulkDestroy:()=>xl,bulkSoftDelete:()=>Rl,bulkStore:()=>Tl,destroy:()=>bl,fetchAll:()=>Dl,fetchById:()=>vl,softDelete:()=>_l,store:()=>Fl,update:()=>Sl,updateDeliverySettings:()=>El,updateStatus:()=>Cl});import{db as br,matchedRows as hl}from"@stacksjs/database/runtime";async function bl(e){try{let t=await br.deleteFrom("digital_deliveries").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete digital delivery: ${t.message}`);throw t}}async function _l(e){try{return(await hl(br.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${t.message}`);throw t}}async function xl(e){if(!e.length)return 0;try{let t=await br.deleteFrom("digital_deliveries").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${t.message}`);throw t}}async function Rl(e){if(!e.length)return 0;try{return(await hl(br.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${t.message}`);throw t}}import{db as Pl}from"@stacksjs/database/runtime";async function vl(e){let t=await Pl.selectFrom("digital_deliveries").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function Dl(){return g(await Pl.selectFrom("digital_deliveries").selectAll().execute())}var{randomUUIDv7:kl}=globalThis.Bun;import{db as zo}from"@stacksjs/database/runtime";async function Fl(e){try{let t=kl(),r={..._t(e),uuid:t};await zo.insertInto("digital_deliveries").values(r).executeTakeFirst();let n=await zo.selectFrom("digital_deliveries").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created digital delivery");return l(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create digital delivery: ${t.message}`);throw t}}async function Tl(e){if(!e.length)return 0;try{let t=e.map((n)=>({..._t(n),uuid:kl()})),r=await zo.insertInto("digital_deliveries").values(t).executeTakeFirst();return f(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${t.message}`);throw t}}import{db as Go}from"@stacksjs/database/runtime";import{formatDate as Vo}from"@stacksjs/orm";async function Sl(e,t){try{if(!e)throw Error("Digital delivery ID is required for update");let r=await Go.updateTable("digital_deliveries").set({..._t(t),updated_at:Vo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function Cl(e,t){try{let r=await Go.updateTable("digital_deliveries").set({status:t,updated_at:Vo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function El(e,t,r,n,o){try{let a={updated_at:Vo(new Date)};if(t!==void 0)a.download_limit=t;if(r!==void 0)a.expiry_days=r;if(n!==void 0)a.requires_login=n;if(o!==void 0)a.automatic_delivery=o;let s=await Go.updateTable("digital_deliveries").set(a).where("id","=",e).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return l(s)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var Rr={};D(Rr,{bulkDestroy:()=>$l,bulkStore:()=>Bl,destroy:()=>Nl,fetchAll:()=>Ml,fetchById:()=>xr,store:()=>Jl,update:()=>Ul,updateContact:()=>Ll,updateStatus:()=>Wl});import{db as Il}from"@stacksjs/database/runtime";import{db as Al}from"@stacksjs/database/runtime";async function xr(e){let t=await Al.selectFrom("couriers").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function Ml(){return g(await Al.selectFrom("couriers").selectAll().execute())}async function Nl(e){try{let t=await Il.deleteFrom("couriers").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete courier: ${t.message}`);throw t}}async function $l(e){if(!e.length)return 0;let t=0;try{return await Il.transaction(async(r)=>{for(let n of e)if(await xr(n))await r.deleteFrom("couriers").where("id","=",n).execute(),t++}),t}catch(r){if(r instanceof Error)throw TypeError(`Failed to delete couriers in bulk: ${r.message}`);throw r}}var{randomUUIDv7:Ol}=globalThis.Bun;import{db as qo}from"@stacksjs/database/runtime";async function Jl(e){try{let t=Ol(),r={...Rt(e),uuid:t};await qo.insertInto("couriers").values(r).executeTakeFirst();let n=await qo.selectFrom("couriers").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created courier");return l(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create courier: ${t.message}`);throw t}}async function Bl(e){if(!e.length)return 0;try{let t=e.map((n)=>({...Rt(n),uuid:Ol()})),r=await qo.insertInto("couriers").values(t).executeTakeFirst();return f(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create couriers in bulk: ${t.message}`);throw t}}import{db as Ho}from"@stacksjs/database/runtime";import{formatDate as Ko}from"@stacksjs/orm";async function Ul(e,t){try{if(!e)throw Error("Courier ID is required for update");let r=await Ho.updateTable("couriers").set({...Rt(t),updated_at:Ko(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier: ${r.message}`);throw r}}async function Wl(e,t){try{let r=await Ho.updateTable("couriers").set({status:t,updated_at:Ko(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update courier status");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier status: ${r.message}`);throw r}}async function Ll(e,t){try{let r={updated_at:Ko(new Date)};if(t!==void 0)r.phone=t;let n=await Ho.updateTable("couriers").set(r).where("id","=",e).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update contact information");return l(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var kr={};D(kr,{PRECISION_RANK:()=>vt,checkCoverage:()=>Fy,formatQuery:()=>Ke,geocode:()=>ky,geocodingDriver:()=>Hl,nominatimDriver:()=>Dr,setGeocodingDriver:()=>Dy});var Ne=(e)=>e*Math.PI/180;function ke(e,t){let r=Ne(t.latitude-e.latitude),n=Ne(t.longitude-e.longitude),o=Ne(e.latitude),a=Ne(t.latitude),s=Math.sin(r/2)**2+Math.sin(n/2)**2*Math.cos(o)*Math.cos(a);return 12742017.6*Math.asin(Math.sqrt(s))}function Pr(e,t){let r=Ne(e.latitude),n=Ne(t.latitude),o=Ne(t.longitude-e.longitude),a=Math.sin(o)*Math.cos(n),s=Math.cos(r)*Math.sin(n)-Math.sin(r)*Math.cos(n)*Math.cos(o);return(Math.atan2(a,s)*180/Math.PI+360)%360}function vr(e,t,r={}){let n=r.detourFactor??1.35,o=r.minimumSeconds??30;if(!Number.isFinite(t)||t<=0.5)return null;let a=e*n/t;return Math.max(o,Math.round(a))}function jl(e,t,r){return ke(e,t)<=r}function Pt(e){return typeof e?.latitude==="number"&&typeof e?.longitude==="number"&&Number.isFinite(e.latitude)&&Number.isFinite(e.longitude)}var vt={unknown:0,locality:1,postal:2,street:3,rooftop:4};function Ke(e){return[e.street,e.city,e.region,e.postalCode,e.country].map((t)=>String(t??"").trim()).filter(Boolean).join(", ")}var Ry="https://nominatim.openstreetmap.org/search",zl=1000,Gl=0,Vl=Promise.resolve();async function Py(e){let t=Vl.then(async()=>{let r=Date.now()-Gl;if(r<zl)await Bun.sleep(zl-r);return Gl=Date.now(),e()});return Vl=t.then(()=>{return},()=>{return}),t}function vy(e){let t=e.address??{},r=String(e.addresstype??""),n=String(e.type??""),o=String(e.category??e.class??"");if(t.house_number||n==="house"||n==="building"||r==="building")return"rooftop";if(t.road||o==="highway"||r==="road")return"street";if(r==="postcode"||t.postcode&&!t.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(r))return"locality";return"unknown"}function Dr(e={}){let t=e.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,r=e.endpoint??Ry;return{name:"nominatim",async geocode(n){let o=Ke(n);if(!o)return null;let a=new URL(r);if(a.searchParams.set("q",o),a.searchParams.set("format","jsonv2"),a.searchParams.set("limit","1"),a.searchParams.set("addressdetails","1"),n.country)a.searchParams.set("countrycodes",n.country.toLowerCase());let s=await Py(()=>fetch(a,{headers:{"user-agent":t,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!s.ok)throw Error(`Nominatim responded ${s.status}`);let u=(await s.json())?.[0];if(!u)return null;let c=Number(u.lat),d=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(d))return null;let m=vy(u);return{latitude:c,longitude:d,formatted:String(u.display_name??o),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[m],precision:m,provider:"nominatim"}}}}var ql=null;function Dy(e){ql=e}function Hl(){return ql??Dr()}async function ky(e,t={}){let r=t.driver??Hl(),n=t.minimumPrecision??"street",o=`geocode:${r.name}:${Ke(e).toLowerCase()}`,a=await Ty(o);if(a!==void 0)return a;let s=await r.geocode(e),i=s&&vt[s.precision]>=vt[n]?s:null;return await Sy(o,i,i?t.cacheSeconds??2592000:600),i}function Fy(e,t,r){if(t.length===0)return null;let n=t[0],o=ke(e,n);for(let a of t.slice(1)){let s=ke(e,a);if(s<o)o=s,n=a}return{covered:o<=r,distanceMeters:Math.round(o),nearest:n}}async function Ty(e){try{let r=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!r)return;let n=await r.get(e);if(n===null||n===void 0)return;return n==="null"?null:JSON.parse(String(n))}catch{return}}async function Sy(e,t,r){try{let o=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!o)return;await o.set(e,t===null?"null":JSON.stringify(t),r)}catch{}}var Sr={};D(Sr,{LicenseKeyInputError:()=>J,bulkDestroy:()=>Yl,bulkSoftDelete:()=>Xl,bulkStore:()=>ip,destroy:()=>Zl,fetchAll:()=>rp,fetchById:()=>tp,softDelete:()=>Ql,store:()=>sp,update:()=>up,updateExpiration:()=>dp,updateStatus:()=>cp,validateLicenseKeyWrite:()=>$e});import{db as Fr,matchedRows as Kl}from"@stacksjs/database/runtime";async function Zl(e){try{let t=await Fr.deleteFrom("license_keys").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete license key: ${t.message}`);throw t}}async function Ql(e){try{return(await Kl(Fr.updateTable("license_keys").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete license key: ${t.message}`);throw t}}async function Yl(e){if(!e.length)return 0;try{let t=await Fr.deleteFrom("license_keys").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete license keys: ${t.message}`);throw t}}async function Xl(e){if(!e.length)return 0;try{return(await Kl(Fr.updateTable("license_keys").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete license keys: ${t.message}`);throw t}}import{db as ep}from"@stacksjs/database/runtime";async function tp(e){let t=await ep.selectFrom("license_keys").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function rp(){return g(await ep.selectFrom("license_keys").selectAll().execute())}var{randomUUIDv7:ap}=globalThis.Bun;import{db as Yo}from"@stacksjs/database/runtime";import{db as Zo}from"@stacksjs/database/runtime";var np=["Standard License","Premium License","Enterprise License"],op=["active","inactive","unassigned"];class J extends TypeError{constructor(e){super(e);this.name="LicenseKeyInputError"}}function Dt(e,t,r){return e[r]!==void 0?e[r]:t?.[r]}function Qo(e,t,r,n){let o=Dt(e,t,r);if(o===void 0||o===null||o==="")return null;let a=Number(o);if(!Number.isSafeInteger(a)||a<1)throw new J(`${n} must be a positive integer or null.`);return a}function Cy(e){if(typeof e==="number")return e>2147483647?Math.floor(e/1000):e;if(typeof e==="string"&&/^\d{10,13}$/.test(e))return e.length===13?Math.floor(Number(e)/1000):Number(e);if(typeof e==="string"){let t=/^\d{4}-\d{2}-\d{2} \d/.test(e)?`${e.replace(" ","T")}Z`:e;return Math.floor(new Date(t).getTime()/1000)}return Number.NaN}async function $e(e,t){let r=String(Dt(e,t,"key")||"").trim().toUpperCase(),n=String(Dt(e,t,"template")||""),o=String(Dt(e,t,"status")||""),a=Cy(Dt(e,t,"expiry_date")),s=Qo(e,t,"customer_id","Customer"),i=Qo(e,t,"product_id","Product"),u=Qo(e,t,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new J("License key must use five groups of four uppercase letters or numbers.");if(!np.includes(n))throw new J(`Template must be one of: ${np.join(", ")}.`);if(!op.includes(o))throw new J(`Status must be one of: ${op.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new J("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,d,m]=await Promise.all([s?Zo.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?Zo.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?Zo.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new J(`Customer ${s} was not found.`);if(i&&!d)throw new J(`Product ${i} was not found.`);if(u&&!m)throw new J(`Order ${u} was not found.`);if(s&&m?.customer_id&&Number(m.customer_id)!==s)throw new J(`Order ${u} belongs to Customer ${m.customer_id}, not Customer ${s}.`);return{...e,key:r,template:n,expiry_date:a,status:o,customer_id:s,product_id:i,order_id:u}}async function sp(e){try{let t=ap(),r=xt(e),n={...await $e(r),uuid:t};await Yo.insertInto("license_keys").values(n).executeTakeFirst();let o=await Yo.selectFrom("license_keys").where("uuid","=",t).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created license key");return l(o)}catch(t){if(t instanceof J)throw t;if(t instanceof Error){if(t.message.includes("UNIQUE constraint failed: license_keys.key"))throw new J("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${t.message}`)}throw t}}async function ip(e){if(!e.length)return 0;try{let t=await Promise.all(e.map(async(n)=>({...await $e(xt(n)),uuid:ap()}))),r=await Yo.insertInto("license_keys").values(t).executeTakeFirst();return f(r)}catch(t){if(t instanceof J)throw t;if(t instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${t.message}`);throw t}}import{db as Tr}from"@stacksjs/database/runtime";import{formatDate as Xo}from"@stacksjs/orm";async function up(e,t){try{if(!e)throw Error("License key ID is required for update");let r=await Tr.selectFrom("license_keys").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=xt(t),o=await $e(n,r),a=await Tr.updateTable("license_keys").set({...o,updated_at:Xo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!a)return;return l(a)}catch(r){if(r instanceof J)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new J("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function cp(e,t){try{let r=await Tr.updateTable("license_keys").set({status:t,updated_at:Xo(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function dp(e,t){try{let r={updated_at:Xo(new Date)};if(t!==void 0)r.expiry_date=t;let n=await Tr.updateTable("license_keys").set(r).where("id","=",e).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update expiration information");return l(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var Mr={};D(Mr,{bulkDestroy:()=>fp,bulkSoftDelete:()=>wp,bulkStore:()=>bp,destroy:()=>pp,fetchAll:()=>yp,fetchById:()=>Ar,formatShippingOptions:()=>_p,getActiveShippingMethods:()=>xp,softDelete:()=>mp,store:()=>hp,update:()=>Rp,updatePricing:()=>vp,updateStatus:()=>Pp});import{db as Cr,matchedRows as lp}from"@stacksjs/database/runtime";async function pp(e){try{let t=await Cr.deleteFrom("shipping_methods").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping method: ${t.message}`);throw t}}async function mp(e){try{return(await lp(Cr.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${t.message}`);throw t}}async function fp(e){if(!e.length)return 0;try{let t=await Cr.deleteFrom("shipping_methods").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping methods: ${t.message}`);throw t}}async function wp(e){if(!e.length)return 0;try{return(await lp(Cr.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${t.message}`);throw t}}import{db as Er}from"@stacksjs/database/runtime";async function Ar(e){let t=await Er.selectFrom("shipping_methods").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=await Er.selectFrom("shipping_zones").where("shipping_method_id","=",e).selectAll().execute();return{...t,shippingZones:r}}return}async function yp(){let e=await Er.selectFrom("shipping_methods").selectAll().execute();if(e.length===0)return[];let t=[...new Set(e.map((a)=>a.id))],o=(await Er.selectFrom("shipping_zones").where("shipping_method_id","in",t).selectAll().execute()).reduce((a,s)=>{let i=s.shipping_method_id;if(i!==null&&i!==void 0){if(!a[i])a[i]=[];a[i].push(s)}return a},{});return e.map((a)=>({...a,shipping_zones:o[a.id]||[]}))}var{randomUUIDv7:gp}=globalThis.Bun;import{db as kt}from"@stacksjs/database/runtime";async function hp(e){try{let t=gp(),r={...ht(e),uuid:t};await kt.insertInto("shipping_methods").values(r).executeTakeFirst();let n=await kt.selectFrom("shipping_methods").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created shipping method");return l(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping method: ${t.message}`);throw t}}async function bp(e){if(!e.length)return 0;try{let t=e.map((n)=>({...ht(n),uuid:gp()})),r=await kt.insertInto("shipping_methods").values(t).executeTakeFirst();return f(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${t.message}`);throw t}}function _p(){try{return kt.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(e){if(e instanceof Error)throw TypeError(`Failed to format shipping options: ${e.message}`);throw e}}async function xp(){try{let e=await kt.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute();return g(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get active shipping methods: ${e.message}`);throw e}}import{db as ea}from"@stacksjs/database/runtime";import{formatDate as ta}from"@stacksjs/orm";async function Rp(e,t){try{if(!e)throw Error("Shipping method ID is required for update");let r=await ea.updateTable("shipping_methods").set({...ht(t),updated_at:ta(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function Pp(e,t){try{let r=await ea.updateTable("shipping_methods").set({status:t,updated_at:ta(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function vp(e,t,r){try{let n={updated_at:ta(new Date)};if(t!==void 0)n.base_rate=t;if(r!==void 0)n.free_shipping=r;let o=await ea.updateTable("shipping_methods").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update pricing information");return l(o)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update pricing information: ${n.message}`);throw n}}var Jr={};D(Jr,{ShippingRateInputError:()=>j,bulkDestroy:()=>kp,bulkStore:()=>jp,bulkUpdate:()=>Gp,destroy:()=>Dp,destroyByMethod:()=>Tp,destroyByZone:()=>Fp,fetchAll:()=>Ep,fetchById:()=>Cp,formatShippingRateOptions:()=>Np,getRateByWeightAndAddress:()=>Mp,getRateByWeightAndZone:()=>ra,getRatesByZone:()=>Ap,getShippingRatesByMethod:()=>$p,resolveZoneForAddress:()=>Nr,store:()=>Lp,update:()=>zp,updateByMethod:()=>qp,updateByZone:()=>Vp,validateShippingRateWrite:()=>Oe,validateZoneMatchesAddress:()=>Ip});import{db as Ir}from"@stacksjs/database/runtime";async function Dp(e){try{let t=await Ir.deleteFrom("shipping_rates").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rate: ${t.message}`);throw t}}async function kp(e){if(!e.length)return 0;try{let t=await Ir.deleteFrom("shipping_rates").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates: ${t.message}`);throw t}}async function Fp(e){try{let t=await Ir.deleteFrom("shipping_rates").where("shipping_zone_id","=",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${t.message}`);throw t}}async function Tp(e){try{let t=await Ir.deleteFrom("shipping_rates").where("shipping_method_id","=",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${t.message}`);throw t}}import{db as X}from"@stacksjs/database/runtime";async function Cp(e){let t=await X.selectFrom("shipping_rates").where("id","=",e).selectAll().executeTakeFirst();if(t){let r=null,n=null;if(t.shipping_zone_id)r=await X.selectFrom("shipping_zones").where("id","=",t.shipping_zone_id).selectAll().executeTakeFirst();if(t.shipping_method_id)n=await X.selectFrom("shipping_methods").where("id","=",t.shipping_method_id).selectAll().executeTakeFirst();return{...t,shipping_zone:r,shipping_method:n}}return}async function Ep(){let e=await X.selectFrom("shipping_rates").selectAll().execute();if(e.length===0)return[];let t=[...new Set(e.map((i)=>i.shipping_zone_id).filter((i)=>i!==null&&i!==void 0))],r=[...new Set(e.map((i)=>i.shipping_method_id).filter((i)=>i!==null&&i!==void 0))],[n,o]=await Promise.all([t.length?X.selectFrom("shipping_zones").where("id","in",t).selectAll().execute():[],r.length?X.selectFrom("shipping_methods").where("id","in",r).selectAll().execute():[]]),a=n.reduce((i,u)=>(i[u.id]=u,i),{}),s=o.reduce((i,u)=>(i[u.id]=u,i),{});return e.map((i)=>({...i,shipping_zone:i.shipping_zone_id?a[i.shipping_zone_id]:[],shipping_method:i.shipping_method_id?s[i.shipping_method_id]:[]}))}async function Ap(e){try{let t=await X.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).orderBy("weight_from").execute();return g(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${t.message}`);throw t}}async function ra(e,t){try{let r=await X.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).where("weight_from","<=",e).where("weight_to",">=",e).executeTakeFirst();return l(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 Nr(e){if(!e?.countryCode)return null;try{let t=await X.selectFrom("shipping_zones").selectAll().where("countries","like",`%${e.countryCode}%`).where("status","=","active").execute();if(t.length===0)return null;let r=null;for(let n of t){let o=1;if(e.region&&n.regions&&Sp(n.regions,e.region))o=2;if(e.postalCode&&n.postal_codes&&Sp(n.postal_codes,e.postalCode))o=3;if(!r||o>r.score)r={id:n.id,score:o}}return r?.id??null}catch{return null}}async function Mp(e,t){let r=await Nr(t);if(r==null)return;return ra(e,r)}async function Ip(e,t){return await Nr(t)===e}function Sp(e,t){if(!e||!t)return!1;let r=t.trim().toUpperCase();for(let n of e.split(/[,|;]/))if(n.trim().toUpperCase()===r)return!0;return!1}async function Np(){try{return(await X.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((t)=>t.shipping_method_id!==null&&t.shipping_method_id!==void 0&&t.shipping_zone_id!==null&&t.shipping_zone_id!==void 0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to format shipping rate options: ${e.message}`);throw e}}async function $p(e){try{let t=await X.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",e).orderBy("weight_from").execute();return g(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${t.message}`);throw t}}var{randomUUIDv7:Wp}=globalThis.Bun;import{db as na}from"@stacksjs/database/runtime";import{db as Ft}from"@stacksjs/database/runtime";async function Op(){return g(await Ft.selectFrom("shipping_zones").selectAll().execute())}async function $r(e){let t=await Ft.selectFrom("shipping_zones").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}function Jp(){try{return Ft.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(e){if(e instanceof Error)throw TypeError(`Failed to format shipping zone options: ${e.message}`);throw e}}async function Bp(){try{let e=await Ft.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute();return g(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get active shipping zones: ${e.message}`);throw e}}async function Up(e){try{let t=await Ft.selectFrom("shipping_zones").selectAll().where("countries","like",`%${e}%`).where("status","=","active").orderBy("name").execute();return g(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${t.message}`);throw t}}class j extends TypeError{constructor(e){super(e);this.name="ShippingRateInputError"}}function Tt(e,t,r){return Number(e[r]??t?.[r])}async function Oe(e,t){let r=Tt(e,t,"shipping_method_id"),n=Tt(e,t,"shipping_zone_id"),o=Tt(e,t,"weight_from"),a=Tt(e,t,"weight_to"),s=Tt(e,t,"rate");if(!Number.isSafeInteger(r)||r<1)throw new j("Shipping method must be a positive integer.");if(!Number.isSafeInteger(n)||n<1)throw new j("Shipping zone must be a positive integer.");if(!Number.isFinite(o)||o<0)throw new j("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<o)throw new j("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new j("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([Ar(r),$r(n)]);if(!i)throw new j(`Shipping method ${r} was not found.`);if(!u)throw new j(`Shipping zone ${n} was not found.`);if(Number(u.shipping_method_id)!==r)throw new j(`Shipping zone ${n} is not assigned to shipping method ${r}.`)}async function Lp(e){try{let t=ye(e),r=Number(t.shipping_method_id),n=Number(t.shipping_zone_id);await Oe(t);let o=Wp(),a={...t,shipping_method_id:r,shipping_zone_id:n,uuid:o};await na.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await na.selectFrom("shipping_rates").where("uuid","=",o).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return l(s)}catch(t){if(t instanceof j)throw t;if(t instanceof Error)throw TypeError(`Failed to create shipping rate: ${t.message}`);throw t}}async function jp(e){if(!e.length)return 0;try{for(let n of e){let o=ye(n);await Oe(o)}let t=e.map((n)=>({...ye(n),uuid:Wp()})),r=await na.insertInto("shipping_rates").values(t).executeTakeFirst();return f(r)}catch(t){if(t instanceof j)throw t;if(t instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${t.message}`);throw t}}import{db as St,matchedRows as oa}from"@stacksjs/database/runtime";import{formatDate as Or}from"@stacksjs/orm";async function zp(e,t){try{if(!e)throw Error("Shipping rate ID is required for update");let r=await St.selectFrom("shipping_rates").where("id","=",e).selectAll().executeTakeFirst();if(!r)return;let n=ye(t);await Oe(n,r);let o=await St.updateTable("shipping_rates").set({...n,updated_at:Or(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!o)return;return l(o)}catch(r){if(r instanceof j)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function Gp(e){if(!e.length)return 0;try{let t=0;for(let{id:r,data:n}of e)if((await oa(St.updateTable("shipping_rates").set({...ye(n),updated_at:Or(new Date)}).where("id","=",r))).length>0)t++;return t}catch(t){if(t instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${t.message}`);throw t}}async function Vp(e,t){try{return(await oa(St.updateTable("shipping_rates").set({...ye(t),updated_at:Or(new Date)}).where("shipping_zone_id","=",e))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function qp(e,t){try{return(await oa(St.updateTable("shipping_rates").set({...ye(t),updated_at:Or(new Date)}).where("shipping_method_id","=",e))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var Vr={};D(Vr,{ARRIVAL_RADIUS_METERS:()=>ia,NEARBY_RADIUS_METERS:()=>sa,assignStop:()=>Kp,bearingInDegrees:()=>Pr,broadcastToChannel:()=>ge,completeStop:()=>Qp,distanceInMeters:()=>ke,emitDeliveryArrived:()=>jr,emitDeliveryAssigned:()=>Ur,emitDeliveryCompleted:()=>zr,emitDeliveryFailed:()=>Gr,emitDeliveryNearby:()=>Lr,emitDeliveryPosition:()=>Br,emitDeliveryStarted:()=>Wr,estimateSecondsRemaining:()=>vr,failStop:()=>Yp,hasCoordinates:()=>Pt,isWithin:()=>jl,orderTrackingChannel:()=>Fe,recordCourierPing:()=>Hp,routeTrackingChannel:()=>aa,startRoute:()=>Xp,startStop:()=>Zp});function Fe(e){return`order.${e}`}function aa(e){return`delivery-route.${e}`}async function Ze(e,t){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let n=r.dispatch;if(typeof n!=="function")return;n(e,t)}catch{}}async function ge(e,t,r){try{let n=await import("@stacksjs/realtime").catch(()=>null);if(!n)return;let o=n.channel;if(typeof o!=="function")return;await o(e).broadcast(t,r,"private")}catch{}}async function Br(e,t,r){await Promise.all([...e.map((n)=>ge(Fe(n),"delivery:position",r)),t==null?Promise.resolve():ge(aa(t),"delivery:position",r)])}async function Ur(e){if(await Ze("delivery:assigned",{stop:e}),e.order_id!=null)await ge(Fe(e.order_id),"delivery:assigned",{stop:e})}async function Wr(e){if(await Ze("delivery:started",{stop:e}),e.order_id!=null)await ge(Fe(e.order_id),"delivery:started",{stop:e})}async function Lr(e,t,r){if(await Ze("delivery:nearby",{stop:e,distanceMeters:t,etaSeconds:r}),e.order_id!=null)await ge(Fe(e.order_id),"delivery:nearby",{stop:e,distanceMeters:t,etaSeconds:r})}async function jr(e){if(await Ze("delivery:arrived",{stop:e}),e.order_id!=null)await ge(Fe(e.order_id),"delivery:arrived",{stop:e})}async function zr(e){if(await Ze("delivery:completed",{stop:e}),e.order_id!=null)await ge(Fe(e.order_id),"delivery:completed",{stop:e})}async function Gr(e,t){await Ze("delivery:failed",{stop:e,reason:t})}var{randomUUIDv7:Ey}=globalThis.Bun;import{db as he}from"@stacksjs/database/runtime";var sa=400,ia=60,Ay=250;async function Hp(e){let t=e.recordedAt??new Date().toISOString(),r=typeof e.accuracy!=="number"||e.accuracy<=Ay,n=await he.selectFrom("couriers").where("id","=",e.courierId).select(["id","latitude","longitude"]).executeTakeFirst();if(!n)throw Error(`Unknown courier: ${e.courierId}`);let o=Pt(n)?{latitude:n.latitude,longitude:n.longitude}:null,a=typeof e.heading==="number"?e.heading:o?Pr(o,e):null,s=await My(e.courierId),i=s?await Iy(s.id):null,u=null,c=null,d=!1,m=!1,p=i&&Pt({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&p)u=Math.round(ke(e,p)),c=vr(u,e.speed??0),m=u<=ia&&i.arrived_at==null,d=!m&&u<=sa&&i.status==="en_route"&&i.notified_nearby_at==null;let y=await Ny({courierId:e.courierId,routeId:s?.id??null,latitude:e.latitude,longitude:e.longitude,heading:a,speed:e.speed??null,accuracy:e.accuracy??null,recordedAt:t});if(r)await he.updateTable("couriers").set({latitude:e.latitude,longitude:e.longitude,heading:a,speed:e.speed??0,last_ping_at:t}).where("id","=",e.courierId).execute();if(i&&(u!=null||c!=null))await he.updateTable("delivery_stops").set({eta_at:c==null?i.eta_at:new Date(Date.now()+c*1000).toISOString()}).where("id","=",i.id).execute();if(r)await Br(i?.order_id==null?[]:[i.order_id],s?.id??null,{courierId:e.courierId,routeId:s?.id??null,latitude:e.latitude,longitude:e.longitude,heading:a,speed:e.speed??null,accuracy:e.accuracy??null,recordedAt:t,distanceToStopMeters:u,etaSeconds:c});if(d&&i)await he.updateTable("delivery_stops").set({notified_nearby_at:t}).where("id","=",i.id).execute(),await Lr(i,u,c);if(m&&i)await he.updateTable("delivery_stops").set({status:"arrived",arrived_at:t}).where("id","=",i.id).execute(),await jr({...i,status:"arrived",arrived_at:t});return{pingId:y,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:d,crossedArrival:m}}async function My(e){return await he.selectFrom("delivery_routes").where("courier_id","=",e).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function Iy(e){let t=await he.selectFrom("delivery_stops").where("delivery_route_id","=",e).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return t.find((r)=>r.status==="en_route")??t.find((r)=>r.status==="arrived")??t[0]??null}async function Ny(e){let t=Ey();return await he.insertInto("courier_pings").values({uuid:t,courier_id:e.courierId,delivery_route_id:e.routeId,latitude:e.latitude,longitude:e.longitude,heading:e.heading,speed:e.speed??0,accuracy:e.accuracy,recorded_at:e.recordedAt}).executeTakeFirst(),(await he.selectFrom("courier_pings").where("uuid","=",t).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:$y}=globalThis.Bun;import{db as z}from"@stacksjs/database/runtime";function ua(e){return e.type==="pickup"}async function Kp(e){let t=$y(),r=e.sequence??await Jy(e.deliveryRouteId);await z.insertInto("delivery_stops").values({uuid:t,delivery_route_id:e.deliveryRouteId,order_id:e.orderId??null,sequence:r,status:"pending",address:e.address,latitude:e.latitude??null,longitude:e.longitude??null,recipient_name:e.recipientName??null,recipient_phone:e.recipientPhone??null,eta_at:e.etaAt??null,type:e.type??"dropoff"}).executeTakeFirst();let n=await Uy(t);if(n)await Ur(n);return n??{}}async function Zp(e){await z.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",e).execute();let t=await da(e);if(!t)return null;if(t.order_id!=null&&!ua(t))await ca(t.order_id,"OUT_FOR_DELIVERY");return await Wr(t),t}async function Qp(e,t){let r=new Date().toISOString();await z.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await By(e)?{}:{arrived_at:r},...t?{notes:t}:{}}).where("id","=",e).execute();let n=await da(e);if(!n)return null;if(n.order_id!=null)await ca(n.order_id,ua(n)?"OUT_FOR_DELIVERY":"DELIVERED");return await zr(n),await em(n.delivery_route_id),n}async function Yp(e,t){await z.updateTable("delivery_stops").set({status:"failed",notes:t}).where("id","=",e).execute();let r=await da(e);if(!r)return null;if(r.order_id!=null&&!ua(r))await ca(r.order_id,"SHIPPED");return await Gr(r,t),await em(r.delivery_route_id),r}async function Xp(e){await z.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",e).execute()}async function em(e){if(e==null)return;if(await z.selectFrom("delivery_stops").where("delivery_route_id","=",e).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await z.selectFrom("delivery_routes").where("id","=",e).select(["courier_id"]).executeTakeFirst();if(await z.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",e).execute(),r?.courier_id!=null)await z.updateTable("couriers").set({status:"active"}).where("id","=",r.courier_id).execute()}async function ca(e,t){let r=await z.selectFrom("orders").where("id","=",e).select(["id","status"]).executeTakeFirst();if(!r)return;let n=await Promise.resolve().then(() => (ze(),{}));let s=Oy(r.status,t,Le);if(s.length===0){let{log:i}=await import("@stacksjs/logging").catch(()=>({log:null}));i?.warn(`[delivery] refused to move order ${e} from ${r.status} to ${t}: no legal transition`);return}for(let i of s)await z.updateTable("orders").set({status:i}).where("id","=",e).execute(),await je(i,{...r,status:i})}function Oy(e,t,r){if(e===t)return[];if(r(e,t))return[t];for(let n of["PROCESSING","SHIPPED"]){if(n===e||n===t)continue;if(r(e,n)&&r(n,t))return[n,t]}return[]}async function Jy(e){return(await z.selectFrom("delivery_stops").where("delivery_route_id","=",e).select(["sequence"]).execute()).reduce((r,n)=>Math.max(r,n.sequence??0),0)+1}async function By(e){return(await z.selectFrom("delivery_stops").where("id","=",e).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function da(e){return await z.selectFrom("delivery_stops").where("id","=",e).selectAll().executeTakeFirst()??null}async function Uy(e){return await z.selectFrom("delivery_stops").where("uuid","=",e).selectAll().executeTakeFirst()??null}var Zr={};D(Zr,{bulkDestroy:()=>om,bulkSoftDelete:()=>am,bulkStore:()=>um,destroy:()=>rm,fetchAll:()=>Op,fetchById:()=>$r,formatZoneOptions:()=>Jp,getActiveShippingZones:()=>Bp,getZonesByCountry:()=>Up,softDelete:()=>nm,store:()=>im,update:()=>cm,updateCountries:()=>lm,updateRegionsAndPostalCodes:()=>pm,updateStatus:()=>dm});import{db as qr,matchedRows as tm}from"@stacksjs/database/runtime";async function rm(e){try{let t=await qr.deleteFrom("shipping_zones").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping zone: ${t.message}`);throw t}}async function nm(e){try{return(await tm(qr.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",e))).length>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${t.message}`);throw t}}async function om(e){if(!e.length)return 0;try{let t=await qr.deleteFrom("shipping_zones").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete shipping zones: ${t.message}`);throw t}}async function am(e){if(!e.length)return 0;try{return(await tm(qr.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",e))).length}catch(t){if(t instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${t.message}`);throw t}}var{randomUUIDv7:sm}=globalThis.Bun;import{db as la}from"@stacksjs/database/runtime";async function im(e){try{let t=sm(),r={...bt(e),uuid:t};await la.insertInto("shipping_zones").values(r).executeTakeFirst();let n=await la.selectFrom("shipping_zones").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created shipping zone");return l(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping zone: ${t.message}`);throw t}}async function um(e){if(!e.length)return 0;try{let t=e.map((n)=>({...bt(n),uuid:sm()})),r=await la.insertInto("shipping_zones").values(t).executeTakeFirst();return f(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${t.message}`);throw t}}import{db as Hr}from"@stacksjs/database/runtime";import{formatDate as Kr}from"@stacksjs/orm";async function cm(e,t){try{if(!e)throw Error("Shipping zone ID is required for update");let r=await Hr.updateTable("shipping_zones").set({...bt(t),updated_at:Kr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)return;return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function dm(e,t){try{let r=await Hr.updateTable("shipping_zones").set({status:t,updated_at:Kr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function lm(e,t){try{let r=await Hr.updateTable("shipping_zones").set({countries:t,updated_at:Kr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function pm(e,t,r){try{let n={updated_at:Kr(new Date)};if(t!==void 0)n.regions=t;if(r!==void 0)n.postal_codes=r;let o=await Hr.updateTable("shipping_zones").set(n).where("id","=",e).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update regions and postal codes");return l(o)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${n.message}`);throw n}}var Wy={digital:_r,couriers:Rr,geocoding:kr,licenses:Sr,methods:Mr,rates:Jr,routes:hr,tracking:Vr,zones:Zr},Ly=Wy;var wa={};D(wa,{activeTaxRates:()=>ma,breakdownFor:()=>fa,bulkDestroy:()=>ym,bulkStore:()=>Pm,destroy:()=>wm,fetchAll:()=>bm,fetchById:()=>hm,store:()=>Rm,taxFor:()=>mm,update:()=>vm,updateDefaultStatus:()=>Fm,updateRate:()=>km,updateStatus:()=>Dm});import{db as jy}from"@stacksjs/database/runtime";function zy(e){let t=Number(e);return Number.isFinite(t)?t/100:0}async function ma(e={}){let t=jy.selectFrom("tax_rates").where("status","=","active").selectAll();if(e.country)t=t.where("country","=",e.country);let r=await t.execute();if(!e.codes?.length)return r;let n=new Set(e.codes);return r.filter((o)=>n.has(String(o.code??"")))}function fa(e,t,r={}){let n=Math.max(0,Math.round(e)),o=[],a=0,s=0;for(let i of t){let u=zy(i.rate),c=Math.round(n*u),d=Boolean(r.exempt&&i.exemptible);if(d)s+=c;else a+=c;o.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:d?0:c,exempted:d})}return{taxable:n,components:o,tax:a,exempted:s}}async function mm(e,t={}){return fa(e,await ma(t),t)}import{db as fm}from"@stacksjs/database/runtime";async function wm(e){try{let t=await fm.deleteFrom("tax_rates").where("id","=",e).executeTakeFirst();return f(t)>0}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete tax rate: ${t.message}`);throw t}}async function ym(e){if(!e.length)return 0;try{let t=await fm.deleteFrom("tax_rates").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete tax rates: ${t.message}`);throw t}}import{db as gm}from"@stacksjs/database/runtime";async function hm(e){let t=await gm.selectFrom("tax_rates").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function bm(){return g(await gm.selectFrom("tax_rates").selectAll().execute())}var{randomUUIDv7:_m}=globalThis.Bun;import{db as xm}from"@stacksjs/database/runtime";async function Rm(e){try{return await xm.transaction(async(t)=>{let r={...e,uuid:_m()};if(r.is_default)await t.updateTable("tax_rates").set({is_default:!1}).execute();let n=await t.insertInto("tax_rates").values(r).returningAll().executeTakeFirst();if(!n)throw Error("Failed to create tax rate");return l(n)})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create tax rate: ${t.message}`);throw t}}async function Pm(e){if(!e.length)return 0;try{return await xm.transaction(async(t)=>{let r=0;for(let n of e){let o={...n,uuid:_m()};if(o.is_default)await t.updateTable("tax_rates").set({is_default:!1}).execute();if(await t.insertInto("tax_rates").values(o).executeTakeFirst())r++}return r})}catch(t){if(t instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${t.message}`);throw t}}import{db as Qr}from"@stacksjs/database/runtime";import{formatDate as Yr}from"@stacksjs/orm";async function vm(e,t){try{if(!e)throw Error("Tax rate ID is required for update");return await Qr.transaction(async(r)=>{let n=await r.selectFrom("tax_rates").select("is_default").where("id","=",e).executeTakeFirst();if(!n)return;let o=t.is_default??Boolean(n.is_default),a=Yr(new Date);if(o)await r.updateTable("tax_rates").set({is_default:!1,updated_at:a}).where("id","!=",e).execute();let s=await r.updateTable("tax_rates").set({...t,updated_at:a}).where("id","=",e).returningAll().executeTakeFirst();if(!s)return;return l(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function Dm(e,t){try{let r=await Qr.updateTable("tax_rates").set({status:t,updated_at:Yr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function km(e,t){try{let r=await Qr.updateTable("tax_rates").set({rate:t,updated_at:Yr(new Date)}).where("id","=",e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return l(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function Fm(e,t){try{return await Qr.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",e).executeTakeFirst())return!1;let o=Yr(new Date);if(t)await r.updateTable("tax_rates").set({is_default:!1,updated_at:o}).where("id","!=",e).execute();return await r.updateTable("tax_rates").set({is_default:t,updated_at:o}).where("id","=",e).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate default status: ${r.message}`);throw r}}var xa={};D(xa,{default:()=>eg,products:()=>en,restaurant:()=>Ye});var en={};D(en,{bulkDestroy:()=>Sm,bulkStore:()=>Vm,destroy:()=>Tm,fetchAll:()=>Cm,fetchById:()=>Ct,fetchCancelledBetweenDates:()=>Om,fetchConversionRates:()=>Um,fetchCountBetweenDates:()=>Wm,fetchCountByAllQuantities:()=>Im,fetchCountByDate:()=>Am,fetchCountByDateGrouped:()=>Lm,fetchCountByQuantity:()=>Mm,fetchCountBySource:()=>Em,fetchCountByStatus:()=>Bm,fetchNotifiedBetweenDates:()=>Nm,fetchPurchasedBetweenDates:()=>$m,fetchWaiting:()=>Jm,store:()=>Gm,update:()=>Xr,updatePartySize:()=>Hm,updateStatus:()=>qm});import{db as ya}from"@stacksjs/database/runtime";async function Tm(e){try{let t=await ya.selectFrom("waitlist_products").where("id","=",e).selectAll().executeTakeFirst();if(!t)return;return await ya.deleteFrom("waitlist_products").where("id","=",e).execute(),l(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete waitlist product: ${t.message}`);throw t}}async function Sm(e){if(!e.length)return 0;try{let t=await ya.deleteFrom("waitlist_products").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${t.message}`);throw t}}import{db as M}from"@stacksjs/database/runtime";import{formatDate as N}from"@stacksjs/orm";async function Ct(e){let t=await M.selectFrom("waitlist_products").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function Cm(){return g(await M.selectFrom("waitlist_products").selectAll().execute())}async function Em(e,t){let r=M.selectFrom("waitlist_products").select(["source",M.fn.count("id").as("count")]).groupBy("source");if(e&&t){let o=N(e),a=N(t);r=r.where("created_at",">=",o).where("created_at","<=",a)}return(await r.execute()).reduce((o,{source:a,count:s})=>(o[a]=s,o),{})}async function Am(e=new Date){let t=new Date(e);t.setHours(0,0,0,0);let r=new Date(e);r.setHours(23,59,59,999);let n=N(t),o=N(r);return(await M.selectFrom("waitlist_products").select(M.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",o).executeTakeFirst())?.count??0}async function Mm(e){return(await M.selectFrom("waitlist_products").select(M.fn.count("id").as("count")).where("quantity","=",e).executeTakeFirst())?.count??0}async function Im(e,t){let r=M.selectFrom("waitlist_products").select(["quantity",M.fn.count("id").as("count")]).groupBy("quantity");if(e&&t){let o=N(e),a=N(t);r=r.where("created_at",">=",o).where("created_at","<=",a)}return(await r.execute()).reduce((o,{quantity:a,count:s})=>(o[a]=s,o),{})}async function Nm(e,t){let r=N(e),n=N(t),o=await M.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",n).whereNotNull("notified_at").execute();return g(o)}async function $m(e,t){let r=N(e),n=N(t),o=await M.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",n).whereNotNull("purchased_at").execute();return g(o)}async function Om(e,t){let r=N(e),n=N(t),o=await M.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",n).whereNotNull("cancelled_at").execute();return g(o)}async function Jm(){let e=await M.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute();return g(e)}async function Bm(e,t,r){let n=M.selectFrom("waitlist_products").select(M.fn.count("id").as("count")).where("status","=",e);if(t&&r){let a=N(t),s=N(r);n=n.where("created_at",">=",a).where("created_at","<=",s)}return(await n.executeTakeFirst())?.count??0}async function Um(e,t){let r=M.selectFrom("waitlist_products").select(["status",M.fn.count("id").as("count")]).groupBy("status");if(e&&t){let u=N(e),c=N(t);r=r.where("created_at",">=",u).where("created_at","<=",c)}let n=await r.execute(),o=n.reduce((u,{count:c})=>u+c,0),a=Number(n.find((u)=>u.status==="purchased")?.count??0),s=o>0?a/o*100:0,i=n.reduce((u,{status:c,count:d})=>(u[c]={count:d,percentage:o>0?d/o*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function Wm(e,t){let r=N(e),n=N(t);return(await M.selectFrom("waitlist_products").select(M.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",n).executeTakeFirst())?.count??0}async function Lm(e,t){let r=M.selectFrom("waitlist_products").select(["created_at"]);if(e&&t){let a=N(e),s=N(t);r=r.where("created_at",">=",a).where("created_at","<=",s)}let o=(await r.execute()).reduce((a,{created_at:s})=>{let i=(s||"").split("T")[0]||"unknown";return a[i]=(a[i]||0)+1,a},{});return Object.entries(o).map(([a,s])=>({date:a,count:s})).sort((a,s)=>a.date.localeCompare(s.date))}var{randomUUIDv7:zm}=globalThis.Bun;import{db as ga}from"@stacksjs/database/runtime";import{formatDate as jm}from"@stacksjs/orm";var Gy={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Vy(e){return typeof e==="number"||e instanceof Date?jm(e):e}function Et(e,t={}){let r=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0));if(r.quantity===void 0&&r.party_size!==void 0)r.quantity=r.party_size;delete r.party_size;for(let o of["notified_at","purchased_at","cancelled_at"])if(r[o]!==void 0)r[o]=Vy(r[o]);let n=Gy[r.status];if(n&&r[n]===void 0&&!t[n])r[n]=jm(new Date);return r}async function Gm(e){try{let t=zm(),r={...Et(e),uuid:t,status:e.status||"waiting"};await ga.insertInto("waitlist_products").values(r).executeTakeFirst();let n=await ga.selectFrom("waitlist_products").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create waitlist product");return l(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create waitlist product: ${t.message}`);throw t}}async function Vm(e){if(!e.length)return 0;try{let t=e.map((n)=>({...Et(n),status:n.status||"waiting",uuid:zm()})),r=await ga.insertInto("waitlist_products").values(t).executeTakeFirst();return f(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${t.message}`);throw t}}import{db as qy}from"@stacksjs/database/runtime";import{formatDate as Hy}from"@stacksjs/orm";async function Xr(e,t){try{if(!e)throw Error("Waitlist product ID is required for update");let r=await Ct(e);if(!r)return;await qy.updateTable("waitlist_products").set({...Et(t,r),updated_at:Hy(new Date)}).where("id","=",e).execute();let n=await Ct(e);if(!n)return;return l(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function qm(e,t){return await Xr(e,{status:t})}async function Hm(e,t){return await Xr(e,{quantity:t})}var Ye={};D(Ye,{bulkDestroy:()=>Zm,bulkStore:()=>hf,destroy:()=>Km,fetchAll:()=>Qm,fetchAverageWaitTimes:()=>sf,fetchBetweenDates:()=>rf,fetchById:()=>At,fetchConversionRates:()=>af,fetchCountByAllPartySizes:()=>tf,fetchCountByDate:()=>Xm,fetchCountByPartySize:()=>ef,fetchCountByTablePreference:()=>Ym,fetchCurrentWaitTimes:()=>mf,fetchNoShowStats:()=>pf,fetchSeatedBetweenDates:()=>nf,fetchSeatedStats:()=>ff,fetchSeatingRate:()=>lf,fetchTablesTurnedToday:()=>df,fetchTimeSeriesStats:()=>wf,fetchWaiting:()=>of,fetchWaitingWithPartySizes:()=>cf,fetchWaitingWithQuotedTimes:()=>uf,store:()=>gf,update:()=>Qe,updatePartySize:()=>_f,updateQueuePosition:()=>Rf,updateStatus:()=>bf,updateWaitTimes:()=>xf});import{db as ha}from"@stacksjs/database/runtime";async function Km(e){try{let t=await ha.selectFrom("waitlist_restaurants").where("id","=",e).selectAll().executeTakeFirst();if(!t)return;return await ha.deleteFrom("waitlist_restaurants").where("id","=",e).execute(),l(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${t.message}`);throw t}}async function Zm(e){if(!e.length)return 0;try{let t=await ha.deleteFrom("waitlist_restaurants").where("id","in",e).executeTakeFirst();return f(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${t.message}`);throw t}}import{db as F}from"@stacksjs/database/runtime";import{formatDate as Z}from"@stacksjs/orm";async function At(e){let t=await F.selectFrom("waitlist_restaurants").where("id","=",e).selectAll().executeTakeFirst();return l(t,!0)}async function Qm(){return g(await F.selectFrom("waitlist_restaurants").selectAll().execute())}async function Ym(){return(await F.selectFrom("waitlist_restaurants").select(["table_preference",F.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((t,{table_preference:r,count:n})=>(t[r]=n,t),{})}async function Xm(e=new Date){let t=new Date(e);t.setHours(0,0,0,0);let r=new Date(e);r.setHours(23,59,59,999);let n=Z(t),o=Z(r);return(await F.selectFrom("waitlist_restaurants").select(F.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",o).executeTakeFirst())?.count??0}async function ef(e){return(await F.selectFrom("waitlist_restaurants").select(F.fn.count("id").as("count")).where("party_size","=",e).executeTakeFirst())?.count??0}async function tf(){return(await F.selectFrom("waitlist_restaurants").select(["party_size",F.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((t,{party_size:r,count:n})=>(t[r]=n,t),{})}async function rf(e,t){let r=Z(e),n=Z(t),o=await F.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",n).execute();return g(o)}async function nf(e,t){let r=Z(e),n=Z(t),o=await F.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",n).where("status","=","seated").execute();return g(o)}async function of(){let e=await F.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute();return g(e)}async function af(){let e=await F.selectFrom("waitlist_restaurants").select(["status",F.fn.count("id").as("count")]).groupBy("status").execute(),t=e.reduce((a,{count:s})=>a+s,0),r=e.find((a)=>a.status==="seated")?.count??0,n=t>0?Number(r)/t*100:0,o=e.reduce((a,{status:s,count:i})=>(a[s]={count:i,percentage:t>0?i/t*100:0},a),{});return{totalConversionRate:n,statusBreakdown:o}}async function sf(){let e=await F.selectFrom("waitlist_restaurants").select([F.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),F.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:e?.avg_quoted_wait_time??0,averageActualWaitTime:e?.avg_actual_wait_time??0}}async function uf(){let e=g(await F.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),t=e.reduce((n,o)=>n+(o.quoted_wait_time??0),0),r=e.length>0?t/e.length:0;return{entries:e,totalQuotedWaitTime:t,averageQuotedWaitTime:r}}async function cf(){let e=g(await F.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),t=e.reduce((o,a)=>o+a.party_size,0),r=e.length>0?t/e.length:0,n=e.reduce((o,a)=>(o[a.party_size]=(o[a.party_size]||0)+1,o),{});return{entries:e,totalPartySize:t,averagePartySize:r,partySizeBreakdown:n}}async function df(){let e=new Date,t=new Date(e);t.setHours(0,0,0,0);let r=new Date(e);r.setHours(23,59,59,999);let n=Z(t),o=Z(r),a=await F.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",n).where("check_in_time","<=",o).execute(),s=a.length,i=a.reduce((m,p)=>m+p.party_size,0),u=s>0?i/s:0,c=a.reduce((m,p)=>(m[p.table_preference]=(m[p.table_preference]||0)+1,m),{}),d=a.reduce((m,p)=>(m[p.party_size]=(m[p.party_size]||0)+1,m),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:d}}async function lf(e,t){let r=Z(e),n=Z(t),o=await F.selectFrom("waitlist_restaurants").select(["status",F.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",n).groupBy("status").execute(),a=o.reduce((c,{count:d})=>c+d,0),s=o.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=o.reduce((c,{status:d,count:m})=>(c[d]={count:m,percentage:a>0?m/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function pf(e,t){let r=Z(e),n=Z(t),o=F.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",n),a=await F.selectFrom("waitlist_restaurants").select(F.fn.count("id").as("count")).where("check_in_time",">=",r).where("check_in_time","<=",n).executeTakeFirst(),s=await o.execute(),i=s.length,u=a?.count&&a.count>0?i/a.count*100:0,c=s.reduce((w,b)=>w+(b.quoted_wait_time??0),0),d=i>0?c/i:0,m=s.reduce((w,b)=>w+b.party_size,0),p=i>0?m/i:0,y=s.reduce((w,b)=>(w[b.table_preference]=(w[b.table_preference]||0)+1,w),{}),_=s.reduce((w,b)=>(w[b.party_size]=(w[b.party_size]||0)+1,w),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:d,averagePartySize:p,breakdownByTablePreference:y,breakdownByPartySize:_}}async function mf(){let e=await F.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),t=e.reduce((o,a)=>o+(a.quoted_wait_time||0),0),r=e.reduce((o,a)=>o+(a.actual_wait_time||0),0),n=e.length;return{averageQuoted:n>0?t/n:0,averageActual:n>0?r/n:0}}async function ff(){let e=Date.now()-86400000,t=await F.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",e).execute(),r=Array.from({length:24},(n,o)=>({hour:o,count:t.filter((a)=>a.seated_at===o).length}));return{total:t.length,byHour:r}}async function wf(){return(await F.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((t,r)=>{let n=r.created_at;if(!t[n])t[n]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return t[n].total++,t[n][r.status]++,t},{})}var{randomUUIDv7:yf}=globalThis.Bun;import{db as _a}from"@stacksjs/database/runtime";import{formatDate as ba}from"@stacksjs/orm";var Ky={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function Zy(e){if(typeof e==="number")return ba(e<=2147483647?e*1000:e);if(e instanceof Date)return ba(e);return e}function Mt(e,t={}){let r=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0));for(let o of["check_in_time","seated_at","no_show_at","cancelled_at"])if(r[o]!==void 0)r[o]=Zy(r[o]);let n=Ky[r.status];if(n&&r[n]===void 0&&!t[n])r[n]=ba(new Date);return r}async function gf(e){try{let t=yf(),r={...Mt(e),status:e.status||"waiting",uuid:t};await _a.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let n=await _a.selectFrom("waitlist_restaurants").where("uuid","=",t).selectAll().executeTakeFirst();if(!n)throw Error("Failed to create restaurant waitlist entry");return l(n)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${t.message}`);throw t}}async function hf(e){if(!e.length)return 0;try{let t=e.map((n)=>({...Mt(n),status:n.status||"waiting",uuid:yf()})),r=await _a.insertInto("waitlist_restaurants").values(t).executeTakeFirst();return f(r)}catch(t){if(t instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${t.message}`);throw t}}import{db as Qy}from"@stacksjs/database/runtime";import{formatDate as Yy}from"@stacksjs/orm";async function Qe(e,t){try{if(!e)throw Error("Restaurant waitlist entry ID is required for update");let r=await At(e);if(!r)return;await Qy.updateTable("waitlist_restaurants").set({...Mt(t,r),updated_at:Yy(new Date)}).where("id","=",e).execute();let n=await At(e);if(!n)return;return l(n)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function bf(e,t){return await Qe(e,{status:t})}async function _f(e,t){return await Qe(e,{party_size:t})}async function xf(e,t,r){return await Qe(e,{quoted_wait_time:t,...r===void 0?{}:{actual_wait_time:r}})}async function Rf(e,t){return await Qe(e,{queue_position:t})}var Xy={products:en,restaurant:Ye},eg=Xy;var tg={auctions:Sn,carts:Cn,coupons:Zn,customers:Yn,devices:no,errors:so,giftCards:co,orders:Fo,payments:To,products:No,receipts:Wo,restaurant:Ye,shippings:pa,tax:wa,waitlists:xa},sS=tg;export{O as PriceFormatError,Sn as auctions,Cn as carts,Es as catalogImport,tg as commerce,Zn as coupons,W as currencyExponent,Yn as customers,H as decimalToMinor,sS as default,no as devices,so as errors,ja as formatCurrency,te as formatMinor,co as giftCards,ue as minorToDecimal,za as minorToInput,An as minorToMajor,qa as money,Mn as moneyInputError,Ga as moneyInputStep,Fo as orders,Va as parseMoneyInput,To as payments,No as products,Wo as receipts,Ye as restaurant,pa as shippings,wa as tax,xa as waitlists};
|