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