@stacksjs/commerce 0.70.380 → 0.71.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- var H3=Object.defineProperty;var M3=(J)=>J;function x3(J,$){this[J]=M3.bind(null,$)}var B=(J,$)=>{for(var G in $)H3(J,G,{get:$[G],enumerable:!0,configurable:!0,set:x3.bind($,G)})};var z3=(J,$)=>()=>(J&&($=J(J=0)),$);var J0=import.meta.require;var VJ={};B(VJ,{emitOrderShipped:()=>W$,emitOrderRefunded:()=>M0,emitOrderPaid:()=>d,emitOrderOutForDelivery:()=>BJ,emitOrderDelivered:()=>F$,emitOrderCreated:()=>f0,emitOrderCancelled:()=>H0,emitForStatus:()=>k0,canTransition:()=>w0});function w0(J,$){if(J===$)return!0;return y3[J]?.includes($)??!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 f0(J){await Z0("order:created",{order:J})}async function d(J,$){await Z0("order:paid",{order:J,payment:$})}async function W$(J){await Z0("order:shipped",{order:J})}async function BJ(J){await Z0("order:out_for_delivery",{order:J})}async function F$(J){await Z0("order:delivered",{order:J})}async function H0(J,$){await Z0("order:cancelled",{order:J,reason:$})}async function M0(J,$){await Z0("order:refunded",{order:J,refundAmount:$})}async function k0(J,$){switch(J){case"PROCESSING":return d($);case"SHIPPED":return W$($);case"OUT_FOR_DELIVERY":return BJ($);case"DELIVERED":return F$($);case"CANCELLED":return H0($);case"REFUNDED":return M0($);case"PENDING":default:}}var y3;var x0=z3(()=>{y3={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 H4={};B(H4,{update:()=>o1,store:()=>c1,redeem:()=>s1,getActiveCouponsMoMChange:()=>m1,fetchTopRedeemedCoupons:()=>v1,fetchStats:()=>I1,fetchRedemptionTrend:()=>y1,fetchRedemptionStats:()=>D1,fetchCouponCountsByType:()=>g1,fetchCouponCounts:()=>h1,fetchConversionRate:()=>b1,fetchById:()=>G0,fetchByCode:()=>k1,fetchAll:()=>f1,fetchActive:()=>C1,deleteExpiredCoupons:()=>q1,deleteCoupons:()=>E1,deleteCoupon:()=>T1});import{db as e0}from"@stacksjs/database";import{formatDate as B3}from"@stacksjs/orm";function Q(J){if(typeof J==="number")return Number.isFinite(J)?J:0;if(typeof J==="bigint")return Number(J);if(!J||typeof J!=="object")return 0;let $=J;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[G]!==void 0&&$[G]!==null)return Q($[G]);if(Array.isArray(J))return J.reduce((G,X)=>G+Q(X),0);return 0}async function T1(J){let $=await e0.deleteFrom("coupons").where("id","=",J).executeTakeFirst();return Q($)>0}async function E1(J){if(!J.length)return 0;return(await e0.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function q1(){let J=B3(new Date),$=await e0.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return Q($)}import{db as x}from"@stacksjs/database";import{extractDate as j1,formatDate as w1}from"@stacksjs/orm";import{camelCase as V3}from"@stacksjs/strings";function $$(J){let $=Object.fromEntries(Object.entries(J).map(([G,X])=>[V3(G),X]));if($.endDate)$.endDate=j1(new Date($.endDate));if($.startDate)$.startDate=j1(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function f1(){return(await x.selectFrom("coupons").selectAll().execute()).map($$)}async function G0(J){let $=await x.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return $$($);return}async function k1(J){let $=await x.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return $$($);return}async function C1(){let J=w1(new Date);return(await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map($$)}async function I1(){let J=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).executeTakeFirst(),$=w1(new Date),G=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(x.fn.count("id").as("count")).executeTakeFirst(),X=await x.selectFrom("coupons").select(["discount_type",x.fn.count("id").as("count")]).groupBy("discount_type").execute(),Z=await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),Y=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",$).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(J?.count||0),active:Number(G?.count||0),by_type:X,most_used:Z,upcoming:Y}}async function h1(){let J=new Date,$=new Date(J);$.setDate(J.getDate()-7);let G=new Date(J);G.setMonth(J.getMonth()-1);let X=new Date(J);X.setFullYear(J.getFullYear()-1);let Z=await t0(null,null,J),Y=await t0($,null,J),L=await t0(G,null,J),K=await t0(X,null,J);return{week:Y,month:L,year:K,all_time:Z}}async function t0(J,$,G){let X=x.selectFrom("coupons");if(J)X=X.where("created_at",">=",J.toISOString());if($)X=X.where("created_at","<=",$.toISOString());let Z=await X.select(x.fn.count("id").as("count")).executeTakeFirst(),Y=x.selectFrom("coupons");if(J)Y=Y.where("created_at",">=",J.toISOString());if($)Y=Y.where("created_at","<=",$.toISOString());Y=Y.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let L=await Y.select(x.fn.count("id").as("count")).executeTakeFirst(),K=Number(Z?.count||0),W=Number(L?.count||0),F=K-W;return{total:K,active:W,inactive:F}}async function g1(){let J=new Date,$=await x.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:X}of $){let Z=await x.selectFrom("coupons").where("discount_type","=",X).select(x.fn.count("id").as("count")).executeTakeFirst(),Y=await x.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),L=Number(Z?.count||0),K=Number(Y?.count||0);G[X]={total:L,active:K,inactive:L-K}}return G}async function D1(){let J=await x.selectFrom("coupons").select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,G=new Date($);G.setDate($.getDate()-7);let X=new Date($);X.setMonth($.getMonth()-1);let Z=new Date($);Z.setFullYear($.getFullYear()-1);let Y=await x.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await x.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),K=await x.selectFrom("coupons").where("updated_at",">=",Z.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await x.selectFrom("coupons").select(["discount_type",x.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),F={};return W.forEach((N)=>{F[N.discount_type]=Number(N.total||0)}),{total:Number(J?.total||0),week:Number(Y?.total||0),month:Number(L?.total||0),year:Number(K?.total||0),by_type:F}}async function v1(J=5){return await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(J).execute()}async function y1(J=30){let $=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-J);let X=await x.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),Z={};return X.forEach((Y)=>{let L=Y.updated_at?new Date(Y.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!Z[L])Z[L]=0;Z[L]+=Y?.usage_count||0}),Object.entries(Z).map(([Y,L])=>({date:Y,count:L}))}async function b1(){let J=new Date,$=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),G=await x.selectFrom("coupons").where("usage_count",">",0).select(x.fn.count("id").as("count")).executeTakeFirst(),X=Number($?.count||0),Z=Number(G?.count||0);return{rate:X>0?Z/X*100:0,total_active:X,total_redeemed:Z}}async function m1(){let J=new Date,$=new Date(J.getFullYear(),J.getMonth(),1),G=new Date(J.getFullYear(),J.getMonth()-1,1),X=new Date(J.getFullYear(),J.getMonth(),0),Z=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),Y=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",G).executeTakeFirst(),L=Number(Z?.count||0),K=Number(Y?.count||0),W=L-K,F=K!==0?W/K*100:L>0?100:0;return{current_month:L,previous_month:K,difference:W,percentage_change:F}}var{randomUUIDv7:A3}=globalThis.Bun;import{db as p1}from"@stacksjs/database";import{HttpError as l1}from"@stacksjs/error-handling";import{isUniqueViolation as O3}from"@stacksjs/orm";async function c1(J){try{let $=A3();return await p1.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await p1.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof l1)throw $;if(O3($))throw new l1(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as n1}from"@stacksjs/database";import{HttpError as u1}from"@stacksjs/error-handling";import{formatDate as i1,isUniqueViolation as _3}from"@stacksjs/orm";async function o1(J,$){if(!await G0(J))return;try{return await n1.updateTable("coupons").set({...$,updated_at:i1(new Date)}).where("id","=",J).execute(),await G0(J)}catch(X){if(X instanceof u1)throw X;if(_3(X))throw new u1(409,"A coupon with this code already exists");if(X instanceof Error)throw Error(`Failed to update coupon: ${X.message}`);throw X}}async function s1(J){let $=i1(new Date),G=await n1.unsafe(`UPDATE coupons
2
+ var FZ=Object.defineProperty;var LZ=($)=>$;function NZ($,J){this[$]=LZ.bind(null,J)}var B=($,J)=>{for(var G in J)FZ($,G,{get:J[G],enumerable:!0,configurable:!0,set:NZ.bind(J,G)})};var HZ=($,J)=>()=>($&&(J=$($=0)),J);var n=import.meta.require;var V6={};B(V6,{emitOrderShipped:()=>j$,emitOrderRefunded:()=>S0,emitOrderPaid:()=>Y0,emitOrderOutForDelivery:()=>z6,emitOrderDelivered:()=>q$,emitOrderCreated:()=>s0,emitOrderCancelled:()=>U0,emitForStatus:()=>o0,canTransition:()=>i0});function i0($,J){if($===J)return!0;return mZ[$]?.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 z6($){await z0("order:out_for_delivery",{order:$})}async function q$($){await z0("order:delivered",{order:$})}async function U0($,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 z6(J);case"DELIVERED":return q$(J);case"CANCELLED":return U0(J);case"REFUNDED":return S0(J);case"PENDING":default:}}var mZ;var P0=HZ(()=>{mZ={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 Z1={};B(Z1,{winnerNotification:()=>BZ,settleAuction:()=>r4,settle:()=>b0,rulesFor:()=>y0,resolveBid:()=>v0,pledges:()=>X1,pledgeTotal:()=>J1,pledgeLevels:()=>R7,placeBid:()=>m4,outbidNotification:()=>xZ,openAuction:()=>o4,nextMinimumBid:()=>o,makePledge:()=>A7,lots:()=>e4,leadingBid:()=>g0,incrementFor:()=>D,fetchPledges:()=>G1,fetchItems:()=>d,fetchCatalogue:()=>n4,fetchAuctionForEvent:()=>u4,fetchAuction:()=>m,extendedCloseAt:()=>D0,engine:()=>c4,effectiveCloseAt:()=>G0,determineWinner:()=>A0,currencyFor:()=>b4,closingSoonNotification:()=>MZ,closingSoon:()=>t4,closeItem:()=>p0,closeDueItems:()=>d4,closeAuction:()=>a4,broadcastPledge:()=>v4,broadcastItemClosed:()=>y4,broadcastBid:()=>D4,bidsForItem:()=>f4,bidsForAuction:()=>C4,bidsByBidder:()=>h4,bids:()=>l4,biddersFor:()=>I4,auctionTotals:()=>i4,auctionChannel:()=>x$,DEFAULT_INCREMENT_LADDER:()=>s});var l4={};B(l4,{placeBid:()=>m4,leadingBid:()=>g0,bidsForItem:()=>f4,bidsForAuction:()=>C4,bidsByBidder:()=>h4,biddersFor:()=>I4});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 f4($){return await i.selectFrom("bids").selectAll().where("auction_item_id","=",$).orderBy("placed_at","desc").execute()??[]}async function C4($){return await i.selectFrom("bids").selectAll().where("auction_id","=",$).orderBy("placed_at","asc").execute()??[]}async function h4($,J){return await i.selectFrom("bids").selectAll().where("auction_id","=",$).where("bidder_email","=",J.toLowerCase()).orderBy("placed_at","desc").execute()??[]}async function I4($){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:VZ}=globalThis.Bun;import{db as p4}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 g4(){try{return(await import("@stacksjs/realtime")).emit??null}catch{return null}}async function D4($){let J=await g4();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 v4($,J){let G=await g4();if(!G)return;await G(x$($.auction_id),"pledge.made",{donorName:$.donor_name,amount:$.amount,level:$.level??null,runningTotal:J})}async function y4($,J,G){let X=await g4();if(!X)return;await X(x$($),"item.closed",{itemId:J,...G})}import{config as zZ}from"@stacksjs/config";function _7(){return zZ.commerce??{}}function O7(){return _7().auction??{}}function y0($){let J=O7();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 b4($){return $?.currency??O7().currency??_7().currency??"USD"}function B$($){return $.toISOString().slice(0,19).replace("T"," ")}async function m4($){let J=$.now??new Date,G=await p4.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 p4.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 p4.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 R=Q.leader?.isChallenger===!0,O=VZ();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:R?"leading":"outbid",placed_at:B$(J)}).execute(),Y){if(R)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 D4(z).catch(()=>{return}),z}var c4={};B(c4,{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 e4={};B(e4,{settleAuction:()=>r4,openAuction:()=>o4,fetchItems:()=>d,fetchCatalogue:()=>n4,fetchAuctionForEvent:()=>u4,fetchAuction:()=>m,closingSoon:()=>t4,closeItem:()=>p0,closeDueItems:()=>d4,closeAuction:()=>a4,auctionTotals:()=>i4});import{db as v}from"@stacksjs/database";async function m($){return await v.selectFrom("auctions").selectAll().where("id","=",$).executeTakeFirst()??null}async function u4($){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 n4($){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 i4($){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 s4($){return $.toISOString().slice(0,19).replace("T"," ")}async function o4($,J=new Date){return await X0.updateTable("auctions").set({status:"open",opens_at:s4(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:s4(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 y4($.auction_id,$.id,{status:X.status,amount:X.amount,winnerName:X.winnerName}).catch(()=>{return}),X}async function d4($,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 a4($,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:s4(J)}).where("id","=",$).execute(),X}async function r4($,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:b4(G),goalAmount:G.goal_amount??null})}async function t4($,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 $1($,J="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:J,minimumFractionDigits:0}).format($/100)}function xZ($,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 ${$1($.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 BZ($,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 ${$1($.amount,J)}. The school will be in touch with payment and pickup details.`,data:{itemId:$.itemId,lotNumber:$.lotNumber,title:$.title,amount:$.amount}}}function MZ($,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 ${$1(G,X)}.`,data:{itemId:$.id,lotNumber:$.lot_number,title:$.title,currentBid:G,closesAt:$.closes_at}}}var X1={};B(X1,{pledgeTotal:()=>J1,pledgeLevels:()=>R7,makePledge:()=>A7,fetchPledges:()=>G1});var{randomUUIDv7:_Z}=globalThis.Bun;import{db as m0}from"@stacksjs/database";async function A7($){let J=_Z();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 v4(G,await J1($.auctionId)).catch(()=>{return}),G}async function J1($){return(await m0.selectFrom("pledges").select(["amount"]).where("auction_id","=",$).where("status","=","confirmed").execute()??[]).reduce((G,X)=>G+X.amount,0)}async function G1($){return await m0.selectFrom("pledges").selectAll().where("auction_id","=",$).orderBy("amount","desc").execute()??[]}async function R7($){let J=(await G1($)).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 Y1={};B(Y1,{update:()=>u7,store:()=>p7,redeem:()=>n7,getActiveCouponsMoMChange:()=>v7,fetchTopRedeemedCoupons:()=>I7,fetchStats:()=>w7,fetchRedemptionTrend:()=>g7,fetchRedemptionStats:()=>h7,fetchCouponCountsByType:()=>C7,fetchCouponCounts:()=>f7,fetchConversionRate:()=>D7,fetchById:()=>N0,fetchByCode:()=>q7,fetchAll:()=>j7,fetchActive:()=>k7,deleteExpiredCoupons:()=>P7,deleteCoupons:()=>S7,deleteCoupon:()=>U7});import{db as M$}from"@stacksjs/database";import{formatDate as OZ}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 U7($){let J=await M$.deleteFrom("coupons").where("id","=",$).executeTakeFirst();return L(J)>0}async function S7($){if(!$.length)return 0;return(await M$.deleteFrom("coupons").where("id","in",$).execute()).length||0}async function P7(){let $=OZ(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 T7}from"@stacksjs/orm";import{camelCase as AZ}from"@stacksjs/strings";function O$($){let J=Object.fromEntries(Object.entries($).map(([G,X])=>[AZ(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 j7(){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 q7($){let J=await V.selectFrom("coupons").where("code","=",$).selectAll().executeTakeFirst();if(J)return O$(J);return}async function k7(){let $=T7(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).selectAll().execute()).map(O$)}async function w7(){let $=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).executeTakeFirst(),J=T7(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 f7(){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 C7(){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 h7(){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 I7($=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 g7($=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 D7(){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 v7(){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:RZ}=globalThis.Bun;import{db as y7}from"@stacksjs/database";import{HttpError as b7}from"@stacksjs/error-handling";import{isUniqueViolation as UZ}from"@stacksjs/orm";async function p7($){try{let J=RZ();return await y7.insertInto("coupons").values({...$,uuid:J}).executeTakeFirst(),await y7.selectFrom("coupons").where("uuid","=",J).selectAll().executeTakeFirst()}catch(J){if(J instanceof b7)throw J;if(UZ(J))throw new b7(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 l7}from"@stacksjs/database";import{HttpError as m7}from"@stacksjs/error-handling";import{formatDate as c7,isUniqueViolation as SZ}from"@stacksjs/orm";async function u7($,J){if(!await N0($))return;try{return await l7.updateTable("coupons").set({...J,updated_at:c7(new Date)}).where("id","=",$).execute(),await N0($)}catch(X){if(X instanceof m7)throw X;if(SZ(X))throw new m7(409,"A coupon with this code already exists");if(X instanceof Error)throw Error(`Failed to update coupon: ${X.message}`);throw X}}async function n7($){let J=c7(new Date),G=await l7.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,$,$]),X=typeof G?.execute==="function"?await G.execute():G;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0){let W=await G0(J);if(W)return{ok:!0,coupon:W};return{ok:!1,reason:"not-found"}}let Y=await G0(J);if(!Y)return{ok:!1,reason:"not-found"};if(!Y.isActive)return{ok:!1,reason:"inactive"};let L=!Y.startDate||Y.startDate<=$,K=!Y.endDate||Y.endDate>=$;if(!L||!K)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var M4={};B(M4,{update:()=>X7,store:()=>J7,fetchById:()=>J$,fetchAll:()=>t1,destroy:()=>a1,bulkDestroy:()=>r1});import{db as d1}from"@stacksjs/database";async function a1(J){try{let $=await d1.deleteFrom("customers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function r1(J){if(!J.length)return 0;try{let $=await d1.deleteFrom("customers").where("id","in",J).executeTakeFirst();return Q($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as e1}from"@stacksjs/database";async function J$(J){return await e1.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function t1(){return await e1.selectFrom("customers").selectAll().execute()}import{db as R3}from"@stacksjs/database";import{HttpError as $7}from"@stacksjs/error-handling";import{isUniqueViolation as U3}from"@stacksjs/orm";async function J7(J){try{let $={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await R3.insertInto("customers").values($).executeTakeFirst();if(!G)throw Error("Failed to create customer");let X=G.insertId||Number(G.numInsertedOrUpdatedRows);return await J$(Number(X))}catch($){if($ instanceof $7)throw $;if(U3($))throw new $7(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as P3}from"@stacksjs/database";import{HttpError as G7}from"@stacksjs/error-handling";import{formatDate as S3,isUniqueViolation as T3}from"@stacksjs/orm";async function X7(J,$){try{if(!J)throw Error("Customer ID is required for update");let G=await P3.updateTable("customers").set({...$,updated_at:S3(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof G7)throw G;if(T3(G))throw new G7(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var A4={};B(A4,{updateStatus:()=>R7,updatePrintCount:()=>U7,update:()=>_7,storePrintDevicesExport:()=>B7,store:()=>A7,getPrinterStatusCounts:()=>M7,fetchErrorsByDeviceId:()=>N7,fetchById:()=>l,fetchAll:()=>G$,exportPrintDevices:()=>X$,downloadPrintDevices:()=>z7,destroy:()=>Y7,countTotalPrints:()=>W7,countPrintsByDeviceId:()=>F7,countAll:()=>K7,calculatePrinterHealth:()=>H7,calculateErrorRate:()=>Q7,bulkStore:()=>O7,bulkDestroy:()=>L7});import{db as Z7}from"@stacksjs/database";async function Y7(J){try{let $=await Z7.deleteFrom("print_devices").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function L7(J){if(!J.length)return 0;try{let $=await Z7.deleteFrom("print_devices").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as E3}from"ts-spreadsheets";import{db as j}from"@stacksjs/database";async function l(J){return await j.selectFrom("print_devices").where("id","=",J).selectAll().executeTakeFirst()}async function G$(){return await j.selectFrom("print_devices").selectAll().execute()}async function K7(){let J=await j.selectFrom("print_devices").select(j.fn.count("id").as("count")).executeTakeFirst();return Number(J?.count||0)}async function W7(){let J=await j.selectFrom("print_devices").select(j.fn.sum("print_count").as("total")).executeTakeFirst();return Number(J?.total||0)}async function F7(J){return(await j.selectFrom("print_devices").select("print_count").where("id","=",J).executeTakeFirst())?.print_count??0}async function Q7(){let J=await j.selectFrom("receipts").select([j.fn.count("id").as("total"),j.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.failed_count??0)/J.total*100)}async function N7(J){return await j.selectFrom("receipts").where("print_device_id","=",J).where("status","=","failed").selectAll().execute()}async function H7(){let J=await j.selectFrom("print_devices").select([j.fn.count("id").as("total"),j.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.online_count??0)/J.total*100)}async function M7(){return(await j.selectFrom("print_devices").select(["status",j.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,G)=>{return $[G.status]=Number(G.count||0),$},{})}function x4(J,$,G=$){let X=J;return X[String($)]??X[G]}function q3(J){if(J instanceof Date)return J;if(typeof J==="number")return new Date(J);if(typeof J==="string")return new Date(/^\d+$/.test(J)?Number(J):J);return new Date(Number.NaN)}function x7(J,$,G=$){let X=x4(J,$,G);if(typeof X==="number")return X;let Z=Number(X);return Number.isFinite(Z)?Z:0}function T0(J,$,G=$){let X=x4(J,$,G);return X==null?"":String(X)}async function X$(J="csv"){let $=await G$(),G=j3($);return E3(G,{type:J})}function j3(J){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=J.map((X)=>{return[x7(X,"id"),T0(X,"name"),T0(X,"macAddress","mac_address"),T0(X,"location"),T0(X,"terminal"),T0(X,"status"),q3(x4(X,"lastPing","last_ping")).toLocaleString(),x7(X,"printCount","print_count")]});return{headings:$,data:G}}async function z7(J="csv",$){let G=await X$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function B7(J="csv",$){let G=await X$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}var{randomUUIDv7:V7}=globalThis.Bun;import{db as z4}from"@stacksjs/database";async function A7(J){try{let $=V7(),G={last_ping:0,print_count:0,...J,uuid:$};return await z4.insertInto("print_devices").values(G).executeTakeFirst(),await z4.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function O7(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={last_ping:0,print_count:0,...G,uuid:V7()};await z4.insertInto("print_devices").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as B4}from"@stacksjs/database";import{formatDate as V4}from"@stacksjs/orm";async function _7(J,$){if(!await l(J))return;try{return await B4.updateTable("print_devices").set({...$,updated_at:V4(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device: ${X.message}`);throw X}}async function R7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await B4.updateTable("print_devices").set({status:$,updated_at:V4(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device status: ${X.message}`);throw X}}async function U7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await B4.updateTable("print_devices").set({print_count:$,updated_at:V4(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print count: ${X.message}`);throw X}}var R4={};B(R4,{update:()=>k7,unresolveGroup:()=>g7,resolveGroup:()=>I7,ignoreGroup:()=>h7,fetchTimeline:()=>f7,fetchStats:()=>w7,fetchGrouped:()=>q7,fetchById:()=>E7,fetchByGroup:()=>j7,fetchAll:()=>Y$,destroyGroup:()=>T7,destroy:()=>P7,bulkUpdateStatus:()=>C7,bulkDestroy:()=>S7});import{db as O4}from"@stacksjs/database";import{log as _4}from"@stacksjs/logging";async function P7(J){try{return await O4.deleteFrom("errors").where("id","=",J).execute(),!0}catch($){return _4.error("[commerce/errors] destroy failed",{id:J,error:$}),!1}}async function S7(J){try{return await O4.deleteFrom("errors").where("id","in",J).execute(),!0}catch($){return _4.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:$}),!1}}async function T7(J,$){try{return await O4.deleteFrom("errors").where("type","=",J).where("message","=",$).execute(),!0}catch(G){return _4.error("[commerce/errors] destroyGroup failed",{type:J,message:$,error:G}),!1}}import{db as Z$}from"@stacksjs/database";async function E7(J){return await Z$.selectFrom("errors").where("id","=",J).selectAll().executeTakeFirst()}async function Y$(){return await Z$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function q7(){let J=await Z$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let X of J){let Z=`${X.type}:${X.message}`;if(!$.has(Z))$.set(Z,{errors:[],firstSeen:new Date(X.created_at),lastSeen:new Date(X.created_at)});let Y=$.get(Z);Y.errors.push(X);let L=new Date(X.created_at);if(L<Y.firstSeen)Y.firstSeen=L;if(L>Y.lastSeen)Y.lastSeen=L}let G=[];for(let[X,Z]of $){let Y=Z.errors[0];if(!Y)continue;let L=Z.errors.find((W)=>W.status!==null)?.status,K="unresolved";if(L===1)K="resolved";else if(L===2)K="ignored";G.push({id:Y.id,type:Y.type,message:Y.message,stack:Y.stack,status:K,count:Z.errors.length,first_seen:Z.firstSeen.toISOString(),last_seen:Z.lastSeen.toISOString(),error_ids:Z.errors.map((W)=>W.id)})}return G.sort((X,Z)=>new Date(Z.last_seen).getTime()-new Date(X.last_seen).getTime()),G}async function j7(J,$){return await Z$.selectFrom("errors").where("type","=",J).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function w7(){let J=await Y$(),$=new Date,G=new Date($.getTime()-86400000),X=new Date($.getTime()-172800000),Z=J.filter((K)=>new Date(K.created_at)>=G).length,Y=J.filter((K)=>{let W=new Date(K.created_at);return W>=X&&W<G}).length,L=Y===0?Z>0?100:0:Math.round((Z-Y)/Y*100);return{total:J.length,unresolved:J.filter((K)=>K.status===null||K.status===0).length,resolved:J.filter((K)=>K.status===1).length,ignored:J.filter((K)=>K.status===2).length,last_24h:Z,trend:L}}async function f7(){let J=await Y$(),$=new Date,G=[];for(let X=23;X>=0;X--){let Z=new Date($.getTime()-X*60*60*1000);Z.setMinutes(0,0,0);let Y=new Date(Z.getTime()+3600000),L=J.filter((K)=>{let W=new Date(K.created_at);return W>=Z&&W<Y}).length;G.push({hour:Z.toISOString(),count:L})}return G}import{db as E0}from"@stacksjs/database";import{sql as q0}from"@stacksjs/database";import{log as j0}from"@stacksjs/logging";async function k7(J,$){try{return await E0.updateTable("errors").set({...$,updated_at:q0.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(G){return j0.error("[commerce/errors] update failed",{id:J,error:G}),!1}}async function C7(J,$){try{return await E0.updateTable("errors").set({status:$,updated_at:q0.raw("CURRENT_TIMESTAMP")}).where("id","in",J).execute(),!0}catch(G){return j0.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:$,error:G}),!1}}async function I7(J,$){try{return await E0.updateTable("errors").set({status:1,updated_at:q0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return j0.error("[commerce/errors] resolveGroup failed",{type:J,message:$,error:G}),!1}}async function h7(J,$){try{return await E0.updateTable("errors").set({status:2,updated_at:q0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return j0.error("[commerce/errors] ignoreGroup failed",{type:J,message:$,error:G}),!1}}async function g7(J,$){try{return await E0.updateTable("errors").set({status:0,updated_at:q0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return j0.error("[commerce/errors] unresolveGroup failed",{type:J,message:$,error:G}),!1}}var P4={};B(P4,{updateBalance:()=>$J,update:()=>t7,store:()=>d7,fetchTotalValue:()=>l7,fetchTotalCurrentBalance:()=>c7,fetchStats:()=>y7,fetchById:()=>X0,fetchByCode:()=>U4,fetchAll:()=>D7,fetchActive:()=>v7,destroy:()=>n7,compareActiveGiftCards:()=>m7,checkBalance:()=>b7,calculateGiftCardValues:()=>p7,bulkDestroy:()=>i7});import{db as u7}from"@stacksjs/database";import{formatDate as U5}from"@stacksjs/orm";import{db as P,sql as C}from"@stacksjs/database";import{formatDate as s,toTimestamp as N0}from"@stacksjs/orm";import{aggregateFunctions as w3,db as f3}from"@stacksjs/database";async function h(J,$,G){let X=f3.selectFrom(J);if(G)X=G(X);X=X.select(Object.entries($).map(([L,K])=>{let W=K.column??"id",F=w3[K.kind](W);if(K.filter)F=F.filterWhere(K.filter.column,K.filter.op,K.filter.value);return F.as(L)}));let Z=await X.executeTakeFirst(),Y={};for(let L of Object.keys($)){let K=Z?.[L];Y[L]=typeof K==="number"?K:Number(K??0)||0}return Y}async function D7(){return await P.selectFrom("gift_cards").selectAll().execute()}async function X0(J){return await P.selectFrom("gift_cards").where("id","=",J).selectAll().executeTakeFirst()}async function U4(J){return await P.selectFrom("gift_cards").where("code","=",J).selectAll().executeTakeFirst()}async function v7(){return await P.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function y7(){let{count:J}=await h("gift_cards",{count:{kind:"count"}}),$=N0(new Date),G=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal($)} OR expiry_date IS NULL)`).select(P.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("gift_cards").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute(),{count:Z}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:Y}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:L}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance > 0.75`)),K=new Date;K.setDate(K.getDate()+30);let W=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",N0(K)).where("expiry_date",">=",$).selectAll().limit(5).execute(),F=await P.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:J,active:Number(G?.count||0),by_status:X.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:Z,medium:Y,high:L},expiring_soon:W,recently_used:F}}async function b7(J){let $=await U4(J);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function m7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),L=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",s(Z)).where("created_at","<=",s(X)).executeTakeFirst(),K=Number(Y?.count||0),W=Number(L?.count||0),F=K-W,N=W!==0?F/W*100:K>0?100:0;return{current_period:K,previous_period:W,difference:F,percentage_change:N,days_range:J}}async function p7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),L=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",s(Z)).where("created_at","<=",s(X)).executeTakeFirst(),K=Number(Y?.total_initial||0),W=Number(Y?.total_balance||0),F=Number(Y?.card_count||0),N=Number(L?.total_initial||0),H=Number(L?.total_balance||0),M=Number(L?.card_count||0),O=K>0?(K-W)/K*100:0,R=N>0?(N-H)/N*100:0,_=F>0?K/F:0,U=F>0?W/F:0,m=K-N,t=W-H,$0=F-M,Q0=N!==0?m/N*100:K>0?100:0,p=H!==0?t/H*100:W>0?100:0,N3=M!==0?$0/M*100:F>0?100:0;return{current_period:{total_initial_value:K,total_remaining_balance:W,utilization_rate:O,card_count:F,average_initial_value:_,average_remaining_balance:U},previous_period:{total_initial_value:N,total_remaining_balance:H,utilization_rate:R,card_count:M},comparison:{initial_value:{difference:m,percentage:Math.abs(Q0),is_increase:m>=0},balance:{difference:t,percentage:Math.abs(p),is_increase:t>=0},card_count:{difference:$0,percentage:Math.abs(N3),is_increase:$0>=0}},days_range:J}}async function l7(){let{total_value:J}=await h("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:J}}async function c7(){let{total_balance:J}=await h("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:J}}async function n7(J){let $=await u7.deleteFrom("gift_cards").where("id","=",J).executeTakeFirst();return Q($)>0}async function i7(J){if(!J.length)return 0;let $=await u7.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return Q($)}var{randomUUIDv7:k3}=globalThis.Bun;import{db as o7}from"@stacksjs/database";import{HttpError as s7}from"@stacksjs/error-handling";import{isUniqueViolation as C3}from"@stacksjs/orm";async function d7(J){let $=J,G={...J,current_balance:$.current_balance??$.initial_balance,status:J.status||"ACTIVE",is_active:$.is_active??!0,uuid:k3()};try{let X=await o7.insertInto("gift_cards").values(G).executeTakeFirst(),Z=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if(Z)return await o7.selectFrom("gift_cards").where("id","=",Z).selectAll().executeTakeFirst();return}catch(X){if(X instanceof s7)throw X;if(C3(X))throw new s7(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 r7}from"@stacksjs/database";import{HttpError as a7}from"@stacksjs/error-handling";import{formatDate as e7,isUniqueViolation as I3}from"@stacksjs/orm";async function t7(J,$){if(!await X0(J))return;try{return await r7.updateTable("gift_cards").set({...$,updated_at:e7(new Date)}).where("id","=",J).execute(),await X0(J)}catch(X){if(X instanceof a7)throw X;if(I3(X))throw new a7(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 $J(J,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let G=e7(new Date),X=await r7.unsafe(`UPDATE gift_cards
8
+ AND (end_date IS NULL OR end_date >= ?)`,[J,$,J,J]),X=typeof G?.execute==="function"?await G.execute():G;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0){let Q=await N0($);if(Q)return{ok:!0,coupon:Q};return{ok:!1,reason:"not-found"}}let Y=await N0($);if(!Y)return{ok:!1,reason:"not-found"};if(!Y.isActive)return{ok:!1,reason:"inactive"};let K=!Y.startDate||Y.startDate<=J,W=!Y.endDate||Y.endDate>=J;if(!K||!W)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var K1={};B(K1,{update:()=>$J,store:()=>t7,fetchById:()=>A$,fetchAll:()=>a7,destroy:()=>s7,bulkDestroy:()=>o7});import{db as i7}from"@stacksjs/database";async function s7($){try{let J=await i7.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 o7($){if(!$.length)return 0;try{let J=await i7.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 d7}from"@stacksjs/database";async function A$($){return await d7.selectFrom("customers").where("id","=",$).selectAll().executeTakeFirst()}async function a7(){return await d7.selectFrom("customers").selectAll().execute()}import{db as PZ}from"@stacksjs/database";import{HttpError as r7}from"@stacksjs/error-handling";import{isUniqueViolation as EZ}from"@stacksjs/orm";async function t7($){try{let J={...$,avatar:$.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await PZ.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 r7)throw J;if(EZ(J))throw new r7(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 TZ}from"@stacksjs/database";import{HttpError as e7}from"@stacksjs/error-handling";import{formatDate as jZ,isUniqueViolation as qZ}from"@stacksjs/orm";async function $J($,J){try{if(!$)throw Error("Customer ID is required for update");let G=await TZ.updateTable("customers").set({...J,updated_at:jZ(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof e7)throw G;if(qZ(G))throw new e7(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var N1={};B(N1,{updateStatus:()=>_J,updatePrintCount:()=>OJ,update:()=>MJ,storePrintDevicesExport:()=>zJ,store:()=>xJ,getPrinterStatusCounts:()=>LJ,fetchErrorsByDeviceId:()=>QJ,fetchById:()=>a,fetchAll:()=>R$,exportPrintDevices:()=>U$,downloadPrintDevices:()=>HJ,destroy:()=>GJ,countTotalPrints:()=>YJ,countPrintsByDeviceId:()=>KJ,countAll:()=>ZJ,calculatePrinterHealth:()=>FJ,calculateErrorRate:()=>WJ,bulkStore:()=>BJ,bulkDestroy:()=>XJ});import{db as JJ}from"@stacksjs/database";async function GJ($){try{let J=await JJ.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 XJ($){if(!$.length)return 0;try{let J=await JJ.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 kZ}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 R$(){return await q.selectFrom("print_devices").selectAll().execute()}async function ZJ(){let $=await q.selectFrom("print_devices").select(q.fn.count("id").as("count")).executeTakeFirst();return Number($?.count||0)}async function YJ(){let $=await q.selectFrom("print_devices").select(q.fn.sum("print_count").as("total")).executeTakeFirst();return Number($?.total||0)}async function KJ($){return(await q.selectFrom("print_devices").select("print_count").where("id","=",$).executeTakeFirst())?.print_count??0}async function WJ(){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 QJ($){return await q.selectFrom("receipts").where("print_device_id","=",$).where("status","=","failed").selectAll().execute()}async function FJ(){let $=await q.selectFrom("print_devices").select([q.fn.count("id").as("total"),q.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!$?.total||$.total===0)return 0;return Number(($.online_count??0)/$.total*100)}async function LJ(){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 W1($,J,G=J){let X=$;return X[String(J)]??X[G]}function wZ($){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 NJ($,J,G=J){let X=W1($,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=W1($,J,G);return X==null?"":String(X)}async function U$($="csv"){let J=await R$(),G=fZ(J);return kZ(G,{type:$})}function fZ($){let J=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=$.map((X)=>{return[NJ(X,"id"),l0(X,"name"),l0(X,"macAddress","mac_address"),l0(X,"location"),l0(X,"terminal"),l0(X,"status"),wZ(W1(X,"lastPing","last_ping")).toLocaleString(),NJ(X,"printCount","print_count")]});return{headings:J,data:G}}async function HJ($="csv",J){let G=await U$($),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${$}`;return G.download(J||X)}async function zJ($="csv",J){let G=await U$($),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${$}`;G.store(J||X)}var{randomUUIDv7:VJ}=globalThis.Bun;import{db as Q1}from"@stacksjs/database";async function xJ($){try{let J=VJ(),G={last_ping:0,print_count:0,...$,uuid:J};return await Q1.insertInto("print_devices").values(G).executeTakeFirst(),await Q1.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 BJ($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={last_ping:0,print_count:0,...G,uuid:VJ()};await Q1.insertInto("print_devices").values(X).execute(),J++}return J}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as F1}from"@stacksjs/database";import{formatDate as L1}from"@stacksjs/orm";async function MJ($,J){if(!await a($))return;try{return await F1.updateTable("print_devices").set({...J,updated_at:L1(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 _J($,J){if(!await a($))throw Error(`Print device with ID ${$} not found`);try{return await F1.updateTable("print_devices").set({status:J,updated_at:L1(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 OJ($,J){if(!await a($))throw Error(`Print device with ID ${$} not found`);try{return await F1.updateTable("print_devices").set({print_count:J,updated_at:L1(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 V1={};B(V1,{update:()=>qJ,unresolveGroup:()=>CJ,resolveGroup:()=>wJ,ignoreGroup:()=>fJ,fetchTimeline:()=>jJ,fetchStats:()=>TJ,fetchGrouped:()=>PJ,fetchById:()=>SJ,fetchByGroup:()=>EJ,fetchAll:()=>P$,destroyGroup:()=>UJ,destroy:()=>AJ,bulkUpdateStatus:()=>kJ,bulkDestroy:()=>RJ});import{db as H1}from"@stacksjs/database";import{log as z1}from"@stacksjs/logging";async function AJ($){try{return await H1.deleteFrom("errors").where("id","=",$).execute(),!0}catch(J){return z1.error("[commerce/errors] destroy failed",{id:$,error:J}),!1}}async function RJ($){try{return await H1.deleteFrom("errors").where("id","in",$).execute(),!0}catch(J){return z1.error("[commerce/errors] bulkDestroy failed",{count:$.length,error:J}),!1}}async function UJ($,J){try{return await H1.deleteFrom("errors").where("type","=",$).where("message","=",J).execute(),!0}catch(G){return z1.error("[commerce/errors] destroyGroup failed",{type:$,message:J,error:G}),!1}}import{db as S$}from"@stacksjs/database";async function SJ($){return await S$.selectFrom("errors").where("id","=",$).selectAll().executeTakeFirst()}async function P$(){return await S$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function PJ(){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 TJ(){let $=await P$(),J=new Date,G=new Date(J.getTime()-86400000),X=new Date(J.getTime()-172800000),Z=$.filter((W)=>new Date(W.created_at)>=G).length,Y=$.filter((W)=>{let Q=new Date(W.created_at);return Q>=X&&Q<G}).length,K=Y===0?Z>0?100:0:Math.round((Z-Y)/Y*100);return{total:$.length,unresolved:$.filter((W)=>W.status===null||W.status===0).length,resolved:$.filter((W)=>W.status===1).length,ignored:$.filter((W)=>W.status===2).length,last_24h:Z,trend:K}}async function jJ(){let $=await P$(),J=new Date,G=[];for(let X=23;X>=0;X--){let Z=new Date(J.getTime()-X*60*60*1000);Z.setMinutes(0,0,0);let Y=new Date(Z.getTime()+3600000),K=$.filter((W)=>{let Q=new Date(W.created_at);return Q>=Z&&Q<Y}).length;G.push({hour:Z.toISOString(),count:K})}return G}import{db as c0}from"@stacksjs/database";import{sql as u0}from"@stacksjs/database";import{log as n0}from"@stacksjs/logging";async function qJ($,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 kJ($,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 wJ($,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 fJ($,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 CJ($,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 B1={};B(B1,{updateBalance:()=>rJ,update:()=>aJ,store:()=>iJ,fetchTotalValue:()=>bJ,fetchTotalCurrentBalance:()=>pJ,fetchStats:()=>gJ,fetchById:()=>H0,fetchByCode:()=>x1,fetchAll:()=>hJ,fetchActive:()=>IJ,destroy:()=>lJ,compareActiveGiftCards:()=>vJ,checkBalance:()=>DJ,calculateGiftCardValues:()=>yJ,bulkDestroy:()=>cJ});import{db as mJ}from"@stacksjs/database";import{formatDate as UW}from"@stacksjs/orm";import{db as S,sql as C}from"@stacksjs/database";import{formatDate as Z0,toTimestamp as R0}from"@stacksjs/orm";import{aggregateFunctions as CZ,db as hZ}from"@stacksjs/database";async function I($,J,G){let X=hZ.selectFrom($);if(G)X=G(X);X=X.select(Object.entries(J).map(([K,W])=>{let Q=W.column??"id",F=CZ[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 hJ(){return await S.selectFrom("gift_cards").selectAll().execute()}async function H0($){return await S.selectFrom("gift_cards").where("id","=",$).selectAll().executeTakeFirst()}async function x1($){return await S.selectFrom("gift_cards").where("code","=",$).selectAll().executeTakeFirst()}async function IJ(){return await S.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function gJ(){let{count:$}=await I("gift_cards",{count:{kind:"count"}}),J=R0(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","<=",R0(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 DJ($){let J=await x1($);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 vJ($=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(R0(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(R0(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 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.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(R0(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(R0(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,R=N>0?(N-H)/N*100:0,O=F>0?W/F:0,U=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,QZ=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:U},previous_period:{total_initial_value:N,total_remaining_balance:H,utilization_rate:R,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(QZ),is_increase:L0>=0}},days_range:$}}async function bJ(){let{total_value:$}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:$}}async function pJ(){let{total_balance:$}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:$}}async function lJ($){let J=await mJ.deleteFrom("gift_cards").where("id","=",$).executeTakeFirst();return L(J)>0}async function cJ($){if(!$.length)return 0;let J=await mJ.deleteFrom("gift_cards").where("id","in",$).executeTakeFirst();return L(J)}var{randomUUIDv7:IZ}=globalThis.Bun;import{db as uJ}from"@stacksjs/database";import{HttpError as nJ}from"@stacksjs/error-handling";import{isUniqueViolation as gZ}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:IZ()};try{let X=await uJ.insertInto("gift_cards").values(G).executeTakeFirst(),Z=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if(Z)return await uJ.selectFrom("gift_cards").where("id","=",Z).selectAll().executeTakeFirst();return}catch(X){if(X instanceof nJ)throw X;if(gZ(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 DZ}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(DZ(X))throw new sJ(409,"A gift card with this code already exists");if(X instanceof Error)throw Error(`Failed to update gift card: ${X.message}`);throw X}}async function rJ($,J){if(!Number.isFinite(J))throw Error(`Gift card balance adjustment must be a finite number, got ${J}`);let G=dJ(new Date),X=await oJ.unsafe(`UPDATE gift_cards
9
9
  SET current_balance = current_balance + ?,
10
10
  last_used_date = ?,
11
11
  status = CASE WHEN current_balance + ? = 0 THEN 'USED' ELSE 'ACTIVE' END,
@@ -13,15 +13,15 @@ var H3=Object.defineProperty;var M3=(J)=>J;function x3(J,$){this[J]=M3.bind(null
13
13
  WHERE id = ?
14
14
  AND is_active = 1
15
15
  AND status = 'ACTIVE'
16
- AND current_balance + ? >= 0`,[$,G,$,G,J,$]),Z=typeof X?.execute==="function"?await X.execute():X;if(Number(Z?.changes??Z?.numUpdatedRows??Z?.affectedRows??0)>0)return await X0(J);let L=await X0(J);if(!L)throw Error(`Gift card with ID ${J} not found`);if(!L.is_active||L.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var C4={};B(C4,{validateQuantityBounds:()=>k4,validateCouponStacking:()=>kJ,validateCartQuantities:()=>CJ,updateStatus:()=>TJ,updateDeliveryInfo:()=>EJ,update:()=>SJ,storeOrdersExport:()=>KJ,store:()=>zJ,softDelete:()=>GJ,registerCommerceWebhookHandlers:()=>jJ,recomputeOrderTotals:()=>fJ,placeOrder:()=>PJ,handlePaymentIntentSucceeded:()=>j4,handlePaymentIntentFailed:()=>w4,handleChargeRefunded:()=>f4,findOrderByIdempotencyKey:()=>N$,fetchStats:()=>FJ,fetchDailyOrderTrends:()=>HJ,fetchById:()=>c,fetchAll:()=>WJ,exportOrders:()=>K$,emitOrderShipped:()=>W$,emitOrderRefunded:()=>M0,emitOrderPaid:()=>d,emitOrderDelivered:()=>F$,emitOrderCreated:()=>f0,emitOrderCancelled:()=>H0,emitForStatus:()=>k0,downloadOrders:()=>LJ,destroy:()=>JJ,compareOrdersByPeriod:()=>QJ,cleanupAbandonedCarts:()=>IJ,canTransition:()=>w0,calculateOrderMetrics:()=>NJ,bulkSoftDelete:()=>ZJ,bulkDestroy:()=>XJ});import{db as L$}from"@stacksjs/database";async function JJ(J){try{let $=await L$.deleteFrom("orders").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function GJ(J){try{let $=await L$.updateTable("orders").set({status:"CANCELED"}).where("id","=",J).executeTakeFirst();return Number($.numUpdatedRows)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete order: ${$.message}`);throw $}}async function XJ(J){if(!J.length)return 0;try{let $=await L$.deleteFrom("orders").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}async function ZJ(J){if(!J.length)return 0;try{let $=await L$.updateTable("orders").set({status:"CANCELED"}).where("id","in",J).executeTakeFirst();return Number($.numUpdatedRows)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete orders: ${$.message}`);throw $}}import{db as YJ}from"@stacksjs/database";import{createSpreadsheet as h3}from"ts-spreadsheets";async function K$(J="csv"){let $=await g3(),G=D3($);return h3(G,{type:J})}async function g3(){let J=await YJ.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),$=J.map((Y)=>Y.id);if($.length===0)return[];let X=(await YJ.selectFrom("order_items").where("order_items.order_id","in",$).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((Y,L)=>{if(!L.order_id)return Y;if(!Y[L.order_id])Y[L.order_id]={totalItems:0,totalPrice:0};return Y[L.order_id].totalItems+=L.quantity,Y[L.order_id].totalPrice+=L.price*L.quantity,Y},{});return J.map((Y)=>{let L=X[Y.id]||{totalItems:0,totalPrice:0};return{...Y,totalItems:L.totalItems,totalPrice:L.totalPrice}})}function D3(J){let $=["Order ID","Customer","Date","Total","Status","Items"],G=J.map((X)=>{let Z=X.order_items?.map((Y)=>`${Y.product?.name} (Qty: ${Y.quantity}, Price: $${Y.price})`).join(" | ")||"No Items";return[X.id,X.customer?.name||"N/A",X.created_at,X.total_amount,X.status,Z]});return{headings:$,data:G}}async function LJ(J="csv",$){let G=await K$(J),X=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function KJ(J="csv",$){let G=await K$(J),X=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}import{db as V}from"@stacksjs/database";async function WJ(J){let $=V.selectFrom("orders").selectAll().orderBy("created_at","desc");if(J)$=$.limit(J);let G=await $.execute();return await Promise.all(G.map(async(X)=>{let Z=await V.selectFrom("order_items").where("order_id","=",X.id).selectAll().execute();return{...X,items:Z}}))}async function c(J){return await V.selectFrom("orders").where("id","=",J).selectAll().executeTakeFirst()}async function FJ(){let J=await V.selectFrom("orders").select(V.fn.count("id").as("count")).executeTakeFirst(),$=await V.selectFrom("orders").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),G=await V.selectFrom("orders").select(["order_type",V.fn.count("id").as("count")]).groupBy("order_type").execute(),X=await V.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),Z=await Promise.all(X.map(async(L)=>{let K=await V.selectFrom("order_items").where("order_id","=",L.id).selectAll().execute();return{...L,items:K}})),Y=await V.selectFrom("orders").select(V.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(J?.count||0),by_status:$,by_type:G,recent:Z,revenue:Number(Y?.total||0)}}async function QJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await V.selectFrom("orders").select(V.fn.count("id").as("count")).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),L=await V.selectFrom("orders").select(V.fn.count("id").as("count")).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),K=Number(Y?.count||0),W=Number(L?.count||0),F=K-W,N=W!==0?F/W*100:K>0?100:0;return{current_period:K,previous_period:W,difference:F,percentage_change:N,days_range:J}}async function NJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await V.selectFrom("orders").select([V.fn.count("id").as("total_orders"),V.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),L=await V.selectFrom("orders").select([V.fn.count("id").as("total_orders"),V.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),K=await V.selectFrom("orders").select(["status",V.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("status").execute(),W=await V.selectFrom("orders").select(["order_type",V.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("order_type").execute(),F=Number(Y?.total_orders||0),N=Number(Y?.total_revenue||0),H=F>0?N/F:0,M=Number(L?.total_orders||0),O=Number(L?.total_revenue||0),R=M>0?O/M:0,_=F-M,U=N-O,m=H-R,t=M!==0?_/M*100:F>0?100:0,$0=O!==0?U/O*100:N>0?100:0,Q0=R!==0?m/R*100:H>0?100:0;return{current_period:{total_orders:F,total_revenue:N,average_order_value:H,orders_by_status:K.map((p)=>({status:p.status,count:Number(p.count)})),orders_by_type:W.map((p)=>({order_type:p.order_type,count:Number(p.count)}))},previous_period:{total_orders:M,total_revenue:O,average_order_value:R},comparison:{orders:{difference:_,percentage:Math.abs(t),is_increase:_>=0},revenue:{difference:U,percentage:Math.abs($0),is_increase:U>=0},average_order_value:{difference:m,percentage:Math.abs(Q0),is_increase:m>=0}},days_range:J}}async function HJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=await V.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).orderBy("created_at","asc").execute(),Z=new Map;for(let Y of X){let L=(Y.created_at||"").split("T")[0]||"unknown",K=Z.get(L)||{order_count:0,revenue:0};K.order_count++,K.revenue+=Number(Y.total_amount||0),Z.set(L,K)}return Array.from(Z.entries()).map(([Y,L])=>({date:Y,order_count:L.order_count,revenue:L.revenue}))}var{randomUUIDv7:v3}=globalThis.Bun;import{db as MJ}from"@stacksjs/database";import{formatDate as xJ}from"@stacksjs/orm";async function zJ(J){let $={...J,status:J.status||"PENDING",uuid:v3(),created_at:xJ(new Date),updated_at:xJ(new Date)};try{let G=await MJ.insertInto("orders").values($).executeTakeFirst(),X=Number(G?.insertId)||Number(G?.numInsertedOrUpdatedRows);if(X)return await MJ.selectFrom("orders").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof Error)throw Error(`Failed to create order: ${G.message}`);throw G}}x0();var{randomUUIDv7:OJ}=globalThis.Bun;import{db as Q$}from"@stacksjs/database";import{formatDate as l3,isUniqueViolation as _J}from"@stacksjs/orm";import{sqlHelpers as b3}from"@stacksjs/database";import{env as m3}from"@stacksjs/env";function p3(J,$,G,X){let Z=b3(J).param;return{query:`UPDATE products
16
+ AND current_balance + ? >= 0`,[J,G,J,G,$,J]),Z=typeof X?.execute==="function"?await X.execute():X;if(Number(Z?.changes??Z?.numUpdatedRows??Z?.affectedRows??0)>0)return await H0($);let K=await H0($);if(!K)throw Error(`Gift card with ID ${$} not found`);if(!K.is_active||K.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var E1={};B(E1,{validateQuantityBounds:()=>P1,validateCouponStacking:()=>q6,validateCartQuantities:()=>k6,updateStatus:()=>U6,updateDeliveryInfo:()=>S6,update:()=>R6,storeOrdersExport:()=>Z6,store:()=>H6,softDelete:()=>eJ,registerCommerceWebhookHandlers:()=>E6,recomputeOrderTotals:()=>j6,placeOrder:()=>A6,handlePaymentIntentSucceeded:()=>R1,handlePaymentIntentFailed:()=>U1,handleChargeRefunded:()=>S1,findOrderByIdempotencyKey:()=>w$,fetchStats:()=>K6,fetchDailyOrderTrends:()=>F6,fetchById:()=>r,fetchAll:()=>Y6,exportOrders:()=>T$,emitOrderShipped:()=>j$,emitOrderRefunded:()=>S0,emitOrderPaid:()=>Y0,emitOrderDelivered:()=>q$,emitOrderCreated:()=>s0,emitOrderCancelled:()=>U0,emitForStatus:()=>o0,downloadOrders:()=>X6,destroy:()=>tJ,compareOrdersByPeriod:()=>W6,cleanupAbandonedCarts:()=>w6,canTransition:()=>i0,calculateOrderMetrics:()=>Q6,bulkSoftDelete:()=>J6,bulkDestroy:()=>$6});import{db as E$}from"@stacksjs/database";async function tJ($){try{let J=await E$.deleteFrom("orders").where("id","=",$).executeTakeFirst();return L(J)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function eJ($){try{let J=await E$.updateTable("orders").set({status:"CANCELED"}).where("id","=",$).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete order: ${J.message}`);throw J}}async function $6($){if(!$.length)return 0;try{let J=await E$.deleteFrom("orders").where("id","in",$).executeTakeFirst();return L(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}async function J6($){if(!$.length)return 0;try{let J=await E$.updateTable("orders").set({status:"CANCELED"}).where("id","in",$).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete orders: ${J.message}`);throw J}}import{db as G6}from"@stacksjs/database";import{createSpreadsheet as vZ}from"ts-spreadsheets";async function T$($="csv"){let J=await yZ(),G=bZ(J);return vZ(G,{type:$})}async function yZ(){let $=await G6.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),J=$.map((Y)=>Y.id);if(J.length===0)return[];let X=(await G6.selectFrom("order_items").where("order_items.order_id","in",J).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((Y,K)=>{if(!K.order_id)return Y;if(!Y[K.order_id])Y[K.order_id]={totalItems:0,totalPrice:0};return Y[K.order_id].totalItems+=K.quantity,Y[K.order_id].totalPrice+=K.price*K.quantity,Y},{});return $.map((Y)=>{let K=X[Y.id]||{totalItems:0,totalPrice:0};return{...Y,totalItems:K.totalItems,totalPrice:K.totalPrice}})}function bZ($){let J=["Order ID","Customer","Date","Total","Status","Items"],G=$.map((X)=>{let Z=X.order_items?.map((Y)=>`${Y.product?.name} (Qty: ${Y.quantity}, Price: $${Y.price})`).join(" | ")||"No Items";return[X.id,X.customer?.name||"N/A",X.created_at,X.total_amount,X.status,Z]});return{headings:J,data:G}}async function X6($="csv",J){let G=await T$($),X=`orders_export_${new Date().toISOString().split("T")[0]}.${$}`;return G.download(J||X)}async function Z6($="csv",J){let G=await T$($),X=`orders_export_${new Date().toISOString().split("T")[0]}.${$}`;G.store(J||X)}import{db as _}from"@stacksjs/database";async function Y6($){let J=_.selectFrom("orders").selectAll().orderBy("created_at","desc");if($)J=J.limit($);let G=await J.execute();return await Promise.all(G.map(async(X)=>{let Z=await _.selectFrom("order_items").where("order_id","=",X.id).selectAll().execute();return{...X,items:Z}}))}async function r($){return await _.selectFrom("orders").where("id","=",$).selectAll().executeTakeFirst()}async function K6(){let $=await _.selectFrom("orders").select(_.fn.count("id").as("count")).executeTakeFirst(),J=await _.selectFrom("orders").select(["status",_.fn.count("id").as("count")]).groupBy("status").execute(),G=await _.selectFrom("orders").select(["order_type",_.fn.count("id").as("count")]).groupBy("order_type").execute(),X=await _.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),Z=await Promise.all(X.map(async(K)=>{let W=await _.selectFrom("order_items").where("order_id","=",K.id).selectAll().execute();return{...K,items:W}})),Y=await _.selectFrom("orders").select(_.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number($?.count||0),by_status:J,by_type:G,recent:Z,revenue:Number(Y?.total||0)}}async function W6($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-$);let Y=await _.selectFrom("orders").select(_.fn.count("id").as("count")).where("created_at",">=",G.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),K=await _.selectFrom("orders").select(_.fn.count("id").as("count")).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),W=Number(Y?.count||0),Q=Number(K?.count||0),F=W-Q,N=Q!==0?F/Q*100:W>0?100:0;return{current_period:W,previous_period:Q,difference:F,percentage_change:N,days_range:$}}async function Q6($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-$);let Y=await _.selectFrom("orders").select([_.fn.count("id").as("total_orders"),_.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",G.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),K=await _.selectFrom("orders").select([_.fn.count("id").as("total_orders"),_.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),W=await _.selectFrom("orders").select(["status",_.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",J.toISOString()).groupBy("status").execute(),Q=await _.selectFrom("orders").select(["order_type",_.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",J.toISOString()).groupBy("order_type").execute(),F=Number(Y?.total_orders||0),N=Number(Y?.total_revenue||0),H=F>0?N/F:0,z=Number(K?.total_orders||0),x=Number(K?.total_revenue||0),R=z>0?x/z:0,O=F-z,U=N-x,c=H-R,F0=z!==0?O/z*100:F>0?100:0,L0=x!==0?U/x*100:N>0?100:0,O0=R!==0?c/R*100:H>0?100:0;return{current_period:{total_orders:F,total_revenue:N,average_order_value:H,orders_by_status:W.map((u)=>({status:u.status,count:Number(u.count)})),orders_by_type:Q.map((u)=>({order_type:u.order_type,count:Number(u.count)}))},previous_period:{total_orders:z,total_revenue:x,average_order_value:R},comparison:{orders:{difference:O,percentage:Math.abs(F0),is_increase:O>=0},revenue:{difference:U,percentage:Math.abs(L0),is_increase:U>=0},average_order_value:{difference:c,percentage:Math.abs(O0),is_increase:c>=0}},days_range:$}}async function F6($=30){let J=new Date,G=new Date(J);G.setDate(J.getDate()-$);let X=await _.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",G.toISOString()).where("created_at","<=",J.toISOString()).orderBy("created_at","asc").execute(),Z=new Map;for(let Y of X){let K=(Y.created_at||"").split("T")[0]||"unknown",W=Z.get(K)||{order_count:0,revenue:0};W.order_count++,W.revenue+=Number(Y.total_amount||0),Z.set(K,W)}return Array.from(Z.entries()).map(([Y,K])=>({date:Y,order_count:K.order_count,revenue:K.revenue}))}var{randomUUIDv7:pZ}=globalThis.Bun;import{db as L6}from"@stacksjs/database";import{formatDate as N6}from"@stacksjs/orm";async function H6($){let J={...$,status:$.status||"PENDING",uuid:pZ(),created_at:N6(new Date),updated_at:N6(new Date)};try{let G=await L6.insertInto("orders").values(J).executeTakeFirst(),X=Number(G?.insertId)||Number(G?.numInsertedOrUpdatedRows);if(X)return await L6.selectFrom("orders").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof Error)throw Error(`Failed to create order: ${G.message}`);throw G}}P0();var{randomUUIDv7:B6}=globalThis.Bun;import{db as k$}from"@stacksjs/database";import{formatDate as nZ,isUniqueViolation as M6}from"@stacksjs/orm";import{sqlHelpers as lZ}from"@stacksjs/database";import{env as cZ}from"@stacksjs/env";function uZ($,J,G,X){let Z=lZ($).param;return{query:`UPDATE products
17
17
  SET inventory_count = inventory_count + ${Z(1)},
18
18
  updated_at = ${Z(2)}
19
19
  WHERE id = ${Z(3)}
20
- AND inventory_count + ${Z(4)} >= 0`,parameters:[G,X,$,G]}}async function AJ(J,$,G,X){let Z=p3(m3.DB_CONNECTION||"sqlite",$,G,X),Y=await J.unsafe(Z.query,Z.parameters),L=typeof Y?.execute==="function"?await Y.execute():Y;return Q(L)}var RJ=!1;function UJ(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function N$(J){try{let $=await Q$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await Q$.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(UJ($)){if(!RJ)RJ=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw $}}async function PJ(J){if(J.idempotencyKey){let $=await N$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await Q$.transaction(async(G)=>{let X=l3(new Date),Z=OJ(),Y={...J.order,status:J.order.status||"PENDING",uuid:Z,created_at:X,updated_at:X};await G.insertInto("orders").values(Y).executeTakeFirst();let L=await G.selectFrom("orders").where("uuid","=",Z).selectAll().executeTakeFirst(),K=Number(L?.id);if(!Number.isSafeInteger(K)||K<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let W;if(J.items&&J.items.length>0){let H=J.items.map((M)=>{if(!Number.isInteger(M.productId)||M.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(M.quantity)||M.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(M.price)||M.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:K,product_id:M.productId,quantity:M.quantity,price:M.price,special_instructions:M.specialInstructions||null,created_at:X,updated_at:X}});await G.insertInto("order_items").values(H).execute(),W=await G.selectFrom("order_items").where("order_id","=",K).selectAll().execute()}let F;if(J.payment)try{let H=OJ();if(await G.insertInto("payments").values({...J.payment,order_id:K,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(_J(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(J.inventory&&J.inventory.length>0)for(let H=0;H<J.inventory.length;H++){let{id:M,delta:O}=J.inventory[H];if(!Number.isFinite(O)||O===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await AJ(G,M,O,X))throw Object.assign(Error(`inventory adjust failed for product ${M}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:K,created_at:X}).execute()}catch(H){if(_J(H))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!UJ(H))throw H}let N=await G.selectFrom("orders").where("id","=",K).selectAll().executeTakeFirst();if(!N)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:N,items:W,payment:F}});if(f0($.order),$.payment)d($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&J.idempotencyKey){let G=await N$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}x0();import{db as S4}from"@stacksjs/database";import{formatDate as T4}from"@stacksjs/orm";x0();async function SJ(J,$){if(!await c(J))return;try{return await S4.updateTable("orders").set({...$,updated_at:T4(new Date)}).where("id","=",J).execute(),await c(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order: ${X.message}`);throw X}}async function TJ(J,$){let G=await c(J);if(!G)throw Error(`Order with ID ${J} not found`);let X=G.status??"PENDING";if(!w0(X,$))throw Error(`[commerce/orders] illegal status transition ${X} \u2192 ${$}`);try{await S4.updateTable("orders").set({status:$,updated_at:T4(new Date)}).where("id","=",J).execute();let Z=await c(J);if(Z)k0($,Z);return Z}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update order status: ${Z.message}`);throw Z}}async function EJ(J,$,G){let X=await c(J);if(!X)throw Error(`Order with ID ${J} not found`);let Z={updated_at:T4(new Date)};if($!==void 0)Z.delivery_address=$;if(G!==void 0)Z.estimated_delivery_time=G;if(Object.keys(Z).length===1)return X;try{return await S4.updateTable("orders").set(Z).where("id","=",J).execute(),await c(J)}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery information: ${Y.message}`);throw Y}}x0();import{db as z0}from"@stacksjs/database";import{formatDate as H$}from"@stacksjs/orm";async function E4(J){let $=await z0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await z0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var qJ=!1;function c3(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function q4(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:H$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(c3(G)){if(!qJ)qJ=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw G}}async function j4(J){let G=J.data.object?.id;if(!G)return;await z0.transaction(async(Z)=>{if(!await q4(J.id,Z))return;let L=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let K=H$(new Date);await Z.updateTable("payments").set({status:"succeeded",updated_at:K}).where("id","=",L.id).execute();let W=await Z.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(W&&W.status==="PENDING")await Z.updateTable("orders").set({status:"PROCESSING",updated_at:K}).where("id","=",W.id).execute()});let X=await E4(G);if(X)await d(X)}async function w4(J){let $=J.data.object,G=$?.id;if(!G)return;let Z=$?.last_payment_error?.message??"payment failed";await z0.transaction(async(L)=>{if(!await q4(J.id,L))return;let W=await L.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!W)return;let F=H$(new Date);await L.updateTable("payments").set({status:"failed",failure_reason:Z,updated_at:F}).where("id","=",W.id).execute();let N=await L.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await L.updateTable("orders").set({status:"CANCELLED",updated_at:F}).where("id","=",N.id).execute()});let Y=await E4(G);if(Y)await H0(Y,Z)}async function f4(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let X=$?.amount_refunded??0;await z0.transaction(async(Y)=>{if(!await q4(J.id,Y))return;let K=await Y.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!K)return;let W=H$(new Date);await Y.updateTable("payments").set({status:"refunded",refund_amount:X,updated_at:W}).where("id","=",K.id).execute();let F=await Y.selectFrom("orders").where("id","=",K.order_id).selectAll().executeTakeFirst();if(F&&F.status!=="REFUNDED")await Y.updateTable("orders").set({status:"REFUNDED",updated_at:W}).where("id","=",F.id).execute()});let Z=await E4(G);if(Z)await M0(Z,X)}async function jJ(){let J=await import("@stacksjs/payments").catch(()=>null);if(!J)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:G}=J;if(typeof $!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:j4,failed:w4}),G({refunded:f4}),()=>{}}import{db as wJ}from"@stacksjs/database";async function u3(J){if(J.length===0)return new Map;let $=await wJ.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),G=new Map;for(let X of $){let Z=Number(X.price);if(Number.isFinite(Z))G.set(X.id,Math.round(Z))}return G}async function n3(J){try{let $=await wJ.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),G=Number($?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function fJ(J){let $=J.items.map((R)=>R.productId),G=await u3($),X=J.taxRateId!=null?await n3(J.taxRateId):0,Z=0,Y=[];for(let R of J.items){let _=R.unitPriceCents??G.get(R.productId)??0,U=Math.round(_*R.quantity);Z+=U,Y.push({productId:R.productId,quantity:R.quantity,unitPriceCents:_,lineCents:U})}let L=Math.max(0,J.discountCents??0),K=Math.max(0,Z-L),W=Math.round(K*X),F=Math.max(0,J.shippingCents??0),N=Z-L+W+F,H=J.maxDriftCents??5,M=!1,O=0;if(J.clientTotalCents!=null)O=Math.abs(N-J.clientTotalCents),M=O>H;return{subtotalCents:Z,discountCents:L,taxCents:W,shippingCents:F,totalCents:N,resolvedItems:Y,priceChanged:M,diffCents:O}}import{db as M$}from"@stacksjs/database";function kJ(J,$={}){let G=J.length;if(G<=1)return{ok:!0,count:G};if(!$.allowMultiple)return{ok:!1,count:G,reason:"multiple-not-allowed"};let X=$.maxStacked??Number.POSITIVE_INFINITY;if(G>X)return{ok:!1,count:G,reason:"exceeds-max-stacked"};return{ok:!0,count:G}}async function k4(J,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:J,quantity:$,reason:"non-positive"};let G;try{G=await M$.selectFrom("products").where("id","=",J).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:J,quantity:$}}if(!G)return{ok:!1,productId:J,quantity:$,reason:"product-missing"};let X=G.min_order_qty??null,Z=G.max_order_qty??null;if(X!=null&&$<X)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:X};if(Z!=null&&$>Z)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:Z};return{ok:!0,productId:J,quantity:$}}async function CJ(J){for(let G of J){let X=await k4(G.productId,G.quantity);if(!X.ok)return X}let $=J[J.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function IJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,Z=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let Y=await M$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[Z,Z,G]),L=typeof Y?.execute==="function"?await Y.execute():Y;return{deleted:Number(L?.changes??L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??0),cutoffAt:Z}}catch{try{let Y=await M$.selectFrom("carts").where("updated_at","<",Z).select(["id"]).limit(G).execute();if(Y.length===0)return{deleted:0,cutoffAt:Z};let L=Y.map((F)=>F.id),K=await M$.deleteFrom("carts").where("id","in",L).execute();return{deleted:Number(K?.numDeletedRows??K?.[0]?.numDeletedRows??K?.affectedRows??Y.length),cutoffAt:Z}}catch{return{deleted:0,cutoffAt:Z}}}}var I4={};B(I4,{update:()=>iJ,store:()=>cJ,recordRefund:()=>oJ,fetchPaymentStatsByMethod:()=>bJ,fetchPaymentStats:()=>yJ,fetchMonthlyPaymentTrends:()=>mJ,fetchById:()=>Y0,fetchAll:()=>vJ,destroy:()=>gJ,bulkDestroy:()=>DJ});import{db as hJ}from"@stacksjs/database";async function gJ(J){try{let $=await hJ.deleteFrom("payments").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function DJ(J){if(!J.length)return 0;try{let $=await hJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as w}from"@stacksjs/database";import{formatDate as D}from"@stacksjs/orm";async function vJ(){return await w.selectFrom("payments").selectAll().execute()}async function Y0(J){return await w.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function yJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await w.selectFrom("payments").select([w.fn.count("id").as("transaction_count"),w.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").executeTakeFirst(),L=await w.selectFrom("payments").select([w.fn.count("id").as("transaction_count"),w.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(Z)).where("created_at","<=",D(X)).where("status","=","completed").executeTakeFirst(),K=await w.selectFrom("payments").select(w.fn.count("id").as("count")).where("created_at",">=",D(G)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(Y?.transaction_count||0),F=Number(Y?.total_revenue||0),N=W>0?F/W:0,H=Number(L?.transaction_count||0),M=Number(L?.total_revenue||0),O=H>0?M/H:0,R=W-H,_=F-M,U=N-O,m=H>0?R/H*100:W>0?100:0,t=M>0?_/M*100:F>0?100:0,$0=O>0?U/O*100:N>0?100:0,Q0=Number(K?.count||0),p=Q0>0?W/Q0*100:0;return{total_transactions:W,total_revenue:F,average_transaction:N,successful_rate:p,comparison:{transactions:{difference:R,percentage:Math.abs(m),is_increase:R>=0},revenue:{difference:_,percentage:Math.abs(t),is_increase:_>=0},average:{difference:U,percentage:Math.abs($0),is_increase:U>=0}}}}async function bJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=await w.selectFrom("payments").select([w.fn.count("id").as("total_count"),w.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").executeTakeFirst(),Z=Number(X?.total_count||0),Y=await w.selectFrom("payments").select(["method",w.fn.count("id").as("count"),w.fn.sum("amount").as("revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").groupBy("method").execute(),L={};return Y.forEach((K)=>{let W=Number(K.count||0),F=Number(K.revenue||0),N=Z>0?W/Z*100:0;L[K.method]={count:W,revenue:F,percentage_of_total:N}}),L}async function mJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await w.selectFrom("payments").selectAll().where("created_at",">=",D($)).where("status","=","completed").execute(),X={};for(let Y of G){let L=Y.created_at?new Date(Y.created_at):new Date,K=L.getFullYear(),W=L.getMonth()+1,F=`${K}-${String(W).padStart(2,"0")}`;if(!X[F])X[F]={year:K,month:W,transactions:0,revenue:0};X[F].transactions++,X[F].revenue+=Number(Y.amount||0)}return Object.keys(X).sort().map((Y)=>{let L=X[Y],K=L.transactions,W=L.revenue,F=K>0?W/K:0;return{month:new Date(L.year,L.month-1,1).toLocaleString("default",{month:"short"}),year:L.year,transactions:K,revenue:W,average:F}})}var{randomUUIDv7:i3}=globalThis.Bun;import{db as pJ}from"@stacksjs/database";import{HttpError as lJ}from"@stacksjs/error-handling";import{isUniqueViolation as o3}from"@stacksjs/orm";async function cJ(J){let $=i3(),G={...J,status:J.status||"pending",currency:J.currency||"USD",uuid:$};try{return await pJ.insertInto("payments").values(G).executeTakeFirst(),await pJ.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(X){if(X instanceof lJ)throw X;if(o3(X))throw new lJ(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 uJ,sqlHelpers as s3}from"@stacksjs/database";import{env as d3}from"@stacksjs/env";import{formatDate as nJ}from"@stacksjs/orm";async function iJ(J,$){if(!await Y0(J))return;try{return await uJ.updateTable("payments").set({...$,updated_at:nJ(new Date)}).where("id","=",J).execute(),await Y0(J)}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 a3=new Set(["completed","succeeded","partiallyRefunded"]);async function oJ(J,$){if(!Number.isSafeInteger(J)||J<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger($)||$<=0)throw TypeError("Refund amount must be a positive integer in minor units");let X=s3(d3.DB_CONNECTION||"sqlite").param,Z=nJ(new Date),Y=await uJ.unsafe(`UPDATE payments
20
+ AND inventory_count + ${Z(4)} >= 0`,parameters:[G,X,J,G]}}async function x6($,J,G,X){let Z=uZ(cZ.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 _6=!1;function O6($){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(O6(J)){if(!_6)_6=!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 A6($){if($.idempotencyKey){let J=await w$($.idempotencyKey);if(J)return{ok:!0,order:J}}try{let J=await k$.transaction(async(G)=>{let X=nZ(new Date),Z=B6(),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=B6();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(M6(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 x6(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(M6(H))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!O6(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}}P0();import{db as M1}from"@stacksjs/database";import{formatDate as _1}from"@stacksjs/orm";P0();async function R6($,J){if(!await r($))return;try{return await M1.updateTable("orders").set({...J,updated_at:_1(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 U6($,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 M1.updateTable("orders").set({status:J,updated_at:_1(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 S6($,J,G){let X=await r($);if(!X)throw Error(`Order with ID ${$} not found`);let Z={updated_at:_1(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 M1.updateTable("orders").set(Z).where("id","=",$).execute(),await r($)}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery information: ${Y.message}`);throw Y}}P0();import{db as E0}from"@stacksjs/database";import{formatDate as f$}from"@stacksjs/orm";async function O1($){let J=await E0.selectFrom("payments").where("transaction_id","=",$).selectAll().executeTakeFirst();if(!J)return null;return await E0.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}var P6=!1;function iZ($){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 A1($,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(iZ(G)){if(!P6)P6=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw G}}async function R1($){let G=$.data.object?.id;if(!G)return;await E0.transaction(async(Z)=>{if(!await A1($.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 O1(G);if(X)await Y0(X)}async function U1($){let J=$.data.object,G=J?.id;if(!G)return;let Z=J?.last_payment_error?.message??"payment failed";await E0.transaction(async(K)=>{if(!await A1($.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 O1(G);if(Y)await U0(Y,Z)}async function S1($){let J=$.data.object,G=J?.payment_intent;if(!G)return;let X=J?.amount_refunded??0;await E0.transaction(async(Y)=>{if(!await A1($.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 O1(G);if(Z)await S0(Z,X)}async function E6(){let $=await import("@stacksjs/payments").catch(()=>null);if(!$)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:J,onCharge:G}=$;if(typeof J!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return J({succeeded:R1,failed:U1}),G({refunded:S1}),()=>{}}import{db as T6}from"@stacksjs/database";async function sZ($){if($.length===0)return new Map;let J=await T6.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 oZ($){try{let J=await T6.selectFrom("tax_rates").where("id","=",$).select(["rate"]).executeTakeFirst(),G=Number(J?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function j6($){let J=$.items.map((R)=>R.productId),G=await sZ(J),X=$.taxRateId!=null?await oZ($.taxRateId):0,Z=0,Y=[];for(let R of $.items){let O=R.unitPriceCents??G.get(R.productId)??0,U=Math.round(O*R.quantity);Z+=U,Y.push({productId:R.productId,quantity:R.quantity,unitPriceCents:O,lineCents:U})}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 q6($,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 P1($,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 k6($){for(let G of $){let X=await P1(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 w6($={}){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 T1={};B(T1,{update:()=>c6,store:()=>p6,recordRefund:()=>u6,fetchPaymentStatsByMethod:()=>D6,fetchPaymentStats:()=>g6,fetchMonthlyPaymentTrends:()=>v6,fetchById:()=>V0,fetchAll:()=>I6,destroy:()=>C6,bulkDestroy:()=>h6});import{db as f6}from"@stacksjs/database";async function C6($){try{let J=await f6.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 h6($){if(!$.length)return 0;try{let J=await f6.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 I6(){return await k.selectFrom("payments").selectAll().execute()}async function V0($){return await k.selectFrom("payments").selectAll().where("id","=",$).executeTakeFirst()}async function g6($=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,R=Q-H,O=F-z,U=N-x,c=H>0?R/H*100:Q>0?100:0,F0=z>0?O/z*100:F>0?100:0,L0=x>0?U/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:R,percentage:Math.abs(c),is_increase:R>=0},revenue:{difference:O,percentage:Math.abs(F0),is_increase:O>=0},average:{difference:U,percentage:Math.abs(L0),is_increase:U>=0}}}}async function D6($=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 v6(){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:dZ}=globalThis.Bun;import{db as y6}from"@stacksjs/database";import{HttpError as b6}from"@stacksjs/error-handling";import{isUniqueViolation as aZ}from"@stacksjs/orm";async function p6($){let J=dZ(),G={...$,status:$.status||"pending",currency:$.currency||"USD",uuid:J};try{return await y6.insertInto("payments").values(G).executeTakeFirst(),await y6.selectFrom("payments").where("uuid","=",J).selectAll().executeTakeFirst()}catch(X){if(X instanceof b6)throw X;if(aZ(X))throw new b6(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 m6,sqlHelpers as rZ}from"@stacksjs/database";import{env as tZ}from"@stacksjs/env";import{formatDate as l6}from"@stacksjs/orm";async function c6($,J){if(!await V0($))return;try{return await m6.updateTable("payments").set({...J,updated_at:l6(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 eZ=new Set(["completed","succeeded","partiallyRefunded"]);async function u6($,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=rZ(tZ.DB_CONNECTION||"sqlite").param,Z=l6(new Date),Y=await m6.unsafe(`UPDATE payments
21
21
  SET refund_amount = COALESCE(refund_amount, 0) + ${X(1)},
22
22
  status = CASE WHEN COALESCE(refund_amount, 0) + ${X(2)} = amount
23
23
  THEN 'refunded' ELSE 'partiallyRefunded' END,
24
24
  updated_at = ${X(3)}
25
25
  WHERE id = ${X(4)}
26
26
  AND status IN ('completed', 'succeeded', 'partiallyRefunded')
27
- AND COALESCE(refund_amount, 0) + ${X(5)} <= amount`,[$,$,Z,J,$]),L=typeof Y?.execute==="function"?await Y.execute():Y;if(Number(L?.numUpdatedRows??L?.[0]?.numUpdatedRows??L?.numAffectedRows??L?.affectedRows??L?.[0]?.affectedRows??L?.changes??0)>0){let M=await Y0(J);if(M)return M;throw Error(`Payment with ID ${J} disappeared during refund`)}let W=await Y0(J);if(!W)throw Error(`Payment with ID ${J} not found`);let F=String(W.status||"");if(!a3.has(F))throw Error(`Payment status ${F||"unknown"} cannot be refunded`);let N=W,H=Number(W.amount||0)-Number(N.refundAmount??N.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${H} minor units`)}var m4={};B(m4,{variants:()=>P$,units:()=>U$,reviews:()=>O$,manufacturers:()=>A$,items:()=>V$,default:()=>WZ,categories:()=>B$});var B$={};B(B$,{updateParent:()=>H6,updateDisplayOrder:()=>Q6,updateActiveStatus:()=>N6,update:()=>F6,store:()=>g4,removeChildCategories:()=>Z6,remove:()=>G6,findOrCreateByName:()=>W6,fetchStats:()=>tJ,fetchRootCategories:()=>aJ,fetchChildCategories:()=>rJ,fetchCategoryTree:()=>J6,fetchByName:()=>sJ,fetchById:()=>f,fetchByDisplayOrder:()=>eJ,fetchAll:()=>h4,fetchActive:()=>dJ,deactivateChildCategories:()=>L6,deactivate:()=>Y6,compareCategoryGrowth:()=>$6,bulkRemove:()=>X6});import{db as B0}from"@stacksjs/database";import{db as S}from"@stacksjs/database";import{formatDate as C0}from"@stacksjs/orm";async function h4(){return await S.selectFrom("categories").selectAll().execute()}async function f(J){return await S.selectFrom("categories").where("id","=",J).selectAll().executeTakeFirst()}async function sJ(J){return await S.selectFrom("categories").where("name","=",J).selectAll().executeTakeFirst()}async function dJ(){return await S.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function aJ(){return await S.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function rJ(J){return await S.selectFrom("categories").where("parent_category_id","=",J).where("is_active","=",!0).selectAll().execute()}async function eJ(J=!0){let $=S.selectFrom("categories").where("is_active","=",!0).selectAll();if(J)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function tJ(){let J=await S.selectFrom("categories").select(S.fn.count("id").as("count")).executeTakeFirst(),$=await S.selectFrom("categories").where("is_active","=",!0).select(S.fn.count("id").as("count")).executeTakeFirst(),G=await S.selectFrom("categories").whereNull("parent_category_id").select(S.fn.count("id").as("count")).executeTakeFirst(),X=await S.selectFrom("categories").whereNotNull("image_url").select(S.fn.count("id").as("count")).executeTakeFirst(),Z=new Date;Z.setDate(Z.getDate()-30);let Y=C0(Z),L=await S.selectFrom("categories").where("created_at",">=",Y).selectAll().limit(5).execute(),K=await S.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",S.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number($?.count||0),root_categories:Number(G?.count||0),child_categories:Number(J?.count||0)-Number(G?.count||0),with_images:Number(X?.count||0),recently_added:L,top_parent_categories:K.map((W)=>({id:String(W.parent_category_id||""),name:String(W.parent_name||""),child_count:Number(W.child_count)}))}}async function $6(J=30){let $=new Date,G=C0($),X=new Date;X.setDate($.getDate()-J);let Z=C0(X),Y=new Date(X);Y.setDate(Y.getDate()-1);let L=C0(Y),K=new Date(Y);K.setDate(Y.getDate()-J);let W=C0(K),F=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",G).executeTakeFirst(),N=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",W).where("created_at","<=",L).executeTakeFirst(),H=Number(F?.count||0),M=Number(N?.count||0),O=H-M,R=M!==0?O/M*100:H>0?100:0;return{current_period:H,previous_period:M,difference:O,percentage_change:R,days_range:J}}async function J6(){let J=await h4(),$=new Map;J.forEach((Z)=>{$.set(Z.id,{...Z,children:[]})});let G=[];J.forEach((Z)=>{let Y=$.get(Z.id);if(Z.parent_category_id){let L=$.get(Z.parent_category_id);if(L)L.children.push(Y)}else G.push(Y)}),G.sort((Z,Y)=>Z.display_order-Y.display_order);let X=(Z)=>{Z.sort((Y,L)=>Y.display_order-L.display_order),Z.forEach((Y)=>{if(Y.children.length>0)X(Y.children)})};return X(G),G}async function G6(J){let $=await B0.deleteFrom("categories").where("id","=",J).executeTakeFirst();return Q($)>0}async function X6(J){if(!J.length)return 0;let $=await B0.deleteFrom("categories").where("id","in",J).executeTakeFirst();return Q($)}async function Z6(J){let $=await B0.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return Q($)}async function Y6(J){if(!await f(J))throw Error(`Category with ID ${J} not found`);return!!await B0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",J).executeTakeFirst()}async function L6(J){let $=await B0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",J).execute();return Number($.length)||0}var{randomUUIDv7:r3}=globalThis.Bun;import{db as K6}from"@stacksjs/database";import{HttpError as x$}from"@stacksjs/error-handling";import{isUniqueViolation as e3}from"@stacksjs/orm";import{slug as t3}from"@stacksjs/strings";async function g4(J){try{let $=J.parent_category_id?Number(J.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new x$(422,"Parent category ID must be a positive integer");if($&&!await f($))throw new x$(422,`Parent category with ID ${J.parent_category_id} not found`);let G={...J,uuid:r3(),is_active:J.is_active??!0,parent_category_id:J.parent_category_id||null},X=await K6.insertInto("categories").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create category");return X}catch($){if($ instanceof x$)throw $;if(e3($))throw new x$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function W6(J){if(!J.name)throw Error("Name is required");let $=await K6.selectFrom("categories").selectAll().where("name","=",J.name).executeTakeFirst();if($)return $;let G={name:J.name,slug:t3(J.name),is_active:J.is_active??!0,display_order:0};return await g4(G)}import{db as I0}from"@stacksjs/database";import{HttpError as V0}from"@stacksjs/error-handling";import{formatDate as z$,isUniqueViolation as $Z}from"@stacksjs/orm";async function F6(J,$){if(!await f(J))return;if(Object.hasOwn($,"parent_category_id")){let X=$.parent_category_id?Number($.parent_category_id):void 0;if(X!==void 0&&(!Number.isSafeInteger(X)||X<=0))throw new V0(422,"Parent category ID must be a positive integer");if(X===J)throw new V0(422,"A category cannot be its own parent");if(X&&!await f(X))throw new V0(422,`Parent category with ID ${$.parent_category_id} not found`);if(X&&await M6(J,String(X)))throw new V0(422,"This operation would create a circular category hierarchy")}try{let X=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},Z=await I0.updateTable("categories").set({...$,...X,updated_at:z$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(X){if(X instanceof V0)throw X;if($Z(X))throw new V0(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 Q6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);try{return await I0.updateTable("categories").set({display_order:$,updated_at:z$(new Date)}).where("id","=",J).execute(),await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category display order: ${X.message}`);throw X}}async function N6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);try{return await I0.updateTable("categories").set({is_active:$,updated_at:z$(new Date)}).where("id","=",J).execute(),await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function H6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);if($){let X=Number($);if(X===J)throw Error("A category cannot be its own parent");if(!await f(X))throw Error(`Parent category with ID ${$} not found`);if(await M6(J,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let X={updated_at:z$(new Date)};if($===null)await I0.updateTable("categories").set({...X,parent_category_id:null}).where("id","=",J).execute();else await I0.updateTable("categories").set({...X,parent_category_id:$}).where("id","=",J).execute();return await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category parent: ${X.message}`);throw X}}async function M6(J,$){let G=Number($),X=new Set;while(G){if(X.has(G))return!0;if(G===J)return!0;X.add(G);let Z=await f(G),Y=Z?.parent_category_id??Z?.parentCategoryId;if(!Z||!Y)return!1;G=Number(Y)}return!1}var V$={};B(V$,{updateInventory:()=>T6,updateAvailability:()=>S6,update:()=>P6,store:()=>R6,fetchTopProducts:()=>A6,fetchById:()=>u,fetchAll:()=>V6,destroy:()=>z6,bulkStore:()=>U6,bulkDestroy:()=>B6});import{db as x6}from"@stacksjs/database";async function z6(J){try{let $=await x6.deleteFrom("products").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function B6(J){if(!J.length)return 0;try{let $=await x6.deleteFrom("products").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as a,sql as JZ}from"@stacksjs/database";async function u(J){let $=await a.selectFrom("products").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.manufacturer_id)G=await a.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)X=await a.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:G,category:X}}return}async function V6(){let J=await a.selectFrom("products").selectAll().execute(),$=J.map((F)=>F.manufacturer_id).filter((F)=>F!==null&&F!==void 0),G=J.map((F)=>F.category_id).filter((F)=>F!==null&&F!==void 0),X=a.selectFrom("manufacturers"),Z=a.selectFrom("categories");if($.length>0)X=X.where("id","in",$);if(G.length>0)Z=Z.where("id","in",G);let Y=await X.selectAll().execute(),L=await Z.selectAll().execute(),K=Y.reduce((F,N)=>{return F[N.id]=N,F},{}),W=L.reduce((F,N)=>{return F[N.id]=N,F},{});return J.map((F)=>({...F,manufacturer:F.manufacturer_id?K[F.manufacturer_id]:null,category:F.category_id?W[F.category_id]:null}))}async function A6(J=5){try{return(await a.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",a.fn.sum("order_items.quantity").as("units_sold"),JZ`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(J).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($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:O6}=globalThis.Bun;import{db as _6}from"@stacksjs/database";async function R6(J){try{let $={...J,uuid:O6()},G=await _6.insertInto("products").values($).executeTakeFirst();if(!G)throw Error("Failed to create product item");let X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),Z=await u(X);if(!Z)throw Error("Failed to create product item");return Z}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function U6(J){if(!J.length)return 0;let $=0;try{return await _6.transaction().execute(async(G)=>{for(let X of J){let Z={...X,uuid:O6()};await G.insertInto("products").values(Z).execute(),$++}}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as D4}from"@stacksjs/database";import{formatDate as v4}from"@stacksjs/orm";async function P6(J,$){try{if(!J)throw Error("Product item ID is required for update");let G=await D4.updateTable("products").set({...$,updated_at:v4(new Date)}).where("id","=",J).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 S6(J,$){if(!await u(J))throw Error(`Product item with ID ${J} not found`);try{return await D4.updateTable("products").set({is_available:$,updated_at:v4(new Date)}).where("id","=",J).execute(),await u(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item availability: ${X.message}`);throw X}}async function T6(J,$){let G=await u(J);if(!G)throw Error(`Product item with ID ${J} not found`);let X={updated_at:v4(new Date)};if($!==void 0)X.inventory_count=$;if(Object.keys(X).length===1)return G;try{return await D4.updateTable("products").set(X).where("id","=",J).execute(),await u(J)}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update inventory information: ${Z.message}`);throw Z}}var A$={};B(A$,{updateFeaturedStatus:()=>l6,updateByUuid:()=>c6,update:()=>p6,store:()=>y6,fetchWithProductCount:()=>h6,fetchFeatured:()=>C6,fetchByUuid:()=>k6,fetchById:()=>f6,fetchByCountry:()=>I6,fetchAll:()=>w6,destroy:()=>q6,bulkStore:()=>b6,bulkDestroy:()=>j6});import{db as E6}from"@stacksjs/database";async function q6(J){try{let $=await E6.deleteFrom("manufacturers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function j6(J){if(!J.length)return 0;try{let $=await E6.deleteFrom("manufacturers").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as n}from"@stacksjs/database";function w6(){return n.selectFrom("manufacturers").selectAll().execute()}async function f6(J){return await n.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function k6(J){return await n.selectFrom("manufacturers").where("uuid","=",J).selectAll().executeTakeFirst()}async function C6(J=10){return await n.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(J).execute()}async function I6(J,$={}){let G=$.page||1,X=$.limit||2,Z=await n.selectFrom("manufacturers").select(n.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),Y=Number(Z?.total||0),L=await n.selectFrom("manufacturers").selectAll().where("country","=",J).limit(X).offset((G-1)*X).execute(),K=Math.ceil(Y/X);return{data:L,paging:{total_records:Y,page:G,total_pages:K},next_cursor:G<K?G+1:null}}async function h6(J={}){let $=n.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(J.country)$=$.where("m.country","=",J.country);if(J.featured!==void 0)$=$.where("m.featured","=",J.featured);return $=$.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",n.fn.count("p.id").as("product_count")]).groupBy("m.id"),$.execute()}var{randomUUIDv7:D6}=globalThis.Bun;import{db as v6}from"@stacksjs/database";import{HttpError as g6}from"@stacksjs/error-handling";import{isUniqueViolation as GZ}from"@stacksjs/orm";async function y6(J){try{let $={...J,uuid:D6(),featured:J.featured??!1},G=await v6.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch($){if($ instanceof g6)throw $;if(GZ($))throw new g6(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function b6(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:D6(),featured:G.featured??!1};await v6.insertInto("manufacturers").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${G.message}`);throw G}}import{db as y4}from"@stacksjs/database";import{HttpError as m6}from"@stacksjs/error-handling";import{formatDate as b4,isUniqueViolation as XZ}from"@stacksjs/orm";async function p6(J,$){try{if(!J)throw Error("Manufacturer ID is required for update");let G=await y4.updateTable("manufacturers").set({...$,updated_at:b4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof m6)throw G;if(XZ(G))throw new m6(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function l6(J,$){try{let G=await y4.updateTable("manufacturers").set({featured:$,updated_at:b4(new Date)}).where("id","=",J).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 c6(J,$){try{let G=await y4.updateTable("manufacturers").set({...$,updated_at:b4(new Date)}).where("uuid","=",J).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 O$={};B(O$,{updateVotes:()=>W2,update:()=>K2,store:()=>Z2,fetchStatsByProductIds:()=>X2,fetchStats:()=>G2,fetchMostHelpfulByProductId:()=>e6,fetchByUserId:()=>a6,fetchByProductId:()=>d6,fetchById:()=>o6,fetchApprovedByProductId:()=>r6,fetchAll:()=>s6,destroy:()=>n6,bulkDestroy:()=>i6});import{db as u6}from"@stacksjs/database";async function n6(J){try{let $=await u6.deleteFrom("reviews").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function i6(J){if(!J.length)return 0;try{let $=await u6.deleteFrom("reviews").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as A0}from"@stacksjs/database";async function o6(J){return await A0.selectFrom("reviews").where("id","=",J).selectAll().executeTakeFirst()}async function s6(){return await A0.selectFrom("reviews").selectAll().execute()}async function d6(J){return await A0.selectFrom("reviews").where("product_id","=",J).selectAll().execute()}async function a6(J){return await A0.selectFrom("reviews").where("customer_id","=",J).selectAll().execute()}async function r6(J){return await A0.selectFrom("reviews").where("product_id","=",J).where("is_approved","=",!0).selectAll().execute()}async function e6(J){return await A0.selectFrom("reviews").where("product_id","=",J).orderBy("helpful_votes","desc").selectAll().execute()}import{db as t6}from"@stacksjs/database";function $2(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function J2(J){let $=$2();$.total=J.length;let G=0;for(let X of J){if(X.rating===null||X.rating===void 0){$.commentsOnly++;continue}let Z=Number(X.rating);if(Number.isNaN(Z)){$.commentsOnly++;continue}$.rated++,G+=Z;let Y=Math.min(5,Math.max(1,Math.round(Z)));$.distribution[Y]++}if($.rated>0)$.average=Math.round(G/$.rated*10)/10;return $}async function G2(J){let $=await t6.selectFrom("reviews").select(["rating"]).where("product_id","=",J).where("is_approved","=",!0).execute();return J2($)}async function X2(J){let $=new Map;for(let Z of J)$.set(Z,$2());if(J.length===0)return $;let G=await t6.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",J).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)$.set(Z,J2(Y));return $}var{randomUUIDv7:ZZ}=globalThis.Bun;import{db as YZ}from"@stacksjs/database";function LZ(J){let $=J.rating!==void 0&&J.rating!==null,G=typeof J.content==="string"&&J.content.trim().length>0,X=typeof J.title==="string"&&J.title.trim().length>0;return!$&&!G&&!X}async function Z2(J){try{if(LZ(J))throw Error("A review needs a rating or something written: both were empty");let $={...J,uuid:ZZ(),rating:J.rating??null,is_verified_purchase:J.is_verified_purchase??!1,is_approved:J.is_approved??!1,helpful_votes:J.helpful_votes??0,unhelpful_votes:J.unhelpful_votes??0,is_featured:J.is_featured??!1},G=await YZ.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create review");return G}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${$.message}`)}throw $}}import{db as Y2}from"@stacksjs/database";import{formatDate as L2}from"@stacksjs/orm";async function K2(J,$){try{if(!J)throw Error("Review ID is required for update");let G=await Y2.updateTable("reviews").set({...$,updated_at:L2(new Date)}).where("id","=",J).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 W2(J,$,G=!0){try{let X=$==="helpful"?"helpful_votes":"unhelpful_votes",Z=G?`COALESCE("${X}", 0) + 1`:`MAX(COALESCE("${X}", 0) - 1, 0)`,Y=await Y2.unsafe(`UPDATE "reviews" SET "${X}" = ${Z}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[L2(new Date),J]).execute(),L=Array.isArray(Y)?Y[0]:Y;if(!L)throw Error("Failed to update review votes");return L}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var U$={};B(U$,{updateDefaultStatus:()=>U2,update:()=>_2,store:()=>B2,getDefaultUnit:()=>O2,formatUnitOptions:()=>A2,fetchById:()=>M2,fetchAll:()=>x2,destroy:()=>Q2,bulkUpdate:()=>R2,bulkStore:()=>V2,bulkDestroy:()=>N2});import{db as F2}from"@stacksjs/database";async function Q2(J){try{let $=await F2.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function N2(J){if(!J.length)return 0;try{let $=await F2.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as H2}from"@stacksjs/database";async function M2(J){return await H2.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function x2(){return await H2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:z2}=globalThis.Bun;import{db as h0}from"@stacksjs/database";async function B2(J){try{return await h0.transaction(async($)=>{let G={...J,uuid:z2()},X=await $.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(G.is_default&&G.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();return X})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function V2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:z2()},Z=await h0.insertInto("product_units").values(X).returningAll().executeTakeFirst();if(X.is_default&&X.type&&Z)await h0.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",Z.id).execute();$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function A2(J){try{let $=h0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(J)$=$.where("type","=",J);return $=$.orderBy("name"),$.execute().then((G)=>G.map((X)=>({id:String(X.id),name:X.name,abbreviation:X.abbreviation,is_default:X.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function O2(J){try{return await h0.selectFrom("product_units").selectAll().where("type","=",J).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as _$}from"@stacksjs/database";import{formatDate as R$}from"@stacksjs/orm";async function _2(J,$){try{if(!J)throw Error("Product unit ID is required for update");return await _$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",J).executeTakeFirst();if(!X)return;let Z=$.type??X.type;if(($.is_default??Boolean(X.is_default))&&Z)await G.updateTable("product_units").set({is_default:!1,updated_at:R$(new Date)}).where("type","=",Z).where("id","!=",J).execute();let L=await G.updateTable("product_units").set({...$,updated_at:R$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!L)return;return L})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function R2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X=G;if(!X.id)continue;let Z=X.data&&typeof X.data==="object"?X.data:{...X};delete Z.id;let Y=await _$.updateTable("product_units").set({...Z,updated_at:R$(new Date)}).where("id","=",X.id).executeTakeFirst(),L=Z;if(L.is_default===!0&&L.type)await _$.updateTable("product_units").set({is_default:!1}).where("type","=",L.type).where("id","!=",X.id).execute();if(Number(Y.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function U2(J,$){try{return await _$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!X)return!1;let Z=R$(new Date);if($&&X.type)await G.updateTable("product_units").set({is_default:!1,updated_at:Z}).where("type","=",X.type).where("id","!=",J).execute();return await G.updateTable("product_units").set({is_default:$,updated_at:Z}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var P$={};B(P$,{update:()=>v2,store:()=>k2,generateVariantCombinations:()=>h2,formatVariantOptions:()=>I2,fetchById:()=>q2,fetchAll:()=>j2,destroy:()=>S2,bulkUpdate:()=>y2,bulkStore:()=>C2,bulkDestroy:()=>T2});import{db as P2}from"@stacksjs/database";async function S2(J){try{let $=await P2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function T2(J){if(!J.length)return 0;try{let $=await P2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as E2}from"@stacksjs/database";async function q2(J){return await E2.selectFrom("product_variants").where("id","=",J).selectAll().executeTakeFirst()}async function j2(){return await E2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:w2}=globalThis.Bun;import{db as f2}from"@stacksjs/database";async function k2(J){try{let $={...J,uuid:w2()},G=await f2.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product variant");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function C2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:w2()};await f2.insertInto("product_variants").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${G.message}`);throw G}}function I2(J){if(!J||!J.length)return JSON.stringify([]);let $=J.map((G)=>G.trim()).filter(Boolean);return JSON.stringify($)}function h2(J){let $=Object.keys(J);if(!$.length)return[];function G(X,Z){if(X===$.length)return[Z];let Y=$[X],L=J[Y]??[],K=[];for(let W of L){let F={...Z,[Y]:W};K.push(...G(X+1,F))}return K}return G(0,{})}import{db as g2}from"@stacksjs/database";import{formatDate as D2}from"@stacksjs/orm";async function v2(J,$){try{let G=await g2.updateTable("product_variants").set({...$,updated_at:D2(new Date)}).where("id","=",J).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 y2(J){if(!J.length)return 0;let $=0;try{for(let G of J){if(!G.id)continue;let X=await g2.updateTable("product_variants").set({...G,updated_at:D2(new Date)}).where("id","=",G.id).executeTakeFirst();if(Number(X.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${G.message}`);throw G}}var KZ={categories:B$,items:V$,manufacturers:A$,reviews:O$,units:U$,variants:P$},WZ=KZ;var i4={};B(i4,{updateStatus:()=>e2,updatePrintJob:()=>t2,update:()=>r2,store:()=>d2,fetchSuccessRate:()=>u2,fetchPrintsPerHour:()=>o2,fetchPrintTimeStats:()=>i2,fetchPrintJobStats:()=>c2,fetchPageStats:()=>n2,fetchById:()=>O0,fetchAll:()=>l2,destroy:()=>m2,bulkStore:()=>a2,bulkDestroy:()=>p2});import{db as b2}from"@stacksjs/database";async function m2(J){try{let $=await b2.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function p2(J){if(!J.length)return 0;try{let $=await b2.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as p4}from"@stacksjs/database";import{formatDate as FZ}from"@stacksjs/orm";function b(J){return FZ(J)}function QZ(J){if(J instanceof Date)return Number.isNaN(J.getTime())?null:J;if(typeof J==="number"){let X=new Date(J<=2147483647?J*1000:J);return Number.isNaN(X.getTime())?null:X}let $=String(J||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let X=new Date(Number($)*1000);return Number.isNaN(X.getTime())?null:X}let G=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function O0(J){return await p4.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function l2(){return await p4.selectFrom("receipts").selectAll().execute()}async function c2(J,$){let G=b(J),X=b($),Z=await h("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 u2(J,$){let G=b(J),X=b($),Z=await h("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"}}},(L)=>L.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 n2(J,$){let G=b(J),X=b($),Z=await h("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 i2(J,$){let G=b(J),X=b($),Z=await h("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 o2(J,$){let G=typeof J==="number"?J:J.getTime(),X=typeof $==="number"?$:$.getTime(),Z=b(J),Y=b($),L=await p4.selectFrom("receipts").where("timestamp",">=",Z).where("timestamp","<=",Y).selectAll().execute(),K=L.length,W=Math.ceil((X-G)/3600000),F=W>0?Math.round(K/W):0,N=Array.from({length:24},(H,M)=>({hour:M,count:0}));return L.forEach((H)=>{let M=QZ(H.timestamp);if(!M)return;N[M.getHours()].count++}),{totalPrints:K,totalHours:W,printsPerHour:F,hourlyBreakdown:N}}var{randomUUIDv7:s2}=globalThis.Bun;import{db as c4}from"@stacksjs/database";import{formatDate as l4}from"@stacksjs/orm";function g0(J){try{if(typeof J==="number")return l4(J<=2147483647?J*1000:J);if(typeof J==="string"&&/^\d{10}$/.test(J))return l4(Number(J)*1000);return l4(J)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function d2(J){try{let $=s2(),G={...J,timestamp:g0(J.timestamp),uuid:$};await c4.insertInto("receipts").values(G).executeTakeFirst();let X=await c4.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function a2(J){if(!J.length)return 0;try{let $=J.map((X)=>({...X,timestamp:g0(X.timestamp),uuid:s2()})),G=await c4.insertInto("receipts").values($).executeTakeFirst();return Number(G.numInsertedOrUpdatedRows??G.numAffectedRows??G.affectedRows??G.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as u4}from"@stacksjs/database";import{formatDate as n4}from"@stacksjs/orm";async function r2(J,$){try{if(!J)throw Error("Receipt ID is required for update");let G={...$,...$.timestamp===void 0?{}:{timestamp:g0($.timestamp)},updated_at:n4(new Date)};await u4.updateTable("receipts").set(G).where("id","=",J).execute();let X=await O0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function e2(J,$){try{await u4.updateTable("receipts").set({status:$,updated_at:n4(new Date)}).where("id","=",J).execute();let G=await O0(J);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 t2(J,$,G,X){try{let Z={updated_at:n4(new Date)};if($!==void 0)Z.size=$;if(G!==void 0)Z.pages=G;if(X!==void 0)Z.duration=X;await u4.updateTable("receipts").set(Z).where("id","=",J).execute();let Y=await O0(J);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 z1={};B(z1,{zones:()=>K4,tracking:()=>X4,routes:()=>w$,rates:()=>d$,methods:()=>u$,licenses:()=>m$,geocoding:()=>v$,drivers:()=>I$,digital:()=>k$,default:()=>hZ});var w$={};B(w$,{validateDeliveryRouteWrite:()=>_0,updateStops:()=>FG,updateMetrics:()=>QG,updateLastActive:()=>KG,update:()=>WG,store:()=>LG,fetchById:()=>T$,fetchByDriver:()=>YG,fetchAll:()=>XG,fetchActive:()=>ZG,destroy:()=>JG,bulkDestroy:()=>GG,DeliveryRouteInputError:()=>I});import{db as $G}from"@stacksjs/database";async function JG(J){try{let $=await $G.deleteFrom("delivery_routes").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function GG(J){if(!J.length)return 0;try{let $=await $G.deleteFrom("delivery_routes").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as S$}from"@stacksjs/database";async function T$(J){return await S$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function XG(){return await S$.selectFrom("delivery_routes").selectAll().execute()}async function ZG(){return await S$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function YG(J){return await S$.selectFrom("delivery_routes").where("driver","=",J).selectAll().execute()}var{randomUUIDv7:MZ}=globalThis.Bun;import{db as o4}from"@stacksjs/database";function L0(J,$){let G={};for(let[X,Z]of Object.entries($))for(let Y of Z){if(!Object.prototype.hasOwnProperty.call(J,Y)||J[Y]===void 0)continue;G[X]=J[Y];break}return G}function D0(J){return L0(J,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function i(J){return L0(J,{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 v0(J){return L0(J,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function y0(J){return L0(J,{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 b0(J){return L0(J,{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 m0(J){return L0(J,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function E$(J){return L0(J,{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 NZ}from"@stacksjs/database";class I extends TypeError{constructor(J){super(J);this.name="DeliveryRouteInputError"}}function q$(J,$,G){return Number(J[G]??$?.[G])}function HZ(J,$){let G=J.last_active??$?.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 _0(J,$){let G=q$(J,$,"driver_id"),X=q$(J,$,"stops"),Z=q$(J,$,"delivery_time"),Y=q$(J,$,"total_distance"),L=HZ(J,$);if(!Number.isSafeInteger(G)||G<1)throw new I("Driver must be a positive integer.");if(!Number.isSafeInteger(X)||X<0)throw new I("Stops must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new I("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(Y)||Y<0)throw new I("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(L)||L<0)throw new I("Last active must be a valid Unix timestamp.");let K=await NZ.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!K)throw new I(`Driver ${G} was not found.`);return{...J,driver_id:Number(K.id),driver:K.name,vehicle:K.vehicle_number,last_active:L}}async function LG(J){try{let $=MZ(),G=E$(J),Z={...await _0(G),uuid:$};await o4.insertInto("delivery_routes").values(Z).executeTakeFirst();let Y=await o4.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!Y)throw Error("Failed to create delivery route");return Y}catch($){if($ instanceof I)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function KG(J){try{await o4.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",J).execute();let $=await T$(J);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as j$}from"@stacksjs/database";import{formatDate as s4}from"@stacksjs/orm";async function WG(J,$){try{if(!J)throw Error("Delivery route ID is required for update");let G=await j$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=E$($),Z=await _0(X,G),Y=await j$.updateTable("delivery_routes").set({...Z,updated_at:s4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof I)throw G;if(G instanceof Error)throw TypeError(`Failed to update delivery route: ${G.message}`);throw G}}async function FG(J,$){try{let G=await j$.updateTable("delivery_routes").set({stops:$,updated_at:s4(new Date)}).where("id","=",J).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 QG(J,$,G){try{let X={updated_at:s4(new Date)};if($!==void 0)X.delivery_time=$;if(G!==void 0)X.total_distance=G;let Z=await j$.updateTable("delivery_routes").set(X).where("id","=",J).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 k$={};B(k$,{updateStatus:()=>UG,updateDeliverySettings:()=>PG,update:()=>RG,store:()=>OG,softDelete:()=>HG,fetchById:()=>BG,fetchAll:()=>VG,destroy:()=>NG,bulkStore:()=>_G,bulkSoftDelete:()=>xG,bulkDestroy:()=>MG});import{db as f$}from"@stacksjs/database";async function NG(J){try{let $=await f$.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function HG(J){try{let $=await f$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function MG(J){if(!J.length)return 0;try{let $=await f$.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function xG(J){if(!J.length)return 0;try{let $=await f$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as zG}from"@stacksjs/database";async function BG(J){return await zG.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function VG(){return await zG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:AG}=globalThis.Bun;import{db as d4}from"@stacksjs/database";async function OG(J){try{let $=AG(),G={...y0(J),uuid:$};await d4.insertInto("digital_deliveries").values(G).executeTakeFirst();let X=await d4.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created digital delivery");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function _G(J){if(!J.length)return 0;try{let $=J.map((X)=>({...y0(X),uuid:AG()})),G=await d4.insertInto("digital_deliveries").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as a4}from"@stacksjs/database";import{formatDate as r4}from"@stacksjs/orm";async function RG(J,$){try{if(!J)throw Error("Digital delivery ID is required for update");let G=await a4.updateTable("digital_deliveries").set({...y0($),updated_at:r4(new Date)}).where("id","=",J).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 UG(J,$){try{let G=await a4.updateTable("digital_deliveries").set({status:$,updated_at:r4(new Date)}).where("id","=",J).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 PG(J,$,G,X,Z){try{let Y={updated_at:r4(new Date)};if($!==void 0)Y.download_limit=$;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 L=await a4.updateTable("digital_deliveries").set(Y).where("id","=",J).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update delivery settings");return L}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery settings: ${Y.message}`);throw Y}}var I$={};B(I$,{updateStatus:()=>IG,updateContact:()=>hG,update:()=>CG,store:()=>fG,fetchById:()=>C$,fetchAll:()=>TG,destroy:()=>qG,bulkStore:()=>kG,bulkDestroy:()=>jG});import{db as EG}from"@stacksjs/database";import{db as SG}from"@stacksjs/database";async function C$(J){return await SG.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function TG(){return await SG.selectFrom("drivers").selectAll().execute()}async function qG(J){try{let $=await EG.deleteFrom("drivers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function jG(J){if(!J.length)return 0;let $=0;try{return await EG.transaction().execute(async(G)=>{for(let X of J)if(await C$(X))await G.deleteFrom("drivers").where("id","=",X).execute(),$++}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${G.message}`);throw G}}var{randomUUIDv7:wG}=globalThis.Bun;import{db as e4}from"@stacksjs/database";async function fG(J){try{let $=wG(),G={...m0(J),uuid:$};await e4.insertInto("drivers").values(G).executeTakeFirst();let X=await e4.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created driver");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function kG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...m0(X),uuid:wG()})),G=await e4.insertInto("drivers").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as t4}from"@stacksjs/database";import{formatDate as $1}from"@stacksjs/orm";async function CG(J,$){try{if(!J)throw Error("Driver ID is required for update");let G=await t4.updateTable("drivers").set({...m0($),updated_at:$1(new Date)}).where("id","=",J).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 IG(J,$){try{let G=await t4.updateTable("drivers").set({status:$,updated_at:$1(new Date)}).where("id","=",J).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 hG(J,$){try{let G={updated_at:$1(new Date)};if($!==void 0)G.phone=$;let X=await t4.updateTable("drivers").set(G).where("id","=",J).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 v$={};B(v$,{setGeocodingDriver:()=>VZ,nominatimDriver:()=>D$,geocodingDriver:()=>mG,geocode:()=>AZ,formatQuery:()=>R0,checkCoverage:()=>OZ,PRECISION_RANK:()=>l0});var K0=(J)=>J*Math.PI/180;function r(J,$){let G=K0($.latitude-J.latitude),X=K0($.longitude-J.longitude),Z=K0(J.latitude),Y=K0($.latitude),L=Math.sin(G/2)**2+Math.sin(X/2)**2*Math.cos(Z)*Math.cos(Y);return 12742017.6*Math.asin(Math.sqrt(L))}function h$(J,$){let G=K0(J.latitude),X=K0($.latitude),Z=K0($.longitude-J.longitude),Y=Math.sin(Z)*Math.cos(X),L=Math.cos(G)*Math.sin(X)-Math.sin(G)*Math.cos(X)*Math.cos(Z);return(Math.atan2(Y,L)*180/Math.PI+360)%360}function g$(J,$,G={}){let X=G.detourFactor??1.35,Z=G.minimumSeconds??30;if(!Number.isFinite($)||$<=0.5)return null;let Y=J*X/$;return Math.max(Z,Math.round(Y))}function gG(J,$,G){return r(J,$)<=G}function p0(J){return typeof J?.latitude==="number"&&typeof J?.longitude==="number"&&Number.isFinite(J.latitude)&&Number.isFinite(J.longitude)}var l0={unknown:0,locality:1,postal:2,street:3,rooftop:4};function R0(J){return[J.street,J.city,J.region,J.postalCode,J.country].map(($)=>String($??"").trim()).filter(Boolean).join(", ")}var xZ="https://nominatim.openstreetmap.org/search",DG=1000,vG=0,yG=Promise.resolve();async function zZ(J){let $=yG.then(async()=>{let G=Date.now()-vG;if(G<DG)await Bun.sleep(DG-G);return vG=Date.now(),J()});return yG=$.then(()=>{return},()=>{return}),$}function BZ(J){let $=J.address??{},G=String(J.addresstype??""),X=String(J.type??""),Z=String(J.category??J.class??"");if($.house_number||X==="house"||X==="building"||G==="building")return"rooftop";if($.road||Z==="highway"||G==="road")return"street";if(G==="postcode"||$.postcode&&!$.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(G))return"locality";return"unknown"}function D$(J={}){let $=J.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,G=J.endpoint??xZ;return{name:"nominatim",async geocode(X){let Z=R0(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 L=await zZ(()=>fetch(Y,{headers:{"user-agent":$,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!L.ok)throw Error(`Nominatim responded ${L.status}`);let W=(await L.json())?.[0];if(!W)return null;let F=Number(W.lat),N=Number(W.lon);if(!Number.isFinite(F)||!Number.isFinite(N))return null;let H=BZ(W);return{latitude:F,longitude:N,formatted:String(W.display_name??Z),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[H],precision:H,provider:"nominatim"}}}}var bG=null;function VZ(J){bG=J}function mG(){return bG??D$()}async function AZ(J,$={}){let G=$.driver??mG(),X=$.minimumPrecision??"street",Z=`geocode:${G.name}:${R0(J).toLowerCase()}`,Y=await _Z(Z);if(Y!==void 0)return Y;let L=await G.geocode(J),K=L&&l0[L.precision]>=l0[X]?L:null;return await RZ(Z,K,K?$.cacheSeconds??2592000:600),K}function OZ(J,$,G){if($.length===0)return null;let X=$[0],Z=r(J,X);for(let Y of $.slice(1)){let L=r(J,Y);if(L<Z)Z=L,X=Y}return{covered:Z<=G,distanceMeters:Math.round(Z),nearest:X}}async function _Z(J){try{let G=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!G)return;let X=await G.get(J);if(X===null||X===void 0)return;return X==="null"?null:JSON.parse(String(X))}catch{return}}async function RZ(J,$,G){try{let Z=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!Z)return;await Z.set(J,$===null?"null":JSON.stringify($),G)}catch{}}var m$={};B(m$,{validateLicenseKeyWrite:()=>W0,updateStatus:()=>$X,updateExpiration:()=>JX,update:()=>tG,store:()=>rG,softDelete:()=>lG,fetchById:()=>iG,fetchAll:()=>oG,destroy:()=>pG,bulkStore:()=>eG,bulkSoftDelete:()=>uG,bulkDestroy:()=>cG,LicenseKeyInputError:()=>E});import{db as y$}from"@stacksjs/database";async function pG(J){try{let $=await y$.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function lG(J){try{let $=await y$.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function cG(J){if(!J.length)return 0;try{let $=await y$.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function uG(J){if(!J.length)return 0;try{let $=await y$.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as nG}from"@stacksjs/database";async function iG(J){return await nG.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst()}async function oG(){return await nG.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:aG}=globalThis.Bun;import{db as X1}from"@stacksjs/database";import{db as J1}from"@stacksjs/database";var sG=["Standard License","Premium License","Enterprise License"],dG=["active","inactive","unassigned"];class E extends TypeError{constructor(J){super(J);this.name="LicenseKeyInputError"}}function c0(J,$,G){return J[G]!==void 0?J[G]:$?.[G]}function G1(J,$,G,X){let Z=c0(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 UZ(J){if(typeof J==="number")return J>2147483647?Math.floor(J/1000):J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return J.length===13?Math.floor(Number(J)/1000):Number(J);if(typeof J==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(J)?`${J.replace(" ","T")}Z`:J;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function W0(J,$){let G=String(c0(J,$,"key")||"").trim().toUpperCase(),X=String(c0(J,$,"template")||""),Z=String(c0(J,$,"status")||""),Y=UZ(c0(J,$,"expiry_date")),L=G1(J,$,"customer_id","Customer"),K=G1(J,$,"product_id","Product"),W=G1(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(!sG.includes(X))throw new E(`Template must be one of: ${sG.join(", ")}.`);if(!dG.includes(Z))throw new E(`Status must be one of: ${dG.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([L?J1.selectFrom("customers").where("id","=",L).select("id").executeTakeFirst():null,K?J1.selectFrom("products").where("id","=",K).select("id").executeTakeFirst():null,W?J1.selectFrom("orders").where("id","=",W).select(["id","customer_id"]).executeTakeFirst():null]);if(L&&!F)throw new E(`Customer ${L} was not found.`);if(K&&!N)throw new E(`Product ${K} was not found.`);if(W&&!H)throw new E(`Order ${W} was not found.`);if(L&&H?.customer_id&&Number(H.customer_id)!==L)throw new E(`Order ${W} belongs to Customer ${H.customer_id}, not Customer ${L}.`);return{...J,key:G,template:X,expiry_date:Y,status:Z,customer_id:L,product_id:K,order_id:W}}async function rG(J){try{let $=aG(),G=b0(J),X={...await W0(G),uuid:$};await X1.insertInto("license_keys").values(X).executeTakeFirst();let Z=await X1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created license key");return Z}catch($){if($ instanceof E)throw $;if($ instanceof Error){if($.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: ${$.message}`)}throw $}}async function eG(J){if(!J.length)return 0;try{let $=await Promise.all(J.map(async(X)=>({...await W0(b0(X)),uuid:aG()}))),G=await X1.insertInto("license_keys").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof E)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as b$}from"@stacksjs/database";import{formatDate as Z1}from"@stacksjs/orm";async function tG(J,$){try{if(!J)throw Error("License key ID is required for update");let G=await b$.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=b0($),Z=await W0(X,G),Y=await b$.updateTable("license_keys").set({...Z,updated_at:Z1(new Date)}).where("id","=",J).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 $X(J,$){try{let G=await b$.updateTable("license_keys").set({status:$,updated_at:Z1(new Date)}).where("id","=",J).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 JX(J,$){try{let G={updated_at:Z1(new Date)};if($!==void 0)G.expiry_date=$;let X=await b$.updateTable("license_keys").set(G).where("id","=",J).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 u$={};B(u$,{updateStatus:()=>MX,updatePricing:()=>xX,update:()=>HX,store:()=>WX,softDelete:()=>XX,getActiveShippingMethods:()=>NX,formatShippingOptions:()=>QX,fetchById:()=>c$,fetchAll:()=>LX,destroy:()=>GX,bulkStore:()=>FX,bulkSoftDelete:()=>YX,bulkDestroy:()=>ZX});import{db as p$}from"@stacksjs/database";async function GX(J){try{let $=await p$.deleteFrom("shipping_methods").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function XX(J){try{let $=await p$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function ZX(J){if(!J.length)return 0;try{let $=await p$.deleteFrom("shipping_methods").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function YX(J){if(!J.length)return 0;try{let $=await p$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as l$}from"@stacksjs/database";async function c$(J){let $=await l$.selectFrom("shipping_methods").where("id","=",J).selectAll().executeTakeFirst();if($){let G=await l$.selectFrom("shipping_zones").where("shipping_method_id","=",J).selectAll().execute();return{...$,shippingZones:G}}return}async function LX(){let J=await l$.selectFrom("shipping_methods").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((Y)=>Y.id))],Z=(await l$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((Y,L)=>{let K=L.shipping_method_id;if(K!==null&&K!==void 0){if(!Y[K])Y[K]=[];Y[K].push(L)}return Y},{});return J.map((Y)=>({...Y,shipping_zones:Z[Y.id]||[]}))}var{randomUUIDv7:KX}=globalThis.Bun;import{db as u0}from"@stacksjs/database";async function WX(J){try{let $=KX(),G={...D0(J),uuid:$};await u0.insertInto("shipping_methods").values(G).executeTakeFirst();let X=await u0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping method");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function FX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...D0(X),uuid:KX()})),G=await u0.insertInto("shipping_methods").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function QX(){try{return u0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping options: ${J.message}`);throw J}}async function NX(){try{return await u0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping methods: ${J.message}`);throw J}}import{db as Y1}from"@stacksjs/database";import{formatDate as L1}from"@stacksjs/orm";async function HX(J,$){try{if(!J)throw Error("Shipping method ID is required for update");let G=await Y1.updateTable("shipping_methods").set({...D0($),updated_at:L1(new Date)}).where("id","=",J).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 MX(J,$){try{let G=await Y1.updateTable("shipping_methods").set({status:$,updated_at:L1(new Date)}).where("id","=",J).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 xX(J,$,G){try{let X={updated_at:L1(new Date)};if($!==void 0)X.base_rate=$;if(G!==void 0)X.free_shipping=G;let Z=await Y1.updateTable("shipping_methods").set(X).where("id","=",J).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 d$={};B(d$,{validateZoneMatchesAddress:()=>SX,validateShippingRateWrite:()=>F0,updateByZone:()=>DX,updateByMethod:()=>vX,update:()=>hX,store:()=>CX,resolveZoneForAddress:()=>i$,getShippingRatesByMethod:()=>EX,getRatesByZone:()=>UX,getRateByWeightAndZone:()=>K1,getRateByWeightAndAddress:()=>PX,formatShippingRateOptions:()=>TX,fetchById:()=>_X,fetchAll:()=>RX,destroyByZone:()=>VX,destroyByMethod:()=>AX,destroy:()=>zX,bulkUpdate:()=>gX,bulkStore:()=>IX,bulkDestroy:()=>BX,ShippingRateInputError:()=>k});import{db as n$}from"@stacksjs/database";async function zX(J){try{let $=await n$.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function BX(J){if(!J.length)return 0;try{let $=await n$.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function VX(J){try{let $=await n$.deleteFrom("shipping_rates").where("shipping_zone_id","=",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function AX(J){try{let $=await n$.deleteFrom("shipping_rates").where("shipping_method_id","=",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as v}from"@stacksjs/database";async function _X(J){let $=await v.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.shipping_zone_id)G=await v.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)X=await v.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:G,shipping_method:X}}return}async function RX(){let J=await v.selectFrom("shipping_rates").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((K)=>K.shipping_zone_id).filter((K)=>K!==null&&K!==void 0))],G=[...new Set(J.map((K)=>K.shipping_method_id).filter((K)=>K!==null&&K!==void 0))],[X,Z]=await Promise.all([$.length?v.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],G.length?v.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),Y=X.reduce((K,W)=>{return K[W.id]=W,K},{}),L=Z.reduce((K,W)=>{return K[W.id]=W,K},{});return J.map((K)=>({...K,shipping_zone:K.shipping_zone_id?Y[K.shipping_zone_id]:[],shipping_method:K.shipping_method_id?L[K.shipping_method_id]:[]}))}async function UX(J){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function K1(J,$){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function i$(J){if(!J?.countryCode)return null;try{let $=await v.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let G=null;for(let X of $){let Z=1;if(J.region&&X.regions&&OX(X.regions,J.region))Z=2;if(J.postalCode&&X.postal_codes&&OX(X.postal_codes,J.postalCode))Z=3;if(!G||Z>G.score)G={id:X.id,score:Z}}return G?.id??null}catch{return null}}async function PX(J,$){let G=await i$($);if(G==null)return;return K1(J,G)}async function SX(J,$){return await i$($)===J}function OX(J,$){if(!J||!$)return!1;let G=$.trim().toUpperCase();for(let X of J.split(/[,|;]/))if(X.trim().toUpperCase()===G)return!0;return!1}async function TX(){try{return(await v.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function EX(J){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:kX}=globalThis.Bun;import{db as W1}from"@stacksjs/database";import{db as n0}from"@stacksjs/database";async function qX(){return await n0.selectFrom("shipping_zones").selectAll().execute()}async function o$(J){return await n0.selectFrom("shipping_zones").where("id","=",J).selectAll().executeTakeFirst()}function jX(){try{return n0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping zone options: ${J.message}`);throw J}}async function wX(){try{return await n0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping zones: ${J.message}`);throw J}}async function fX(J){try{return await n0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class k extends TypeError{constructor(J){super(J);this.name="ShippingRateInputError"}}function i0(J,$,G){return Number(J[G]??$?.[G])}async function F0(J,$){let G=i0(J,$,"shipping_method_id"),X=i0(J,$,"shipping_zone_id"),Z=i0(J,$,"weight_from"),Y=i0(J,$,"weight_to"),L=i0(J,$,"rate");if(!Number.isSafeInteger(G)||G<1)throw new k("Shipping method must be a positive integer.");if(!Number.isSafeInteger(X)||X<1)throw new k("Shipping zone must be a positive integer.");if(!Number.isFinite(Z)||Z<0)throw new k("Weight from must be a non-negative number.");if(!Number.isFinite(Y)||Y<Z)throw new k("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(L)||L<0)throw new k("Rate must be a non-negative integer in minor currency units.");let[K,W]=await Promise.all([c$(G),o$(X)]);if(!K)throw new k(`Shipping method ${G} was not found.`);if(!W)throw new k(`Shipping zone ${X} was not found.`);if(Number(W.shipping_method_id)!==G)throw new k(`Shipping zone ${X} is not assigned to shipping method ${G}.`)}async function CX(J){try{let $=i(J),G=Number($.shipping_method_id),X=Number($.shipping_zone_id);await F0($);let Z=kX(),Y={...$,shipping_method_id:G,shipping_zone_id:X,uuid:Z};await W1.insertInto("shipping_rates").values(Y).executeTakeFirst();let L=await W1.selectFrom("shipping_rates").where("uuid","=",Z).selectAll().executeTakeFirst();if(!L)throw Error("Failed to resolve created shipping rate");return L}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function IX(J){if(!J.length)return 0;try{for(let X of J){let Z=i(X);await F0(Z)}let $=J.map((X)=>({...i(X),uuid:kX()})),G=await W1.insertInto("shipping_rates").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as o0}from"@stacksjs/database";import{formatDate as s$}from"@stacksjs/orm";async function hX(J,$){try{if(!J)throw Error("Shipping rate ID is required for update");let G=await o0.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=i($);await F0(X,G);let Z=await o0.updateTable("shipping_rates").set({...X,updated_at:s$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(G){if(G instanceof k)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function gX(J){if(!J.length)return 0;try{let $=0;for(let{id:G,data:X}of J){let Z=await o0.updateTable("shipping_rates").set({...i(X),updated_at:s$(new Date)}).where("id","=",G).executeTakeFirst();if(Q(Z)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function DX(J,$){try{let G=await o0.updateTable("shipping_rates").set({...i($),updated_at:s$(new Date)}).where("shipping_zone_id","=",J).executeTakeFirst();return Q(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${G.message}`);throw G}}async function vX(J,$){try{let G=await o0.updateTable("shipping_rates").set({...i($),updated_at:s$(new Date)}).where("shipping_method_id","=",J).executeTakeFirst();return Q(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var X4={};B(X4,{startStop:()=>mX,startRoute:()=>cX,routeTrackingChannel:()=>F1,recordDriverPing:()=>yX,orderTrackingChannel:()=>e,isWithin:()=>gG,hasCoordinates:()=>p0,failStop:()=>lX,estimateSecondsRemaining:()=>g$,emitDeliveryStarted:()=>e$,emitDeliveryPosition:()=>a$,emitDeliveryNearby:()=>t$,emitDeliveryFailed:()=>G4,emitDeliveryCompleted:()=>J4,emitDeliveryAssigned:()=>r$,emitDeliveryArrived:()=>$4,distanceInMeters:()=>r,completeStop:()=>pX,broadcastToChannel:()=>o,bearingInDegrees:()=>h$,assignStop:()=>bX,NEARBY_RADIUS_METERS:()=>Q1,ARRIVAL_RADIUS_METERS:()=>N1});function e(J){return`order.${J}`}function F1(J){return`delivery-route.${J}`}async function U0(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 o(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(J).broadcast($,G,"private")}catch{}}async function a$(J,$,G){await Promise.all([...J.map((X)=>o(e(X),"delivery:position",G)),$==null?Promise.resolve():o(F1($),"delivery:position",G)])}async function r$(J){if(await U0("delivery:assigned",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:assigned",{stop:J})}async function e$(J){if(await U0("delivery:started",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:started",{stop:J})}async function t$(J,$,G){if(await U0("delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G}),J.order_id!=null)await o(e(J.order_id),"delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G})}async function $4(J){if(await U0("delivery:arrived",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:arrived",{stop:J})}async function J4(J){if(await U0("delivery:completed",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:completed",{stop:J})}async function G4(J,$){await U0("delivery:failed",{stop:J,reason:$})}var{randomUUIDv7:PZ}=globalThis.Bun;import{db as y}from"@stacksjs/database";var Q1=400,N1=60,SZ=250;async function yX(J){let $=J.recordedAt??new Date().toISOString(),G=typeof J.accuracy!=="number"||J.accuracy<=SZ,X=await y.selectFrom("drivers").where("id","=",J.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!X)throw Error(`Unknown driver: ${J.driverId}`);let Z=p0(X)?{latitude:X.latitude,longitude:X.longitude}:null,Y=typeof J.heading==="number"?J.heading:Z?h$(Z,J):null,L=await TZ(J.driverId),K=L?await EZ(L.id):null,W=null,F=null,N=!1,H=!1,M=K&&p0({latitude:K.latitude??void 0,longitude:K.longitude??void 0})?{latitude:K.latitude,longitude:K.longitude}:null;if(G&&K&&M)W=Math.round(r(J,M)),F=g$(W,J.speed??0),H=W<=N1&&K.arrived_at==null,N=!H&&W<=Q1&&K.status==="en_route"&&K.notified_nearby_at==null;let O=await qZ({driverId:J.driverId,routeId:L?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$});if(G)await y.updateTable("drivers").set({latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??0,last_ping_at:$}).where("id","=",J.driverId).execute();if(K&&(W!=null||F!=null))await y.updateTable("delivery_stops").set({eta_at:F==null?K.eta_at:new Date(Date.now()+F*1000).toISOString()}).where("id","=",K.id).execute();if(G)await a$(K?.order_id==null?[]:[K.order_id],L?.id??null,{driverId:J.driverId,routeId:L?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$,distanceToStopMeters:W,etaSeconds:F});if(N&&K)await y.updateTable("delivery_stops").set({notified_nearby_at:$}).where("id","=",K.id).execute(),await t$(K,W,F);if(H&&K)await y.updateTable("delivery_stops").set({status:"arrived",arrived_at:$}).where("id","=",K.id).execute(),await $4({...K,status:"arrived",arrived_at:$});return{pingId:O,routeId:L?.id??null,stopId:K?.id??null,distanceToStopMeters:W,etaSeconds:F,crossedNearby:N,crossedArrival:H}}async function TZ(J){return await y.selectFrom("delivery_routes").where("driver_id","=",J).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function EZ(J){let $=await y.selectFrom("delivery_stops").where("delivery_route_id","=",J).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 $.find((G)=>G.status==="en_route")??$.find((G)=>G.status==="arrived")??$[0]??null}async function qZ(J){let $=PZ();return await y.insertInto("driver_pings").values({uuid:$,driver_id:J.driverId,delivery_route_id:J.routeId,latitude:J.latitude,longitude:J.longitude,heading:J.heading,speed:J.speed??0,accuracy:J.accuracy,recorded_at:J.recordedAt}).executeTakeFirst(),(await y.selectFrom("driver_pings").where("uuid","=",$).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:jZ}=globalThis.Bun;import{db as q}from"@stacksjs/database";async function bX(J){let $=jZ(),G=J.sequence??await fZ(J.deliveryRouteId);await q.insertInto("delivery_stops").values({uuid:$,delivery_route_id:J.deliveryRouteId,order_id:J.orderId??null,sequence:G,status:"pending",address:J.address,latitude:J.latitude??null,longitude:J.longitude??null,recipient_name:J.recipientName??null,recipient_phone:J.recipientPhone??null,eta_at:J.etaAt??null}).executeTakeFirst();let X=await CZ($);if(X)await r$(X);return X??{}}async function mX(J){await q.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",J).execute();let $=await M1(J);if(!$)return null;if($.order_id!=null)await H1($.order_id,"OUT_FOR_DELIVERY");return await e$($),$}async function pX(J,$){let G=new Date().toISOString();await q.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await kZ(J)?{}:{arrived_at:G},...$?{notes:$}:{}}).where("id","=",J).execute();let X=await M1(J);if(!X)return null;if(X.order_id!=null)await H1(X.order_id,"DELIVERED");return await J4(X),await uX(X.delivery_route_id),X}async function lX(J,$){await q.updateTable("delivery_stops").set({status:"failed",notes:$}).where("id","=",J).execute();let G=await M1(J);if(!G)return null;if(G.order_id!=null)await H1(G.order_id,"SHIPPED");return await G4(G,$),await uX(G.delivery_route_id),G}async function cX(J){await q.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",J).execute()}async function uX(J){if(J==null)return;if(await q.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let G=await q.selectFrom("delivery_routes").where("id","=",J).select(["driver_id"]).executeTakeFirst();if(await q.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",J).execute(),G?.driver_id!=null)await q.updateTable("drivers").set({status:"active"}).where("id","=",G.driver_id).execute()}async function H1(J,$){let G=await q.selectFrom("orders").where("id","=",J).select(["id","status"]).executeTakeFirst();if(!G)return;let X=await Promise.resolve().then(() => (x0(),VJ)),{canTransition:Z,emitForStatus:Y}=X,L=wZ(G.status,$,Z);if(L.length===0){let{log:K}=await import("@stacksjs/logging").catch(()=>({log:null}));K?.warn(`[delivery] refused to move order ${J} from ${G.status} to ${$}: no legal transition`);return}for(let K of L)await q.updateTable("orders").set({status:K}).where("id","=",J).execute(),await Y(K,{...G,status:K})}function wZ(J,$,G){if(J===$)return[];if(G(J,$))return[$];for(let X of["PROCESSING","SHIPPED"]){if(X===J||X===$)continue;if(G(J,X)&&G(X,$))return[X,$]}return[]}async function fZ(J){return(await q.selectFrom("delivery_stops").where("delivery_route_id","=",J).select(["sequence"]).execute()).reduce((G,X)=>Math.max(G,X.sequence??0),0)+1}async function kZ(J){return(await q.selectFrom("delivery_stops").where("id","=",J).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function M1(J){return await q.selectFrom("delivery_stops").where("id","=",J).selectAll().executeTakeFirst()??null}async function CZ(J){return await q.selectFrom("delivery_stops").where("uuid","=",J).selectAll().executeTakeFirst()??null}var K4={};B(K4,{updateStatus:()=>tX,updateRegionsAndPostalCodes:()=>J9,updateCountries:()=>$9,update:()=>eX,store:()=>aX,softDelete:()=>iX,getZonesByCountry:()=>fX,getActiveShippingZones:()=>wX,formatZoneOptions:()=>jX,fetchById:()=>o$,fetchAll:()=>qX,destroy:()=>nX,bulkStore:()=>rX,bulkSoftDelete:()=>sX,bulkDestroy:()=>oX});import{db as Z4}from"@stacksjs/database";async function nX(J){try{let $=await Z4.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function iX(J){try{let $=await Z4.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function oX(J){if(!J.length)return 0;try{let $=await Z4.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function sX(J){if(!J.length)return 0;try{let $=await Z4.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:dX}=globalThis.Bun;import{db as x1}from"@stacksjs/database";async function aX(J){try{let $=dX(),G={...v0(J),uuid:$};await x1.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await x1.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping zone");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function rX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...v0(X),uuid:dX()})),G=await x1.insertInto("shipping_zones").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as Y4}from"@stacksjs/database";import{formatDate as L4}from"@stacksjs/orm";async function eX(J,$){try{if(!J)throw Error("Shipping zone ID is required for update");let G=await Y4.updateTable("shipping_zones").set({...v0($),updated_at:L4(new Date)}).where("id","=",J).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 tX(J,$){try{let G=await Y4.updateTable("shipping_zones").set({status:$,updated_at:L4(new Date)}).where("id","=",J).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 $9(J,$){try{let G=await Y4.updateTable("shipping_zones").set({countries:$,updated_at:L4(new Date)}).where("id","=",J).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 J9(J,$,G){try{let X={updated_at:L4(new Date)};if($!==void 0)X.regions=$;if(G!==void 0)X.postal_codes=G;let Z=await Y4.updateTable("shipping_zones").set(X).where("id","=",J).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 IZ={digital:k$,drivers:I$,geocoding:v$,licenses:m$,methods:u$,rates:d$,routes:w$,tracking:X4,zones:K4},hZ=IZ;var A1={};B(A1,{updateStatus:()=>x9,updateRate:()=>z9,updateDefaultStatus:()=>B9,update:()=>M9,taxFor:()=>G9,store:()=>N9,fetchById:()=>K9,fetchAll:()=>W9,destroy:()=>Z9,bulkStore:()=>H9,bulkDestroy:()=>Y9,breakdownFor:()=>V1,activeTaxRates:()=>B1});import{db as gZ}from"@stacksjs/database";function DZ(J){let $=Number(J);return Number.isFinite($)?$/100:0}async function B1(J={}){let $=gZ.selectFrom("tax_rates").where("status","=","active").selectAll();if(J.country)$=$.where("country","=",J.country);let G=await $.execute();if(!J.codes?.length)return G;let X=new Set(J.codes);return G.filter((Z)=>X.has(String(Z.code??"")))}function V1(J,$,G={}){let X=Math.max(0,Math.round(J)),Z=[],Y=0,L=0;for(let K of $){let W=DZ(K.rate),F=Math.round(X*W),N=Boolean(G.exempt&&K.exemptible);if(N)L+=F;else Y+=F;Z.push({id:Number(K.id),code:String(K.code??""),name:String(K.name??""),rate:W,amount:N?0:F,exempted:N})}return{taxable:X,components:Z,tax:Y,exempted:L}}async function G9(J,$={}){return V1(J,await B1($),$)}import{db as X9}from"@stacksjs/database";async function Z9(J){try{let $=await X9.deleteFrom("tax_rates").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function Y9(J){if(!J.length)return 0;try{let $=await X9.deleteFrom("tax_rates").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as L9}from"@stacksjs/database";async function K9(J){return await L9.selectFrom("tax_rates").where("id","=",J).selectAll().executeTakeFirst()}async function W9(){return await L9.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:F9}=globalThis.Bun;import{db as Q9}from"@stacksjs/database";async function N9(J){try{return await Q9.transaction(async($)=>{let G={...J,uuid:F9()};if(G.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let X=await $.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function H9(J){if(!J.length)return 0;try{return await Q9.transaction(async($)=>{let G=0;for(let X of J){let Z={...X,uuid:F9()};if(Z.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(Z).executeTakeFirst())G++}return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as W4}from"@stacksjs/database";import{formatDate as F4}from"@stacksjs/orm";async function M9(J,$){try{if(!J)throw Error("Tax rate ID is required for update");return await W4.transaction(async(G)=>{let X=await G.selectFrom("tax_rates").select("is_default").where("id","=",J).executeTakeFirst();if(!X)return;let Z=$.is_default??Boolean(X.is_default),Y=F4(new Date);if(Z)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Y}).where("id","!=",J).execute();let L=await G.updateTable("tax_rates").set({...$,updated_at:Y}).where("id","=",J).returningAll().executeTakeFirst();if(!L)return;return L})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function x9(J,$){try{let G=await W4.updateTable("tax_rates").set({status:$,updated_at:F4(new Date)}).where("id","=",J).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 z9(J,$){try{let G=await W4.updateTable("tax_rates").set({rate:$,updated_at:F4(new Date)}).where("id","=",J).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 B9(J,$){try{return await W4.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",J).executeTakeFirst())return!1;let Z=F4(new Date);if($)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Z}).where("id","!=",J).execute();return await G.updateTable("tax_rates").set({is_default:$,updated_at:Z}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var S1={};B(S1,{restaurant:()=>S0,products:()=>N4,default:()=>iZ});var N4={};B(N4,{updateStatus:()=>D9,updatePartySize:()=>v9,update:()=>Q4,store:()=>h9,fetchWaiting:()=>q9,fetchPurchasedBetweenDates:()=>T9,fetchNotifiedBetweenDates:()=>S9,fetchCountByStatus:()=>j9,fetchCountBySource:()=>_9,fetchCountByQuantity:()=>U9,fetchCountByDateGrouped:()=>k9,fetchCountByDate:()=>R9,fetchCountByAllQuantities:()=>P9,fetchCountBetweenDates:()=>f9,fetchConversionRates:()=>w9,fetchCancelledBetweenDates:()=>E9,fetchById:()=>s0,fetchAll:()=>O9,destroy:()=>V9,bulkStore:()=>g9,bulkDestroy:()=>A9});import{db as O1}from"@stacksjs/database";async function V9(J){try{let $=await O1.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await O1.deleteFrom("waitlist_products").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function A9(J){if(!J.length)return 0;try{let $=await O1.deleteFrom("waitlist_products").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as T}from"@stacksjs/orm";async function s0(J){return await A.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function O9(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function _9(J,$){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(J&&$){let Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{source:Y,count:L})=>{return Z[Y]=L,Z},{})}async function R9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=T($),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 U9(J){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",J).executeTakeFirst())?.count??0}async function P9(J,$){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(J&&$){let Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{quantity:Y,count:L})=>{return Z[Y]=L,Z},{})}async function S9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",X).whereNotNull("notified_at").execute()}async function T9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",X).whereNotNull("purchased_at").execute()}async function E9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",X).whereNotNull("cancelled_at").execute()}async function q9(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function j9(J,$,G){let X=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",J);if($&&G){let Y=T($),L=T(G);X=X.where("created_at",">=",Y).where("created_at","<=",L)}return(await X.executeTakeFirst())?.count??0}async function w9(J,$){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(J&&$){let W=T(J),F=T($);G=G.where("created_at",">=",W).where("created_at","<=",F)}let X=await G.execute(),Z=X.reduce((W,{count:F})=>W+F,0),Y=X.find((W)=>W.status==="purchased")?.count??0,L=Z>0?Y/Z*100:0,K=X.reduce((W,{status:F,count:N})=>{return W[F]={count:N,percentage:Z>0?N/Z*100:0},W},{});return{totalConversionRate:L,statusBreakdown:K}}async function f9(J,$){let G=T(J),X=T($);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 k9(J,$){let G=A.selectFrom("waitlist_products").select(["created_at"]);if(J&&$){let Y=T(J),L=T($);G=G.where("created_at",">=",Y).where("created_at","<=",L)}let Z=(await G.execute()).reduce((Y,{created_at:L})=>{let K=(L||"").split("T")[0]||"unknown";return Y[K]=(Y[K]||0)+1,Y},{});return Object.entries(Z).map(([Y,L])=>({date:Y,count:L})).sort((Y,L)=>Y.date.localeCompare(L.date))}var{randomUUIDv7:I9}=globalThis.Bun;import{db as _1}from"@stacksjs/database";import{formatDate as C9}from"@stacksjs/orm";var vZ={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function yZ(J){return typeof J==="number"||J instanceof Date?C9(J):J}function d0(J,$={}){let G=Object.fromEntries(Object.entries(J).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]=yZ(G[Z]);let X=vZ[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=C9(new Date);return G}async function h9(J){try{let $=I9(),G={...d0(J),uuid:$,status:J.status||"waiting"};await _1.insertInto("waitlist_products").values(G).executeTakeFirst();let X=await _1.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create waitlist product");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function g9(J){if(!J.length)return 0;try{let $=J.map((X)=>({...d0(X),status:X.status||"waiting",uuid:I9()})),G=await _1.insertInto("waitlist_products").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as bZ}from"@stacksjs/database";import{formatDate as mZ}from"@stacksjs/orm";async function Q4(J,$){try{if(!J)throw Error("Waitlist product ID is required for update");let G=await s0(J);if(!G)return;await bZ.updateTable("waitlist_products").set({...d0($,G),updated_at:mZ(new Date)}).where("id","=",J).execute();let X=await s0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update waitlist product: ${G.message}`);throw G}}async function D9(J,$){return await Q4(J,{status:$})}async function v9(J,$){return await Q4(J,{quantity:$})}var S0={};B(S0,{updateWaitTimes:()=>F3,updateStatus:()=>K3,updateQueuePosition:()=>Q3,updatePartySize:()=>W3,update:()=>P0,store:()=>Y3,fetchWaitingWithQuotedTimes:()=>a9,fetchWaitingWithPartySizes:()=>r9,fetchWaiting:()=>o9,fetchTimeSeriesStats:()=>X3,fetchTablesTurnedToday:()=>e9,fetchSeatingRate:()=>t9,fetchSeatedStats:()=>G3,fetchSeatedBetweenDates:()=>i9,fetchNoShowStats:()=>$3,fetchCurrentWaitTimes:()=>J3,fetchCountByTablePreference:()=>p9,fetchCountByPartySize:()=>c9,fetchCountByDate:()=>l9,fetchCountByAllPartySizes:()=>u9,fetchConversionRates:()=>s9,fetchById:()=>a0,fetchBetweenDates:()=>n9,fetchAverageWaitTimes:()=>d9,fetchAll:()=>m9,destroy:()=>y9,bulkStore:()=>L3,bulkDestroy:()=>b9});import{db as R1}from"@stacksjs/database";async function y9(J){try{let $=await R1.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await R1.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function b9(J){if(!J.length)return 0;try{let $=await R1.deleteFrom("waitlist_restaurants").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as z}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function a0(J){return await z.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function m9(){return await z.selectFrom("waitlist_restaurants").selectAll().execute()}async function p9(){return(await z.selectFrom("waitlist_restaurants").select(["table_preference",z.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:G,count:X})=>{return $[G]=X,$},{})}async function l9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),Z=g(G);return(await z.selectFrom("waitlist_restaurants").select(z.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function c9(J){return(await z.selectFrom("waitlist_restaurants").select(z.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function u9(){return(await z.selectFrom("waitlist_restaurants").select(["party_size",z.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:G,count:X})=>{return $[G]=X,$},{})}async function n9(J,$){let G=g(J),X=g($);return await z.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",X).execute()}async function i9(J,$){let G=g(J),X=g($);return await z.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",X).where("status","=","seated").execute()}async function o9(){return await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function s9(){let J=await z.selectFrom("waitlist_restaurants").select(["status",z.fn.count("id").as("count")]).groupBy("status").execute(),$=J.reduce((Y,{count:L})=>Y+L,0),G=J.find((Y)=>Y.status==="seated")?.count??0,X=$>0?Number(G)/$*100:0,Z=J.reduce((Y,{status:L,count:K})=>{return Y[L]={count:K,percentage:$>0?K/$*100:0},Y},{});return{totalConversionRate:X,statusBreakdown:Z}}async function d9(){let J=await z.selectFrom("waitlist_restaurants").select([z.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),z.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:J?.avg_quoted_wait_time??0,averageActualWaitTime:J?.avg_actual_wait_time??0}}async function a9(){let J=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((X,Z)=>X+(Z.quoted_wait_time??0),0),G=J.length>0?$/J.length:0;return{entries:J,totalQuotedWaitTime:$,averageQuotedWaitTime:G}}async function r9(){let J=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((Z,Y)=>Z+Y.party_size,0),G=J.length>0?$/J.length:0,X=J.reduce((Z,Y)=>{return Z[Y.party_size]=(Z[Y.party_size]||0)+1,Z},{});return{entries:J,totalPartySize:$,averagePartySize:G,partySizeBreakdown:X}}async function e9(){let J=new Date,$=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),Z=g(G),Y=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",X).where("check_in_time","<=",Z).execute(),L=Y.length,K=Y.reduce((H,M)=>H+M.party_size,0),W=L>0?K/L:0,F=Y.reduce((H,M)=>{return H[M.table_preference]=(H[M.table_preference]||0)+1,H},{}),N=Y.reduce((H,M)=>{return H[M.party_size]=(H[M.party_size]||0)+1,H},{});return{totalTablesTurned:L,averagePartySize:W,totalCustomersSeated:K,breakdownByTablePreference:F,breakdownByPartySize:N}}async function t9(J,$){let G=g(J),X=g($),Z=await z.selectFrom("waitlist_restaurants").select(["status",z.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),L=Z.find((F)=>F.status==="seated")?.count??0,K=Y>0?Number(L)/Y*100:0,W=Z.reduce((F,{status:N,count:H})=>{return F[N]={count:H,percentage:Y>0?H/Y*100:0},F},{});return{totalEntries:Y,seatedEntries:L,seatingRate:K,statusBreakdown:W}}async function $3(J,$){let G=g(J),X=g($),Z=z.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",X),Y=await z.selectFrom("waitlist_restaurants").select(z.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",X).executeTakeFirst(),L=await Z.execute(),K=L.length,W=Y?.count&&Y.count>0?K/Y.count*100:0,F=L.reduce((_,U)=>_+(U.quoted_wait_time??0),0),N=K>0?F/K:0,H=L.reduce((_,U)=>_+U.party_size,0),M=K>0?H/K:0,O=L.reduce((_,U)=>{return _[U.table_preference]=(_[U.table_preference]||0)+1,_},{}),R=L.reduce((_,U)=>{return _[U.party_size]=(_[U.party_size]||0)+1,_},{});return{totalNoShows:K,noShowRate:W,averageQuotedWaitTime:N,averagePartySize:M,breakdownByTablePreference:O,breakdownByPartySize:R}}async function J3(){let J=await z.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=J.reduce((Z,Y)=>Z+(Y.actual_wait_time||0),0),X=J.length;return{averageQuoted:X>0?$/X:0,averageActual:X>0?G/X:0}}async function G3(){let J=Date.now()-86400000,$=await z.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),G=Array.from({length:24},(X,Z)=>({hour:Z,count:$.filter((Y)=>{return Y.seated_at===Z}).length}));return{total:$.length,byHour:G}}async function X3(){return(await z.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,G)=>{let X=G.created_at;if(!$[X])$[X]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[X].total++,$[X][G.status]++,$},{})}var{randomUUIDv7:Z3}=globalThis.Bun;import{db as P1}from"@stacksjs/database";import{formatDate as U1}from"@stacksjs/orm";var pZ={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function lZ(J){if(typeof J==="number")return U1(J<=2147483647?J*1000:J);if(J instanceof Date)return U1(J);return J}function r0(J,$={}){let G=Object.fromEntries(Object.entries(J).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]=lZ(G[Z]);let X=pZ[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=U1(new Date);return G}async function Y3(J){try{let $=Z3(),G={...r0(J),status:J.status||"waiting",uuid:$};await P1.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let X=await P1.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create restaurant waitlist entry");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function L3(J){if(!J.length)return 0;try{let $=J.map((X)=>({...r0(X),status:X.status||"waiting",uuid:Z3()})),G=await P1.insertInto("waitlist_restaurants").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as cZ}from"@stacksjs/database";import{formatDate as uZ}from"@stacksjs/orm";async function P0(J,$){try{if(!J)throw Error("Restaurant waitlist entry ID is required for update");let G=await a0(J);if(!G)return;await cZ.updateTable("waitlist_restaurants").set({...r0($,G),updated_at:uZ(new Date)}).where("id","=",J).execute();let X=await a0(J);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 K3(J,$){return await P0(J,{status:$})}async function W3(J,$){return await P0(J,{party_size:$})}async function F3(J,$,G){return await P0(J,{quoted_wait_time:$,...G===void 0?{}:{actual_wait_time:G}})}async function Q3(J,$){return await P0(J,{queue_position:$})}var nZ={products:N4,restaurant:S0},iZ=nZ;var oZ={coupons:H4,customers:M4,devices:A4,errors:R4,giftCards:P4,orders:C4,payments:I4,products:m4,receipts:i4,restaurant:S0,shippings:z1,tax:A1,waitlists:S1},k8=oZ;export{S1 as waitlists,A1 as tax,z1 as shippings,S0 as restaurant,i4 as receipts,m4 as products,I4 as payments,C4 as orders,P4 as giftCards,R4 as errors,A4 as devices,k8 as default,M4 as customers,H4 as coupons,oZ as commerce};
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(!eZ.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 h1={};B(h1,{variants:()=>l$,units:()=>m$,reviews:()=>y$,manufacturers:()=>v$,items:()=>D$,default:()=>NY,categories:()=>g$});var g$={};B(g$,{updateParent:()=>F2,updateDisplayOrder:()=>W2,updateActiveStatus:()=>Q2,update:()=>K2,store:()=>q1,removeChildCategories:()=>J2,remove:()=>e6,findOrCreateByName:()=>Y2,fetchStats:()=>a6,fetchRootCategories:()=>s6,fetchChildCategories:()=>o6,fetchCategoryTree:()=>t6,fetchByName:()=>n6,fetchById:()=>w,fetchByDisplayOrder:()=>d6,fetchAll:()=>j1,fetchActive:()=>i6,deactivateChildCategories:()=>X2,deactivate:()=>G2,compareCategoryGrowth:()=>r6,bulkRemove:()=>$2});import{db as T0}from"@stacksjs/database";import{db as P}from"@stacksjs/database";import{formatDate as d0}from"@stacksjs/orm";async function j1(){return await P.selectFrom("categories").selectAll().execute()}async function w($){return await P.selectFrom("categories").where("id","=",$).selectAll().executeTakeFirst()}async function n6($){return await P.selectFrom("categories").where("name","=",$).selectAll().executeTakeFirst()}async function i6(){return await P.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function s6(){return await P.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function o6($){return await P.selectFrom("categories").where("parent_category_id","=",$).where("is_active","=",!0).selectAll().execute()}async function d6($=!0){let J=P.selectFrom("categories").where("is_active","=",!0).selectAll();if($)return await J.orderBy("display_order","asc").execute();else return await J.orderBy("display_order","desc").execute()}async function a6(){let $=await P.selectFrom("categories").select(P.fn.count("id").as("count")).executeTakeFirst(),J=await P.selectFrom("categories").where("is_active","=",!0).select(P.fn.count("id").as("count")).executeTakeFirst(),G=await P.selectFrom("categories").whereNull("parent_category_id").select(P.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("categories").whereNotNull("image_url").select(P.fn.count("id").as("count")).executeTakeFirst(),Z=new Date;Z.setDate(Z.getDate()-30);let Y=d0(Z),K=await P.selectFrom("categories").where("created_at",">=",Y).selectAll().limit(5).execute(),W=await P.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",P.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number($?.count||0),active:Number(J?.count||0),root_categories:Number(G?.count||0),child_categories:Number($?.count||0)-Number(G?.count||0),with_images:Number(X?.count||0),recently_added:K,top_parent_categories:W.map((Q)=>({id:String(Q.parent_category_id||""),name:String(Q.parent_name||""),child_count:Number(Q.child_count)}))}}async function r6($=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 P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",G).executeTakeFirst(),N=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",Q).where("created_at","<=",K).executeTakeFirst(),H=Number(F?.count||0),z=Number(N?.count||0),x=H-z,R=z!==0?x/z*100:H>0?100:0;return{current_period:H,previous_period:z,difference:x,percentage_change:R,days_range:$}}async function t6(){let $=await j1(),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 e6($){let J=await T0.deleteFrom("categories").where("id","=",$).executeTakeFirst();return L(J)>0}async function $2($){if(!$.length)return 0;let J=await T0.deleteFrom("categories").where("id","in",$).executeTakeFirst();return L(J)}async function J2($){let J=await T0.deleteFrom("categories").where("parent_category_id","=",$).executeTakeFirst();return L(J)}async function G2($){if(!await w($))throw Error(`Category with ID ${$} not found`);return!!await T0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",$).executeTakeFirst()}async function X2($){let J=await T0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",$).execute();return Number(J.length)||0}var{randomUUIDv7:$Y}=globalThis.Bun;import{db as Z2}from"@stacksjs/database";import{HttpError as h$}from"@stacksjs/error-handling";import{isUniqueViolation as JY}from"@stacksjs/orm";import{slug as GY}from"@stacksjs/strings";async function q1($){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:$Y(),is_active:$.is_active??!0,parent_category_id:$.parent_category_id||null},X=await Z2.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(JY(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 Y2($){if(!$.name)throw Error("Name is required");let J=await Z2.selectFrom("categories").selectAll().where("name","=",$.name).executeTakeFirst();if(J)return J;let G={name:$.name,slug:GY($.name),is_active:$.is_active??!0,display_order:0};return await q1(G)}import{db as a0}from"@stacksjs/database";import{HttpError as j0}from"@stacksjs/error-handling";import{formatDate as I$,isUniqueViolation as XY}from"@stacksjs/orm";async function K2($,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 L2($,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(XY(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 W2($,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 Q2($,J){if(!await w($))throw Error(`Category with ID ${$} not found`);try{return await a0.updateTable("categories").set({is_active:J,updated_at:I$(new Date)}).where("id","=",$).execute(),await w($)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function F2($,J){if(!await w($))throw Error(`Category with ID ${$} not found`);if(J){let X=Number(J);if(X===$)throw Error("A category cannot be its own parent");if(!await w(X))throw Error(`Parent category with ID ${J} not found`);if(await L2($,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 L2($,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:()=>U2,updateAvailability:()=>R2,update:()=>A2,store:()=>_2,fetchTopProducts:()=>x2,fetchById:()=>t,fetchAll:()=>V2,destroy:()=>H2,bulkStore:()=>O2,bulkDestroy:()=>z2});import{db as N2}from"@stacksjs/database";async function H2($){try{let J=await N2.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 z2($){if(!$.length)return 0;try{let J=await N2.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 ZY}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 V2(){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 x2($=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"),ZY`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:B2}=globalThis.Bun;import{db as M2}from"@stacksjs/database";async function _2($){try{let J={...$,uuid:B2()},G=await M2.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 O2($){if(!$.length)return 0;let J=0;try{return await M2.transaction().execute(async(G)=>{for(let X of $){let Z={...X,uuid:B2()};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 k1}from"@stacksjs/database";import{formatDate as w1}from"@stacksjs/orm";async function A2($,J){try{if(!$)throw Error("Product item ID is required for update");let G=await k1.updateTable("products").set({...J,updated_at:w1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item: ${G.message}`);throw G}}async function R2($,J){if(!await t($))throw Error(`Product item with ID ${$} not found`);try{return await k1.updateTable("products").set({is_available:J,updated_at:w1(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 U2($,J){let G=await t($);if(!G)throw Error(`Product item with ID ${$} not found`);let X={updated_at:w1(new Date)};if(J!==void 0)X.inventory_count=J;if(Object.keys(X).length===1)return G;try{return await k1.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:()=>b2,updateByUuid:()=>p2,update:()=>y2,store:()=>g2,fetchWithProductCount:()=>f2,fetchFeatured:()=>k2,fetchByUuid:()=>q2,fetchById:()=>j2,fetchByCountry:()=>w2,fetchAll:()=>T2,destroy:()=>P2,bulkStore:()=>D2,bulkDestroy:()=>E2});import{db as S2}from"@stacksjs/database";async function P2($){try{let J=await S2.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 S2.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 T2(){return e.selectFrom("manufacturers").selectAll().execute()}async function j2($){return await e.selectFrom("manufacturers").where("id","=",$).selectAll().executeTakeFirst()}async function q2($){return await e.selectFrom("manufacturers").where("uuid","=",$).selectAll().executeTakeFirst()}async function k2($=10){return await e.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit($).execute()}async function w2($,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 f2($={}){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:h2}=globalThis.Bun;import{db as I2}from"@stacksjs/database";import{HttpError as C2}from"@stacksjs/error-handling";import{isUniqueViolation as YY}from"@stacksjs/orm";async function g2($){try{let J={...$,uuid:h2(),featured:$.featured??!1},G=await I2.insertInto("manufacturers").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch(J){if(J instanceof C2)throw J;if(YY(J))throw new C2(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to create manufacturer: ${J.message}`);throw J}}async function D2($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={...G,uuid:h2(),featured:G.featured??!1};await I2.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 f1}from"@stacksjs/database";import{HttpError as v2}from"@stacksjs/error-handling";import{formatDate as C1,isUniqueViolation as KY}from"@stacksjs/orm";async function y2($,J){try{if(!$)throw Error("Manufacturer ID is required for update");let G=await f1.updateTable("manufacturers").set({...J,updated_at:C1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof v2)throw G;if(KY(G))throw new v2(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function b2($,J){try{let G=await f1.updateTable("manufacturers").set({featured:J,updated_at:C1(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 p2($,J){try{let G=await f1.updateTable("manufacturers").set({...J,updated_at:C1(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:()=>YG,update:()=>ZG,store:()=>JG,fetchStatsByProductIds:()=>$G,fetchStats:()=>e2,fetchMostHelpfulByProductId:()=>d2,fetchByUserId:()=>s2,fetchByProductId:()=>i2,fetchById:()=>u2,fetchApprovedByProductId:()=>o2,fetchAll:()=>n2,destroy:()=>l2,bulkDestroy:()=>c2});import{db as m2}from"@stacksjs/database";async function l2($){try{let J=await m2.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 c2($){if(!$.length)return 0;try{let J=await m2.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 u2($){return await q0.selectFrom("reviews").where("id","=",$).selectAll().executeTakeFirst()}async function n2(){return await q0.selectFrom("reviews").selectAll().execute()}async function i2($){return await q0.selectFrom("reviews").where("product_id","=",$).selectAll().execute()}async function s2($){return await q0.selectFrom("reviews").where("customer_id","=",$).selectAll().execute()}async function o2($){return await q0.selectFrom("reviews").where("product_id","=",$).where("is_approved","=",!0).selectAll().execute()}async function d2($){return await q0.selectFrom("reviews").where("product_id","=",$).orderBy("helpful_votes","desc").selectAll().execute()}import{db as a2}from"@stacksjs/database";function r2(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function t2($){let J=r2();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 e2($){let J=await a2.selectFrom("reviews").select(["rating"]).where("product_id","=",$).where("is_approved","=",!0).execute();return t2(J)}async function $G($){let J=new Map;for(let Z of $)J.set(Z,r2());if($.length===0)return J;let G=await a2.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,t2(Y));return J}var{randomUUIDv7:WY}=globalThis.Bun;import{db as QY}from"@stacksjs/database";function FY($){let J=$.rating!==void 0&&$.rating!==null,G=typeof $.content==="string"&&$.content.trim().length>0,X=typeof $.title==="string"&&$.title.trim().length>0;return!J&&!G&&!X}async function JG($){try{if(FY($))throw Error("A review needs a rating or something written: both were empty");let J={...$,uuid:WY(),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 QY.insertInto("reviews").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create review");return G}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${J.message}`)}throw J}}import{db as GG}from"@stacksjs/database";import{formatDate as XG}from"@stacksjs/orm";async function ZG($,J){try{if(!$)throw Error("Review ID is required for update");let G=await GG.updateTable("reviews").set({...J,updated_at:XG(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 YG($,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 GG.unsafe(`UPDATE "reviews" SET "${X}" = ${Z}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[XG(new Date),$]).execute(),K=Array.isArray(Y)?Y[0]:Y;if(!K)throw Error("Failed to update review votes");return K}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var m$={};B(m$,{updateDefaultStatus:()=>OG,update:()=>MG,store:()=>zG,getDefaultUnit:()=>BG,formatUnitOptions:()=>xG,fetchById:()=>LG,fetchAll:()=>NG,destroy:()=>WG,bulkUpdate:()=>_G,bulkStore:()=>VG,bulkDestroy:()=>QG});import{db as KG}from"@stacksjs/database";async function WG($){try{let J=await KG.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 QG($){if(!$.length)return 0;try{let J=await KG.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 FG}from"@stacksjs/database";async function LG($){return await FG.selectFrom("product_units").where("id","=",$).selectAll().executeTakeFirst()}async function NG(){return await FG.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:HG}=globalThis.Bun;import{db as r0}from"@stacksjs/database";async function zG($){try{return await r0.transaction(async(J)=>{let G={...$,uuid:HG()},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 VG($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={...G,uuid:HG()},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 xG($){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 BG($){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 MG($,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 _G($){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 OG($,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:()=>IG,store:()=>qG,generateVariantCombinations:()=>fG,formatVariantOptions:()=>wG,fetchById:()=>PG,fetchAll:()=>EG,destroy:()=>RG,bulkUpdate:()=>gG,bulkStore:()=>kG,bulkDestroy:()=>UG});import{db as AG}from"@stacksjs/database";async function RG($){try{let J=await AG.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 UG($){if(!$.length)return 0;try{let J=await AG.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 SG}from"@stacksjs/database";async function PG($){return await SG.selectFrom("product_variants").where("id","=",$).selectAll().executeTakeFirst()}async function EG(){return await SG.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:TG}=globalThis.Bun;import{db as jG}from"@stacksjs/database";async function qG($){try{let J={...$,uuid:TG()},G=await jG.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 kG($){if(!$.length)return 0;let J=0;try{for(let G of $){let X={...G,uuid:TG()};await jG.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 wG($){if(!$||!$.length)return JSON.stringify([]);let J=$.map((G)=>G.trim()).filter(Boolean);return JSON.stringify(J)}function fG($){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 CG}from"@stacksjs/database";import{formatDate as hG}from"@stacksjs/orm";async function IG($,J){try{let G=await CG.updateTable("product_variants").set({...J,updated_at:hG(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 gG($){if(!$.length)return 0;let J=0;try{for(let G of $){if(!G.id)continue;let X=await CG.updateTable("product_variants").set({...G,updated_at:hG(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 LY={categories:g$,items:D$,manufacturers:v$,reviews:y$,units:m$,variants:l$},NY=LY;var b1={};B(b1,{updateStatus:()=>dG,updatePrintJob:()=>aG,update:()=>oG,store:()=>iG,fetchSuccessRate:()=>mG,fetchPrintsPerHour:()=>uG,fetchPrintTimeStats:()=>cG,fetchPrintJobStats:()=>pG,fetchPageStats:()=>lG,fetchById:()=>k0,fetchAll:()=>bG,destroy:()=>vG,bulkStore:()=>sG,bulkDestroy:()=>yG});import{db as DG}from"@stacksjs/database";async function vG($){try{let J=await DG.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 yG($){if(!$.length)return 0;try{let J=await DG.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 I1}from"@stacksjs/database";import{formatDate as HY}from"@stacksjs/orm";function l($){return HY($)}function zY($){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 I1.selectFrom("receipts").where("id","=",$).selectAll().executeTakeFirst()}async function bG(){return await I1.selectFrom("receipts").selectAll().execute()}async function pG($,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 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"}}},(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 lG($,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 cG($,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 uG($,J){let G=typeof $==="number"?$:$.getTime(),X=typeof J==="number"?J:J.getTime(),Z=l($),Y=l(J),K=await I1.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=zY(H.timestamp);if(!z)return;N[z.getHours()].count++}),{totalPrints:W,totalHours:Q,printsPerHour:F,hourlyBreakdown:N}}var{randomUUIDv7:nG}=globalThis.Bun;import{db as D1}from"@stacksjs/database";import{formatDate as g1}from"@stacksjs/orm";function t0($){try{if(typeof $==="number")return g1($<=2147483647?$*1000:$);if(typeof $==="string"&&/^\d{10}$/.test($))return g1(Number($)*1000);return g1($)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function iG($){try{let J=nG(),G={...$,timestamp:t0($.timestamp),uuid:J};await D1.insertInto("receipts").values(G).executeTakeFirst();let X=await D1.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 sG($){if(!$.length)return 0;try{let J=$.map((X)=>({...X,timestamp:t0(X.timestamp),uuid:nG()})),G=await D1.insertInto("receipts").values(J).executeTakeFirst();return Number(G.numInsertedOrUpdatedRows??G.numAffectedRows??G.affectedRows??G.changes??0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${J.message}`);throw J}}import{db as v1}from"@stacksjs/database";import{formatDate as y1}from"@stacksjs/orm";async function oG($,J){try{if(!$)throw Error("Receipt ID is required for update");let G={...J,...J.timestamp===void 0?{}:{timestamp:t0(J.timestamp)},updated_at:y1(new Date)};await v1.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 dG($,J){try{await v1.updateTable("receipts").set({status:J,updated_at:y1(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 aG($,J,G,X){try{let Z={updated_at:y1(new Date)};if(J!==void 0)Z.size=J;if(G!==void 0)Z.pages=G;if(X!==void 0)Z.duration=X;await v1.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 Q7={};B(Q7,{zones:()=>T4,tracking:()=>U4,routes:()=>o$,rates:()=>V4,methods:()=>F4,licenses:()=>Y4,geocoding:()=>G4,drivers:()=>t$,digital:()=>a$,default:()=>vY});var o$={};B(o$,{validateDeliveryRouteWrite:()=>w0,updateStops:()=>KX,updateMetrics:()=>WX,updateLastActive:()=>ZX,update:()=>YX,store:()=>XX,fetchById:()=>u$,fetchByDriver:()=>GX,fetchAll:()=>$X,fetchActive:()=>JX,destroy:()=>tG,bulkDestroy:()=>eG,DeliveryRouteInputError:()=>h});import{db as rG}from"@stacksjs/database";async function tG($){try{let J=await rG.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 eG($){if(!$.length)return 0;try{let J=await rG.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 c$}from"@stacksjs/database";async function u$($){return await c$.selectFrom("delivery_routes").where("id","=",$).selectAll().executeTakeFirst()}async function $X(){return await c$.selectFrom("delivery_routes").selectAll().execute()}async function JX(){return await c$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function GX($){return await c$.selectFrom("delivery_routes").where("driver","=",$).selectAll().execute()}var{randomUUIDv7:BY}=globalThis.Bun;import{db as p1}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 n$($){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 VY}from"@stacksjs/database";class h extends TypeError{constructor($){super($);this.name="DeliveryRouteInputError"}}function i$($,J,G){return Number($[G]??J?.[G])}function xY($,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=i$($,J,"driver_id"),X=i$($,J,"stops"),Z=i$($,J,"delivery_time"),Y=i$($,J,"total_distance"),K=xY($,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 VY.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 XX($){try{let J=BY(),G=n$($),Z={...await w0(G),uuid:J};await p1.insertInto("delivery_routes").values(Z).executeTakeFirst();let Y=await p1.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 ZX($){try{await p1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",$).execute();let J=await u$($);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 s$}from"@stacksjs/database";import{formatDate as m1}from"@stacksjs/orm";async function YX($,J){try{if(!$)throw Error("Delivery route ID is required for update");let G=await s$.selectFrom("delivery_routes").where("id","=",$).selectAll().executeTakeFirst();if(!G)return;let X=n$(J),Z=await w0(X,G),Y=await s$.updateTable("delivery_routes").set({...Z,updated_at:m1(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 KX($,J){try{let G=await s$.updateTable("delivery_routes").set({stops:J,updated_at:m1(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 WX($,J,G){try{let X={updated_at:m1(new Date)};if(J!==void 0)X.delivery_time=J;if(G!==void 0)X.total_distance=G;let Z=await s$.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 a$={};B(a$,{updateStatus:()=>OX,updateDeliverySettings:()=>AX,update:()=>_X,store:()=>BX,softDelete:()=>FX,fetchById:()=>zX,fetchAll:()=>VX,destroy:()=>QX,bulkStore:()=>MX,bulkSoftDelete:()=>NX,bulkDestroy:()=>LX});import{db as d$}from"@stacksjs/database";async function QX($){try{let J=await d$.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 FX($){try{let J=await d$.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 LX($){if(!$.length)return 0;try{let J=await d$.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 NX($){if(!$.length)return 0;try{let J=await d$.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 HX}from"@stacksjs/database";async function zX($){return await HX.selectFrom("digital_deliveries").where("id","=",$).selectAll().executeTakeFirst()}async function VX(){return await HX.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:xX}=globalThis.Bun;import{db as l1}from"@stacksjs/database";async function BX($){try{let J=xX(),G={...J$($),uuid:J};await l1.insertInto("digital_deliveries").values(G).executeTakeFirst();let X=await l1.selectFrom("digital_deliveries").where("uuid","=",J).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created digital delivery");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital delivery: ${J.message}`);throw J}}async function MX($){if(!$.length)return 0;try{let J=$.map((X)=>({...J$(X),uuid:xX()})),G=await l1.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 c1}from"@stacksjs/database";import{formatDate as u1}from"@stacksjs/orm";async function _X($,J){try{if(!$)throw Error("Digital delivery ID is required for update");let G=await c1.updateTable("digital_deliveries").set({...J$(J),updated_at:u1(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 OX($,J){try{let G=await c1.updateTable("digital_deliveries").set({status:J,updated_at:u1(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 AX($,J,G,X,Z){try{let Y={updated_at:u1(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 c1.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 t$={};B(t$,{updateStatus:()=>wX,updateContact:()=>fX,update:()=>kX,store:()=>jX,fetchById:()=>r$,fetchAll:()=>UX,destroy:()=>PX,bulkStore:()=>qX,bulkDestroy:()=>EX});import{db as SX}from"@stacksjs/database";import{db as RX}from"@stacksjs/database";async function r$($){return await RX.selectFrom("drivers").where("id","=",$).selectAll().executeTakeFirst()}async function UX(){return await RX.selectFrom("drivers").selectAll().execute()}async function PX($){try{let J=await SX.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 SX.transaction().execute(async(G)=>{for(let X of $)if(await r$(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:TX}=globalThis.Bun;import{db as n1}from"@stacksjs/database";async function jX($){try{let J=TX(),G={...X$($),uuid:J};await n1.insertInto("drivers").values(G).executeTakeFirst();let X=await n1.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 qX($){if(!$.length)return 0;try{let J=$.map((X)=>({...X$(X),uuid:TX()})),G=await n1.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 i1}from"@stacksjs/database";import{formatDate as s1}from"@stacksjs/orm";async function kX($,J){try{if(!$)throw Error("Driver ID is required for update");let G=await i1.updateTable("drivers").set({...X$(J),updated_at:s1(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 wX($,J){try{let G=await i1.updateTable("drivers").set({status:J,updated_at:s1(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 fX($,J){try{let G={updated_at:s1(new Date)};if(J!==void 0)G.phone=J;let X=await i1.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 G4={};B(G4,{setGeocodingDriver:()=>AY,nominatimDriver:()=>J4,geocodingDriver:()=>vX,geocode:()=>RY,formatQuery:()=>f0,checkCoverage:()=>UY,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 e$($,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 $4($,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 CX($,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 MY="https://nominatim.openstreetmap.org/search",hX=1000,IX=0,gX=Promise.resolve();async function _Y($){let J=gX.then(async()=>{let G=Date.now()-IX;if(G<hX)await Bun.sleep(hX-G);return IX=Date.now(),$()});return gX=J.then(()=>{return},()=>{return}),J}function OY($){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 J4($={}){let J=$.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,G=$.endpoint??MY;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 _Y(()=>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=OY(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 DX=null;function AY($){DX=$}function vX(){return DX??J4()}async function RY($,J={}){let G=J.driver??vX(),X=J.minimumPrecision??"street",Z=`geocode:${G.name}:${f0($).toLowerCase()}`,Y=await SY(Z);if(Y!==void 0)return Y;let K=await G.geocode($),W=K&&Y$[K.precision]>=Y$[X]?K:null;return await PY(Z,W,W?J.cacheSeconds??2592000:600),W}function UY($,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 SY($){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 PY($,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 Y4={};B(Y4,{validateLicenseKeyWrite:()=>M0,updateStatus:()=>rX,updateExpiration:()=>tX,update:()=>aX,store:()=>oX,softDelete:()=>bX,fetchById:()=>cX,fetchAll:()=>uX,destroy:()=>yX,bulkStore:()=>dX,bulkSoftDelete:()=>mX,bulkDestroy:()=>pX,LicenseKeyInputError:()=>T});import{db as X4}from"@stacksjs/database";async function yX($){try{let J=await X4.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 bX($){try{let J=await X4.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 pX($){if(!$.length)return 0;try{let J=await X4.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 mX($){if(!$.length)return 0;try{let J=await X4.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 lX}from"@stacksjs/database";async function cX($){return await lX.selectFrom("license_keys").where("id","=",$).selectAll().executeTakeFirst()}async function uX(){return await lX.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:sX}=globalThis.Bun;import{db as a1}from"@stacksjs/database";import{db as o1}from"@stacksjs/database";var nX=["Standard License","Premium License","Enterprise License"],iX=["active","inactive","unassigned"];class T extends TypeError{constructor($){super($);this.name="LicenseKeyInputError"}}function K$($,J,G){return $[G]!==void 0?$[G]:J?.[G]}function d1($,J,G,X){let Z=K$($,J,G);if(Z===void 0||Z===null||Z==="")return null;let Y=Number(Z);if(!Number.isSafeInteger(Y)||Y<1)throw new T(`${X} must be a positive integer or null.`);return Y}function EY($){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=EY(K$($,J,"expiry_date")),K=d1($,J,"customer_id","Customer"),W=d1($,J,"product_id","Product"),Q=d1($,J,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new T("License key must use five groups of four uppercase letters or numbers.");if(!nX.includes(X))throw new T(`Template must be one of: ${nX.join(", ")}.`);if(!iX.includes(Z))throw new T(`Status must be one of: ${iX.join(", ")}.`);if(!Number.isSafeInteger(Y)||Y<0||Y>2147483647)throw new T("Expiry date must be a Unix timestamp between 1970 and 2038.");let[F,N,H]=await Promise.all([K?o1.selectFrom("customers").where("id","=",K).select("id").executeTakeFirst():null,W?o1.selectFrom("products").where("id","=",W).select("id").executeTakeFirst():null,Q?o1.selectFrom("orders").where("id","=",Q).select(["id","customer_id"]).executeTakeFirst():null]);if(K&&!F)throw new T(`Customer ${K} was not found.`);if(W&&!N)throw new T(`Product ${W} was not found.`);if(Q&&!H)throw new T(`Order ${Q} was not found.`);if(K&&H?.customer_id&&Number(H.customer_id)!==K)throw new T(`Order ${Q} belongs to Customer ${H.customer_id}, not Customer ${K}.`);return{...$,key:G,template:X,expiry_date:Y,status:Z,customer_id:K,product_id:W,order_id:Q}}async function oX($){try{let J=sX(),G=G$($),X={...await M0(G),uuid:J};await a1.insertInto("license_keys").values(X).executeTakeFirst();let Z=await a1.selectFrom("license_keys").where("uuid","=",J).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created license key");return Z}catch(J){if(J instanceof T)throw J;if(J instanceof Error){if(J.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${J.message}`)}throw J}}async function dX($){if(!$.length)return 0;try{let J=await Promise.all($.map(async(X)=>({...await M0(G$(X)),uuid:sX()}))),G=await a1.insertInto("license_keys").values(J).executeTakeFirst();return L(G)}catch(J){if(J instanceof T)throw J;if(J instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${J.message}`);throw J}}import{db as Z4}from"@stacksjs/database";import{formatDate as r1}from"@stacksjs/orm";async function aX($,J){try{if(!$)throw Error("License key ID is required for update");let G=await Z4.selectFrom("license_keys").where("id","=",$).selectAll().executeTakeFirst();if(!G)return;let X=G$(J),Z=await M0(X,G),Y=await Z4.updateTable("license_keys").set({...Z,updated_at:r1(new Date)}).where("id","=",$).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof T)throw G;if(G instanceof Error){if(G.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${G.message}`)}throw G}}async function rX($,J){try{let G=await Z4.updateTable("license_keys").set({status:J,updated_at:r1(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 tX($,J){try{let G={updated_at:r1(new Date)};if(J!==void 0)G.expiry_date=J;let X=await Z4.updateTable("license_keys").set(G).where("id","=",$).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update expiration information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update expiration information: ${G.message}`);throw G}}var F4={};B(F4,{updateStatus:()=>L9,updatePricing:()=>N9,update:()=>F9,store:()=>Y9,softDelete:()=>$9,getActiveShippingMethods:()=>Q9,formatShippingOptions:()=>W9,fetchById:()=>Q4,fetchAll:()=>X9,destroy:()=>eX,bulkStore:()=>K9,bulkSoftDelete:()=>G9,bulkDestroy:()=>J9});import{db as K4}from"@stacksjs/database";async function eX($){try{let J=await K4.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 $9($){try{let J=await K4.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 J9($){if(!$.length)return 0;try{let J=await K4.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 G9($){if(!$.length)return 0;try{let J=await K4.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 W4}from"@stacksjs/database";async function Q4($){let J=await W4.selectFrom("shipping_methods").where("id","=",$).selectAll().executeTakeFirst();if(J){let G=await W4.selectFrom("shipping_zones").where("shipping_method_id","=",$).selectAll().execute();return{...J,shippingZones:G}}return}async function X9(){let $=await W4.selectFrom("shipping_methods").selectAll().execute();if($.length===0)return[];let J=[...new Set($.map((Y)=>Y.id))],Z=(await W4.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:Z9}=globalThis.Bun;import{db as W$}from"@stacksjs/database";async function Y9($){try{let J=Z9(),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 K9($){if(!$.length)return 0;try{let J=$.map((X)=>({...e0(X),uuid:Z9()})),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 W9(){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 Q9(){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 t1}from"@stacksjs/database";import{formatDate as e1}from"@stacksjs/orm";async function F9($,J){try{if(!$)throw Error("Shipping method ID is required for update");let G=await t1.updateTable("shipping_methods").set({...e0(J),updated_at:e1(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 L9($,J){try{let G=await t1.updateTable("shipping_methods").set({status:J,updated_at:e1(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 N9($,J,G){try{let X={updated_at:e1(new Date)};if(J!==void 0)X.base_rate=J;if(G!==void 0)X.free_shipping=G;let Z=await t1.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 V4={};B(V4,{validateZoneMatchesAddress:()=>R9,validateShippingRateWrite:()=>_0,updateByZone:()=>h9,updateByMethod:()=>I9,update:()=>f9,store:()=>k9,resolveZoneForAddress:()=>N4,getShippingRatesByMethod:()=>S9,getRatesByZone:()=>O9,getRateByWeightAndZone:()=>$7,getRateByWeightAndAddress:()=>A9,formatShippingRateOptions:()=>U9,fetchById:()=>M9,fetchAll:()=>_9,destroyByZone:()=>V9,destroyByMethod:()=>x9,destroy:()=>H9,bulkUpdate:()=>C9,bulkStore:()=>w9,bulkDestroy:()=>z9,ShippingRateInputError:()=>f});import{db as L4}from"@stacksjs/database";async function H9($){try{let J=await L4.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 z9($){if(!$.length)return 0;try{let J=await L4.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 V9($){try{let J=await L4.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 x9($){try{let J=await L4.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 M9($){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 _9(){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 O9($){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 $7($,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 N4($){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&&B9(X.regions,$.region))Z=2;if($.postalCode&&X.postal_codes&&B9(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 A9($,J){let G=await N4(J);if(G==null)return;return $7($,G)}async function R9($,J){return await N4(J)===$}function B9($,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 U9(){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 S9($){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:q9}=globalThis.Bun;import{db as J7}from"@stacksjs/database";import{db as Q$}from"@stacksjs/database";async function P9(){return await Q$.selectFrom("shipping_zones").selectAll().execute()}async function H4($){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 T9(){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 j9($){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([Q4(G),H4(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 k9($){try{let J=$0($),G=Number(J.shipping_method_id),X=Number(J.shipping_zone_id);await _0(J);let Z=q9(),Y={...J,shipping_method_id:G,shipping_zone_id:X,uuid:Z};await J7.insertInto("shipping_rates").values(Y).executeTakeFirst();let K=await J7.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 w9($){if(!$.length)return 0;try{for(let X of $){let Z=$0(X);await _0(Z)}let J=$.map((X)=>({...$0(X),uuid:q9()})),G=await J7.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 z4}from"@stacksjs/orm";async function f9($,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:z4(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 C9($){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:z4(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 h9($,J){try{let G=await L$.updateTable("shipping_rates").set({...$0(J),updated_at:z4(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 I9($,J){try{let G=await L$.updateTable("shipping_rates").set({...$0(J),updated_at:z4(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 U4={};B(U4,{startStop:()=>v9,startRoute:()=>p9,routeTrackingChannel:()=>G7,recordDriverPing:()=>g9,orderTrackingChannel:()=>Q0,isWithin:()=>CX,hasCoordinates:()=>Z$,failStop:()=>b9,estimateSecondsRemaining:()=>$4,emitDeliveryStarted:()=>M4,emitDeliveryPosition:()=>x4,emitDeliveryNearby:()=>_4,emitDeliveryFailed:()=>R4,emitDeliveryCompleted:()=>A4,emitDeliveryAssigned:()=>B4,emitDeliveryArrived:()=>O4,distanceInMeters:()=>W0,completeStop:()=>y9,broadcastToChannel:()=>J0,bearingInDegrees:()=>e$,assignStop:()=>D9,NEARBY_RADIUS_METERS:()=>X7,ARRIVAL_RADIUS_METERS:()=>Z7});function Q0($){return`order.${$}`}function G7($){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 x4($,J,G){await Promise.all([...$.map((X)=>J0(Q0(X),"delivery:position",G)),J==null?Promise.resolve():J0(G7(J),"delivery:position",G)])}async function B4($){if(await C0("delivery:assigned",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:assigned",{stop:$})}async function M4($){if(await C0("delivery:started",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:started",{stop:$})}async function _4($,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 O4($){if(await C0("delivery:arrived",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:arrived",{stop:$})}async function A4($){if(await C0("delivery:completed",{stop:$}),$.order_id!=null)await J0(Q0($.order_id),"delivery:completed",{stop:$})}async function R4($,J){await C0("delivery:failed",{stop:$,reason:J})}var{randomUUIDv7:TY}=globalThis.Bun;import{db as p}from"@stacksjs/database";var X7=400,Z7=60,jY=250;async function g9($){let J=$.recordedAt??new Date().toISOString(),G=typeof $.accuracy!=="number"||$.accuracy<=jY,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?e$(Z,$):null,K=await qY($.driverId),W=K?await kY(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=$4(Q,$.speed??0),H=Q<=Z7&&W.arrived_at==null,N=!H&&Q<=X7&&W.status==="en_route"&&W.notified_nearby_at==null;let x=await wY({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 x4(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 _4(W,Q,F);if(H&&W)await p.updateTable("delivery_stops").set({status:"arrived",arrived_at:J}).where("id","=",W.id).execute(),await O4({...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 qY($){return await p.selectFrom("delivery_routes").where("driver_id","=",$).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function kY($){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 wY($){let J=TY();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:fY}=globalThis.Bun;import{db as j}from"@stacksjs/database";async function D9($){let J=fY(),G=$.sequence??await hY($.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 gY(J);if(X)await B4(X);return X??{}}async function v9($){await j.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",$).execute();let J=await K7($);if(!J)return null;if(J.order_id!=null)await Y7(J.order_id,"OUT_FOR_DELIVERY");return await M4(J),J}async function y9($,J){let G=new Date().toISOString();await j.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await IY($)?{}:{arrived_at:G},...J?{notes:J}:{}}).where("id","=",$).execute();let X=await K7($);if(!X)return null;if(X.order_id!=null)await Y7(X.order_id,"DELIVERED");return await A4(X),await m9(X.delivery_route_id),X}async function b9($,J){await j.updateTable("delivery_stops").set({status:"failed",notes:J}).where("id","=",$).execute();let G=await K7($);if(!G)return null;if(G.order_id!=null)await Y7(G.order_id,"SHIPPED");return await R4(G,J),await m9(G.delivery_route_id),G}async function p9($){await j.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",$).execute()}async function m9($){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 Y7($,J){let G=await j.selectFrom("orders").where("id","=",$).select(["id","status"]).executeTakeFirst();if(!G)return;let X=await Promise.resolve().then(() => (P0(),V6)),{canTransition:Z,emitForStatus:Y}=X,K=CY(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 CY($,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 hY($){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 IY($){return(await j.selectFrom("delivery_stops").where("id","=",$).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function K7($){return await j.selectFrom("delivery_stops").where("id","=",$).selectAll().executeTakeFirst()??null}async function gY($){return await j.selectFrom("delivery_stops").where("uuid","=",$).selectAll().executeTakeFirst()??null}var T4={};B(T4,{updateStatus:()=>a9,updateRegionsAndPostalCodes:()=>t9,updateCountries:()=>r9,update:()=>d9,store:()=>s9,softDelete:()=>c9,getZonesByCountry:()=>j9,getActiveShippingZones:()=>T9,formatZoneOptions:()=>E9,fetchById:()=>H4,fetchAll:()=>P9,destroy:()=>l9,bulkStore:()=>o9,bulkSoftDelete:()=>n9,bulkDestroy:()=>u9});import{db as S4}from"@stacksjs/database";async function l9($){try{let J=await S4.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 c9($){try{let J=await S4.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 u9($){if(!$.length)return 0;try{let J=await S4.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 n9($){if(!$.length)return 0;try{let J=await S4.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:i9}=globalThis.Bun;import{db as W7}from"@stacksjs/database";async function s9($){try{let J=i9(),G={...$$($),uuid:J};await W7.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await W7.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 o9($){if(!$.length)return 0;try{let J=$.map((X)=>({...$$(X),uuid:i9()})),G=await W7.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 P4}from"@stacksjs/database";import{formatDate as E4}from"@stacksjs/orm";async function d9($,J){try{if(!$)throw Error("Shipping zone ID is required for update");let G=await P4.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 a9($,J){try{let G=await P4.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 r9($,J){try{let G=await P4.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 t9($,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 P4.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 DY={digital:a$,drivers:t$,geocoding:G4,licenses:Y4,methods:F4,rates:V4,routes:o$,tracking:U4,zones:T4},vY=DY;var N7={};B(N7,{updateStatus:()=>N3,updateRate:()=>H3,updateDefaultStatus:()=>z3,update:()=>L3,taxFor:()=>e9,store:()=>Q3,fetchById:()=>Z3,fetchAll:()=>Y3,destroy:()=>J3,bulkStore:()=>F3,bulkDestroy:()=>G3,breakdownFor:()=>L7,activeTaxRates:()=>F7});import{db as yY}from"@stacksjs/database";function bY($){let J=Number($);return Number.isFinite(J)?J/100:0}async function F7($={}){let J=yY.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 L7($,J,G={}){let X=Math.max(0,Math.round($)),Z=[],Y=0,K=0;for(let W of J){let Q=bY(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 e9($,J={}){return L7($,await F7(J),J)}import{db as $3}from"@stacksjs/database";async function J3($){try{let J=await $3.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 G3($){if(!$.length)return 0;try{let J=await $3.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 X3}from"@stacksjs/database";async function Z3($){return await X3.selectFrom("tax_rates").where("id","=",$).selectAll().executeTakeFirst()}async function Y3(){return await X3.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:K3}=globalThis.Bun;import{db as W3}from"@stacksjs/database";async function Q3($){try{return await W3.transaction(async(J)=>{let G={...$,uuid:K3()};if(G.is_default)await J.updateTable("tax_rates").set({is_default:!1}).execute();let X=await J.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X})}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rate: ${J.message}`);throw J}}async function F3($){if(!$.length)return 0;try{return await W3.transaction(async(J)=>{let G=0;for(let X of $){let Z={...X,uuid:K3()};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 j4}from"@stacksjs/database";import{formatDate as q4}from"@stacksjs/orm";async function L3($,J){try{if(!$)throw Error("Tax rate ID is required for update");return await j4.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=q4(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 N3($,J){try{let G=await j4.updateTable("tax_rates").set({status:J,updated_at:q4(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 H3($,J){try{let G=await j4.updateTable("tax_rates").set({rate:J,updated_at:q4(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 z3($,J){try{return await j4.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",$).executeTakeFirst())return!1;let Z=q4(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 M7={};B(M7,{restaurant:()=>I0,products:()=>w4,default:()=>dY});var w4={};B(w4,{updateStatus:()=>h3,updatePartySize:()=>I3,update:()=>k4,store:()=>f3,fetchWaiting:()=>P3,fetchPurchasedBetweenDates:()=>U3,fetchNotifiedBetweenDates:()=>R3,fetchCountByStatus:()=>E3,fetchCountBySource:()=>M3,fetchCountByQuantity:()=>O3,fetchCountByDateGrouped:()=>q3,fetchCountByDate:()=>_3,fetchCountByAllQuantities:()=>A3,fetchCountBetweenDates:()=>j3,fetchConversionRates:()=>T3,fetchCancelledBetweenDates:()=>S3,fetchById:()=>N$,fetchAll:()=>B3,destroy:()=>V3,bulkStore:()=>C3,bulkDestroy:()=>x3});import{db as H7}from"@stacksjs/database";async function V3($){try{let J=await H7.selectFrom("waitlist_products").where("id","=",$).selectAll().executeTakeFirst();if(!J)return;return await H7.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 x3($){if(!$.length)return 0;try{let J=await H7.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 E}from"@stacksjs/orm";async function N$($){return await A.selectFrom("waitlist_products").where("id","=",$).selectAll().executeTakeFirst()}async function B3(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function M3($,J){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if($&&J){let Z=E($),Y=E(J);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{source:Y,count:K})=>{return Z[Y]=K,Z},{})}async function _3($=new Date){let J=new Date($);J.setHours(0,0,0,0);let G=new Date($);G.setHours(23,59,59,999);let X=E(J),Z=E(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function O3($){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",$).executeTakeFirst())?.count??0}async function A3($,J){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if($&&J){let Z=E($),Y=E(J);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{quantity:Y,count:K})=>{return Z[Y]=K,Z},{})}async function R3($,J){let G=E($),X=E(J);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",X).whereNotNull("notified_at").execute()}async function U3($,J){let G=E($),X=E(J);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",X).whereNotNull("purchased_at").execute()}async function S3($,J){let G=E($),X=E(J);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",X).whereNotNull("cancelled_at").execute()}async function P3(){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=E(J),K=E(G);X=X.where("created_at",">=",Y).where("created_at","<=",K)}return(await X.executeTakeFirst())?.count??0}async function T3($,J){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if($&&J){let Q=E($),F=E(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 j3($,J){let G=E($),X=E(J);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function q3($,J){let G=A.selectFrom("waitlist_products").select(["created_at"]);if($&&J){let Y=E($),K=E(J);G=G.where("created_at",">=",Y).where("created_at","<=",K)}let Z=(await G.execute()).reduce((Y,{created_at:K})=>{let W=(K||"").split("T")[0]||"unknown";return Y[W]=(Y[W]||0)+1,Y},{});return Object.entries(Z).map(([Y,K])=>({date:Y,count:K})).sort((Y,K)=>Y.date.localeCompare(K.date))}var{randomUUIDv7:w3}=globalThis.Bun;import{db as z7}from"@stacksjs/database";import{formatDate as k3}from"@stacksjs/orm";var pY={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function mY($){return typeof $==="number"||$ instanceof Date?k3($):$}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]=mY(G[Z]);let X=pY[G.status];if(X&&G[X]===void 0&&!J[X])G[X]=k3(new Date);return G}async function f3($){try{let J=w3(),G={...H$($),uuid:J,status:$.status||"waiting"};await z7.insertInto("waitlist_products").values(G).executeTakeFirst();let X=await z7.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 C3($){if(!$.length)return 0;try{let J=$.map((X)=>({...H$(X),status:X.status||"waiting",uuid:w3()})),G=await z7.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 lY}from"@stacksjs/database";import{formatDate as cY}from"@stacksjs/orm";async function k4($,J){try{if(!$)throw Error("Waitlist product ID is required for update");let G=await N$($);if(!G)return;await lY.updateTable("waitlist_products").set({...H$(J,G),updated_at:cY(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 h3($,J){return await k4($,{status:J})}async function I3($,J){return await k4($,{quantity:J})}var I0={};B(I0,{updateWaitTimes:()=>KZ,updateStatus:()=>ZZ,updateQueuePosition:()=>WZ,updatePartySize:()=>YZ,update:()=>h0,store:()=>GZ,fetchWaitingWithQuotedTimes:()=>s3,fetchWaitingWithPartySizes:()=>o3,fetchWaiting:()=>u3,fetchTimeSeriesStats:()=>$Z,fetchTablesTurnedToday:()=>d3,fetchSeatingRate:()=>a3,fetchSeatedStats:()=>e3,fetchSeatedBetweenDates:()=>c3,fetchNoShowStats:()=>r3,fetchCurrentWaitTimes:()=>t3,fetchCountByTablePreference:()=>y3,fetchCountByPartySize:()=>p3,fetchCountByDate:()=>b3,fetchCountByAllPartySizes:()=>m3,fetchConversionRates:()=>n3,fetchById:()=>z$,fetchBetweenDates:()=>l3,fetchAverageWaitTimes:()=>i3,fetchAll:()=>v3,destroy:()=>g3,bulkStore:()=>XZ,bulkDestroy:()=>D3});import{db as V7}from"@stacksjs/database";async function g3($){try{let J=await V7.selectFrom("waitlist_restaurants").where("id","=",$).selectAll().executeTakeFirst();if(!J)return;return await V7.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 D3($){if(!$.length)return 0;try{let J=await V7.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 v3(){return await M.selectFrom("waitlist_restaurants").selectAll().execute()}async function y3(){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 b3($=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 p3($){return(await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("party_size","=",$).executeTakeFirst())?.count??0}async function m3(){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 l3($,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 c3($,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 u3(){return await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function n3(){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 i3(){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 s3(){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 o3(){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 d3(){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 a3($,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 r3($,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,U)=>O+(U.quoted_wait_time??0),0),N=W>0?F/W:0,H=K.reduce((O,U)=>O+U.party_size,0),z=W>0?H/W:0,x=K.reduce((O,U)=>{return O[U.table_preference]=(O[U.table_preference]||0)+1,O},{}),R=K.reduce((O,U)=>{return O[U.party_size]=(O[U.party_size]||0)+1,O},{});return{totalNoShows:W,noShowRate:Q,averageQuotedWaitTime:N,averagePartySize:z,breakdownByTablePreference:x,breakdownByPartySize:R}}async function t3(){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 e3(){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 $Z(){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:JZ}=globalThis.Bun;import{db as B7}from"@stacksjs/database";import{formatDate as x7}from"@stacksjs/orm";var uY={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function nY($){if(typeof $==="number")return x7($<=2147483647?$*1000:$);if($ instanceof Date)return x7($);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]=nY(G[Z]);let X=uY[G.status];if(X&&G[X]===void 0&&!J[X])G[X]=x7(new Date);return G}async function GZ($){try{let J=JZ(),G={...V$($),status:$.status||"waiting",uuid:J};await B7.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let X=await B7.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 XZ($){if(!$.length)return 0;try{let J=$.map((X)=>({...V$(X),status:X.status||"waiting",uuid:JZ()})),G=await B7.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 iY}from"@stacksjs/database";import{formatDate as sY}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 iY.updateTable("waitlist_restaurants").set({...V$(J,G),updated_at:sY(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 ZZ($,J){return await h0($,{status:J})}async function YZ($,J){return await h0($,{party_size:J})}async function KZ($,J,G){return await h0($,{quoted_wait_time:J,...G===void 0?{}:{actual_wait_time:G}})}async function WZ($,J){return await h0($,{queue_position:J})}var oY={products:w4,restaurant:I0},dY=oY;var aY={auctions:Z1,coupons:Y1,customers:K1,devices:N1,errors:V1,giftCards:B1,orders:E1,payments:T1,products:h1,receipts:b1,restaurant:I0,shippings:Q7,tax:N7,waitlists:M7},fV=aY;export{M7 as waitlists,N7 as tax,Q7 as shippings,I0 as restaurant,b1 as receipts,h1 as products,T1 as payments,E1 as orders,B1 as giftCards,V1 as errors,N1 as devices,fV as default,K1 as customers,Y1 as coupons,aY as commerce,Z1 as auctions};