@stacksjs/commerce 0.72.25 → 0.72.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +5 -5
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var FZ=Object.defineProperty;var NZ=($)=>$;function HZ($,J){this[$]=NZ.bind(null,J)}var B=($,J)=>{for(var G in J)FZ($,G,{get:J[G],enumerable:!0,configurable:!0,set:HZ.bind(J,G)})};var zZ=($,J)=>()=>($&&(J=$($=0)),J);var n=import.meta.require;var x6={};B(x6,{emitOrderShipped:()=>j$,emitOrderRefunded:()=>S0,emitOrderPaid:()=>Y0,emitOrderOutForDelivery:()=>V6,emitOrderDelivered:()=>q$,emitOrderCreated:()=>s0,emitOrderCancelled:()=>R0,emitForStatus:()=>o0,canTransition:()=>i0});function i0($,J){if($===J)return!0;return lZ[$]?.includes(J)??!1}async function z0($,J){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X($,J)}catch{}}async function s0($){await z0("order:created",{order:$})}async function Y0($,J){await z0("order:paid",{order:$,payment:J})}async function j$($){await z0("order:shipped",{order:$})}async function V6($){await z0("order:out_for_delivery",{order:$})}async function q$($){await z0("order:delivered",{order:$})}async function R0($,J){await z0("order:cancelled",{order:$,reason:J})}async function S0($,J){await z0("order:refunded",{order:$,refundAmount:J})}async function o0($,J){switch($){case"PROCESSING":return Y0(J);case"SHIPPED":return j$(J);case"OUT_FOR_DELIVERY":return V6(J);case"DELIVERED":return q$(J);case"CANCELLED":return R0(J);case"REFUNDED":return S0(J);case"PENDING":default:}}var lZ;var P0=zZ(()=>{lZ={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 Y1={};B(Y1,{winnerNotification:()=>MZ,settleAuction:()=>t4,settle:()=>b0,rulesFor:()=>y0,resolveBid:()=>v0,pledges:()=>Z1,pledgeTotal:()=>G1,pledgeLevels:()=>R7,placeBid:()=>l4,outbidNotification:()=>BZ,openAuction:()=>d4,nextMinimumBid:()=>o,makePledge:()=>U7,lots:()=>$1,leadingBid:()=>g0,incrementFor:()=>D,fetchPledges:()=>X1,fetchItems:()=>d,fetchCatalogue:()=>i4,fetchAuctionForEvent:()=>n4,fetchAuction:()=>m,extendedCloseAt:()=>D0,engine:()=>u4,effectiveCloseAt:()=>G0,determineWinner:()=>A0,currencyFor:()=>p4,closingSoonNotification:()=>_Z,closingSoon:()=>e4,closeItem:()=>p0,closeDueItems:()=>a4,closeAuction:()=>r4,broadcastPledge:()=>y4,broadcastItemClosed:()=>b4,broadcastBid:()=>v4,bidsForItem:()=>C4,bidsForAuction:()=>h4,bidsByBidder:()=>I4,bids:()=>c4,biddersFor:()=>g4,auctionTotals:()=>s4,auctionChannel:()=>x$,DEFAULT_INCREMENT_LADDER:()=>s});var c4={};B(c4,{placeBid:()=>l4,leadingBid:()=>g0,bidsForItem:()=>C4,bidsForAuction:()=>h4,bidsByBidder:()=>I4,biddersFor:()=>g4});import{db as i}from"@stacksjs/database";async function g0($){return await i.selectFrom("bids").selectAll().where("auction_item_id","=",$).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function C4($){return await i.selectFrom("bids").selectAll().where("auction_item_id","=",$).orderBy("placed_at","desc").execute()??[]}async function h4($){return await i.selectFrom("bids").selectAll().where("auction_id","=",$).orderBy("placed_at","asc").execute()??[]}async function I4($,J){return await i.selectFrom("bids").selectAll().where("auction_id","=",$).where("bidder_email","=",J.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function g4($){let J=await i.selectFrom("bids").select(["bidder_name","bidder_email"]).where("auction_id","=",$).execute(),G=new Map;for(let X of J??[]){let Z=X.bidder_email.toLowerCase();if(!G.has(Z))G.set(Z,{name:X.bidder_name,email:X.bidder_email})}return[...G.values()]}var{randomUUIDv7:xZ}=globalThis.Bun;import{db as m4}from"@stacksjs/database";function D0($,J,G,X){if(G.antiSnipeMinutes<=0||G.extendOnBidWindowMinutes<=0)return null;if($.extension_count>=G.maxExtensions)return null;let Z=J.getTime()-X.getTime();if(Z<=0)return null;if(Z>G.extendOnBidWindowMinutes*60000)return null;let Y=new Date(X.getTime()+G.antiSnipeMinutes*60000);return Y>J?Y:null}function G0($,J){return new Date($.closes_at??J)}var s=[{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 D($,J=s,G){if(G&&G>0)return G;for(let X of J)if(X.upTo===null||$<X.upTo)return X.step;return J[J.length-1]?.step??100}function o($,J,G=s){if(J===null||J<=0)return $.starting_bid;return J+D(J,G,$.min_increment)}function v0($,J,G,X=s){let Z=Math.max(G.amount,G.maxAmount??0),Y=o($,J?J.amount:null,X);if(G.maxAmount!=null&&G.maxAmount<G.amount)return{accepted:!1,reason:"max_below_amount",message:"Your maximum bid has to be at least as much as your bid.",nextMinimumBid:Y};if(Z<Y)return{accepted:!1,reason:"below_minimum",message:`The next bid on this lot is ${Y/100}.`,nextMinimumBid:Y};if($.buy_now_price&&Z>=$.buy_now_price)return{accepted:!0,buyNow:!0,leader:{bidderEmail:G.bidderEmail,bidderName:G.bidderName,amount:$.buy_now_price,maxAmount:$.buy_now_price,isChallenger:!0},challengerAmount:$.buy_now_price,outbid:J?{bidderEmail:J.bidder_email,bidderName:J.bidder_name,amount:J.amount}:void 0,nextMinimumBid:$.buy_now_price};if(!J){let N=Math.max($.starting_bid,G.amount);return{accepted:!0,leader:{bidderEmail:G.bidderEmail,bidderName:G.bidderName,amount:N,maxAmount:G.maxAmount??null,isChallenger:!0},challengerAmount:N,nextMinimumBid:N+D(N,X,$.min_increment)}}let K=Math.max(J.amount,J.max_amount??0);if(J.bidder_email.toLowerCase()===G.bidderEmail.toLowerCase()){if(Z<=K)return{accepted:!1,reason:"already_leading",message:"You are already the leading bidder at or above that amount.",nextMinimumBid:Y};return{accepted:!0,leader:{bidderEmail:J.bidder_email,bidderName:J.bidder_name,amount:J.amount,maxAmount:Z,isChallenger:!1},challengerAmount:J.amount,nextMinimumBid:J.amount+D(J.amount,X,$.min_increment)}}if(Z>K){let N=K+D(K,X,$.min_increment),H=Math.min(Z,Math.max(N,Y));return{accepted:!0,leader:{bidderEmail:G.bidderEmail,bidderName:G.bidderName,amount:H,maxAmount:G.maxAmount??null,isChallenger:!0},challengerAmount:H,outbid:{bidderEmail:J.bidder_email,bidderName:J.bidder_name,amount:J.amount},nextMinimumBid:H+D(H,X,$.min_increment)}}let Q=Z+D(Z,X,$.min_increment),L=Math.min(K,Math.max(Q,Z));return{accepted:!0,leader:{bidderEmail:J.bidder_email,bidderName:J.bidder_name,amount:L,maxAmount:J.max_amount??null,isChallenger:!1},challengerAmount:Z,outbid:{bidderEmail:G.bidderEmail,bidderName:G.bidderName,amount:Z},nextMinimumBid:L+D(L,X,$.min_increment)}}function x$($){return`auction.${$}`}async function D4(){try{return(await import("@stacksjs/realtime")).emit??null}catch{return null}}async function v4($){let J=await D4();if(!J||!$.item||!$.leader)return;await J(x$($.item.auction_id),"bid.placed",{itemId:$.item.id,lotNumber:$.item.lot_number,amount:$.leader.amount,nextMinimumBid:$.nextMinimumBid,leaderName:$.leader.bidderName,status:$.item.status,closesAt:$.item.closes_at,extended:Boolean($.extendedTo),soldViaBuyNow:Boolean($.buyNow)})}async function y4($,J){let G=await D4();if(!G)return;await G(x$($.auction_id),"pledge.made",{donorName:$.donor_name,amount:$.amount,level:$.level??null,runningTotal:J})}async function b4($,J,G){let X=await D4();if(!X)return;await X(x$($),"item.closed",{itemId:J,...G})}import{config as VZ}from"@stacksjs/config";function O7(){return VZ.commerce??{}}function A7(){return O7().auction??{}}function y0($){let J=A7();return{increments:J.increments?.length?J.increments:s,antiSnipeMinutes:$?.anti_snipe_minutes??J.antiSnipeMinutes??2,extendOnBidWindowMinutes:$?.extend_on_bid_window_minutes??J.extendOnBidWindowMinutes??2,maxExtensions:$?.max_extensions??J.maxExtensions??20}}function p4($){return $?.currency??A7().currency??O7().currency??"USD"}function B$($){return $.toISOString().slice(0,19).replace("T"," ")}async function l4($){let J=$.now??new Date,G=await m4.selectFrom("auction_items").selectAll().where("id","=",$.itemId).executeTakeFirst();if(!G)return{accepted:!1,reason:"item_not_found",message:"That lot is no longer available.",nextMinimumBid:0};let X=await m4.selectFrom("auctions").selectAll().where("id","=",G.auction_id).executeTakeFirst(),Z=y0(X),Y=await g0(G.id),K=o(G,Y?.amount??null,Z.increments);if(!X||X.status!=="open"||new Date(X.opens_at)>J)return{accepted:!1,reason:"auction_not_open",message:"Bidding is not open yet.",nextMinimumBid:K,item:G};let W=G0(G,X.closes_at);if(G.status!=="open"||W<=J)return{accepted:!1,reason:"item_not_open",message:"Bidding on this lot has closed.",nextMinimumBid:K,item:G};let Q=v0(G,Y,{bidderEmail:$.bidderEmail,bidderName:$.bidderName,amount:$.amount,maxAmount:$.maxAmount},Z.increments);if(!Q.accepted)return{...Q,item:G};let L=Q.buyNow?null:D0(G,W,Z,J),N=Q.leader&&!Q.leader.isChallenger&&Y&&Y.bidder_email.toLowerCase()===$.bidderEmail.toLowerCase(),H=await m4.transaction(async(x)=>{if(N&&Y)return await x.updateTable("bids").set({max_amount:Q.leader.maxAmount}).where("id","=",Y.id).execute(),{...Y,max_amount:Q.leader.maxAmount};let U=Q.leader?.isChallenger===!0,O=xZ();if(await x.insertInto("bids").values({uuid:O,auction_id:G.auction_id,auction_item_id:G.id,bidder_name:$.bidderName,bidder_email:$.bidderEmail.toLowerCase(),amount:Q.challengerAmount??$.amount,max_amount:$.maxAmount??null,status:U?"leading":"outbid",placed_at:B$(J)}).execute(),Y){if(U)await x.updateTable("bids").set({status:"outbid"}).where("id","=",Y.id).execute();else if(Q.leader&&Q.leader.amount!==Y.amount)await x.updateTable("bids").set({amount:Q.leader.amount}).where("id","=",Y.id).execute()}if(Q.buyNow)await x.updateTable("auction_items").set({status:"sold",closes_at:B$(J)}).where("id","=",G.id).execute();else if(L)await x.updateTable("auction_items").set({closes_at:B$(L),extension_count:G.extension_count+1}).where("id","=",G.id).execute();return await x.selectFrom("bids").selectAll().where("uuid","=",O).executeTakeFirst()}),z={...Q,bid:H,item:{...G,status:Q.buyNow?"sold":G.status,closes_at:L?B$(L):G.closes_at,extension_count:L?G.extension_count+1:G.extension_count},extendedTo:L??void 0};return await v4(z).catch(()=>{return}),z}var u4={};B(u4,{settle:()=>b0,resolveBid:()=>v0,nextMinimumBid:()=>o,incrementFor:()=>D,extendedCloseAt:()=>D0,effectiveCloseAt:()=>G0,determineWinner:()=>A0,DEFAULT_INCREMENT_LADDER:()=>s});function A0($,J){let G=J.filter((Y)=>Y.status!=="invalid");if(G.length===0)return{itemId:$.id,lotNumber:$.lot_number,title:$.title,status:"passed",amount:0,passedReason:"no_bids"};let Z=[...G].sort((Y,K)=>{if(K.amount!==Y.amount)return K.amount-Y.amount;return new Date(Y.placed_at).getTime()-new Date(K.placed_at).getTime()})[0];if($.reserve_price&&Z.amount<$.reserve_price)return{itemId:$.id,lotNumber:$.lot_number,title:$.title,status:"passed",amount:Z.amount,passedReason:"reserve_not_met"};return{itemId:$.id,lotNumber:$.lot_number,title:$.title,status:"sold",winningBidId:Z.id,winnerName:Z.bidder_name,winnerEmail:Z.bidder_email,amount:Z.amount}}function b0($,J,G,X){let Z=J.filter((H)=>H.status==="sold"),Y=J.filter((H)=>H.status==="passed"),K=Z.reduce((H,z)=>H+z.amount,0),W=G.filter((H)=>H.status==="confirmed").reduce((H,z)=>H+z.amount,0),Q=new Map($.map((H)=>[H.id,H.fair_market_value??null])),L=Z.reduce((H,z)=>{let x=Q.get(z.itemId);return x==null?H:H+(z.amount-x)},0),N=J.length;return{auctionId:X.auctionId,currency:X.currency,totalRaised:K+W,bidRevenue:K,pledgeRevenue:W,goalAmount:X.goalAmount??null,itemsSold:Z.length,itemsPassed:Y.length,sellThrough:N===0?0:Z.length/N,valueDelta:L,outcomes:J}}var $1={};B($1,{settleAuction:()=>t4,openAuction:()=>d4,fetchItems:()=>d,fetchCatalogue:()=>i4,fetchAuctionForEvent:()=>n4,fetchAuction:()=>m,closingSoon:()=>e4,closeItem:()=>p0,closeDueItems:()=>a4,closeAuction:()=>r4,auctionTotals:()=>s4});import{db as v}from"@stacksjs/database";async function m($){return await v.selectFrom("auctions").selectAll().where("id","=",$).executeTakeFirst()??null}async function n4($){return await v.selectFrom("auctions").selectAll().where("event_id","=",$).executeTakeFirst()??null}async function d($){return await v.selectFrom("auction_items").selectAll().where("auction_id","=",$).orderBy("lot_number","asc").execute()??[]}async function i4($){let[J,G]=await Promise.all([m($),d($)]),X=y0(J),Z=await v.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",$).where("status","in",["leading","won"]).execute(),Y=await v.selectFrom("bids").select(["auction_item_id"]).where("auction_id","=",$).where("status","!=","invalid").execute(),K=new Map((Z??[]).map((Q)=>[Q.auction_item_id,Q])),W=new Map;for(let Q of Y??[])W.set(Q.auction_item_id,(W.get(Q.auction_item_id)??0)+1);return G.map((Q)=>{let L=K.get(Q.id)??null;return{...Q,currentBid:L?.amount??0,bidCount:W.get(Q.id)??0,nextMinimumBid:o(Q,L?.amount??null,X.increments),leaderName:L?.bidder_name??null}})}async function s4($){let J=await m($),G=await v.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",$).where("status","!=","invalid").execute(),X=await v.selectFrom("pledges").select(["amount"]).where("auction_id","=",$).where("status","=","confirmed").execute(),Z=G??[],K=Z.filter((L)=>L.status==="leading"||L.status==="won").reduce((L,N)=>L+N.amount,0),W=(X??[]).reduce((L,N)=>L+N.amount,0),Q=await v.selectFrom("auction_items").where("auction_id","=",$).count();return{currentBidTotal:K,pledgeTotal:W,raised:K+W,goalAmount:J?.goal_amount??null,bidCount:Z.length,bidderCount:new Set(Z.map((L)=>L.bidder_email.toLowerCase())).size,lotsOffered:Number(Q??0),lotsWithBids:new Set(Z.map((L)=>L.auction_item_id)).size}}import{db as X0}from"@stacksjs/database";function o4($){return $.toISOString().slice(0,19).replace("T"," ")}async function d4($,J=new Date){return await X0.updateTable("auctions").set({status:"open",opens_at:o4(J)}).where("id","=",$).execute(),await X0.updateTable("auction_items").set({status:"open"}).where("auction_id","=",$).where("status","=","closed").execute(),m($)}async function p0($,J=new Date){if($.status==="sold"||$.status==="passed")return null;let G=await X0.selectFrom("bids").selectAll().where("auction_item_id","=",$.id).execute(),X=A0($,G??[]);return await X0.transaction(async(Z)=>{if(await Z.updateTable("auction_items").set({status:X.status,closes_at:o4(J)}).where("id","=",$.id).execute(),X.winningBidId)await Z.updateTable("bids").set({status:"won"}).where("id","=",X.winningBidId).execute();await Z.updateTable("bids").set({status:"lost"}).where("auction_item_id","=",$.id).where("status","in",["leading","outbid"]).execute()}),await b4($.auction_id,$.id,{status:X.status,amount:X.amount,winnerName:X.winnerName}).catch(()=>{return}),X}async function a4($,J=new Date){let G=await m($);if(!G)return[];let X=await d($),Z=[];for(let Y of X){if(Y.status!=="open")continue;if(G0(Y,G.closes_at)>J)continue;let K=await p0(Y,J);if(K)Z.push(K)}return Z}async function r4($,J=new Date){let G=await d($),X=[];for(let Z of G){let Y=await p0(Z,J);if(Y)X.push(Y)}return await X0.updateTable("auctions").set({status:"closed",closes_at:o4(J)}).where("id","=",$).execute(),X}async function t4($,J={}){let G=await m($);if(!G)return null;let X=await d($),Z=await X0.selectFrom("bids").selectAll().where("auction_id","=",$).execute(),Y=await X0.selectFrom("pledges").selectAll().where("auction_id","=",$).execute(),K=new Map;for(let Q of Z??[]){let L=K.get(Q.auction_item_id)??[];L.push(Q),K.set(Q.auction_item_id,L)}let W=X.map((Q)=>{let L=A0(Q,K.get(Q.id)??[]);return Q.status==="passed"?{...L,status:"passed"}:L});if(J.markSettled)await X0.updateTable("auctions").set({status:"settled"}).where("id","=",$).execute();return b0(X,W,Y??[],{auctionId:$,currency:p4(G),goalAmount:G.goal_amount??null})}async function e4($,J,G=new Date){let X=await m($);if(!X)return[];let Z=new Date(G.getTime()+J*60000);return(await d($)).filter((Y)=>{if(Y.status!=="open")return!1;let K=G0(Y,X.closes_at);return K>G&&K<=Z})}function J1($,J="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:J,minimumFractionDigits:0}).format($/100)}function BZ($,J="USD"){if(!$.outbid||!$.item)return null;let G=$.item;return{to:{name:$.outbid.bidderName,email:$.outbid.bidderEmail},type:"outbid",subject:`You have been outbid on lot ${G.lot_number}: ${G.title}`,body:`Someone has bid higher on "${G.title}". The next bid is ${J1($.nextMinimumBid,J)}. Bidding closes ${new Date(G.closes_at??"").toLocaleString()}.`,data:{itemId:G.id,lotNumber:G.lot_number,title:G.title,nextMinimumBid:$.nextMinimumBid,closesAt:G.closes_at}}}function MZ($,J="USD"){if($.status!=="sold"||!$.winnerEmail)return null;return{to:{name:$.winnerName??"Bidder",email:$.winnerEmail},type:"winner",subject:`You won lot ${$.lotNumber}: ${$.title}`,body:`Congratulations - you won "${$.title}" at ${J1($.amount,J)}. The school will be in touch with payment and pickup details.`,data:{itemId:$.itemId,lotNumber:$.lotNumber,title:$.title,amount:$.amount}}}function _Z($,J,G,X="USD"){return{to:J,type:"closing_soon",subject:`Closing soon: lot ${$.lot_number}, ${$.title}`,body:`"${$.title}" closes at ${new Date($.closes_at??"").toLocaleString()}. The current bid is ${J1(G,X)}.`,data:{itemId:$.id,lotNumber:$.lot_number,title:$.title,currentBid:G,closesAt:$.closes_at}}}var Z1={};B(Z1,{pledgeTotal:()=>G1,pledgeLevels:()=>R7,makePledge:()=>U7,fetchPledges:()=>X1});var{randomUUIDv7:OZ}=globalThis.Bun;import{db as m0}from"@stacksjs/database";async function U7($){let J=OZ();await m0.insertInto("pledges").values({uuid:J,auction_id:$.auctionId,donor_name:$.donorName,donor_email:$.donorEmail.toLowerCase(),amount:$.amount,level:$.level??null,status:$.status??"confirmed"}).execute();let G=await m0.selectFrom("pledges").selectAll().where("uuid","=",J).executeTakeFirst();return await y4(G,await G1($.auctionId)).catch(()=>{return}),G}async function G1($){return(await m0.selectFrom("pledges").select(["amount"]).where("auction_id","=",$).where("status","=","confirmed").execute()??[]).reduce((G,X)=>G+X.amount,0)}async function X1($){return await m0.selectFrom("pledges").selectAll().where("auction_id","=",$).orderBy("amount","desc").execute()??[]}async function R7($){let J=(await X1($)).filter((X)=>X.status==="confirmed"),G=new Map;for(let X of J){let Z=X.level??"other",Y=G.get(Z)??{amount:0,count:0};Y.amount+=X.amount,Y.count+=1,G.set(Z,Y)}return[...G.entries()].map(([X,Z])=>({level:X,...Z})).sort((X,Z)=>Z.amount-X.amount)}var K1={};B(K1,{update:()=>n7,store:()=>m7,redeem:()=>i7,getActiveCouponsMoMChange:()=>y7,fetchTopRedeemedCoupons:()=>g7,fetchStats:()=>f7,fetchRedemptionTrend:()=>D7,fetchRedemptionStats:()=>I7,fetchCouponCountsByType:()=>h7,fetchCouponCounts:()=>C7,fetchConversionRate:()=>v7,fetchById:()=>N0,fetchByCode:()=>k7,fetchAll:()=>q7,fetchActive:()=>w7,deleteExpiredCoupons:()=>E7,deleteCoupons:()=>P7,deleteCoupon:()=>S7});import{db as M$}from"@stacksjs/database";import{formatDate as AZ}from"@stacksjs/orm";function F($){if(typeof $==="number")return Number.isFinite($)?$:0;if(typeof $==="bigint")return Number($);if(!$||typeof $!=="object")return 0;let J=$;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if(J[G]!==void 0&&J[G]!==null)return F(J[G]);if(Array.isArray($))return $.reduce((G,X)=>G+F(X),0);return 0}async function S7($){let J=await M$.deleteFrom("coupons").where("id","=",$).executeTakeFirst();return F(J)>0}async function P7($){if(!$.length)return 0;return(await M$.deleteFrom("coupons").where("id","in",$).execute()).length||0}async function E7(){let $=AZ(new Date),J=await M$.deleteFrom("coupons").where("end_date","<",$).executeTakeFirst();return F(J)}import{db as V}from"@stacksjs/database";import{extractDate as T7,formatDate as j7}from"@stacksjs/orm";import{camelCase as UZ}from"@stacksjs/strings";function O$($){let J=Object.fromEntries(Object.entries($).map(([G,X])=>[UZ(G),X]));if(J.endDate)J.endDate=T7(new Date(J.endDate));if(J.startDate)J.startDate=T7(new Date(J.startDate));if(J.isActive!==void 0)J.isActive=Boolean(J.isActive);return J}async function q7(){return(await V.selectFrom("coupons").selectAll().execute()).map(O$)}async function N0($){let J=await V.selectFrom("coupons").where("id","=",$).selectAll().executeTakeFirst();if(J)return O$(J);return}async function k7($){let J=await V.selectFrom("coupons").where("code","=",$).selectAll().executeTakeFirst();if(J)return O$(J);return}async function w7(){let $=j7(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).selectAll().execute()).map(O$)}async function f7(){let $=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).executeTakeFirst(),J=j7(new Date),G=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(V.fn.count("id").as("count")).executeTakeFirst(),X=await V.selectFrom("coupons").select(["discount_type",V.fn.count("id").as("count")]).groupBy("discount_type").execute(),Z=await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),Y=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",J).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number($?.count||0),active:Number(G?.count||0),by_type:X,most_used:Z,upcoming:Y}}async function C7(){let $=new Date,J=new Date($);J.setDate($.getDate()-7);let G=new Date($);G.setMonth($.getMonth()-1);let X=new Date($);X.setFullYear($.getFullYear()-1);let Z=await _$(null,null,$),Y=await _$(J,null,$),K=await _$(G,null,$),W=await _$(X,null,$);return{week:Y,month:K,year:W,all_time:Z}}async function _$($,J,G){let X=V.selectFrom("coupons");if($)X=X.where("created_at",">=",$.toISOString());if(J)X=X.where("created_at","<=",J.toISOString());let Z=await X.select(V.fn.count("id").as("count")).executeTakeFirst(),Y=V.selectFrom("coupons");if($)Y=Y.where("created_at",">=",$.toISOString());if(J)Y=Y.where("created_at","<=",J.toISOString());Y=Y.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let K=await Y.select(V.fn.count("id").as("count")).executeTakeFirst(),W=Number(Z?.count||0),Q=Number(K?.count||0),L=W-Q;return{total:W,active:Q,inactive:L}}async function h7(){let $=new Date,J=await V.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:X}of J){let Z=await V.selectFrom("coupons").where("discount_type","=",X).select(V.fn.count("id").as("count")).executeTakeFirst(),Y=await V.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(V.fn.count("id").as("count")).executeTakeFirst(),K=Number(Z?.count||0),W=Number(Y?.count||0);G[X]={total:K,active:W,inactive:K-W}}return G}async function I7(){let $=await V.selectFrom("coupons").select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),J=new Date,G=new Date(J);G.setDate(J.getDate()-7);let X=new Date(J);X.setMonth(J.getMonth()-1);let Z=new Date(J);Z.setFullYear(J.getFullYear()-1);let Y=await V.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),K=await V.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await V.selectFrom("coupons").where("updated_at",">=",Z.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),Q=await V.selectFrom("coupons").select(["discount_type",V.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),L={};return Q.forEach((N)=>{L[N.discount_type]=Number(N.total||0)}),{total:Number($?.total||0),week:Number(Y?.total||0),month:Number(K?.total||0),year:Number(W?.total||0),by_type:L}}async function g7($=5){return await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit($).execute()}async function D7($=30){let J=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-$);let X=await V.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",J).where("usage_count",">",0).orderBy("updated_at","desc").execute(),Z={};return X.forEach((Y)=>{let K=Y.updated_at?new Date(Y.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!Z[K])Z[K]=0;Z[K]+=Y?.usage_count||0}),Object.entries(Z).map(([Y,K])=>({date:Y,count:K}))}async function v7(){let $=new Date,J=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(V.fn.count("id").as("count")).executeTakeFirst(),G=await V.selectFrom("coupons").where("usage_count",">",0).select(V.fn.count("id").as("count")).executeTakeFirst(),X=Number(J?.count||0),Z=Number(G?.count||0);return{rate:X>0?Z/X*100:0,total_active:X,total_redeemed:Z}}async function y7(){let $=new Date,J=new Date($.getFullYear(),$.getMonth(),1),G=new Date($.getFullYear(),$.getMonth()-1,1),X=new Date($.getFullYear(),$.getMonth(),0),Z=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",J).executeTakeFirst(),Y=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",G).executeTakeFirst(),K=Number(Z?.count||0),W=Number(Y?.count||0),Q=K-W,L=W!==0?Q/W*100:K>0?100:0;return{current_month:K,previous_month:W,difference:Q,percentage_change:L}}var{randomUUIDv7:RZ}=globalThis.Bun;import{db as b7}from"@stacksjs/database";import{HttpError as p7}from"@stacksjs/error-handling";import{isUniqueViolation as SZ}from"@stacksjs/orm";async function m7($){try{let J=RZ();return await b7.insertInto("coupons").values({...$,uuid:J}).executeTakeFirst(),await b7.selectFrom("coupons").where("uuid","=",J).selectAll().executeTakeFirst()}catch(J){if(J instanceof p7)throw J;if(SZ(J))throw new p7(409,"A coupon with this code already exists");if(J instanceof Error)throw Error(`Failed to create coupon: ${J.message}`);throw J}}import{db as c7}from"@stacksjs/database";import{HttpError as l7}from"@stacksjs/error-handling";import{formatDate as u7,isUniqueViolation as PZ}from"@stacksjs/orm";async function n7($,J){if(!await N0($))return;try{return await c7.updateTable("coupons").set({...J,updated_at:u7(new Date)}).where("id","=",$).execute(),await N0($)}catch(X){if(X instanceof l7)throw X;if(PZ(X))throw new l7(409,"A coupon with this code already exists");if(X instanceof Error)throw Error(`Failed to update coupon: ${X.message}`);throw X}}async function i7($){let J=u7(new Date),G=await c7.unsafe(`UPDATE coupons
|
|
2
|
+
var LZ=Object.defineProperty;var NZ=($)=>$;function HZ($,J){this[$]=NZ.bind(null,J)}var B=($,J)=>{for(var G in J)LZ($,G,{get:J[G],enumerable:!0,configurable:!0,set:HZ.bind(J,G)})};var zZ=($,J)=>()=>($&&(J=$($=0)),J);var n=import.meta.require;var x6={};B(x6,{emitOrderShipped:()=>j$,emitOrderRefunded:()=>S0,emitOrderPaid:()=>Y0,emitOrderOutForDelivery:()=>V6,emitOrderDelivered:()=>q$,emitOrderCreated:()=>s0,emitOrderCancelled:()=>P0,emitForStatus:()=>o0,canTransition:()=>i0});function i0($,J){if($===J)return!0;return lZ[$]?.includes(J)??!1}async function z0($,J){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X($,J)}catch{}}async function s0($){await z0("order:created",{order:$})}async function Y0($,J){await z0("order:paid",{order:$,payment:J})}async function j$($){await z0("order:shipped",{order:$})}async function V6($){await z0("order:out_for_delivery",{order:$})}async function q$($){await z0("order:delivered",{order:$})}async function P0($,J){await z0("order:cancelled",{order:$,reason:J})}async function S0($,J){await z0("order:refunded",{order:$,refundAmount:J})}async function o0($,J){switch($){case"PROCESSING":return Y0(J);case"SHIPPED":return j$(J);case"OUT_FOR_DELIVERY":return V6(J);case"DELIVERED":return q$(J);case"CANCELLED":return P0(J);case"REFUNDED":return S0(J);case"PENDING":default:}}var lZ;var R0=zZ(()=>{lZ={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 Y1={};B(Y1,{winnerNotification:()=>MZ,settleAuction:()=>t4,settle:()=>b0,rulesFor:()=>y0,resolveBid:()=>v0,pledges:()=>Z1,pledgeTotal:()=>G1,pledgeLevels:()=>P7,placeBid:()=>l4,outbidNotification:()=>BZ,openAuction:()=>d4,nextMinimumBid:()=>o,makePledge:()=>U7,lots:()=>$1,leadingBid:()=>g0,incrementFor:()=>D,fetchPledges:()=>X1,fetchItems:()=>d,fetchCatalogue:()=>i4,fetchAuctionForEvent:()=>n4,fetchAuction:()=>m,extendedCloseAt:()=>D0,engine:()=>u4,effectiveCloseAt:()=>G0,determineWinner:()=>A0,currencyFor:()=>p4,closingSoonNotification:()=>_Z,closingSoon:()=>e4,closeItem:()=>p0,closeDueItems:()=>a4,closeAuction:()=>r4,broadcastPledge:()=>y4,broadcastItemClosed:()=>b4,broadcastBid:()=>v4,bidsForItem:()=>C4,bidsForAuction:()=>h4,bidsByBidder:()=>I4,bids:()=>c4,biddersFor:()=>g4,auctionTotals:()=>s4,auctionChannel:()=>x$,DEFAULT_INCREMENT_LADDER:()=>s});var c4={};B(c4,{placeBid:()=>l4,leadingBid:()=>g0,bidsForItem:()=>C4,bidsForAuction:()=>h4,bidsByBidder:()=>I4,biddersFor:()=>g4});import{db as i}from"@stacksjs/database";async function g0($){return await i.selectFrom("bids").selectAll().where("auction_item_id","=",$).where("status","=","leading").orderBy("amount","desc").executeTakeFirst()??null}async function C4($){return await i.selectFrom("bids").selectAll().where("auction_item_id","=",$).orderBy("placed_at","desc").execute()??[]}async function h4($){return await i.selectFrom("bids").selectAll().where("auction_id","=",$).orderBy("placed_at","asc").execute()??[]}async function I4($,J){return await i.selectFrom("bids").selectAll().where("auction_id","=",$).where("bidder_email","=",J.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function g4($){let J=await i.selectFrom("bids").select(["bidder_name","bidder_email"]).where("auction_id","=",$).execute(),G=new Map;for(let X of J??[]){let Z=X.bidder_email.toLowerCase();if(!G.has(Z))G.set(Z,{name:X.bidder_name,email:X.bidder_email})}return[...G.values()]}var{randomUUIDv7:xZ}=globalThis.Bun;import{db as m4}from"@stacksjs/database";function D0($,J,G,X){if(G.antiSnipeMinutes<=0||G.extendOnBidWindowMinutes<=0)return null;if($.extension_count>=G.maxExtensions)return null;let Z=J.getTime()-X.getTime();if(Z<=0)return null;if(Z>G.extendOnBidWindowMinutes*60000)return null;let Y=new Date(X.getTime()+G.antiSnipeMinutes*60000);return Y>J?Y:null}function G0($,J){return new Date($.closes_at??J)}var s=[{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 D($,J=s,G){if(G&&G>0)return G;for(let X of J)if(X.upTo===null||$<X.upTo)return X.step;return J[J.length-1]?.step??100}function o($,J,G=s){if(J===null||J<=0)return $.starting_bid;return J+D(J,G,$.min_increment)}function v0($,J,G,X=s){let Z=Math.max(G.amount,G.maxAmount??0),Y=o($,J?J.amount:null,X);if(G.maxAmount!=null&&G.maxAmount<G.amount)return{accepted:!1,reason:"max_below_amount",message:"Your maximum bid has to be at least as much as your bid.",nextMinimumBid:Y};if(Z<Y)return{accepted:!1,reason:"below_minimum",message:`The next bid on this lot is ${Y/100}.`,nextMinimumBid:Y};if($.buy_now_price&&Z>=$.buy_now_price)return{accepted:!0,buyNow:!0,leader:{bidderEmail:G.bidderEmail,bidderName:G.bidderName,amount:$.buy_now_price,maxAmount:$.buy_now_price,isChallenger:!0},challengerAmount:$.buy_now_price,outbid:J?{bidderEmail:J.bidder_email,bidderName:J.bidder_name,amount:J.amount}:void 0,nextMinimumBid:$.buy_now_price};if(!J){let N=Math.max($.starting_bid,G.amount);return{accepted:!0,leader:{bidderEmail:G.bidderEmail,bidderName:G.bidderName,amount:N,maxAmount:G.maxAmount??null,isChallenger:!0},challengerAmount:N,nextMinimumBid:N+D(N,X,$.min_increment)}}let K=Math.max(J.amount,J.max_amount??0);if(J.bidder_email.toLowerCase()===G.bidderEmail.toLowerCase()){if(Z<=K)return{accepted:!1,reason:"already_leading",message:"You are already the leading bidder at or above that amount.",nextMinimumBid:Y};return{accepted:!0,leader:{bidderEmail:J.bidder_email,bidderName:J.bidder_name,amount:J.amount,maxAmount:Z,isChallenger:!1},challengerAmount:J.amount,nextMinimumBid:J.amount+D(J.amount,X,$.min_increment)}}if(Z>K){let N=K+D(K,X,$.min_increment),H=Math.min(Z,Math.max(N,Y));return{accepted:!0,leader:{bidderEmail:G.bidderEmail,bidderName:G.bidderName,amount:H,maxAmount:G.maxAmount??null,isChallenger:!0},challengerAmount:H,outbid:{bidderEmail:J.bidder_email,bidderName:J.bidder_name,amount:J.amount},nextMinimumBid:H+D(H,X,$.min_increment)}}let Q=Z+D(Z,X,$.min_increment),F=Math.min(K,Math.max(Q,Z));return{accepted:!0,leader:{bidderEmail:J.bidder_email,bidderName:J.bidder_name,amount:F,maxAmount:J.max_amount??null,isChallenger:!1},challengerAmount:Z,outbid:{bidderEmail:G.bidderEmail,bidderName:G.bidderName,amount:Z},nextMinimumBid:F+D(F,X,$.min_increment)}}function x$($){return`auction.${$}`}async function D4(){try{return(await import("@stacksjs/realtime")).emit??null}catch{return null}}async function v4($){let J=await D4();if(!J||!$.item||!$.leader)return;await J(x$($.item.auction_id),"bid.placed",{itemId:$.item.id,lotNumber:$.item.lot_number,amount:$.leader.amount,nextMinimumBid:$.nextMinimumBid,leaderName:$.leader.bidderName,status:$.item.status,closesAt:$.item.closes_at,extended:Boolean($.extendedTo),soldViaBuyNow:Boolean($.buyNow)})}async function y4($,J){let G=await D4();if(!G)return;await G(x$($.auction_id),"pledge.made",{donorName:$.donor_name,amount:$.amount,level:$.level??null,runningTotal:J})}async function b4($,J,G){let X=await D4();if(!X)return;await X(x$($),"item.closed",{itemId:J,...G})}import{config as VZ}from"@stacksjs/config";function O7(){return VZ.commerce??{}}function A7(){return O7().auction??{}}function y0($){let J=A7();return{increments:J.increments?.length?J.increments:s,antiSnipeMinutes:$?.anti_snipe_minutes??J.antiSnipeMinutes??2,extendOnBidWindowMinutes:$?.extend_on_bid_window_minutes??J.extendOnBidWindowMinutes??2,maxExtensions:$?.max_extensions??J.maxExtensions??20}}function p4($){return $?.currency??A7().currency??O7().currency??"USD"}function B$($){return $.toISOString().slice(0,19).replace("T"," ")}async function l4($){let J=$.now??new Date,G=await m4.selectFrom("auction_items").selectAll().where("id","=",$.itemId).executeTakeFirst();if(!G)return{accepted:!1,reason:"item_not_found",message:"That lot is no longer available.",nextMinimumBid:0};let X=await m4.selectFrom("auctions").selectAll().where("id","=",G.auction_id).executeTakeFirst(),Z=y0(X),Y=await g0(G.id),K=o(G,Y?.amount??null,Z.increments);if(!X||X.status!=="open"||new Date(X.opens_at)>J)return{accepted:!1,reason:"auction_not_open",message:"Bidding is not open yet.",nextMinimumBid:K,item:G};let W=G0(G,X.closes_at);if(G.status!=="open"||W<=J)return{accepted:!1,reason:"item_not_open",message:"Bidding on this lot has closed.",nextMinimumBid:K,item:G};let Q=v0(G,Y,{bidderEmail:$.bidderEmail,bidderName:$.bidderName,amount:$.amount,maxAmount:$.maxAmount},Z.increments);if(!Q.accepted)return{...Q,item:G};let F=Q.buyNow?null:D0(G,W,Z,J),N=Q.leader&&!Q.leader.isChallenger&&Y&&Y.bidder_email.toLowerCase()===$.bidderEmail.toLowerCase(),H=await m4.transaction(async(x)=>{if(N&&Y)return await x.updateTable("bids").set({max_amount:Q.leader.maxAmount}).where("id","=",Y.id).execute(),{...Y,max_amount:Q.leader.maxAmount};let U=Q.leader?.isChallenger===!0,O=xZ();if(await x.insertInto("bids").values({uuid:O,auction_id:G.auction_id,auction_item_id:G.id,bidder_name:$.bidderName,bidder_email:$.bidderEmail.toLowerCase(),amount:Q.challengerAmount??$.amount,max_amount:$.maxAmount??null,status:U?"leading":"outbid",placed_at:B$(J)}).execute(),Y){if(U)await x.updateTable("bids").set({status:"outbid"}).where("id","=",Y.id).execute();else if(Q.leader&&Q.leader.amount!==Y.amount)await x.updateTable("bids").set({amount:Q.leader.amount}).where("id","=",Y.id).execute()}if(Q.buyNow)await x.updateTable("auction_items").set({status:"sold",closes_at:B$(J)}).where("id","=",G.id).execute();else if(F)await x.updateTable("auction_items").set({closes_at:B$(F),extension_count:G.extension_count+1}).where("id","=",G.id).execute();return await x.selectFrom("bids").selectAll().where("uuid","=",O).executeTakeFirst()}),z={...Q,bid:H,item:{...G,status:Q.buyNow?"sold":G.status,closes_at:F?B$(F):G.closes_at,extension_count:F?G.extension_count+1:G.extension_count},extendedTo:F??void 0};return await v4(z).catch(()=>{return}),z}var u4={};B(u4,{settle:()=>b0,resolveBid:()=>v0,nextMinimumBid:()=>o,incrementFor:()=>D,extendedCloseAt:()=>D0,effectiveCloseAt:()=>G0,determineWinner:()=>A0,DEFAULT_INCREMENT_LADDER:()=>s});function A0($,J){let G=J.filter((Y)=>Y.status!=="invalid");if(G.length===0)return{itemId:$.id,lotNumber:$.lot_number,title:$.title,status:"passed",amount:0,passedReason:"no_bids"};let Z=[...G].sort((Y,K)=>{if(K.amount!==Y.amount)return K.amount-Y.amount;return new Date(Y.placed_at).getTime()-new Date(K.placed_at).getTime()})[0];if($.reserve_price&&Z.amount<$.reserve_price)return{itemId:$.id,lotNumber:$.lot_number,title:$.title,status:"passed",amount:Z.amount,passedReason:"reserve_not_met"};return{itemId:$.id,lotNumber:$.lot_number,title:$.title,status:"sold",winningBidId:Z.id,winnerName:Z.bidder_name,winnerEmail:Z.bidder_email,amount:Z.amount}}function b0($,J,G,X){let Z=J.filter((H)=>H.status==="sold"),Y=J.filter((H)=>H.status==="passed"),K=Z.reduce((H,z)=>H+z.amount,0),W=G.filter((H)=>H.status==="confirmed").reduce((H,z)=>H+z.amount,0),Q=new Map($.map((H)=>[H.id,H.fair_market_value??null])),F=Z.reduce((H,z)=>{let x=Q.get(z.itemId);return x==null?H:H+(z.amount-x)},0),N=J.length;return{auctionId:X.auctionId,currency:X.currency,totalRaised:K+W,bidRevenue:K,pledgeRevenue:W,goalAmount:X.goalAmount??null,itemsSold:Z.length,itemsPassed:Y.length,sellThrough:N===0?0:Z.length/N,valueDelta:F,outcomes:J}}var $1={};B($1,{settleAuction:()=>t4,openAuction:()=>d4,fetchItems:()=>d,fetchCatalogue:()=>i4,fetchAuctionForEvent:()=>n4,fetchAuction:()=>m,closingSoon:()=>e4,closeItem:()=>p0,closeDueItems:()=>a4,closeAuction:()=>r4,auctionTotals:()=>s4});import{db as v}from"@stacksjs/database";async function m($){return await v.selectFrom("auctions").selectAll().where("id","=",$).executeTakeFirst()??null}async function n4($){return await v.selectFrom("auctions").selectAll().where("event_id","=",$).executeTakeFirst()??null}async function d($){return await v.selectFrom("auction_items").selectAll().where("auction_id","=",$).orderBy("lot_number","asc").execute()??[]}async function i4($){let[J,G]=await Promise.all([m($),d($)]),X=y0(J),Z=await v.selectFrom("bids").select(["auction_item_id","amount","bidder_name"]).where("auction_id","=",$).where("status","in",["leading","won"]).execute(),Y=await v.selectFrom("bids").select(["auction_item_id"]).where("auction_id","=",$).where("status","!=","invalid").execute(),K=new Map((Z??[]).map((Q)=>[Q.auction_item_id,Q])),W=new Map;for(let Q of Y??[])W.set(Q.auction_item_id,(W.get(Q.auction_item_id)??0)+1);return G.map((Q)=>{let F=K.get(Q.id)??null;return{...Q,currentBid:F?.amount??0,bidCount:W.get(Q.id)??0,nextMinimumBid:o(Q,F?.amount??null,X.increments),leaderName:F?.bidder_name??null}})}async function s4($){let J=await m($),G=await v.selectFrom("bids").select(["auction_item_id","amount","bidder_email","status"]).where("auction_id","=",$).where("status","!=","invalid").execute(),X=await v.selectFrom("pledges").select(["amount"]).where("auction_id","=",$).where("status","=","confirmed").execute(),Z=G??[],K=Z.filter((F)=>F.status==="leading"||F.status==="won").reduce((F,N)=>F+N.amount,0),W=(X??[]).reduce((F,N)=>F+N.amount,0),Q=await v.selectFrom("auction_items").where("auction_id","=",$).count();return{currentBidTotal:K,pledgeTotal:W,raised:K+W,goalAmount:J?.goal_amount??null,bidCount:Z.length,bidderCount:new Set(Z.map((F)=>F.bidder_email.toLowerCase())).size,lotsOffered:Number(Q??0),lotsWithBids:new Set(Z.map((F)=>F.auction_item_id)).size}}import{db as X0}from"@stacksjs/database";function o4($){return $.toISOString().slice(0,19).replace("T"," ")}async function d4($,J=new Date){return await X0.updateTable("auctions").set({status:"open",opens_at:o4(J)}).where("id","=",$).execute(),await X0.updateTable("auction_items").set({status:"open"}).where("auction_id","=",$).where("status","=","closed").execute(),m($)}async function p0($,J=new Date){if($.status==="sold"||$.status==="passed")return null;let G=await X0.selectFrom("bids").selectAll().where("auction_item_id","=",$.id).execute(),X=A0($,G??[]);return await X0.transaction(async(Z)=>{if(await Z.updateTable("auction_items").set({status:X.status,closes_at:o4(J)}).where("id","=",$.id).execute(),X.winningBidId)await Z.updateTable("bids").set({status:"won"}).where("id","=",X.winningBidId).execute();await Z.updateTable("bids").set({status:"lost"}).where("auction_item_id","=",$.id).where("status","in",["leading","outbid"]).execute()}),await b4($.auction_id,$.id,{status:X.status,amount:X.amount,winnerName:X.winnerName}).catch(()=>{return}),X}async function a4($,J=new Date){let G=await m($);if(!G)return[];let X=await d($),Z=[];for(let Y of X){if(Y.status!=="open")continue;if(G0(Y,G.closes_at)>J)continue;let K=await p0(Y,J);if(K)Z.push(K)}return Z}async function r4($,J=new Date){let G=await d($),X=[];for(let Z of G){let Y=await p0(Z,J);if(Y)X.push(Y)}return await X0.updateTable("auctions").set({status:"closed",closes_at:o4(J)}).where("id","=",$).execute(),X}async function t4($,J={}){let G=await m($);if(!G)return null;let X=await d($),Z=await X0.selectFrom("bids").selectAll().where("auction_id","=",$).execute(),Y=await X0.selectFrom("pledges").selectAll().where("auction_id","=",$).execute(),K=new Map;for(let Q of Z??[]){let F=K.get(Q.auction_item_id)??[];F.push(Q),K.set(Q.auction_item_id,F)}let W=X.map((Q)=>{let F=A0(Q,K.get(Q.id)??[]);return Q.status==="passed"?{...F,status:"passed"}:F});if(J.markSettled)await X0.updateTable("auctions").set({status:"settled"}).where("id","=",$).execute();return b0(X,W,Y??[],{auctionId:$,currency:p4(G),goalAmount:G.goal_amount??null})}async function e4($,J,G=new Date){let X=await m($);if(!X)return[];let Z=new Date(G.getTime()+J*60000);return(await d($)).filter((Y)=>{if(Y.status!=="open")return!1;let K=G0(Y,X.closes_at);return K>G&&K<=Z})}function J1($,J="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:J,minimumFractionDigits:0}).format($/100)}function BZ($,J="USD"){if(!$.outbid||!$.item)return null;let G=$.item;return{to:{name:$.outbid.bidderName,email:$.outbid.bidderEmail},type:"outbid",subject:`You have been outbid on lot ${G.lot_number}: ${G.title}`,body:`Someone has bid higher on "${G.title}". The next bid is ${J1($.nextMinimumBid,J)}. Bidding closes ${new Date(G.closes_at??"").toLocaleString()}.`,data:{itemId:G.id,lotNumber:G.lot_number,title:G.title,nextMinimumBid:$.nextMinimumBid,closesAt:G.closes_at}}}function MZ($,J="USD"){if($.status!=="sold"||!$.winnerEmail)return null;return{to:{name:$.winnerName??"Bidder",email:$.winnerEmail},type:"winner",subject:`You won lot ${$.lotNumber}: ${$.title}`,body:`Congratulations - you won "${$.title}" at ${J1($.amount,J)}. The school will be in touch with payment and pickup details.`,data:{itemId:$.itemId,lotNumber:$.lotNumber,title:$.title,amount:$.amount}}}function _Z($,J,G,X="USD"){return{to:J,type:"closing_soon",subject:`Closing soon: lot ${$.lot_number}, ${$.title}`,body:`"${$.title}" closes at ${new Date($.closes_at??"").toLocaleString()}. The current bid is ${J1(G,X)}.`,data:{itemId:$.id,lotNumber:$.lot_number,title:$.title,currentBid:G,closesAt:$.closes_at}}}var Z1={};B(Z1,{pledgeTotal:()=>G1,pledgeLevels:()=>P7,makePledge:()=>U7,fetchPledges:()=>X1});var{randomUUIDv7:OZ}=globalThis.Bun;import{db as m0}from"@stacksjs/database";async function U7($){let J=OZ();await m0.insertInto("pledges").values({uuid:J,auction_id:$.auctionId,donor_name:$.donorName,donor_email:$.donorEmail.toLowerCase(),amount:$.amount,level:$.level??null,status:$.status??"confirmed"}).execute();let G=await m0.selectFrom("pledges").selectAll().where("uuid","=",J).executeTakeFirst();return await y4(G,await G1($.auctionId)).catch(()=>{return}),G}async function G1($){return(await m0.selectFrom("pledges").select(["amount"]).where("auction_id","=",$).where("status","=","confirmed").execute()??[]).reduce((G,X)=>G+X.amount,0)}async function X1($){return await m0.selectFrom("pledges").selectAll().where("auction_id","=",$).orderBy("amount","desc").execute()??[]}async function P7($){let J=(await X1($)).filter((X)=>X.status==="confirmed"),G=new Map;for(let X of J){let Z=X.level??"other",Y=G.get(Z)??{amount:0,count:0};Y.amount+=X.amount,Y.count+=1,G.set(Z,Y)}return[...G.entries()].map(([X,Z])=>({level:X,...Z})).sort((X,Z)=>Z.amount-X.amount)}var K1={};B(K1,{update:()=>n7,store:()=>m7,redeem:()=>i7,getActiveCouponsMoMChange:()=>y7,fetchTopRedeemedCoupons:()=>g7,fetchStats:()=>f7,fetchRedemptionTrend:()=>D7,fetchRedemptionStats:()=>I7,fetchCouponCountsByType:()=>h7,fetchCouponCounts:()=>C7,fetchConversionRate:()=>v7,fetchById:()=>N0,fetchByCode:()=>k7,fetchAll:()=>q7,fetchActive:()=>w7,deleteExpiredCoupons:()=>T7,deleteCoupons:()=>R7,deleteCoupon:()=>S7});import{db as M$}from"@stacksjs/database";import{formatDate as AZ}from"@stacksjs/orm";function L($){if(typeof $==="number")return Number.isFinite($)?$:0;if(typeof $==="bigint")return Number($);if(!$||typeof $!=="object")return 0;let J=$;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if(J[G]!==void 0&&J[G]!==null)return L(J[G]);if(Array.isArray($))return $.reduce((G,X)=>G+L(X),0);return 0}async function S7($){let J=await M$.deleteFrom("coupons").where("id","=",$).executeTakeFirst();return L(J)>0}async function R7($){if(!$.length)return 0;return(await M$.deleteFrom("coupons").where("id","in",$).execute()).length||0}async function T7(){let $=AZ(new Date),J=await M$.deleteFrom("coupons").where("end_date","<",$).executeTakeFirst();return L(J)}import{db as V}from"@stacksjs/database";import{extractDate as E7,formatDate as j7}from"@stacksjs/orm";import{camelCase as UZ}from"@stacksjs/strings";function O$($){let J=Object.fromEntries(Object.entries($).map(([G,X])=>[UZ(G),X]));if(J.endDate)J.endDate=E7(new Date(J.endDate));if(J.startDate)J.startDate=E7(new Date(J.startDate));if(J.isActive!==void 0)J.isActive=Boolean(J.isActive);return J}async function q7(){return(await V.selectFrom("coupons").selectAll().execute()).map(O$)}async function N0($){let J=await V.selectFrom("coupons").where("id","=",$).selectAll().executeTakeFirst();if(J)return O$(J);return}async function k7($){let J=await V.selectFrom("coupons").where("code","=",$).selectAll().executeTakeFirst();if(J)return O$(J);return}async function w7(){let $=j7(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).selectAll().execute()).map(O$)}async function f7(){let $=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).executeTakeFirst(),J=j7(new Date),G=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(V.fn.count("id").as("count")).executeTakeFirst(),X=await V.selectFrom("coupons").select(["discount_type",V.fn.count("id").as("count")]).groupBy("discount_type").execute(),Z=await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),Y=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",J).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number($?.count||0),active:Number(G?.count||0),by_type:X,most_used:Z,upcoming:Y}}async function C7(){let $=new Date,J=new Date($);J.setDate($.getDate()-7);let G=new Date($);G.setMonth($.getMonth()-1);let X=new Date($);X.setFullYear($.getFullYear()-1);let Z=await _$(null,null,$),Y=await _$(J,null,$),K=await _$(G,null,$),W=await _$(X,null,$);return{week:Y,month:K,year:W,all_time:Z}}async function _$($,J,G){let X=V.selectFrom("coupons");if($)X=X.where("created_at",">=",$.toISOString());if(J)X=X.where("created_at","<=",J.toISOString());let Z=await X.select(V.fn.count("id").as("count")).executeTakeFirst(),Y=V.selectFrom("coupons");if($)Y=Y.where("created_at",">=",$.toISOString());if(J)Y=Y.where("created_at","<=",J.toISOString());Y=Y.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let K=await Y.select(V.fn.count("id").as("count")).executeTakeFirst(),W=Number(Z?.count||0),Q=Number(K?.count||0),F=W-Q;return{total:W,active:Q,inactive:F}}async function h7(){let $=new Date,J=await V.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:X}of J){let Z=await V.selectFrom("coupons").where("discount_type","=",X).select(V.fn.count("id").as("count")).executeTakeFirst(),Y=await V.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(V.fn.count("id").as("count")).executeTakeFirst(),K=Number(Z?.count||0),W=Number(Y?.count||0);G[X]={total:K,active:W,inactive:K-W}}return G}async function I7(){let $=await V.selectFrom("coupons").select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),J=new Date,G=new Date(J);G.setDate(J.getDate()-7);let X=new Date(J);X.setMonth(J.getMonth()-1);let Z=new Date(J);Z.setFullYear(J.getFullYear()-1);let Y=await V.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),K=await V.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await V.selectFrom("coupons").where("updated_at",">=",Z.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),Q=await V.selectFrom("coupons").select(["discount_type",V.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),F={};return Q.forEach((N)=>{F[N.discount_type]=Number(N.total||0)}),{total:Number($?.total||0),week:Number(Y?.total||0),month:Number(K?.total||0),year:Number(W?.total||0),by_type:F}}async function g7($=5){return await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit($).execute()}async function D7($=30){let J=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-$);let X=await V.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",J).where("usage_count",">",0).orderBy("updated_at","desc").execute(),Z={};return X.forEach((Y)=>{let K=Y.updated_at?new Date(Y.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!Z[K])Z[K]=0;Z[K]+=Y?.usage_count||0}),Object.entries(Z).map(([Y,K])=>({date:Y,count:K}))}async function v7(){let $=new Date,J=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(V.fn.count("id").as("count")).executeTakeFirst(),G=await V.selectFrom("coupons").where("usage_count",">",0).select(V.fn.count("id").as("count")).executeTakeFirst(),X=Number(J?.count||0),Z=Number(G?.count||0);return{rate:X>0?Z/X*100:0,total_active:X,total_redeemed:Z}}async function y7(){let $=new Date,J=new Date($.getFullYear(),$.getMonth(),1),G=new Date($.getFullYear(),$.getMonth()-1,1),X=new Date($.getFullYear(),$.getMonth(),0),Z=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",J).executeTakeFirst(),Y=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",G).executeTakeFirst(),K=Number(Z?.count||0),W=Number(Y?.count||0),Q=K-W,F=W!==0?Q/W*100:K>0?100:0;return{current_month:K,previous_month:W,difference:Q,percentage_change:F}}var{randomUUIDv7:PZ}=globalThis.Bun;import{db as b7}from"@stacksjs/database";import{HttpError as p7}from"@stacksjs/error-handling";import{isUniqueViolation as SZ}from"@stacksjs/orm";async function m7($){try{let J=PZ();return await b7.insertInto("coupons").values({...$,uuid:J}).executeTakeFirst(),await b7.selectFrom("coupons").where("uuid","=",J).selectAll().executeTakeFirst()}catch(J){if(J instanceof p7)throw J;if(SZ(J))throw new p7(409,"A coupon with this code already exists");if(J instanceof Error)throw Error(`Failed to create coupon: ${J.message}`);throw J}}import{db as c7}from"@stacksjs/database";import{HttpError as l7}from"@stacksjs/error-handling";import{formatDate as u7,isUniqueViolation as RZ}from"@stacksjs/orm";async function n7($,J){if(!await N0($))return;try{return await c7.updateTable("coupons").set({...J,updated_at:u7(new Date)}).where("id","=",$).execute(),await N0($)}catch(X){if(X instanceof l7)throw X;if(RZ(X))throw new l7(409,"A coupon with this code already exists");if(X instanceof Error)throw Error(`Failed to update coupon: ${X.message}`);throw X}}async function i7($){let J=u7(new Date),G=await c7.unsafe(`UPDATE coupons
|
|
3
3
|
SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ?
|
|
4
4
|
WHERE id = ?
|
|
5
5
|
AND (max_uses IS NULL OR usage_count < max_uses)
|
|
6
6
|
AND is_active = 1
|
|
7
7
|
AND (start_date IS NULL OR start_date <= ?)
|
|
8
|
-
AND (end_date IS NULL OR end_date >= ?)`,[J,$,J,J]),X=typeof G?.execute==="function"?await G.execute():G;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0){let Q=await N0($);if(Q)return{ok:!0,coupon:Q};return{ok:!1,reason:"not-found"}}let Y=await N0($);if(!Y)return{ok:!1,reason:"not-found"};if(!Y.isActive)return{ok:!1,reason:"inactive"};let K=!Y.startDate||Y.startDate<=J,W=!Y.endDate||Y.endDate>=J;if(!K||!W)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var W1={};B(W1,{update:()=>JJ,store:()=>e7,fetchById:()=>A$,fetchAll:()=>r7,destroy:()=>o7,bulkDestroy:()=>d7});import{db as s7}from"@stacksjs/database";async function o7($){try{let J=await s7.deleteFrom("customers").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customer: ${J.message}`);throw J}}async function d7($){if(!$.length)return 0;try{let J=await s7.deleteFrom("customers").where("id","in",$).executeTakeFirst();return F(J)||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${J.message}`);throw J}}import{db as a7}from"@stacksjs/database";async function A$($){return await a7.selectFrom("customers").where("id","=",$).selectAll().executeTakeFirst()}async function r7(){return await a7.selectFrom("customers").selectAll().execute()}import{db as EZ}from"@stacksjs/database";import{HttpError as t7}from"@stacksjs/error-handling";import{isUniqueViolation as TZ}from"@stacksjs/orm";async function e7($){try{let J={...$,avatar:$.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await EZ.insertInto("customers").values(J).executeTakeFirst();if(!G)throw Error("Failed to create customer");let X=G.insertId||Number(G.numInsertedOrUpdatedRows);return await A$(Number(X))}catch(J){if(J instanceof t7)throw J;if(TZ(J))throw new t7(409,"A customer with this email already exists");if(J instanceof Error)throw Error(`Failed to create customer: ${J.message}`);throw J}}import{db as jZ}from"@stacksjs/database";import{HttpError as $J}from"@stacksjs/error-handling";import{formatDate as qZ,isUniqueViolation as kZ}from"@stacksjs/orm";async function JJ($,J){try{if(!$)throw Error("Customer ID is required for update");let G=await jZ.updateTable("customers").set({...J,updated_at:qZ(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof $J)throw G;if(kZ(G))throw new $J(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var H1={};B(H1,{updateStatus:()=>OJ,updatePrintCount:()=>AJ,update:()=>_J,storePrintDevicesExport:()=>VJ,store:()=>BJ,getPrinterStatusCounts:()=>NJ,fetchErrorsByDeviceId:()=>LJ,fetchById:()=>a,fetchAll:()=>U$,exportPrintDevices:()=>R$,downloadPrintDevices:()=>zJ,destroy:()=>XJ,countTotalPrints:()=>KJ,countPrintsByDeviceId:()=>WJ,countAll:()=>YJ,calculatePrinterHealth:()=>FJ,calculateErrorRate:()=>QJ,bulkStore:()=>MJ,bulkDestroy:()=>ZJ});import{db as GJ}from"@stacksjs/database";async function XJ($){try{let J=await GJ.deleteFrom("print_devices").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print device: ${J.message}`);throw J}}async function ZJ($){if(!$.length)return 0;try{let J=await GJ.deleteFrom("print_devices").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print devices: ${J.message}`);throw J}}import{createSpreadsheet as wZ}from"ts-spreadsheets";import{db as q}from"@stacksjs/database";async function a($){return await q.selectFrom("print_devices").where("id","=",$).selectAll().executeTakeFirst()}async function U$(){return await q.selectFrom("print_devices").selectAll().execute()}async function YJ(){let $=await q.selectFrom("print_devices").select(q.fn.count("id").as("count")).executeTakeFirst();return Number($?.count||0)}async function KJ(){let $=await q.selectFrom("print_devices").select(q.fn.sum("print_count").as("total")).executeTakeFirst();return Number($?.total||0)}async function WJ($){return(await q.selectFrom("print_devices").select("print_count").where("id","=",$).executeTakeFirst())?.print_count??0}async function QJ(){let $=await q.selectFrom("receipts").select([q.fn.count("id").as("total"),q.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!$?.total||$.total===0)return 0;return Number(($.failed_count??0)/$.total*100)}async function LJ($){return await q.selectFrom("receipts").where("print_device_id","=",$).where("status","=","failed").selectAll().execute()}async function FJ(){let $=await q.selectFrom("print_devices").select([q.fn.count("id").as("total"),q.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!$?.total||$.total===0)return 0;return Number(($.online_count??0)/$.total*100)}async function NJ(){return(await q.selectFrom("print_devices").select(["status",q.fn.count("id").as("count")]).groupBy("status").execute()).reduce((J,G)=>{return J[G.status]=Number(G.count||0),J},{})}function Q1($,J,G=J){let X=$;return X[String(J)]??X[G]}function fZ($){if($ instanceof Date)return $;if(typeof $==="number")return new Date($);if(typeof $==="string")return new Date(/^\d+$/.test($)?Number($):$);return new Date(Number.NaN)}function HJ($,J,G=J){let X=Q1($,J,G);if(typeof X==="number")return X;let Z=Number(X);return Number.isFinite(Z)?Z:0}function l0($,J,G=J){let X=Q1($,J,G);return X==null?"":String(X)}async function R$($="csv"){let J=await U$(),G=CZ(J);return wZ(G,{type:$})}function CZ($){let J=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=$.map((X)=>{return[HJ(X,"id"),l0(X,"name"),l0(X,"macAddress","mac_address"),l0(X,"location"),l0(X,"terminal"),l0(X,"status"),fZ(Q1(X,"lastPing","last_ping")).toLocaleString(),HJ(X,"printCount","print_count")]});return{headings:J,data:G}}async function zJ($="csv",J){let G=await R$($),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${$}`;return G.download(J||X)}async function VJ($="csv",J){let G=await R$($),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${$}`;G.store(J||X)}var{randomUUIDv7:xJ}=globalThis.Bun;import{db as L1}from"@stacksjs/database";async function BJ($){try{let J=xJ(),G={last_ping:0,print_count:0,...$,uuid:J};return await L1.insertInto("print_devices").values(G).executeTakeFirst(),await L1.selectFrom("print_devices").where("uuid","=",J).selectAll().executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print device: ${J.message}`);throw J}}async function MJ($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={last_ping:0,print_count:0,...G,uuid:xJ()};await L1.insertInto("print_devices").values(X).execute(),J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as F1}from"@stacksjs/database";import{formatDate as N1}from"@stacksjs/orm";async function _J($,J){if(!await a($))return;try{return await F1.updateTable("print_devices").set({...J,updated_at:N1(new Date)}).where("id","=",$).execute(),await a($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device: ${X.message}`);throw X}}async function OJ($,J){if(!await a($))throw Error(`Print device with ID ${$} not found`);try{return await F1.updateTable("print_devices").set({status:J,updated_at:N1(new Date)}).where("id","=",$).execute(),await a($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device status: ${X.message}`);throw X}}async function AJ($,J){if(!await a($))throw Error(`Print device with ID ${$} not found`);try{return await F1.updateTable("print_devices").set({print_count:J,updated_at:N1(new Date)}).where("id","=",$).execute(),await a($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print count: ${X.message}`);throw X}}var x1={};B(x1,{update:()=>kJ,unresolveGroup:()=>hJ,resolveGroup:()=>fJ,ignoreGroup:()=>CJ,fetchTimeline:()=>qJ,fetchStats:()=>jJ,fetchGrouped:()=>EJ,fetchById:()=>PJ,fetchByGroup:()=>TJ,fetchAll:()=>P$,destroyGroup:()=>SJ,destroy:()=>UJ,bulkUpdateStatus:()=>wJ,bulkDestroy:()=>RJ});import{db as z1}from"@stacksjs/database";import{log as V1}from"@stacksjs/logging";async function UJ($){try{return await z1.deleteFrom("errors").where("id","=",$).execute(),!0}catch(J){return V1.error("[commerce/errors] destroy failed",{id:$,error:J}),!1}}async function RJ($){try{return await z1.deleteFrom("errors").where("id","in",$).execute(),!0}catch(J){return V1.error("[commerce/errors] bulkDestroy failed",{count:$.length,error:J}),!1}}async function SJ($,J){try{return await z1.deleteFrom("errors").where("type","=",$).where("message","=",J).execute(),!0}catch(G){return V1.error("[commerce/errors] destroyGroup failed",{type:$,message:J,error:G}),!1}}import{db as S$}from"@stacksjs/database";async function PJ($){return await S$.selectFrom("errors").where("id","=",$).selectAll().executeTakeFirst()}async function P$(){return await S$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function EJ(){let $=await S$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),J=new Map;for(let X of $){let Z=`${X.type}:${X.message}`;if(!J.has(Z))J.set(Z,{errors:[],firstSeen:new Date(X.created_at),lastSeen:new Date(X.created_at)});let Y=J.get(Z);Y.errors.push(X);let K=new Date(X.created_at);if(K<Y.firstSeen)Y.firstSeen=K;if(K>Y.lastSeen)Y.lastSeen=K}let G=[];for(let[X,Z]of J){let Y=Z.errors[0];if(!Y)continue;let K=Z.errors.find((Q)=>Q.status!==null)?.status,W="unresolved";if(K===1)W="resolved";else if(K===2)W="ignored";G.push({id:Y.id,type:Y.type,message:Y.message,stack:Y.stack,status:W,count:Z.errors.length,first_seen:Z.firstSeen.toISOString(),last_seen:Z.lastSeen.toISOString(),error_ids:Z.errors.map((Q)=>Q.id)})}return G.sort((X,Z)=>new Date(Z.last_seen).getTime()-new Date(X.last_seen).getTime()),G}async function TJ($,J){return await S$.selectFrom("errors").where("type","=",$).where("message","=",J).selectAll().orderBy("created_at","desc").execute()}async function jJ(){let $=await P$(),J=new Date,G=new Date(J.getTime()-86400000),X=new Date(J.getTime()-172800000),Z=$.filter((W)=>new Date(W.created_at)>=G).length,Y=$.filter((W)=>{let Q=new Date(W.created_at);return Q>=X&&Q<G}).length,K=Y===0?Z>0?100:0:Math.round((Z-Y)/Y*100);return{total:$.length,unresolved:$.filter((W)=>W.status===null||W.status===0).length,resolved:$.filter((W)=>W.status===1).length,ignored:$.filter((W)=>W.status===2).length,last_24h:Z,trend:K}}async function qJ(){let $=await P$(),J=new Date,G=[];for(let X=23;X>=0;X--){let Z=new Date(J.getTime()-X*60*60*1000);Z.setMinutes(0,0,0);let Y=new Date(Z.getTime()+3600000),K=$.filter((W)=>{let Q=new Date(W.created_at);return Q>=Z&&Q<Y}).length;G.push({hour:Z.toISOString(),count:K})}return G}import{db as c0}from"@stacksjs/database";import{sql as u0}from"@stacksjs/database";import{log as n0}from"@stacksjs/logging";async function kJ($,J){try{return await c0.updateTable("errors").set({...J,updated_at:u0.raw("CURRENT_TIMESTAMP")}).where("id","=",$).execute(),!0}catch(G){return n0.error("[commerce/errors] update failed",{id:$,error:G}),!1}}async function wJ($,J){try{return await c0.updateTable("errors").set({status:J,updated_at:u0.raw("CURRENT_TIMESTAMP")}).where("id","in",$).execute(),!0}catch(G){return n0.error("[commerce/errors] bulkUpdateStatus failed",{count:$.length,status:J,error:G}),!1}}async function fJ($,J){try{return await c0.updateTable("errors").set({status:1,updated_at:u0.raw("CURRENT_TIMESTAMP")}).where("type","=",$).where("message","=",J).execute(),!0}catch(G){return n0.error("[commerce/errors] resolveGroup failed",{type:$,message:J,error:G}),!1}}async function CJ($,J){try{return await c0.updateTable("errors").set({status:2,updated_at:u0.raw("CURRENT_TIMESTAMP")}).where("type","=",$).where("message","=",J).execute(),!0}catch(G){return n0.error("[commerce/errors] ignoreGroup failed",{type:$,message:J,error:G}),!1}}async function hJ($,J){try{return await c0.updateTable("errors").set({status:0,updated_at:u0.raw("CURRENT_TIMESTAMP")}).where("type","=",$).where("message","=",J).execute(),!0}catch(G){return n0.error("[commerce/errors] unresolveGroup failed",{type:$,message:J,error:G}),!1}}var _1={};B(_1,{updateBalance:()=>rJ,update:()=>aJ,store:()=>iJ,fetchTotalValue:()=>pJ,fetchTotalCurrentBalance:()=>mJ,fetchStats:()=>DJ,fetchById:()=>H0,fetchByCode:()=>B1,fetchAll:()=>IJ,fetchActive:()=>gJ,destroy:()=>cJ,compareActiveGiftCards:()=>yJ,checkBalance:()=>vJ,calculateGiftCardValues:()=>bJ,bulkDestroy:()=>uJ});import{db as lJ}from"@stacksjs/database";import{formatDate as EW}from"@stacksjs/orm";import{db as S,sql as C}from"@stacksjs/database";import{formatDate as Z0,toTimestamp as U0}from"@stacksjs/orm";import{aggregateFunctions as hZ,db as IZ}from"@stacksjs/database";async function I($,J,G){let X=IZ.selectFrom($);if(G)X=G(X);X=X.select(Object.entries(J).map(([K,W])=>{let Q=W.column??"id",L=hZ[W.kind](Q);if(W.filter)L=L.filterWhere(W.filter.column,W.filter.op,W.filter.value);return L.as(K)}));let Z=await X.executeTakeFirst(),Y={};for(let K of Object.keys(J)){let W=Z?.[K];Y[K]=typeof W==="number"?W:Number(W??0)||0}return Y}async function IJ(){return await S.selectFrom("gift_cards").selectAll().execute()}async function H0($){return await S.selectFrom("gift_cards").where("id","=",$).selectAll().executeTakeFirst()}async function B1($){return await S.selectFrom("gift_cards").where("code","=",$).selectAll().executeTakeFirst()}async function gJ(){return await S.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function DJ(){let{count:$}=await I("gift_cards",{count:{kind:"count"}}),J=U0(new Date),G=await S.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(J)} OR expiry_date IS NULL)`).select(S.fn.count("id").as("count")).executeTakeFirst(),X=await S.selectFrom("gift_cards").select(["status",S.fn.count("id").as("count")]).groupBy("status").execute(),{count:Z}=await I("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:Y}=await I("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:K}=await I("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance > 0.75`)),W=new Date;W.setDate(W.getDate()+30);let Q=await S.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",U0(W)).where("expiry_date",">=",J).selectAll().limit(5).execute(),L=await S.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:$,active:Number(G?.count||0),by_status:X.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:Z,medium:Y,high:K},expiring_soon:Q,recently_used:L}}async function vJ($){let J=await B1($);if(!J)return{valid:!1,message:"Gift card not found"};if(!J.isActive||J.status!=="ACTIVE")return{valid:!1,balance:J.currentBalance,currency:J.currency,message:`Gift card is ${J.status.toLowerCase()}`};if(J.expiryDate){if(new Date(J.expiryDate)<new Date)return{valid:!1,balance:J.currentBalance,currency:J.currency,message:"Gift card has expired"}}return{valid:!0,balance:J.currentBalance,currency:J.currency}}async function yJ($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-$);let Y=await S.selectFrom("gift_cards").select(S.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(U0(J))} OR expiry_date IS NULL)`).where("created_at",">=",Z0(G)).where("created_at","<=",Z0(J)).executeTakeFirst(),K=await S.selectFrom("gift_cards").select(S.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(U0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",Z0(Z)).where("created_at","<=",Z0(X)).executeTakeFirst(),W=Number(Y?.count||0),Q=Number(K?.count||0),L=W-Q,N=Q!==0?L/Q*100:W>0?100:0;return{current_period:W,previous_period:Q,difference:L,percentage_change:N,days_range:$}}async function bJ($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-$);let Y=await S.selectFrom("gift_cards").select([S.fn.sum("initial_balance").as("total_initial"),S.fn.sum("current_balance").as("total_balance"),S.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(U0(J))} OR expiry_date IS NULL)`).where("created_at",">=",Z0(G)).where("created_at","<=",Z0(J)).executeTakeFirst(),K=await S.selectFrom("gift_cards").select([S.fn.sum("initial_balance").as("total_initial"),S.fn.sum("current_balance").as("total_balance"),S.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(U0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",Z0(Z)).where("created_at","<=",Z0(X)).executeTakeFirst(),W=Number(Y?.total_initial||0),Q=Number(Y?.total_balance||0),L=Number(Y?.card_count||0),N=Number(K?.total_initial||0),H=Number(K?.total_balance||0),z=Number(K?.card_count||0),x=W>0?(W-Q)/W*100:0,U=N>0?(N-H)/N*100:0,O=L>0?W/L:0,R=L>0?Q/L:0,c=W-N,L0=Q-H,F0=L-z,O0=N!==0?c/N*100:W>0?100:0,u=H!==0?L0/H*100:Q>0?100:0,LZ=z!==0?F0/z*100:L>0?100:0;return{current_period:{total_initial_value:W,total_remaining_balance:Q,utilization_rate:x,card_count:L,average_initial_value:O,average_remaining_balance:R},previous_period:{total_initial_value:N,total_remaining_balance:H,utilization_rate:U,card_count:z},comparison:{initial_value:{difference:c,percentage:Math.abs(O0),is_increase:c>=0},balance:{difference:L0,percentage:Math.abs(u),is_increase:L0>=0},card_count:{difference:F0,percentage:Math.abs(LZ),is_increase:F0>=0}},days_range:$}}async function pJ(){let{total_value:$}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:$}}async function mJ(){let{total_balance:$}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:$}}async function cJ($){let J=await lJ.deleteFrom("gift_cards").where("id","=",$).executeTakeFirst();return F(J)>0}async function uJ($){if(!$.length)return 0;let J=await lJ.deleteFrom("gift_cards").where("id","in",$).executeTakeFirst();return F(J)}var{randomUUIDv7:gZ}=globalThis.Bun;import{db as M1}from"@stacksjs/database";import{HttpError as nJ}from"@stacksjs/error-handling";import{isUniqueViolation as DZ}from"@stacksjs/orm";async function iJ($){let J=$,G={...$,current_balance:J.current_balance??J.initial_balance,status:$.status||"ACTIVE",is_active:J.is_active??!0,uuid:gZ()};try{let Z=await M1.insertInto("gift_cards").values(G).executeTakeFirst()??{},Y=Number(Z.insertId??0)||Number(Z.numInsertedOrUpdatedRows??0);if(Y)return await M1.selectFrom("gift_cards").where("id","=",Y).selectAll().executeTakeFirst();return}catch(X){if(X instanceof nJ)throw X;if(DZ(X))throw new nJ(409,"A gift card with this code already exists");if(X instanceof Error)throw Error(`Failed to create gift card: ${X.message}`);throw X}}import{db as oJ}from"@stacksjs/database";import{HttpError as sJ}from"@stacksjs/error-handling";import{formatDate as dJ,isUniqueViolation as vZ}from"@stacksjs/orm";async function aJ($,J){if(!await H0($))return;try{return await oJ.updateTable("gift_cards").set({...J,updated_at:dJ(new Date)}).where("id","=",$).execute(),await H0($)}catch(X){if(X instanceof sJ)throw X;if(vZ(X))throw new sJ(409,"A gift card with this code already exists");if(X instanceof Error)throw Error(`Failed to update gift card: ${X.message}`);throw X}}async function rJ($,J){if(!Number.isFinite(J))throw Error(`Gift card balance adjustment must be a finite number, got ${J}`);let G=dJ(new Date),X=await oJ.unsafe(`UPDATE gift_cards
|
|
8
|
+
AND (end_date IS NULL OR end_date >= ?)`,[J,$,J,J]),X=typeof G?.execute==="function"?await G.execute():G;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0){let Q=await N0($);if(Q)return{ok:!0,coupon:Q};return{ok:!1,reason:"not-found"}}let Y=await N0($);if(!Y)return{ok:!1,reason:"not-found"};if(!Y.isActive)return{ok:!1,reason:"inactive"};let K=!Y.startDate||Y.startDate<=J,W=!Y.endDate||Y.endDate>=J;if(!K||!W)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var W1={};B(W1,{update:()=>JJ,store:()=>e7,fetchById:()=>A$,fetchAll:()=>r7,destroy:()=>o7,bulkDestroy:()=>d7});import{db as s7}from"@stacksjs/database";async function o7($){try{let J=await s7.deleteFrom("customers").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customer: ${J.message}`);throw J}}async function d7($){if(!$.length)return 0;try{let J=await s7.deleteFrom("customers").where("id","in",$).executeTakeFirst();return L(J)||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${J.message}`);throw J}}import{db as a7}from"@stacksjs/database";async function A$($){return await a7.selectFrom("customers").where("id","=",$).selectAll().executeTakeFirst()}async function r7(){return await a7.selectFrom("customers").selectAll().execute()}import{db as TZ}from"@stacksjs/database";import{HttpError as t7}from"@stacksjs/error-handling";import{isUniqueViolation as EZ}from"@stacksjs/orm";async function e7($){try{let J={...$,avatar:$.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await TZ.insertInto("customers").values(J).executeTakeFirst();if(!G)throw Error("Failed to create customer");let X=G.insertId||Number(G.numInsertedOrUpdatedRows);return await A$(Number(X))}catch(J){if(J instanceof t7)throw J;if(EZ(J))throw new t7(409,"A customer with this email already exists");if(J instanceof Error)throw Error(`Failed to create customer: ${J.message}`);throw J}}import{db as jZ}from"@stacksjs/database";import{HttpError as $J}from"@stacksjs/error-handling";import{formatDate as qZ,isUniqueViolation as kZ}from"@stacksjs/orm";async function JJ($,J){try{if(!$)throw Error("Customer ID is required for update");let G=await jZ.updateTable("customers").set({...J,updated_at:qZ(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof $J)throw G;if(kZ(G))throw new $J(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var H1={};B(H1,{updateStatus:()=>OJ,updatePrintCount:()=>AJ,update:()=>_J,storePrintDevicesExport:()=>VJ,store:()=>BJ,getPrinterStatusCounts:()=>NJ,fetchErrorsByDeviceId:()=>FJ,fetchById:()=>a,fetchAll:()=>U$,exportPrintDevices:()=>P$,downloadPrintDevices:()=>zJ,destroy:()=>XJ,countTotalPrints:()=>KJ,countPrintsByDeviceId:()=>WJ,countAll:()=>YJ,calculatePrinterHealth:()=>LJ,calculateErrorRate:()=>QJ,bulkStore:()=>MJ,bulkDestroy:()=>ZJ});import{db as GJ}from"@stacksjs/database";async function XJ($){try{let J=await GJ.deleteFrom("print_devices").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print device: ${J.message}`);throw J}}async function ZJ($){if(!$.length)return 0;try{let J=await GJ.deleteFrom("print_devices").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print devices: ${J.message}`);throw J}}import{createSpreadsheet as wZ}from"ts-spreadsheets";import{db as q}from"@stacksjs/database";async function a($){return await q.selectFrom("print_devices").where("id","=",$).selectAll().executeTakeFirst()}async function U$(){return await q.selectFrom("print_devices").selectAll().execute()}async function YJ(){let $=await q.selectFrom("print_devices").select(q.fn.count("id").as("count")).executeTakeFirst();return Number($?.count||0)}async function KJ(){let $=await q.selectFrom("print_devices").select(q.fn.sum("print_count").as("total")).executeTakeFirst();return Number($?.total||0)}async function WJ($){return(await q.selectFrom("print_devices").select("print_count").where("id","=",$).executeTakeFirst())?.print_count??0}async function QJ(){let $=await q.selectFrom("receipts").select([q.fn.count("id").as("total"),q.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!$?.total||$.total===0)return 0;return Number(($.failed_count??0)/$.total*100)}async function FJ($){return await q.selectFrom("receipts").where("print_device_id","=",$).where("status","=","failed").selectAll().execute()}async function LJ(){let $=await q.selectFrom("print_devices").select([q.fn.count("id").as("total"),q.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!$?.total||$.total===0)return 0;return Number(($.online_count??0)/$.total*100)}async function NJ(){return(await q.selectFrom("print_devices").select(["status",q.fn.count("id").as("count")]).groupBy("status").execute()).reduce((J,G)=>{return J[G.status]=Number(G.count||0),J},{})}function Q1($,J,G=J){let X=$;return X[String(J)]??X[G]}function fZ($){if($ instanceof Date)return $;if(typeof $==="number")return new Date($);if(typeof $==="string")return new Date(/^\d+$/.test($)?Number($):$);return new Date(Number.NaN)}function HJ($,J,G=J){let X=Q1($,J,G);if(typeof X==="number")return X;let Z=Number(X);return Number.isFinite(Z)?Z:0}function l0($,J,G=J){let X=Q1($,J,G);return X==null?"":String(X)}async function P$($="csv"){let J=await U$(),G=CZ(J);return wZ(G,{type:$})}function CZ($){let J=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=$.map((X)=>{return[HJ(X,"id"),l0(X,"name"),l0(X,"macAddress","mac_address"),l0(X,"location"),l0(X,"terminal"),l0(X,"status"),fZ(Q1(X,"lastPing","last_ping")).toLocaleString(),HJ(X,"printCount","print_count")]});return{headings:J,data:G}}async function zJ($="csv",J){let G=await P$($),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${$}`;return G.download(J||X)}async function VJ($="csv",J){let G=await P$($),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${$}`;G.store(J||X)}var{randomUUIDv7:xJ}=globalThis.Bun;import{db as F1}from"@stacksjs/database";async function BJ($){try{let J=xJ(),G={last_ping:0,print_count:0,...$,uuid:J};return await F1.insertInto("print_devices").values(G).executeTakeFirst(),await F1.selectFrom("print_devices").where("uuid","=",J).selectAll().executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print device: ${J.message}`);throw J}}async function MJ($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={last_ping:0,print_count:0,...G,uuid:xJ()};await F1.insertInto("print_devices").values(X).execute(),J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as L1}from"@stacksjs/database";import{formatDate as N1}from"@stacksjs/orm";async function _J($,J){if(!await a($))return;try{return await L1.updateTable("print_devices").set({...J,updated_at:N1(new Date)}).where("id","=",$).execute(),await a($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device: ${X.message}`);throw X}}async function OJ($,J){if(!await a($))throw Error(`Print device with ID ${$} not found`);try{return await L1.updateTable("print_devices").set({status:J,updated_at:N1(new Date)}).where("id","=",$).execute(),await a($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device status: ${X.message}`);throw X}}async function AJ($,J){if(!await a($))throw Error(`Print device with ID ${$} not found`);try{return await L1.updateTable("print_devices").set({print_count:J,updated_at:N1(new Date)}).where("id","=",$).execute(),await a($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print count: ${X.message}`);throw X}}var x1={};B(x1,{update:()=>kJ,unresolveGroup:()=>hJ,resolveGroup:()=>fJ,ignoreGroup:()=>CJ,fetchTimeline:()=>qJ,fetchStats:()=>jJ,fetchGrouped:()=>TJ,fetchById:()=>RJ,fetchByGroup:()=>EJ,fetchAll:()=>R$,destroyGroup:()=>SJ,destroy:()=>UJ,bulkUpdateStatus:()=>wJ,bulkDestroy:()=>PJ});import{db as z1}from"@stacksjs/database";import{log as V1}from"@stacksjs/logging";async function UJ($){try{return await z1.deleteFrom("errors").where("id","=",$).execute(),!0}catch(J){return V1.error("[commerce/errors] destroy failed",{id:$,error:J}),!1}}async function PJ($){try{return await z1.deleteFrom("errors").where("id","in",$).execute(),!0}catch(J){return V1.error("[commerce/errors] bulkDestroy failed",{count:$.length,error:J}),!1}}async function SJ($,J){try{return await z1.deleteFrom("errors").where("type","=",$).where("message","=",J).execute(),!0}catch(G){return V1.error("[commerce/errors] destroyGroup failed",{type:$,message:J,error:G}),!1}}import{db as S$}from"@stacksjs/database";async function RJ($){return await S$.selectFrom("errors").where("id","=",$).selectAll().executeTakeFirst()}async function R$(){return await S$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function TJ(){let $=await S$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),J=new Map;for(let X of $){let Z=`${X.type}:${X.message}`;if(!J.has(Z))J.set(Z,{errors:[],firstSeen:new Date(X.created_at),lastSeen:new Date(X.created_at)});let Y=J.get(Z);Y.errors.push(X);let K=new Date(X.created_at);if(K<Y.firstSeen)Y.firstSeen=K;if(K>Y.lastSeen)Y.lastSeen=K}let G=[];for(let[X,Z]of J){let Y=Z.errors[0];if(!Y)continue;let K=Z.errors.find((Q)=>Q.status!==null)?.status,W="unresolved";if(K===1)W="resolved";else if(K===2)W="ignored";G.push({id:Y.id,type:Y.type,message:Y.message,stack:Y.stack,status:W,count:Z.errors.length,first_seen:Z.firstSeen.toISOString(),last_seen:Z.lastSeen.toISOString(),error_ids:Z.errors.map((Q)=>Q.id)})}return G.sort((X,Z)=>new Date(Z.last_seen).getTime()-new Date(X.last_seen).getTime()),G}async function EJ($,J){return await S$.selectFrom("errors").where("type","=",$).where("message","=",J).selectAll().orderBy("created_at","desc").execute()}async function jJ(){let $=await R$(),J=new Date,G=new Date(J.getTime()-86400000),X=new Date(J.getTime()-172800000),Z=$.filter((W)=>new Date(W.created_at)>=G).length,Y=$.filter((W)=>{let Q=new Date(W.created_at);return Q>=X&&Q<G}).length,K=Y===0?Z>0?100:0:Math.round((Z-Y)/Y*100);return{total:$.length,unresolved:$.filter((W)=>W.status===null||W.status===0).length,resolved:$.filter((W)=>W.status===1).length,ignored:$.filter((W)=>W.status===2).length,last_24h:Z,trend:K}}async function qJ(){let $=await R$(),J=new Date,G=[];for(let X=23;X>=0;X--){let Z=new Date(J.getTime()-X*60*60*1000);Z.setMinutes(0,0,0);let Y=new Date(Z.getTime()+3600000),K=$.filter((W)=>{let Q=new Date(W.created_at);return Q>=Z&&Q<Y}).length;G.push({hour:Z.toISOString(),count:K})}return G}import{db as c0}from"@stacksjs/database";import{sql as u0}from"@stacksjs/database";import{log as n0}from"@stacksjs/logging";async function kJ($,J){try{return await c0.updateTable("errors").set({...J,updated_at:u0.raw("CURRENT_TIMESTAMP")}).where("id","=",$).execute(),!0}catch(G){return n0.error("[commerce/errors] update failed",{id:$,error:G}),!1}}async function wJ($,J){try{return await c0.updateTable("errors").set({status:J,updated_at:u0.raw("CURRENT_TIMESTAMP")}).where("id","in",$).execute(),!0}catch(G){return n0.error("[commerce/errors] bulkUpdateStatus failed",{count:$.length,status:J,error:G}),!1}}async function fJ($,J){try{return await c0.updateTable("errors").set({status:1,updated_at:u0.raw("CURRENT_TIMESTAMP")}).where("type","=",$).where("message","=",J).execute(),!0}catch(G){return n0.error("[commerce/errors] resolveGroup failed",{type:$,message:J,error:G}),!1}}async function CJ($,J){try{return await c0.updateTable("errors").set({status:2,updated_at:u0.raw("CURRENT_TIMESTAMP")}).where("type","=",$).where("message","=",J).execute(),!0}catch(G){return n0.error("[commerce/errors] ignoreGroup failed",{type:$,message:J,error:G}),!1}}async function hJ($,J){try{return await c0.updateTable("errors").set({status:0,updated_at:u0.raw("CURRENT_TIMESTAMP")}).where("type","=",$).where("message","=",J).execute(),!0}catch(G){return n0.error("[commerce/errors] unresolveGroup failed",{type:$,message:J,error:G}),!1}}var _1={};B(_1,{updateBalance:()=>rJ,update:()=>aJ,store:()=>iJ,fetchTotalValue:()=>pJ,fetchTotalCurrentBalance:()=>mJ,fetchStats:()=>DJ,fetchById:()=>H0,fetchByCode:()=>B1,fetchAll:()=>IJ,fetchActive:()=>gJ,destroy:()=>cJ,compareActiveGiftCards:()=>yJ,checkBalance:()=>vJ,calculateGiftCardValues:()=>bJ,bulkDestroy:()=>uJ});import{db as lJ}from"@stacksjs/database";import{formatDate as EW}from"@stacksjs/orm";import{db as S,sql as C}from"@stacksjs/database";import{formatDate as Z0,toTimestamp as U0}from"@stacksjs/orm";import{aggregateFunctions as hZ,db as IZ}from"@stacksjs/database";async function I($,J,G){let X=IZ.selectFrom($);if(G)X=G(X);X=X.select(Object.entries(J).map(([K,W])=>{let Q=W.column??"id",F=hZ[W.kind](Q);if(W.filter)F=F.filterWhere(W.filter.column,W.filter.op,W.filter.value);return F.as(K)}));let Z=await X.executeTakeFirst(),Y={};for(let K of Object.keys(J)){let W=Z?.[K];Y[K]=typeof W==="number"?W:Number(W??0)||0}return Y}async function IJ(){return await S.selectFrom("gift_cards").selectAll().execute()}async function H0($){return await S.selectFrom("gift_cards").where("id","=",$).selectAll().executeTakeFirst()}async function B1($){return await S.selectFrom("gift_cards").where("code","=",$).selectAll().executeTakeFirst()}async function gJ(){return await S.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function DJ(){let{count:$}=await I("gift_cards",{count:{kind:"count"}}),J=U0(new Date),G=await S.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(J)} OR expiry_date IS NULL)`).select(S.fn.count("id").as("count")).executeTakeFirst(),X=await S.selectFrom("gift_cards").select(["status",S.fn.count("id").as("count")]).groupBy("status").execute(),{count:Z}=await I("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:Y}=await I("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:K}=await I("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance > 0.75`)),W=new Date;W.setDate(W.getDate()+30);let Q=await S.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",U0(W)).where("expiry_date",">=",J).selectAll().limit(5).execute(),F=await S.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:$,active:Number(G?.count||0),by_status:X.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:Z,medium:Y,high:K},expiring_soon:Q,recently_used:F}}async function vJ($){let J=await B1($);if(!J)return{valid:!1,message:"Gift card not found"};if(!J.isActive||J.status!=="ACTIVE")return{valid:!1,balance:J.currentBalance,currency:J.currency,message:`Gift card is ${J.status.toLowerCase()}`};if(J.expiryDate){if(new Date(J.expiryDate)<new Date)return{valid:!1,balance:J.currentBalance,currency:J.currency,message:"Gift card has expired"}}return{valid:!0,balance:J.currentBalance,currency:J.currency}}async function yJ($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-$);let Y=await S.selectFrom("gift_cards").select(S.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(U0(J))} OR expiry_date IS NULL)`).where("created_at",">=",Z0(G)).where("created_at","<=",Z0(J)).executeTakeFirst(),K=await S.selectFrom("gift_cards").select(S.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(U0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",Z0(Z)).where("created_at","<=",Z0(X)).executeTakeFirst(),W=Number(Y?.count||0),Q=Number(K?.count||0),F=W-Q,N=Q!==0?F/Q*100:W>0?100:0;return{current_period:W,previous_period:Q,difference:F,percentage_change:N,days_range:$}}async function bJ($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-$);let Y=await S.selectFrom("gift_cards").select([S.fn.sum("initial_balance").as("total_initial"),S.fn.sum("current_balance").as("total_balance"),S.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(U0(J))} OR expiry_date IS NULL)`).where("created_at",">=",Z0(G)).where("created_at","<=",Z0(J)).executeTakeFirst(),K=await S.selectFrom("gift_cards").select([S.fn.sum("initial_balance").as("total_initial"),S.fn.sum("current_balance").as("total_balance"),S.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(U0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",Z0(Z)).where("created_at","<=",Z0(X)).executeTakeFirst(),W=Number(Y?.total_initial||0),Q=Number(Y?.total_balance||0),F=Number(Y?.card_count||0),N=Number(K?.total_initial||0),H=Number(K?.total_balance||0),z=Number(K?.card_count||0),x=W>0?(W-Q)/W*100:0,U=N>0?(N-H)/N*100:0,O=F>0?W/F:0,P=F>0?Q/F:0,c=W-N,F0=Q-H,L0=F-z,O0=N!==0?c/N*100:W>0?100:0,u=H!==0?F0/H*100:Q>0?100:0,FZ=z!==0?L0/z*100:F>0?100:0;return{current_period:{total_initial_value:W,total_remaining_balance:Q,utilization_rate:x,card_count:F,average_initial_value:O,average_remaining_balance:P},previous_period:{total_initial_value:N,total_remaining_balance:H,utilization_rate:U,card_count:z},comparison:{initial_value:{difference:c,percentage:Math.abs(O0),is_increase:c>=0},balance:{difference:F0,percentage:Math.abs(u),is_increase:F0>=0},card_count:{difference:L0,percentage:Math.abs(FZ),is_increase:L0>=0}},days_range:$}}async function pJ(){let{total_value:$}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:$}}async function mJ(){let{total_balance:$}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:$}}async function cJ($){let J=await lJ.deleteFrom("gift_cards").where("id","=",$).executeTakeFirst();return L(J)>0}async function uJ($){if(!$.length)return 0;let J=await lJ.deleteFrom("gift_cards").where("id","in",$).executeTakeFirst();return L(J)}var{randomUUIDv7:gZ}=globalThis.Bun;import{db as M1}from"@stacksjs/database";import{HttpError as nJ}from"@stacksjs/error-handling";import{isUniqueViolation as DZ}from"@stacksjs/orm";async function iJ($){let J=$,G={...$,current_balance:J.current_balance??J.initial_balance,status:$.status||"ACTIVE",is_active:J.is_active??!0,uuid:gZ()};try{let Z=await M1.insertInto("gift_cards").values(G).executeTakeFirst()??{},Y=Number(Z.insertId??0)||Number(Z.numInsertedOrUpdatedRows??0);if(Y)return await M1.selectFrom("gift_cards").where("id","=",Y).selectAll().executeTakeFirst();return}catch(X){if(X instanceof nJ)throw X;if(DZ(X))throw new nJ(409,"A gift card with this code already exists");if(X instanceof Error)throw Error(`Failed to create gift card: ${X.message}`);throw X}}import{db as oJ}from"@stacksjs/database";import{HttpError as sJ}from"@stacksjs/error-handling";import{formatDate as dJ,isUniqueViolation as vZ}from"@stacksjs/orm";async function aJ($,J){if(!await H0($))return;try{return await oJ.updateTable("gift_cards").set({...J,updated_at:dJ(new Date)}).where("id","=",$).execute(),await H0($)}catch(X){if(X instanceof sJ)throw X;if(vZ(X))throw new sJ(409,"A gift card with this code already exists");if(X instanceof Error)throw Error(`Failed to update gift card: ${X.message}`);throw X}}async function rJ($,J){if(!Number.isFinite(J))throw Error(`Gift card balance adjustment must be a finite number, got ${J}`);let G=dJ(new Date),X=await oJ.unsafe(`UPDATE gift_cards
|
|
9
9
|
SET current_balance = current_balance + ?,
|
|
10
10
|
last_used_date = ?,
|
|
11
11
|
status = CASE WHEN current_balance + ? = 0 THEN 'USED' ELSE 'ACTIVE' END,
|
|
@@ -13,15 +13,15 @@ var FZ=Object.defineProperty;var NZ=($)=>$;function HZ($,J){this[$]=NZ.bind(null
|
|
|
13
13
|
WHERE id = ?
|
|
14
14
|
AND is_active = 1
|
|
15
15
|
AND status = 'ACTIVE'
|
|
16
|
-
AND current_balance + ? >= 0`,[J,G,J,G,$,J]),Z=typeof X?.execute==="function"?await X.execute():X;if(Number(Z?.changes??Z?.numUpdatedRows??Z?.affectedRows??0)>0)return await H0($);let K=await H0($);if(!K)throw Error(`Gift card with ID ${$} not found`);if(!K.is_active||K.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var j1={};B(j1,{validateQuantityBounds:()=>
|
|
16
|
+
AND current_balance + ? >= 0`,[J,G,J,G,$,J]),Z=typeof X?.execute==="function"?await X.execute():X;if(Number(Z?.changes??Z?.numUpdatedRows??Z?.affectedRows??0)>0)return await H0($);let K=await H0($);if(!K)throw Error(`Gift card with ID ${$} not found`);if(!K.is_active||K.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var j1={};B(j1,{validateQuantityBounds:()=>E1,validateCouponStacking:()=>k6,validateCartQuantities:()=>w6,updateStatus:()=>S6,updateDeliveryInfo:()=>R6,update:()=>P6,storeOrdersExport:()=>Z6,store:()=>z6,softDelete:()=>eJ,registerCommerceWebhookHandlers:()=>E6,recomputeOrderTotals:()=>q6,placeOrder:()=>U6,handlePaymentIntentSucceeded:()=>S1,handlePaymentIntentFailed:()=>R1,handleChargeRefunded:()=>T1,findOrderByIdempotencyKey:()=>w$,fetchStats:()=>W6,fetchDailyOrderTrends:()=>L6,fetchById:()=>r,fetchAll:()=>K6,exportOrders:()=>E$,emitOrderShipped:()=>j$,emitOrderRefunded:()=>S0,emitOrderPaid:()=>Y0,emitOrderDelivered:()=>q$,emitOrderCreated:()=>s0,emitOrderCancelled:()=>P0,emitForStatus:()=>o0,downloadOrders:()=>X6,destroy:()=>tJ,compareOrdersByPeriod:()=>Q6,cleanupAbandonedCarts:()=>f6,canTransition:()=>i0,calculateOrderMetrics:()=>F6,bulkSoftDelete:()=>J6,bulkDestroy:()=>$6});import{db as T$}from"@stacksjs/database";async function tJ($){try{let J=await T$.deleteFrom("orders").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function eJ($){try{let J=await T$.updateTable("orders").set({status:"CANCELED"}).where("id","=",$).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete order: ${J.message}`);throw J}}async function $6($){if(!$.length)return 0;try{let J=await T$.deleteFrom("orders").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}async function J6($){if(!$.length)return 0;try{let J=await T$.updateTable("orders").set({status:"CANCELED"}).where("id","in",$).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete orders: ${J.message}`);throw J}}import{db as G6}from"@stacksjs/database";import{createSpreadsheet as yZ}from"ts-spreadsheets";async function E$($="csv"){let J=await bZ(),G=pZ(J);return yZ(G,{type:$})}async function bZ(){let $=await G6.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),J=$.map((Y)=>Y.id);if(J.length===0)return[];let X=(await G6.selectFrom("order_items").where("order_items.order_id","in",J).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((Y,K)=>{if(!K.order_id)return Y;if(!Y[K.order_id])Y[K.order_id]={totalItems:0,totalPrice:0};return Y[K.order_id].totalItems+=K.quantity,Y[K.order_id].totalPrice+=K.price*K.quantity,Y},{});return $.map((Y)=>{let K=X[Y.id]||{totalItems:0,totalPrice:0};return{...Y,totalItems:K.totalItems,totalPrice:K.totalPrice}})}function pZ($){let J=["Order ID","Customer","Date","Total","Status","Items"],G=$.map((X)=>{let Z=X.order_items?.map((Y)=>`${Y.product?.name} (Qty: ${Y.quantity}, Price: $${Y.price})`).join(" | ")||"No Items";return[X.id,X.customer?.name||"N/A",X.created_at,X.total_amount,X.status,Z]});return{headings:J,data:G}}async function X6($="csv",J){let G=await E$($),X=`orders_export_${new Date().toISOString().split("T")[0]}.${$}`;return G.download(J||X)}async function Z6($="csv",J){let G=await E$($),X=`orders_export_${new Date().toISOString().split("T")[0]}.${$}`;G.store(J||X)}import{asRows as Y6,db as _}from"@stacksjs/database";async function K6($){let J=_.selectFrom("orders").selectAll().orderBy("created_at","desc");if($)J=J.limit($);let G=Y6(await J.execute());return await Promise.all(G.map(async(X)=>{let Z=await _.selectFrom("order_items").where("order_id","=",X.id).selectAll().execute();return{...X,items:Z}}))}async function r($){return await _.selectFrom("orders").where("id","=",$).selectAll().executeTakeFirst()}async function W6(){let $=await _.selectFrom("orders").select(_.fn.count("id").as("count")).executeTakeFirst(),J=await _.selectFrom("orders").select(["status",_.fn.count("id").as("count")]).groupBy("status").execute(),G=await _.selectFrom("orders").select(["order_type",_.fn.count("id").as("count")]).groupBy("order_type").execute(),X=Y6(await _.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute()),Z=await Promise.all(X.map(async(K)=>{let W=await _.selectFrom("order_items").where("order_id","=",K.id).selectAll().execute();return{...K,items:W}})),Y=await _.selectFrom("orders").select(_.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number($?.count||0),by_status:J,by_type:G,recent:Z,revenue:Number(Y?.total||0)}}async function Q6($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-$);let Y=await _.selectFrom("orders").select(_.fn.count("id").as("count")).where("created_at",">=",G.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),K=await _.selectFrom("orders").select(_.fn.count("id").as("count")).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),W=Number(Y?.count||0),Q=Number(K?.count||0),F=W-Q,N=Q!==0?F/Q*100:W>0?100:0;return{current_period:W,previous_period:Q,difference:F,percentage_change:N,days_range:$}}async function F6($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-$);let Y=await _.selectFrom("orders").select([_.fn.count("id").as("total_orders"),_.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",G.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),K=await _.selectFrom("orders").select([_.fn.count("id").as("total_orders"),_.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),W=await _.selectFrom("orders").select(["status",_.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",J.toISOString()).groupBy("status").execute(),Q=await _.selectFrom("orders").select(["order_type",_.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",J.toISOString()).groupBy("order_type").execute(),F=Number(Y?.total_orders||0),N=Number(Y?.total_revenue||0),H=F>0?N/F:0,z=Number(K?.total_orders||0),x=Number(K?.total_revenue||0),U=z>0?x/z:0,O=F-z,P=N-x,c=H-U,F0=z!==0?O/z*100:F>0?100:0,L0=x!==0?P/x*100:N>0?100:0,O0=U!==0?c/U*100:H>0?100:0;return{current_period:{total_orders:F,total_revenue:N,average_order_value:H,orders_by_status:W.map((u)=>({status:u.status,count:Number(u.count)})),orders_by_type:Q.map((u)=>({order_type:u.order_type,count:Number(u.count)}))},previous_period:{total_orders:z,total_revenue:x,average_order_value:U},comparison:{orders:{difference:O,percentage:Math.abs(F0),is_increase:O>=0},revenue:{difference:P,percentage:Math.abs(L0),is_increase:P>=0},average_order_value:{difference:c,percentage:Math.abs(O0),is_increase:c>=0}},days_range:$}}async function L6($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=await _.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",G.toISOString()).where("created_at","<=",J.toISOString()).orderBy("created_at","asc").execute(),Z=new Map;for(let Y of X){let K=(Y.created_at||"").split("T")[0]||"unknown",W=Z.get(K)||{order_count:0,revenue:0};W.order_count++,W.revenue+=Number(Y.total_amount||0),Z.set(K,W)}return Array.from(Z.entries()).map(([Y,K])=>({date:Y,order_count:K.order_count,revenue:K.revenue}))}var{randomUUIDv7:mZ}=globalThis.Bun;import{db as N6}from"@stacksjs/database";import{formatDate as H6}from"@stacksjs/orm";async function z6($){let J={...$,status:$.status||"PENDING",uuid:mZ(),created_at:H6(new Date),updated_at:H6(new Date)};try{let G=await N6.insertInto("orders").values(J).executeTakeFirst(),X=Number(G?.insertId)||Number(G?.numInsertedOrUpdatedRows);if(X)return await N6.selectFrom("orders").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof Error)throw Error(`Failed to create order: ${G.message}`);throw G}}R0();var{randomUUIDv7:M6}=globalThis.Bun;import{db as k$}from"@stacksjs/database";import{formatDate as iZ,isUniqueViolation as _6}from"@stacksjs/orm";import{sqlHelpers as cZ}from"@stacksjs/database";import{env as uZ}from"@stacksjs/env";function nZ($,J,G,X){let Z=cZ($).param;return{query:`UPDATE products
|
|
17
17
|
SET inventory_count = inventory_count + ${Z(1)},
|
|
18
18
|
updated_at = ${Z(2)}
|
|
19
19
|
WHERE id = ${Z(3)}
|
|
20
|
-
AND inventory_count + ${Z(4)} >= 0`,parameters:[G,X,J,G]}}async function B6($,J,G,X){let Z=nZ(uZ.DB_CONNECTION||"sqlite",J,G,X),Y=await $.unsafe(Z.query,Z.parameters),K=typeof Y?.execute==="function"?await Y.execute():Y;return F(K)}var O6=!1;function A6($){let J=$,G=J?.message??"";return J?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function w$($){try{let J=await k$.selectFrom("order_idempotency").where("idempotency_key","=",$).selectAll().executeTakeFirst();if(!J)return null;return await k$.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}catch(J){if(A6(J)){if(!O6)O6=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw J}}async function U6($){if($.idempotencyKey){let J=await w$($.idempotencyKey);if(J)return{ok:!0,order:J}}try{let J=await k$.transaction(async(G)=>{let X=iZ(new Date),Z=M6(),Y={...$.order,status:$.order.status||"PENDING",uuid:Z,created_at:X,updated_at:X};await G.insertInto("orders").values(Y).executeTakeFirst();let K=await G.selectFrom("orders").where("uuid","=",Z).selectAll().executeTakeFirst(),W=Number(K?.id);if(!Number.isSafeInteger(W)||W<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let Q;if($.items&&$.items.length>0){let H=$.items.map((z)=>{if(!Number.isInteger(z.productId)||z.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(z.quantity)||z.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(z.price)||z.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:W,product_id:z.productId,quantity:z.quantity,price:z.price,special_instructions:z.specialInstructions||null,created_at:X,updated_at:X}});await G.insertInto("order_items").values(H).execute(),Q=await G.selectFrom("order_items").where("order_id","=",W).selectAll().execute()}let L;if($.payment)try{let H=M6();if(await G.insertInto("payments").values({...$.payment,order_id:W,uuid:H,created_at:X,updated_at:X}).executeTakeFirst(),L=await G.selectFrom("payments").where("uuid","=",H).selectAll().executeTakeFirst(),!L)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(H){if(_6(H))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(H,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if($.inventory&&$.inventory.length>0)for(let H=0;H<$.inventory.length;H++){let{id:z,delta:x}=$.inventory[H];if(!Number.isFinite(x)||x===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await B6(G,z,x,X))throw Object.assign(Error(`inventory adjust failed for product ${z}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if($.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:$.idempotencyKey,order_id:W,created_at:X}).execute()}catch(H){if(_6(H))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!A6(H))throw H}let N=await G.selectFrom("orders").where("id","=",W).selectAll().executeTakeFirst();if(!N)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:N,items:Q,payment:L}});if(s0(J.order),J.payment)Y0(J.order,J.payment);return{ok:!0,order:J.order,items:J.items,payment:J.payment}}catch(J){if(J?.__placeFail){if(J.reason==="duplicate-idempotency-key"&&$.idempotencyKey){let G=await w$($.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:J.reason,failedAt:J.failedAt,error:J}}throw J}}P0();import{db as O1}from"@stacksjs/database";import{formatDate as A1}from"@stacksjs/orm";P0();async function R6($,J){if(!await r($))return;try{return await O1.updateTable("orders").set({...J,updated_at:A1(new Date)}).where("id","=",$).execute(),await r($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order: ${X.message}`);throw X}}async function S6($,J){let G=await r($);if(!G)throw Error(`Order with ID ${$} not found`);let X=G.status??"PENDING";if(!i0(X,J))throw Error(`[commerce/orders] illegal status transition ${X} \u2192 ${J}`);try{await O1.updateTable("orders").set({status:J,updated_at:A1(new Date)}).where("id","=",$).execute();let Z=await r($);if(Z)o0(J,Z);return Z}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update order status: ${Z.message}`);throw Z}}async function P6($,J,G){let X=await r($);if(!X)throw Error(`Order with ID ${$} not found`);let Z={updated_at:A1(new Date)};if(J!==void 0)Z.delivery_address=J;if(G!==void 0)Z.estimated_delivery_time=G;if(Object.keys(Z).length===1)return X;try{return await O1.updateTable("orders").set(Z).where("id","=",$).execute(),await r($)}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery information: ${Y.message}`);throw Y}}P0();import{db as E0}from"@stacksjs/database";import{formatDate as f$}from"@stacksjs/orm";async function U1($){let J=await E0.selectFrom("payments").where("transaction_id","=",$).selectAll().executeTakeFirst();if(!J)return null;return await E0.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}var E6=!1;function sZ($){let J=$,G=J?.message??"";return J?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function R1($,J){try{return await J.insertInto("stripe_webhook_events").values({event_id:$,processed_at:f$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(sZ(G)){if(!E6)E6=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw G}}async function S1($){let G=$.data.object?.id;if(!G)return;await E0.transaction(async(Z)=>{if(!await R1($.id,Z))return;let K=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!K)return;let W=f$(new Date);await Z.updateTable("payments").set({status:"succeeded",updated_at:W}).where("id","=",K.id).execute();let Q=await Z.selectFrom("orders").where("id","=",K.order_id).selectAll().executeTakeFirst();if(Q&&Q.status==="PENDING")await Z.updateTable("orders").set({status:"PROCESSING",updated_at:W}).where("id","=",Q.id).execute()});let X=await U1(G);if(X)await Y0(X)}async function P1($){let J=$.data.object,G=J?.id;if(!G)return;let Z=J?.last_payment_error?.message??"payment failed";await E0.transaction(async(K)=>{if(!await R1($.id,K))return;let Q=await K.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Q)return;let L=f$(new Date);await K.updateTable("payments").set({status:"failed",failure_reason:Z,updated_at:L}).where("id","=",Q.id).execute();let N=await K.selectFrom("orders").where("id","=",Q.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await K.updateTable("orders").set({status:"CANCELLED",updated_at:L}).where("id","=",N.id).execute()});let Y=await U1(G);if(Y)await R0(Y,Z)}async function E1($){let J=$.data.object,G=J?.payment_intent;if(!G)return;let X=J?.amount_refunded??0;await E0.transaction(async(Y)=>{if(!await R1($.id,Y))return;let W=await Y.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!W)return;let Q=f$(new Date);await Y.updateTable("payments").set({status:"refunded",refund_amount:X,updated_at:Q}).where("id","=",W.id).execute();let L=await Y.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(L&&L.status!=="REFUNDED")await Y.updateTable("orders").set({status:"REFUNDED",updated_at:Q}).where("id","=",L.id).execute()});let Z=await U1(G);if(Z)await S0(Z,X)}async function T6(){let $=await import("@stacksjs/payments").catch(()=>null);if(!$)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:J,onCharge:G}=$;if(typeof J!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return J({succeeded:S1,failed:P1}),G({refunded:E1}),()=>{}}import{db as j6}from"@stacksjs/database";async function oZ($){if($.length===0)return new Map;let J=await j6.selectFrom("products").where("id","in",$).select(["id","price"]).execute(),G=new Map;for(let X of J){let Z=Number(X.price);if(Number.isFinite(Z))G.set(X.id,Math.round(Z))}return G}async function dZ($){try{let J=await j6.selectFrom("tax_rates").where("id","=",$).select(["rate"]).executeTakeFirst(),G=Number(J?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function q6($){let J=$.items.map((U)=>U.productId),G=await oZ(J),X=$.taxRateId!=null?await dZ($.taxRateId):0,Z=0,Y=[];for(let U of $.items){let O=U.unitPriceCents??G.get(U.productId)??0,R=Math.round(O*U.quantity);Z+=R,Y.push({productId:U.productId,quantity:U.quantity,unitPriceCents:O,lineCents:R})}let K=Math.max(0,$.discountCents??0),W=Math.max(0,Z-K),Q=Math.round(W*X),L=Math.max(0,$.shippingCents??0),N=Z-K+Q+L,H=$.maxDriftCents??5,z=!1,x=0;if($.clientTotalCents!=null)x=Math.abs(N-$.clientTotalCents),z=x>H;return{subtotalCents:Z,discountCents:K,taxCents:Q,shippingCents:L,totalCents:N,resolvedItems:Y,priceChanged:z,diffCents:x}}import{db as C$}from"@stacksjs/database";function k6($,J={}){let G=$.length;if(G<=1)return{ok:!0,count:G};if(!J.allowMultiple)return{ok:!1,count:G,reason:"multiple-not-allowed"};let X=J.maxStacked??Number.POSITIVE_INFINITY;if(G>X)return{ok:!1,count:G,reason:"exceeds-max-stacked"};return{ok:!0,count:G}}async function T1($,J){if(!Number.isFinite(J)||J<=0)return{ok:!1,productId:$,quantity:J,reason:"non-positive"};let G;try{G=await C$.selectFrom("products").where("id","=",$).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:$,quantity:J}}if(!G)return{ok:!1,productId:$,quantity:J,reason:"product-missing"};let X=G.min_order_qty??null,Z=G.max_order_qty??null;if(X!=null&&J<X)return{ok:!1,productId:$,quantity:J,reason:"below-min",bound:X};if(Z!=null&&J>Z)return{ok:!1,productId:$,quantity:J,reason:"above-max",bound:Z};return{ok:!0,productId:$,quantity:J}}async function w6($){for(let G of $){let X=await T1(G.productId,G.quantity);if(!X.ok)return X}let J=$[$.length-1]??{productId:0,quantity:0};return{ok:!0,productId:J.productId,quantity:J.quantity}}async function f6($={}){let J=$.olderThanDays??30,G=$.limit??1000,Z=new Date(Date.now()-J*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let Y=await C$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[Z,Z,G]),K=typeof Y?.execute==="function"?await Y.execute():Y;return{deleted:Number(K?.changes??K?.numDeletedRows??K?.[0]?.numDeletedRows??K?.affectedRows??0),cutoffAt:Z}}catch{try{let Y=await C$.selectFrom("carts").where("updated_at","<",Z).select(["id"]).limit(G).execute();if(Y.length===0)return{deleted:0,cutoffAt:Z};let K=Y.map((L)=>L.id),W=await C$.deleteFrom("carts").where("id","in",K).execute();return{deleted:Number(W?.numDeletedRows??W?.[0]?.numDeletedRows??W?.affectedRows??Y.length),cutoffAt:Z}}catch{return{deleted:0,cutoffAt:Z}}}}var q1={};B(q1,{update:()=>u6,store:()=>m6,recordRefund:()=>n6,fetchPaymentStatsByMethod:()=>v6,fetchPaymentStats:()=>D6,fetchMonthlyPaymentTrends:()=>y6,fetchById:()=>V0,fetchAll:()=>g6,destroy:()=>h6,bulkDestroy:()=>I6});import{db as C6}from"@stacksjs/database";async function h6($){try{let J=await C6.deleteFrom("payments").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payment: ${J.message}`);throw J}}async function I6($){if(!$.length)return 0;try{let J=await C6.deleteFrom("payments").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payments: ${J.message}`);throw J}}import{db as k}from"@stacksjs/database";import{formatDate as y}from"@stacksjs/orm";async function g6(){return await k.selectFrom("payments").selectAll().execute()}async function V0($){return await k.selectFrom("payments").selectAll().where("id","=",$).executeTakeFirst()}async function D6($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-$);let Y=await k.selectFrom("payments").select([k.fn.count("id").as("transaction_count"),k.fn.sum("amount").as("total_revenue")]).where("created_at",">=",y(G)).where("created_at","<=",y(J)).where("status","=","completed").executeTakeFirst(),K=await k.selectFrom("payments").select([k.fn.count("id").as("transaction_count"),k.fn.sum("amount").as("total_revenue")]).where("created_at",">=",y(Z)).where("created_at","<=",y(X)).where("status","=","completed").executeTakeFirst(),W=await k.selectFrom("payments").select(k.fn.count("id").as("count")).where("created_at",">=",y(G)).where("created_at","<=",y(J)).executeTakeFirst(),Q=Number(Y?.transaction_count||0),L=Number(Y?.total_revenue||0),N=Q>0?L/Q:0,H=Number(K?.transaction_count||0),z=Number(K?.total_revenue||0),x=H>0?z/H:0,U=Q-H,O=L-z,R=N-x,c=H>0?U/H*100:Q>0?100:0,L0=z>0?O/z*100:L>0?100:0,F0=x>0?R/x*100:N>0?100:0,O0=Number(W?.count||0),u=O0>0?Q/O0*100:0;return{total_transactions:Q,total_revenue:L,average_transaction:N,successful_rate:u,comparison:{transactions:{difference:U,percentage:Math.abs(c),is_increase:U>=0},revenue:{difference:O,percentage:Math.abs(L0),is_increase:O>=0},average:{difference:R,percentage:Math.abs(F0),is_increase:R>=0}}}}async function v6($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=await k.selectFrom("payments").select([k.fn.count("id").as("total_count"),k.fn.sum("amount").as("total_revenue")]).where("created_at",">=",y(G)).where("created_at","<=",y(J)).where("status","=","completed").executeTakeFirst(),Z=Number(X?.total_count||0),Y=await k.selectFrom("payments").select(["method",k.fn.count("id").as("count"),k.fn.sum("amount").as("revenue")]).where("created_at",">=",y(G)).where("created_at","<=",y(J)).where("status","=","completed").groupBy("method").execute(),K={};return Y.forEach((W)=>{let Q=Number(W.count||0),L=Number(W.revenue||0),N=Z>0?Q/Z*100:0;K[W.method]={count:Q,revenue:L,percentage_of_total:N}}),K}async function y6(){let $=new Date,J=new Date($);J.setMonth($.getMonth()-11),J.setDate(1);let G=await k.selectFrom("payments").selectAll().where("created_at",">=",y(J)).where("status","=","completed").execute(),X={};for(let Y of G){let K=Y.created_at?new Date(Y.created_at):new Date,W=K.getFullYear(),Q=K.getMonth()+1,L=`${W}-${String(Q).padStart(2,"0")}`;if(!X[L])X[L]={year:W,month:Q,transactions:0,revenue:0};X[L].transactions++,X[L].revenue+=Number(Y.amount||0)}return Object.keys(X).sort().map((Y)=>{let K=X[Y],W=K.transactions,Q=K.revenue,L=W>0?Q/W:0;return{month:new Date(K.year,K.month-1,1).toLocaleString("default",{month:"short"}),year:K.year,transactions:W,revenue:Q,average:L}})}var{randomUUIDv7:aZ}=globalThis.Bun;import{db as b6}from"@stacksjs/database";import{HttpError as p6}from"@stacksjs/error-handling";import{isUniqueViolation as rZ}from"@stacksjs/orm";async function m6($){let J=aZ(),G={...$,status:$.status||"pending",currency:$.currency||"USD",uuid:J};try{return await b6.insertInto("payments").values(G).executeTakeFirst(),await b6.selectFrom("payments").where("uuid","=",J).selectAll().executeTakeFirst()}catch(X){if(X instanceof p6)throw X;if(rZ(X))throw new p6(409,"A payment with this transaction ID already exists");if(X instanceof Error){if(X.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${X.message}`)}throw X}}import{db as l6,sqlHelpers as tZ}from"@stacksjs/database";import{env as eZ}from"@stacksjs/env";import{formatDate as c6}from"@stacksjs/orm";async function u6($,J){if(!await V0($))return;try{return await l6.updateTable("payments").set({...J,updated_at:c6(new Date)}).where("id","=",$).execute(),await V0($)}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${X.message}`)}throw X}}var $Y=new Set(["completed","succeeded","partiallyRefunded"]);async function n6($,J){if(!Number.isSafeInteger($)||$<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger(J)||J<=0)throw TypeError("Refund amount must be a positive integer in minor units");let X=tZ(eZ.DB_CONNECTION||"sqlite").param,Z=c6(new Date),Y=await l6.unsafe(`UPDATE payments
|
|
20
|
+
AND inventory_count + ${Z(4)} >= 0`,parameters:[G,X,J,G]}}async function B6($,J,G,X){let Z=nZ(uZ.DB_CONNECTION||"sqlite",J,G,X),Y=await $.unsafe(Z.query,Z.parameters),K=typeof Y?.execute==="function"?await Y.execute():Y;return L(K)}var O6=!1;function A6($){let J=$,G=J?.message??"";return J?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function w$($){try{let J=await k$.selectFrom("order_idempotency").where("idempotency_key","=",$).selectAll().executeTakeFirst();if(!J)return null;return await k$.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}catch(J){if(A6(J)){if(!O6)O6=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw J}}async function U6($){if($.idempotencyKey){let J=await w$($.idempotencyKey);if(J)return{ok:!0,order:J}}try{let J=await k$.transaction(async(G)=>{let X=iZ(new Date),Z=M6(),Y={...$.order,status:$.order.status||"PENDING",uuid:Z,created_at:X,updated_at:X};await G.insertInto("orders").values(Y).executeTakeFirst();let K=await G.selectFrom("orders").where("uuid","=",Z).selectAll().executeTakeFirst(),W=Number(K?.id);if(!Number.isSafeInteger(W)||W<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let Q;if($.items&&$.items.length>0){let H=$.items.map((z)=>{if(!Number.isInteger(z.productId)||z.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(z.quantity)||z.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(z.price)||z.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:W,product_id:z.productId,quantity:z.quantity,price:z.price,special_instructions:z.specialInstructions||null,created_at:X,updated_at:X}});await G.insertInto("order_items").values(H).execute(),Q=await G.selectFrom("order_items").where("order_id","=",W).selectAll().execute()}let F;if($.payment)try{let H=M6();if(await G.insertInto("payments").values({...$.payment,order_id:W,uuid:H,created_at:X,updated_at:X}).executeTakeFirst(),F=await G.selectFrom("payments").where("uuid","=",H).selectAll().executeTakeFirst(),!F)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(H){if(_6(H))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(H,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if($.inventory&&$.inventory.length>0)for(let H=0;H<$.inventory.length;H++){let{id:z,delta:x}=$.inventory[H];if(!Number.isFinite(x)||x===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await B6(G,z,x,X))throw Object.assign(Error(`inventory adjust failed for product ${z}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if($.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:$.idempotencyKey,order_id:W,created_at:X}).execute()}catch(H){if(_6(H))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!A6(H))throw H}let N=await G.selectFrom("orders").where("id","=",W).selectAll().executeTakeFirst();if(!N)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:N,items:Q,payment:F}});if(s0(J.order),J.payment)Y0(J.order,J.payment);return{ok:!0,order:J.order,items:J.items,payment:J.payment}}catch(J){if(J?.__placeFail){if(J.reason==="duplicate-idempotency-key"&&$.idempotencyKey){let G=await w$($.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:J.reason,failedAt:J.failedAt,error:J}}throw J}}R0();import{db as O1}from"@stacksjs/database";import{formatDate as A1}from"@stacksjs/orm";R0();async function P6($,J){if(!await r($))return;try{return await O1.updateTable("orders").set({...J,updated_at:A1(new Date)}).where("id","=",$).execute(),await r($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order: ${X.message}`);throw X}}async function S6($,J){let G=await r($);if(!G)throw Error(`Order with ID ${$} not found`);let X=G.status??"PENDING";if(!i0(X,J))throw Error(`[commerce/orders] illegal status transition ${X} \u2192 ${J}`);try{await O1.updateTable("orders").set({status:J,updated_at:A1(new Date)}).where("id","=",$).execute();let Z=await r($);if(Z)o0(J,Z);return Z}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update order status: ${Z.message}`);throw Z}}async function R6($,J,G){let X=await r($);if(!X)throw Error(`Order with ID ${$} not found`);let Z={updated_at:A1(new Date)};if(J!==void 0)Z.delivery_address=J;if(G!==void 0)Z.estimated_delivery_time=G;if(Object.keys(Z).length===1)return X;try{return await O1.updateTable("orders").set(Z).where("id","=",$).execute(),await r($)}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery information: ${Y.message}`);throw Y}}R0();import{db as T0}from"@stacksjs/database";import{formatDate as f$}from"@stacksjs/orm";async function U1($){let J=await T0.selectFrom("payments").where("transaction_id","=",$).selectAll().executeTakeFirst();if(!J)return null;return await T0.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}var T6=!1;function sZ($){let J=$,G=J?.message??"";return J?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function P1($,J){try{return await J.insertInto("stripe_webhook_events").values({event_id:$,processed_at:f$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(sZ(G)){if(!T6)T6=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw G}}async function S1($){let G=$.data.object?.id;if(!G)return;await T0.transaction(async(Z)=>{if(!await P1($.id,Z))return;let K=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!K)return;let W=f$(new Date);await Z.updateTable("payments").set({status:"succeeded",updated_at:W}).where("id","=",K.id).execute();let Q=await Z.selectFrom("orders").where("id","=",K.order_id).selectAll().executeTakeFirst();if(Q&&Q.status==="PENDING")await Z.updateTable("orders").set({status:"PROCESSING",updated_at:W}).where("id","=",Q.id).execute()});let X=await U1(G);if(X)await Y0(X)}async function R1($){let J=$.data.object,G=J?.id;if(!G)return;let Z=J?.last_payment_error?.message??"payment failed";await T0.transaction(async(K)=>{if(!await P1($.id,K))return;let Q=await K.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Q)return;let F=f$(new Date);await K.updateTable("payments").set({status:"failed",failure_reason:Z,updated_at:F}).where("id","=",Q.id).execute();let N=await K.selectFrom("orders").where("id","=",Q.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await K.updateTable("orders").set({status:"CANCELLED",updated_at:F}).where("id","=",N.id).execute()});let Y=await U1(G);if(Y)await P0(Y,Z)}async function T1($){let J=$.data.object,G=J?.payment_intent;if(!G)return;let X=J?.amount_refunded??0;await T0.transaction(async(Y)=>{if(!await P1($.id,Y))return;let W=await Y.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!W)return;let Q=f$(new Date);await Y.updateTable("payments").set({status:"refunded",refund_amount:X,updated_at:Q}).where("id","=",W.id).execute();let F=await Y.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(F&&F.status!=="REFUNDED")await Y.updateTable("orders").set({status:"REFUNDED",updated_at:Q}).where("id","=",F.id).execute()});let Z=await U1(G);if(Z)await S0(Z,X)}async function E6(){let $=await import("@stacksjs/payments").catch(()=>null);if(!$)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:J,onCharge:G}=$;if(typeof J!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return J({succeeded:S1,failed:R1}),G({refunded:T1}),()=>{}}import{db as j6}from"@stacksjs/database";async function oZ($){if($.length===0)return new Map;let J=await j6.selectFrom("products").where("id","in",$).select(["id","price"]).execute(),G=new Map;for(let X of J){let Z=Number(X.price);if(Number.isFinite(Z))G.set(X.id,Math.round(Z))}return G}async function dZ($){try{let J=await j6.selectFrom("tax_rates").where("id","=",$).select(["rate"]).executeTakeFirst(),G=Number(J?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function q6($){let J=$.items.map((U)=>U.productId),G=await oZ(J),X=$.taxRateId!=null?await dZ($.taxRateId):0,Z=0,Y=[];for(let U of $.items){let O=U.unitPriceCents??G.get(U.productId)??0,P=Math.round(O*U.quantity);Z+=P,Y.push({productId:U.productId,quantity:U.quantity,unitPriceCents:O,lineCents:P})}let K=Math.max(0,$.discountCents??0),W=Math.max(0,Z-K),Q=Math.round(W*X),F=Math.max(0,$.shippingCents??0),N=Z-K+Q+F,H=$.maxDriftCents??5,z=!1,x=0;if($.clientTotalCents!=null)x=Math.abs(N-$.clientTotalCents),z=x>H;return{subtotalCents:Z,discountCents:K,taxCents:Q,shippingCents:F,totalCents:N,resolvedItems:Y,priceChanged:z,diffCents:x}}import{db as C$}from"@stacksjs/database";function k6($,J={}){let G=$.length;if(G<=1)return{ok:!0,count:G};if(!J.allowMultiple)return{ok:!1,count:G,reason:"multiple-not-allowed"};let X=J.maxStacked??Number.POSITIVE_INFINITY;if(G>X)return{ok:!1,count:G,reason:"exceeds-max-stacked"};return{ok:!0,count:G}}async function E1($,J){if(!Number.isFinite(J)||J<=0)return{ok:!1,productId:$,quantity:J,reason:"non-positive"};let G;try{G=await C$.selectFrom("products").where("id","=",$).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:$,quantity:J}}if(!G)return{ok:!1,productId:$,quantity:J,reason:"product-missing"};let X=G.min_order_qty??null,Z=G.max_order_qty??null;if(X!=null&&J<X)return{ok:!1,productId:$,quantity:J,reason:"below-min",bound:X};if(Z!=null&&J>Z)return{ok:!1,productId:$,quantity:J,reason:"above-max",bound:Z};return{ok:!0,productId:$,quantity:J}}async function w6($){for(let G of $){let X=await E1(G.productId,G.quantity);if(!X.ok)return X}let J=$[$.length-1]??{productId:0,quantity:0};return{ok:!0,productId:J.productId,quantity:J.quantity}}async function f6($={}){let J=$.olderThanDays??30,G=$.limit??1000,Z=new Date(Date.now()-J*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let Y=await C$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[Z,Z,G]),K=typeof Y?.execute==="function"?await Y.execute():Y;return{deleted:Number(K?.changes??K?.numDeletedRows??K?.[0]?.numDeletedRows??K?.affectedRows??0),cutoffAt:Z}}catch{try{let Y=await C$.selectFrom("carts").where("updated_at","<",Z).select(["id"]).limit(G).execute();if(Y.length===0)return{deleted:0,cutoffAt:Z};let K=Y.map((F)=>F.id),W=await C$.deleteFrom("carts").where("id","in",K).execute();return{deleted:Number(W?.numDeletedRows??W?.[0]?.numDeletedRows??W?.affectedRows??Y.length),cutoffAt:Z}}catch{return{deleted:0,cutoffAt:Z}}}}var q1={};B(q1,{update:()=>u6,store:()=>m6,recordRefund:()=>n6,fetchPaymentStatsByMethod:()=>v6,fetchPaymentStats:()=>D6,fetchMonthlyPaymentTrends:()=>y6,fetchById:()=>V0,fetchAll:()=>g6,destroy:()=>h6,bulkDestroy:()=>I6});import{db as C6}from"@stacksjs/database";async function h6($){try{let J=await C6.deleteFrom("payments").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payment: ${J.message}`);throw J}}async function I6($){if(!$.length)return 0;try{let J=await C6.deleteFrom("payments").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payments: ${J.message}`);throw J}}import{db as k}from"@stacksjs/database";import{formatDate as y}from"@stacksjs/orm";async function g6(){return await k.selectFrom("payments").selectAll().execute()}async function V0($){return await k.selectFrom("payments").selectAll().where("id","=",$).executeTakeFirst()}async function D6($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-$);let Y=await k.selectFrom("payments").select([k.fn.count("id").as("transaction_count"),k.fn.sum("amount").as("total_revenue")]).where("created_at",">=",y(G)).where("created_at","<=",y(J)).where("status","=","completed").executeTakeFirst(),K=await k.selectFrom("payments").select([k.fn.count("id").as("transaction_count"),k.fn.sum("amount").as("total_revenue")]).where("created_at",">=",y(Z)).where("created_at","<=",y(X)).where("status","=","completed").executeTakeFirst(),W=await k.selectFrom("payments").select(k.fn.count("id").as("count")).where("created_at",">=",y(G)).where("created_at","<=",y(J)).executeTakeFirst(),Q=Number(Y?.transaction_count||0),F=Number(Y?.total_revenue||0),N=Q>0?F/Q:0,H=Number(K?.transaction_count||0),z=Number(K?.total_revenue||0),x=H>0?z/H:0,U=Q-H,O=F-z,P=N-x,c=H>0?U/H*100:Q>0?100:0,F0=z>0?O/z*100:F>0?100:0,L0=x>0?P/x*100:N>0?100:0,O0=Number(W?.count||0),u=O0>0?Q/O0*100:0;return{total_transactions:Q,total_revenue:F,average_transaction:N,successful_rate:u,comparison:{transactions:{difference:U,percentage:Math.abs(c),is_increase:U>=0},revenue:{difference:O,percentage:Math.abs(F0),is_increase:O>=0},average:{difference:P,percentage:Math.abs(L0),is_increase:P>=0}}}}async function v6($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=await k.selectFrom("payments").select([k.fn.count("id").as("total_count"),k.fn.sum("amount").as("total_revenue")]).where("created_at",">=",y(G)).where("created_at","<=",y(J)).where("status","=","completed").executeTakeFirst(),Z=Number(X?.total_count||0),Y=await k.selectFrom("payments").select(["method",k.fn.count("id").as("count"),k.fn.sum("amount").as("revenue")]).where("created_at",">=",y(G)).where("created_at","<=",y(J)).where("status","=","completed").groupBy("method").execute(),K={};return Y.forEach((W)=>{let Q=Number(W.count||0),F=Number(W.revenue||0),N=Z>0?Q/Z*100:0;K[W.method]={count:Q,revenue:F,percentage_of_total:N}}),K}async function y6(){let $=new Date,J=new Date($);J.setMonth($.getMonth()-11),J.setDate(1);let G=await k.selectFrom("payments").selectAll().where("created_at",">=",y(J)).where("status","=","completed").execute(),X={};for(let Y of G){let K=Y.created_at?new Date(Y.created_at):new Date,W=K.getFullYear(),Q=K.getMonth()+1,F=`${W}-${String(Q).padStart(2,"0")}`;if(!X[F])X[F]={year:W,month:Q,transactions:0,revenue:0};X[F].transactions++,X[F].revenue+=Number(Y.amount||0)}return Object.keys(X).sort().map((Y)=>{let K=X[Y],W=K.transactions,Q=K.revenue,F=W>0?Q/W:0;return{month:new Date(K.year,K.month-1,1).toLocaleString("default",{month:"short"}),year:K.year,transactions:W,revenue:Q,average:F}})}var{randomUUIDv7:aZ}=globalThis.Bun;import{db as b6}from"@stacksjs/database";import{HttpError as p6}from"@stacksjs/error-handling";import{isUniqueViolation as rZ}from"@stacksjs/orm";async function m6($){let J=aZ(),G={...$,status:$.status||"pending",currency:$.currency||"USD",uuid:J};try{return await b6.insertInto("payments").values(G).executeTakeFirst(),await b6.selectFrom("payments").where("uuid","=",J).selectAll().executeTakeFirst()}catch(X){if(X instanceof p6)throw X;if(rZ(X))throw new p6(409,"A payment with this transaction ID already exists");if(X instanceof Error){if(X.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${X.message}`)}throw X}}import{db as l6,sqlHelpers as tZ}from"@stacksjs/database";import{env as eZ}from"@stacksjs/env";import{formatDate as c6}from"@stacksjs/orm";async function u6($,J){if(!await V0($))return;try{return await l6.updateTable("payments").set({...J,updated_at:c6(new Date)}).where("id","=",$).execute(),await V0($)}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${X.message}`)}throw X}}var $Y=new Set(["completed","succeeded","partiallyRefunded"]);async function n6($,J){if(!Number.isSafeInteger($)||$<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger(J)||J<=0)throw TypeError("Refund amount must be a positive integer in minor units");let X=tZ(eZ.DB_CONNECTION||"sqlite").param,Z=c6(new Date),Y=await l6.unsafe(`UPDATE payments
|
|
21
21
|
SET refund_amount = COALESCE(refund_amount, 0) + ${X(1)},
|
|
22
22
|
status = CASE WHEN COALESCE(refund_amount, 0) + ${X(2)} = amount
|
|
23
23
|
THEN 'refunded' ELSE 'partiallyRefunded' END,
|
|
24
24
|
updated_at = ${X(3)}
|
|
25
25
|
WHERE id = ${X(4)}
|
|
26
26
|
AND status IN ('completed', 'succeeded', 'partiallyRefunded')
|
|
27
|
-
AND COALESCE(refund_amount, 0) + ${X(5)} <= amount`,[J,J,Z,$,J]),K=typeof Y?.execute==="function"?await Y.execute():Y;if(Number(K?.numUpdatedRows??K?.[0]?.numUpdatedRows??K?.numAffectedRows??K?.affectedRows??K?.[0]?.affectedRows??K?.changes??0)>0){let z=await V0($);if(z)return z;throw Error(`Payment with ID ${$} disappeared during refund`)}let Q=await V0($);if(!Q)throw Error(`Payment with ID ${$} not found`);let L=String(Q.status||"");if(!$Y.has(L))throw Error(`Payment status ${L||"unknown"} cannot be refunded`);let N=Q,H=Number(Q.amount||0)-Number(N.refundAmount??N.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${H} minor units`)}var g1={};B(g1,{variants:()=>l$,units:()=>m$,reviews:()=>y$,manufacturers:()=>v$,items:()=>D$,default:()=>HY,categories:()=>g$});var g$={};B(g$,{updateParent:()=>F2,updateDisplayOrder:()=>Q2,updateActiveStatus:()=>L2,update:()=>W2,store:()=>w1,removeChildCategories:()=>G2,remove:()=>$2,findOrCreateByName:()=>K2,fetchStats:()=>r6,fetchRootCategories:()=>o6,fetchChildCategories:()=>d6,fetchCategoryTree:()=>e6,fetchByName:()=>i6,fetchById:()=>w,fetchByDisplayOrder:()=>a6,fetchAll:()=>k1,fetchActive:()=>s6,deactivateChildCategories:()=>Z2,deactivate:()=>X2,compareCategoryGrowth:()=>t6,bulkRemove:()=>J2});import{db as T0}from"@stacksjs/database";import{db as P}from"@stacksjs/database";import{formatDate as d0}from"@stacksjs/orm";async function k1(){return await P.selectFrom("categories").selectAll().execute()}async function w($){return await P.selectFrom("categories").where("id","=",$).selectAll().executeTakeFirst()}async function i6($){return await P.selectFrom("categories").where("name","=",$).selectAll().executeTakeFirst()}async function s6(){return await P.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function o6(){return await P.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function d6($){return await P.selectFrom("categories").where("parent_category_id","=",$).where("is_active","=",!0).selectAll().execute()}async function a6($=!0){let J=P.selectFrom("categories").where("is_active","=",!0).selectAll();if($)return await J.orderBy("display_order","asc").execute();else return await J.orderBy("display_order","desc").execute()}async function r6(){let $=await P.selectFrom("categories").select(P.fn.count("id").as("count")).executeTakeFirst(),J=await P.selectFrom("categories").where("is_active","=",!0).select(P.fn.count("id").as("count")).executeTakeFirst(),G=await P.selectFrom("categories").whereNull("parent_category_id").select(P.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("categories").whereNotNull("image_url").select(P.fn.count("id").as("count")).executeTakeFirst(),Z=new Date;Z.setDate(Z.getDate()-30);let Y=d0(Z),K=await P.selectFrom("categories").where("created_at",">=",Y).selectAll().limit(5).execute(),W=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($?.count||0),active:Number(J?.count||0),root_categories:Number(G?.count||0),child_categories:Number($?.count||0)-Number(G?.count||0),with_images:Number(X?.count||0),recently_added:K,top_parent_categories:W.map((Q)=>({id:String(Q.parent_category_id||""),name:String(Q.parent_name||""),child_count:Number(Q.child_count)}))}}async function t6($=30){let J=new Date,G=d0(J),X=new Date;X.setDate(J.getDate()-$);let Z=d0(X),Y=new Date(X);Y.setDate(Y.getDate()-1);let K=d0(Y),W=new Date(Y);W.setDate(Y.getDate()-$);let Q=d0(W),L=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",G).executeTakeFirst(),N=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",Q).where("created_at","<=",K).executeTakeFirst(),H=Number(L?.count||0),z=Number(N?.count||0),x=H-z,U=z!==0?x/z*100:H>0?100:0;return{current_period:H,previous_period:z,difference:x,percentage_change:U,days_range:$}}async function e6(){let $=await k1(),J=new Map;$.forEach((Z)=>{J.set(Z.id,{...Z,children:[]})});let G=[];$.forEach((Z)=>{let Y=J.get(Z.id);if(Z.parent_category_id){let K=J.get(Z.parent_category_id);if(K)K.children.push(Y)}else G.push(Y)}),G.sort((Z,Y)=>Z.display_order-Y.display_order);let X=(Z)=>{Z.sort((Y,K)=>Y.display_order-K.display_order),Z.forEach((Y)=>{if(Y.children.length>0)X(Y.children)})};return X(G),G}async function $2($){let J=await T0.deleteFrom("categories").where("id","=",$).executeTakeFirst();return F(J)>0}async function J2($){if(!$.length)return 0;let J=await T0.deleteFrom("categories").where("id","in",$).executeTakeFirst();return F(J)}async function G2($){let J=await T0.deleteFrom("categories").where("parent_category_id","=",$).executeTakeFirst();return F(J)}async function X2($){if(!await w($))throw Error(`Category with ID ${$} not found`);return!!await T0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",$).executeTakeFirst()}async function Z2($){let J=await T0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",$).execute();return Number(J.length)||0}var{randomUUIDv7:JY}=globalThis.Bun;import{db as Y2}from"@stacksjs/database";import{HttpError as h$}from"@stacksjs/error-handling";import{isUniqueViolation as GY}from"@stacksjs/orm";import{slug as XY}from"@stacksjs/strings";async function w1($){try{let J=$.parent_category_id?Number($.parent_category_id):void 0;if(J!==void 0&&(!Number.isSafeInteger(J)||J<=0))throw new h$(422,"Parent category ID must be a positive integer");if(J&&!await w(J))throw new h$(422,`Parent category with ID ${$.parent_category_id} not found`);let G={...$,uuid:JY(),is_active:$.is_active??!0,parent_category_id:$.parent_category_id||null},X=await Y2.insertInto("categories").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create category");return X}catch(J){if(J instanceof h$)throw J;if(GY(J))throw new h$(409,"A category with this name or slug already exists");if(J instanceof Error)throw Error(`Failed to create category: ${J.message}`);throw J}}async function K2($){if(!$.name)throw Error("Name is required");let J=await Y2.selectFrom("categories").selectAll().where("name","=",$.name).executeTakeFirst();if(J)return J;let G={name:$.name,slug:XY($.name),is_active:$.is_active??!0,display_order:0};return await w1(G)}import{db as a0}from"@stacksjs/database";import{HttpError as j0}from"@stacksjs/error-handling";import{formatDate as I$,isUniqueViolation as ZY}from"@stacksjs/orm";async function W2($,J){if(!await w($))return;if(Object.hasOwn(J,"parent_category_id")){let X=J.parent_category_id?Number(J.parent_category_id):void 0;if(X!==void 0&&(!Number.isSafeInteger(X)||X<=0))throw new j0(422,"Parent category ID must be a positive integer");if(X===$)throw new j0(422,"A category cannot be its own parent");if(X&&!await w(X))throw new j0(422,`Parent category with ID ${J.parent_category_id} not found`);if(X&&await N2($,String(X)))throw new j0(422,"This operation would create a circular category hierarchy")}try{let X=Object.hasOwn(J,"parent_category_id")?{parent_category_id:J.parent_category_id||null}:{},Z=await a0.updateTable("categories").set({...J,...X,updated_at:I$(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(X){if(X instanceof j0)throw X;if(ZY(X))throw new j0(409,"A category with this name or slug already exists");if(X instanceof Error)throw Error(`Failed to update category: ${X.message}`);throw X}}async function Q2($,J){if(!await w($))throw Error(`Category with ID ${$} not found`);try{return await a0.updateTable("categories").set({display_order:J,updated_at:I$(new Date)}).where("id","=",$).execute(),await w($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category display order: ${X.message}`);throw X}}async function L2($,J){if(!await w($))throw Error(`Category with ID ${$} not found`);try{return await a0.updateTable("categories").set({is_active:J,updated_at:I$(new Date)}).where("id","=",$).execute(),await w($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function F2($,J){if(!await w($))throw Error(`Category with ID ${$} not found`);if(J){let X=Number(J);if(X===$)throw Error("A category cannot be its own parent");if(!await w(X))throw Error(`Parent category with ID ${J} not found`);if(await N2($,J))throw Error("This operation would create a circular reference in the category hierarchy")}try{let X={updated_at:I$(new Date)};if(J===null)await a0.updateTable("categories").set({...X,parent_category_id:null}).where("id","=",$).execute();else await a0.updateTable("categories").set({...X,parent_category_id:J}).where("id","=",$).execute();return await w($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category parent: ${X.message}`);throw X}}async function N2($,J){let G=Number(J),X=new Set;while(G){if(X.has(G))return!0;if(G===$)return!0;X.add(G);let Z=await w(G),Y=Z?.parent_category_id??Z?.parentCategoryId;if(!Z||!Y)return!1;G=Number(Y)}return!1}var D$={};B(D$,{updateInventory:()=>S2,updateAvailability:()=>R2,update:()=>U2,store:()=>O2,fetchTopProducts:()=>B2,fetchById:()=>t,fetchAll:()=>x2,destroy:()=>z2,bulkStore:()=>A2,bulkDestroy:()=>V2});import{db as H2}from"@stacksjs/database";async function z2($){try{let J=await H2.deleteFrom("products").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product item: ${J.message}`);throw J}}async function V2($){if(!$.length)return 0;try{let J=await H2.deleteFrom("products").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product items: ${J.message}`);throw J}}import{db as K0,sql as YY}from"@stacksjs/database";async function t($){let J=await K0.selectFrom("products").where("id","=",$).selectAll().executeTakeFirst();if(J){let G=null,X=null;if(J.manufacturer_id)G=await K0.selectFrom("manufacturers").where("id","=",J.manufacturer_id).selectAll().executeTakeFirst();if(J.category_id)X=await K0.selectFrom("categories").where("id","=",J.category_id).selectAll().executeTakeFirst();return{...J,manufacturer:G,category:X}}return}async function x2(){let $=await K0.selectFrom("products").selectAll().execute(),J=$.map((L)=>L.manufacturer_id).filter((L)=>L!==null&&L!==void 0),G=$.map((L)=>L.category_id).filter((L)=>L!==null&&L!==void 0),X=K0.selectFrom("manufacturers"),Z=K0.selectFrom("categories");if(J.length>0)X=X.where("id","in",J);if(G.length>0)Z=Z.where("id","in",G);let Y=await X.selectAll().execute(),K=await Z.selectAll().execute(),W=Y.reduce((L,N)=>{return L[N.id]=N,L},{}),Q=K.reduce((L,N)=>{return L[N.id]=N,L},{});return $.map((L)=>({...L,manufacturer:L.manufacturer_id?W[L.manufacturer_id]:null,category:L.category_id?Q[L.category_id]:null}))}async function B2($=5){try{return(await K0.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",K0.fn.sum("order_items.quantity").as("units_sold"),YY`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($).execute()).map((G)=>({id:Number(G.id),name:String(G.name??"Unnamed product"),units_sold:Number(G.units_sold??0),revenue:Number(G.revenue??0),inventory_count:Number(G.inventory_count??0)}))}catch(J){if(J instanceof Error)throw TypeError(`Failed to fetch top products: ${J.message}`);throw J}}var{randomUUIDv7:M2}=globalThis.Bun;import{db as _2}from"@stacksjs/database";async function O2($){try{let J={...$,uuid:M2()},G=await _2.insertInto("products").values(J).executeTakeFirst();if(!G)throw Error("Failed to create product item");let X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),Z=await t(X);if(!Z)throw Error("Failed to create product item");return Z}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product item: ${J.message}`);throw J}}async function A2($){if(!$.length)return 0;let J=0;try{return await _2.transaction().execute(async(G)=>{for(let X of $){let Z={...X,uuid:M2()};await G.insertInto("products").values(Z).execute(),J++}}),J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as f1}from"@stacksjs/database";import{formatDate as C1}from"@stacksjs/orm";async function U2($,J){try{if(!$)throw Error("Product item ID is required for update");let G=await f1.updateTable("products").set({...J,updated_at:C1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item: ${G.message}`);throw G}}async function R2($,J){if(!await t($))throw Error(`Product item with ID ${$} not found`);try{return await f1.updateTable("products").set({is_available:J,updated_at:C1(new Date)}).where("id","=",$).execute(),await t($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item availability: ${X.message}`);throw X}}async function S2($,J){let G=await t($);if(!G)throw Error(`Product item with ID ${$} not found`);let X={updated_at:C1(new Date)};if(J!==void 0)X.inventory_count=J;if(Object.keys(X).length===1)return G;try{return await f1.updateTable("products").set(X).where("id","=",$).execute(),await t($)}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update inventory information: ${Z.message}`);throw Z}}var v$={};B(v$,{updateFeaturedStatus:()=>p2,updateByUuid:()=>m2,update:()=>b2,store:()=>D2,fetchWithProductCount:()=>C2,fetchFeatured:()=>w2,fetchByUuid:()=>k2,fetchById:()=>q2,fetchByCountry:()=>f2,fetchAll:()=>j2,destroy:()=>E2,bulkStore:()=>v2,bulkDestroy:()=>T2});import{db as P2}from"@stacksjs/database";async function E2($){try{let J=await P2.deleteFrom("manufacturers").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function T2($){if(!$.length)return 0;try{let J=await P2.deleteFrom("manufacturers").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}import{db as e}from"@stacksjs/database";function j2(){return e.selectFrom("manufacturers").selectAll().execute()}async function q2($){return await e.selectFrom("manufacturers").where("id","=",$).selectAll().executeTakeFirst()}async function k2($){return await e.selectFrom("manufacturers").where("uuid","=",$).selectAll().executeTakeFirst()}async function w2($=10){return await e.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit($).execute()}async function f2($,J={}){let G=J.page||1,X=J.limit||2,Z=await e.selectFrom("manufacturers").select(e.fn.count("id").as("total")).where("country","=",$).executeTakeFirst(),Y=Number(Z?.total||0),K=await e.selectFrom("manufacturers").selectAll().where("country","=",$).limit(X).offset((G-1)*X).execute(),W=Math.ceil(Y/X);return{data:K,paging:{total_records:Y,page:G,total_pages:W},next_cursor:G<W?G+1:null}}async function C2($={}){let J=e.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if($.country)J=J.where("m.country","=",$.country);if($.featured!==void 0)J=J.where("m.featured","=",$.featured);return J=J.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",e.fn.count("p.id").as("product_count")]).groupBy("m.id"),J.execute()}var{randomUUIDv7:I2}=globalThis.Bun;import{db as g2}from"@stacksjs/database";import{HttpError as h2}from"@stacksjs/error-handling";import{isUniqueViolation as KY}from"@stacksjs/orm";async function D2($){try{let J={...$,uuid:I2(),featured:$.featured??!1},G=await g2.insertInto("manufacturers").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch(J){if(J instanceof h2)throw J;if(KY(J))throw new h2(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to create manufacturer: ${J.message}`);throw J}}async function v2($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={...G,uuid:I2(),featured:G.featured??!1};await g2.insertInto("manufacturers").values(X).execute(),J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${G.message}`);throw G}}import{db as h1}from"@stacksjs/database";import{HttpError as y2}from"@stacksjs/error-handling";import{formatDate as I1,isUniqueViolation as WY}from"@stacksjs/orm";async function b2($,J){try{if(!$)throw Error("Manufacturer ID is required for update");let G=await h1.updateTable("manufacturers").set({...J,updated_at:I1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof y2)throw G;if(WY(G))throw new y2(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function p2($,J){try{let G=await h1.updateTable("manufacturers").set({featured:J,updated_at:I1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer featured status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${G.message}`);throw G}}async function m2($,J){try{let G=await h1.updateTable("manufacturers").set({...J,updated_at:I1(new Date)}).where("uuid","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer: ${G.message}`);throw G}}var y$={};B(y$,{updateVotes:()=>KG,update:()=>YG,store:()=>GG,fetchStatsByProductIds:()=>JG,fetchStats:()=>$G,fetchMostHelpfulByProductId:()=>a2,fetchByUserId:()=>o2,fetchByProductId:()=>s2,fetchById:()=>n2,fetchApprovedByProductId:()=>d2,fetchAll:()=>i2,destroy:()=>c2,bulkDestroy:()=>u2});import{db as l2}from"@stacksjs/database";async function c2($){try{let J=await l2.deleteFrom("reviews").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete review: ${J.message}`);throw J}}async function u2($){if(!$.length)return 0;try{let J=await l2.deleteFrom("reviews").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete reviews: ${J.message}`);throw J}}import{db as q0}from"@stacksjs/database";async function n2($){return await q0.selectFrom("reviews").where("id","=",$).selectAll().executeTakeFirst()}async function i2(){return await q0.selectFrom("reviews").selectAll().execute()}async function s2($){return await q0.selectFrom("reviews").where("product_id","=",$).selectAll().execute()}async function o2($){return await q0.selectFrom("reviews").where("customer_id","=",$).selectAll().execute()}async function d2($){return await q0.selectFrom("reviews").where("product_id","=",$).where("is_approved","=",!0).selectAll().execute()}async function a2($){return await q0.selectFrom("reviews").where("product_id","=",$).orderBy("helpful_votes","desc").selectAll().execute()}import{db as r2}from"@stacksjs/database";function t2(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function e2($){let J=t2();J.total=$.length;let G=0;for(let X of $){if(X.rating===null||X.rating===void 0){J.commentsOnly++;continue}let Z=Number(X.rating);if(Number.isNaN(Z)){J.commentsOnly++;continue}J.rated++,G+=Z;let Y=Math.min(5,Math.max(1,Math.round(Z)));J.distribution[Y]++}if(J.rated>0)J.average=Math.round(G/J.rated*10)/10;return J}async function $G($){let J=await r2.selectFrom("reviews").select(["rating"]).where("product_id","=",$).where("is_approved","=",!0).execute();return e2(J)}async function JG($){let J=new Map;for(let Z of $)J.set(Z,t2());if($.length===0)return J;let G=await r2.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",$).where("is_approved","=",!0).execute(),X=new Map;for(let Z of G){let Y=X.get(Z.product_id);if(Y)Y.push({rating:Z.rating});else X.set(Z.product_id,[{rating:Z.rating}])}for(let[Z,Y]of X)J.set(Z,e2(Y));return J}var{randomUUIDv7:QY}=globalThis.Bun;import{db as LY}from"@stacksjs/database";function FY($){let J=$.rating!==void 0&&$.rating!==null,G=typeof $.content==="string"&&$.content.trim().length>0,X=typeof $.title==="string"&&$.title.trim().length>0;return!J&&!G&&!X}async function GG($){try{if(FY($))throw Error("A review needs a rating or something written: both were empty");let J={...$,uuid:QY(),rating:$.rating??null,is_verified_purchase:$.is_verified_purchase??!1,is_approved:$.is_approved??!1,helpful_votes:$.helpful_votes??0,unhelpful_votes:$.unhelpful_votes??0,is_featured:$.is_featured??!1},G=await LY.insertInto("reviews").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create review");return G}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${J.message}`)}throw J}}import{db as XG}from"@stacksjs/database";import{formatDate as ZG}from"@stacksjs/orm";async function YG($,J){try{if(!$)throw Error("Review ID is required for update");let G=await XG.updateTable("reviews").set({...J,updated_at:ZG(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review: ${G.message}`);throw G}}async function KG($,J,G=!0){try{let X=J==="helpful"?"helpful_votes":"unhelpful_votes",Z=G?`COALESCE("${X}", 0) + 1`:`MAX(COALESCE("${X}", 0) - 1, 0)`,Y=await XG.unsafe(`UPDATE "reviews" SET "${X}" = ${Z}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[ZG(new Date),$]).execute(),K=Array.isArray(Y)?Y[0]:Y;if(!K)throw Error("Failed to update review votes");return K}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var m$={};B(m$,{updateDefaultStatus:()=>AG,update:()=>_G,store:()=>VG,getDefaultUnit:()=>MG,formatUnitOptions:()=>BG,fetchById:()=>NG,fetchAll:()=>HG,destroy:()=>QG,bulkUpdate:()=>OG,bulkStore:()=>xG,bulkDestroy:()=>LG});import{db as WG}from"@stacksjs/database";async function QG($){try{let J=await WG.deleteFrom("product_units").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product unit: ${J.message}`);throw J}}async function LG($){if(!$.length)return 0;try{let J=await WG.deleteFrom("product_units").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product units: ${J.message}`);throw J}}import{db as FG}from"@stacksjs/database";async function NG($){return await FG.selectFrom("product_units").where("id","=",$).selectAll().executeTakeFirst()}async function HG(){return await FG.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:zG}=globalThis.Bun;import{db as r0}from"@stacksjs/database";async function VG($){try{return await r0.transaction(async(J)=>{let G={...$,uuid:zG()},X=await J.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(G.is_default&&G.type)await J.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();return X})}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product unit: ${J.message}`);throw J}}async function xG($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={...G,uuid:zG()},Z=await r0.insertInto("product_units").values(X).returningAll().executeTakeFirst();if(X.is_default&&X.type&&Z)await r0.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",Z.id).execute();J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function BG($){try{let J=r0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if($)J=J.where("type","=",$);return J=J.orderBy("name"),J.execute().then((G)=>G.map((X)=>({id:String(X.id),name:X.name,abbreviation:X.abbreviation,is_default:X.is_default})))}catch(J){if(J instanceof Error)throw TypeError(`Failed to format unit options: ${J.message}`);throw J}}async function MG($){try{return await r0.selectFrom("product_units").selectAll().where("type","=",$).where("is_default","=",!0).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get default unit: ${J.message}`);throw J}}import{db as b$}from"@stacksjs/database";import{formatDate as p$}from"@stacksjs/orm";async function _G($,J){try{if(!$)throw Error("Product unit ID is required for update");return await b$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",$).executeTakeFirst();if(!X)return;let Z=J.type??X.type;if((J.is_default??Boolean(X.is_default))&&Z)await G.updateTable("product_units").set({is_default:!1,updated_at:p$(new Date)}).where("type","=",Z).where("id","!=",$).execute();let K=await G.updateTable("product_units").set({...J,updated_at:p$(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!K)return;return K})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function OG($){if(!$.length)return 0;let J=0;try{for(let G of $){let X=G;if(!X.id)continue;let Z=X.data&&typeof X.data==="object"?X.data:{...X};delete Z.id;let Y=await b$.updateTable("product_units").set({...Z,updated_at:p$(new Date)}).where("id","=",X.id).executeTakeFirst(),K=Z;if(K.is_default===!0&&K.type)await b$.updateTable("product_units").set({is_default:!1}).where("type","=",K.type).where("id","!=",X.id).execute();if(Number(Y.numUpdatedRows)>0)J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function AG($,J){try{return await b$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select("type").where("id","=",$).executeTakeFirst();if(!X)return!1;let Z=p$(new Date);if(J&&X.type)await G.updateTable("product_units").set({is_default:!1,updated_at:Z}).where("type","=",X.type).where("id","!=",$).execute();return await G.updateTable("product_units").set({is_default:J,updated_at:Z}).where("id","=",$).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var l$={};B(l$,{update:()=>gG,store:()=>kG,generateVariantCombinations:()=>CG,formatVariantOptions:()=>fG,fetchById:()=>EG,fetchAll:()=>TG,destroy:()=>RG,bulkUpdate:()=>DG,bulkStore:()=>wG,bulkDestroy:()=>SG});import{db as UG}from"@stacksjs/database";async function RG($){try{let J=await UG.deleteFrom("product_variants").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variant: ${J.message}`);throw J}}async function SG($){if(!$.length)return 0;try{let J=await UG.deleteFrom("product_variants").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variants: ${J.message}`);throw J}}import{db as PG}from"@stacksjs/database";async function EG($){return await PG.selectFrom("product_variants").where("id","=",$).selectAll().executeTakeFirst()}async function TG(){return await PG.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:jG}=globalThis.Bun;import{db as qG}from"@stacksjs/database";async function kG($){try{let J={...$,uuid:jG()},G=await qG.insertInto("product_variants").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product variant");return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variant: ${J.message}`);throw J}}async function wG($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={...G,uuid:jG()};await qG.insertInto("product_variants").values(X).execute(),J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${G.message}`);throw G}}function fG($){if(!$||!$.length)return JSON.stringify([]);let J=$.map((G)=>G.trim()).filter(Boolean);return JSON.stringify(J)}function CG($){let J=Object.keys($);if(!J.length)return[];function G(X,Z){if(X===J.length)return[Z];let Y=J[X],K=$[Y]??[],W=[];for(let Q of K){let L={...Z,[Y]:Q};W.push(...G(X+1,L))}return W}return G(0,{})}import{db as hG}from"@stacksjs/database";import{formatDate as IG}from"@stacksjs/orm";async function gG($,J){try{let G=await hG.updateTable("product_variants").set({...J,updated_at:IG(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variant: ${G.message}`);throw G}}async function DG($){if(!$.length)return 0;let J=0;try{for(let G of $){if(!G.id)continue;let X=await hG.updateTable("product_variants").set({...G,updated_at:IG(new Date)}).where("id","=",G.id).executeTakeFirst();if(Number(X.numUpdatedRows)>0)J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${G.message}`);throw G}}var NY={categories:g$,items:D$,manufacturers:v$,reviews:y$,units:m$,variants:l$},HY=NY;var p1={};B(p1,{updateStatus:()=>aG,updatePrintJob:()=>rG,update:()=>dG,store:()=>sG,fetchSuccessRate:()=>lG,fetchPrintsPerHour:()=>nG,fetchPrintTimeStats:()=>uG,fetchPrintJobStats:()=>mG,fetchPageStats:()=>cG,fetchById:()=>k0,fetchAll:()=>pG,destroy:()=>yG,bulkStore:()=>oG,bulkDestroy:()=>bG});import{db as vG}from"@stacksjs/database";async function yG($){try{let J=await vG.deleteFrom("receipts").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print log: ${J.message}`);throw J}}async function bG($){if(!$.length)return 0;try{let J=await vG.deleteFrom("receipts").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete receipts: ${J.message}`);throw J}}import{db as D1}from"@stacksjs/database";import{formatDate as zY}from"@stacksjs/orm";function l($){return zY($)}function VY($){if($ instanceof Date)return Number.isNaN($.getTime())?null:$;if(typeof $==="number"){let X=new Date($<=2147483647?$*1000:$);return Number.isNaN(X.getTime())?null:X}let J=String($||"").trim();if(!J)return null;if(/^\d{10}$/.test(J)){let X=new Date(Number(J)*1000);return Number.isNaN(X.getTime())?null:X}let G=new Date(J.includes("T")?J:`${J.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function k0($){return await D1.selectFrom("receipts").where("id","=",$).selectAll().executeTakeFirst()}async function pG(){return await D1.selectFrom("receipts").selectAll().execute()}async function mG($,J){let G=l($),X=l(J),Z=await I("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"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning,averageSize:Math.round(Z.averageSize),averagePages:Math.round(Z.averagePages),averageDuration:Math.round(Z.averageDuration)}}async function lG($,J){let G=l($),X=l(J),Z=await I("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"}}},(K)=>K.where("timestamp",">=",G).where("timestamp","<=",X));return{successRate:Z.total>0?Math.round(Z.success/Z.total*100):0,total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning}}async function cG($,J){let G=l($),X=l(J),Z=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{totalPages:Z.totalPages,averagePagesPerReceipt:Math.round(Z.averagePagesPerReceipt),totalReceipts:Z.totalReceipts}}async function uG($,J){let G=l($),X=l(J),Z=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{averageDuration:Math.round(Z.averageDuration),minDuration:Z.minDuration,maxDuration:Z.maxDuration,totalJobs:Z.totalJobs}}async function nG($,J){let G=typeof $==="number"?$:$.getTime(),X=typeof J==="number"?J:J.getTime(),Z=l($),Y=l(J),K=await D1.selectFrom("receipts").where("timestamp",">=",Z).where("timestamp","<=",Y).selectAll().execute(),W=K.length,Q=Math.ceil((X-G)/3600000),L=Q>0?Math.round(W/Q):0,N=Array.from({length:24},(H,z)=>({hour:z,count:0}));return K.forEach((H)=>{let z=VY(H.timestamp);if(!z)return;N[z.getHours()].count++}),{totalPrints:W,totalHours:Q,printsPerHour:L,hourlyBreakdown:N}}var{randomUUIDv7:iG}=globalThis.Bun;import{db as c$}from"@stacksjs/database";import{formatDate as v1}from"@stacksjs/orm";function t0($){try{if(typeof $==="number")return v1($<=2147483647?$*1000:$);if(typeof $==="string"&&/^\d{10}$/.test($))return v1(Number($)*1000);return v1($)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function sG($){try{let J=iG(),G={...$,timestamp:t0($.timestamp),uuid:J};await c$.insertInto("receipts").values(G).executeTakeFirst();let X=await c$.selectFrom("receipts").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipt: ${J.message}`);throw J}}async function oG($){if(!$.length)return 0;try{let J=$.map((Z)=>({...Z,timestamp:t0(Z.timestamp),uuid:iG()})),X=await c$.insertInto("receipts").values(J).executeTakeFirst()??{};return Number(X.numInsertedOrUpdatedRows??X.numAffectedRows??X.affectedRows??X.changes??0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${J.message}`);throw J}}import{db as y1}from"@stacksjs/database";import{formatDate as b1}from"@stacksjs/orm";async function dG($,J){try{if(!$)throw Error("Receipt ID is required for update");let G={...J,...J.timestamp===void 0?{}:{timestamp:t0(J.timestamp)},updated_at:b1(new Date)};await y1.updateTable("receipts").set(G).where("id","=",$).execute();let X=await k0($);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function aG($,J){try{await y1.updateTable("receipts").set({status:J,updated_at:b1(new Date)}).where("id","=",$).execute();let G=await k0($);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function rG($,J,G,X){try{let Z={updated_at:b1(new Date)};if(J!==void 0)Z.size=J;if(G!==void 0)Z.pages=G;if(X!==void 0)Z.duration=X;await y1.updateTable("receipts").set(Z).where("id","=",$).execute();let Y=await k0($);if(!Y)throw Error("Failed to update receipt job information");return Y}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update receipt job information: ${Z.message}`);throw Z}}var L7={};B(L7,{zones:()=>j4,tracking:()=>S4,routes:()=>d$,rates:()=>x4,methods:()=>F4,licenses:()=>K4,geocoding:()=>X4,drivers:()=>e$,digital:()=>r$,default:()=>pY});var d$={};B(d$,{validateDeliveryRouteWrite:()=>w0,updateStops:()=>WX,updateMetrics:()=>QX,updateLastActive:()=>YX,update:()=>KX,store:()=>ZX,fetchById:()=>n$,fetchByDriver:()=>XX,fetchAll:()=>JX,fetchActive:()=>GX,destroy:()=>eG,bulkDestroy:()=>$X,DeliveryRouteInputError:()=>h});import{db as tG}from"@stacksjs/database";async function eG($){try{let J=await tG.deleteFrom("delivery_routes").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery route: ${J.message}`);throw J}}async function $X($){if(!$.length)return 0;try{let J=await tG.deleteFrom("delivery_routes").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery routes: ${J.message}`);throw J}}import{db as u$}from"@stacksjs/database";async function n$($){return await u$.selectFrom("delivery_routes").where("id","=",$).selectAll().executeTakeFirst()}async function JX(){return await u$.selectFrom("delivery_routes").selectAll().execute()}async function GX(){return await u$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function XX($){return await u$.selectFrom("delivery_routes").where("driver","=",$).selectAll().execute()}var{randomUUIDv7:MY}=globalThis.Bun;import{db as m1}from"@stacksjs/database";function x0($,J){let G={};for(let[X,Z]of Object.entries(J))for(let Y of Z){if(!Object.prototype.hasOwnProperty.call($,Y)||$[Y]===void 0)continue;G[X]=$[Y];break}return G}function e0($){return x0($,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function $0($){return x0($,{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 $$($){return x0($,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function J$($){return x0($,{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 G$($){return x0($,{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 X$($){return x0($,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function i$($){return x0($,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as xY}from"@stacksjs/database";class h extends TypeError{constructor($){super($);this.name="DeliveryRouteInputError"}}function s$($,J,G){return Number($[G]??J?.[G])}function BY($,J){let G=$.last_active??J?.last_active;if(G===void 0||G===null)return Date.now();if(G instanceof Date)return G.getTime();if(typeof G==="number")return G;if(typeof G==="string"&&/^\d{10,13}$/.test(G))return Number(G);return Number.NaN}async function w0($,J){let G=s$($,J,"driver_id"),X=s$($,J,"stops"),Z=s$($,J,"delivery_time"),Y=s$($,J,"total_distance"),K=BY($,J);if(!Number.isSafeInteger(G)||G<1)throw new h("Driver must be a positive integer.");if(!Number.isSafeInteger(X)||X<0)throw new h("Stops must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new h("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(Y)||Y<0)throw new h("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(K)||K<0)throw new h("Last active must be a valid Unix timestamp.");let W=await xY.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!W)throw new h(`Driver ${G} was not found.`);return{...$,driver_id:Number(W.id),driver:W.name,vehicle:W.vehicle_number,last_active:K}}async function ZX($){try{let J=MY(),G=i$($),Z={...await w0(G),uuid:J};await m1.insertInto("delivery_routes").values(Z).executeTakeFirst();let Y=await m1.selectFrom("delivery_routes").where("uuid","=",J).selectAll().executeTakeFirst();if(!Y)throw Error("Failed to create delivery route");return Y}catch(J){if(J instanceof h)throw J;if(J instanceof Error)throw TypeError(`Failed to create delivery route: ${J.message}`);throw J}}async function YX($){try{await m1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",$).execute();let J=await n$($);if(!J)throw Error("Failed to update delivery route last active");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route last active: ${J.message}`);throw J}}import{db as o$}from"@stacksjs/database";import{formatDate as l1}from"@stacksjs/orm";async function KX($,J){try{if(!$)throw Error("Delivery route ID is required for update");let G=await o$.selectFrom("delivery_routes").where("id","=",$).selectAll().executeTakeFirst();if(!G)return;let X=i$(J),Z=await w0(X,G),Y=await o$.updateTable("delivery_routes").set({...Z,updated_at:l1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof h)throw G;if(G instanceof Error)throw TypeError(`Failed to update delivery route: ${G.message}`);throw G}}async function WX($,J){try{let G=await o$.updateTable("delivery_routes").set({stops:J,updated_at:l1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update delivery route stops");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery route stops: ${G.message}`);throw G}}async function QX($,J,G){try{let X={updated_at:l1(new Date)};if(J!==void 0)X.delivery_time=J;if(G!==void 0)X.total_distance=G;let Z=await o$.updateTable("delivery_routes").set(X).where("id","=",$).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update delivery metrics");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery metrics: ${X.message}`);throw X}}var r$={};B(r$,{updateStatus:()=>AX,updateDeliverySettings:()=>UX,update:()=>OX,store:()=>MX,softDelete:()=>FX,fetchById:()=>VX,fetchAll:()=>xX,destroy:()=>LX,bulkStore:()=>_X,bulkSoftDelete:()=>HX,bulkDestroy:()=>NX});import{db as a$}from"@stacksjs/database";async function LX($){try{let J=await a$.deleteFrom("digital_deliveries").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital delivery: ${J.message}`);throw J}}async function FX($){try{let J=await a$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${J.message}`);throw J}}async function NX($){if(!$.length)return 0;try{let J=await a$.deleteFrom("digital_deliveries").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${J.message}`);throw J}}async function HX($){if(!$.length)return 0;try{let J=await a$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${J.message}`);throw J}}import{db as zX}from"@stacksjs/database";async function VX($){return await zX.selectFrom("digital_deliveries").where("id","=",$).selectAll().executeTakeFirst()}async function xX(){return await zX.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:BX}=globalThis.Bun;import{asRow as _Y,db as c1}from"@stacksjs/database";async function MX($){try{let J=BX(),G={...J$($),uuid:J};await c1.insertInto("digital_deliveries").values(G).executeTakeFirst();let X=await c1.selectFrom("digital_deliveries").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created digital delivery");return _Y(X)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital delivery: ${J.message}`);throw J}}async function _X($){if(!$.length)return 0;try{let J=$.map((X)=>({...J$(X),uuid:BX()})),G=await c1.insertInto("digital_deliveries").values(J).executeTakeFirst();return F(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${J.message}`);throw J}}import{db as u1}from"@stacksjs/database";import{formatDate as n1}from"@stacksjs/orm";async function OX($,J){try{if(!$)throw Error("Digital delivery ID is required for update");let G=await u1.updateTable("digital_deliveries").set({...J$(J),updated_at:n1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery: ${G.message}`);throw G}}async function AX($,J){try{let G=await u1.updateTable("digital_deliveries").set({status:J,updated_at:n1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update digital delivery status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery status: ${G.message}`);throw G}}async function UX($,J,G,X,Z){try{let Y={updated_at:n1(new Date)};if(J!==void 0)Y.download_limit=J;if(G!==void 0)Y.expiry_days=G;if(X!==void 0)Y.requires_login=X;if(Z!==void 0)Y.automatic_delivery=Z;let K=await u1.updateTable("digital_deliveries").set(Y).where("id","=",$).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update delivery settings");return K}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery settings: ${Y.message}`);throw Y}}var e$={};B(e$,{updateStatus:()=>fX,updateContact:()=>CX,update:()=>wX,store:()=>qX,fetchById:()=>t$,fetchAll:()=>SX,destroy:()=>EX,bulkStore:()=>kX,bulkDestroy:()=>TX});import{db as PX}from"@stacksjs/database";import{db as RX}from"@stacksjs/database";async function t$($){return await RX.selectFrom("drivers").where("id","=",$).selectAll().executeTakeFirst()}async function SX(){return await RX.selectFrom("drivers").selectAll().execute()}async function EX($){try{let J=await PX.deleteFrom("drivers").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete driver: ${J.message}`);throw J}}async function TX($){if(!$.length)return 0;let J=0;try{return await PX.transaction().execute(async(G)=>{for(let X of $)if(await t$(X))await G.deleteFrom("drivers").where("id","=",X).execute(),J++}),J}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${G.message}`);throw G}}var{randomUUIDv7:jX}=globalThis.Bun;import{db as i1}from"@stacksjs/database";async function qX($){try{let J=jX(),G={...X$($),uuid:J};await i1.insertInto("drivers").values(G).executeTakeFirst();let X=await i1.selectFrom("drivers").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created driver");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create driver: ${J.message}`);throw J}}async function kX($){if(!$.length)return 0;try{let J=$.map((X)=>({...X$(X),uuid:jX()})),G=await i1.insertInto("drivers").values(J).executeTakeFirst();return F(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${J.message}`);throw J}}import{db as s1}from"@stacksjs/database";import{formatDate as o1}from"@stacksjs/orm";async function wX($,J){try{if(!$)throw Error("Driver ID is required for update");let G=await s1.updateTable("drivers").set({...X$(J),updated_at:o1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver: ${G.message}`);throw G}}async function fX($,J){try{let G=await s1.updateTable("drivers").set({status:J,updated_at:o1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update driver status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver status: ${G.message}`);throw G}}async function CX($,J){try{let G={updated_at:o1(new Date)};if(J!==void 0)G.phone=J;let X=await s1.updateTable("drivers").set(G).where("id","=",$).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update contact information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update contact information: ${G.message}`);throw G}}var X4={};B(X4,{setGeocodingDriver:()=>RY,nominatimDriver:()=>G4,geocodingDriver:()=>yX,geocode:()=>SY,formatQuery:()=>f0,checkCoverage:()=>PY,PRECISION_RANK:()=>Y$});var B0=($)=>$*Math.PI/180;function W0($,J){let G=B0(J.latitude-$.latitude),X=B0(J.longitude-$.longitude),Z=B0($.latitude),Y=B0(J.latitude),K=Math.sin(G/2)**2+Math.sin(X/2)**2*Math.cos(Z)*Math.cos(Y);return 12742017.6*Math.asin(Math.sqrt(K))}function $4($,J){let G=B0($.latitude),X=B0(J.latitude),Z=B0(J.longitude-$.longitude),Y=Math.sin(Z)*Math.cos(X),K=Math.cos(G)*Math.sin(X)-Math.sin(G)*Math.cos(X)*Math.cos(Z);return(Math.atan2(Y,K)*180/Math.PI+360)%360}function J4($,J,G={}){let X=G.detourFactor??1.35,Z=G.minimumSeconds??30;if(!Number.isFinite(J)||J<=0.5)return null;let Y=$*X/J;return Math.max(Z,Math.round(Y))}function hX($,J,G){return W0($,J)<=G}function Z$($){return typeof $?.latitude==="number"&&typeof $?.longitude==="number"&&Number.isFinite($.latitude)&&Number.isFinite($.longitude)}var Y$={unknown:0,locality:1,postal:2,street:3,rooftop:4};function f0($){return[$.street,$.city,$.region,$.postalCode,$.country].map((J)=>String(J??"").trim()).filter(Boolean).join(", ")}var OY="https://nominatim.openstreetmap.org/search",IX=1000,gX=0,DX=Promise.resolve();async function AY($){let J=DX.then(async()=>{let G=Date.now()-gX;if(G<IX)await Bun.sleep(IX-G);return gX=Date.now(),$()});return DX=J.then(()=>{return},()=>{return}),J}function UY($){let J=$.address??{},G=String($.addresstype??""),X=String($.type??""),Z=String($.category??$.class??"");if(J.house_number||X==="house"||X==="building"||G==="building")return"rooftop";if(J.road||Z==="highway"||G==="road")return"street";if(G==="postcode"||J.postcode&&!J.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(G))return"locality";return"unknown"}function G4($={}){let J=$.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,G=$.endpoint??OY;return{name:"nominatim",async geocode(X){let Z=f0(X);if(!Z)return null;let Y=new URL(G);if(Y.searchParams.set("q",Z),Y.searchParams.set("format","jsonv2"),Y.searchParams.set("limit","1"),Y.searchParams.set("addressdetails","1"),X.country)Y.searchParams.set("countrycodes",X.country.toLowerCase());let K=await AY(()=>fetch(Y,{headers:{"user-agent":J,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!K.ok)throw Error(`Nominatim responded ${K.status}`);let Q=(await K.json())?.[0];if(!Q)return null;let L=Number(Q.lat),N=Number(Q.lon);if(!Number.isFinite(L)||!Number.isFinite(N))return null;let H=UY(Q);return{latitude:L,longitude:N,formatted:String(Q.display_name??Z),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[H],precision:H,provider:"nominatim"}}}}var vX=null;function RY($){vX=$}function yX(){return vX??G4()}async function SY($,J={}){let G=J.driver??yX(),X=J.minimumPrecision??"street",Z=`geocode:${G.name}:${f0($).toLowerCase()}`,Y=await EY(Z);if(Y!==void 0)return Y;let K=await G.geocode($),W=K&&Y$[K.precision]>=Y$[X]?K:null;return await TY(Z,W,W?J.cacheSeconds??2592000:600),W}function PY($,J,G){if(J.length===0)return null;let X=J[0],Z=W0($,X);for(let Y of J.slice(1)){let K=W0($,Y);if(K<Z)Z=K,X=Y}return{covered:Z<=G,distanceMeters:Math.round(Z),nearest:X}}async function EY($){try{let G=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!G)return;let X=await G.get($);if(X===null||X===void 0)return;return X==="null"?null:JSON.parse(String(X))}catch{return}}async function TY($,J,G){try{let Z=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!Z)return;await Z.set($,J===null?"null":JSON.stringify(J),G)}catch{}}var K4={};B(K4,{validateLicenseKeyWrite:()=>M0,updateStatus:()=>tX,updateExpiration:()=>eX,update:()=>rX,store:()=>dX,softDelete:()=>pX,fetchById:()=>uX,fetchAll:()=>nX,destroy:()=>bX,bulkStore:()=>aX,bulkSoftDelete:()=>lX,bulkDestroy:()=>mX,LicenseKeyInputError:()=>T});import{db as Z4}from"@stacksjs/database";async function bX($){try{let J=await Z4.deleteFrom("license_keys").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license key: ${J.message}`);throw J}}async function pX($){try{let J=await Z4.updateTable("license_keys").set({status:"inactive"}).where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license key: ${J.message}`);throw J}}async function mX($){if(!$.length)return 0;try{let J=await Z4.deleteFrom("license_keys").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license keys: ${J.message}`);throw J}}async function lX($){if(!$.length)return 0;try{let J=await Z4.updateTable("license_keys").set({status:"inactive"}).where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license keys: ${J.message}`);throw J}}import{db as cX}from"@stacksjs/database";async function uX($){return await cX.selectFrom("license_keys").where("id","=",$).selectAll().executeTakeFirst()}async function nX(){return await cX.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:oX}=globalThis.Bun;import{asRow as qY,db as r1}from"@stacksjs/database";import{db as d1}from"@stacksjs/database";var iX=["Standard License","Premium License","Enterprise License"],sX=["active","inactive","unassigned"];class T extends TypeError{constructor($){super($);this.name="LicenseKeyInputError"}}function K$($,J,G){return $[G]!==void 0?$[G]:J?.[G]}function a1($,J,G,X){let Z=K$($,J,G);if(Z===void 0||Z===null||Z==="")return null;let Y=Number(Z);if(!Number.isSafeInteger(Y)||Y<1)throw new T(`${X} must be a positive integer or null.`);return Y}function jY($){if(typeof $==="number")return $>2147483647?Math.floor($/1000):$;if(typeof $==="string"&&/^\d{10,13}$/.test($))return $.length===13?Math.floor(Number($)/1000):Number($);if(typeof $==="string"){let J=/^\d{4}-\d{2}-\d{2} \d/.test($)?`${$.replace(" ","T")}Z`:$;return Math.floor(new Date(J).getTime()/1000)}return Number.NaN}async function M0($,J){let G=String(K$($,J,"key")||"").trim().toUpperCase(),X=String(K$($,J,"template")||""),Z=String(K$($,J,"status")||""),Y=jY(K$($,J,"expiry_date")),K=a1($,J,"customer_id","Customer"),W=a1($,J,"product_id","Product"),Q=a1($,J,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new T("License key must use five groups of four uppercase letters or numbers.");if(!iX.includes(X))throw new T(`Template must be one of: ${iX.join(", ")}.`);if(!sX.includes(Z))throw new T(`Status must be one of: ${sX.join(", ")}.`);if(!Number.isSafeInteger(Y)||Y<0||Y>2147483647)throw new T("Expiry date must be a Unix timestamp between 1970 and 2038.");let[L,N,H]=await Promise.all([K?d1.selectFrom("customers").where("id","=",K).select("id").executeTakeFirst():null,W?d1.selectFrom("products").where("id","=",W).select("id").executeTakeFirst():null,Q?d1.selectFrom("orders").where("id","=",Q).select(["id","customer_id"]).executeTakeFirst():null]);if(K&&!L)throw new T(`Customer ${K} was not found.`);if(W&&!N)throw new T(`Product ${W} was not found.`);if(Q&&!H)throw new T(`Order ${Q} was not found.`);if(K&&H?.customer_id&&Number(H.customer_id)!==K)throw new T(`Order ${Q} belongs to Customer ${H.customer_id}, not Customer ${K}.`);return{...$,key:G,template:X,expiry_date:Y,status:Z,customer_id:K,product_id:W,order_id:Q}}async function dX($){try{let J=oX(),G=G$($),X={...await M0(G),uuid:J};await r1.insertInto("license_keys").values(X).executeTakeFirst();let Z=await r1.selectFrom("license_keys").where("uuid","=",J).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created license key");return qY(Z)}catch(J){if(J instanceof T)throw J;if(J instanceof Error){if(J.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: ${J.message}`)}throw J}}async function aX($){if(!$.length)return 0;try{let J=await Promise.all($.map(async(X)=>({...await M0(G$(X)),uuid:oX()}))),G=await r1.insertInto("license_keys").values(J).executeTakeFirst();return F(G)}catch(J){if(J instanceof T)throw J;if(J instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${J.message}`);throw J}}import{db as Y4}from"@stacksjs/database";import{formatDate as t1}from"@stacksjs/orm";async function rX($,J){try{if(!$)throw Error("License key ID is required for update");let G=await Y4.selectFrom("license_keys").where("id","=",$).selectAll().executeTakeFirst();if(!G)return;let X=G$(J),Z=await M0(X,G),Y=await Y4.updateTable("license_keys").set({...Z,updated_at:t1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof T)throw G;if(G instanceof Error){if(G.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: ${G.message}`)}throw G}}async function tX($,J){try{let G=await Y4.updateTable("license_keys").set({status:J,updated_at:t1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update license key status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update license key status: ${G.message}`);throw G}}async function eX($,J){try{let G={updated_at:t1(new Date)};if(J!==void 0)G.expiry_date=J;let X=await Y4.updateTable("license_keys").set(G).where("id","=",$).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update expiration information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update expiration information: ${G.message}`);throw G}}var F4={};B(F4,{updateStatus:()=>N9,updatePricing:()=>H9,update:()=>F9,store:()=>K9,softDelete:()=>J9,getActiveShippingMethods:()=>L9,formatShippingOptions:()=>Q9,fetchById:()=>L4,fetchAll:()=>Z9,destroy:()=>$9,bulkStore:()=>W9,bulkSoftDelete:()=>X9,bulkDestroy:()=>G9});import{db as W4}from"@stacksjs/database";async function $9($){try{let J=await W4.deleteFrom("shipping_methods").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping method: ${J.message}`);throw J}}async function J9($){try{let J=await W4.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${J.message}`);throw J}}async function G9($){if(!$.length)return 0;try{let J=await W4.deleteFrom("shipping_methods").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping methods: ${J.message}`);throw J}}async function X9($){if(!$.length)return 0;try{let J=await W4.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${J.message}`);throw J}}import{db as Q4}from"@stacksjs/database";async function L4($){let J=await Q4.selectFrom("shipping_methods").where("id","=",$).selectAll().executeTakeFirst();if(J){let G=await Q4.selectFrom("shipping_zones").where("shipping_method_id","=",$).selectAll().execute();return{...J,shippingZones:G}}return}async function Z9(){let $=await Q4.selectFrom("shipping_methods").selectAll().execute();if($.length===0)return[];let J=[...new Set($.map((Y)=>Y.id))],Z=(await Q4.selectFrom("shipping_zones").where("shipping_method_id","in",J).selectAll().execute()).reduce((Y,K)=>{let W=K.shipping_method_id;if(W!==null&&W!==void 0){if(!Y[W])Y[W]=[];Y[W].push(K)}return Y},{});return $.map((Y)=>({...Y,shipping_zones:Z[Y.id]||[]}))}var{randomUUIDv7:Y9}=globalThis.Bun;import{db as W$}from"@stacksjs/database";async function K9($){try{let J=Y9(),G={...e0($),uuid:J};await W$.insertInto("shipping_methods").values(G).executeTakeFirst();let X=await W$.selectFrom("shipping_methods").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping method");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping method: ${J.message}`);throw J}}async function W9($){if(!$.length)return 0;try{let J=$.map((X)=>({...e0(X),uuid:Y9()})),G=await W$.insertInto("shipping_methods").values(J).executeTakeFirst();return F(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${J.message}`);throw J}}function Q9(){try{return W$.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to format shipping options: ${$.message}`);throw $}}async function L9(){try{return await W$.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get active shipping methods: ${$.message}`);throw $}}import{db as e1}from"@stacksjs/database";import{formatDate as $7}from"@stacksjs/orm";async function F9($,J){try{if(!$)throw Error("Shipping method ID is required for update");let G=await e1.updateTable("shipping_methods").set({...e0(J),updated_at:$7(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method: ${G.message}`);throw G}}async function N9($,J){try{let G=await e1.updateTable("shipping_methods").set({status:J,updated_at:$7(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping method status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method status: ${G.message}`);throw G}}async function H9($,J,G){try{let X={updated_at:$7(new Date)};if(J!==void 0)X.base_rate=J;if(G!==void 0)X.free_shipping=G;let Z=await e1.updateTable("shipping_methods").set(X).where("id","=",$).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update pricing information");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update pricing information: ${X.message}`);throw X}}var x4={};B(x4,{validateZoneMatchesAddress:()=>R9,validateShippingRateWrite:()=>_0,updateByZone:()=>I9,updateByMethod:()=>g9,update:()=>C9,store:()=>w9,resolveZoneForAddress:()=>H4,getShippingRatesByMethod:()=>P9,getRatesByZone:()=>A9,getRateByWeightAndZone:()=>J7,getRateByWeightAndAddress:()=>U9,formatShippingRateOptions:()=>S9,fetchById:()=>_9,fetchAll:()=>O9,destroyByZone:()=>x9,destroyByMethod:()=>B9,destroy:()=>z9,bulkUpdate:()=>h9,bulkStore:()=>f9,bulkDestroy:()=>V9,ShippingRateInputError:()=>f});import{db as N4}from"@stacksjs/database";async function z9($){try{let J=await N4.deleteFrom("shipping_rates").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rate: ${J.message}`);throw J}}async function V9($){if(!$.length)return 0;try{let J=await N4.deleteFrom("shipping_rates").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates: ${J.message}`);throw J}}async function x9($){try{let J=await N4.deleteFrom("shipping_rates").where("shipping_zone_id","=",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${J.message}`);throw J}}async function B9($){try{let J=await N4.deleteFrom("shipping_rates").where("shipping_method_id","=",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${J.message}`);throw J}}import{db as b}from"@stacksjs/database";async function _9($){let J=await b.selectFrom("shipping_rates").where("id","=",$).selectAll().executeTakeFirst();if(J){let G=null,X=null;if(J.shipping_zone_id)G=await b.selectFrom("shipping_zones").where("id","=",J.shipping_zone_id).selectAll().executeTakeFirst();if(J.shipping_method_id)X=await b.selectFrom("shipping_methods").where("id","=",J.shipping_method_id).selectAll().executeTakeFirst();return{...J,shipping_zone:G,shipping_method:X}}return}async function O9(){let $=await b.selectFrom("shipping_rates").selectAll().execute();if($.length===0)return[];let J=[...new Set($.map((W)=>W.shipping_zone_id).filter((W)=>W!==null&&W!==void 0))],G=[...new Set($.map((W)=>W.shipping_method_id).filter((W)=>W!==null&&W!==void 0))],[X,Z]=await Promise.all([J.length?b.selectFrom("shipping_zones").where("id","in",J).selectAll().execute():[],G.length?b.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),Y=X.reduce((W,Q)=>{return W[Q.id]=Q,W},{}),K=Z.reduce((W,Q)=>{return W[Q.id]=Q,W},{});return $.map((W)=>({...W,shipping_zone:W.shipping_zone_id?Y[W.shipping_zone_id]:[],shipping_method:W.shipping_method_id?K[W.shipping_method_id]:[]}))}async function A9($){try{return await b.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${J.message}`);throw J}}async function J7($,J){try{return await b.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).where("weight_from","<=",$).where("weight_to",">=",$).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function H4($){if(!$?.countryCode)return null;try{let J=await b.selectFrom("shipping_zones").selectAll().where("countries","like",`%${$.countryCode}%`).where("status","=","active").execute();if(J.length===0)return null;let G=null;for(let X of J){let Z=1;if($.region&&X.regions&&M9(X.regions,$.region))Z=2;if($.postalCode&&X.postal_codes&&M9(X.postal_codes,$.postalCode))Z=3;if(!G||Z>G.score)G={id:X.id,score:Z}}return G?.id??null}catch{return null}}async function U9($,J){let G=await H4(J);if(G==null)return;return J7($,G)}async function R9($,J){return await H4(J)===$}function M9($,J){if(!$||!J)return!1;let G=J.trim().toUpperCase();for(let X of $.split(/[,|;]/))if(X.trim().toUpperCase()===G)return!0;return!1}async function S9(){try{return(await b.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((J)=>J.shipping_method_id!==null&&J.shipping_method_id!==void 0&&J.shipping_zone_id!==null&&J.shipping_zone_id!==void 0)}catch($){if($ instanceof Error)throw TypeError(`Failed to format shipping rate options: ${$.message}`);throw $}}async function P9($){try{return await b.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",$).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${J.message}`);throw J}}var{randomUUIDv7:k9}=globalThis.Bun;import{db as G7}from"@stacksjs/database";import{db as Q$}from"@stacksjs/database";async function E9(){return await Q$.selectFrom("shipping_zones").selectAll().execute()}async function z4($){return await Q$.selectFrom("shipping_zones").where("id","=",$).selectAll().executeTakeFirst()}function T9(){try{return Q$.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to format shipping zone options: ${$.message}`);throw $}}async function j9(){try{return await Q$.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get active shipping zones: ${$.message}`);throw $}}async function q9($){try{return await Q$.selectFrom("shipping_zones").selectAll().where("countries","like",`%${$}%`).where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${J.message}`);throw J}}class f extends TypeError{constructor($){super($);this.name="ShippingRateInputError"}}function L$($,J,G){return Number($[G]??J?.[G])}async function _0($,J){let G=L$($,J,"shipping_method_id"),X=L$($,J,"shipping_zone_id"),Z=L$($,J,"weight_from"),Y=L$($,J,"weight_to"),K=L$($,J,"rate");if(!Number.isSafeInteger(G)||G<1)throw new f("Shipping method must be a positive integer.");if(!Number.isSafeInteger(X)||X<1)throw new f("Shipping zone must be a positive integer.");if(!Number.isFinite(Z)||Z<0)throw new f("Weight from must be a non-negative number.");if(!Number.isFinite(Y)||Y<Z)throw new f("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(K)||K<0)throw new f("Rate must be a non-negative integer in minor currency units.");let[W,Q]=await Promise.all([L4(G),z4(X)]);if(!W)throw new f(`Shipping method ${G} was not found.`);if(!Q)throw new f(`Shipping zone ${X} was not found.`);if(Number(Q.shipping_method_id)!==G)throw new f(`Shipping zone ${X} is not assigned to shipping method ${G}.`)}async function w9($){try{let J=$0($),G=Number(J.shipping_method_id),X=Number(J.shipping_zone_id);await _0(J);let Z=k9(),Y={...J,shipping_method_id:G,shipping_zone_id:X,uuid:Z};await G7.insertInto("shipping_rates").values(Y).executeTakeFirst();let K=await G7.selectFrom("shipping_rates").where("uuid","=",Z).selectAll().executeTakeFirst();if(!K)throw Error("Failed to resolve created shipping rate");return K}catch(J){if(J instanceof f)throw J;if(J instanceof Error)throw TypeError(`Failed to create shipping rate: ${J.message}`);throw J}}async function f9($){if(!$.length)return 0;try{for(let X of $){let Z=$0(X);await _0(Z)}let J=$.map((X)=>({...$0(X),uuid:k9()})),G=await G7.insertInto("shipping_rates").values(J).executeTakeFirst();return F(G)}catch(J){if(J instanceof f)throw J;if(J instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${J.message}`);throw J}}import{db as F$}from"@stacksjs/database";import{formatDate as V4}from"@stacksjs/orm";async function C9($,J){try{if(!$)throw Error("Shipping rate ID is required for update");let G=await F$.selectFrom("shipping_rates").where("id","=",$).selectAll().executeTakeFirst();if(!G)return;let X=$0(J);await _0(X,G);let Z=await F$.updateTable("shipping_rates").set({...X,updated_at:V4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(G){if(G instanceof f)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function h9($){if(!$.length)return 0;try{let J=0;for(let{id:G,data:X}of $){let Z=await F$.updateTable("shipping_rates").set({...$0(X),updated_at:V4(new Date)}).where("id","=",G).executeTakeFirst();if(F(Z)>0)J++}return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${J.message}`);throw J}}async function I9($,J){try{let G=await F$.updateTable("shipping_rates").set({...$0(J),updated_at:V4(new Date)}).where("shipping_zone_id","=",$).executeTakeFirst();return F(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${G.message}`);throw G}}async function g9($,J){try{let G=await F$.updateTable("shipping_rates").set({...$0(J),updated_at:V4(new Date)}).where("shipping_method_id","=",$).executeTakeFirst();return F(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var S4={};B(S4,{startStop:()=>y9,startRoute:()=>m9,routeTrackingChannel:()=>X7,recordDriverPing:()=>D9,orderTrackingChannel:()=>Q0,isWithin:()=>hX,hasCoordinates:()=>Z$,failStop:()=>p9,estimateSecondsRemaining:()=>J4,emitDeliveryStarted:()=>_4,emitDeliveryPosition:()=>B4,emitDeliveryNearby:()=>O4,emitDeliveryFailed:()=>R4,emitDeliveryCompleted:()=>U4,emitDeliveryAssigned:()=>M4,emitDeliveryArrived:()=>A4,distanceInMeters:()=>W0,completeStop:()=>b9,broadcastToChannel:()=>J0,bearingInDegrees:()=>$4,assignStop:()=>v9,NEARBY_RADIUS_METERS:()=>Z7,ARRIVAL_RADIUS_METERS:()=>Y7});function Q0($){return`order.${$}`}function X7($){return`delivery-route.${$}`}async function C0($,J){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X($,J)}catch{}}async function J0($,J,G){try{let X=await import("@stacksjs/realtime").catch(()=>null);if(!X)return;let Z=X.channel;if(typeof Z!=="function")return;await Z($).broadcast(J,G,"private")}catch{}}async function B4($,J,G){await Promise.all([...$.map((X)=>J0(Q0(X),"delivery:position",G)),J==null?Promise.resolve():J0(X7(J),"delivery:position",G)])}async function M4($){if(await C0("delivery:assigned",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:assigned",{stop:$})}async function _4($){if(await C0("delivery:started",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:started",{stop:$})}async function O4($,J,G){if(await C0("delivery:nearby",{stop:$,distanceMeters:J,etaSeconds:G}),$.order_id!=null)await J0(Q0($.order_id),"delivery:nearby",{stop:$,distanceMeters:J,etaSeconds:G})}async function A4($){if(await C0("delivery:arrived",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:arrived",{stop:$})}async function U4($){if(await C0("delivery:completed",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:completed",{stop:$})}async function R4($,J){await C0("delivery:failed",{stop:$,reason:J})}var{randomUUIDv7:kY}=globalThis.Bun;import{db as p}from"@stacksjs/database";var Z7=400,Y7=60,wY=250;async function D9($){let J=$.recordedAt??new Date().toISOString(),G=typeof $.accuracy!=="number"||$.accuracy<=wY,X=await p.selectFrom("drivers").where("id","=",$.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!X)throw Error(`Unknown driver: ${$.driverId}`);let Z=Z$(X)?{latitude:X.latitude,longitude:X.longitude}:null,Y=typeof $.heading==="number"?$.heading:Z?$4(Z,$):null,K=await fY($.driverId),W=K?await CY(K.id):null,Q=null,L=null,N=!1,H=!1,z=W&&Z$({latitude:W.latitude??void 0,longitude:W.longitude??void 0})?{latitude:W.latitude,longitude:W.longitude}:null;if(G&&W&&z)Q=Math.round(W0($,z)),L=J4(Q,$.speed??0),H=Q<=Y7&&W.arrived_at==null,N=!H&&Q<=Z7&&W.status==="en_route"&&W.notified_nearby_at==null;let x=await hY({driverId:$.driverId,routeId:K?.id??null,latitude:$.latitude,longitude:$.longitude,heading:Y,speed:$.speed??null,accuracy:$.accuracy??null,recordedAt:J});if(G)await p.updateTable("drivers").set({latitude:$.latitude,longitude:$.longitude,heading:Y,speed:$.speed??0,last_ping_at:J}).where("id","=",$.driverId).execute();if(W&&(Q!=null||L!=null))await p.updateTable("delivery_stops").set({eta_at:L==null?W.eta_at:new Date(Date.now()+L*1000).toISOString()}).where("id","=",W.id).execute();if(G)await B4(W?.order_id==null?[]:[W.order_id],K?.id??null,{driverId:$.driverId,routeId:K?.id??null,latitude:$.latitude,longitude:$.longitude,heading:Y,speed:$.speed??null,accuracy:$.accuracy??null,recordedAt:J,distanceToStopMeters:Q,etaSeconds:L});if(N&&W)await p.updateTable("delivery_stops").set({notified_nearby_at:J}).where("id","=",W.id).execute(),await O4(W,Q,L);if(H&&W)await p.updateTable("delivery_stops").set({status:"arrived",arrived_at:J}).where("id","=",W.id).execute(),await A4({...W,status:"arrived",arrived_at:J});return{pingId:x,routeId:K?.id??null,stopId:W?.id??null,distanceToStopMeters:Q,etaSeconds:L,crossedNearby:N,crossedArrival:H}}async function fY($){return await p.selectFrom("delivery_routes").where("driver_id","=",$).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function CY($){let J=await p.selectFrom("delivery_stops").where("delivery_route_id","=",$).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 J.find((G)=>G.status==="en_route")??J.find((G)=>G.status==="arrived")??J[0]??null}async function hY($){let J=kY();return await p.insertInto("driver_pings").values({uuid:J,driver_id:$.driverId,delivery_route_id:$.routeId,latitude:$.latitude,longitude:$.longitude,heading:$.heading,speed:$.speed??0,accuracy:$.accuracy,recorded_at:$.recordedAt}).executeTakeFirst(),(await p.selectFrom("driver_pings").where("uuid","=",J).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:IY}=globalThis.Bun;import{db as j}from"@stacksjs/database";async function v9($){let J=IY(),G=$.sequence??await DY($.deliveryRouteId);await j.insertInto("delivery_stops").values({uuid:J,delivery_route_id:$.deliveryRouteId,order_id:$.orderId??null,sequence:G,status:"pending",address:$.address,latitude:$.latitude??null,longitude:$.longitude??null,recipient_name:$.recipientName??null,recipient_phone:$.recipientPhone??null,eta_at:$.etaAt??null}).executeTakeFirst();let X=await yY(J);if(X)await M4(X);return X??{}}async function y9($){await j.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",$).execute();let J=await W7($);if(!J)return null;if(J.order_id!=null)await K7(J.order_id,"OUT_FOR_DELIVERY");return await _4(J),J}async function b9($,J){let G=new Date().toISOString();await j.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await vY($)?{}:{arrived_at:G},...J?{notes:J}:{}}).where("id","=",$).execute();let X=await W7($);if(!X)return null;if(X.order_id!=null)await K7(X.order_id,"DELIVERED");return await U4(X),await l9(X.delivery_route_id),X}async function p9($,J){await j.updateTable("delivery_stops").set({status:"failed",notes:J}).where("id","=",$).execute();let G=await W7($);if(!G)return null;if(G.order_id!=null)await K7(G.order_id,"SHIPPED");return await R4(G,J),await l9(G.delivery_route_id),G}async function m9($){await j.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",$).execute()}async function l9($){if($==null)return;if(await j.selectFrom("delivery_stops").where("delivery_route_id","=",$).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let G=await j.selectFrom("delivery_routes").where("id","=",$).select(["driver_id"]).executeTakeFirst();if(await j.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",$).execute(),G?.driver_id!=null)await j.updateTable("drivers").set({status:"active"}).where("id","=",G.driver_id).execute()}async function K7($,J){let G=await j.selectFrom("orders").where("id","=",$).select(["id","status"]).executeTakeFirst();if(!G)return;let X=await Promise.resolve().then(() => (P0(),x6)),{canTransition:Z,emitForStatus:Y}=X,K=gY(G.status,J,Z);if(K.length===0){let{log:W}=await import("@stacksjs/logging").catch(()=>({log:null}));W?.warn(`[delivery] refused to move order ${$} from ${G.status} to ${J}: no legal transition`);return}for(let W of K)await j.updateTable("orders").set({status:W}).where("id","=",$).execute(),await Y(W,{...G,status:W})}function gY($,J,G){if($===J)return[];if(G($,J))return[J];for(let X of["PROCESSING","SHIPPED"]){if(X===$||X===J)continue;if(G($,X)&&G(X,J))return[X,J]}return[]}async function DY($){return(await j.selectFrom("delivery_stops").where("delivery_route_id","=",$).select(["sequence"]).execute()).reduce((G,X)=>Math.max(G,X.sequence??0),0)+1}async function vY($){return(await j.selectFrom("delivery_stops").where("id","=",$).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function W7($){return await j.selectFrom("delivery_stops").where("id","=",$).selectAll().executeTakeFirst()??null}async function yY($){return await j.selectFrom("delivery_stops").where("uuid","=",$).selectAll().executeTakeFirst()??null}var j4={};B(j4,{updateStatus:()=>r9,updateRegionsAndPostalCodes:()=>e9,updateCountries:()=>t9,update:()=>a9,store:()=>o9,softDelete:()=>u9,getZonesByCountry:()=>q9,getActiveShippingZones:()=>j9,formatZoneOptions:()=>T9,fetchById:()=>z4,fetchAll:()=>E9,destroy:()=>c9,bulkStore:()=>d9,bulkSoftDelete:()=>i9,bulkDestroy:()=>n9});import{db as P4}from"@stacksjs/database";async function c9($){try{let J=await P4.deleteFrom("shipping_zones").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zone: ${J.message}`);throw J}}async function u9($){try{let J=await P4.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${J.message}`);throw J}}async function n9($){if(!$.length)return 0;try{let J=await P4.deleteFrom("shipping_zones").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zones: ${J.message}`);throw J}}async function i9($){if(!$.length)return 0;try{let J=await P4.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${J.message}`);throw J}}var{randomUUIDv7:s9}=globalThis.Bun;import{db as Q7}from"@stacksjs/database";async function o9($){try{let J=s9(),G={...$$($),uuid:J};await Q7.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await Q7.selectFrom("shipping_zones").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping zone");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zone: ${J.message}`);throw J}}async function d9($){if(!$.length)return 0;try{let J=$.map((X)=>({...$$(X),uuid:s9()})),G=await Q7.insertInto("shipping_zones").values(J).executeTakeFirst();return F(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${J.message}`);throw J}}import{db as E4}from"@stacksjs/database";import{formatDate as T4}from"@stacksjs/orm";async function a9($,J){try{if(!$)throw Error("Shipping zone ID is required for update");let G=await E4.updateTable("shipping_zones").set({...$$(J),updated_at:T4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone: ${G.message}`);throw G}}async function r9($,J){try{let G=await E4.updateTable("shipping_zones").set({status:J,updated_at:T4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone status: ${G.message}`);throw G}}async function t9($,J){try{let G=await E4.updateTable("shipping_zones").set({countries:J,updated_at:T4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone countries");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${G.message}`);throw G}}async function e9($,J,G){try{let X={updated_at:T4(new Date)};if(J!==void 0)X.regions=J;if(G!==void 0)X.postal_codes=G;let Z=await E4.updateTable("shipping_zones").set(X).where("id","=",$).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update regions and postal codes");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${X.message}`);throw X}}var bY={digital:r$,drivers:e$,geocoding:X4,licenses:K4,methods:F4,rates:x4,routes:d$,tracking:S4,zones:j4},pY=bY;var H7={};B(H7,{updateStatus:()=>H3,updateRate:()=>z3,updateDefaultStatus:()=>V3,update:()=>N3,taxFor:()=>$3,store:()=>L3,fetchById:()=>Y3,fetchAll:()=>K3,destroy:()=>G3,bulkStore:()=>F3,bulkDestroy:()=>X3,breakdownFor:()=>N7,activeTaxRates:()=>F7});import{db as mY}from"@stacksjs/database";function lY($){let J=Number($);return Number.isFinite(J)?J/100:0}async function F7($={}){let J=mY.selectFrom("tax_rates").where("status","=","active").selectAll();if($.country)J=J.where("country","=",$.country);let G=await J.execute();if(!$.codes?.length)return G;let X=new Set($.codes);return G.filter((Z)=>X.has(String(Z.code??"")))}function N7($,J,G={}){let X=Math.max(0,Math.round($)),Z=[],Y=0,K=0;for(let W of J){let Q=lY(W.rate),L=Math.round(X*Q),N=Boolean(G.exempt&&W.exemptible);if(N)K+=L;else Y+=L;Z.push({id:Number(W.id),code:String(W.code??""),name:String(W.name??""),rate:Q,amount:N?0:L,exempted:N})}return{taxable:X,components:Z,tax:Y,exempted:K}}async function $3($,J={}){return N7($,await F7(J),J)}import{db as J3}from"@stacksjs/database";async function G3($){try{let J=await J3.deleteFrom("tax_rates").where("id","=",$).executeTakeFirst();return F(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rate: ${J.message}`);throw J}}async function X3($){if(!$.length)return 0;try{let J=await J3.deleteFrom("tax_rates").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rates: ${J.message}`);throw J}}import{db as Z3}from"@stacksjs/database";async function Y3($){return await Z3.selectFrom("tax_rates").where("id","=",$).selectAll().executeTakeFirst()}async function K3(){return await Z3.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:W3}=globalThis.Bun;import{db as Q3}from"@stacksjs/database";async function L3($){try{return await Q3.transaction(async(J)=>{let G={...$,uuid:W3()};if(G.is_default)await J.updateTable("tax_rates").set({is_default:!1}).execute();let X=await J.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X})}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rate: ${J.message}`);throw J}}async function F3($){if(!$.length)return 0;try{return await Q3.transaction(async(J)=>{let G=0;for(let X of $){let Z={...X,uuid:W3()};if(Z.is_default)await J.updateTable("tax_rates").set({is_default:!1}).execute();if(await J.insertInto("tax_rates").values(Z).executeTakeFirst())G++}return G})}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${J.message}`);throw J}}import{db as q4}from"@stacksjs/database";import{formatDate as k4}from"@stacksjs/orm";async function N3($,J){try{if(!$)throw Error("Tax rate ID is required for update");return await q4.transaction(async(G)=>{let X=await G.selectFrom("tax_rates").select("is_default").where("id","=",$).executeTakeFirst();if(!X)return;let Z=J.is_default??Boolean(X.is_default),Y=k4(new Date);if(Z)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Y}).where("id","!=",$).execute();let K=await G.updateTable("tax_rates").set({...J,updated_at:Y}).where("id","=",$).returningAll().executeTakeFirst();if(!K)return;return K})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function H3($,J){try{let G=await q4.updateTable("tax_rates").set({status:J,updated_at:k4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update tax rate status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate status: ${G.message}`);throw G}}async function z3($,J){try{let G=await q4.updateTable("tax_rates").set({rate:J,updated_at:k4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update rate information");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update rate information: ${G.message}`);throw G}}async function V3($,J){try{return await q4.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",$).executeTakeFirst())return!1;let Z=k4(new Date);if(J)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Z}).where("id","!=",$).execute();return await G.updateTable("tax_rates").set({is_default:J,updated_at:Z}).where("id","=",$).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var _7={};B(_7,{restaurant:()=>I0,products:()=>f4,default:()=>tY});var f4={};B(f4,{updateStatus:()=>I3,updatePartySize:()=>g3,update:()=>w4,store:()=>C3,fetchWaiting:()=>E3,fetchPurchasedBetweenDates:()=>S3,fetchNotifiedBetweenDates:()=>R3,fetchCountByStatus:()=>T3,fetchCountBySource:()=>_3,fetchCountByQuantity:()=>A3,fetchCountByDateGrouped:()=>k3,fetchCountByDate:()=>O3,fetchCountByAllQuantities:()=>U3,fetchCountBetweenDates:()=>q3,fetchConversionRates:()=>j3,fetchCancelledBetweenDates:()=>P3,fetchById:()=>N$,fetchAll:()=>M3,destroy:()=>x3,bulkStore:()=>h3,bulkDestroy:()=>B3});import{db as z7}from"@stacksjs/database";async function x3($){try{let J=await z7.selectFrom("waitlist_products").where("id","=",$).selectAll().executeTakeFirst();if(!J)return;return await z7.deleteFrom("waitlist_products").where("id","=",$).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist product: ${J.message}`);throw J}}async function B3($){if(!$.length)return 0;try{let J=await z7.deleteFrom("waitlist_products").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${J.message}`);throw J}}import{db as A}from"@stacksjs/database";import{formatDate as E}from"@stacksjs/orm";async function N$($){return await A.selectFrom("waitlist_products").where("id","=",$).selectAll().executeTakeFirst()}async function M3(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function _3($,J){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if($&&J){let Z=E($),Y=E(J);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{source:Y,count:K})=>{return Z[Y]=K,Z},{})}async function O3($=new Date){let J=new Date($);J.setHours(0,0,0,0);let G=new Date($);G.setHours(23,59,59,999);let X=E(J),Z=E(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function A3($){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",$).executeTakeFirst())?.count??0}async function U3($,J){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if($&&J){let Z=E($),Y=E(J);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{quantity:Y,count:K})=>{return Z[Y]=K,Z},{})}async function R3($,J){let G=E($),X=E(J);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",X).whereNotNull("notified_at").execute()}async function S3($,J){let G=E($),X=E(J);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",X).whereNotNull("purchased_at").execute()}async function P3($,J){let G=E($),X=E(J);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",X).whereNotNull("cancelled_at").execute()}async function E3(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function T3($,J,G){let X=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",$);if(J&&G){let Y=E(J),K=E(G);X=X.where("created_at",">=",Y).where("created_at","<=",K)}return(await X.executeTakeFirst())?.count??0}async function j3($,J){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if($&&J){let Q=E($),L=E(J);G=G.where("created_at",">=",Q).where("created_at","<=",L)}let X=await G.execute(),Z=X.reduce((Q,{count:L})=>Q+L,0),Y=X.find((Q)=>Q.status==="purchased")?.count??0,K=Z>0?Y/Z*100:0,W=X.reduce((Q,{status:L,count:N})=>{return Q[L]={count:N,percentage:Z>0?N/Z*100:0},Q},{});return{totalConversionRate:K,statusBreakdown:W}}async function q3($,J){let G=E($),X=E(J);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function k3($,J){let G=A.selectFrom("waitlist_products").select(["created_at"]);if($&&J){let Y=E($),K=E(J);G=G.where("created_at",">=",Y).where("created_at","<=",K)}let Z=(await G.execute()).reduce((Y,{created_at:K})=>{let W=(K||"").split("T")[0]||"unknown";return Y[W]=(Y[W]||0)+1,Y},{});return Object.entries(Z).map(([Y,K])=>({date:Y,count:K})).sort((Y,K)=>Y.date.localeCompare(K.date))}var{randomUUIDv7:f3}=globalThis.Bun;import{db as V7}from"@stacksjs/database";import{formatDate as w3}from"@stacksjs/orm";var cY={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function uY($){return typeof $==="number"||$ instanceof Date?w3($):$}function H$($,J={}){let G=Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let Z of["notified_at","purchased_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=uY(G[Z]);let X=cY[G.status];if(X&&G[X]===void 0&&!J[X])G[X]=w3(new Date);return G}async function C3($){try{let J=f3(),G={...H$($),uuid:J,status:$.status||"waiting"};await V7.insertInto("waitlist_products").values(G).executeTakeFirst();let X=await V7.selectFrom("waitlist_products").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create waitlist product");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist product: ${J.message}`);throw J}}async function h3($){if(!$.length)return 0;try{let J=$.map((X)=>({...H$(X),status:X.status||"waiting",uuid:f3()})),G=await V7.insertInto("waitlist_products").values(J).executeTakeFirst();return F(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${J.message}`);throw J}}import{db as nY}from"@stacksjs/database";import{formatDate as iY}from"@stacksjs/orm";async function w4($,J){try{if(!$)throw Error("Waitlist product ID is required for update");let G=await N$($);if(!G)return;await nY.updateTable("waitlist_products").set({...H$(J,G),updated_at:iY(new Date)}).where("id","=",$).execute();let X=await N$($);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update waitlist product: ${G.message}`);throw G}}async function I3($,J){return await w4($,{status:J})}async function g3($,J){return await w4($,{quantity:J})}var I0={};B(I0,{updateWaitTimes:()=>WZ,updateStatus:()=>YZ,updateQueuePosition:()=>QZ,updatePartySize:()=>KZ,update:()=>h0,store:()=>XZ,fetchWaitingWithQuotedTimes:()=>o3,fetchWaitingWithPartySizes:()=>d3,fetchWaiting:()=>n3,fetchTimeSeriesStats:()=>JZ,fetchTablesTurnedToday:()=>a3,fetchSeatingRate:()=>r3,fetchSeatedStats:()=>$Z,fetchSeatedBetweenDates:()=>u3,fetchNoShowStats:()=>t3,fetchCurrentWaitTimes:()=>e3,fetchCountByTablePreference:()=>b3,fetchCountByPartySize:()=>m3,fetchCountByDate:()=>p3,fetchCountByAllPartySizes:()=>l3,fetchConversionRates:()=>i3,fetchById:()=>z$,fetchBetweenDates:()=>c3,fetchAverageWaitTimes:()=>s3,fetchAll:()=>y3,destroy:()=>D3,bulkStore:()=>ZZ,bulkDestroy:()=>v3});import{db as x7}from"@stacksjs/database";async function D3($){try{let J=await x7.selectFrom("waitlist_restaurants").where("id","=",$).selectAll().executeTakeFirst();if(!J)return;return await x7.deleteFrom("waitlist_restaurants").where("id","=",$).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${J.message}`);throw J}}async function v3($){if(!$.length)return 0;try{let J=await x7.deleteFrom("waitlist_restaurants").where("id","in",$).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as M}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function z$($){return await M.selectFrom("waitlist_restaurants").where("id","=",$).selectAll().executeTakeFirst()}async function y3(){return await M.selectFrom("waitlist_restaurants").selectAll().execute()}async function b3(){return(await M.selectFrom("waitlist_restaurants").select(["table_preference",M.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((J,{table_preference:G,count:X})=>{return J[G]=X,J},{})}async function p3($=new Date){let J=new Date($);J.setHours(0,0,0,0);let G=new Date($);G.setHours(23,59,59,999);let X=g(J),Z=g(G);return(await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function m3($){return(await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("party_size","=",$).executeTakeFirst())?.count??0}async function l3(){return(await M.selectFrom("waitlist_restaurants").select(["party_size",M.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((J,{party_size:G,count:X})=>{return J[G]=X,J},{})}async function c3($,J){let G=g($),X=g(J);return await M.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",X).execute()}async function u3($,J){let G=g($),X=g(J);return await M.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",X).where("status","=","seated").execute()}async function n3(){return await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function i3(){let $=await M.selectFrom("waitlist_restaurants").select(["status",M.fn.count("id").as("count")]).groupBy("status").execute(),J=$.reduce((Y,{count:K})=>Y+K,0),G=$.find((Y)=>Y.status==="seated")?.count??0,X=J>0?Number(G)/J*100:0,Z=$.reduce((Y,{status:K,count:W})=>{return Y[K]={count:W,percentage:J>0?W/J*100:0},Y},{});return{totalConversionRate:X,statusBreakdown:Z}}async function s3(){let $=await M.selectFrom("waitlist_restaurants").select([M.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),M.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:$?.avg_quoted_wait_time??0,averageActualWaitTime:$?.avg_actual_wait_time??0}}async function o3(){let $=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=$.reduce((X,Z)=>X+(Z.quoted_wait_time??0),0),G=$.length>0?J/$.length:0;return{entries:$,totalQuotedWaitTime:J,averageQuotedWaitTime:G}}async function d3(){let $=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=$.reduce((Z,Y)=>Z+Y.party_size,0),G=$.length>0?J/$.length:0,X=$.reduce((Z,Y)=>{return Z[Y.party_size]=(Z[Y.party_size]||0)+1,Z},{});return{entries:$,totalPartySize:J,averagePartySize:G,partySizeBreakdown:X}}async function a3(){let $=new Date,J=new Date($);J.setHours(0,0,0,0);let G=new Date($);G.setHours(23,59,59,999);let X=g(J),Z=g(G),Y=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",X).where("check_in_time","<=",Z).execute(),K=Y.length,W=Y.reduce((H,z)=>H+z.party_size,0),Q=K>0?W/K:0,L=Y.reduce((H,z)=>{return H[z.table_preference]=(H[z.table_preference]||0)+1,H},{}),N=Y.reduce((H,z)=>{return H[z.party_size]=(H[z.party_size]||0)+1,H},{});return{totalTablesTurned:K,averagePartySize:Q,totalCustomersSeated:W,breakdownByTablePreference:L,breakdownByPartySize:N}}async function r3($,J){let G=g($),X=g(J),Z=await M.selectFrom("waitlist_restaurants").select(["status",M.fn.count("id").as("count")]).where("check_in_time",">=",G).where("check_in_time","<=",X).groupBy("status").execute(),Y=Z.reduce((L,{count:N})=>L+N,0),K=Z.find((L)=>L.status==="seated")?.count??0,W=Y>0?Number(K)/Y*100:0,Q=Z.reduce((L,{status:N,count:H})=>{return L[N]={count:H,percentage:Y>0?H/Y*100:0},L},{});return{totalEntries:Y,seatedEntries:K,seatingRate:W,statusBreakdown:Q}}async function t3($,J){let G=g($),X=g(J),Z=M.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",X),Y=await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",X).executeTakeFirst(),K=await Z.execute(),W=K.length,Q=Y?.count&&Y.count>0?W/Y.count*100:0,L=K.reduce((O,R)=>O+(R.quoted_wait_time??0),0),N=W>0?L/W:0,H=K.reduce((O,R)=>O+R.party_size,0),z=W>0?H/W:0,x=K.reduce((O,R)=>{return O[R.table_preference]=(O[R.table_preference]||0)+1,O},{}),U=K.reduce((O,R)=>{return O[R.party_size]=(O[R.party_size]||0)+1,O},{});return{totalNoShows:W,noShowRate:Q,averageQuotedWaitTime:N,averagePartySize:z,breakdownByTablePreference:x,breakdownByPartySize:U}}async function e3(){let $=await M.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),J=$.reduce((Z,Y)=>Z+(Y.quoted_wait_time||0),0),G=$.reduce((Z,Y)=>Z+(Y.actual_wait_time||0),0),X=$.length;return{averageQuoted:X>0?J/X:0,averageActual:X>0?G/X:0}}async function $Z(){let $=Date.now()-86400000,J=await M.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",$).execute(),G=Array.from({length:24},(X,Z)=>({hour:Z,count:J.filter((Y)=>{return Y.seated_at===Z}).length}));return{total:J.length,byHour:G}}async function JZ(){return(await M.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((J,G)=>{let X=G.created_at;if(!J[X])J[X]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return J[X].total++,J[X][G.status]++,J},{})}var{randomUUIDv7:GZ}=globalThis.Bun;import{db as M7}from"@stacksjs/database";import{formatDate as B7}from"@stacksjs/orm";var sY={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function oY($){if(typeof $==="number")return B7($<=2147483647?$*1000:$);if($ instanceof Date)return B7($);return $}function V$($,J={}){let G=Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0));for(let Z of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=oY(G[Z]);let X=sY[G.status];if(X&&G[X]===void 0&&!J[X])G[X]=B7(new Date);return G}async function XZ($){try{let J=GZ(),G={...V$($),status:$.status||"waiting",uuid:J};await M7.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let X=await M7.selectFrom("waitlist_restaurants").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create restaurant waitlist entry");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${J.message}`);throw J}}async function ZZ($){if(!$.length)return 0;try{let J=$.map((X)=>({...V$(X),status:X.status||"waiting",uuid:GZ()})),G=await M7.insertInto("waitlist_restaurants").values(J).executeTakeFirst();return F(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as dY}from"@stacksjs/database";import{formatDate as aY}from"@stacksjs/orm";async function h0($,J){try{if(!$)throw Error("Restaurant waitlist entry ID is required for update");let G=await z$($);if(!G)return;await dY.updateTable("waitlist_restaurants").set({...V$(J,G),updated_at:aY(new Date)}).where("id","=",$).execute();let X=await z$($);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${G.message}`);throw G}}async function YZ($,J){return await h0($,{status:J})}async function KZ($,J){return await h0($,{party_size:J})}async function WZ($,J,G){return await h0($,{quoted_wait_time:J,...G===void 0?{}:{actual_wait_time:G}})}async function QZ($,J){return await h0($,{queue_position:J})}var rY={products:f4,restaurant:I0},tY=rY;var eY={auctions:Y1,coupons:K1,customers:W1,devices:H1,errors:x1,giftCards:_1,orders:j1,payments:q1,products:g1,receipts:p1,restaurant:I0,shippings:L7,tax:H7,waitlists:_7},IV=eY;export{_7 as waitlists,H7 as tax,L7 as shippings,I0 as restaurant,p1 as receipts,g1 as products,q1 as payments,j1 as orders,_1 as giftCards,x1 as errors,H1 as devices,IV as default,W1 as customers,K1 as coupons,eY as commerce,Y1 as auctions};
|
|
27
|
+
AND COALESCE(refund_amount, 0) + ${X(5)} <= amount`,[J,J,Z,$,J]),K=typeof Y?.execute==="function"?await Y.execute():Y;if(Number(K?.numUpdatedRows??K?.[0]?.numUpdatedRows??K?.numAffectedRows??K?.affectedRows??K?.[0]?.affectedRows??K?.changes??0)>0){let z=await V0($);if(z)return z;throw Error(`Payment with ID ${$} disappeared during refund`)}let Q=await V0($);if(!Q)throw Error(`Payment with ID ${$} not found`);let F=String(Q.status||"");if(!$Y.has(F))throw Error(`Payment status ${F||"unknown"} cannot be refunded`);let N=Q,H=Number(Q.amount||0)-Number(N.refundAmount??N.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${H} minor units`)}var g1={};B(g1,{variants:()=>l$,units:()=>m$,reviews:()=>y$,manufacturers:()=>v$,items:()=>D$,default:()=>zY,categories:()=>g$});var g$={};B(g$,{updateParent:()=>L2,updateDisplayOrder:()=>Q2,updateActiveStatus:()=>F2,update:()=>W2,store:()=>w1,removeChildCategories:()=>G2,remove:()=>$2,findOrCreateByName:()=>K2,fetchStats:()=>r6,fetchRootCategories:()=>o6,fetchChildCategories:()=>d6,fetchCategoryTree:()=>e6,fetchByName:()=>i6,fetchById:()=>w,fetchByDisplayOrder:()=>a6,fetchAll:()=>k1,fetchActive:()=>s6,deactivateChildCategories:()=>Z2,deactivate:()=>X2,compareCategoryGrowth:()=>t6,bulkRemove:()=>J2});import{db as E0}from"@stacksjs/database";import{db as R}from"@stacksjs/database";import{formatDate as d0}from"@stacksjs/orm";async function k1(){return await R.selectFrom("categories").selectAll().execute()}async function w($){return await R.selectFrom("categories").where("id","=",$).selectAll().executeTakeFirst()}async function i6($){return await R.selectFrom("categories").where("name","=",$).selectAll().executeTakeFirst()}async function s6(){return await R.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function o6(){return await R.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function d6($){return await R.selectFrom("categories").where("parent_category_id","=",$).where("is_active","=",!0).selectAll().execute()}async function a6($=!0){let J=R.selectFrom("categories").where("is_active","=",!0).selectAll();if($)return await J.orderBy("display_order","asc").execute();else return await J.orderBy("display_order","desc").execute()}async function r6(){let $=await R.selectFrom("categories").select(R.fn.count("id").as("count")).executeTakeFirst(),J=await R.selectFrom("categories").where("is_active","=",!0).select(R.fn.count("id").as("count")).executeTakeFirst(),G=await R.selectFrom("categories").whereNull("parent_category_id").select(R.fn.count("id").as("count")).executeTakeFirst(),X=await R.selectFrom("categories").whereNotNull("image_url").select(R.fn.count("id").as("count")).executeTakeFirst(),Z=new Date;Z.setDate(Z.getDate()-30);let Y=d0(Z),K=await R.selectFrom("categories").where("created_at",">=",Y).selectAll().limit(5).execute(),W=await R.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",R.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number($?.count||0),active:Number(J?.count||0),root_categories:Number(G?.count||0),child_categories:Number($?.count||0)-Number(G?.count||0),with_images:Number(X?.count||0),recently_added:K,top_parent_categories:W.map((Q)=>({id:String(Q.parent_category_id||""),name:String(Q.parent_name||""),child_count:Number(Q.child_count)}))}}async function t6($=30){let J=new Date,G=d0(J),X=new Date;X.setDate(J.getDate()-$);let Z=d0(X),Y=new Date(X);Y.setDate(Y.getDate()-1);let K=d0(Y),W=new Date(Y);W.setDate(Y.getDate()-$);let Q=d0(W),F=await R.selectFrom("categories").select(R.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",G).executeTakeFirst(),N=await R.selectFrom("categories").select(R.fn.count("id").as("count")).where("created_at",">=",Q).where("created_at","<=",K).executeTakeFirst(),H=Number(F?.count||0),z=Number(N?.count||0),x=H-z,U=z!==0?x/z*100:H>0?100:0;return{current_period:H,previous_period:z,difference:x,percentage_change:U,days_range:$}}async function e6(){let $=await k1(),J=new Map;$.forEach((Z)=>{J.set(Z.id,{...Z,children:[]})});let G=[];$.forEach((Z)=>{let Y=J.get(Z.id);if(Z.parent_category_id){let K=J.get(Z.parent_category_id);if(K)K.children.push(Y)}else G.push(Y)}),G.sort((Z,Y)=>Z.display_order-Y.display_order);let X=(Z)=>{Z.sort((Y,K)=>Y.display_order-K.display_order),Z.forEach((Y)=>{if(Y.children.length>0)X(Y.children)})};return X(G),G}async function $2($){let J=await E0.deleteFrom("categories").where("id","=",$).executeTakeFirst();return L(J)>0}async function J2($){if(!$.length)return 0;let J=await E0.deleteFrom("categories").where("id","in",$).executeTakeFirst();return L(J)}async function G2($){let J=await E0.deleteFrom("categories").where("parent_category_id","=",$).executeTakeFirst();return L(J)}async function X2($){if(!await w($))throw Error(`Category with ID ${$} not found`);return!!await E0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",$).executeTakeFirst()}async function Z2($){let J=await E0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",$).execute();return Number(J.length)||0}var{randomUUIDv7:JY}=globalThis.Bun;import{db as Y2}from"@stacksjs/database";import{HttpError as h$}from"@stacksjs/error-handling";import{isUniqueViolation as GY}from"@stacksjs/orm";import{slug as XY}from"@stacksjs/strings";async function w1($){try{let J=$.parent_category_id?Number($.parent_category_id):void 0;if(J!==void 0&&(!Number.isSafeInteger(J)||J<=0))throw new h$(422,"Parent category ID must be a positive integer");if(J&&!await w(J))throw new h$(422,`Parent category with ID ${$.parent_category_id} not found`);let G={...$,uuid:JY(),is_active:$.is_active??!0,parent_category_id:$.parent_category_id||null},X=await Y2.insertInto("categories").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create category");return X}catch(J){if(J instanceof h$)throw J;if(GY(J))throw new h$(409,"A category with this name or slug already exists");if(J instanceof Error)throw Error(`Failed to create category: ${J.message}`);throw J}}async function K2($){if(!$.name)throw Error("Name is required");let J=await Y2.selectFrom("categories").selectAll().where("name","=",$.name).executeTakeFirst();if(J)return J;let G={name:$.name,slug:XY($.name),is_active:$.is_active??!0,display_order:0};return await w1(G)}import{db as a0}from"@stacksjs/database";import{HttpError as j0}from"@stacksjs/error-handling";import{formatDate as I$,isUniqueViolation as ZY}from"@stacksjs/orm";async function W2($,J){if(!await w($))return;if(Object.hasOwn(J,"parent_category_id")){let X=J.parent_category_id?Number(J.parent_category_id):void 0;if(X!==void 0&&(!Number.isSafeInteger(X)||X<=0))throw new j0(422,"Parent category ID must be a positive integer");if(X===$)throw new j0(422,"A category cannot be its own parent");if(X&&!await w(X))throw new j0(422,`Parent category with ID ${J.parent_category_id} not found`);if(X&&await N2($,String(X)))throw new j0(422,"This operation would create a circular category hierarchy")}try{let X=Object.hasOwn(J,"parent_category_id")?{parent_category_id:J.parent_category_id||null}:{},Z=await a0.updateTable("categories").set({...J,...X,updated_at:I$(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(X){if(X instanceof j0)throw X;if(ZY(X))throw new j0(409,"A category with this name or slug already exists");if(X instanceof Error)throw Error(`Failed to update category: ${X.message}`);throw X}}async function Q2($,J){if(!await w($))throw Error(`Category with ID ${$} not found`);try{return await a0.updateTable("categories").set({display_order:J,updated_at:I$(new Date)}).where("id","=",$).execute(),await w($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category display order: ${X.message}`);throw X}}async function F2($,J){if(!await w($))throw Error(`Category with ID ${$} not found`);try{return await a0.updateTable("categories").set({is_active:J,updated_at:I$(new Date)}).where("id","=",$).execute(),await w($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function L2($,J){if(!await w($))throw Error(`Category with ID ${$} not found`);if(J){let X=Number(J);if(X===$)throw Error("A category cannot be its own parent");if(!await w(X))throw Error(`Parent category with ID ${J} not found`);if(await N2($,J))throw Error("This operation would create a circular reference in the category hierarchy")}try{let X={updated_at:I$(new Date)};if(J===null)await a0.updateTable("categories").set({...X,parent_category_id:null}).where("id","=",$).execute();else await a0.updateTable("categories").set({...X,parent_category_id:J}).where("id","=",$).execute();return await w($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category parent: ${X.message}`);throw X}}async function N2($,J){let G=Number(J),X=new Set;while(G){if(X.has(G))return!0;if(G===$)return!0;X.add(G);let Z=await w(G),Y=Z?.parent_category_id??Z?.parentCategoryId;if(!Z||!Y)return!1;G=Number(Y)}return!1}var D$={};B(D$,{updateInventory:()=>S2,updateAvailability:()=>P2,update:()=>U2,store:()=>O2,fetchTopProducts:()=>B2,fetchById:()=>t,fetchAll:()=>x2,destroy:()=>z2,bulkStore:()=>A2,bulkDestroy:()=>V2});import{db as H2}from"@stacksjs/database";async function z2($){try{let J=await H2.deleteFrom("products").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product item: ${J.message}`);throw J}}async function V2($){if(!$.length)return 0;try{let J=await H2.deleteFrom("products").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product items: ${J.message}`);throw J}}import{db as K0,sql as YY}from"@stacksjs/database";async function t($){let J=await K0.selectFrom("products").where("id","=",$).selectAll().executeTakeFirst();if(J){let G=null,X=null;if(J.manufacturer_id)G=await K0.selectFrom("manufacturers").where("id","=",J.manufacturer_id).selectAll().executeTakeFirst();if(J.category_id)X=await K0.selectFrom("categories").where("id","=",J.category_id).selectAll().executeTakeFirst();return{...J,manufacturer:G,category:X}}return}async function x2(){let $=await K0.selectFrom("products").selectAll().execute(),J=$.map((F)=>F.manufacturer_id).filter((F)=>F!==null&&F!==void 0),G=$.map((F)=>F.category_id).filter((F)=>F!==null&&F!==void 0),X=K0.selectFrom("manufacturers"),Z=K0.selectFrom("categories");if(J.length>0)X=X.where("id","in",J);if(G.length>0)Z=Z.where("id","in",G);let Y=await X.selectAll().execute(),K=await Z.selectAll().execute(),W=Y.reduce((F,N)=>{return F[N.id]=N,F},{}),Q=K.reduce((F,N)=>{return F[N.id]=N,F},{});return $.map((F)=>({...F,manufacturer:F.manufacturer_id?W[F.manufacturer_id]:null,category:F.category_id?Q[F.category_id]:null}))}async function B2($=5){try{return(await K0.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",K0.fn.sum("order_items.quantity").as("units_sold"),YY`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($).execute()).map((G)=>({id:Number(G.id),name:String(G.name??"Unnamed product"),units_sold:Number(G.units_sold??0),revenue:Number(G.revenue??0),inventory_count:Number(G.inventory_count??0)}))}catch(J){if(J instanceof Error)throw TypeError(`Failed to fetch top products: ${J.message}`);throw J}}var{randomUUIDv7:M2}=globalThis.Bun;import{db as _2}from"@stacksjs/database";async function O2($){try{let J={...$,uuid:M2()},G=await _2.insertInto("products").values(J).executeTakeFirst();if(!G)throw Error("Failed to create product item");let X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),Z=await t(X);if(!Z)throw Error("Failed to create product item");return Z}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product item: ${J.message}`);throw J}}async function A2($){if(!$.length)return 0;let J=0;try{return await _2.transaction().execute(async(G)=>{for(let X of $){let Z={...X,uuid:M2()};await G.insertInto("products").values(Z).execute(),J++}}),J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as f1}from"@stacksjs/database";import{formatDate as C1}from"@stacksjs/orm";async function U2($,J){try{if(!$)throw Error("Product item ID is required for update");let G=await f1.updateTable("products").set({...J,updated_at:C1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item: ${G.message}`);throw G}}async function P2($,J){if(!await t($))throw Error(`Product item with ID ${$} not found`);try{return await f1.updateTable("products").set({is_available:J,updated_at:C1(new Date)}).where("id","=",$).execute(),await t($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item availability: ${X.message}`);throw X}}async function S2($,J){let G=await t($);if(!G)throw Error(`Product item with ID ${$} not found`);let X={updated_at:C1(new Date)};if(J!==void 0)X.inventory_count=J;if(Object.keys(X).length===1)return G;try{return await f1.updateTable("products").set(X).where("id","=",$).execute(),await t($)}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update inventory information: ${Z.message}`);throw Z}}var v$={};B(v$,{updateFeaturedStatus:()=>p2,updateByUuid:()=>m2,update:()=>b2,store:()=>D2,fetchWithProductCount:()=>C2,fetchFeatured:()=>w2,fetchByUuid:()=>k2,fetchById:()=>q2,fetchByCountry:()=>f2,fetchAll:()=>j2,destroy:()=>T2,bulkStore:()=>v2,bulkDestroy:()=>E2});import{db as R2}from"@stacksjs/database";async function T2($){try{let J=await R2.deleteFrom("manufacturers").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function E2($){if(!$.length)return 0;try{let J=await R2.deleteFrom("manufacturers").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}import{db as e}from"@stacksjs/database";function j2(){return e.selectFrom("manufacturers").selectAll().execute()}async function q2($){return await e.selectFrom("manufacturers").where("id","=",$).selectAll().executeTakeFirst()}async function k2($){return await e.selectFrom("manufacturers").where("uuid","=",$).selectAll().executeTakeFirst()}async function w2($=10){return await e.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit($).execute()}async function f2($,J={}){let G=J.page||1,X=J.limit||2,Z=await e.selectFrom("manufacturers").select(e.fn.count("id").as("total")).where("country","=",$).executeTakeFirst(),Y=Number(Z?.total||0),K=await e.selectFrom("manufacturers").selectAll().where("country","=",$).limit(X).offset((G-1)*X).execute(),W=Math.ceil(Y/X);return{data:K,paging:{total_records:Y,page:G,total_pages:W},next_cursor:G<W?G+1:null}}async function C2($={}){let J=e.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if($.country)J=J.where("m.country","=",$.country);if($.featured!==void 0)J=J.where("m.featured","=",$.featured);return J=J.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",e.fn.count("p.id").as("product_count")]).groupBy("m.id"),J.execute()}var{randomUUIDv7:I2}=globalThis.Bun;import{db as g2}from"@stacksjs/database";import{HttpError as h2}from"@stacksjs/error-handling";import{isUniqueViolation as KY}from"@stacksjs/orm";async function D2($){try{let J={...$,uuid:I2(),featured:$.featured??!1},G=await g2.insertInto("manufacturers").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch(J){if(J instanceof h2)throw J;if(KY(J))throw new h2(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to create manufacturer: ${J.message}`);throw J}}async function v2($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={...G,uuid:I2(),featured:G.featured??!1};await g2.insertInto("manufacturers").values(X).execute(),J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${G.message}`);throw G}}import{db as h1}from"@stacksjs/database";import{HttpError as y2}from"@stacksjs/error-handling";import{formatDate as I1,isUniqueViolation as WY}from"@stacksjs/orm";async function b2($,J){try{if(!$)throw Error("Manufacturer ID is required for update");let G=await h1.updateTable("manufacturers").set({...J,updated_at:I1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof y2)throw G;if(WY(G))throw new y2(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function p2($,J){try{let G=await h1.updateTable("manufacturers").set({featured:J,updated_at:I1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer featured status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${G.message}`);throw G}}async function m2($,J){try{let G=await h1.updateTable("manufacturers").set({...J,updated_at:I1(new Date)}).where("uuid","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer: ${G.message}`);throw G}}var y$={};B(y$,{updateVotes:()=>KG,update:()=>YG,store:()=>GG,fetchStatsByProductIds:()=>JG,fetchStats:()=>$G,fetchMostHelpfulByProductId:()=>a2,fetchByUserId:()=>o2,fetchByProductId:()=>s2,fetchById:()=>n2,fetchApprovedByProductId:()=>d2,fetchAll:()=>i2,destroy:()=>c2,bulkDestroy:()=>u2});import{db as l2}from"@stacksjs/database";async function c2($){try{let J=await l2.deleteFrom("reviews").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete review: ${J.message}`);throw J}}async function u2($){if(!$.length)return 0;try{let J=await l2.deleteFrom("reviews").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete reviews: ${J.message}`);throw J}}import{db as q0}from"@stacksjs/database";async function n2($){return await q0.selectFrom("reviews").where("id","=",$).selectAll().executeTakeFirst()}async function i2(){return await q0.selectFrom("reviews").selectAll().execute()}async function s2($){return await q0.selectFrom("reviews").where("product_id","=",$).selectAll().execute()}async function o2($){return await q0.selectFrom("reviews").where("customer_id","=",$).selectAll().execute()}async function d2($){return await q0.selectFrom("reviews").where("product_id","=",$).where("is_approved","=",!0).selectAll().execute()}async function a2($){return await q0.selectFrom("reviews").where("product_id","=",$).orderBy("helpful_votes","desc").selectAll().execute()}import{db as r2}from"@stacksjs/database";function t2(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function e2($){let J=t2();J.total=$.length;let G=0;for(let X of $){if(X.rating===null||X.rating===void 0){J.commentsOnly++;continue}let Z=Number(X.rating);if(Number.isNaN(Z)){J.commentsOnly++;continue}J.rated++,G+=Z;let Y=Math.min(5,Math.max(1,Math.round(Z)));J.distribution[Y]++}if(J.rated>0)J.average=Math.round(G/J.rated*10)/10;return J}async function $G($){let J=await r2.selectFrom("reviews").select(["rating"]).where("product_id","=",$).where("is_approved","=",!0).execute();return e2(J)}async function JG($){let J=new Map;for(let Z of $)J.set(Z,t2());if($.length===0)return J;let G=await r2.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",$).where("is_approved","=",!0).execute(),X=new Map;for(let Z of G){let Y=X.get(Z.product_id);if(Y)Y.push({rating:Z.rating});else X.set(Z.product_id,[{rating:Z.rating}])}for(let[Z,Y]of X)J.set(Z,e2(Y));return J}var{randomUUIDv7:QY}=globalThis.Bun;import{db as FY}from"@stacksjs/database";function LY($){let J=$.rating!==void 0&&$.rating!==null,G=typeof $.content==="string"&&$.content.trim().length>0,X=typeof $.title==="string"&&$.title.trim().length>0;return!J&&!G&&!X}async function GG($){try{if(LY($))throw Error("A review needs a rating or something written: both were empty");let J={...$,uuid:QY(),rating:$.rating??null,is_verified_purchase:$.is_verified_purchase??!1,is_approved:$.is_approved??!1,helpful_votes:$.helpful_votes??0,unhelpful_votes:$.unhelpful_votes??0,is_featured:$.is_featured??!1},G=await FY.insertInto("reviews").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create review");return G}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${J.message}`)}throw J}}import{asRow as NY,db as XG}from"@stacksjs/database";import{formatDate as ZG}from"@stacksjs/orm";async function YG($,J){try{if(!$)throw Error("Review ID is required for update");let G=await XG.updateTable("reviews").set({...J,updated_at:ZG(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review: ${G.message}`);throw G}}async function KG($,J,G=!0){try{let X=J==="helpful"?"helpful_votes":"unhelpful_votes",Z=G?`COALESCE("${X}", 0) + 1`:`MAX(COALESCE("${X}", 0) - 1, 0)`,Y=await XG.unsafe(`UPDATE "reviews" SET "${X}" = ${Z}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[ZG(new Date),$]).execute(),K=Array.isArray(Y)?Y[0]:Y;if(!K)throw Error("Failed to update review votes");return NY(K)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var m$={};B(m$,{updateDefaultStatus:()=>AG,update:()=>_G,store:()=>VG,getDefaultUnit:()=>MG,formatUnitOptions:()=>BG,fetchById:()=>NG,fetchAll:()=>HG,destroy:()=>QG,bulkUpdate:()=>OG,bulkStore:()=>xG,bulkDestroy:()=>FG});import{db as WG}from"@stacksjs/database";async function QG($){try{let J=await WG.deleteFrom("product_units").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product unit: ${J.message}`);throw J}}async function FG($){if(!$.length)return 0;try{let J=await WG.deleteFrom("product_units").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product units: ${J.message}`);throw J}}import{db as LG}from"@stacksjs/database";async function NG($){return await LG.selectFrom("product_units").where("id","=",$).selectAll().executeTakeFirst()}async function HG(){return await LG.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:zG}=globalThis.Bun;import{db as r0}from"@stacksjs/database";async function VG($){try{return await r0.transaction(async(J)=>{let G={...$,uuid:zG()},X=await J.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(G.is_default&&G.type)await J.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();return X})}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product unit: ${J.message}`);throw J}}async function xG($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={...G,uuid:zG()},Z=await r0.insertInto("product_units").values(X).returningAll().executeTakeFirst();if(X.is_default&&X.type&&Z)await r0.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",Z.id).execute();J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function BG($){try{let J=r0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if($)J=J.where("type","=",$);return J=J.orderBy("name"),J.execute().then((G)=>G.map((X)=>({id:String(X.id),name:X.name,abbreviation:X.abbreviation,is_default:X.is_default})))}catch(J){if(J instanceof Error)throw TypeError(`Failed to format unit options: ${J.message}`);throw J}}async function MG($){try{return await r0.selectFrom("product_units").selectAll().where("type","=",$).where("is_default","=",!0).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get default unit: ${J.message}`);throw J}}import{db as b$}from"@stacksjs/database";import{formatDate as p$}from"@stacksjs/orm";async function _G($,J){try{if(!$)throw Error("Product unit ID is required for update");return await b$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",$).executeTakeFirst();if(!X)return;let Z=J.type??X.type;if((J.is_default??Boolean(X.is_default))&&Z)await G.updateTable("product_units").set({is_default:!1,updated_at:p$(new Date)}).where("type","=",Z).where("id","!=",$).execute();let K=await G.updateTable("product_units").set({...J,updated_at:p$(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!K)return;return K})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function OG($){if(!$.length)return 0;let J=0;try{for(let G of $){let X=G;if(!X.id)continue;let Z=X.data&&typeof X.data==="object"?X.data:{...X};delete Z.id;let Y=await b$.updateTable("product_units").set({...Z,updated_at:p$(new Date)}).where("id","=",X.id).executeTakeFirst(),K=Z;if(K.is_default===!0&&K.type)await b$.updateTable("product_units").set({is_default:!1}).where("type","=",K.type).where("id","!=",X.id).execute();if(Number(Y.numUpdatedRows)>0)J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function AG($,J){try{return await b$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select("type").where("id","=",$).executeTakeFirst();if(!X)return!1;let Z=p$(new Date);if(J&&X.type)await G.updateTable("product_units").set({is_default:!1,updated_at:Z}).where("type","=",X.type).where("id","!=",$).execute();return await G.updateTable("product_units").set({is_default:J,updated_at:Z}).where("id","=",$).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var l$={};B(l$,{update:()=>gG,store:()=>kG,generateVariantCombinations:()=>CG,formatVariantOptions:()=>fG,fetchById:()=>TG,fetchAll:()=>EG,destroy:()=>PG,bulkUpdate:()=>DG,bulkStore:()=>wG,bulkDestroy:()=>SG});import{db as UG}from"@stacksjs/database";async function PG($){try{let J=await UG.deleteFrom("product_variants").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variant: ${J.message}`);throw J}}async function SG($){if(!$.length)return 0;try{let J=await UG.deleteFrom("product_variants").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variants: ${J.message}`);throw J}}import{db as RG}from"@stacksjs/database";async function TG($){return await RG.selectFrom("product_variants").where("id","=",$).selectAll().executeTakeFirst()}async function EG(){return await RG.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:jG}=globalThis.Bun;import{db as qG}from"@stacksjs/database";async function kG($){try{let J={...$,uuid:jG()},G=await qG.insertInto("product_variants").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product variant");return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variant: ${J.message}`);throw J}}async function wG($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={...G,uuid:jG()};await qG.insertInto("product_variants").values(X).execute(),J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${G.message}`);throw G}}function fG($){if(!$||!$.length)return JSON.stringify([]);let J=$.map((G)=>G.trim()).filter(Boolean);return JSON.stringify(J)}function CG($){let J=Object.keys($);if(!J.length)return[];function G(X,Z){if(X===J.length)return[Z];let Y=J[X],K=$[Y]??[],W=[];for(let Q of K){let F={...Z,[Y]:Q};W.push(...G(X+1,F))}return W}return G(0,{})}import{db as hG}from"@stacksjs/database";import{formatDate as IG}from"@stacksjs/orm";async function gG($,J){try{let G=await hG.updateTable("product_variants").set({...J,updated_at:IG(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variant: ${G.message}`);throw G}}async function DG($){if(!$.length)return 0;let J=0;try{for(let G of $){if(!G.id)continue;let X=await hG.updateTable("product_variants").set({...G,updated_at:IG(new Date)}).where("id","=",G.id).executeTakeFirst();if(Number(X.numUpdatedRows)>0)J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${G.message}`);throw G}}var HY={categories:g$,items:D$,manufacturers:v$,reviews:y$,units:m$,variants:l$},zY=HY;var p1={};B(p1,{updateStatus:()=>aG,updatePrintJob:()=>rG,update:()=>dG,store:()=>sG,fetchSuccessRate:()=>lG,fetchPrintsPerHour:()=>nG,fetchPrintTimeStats:()=>uG,fetchPrintJobStats:()=>mG,fetchPageStats:()=>cG,fetchById:()=>k0,fetchAll:()=>pG,destroy:()=>yG,bulkStore:()=>oG,bulkDestroy:()=>bG});import{db as vG}from"@stacksjs/database";async function yG($){try{let J=await vG.deleteFrom("receipts").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print log: ${J.message}`);throw J}}async function bG($){if(!$.length)return 0;try{let J=await vG.deleteFrom("receipts").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete receipts: ${J.message}`);throw J}}import{db as D1}from"@stacksjs/database";import{formatDate as VY}from"@stacksjs/orm";function l($){return VY($)}function xY($){if($ instanceof Date)return Number.isNaN($.getTime())?null:$;if(typeof $==="number"){let X=new Date($<=2147483647?$*1000:$);return Number.isNaN(X.getTime())?null:X}let J=String($||"").trim();if(!J)return null;if(/^\d{10}$/.test(J)){let X=new Date(Number(J)*1000);return Number.isNaN(X.getTime())?null:X}let G=new Date(J.includes("T")?J:`${J.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function k0($){return await D1.selectFrom("receipts").where("id","=",$).selectAll().executeTakeFirst()}async function pG(){return await D1.selectFrom("receipts").selectAll().execute()}async function mG($,J){let G=l($),X=l(J),Z=await I("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"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning,averageSize:Math.round(Z.averageSize),averagePages:Math.round(Z.averagePages),averageDuration:Math.round(Z.averageDuration)}}async function lG($,J){let G=l($),X=l(J),Z=await I("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"}}},(K)=>K.where("timestamp",">=",G).where("timestamp","<=",X));return{successRate:Z.total>0?Math.round(Z.success/Z.total*100):0,total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning}}async function cG($,J){let G=l($),X=l(J),Z=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{totalPages:Z.totalPages,averagePagesPerReceipt:Math.round(Z.averagePagesPerReceipt),totalReceipts:Z.totalReceipts}}async function uG($,J){let G=l($),X=l(J),Z=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{averageDuration:Math.round(Z.averageDuration),minDuration:Z.minDuration,maxDuration:Z.maxDuration,totalJobs:Z.totalJobs}}async function nG($,J){let G=typeof $==="number"?$:$.getTime(),X=typeof J==="number"?J:J.getTime(),Z=l($),Y=l(J),K=await D1.selectFrom("receipts").where("timestamp",">=",Z).where("timestamp","<=",Y).selectAll().execute(),W=K.length,Q=Math.ceil((X-G)/3600000),F=Q>0?Math.round(W/Q):0,N=Array.from({length:24},(H,z)=>({hour:z,count:0}));return K.forEach((H)=>{let z=xY(H.timestamp);if(!z)return;N[z.getHours()].count++}),{totalPrints:W,totalHours:Q,printsPerHour:F,hourlyBreakdown:N}}var{randomUUIDv7:iG}=globalThis.Bun;import{db as c$}from"@stacksjs/database";import{formatDate as v1}from"@stacksjs/orm";function t0($){try{if(typeof $==="number")return v1($<=2147483647?$*1000:$);if(typeof $==="string"&&/^\d{10}$/.test($))return v1(Number($)*1000);return v1($)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function sG($){try{let J=iG(),G={...$,timestamp:t0($.timestamp),uuid:J};await c$.insertInto("receipts").values(G).executeTakeFirst();let X=await c$.selectFrom("receipts").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipt: ${J.message}`);throw J}}async function oG($){if(!$.length)return 0;try{let J=$.map((Z)=>({...Z,timestamp:t0(Z.timestamp),uuid:iG()})),X=await c$.insertInto("receipts").values(J).executeTakeFirst()??{};return Number(X.numInsertedOrUpdatedRows??X.numAffectedRows??X.affectedRows??X.changes??0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${J.message}`);throw J}}import{db as y1}from"@stacksjs/database";import{formatDate as b1}from"@stacksjs/orm";async function dG($,J){try{if(!$)throw Error("Receipt ID is required for update");let G={...J,...J.timestamp===void 0?{}:{timestamp:t0(J.timestamp)},updated_at:b1(new Date)};await y1.updateTable("receipts").set(G).where("id","=",$).execute();let X=await k0($);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function aG($,J){try{await y1.updateTable("receipts").set({status:J,updated_at:b1(new Date)}).where("id","=",$).execute();let G=await k0($);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function rG($,J,G,X){try{let Z={updated_at:b1(new Date)};if(J!==void 0)Z.size=J;if(G!==void 0)Z.pages=G;if(X!==void 0)Z.duration=X;await y1.updateTable("receipts").set(Z).where("id","=",$).execute();let Y=await k0($);if(!Y)throw Error("Failed to update receipt job information");return Y}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update receipt job information: ${Z.message}`);throw Z}}var F7={};B(F7,{zones:()=>j4,tracking:()=>S4,routes:()=>d$,rates:()=>x4,methods:()=>L4,licenses:()=>K4,geocoding:()=>X4,drivers:()=>e$,digital:()=>r$,default:()=>mY});var d$={};B(d$,{validateDeliveryRouteWrite:()=>w0,updateStops:()=>WX,updateMetrics:()=>QX,updateLastActive:()=>YX,update:()=>KX,store:()=>ZX,fetchById:()=>n$,fetchByDriver:()=>XX,fetchAll:()=>JX,fetchActive:()=>GX,destroy:()=>eG,bulkDestroy:()=>$X,DeliveryRouteInputError:()=>h});import{db as tG}from"@stacksjs/database";async function eG($){try{let J=await tG.deleteFrom("delivery_routes").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery route: ${J.message}`);throw J}}async function $X($){if(!$.length)return 0;try{let J=await tG.deleteFrom("delivery_routes").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery routes: ${J.message}`);throw J}}import{db as u$}from"@stacksjs/database";async function n$($){return await u$.selectFrom("delivery_routes").where("id","=",$).selectAll().executeTakeFirst()}async function JX(){return await u$.selectFrom("delivery_routes").selectAll().execute()}async function GX(){return await u$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function XX($){return await u$.selectFrom("delivery_routes").where("driver","=",$).selectAll().execute()}var{randomUUIDv7:_Y}=globalThis.Bun;import{db as m1}from"@stacksjs/database";function x0($,J){let G={};for(let[X,Z]of Object.entries(J))for(let Y of Z){if(!Object.prototype.hasOwnProperty.call($,Y)||$[Y]===void 0)continue;G[X]=$[Y];break}return G}function e0($){return x0($,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function $0($){return x0($,{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 $$($){return x0($,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function J$($){return x0($,{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 G$($){return x0($,{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 X$($){return x0($,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function i$($){return x0($,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as BY}from"@stacksjs/database";class h extends TypeError{constructor($){super($);this.name="DeliveryRouteInputError"}}function s$($,J,G){return Number($[G]??J?.[G])}function MY($,J){let G=$.last_active??J?.last_active;if(G===void 0||G===null)return Date.now();if(G instanceof Date)return G.getTime();if(typeof G==="number")return G;if(typeof G==="string"&&/^\d{10,13}$/.test(G))return Number(G);return Number.NaN}async function w0($,J){let G=s$($,J,"driver_id"),X=s$($,J,"stops"),Z=s$($,J,"delivery_time"),Y=s$($,J,"total_distance"),K=MY($,J);if(!Number.isSafeInteger(G)||G<1)throw new h("Driver must be a positive integer.");if(!Number.isSafeInteger(X)||X<0)throw new h("Stops must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new h("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(Y)||Y<0)throw new h("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(K)||K<0)throw new h("Last active must be a valid Unix timestamp.");let W=await BY.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!W)throw new h(`Driver ${G} was not found.`);return{...$,driver_id:Number(W.id),driver:W.name,vehicle:W.vehicle_number,last_active:K}}async function ZX($){try{let J=_Y(),G=i$($),Z={...await w0(G),uuid:J};await m1.insertInto("delivery_routes").values(Z).executeTakeFirst();let Y=await m1.selectFrom("delivery_routes").where("uuid","=",J).selectAll().executeTakeFirst();if(!Y)throw Error("Failed to create delivery route");return Y}catch(J){if(J instanceof h)throw J;if(J instanceof Error)throw TypeError(`Failed to create delivery route: ${J.message}`);throw J}}async function YX($){try{await m1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",$).execute();let J=await n$($);if(!J)throw Error("Failed to update delivery route last active");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route last active: ${J.message}`);throw J}}import{db as o$}from"@stacksjs/database";import{formatDate as l1}from"@stacksjs/orm";async function KX($,J){try{if(!$)throw Error("Delivery route ID is required for update");let G=await o$.selectFrom("delivery_routes").where("id","=",$).selectAll().executeTakeFirst();if(!G)return;let X=i$(J),Z=await w0(X,G),Y=await o$.updateTable("delivery_routes").set({...Z,updated_at:l1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof h)throw G;if(G instanceof Error)throw TypeError(`Failed to update delivery route: ${G.message}`);throw G}}async function WX($,J){try{let G=await o$.updateTable("delivery_routes").set({stops:J,updated_at:l1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update delivery route stops");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery route stops: ${G.message}`);throw G}}async function QX($,J,G){try{let X={updated_at:l1(new Date)};if(J!==void 0)X.delivery_time=J;if(G!==void 0)X.total_distance=G;let Z=await o$.updateTable("delivery_routes").set(X).where("id","=",$).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update delivery metrics");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery metrics: ${X.message}`);throw X}}var r$={};B(r$,{updateStatus:()=>AX,updateDeliverySettings:()=>UX,update:()=>OX,store:()=>MX,softDelete:()=>LX,fetchById:()=>VX,fetchAll:()=>xX,destroy:()=>FX,bulkStore:()=>_X,bulkSoftDelete:()=>HX,bulkDestroy:()=>NX});import{db as a$}from"@stacksjs/database";async function FX($){try{let J=await a$.deleteFrom("digital_deliveries").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital delivery: ${J.message}`);throw J}}async function LX($){try{let J=await a$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${J.message}`);throw J}}async function NX($){if(!$.length)return 0;try{let J=await a$.deleteFrom("digital_deliveries").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${J.message}`);throw J}}async function HX($){if(!$.length)return 0;try{let J=await a$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${J.message}`);throw J}}import{db as zX}from"@stacksjs/database";async function VX($){return await zX.selectFrom("digital_deliveries").where("id","=",$).selectAll().executeTakeFirst()}async function xX(){return await zX.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:BX}=globalThis.Bun;import{asRow as OY,db as c1}from"@stacksjs/database";async function MX($){try{let J=BX(),G={...J$($),uuid:J};await c1.insertInto("digital_deliveries").values(G).executeTakeFirst();let X=await c1.selectFrom("digital_deliveries").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created digital delivery");return OY(X)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital delivery: ${J.message}`);throw J}}async function _X($){if(!$.length)return 0;try{let J=$.map((X)=>({...J$(X),uuid:BX()})),G=await c1.insertInto("digital_deliveries").values(J).executeTakeFirst();return L(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${J.message}`);throw J}}import{db as u1}from"@stacksjs/database";import{formatDate as n1}from"@stacksjs/orm";async function OX($,J){try{if(!$)throw Error("Digital delivery ID is required for update");let G=await u1.updateTable("digital_deliveries").set({...J$(J),updated_at:n1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery: ${G.message}`);throw G}}async function AX($,J){try{let G=await u1.updateTable("digital_deliveries").set({status:J,updated_at:n1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update digital delivery status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery status: ${G.message}`);throw G}}async function UX($,J,G,X,Z){try{let Y={updated_at:n1(new Date)};if(J!==void 0)Y.download_limit=J;if(G!==void 0)Y.expiry_days=G;if(X!==void 0)Y.requires_login=X;if(Z!==void 0)Y.automatic_delivery=Z;let K=await u1.updateTable("digital_deliveries").set(Y).where("id","=",$).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update delivery settings");return K}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery settings: ${Y.message}`);throw Y}}var e$={};B(e$,{updateStatus:()=>fX,updateContact:()=>CX,update:()=>wX,store:()=>qX,fetchById:()=>t$,fetchAll:()=>SX,destroy:()=>TX,bulkStore:()=>kX,bulkDestroy:()=>EX});import{db as RX}from"@stacksjs/database";import{db as PX}from"@stacksjs/database";async function t$($){return await PX.selectFrom("drivers").where("id","=",$).selectAll().executeTakeFirst()}async function SX(){return await PX.selectFrom("drivers").selectAll().execute()}async function TX($){try{let J=await RX.deleteFrom("drivers").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete driver: ${J.message}`);throw J}}async function EX($){if(!$.length)return 0;let J=0;try{return await RX.transaction().execute(async(G)=>{for(let X of $)if(await t$(X))await G.deleteFrom("drivers").where("id","=",X).execute(),J++}),J}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${G.message}`);throw G}}var{randomUUIDv7:jX}=globalThis.Bun;import{db as i1}from"@stacksjs/database";async function qX($){try{let J=jX(),G={...X$($),uuid:J};await i1.insertInto("drivers").values(G).executeTakeFirst();let X=await i1.selectFrom("drivers").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created driver");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create driver: ${J.message}`);throw J}}async function kX($){if(!$.length)return 0;try{let J=$.map((X)=>({...X$(X),uuid:jX()})),G=await i1.insertInto("drivers").values(J).executeTakeFirst();return L(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${J.message}`);throw J}}import{db as s1}from"@stacksjs/database";import{formatDate as o1}from"@stacksjs/orm";async function wX($,J){try{if(!$)throw Error("Driver ID is required for update");let G=await s1.updateTable("drivers").set({...X$(J),updated_at:o1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver: ${G.message}`);throw G}}async function fX($,J){try{let G=await s1.updateTable("drivers").set({status:J,updated_at:o1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update driver status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver status: ${G.message}`);throw G}}async function CX($,J){try{let G={updated_at:o1(new Date)};if(J!==void 0)G.phone=J;let X=await s1.updateTable("drivers").set(G).where("id","=",$).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update contact information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update contact information: ${G.message}`);throw G}}var X4={};B(X4,{setGeocodingDriver:()=>SY,nominatimDriver:()=>G4,geocodingDriver:()=>yX,geocode:()=>RY,formatQuery:()=>f0,checkCoverage:()=>TY,PRECISION_RANK:()=>Y$});var B0=($)=>$*Math.PI/180;function W0($,J){let G=B0(J.latitude-$.latitude),X=B0(J.longitude-$.longitude),Z=B0($.latitude),Y=B0(J.latitude),K=Math.sin(G/2)**2+Math.sin(X/2)**2*Math.cos(Z)*Math.cos(Y);return 12742017.6*Math.asin(Math.sqrt(K))}function $4($,J){let G=B0($.latitude),X=B0(J.latitude),Z=B0(J.longitude-$.longitude),Y=Math.sin(Z)*Math.cos(X),K=Math.cos(G)*Math.sin(X)-Math.sin(G)*Math.cos(X)*Math.cos(Z);return(Math.atan2(Y,K)*180/Math.PI+360)%360}function J4($,J,G={}){let X=G.detourFactor??1.35,Z=G.minimumSeconds??30;if(!Number.isFinite(J)||J<=0.5)return null;let Y=$*X/J;return Math.max(Z,Math.round(Y))}function hX($,J,G){return W0($,J)<=G}function Z$($){return typeof $?.latitude==="number"&&typeof $?.longitude==="number"&&Number.isFinite($.latitude)&&Number.isFinite($.longitude)}var Y$={unknown:0,locality:1,postal:2,street:3,rooftop:4};function f0($){return[$.street,$.city,$.region,$.postalCode,$.country].map((J)=>String(J??"").trim()).filter(Boolean).join(", ")}var AY="https://nominatim.openstreetmap.org/search",IX=1000,gX=0,DX=Promise.resolve();async function UY($){let J=DX.then(async()=>{let G=Date.now()-gX;if(G<IX)await Bun.sleep(IX-G);return gX=Date.now(),$()});return DX=J.then(()=>{return},()=>{return}),J}function PY($){let J=$.address??{},G=String($.addresstype??""),X=String($.type??""),Z=String($.category??$.class??"");if(J.house_number||X==="house"||X==="building"||G==="building")return"rooftop";if(J.road||Z==="highway"||G==="road")return"street";if(G==="postcode"||J.postcode&&!J.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(G))return"locality";return"unknown"}function G4($={}){let J=$.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,G=$.endpoint??AY;return{name:"nominatim",async geocode(X){let Z=f0(X);if(!Z)return null;let Y=new URL(G);if(Y.searchParams.set("q",Z),Y.searchParams.set("format","jsonv2"),Y.searchParams.set("limit","1"),Y.searchParams.set("addressdetails","1"),X.country)Y.searchParams.set("countrycodes",X.country.toLowerCase());let K=await UY(()=>fetch(Y,{headers:{"user-agent":J,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!K.ok)throw Error(`Nominatim responded ${K.status}`);let Q=(await K.json())?.[0];if(!Q)return null;let F=Number(Q.lat),N=Number(Q.lon);if(!Number.isFinite(F)||!Number.isFinite(N))return null;let H=PY(Q);return{latitude:F,longitude:N,formatted:String(Q.display_name??Z),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[H],precision:H,provider:"nominatim"}}}}var vX=null;function SY($){vX=$}function yX(){return vX??G4()}async function RY($,J={}){let G=J.driver??yX(),X=J.minimumPrecision??"street",Z=`geocode:${G.name}:${f0($).toLowerCase()}`,Y=await EY(Z);if(Y!==void 0)return Y;let K=await G.geocode($),W=K&&Y$[K.precision]>=Y$[X]?K:null;return await jY(Z,W,W?J.cacheSeconds??2592000:600),W}function TY($,J,G){if(J.length===0)return null;let X=J[0],Z=W0($,X);for(let Y of J.slice(1)){let K=W0($,Y);if(K<Z)Z=K,X=Y}return{covered:Z<=G,distanceMeters:Math.round(Z),nearest:X}}async function EY($){try{let G=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!G)return;let X=await G.get($);if(X===null||X===void 0)return;return X==="null"?null:JSON.parse(String(X))}catch{return}}async function jY($,J,G){try{let Z=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!Z)return;await Z.set($,J===null?"null":JSON.stringify(J),G)}catch{}}var K4={};B(K4,{validateLicenseKeyWrite:()=>M0,updateStatus:()=>tX,updateExpiration:()=>eX,update:()=>rX,store:()=>dX,softDelete:()=>pX,fetchById:()=>uX,fetchAll:()=>nX,destroy:()=>bX,bulkStore:()=>aX,bulkSoftDelete:()=>lX,bulkDestroy:()=>mX,LicenseKeyInputError:()=>E});import{db as Z4}from"@stacksjs/database";async function bX($){try{let J=await Z4.deleteFrom("license_keys").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license key: ${J.message}`);throw J}}async function pX($){try{let J=await Z4.updateTable("license_keys").set({status:"inactive"}).where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license key: ${J.message}`);throw J}}async function mX($){if(!$.length)return 0;try{let J=await Z4.deleteFrom("license_keys").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license keys: ${J.message}`);throw J}}async function lX($){if(!$.length)return 0;try{let J=await Z4.updateTable("license_keys").set({status:"inactive"}).where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license keys: ${J.message}`);throw J}}import{db as cX}from"@stacksjs/database";async function uX($){return await cX.selectFrom("license_keys").where("id","=",$).selectAll().executeTakeFirst()}async function nX(){return await cX.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:oX}=globalThis.Bun;import{asRow as kY,db as r1}from"@stacksjs/database";import{db as d1}from"@stacksjs/database";var iX=["Standard License","Premium License","Enterprise License"],sX=["active","inactive","unassigned"];class E extends TypeError{constructor($){super($);this.name="LicenseKeyInputError"}}function K$($,J,G){return $[G]!==void 0?$[G]:J?.[G]}function a1($,J,G,X){let Z=K$($,J,G);if(Z===void 0||Z===null||Z==="")return null;let Y=Number(Z);if(!Number.isSafeInteger(Y)||Y<1)throw new E(`${X} must be a positive integer or null.`);return Y}function qY($){if(typeof $==="number")return $>2147483647?Math.floor($/1000):$;if(typeof $==="string"&&/^\d{10,13}$/.test($))return $.length===13?Math.floor(Number($)/1000):Number($);if(typeof $==="string"){let J=/^\d{4}-\d{2}-\d{2} \d/.test($)?`${$.replace(" ","T")}Z`:$;return Math.floor(new Date(J).getTime()/1000)}return Number.NaN}async function M0($,J){let G=String(K$($,J,"key")||"").trim().toUpperCase(),X=String(K$($,J,"template")||""),Z=String(K$($,J,"status")||""),Y=qY(K$($,J,"expiry_date")),K=a1($,J,"customer_id","Customer"),W=a1($,J,"product_id","Product"),Q=a1($,J,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new E("License key must use five groups of four uppercase letters or numbers.");if(!iX.includes(X))throw new E(`Template must be one of: ${iX.join(", ")}.`);if(!sX.includes(Z))throw new E(`Status must be one of: ${sX.join(", ")}.`);if(!Number.isSafeInteger(Y)||Y<0||Y>2147483647)throw new E("Expiry date must be a Unix timestamp between 1970 and 2038.");let[F,N,H]=await Promise.all([K?d1.selectFrom("customers").where("id","=",K).select("id").executeTakeFirst():null,W?d1.selectFrom("products").where("id","=",W).select("id").executeTakeFirst():null,Q?d1.selectFrom("orders").where("id","=",Q).select(["id","customer_id"]).executeTakeFirst():null]);if(K&&!F)throw new E(`Customer ${K} was not found.`);if(W&&!N)throw new E(`Product ${W} was not found.`);if(Q&&!H)throw new E(`Order ${Q} was not found.`);if(K&&H?.customer_id&&Number(H.customer_id)!==K)throw new E(`Order ${Q} belongs to Customer ${H.customer_id}, not Customer ${K}.`);return{...$,key:G,template:X,expiry_date:Y,status:Z,customer_id:K,product_id:W,order_id:Q}}async function dX($){try{let J=oX(),G=G$($),X={...await M0(G),uuid:J};await r1.insertInto("license_keys").values(X).executeTakeFirst();let Z=await r1.selectFrom("license_keys").where("uuid","=",J).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created license key");return kY(Z)}catch(J){if(J instanceof E)throw J;if(J instanceof Error){if(J.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${J.message}`)}throw J}}async function aX($){if(!$.length)return 0;try{let J=await Promise.all($.map(async(X)=>({...await M0(G$(X)),uuid:oX()}))),G=await r1.insertInto("license_keys").values(J).executeTakeFirst();return L(G)}catch(J){if(J instanceof E)throw J;if(J instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${J.message}`);throw J}}import{db as Y4}from"@stacksjs/database";import{formatDate as t1}from"@stacksjs/orm";async function rX($,J){try{if(!$)throw Error("License key ID is required for update");let G=await Y4.selectFrom("license_keys").where("id","=",$).selectAll().executeTakeFirst();if(!G)return;let X=G$(J),Z=await M0(X,G),Y=await Y4.updateTable("license_keys").set({...Z,updated_at:t1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof E)throw G;if(G instanceof Error){if(G.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${G.message}`)}throw G}}async function tX($,J){try{let G=await Y4.updateTable("license_keys").set({status:J,updated_at:t1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update license key status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update license key status: ${G.message}`);throw G}}async function eX($,J){try{let G={updated_at:t1(new Date)};if(J!==void 0)G.expiry_date=J;let X=await Y4.updateTable("license_keys").set(G).where("id","=",$).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update expiration information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update expiration information: ${G.message}`);throw G}}var L4={};B(L4,{updateStatus:()=>N9,updatePricing:()=>H9,update:()=>L9,store:()=>K9,softDelete:()=>J9,getActiveShippingMethods:()=>F9,formatShippingOptions:()=>Q9,fetchById:()=>F4,fetchAll:()=>Z9,destroy:()=>$9,bulkStore:()=>W9,bulkSoftDelete:()=>X9,bulkDestroy:()=>G9});import{db as W4}from"@stacksjs/database";async function $9($){try{let J=await W4.deleteFrom("shipping_methods").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping method: ${J.message}`);throw J}}async function J9($){try{let J=await W4.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${J.message}`);throw J}}async function G9($){if(!$.length)return 0;try{let J=await W4.deleteFrom("shipping_methods").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping methods: ${J.message}`);throw J}}async function X9($){if(!$.length)return 0;try{let J=await W4.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${J.message}`);throw J}}import{db as Q4}from"@stacksjs/database";async function F4($){let J=await Q4.selectFrom("shipping_methods").where("id","=",$).selectAll().executeTakeFirst();if(J){let G=await Q4.selectFrom("shipping_zones").where("shipping_method_id","=",$).selectAll().execute();return{...J,shippingZones:G}}return}async function Z9(){let $=await Q4.selectFrom("shipping_methods").selectAll().execute();if($.length===0)return[];let J=[...new Set($.map((Y)=>Y.id))],Z=(await Q4.selectFrom("shipping_zones").where("shipping_method_id","in",J).selectAll().execute()).reduce((Y,K)=>{let W=K.shipping_method_id;if(W!==null&&W!==void 0){if(!Y[W])Y[W]=[];Y[W].push(K)}return Y},{});return $.map((Y)=>({...Y,shipping_zones:Z[Y.id]||[]}))}var{randomUUIDv7:Y9}=globalThis.Bun;import{db as W$}from"@stacksjs/database";async function K9($){try{let J=Y9(),G={...e0($),uuid:J};await W$.insertInto("shipping_methods").values(G).executeTakeFirst();let X=await W$.selectFrom("shipping_methods").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping method");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping method: ${J.message}`);throw J}}async function W9($){if(!$.length)return 0;try{let J=$.map((X)=>({...e0(X),uuid:Y9()})),G=await W$.insertInto("shipping_methods").values(J).executeTakeFirst();return L(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${J.message}`);throw J}}function Q9(){try{return W$.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to format shipping options: ${$.message}`);throw $}}async function F9(){try{return await W$.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get active shipping methods: ${$.message}`);throw $}}import{db as e1}from"@stacksjs/database";import{formatDate as $7}from"@stacksjs/orm";async function L9($,J){try{if(!$)throw Error("Shipping method ID is required for update");let G=await e1.updateTable("shipping_methods").set({...e0(J),updated_at:$7(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method: ${G.message}`);throw G}}async function N9($,J){try{let G=await e1.updateTable("shipping_methods").set({status:J,updated_at:$7(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping method status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method status: ${G.message}`);throw G}}async function H9($,J,G){try{let X={updated_at:$7(new Date)};if(J!==void 0)X.base_rate=J;if(G!==void 0)X.free_shipping=G;let Z=await e1.updateTable("shipping_methods").set(X).where("id","=",$).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update pricing information");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update pricing information: ${X.message}`);throw X}}var x4={};B(x4,{validateZoneMatchesAddress:()=>P9,validateShippingRateWrite:()=>_0,updateByZone:()=>I9,updateByMethod:()=>g9,update:()=>C9,store:()=>w9,resolveZoneForAddress:()=>H4,getShippingRatesByMethod:()=>R9,getRatesByZone:()=>A9,getRateByWeightAndZone:()=>J7,getRateByWeightAndAddress:()=>U9,formatShippingRateOptions:()=>S9,fetchById:()=>_9,fetchAll:()=>O9,destroyByZone:()=>x9,destroyByMethod:()=>B9,destroy:()=>z9,bulkUpdate:()=>h9,bulkStore:()=>f9,bulkDestroy:()=>V9,ShippingRateInputError:()=>f});import{db as N4}from"@stacksjs/database";async function z9($){try{let J=await N4.deleteFrom("shipping_rates").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rate: ${J.message}`);throw J}}async function V9($){if(!$.length)return 0;try{let J=await N4.deleteFrom("shipping_rates").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates: ${J.message}`);throw J}}async function x9($){try{let J=await N4.deleteFrom("shipping_rates").where("shipping_zone_id","=",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${J.message}`);throw J}}async function B9($){try{let J=await N4.deleteFrom("shipping_rates").where("shipping_method_id","=",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${J.message}`);throw J}}import{db as b}from"@stacksjs/database";async function _9($){let J=await b.selectFrom("shipping_rates").where("id","=",$).selectAll().executeTakeFirst();if(J){let G=null,X=null;if(J.shipping_zone_id)G=await b.selectFrom("shipping_zones").where("id","=",J.shipping_zone_id).selectAll().executeTakeFirst();if(J.shipping_method_id)X=await b.selectFrom("shipping_methods").where("id","=",J.shipping_method_id).selectAll().executeTakeFirst();return{...J,shipping_zone:G,shipping_method:X}}return}async function O9(){let $=await b.selectFrom("shipping_rates").selectAll().execute();if($.length===0)return[];let J=[...new Set($.map((W)=>W.shipping_zone_id).filter((W)=>W!==null&&W!==void 0))],G=[...new Set($.map((W)=>W.shipping_method_id).filter((W)=>W!==null&&W!==void 0))],[X,Z]=await Promise.all([J.length?b.selectFrom("shipping_zones").where("id","in",J).selectAll().execute():[],G.length?b.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),Y=X.reduce((W,Q)=>{return W[Q.id]=Q,W},{}),K=Z.reduce((W,Q)=>{return W[Q.id]=Q,W},{});return $.map((W)=>({...W,shipping_zone:W.shipping_zone_id?Y[W.shipping_zone_id]:[],shipping_method:W.shipping_method_id?K[W.shipping_method_id]:[]}))}async function A9($){try{return await b.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${J.message}`);throw J}}async function J7($,J){try{return await b.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).where("weight_from","<=",$).where("weight_to",">=",$).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function H4($){if(!$?.countryCode)return null;try{let J=await b.selectFrom("shipping_zones").selectAll().where("countries","like",`%${$.countryCode}%`).where("status","=","active").execute();if(J.length===0)return null;let G=null;for(let X of J){let Z=1;if($.region&&X.regions&&M9(X.regions,$.region))Z=2;if($.postalCode&&X.postal_codes&&M9(X.postal_codes,$.postalCode))Z=3;if(!G||Z>G.score)G={id:X.id,score:Z}}return G?.id??null}catch{return null}}async function U9($,J){let G=await H4(J);if(G==null)return;return J7($,G)}async function P9($,J){return await H4(J)===$}function M9($,J){if(!$||!J)return!1;let G=J.trim().toUpperCase();for(let X of $.split(/[,|;]/))if(X.trim().toUpperCase()===G)return!0;return!1}async function S9(){try{return(await b.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((J)=>J.shipping_method_id!==null&&J.shipping_method_id!==void 0&&J.shipping_zone_id!==null&&J.shipping_zone_id!==void 0)}catch($){if($ instanceof Error)throw TypeError(`Failed to format shipping rate options: ${$.message}`);throw $}}async function R9($){try{return await b.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",$).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${J.message}`);throw J}}var{randomUUIDv7:k9}=globalThis.Bun;import{db as G7}from"@stacksjs/database";import{db as Q$}from"@stacksjs/database";async function T9(){return await Q$.selectFrom("shipping_zones").selectAll().execute()}async function z4($){return await Q$.selectFrom("shipping_zones").where("id","=",$).selectAll().executeTakeFirst()}function E9(){try{return Q$.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to format shipping zone options: ${$.message}`);throw $}}async function j9(){try{return await Q$.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get active shipping zones: ${$.message}`);throw $}}async function q9($){try{return await Q$.selectFrom("shipping_zones").selectAll().where("countries","like",`%${$}%`).where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${J.message}`);throw J}}class f extends TypeError{constructor($){super($);this.name="ShippingRateInputError"}}function F$($,J,G){return Number($[G]??J?.[G])}async function _0($,J){let G=F$($,J,"shipping_method_id"),X=F$($,J,"shipping_zone_id"),Z=F$($,J,"weight_from"),Y=F$($,J,"weight_to"),K=F$($,J,"rate");if(!Number.isSafeInteger(G)||G<1)throw new f("Shipping method must be a positive integer.");if(!Number.isSafeInteger(X)||X<1)throw new f("Shipping zone must be a positive integer.");if(!Number.isFinite(Z)||Z<0)throw new f("Weight from must be a non-negative number.");if(!Number.isFinite(Y)||Y<Z)throw new f("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(K)||K<0)throw new f("Rate must be a non-negative integer in minor currency units.");let[W,Q]=await Promise.all([F4(G),z4(X)]);if(!W)throw new f(`Shipping method ${G} was not found.`);if(!Q)throw new f(`Shipping zone ${X} was not found.`);if(Number(Q.shipping_method_id)!==G)throw new f(`Shipping zone ${X} is not assigned to shipping method ${G}.`)}async function w9($){try{let J=$0($),G=Number(J.shipping_method_id),X=Number(J.shipping_zone_id);await _0(J);let Z=k9(),Y={...J,shipping_method_id:G,shipping_zone_id:X,uuid:Z};await G7.insertInto("shipping_rates").values(Y).executeTakeFirst();let K=await G7.selectFrom("shipping_rates").where("uuid","=",Z).selectAll().executeTakeFirst();if(!K)throw Error("Failed to resolve created shipping rate");return K}catch(J){if(J instanceof f)throw J;if(J instanceof Error)throw TypeError(`Failed to create shipping rate: ${J.message}`);throw J}}async function f9($){if(!$.length)return 0;try{for(let X of $){let Z=$0(X);await _0(Z)}let J=$.map((X)=>({...$0(X),uuid:k9()})),G=await G7.insertInto("shipping_rates").values(J).executeTakeFirst();return L(G)}catch(J){if(J instanceof f)throw J;if(J instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${J.message}`);throw J}}import{db as L$}from"@stacksjs/database";import{formatDate as V4}from"@stacksjs/orm";async function C9($,J){try{if(!$)throw Error("Shipping rate ID is required for update");let G=await L$.selectFrom("shipping_rates").where("id","=",$).selectAll().executeTakeFirst();if(!G)return;let X=$0(J);await _0(X,G);let Z=await L$.updateTable("shipping_rates").set({...X,updated_at:V4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(G){if(G instanceof f)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function h9($){if(!$.length)return 0;try{let J=0;for(let{id:G,data:X}of $){let Z=await L$.updateTable("shipping_rates").set({...$0(X),updated_at:V4(new Date)}).where("id","=",G).executeTakeFirst();if(L(Z)>0)J++}return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${J.message}`);throw J}}async function I9($,J){try{let G=await L$.updateTable("shipping_rates").set({...$0(J),updated_at:V4(new Date)}).where("shipping_zone_id","=",$).executeTakeFirst();return L(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${G.message}`);throw G}}async function g9($,J){try{let G=await L$.updateTable("shipping_rates").set({...$0(J),updated_at:V4(new Date)}).where("shipping_method_id","=",$).executeTakeFirst();return L(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var S4={};B(S4,{startStop:()=>y9,startRoute:()=>m9,routeTrackingChannel:()=>X7,recordDriverPing:()=>D9,orderTrackingChannel:()=>Q0,isWithin:()=>hX,hasCoordinates:()=>Z$,failStop:()=>p9,estimateSecondsRemaining:()=>J4,emitDeliveryStarted:()=>_4,emitDeliveryPosition:()=>B4,emitDeliveryNearby:()=>O4,emitDeliveryFailed:()=>P4,emitDeliveryCompleted:()=>U4,emitDeliveryAssigned:()=>M4,emitDeliveryArrived:()=>A4,distanceInMeters:()=>W0,completeStop:()=>b9,broadcastToChannel:()=>J0,bearingInDegrees:()=>$4,assignStop:()=>v9,NEARBY_RADIUS_METERS:()=>Z7,ARRIVAL_RADIUS_METERS:()=>Y7});function Q0($){return`order.${$}`}function X7($){return`delivery-route.${$}`}async function C0($,J){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X($,J)}catch{}}async function J0($,J,G){try{let X=await import("@stacksjs/realtime").catch(()=>null);if(!X)return;let Z=X.channel;if(typeof Z!=="function")return;await Z($).broadcast(J,G,"private")}catch{}}async function B4($,J,G){await Promise.all([...$.map((X)=>J0(Q0(X),"delivery:position",G)),J==null?Promise.resolve():J0(X7(J),"delivery:position",G)])}async function M4($){if(await C0("delivery:assigned",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:assigned",{stop:$})}async function _4($){if(await C0("delivery:started",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:started",{stop:$})}async function O4($,J,G){if(await C0("delivery:nearby",{stop:$,distanceMeters:J,etaSeconds:G}),$.order_id!=null)await J0(Q0($.order_id),"delivery:nearby",{stop:$,distanceMeters:J,etaSeconds:G})}async function A4($){if(await C0("delivery:arrived",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:arrived",{stop:$})}async function U4($){if(await C0("delivery:completed",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:completed",{stop:$})}async function P4($,J){await C0("delivery:failed",{stop:$,reason:J})}var{randomUUIDv7:wY}=globalThis.Bun;import{db as p}from"@stacksjs/database";var Z7=400,Y7=60,fY=250;async function D9($){let J=$.recordedAt??new Date().toISOString(),G=typeof $.accuracy!=="number"||$.accuracy<=fY,X=await p.selectFrom("drivers").where("id","=",$.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!X)throw Error(`Unknown driver: ${$.driverId}`);let Z=Z$(X)?{latitude:X.latitude,longitude:X.longitude}:null,Y=typeof $.heading==="number"?$.heading:Z?$4(Z,$):null,K=await CY($.driverId),W=K?await hY(K.id):null,Q=null,F=null,N=!1,H=!1,z=W&&Z$({latitude:W.latitude??void 0,longitude:W.longitude??void 0})?{latitude:W.latitude,longitude:W.longitude}:null;if(G&&W&&z)Q=Math.round(W0($,z)),F=J4(Q,$.speed??0),H=Q<=Y7&&W.arrived_at==null,N=!H&&Q<=Z7&&W.status==="en_route"&&W.notified_nearby_at==null;let x=await IY({driverId:$.driverId,routeId:K?.id??null,latitude:$.latitude,longitude:$.longitude,heading:Y,speed:$.speed??null,accuracy:$.accuracy??null,recordedAt:J});if(G)await p.updateTable("drivers").set({latitude:$.latitude,longitude:$.longitude,heading:Y,speed:$.speed??0,last_ping_at:J}).where("id","=",$.driverId).execute();if(W&&(Q!=null||F!=null))await p.updateTable("delivery_stops").set({eta_at:F==null?W.eta_at:new Date(Date.now()+F*1000).toISOString()}).where("id","=",W.id).execute();if(G)await B4(W?.order_id==null?[]:[W.order_id],K?.id??null,{driverId:$.driverId,routeId:K?.id??null,latitude:$.latitude,longitude:$.longitude,heading:Y,speed:$.speed??null,accuracy:$.accuracy??null,recordedAt:J,distanceToStopMeters:Q,etaSeconds:F});if(N&&W)await p.updateTable("delivery_stops").set({notified_nearby_at:J}).where("id","=",W.id).execute(),await O4(W,Q,F);if(H&&W)await p.updateTable("delivery_stops").set({status:"arrived",arrived_at:J}).where("id","=",W.id).execute(),await A4({...W,status:"arrived",arrived_at:J});return{pingId:x,routeId:K?.id??null,stopId:W?.id??null,distanceToStopMeters:Q,etaSeconds:F,crossedNearby:N,crossedArrival:H}}async function CY($){return await p.selectFrom("delivery_routes").where("driver_id","=",$).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function hY($){let J=await p.selectFrom("delivery_stops").where("delivery_route_id","=",$).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 J.find((G)=>G.status==="en_route")??J.find((G)=>G.status==="arrived")??J[0]??null}async function IY($){let J=wY();return await p.insertInto("driver_pings").values({uuid:J,driver_id:$.driverId,delivery_route_id:$.routeId,latitude:$.latitude,longitude:$.longitude,heading:$.heading,speed:$.speed??0,accuracy:$.accuracy,recorded_at:$.recordedAt}).executeTakeFirst(),(await p.selectFrom("driver_pings").where("uuid","=",J).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:gY}=globalThis.Bun;import{db as j}from"@stacksjs/database";async function v9($){let J=gY(),G=$.sequence??await vY($.deliveryRouteId);await j.insertInto("delivery_stops").values({uuid:J,delivery_route_id:$.deliveryRouteId,order_id:$.orderId??null,sequence:G,status:"pending",address:$.address,latitude:$.latitude??null,longitude:$.longitude??null,recipient_name:$.recipientName??null,recipient_phone:$.recipientPhone??null,eta_at:$.etaAt??null}).executeTakeFirst();let X=await bY(J);if(X)await M4(X);return X??{}}async function y9($){await j.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",$).execute();let J=await W7($);if(!J)return null;if(J.order_id!=null)await K7(J.order_id,"OUT_FOR_DELIVERY");return await _4(J),J}async function b9($,J){let G=new Date().toISOString();await j.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await yY($)?{}:{arrived_at:G},...J?{notes:J}:{}}).where("id","=",$).execute();let X=await W7($);if(!X)return null;if(X.order_id!=null)await K7(X.order_id,"DELIVERED");return await U4(X),await l9(X.delivery_route_id),X}async function p9($,J){await j.updateTable("delivery_stops").set({status:"failed",notes:J}).where("id","=",$).execute();let G=await W7($);if(!G)return null;if(G.order_id!=null)await K7(G.order_id,"SHIPPED");return await P4(G,J),await l9(G.delivery_route_id),G}async function m9($){await j.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",$).execute()}async function l9($){if($==null)return;if(await j.selectFrom("delivery_stops").where("delivery_route_id","=",$).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let G=await j.selectFrom("delivery_routes").where("id","=",$).select(["driver_id"]).executeTakeFirst();if(await j.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",$).execute(),G?.driver_id!=null)await j.updateTable("drivers").set({status:"active"}).where("id","=",G.driver_id).execute()}async function K7($,J){let G=await j.selectFrom("orders").where("id","=",$).select(["id","status"]).executeTakeFirst();if(!G)return;let X=await Promise.resolve().then(() => (R0(),x6)),{canTransition:Z,emitForStatus:Y}=X,K=DY(G.status,J,Z);if(K.length===0){let{log:W}=await import("@stacksjs/logging").catch(()=>({log:null}));W?.warn(`[delivery] refused to move order ${$} from ${G.status} to ${J}: no legal transition`);return}for(let W of K)await j.updateTable("orders").set({status:W}).where("id","=",$).execute(),await Y(W,{...G,status:W})}function DY($,J,G){if($===J)return[];if(G($,J))return[J];for(let X of["PROCESSING","SHIPPED"]){if(X===$||X===J)continue;if(G($,X)&&G(X,J))return[X,J]}return[]}async function vY($){return(await j.selectFrom("delivery_stops").where("delivery_route_id","=",$).select(["sequence"]).execute()).reduce((G,X)=>Math.max(G,X.sequence??0),0)+1}async function yY($){return(await j.selectFrom("delivery_stops").where("id","=",$).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function W7($){return await j.selectFrom("delivery_stops").where("id","=",$).selectAll().executeTakeFirst()??null}async function bY($){return await j.selectFrom("delivery_stops").where("uuid","=",$).selectAll().executeTakeFirst()??null}var j4={};B(j4,{updateStatus:()=>r9,updateRegionsAndPostalCodes:()=>e9,updateCountries:()=>t9,update:()=>a9,store:()=>o9,softDelete:()=>u9,getZonesByCountry:()=>q9,getActiveShippingZones:()=>j9,formatZoneOptions:()=>E9,fetchById:()=>z4,fetchAll:()=>T9,destroy:()=>c9,bulkStore:()=>d9,bulkSoftDelete:()=>i9,bulkDestroy:()=>n9});import{db as R4}from"@stacksjs/database";async function c9($){try{let J=await R4.deleteFrom("shipping_zones").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zone: ${J.message}`);throw J}}async function u9($){try{let J=await R4.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${J.message}`);throw J}}async function n9($){if(!$.length)return 0;try{let J=await R4.deleteFrom("shipping_zones").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zones: ${J.message}`);throw J}}async function i9($){if(!$.length)return 0;try{let J=await R4.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${J.message}`);throw J}}var{randomUUIDv7:s9}=globalThis.Bun;import{db as Q7}from"@stacksjs/database";async function o9($){try{let J=s9(),G={...$$($),uuid:J};await Q7.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await Q7.selectFrom("shipping_zones").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping zone");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zone: ${J.message}`);throw J}}async function d9($){if(!$.length)return 0;try{let J=$.map((X)=>({...$$(X),uuid:s9()})),G=await Q7.insertInto("shipping_zones").values(J).executeTakeFirst();return L(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${J.message}`);throw J}}import{db as T4}from"@stacksjs/database";import{formatDate as E4}from"@stacksjs/orm";async function a9($,J){try{if(!$)throw Error("Shipping zone ID is required for update");let G=await T4.updateTable("shipping_zones").set({...$$(J),updated_at:E4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone: ${G.message}`);throw G}}async function r9($,J){try{let G=await T4.updateTable("shipping_zones").set({status:J,updated_at:E4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone status: ${G.message}`);throw G}}async function t9($,J){try{let G=await T4.updateTable("shipping_zones").set({countries:J,updated_at:E4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone countries");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${G.message}`);throw G}}async function e9($,J,G){try{let X={updated_at:E4(new Date)};if(J!==void 0)X.regions=J;if(G!==void 0)X.postal_codes=G;let Z=await T4.updateTable("shipping_zones").set(X).where("id","=",$).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update regions and postal codes");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${X.message}`);throw X}}var pY={digital:r$,drivers:e$,geocoding:X4,licenses:K4,methods:L4,rates:x4,routes:d$,tracking:S4,zones:j4},mY=pY;var H7={};B(H7,{updateStatus:()=>H3,updateRate:()=>z3,updateDefaultStatus:()=>V3,update:()=>N3,taxFor:()=>$3,store:()=>F3,fetchById:()=>Y3,fetchAll:()=>K3,destroy:()=>G3,bulkStore:()=>L3,bulkDestroy:()=>X3,breakdownFor:()=>N7,activeTaxRates:()=>L7});import{db as lY}from"@stacksjs/database";function cY($){let J=Number($);return Number.isFinite(J)?J/100:0}async function L7($={}){let J=lY.selectFrom("tax_rates").where("status","=","active").selectAll();if($.country)J=J.where("country","=",$.country);let G=await J.execute();if(!$.codes?.length)return G;let X=new Set($.codes);return G.filter((Z)=>X.has(String(Z.code??"")))}function N7($,J,G={}){let X=Math.max(0,Math.round($)),Z=[],Y=0,K=0;for(let W of J){let Q=cY(W.rate),F=Math.round(X*Q),N=Boolean(G.exempt&&W.exemptible);if(N)K+=F;else Y+=F;Z.push({id:Number(W.id),code:String(W.code??""),name:String(W.name??""),rate:Q,amount:N?0:F,exempted:N})}return{taxable:X,components:Z,tax:Y,exempted:K}}async function $3($,J={}){return N7($,await L7(J),J)}import{db as J3}from"@stacksjs/database";async function G3($){try{let J=await J3.deleteFrom("tax_rates").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rate: ${J.message}`);throw J}}async function X3($){if(!$.length)return 0;try{let J=await J3.deleteFrom("tax_rates").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rates: ${J.message}`);throw J}}import{db as Z3}from"@stacksjs/database";async function Y3($){return await Z3.selectFrom("tax_rates").where("id","=",$).selectAll().executeTakeFirst()}async function K3(){return await Z3.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:W3}=globalThis.Bun;import{db as Q3}from"@stacksjs/database";async function F3($){try{return await Q3.transaction(async(J)=>{let G={...$,uuid:W3()};if(G.is_default)await J.updateTable("tax_rates").set({is_default:!1}).execute();let X=await J.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X})}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rate: ${J.message}`);throw J}}async function L3($){if(!$.length)return 0;try{return await Q3.transaction(async(J)=>{let G=0;for(let X of $){let Z={...X,uuid:W3()};if(Z.is_default)await J.updateTable("tax_rates").set({is_default:!1}).execute();if(await J.insertInto("tax_rates").values(Z).executeTakeFirst())G++}return G})}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${J.message}`);throw J}}import{db as q4}from"@stacksjs/database";import{formatDate as k4}from"@stacksjs/orm";async function N3($,J){try{if(!$)throw Error("Tax rate ID is required for update");return await q4.transaction(async(G)=>{let X=await G.selectFrom("tax_rates").select("is_default").where("id","=",$).executeTakeFirst();if(!X)return;let Z=J.is_default??Boolean(X.is_default),Y=k4(new Date);if(Z)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Y}).where("id","!=",$).execute();let K=await G.updateTable("tax_rates").set({...J,updated_at:Y}).where("id","=",$).returningAll().executeTakeFirst();if(!K)return;return K})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function H3($,J){try{let G=await q4.updateTable("tax_rates").set({status:J,updated_at:k4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update tax rate status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate status: ${G.message}`);throw G}}async function z3($,J){try{let G=await q4.updateTable("tax_rates").set({rate:J,updated_at:k4(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update rate information");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update rate information: ${G.message}`);throw G}}async function V3($,J){try{return await q4.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",$).executeTakeFirst())return!1;let Z=k4(new Date);if(J)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Z}).where("id","!=",$).execute();return await G.updateTable("tax_rates").set({is_default:J,updated_at:Z}).where("id","=",$).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var _7={};B(_7,{restaurant:()=>I0,products:()=>f4,default:()=>eY});var f4={};B(f4,{updateStatus:()=>I3,updatePartySize:()=>g3,update:()=>w4,store:()=>C3,fetchWaiting:()=>T3,fetchPurchasedBetweenDates:()=>S3,fetchNotifiedBetweenDates:()=>P3,fetchCountByStatus:()=>E3,fetchCountBySource:()=>_3,fetchCountByQuantity:()=>A3,fetchCountByDateGrouped:()=>k3,fetchCountByDate:()=>O3,fetchCountByAllQuantities:()=>U3,fetchCountBetweenDates:()=>q3,fetchConversionRates:()=>j3,fetchCancelledBetweenDates:()=>R3,fetchById:()=>N$,fetchAll:()=>M3,destroy:()=>x3,bulkStore:()=>h3,bulkDestroy:()=>B3});import{db as z7}from"@stacksjs/database";async function x3($){try{let J=await z7.selectFrom("waitlist_products").where("id","=",$).selectAll().executeTakeFirst();if(!J)return;return await z7.deleteFrom("waitlist_products").where("id","=",$).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist product: ${J.message}`);throw J}}async function B3($){if(!$.length)return 0;try{let J=await z7.deleteFrom("waitlist_products").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${J.message}`);throw J}}import{db as A}from"@stacksjs/database";import{formatDate as T}from"@stacksjs/orm";async function N$($){return await A.selectFrom("waitlist_products").where("id","=",$).selectAll().executeTakeFirst()}async function M3(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function _3($,J){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if($&&J){let Z=T($),Y=T(J);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{source:Y,count:K})=>{return Z[Y]=K,Z},{})}async function O3($=new Date){let J=new Date($);J.setHours(0,0,0,0);let G=new Date($);G.setHours(23,59,59,999);let X=T(J),Z=T(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function A3($){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",$).executeTakeFirst())?.count??0}async function U3($,J){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if($&&J){let Z=T($),Y=T(J);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{quantity:Y,count:K})=>{return Z[Y]=K,Z},{})}async function P3($,J){let G=T($),X=T(J);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",X).whereNotNull("notified_at").execute()}async function S3($,J){let G=T($),X=T(J);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",X).whereNotNull("purchased_at").execute()}async function R3($,J){let G=T($),X=T(J);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",X).whereNotNull("cancelled_at").execute()}async function T3(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function E3($,J,G){let X=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",$);if(J&&G){let Y=T(J),K=T(G);X=X.where("created_at",">=",Y).where("created_at","<=",K)}return(await X.executeTakeFirst())?.count??0}async function j3($,J){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if($&&J){let Q=T($),F=T(J);G=G.where("created_at",">=",Q).where("created_at","<=",F)}let X=await G.execute(),Z=X.reduce((Q,{count:F})=>Q+F,0),Y=X.find((Q)=>Q.status==="purchased")?.count??0,K=Z>0?Y/Z*100:0,W=X.reduce((Q,{status:F,count:N})=>{return Q[F]={count:N,percentage:Z>0?N/Z*100:0},Q},{});return{totalConversionRate:K,statusBreakdown:W}}async function q3($,J){let G=T($),X=T(J);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function k3($,J){let G=A.selectFrom("waitlist_products").select(["created_at"]);if($&&J){let Y=T($),K=T(J);G=G.where("created_at",">=",Y).where("created_at","<=",K)}let Z=(await G.execute()).reduce((Y,{created_at:K})=>{let W=(K||"").split("T")[0]||"unknown";return Y[W]=(Y[W]||0)+1,Y},{});return Object.entries(Z).map(([Y,K])=>({date:Y,count:K})).sort((Y,K)=>Y.date.localeCompare(K.date))}var{randomUUIDv7:f3}=globalThis.Bun;import{db as V7}from"@stacksjs/database";import{formatDate as w3}from"@stacksjs/orm";var uY={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function nY($){return typeof $==="number"||$ instanceof Date?w3($):$}function H$($,J={}){let G=Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let Z of["notified_at","purchased_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=nY(G[Z]);let X=uY[G.status];if(X&&G[X]===void 0&&!J[X])G[X]=w3(new Date);return G}async function C3($){try{let J=f3(),G={...H$($),uuid:J,status:$.status||"waiting"};await V7.insertInto("waitlist_products").values(G).executeTakeFirst();let X=await V7.selectFrom("waitlist_products").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create waitlist product");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist product: ${J.message}`);throw J}}async function h3($){if(!$.length)return 0;try{let J=$.map((X)=>({...H$(X),status:X.status||"waiting",uuid:f3()})),G=await V7.insertInto("waitlist_products").values(J).executeTakeFirst();return L(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${J.message}`);throw J}}import{db as iY}from"@stacksjs/database";import{formatDate as sY}from"@stacksjs/orm";async function w4($,J){try{if(!$)throw Error("Waitlist product ID is required for update");let G=await N$($);if(!G)return;await iY.updateTable("waitlist_products").set({...H$(J,G),updated_at:sY(new Date)}).where("id","=",$).execute();let X=await N$($);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update waitlist product: ${G.message}`);throw G}}async function I3($,J){return await w4($,{status:J})}async function g3($,J){return await w4($,{quantity:J})}var I0={};B(I0,{updateWaitTimes:()=>WZ,updateStatus:()=>YZ,updateQueuePosition:()=>QZ,updatePartySize:()=>KZ,update:()=>h0,store:()=>XZ,fetchWaitingWithQuotedTimes:()=>o3,fetchWaitingWithPartySizes:()=>d3,fetchWaiting:()=>n3,fetchTimeSeriesStats:()=>JZ,fetchTablesTurnedToday:()=>a3,fetchSeatingRate:()=>r3,fetchSeatedStats:()=>$Z,fetchSeatedBetweenDates:()=>u3,fetchNoShowStats:()=>t3,fetchCurrentWaitTimes:()=>e3,fetchCountByTablePreference:()=>b3,fetchCountByPartySize:()=>m3,fetchCountByDate:()=>p3,fetchCountByAllPartySizes:()=>l3,fetchConversionRates:()=>i3,fetchById:()=>z$,fetchBetweenDates:()=>c3,fetchAverageWaitTimes:()=>s3,fetchAll:()=>y3,destroy:()=>D3,bulkStore:()=>ZZ,bulkDestroy:()=>v3});import{db as x7}from"@stacksjs/database";async function D3($){try{let J=await x7.selectFrom("waitlist_restaurants").where("id","=",$).selectAll().executeTakeFirst();if(!J)return;return await x7.deleteFrom("waitlist_restaurants").where("id","=",$).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${J.message}`);throw J}}async function v3($){if(!$.length)return 0;try{let J=await x7.deleteFrom("waitlist_restaurants").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as M}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function z$($){return await M.selectFrom("waitlist_restaurants").where("id","=",$).selectAll().executeTakeFirst()}async function y3(){return await M.selectFrom("waitlist_restaurants").selectAll().execute()}async function b3(){return(await M.selectFrom("waitlist_restaurants").select(["table_preference",M.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((J,{table_preference:G,count:X})=>{return J[G]=X,J},{})}async function p3($=new Date){let J=new Date($);J.setHours(0,0,0,0);let G=new Date($);G.setHours(23,59,59,999);let X=g(J),Z=g(G);return(await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function m3($){return(await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("party_size","=",$).executeTakeFirst())?.count??0}async function l3(){return(await M.selectFrom("waitlist_restaurants").select(["party_size",M.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((J,{party_size:G,count:X})=>{return J[G]=X,J},{})}async function c3($,J){let G=g($),X=g(J);return await M.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",X).execute()}async function u3($,J){let G=g($),X=g(J);return await M.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",X).where("status","=","seated").execute()}async function n3(){return await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function i3(){let $=await M.selectFrom("waitlist_restaurants").select(["status",M.fn.count("id").as("count")]).groupBy("status").execute(),J=$.reduce((Y,{count:K})=>Y+K,0),G=$.find((Y)=>Y.status==="seated")?.count??0,X=J>0?Number(G)/J*100:0,Z=$.reduce((Y,{status:K,count:W})=>{return Y[K]={count:W,percentage:J>0?W/J*100:0},Y},{});return{totalConversionRate:X,statusBreakdown:Z}}async function s3(){let $=await M.selectFrom("waitlist_restaurants").select([M.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),M.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:$?.avg_quoted_wait_time??0,averageActualWaitTime:$?.avg_actual_wait_time??0}}async function o3(){let $=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=$.reduce((X,Z)=>X+(Z.quoted_wait_time??0),0),G=$.length>0?J/$.length:0;return{entries:$,totalQuotedWaitTime:J,averageQuotedWaitTime:G}}async function d3(){let $=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=$.reduce((Z,Y)=>Z+Y.party_size,0),G=$.length>0?J/$.length:0,X=$.reduce((Z,Y)=>{return Z[Y.party_size]=(Z[Y.party_size]||0)+1,Z},{});return{entries:$,totalPartySize:J,averagePartySize:G,partySizeBreakdown:X}}async function a3(){let $=new Date,J=new Date($);J.setHours(0,0,0,0);let G=new Date($);G.setHours(23,59,59,999);let X=g(J),Z=g(G),Y=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",X).where("check_in_time","<=",Z).execute(),K=Y.length,W=Y.reduce((H,z)=>H+z.party_size,0),Q=K>0?W/K:0,F=Y.reduce((H,z)=>{return H[z.table_preference]=(H[z.table_preference]||0)+1,H},{}),N=Y.reduce((H,z)=>{return H[z.party_size]=(H[z.party_size]||0)+1,H},{});return{totalTablesTurned:K,averagePartySize:Q,totalCustomersSeated:W,breakdownByTablePreference:F,breakdownByPartySize:N}}async function r3($,J){let G=g($),X=g(J),Z=await M.selectFrom("waitlist_restaurants").select(["status",M.fn.count("id").as("count")]).where("check_in_time",">=",G).where("check_in_time","<=",X).groupBy("status").execute(),Y=Z.reduce((F,{count:N})=>F+N,0),K=Z.find((F)=>F.status==="seated")?.count??0,W=Y>0?Number(K)/Y*100:0,Q=Z.reduce((F,{status:N,count:H})=>{return F[N]={count:H,percentage:Y>0?H/Y*100:0},F},{});return{totalEntries:Y,seatedEntries:K,seatingRate:W,statusBreakdown:Q}}async function t3($,J){let G=g($),X=g(J),Z=M.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",X),Y=await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",X).executeTakeFirst(),K=await Z.execute(),W=K.length,Q=Y?.count&&Y.count>0?W/Y.count*100:0,F=K.reduce((O,P)=>O+(P.quoted_wait_time??0),0),N=W>0?F/W:0,H=K.reduce((O,P)=>O+P.party_size,0),z=W>0?H/W:0,x=K.reduce((O,P)=>{return O[P.table_preference]=(O[P.table_preference]||0)+1,O},{}),U=K.reduce((O,P)=>{return O[P.party_size]=(O[P.party_size]||0)+1,O},{});return{totalNoShows:W,noShowRate:Q,averageQuotedWaitTime:N,averagePartySize:z,breakdownByTablePreference:x,breakdownByPartySize:U}}async function e3(){let $=await M.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),J=$.reduce((Z,Y)=>Z+(Y.quoted_wait_time||0),0),G=$.reduce((Z,Y)=>Z+(Y.actual_wait_time||0),0),X=$.length;return{averageQuoted:X>0?J/X:0,averageActual:X>0?G/X:0}}async function $Z(){let $=Date.now()-86400000,J=await M.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",$).execute(),G=Array.from({length:24},(X,Z)=>({hour:Z,count:J.filter((Y)=>{return Y.seated_at===Z}).length}));return{total:J.length,byHour:G}}async function JZ(){return(await M.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((J,G)=>{let X=G.created_at;if(!J[X])J[X]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return J[X].total++,J[X][G.status]++,J},{})}var{randomUUIDv7:GZ}=globalThis.Bun;import{db as M7}from"@stacksjs/database";import{formatDate as B7}from"@stacksjs/orm";var oY={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function dY($){if(typeof $==="number")return B7($<=2147483647?$*1000:$);if($ instanceof Date)return B7($);return $}function V$($,J={}){let G=Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0));for(let Z of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=dY(G[Z]);let X=oY[G.status];if(X&&G[X]===void 0&&!J[X])G[X]=B7(new Date);return G}async function XZ($){try{let J=GZ(),G={...V$($),status:$.status||"waiting",uuid:J};await M7.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let X=await M7.selectFrom("waitlist_restaurants").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create restaurant waitlist entry");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${J.message}`);throw J}}async function ZZ($){if(!$.length)return 0;try{let J=$.map((X)=>({...V$(X),status:X.status||"waiting",uuid:GZ()})),G=await M7.insertInto("waitlist_restaurants").values(J).executeTakeFirst();return L(G)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as aY}from"@stacksjs/database";import{formatDate as rY}from"@stacksjs/orm";async function h0($,J){try{if(!$)throw Error("Restaurant waitlist entry ID is required for update");let G=await z$($);if(!G)return;await aY.updateTable("waitlist_restaurants").set({...V$(J,G),updated_at:rY(new Date)}).where("id","=",$).execute();let X=await z$($);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${G.message}`);throw G}}async function YZ($,J){return await h0($,{status:J})}async function KZ($,J){return await h0($,{party_size:J})}async function WZ($,J,G){return await h0($,{quoted_wait_time:J,...G===void 0?{}:{actual_wait_time:G}})}async function QZ($,J){return await h0($,{queue_position:J})}var tY={products:f4,restaurant:I0},eY=tY;var $5={auctions:Y1,coupons:K1,customers:W1,devices:H1,errors:x1,giftCards:_1,orders:j1,payments:q1,products:g1,receipts:p1,restaurant:I0,shippings:F7,tax:H7,waitlists:_7},gV=$5;export{_7 as waitlists,H7 as tax,F7 as shippings,I0 as restaurant,p1 as receipts,g1 as products,q1 as payments,j1 as orders,_1 as giftCards,x1 as errors,H1 as devices,gV as default,W1 as customers,K1 as coupons,$5 as commerce,Y1 as auctions};
|