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