@stacksjs/commerce 0.70.297 → 0.70.299

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- var oX=Object.defineProperty;var sX=(J)=>J;function dX(J,$){this[J]=sX.bind(null,$)}var z=(J,$)=>{for(var G in $)oX(J,G,{get:$[G],enumerable:!0,configurable:!0,set:dX.bind($,G)})};var aX=(J,$)=>()=>(J&&($=J(J=0)),$);var s0=import.meta.require;var KJ={};z(KJ,{emitOrderShipped:()=>W$,emitOrderRefunded:()=>Q0,emitOrderPaid:()=>d,emitOrderOutForDelivery:()=>LJ,emitOrderDelivered:()=>Z$,emitOrderCreated:()=>w0,emitOrderCancelled:()=>F0,emitForStatus:()=>q0,canTransition:()=>P0});function P0(J,$){if(J===$)return!0;return _9[J]?.includes($)??!1}async function G0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let N=G.dispatch;if(typeof N!=="function")return;N(J,$)}catch{}}async function w0(J){await G0("order:created",{order:J})}async function d(J,$){await G0("order:paid",{order:J,payment:$})}async function W$(J){await G0("order:shipped",{order:J})}async function LJ(J){await G0("order:out_for_delivery",{order:J})}async function Z$(J){await G0("order:delivered",{order:J})}async function F0(J,$){await G0("order:cancelled",{order:J,reason:$})}async function Q0(J,$){await G0("order:refunded",{order:J,refundAmount:$})}async function q0(J,$){switch(J){case"PROCESSING":return d($);case"SHIPPED":return W$($);case"OUT_FOR_DELIVERY":return LJ($);case"DELIVERED":return Z$($);case"CANCELLED":return F0($);case"REFUNDED":return Q0($);case"PENDING":default:}}var _9;var M0=aX(()=>{_9={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={};z(Y1,{update:()=>m4,store:()=>v4,redeem:()=>p4,getActiveCouponsMoMChange:()=>h4,fetchTopRedeemedCoupons:()=>k4,fetchStats:()=>w4,fetchRedemptionTrend:()=>j4,fetchRedemptionStats:()=>E4,fetchCouponCountsByType:()=>f4,fetchCouponCounts:()=>q4,fetchConversionRate:()=>C4,fetchById:()=>$0,fetchByCode:()=>T4,fetchAll:()=>U4,fetchActive:()=>P4,deleteExpiredCoupons:()=>R4,deleteCoupons:()=>_4,deleteCoupon:()=>A4});import{db as d0}from"@stacksjs/database";import{formatDate as eX}from"@stacksjs/orm";function F(J){if(typeof J==="number")return Number.isFinite(J)?J:0;if(typeof J==="bigint")return Number(J);if(!J||typeof J!=="object")return 0;let $=J;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[G]!==void 0&&$[G]!==null)return F($[G]);if(Array.isArray(J))return J.reduce((G,N)=>G+F(N),0);return 0}async function A4(J){let $=await d0.deleteFrom("coupons").where("id","=",J).executeTakeFirst();return F($)>0}async function _4(J){if(!J.length)return 0;return(await d0.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function R4(){let J=eX(new Date),$=await d0.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return F($)}import{db as V}from"@stacksjs/database";import{extractDate as O4,formatDate as S4}from"@stacksjs/orm";import{camelCase as rX}from"@stacksjs/strings";function e0(J){let $=Object.fromEntries(Object.entries(J).map(([G,N])=>[rX(G),N]));if($.endDate)$.endDate=O4(new Date($.endDate));if($.startDate)$.startDate=O4(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function U4(){return(await V.selectFrom("coupons").selectAll().execute()).map(e0)}async function $0(J){let $=await V.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return e0($);return}async function T4(J){let $=await V.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return e0($);return}async function P4(){let J=S4(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map(e0)}async function w4(){let J=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).executeTakeFirst(),$=S4(new Date),G=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(V.fn.count("id").as("count")).executeTakeFirst(),N=await V.selectFrom("coupons").select(["discount_type",V.fn.count("id").as("count")]).groupBy("discount_type").execute(),X=await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),W=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",$).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(J?.count||0),active:Number(G?.count||0),by_type:N,most_used:X,upcoming:W}}async function q4(){let J=new Date,$=new Date(J);$.setDate(J.getDate()-7);let G=new Date(J);G.setMonth(J.getMonth()-1);let N=new Date(J);N.setFullYear(J.getFullYear()-1);let X=await a0(null,null,J),W=await a0($,null,J),Z=await a0(G,null,J),Y=await a0(N,null,J);return{week:W,month:Z,year:Y,all_time:X}}async function a0(J,$,G){let N=V.selectFrom("coupons");if(J)N=N.where("created_at",">=",J.toISOString());if($)N=N.where("created_at","<=",$.toISOString());let X=await N.select(V.fn.count("id").as("count")).executeTakeFirst(),W=V.selectFrom("coupons");if(J)W=W.where("created_at",">=",J.toISOString());if($)W=W.where("created_at","<=",$.toISOString());W=W.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let Z=await W.select(V.fn.count("id").as("count")).executeTakeFirst(),Y=Number(X?.count||0),L=Number(Z?.count||0),K=Y-L;return{total:Y,active:L,inactive:K}}async function f4(){let J=new Date,$=await V.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:N}of $){let X=await V.selectFrom("coupons").where("discount_type","=",N).select(V.fn.count("id").as("count")).executeTakeFirst(),W=await V.selectFrom("coupons").where("discount_type","=",N).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(V.fn.count("id").as("count")).executeTakeFirst(),Z=Number(X?.count||0),Y=Number(W?.count||0);G[N]={total:Z,active:Y,inactive:Z-Y}}return G}async function E4(){let J=await V.selectFrom("coupons").select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,G=new Date($);G.setDate($.getDate()-7);let N=new Date($);N.setMonth($.getMonth()-1);let X=new Date($);X.setFullYear($.getFullYear()-1);let W=await V.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),Z=await V.selectFrom("coupons").where("updated_at",">=",N.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await V.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await V.selectFrom("coupons").select(["discount_type",V.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),K={};return L.forEach((Q)=>{K[Q.discount_type]=Number(Q.total||0)}),{total:Number(J?.total||0),week:Number(W?.total||0),month:Number(Z?.total||0),year:Number(Y?.total||0),by_type:K}}async function k4(J=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(J).execute()}async function j4(J=30){let $=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-J);let N=await V.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),X={};return N.forEach((W)=>{let Z=W.updated_at?new Date(W.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!X[Z])X[Z]=0;X[Z]+=W?.usage_count||0}),Object.entries(X).map(([W,Z])=>({date:W,count:Z}))}async function C4(){let J=new Date,$=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).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(),N=Number($?.count||0),X=Number(G?.count||0);return{rate:N>0?X/N*100:0,total_active:N,total_redeemed:X}}async function h4(){let J=new Date,$=new Date(J.getFullYear(),J.getMonth(),1),G=new Date(J.getFullYear(),J.getMonth()-1,1),N=new Date(J.getFullYear(),J.getMonth(),0),X=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),W=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",G).executeTakeFirst(),Z=Number(X?.count||0),Y=Number(W?.count||0),L=Z-Y,K=Y!==0?L/Y*100:Z>0?100:0;return{current_month:Z,previous_month:Y,difference:L,percentage_change:K}}var{randomUUIDv7:tX}=globalThis.Bun;import{db as I4}from"@stacksjs/database";import{HttpError as g4}from"@stacksjs/error-handling";import{isUniqueViolation as $9}from"@stacksjs/orm";async function v4(J){try{let $=tX();return await I4.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await I4.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof g4)throw $;if($9($))throw new g4(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as D4}from"@stacksjs/database";import{HttpError as y4}from"@stacksjs/error-handling";import{formatDate as b4,isUniqueViolation as J9}from"@stacksjs/orm";async function m4(J,$){if(!await $0(J))return;try{return await D4.updateTable("coupons").set({...$,updated_at:b4(new Date)}).where("id","=",J).execute(),await $0(J)}catch(N){if(N instanceof y4)throw N;if(J9(N))throw new y4(409,"A coupon with this code already exists");if(N instanceof Error)throw Error(`Failed to update coupon: ${N.message}`);throw N}}async function p4(J){let $=b4(new Date),G=await D4.unsafe(`UPDATE coupons
2
+ var G3=Object.defineProperty;var X3=(J)=>J;function W3(J,$){this[J]=X3.bind(null,$)}var z=(J,$)=>{for(var G in $)G3(J,G,{get:$[G],enumerable:!0,configurable:!0,set:W3.bind($,G)})};var Z3=(J,$)=>()=>(J&&($=J(J=0)),$);var J0=import.meta.require;var xJ={};z(xJ,{emitOrderShipped:()=>L$,emitOrderRefunded:()=>x0,emitOrderPaid:()=>d,emitOrderOutForDelivery:()=>HJ,emitOrderDelivered:()=>N$,emitOrderCreated:()=>q0,emitOrderCancelled:()=>H0,emitForStatus:()=>k0,canTransition:()=>f0});function f0(J,$){if(J===$)return!0;return f3[J]?.includes($)??!1}async function W0(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 q0(J){await W0("order:created",{order:J})}async function d(J,$){await W0("order:paid",{order:J,payment:$})}async function L$(J){await W0("order:shipped",{order:J})}async function HJ(J){await W0("order:out_for_delivery",{order:J})}async function N$(J){await W0("order:delivered",{order:J})}async function H0(J,$){await W0("order:cancelled",{order:J,reason:$})}async function x0(J,$){await W0("order:refunded",{order:J,refundAmount:$})}async function k0(J,$){switch(J){case"PROCESSING":return d($);case"SHIPPED":return L$($);case"OUT_FOR_DELIVERY":return HJ($);case"DELIVERED":return N$($);case"CANCELLED":return H0($);case"REFUNDED":return x0($);case"PENDING":default:}}var f3;var V0=Z3(()=>{f3={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 Q1={};z(Q1,{update:()=>u4,store:()=>m4,redeem:()=>n4,getActiveCouponsMoMChange:()=>D4,fetchTopRedeemedCoupons:()=>I4,fetchStats:()=>k4,fetchRedemptionTrend:()=>g4,fetchRedemptionStats:()=>h4,fetchCouponCountsByType:()=>C4,fetchCouponCounts:()=>j4,fetchConversionRate:()=>v4,fetchById:()=>G0,fetchByCode:()=>f4,fetchAll:()=>E4,fetchActive:()=>q4,deleteExpiredCoupons:()=>S4,deleteCoupons:()=>P4,deleteCoupon:()=>U4});import{db as e0}from"@stacksjs/database";import{formatDate as Y3}from"@stacksjs/orm";function F(J){if(typeof J==="number")return Number.isFinite(J)?J:0;if(typeof J==="bigint")return Number(J);if(!J||typeof J!=="object")return 0;let $=J;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[G]!==void 0&&$[G]!==null)return F($[G]);if(Array.isArray(J))return J.reduce((G,X)=>G+F(X),0);return 0}async function U4(J){let $=await e0.deleteFrom("coupons").where("id","=",J).executeTakeFirst();return F($)>0}async function P4(J){if(!J.length)return 0;return(await e0.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function S4(){let J=Y3(new Date),$=await e0.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return F($)}import{db as V}from"@stacksjs/database";import{extractDate as w4,formatDate as T4}from"@stacksjs/orm";import{camelCase as L3}from"@stacksjs/strings";function t0(J){let $=Object.fromEntries(Object.entries(J).map(([G,X])=>[L3(G),X]));if($.endDate)$.endDate=w4(new Date($.endDate));if($.startDate)$.startDate=w4(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function E4(){return(await V.selectFrom("coupons").selectAll().execute()).map(t0)}async function G0(J){let $=await V.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function f4(J){let $=await V.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function q4(){let J=T4(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map(t0)}async function k4(){let J=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).executeTakeFirst(),$=T4(new Date),G=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).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(),W=await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),Z=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",$).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(J?.count||0),active:Number(G?.count||0),by_type:X,most_used:W,upcoming:Z}}async function j4(){let J=new Date,$=new Date(J);$.setDate(J.getDate()-7);let G=new Date(J);G.setMonth(J.getMonth()-1);let X=new Date(J);X.setFullYear(J.getFullYear()-1);let W=await r0(null,null,J),Z=await r0($,null,J),Y=await r0(G,null,J),L=await r0(X,null,J);return{week:Z,month:Y,year:L,all_time:W}}async function r0(J,$,G){let X=V.selectFrom("coupons");if(J)X=X.where("created_at",">=",J.toISOString());if($)X=X.where("created_at","<=",$.toISOString());let W=await X.select(V.fn.count("id").as("count")).executeTakeFirst(),Z=V.selectFrom("coupons");if(J)Z=Z.where("created_at",">=",J.toISOString());if($)Z=Z.where("created_at","<=",$.toISOString());Z=Z.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let Y=await Z.select(V.fn.count("id").as("count")).executeTakeFirst(),L=Number(W?.count||0),N=Number(Y?.count||0),K=L-N;return{total:L,active:N,inactive:K}}async function C4(){let J=new Date,$=await V.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:X}of $){let W=await V.selectFrom("coupons").where("discount_type","=",X).select(V.fn.count("id").as("count")).executeTakeFirst(),Z=await V.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(V.fn.count("id").as("count")).executeTakeFirst(),Y=Number(W?.count||0),L=Number(Z?.count||0);G[X]={total:Y,active:L,inactive:Y-L}}return G}async function h4(){let J=await V.selectFrom("coupons").select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,G=new Date($);G.setDate($.getDate()-7);let X=new Date($);X.setMonth($.getMonth()-1);let W=new Date($);W.setFullYear($.getFullYear()-1);let Z=await V.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await V.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await V.selectFrom("coupons").where("updated_at",">=",W.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),N=await V.selectFrom("coupons").select(["discount_type",V.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),K={};return N.forEach((Q)=>{K[Q.discount_type]=Number(Q.total||0)}),{total:Number(J?.total||0),week:Number(Z?.total||0),month:Number(Y?.total||0),year:Number(L?.total||0),by_type:K}}async function I4(J=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(J).execute()}async function g4(J=30){let $=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-J);let X=await V.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),W={};return X.forEach((Z)=>{let Y=Z.updated_at?new Date(Z.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!W[Y])W[Y]=0;W[Y]+=Z?.usage_count||0}),Object.entries(W).map(([Z,Y])=>({date:Z,count:Y}))}async function v4(){let J=new Date,$=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).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($?.count||0),W=Number(G?.count||0);return{rate:X>0?W/X*100:0,total_active:X,total_redeemed:W}}async function D4(){let J=new Date,$=new Date(J.getFullYear(),J.getMonth(),1),G=new Date(J.getFullYear(),J.getMonth()-1,1),X=new Date(J.getFullYear(),J.getMonth(),0),W=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),Z=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",G).executeTakeFirst(),Y=Number(W?.count||0),L=Number(Z?.count||0),N=Y-L,K=L!==0?N/L*100:Y>0?100:0;return{current_month:Y,previous_month:L,difference:N,percentage_change:K}}var{randomUUIDv7:N3}=globalThis.Bun;import{db as y4}from"@stacksjs/database";import{HttpError as b4}from"@stacksjs/error-handling";import{isUniqueViolation as K3}from"@stacksjs/orm";async function m4(J){try{let $=N3();return await y4.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await y4.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof b4)throw $;if(K3($))throw new b4(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as l4}from"@stacksjs/database";import{HttpError as p4}from"@stacksjs/error-handling";import{formatDate as c4,isUniqueViolation as F3}from"@stacksjs/orm";async function u4(J,$){if(!await G0(J))return;try{return await l4.updateTable("coupons").set({...$,updated_at:c4(new Date)}).where("id","=",J).execute(),await G0(J)}catch(X){if(X instanceof p4)throw X;if(F3(X))throw new p4(409,"A coupon with this code already exists");if(X instanceof Error)throw Error(`Failed to update coupon: ${X.message}`);throw X}}async function n4(J){let $=c4(new Date),G=await l4.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,$,$]),N=typeof G?.execute==="function"?await G.execute():G;if(Number(N?.changes??N?.numUpdatedRows??N?.affectedRows??0)>0){let L=await $0(J);if(L)return{ok:!0,coupon:L};return{ok:!1,reason:"not-found"}}let W=await $0(J);if(!W)return{ok:!1,reason:"not-found"};if(!W.isActive)return{ok:!1,reason:"inactive"};let Z=!W.startDate||W.startDate<=$,Y=!W.endDate||W.endDate>=$;if(!Z||!Y)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var L1={};z(L1,{update:()=>a4,store:()=>s4,fetchById:()=>r0,fetchAll:()=>i4,destroy:()=>c4,bulkDestroy:()=>u4});import{db as l4}from"@stacksjs/database";async function c4(J){try{let $=await l4.deleteFrom("customers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function u4(J){if(!J.length)return 0;try{let $=await l4.deleteFrom("customers").where("id","in",J).executeTakeFirst();return F($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as n4}from"@stacksjs/database";async function r0(J){return await n4.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function i4(){return await n4.selectFrom("customers").selectAll().execute()}import{db as G9}from"@stacksjs/database";import{HttpError as o4}from"@stacksjs/error-handling";import{isUniqueViolation as N9}from"@stacksjs/orm";async function s4(J){try{let $={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await G9.insertInto("customers").values($).executeTakeFirst();if(!G)throw Error("Failed to create customer");let N=G.insertId||Number(G.numInsertedOrUpdatedRows);return await r0(Number(N))}catch($){if($ instanceof o4)throw $;if(N9($))throw new o4(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as X9}from"@stacksjs/database";import{HttpError as d4}from"@stacksjs/error-handling";import{formatDate as W9,isUniqueViolation as Z9}from"@stacksjs/orm";async function a4(J,$){try{if(!J)throw Error("Customer ID is required for update");let G=await X9.updateTable("customers").set({...$,updated_at:W9(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof d4)throw G;if(Z9(G))throw new d4(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var H1={};z(H1,{updateStatus:()=>H7,updatePrintCount:()=>V7,update:()=>M7,storePrintDevicesExport:()=>L7,store:()=>F7,getPrinterStatusCounts:()=>Z7,fetchErrorsByDeviceId:()=>X7,fetchById:()=>l,fetchAll:()=>t0,exportPrintDevices:()=>$$,downloadPrintDevices:()=>Y7,destroy:()=>r4,countTotalPrints:()=>J7,countPrintsByDeviceId:()=>G7,countAll:()=>$7,calculatePrinterHealth:()=>W7,calculateErrorRate:()=>N7,bulkStore:()=>Q7,bulkDestroy:()=>t4});import{db as e4}from"@stacksjs/database";async function r4(J){try{let $=await e4.deleteFrom("print_devices").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function t4(J){if(!J.length)return 0;try{let $=await e4.deleteFrom("print_devices").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as Y9}from"ts-spreadsheets";import{db as q}from"@stacksjs/database";async function l(J){return await q.selectFrom("print_devices").where("id","=",J).selectAll().executeTakeFirst()}async function t0(){return await q.selectFrom("print_devices").selectAll().execute()}async function $7(){let J=await q.selectFrom("print_devices").select(q.fn.count("id").as("count")).executeTakeFirst();return Number(J?.count||0)}async function J7(){let J=await q.selectFrom("print_devices").select(q.fn.sum("print_count").as("total")).executeTakeFirst();return Number(J?.total||0)}async function G7(J){return(await q.selectFrom("print_devices").select("print_count").where("id","=",J).executeTakeFirst())?.print_count??0}async function N7(){let J=await q.selectFrom("receipts").select([q.fn.count("id").as("total"),q.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.failed_count??0)/J.total*100)}async function X7(J){return await q.selectFrom("receipts").where("print_device_id","=",J).where("status","=","failed").selectAll().execute()}async function W7(){let J=await q.selectFrom("print_devices").select([q.fn.count("id").as("total"),q.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.online_count??0)/J.total*100)}async function Z7(){return(await q.selectFrom("print_devices").select(["status",q.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,G)=>{return $[G.status]=Number(G.count||0),$},{})}function K1(J,$,G=$){return J?.[$]??J?.[G]}function L9(J){let $=String(J||""),G=/^\d+$/.test($)?Number($):J;return new Date(G)}async function $$(J="csv"){let $=await t0(),G=K9($);return Y9(G,{type:J})}function K9(J){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=J.map((N)=>{return[N.id,N.name,K1(N,"macAddress","mac_address"),N.location,N.terminal,N.status,L9(K1(N,"lastPing","last_ping")).toLocaleString(),K1(N,"printCount","print_count")]});return{headings:$,data:G}}async function Y7(J="csv",$){let G=await $$(J),N=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||N)}async function L7(J="csv",$){let G=await $$(J),N=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||N)}var{randomUUIDv7:K7}=globalThis.Bun;import{db as F1}from"@stacksjs/database";async function F7(J){try{let $=K7(),G={last_ping:0,print_count:0,...J,uuid:$};return await F1.insertInto("print_devices").values(G).executeTakeFirst(),await F1.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function Q7(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={last_ping:0,print_count:0,...G,uuid:K7()};await F1.insertInto("print_devices").values(N).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as Q1}from"@stacksjs/database";import{formatDate as M1}from"@stacksjs/orm";async function M7(J,$){if(!await l(J))return;try{return await Q1.updateTable("print_devices").set({...$,updated_at:M1(new Date)}).where("id","=",J).execute(),await l(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update print device: ${N.message}`);throw N}}async function H7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await Q1.updateTable("print_devices").set({status:$,updated_at:M1(new Date)}).where("id","=",J).execute(),await l(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update print device status: ${N.message}`);throw N}}async function V7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await Q1.updateTable("print_devices").set({print_count:$,updated_at:M1(new Date)}).where("id","=",J).execute(),await l(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update print count: ${N.message}`);throw N}}var z1={};z(z1,{update:()=>U7,unresolveGroup:()=>q7,resolveGroup:()=>P7,ignoreGroup:()=>w7,fetchTimeline:()=>S7,fetchStats:()=>O7,fetchGrouped:()=>_7,fetchById:()=>A7,fetchByGroup:()=>R7,fetchAll:()=>G$,destroyGroup:()=>B7,destroy:()=>x7,bulkUpdateStatus:()=>T7,bulkDestroy:()=>z7});import{db as V1}from"@stacksjs/database";import{log as x1}from"@stacksjs/logging";async function x7(J){try{return await V1.deleteFrom("errors").where("id","=",J).execute(),!0}catch($){return x1.error("[commerce/errors] destroy failed",{id:J,error:$}),!1}}async function z7(J){try{return await V1.deleteFrom("errors").where("id","in",J).execute(),!0}catch($){return x1.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:$}),!1}}async function B7(J,$){try{return await V1.deleteFrom("errors").where("type","=",J).where("message","=",$).execute(),!0}catch(G){return x1.error("[commerce/errors] destroyGroup failed",{type:J,message:$,error:G}),!1}}import{db as J$}from"@stacksjs/database";async function A7(J){return await J$.selectFrom("errors").where("id","=",J).selectAll().executeTakeFirst()}async function G$(){return await J$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function _7(){let J=await J$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let N of J){let X=`${N.type}:${N.message}`;if(!$.has(X))$.set(X,{errors:[],firstSeen:new Date(N.created_at),lastSeen:new Date(N.created_at)});let W=$.get(X);W.errors.push(N);let Z=new Date(N.created_at);if(Z<W.firstSeen)W.firstSeen=Z;if(Z>W.lastSeen)W.lastSeen=Z}let G=[];for(let[N,X]of $){let W=X.errors[0];if(!W)continue;let Z=X.errors.find((L)=>L.status!==null)?.status,Y="unresolved";if(Z===1)Y="resolved";else if(Z===2)Y="ignored";G.push({id:W.id,type:W.type,message:W.message,stack:W.stack,status:Y,count:X.errors.length,first_seen:X.firstSeen.toISOString(),last_seen:X.lastSeen.toISOString(),error_ids:X.errors.map((L)=>L.id)})}return G.sort((N,X)=>new Date(X.last_seen).getTime()-new Date(N.last_seen).getTime()),G}async function R7(J,$){return await J$.selectFrom("errors").where("type","=",J).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function O7(){let J=await G$(),$=new Date,G=new Date($.getTime()-86400000),N=new Date($.getTime()-172800000),X=J.filter((Y)=>new Date(Y.created_at)>=G).length,W=J.filter((Y)=>{let L=new Date(Y.created_at);return L>=N&&L<G}).length,Z=W===0?X>0?100:0:Math.round((X-W)/W*100);return{total:J.length,unresolved:J.filter((Y)=>Y.status===null||Y.status===0).length,resolved:J.filter((Y)=>Y.status===1).length,ignored:J.filter((Y)=>Y.status===2).length,last_24h:X,trend:Z}}async function S7(){let J=await G$(),$=new Date,G=[];for(let N=23;N>=0;N--){let X=new Date($.getTime()-N*60*60*1000);X.setMinutes(0,0,0);let W=new Date(X.getTime()+3600000),Z=J.filter((Y)=>{let L=new Date(Y.created_at);return L>=X&&L<W}).length;G.push({hour:X.toISOString(),count:Z})}return G}import{db as S0}from"@stacksjs/database";import{sql as U0}from"@stacksjs/database";import{log as T0}from"@stacksjs/logging";async function U7(J,$){try{return await S0.updateTable("errors").set({...$,updated_at:U0.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(G){return T0.error("[commerce/errors] update failed",{id:J,error:G}),!1}}async function T7(J,$){try{return await S0.updateTable("errors").set({status:$,updated_at:U0.raw("CURRENT_TIMESTAMP")}).where("id","in",J).execute(),!0}catch(G){return T0.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:$,error:G}),!1}}async function P7(J,$){try{return await S0.updateTable("errors").set({status:1,updated_at:U0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return T0.error("[commerce/errors] resolveGroup failed",{type:J,message:$,error:G}),!1}}async function w7(J,$){try{return await S0.updateTable("errors").set({status:2,updated_at:U0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return T0.error("[commerce/errors] ignoreGroup failed",{type:J,message:$,error:G}),!1}}async function q7(J,$){try{return await S0.updateTable("errors").set({status:0,updated_at:U0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return T0.error("[commerce/errors] unresolveGroup failed",{type:J,message:$,error:G}),!1}}var A1={};z(A1,{updateBalance:()=>i7,update:()=>n7,store:()=>p7,fetchTotalValue:()=>I7,fetchTotalCurrentBalance:()=>g7,fetchStats:()=>k7,fetchById:()=>J0,fetchByCode:()=>B1,fetchAll:()=>f7,fetchActive:()=>E7,destroy:()=>y7,compareActiveGiftCards:()=>C7,checkBalance:()=>j7,calculateGiftCardValues:()=>h7,bulkDestroy:()=>D7});import{db as v7}from"@stacksjs/database";import{formatDate as nW}from"@stacksjs/orm";import{db as U,sql as C}from"@stacksjs/database";import{formatDate as s,toTimestamp as K0}from"@stacksjs/orm";import{aggregateFunctions as F9,db as Q9}from"@stacksjs/database";async function I(J,$,G){let N=Q9.selectFrom(J);if(G)N=G(N);N=N.select(Object.entries($).map(([Z,Y])=>{let L=Y.column??"id",K=F9[Y.kind](L);if(Y.filter)K=K.filterWhere(Y.filter.column,Y.filter.op,Y.filter.value);return K.as(Z)}));let X=await N.executeTakeFirst(),W={};for(let Z of Object.keys($)){let Y=X?.[Z];W[Z]=typeof Y==="number"?Y:Number(Y??0)||0}return W}async function f7(){return await U.selectFrom("gift_cards").selectAll().execute()}async function J0(J){return await U.selectFrom("gift_cards").where("id","=",J).selectAll().executeTakeFirst()}async function B1(J){return await U.selectFrom("gift_cards").where("code","=",J).selectAll().executeTakeFirst()}async function E7(){return await U.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function k7(){let{count:J}=await I("gift_cards",{count:{kind:"count"}}),$=K0(new Date),G=await U.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal($)} OR expiry_date IS NULL)`).select(U.fn.count("id").as("count")).executeTakeFirst(),N=await U.selectFrom("gift_cards").select(["status",U.fn.count("id").as("count")]).groupBy("status").execute(),{count:X}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:W}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:Z}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance > 0.75`)),Y=new Date;Y.setDate(Y.getDate()+30);let L=await U.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",K0(Y)).where("expiry_date",">=",$).selectAll().limit(5).execute(),K=await U.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:J,active:Number(G?.count||0),by_status:N.map((Q)=>({status:Q.status,count:Number(Q.count)})),by_balance:{low:X,medium:W,high:Z},expiring_soon:L,recently_used:K}}async function j7(J){let $=await B1(J);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function C7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await U.selectFrom("gift_cards").select(U.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),Z=await U.selectFrom("gift_cards").select(U.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0(X))} OR expiry_date IS NULL)`).where("created_at",">=",s(X)).where("created_at","<=",s(N)).executeTakeFirst(),Y=Number(W?.count||0),L=Number(Z?.count||0),K=Y-L,Q=L!==0?K/L*100:Y>0?100:0;return{current_period:Y,previous_period:L,difference:K,percentage_change:Q,days_range:J}}async function h7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await U.selectFrom("gift_cards").select([U.fn.sum("initial_balance").as("total_initial"),U.fn.sum("current_balance").as("total_balance"),U.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),Z=await U.selectFrom("gift_cards").select([U.fn.sum("initial_balance").as("total_initial"),U.fn.sum("current_balance").as("total_balance"),U.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0(X))} OR expiry_date IS NULL)`).where("created_at",">=",s(X)).where("created_at","<=",s(N)).executeTakeFirst(),Y=Number(W?.total_initial||0),L=Number(W?.total_balance||0),K=Number(W?.card_count||0),Q=Number(Z?.total_initial||0),M=Number(Z?.total_balance||0),H=Number(Z?.card_count||0),_=Y>0?(Y-L)/Y*100:0,O=Q>0?(Q-M)/Q*100:0,R=K>0?Y/K:0,S=K>0?L/K:0,m=Y-Q,r=L-M,t=K-H,L0=Q!==0?m/Q*100:Y>0?100:0,p=M!==0?r/M*100:L>0?100:0,iX=H!==0?t/H*100:K>0?100:0;return{current_period:{total_initial_value:Y,total_remaining_balance:L,utilization_rate:_,card_count:K,average_initial_value:R,average_remaining_balance:S},previous_period:{total_initial_value:Q,total_remaining_balance:M,utilization_rate:O,card_count:H},comparison:{initial_value:{difference:m,percentage:Math.abs(L0),is_increase:m>=0},balance:{difference:r,percentage:Math.abs(p),is_increase:r>=0},card_count:{difference:t,percentage:Math.abs(iX),is_increase:t>=0}},days_range:J}}async function I7(){let{total_value:J}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:J}}async function g7(){let{total_balance:J}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:J}}async function y7(J){let $=await v7.deleteFrom("gift_cards").where("id","=",J).executeTakeFirst();return F($)>0}async function D7(J){if(!J.length)return 0;let $=await v7.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return F($)}var{randomUUIDv7:M9}=globalThis.Bun;import{db as b7}from"@stacksjs/database";import{HttpError as m7}from"@stacksjs/error-handling";import{isUniqueViolation as H9}from"@stacksjs/orm";async function p7(J){let $=J,G={...J,current_balance:$.current_balance??$.initial_balance,status:J.status||"ACTIVE",is_active:$.is_active??!0,uuid:M9()};try{let N=await b7.insertInto("gift_cards").values(G).executeTakeFirst(),X=Number(N.insertId)||Number(N.numInsertedOrUpdatedRows);if(X)return await b7.selectFrom("gift_cards").where("id","=",X).selectAll().executeTakeFirst();return}catch(N){if(N instanceof m7)throw N;if(H9(N))throw new m7(409,"A gift card with this code already exists");if(N instanceof Error)throw Error(`Failed to create gift card: ${N.message}`);throw N}}import{db as c7}from"@stacksjs/database";import{HttpError as l7}from"@stacksjs/error-handling";import{formatDate as u7,isUniqueViolation as V9}from"@stacksjs/orm";async function n7(J,$){if(!await J0(J))return;try{return await c7.updateTable("gift_cards").set({...$,updated_at:u7(new Date)}).where("id","=",J).execute(),await J0(J)}catch(N){if(N instanceof l7)throw N;if(V9(N))throw new l7(409,"A gift card with this code already exists");if(N instanceof Error)throw Error(`Failed to update gift card: ${N.message}`);throw N}}async function i7(J,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let G=u7(new Date),N=await c7.unsafe(`UPDATE gift_cards
8
+ AND (end_date IS NULL OR end_date >= ?)`,[$,J,$,$]),X=typeof G?.execute==="function"?await G.execute():G;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0){let N=await G0(J);if(N)return{ok:!0,coupon:N};return{ok:!1,reason:"not-found"}}let Z=await G0(J);if(!Z)return{ok:!1,reason:"not-found"};if(!Z.isActive)return{ok:!1,reason:"inactive"};let Y=!Z.startDate||Z.startDate<=$,L=!Z.endDate||Z.endDate>=$;if(!Y||!L)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var H1={};z(H1,{update:()=>$7,store:()=>r4,fetchById:()=>$$,fetchAll:()=>a4,destroy:()=>o4,bulkDestroy:()=>s4});import{db as i4}from"@stacksjs/database";async function o4(J){try{let $=await i4.deleteFrom("customers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function s4(J){if(!J.length)return 0;try{let $=await i4.deleteFrom("customers").where("id","in",J).executeTakeFirst();return F($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as d4}from"@stacksjs/database";async function $$(J){return await d4.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function a4(){return await d4.selectFrom("customers").selectAll().execute()}import{db as Q3}from"@stacksjs/database";import{HttpError as e4}from"@stacksjs/error-handling";import{isUniqueViolation as H3}from"@stacksjs/orm";async function r4(J){try{let $={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await Q3.insertInto("customers").values($).executeTakeFirst();if(!G)throw Error("Failed to create customer");let X=G.insertId||Number(G.numInsertedOrUpdatedRows);return await $$(Number(X))}catch($){if($ instanceof e4)throw $;if(H3($))throw new e4(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as x3}from"@stacksjs/database";import{HttpError as t4}from"@stacksjs/error-handling";import{formatDate as V3,isUniqueViolation as M3}from"@stacksjs/orm";async function $7(J,$){try{if(!J)throw Error("Customer ID is required for update");let G=await x3.updateTable("customers").set({...$,updated_at:V3(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof t4)throw G;if(M3(G))throw new t4(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var B1={};z(B1,{updateStatus:()=>B7,updatePrintCount:()=>A7,update:()=>z7,storePrintDevicesExport:()=>H7,store:()=>V7,getPrinterStatusCounts:()=>F7,fetchErrorsByDeviceId:()=>N7,fetchById:()=>l,fetchAll:()=>J$,exportPrintDevices:()=>G$,downloadPrintDevices:()=>Q7,destroy:()=>G7,countTotalPrints:()=>Z7,countPrintsByDeviceId:()=>Y7,countAll:()=>W7,calculatePrinterHealth:()=>K7,calculateErrorRate:()=>L7,bulkStore:()=>M7,bulkDestroy:()=>X7});import{db as J7}from"@stacksjs/database";async function G7(J){try{let $=await J7.deleteFrom("print_devices").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function X7(J){if(!J.length)return 0;try{let $=await J7.deleteFrom("print_devices").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as z3}from"ts-spreadsheets";import{db as f}from"@stacksjs/database";async function l(J){return await f.selectFrom("print_devices").where("id","=",J).selectAll().executeTakeFirst()}async function J$(){return await f.selectFrom("print_devices").selectAll().execute()}async function W7(){let J=await f.selectFrom("print_devices").select(f.fn.count("id").as("count")).executeTakeFirst();return Number(J?.count||0)}async function Z7(){let J=await f.selectFrom("print_devices").select(f.fn.sum("print_count").as("total")).executeTakeFirst();return Number(J?.total||0)}async function Y7(J){return(await f.selectFrom("print_devices").select("print_count").where("id","=",J).executeTakeFirst())?.print_count??0}async function L7(){let J=await f.selectFrom("receipts").select([f.fn.count("id").as("total"),f.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.failed_count??0)/J.total*100)}async function N7(J){return await f.selectFrom("receipts").where("print_device_id","=",J).where("status","=","failed").selectAll().execute()}async function K7(){let J=await f.selectFrom("print_devices").select([f.fn.count("id").as("total"),f.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.online_count??0)/J.total*100)}async function F7(){return(await f.selectFrom("print_devices").select(["status",f.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,G)=>{return $[G.status]=Number(G.count||0),$},{})}function x1(J,$,G=$){return J?.[$]??J?.[G]}function B3(J){let $=String(J||""),G=/^\d+$/.test($)?Number($):J;return new Date(G)}async function G$(J="csv"){let $=await J$(),G=A3($);return z3(G,{type:J})}function A3(J){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=J.map((X)=>{return[X.id,X.name,x1(X,"macAddress","mac_address"),X.location,X.terminal,X.status,B3(x1(X,"lastPing","last_ping")).toLocaleString(),x1(X,"printCount","print_count")]});return{headings:$,data:G}}async function Q7(J="csv",$){let G=await G$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function H7(J="csv",$){let G=await G$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}var{randomUUIDv7:x7}=globalThis.Bun;import{db as V1}from"@stacksjs/database";async function V7(J){try{let $=x7(),G={last_ping:0,print_count:0,...J,uuid:$};return await V1.insertInto("print_devices").values(G).executeTakeFirst(),await V1.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function M7(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={last_ping:0,print_count:0,...G,uuid:x7()};await V1.insertInto("print_devices").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as M1}from"@stacksjs/database";import{formatDate as z1}from"@stacksjs/orm";async function z7(J,$){if(!await l(J))return;try{return await M1.updateTable("print_devices").set({...$,updated_at:z1(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device: ${X.message}`);throw X}}async function B7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await M1.updateTable("print_devices").set({status:$,updated_at:z1(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device status: ${X.message}`);throw X}}async function A7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await M1.updateTable("print_devices").set({print_count:$,updated_at:z1(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print count: ${X.message}`);throw X}}var O1={};z(O1,{update:()=>E7,unresolveGroup:()=>j7,resolveGroup:()=>q7,ignoreGroup:()=>k7,fetchTimeline:()=>T7,fetchStats:()=>w7,fetchGrouped:()=>P7,fetchById:()=>U7,fetchByGroup:()=>S7,fetchAll:()=>W$,destroyGroup:()=>R7,destroy:()=>_7,bulkUpdateStatus:()=>f7,bulkDestroy:()=>O7});import{db as A1}from"@stacksjs/database";import{log as _1}from"@stacksjs/logging";async function _7(J){try{return await A1.deleteFrom("errors").where("id","=",J).execute(),!0}catch($){return _1.error("[commerce/errors] destroy failed",{id:J,error:$}),!1}}async function O7(J){try{return await A1.deleteFrom("errors").where("id","in",J).execute(),!0}catch($){return _1.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:$}),!1}}async function R7(J,$){try{return await A1.deleteFrom("errors").where("type","=",J).where("message","=",$).execute(),!0}catch(G){return _1.error("[commerce/errors] destroyGroup failed",{type:J,message:$,error:G}),!1}}import{db as X$}from"@stacksjs/database";async function U7(J){return await X$.selectFrom("errors").where("id","=",J).selectAll().executeTakeFirst()}async function W$(){return await X$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function P7(){let J=await X$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let X of J){let W=`${X.type}:${X.message}`;if(!$.has(W))$.set(W,{errors:[],firstSeen:new Date(X.created_at),lastSeen:new Date(X.created_at)});let Z=$.get(W);Z.errors.push(X);let Y=new Date(X.created_at);if(Y<Z.firstSeen)Z.firstSeen=Y;if(Y>Z.lastSeen)Z.lastSeen=Y}let G=[];for(let[X,W]of $){let Z=W.errors[0];if(!Z)continue;let Y=W.errors.find((N)=>N.status!==null)?.status,L="unresolved";if(Y===1)L="resolved";else if(Y===2)L="ignored";G.push({id:Z.id,type:Z.type,message:Z.message,stack:Z.stack,status:L,count:W.errors.length,first_seen:W.firstSeen.toISOString(),last_seen:W.lastSeen.toISOString(),error_ids:W.errors.map((N)=>N.id)})}return G.sort((X,W)=>new Date(W.last_seen).getTime()-new Date(X.last_seen).getTime()),G}async function S7(J,$){return await X$.selectFrom("errors").where("type","=",J).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function w7(){let J=await W$(),$=new Date,G=new Date($.getTime()-86400000),X=new Date($.getTime()-172800000),W=J.filter((L)=>new Date(L.created_at)>=G).length,Z=J.filter((L)=>{let N=new Date(L.created_at);return N>=X&&N<G}).length,Y=Z===0?W>0?100:0:Math.round((W-Z)/Z*100);return{total:J.length,unresolved:J.filter((L)=>L.status===null||L.status===0).length,resolved:J.filter((L)=>L.status===1).length,ignored:J.filter((L)=>L.status===2).length,last_24h:W,trend:Y}}async function T7(){let J=await W$(),$=new Date,G=[];for(let X=23;X>=0;X--){let W=new Date($.getTime()-X*60*60*1000);W.setMinutes(0,0,0);let Z=new Date(W.getTime()+3600000),Y=J.filter((L)=>{let N=new Date(L.created_at);return N>=W&&N<Z}).length;G.push({hour:W.toISOString(),count:Y})}return G}import{db as w0}from"@stacksjs/database";import{sql as T0}from"@stacksjs/database";import{log as E0}from"@stacksjs/logging";async function E7(J,$){try{return await w0.updateTable("errors").set({...$,updated_at:T0.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(G){return E0.error("[commerce/errors] update failed",{id:J,error:G}),!1}}async function f7(J,$){try{return await w0.updateTable("errors").set({status:$,updated_at:T0.raw("CURRENT_TIMESTAMP")}).where("id","in",J).execute(),!0}catch(G){return E0.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:$,error:G}),!1}}async function q7(J,$){try{return await w0.updateTable("errors").set({status:1,updated_at:T0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return E0.error("[commerce/errors] resolveGroup failed",{type:J,message:$,error:G}),!1}}async function k7(J,$){try{return await w0.updateTable("errors").set({status:2,updated_at:T0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return E0.error("[commerce/errors] ignoreGroup failed",{type:J,message:$,error:G}),!1}}async function j7(J,$){try{return await w0.updateTable("errors").set({status:0,updated_at:T0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return E0.error("[commerce/errors] unresolveGroup failed",{type:J,message:$,error:G}),!1}}var U1={};z(U1,{updateBalance:()=>a7,update:()=>d7,store:()=>n7,fetchTotalValue:()=>y7,fetchTotalCurrentBalance:()=>b7,fetchStats:()=>I7,fetchById:()=>X0,fetchByCode:()=>R1,fetchAll:()=>C7,fetchActive:()=>h7,destroy:()=>p7,compareActiveGiftCards:()=>v7,checkBalance:()=>g7,calculateGiftCardValues:()=>D7,bulkDestroy:()=>l7});import{db as m7}from"@stacksjs/database";import{formatDate as KY}from"@stacksjs/orm";import{db as P,sql as C}from"@stacksjs/database";import{formatDate as s,toTimestamp as Q0}from"@stacksjs/orm";import{aggregateFunctions as _3,db as O3}from"@stacksjs/database";async function I(J,$,G){let X=O3.selectFrom(J);if(G)X=G(X);X=X.select(Object.entries($).map(([Y,L])=>{let N=L.column??"id",K=_3[L.kind](N);if(L.filter)K=K.filterWhere(L.filter.column,L.filter.op,L.filter.value);return K.as(Y)}));let W=await X.executeTakeFirst(),Z={};for(let Y of Object.keys($)){let L=W?.[Y];Z[Y]=typeof L==="number"?L:Number(L??0)||0}return Z}async function C7(){return await P.selectFrom("gift_cards").selectAll().execute()}async function X0(J){return await P.selectFrom("gift_cards").where("id","=",J).selectAll().executeTakeFirst()}async function R1(J){return await P.selectFrom("gift_cards").where("code","=",J).selectAll().executeTakeFirst()}async function h7(){return await P.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function I7(){let{count:J}=await I("gift_cards",{count:{kind:"count"}}),$=Q0(new Date),G=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal($)} OR expiry_date IS NULL)`).select(P.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("gift_cards").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute(),{count:W}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:Z}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:Y}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance > 0.75`)),L=new Date;L.setDate(L.getDate()+30);let N=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",Q0(L)).where("expiry_date",">=",$).selectAll().limit(5).execute(),K=await P.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:J,active:Number(G?.count||0),by_status:X.map((Q)=>({status:Q.status,count:Number(Q.count)})),by_balance:{low:W,medium:Z,high:Y},expiring_soon:N,recently_used:K}}async function g7(J){let $=await R1(J);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function v7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let W=new Date(X);W.setDate(X.getDate()-J);let Z=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(Q0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),Y=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(Q0(W))} OR expiry_date IS NULL)`).where("created_at",">=",s(W)).where("created_at","<=",s(X)).executeTakeFirst(),L=Number(Z?.count||0),N=Number(Y?.count||0),K=L-N,Q=N!==0?K/N*100:L>0?100:0;return{current_period:L,previous_period:N,difference:K,percentage_change:Q,days_range:J}}async function D7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let W=new Date(X);W.setDate(X.getDate()-J);let Z=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(Q0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),Y=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(Q0(W))} OR expiry_date IS NULL)`).where("created_at",">=",s(W)).where("created_at","<=",s(X)).executeTakeFirst(),L=Number(Z?.total_initial||0),N=Number(Z?.total_balance||0),K=Number(Z?.card_count||0),Q=Number(Y?.total_initial||0),H=Number(Y?.total_balance||0),x=Number(Y?.card_count||0),_=L>0?(L-N)/L*100:0,R=Q>0?(Q-H)/Q*100:0,O=K>0?L/K:0,U=K>0?N/K:0,m=L-Q,t=N-H,$0=K-x,F0=Q!==0?m/Q*100:L>0?100:0,p=H!==0?t/H*100:N>0?100:0,J3=x!==0?$0/x*100:K>0?100:0;return{current_period:{total_initial_value:L,total_remaining_balance:N,utilization_rate:_,card_count:K,average_initial_value:O,average_remaining_balance:U},previous_period:{total_initial_value:Q,total_remaining_balance:H,utilization_rate:R,card_count:x},comparison:{initial_value:{difference:m,percentage:Math.abs(F0),is_increase:m>=0},balance:{difference:t,percentage:Math.abs(p),is_increase:t>=0},card_count:{difference:$0,percentage:Math.abs(J3),is_increase:$0>=0}},days_range:J}}async function y7(){let{total_value:J}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:J}}async function b7(){let{total_balance:J}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:J}}async function p7(J){let $=await m7.deleteFrom("gift_cards").where("id","=",J).executeTakeFirst();return F($)>0}async function l7(J){if(!J.length)return 0;let $=await m7.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return F($)}var{randomUUIDv7:R3}=globalThis.Bun;import{db as c7}from"@stacksjs/database";import{HttpError as u7}from"@stacksjs/error-handling";import{isUniqueViolation as U3}from"@stacksjs/orm";async function n7(J){let $=J,G={...J,current_balance:$.current_balance??$.initial_balance,status:J.status||"ACTIVE",is_active:$.is_active??!0,uuid:R3()};try{let X=await c7.insertInto("gift_cards").values(G).executeTakeFirst(),W=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if(W)return await c7.selectFrom("gift_cards").where("id","=",W).selectAll().executeTakeFirst();return}catch(X){if(X instanceof u7)throw X;if(U3(X))throw new u7(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 o7}from"@stacksjs/database";import{HttpError as i7}from"@stacksjs/error-handling";import{formatDate as s7,isUniqueViolation as P3}from"@stacksjs/orm";async function d7(J,$){if(!await X0(J))return;try{return await o7.updateTable("gift_cards").set({...$,updated_at:s7(new Date)}).where("id","=",J).execute(),await X0(J)}catch(X){if(X instanceof i7)throw X;if(P3(X))throw new i7(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 a7(J,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let G=s7(new Date),X=await o7.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 oX=Object.defineProperty;var sX=(J)=>J;function dX(J,$){this[J]=sX.bind(null
13
13
  WHERE id = ?
14
14
  AND is_active = 1
15
15
  AND status = 'ACTIVE'
16
- AND current_balance + ? >= 0`,[$,G,$,G,J,$]),X=typeof N?.execute==="function"?await N.execute():N;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0)return await J0(J);let Z=await J0(J);if(!Z)throw Error(`Gift card with ID ${J} not found`);if(!Z.is_active||Z.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var q1={};z(q1,{validateQuantityBounds:()=>w1,validateCouponStacking:()=>UJ,validateCartQuantities:()=>TJ,updateStatus:()=>BJ,updateDeliveryInfo:()=>AJ,update:()=>zJ,storeOrdersExport:()=>t7,store:()=>YJ,softDelete:()=>s7,registerCommerceWebhookHandlers:()=>RJ,recomputeOrderTotals:()=>SJ,placeOrder:()=>xJ,handlePaymentIntentSucceeded:()=>U1,handlePaymentIntentFailed:()=>T1,handleChargeRefunded:()=>P1,findOrderByIdempotencyKey:()=>L$,fetchStats:()=>JJ,fetchDailyOrderTrends:()=>XJ,fetchById:()=>c,fetchAll:()=>$J,exportOrders:()=>X$,emitOrderShipped:()=>W$,emitOrderRefunded:()=>Q0,emitOrderPaid:()=>d,emitOrderDelivered:()=>Z$,emitOrderCreated:()=>w0,emitOrderCancelled:()=>F0,emitForStatus:()=>q0,downloadOrders:()=>r7,destroy:()=>o7,compareOrdersByPeriod:()=>GJ,cleanupAbandonedCarts:()=>PJ,canTransition:()=>P0,calculateOrderMetrics:()=>NJ,bulkSoftDelete:()=>a7,bulkDestroy:()=>d7});import{db as N$}from"@stacksjs/database";async function o7(J){try{let $=await N$.deleteFrom("orders").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function s7(J){try{let $=await N$.updateTable("orders").set({status:"CANCELED"}).where("id","=",J).executeTakeFirst();return Number($.numUpdatedRows)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete order: ${$.message}`);throw $}}async function d7(J){if(!J.length)return 0;try{let $=await N$.deleteFrom("orders").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}async function a7(J){if(!J.length)return 0;try{let $=await N$.updateTable("orders").set({status:"CANCELED"}).where("id","in",J).executeTakeFirst();return Number($.numUpdatedRows)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete orders: ${$.message}`);throw $}}import{db as e7}from"@stacksjs/database";import{createSpreadsheet as x9}from"ts-spreadsheets";async function X$(J="csv"){let $=await z9(),G=B9($);return x9(G,{type:J})}async function z9(){let J=await e7.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),$=J.map((W)=>W.id);if($.length===0)return[];let N=(await e7.selectFrom("order_items").where("order_items.order_id","in",$).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((W,Z)=>{if(!Z.order_id)return W;if(!W[Z.order_id])W[Z.order_id]={totalItems:0,totalPrice:0};return W[Z.order_id].totalItems+=Z.quantity,W[Z.order_id].totalPrice+=Z.price*Z.quantity,W},{});return J.map((W)=>{let Z=N[W.id]||{totalItems:0,totalPrice:0};return{...W,totalItems:Z.totalItems,totalPrice:Z.totalPrice}})}function B9(J){let $=["Order ID","Customer","Date","Total","Status","Items"],G=J.map((N)=>{let X=N.order_items?.map((W)=>`${W.product?.name} (Qty: ${W.quantity}, Price: $${W.price})`).join(" | ")||"No Items";return[N.id,N.customer?.name||"N/A",N.created_at,N.total_amount,N.status,X]});return{headings:$,data:G}}async function r7(J="csv",$){let G=await X$(J),N=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||N)}async function t7(J="csv",$){let G=await X$(J),N=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||N)}import{db as B}from"@stacksjs/database";async function $J(J){let $=B.selectFrom("orders").selectAll().orderBy("created_at","desc");if(J)$=$.limit(J);let G=await $.execute();return await Promise.all(G.map(async(N)=>{let X=await B.selectFrom("order_items").where("order_id","=",N.id).selectAll().execute();return{...N,items:X}}))}async function c(J){return await B.selectFrom("orders").where("id","=",J).selectAll().executeTakeFirst()}async function JJ(){let J=await B.selectFrom("orders").select(B.fn.count("id").as("count")).executeTakeFirst(),$=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).groupBy("status").execute(),G=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).groupBy("order_type").execute(),N=await B.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),X=await Promise.all(N.map(async(Z)=>{let Y=await B.selectFrom("order_items").where("order_id","=",Z.id).selectAll().execute();return{...Z,items:Y}})),W=await B.selectFrom("orders").select(B.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(J?.count||0),by_status:$,by_type:G,recent:X,revenue:Number(W?.total||0)}}async function GJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),Z=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",X.toISOString()).where("created_at","<=",N.toISOString()).executeTakeFirst(),Y=Number(W?.count||0),L=Number(Z?.count||0),K=Y-L,Q=L!==0?K/L*100:Y>0?100:0;return{current_period:Y,previous_period:L,difference:K,percentage_change:Q,days_range:J}}async function NJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),Z=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",X.toISOString()).where("created_at","<=",N.toISOString()).executeTakeFirst(),Y=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("status").execute(),L=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("order_type").execute(),K=Number(W?.total_orders||0),Q=Number(W?.total_revenue||0),M=K>0?Q/K:0,H=Number(Z?.total_orders||0),_=Number(Z?.total_revenue||0),O=H>0?_/H:0,R=K-H,S=Q-_,m=M-O,r=H!==0?R/H*100:K>0?100:0,t=_!==0?S/_*100:Q>0?100:0,L0=O!==0?m/O*100:M>0?100:0;return{current_period:{total_orders:K,total_revenue:Q,average_order_value:M,orders_by_status:Y.map((p)=>({status:p.status,count:Number(p.count)})),orders_by_type:L.map((p)=>({order_type:p.order_type,count:Number(p.count)}))},previous_period:{total_orders:H,total_revenue:_,average_order_value:O},comparison:{orders:{difference:R,percentage:Math.abs(r),is_increase:R>=0},revenue:{difference:S,percentage:Math.abs(t),is_increase:S>=0},average_order_value:{difference:m,percentage:Math.abs(L0),is_increase:m>=0}},days_range:J}}async function XJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=await B.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).orderBy("created_at","asc").execute(),X=new Map;for(let W of N){let Z=(W.created_at||"").split("T")[0]||"unknown",Y=X.get(Z)||{order_count:0,revenue:0};Y.order_count++,Y.revenue+=Number(W.total_amount||0),X.set(Z,Y)}return Array.from(X.entries()).map(([W,Z])=>({date:W,order_count:Z.order_count,revenue:Z.revenue}))}var{randomUUIDv7:A9}=globalThis.Bun;import{db as WJ}from"@stacksjs/database";import{formatDate as ZJ}from"@stacksjs/orm";async function YJ(J){let $={...J,status:J.status||"PENDING",uuid:A9(),created_at:ZJ(new Date),updated_at:ZJ(new Date)};try{let G=await WJ.insertInto("orders").values($).executeTakeFirst(),N=Number(G?.insertId)||Number(G?.numInsertedOrUpdatedRows);if(N)return await WJ.selectFrom("orders").where("id","=",N).selectAll().executeTakeFirst();return}catch(G){if(G instanceof Error)throw Error(`Failed to create order: ${G.message}`);throw G}}M0();var{randomUUIDv7:QJ}=globalThis.Bun;import{db as Y$}from"@stacksjs/database";import{formatDate as U9,isUniqueViolation as MJ}from"@stacksjs/orm";import{sqlHelpers as R9}from"@stacksjs/database";import{env as O9}from"@stacksjs/env";function S9(J,$,G,N){let X=R9(J).param;return{query:`UPDATE products
17
- SET inventory_count = inventory_count + ${X(1)},
18
- updated_at = ${X(2)}
19
- WHERE id = ${X(3)}
20
- AND inventory_count + ${X(4)} >= 0`,parameters:[G,N,$,G]}}async function FJ(J,$,G,N){let X=S9(O9.DB_CONNECTION||"sqlite",$,G,N),W=await J.unsafe(X.query,X.parameters),Z=typeof W?.execute==="function"?await W.execute():W;return F(Z)}var HJ=!1;function VJ(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function L$(J){try{let $=await Y$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await Y$.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(VJ($)){if(!HJ)HJ=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw $}}async function xJ(J){if(J.idempotencyKey){let $=await L$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await Y$.transaction(async(G)=>{let N=U9(new Date),X=QJ(),W={...J.order,status:J.order.status||"PENDING",uuid:X,created_at:N,updated_at:N};await G.insertInto("orders").values(W).executeTakeFirst();let Z=await G.selectFrom("orders").where("uuid","=",X).selectAll().executeTakeFirst(),Y=Number(Z?.id);if(!Number.isSafeInteger(Y)||Y<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let L;if(J.items&&J.items.length>0){let M=J.items.map((H)=>{if(!Number.isInteger(H.productId)||H.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(H.quantity)||H.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(H.price)||H.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:Y,product_id:H.productId,quantity:H.quantity,price:H.price,special_instructions:H.specialInstructions||null,created_at:N,updated_at:N}});await G.insertInto("order_items").values(M).execute(),L=await G.selectFrom("order_items").where("order_id","=",Y).selectAll().execute()}let K;if(J.payment)try{let M=QJ();if(await G.insertInto("payments").values({...J.payment,order_id:Y,uuid:M,created_at:N,updated_at:N}).executeTakeFirst(),K=await G.selectFrom("payments").where("uuid","=",M).selectAll().executeTakeFirst(),!K)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(M){if(MJ(M))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(M,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(J.inventory&&J.inventory.length>0)for(let M=0;M<J.inventory.length;M++){let{id:H,delta:_}=J.inventory[M];if(!Number.isFinite(_)||_===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await FJ(G,H,_,N))throw Object.assign(Error(`inventory adjust failed for product ${H}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:Y,created_at:N}).execute()}catch(M){if(MJ(M))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!VJ(M))throw M}let Q=await G.selectFrom("orders").where("id","=",Y).selectAll().executeTakeFirst();if(!Q)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:Q,items:L,payment:K}});if(w0($.order),$.payment)d($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&J.idempotencyKey){let G=await L$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}M0();import{db as _1}from"@stacksjs/database";import{formatDate as R1}from"@stacksjs/orm";M0();async function zJ(J,$){if(!await c(J))return;try{return await _1.updateTable("orders").set({...$,updated_at:R1(new Date)}).where("id","=",J).execute(),await c(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update order: ${N.message}`);throw N}}async function BJ(J,$){let G=await c(J);if(!G)throw Error(`Order with ID ${J} not found`);let N=G.status??"PENDING";if(!P0(N,$))throw Error(`[commerce/orders] illegal status transition ${N} \u2192 ${$}`);try{await _1.updateTable("orders").set({status:$,updated_at:R1(new Date)}).where("id","=",J).execute();let X=await c(J);if(X)q0($,X);return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order status: ${X.message}`);throw X}}async function AJ(J,$,G){let N=await c(J);if(!N)throw Error(`Order with ID ${J} not found`);let X={updated_at:R1(new Date)};if($!==void 0)X.delivery_address=$;if(G!==void 0)X.estimated_delivery_time=G;if(Object.keys(X).length===1)return N;try{return await _1.updateTable("orders").set(X).where("id","=",J).execute(),await c(J)}catch(W){if(W instanceof Error)throw TypeError(`Failed to update delivery information: ${W.message}`);throw W}}M0();import{db as H0}from"@stacksjs/database";import{formatDate as K$}from"@stacksjs/orm";async function O1(J){let $=await H0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await H0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var _J=!1;function T9(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function S1(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:K$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(T9(G)){if(!_J)_J=!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 U1(J){let G=J.data.object?.id;if(!G)return;await H0.transaction(async(X)=>{if(!await S1(J.id,X))return;let Z=await X.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Z)return;let Y=K$(new Date);await X.updateTable("payments").set({status:"succeeded",updated_at:Y}).where("id","=",Z.id).execute();let L=await X.selectFrom("orders").where("id","=",Z.order_id).selectAll().executeTakeFirst();if(L&&L.status==="PENDING")await X.updateTable("orders").set({status:"PROCESSING",updated_at:Y}).where("id","=",L.id).execute()});let N=await O1(G);if(N)await d(N)}async function T1(J){let $=J.data.object,G=$?.id;if(!G)return;let X=$?.last_payment_error?.message??"payment failed";await H0.transaction(async(Z)=>{if(!await S1(J.id,Z))return;let L=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let K=K$(new Date);await Z.updateTable("payments").set({status:"failed",failure_reason:X,updated_at:K}).where("id","=",L.id).execute();let Q=await Z.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(Q&&Q.status==="PENDING")await Z.updateTable("orders").set({status:"CANCELLED",updated_at:K}).where("id","=",Q.id).execute()});let W=await O1(G);if(W)await F0(W,X)}async function P1(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let N=$?.amount_refunded??0;await H0.transaction(async(W)=>{if(!await S1(J.id,W))return;let Y=await W.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Y)return;let L=K$(new Date);await W.updateTable("payments").set({status:"refunded",refund_amount:N,updated_at:L}).where("id","=",Y.id).execute();let K=await W.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(K&&K.status!=="REFUNDED")await W.updateTable("orders").set({status:"REFUNDED",updated_at:L}).where("id","=",K.id).execute()});let X=await O1(G);if(X)await Q0(X,N)}async function RJ(){let J=await import("@stacksjs/payments").catch(()=>null);if(!J)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:G}=J;if(typeof $!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:U1,failed:T1}),G({refunded:P1}),()=>{}}import{db as OJ}from"@stacksjs/database";async function P9(J){if(J.length===0)return new Map;let $=await OJ.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),G=new Map;for(let N of $){let X=Number(N.price);if(Number.isFinite(X))G.set(N.id,Math.round(X))}return G}async function w9(J){try{let $=await OJ.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),G=Number($?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function SJ(J){let $=J.items.map((O)=>O.productId),G=await P9($),N=J.taxRateId!=null?await w9(J.taxRateId):0,X=0,W=[];for(let O of J.items){let R=O.unitPriceCents??G.get(O.productId)??0,S=Math.round(R*O.quantity);X+=S,W.push({productId:O.productId,quantity:O.quantity,unitPriceCents:R,lineCents:S})}let Z=Math.max(0,J.discountCents??0),Y=Math.max(0,X-Z),L=Math.round(Y*N),K=Math.max(0,J.shippingCents??0),Q=X-Z+L+K,M=J.maxDriftCents??5,H=!1,_=0;if(J.clientTotalCents!=null)_=Math.abs(Q-J.clientTotalCents),H=_>M;return{subtotalCents:X,discountCents:Z,taxCents:L,shippingCents:K,totalCents:Q,resolvedItems:W,priceChanged:H,diffCents:_}}import{db as F$}from"@stacksjs/database";function UJ(J,$={}){let G=J.length;if(G<=1)return{ok:!0,count:G};if(!$.allowMultiple)return{ok:!1,count:G,reason:"multiple-not-allowed"};let N=$.maxStacked??Number.POSITIVE_INFINITY;if(G>N)return{ok:!1,count:G,reason:"exceeds-max-stacked"};return{ok:!0,count:G}}async function w1(J,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:J,quantity:$,reason:"non-positive"};let G;try{G=await F$.selectFrom("products").where("id","=",J).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:J,quantity:$}}if(!G)return{ok:!1,productId:J,quantity:$,reason:"product-missing"};let N=G.min_order_qty??null,X=G.max_order_qty??null;if(N!=null&&$<N)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:N};if(X!=null&&$>X)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:X};return{ok:!0,productId:J,quantity:$}}async function TJ(J){for(let G of J){let N=await w1(G.productId,G.quantity);if(!N.ok)return N}let $=J[J.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function PJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,X=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let W=await F$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[X,X,G]),Z=typeof W?.execute==="function"?await W.execute():W;return{deleted:Number(Z?.changes??Z?.numDeletedRows??Z?.[0]?.numDeletedRows??Z?.affectedRows??0),cutoffAt:X}}catch{try{let W=await F$.selectFrom("carts").where("updated_at","<",X).select(["id"]).limit(G).execute();if(W.length===0)return{deleted:0,cutoffAt:X};let Z=W.map((K)=>K.id),Y=await F$.deleteFrom("carts").where("id","in",Z).execute();return{deleted:Number(Y?.numDeletedRows??Y?.[0]?.numDeletedRows??Y?.affectedRows??W.length),cutoffAt:X}}catch{return{deleted:0,cutoffAt:X}}}}var f1={};z(f1,{update:()=>DJ,store:()=>gJ,recordRefund:()=>bJ,fetchPaymentStatsByMethod:()=>jJ,fetchPaymentStats:()=>kJ,fetchMonthlyPaymentTrends:()=>CJ,fetchById:()=>N0,fetchAll:()=>EJ,destroy:()=>qJ,bulkDestroy:()=>fJ});import{db as wJ}from"@stacksjs/database";async function qJ(J){try{let $=await wJ.deleteFrom("payments").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function fJ(J){if(!J.length)return 0;try{let $=await wJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as f}from"@stacksjs/database";import{formatDate as v}from"@stacksjs/orm";async function EJ(){return await f.selectFrom("payments").selectAll().execute()}async function N0(J){return await f.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function kJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await f.selectFrom("payments").select([f.fn.count("id").as("transaction_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),Z=await f.selectFrom("payments").select([f.fn.count("id").as("transaction_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(X)).where("created_at","<=",v(N)).where("status","=","completed").executeTakeFirst(),Y=await f.selectFrom("payments").select(f.fn.count("id").as("count")).where("created_at",">=",v(G)).where("created_at","<=",v($)).executeTakeFirst(),L=Number(W?.transaction_count||0),K=Number(W?.total_revenue||0),Q=L>0?K/L:0,M=Number(Z?.transaction_count||0),H=Number(Z?.total_revenue||0),_=M>0?H/M:0,O=L-M,R=K-H,S=Q-_,m=M>0?O/M*100:L>0?100:0,r=H>0?R/H*100:K>0?100:0,t=_>0?S/_*100:Q>0?100:0,L0=Number(Y?.count||0),p=L0>0?L/L0*100:0;return{total_transactions:L,total_revenue:K,average_transaction:Q,successful_rate:p,comparison:{transactions:{difference:O,percentage:Math.abs(m),is_increase:O>=0},revenue:{difference:R,percentage:Math.abs(r),is_increase:R>=0},average:{difference:S,percentage:Math.abs(t),is_increase:S>=0}}}}async function jJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=await f.selectFrom("payments").select([f.fn.count("id").as("total_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),X=Number(N?.total_count||0),W=await f.selectFrom("payments").select(["method",f.fn.count("id").as("count"),f.fn.sum("amount").as("revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").groupBy("method").execute(),Z={};return W.forEach((Y)=>{let L=Number(Y.count||0),K=Number(Y.revenue||0),Q=X>0?L/X*100:0;Z[Y.method]={count:L,revenue:K,percentage_of_total:Q}}),Z}async function CJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await f.selectFrom("payments").selectAll().where("created_at",">=",v($)).where("status","=","completed").execute(),N={};for(let W of G){let Z=W.created_at?new Date(W.created_at):new Date,Y=Z.getFullYear(),L=Z.getMonth()+1,K=`${Y}-${String(L).padStart(2,"0")}`;if(!N[K])N[K]={year:Y,month:L,transactions:0,revenue:0};N[K].transactions++,N[K].revenue+=Number(W.amount||0)}return Object.keys(N).sort().map((W)=>{let Z=N[W],Y=Z.transactions,L=Z.revenue,K=Y>0?L/Y:0;return{month:new Date(Z.year,Z.month-1,1).toLocaleString("default",{month:"short"}),year:Z.year,transactions:Y,revenue:L,average:K}})}var{randomUUIDv7:q9}=globalThis.Bun;import{db as hJ}from"@stacksjs/database";import{HttpError as IJ}from"@stacksjs/error-handling";import{isUniqueViolation as f9}from"@stacksjs/orm";async function gJ(J){let $=q9(),G={...J,status:J.status||"pending",currency:J.currency||"USD",uuid:$};try{return await hJ.insertInto("payments").values(G).executeTakeFirst(),await hJ.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(N){if(N instanceof IJ)throw N;if(f9(N))throw new IJ(409,"A payment with this transaction ID already exists");if(N instanceof Error){if(N.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${N.message}`)}throw N}}import{db as vJ,sqlHelpers as E9}from"@stacksjs/database";import{env as k9}from"@stacksjs/env";import{formatDate as yJ}from"@stacksjs/orm";async function DJ(J,$){if(!await N0(J))return;try{return await vJ.updateTable("payments").set({...$,updated_at:yJ(new Date)}).where("id","=",J).execute(),await N0(J)}catch(N){if(N instanceof Error){if(N.message.includes("Duplicate entry")&&N.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${N.message}`)}throw N}}var j9=new Set(["completed","succeeded","partiallyRefunded"]);async function bJ(J,$){if(!Number.isSafeInteger(J)||J<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger($)||$<=0)throw TypeError("Refund amount must be a positive integer in minor units");let N=E9(k9.DB_CONNECTION||"sqlite").param,X=yJ(new Date),W=await vJ.unsafe(`UPDATE payments
21
- SET refund_amount = COALESCE(refund_amount, 0) + ${N(1)},
22
- status = CASE WHEN COALESCE(refund_amount, 0) + ${N(2)} = amount
16
+ AND current_balance + ? >= 0`,[$,G,$,G,J,$]),W=typeof X?.execute==="function"?await X.execute():X;if(Number(W?.changes??W?.numUpdatedRows??W?.affectedRows??0)>0)return await X0(J);let Y=await X0(J);if(!Y)throw Error(`Gift card with ID ${J} not found`);if(!Y.is_active||Y.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var j1={};z(j1,{validateQuantityBounds:()=>k1,validateCouponStacking:()=>EJ,validateCartQuantities:()=>fJ,updateStatus:()=>RJ,updateDeliveryInfo:()=>UJ,update:()=>OJ,storeOrdersExport:()=>XJ,store:()=>QJ,softDelete:()=>r7,registerCommerceWebhookHandlers:()=>SJ,recomputeOrderTotals:()=>TJ,placeOrder:()=>_J,handlePaymentIntentSucceeded:()=>E1,handlePaymentIntentFailed:()=>f1,handleChargeRefunded:()=>q1,findOrderByIdempotencyKey:()=>F$,fetchStats:()=>ZJ,fetchDailyOrderTrends:()=>NJ,fetchById:()=>c,fetchAll:()=>WJ,exportOrders:()=>Y$,emitOrderShipped:()=>L$,emitOrderRefunded:()=>x0,emitOrderPaid:()=>d,emitOrderDelivered:()=>N$,emitOrderCreated:()=>q0,emitOrderCancelled:()=>H0,emitForStatus:()=>k0,downloadOrders:()=>GJ,destroy:()=>e7,compareOrdersByPeriod:()=>YJ,cleanupAbandonedCarts:()=>qJ,canTransition:()=>f0,calculateOrderMetrics:()=>LJ,bulkSoftDelete:()=>$J,bulkDestroy:()=>t7});import{db as Z$}from"@stacksjs/database";async function e7(J){try{let $=await Z$.deleteFrom("orders").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function r7(J){try{let $=await Z$.updateTable("orders").set({status:"CANCELED"}).where("id","=",J).executeTakeFirst();return Number($.numUpdatedRows)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete order: ${$.message}`);throw $}}async function t7(J){if(!J.length)return 0;try{let $=await Z$.deleteFrom("orders").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}async function $J(J){if(!J.length)return 0;try{let $=await Z$.updateTable("orders").set({status:"CANCELED"}).where("id","in",J).executeTakeFirst();return Number($.numUpdatedRows)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete orders: ${$.message}`);throw $}}import{db as JJ}from"@stacksjs/database";import{createSpreadsheet as S3}from"ts-spreadsheets";async function Y$(J="csv"){let $=await w3(),G=T3($);return S3(G,{type:J})}async function w3(){let J=await JJ.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),$=J.map((Z)=>Z.id);if($.length===0)return[];let X=(await JJ.selectFrom("order_items").where("order_items.order_id","in",$).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((Z,Y)=>{if(!Y.order_id)return Z;if(!Z[Y.order_id])Z[Y.order_id]={totalItems:0,totalPrice:0};return Z[Y.order_id].totalItems+=Y.quantity,Z[Y.order_id].totalPrice+=Y.price*Y.quantity,Z},{});return J.map((Z)=>{let Y=X[Z.id]||{totalItems:0,totalPrice:0};return{...Z,totalItems:Y.totalItems,totalPrice:Y.totalPrice}})}function T3(J){let $=["Order ID","Customer","Date","Total","Status","Items"],G=J.map((X)=>{let W=X.order_items?.map((Z)=>`${Z.product?.name} (Qty: ${Z.quantity}, Price: $${Z.price})`).join(" | ")||"No Items";return[X.id,X.customer?.name||"N/A",X.created_at,X.total_amount,X.status,W]});return{headings:$,data:G}}async function GJ(J="csv",$){let G=await Y$(J),X=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function XJ(J="csv",$){let G=await Y$(J),X=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}import{db as B}from"@stacksjs/database";async function WJ(J){let $=B.selectFrom("orders").selectAll().orderBy("created_at","desc");if(J)$=$.limit(J);let G=await $.execute();return await Promise.all(G.map(async(X)=>{let W=await B.selectFrom("order_items").where("order_id","=",X.id).selectAll().execute();return{...X,items:W}}))}async function c(J){return await B.selectFrom("orders").where("id","=",J).selectAll().executeTakeFirst()}async function ZJ(){let J=await B.selectFrom("orders").select(B.fn.count("id").as("count")).executeTakeFirst(),$=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).groupBy("status").execute(),G=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).groupBy("order_type").execute(),X=await B.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),W=await Promise.all(X.map(async(Y)=>{let L=await B.selectFrom("order_items").where("order_id","=",Y.id).selectAll().execute();return{...Y,items:L}})),Z=await B.selectFrom("orders").select(B.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(J?.count||0),by_status:$,by_type:G,recent:W,revenue:Number(Z?.total||0)}}async function YJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let W=new Date(X);W.setDate(X.getDate()-J);let Z=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),Y=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",W.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),L=Number(Z?.count||0),N=Number(Y?.count||0),K=L-N,Q=N!==0?K/N*100:L>0?100:0;return{current_period:L,previous_period:N,difference:K,percentage_change:Q,days_range:J}}async function LJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let W=new Date(X);W.setDate(X.getDate()-J);let Z=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),Y=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",W.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),L=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("status").execute(),N=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("order_type").execute(),K=Number(Z?.total_orders||0),Q=Number(Z?.total_revenue||0),H=K>0?Q/K:0,x=Number(Y?.total_orders||0),_=Number(Y?.total_revenue||0),R=x>0?_/x:0,O=K-x,U=Q-_,m=H-R,t=x!==0?O/x*100:K>0?100:0,$0=_!==0?U/_*100:Q>0?100:0,F0=R!==0?m/R*100:H>0?100:0;return{current_period:{total_orders:K,total_revenue:Q,average_order_value:H,orders_by_status:L.map((p)=>({status:p.status,count:Number(p.count)})),orders_by_type:N.map((p)=>({order_type:p.order_type,count:Number(p.count)}))},previous_period:{total_orders:x,total_revenue:_,average_order_value:R},comparison:{orders:{difference:O,percentage:Math.abs(t),is_increase:O>=0},revenue:{difference:U,percentage:Math.abs($0),is_increase:U>=0},average_order_value:{difference:m,percentage:Math.abs(F0),is_increase:m>=0}},days_range:J}}async function NJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=await B.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).orderBy("created_at","asc").execute(),W=new Map;for(let Z of X){let Y=(Z.created_at||"").split("T")[0]||"unknown",L=W.get(Y)||{order_count:0,revenue:0};L.order_count++,L.revenue+=Number(Z.total_amount||0),W.set(Y,L)}return Array.from(W.entries()).map(([Z,Y])=>({date:Z,order_count:Y.order_count,revenue:Y.revenue}))}var{randomUUIDv7:E3}=globalThis.Bun;import{db as KJ}from"@stacksjs/database";import{formatDate as FJ}from"@stacksjs/orm";async function QJ(J){let $={...J,status:J.status||"PENDING",uuid:E3(),created_at:FJ(new Date),updated_at:FJ(new Date)};try{let G=await KJ.insertInto("orders").values($).executeTakeFirst(),X=Number(G?.insertId)||Number(G?.numInsertedOrUpdatedRows);if(X)return await KJ.selectFrom("orders").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof Error)throw Error(`Failed to create order: ${G.message}`);throw G}}V0();var{randomUUIDv7:MJ}=globalThis.Bun;import{db as K$}from"@stacksjs/database";import{formatDate as C3,isUniqueViolation as zJ}from"@stacksjs/orm";import{sqlHelpers as q3}from"@stacksjs/database";import{env as k3}from"@stacksjs/env";function j3(J,$,G,X){let W=q3(J).param;return{query:`UPDATE products
17
+ SET inventory_count = inventory_count + ${W(1)},
18
+ updated_at = ${W(2)}
19
+ WHERE id = ${W(3)}
20
+ AND inventory_count + ${W(4)} >= 0`,parameters:[G,X,$,G]}}async function VJ(J,$,G,X){let W=j3(k3.DB_CONNECTION||"sqlite",$,G,X),Z=await J.unsafe(W.query,W.parameters),Y=typeof Z?.execute==="function"?await Z.execute():Z;return F(Y)}var BJ=!1;function AJ(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function F$(J){try{let $=await K$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await K$.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(AJ($)){if(!BJ)BJ=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw $}}async function _J(J){if(J.idempotencyKey){let $=await F$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await K$.transaction(async(G)=>{let X=C3(new Date),W=MJ(),Z={...J.order,status:J.order.status||"PENDING",uuid:W,created_at:X,updated_at:X};await G.insertInto("orders").values(Z).executeTakeFirst();let Y=await G.selectFrom("orders").where("uuid","=",W).selectAll().executeTakeFirst(),L=Number(Y?.id);if(!Number.isSafeInteger(L)||L<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let N;if(J.items&&J.items.length>0){let H=J.items.map((x)=>{if(!Number.isInteger(x.productId)||x.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(x.quantity)||x.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(x.price)||x.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:L,product_id:x.productId,quantity:x.quantity,price:x.price,special_instructions:x.specialInstructions||null,created_at:X,updated_at:X}});await G.insertInto("order_items").values(H).execute(),N=await G.selectFrom("order_items").where("order_id","=",L).selectAll().execute()}let K;if(J.payment)try{let H=MJ();if(await G.insertInto("payments").values({...J.payment,order_id:L,uuid:H,created_at:X,updated_at:X}).executeTakeFirst(),K=await G.selectFrom("payments").where("uuid","=",H).selectAll().executeTakeFirst(),!K)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(H){if(zJ(H))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(H,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(J.inventory&&J.inventory.length>0)for(let H=0;H<J.inventory.length;H++){let{id:x,delta:_}=J.inventory[H];if(!Number.isFinite(_)||_===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await VJ(G,x,_,X))throw Object.assign(Error(`inventory adjust failed for product ${x}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:L,created_at:X}).execute()}catch(H){if(zJ(H))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!AJ(H))throw H}let Q=await G.selectFrom("orders").where("id","=",L).selectAll().executeTakeFirst();if(!Q)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:Q,items:N,payment:K}});if(q0($.order),$.payment)d($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&J.idempotencyKey){let G=await F$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}V0();import{db as P1}from"@stacksjs/database";import{formatDate as S1}from"@stacksjs/orm";V0();async function OJ(J,$){if(!await c(J))return;try{return await P1.updateTable("orders").set({...$,updated_at:S1(new Date)}).where("id","=",J).execute(),await c(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order: ${X.message}`);throw X}}async function RJ(J,$){let G=await c(J);if(!G)throw Error(`Order with ID ${J} not found`);let X=G.status??"PENDING";if(!f0(X,$))throw Error(`[commerce/orders] illegal status transition ${X} \u2192 ${$}`);try{await P1.updateTable("orders").set({status:$,updated_at:S1(new Date)}).where("id","=",J).execute();let W=await c(J);if(W)k0($,W);return W}catch(W){if(W instanceof Error)throw TypeError(`Failed to update order status: ${W.message}`);throw W}}async function UJ(J,$,G){let X=await c(J);if(!X)throw Error(`Order with ID ${J} not found`);let W={updated_at:S1(new Date)};if($!==void 0)W.delivery_address=$;if(G!==void 0)W.estimated_delivery_time=G;if(Object.keys(W).length===1)return X;try{return await P1.updateTable("orders").set(W).where("id","=",J).execute(),await c(J)}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update delivery information: ${Z.message}`);throw Z}}V0();import{db as M0}from"@stacksjs/database";import{formatDate as Q$}from"@stacksjs/orm";async function w1(J){let $=await M0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await M0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var PJ=!1;function h3(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function T1(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:Q$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(h3(G)){if(!PJ)PJ=!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 E1(J){let G=J.data.object?.id;if(!G)return;await M0.transaction(async(W)=>{if(!await T1(J.id,W))return;let Y=await W.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Y)return;let L=Q$(new Date);await W.updateTable("payments").set({status:"succeeded",updated_at:L}).where("id","=",Y.id).execute();let N=await W.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await W.updateTable("orders").set({status:"PROCESSING",updated_at:L}).where("id","=",N.id).execute()});let X=await w1(G);if(X)await d(X)}async function f1(J){let $=J.data.object,G=$?.id;if(!G)return;let W=$?.last_payment_error?.message??"payment failed";await M0.transaction(async(Y)=>{if(!await T1(J.id,Y))return;let N=await Y.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!N)return;let K=Q$(new Date);await Y.updateTable("payments").set({status:"failed",failure_reason:W,updated_at:K}).where("id","=",N.id).execute();let Q=await Y.selectFrom("orders").where("id","=",N.order_id).selectAll().executeTakeFirst();if(Q&&Q.status==="PENDING")await Y.updateTable("orders").set({status:"CANCELLED",updated_at:K}).where("id","=",Q.id).execute()});let Z=await w1(G);if(Z)await H0(Z,W)}async function q1(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let X=$?.amount_refunded??0;await M0.transaction(async(Z)=>{if(!await T1(J.id,Z))return;let L=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let N=Q$(new Date);await Z.updateTable("payments").set({status:"refunded",refund_amount:X,updated_at:N}).where("id","=",L.id).execute();let K=await Z.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(K&&K.status!=="REFUNDED")await Z.updateTable("orders").set({status:"REFUNDED",updated_at:N}).where("id","=",K.id).execute()});let W=await w1(G);if(W)await x0(W,X)}async function SJ(){let J=await import("@stacksjs/payments").catch(()=>null);if(!J)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:G}=J;if(typeof $!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:E1,failed:f1}),G({refunded:q1}),()=>{}}import{db as wJ}from"@stacksjs/database";async function I3(J){if(J.length===0)return new Map;let $=await wJ.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),G=new Map;for(let X of $){let W=Number(X.price);if(Number.isFinite(W))G.set(X.id,Math.round(W))}return G}async function g3(J){try{let $=await wJ.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),G=Number($?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function TJ(J){let $=J.items.map((R)=>R.productId),G=await I3($),X=J.taxRateId!=null?await g3(J.taxRateId):0,W=0,Z=[];for(let R of J.items){let O=R.unitPriceCents??G.get(R.productId)??0,U=Math.round(O*R.quantity);W+=U,Z.push({productId:R.productId,quantity:R.quantity,unitPriceCents:O,lineCents:U})}let Y=Math.max(0,J.discountCents??0),L=Math.max(0,W-Y),N=Math.round(L*X),K=Math.max(0,J.shippingCents??0),Q=W-Y+N+K,H=J.maxDriftCents??5,x=!1,_=0;if(J.clientTotalCents!=null)_=Math.abs(Q-J.clientTotalCents),x=_>H;return{subtotalCents:W,discountCents:Y,taxCents:N,shippingCents:K,totalCents:Q,resolvedItems:Z,priceChanged:x,diffCents:_}}import{db as H$}from"@stacksjs/database";function EJ(J,$={}){let G=J.length;if(G<=1)return{ok:!0,count:G};if(!$.allowMultiple)return{ok:!1,count:G,reason:"multiple-not-allowed"};let X=$.maxStacked??Number.POSITIVE_INFINITY;if(G>X)return{ok:!1,count:G,reason:"exceeds-max-stacked"};return{ok:!0,count:G}}async function k1(J,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:J,quantity:$,reason:"non-positive"};let G;try{G=await H$.selectFrom("products").where("id","=",J).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:J,quantity:$}}if(!G)return{ok:!1,productId:J,quantity:$,reason:"product-missing"};let X=G.min_order_qty??null,W=G.max_order_qty??null;if(X!=null&&$<X)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:X};if(W!=null&&$>W)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:W};return{ok:!0,productId:J,quantity:$}}async function fJ(J){for(let G of J){let X=await k1(G.productId,G.quantity);if(!X.ok)return X}let $=J[J.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function qJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,W=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let Z=await H$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[W,W,G]),Y=typeof Z?.execute==="function"?await Z.execute():Z;return{deleted:Number(Y?.changes??Y?.numDeletedRows??Y?.[0]?.numDeletedRows??Y?.affectedRows??0),cutoffAt:W}}catch{try{let Z=await H$.selectFrom("carts").where("updated_at","<",W).select(["id"]).limit(G).execute();if(Z.length===0)return{deleted:0,cutoffAt:W};let Y=Z.map((K)=>K.id),L=await H$.deleteFrom("carts").where("id","in",Y).execute();return{deleted:Number(L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??Z.length),cutoffAt:W}}catch{return{deleted:0,cutoffAt:W}}}}var C1={};z(C1,{update:()=>lJ,store:()=>bJ,recordRefund:()=>cJ,fetchPaymentStatsByMethod:()=>gJ,fetchPaymentStats:()=>IJ,fetchMonthlyPaymentTrends:()=>vJ,fetchById:()=>Z0,fetchAll:()=>hJ,destroy:()=>jJ,bulkDestroy:()=>CJ});import{db as kJ}from"@stacksjs/database";async function jJ(J){try{let $=await kJ.deleteFrom("payments").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function CJ(J){if(!J.length)return 0;try{let $=await kJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as q}from"@stacksjs/database";import{formatDate as v}from"@stacksjs/orm";async function hJ(){return await q.selectFrom("payments").selectAll().execute()}async function Z0(J){return await q.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function IJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let W=new Date(X);W.setDate(X.getDate()-J);let Z=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),Y=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(W)).where("created_at","<=",v(X)).where("status","=","completed").executeTakeFirst(),L=await q.selectFrom("payments").select(q.fn.count("id").as("count")).where("created_at",">=",v(G)).where("created_at","<=",v($)).executeTakeFirst(),N=Number(Z?.transaction_count||0),K=Number(Z?.total_revenue||0),Q=N>0?K/N:0,H=Number(Y?.transaction_count||0),x=Number(Y?.total_revenue||0),_=H>0?x/H:0,R=N-H,O=K-x,U=Q-_,m=H>0?R/H*100:N>0?100:0,t=x>0?O/x*100:K>0?100:0,$0=_>0?U/_*100:Q>0?100:0,F0=Number(L?.count||0),p=F0>0?N/F0*100:0;return{total_transactions:N,total_revenue:K,average_transaction:Q,successful_rate:p,comparison:{transactions:{difference:R,percentage:Math.abs(m),is_increase:R>=0},revenue:{difference:O,percentage:Math.abs(t),is_increase:O>=0},average:{difference:U,percentage:Math.abs($0),is_increase:U>=0}}}}async function gJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=await q.selectFrom("payments").select([q.fn.count("id").as("total_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),W=Number(X?.total_count||0),Z=await q.selectFrom("payments").select(["method",q.fn.count("id").as("count"),q.fn.sum("amount").as("revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").groupBy("method").execute(),Y={};return Z.forEach((L)=>{let N=Number(L.count||0),K=Number(L.revenue||0),Q=W>0?N/W*100:0;Y[L.method]={count:N,revenue:K,percentage_of_total:Q}}),Y}async function vJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await q.selectFrom("payments").selectAll().where("created_at",">=",v($)).where("status","=","completed").execute(),X={};for(let Z of G){let Y=Z.created_at?new Date(Z.created_at):new Date,L=Y.getFullYear(),N=Y.getMonth()+1,K=`${L}-${String(N).padStart(2,"0")}`;if(!X[K])X[K]={year:L,month:N,transactions:0,revenue:0};X[K].transactions++,X[K].revenue+=Number(Z.amount||0)}return Object.keys(X).sort().map((Z)=>{let Y=X[Z],L=Y.transactions,N=Y.revenue,K=L>0?N/L:0;return{month:new Date(Y.year,Y.month-1,1).toLocaleString("default",{month:"short"}),year:Y.year,transactions:L,revenue:N,average:K}})}var{randomUUIDv7:v3}=globalThis.Bun;import{db as DJ}from"@stacksjs/database";import{HttpError as yJ}from"@stacksjs/error-handling";import{isUniqueViolation as D3}from"@stacksjs/orm";async function bJ(J){let $=v3(),G={...J,status:J.status||"pending",currency:J.currency||"USD",uuid:$};try{return await DJ.insertInto("payments").values(G).executeTakeFirst(),await DJ.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(X){if(X instanceof yJ)throw X;if(D3(X))throw new yJ(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 mJ,sqlHelpers as y3}from"@stacksjs/database";import{env as b3}from"@stacksjs/env";import{formatDate as pJ}from"@stacksjs/orm";async function lJ(J,$){if(!await Z0(J))return;try{return await mJ.updateTable("payments").set({...$,updated_at:pJ(new Date)}).where("id","=",J).execute(),await Z0(J)}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${X.message}`)}throw X}}var m3=new Set(["completed","succeeded","partiallyRefunded"]);async function cJ(J,$){if(!Number.isSafeInteger(J)||J<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger($)||$<=0)throw TypeError("Refund amount must be a positive integer in minor units");let X=y3(b3.DB_CONNECTION||"sqlite").param,W=pJ(new Date),Z=await mJ.unsafe(`UPDATE payments
21
+ SET refund_amount = COALESCE(refund_amount, 0) + ${X(1)},
22
+ status = CASE WHEN COALESCE(refund_amount, 0) + ${X(2)} = amount
23
23
  THEN 'refunded' ELSE 'partiallyRefunded' END,
24
- updated_at = ${N(3)}
25
- WHERE id = ${N(4)}
24
+ updated_at = ${X(3)}
25
+ WHERE id = ${X(4)}
26
26
  AND status IN ('completed', 'succeeded', 'partiallyRefunded')
27
- AND COALESCE(refund_amount, 0) + ${N(5)} <= amount`,[$,$,X,J,$]),Z=typeof W?.execute==="function"?await W.execute():W;if(Number(Z?.numUpdatedRows??Z?.[0]?.numUpdatedRows??Z?.numAffectedRows??Z?.affectedRows??Z?.[0]?.affectedRows??Z?.changes??0)>0){let H=await N0(J);if(H)return H;throw Error(`Payment with ID ${J} disappeared during refund`)}let L=await N0(J);if(!L)throw Error(`Payment with ID ${J} not found`);let K=String(L.status||"");if(!j9.has(K))throw Error(`Payment status ${K||"unknown"} cannot be refunded`);let Q=L,M=Number(L.amount||0)-Number(Q.refundAmount??Q.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${M} minor units`)}var g1={};z(g1,{variants:()=>R$,units:()=>_$,reviews:()=>z$,manufacturers:()=>x$,items:()=>V$,default:()=>l9,categories:()=>H$});var H$={};z(H$,{updateParent:()=>X6,updateDisplayOrder:()=>G6,updateActiveStatus:()=>N6,update:()=>J6,store:()=>k1,removeChildCategories:()=>aJ,remove:()=>sJ,findOrCreateByName:()=>$6,fetchStats:()=>nJ,fetchRootCategories:()=>lJ,fetchChildCategories:()=>cJ,fetchCategoryTree:()=>oJ,fetchByName:()=>mJ,fetchById:()=>E,fetchByDisplayOrder:()=>uJ,fetchAll:()=>E1,fetchActive:()=>pJ,deactivateChildCategories:()=>rJ,deactivate:()=>eJ,compareCategoryGrowth:()=>iJ,bulkRemove:()=>dJ});import{db as V0}from"@stacksjs/database";import{db as T}from"@stacksjs/database";import{formatDate as f0}from"@stacksjs/orm";async function E1(){return await T.selectFrom("categories").selectAll().execute()}async function E(J){return await T.selectFrom("categories").where("id","=",J).selectAll().executeTakeFirst()}async function mJ(J){return await T.selectFrom("categories").where("name","=",J).selectAll().executeTakeFirst()}async function pJ(){return await T.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function lJ(){return await T.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function cJ(J){return await T.selectFrom("categories").where("parent_category_id","=",J).where("is_active","=",!0).selectAll().execute()}async function uJ(J=!0){let $=T.selectFrom("categories").where("is_active","=",!0).selectAll();if(J)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function nJ(){let J=await T.selectFrom("categories").select(T.fn.count("id").as("count")).executeTakeFirst(),$=await T.selectFrom("categories").where("is_active","=",!0).select(T.fn.count("id").as("count")).executeTakeFirst(),G=await T.selectFrom("categories").whereNull("parent_category_id").select(T.fn.count("id").as("count")).executeTakeFirst(),N=await T.selectFrom("categories").whereNotNull("image_url").select(T.fn.count("id").as("count")).executeTakeFirst(),X=new Date;X.setDate(X.getDate()-30);let W=f0(X),Z=await T.selectFrom("categories").where("created_at",">=",W).selectAll().limit(5).execute(),Y=await T.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",T.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number($?.count||0),root_categories:Number(G?.count||0),child_categories:Number(J?.count||0)-Number(G?.count||0),with_images:Number(N?.count||0),recently_added:Z,top_parent_categories:Y.map((L)=>({id:String(L.parent_category_id||""),name:String(L.parent_name||""),child_count:Number(L.child_count)}))}}async function iJ(J=30){let $=new Date,G=f0($),N=new Date;N.setDate($.getDate()-J);let X=f0(N),W=new Date(N);W.setDate(W.getDate()-1);let Z=f0(W),Y=new Date(W);Y.setDate(W.getDate()-J);let L=f0(Y),K=await T.selectFrom("categories").select(T.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",G).executeTakeFirst(),Q=await T.selectFrom("categories").select(T.fn.count("id").as("count")).where("created_at",">=",L).where("created_at","<=",Z).executeTakeFirst(),M=Number(K?.count||0),H=Number(Q?.count||0),_=M-H,O=H!==0?_/H*100:M>0?100:0;return{current_period:M,previous_period:H,difference:_,percentage_change:O,days_range:J}}async function oJ(){let J=await E1(),$=new Map;J.forEach((X)=>{$.set(X.id,{...X,children:[]})});let G=[];J.forEach((X)=>{let W=$.get(X.id);if(X.parent_category_id){let Z=$.get(X.parent_category_id);if(Z)Z.children.push(W)}else G.push(W)}),G.sort((X,W)=>X.display_order-W.display_order);let N=(X)=>{X.sort((W,Z)=>W.display_order-Z.display_order),X.forEach((W)=>{if(W.children.length>0)N(W.children)})};return N(G),G}async function sJ(J){let $=await V0.deleteFrom("categories").where("id","=",J).executeTakeFirst();return F($)>0}async function dJ(J){if(!J.length)return 0;let $=await V0.deleteFrom("categories").where("id","in",J).executeTakeFirst();return F($)}async function aJ(J){let $=await V0.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return F($)}async function eJ(J){if(!await E(J))throw Error(`Category with ID ${J} not found`);return!!await V0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",J).executeTakeFirst()}async function rJ(J){let $=await V0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",J).execute();return Number($.length)||0}var{randomUUIDv7:C9}=globalThis.Bun;import{db as tJ}from"@stacksjs/database";import{HttpError as Q$}from"@stacksjs/error-handling";import{isUniqueViolation as h9}from"@stacksjs/orm";import{slug as I9}from"@stacksjs/strings";async function k1(J){try{let $=J.parent_category_id?Number(J.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new Q$(422,"Parent category ID must be a positive integer");if($&&!await E($))throw new Q$(422,`Parent category with ID ${J.parent_category_id} not found`);let G={...J,uuid:C9(),is_active:J.is_active??!0,parent_category_id:J.parent_category_id||null},N=await tJ.insertInto("categories").values(G).returningAll().executeTakeFirst();if(!N)throw Error("Failed to create category");return N}catch($){if($ instanceof Q$)throw $;if(h9($))throw new Q$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function $6(J){if(!J.name)throw Error("Name is required");let $=await tJ.selectFrom("categories").selectAll().where("name","=",J.name).executeTakeFirst();if($)return $;let G={name:J.name,slug:I9(J.name),is_active:J.is_active??!0,display_order:0};return await k1(G)}import{db as E0}from"@stacksjs/database";import{HttpError as x0}from"@stacksjs/error-handling";import{formatDate as M$,isUniqueViolation as g9}from"@stacksjs/orm";async function J6(J,$){if(!await E(J))return;if(Object.hasOwn($,"parent_category_id")){let N=$.parent_category_id?Number($.parent_category_id):void 0;if(N!==void 0&&(!Number.isSafeInteger(N)||N<=0))throw new x0(422,"Parent category ID must be a positive integer");if(N===J)throw new x0(422,"A category cannot be its own parent");if(N&&!await E(N))throw new x0(422,`Parent category with ID ${$.parent_category_id} not found`);if(N&&await W6(J,String(N)))throw new x0(422,"This operation would create a circular category hierarchy")}try{let N=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},X=await E0.updateTable("categories").set({...$,...N,updated_at:M$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)return;return X}catch(N){if(N instanceof x0)throw N;if(g9(N))throw new x0(409,"A category with this name or slug already exists");if(N instanceof Error)throw Error(`Failed to update category: ${N.message}`);throw N}}async function G6(J,$){if(!await E(J))throw Error(`Category with ID ${J} not found`);try{return await E0.updateTable("categories").set({display_order:$,updated_at:M$(new Date)}).where("id","=",J).execute(),await E(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update category display order: ${N.message}`);throw N}}async function N6(J,$){if(!await E(J))throw Error(`Category with ID ${J} not found`);try{return await E0.updateTable("categories").set({is_active:$,updated_at:M$(new Date)}).where("id","=",J).execute(),await E(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update category active status: ${N.message}`);throw N}}async function X6(J,$){if(!await E(J))throw Error(`Category with ID ${J} not found`);if($){let N=Number($);if(N===J)throw Error("A category cannot be its own parent");if(!await E(N))throw Error(`Parent category with ID ${$} not found`);if(await W6(J,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let N={updated_at:M$(new Date)};if($===null)await E0.updateTable("categories").set({...N,parent_category_id:null}).where("id","=",J).execute();else await E0.updateTable("categories").set({...N,parent_category_id:$}).where("id","=",J).execute();return await E(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update category parent: ${N.message}`);throw N}}async function W6(J,$){let G=Number($),N=new Set;while(G){if(N.has(G))return!0;if(G===J)return!0;N.add(G);let X=await E(G),W=X?.parent_category_id??X?.parentCategoryId;if(!X||!W)return!1;G=Number(W)}return!1}var V$={};z(V$,{updateInventory:()=>B6,updateAvailability:()=>z6,update:()=>x6,store:()=>H6,fetchTopProducts:()=>F6,fetchById:()=>u,fetchAll:()=>K6,destroy:()=>Y6,bulkStore:()=>V6,bulkDestroy:()=>L6});import{db as Z6}from"@stacksjs/database";async function Y6(J){try{let $=await Z6.deleteFrom("products").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function L6(J){if(!J.length)return 0;try{let $=await Z6.deleteFrom("products").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as a,sql as v9}from"@stacksjs/database";async function u(J){let $=await a.selectFrom("products").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,N=null;if($.manufacturer_id)G=await a.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)N=await a.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:G,category:N}}return}async function K6(){let J=await a.selectFrom("products").selectAll().execute(),$=J.map((K)=>K.manufacturer_id).filter((K)=>K!==null&&K!==void 0),G=J.map((K)=>K.category_id).filter((K)=>K!==null&&K!==void 0),N=a.selectFrom("manufacturers"),X=a.selectFrom("categories");if($.length>0)N=N.where("id","in",$);if(G.length>0)X=X.where("id","in",G);let W=await N.selectAll().execute(),Z=await X.selectAll().execute(),Y=W.reduce((K,Q)=>{return K[Q.id]=Q,K},{}),L=Z.reduce((K,Q)=>{return K[Q.id]=Q,K},{});return J.map((K)=>({...K,manufacturer:K.manufacturer_id?Y[K.manufacturer_id]:null,category:K.category_id?L[K.category_id]:null}))}async function F6(J=5){try{return(await a.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",a.fn.sum("order_items.quantity").as("units_sold"),v9`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(J).execute()).map((G)=>({id:Number(G.id),name:String(G.name??"Unnamed product"),units_sold:Number(G.units_sold??0),revenue:Number(G.revenue??0),inventory_count:Number(G.inventory_count??0)}))}catch($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:Q6}=globalThis.Bun;import{db as M6}from"@stacksjs/database";async function H6(J){try{let $={...J,uuid:Q6()},G=await M6.insertInto("products").values($).executeTakeFirst();if(!G)throw Error("Failed to create product item");let N=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),X=await u(N);if(!X)throw Error("Failed to create product item");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function V6(J){if(!J.length)return 0;let $=0;try{return await M6.transaction().execute(async(G)=>{for(let N of J){let X={...N,uuid:Q6()};await G.insertInto("products").values(X).execute(),$++}}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as j1}from"@stacksjs/database";import{formatDate as C1}from"@stacksjs/orm";async function x6(J,$){try{if(!J)throw Error("Product item ID is required for update");let G=await j1.updateTable("products").set({...$,updated_at:C1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item: ${G.message}`);throw G}}async function z6(J,$){if(!await u(J))throw Error(`Product item with ID ${J} not found`);try{return await j1.updateTable("products").set({is_available:$,updated_at:C1(new Date)}).where("id","=",J).execute(),await u(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update product item availability: ${N.message}`);throw N}}async function B6(J,$){let G=await u(J);if(!G)throw Error(`Product item with ID ${J} not found`);let N={updated_at:C1(new Date)};if($!==void 0)N.inventory_count=$;if(Object.keys(N).length===1)return G;try{return await j1.updateTable("products").set(N).where("id","=",J).execute(),await u(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update inventory information: ${X.message}`);throw X}}var x$={};z(x$,{updateFeaturedStatus:()=>I6,updateByUuid:()=>g6,update:()=>h6,store:()=>k6,fetchWithProductCount:()=>w6,fetchFeatured:()=>T6,fetchByUuid:()=>U6,fetchById:()=>S6,fetchByCountry:()=>P6,fetchAll:()=>O6,destroy:()=>_6,bulkStore:()=>j6,bulkDestroy:()=>R6});import{db as A6}from"@stacksjs/database";async function _6(J){try{let $=await A6.deleteFrom("manufacturers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function R6(J){if(!J.length)return 0;try{let $=await A6.deleteFrom("manufacturers").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as n}from"@stacksjs/database";function O6(){return n.selectFrom("manufacturers").selectAll().execute()}async function S6(J){return await n.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function U6(J){return await n.selectFrom("manufacturers").where("uuid","=",J).selectAll().executeTakeFirst()}async function T6(J=10){return await n.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(J).execute()}async function P6(J,$={}){let G=$.page||1,N=$.limit||2,X=await n.selectFrom("manufacturers").select(n.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),W=Number(X?.total||0),Z=await n.selectFrom("manufacturers").selectAll().where("country","=",J).limit(N).offset((G-1)*N).execute(),Y=Math.ceil(W/N);return{data:Z,paging:{total_records:W,page:G,total_pages:Y},next_cursor:G<Y?G+1:null}}async function w6(J={}){let $=n.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(J.country)$=$.where("m.country","=",J.country);if(J.featured!==void 0)$=$.where("m.featured","=",J.featured);return $=$.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",n.fn.count("p.id").as("product_count")]).groupBy("m.id"),$.execute()}var{randomUUIDv7:f6}=globalThis.Bun;import{db as E6}from"@stacksjs/database";import{HttpError as q6}from"@stacksjs/error-handling";import{isUniqueViolation as y9}from"@stacksjs/orm";async function k6(J){try{let $={...J,uuid:f6(),featured:J.featured??!1},G=await E6.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch($){if($ instanceof q6)throw $;if(y9($))throw new q6(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function j6(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={...G,uuid:f6(),featured:G.featured??!1};await E6.insertInto("manufacturers").values(N).execute(),$++}return $}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 C6}from"@stacksjs/error-handling";import{formatDate as I1,isUniqueViolation as D9}from"@stacksjs/orm";async function h6(J,$){try{if(!J)throw Error("Manufacturer ID is required for update");let G=await h1.updateTable("manufacturers").set({...$,updated_at:I1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof C6)throw G;if(D9(G))throw new C6(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function I6(J,$){try{let G=await h1.updateTable("manufacturers").set({featured:$,updated_at:I1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer featured status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${G.message}`);throw G}}async function g6(J,$){try{let G=await h1.updateTable("manufacturers").set({...$,updated_at:I1(new Date)}).where("uuid","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer: ${G.message}`);throw G}}var z$={};z(z$,{updateVotes:()=>d6,update:()=>s6,store:()=>n6,fetchMostHelpfulByProductId:()=>u6,fetchByUserId:()=>l6,fetchByProductId:()=>p6,fetchById:()=>b6,fetchApprovedByProductId:()=>c6,fetchAll:()=>m6,destroy:()=>y6,bulkDestroy:()=>D6});import{db as v6}from"@stacksjs/database";async function y6(J){try{let $=await v6.deleteFrom("reviews").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function D6(J){if(!J.length)return 0;try{let $=await v6.deleteFrom("reviews").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as z0}from"@stacksjs/database";async function b6(J){return await z0.selectFrom("reviews").where("id","=",J).selectAll().executeTakeFirst()}async function m6(){return await z0.selectFrom("reviews").selectAll().execute()}async function p6(J){return await z0.selectFrom("reviews").where("product_id","=",J).selectAll().execute()}async function l6(J){return await z0.selectFrom("reviews").where("customer_id","=",J).selectAll().execute()}async function c6(J){return await z0.selectFrom("reviews").where("product_id","=",J).where("is_approved","=",!0).selectAll().execute()}async function u6(J){return await z0.selectFrom("reviews").where("product_id","=",J).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:b9}=globalThis.Bun;import{db as m9}from"@stacksjs/database";async function n6(J){try{let $={...J,uuid:b9(),is_verified_purchase:J.is_verified_purchase??!1,is_approved:J.is_approved??!1,helpful_votes:J.helpful_votes??0,unhelpful_votes:J.unhelpful_votes??0,is_featured:J.is_featured??!1},G=await m9.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create review");return G}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${$.message}`)}throw $}}import{db as i6}from"@stacksjs/database";import{formatDate as o6}from"@stacksjs/orm";async function s6(J,$){try{if(!J)throw Error("Review ID is required for update");let G=await i6.updateTable("reviews").set({...$,updated_at:o6(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review: ${G.message}`);throw G}}async function d6(J,$,G=!0){try{let N=$==="helpful"?"helpful_votes":"unhelpful_votes",X=G?`COALESCE("${N}", 0) + 1`:`MAX(COALESCE("${N}", 0) - 1, 0)`,W=await i6.unsafe(`UPDATE "reviews" SET "${N}" = ${X}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[o6(new Date),J]).execute(),Z=Array.isArray(W)?W[0]:W;if(!Z)throw Error("Failed to update review votes");return Z}catch(N){if(N instanceof Error)throw TypeError(`Failed to update review votes: ${N.message}`);throw N}}var _$={};z(_$,{updateDefaultStatus:()=>K2,update:()=>Y2,store:()=>N2,getDefaultUnit:()=>Z2,formatUnitOptions:()=>W2,fetchById:()=>$2,fetchAll:()=>J2,destroy:()=>e6,bulkUpdate:()=>L2,bulkStore:()=>X2,bulkDestroy:()=>r6});import{db as a6}from"@stacksjs/database";async function e6(J){try{let $=await a6.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function r6(J){if(!J.length)return 0;try{let $=await a6.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as t6}from"@stacksjs/database";async function $2(J){return await t6.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function J2(){return await t6.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:G2}=globalThis.Bun;import{db as k0}from"@stacksjs/database";async function N2(J){try{return await k0.transaction(async($)=>{let G={...J,uuid:G2()},N=await $.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!N)throw Error("Failed to create product unit");if(G.is_default&&G.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",N.id).execute();return N})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function X2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={...G,uuid:G2()},X=await k0.insertInto("product_units").values(N).returningAll().executeTakeFirst();if(N.is_default&&N.type&&X)await k0.updateTable("product_units").set({is_default:!1}).where("type","=",N.type).where("id","!=",X.id).execute();$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function W2(J){try{let $=k0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(J)$=$.where("type","=",J);return $=$.orderBy("name"),$.execute().then((G)=>G.map((N)=>({id:String(N.id),name:N.name,abbreviation:N.abbreviation,is_default:N.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function Z2(J){try{return await k0.selectFrom("product_units").selectAll().where("type","=",J).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as B$}from"@stacksjs/database";import{formatDate as A$}from"@stacksjs/orm";async function Y2(J,$){try{if(!J)throw Error("Product unit ID is required for update");return await B$.transaction(async(G)=>{let N=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",J).executeTakeFirst();if(!N)return;let X=$.type??N.type;if(($.is_default??Boolean(N.is_default))&&X)await G.updateTable("product_units").set({is_default:!1,updated_at:A$(new Date)}).where("type","=",X).where("id","!=",J).execute();let Z=await G.updateTable("product_units").set({...$,updated_at:A$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function L2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N=G;if(!N.id)continue;let X=N.data&&typeof N.data==="object"?N.data:{...N};delete X.id;let W=await B$.updateTable("product_units").set({...X,updated_at:A$(new Date)}).where("id","=",N.id).executeTakeFirst(),Z=X;if(Z.is_default===!0&&Z.type)await B$.updateTable("product_units").set({is_default:!1}).where("type","=",Z.type).where("id","!=",N.id).execute();if(Number(W.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function K2(J,$){try{return await B$.transaction(async(G)=>{let N=await G.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!N)return!1;let X=A$(new Date);if($&&N.type)await G.updateTable("product_units").set({is_default:!1,updated_at:X}).where("type","=",N.type).where("id","!=",J).execute();return await G.updateTable("product_units").set({is_default:$,updated_at:X}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var R$={};z(R$,{update:()=>T2,store:()=>A2,generateVariantCombinations:()=>O2,formatVariantOptions:()=>R2,fetchById:()=>V2,fetchAll:()=>x2,destroy:()=>Q2,bulkUpdate:()=>P2,bulkStore:()=>_2,bulkDestroy:()=>M2});import{db as F2}from"@stacksjs/database";async function Q2(J){try{let $=await F2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function M2(J){if(!J.length)return 0;try{let $=await F2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as H2}from"@stacksjs/database";async function V2(J){return await H2.selectFrom("product_variants").where("id","=",J).selectAll().executeTakeFirst()}async function x2(){return await H2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:z2}=globalThis.Bun;import{db as B2}from"@stacksjs/database";async function A2(J){try{let $={...J,uuid:z2()},G=await B2.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product variant");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function _2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={...G,uuid:z2()};await B2.insertInto("product_variants").values(N).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${G.message}`);throw G}}function R2(J){if(!J||!J.length)return JSON.stringify([]);let $=J.map((G)=>G.trim()).filter(Boolean);return JSON.stringify($)}function O2(J){let $=Object.keys(J);if(!$.length)return[];function G(N,X){if(N===$.length)return[X];let W=$[N],Z=J[W]??[],Y=[];for(let L of Z){let K={...X,[W]:L};Y.push(...G(N+1,K))}return Y}return G(0,{})}import{db as S2}from"@stacksjs/database";import{formatDate as U2}from"@stacksjs/orm";async function T2(J,$){try{let G=await S2.updateTable("product_variants").set({...$,updated_at:U2(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variant: ${G.message}`);throw G}}async function P2(J){if(!J.length)return 0;let $=0;try{for(let G of J){if(!G.id)continue;let N=await S2.updateTable("product_variants").set({...G,updated_at:U2(new Date)}).where("id","=",G.id).executeTakeFirst();if(Number(N.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${G.message}`);throw G}}var p9={categories:H$,items:V$,manufacturers:x$,reviews:z$,units:_$,variants:R$},l9=p9;var p1={};z(p1,{updateStatus:()=>b2,updatePrintJob:()=>m2,update:()=>D2,store:()=>v2,fetchSuccessRate:()=>j2,fetchPrintsPerHour:()=>I2,fetchPrintTimeStats:()=>h2,fetchPrintJobStats:()=>k2,fetchPageStats:()=>C2,fetchById:()=>B0,fetchAll:()=>E2,destroy:()=>q2,bulkStore:()=>y2,bulkDestroy:()=>f2});import{db as w2}from"@stacksjs/database";async function q2(J){try{let $=await w2.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function f2(J){if(!J.length)return 0;try{let $=await w2.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as v1}from"@stacksjs/database";import{formatDate as c9}from"@stacksjs/orm";function b(J){return c9(J)}function u9(J){if(J instanceof Date)return Number.isNaN(J.getTime())?null:J;if(typeof J==="number"){let N=new Date(J<=2147483647?J*1000:J);return Number.isNaN(N.getTime())?null:N}let $=String(J||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let N=new Date(Number($)*1000);return Number.isNaN(N.getTime())?null:N}let G=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function B0(J){return await v1.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function E2(){return await v1.selectFrom("receipts").selectAll().execute()}async function k2(J,$){let G=b(J),N=b($),X=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"}},(W)=>W.where("timestamp",">=",G).where("timestamp","<=",N));return{total:X.total,success:X.success,failed:X.failed,warning:X.warning,averageSize:Math.round(X.averageSize),averagePages:Math.round(X.averagePages),averageDuration:Math.round(X.averageDuration)}}async function j2(J,$){let G=b(J),N=b($),X=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"}}},(Z)=>Z.where("timestamp",">=",G).where("timestamp","<=",N));return{successRate:X.total>0?Math.round(X.success/X.total*100):0,total:X.total,success:X.success,failed:X.failed,warning:X.warning}}async function C2(J,$){let G=b(J),N=b($),X=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(W)=>W.where("timestamp",">=",G).where("timestamp","<=",N));return{totalPages:X.totalPages,averagePagesPerReceipt:Math.round(X.averagePagesPerReceipt),totalReceipts:X.totalReceipts}}async function h2(J,$){let G=b(J),N=b($),X=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(W)=>W.where("timestamp",">=",G).where("timestamp","<=",N));return{averageDuration:Math.round(X.averageDuration),minDuration:X.minDuration,maxDuration:X.maxDuration,totalJobs:X.totalJobs}}async function I2(J,$){let G=typeof J==="number"?J:J.getTime(),N=typeof $==="number"?$:$.getTime(),X=b(J),W=b($),Z=await v1.selectFrom("receipts").where("timestamp",">=",X).where("timestamp","<=",W).selectAll().execute(),Y=Z.length,L=Math.ceil((N-G)/3600000),K=L>0?Math.round(Y/L):0,Q=Array.from({length:24},(M,H)=>({hour:H,count:0}));return Z.forEach((M)=>{let H=u9(M.timestamp);if(!H)return;Q[H.getHours()].count++}),{totalPrints:Y,totalHours:L,printsPerHour:K,hourlyBreakdown:Q}}var{randomUUIDv7:g2}=globalThis.Bun;import{db as D1}from"@stacksjs/database";import{formatDate as y1}from"@stacksjs/orm";function j0(J){try{if(typeof J==="number")return y1(J<=2147483647?J*1000:J);if(typeof J==="string"&&/^\d{10}$/.test(J))return y1(Number(J)*1000);return y1(J)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function v2(J){try{let $=g2(),G={...J,timestamp:j0(J.timestamp),uuid:$};await D1.insertInto("receipts").values(G).executeTakeFirst();let N=await D1.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to create receipt");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function y2(J){if(!J.length)return 0;try{let $=J.map((N)=>({...N,timestamp:j0(N.timestamp),uuid:g2()})),G=await D1.insertInto("receipts").values($).executeTakeFirst();return Number(G.numInsertedOrUpdatedRows??G.numAffectedRows??G.affectedRows??G.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as b1}from"@stacksjs/database";import{formatDate as m1}from"@stacksjs/orm";async function D2(J,$){try{if(!J)throw Error("Receipt ID is required for update");let G={...$,...$.timestamp===void 0?{}:{timestamp:j0($.timestamp)},updated_at:m1(new Date)};await b1.updateTable("receipts").set(G).where("id","=",J).execute();let N=await B0(J);if(!N)return;return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function b2(J,$){try{await b1.updateTable("receipts").set({status:$,updated_at:m1(new Date)}).where("id","=",J).execute();let G=await B0(J);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function m2(J,$,G,N){try{let X={updated_at:m1(new Date)};if($!==void 0)X.size=$;if(G!==void 0)X.pages=G;if(N!==void 0)X.duration=N;await b1.updateTable("receipts").set(X).where("id","=",J).execute();let W=await B0(J);if(!W)throw Error("Failed to update receipt job information");return W}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt job information: ${X.message}`);throw X}}var F4={};z(F4,{zones:()=>G1,tracking:()=>r$,routes:()=>w$,rates:()=>l$,methods:()=>y$,licenses:()=>h$,drivers:()=>k$,digital:()=>f$,default:()=>W3});var w$={};z(w$,{validateDeliveryRouteWrite:()=>A0,updateStops:()=>a2,updateMetrics:()=>e2,updateLastActive:()=>s2,update:()=>d2,store:()=>o2,fetchById:()=>S$,fetchByDriver:()=>i2,fetchAll:()=>u2,fetchActive:()=>n2,destroy:()=>l2,bulkDestroy:()=>c2,DeliveryRouteInputError:()=>h});import{db as p2}from"@stacksjs/database";async function l2(J){try{let $=await p2.deleteFrom("delivery_routes").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function c2(J){if(!J.length)return 0;try{let $=await p2.deleteFrom("delivery_routes").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as O$}from"@stacksjs/database";async function S$(J){return await O$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function u2(){return await O$.selectFrom("delivery_routes").selectAll().execute()}async function n2(){return await O$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function i2(J){return await O$.selectFrom("delivery_routes").where("driver","=",J).selectAll().execute()}var{randomUUIDv7:o9}=globalThis.Bun;import{db as l1}from"@stacksjs/database";function X0(J,$){let G={};for(let[N,X]of Object.entries($))for(let W of X){if(!Object.prototype.hasOwnProperty.call(J,W)||J[W]===void 0)continue;G[N]=J[W];break}return G}function C0(J){return X0(J,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function i(J){return X0(J,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function h0(J){return X0(J,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function I0(J){return X0(J,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function g0(J){return X0(J,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function v0(J){return X0(J,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function U$(J){return X0(J,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as n9}from"@stacksjs/database";class h extends TypeError{constructor(J){super(J);this.name="DeliveryRouteInputError"}}function T$(J,$,G){return Number(J[G]??$?.[G])}function i9(J,$){let G=J.last_active??$?.last_active;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 A0(J,$){let G=T$(J,$,"driver_id"),N=T$(J,$,"stops"),X=T$(J,$,"delivery_time"),W=T$(J,$,"total_distance"),Z=i9(J,$);if(!Number.isSafeInteger(G)||G<1)throw new h("Driver must be a positive integer.");if(!Number.isSafeInteger(N)||N<0)throw new h("Stops must be a non-negative integer.");if(!Number.isSafeInteger(X)||X<0)throw new h("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(W)||W<0)throw new h("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new h("Last active must be a valid Unix timestamp.");let Y=await n9.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!Y)throw new h(`Driver ${G} was not found.`);return{...J,driver_id:Number(Y.id),driver:Y.name,vehicle:Y.vehicle_number}}async function o2(J){try{let $=o9(),G=U$(J),X={...await A0(G),uuid:$};await l1.insertInto("delivery_routes").values(X).executeTakeFirst();let W=await l1.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!W)throw Error("Failed to create delivery route");return W}catch($){if($ instanceof h)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function s2(J){try{await l1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",J).execute();let $=await S$(J);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as P$}from"@stacksjs/database";import{formatDate as c1}from"@stacksjs/orm";async function d2(J,$){try{if(!J)throw Error("Delivery route ID is required for update");let G=await P$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let N=U$($),X=await A0(N,G),W=await P$.updateTable("delivery_routes").set({...X,updated_at:c1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!W)return;return W}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 a2(J,$){try{let G=await P$.updateTable("delivery_routes").set({stops:$,updated_at:c1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update delivery route stops");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery route stops: ${G.message}`);throw G}}async function e2(J,$,G){try{let N={updated_at:c1(new Date)};if($!==void 0)N.delivery_time=$;if(G!==void 0)N.total_distance=G;let X=await P$.updateTable("delivery_routes").set(N).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery metrics");return X}catch(N){if(N instanceof Error)throw TypeError(`Failed to update delivery metrics: ${N.message}`);throw N}}var f$={};z(f$,{updateStatus:()=>KG,updateDeliverySettings:()=>FG,update:()=>LG,store:()=>ZG,softDelete:()=>t2,fetchById:()=>NG,fetchAll:()=>XG,destroy:()=>r2,bulkStore:()=>YG,bulkSoftDelete:()=>JG,bulkDestroy:()=>$G});import{db as q$}from"@stacksjs/database";async function r2(J){try{let $=await q$.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function t2(J){try{let $=await q$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function $G(J){if(!J.length)return 0;try{let $=await q$.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function JG(J){if(!J.length)return 0;try{let $=await q$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as GG}from"@stacksjs/database";async function NG(J){return await GG.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function XG(){return await GG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:WG}=globalThis.Bun;import{db as u1}from"@stacksjs/database";async function ZG(J){try{let $=WG(),G={...I0(J),uuid:$};await u1.insertInto("digital_deliveries").values(G).executeTakeFirst();let N=await u1.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created digital delivery");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function YG(J){if(!J.length)return 0;try{let $=J.map((N)=>({...I0(N),uuid:WG()})),G=await u1.insertInto("digital_deliveries").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as n1}from"@stacksjs/database";import{formatDate as i1}from"@stacksjs/orm";async function LG(J,$){try{if(!J)throw Error("Digital delivery ID is required for update");let G=await n1.updateTable("digital_deliveries").set({...I0($),updated_at:i1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery: ${G.message}`);throw G}}async function KG(J,$){try{let G=await n1.updateTable("digital_deliveries").set({status:$,updated_at:i1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update digital delivery status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery status: ${G.message}`);throw G}}async function FG(J,$,G,N,X){try{let W={updated_at:i1(new Date)};if($!==void 0)W.download_limit=$;if(G!==void 0)W.expiry_days=G;if(N!==void 0)W.requires_login=N;if(X!==void 0)W.automatic_delivery=X;let Z=await n1.updateTable("digital_deliveries").set(W).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update delivery settings");return Z}catch(W){if(W instanceof Error)throw TypeError(`Failed to update delivery settings: ${W.message}`);throw W}}var k$={};z(k$,{updateStatus:()=>RG,updateContact:()=>OG,update:()=>_G,store:()=>BG,fetchById:()=>E$,fetchAll:()=>MG,destroy:()=>VG,bulkStore:()=>AG,bulkDestroy:()=>xG});import{db as HG}from"@stacksjs/database";import{db as QG}from"@stacksjs/database";async function E$(J){return await QG.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function MG(){return await QG.selectFrom("drivers").selectAll().execute()}async function VG(J){try{let $=await HG.deleteFrom("drivers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function xG(J){if(!J.length)return 0;let $=0;try{return await HG.transaction().execute(async(G)=>{for(let N of J)if(await E$(N))await G.deleteFrom("drivers").where("id","=",N).execute(),$++}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${G.message}`);throw G}}var{randomUUIDv7:zG}=globalThis.Bun;import{db as o1}from"@stacksjs/database";async function BG(J){try{let $=zG(),G={...v0(J),uuid:$};await o1.insertInto("drivers").values(G).executeTakeFirst();let N=await o1.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created driver");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function AG(J){if(!J.length)return 0;try{let $=J.map((N)=>({...v0(N),uuid:zG()})),G=await o1.insertInto("drivers").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as s1}from"@stacksjs/database";import{formatDate as d1}from"@stacksjs/orm";async function _G(J,$){try{if(!J)throw Error("Driver ID is required for update");let G=await s1.updateTable("drivers").set({...v0($),updated_at:d1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver: ${G.message}`);throw G}}async function RG(J,$){try{let G=await s1.updateTable("drivers").set({status:$,updated_at:d1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update driver status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver status: ${G.message}`);throw G}}async function OG(J,$){try{let G={updated_at:d1(new Date)};if($!==void 0)G.phone=$;let N=await s1.updateTable("drivers").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!N)throw Error("Failed to update contact information");return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update contact information: ${G.message}`);throw G}}var h$={};z(h$,{validateLicenseKeyWrite:()=>W0,updateStatus:()=>gG,updateExpiration:()=>vG,update:()=>IG,store:()=>CG,softDelete:()=>UG,fetchById:()=>qG,fetchAll:()=>fG,destroy:()=>SG,bulkStore:()=>hG,bulkSoftDelete:()=>PG,bulkDestroy:()=>TG,LicenseKeyInputError:()=>w});import{db as j$}from"@stacksjs/database";async function SG(J){try{let $=await j$.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function UG(J){try{let $=await j$.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function TG(J){if(!J.length)return 0;try{let $=await j$.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function PG(J){if(!J.length)return 0;try{let $=await j$.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as wG}from"@stacksjs/database";async function qG(J){return await wG.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst()}async function fG(){return await wG.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:jG}=globalThis.Bun;import{db as r1}from"@stacksjs/database";import{db as a1}from"@stacksjs/database";var EG=["Standard License","Premium License","Enterprise License"],kG=["active","inactive","unassigned"];class w extends TypeError{constructor(J){super(J);this.name="LicenseKeyInputError"}}function y0(J,$,G){return J[G]!==void 0?J[G]:$?.[G]}function e1(J,$,G,N){let X=y0(J,$,G);if(X===void 0||X===null||X==="")return null;let W=Number(X);if(!Number.isSafeInteger(W)||W<1)throw new w(`${N} must be a positive integer or null.`);return W}function s9(J){if(typeof J==="number")return J>2147483647?Math.floor(J/1000):J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return J.length===13?Math.floor(Number(J)/1000):Number(J);if(typeof J==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(J)?`${J.replace(" ","T")}Z`:J;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function W0(J,$){let G=String(y0(J,$,"key")||"").trim().toUpperCase(),N=String(y0(J,$,"template")||""),X=String(y0(J,$,"status")||""),W=s9(y0(J,$,"expiry_date")),Z=e1(J,$,"customer_id","Customer"),Y=e1(J,$,"product_id","Product"),L=e1(J,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new w("License key must use five groups of four uppercase letters or numbers.");if(!EG.includes(N))throw new w(`Template must be one of: ${EG.join(", ")}.`);if(!kG.includes(X))throw new w(`Status must be one of: ${kG.join(", ")}.`);if(!Number.isSafeInteger(W)||W<0||W>2147483647)throw new w("Expiry date must be a Unix timestamp between 1970 and 2038.");let[K,Q,M]=await Promise.all([Z?a1.selectFrom("customers").where("id","=",Z).select("id").executeTakeFirst():null,Y?a1.selectFrom("products").where("id","=",Y).select("id").executeTakeFirst():null,L?a1.selectFrom("orders").where("id","=",L).select(["id","customer_id"]).executeTakeFirst():null]);if(Z&&!K)throw new w(`Customer ${Z} was not found.`);if(Y&&!Q)throw new w(`Product ${Y} was not found.`);if(L&&!M)throw new w(`Order ${L} was not found.`);if(Z&&M?.customer_id&&Number(M.customer_id)!==Z)throw new w(`Order ${L} belongs to Customer ${M.customer_id}, not Customer ${Z}.`);return{...J,key:G,template:N,expiry_date:W,status:X,customer_id:Z,product_id:Y,order_id:L}}async function CG(J){try{let $=jG(),G=g0(J),N={...await W0(G),uuid:$};await r1.insertInto("license_keys").values(N).executeTakeFirst();let X=await r1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created license key");return X}catch($){if($ instanceof w)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new w("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function hG(J){if(!J.length)return 0;try{let $=await Promise.all(J.map(async(N)=>({...await W0(g0(N)),uuid:jG()}))),G=await r1.insertInto("license_keys").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof w)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as C$}from"@stacksjs/database";import{formatDate as t1}from"@stacksjs/orm";async function IG(J,$){try{if(!J)throw Error("License key ID is required for update");let G=await C$.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let N=g0($),X=await W0(N,G),W=await C$.updateTable("license_keys").set({...X,updated_at:t1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!W)return;return W}catch(G){if(G instanceof w)throw G;if(G instanceof Error){if(G.message.includes("UNIQUE constraint failed: license_keys.key"))throw new w("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${G.message}`)}throw G}}async function gG(J,$){try{let G=await C$.updateTable("license_keys").set({status:$,updated_at:t1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update license key status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update license key status: ${G.message}`);throw G}}async function vG(J,$){try{let G={updated_at:t1(new Date)};if($!==void 0)G.expiry_date=$;let N=await C$.updateTable("license_keys").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!N)throw Error("Failed to update expiration information");return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update expiration information: ${G.message}`);throw G}}var y$={};z(y$,{updateStatus:()=>sG,updatePricing:()=>dG,update:()=>oG,store:()=>cG,softDelete:()=>DG,getActiveShippingMethods:()=>iG,formatShippingOptions:()=>nG,fetchById:()=>v$,fetchAll:()=>pG,destroy:()=>yG,bulkStore:()=>uG,bulkSoftDelete:()=>mG,bulkDestroy:()=>bG});import{db as I$}from"@stacksjs/database";async function yG(J){try{let $=await I$.deleteFrom("shipping_methods").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function DG(J){try{let $=await I$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function bG(J){if(!J.length)return 0;try{let $=await I$.deleteFrom("shipping_methods").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function mG(J){if(!J.length)return 0;try{let $=await I$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as g$}from"@stacksjs/database";async function v$(J){let $=await g$.selectFrom("shipping_methods").where("id","=",J).selectAll().executeTakeFirst();if($){let G=await g$.selectFrom("shipping_zones").where("shipping_method_id","=",J).selectAll().execute();return{...$,shippingZones:G}}return}async function pG(){let J=await g$.selectFrom("shipping_methods").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((W)=>W.id))],X=(await g$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((W,Z)=>{let Y=Z.shipping_method_id;if(Y!==null&&Y!==void 0){if(!W[Y])W[Y]=[];W[Y].push(Z)}return W},{});return J.map((W)=>({...W,shipping_zones:X[W.id]||[]}))}var{randomUUIDv7:lG}=globalThis.Bun;import{db as D0}from"@stacksjs/database";async function cG(J){try{let $=lG(),G={...C0(J),uuid:$};await D0.insertInto("shipping_methods").values(G).executeTakeFirst();let N=await D0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created shipping method");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function uG(J){if(!J.length)return 0;try{let $=J.map((N)=>({...C0(N),uuid:lG()})),G=await D0.insertInto("shipping_methods").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function nG(){try{return D0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping options: ${J.message}`);throw J}}async function iG(){try{return await D0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping methods: ${J.message}`);throw J}}import{db as $4}from"@stacksjs/database";import{formatDate as J4}from"@stacksjs/orm";async function oG(J,$){try{if(!J)throw Error("Shipping method ID is required for update");let G=await $4.updateTable("shipping_methods").set({...C0($),updated_at:J4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method: ${G.message}`);throw G}}async function sG(J,$){try{let G=await $4.updateTable("shipping_methods").set({status:$,updated_at:J4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping method status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method status: ${G.message}`);throw G}}async function dG(J,$,G){try{let N={updated_at:J4(new Date)};if($!==void 0)N.base_rate=$;if(G!==void 0)N.free_shipping=G;let X=await $4.updateTable("shipping_methods").set(N).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update pricing information");return X}catch(N){if(N instanceof Error)throw TypeError(`Failed to update pricing information: ${N.message}`);throw N}}var l$={};z(l$,{validateZoneMatchesAddress:()=>WN,validateShippingRateWrite:()=>Z0,updateByZone:()=>BN,updateByMethod:()=>AN,update:()=>xN,store:()=>HN,resolveZoneForAddress:()=>b$,getShippingRatesByMethod:()=>YN,getRatesByZone:()=>NN,getRateByWeightAndZone:()=>G4,getRateByWeightAndAddress:()=>XN,formatShippingRateOptions:()=>ZN,fetchById:()=>JN,fetchAll:()=>GN,destroyByZone:()=>rG,destroyByMethod:()=>tG,destroy:()=>aG,bulkUpdate:()=>zN,bulkStore:()=>VN,bulkDestroy:()=>eG,ShippingRateInputError:()=>j});import{db as D$}from"@stacksjs/database";async function aG(J){try{let $=await D$.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function eG(J){if(!J.length)return 0;try{let $=await D$.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function rG(J){try{let $=await D$.deleteFrom("shipping_rates").where("shipping_zone_id","=",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function tG(J){try{let $=await D$.deleteFrom("shipping_rates").where("shipping_method_id","=",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as y}from"@stacksjs/database";async function JN(J){let $=await y.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,N=null;if($.shipping_zone_id)G=await y.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)N=await y.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:G,shipping_method:N}}return}async function GN(){let J=await y.selectFrom("shipping_rates").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((Y)=>Y.shipping_zone_id).filter((Y)=>Y!==null&&Y!==void 0))],G=[...new Set(J.map((Y)=>Y.shipping_method_id).filter((Y)=>Y!==null&&Y!==void 0))],[N,X]=await Promise.all([$.length?y.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],G.length?y.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),W=N.reduce((Y,L)=>{return Y[L.id]=L,Y},{}),Z=X.reduce((Y,L)=>{return Y[L.id]=L,Y},{});return J.map((Y)=>({...Y,shipping_zone:Y.shipping_zone_id?W[Y.shipping_zone_id]:[],shipping_method:Y.shipping_method_id?Z[Y.shipping_method_id]:[]}))}async function NN(J){try{return await y.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function G4(J,$){try{return await y.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function b$(J){if(!J?.countryCode)return null;try{let $=await y.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let G=null;for(let N of $){let X=1;if(J.region&&N.regions&&$N(N.regions,J.region))X=2;if(J.postalCode&&N.postal_codes&&$N(N.postal_codes,J.postalCode))X=3;if(!G||X>G.score)G={id:N.id,score:X}}return G?.id??null}catch{return null}}async function XN(J,$){let G=await b$($);if(G==null)return;return G4(J,G)}async function WN(J,$){return await b$($)===J}function $N(J,$){if(!J||!$)return!1;let G=$.trim().toUpperCase();for(let N of J.split(/[,|;]/))if(N.trim().toUpperCase()===G)return!0;return!1}async function ZN(){try{return(await y.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function YN(J){try{return await y.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:MN}=globalThis.Bun;import{db as N4}from"@stacksjs/database";import{db as b0}from"@stacksjs/database";async function LN(){return await b0.selectFrom("shipping_zones").selectAll().execute()}async function m$(J){return await b0.selectFrom("shipping_zones").where("id","=",J).selectAll().executeTakeFirst()}function KN(){try{return b0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping zone options: ${J.message}`);throw J}}async function FN(){try{return await b0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping zones: ${J.message}`);throw J}}async function QN(J){try{return await b0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class j extends TypeError{constructor(J){super(J);this.name="ShippingRateInputError"}}function m0(J,$,G){return Number(J[G]??$?.[G])}async function Z0(J,$){let G=m0(J,$,"shipping_method_id"),N=m0(J,$,"shipping_zone_id"),X=m0(J,$,"weight_from"),W=m0(J,$,"weight_to"),Z=m0(J,$,"rate");if(!Number.isSafeInteger(G)||G<1)throw new j("Shipping method must be a positive integer.");if(!Number.isSafeInteger(N)||N<1)throw new j("Shipping zone must be a positive integer.");if(!Number.isFinite(X)||X<0)throw new j("Weight from must be a non-negative number.");if(!Number.isFinite(W)||W<X)throw new j("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(Z)||Z<0)throw new j("Rate must be a non-negative integer in minor currency units.");let[Y,L]=await Promise.all([v$(G),m$(N)]);if(!Y)throw new j(`Shipping method ${G} was not found.`);if(!L)throw new j(`Shipping zone ${N} was not found.`);if(Number(L.shipping_method_id)!==G)throw new j(`Shipping zone ${N} is not assigned to shipping method ${G}.`)}async function HN(J){try{let $=i(J),G=Number($.shipping_method_id),N=Number($.shipping_zone_id);await Z0($);let X=MN(),W={...$,shipping_method_id:G,shipping_zone_id:N,uuid:X};await N4.insertInto("shipping_rates").values(W).executeTakeFirst();let Z=await N4.selectFrom("shipping_rates").where("uuid","=",X).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created shipping rate");return Z}catch($){if($ instanceof j)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function VN(J){if(!J.length)return 0;try{for(let N of J){let X=i(N);await Z0(X)}let $=J.map((N)=>({...i(N),uuid:MN()})),G=await N4.insertInto("shipping_rates").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof j)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as p0}from"@stacksjs/database";import{formatDate as p$}from"@stacksjs/orm";async function xN(J,$){try{if(!J)throw Error("Shipping rate ID is required for update");let G=await p0.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let N=i($);await Z0(N,G);let X=await p0.updateTable("shipping_rates").set({...N,updated_at:p$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)return;return X}catch(G){if(G instanceof j)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function zN(J){if(!J.length)return 0;try{let $=0;for(let{id:G,data:N}of J){let X=await p0.updateTable("shipping_rates").set({...i(N),updated_at:p$(new Date)}).where("id","=",G).executeTakeFirst();if(F(X)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function BN(J,$){try{let G=await p0.updateTable("shipping_rates").set({...i($),updated_at:p$(new Date)}).where("shipping_zone_id","=",J).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 AN(J,$){try{let G=await p0.updateTable("shipping_rates").set({...i($),updated_at:p$(new Date)}).where("shipping_method_id","=",J).executeTakeFirst();return F(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var r$={};z(r$,{startStop:()=>SN,startRoute:()=>PN,routeTrackingChannel:()=>X4,recordDriverPing:()=>RN,orderTrackingChannel:()=>e,isWithin:()=>_N,hasCoordinates:()=>c0,failStop:()=>TN,estimateSecondsRemaining:()=>e$,emitDeliveryStarted:()=>n$,emitDeliveryPosition:()=>c$,emitDeliveryNearby:()=>i$,emitDeliveryFailed:()=>d$,emitDeliveryCompleted:()=>s$,emitDeliveryAssigned:()=>u$,emitDeliveryArrived:()=>o$,distanceInMeters:()=>l0,completeStop:()=>UN,broadcastToChannel:()=>o,bearingInDegrees:()=>a$,assignStop:()=>ON,NEARBY_RADIUS_METERS:()=>W4,ARRIVAL_RADIUS_METERS:()=>Z4});function e(J){return`order.${J}`}function X4(J){return`delivery-route.${J}`}async function _0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let N=G.dispatch;if(typeof N!=="function")return;N(J,$)}catch{}}async function o(J,$,G){try{let N=await import("@stacksjs/realtime").catch(()=>null);if(!N)return;let X=N.channel;if(typeof X!=="function")return;await X(J).broadcast($,G,"private")}catch{}}async function c$(J,$,G){await Promise.all([...J.map((N)=>o(e(N),"delivery:position",G)),$==null?Promise.resolve():o(X4($),"delivery:position",G)])}async function u$(J){if(await _0("delivery:assigned",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:assigned",{stop:J})}async function n$(J){if(await _0("delivery:started",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:started",{stop:J})}async function i$(J,$,G){if(await _0("delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G}),J.order_id!=null)await o(e(J.order_id),"delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G})}async function o$(J){if(await _0("delivery:arrived",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:arrived",{stop:J})}async function s$(J){if(await _0("delivery:completed",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:completed",{stop:J})}async function d$(J,$){await _0("delivery:failed",{stop:J,reason:$})}var Y0=(J)=>J*Math.PI/180;function l0(J,$){let G=Y0($.latitude-J.latitude),N=Y0($.longitude-J.longitude),X=Y0(J.latitude),W=Y0($.latitude),Z=Math.sin(G/2)**2+Math.sin(N/2)**2*Math.cos(X)*Math.cos(W);return 12742017.6*Math.asin(Math.sqrt(Z))}function a$(J,$){let G=Y0(J.latitude),N=Y0($.latitude),X=Y0($.longitude-J.longitude),W=Math.sin(X)*Math.cos(N),Z=Math.cos(G)*Math.sin(N)-Math.sin(G)*Math.cos(N)*Math.cos(X);return(Math.atan2(W,Z)*180/Math.PI+360)%360}function e$(J,$,G={}){let N=G.detourFactor??1.35,X=G.minimumSeconds??30;if(!Number.isFinite($)||$<=0.5)return null;let W=J*N/$;return Math.max(X,Math.round(W))}function _N(J,$,G){return l0(J,$)<=G}function c0(J){return typeof J?.latitude==="number"&&typeof J?.longitude==="number"&&Number.isFinite(J.latitude)&&Number.isFinite(J.longitude)}var{randomUUIDv7:d9}=globalThis.Bun;import{db as D}from"@stacksjs/database";var W4=400,Z4=60,a9=250;async function RN(J){let $=J.recordedAt??new Date().toISOString(),G=typeof J.accuracy!=="number"||J.accuracy<=a9,N=await D.selectFrom("drivers").where("id","=",J.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!N)throw Error(`Unknown driver: ${J.driverId}`);let X=c0(N)?{latitude:N.latitude,longitude:N.longitude}:null,W=typeof J.heading==="number"?J.heading:X?a$(X,J):null,Z=await e9(J.driverId),Y=Z?await r9(Z.id):null,L=null,K=null,Q=!1,M=!1,H=Y&&c0({latitude:Y.latitude??void 0,longitude:Y.longitude??void 0})?{latitude:Y.latitude,longitude:Y.longitude}:null;if(G&&Y&&H)L=Math.round(l0(J,H)),K=e$(L,J.speed??0),M=L<=Z4&&Y.arrived_at==null,Q=!M&&L<=W4&&Y.status==="en_route"&&Y.notified_nearby_at==null;let _=await t9({driverId:J.driverId,routeId:Z?.id??null,latitude:J.latitude,longitude:J.longitude,heading:W,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$});if(G)await D.updateTable("drivers").set({latitude:J.latitude,longitude:J.longitude,heading:W,speed:J.speed??0,last_ping_at:$}).where("id","=",J.driverId).execute();if(Y&&(L!=null||K!=null))await D.updateTable("delivery_stops").set({eta_at:K==null?Y.eta_at:new Date(Date.now()+K*1000).toISOString()}).where("id","=",Y.id).execute();if(G)await c$(Y?.order_id==null?[]:[Y.order_id],Z?.id??null,{driverId:J.driverId,routeId:Z?.id??null,latitude:J.latitude,longitude:J.longitude,heading:W,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$,distanceToStopMeters:L,etaSeconds:K});if(Q&&Y)await D.updateTable("delivery_stops").set({notified_nearby_at:$}).where("id","=",Y.id).execute(),await i$(Y,L,K);if(M&&Y)await D.updateTable("delivery_stops").set({status:"arrived",arrived_at:$}).where("id","=",Y.id).execute(),await o$({...Y,status:"arrived",arrived_at:$});return{pingId:_,routeId:Z?.id??null,stopId:Y?.id??null,distanceToStopMeters:L,etaSeconds:K,crossedNearby:Q,crossedArrival:M}}async function e9(J){return await D.selectFrom("delivery_routes").where("driver_id","=",J).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function r9(J){let $=await D.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return $.find((G)=>G.status==="en_route")??$.find((G)=>G.status==="arrived")??$[0]??null}async function t9(J){let $=d9();return await D.insertInto("driver_pings").values({uuid:$,driver_id:J.driverId,delivery_route_id:J.routeId,latitude:J.latitude,longitude:J.longitude,heading:J.heading,speed:J.speed??0,accuracy:J.accuracy,recorded_at:J.recordedAt}).executeTakeFirst(),(await D.selectFrom("driver_pings").where("uuid","=",$).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:$3}=globalThis.Bun;import{db as k}from"@stacksjs/database";async function ON(J){let $=$3(),G=J.sequence??await J3(J.deliveryRouteId);await k.insertInto("delivery_stops").values({uuid:$,delivery_route_id:J.deliveryRouteId,order_id:J.orderId??null,sequence:G,status:"pending",address:J.address,latitude:J.latitude??null,longitude:J.longitude??null,recipient_name:J.recipientName??null,recipient_phone:J.recipientPhone??null,eta_at:J.etaAt??null}).executeTakeFirst();let N=await N3($);if(N)await u$(N);return N??{}}async function SN(J){await k.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",J).execute();let $=await L4(J);if(!$)return null;if($.order_id!=null)await Y4($.order_id,"OUT_FOR_DELIVERY");return await n$($),$}async function UN(J,$){let G=new Date().toISOString();await k.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await G3(J)?{}:{arrived_at:G},...$?{notes:$}:{}}).where("id","=",J).execute();let N=await L4(J);if(!N)return null;if(N.order_id!=null)await Y4(N.order_id,"DELIVERED");return await s$(N),await wN(N.delivery_route_id),N}async function TN(J,$){await k.updateTable("delivery_stops").set({status:"failed",notes:$}).where("id","=",J).execute();let G=await L4(J);if(!G)return null;if(G.order_id!=null)await Y4(G.order_id,"SHIPPED");return await d$(G,$),await wN(G.delivery_route_id),G}async function PN(J){await k.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",J).execute()}async function wN(J){if(J==null)return;if(await k.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;await k.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",J).execute()}async function Y4(J,$){let G=await k.selectFrom("orders").where("id","=",J).select(["id","status"]).executeTakeFirst();if(!G)return;let{canTransition:N,emitForStatus:X}=await Promise.resolve().then(() => (M0(),KJ));if(!N(G.status,$))return;await k.updateTable("orders").set({status:$}).where("id","=",J).execute(),await X($,{...G,status:$})}async function J3(J){return(await k.selectFrom("delivery_stops").where("delivery_route_id","=",J).select(["sequence"]).execute()).reduce((G,N)=>Math.max(G,N.sequence??0),0)+1}async function G3(J){return(await k.selectFrom("delivery_stops").where("id","=",J).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function L4(J){return await k.selectFrom("delivery_stops").where("id","=",J).selectAll().executeTakeFirst()??null}async function N3(J){return await k.selectFrom("delivery_stops").where("uuid","=",J).selectAll().executeTakeFirst()??null}var G1={};z(G1,{updateStatus:()=>gN,updateRegionsAndPostalCodes:()=>yN,updateCountries:()=>vN,update:()=>IN,store:()=>CN,softDelete:()=>fN,getZonesByCountry:()=>QN,getActiveShippingZones:()=>FN,formatZoneOptions:()=>KN,fetchById:()=>m$,fetchAll:()=>LN,destroy:()=>qN,bulkStore:()=>hN,bulkSoftDelete:()=>kN,bulkDestroy:()=>EN});import{db as t$}from"@stacksjs/database";async function qN(J){try{let $=await t$.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function fN(J){try{let $=await t$.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function EN(J){if(!J.length)return 0;try{let $=await t$.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function kN(J){if(!J.length)return 0;try{let $=await t$.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:jN}=globalThis.Bun;import{db as K4}from"@stacksjs/database";async function CN(J){try{let $=jN(),G={...h0(J),uuid:$};await K4.insertInto("shipping_zones").values(G).executeTakeFirst();let N=await K4.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created shipping zone");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function hN(J){if(!J.length)return 0;try{let $=J.map((N)=>({...h0(N),uuid:jN()})),G=await K4.insertInto("shipping_zones").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as $1}from"@stacksjs/database";import{formatDate as J1}from"@stacksjs/orm";async function IN(J,$){try{if(!J)throw Error("Shipping zone ID is required for update");let G=await $1.updateTable("shipping_zones").set({...h0($),updated_at:J1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone: ${G.message}`);throw G}}async function gN(J,$){try{let G=await $1.updateTable("shipping_zones").set({status:$,updated_at:J1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone status: ${G.message}`);throw G}}async function vN(J,$){try{let G=await $1.updateTable("shipping_zones").set({countries:$,updated_at:J1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone countries");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${G.message}`);throw G}}async function yN(J,$,G){try{let N={updated_at:J1(new Date)};if($!==void 0)N.regions=$;if(G!==void 0)N.postal_codes=G;let X=await $1.updateTable("shipping_zones").set(N).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update regions and postal codes");return X}catch(N){if(N instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${N.message}`);throw N}}var X3={digital:f$,drivers:k$,licenses:h$,methods:y$,rates:l$,routes:w$,tracking:r$,zones:G1},W3=X3;var Q4={};z(Q4,{updateStatus:()=>dN,updateRate:()=>aN,updateDefaultStatus:()=>eN,update:()=>sN,store:()=>iN,fetchById:()=>lN,fetchAll:()=>cN,destroy:()=>bN,bulkStore:()=>oN,bulkDestroy:()=>mN});import{db as DN}from"@stacksjs/database";async function bN(J){try{let $=await DN.deleteFrom("tax_rates").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function mN(J){if(!J.length)return 0;try{let $=await DN.deleteFrom("tax_rates").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as pN}from"@stacksjs/database";async function lN(J){return await pN.selectFrom("tax_rates").where("id","=",J).selectAll().executeTakeFirst()}async function cN(){return await pN.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:uN}=globalThis.Bun;import{db as nN}from"@stacksjs/database";async function iN(J){try{return await nN.transaction(async($)=>{let G={...J,uuid:uN()};if(G.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let N=await $.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!N)throw Error("Failed to create tax rate");return N})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function oN(J){if(!J.length)return 0;try{return await nN.transaction(async($)=>{let G=0;for(let N of J){let X={...N,uuid:uN()};if(X.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(X).executeTakeFirst())G++}return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as N1}from"@stacksjs/database";import{formatDate as X1}from"@stacksjs/orm";async function sN(J,$){try{if(!J)throw Error("Tax rate ID is required for update");return await N1.transaction(async(G)=>{let N=await G.selectFrom("tax_rates").select("is_default").where("id","=",J).executeTakeFirst();if(!N)return;let X=$.is_default??Boolean(N.is_default),W=X1(new Date);if(X)await G.updateTable("tax_rates").set({is_default:!1,updated_at:W}).where("id","!=",J).execute();let Z=await G.updateTable("tax_rates").set({...$,updated_at:W}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function dN(J,$){try{let G=await N1.updateTable("tax_rates").set({status:$,updated_at:X1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update tax rate status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate status: ${G.message}`);throw G}}async function aN(J,$){try{let G=await N1.updateTable("tax_rates").set({rate:$,updated_at:X1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update rate information");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update rate information: ${G.message}`);throw G}}async function eN(J,$){try{return await N1.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",J).executeTakeFirst())return!1;let X=X1(new Date);if($)await G.updateTable("tax_rates").set({is_default:!1,updated_at:X}).where("id","!=",J).execute();return await G.updateTable("tax_rates").set({is_default:$,updated_at:X}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var B4={};z(B4,{restaurant:()=>O0,products:()=>Z1,default:()=>x3});var Z1={};z(Z1,{updateStatus:()=>BX,updatePartySize:()=>AX,update:()=>W1,store:()=>xX,fetchWaiting:()=>LX,fetchPurchasedBetweenDates:()=>ZX,fetchNotifiedBetweenDates:()=>WX,fetchCountByStatus:()=>KX,fetchCountBySource:()=>JX,fetchCountByQuantity:()=>NX,fetchCountByDateGrouped:()=>MX,fetchCountByDate:()=>GX,fetchCountByAllQuantities:()=>XX,fetchCountBetweenDates:()=>QX,fetchConversionRates:()=>FX,fetchCancelledBetweenDates:()=>YX,fetchById:()=>u0,fetchAll:()=>$X,destroy:()=>rN,bulkStore:()=>zX,bulkDestroy:()=>tN});import{db as M4}from"@stacksjs/database";async function rN(J){try{let $=await M4.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await M4.deleteFrom("waitlist_products").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function tN(J){if(!J.length)return 0;try{let $=await M4.deleteFrom("waitlist_products").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as P}from"@stacksjs/orm";async function u0(J){return await A.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function $X(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function JX(J,$){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(J&&$){let X=P(J),W=P($);G=G.where("created_at",">=",X).where("created_at","<=",W)}return(await G.execute()).reduce((X,{source:W,count:Z})=>{return X[W]=Z,X},{})}async function GX(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let N=P($),X=P(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",N).where("created_at","<=",X).executeTakeFirst())?.count??0}async function NX(J){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",J).executeTakeFirst())?.count??0}async function XX(J,$){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(J&&$){let X=P(J),W=P($);G=G.where("created_at",">=",X).where("created_at","<=",W)}return(await G.execute()).reduce((X,{quantity:W,count:Z})=>{return X[W]=Z,X},{})}async function WX(J,$){let G=P(J),N=P($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",N).whereNotNull("notified_at").execute()}async function ZX(J,$){let G=P(J),N=P($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",N).whereNotNull("purchased_at").execute()}async function YX(J,$){let G=P(J),N=P($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",N).whereNotNull("cancelled_at").execute()}async function LX(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function KX(J,$,G){let N=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",J);if($&&G){let W=P($),Z=P(G);N=N.where("created_at",">=",W).where("created_at","<=",Z)}return(await N.executeTakeFirst())?.count??0}async function FX(J,$){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(J&&$){let L=P(J),K=P($);G=G.where("created_at",">=",L).where("created_at","<=",K)}let N=await G.execute(),X=N.reduce((L,{count:K})=>L+K,0),W=N.find((L)=>L.status==="purchased")?.count??0,Z=X>0?W/X*100:0,Y=N.reduce((L,{status:K,count:Q})=>{return L[K]={count:Q,percentage:X>0?Q/X*100:0},L},{});return{totalConversionRate:Z,statusBreakdown:Y}}async function QX(J,$){let G=P(J),N=P($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",N).executeTakeFirst())?.count??0}async function MX(J,$){let G=A.selectFrom("waitlist_products").select(["created_at"]);if(J&&$){let W=P(J),Z=P($);G=G.where("created_at",">=",W).where("created_at","<=",Z)}let X=(await G.execute()).reduce((W,{created_at:Z})=>{let Y=(Z||"").split("T")[0]||"unknown";return W[Y]=(W[Y]||0)+1,W},{});return Object.entries(X).map(([W,Z])=>({date:W,count:Z})).sort((W,Z)=>W.date.localeCompare(Z.date))}var{randomUUIDv7:VX}=globalThis.Bun;import{db as H4}from"@stacksjs/database";import{formatDate as HX}from"@stacksjs/orm";var Z3={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Y3(J){return typeof J==="number"||J instanceof Date?HX(J):J}function n0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,X])=>X!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let X of["notified_at","purchased_at","cancelled_at"])if(G[X]!==void 0)G[X]=Y3(G[X]);let N=Z3[G.status];if(N&&G[N]===void 0&&!$[N])G[N]=HX(new Date);return G}async function xX(J){try{let $=VX(),G={...n0(J),uuid:$,status:J.status||"waiting"};await H4.insertInto("waitlist_products").values(G).executeTakeFirst();let N=await H4.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to create waitlist product");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function zX(J){if(!J.length)return 0;try{let $=J.map((N)=>({...n0(N),status:N.status||"waiting",uuid:VX()})),G=await H4.insertInto("waitlist_products").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as L3}from"@stacksjs/database";import{formatDate as K3}from"@stacksjs/orm";async function W1(J,$){try{if(!J)throw Error("Waitlist product ID is required for update");let G=await u0(J);if(!G)return;await L3.updateTable("waitlist_products").set({...n0($,G),updated_at:K3(new Date)}).where("id","=",J).execute();let N=await u0(J);if(!N)return;return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update waitlist product: ${G.message}`);throw G}}async function BX(J,$){return await W1(J,{status:$})}async function AX(J,$){return await W1(J,{quantity:$})}var O0={};z(O0,{updateWaitTimes:()=>uX,updateStatus:()=>lX,updateQueuePosition:()=>nX,updatePartySize:()=>cX,update:()=>R0,store:()=>mX,fetchWaitingWithQuotedTimes:()=>jX,fetchWaitingWithPartySizes:()=>CX,fetchWaiting:()=>fX,fetchTimeSeriesStats:()=>DX,fetchTablesTurnedToday:()=>hX,fetchSeatingRate:()=>IX,fetchSeatedStats:()=>yX,fetchSeatedBetweenDates:()=>qX,fetchNoShowStats:()=>gX,fetchCurrentWaitTimes:()=>vX,fetchCountByTablePreference:()=>SX,fetchCountByPartySize:()=>TX,fetchCountByDate:()=>UX,fetchCountByAllPartySizes:()=>PX,fetchConversionRates:()=>EX,fetchById:()=>i0,fetchBetweenDates:()=>wX,fetchAverageWaitTimes:()=>kX,fetchAll:()=>OX,destroy:()=>_X,bulkStore:()=>pX,bulkDestroy:()=>RX});import{db as V4}from"@stacksjs/database";async function _X(J){try{let $=await V4.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await V4.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function RX(J){if(!J.length)return 0;try{let $=await V4.deleteFrom("waitlist_restaurants").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as x}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function i0(J){return await x.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function OX(){return await x.selectFrom("waitlist_restaurants").selectAll().execute()}async function SX(){return(await x.selectFrom("waitlist_restaurants").select(["table_preference",x.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:G,count:N})=>{return $[G]=N,$},{})}async function UX(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let N=g($),X=g(G);return(await x.selectFrom("waitlist_restaurants").select(x.fn.count("id").as("count")).where("created_at",">=",N).where("created_at","<=",X).executeTakeFirst())?.count??0}async function TX(J){return(await x.selectFrom("waitlist_restaurants").select(x.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function PX(){return(await x.selectFrom("waitlist_restaurants").select(["party_size",x.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:G,count:N})=>{return $[G]=N,$},{})}async function wX(J,$){let G=g(J),N=g($);return await x.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",N).execute()}async function qX(J,$){let G=g(J),N=g($);return await x.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",N).where("status","=","seated").execute()}async function fX(){return await x.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function EX(){let J=await x.selectFrom("waitlist_restaurants").select(["status",x.fn.count("id").as("count")]).groupBy("status").execute(),$=J.reduce((W,{count:Z})=>W+Z,0),G=J.find((W)=>W.status==="seated")?.count??0,N=$>0?Number(G)/$*100:0,X=J.reduce((W,{status:Z,count:Y})=>{return W[Z]={count:Y,percentage:$>0?Y/$*100:0},W},{});return{totalConversionRate:N,statusBreakdown:X}}async function kX(){let J=await x.selectFrom("waitlist_restaurants").select([x.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),x.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:J?.avg_quoted_wait_time??0,averageActualWaitTime:J?.avg_actual_wait_time??0}}async function jX(){let J=await x.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((N,X)=>N+(X.quoted_wait_time??0),0),G=J.length>0?$/J.length:0;return{entries:J,totalQuotedWaitTime:$,averageQuotedWaitTime:G}}async function CX(){let J=await x.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((X,W)=>X+W.party_size,0),G=J.length>0?$/J.length:0,N=J.reduce((X,W)=>{return X[W.party_size]=(X[W.party_size]||0)+1,X},{});return{entries:J,totalPartySize:$,averagePartySize:G,partySizeBreakdown:N}}async function hX(){let J=new Date,$=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let N=g($),X=g(G),W=await x.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",N).where("check_in_time","<=",X).execute(),Z=W.length,Y=W.reduce((M,H)=>M+H.party_size,0),L=Z>0?Y/Z:0,K=W.reduce((M,H)=>{return M[H.table_preference]=(M[H.table_preference]||0)+1,M},{}),Q=W.reduce((M,H)=>{return M[H.party_size]=(M[H.party_size]||0)+1,M},{});return{totalTablesTurned:Z,averagePartySize:L,totalCustomersSeated:Y,breakdownByTablePreference:K,breakdownByPartySize:Q}}async function IX(J,$){let G=g(J),N=g($),X=await x.selectFrom("waitlist_restaurants").select(["status",x.fn.count("id").as("count")]).where("check_in_time",">=",G).where("check_in_time","<=",N).groupBy("status").execute(),W=X.reduce((K,{count:Q})=>K+Q,0),Z=X.find((K)=>K.status==="seated")?.count??0,Y=W>0?Number(Z)/W*100:0,L=X.reduce((K,{status:Q,count:M})=>{return K[Q]={count:M,percentage:W>0?M/W*100:0},K},{});return{totalEntries:W,seatedEntries:Z,seatingRate:Y,statusBreakdown:L}}async function gX(J,$){let G=g(J),N=g($),X=x.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",N),W=await x.selectFrom("waitlist_restaurants").select(x.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",N).executeTakeFirst(),Z=await X.execute(),Y=Z.length,L=W?.count&&W.count>0?Y/W.count*100:0,K=Z.reduce((R,S)=>R+(S.quoted_wait_time??0),0),Q=Y>0?K/Y:0,M=Z.reduce((R,S)=>R+S.party_size,0),H=Y>0?M/Y:0,_=Z.reduce((R,S)=>{return R[S.table_preference]=(R[S.table_preference]||0)+1,R},{}),O=Z.reduce((R,S)=>{return R[S.party_size]=(R[S.party_size]||0)+1,R},{});return{totalNoShows:Y,noShowRate:L,averageQuotedWaitTime:Q,averagePartySize:H,breakdownByTablePreference:_,breakdownByPartySize:O}}async function vX(){let J=await x.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=J.reduce((X,W)=>X+(W.quoted_wait_time||0),0),G=J.reduce((X,W)=>X+(W.actual_wait_time||0),0),N=J.length;return{averageQuoted:N>0?$/N:0,averageActual:N>0?G/N:0}}async function yX(){let J=Date.now()-86400000,$=await x.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),G=Array.from({length:24},(N,X)=>({hour:X,count:$.filter((W)=>{return W.seated_at===X}).length}));return{total:$.length,byHour:G}}async function DX(){return(await x.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,G)=>{let N=G.created_at;if(!$[N])$[N]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[N].total++,$[N][G.status]++,$},{})}var{randomUUIDv7:bX}=globalThis.Bun;import{db as z4}from"@stacksjs/database";import{formatDate as x4}from"@stacksjs/orm";var F3={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function Q3(J){if(typeof J==="number")return x4(J<=2147483647?J*1000:J);if(J instanceof Date)return x4(J);return J}function o0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,X])=>X!==void 0));for(let X of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[X]!==void 0)G[X]=Q3(G[X]);let N=F3[G.status];if(N&&G[N]===void 0&&!$[N])G[N]=x4(new Date);return G}async function mX(J){try{let $=bX(),G={...o0(J),status:J.status||"waiting",uuid:$};await z4.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let N=await z4.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to create restaurant waitlist entry");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function pX(J){if(!J.length)return 0;try{let $=J.map((N)=>({...o0(N),status:N.status||"waiting",uuid:bX()})),G=await z4.insertInto("waitlist_restaurants").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as M3}from"@stacksjs/database";import{formatDate as H3}from"@stacksjs/orm";async function R0(J,$){try{if(!J)throw Error("Restaurant waitlist entry ID is required for update");let G=await i0(J);if(!G)return;await M3.updateTable("waitlist_restaurants").set({...o0($,G),updated_at:H3(new Date)}).where("id","=",J).execute();let N=await i0(J);if(!N)return;return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${G.message}`);throw G}}async function lX(J,$){return await R0(J,{status:$})}async function cX(J,$){return await R0(J,{party_size:$})}async function uX(J,$,G){return await R0(J,{quoted_wait_time:$,...G===void 0?{}:{actual_wait_time:G}})}async function nX(J,$){return await R0(J,{queue_position:$})}var V3={products:Z1,restaurant:O0},x3=V3;var z3={coupons:Y1,customers:L1,devices:H1,errors:z1,giftCards:A1,orders:q1,payments:f1,products:g1,receipts:p1,restaurant:O0,shippings:F4,tax:Q4,waitlists:B4},mM=z3;export{B4 as waitlists,Q4 as tax,F4 as shippings,O0 as restaurant,p1 as receipts,g1 as products,f1 as payments,q1 as orders,A1 as giftCards,z1 as errors,H1 as devices,mM as default,L1 as customers,Y1 as coupons,z3 as commerce};
27
+ AND COALESCE(refund_amount, 0) + ${X(5)} <= amount`,[$,$,W,J,$]),Y=typeof Z?.execute==="function"?await Z.execute():Z;if(Number(Y?.numUpdatedRows??Y?.[0]?.numUpdatedRows??Y?.numAffectedRows??Y?.affectedRows??Y?.[0]?.affectedRows??Y?.changes??0)>0){let x=await Z0(J);if(x)return x;throw Error(`Payment with ID ${J} disappeared during refund`)}let N=await Z0(J);if(!N)throw Error(`Payment with ID ${J} not found`);let K=String(N.status||"");if(!m3.has(K))throw Error(`Payment status ${K||"unknown"} cannot be refunded`);let Q=N,H=Number(N.amount||0)-Number(Q.refundAmount??Q.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${H} minor units`)}var b1={};z(b1,{variants:()=>U$,units:()=>R$,reviews:()=>A$,manufacturers:()=>B$,items:()=>z$,default:()=>e3,categories:()=>M$});var M$={};z(M$,{updateParent:()=>N6,updateDisplayOrder:()=>Y6,updateActiveStatus:()=>L6,update:()=>Z6,store:()=>I1,removeChildCategories:()=>$6,remove:()=>rJ,findOrCreateByName:()=>W6,fetchStats:()=>dJ,fetchRootCategories:()=>iJ,fetchChildCategories:()=>oJ,fetchCategoryTree:()=>eJ,fetchByName:()=>uJ,fetchById:()=>k,fetchByDisplayOrder:()=>sJ,fetchAll:()=>h1,fetchActive:()=>nJ,deactivateChildCategories:()=>G6,deactivate:()=>J6,compareCategoryGrowth:()=>aJ,bulkRemove:()=>tJ});import{db as z0}from"@stacksjs/database";import{db as S}from"@stacksjs/database";import{formatDate as j0}from"@stacksjs/orm";async function h1(){return await S.selectFrom("categories").selectAll().execute()}async function k(J){return await S.selectFrom("categories").where("id","=",J).selectAll().executeTakeFirst()}async function uJ(J){return await S.selectFrom("categories").where("name","=",J).selectAll().executeTakeFirst()}async function nJ(){return await S.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function iJ(){return await S.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function oJ(J){return await S.selectFrom("categories").where("parent_category_id","=",J).where("is_active","=",!0).selectAll().execute()}async function sJ(J=!0){let $=S.selectFrom("categories").where("is_active","=",!0).selectAll();if(J)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function dJ(){let J=await S.selectFrom("categories").select(S.fn.count("id").as("count")).executeTakeFirst(),$=await S.selectFrom("categories").where("is_active","=",!0).select(S.fn.count("id").as("count")).executeTakeFirst(),G=await S.selectFrom("categories").whereNull("parent_category_id").select(S.fn.count("id").as("count")).executeTakeFirst(),X=await S.selectFrom("categories").whereNotNull("image_url").select(S.fn.count("id").as("count")).executeTakeFirst(),W=new Date;W.setDate(W.getDate()-30);let Z=j0(W),Y=await S.selectFrom("categories").where("created_at",">=",Z).selectAll().limit(5).execute(),L=await S.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",S.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number($?.count||0),root_categories:Number(G?.count||0),child_categories:Number(J?.count||0)-Number(G?.count||0),with_images:Number(X?.count||0),recently_added:Y,top_parent_categories:L.map((N)=>({id:String(N.parent_category_id||""),name:String(N.parent_name||""),child_count:Number(N.child_count)}))}}async function aJ(J=30){let $=new Date,G=j0($),X=new Date;X.setDate($.getDate()-J);let W=j0(X),Z=new Date(X);Z.setDate(Z.getDate()-1);let Y=j0(Z),L=new Date(Z);L.setDate(Z.getDate()-J);let N=j0(L),K=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",W).where("created_at","<=",G).executeTakeFirst(),Q=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",N).where("created_at","<=",Y).executeTakeFirst(),H=Number(K?.count||0),x=Number(Q?.count||0),_=H-x,R=x!==0?_/x*100:H>0?100:0;return{current_period:H,previous_period:x,difference:_,percentage_change:R,days_range:J}}async function eJ(){let J=await h1(),$=new Map;J.forEach((W)=>{$.set(W.id,{...W,children:[]})});let G=[];J.forEach((W)=>{let Z=$.get(W.id);if(W.parent_category_id){let Y=$.get(W.parent_category_id);if(Y)Y.children.push(Z)}else G.push(Z)}),G.sort((W,Z)=>W.display_order-Z.display_order);let X=(W)=>{W.sort((Z,Y)=>Z.display_order-Y.display_order),W.forEach((Z)=>{if(Z.children.length>0)X(Z.children)})};return X(G),G}async function rJ(J){let $=await z0.deleteFrom("categories").where("id","=",J).executeTakeFirst();return F($)>0}async function tJ(J){if(!J.length)return 0;let $=await z0.deleteFrom("categories").where("id","in",J).executeTakeFirst();return F($)}async function $6(J){let $=await z0.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return F($)}async function J6(J){if(!await k(J))throw Error(`Category with ID ${J} not found`);return!!await z0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",J).executeTakeFirst()}async function G6(J){let $=await z0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",J).execute();return Number($.length)||0}var{randomUUIDv7:p3}=globalThis.Bun;import{db as X6}from"@stacksjs/database";import{HttpError as x$}from"@stacksjs/error-handling";import{isUniqueViolation as l3}from"@stacksjs/orm";import{slug as c3}from"@stacksjs/strings";async function I1(J){try{let $=J.parent_category_id?Number(J.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new x$(422,"Parent category ID must be a positive integer");if($&&!await k($))throw new x$(422,`Parent category with ID ${J.parent_category_id} not found`);let G={...J,uuid:p3(),is_active:J.is_active??!0,parent_category_id:J.parent_category_id||null},X=await X6.insertInto("categories").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create category");return X}catch($){if($ instanceof x$)throw $;if(l3($))throw new x$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function W6(J){if(!J.name)throw Error("Name is required");let $=await X6.selectFrom("categories").selectAll().where("name","=",J.name).executeTakeFirst();if($)return $;let G={name:J.name,slug:c3(J.name),is_active:J.is_active??!0,display_order:0};return await I1(G)}import{db as C0}from"@stacksjs/database";import{HttpError as B0}from"@stacksjs/error-handling";import{formatDate as V$,isUniqueViolation as u3}from"@stacksjs/orm";async function Z6(J,$){if(!await k(J))return;if(Object.hasOwn($,"parent_category_id")){let X=$.parent_category_id?Number($.parent_category_id):void 0;if(X!==void 0&&(!Number.isSafeInteger(X)||X<=0))throw new B0(422,"Parent category ID must be a positive integer");if(X===J)throw new B0(422,"A category cannot be its own parent");if(X&&!await k(X))throw new B0(422,`Parent category with ID ${$.parent_category_id} not found`);if(X&&await K6(J,String(X)))throw new B0(422,"This operation would create a circular category hierarchy")}try{let X=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},W=await C0.updateTable("categories").set({...$,...X,updated_at:V$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!W)return;return W}catch(X){if(X instanceof B0)throw X;if(u3(X))throw new B0(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 Y6(J,$){if(!await k(J))throw Error(`Category with ID ${J} not found`);try{return await C0.updateTable("categories").set({display_order:$,updated_at:V$(new Date)}).where("id","=",J).execute(),await k(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category display order: ${X.message}`);throw X}}async function L6(J,$){if(!await k(J))throw Error(`Category with ID ${J} not found`);try{return await C0.updateTable("categories").set({is_active:$,updated_at:V$(new Date)}).where("id","=",J).execute(),await k(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function N6(J,$){if(!await k(J))throw Error(`Category with ID ${J} not found`);if($){let X=Number($);if(X===J)throw Error("A category cannot be its own parent");if(!await k(X))throw Error(`Parent category with ID ${$} not found`);if(await K6(J,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let X={updated_at:V$(new Date)};if($===null)await C0.updateTable("categories").set({...X,parent_category_id:null}).where("id","=",J).execute();else await C0.updateTable("categories").set({...X,parent_category_id:$}).where("id","=",J).execute();return await k(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category parent: ${X.message}`);throw X}}async function K6(J,$){let G=Number($),X=new Set;while(G){if(X.has(G))return!0;if(G===J)return!0;X.add(G);let W=await k(G),Z=W?.parent_category_id??W?.parentCategoryId;if(!W||!Z)return!1;G=Number(Z)}return!1}var z$={};z(z$,{updateInventory:()=>R6,updateAvailability:()=>O6,update:()=>_6,store:()=>B6,fetchTopProducts:()=>V6,fetchById:()=>u,fetchAll:()=>x6,destroy:()=>Q6,bulkStore:()=>A6,bulkDestroy:()=>H6});import{db as F6}from"@stacksjs/database";async function Q6(J){try{let $=await F6.deleteFrom("products").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function H6(J){if(!J.length)return 0;try{let $=await F6.deleteFrom("products").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as a,sql as n3}from"@stacksjs/database";async function u(J){let $=await a.selectFrom("products").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.manufacturer_id)G=await a.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)X=await a.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:G,category:X}}return}async function x6(){let J=await a.selectFrom("products").selectAll().execute(),$=J.map((K)=>K.manufacturer_id).filter((K)=>K!==null&&K!==void 0),G=J.map((K)=>K.category_id).filter((K)=>K!==null&&K!==void 0),X=a.selectFrom("manufacturers"),W=a.selectFrom("categories");if($.length>0)X=X.where("id","in",$);if(G.length>0)W=W.where("id","in",G);let Z=await X.selectAll().execute(),Y=await W.selectAll().execute(),L=Z.reduce((K,Q)=>{return K[Q.id]=Q,K},{}),N=Y.reduce((K,Q)=>{return K[Q.id]=Q,K},{});return J.map((K)=>({...K,manufacturer:K.manufacturer_id?L[K.manufacturer_id]:null,category:K.category_id?N[K.category_id]:null}))}async function V6(J=5){try{return(await a.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",a.fn.sum("order_items.quantity").as("units_sold"),n3`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(J).execute()).map((G)=>({id:Number(G.id),name:String(G.name??"Unnamed product"),units_sold:Number(G.units_sold??0),revenue:Number(G.revenue??0),inventory_count:Number(G.inventory_count??0)}))}catch($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:M6}=globalThis.Bun;import{db as z6}from"@stacksjs/database";async function B6(J){try{let $={...J,uuid:M6()},G=await z6.insertInto("products").values($).executeTakeFirst();if(!G)throw Error("Failed to create product item");let X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),W=await u(X);if(!W)throw Error("Failed to create product item");return W}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function A6(J){if(!J.length)return 0;let $=0;try{return await z6.transaction().execute(async(G)=>{for(let X of J){let W={...X,uuid:M6()};await G.insertInto("products").values(W).execute(),$++}}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as g1}from"@stacksjs/database";import{formatDate as v1}from"@stacksjs/orm";async function _6(J,$){try{if(!J)throw Error("Product item ID is required for update");let G=await g1.updateTable("products").set({...$,updated_at:v1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item: ${G.message}`);throw G}}async function O6(J,$){if(!await u(J))throw Error(`Product item with ID ${J} not found`);try{return await g1.updateTable("products").set({is_available:$,updated_at:v1(new Date)}).where("id","=",J).execute(),await u(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item availability: ${X.message}`);throw X}}async function R6(J,$){let G=await u(J);if(!G)throw Error(`Product item with ID ${J} not found`);let X={updated_at:v1(new Date)};if($!==void 0)X.inventory_count=$;if(Object.keys(X).length===1)return G;try{return await g1.updateTable("products").set(X).where("id","=",J).execute(),await u(J)}catch(W){if(W instanceof Error)throw TypeError(`Failed to update inventory information: ${W.message}`);throw W}}var B$={};z(B$,{updateFeaturedStatus:()=>y6,updateByUuid:()=>b6,update:()=>D6,store:()=>I6,fetchWithProductCount:()=>k6,fetchFeatured:()=>f6,fetchByUuid:()=>E6,fetchById:()=>T6,fetchByCountry:()=>q6,fetchAll:()=>w6,destroy:()=>P6,bulkStore:()=>g6,bulkDestroy:()=>S6});import{db as U6}from"@stacksjs/database";async function P6(J){try{let $=await U6.deleteFrom("manufacturers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function S6(J){if(!J.length)return 0;try{let $=await U6.deleteFrom("manufacturers").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as n}from"@stacksjs/database";function w6(){return n.selectFrom("manufacturers").selectAll().execute()}async function T6(J){return await n.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function E6(J){return await n.selectFrom("manufacturers").where("uuid","=",J).selectAll().executeTakeFirst()}async function f6(J=10){return await n.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(J).execute()}async function q6(J,$={}){let G=$.page||1,X=$.limit||2,W=await n.selectFrom("manufacturers").select(n.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),Z=Number(W?.total||0),Y=await n.selectFrom("manufacturers").selectAll().where("country","=",J).limit(X).offset((G-1)*X).execute(),L=Math.ceil(Z/X);return{data:Y,paging:{total_records:Z,page:G,total_pages:L},next_cursor:G<L?G+1:null}}async function k6(J={}){let $=n.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(J.country)$=$.where("m.country","=",J.country);if(J.featured!==void 0)$=$.where("m.featured","=",J.featured);return $=$.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",n.fn.count("p.id").as("product_count")]).groupBy("m.id"),$.execute()}var{randomUUIDv7:C6}=globalThis.Bun;import{db as h6}from"@stacksjs/database";import{HttpError as j6}from"@stacksjs/error-handling";import{isUniqueViolation as i3}from"@stacksjs/orm";async function I6(J){try{let $={...J,uuid:C6(),featured:J.featured??!1},G=await h6.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch($){if($ instanceof j6)throw $;if(i3($))throw new j6(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function g6(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:C6(),featured:G.featured??!1};await h6.insertInto("manufacturers").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${G.message}`);throw G}}import{db as D1}from"@stacksjs/database";import{HttpError as v6}from"@stacksjs/error-handling";import{formatDate as y1,isUniqueViolation as o3}from"@stacksjs/orm";async function D6(J,$){try{if(!J)throw Error("Manufacturer ID is required for update");let G=await D1.updateTable("manufacturers").set({...$,updated_at:y1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof v6)throw G;if(o3(G))throw new v6(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function y6(J,$){try{let G=await D1.updateTable("manufacturers").set({featured:$,updated_at:y1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer featured status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${G.message}`);throw G}}async function b6(J,$){try{let G=await D1.updateTable("manufacturers").set({...$,updated_at:y1(new Date)}).where("uuid","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer: ${G.message}`);throw G}}var A$={};z(A$,{updateVotes:()=>t6,update:()=>r6,store:()=>d6,fetchMostHelpfulByProductId:()=>s6,fetchByUserId:()=>i6,fetchByProductId:()=>n6,fetchById:()=>c6,fetchApprovedByProductId:()=>o6,fetchAll:()=>u6,destroy:()=>p6,bulkDestroy:()=>l6});import{db as m6}from"@stacksjs/database";async function p6(J){try{let $=await m6.deleteFrom("reviews").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function l6(J){if(!J.length)return 0;try{let $=await m6.deleteFrom("reviews").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as A0}from"@stacksjs/database";async function c6(J){return await A0.selectFrom("reviews").where("id","=",J).selectAll().executeTakeFirst()}async function u6(){return await A0.selectFrom("reviews").selectAll().execute()}async function n6(J){return await A0.selectFrom("reviews").where("product_id","=",J).selectAll().execute()}async function i6(J){return await A0.selectFrom("reviews").where("customer_id","=",J).selectAll().execute()}async function o6(J){return await A0.selectFrom("reviews").where("product_id","=",J).where("is_approved","=",!0).selectAll().execute()}async function s6(J){return await A0.selectFrom("reviews").where("product_id","=",J).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:s3}=globalThis.Bun;import{db as d3}from"@stacksjs/database";async function d6(J){try{let $={...J,uuid:s3(),is_verified_purchase:J.is_verified_purchase??!1,is_approved:J.is_approved??!1,helpful_votes:J.helpful_votes??0,unhelpful_votes:J.unhelpful_votes??0,is_featured:J.is_featured??!1},G=await d3.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create review");return G}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${$.message}`)}throw $}}import{db as a6}from"@stacksjs/database";import{formatDate as e6}from"@stacksjs/orm";async function r6(J,$){try{if(!J)throw Error("Review ID is required for update");let G=await a6.updateTable("reviews").set({...$,updated_at:e6(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review: ${G.message}`);throw G}}async function t6(J,$,G=!0){try{let X=$==="helpful"?"helpful_votes":"unhelpful_votes",W=G?`COALESCE("${X}", 0) + 1`:`MAX(COALESCE("${X}", 0) - 1, 0)`,Z=await a6.unsafe(`UPDATE "reviews" SET "${X}" = ${W}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[e6(new Date),J]).execute(),Y=Array.isArray(Z)?Z[0]:Z;if(!Y)throw Error("Failed to update review votes");return Y}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var R$={};z(R$,{updateDefaultStatus:()=>x2,update:()=>Q2,store:()=>L2,getDefaultUnit:()=>F2,formatUnitOptions:()=>K2,fetchById:()=>W2,fetchAll:()=>Z2,destroy:()=>J2,bulkUpdate:()=>H2,bulkStore:()=>N2,bulkDestroy:()=>G2});import{db as $2}from"@stacksjs/database";async function J2(J){try{let $=await $2.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function G2(J){if(!J.length)return 0;try{let $=await $2.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as X2}from"@stacksjs/database";async function W2(J){return await X2.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function Z2(){return await X2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:Y2}=globalThis.Bun;import{db as h0}from"@stacksjs/database";async function L2(J){try{return await h0.transaction(async($)=>{let G={...J,uuid:Y2()},X=await $.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(G.is_default&&G.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();return X})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function N2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:Y2()},W=await h0.insertInto("product_units").values(X).returningAll().executeTakeFirst();if(X.is_default&&X.type&&W)await h0.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",W.id).execute();$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function K2(J){try{let $=h0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(J)$=$.where("type","=",J);return $=$.orderBy("name"),$.execute().then((G)=>G.map((X)=>({id:String(X.id),name:X.name,abbreviation:X.abbreviation,is_default:X.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function F2(J){try{return await h0.selectFrom("product_units").selectAll().where("type","=",J).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as _$}from"@stacksjs/database";import{formatDate as O$}from"@stacksjs/orm";async function Q2(J,$){try{if(!J)throw Error("Product unit ID is required for update");return await _$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",J).executeTakeFirst();if(!X)return;let W=$.type??X.type;if(($.is_default??Boolean(X.is_default))&&W)await G.updateTable("product_units").set({is_default:!1,updated_at:O$(new Date)}).where("type","=",W).where("id","!=",J).execute();let Y=await G.updateTable("product_units").set({...$,updated_at:O$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function H2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X=G;if(!X.id)continue;let W=X.data&&typeof X.data==="object"?X.data:{...X};delete W.id;let Z=await _$.updateTable("product_units").set({...W,updated_at:O$(new Date)}).where("id","=",X.id).executeTakeFirst(),Y=W;if(Y.is_default===!0&&Y.type)await _$.updateTable("product_units").set({is_default:!1}).where("type","=",Y.type).where("id","!=",X.id).execute();if(Number(Z.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function x2(J,$){try{return await _$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!X)return!1;let W=O$(new Date);if($&&X.type)await G.updateTable("product_units").set({is_default:!1,updated_at:W}).where("type","=",X.type).where("id","!=",J).execute();return await G.updateTable("product_units").set({is_default:$,updated_at:W}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var U$={};z(U$,{update:()=>f2,store:()=>U2,generateVariantCombinations:()=>w2,formatVariantOptions:()=>S2,fetchById:()=>A2,fetchAll:()=>_2,destroy:()=>M2,bulkUpdate:()=>q2,bulkStore:()=>P2,bulkDestroy:()=>z2});import{db as V2}from"@stacksjs/database";async function M2(J){try{let $=await V2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function z2(J){if(!J.length)return 0;try{let $=await V2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as B2}from"@stacksjs/database";async function A2(J){return await B2.selectFrom("product_variants").where("id","=",J).selectAll().executeTakeFirst()}async function _2(){return await B2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:O2}=globalThis.Bun;import{db as R2}from"@stacksjs/database";async function U2(J){try{let $={...J,uuid:O2()},G=await R2.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product variant");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function P2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:O2()};await R2.insertInto("product_variants").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${G.message}`);throw G}}function S2(J){if(!J||!J.length)return JSON.stringify([]);let $=J.map((G)=>G.trim()).filter(Boolean);return JSON.stringify($)}function w2(J){let $=Object.keys(J);if(!$.length)return[];function G(X,W){if(X===$.length)return[W];let Z=$[X],Y=J[Z]??[],L=[];for(let N of Y){let K={...W,[Z]:N};L.push(...G(X+1,K))}return L}return G(0,{})}import{db as T2}from"@stacksjs/database";import{formatDate as E2}from"@stacksjs/orm";async function f2(J,$){try{let G=await T2.updateTable("product_variants").set({...$,updated_at:E2(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variant: ${G.message}`);throw G}}async function q2(J){if(!J.length)return 0;let $=0;try{for(let G of J){if(!G.id)continue;let X=await T2.updateTable("product_variants").set({...G,updated_at:E2(new Date)}).where("id","=",G.id).executeTakeFirst();if(Number(X.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${G.message}`);throw G}}var a3={categories:M$,items:z$,manufacturers:B$,reviews:A$,units:R$,variants:U$},e3=a3;var n1={};z(n1,{updateStatus:()=>c2,updatePrintJob:()=>u2,update:()=>l2,store:()=>m2,fetchSuccessRate:()=>g2,fetchPrintsPerHour:()=>y2,fetchPrintTimeStats:()=>D2,fetchPrintJobStats:()=>I2,fetchPageStats:()=>v2,fetchById:()=>_0,fetchAll:()=>h2,destroy:()=>j2,bulkStore:()=>p2,bulkDestroy:()=>C2});import{db as k2}from"@stacksjs/database";async function j2(J){try{let $=await k2.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function C2(J){if(!J.length)return 0;try{let $=await k2.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as m1}from"@stacksjs/database";import{formatDate as r3}from"@stacksjs/orm";function b(J){return r3(J)}function t3(J){if(J instanceof Date)return Number.isNaN(J.getTime())?null:J;if(typeof J==="number"){let X=new Date(J<=2147483647?J*1000:J);return Number.isNaN(X.getTime())?null:X}let $=String(J||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let X=new Date(Number($)*1000);return Number.isNaN(X.getTime())?null:X}let G=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function _0(J){return await m1.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function h2(){return await m1.selectFrom("receipts").selectAll().execute()}async function I2(J,$){let G=b(J),X=b($),W=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"}},(Z)=>Z.where("timestamp",">=",G).where("timestamp","<=",X));return{total:W.total,success:W.success,failed:W.failed,warning:W.warning,averageSize:Math.round(W.averageSize),averagePages:Math.round(W.averagePages),averageDuration:Math.round(W.averageDuration)}}async function g2(J,$){let G=b(J),X=b($),W=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"}}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{successRate:W.total>0?Math.round(W.success/W.total*100):0,total:W.total,success:W.success,failed:W.failed,warning:W.warning}}async function v2(J,$){let G=b(J),X=b($),W=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(Z)=>Z.where("timestamp",">=",G).where("timestamp","<=",X));return{totalPages:W.totalPages,averagePagesPerReceipt:Math.round(W.averagePagesPerReceipt),totalReceipts:W.totalReceipts}}async function D2(J,$){let G=b(J),X=b($),W=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(Z)=>Z.where("timestamp",">=",G).where("timestamp","<=",X));return{averageDuration:Math.round(W.averageDuration),minDuration:W.minDuration,maxDuration:W.maxDuration,totalJobs:W.totalJobs}}async function y2(J,$){let G=typeof J==="number"?J:J.getTime(),X=typeof $==="number"?$:$.getTime(),W=b(J),Z=b($),Y=await m1.selectFrom("receipts").where("timestamp",">=",W).where("timestamp","<=",Z).selectAll().execute(),L=Y.length,N=Math.ceil((X-G)/3600000),K=N>0?Math.round(L/N):0,Q=Array.from({length:24},(H,x)=>({hour:x,count:0}));return Y.forEach((H)=>{let x=t3(H.timestamp);if(!x)return;Q[x.getHours()].count++}),{totalPrints:L,totalHours:N,printsPerHour:K,hourlyBreakdown:Q}}var{randomUUIDv7:b2}=globalThis.Bun;import{db as l1}from"@stacksjs/database";import{formatDate as p1}from"@stacksjs/orm";function I0(J){try{if(typeof J==="number")return p1(J<=2147483647?J*1000:J);if(typeof J==="string"&&/^\d{10}$/.test(J))return p1(Number(J)*1000);return p1(J)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function m2(J){try{let $=b2(),G={...J,timestamp:I0(J.timestamp),uuid:$};await l1.insertInto("receipts").values(G).executeTakeFirst();let X=await l1.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function p2(J){if(!J.length)return 0;try{let $=J.map((X)=>({...X,timestamp:I0(X.timestamp),uuid:b2()})),G=await l1.insertInto("receipts").values($).executeTakeFirst();return Number(G.numInsertedOrUpdatedRows??G.numAffectedRows??G.affectedRows??G.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as c1}from"@stacksjs/database";import{formatDate as u1}from"@stacksjs/orm";async function l2(J,$){try{if(!J)throw Error("Receipt ID is required for update");let G={...$,...$.timestamp===void 0?{}:{timestamp:I0($.timestamp)},updated_at:u1(new Date)};await c1.updateTable("receipts").set(G).where("id","=",J).execute();let X=await _0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function c2(J,$){try{await c1.updateTable("receipts").set({status:$,updated_at:u1(new Date)}).where("id","=",J).execute();let G=await _0(J);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function u2(J,$,G,X){try{let W={updated_at:u1(new Date)};if($!==void 0)W.size=$;if(G!==void 0)W.pages=G;if(X!==void 0)W.duration=X;await c1.updateTable("receipts").set(W).where("id","=",J).execute();let Z=await _0(J);if(!Z)throw Error("Failed to update receipt job information");return Z}catch(W){if(W instanceof Error)throw TypeError(`Failed to update receipt job information: ${W.message}`);throw W}}var V4={};z(V4,{zones:()=>Y1,tracking:()=>G1,routes:()=>f$,rates:()=>s$,methods:()=>c$,licenses:()=>b$,geocoding:()=>v$,drivers:()=>C$,digital:()=>k$,default:()=>PW});var f$={};z(f$,{validateDeliveryRouteWrite:()=>O0,updateStops:()=>$G,updateMetrics:()=>JG,updateLastActive:()=>r2,update:()=>t2,store:()=>e2,fetchById:()=>S$,fetchByDriver:()=>a2,fetchAll:()=>s2,fetchActive:()=>d2,destroy:()=>i2,bulkDestroy:()=>o2,DeliveryRouteInputError:()=>h});import{db as n2}from"@stacksjs/database";async function i2(J){try{let $=await n2.deleteFrom("delivery_routes").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function o2(J){if(!J.length)return 0;try{let $=await n2.deleteFrom("delivery_routes").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as P$}from"@stacksjs/database";async function S$(J){return await P$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function s2(){return await P$.selectFrom("delivery_routes").selectAll().execute()}async function d2(){return await P$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function a2(J){return await P$.selectFrom("delivery_routes").where("driver","=",J).selectAll().execute()}var{randomUUIDv7:GW}=globalThis.Bun;import{db as i1}from"@stacksjs/database";function Y0(J,$){let G={};for(let[X,W]of Object.entries($))for(let Z of W){if(!Object.prototype.hasOwnProperty.call(J,Z)||J[Z]===void 0)continue;G[X]=J[Z];break}return G}function g0(J){return Y0(J,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function i(J){return Y0(J,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function v0(J){return Y0(J,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function D0(J){return Y0(J,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function y0(J){return Y0(J,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function b0(J){return Y0(J,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function w$(J){return Y0(J,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as $W}from"@stacksjs/database";class h extends TypeError{constructor(J){super(J);this.name="DeliveryRouteInputError"}}function T$(J,$,G){return Number(J[G]??$?.[G])}function JW(J,$){let G=J.last_active??$?.last_active;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 O0(J,$){let G=T$(J,$,"driver_id"),X=T$(J,$,"stops"),W=T$(J,$,"delivery_time"),Z=T$(J,$,"total_distance"),Y=JW(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(W)||W<0)throw new h("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new h("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(Y)||Y<0)throw new h("Last active must be a valid Unix timestamp.");let L=await $W.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!L)throw new h(`Driver ${G} was not found.`);return{...J,driver_id:Number(L.id),driver:L.name,vehicle:L.vehicle_number}}async function e2(J){try{let $=GW(),G=w$(J),W={...await O0(G),uuid:$};await i1.insertInto("delivery_routes").values(W).executeTakeFirst();let Z=await i1.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to create delivery route");return Z}catch($){if($ instanceof h)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function r2(J){try{await i1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",J).execute();let $=await S$(J);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as E$}from"@stacksjs/database";import{formatDate as o1}from"@stacksjs/orm";async function t2(J,$){try{if(!J)throw Error("Delivery route ID is required for update");let G=await E$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=w$($),W=await O0(X,G),Z=await E$.updateTable("delivery_routes").set({...W,updated_at:o1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}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 $G(J,$){try{let G=await E$.updateTable("delivery_routes").set({stops:$,updated_at:o1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update delivery route stops");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery route stops: ${G.message}`);throw G}}async function JG(J,$,G){try{let X={updated_at:o1(new Date)};if($!==void 0)X.delivery_time=$;if(G!==void 0)X.total_distance=G;let W=await E$.updateTable("delivery_routes").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!W)throw Error("Failed to update delivery metrics");return W}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery metrics: ${X.message}`);throw X}}var k$={};z(k$,{updateStatus:()=>xG,updateDeliverySettings:()=>VG,update:()=>HG,store:()=>FG,softDelete:()=>XG,fetchById:()=>LG,fetchAll:()=>NG,destroy:()=>GG,bulkStore:()=>QG,bulkSoftDelete:()=>ZG,bulkDestroy:()=>WG});import{db as q$}from"@stacksjs/database";async function GG(J){try{let $=await q$.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function XG(J){try{let $=await q$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function WG(J){if(!J.length)return 0;try{let $=await q$.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function ZG(J){if(!J.length)return 0;try{let $=await q$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as YG}from"@stacksjs/database";async function LG(J){return await YG.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function NG(){return await YG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:KG}=globalThis.Bun;import{db as s1}from"@stacksjs/database";async function FG(J){try{let $=KG(),G={...D0(J),uuid:$};await s1.insertInto("digital_deliveries").values(G).executeTakeFirst();let X=await s1.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created digital delivery");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function QG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...D0(X),uuid:KG()})),G=await s1.insertInto("digital_deliveries").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as d1}from"@stacksjs/database";import{formatDate as a1}from"@stacksjs/orm";async function HG(J,$){try{if(!J)throw Error("Digital delivery ID is required for update");let G=await d1.updateTable("digital_deliveries").set({...D0($),updated_at:a1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery: ${G.message}`);throw G}}async function xG(J,$){try{let G=await d1.updateTable("digital_deliveries").set({status:$,updated_at:a1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update digital delivery status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery status: ${G.message}`);throw G}}async function VG(J,$,G,X,W){try{let Z={updated_at:a1(new Date)};if($!==void 0)Z.download_limit=$;if(G!==void 0)Z.expiry_days=G;if(X!==void 0)Z.requires_login=X;if(W!==void 0)Z.automatic_delivery=W;let Y=await d1.updateTable("digital_deliveries").set(Z).where("id","=",J).returningAll().executeTakeFirst();if(!Y)throw Error("Failed to update delivery settings");return Y}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update delivery settings: ${Z.message}`);throw Z}}var C$={};z(C$,{updateStatus:()=>SG,updateContact:()=>wG,update:()=>PG,store:()=>RG,fetchById:()=>j$,fetchAll:()=>zG,destroy:()=>AG,bulkStore:()=>UG,bulkDestroy:()=>_G});import{db as BG}from"@stacksjs/database";import{db as MG}from"@stacksjs/database";async function j$(J){return await MG.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function zG(){return await MG.selectFrom("drivers").selectAll().execute()}async function AG(J){try{let $=await BG.deleteFrom("drivers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function _G(J){if(!J.length)return 0;let $=0;try{return await BG.transaction().execute(async(G)=>{for(let X of J)if(await j$(X))await G.deleteFrom("drivers").where("id","=",X).execute(),$++}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${G.message}`);throw G}}var{randomUUIDv7:OG}=globalThis.Bun;import{db as e1}from"@stacksjs/database";async function RG(J){try{let $=OG(),G={...b0(J),uuid:$};await e1.insertInto("drivers").values(G).executeTakeFirst();let X=await e1.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created driver");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function UG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...b0(X),uuid:OG()})),G=await e1.insertInto("drivers").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as r1}from"@stacksjs/database";import{formatDate as t1}from"@stacksjs/orm";async function PG(J,$){try{if(!J)throw Error("Driver ID is required for update");let G=await r1.updateTable("drivers").set({...b0($),updated_at:t1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver: ${G.message}`);throw G}}async function SG(J,$){try{let G=await r1.updateTable("drivers").set({status:$,updated_at:t1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update driver status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver status: ${G.message}`);throw G}}async function wG(J,$){try{let G={updated_at:t1(new Date)};if($!==void 0)G.phone=$;let X=await r1.updateTable("drivers").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update contact information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update contact information: ${G.message}`);throw G}}var v$={};z(v$,{setGeocodingDriver:()=>YW,nominatimDriver:()=>g$,geocodingDriver:()=>jG,geocode:()=>LW,formatQuery:()=>R0,checkCoverage:()=>NW,PRECISION_RANK:()=>p0});var L0=(J)=>J*Math.PI/180;function e(J,$){let G=L0($.latitude-J.latitude),X=L0($.longitude-J.longitude),W=L0(J.latitude),Z=L0($.latitude),Y=Math.sin(G/2)**2+Math.sin(X/2)**2*Math.cos(W)*Math.cos(Z);return 12742017.6*Math.asin(Math.sqrt(Y))}function h$(J,$){let G=L0(J.latitude),X=L0($.latitude),W=L0($.longitude-J.longitude),Z=Math.sin(W)*Math.cos(X),Y=Math.cos(G)*Math.sin(X)-Math.sin(G)*Math.cos(X)*Math.cos(W);return(Math.atan2(Z,Y)*180/Math.PI+360)%360}function I$(J,$,G={}){let X=G.detourFactor??1.35,W=G.minimumSeconds??30;if(!Number.isFinite($)||$<=0.5)return null;let Z=J*X/$;return Math.max(W,Math.round(Z))}function TG(J,$,G){return e(J,$)<=G}function m0(J){return typeof J?.latitude==="number"&&typeof J?.longitude==="number"&&Number.isFinite(J.latitude)&&Number.isFinite(J.longitude)}var p0={unknown:0,locality:1,postal:2,street:3,rooftop:4};function R0(J){return[J.street,J.city,J.region,J.postalCode,J.country].map(($)=>String($??"").trim()).filter(Boolean).join(", ")}var XW="https://nominatim.openstreetmap.org/search",EG=1000,fG=0,qG=Promise.resolve();async function WW(J){let $=qG.then(async()=>{let G=Date.now()-fG;if(G<EG)await Bun.sleep(EG-G);return fG=Date.now(),J()});return qG=$.then(()=>{return},()=>{return}),$}function ZW(J){let $=J.address??{},G=String(J.addresstype??""),X=String(J.type??""),W=String(J.category??J.class??"");if($.house_number||X==="house"||X==="building"||G==="building")return"rooftop";if($.road||W==="highway"||G==="road")return"street";if(G==="postcode"||$.postcode&&!$.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(G))return"locality";return"unknown"}function g$(J={}){let $=J.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,G=J.endpoint??XW;return{name:"nominatim",async geocode(X){let W=R0(X);if(!W)return null;let Z=new URL(G);if(Z.searchParams.set("q",W),Z.searchParams.set("format","jsonv2"),Z.searchParams.set("limit","1"),Z.searchParams.set("addressdetails","1"),X.country)Z.searchParams.set("countrycodes",X.country.toLowerCase());let Y=await WW(()=>fetch(Z,{headers:{"user-agent":$,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!Y.ok)throw Error(`Nominatim responded ${Y.status}`);let N=(await Y.json())?.[0];if(!N)return null;let K=Number(N.lat),Q=Number(N.lon);if(!Number.isFinite(K)||!Number.isFinite(Q))return null;let H=ZW(N);return{latitude:K,longitude:Q,formatted:String(N.display_name??W),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[H],precision:H,provider:"nominatim"}}}}var kG=null;function YW(J){kG=J}function jG(){return kG??g$()}async function LW(J,$={}){let G=$.driver??jG(),X=$.minimumPrecision??"street",W=`geocode:${G.name}:${R0(J).toLowerCase()}`,Z=await KW(W);if(Z!==void 0)return Z;let Y=await G.geocode(J),L=Y&&p0[Y.precision]>=p0[X]?Y:null;return await FW(W,L,L?$.cacheSeconds??2592000:600),L}function NW(J,$,G){if($.length===0)return null;let X=$[0],W=e(J,X);for(let Z of $.slice(1)){let Y=e(J,Z);if(Y<W)W=Y,X=Z}return{covered:W<=G,distanceMeters:Math.round(W),nearest:X}}async function KW(J){try{let G=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!G)return;let X=await G.get(J);if(X===null||X===void 0)return;return X==="null"?null:JSON.parse(String(X))}catch{return}}async function FW(J,$,G){try{let W=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!W)return;await W.set(J,$===null?"null":JSON.stringify($),G)}catch{}}var b$={};z(b$,{validateLicenseKeyWrite:()=>N0,updateStatus:()=>nG,updateExpiration:()=>iG,update:()=>uG,store:()=>lG,softDelete:()=>hG,fetchById:()=>DG,fetchAll:()=>yG,destroy:()=>CG,bulkStore:()=>cG,bulkSoftDelete:()=>gG,bulkDestroy:()=>IG,LicenseKeyInputError:()=>T});import{db as D$}from"@stacksjs/database";async function CG(J){try{let $=await D$.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function hG(J){try{let $=await D$.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function IG(J){if(!J.length)return 0;try{let $=await D$.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function gG(J){if(!J.length)return 0;try{let $=await D$.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as vG}from"@stacksjs/database";async function DG(J){return await vG.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst()}async function yG(){return await vG.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:pG}=globalThis.Bun;import{db as G4}from"@stacksjs/database";import{db as $4}from"@stacksjs/database";var bG=["Standard License","Premium License","Enterprise License"],mG=["active","inactive","unassigned"];class T extends TypeError{constructor(J){super(J);this.name="LicenseKeyInputError"}}function l0(J,$,G){return J[G]!==void 0?J[G]:$?.[G]}function J4(J,$,G,X){let W=l0(J,$,G);if(W===void 0||W===null||W==="")return null;let Z=Number(W);if(!Number.isSafeInteger(Z)||Z<1)throw new T(`${X} must be a positive integer or null.`);return Z}function QW(J){if(typeof J==="number")return J>2147483647?Math.floor(J/1000):J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return J.length===13?Math.floor(Number(J)/1000):Number(J);if(typeof J==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(J)?`${J.replace(" ","T")}Z`:J;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function N0(J,$){let G=String(l0(J,$,"key")||"").trim().toUpperCase(),X=String(l0(J,$,"template")||""),W=String(l0(J,$,"status")||""),Z=QW(l0(J,$,"expiry_date")),Y=J4(J,$,"customer_id","Customer"),L=J4(J,$,"product_id","Product"),N=J4(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(!bG.includes(X))throw new T(`Template must be one of: ${bG.join(", ")}.`);if(!mG.includes(W))throw new T(`Status must be one of: ${mG.join(", ")}.`);if(!Number.isSafeInteger(Z)||Z<0||Z>2147483647)throw new T("Expiry date must be a Unix timestamp between 1970 and 2038.");let[K,Q,H]=await Promise.all([Y?$4.selectFrom("customers").where("id","=",Y).select("id").executeTakeFirst():null,L?$4.selectFrom("products").where("id","=",L).select("id").executeTakeFirst():null,N?$4.selectFrom("orders").where("id","=",N).select(["id","customer_id"]).executeTakeFirst():null]);if(Y&&!K)throw new T(`Customer ${Y} was not found.`);if(L&&!Q)throw new T(`Product ${L} was not found.`);if(N&&!H)throw new T(`Order ${N} was not found.`);if(Y&&H?.customer_id&&Number(H.customer_id)!==Y)throw new T(`Order ${N} belongs to Customer ${H.customer_id}, not Customer ${Y}.`);return{...J,key:G,template:X,expiry_date:Z,status:W,customer_id:Y,product_id:L,order_id:N}}async function lG(J){try{let $=pG(),G=y0(J),X={...await N0(G),uuid:$};await G4.insertInto("license_keys").values(X).executeTakeFirst();let W=await G4.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!W)throw Error("Failed to resolve created license key");return W}catch($){if($ instanceof T)throw $;if($ instanceof Error){if($.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: ${$.message}`)}throw $}}async function cG(J){if(!J.length)return 0;try{let $=await Promise.all(J.map(async(X)=>({...await N0(y0(X)),uuid:pG()}))),G=await G4.insertInto("license_keys").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof T)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as y$}from"@stacksjs/database";import{formatDate as X4}from"@stacksjs/orm";async function uG(J,$){try{if(!J)throw Error("License key ID is required for update");let G=await y$.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=y0($),W=await N0(X,G),Z=await y$.updateTable("license_keys").set({...W,updated_at:X4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}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 nG(J,$){try{let G=await y$.updateTable("license_keys").set({status:$,updated_at:X4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update license key status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update license key status: ${G.message}`);throw G}}async function iG(J,$){try{let G={updated_at:X4(new Date)};if($!==void 0)G.expiry_date=$;let X=await y$.updateTable("license_keys").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update expiration information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update expiration information: ${G.message}`);throw G}}var c$={};z(c$,{updateStatus:()=>WX,updatePricing:()=>ZX,update:()=>XX,store:()=>tG,softDelete:()=>sG,getActiveShippingMethods:()=>GX,formatShippingOptions:()=>JX,fetchById:()=>l$,fetchAll:()=>eG,destroy:()=>oG,bulkStore:()=>$X,bulkSoftDelete:()=>aG,bulkDestroy:()=>dG});import{db as m$}from"@stacksjs/database";async function oG(J){try{let $=await m$.deleteFrom("shipping_methods").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function sG(J){try{let $=await m$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function dG(J){if(!J.length)return 0;try{let $=await m$.deleteFrom("shipping_methods").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function aG(J){if(!J.length)return 0;try{let $=await m$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as p$}from"@stacksjs/database";async function l$(J){let $=await p$.selectFrom("shipping_methods").where("id","=",J).selectAll().executeTakeFirst();if($){let G=await p$.selectFrom("shipping_zones").where("shipping_method_id","=",J).selectAll().execute();return{...$,shippingZones:G}}return}async function eG(){let J=await p$.selectFrom("shipping_methods").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((Z)=>Z.id))],W=(await p$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((Z,Y)=>{let L=Y.shipping_method_id;if(L!==null&&L!==void 0){if(!Z[L])Z[L]=[];Z[L].push(Y)}return Z},{});return J.map((Z)=>({...Z,shipping_zones:W[Z.id]||[]}))}var{randomUUIDv7:rG}=globalThis.Bun;import{db as c0}from"@stacksjs/database";async function tG(J){try{let $=rG(),G={...g0(J),uuid:$};await c0.insertInto("shipping_methods").values(G).executeTakeFirst();let X=await c0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping method");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function $X(J){if(!J.length)return 0;try{let $=J.map((X)=>({...g0(X),uuid:rG()})),G=await c0.insertInto("shipping_methods").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function JX(){try{return c0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping options: ${J.message}`);throw J}}async function GX(){try{return await c0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping methods: ${J.message}`);throw J}}import{db as W4}from"@stacksjs/database";import{formatDate as Z4}from"@stacksjs/orm";async function XX(J,$){try{if(!J)throw Error("Shipping method ID is required for update");let G=await W4.updateTable("shipping_methods").set({...g0($),updated_at:Z4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method: ${G.message}`);throw G}}async function WX(J,$){try{let G=await W4.updateTable("shipping_methods").set({status:$,updated_at:Z4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping method status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method status: ${G.message}`);throw G}}async function ZX(J,$,G){try{let X={updated_at:Z4(new Date)};if($!==void 0)X.base_rate=$;if(G!==void 0)X.free_shipping=G;let W=await W4.updateTable("shipping_methods").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!W)throw Error("Failed to update pricing information");return W}catch(X){if(X instanceof Error)throw TypeError(`Failed to update pricing information: ${X.message}`);throw X}}var s$={};z(s$,{validateZoneMatchesAddress:()=>MX,validateShippingRateWrite:()=>K0,updateByZone:()=>EX,updateByMethod:()=>fX,update:()=>wX,store:()=>PX,resolveZoneForAddress:()=>n$,getShippingRatesByMethod:()=>BX,getRatesByZone:()=>xX,getRateByWeightAndZone:()=>Y4,getRateByWeightAndAddress:()=>VX,formatShippingRateOptions:()=>zX,fetchById:()=>QX,fetchAll:()=>HX,destroyByZone:()=>NX,destroyByMethod:()=>KX,destroy:()=>YX,bulkUpdate:()=>TX,bulkStore:()=>SX,bulkDestroy:()=>LX,ShippingRateInputError:()=>j});import{db as u$}from"@stacksjs/database";async function YX(J){try{let $=await u$.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function LX(J){if(!J.length)return 0;try{let $=await u$.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function NX(J){try{let $=await u$.deleteFrom("shipping_rates").where("shipping_zone_id","=",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function KX(J){try{let $=await u$.deleteFrom("shipping_rates").where("shipping_method_id","=",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as D}from"@stacksjs/database";async function QX(J){let $=await D.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.shipping_zone_id)G=await D.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)X=await D.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:G,shipping_method:X}}return}async function HX(){let J=await D.selectFrom("shipping_rates").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((L)=>L.shipping_zone_id).filter((L)=>L!==null&&L!==void 0))],G=[...new Set(J.map((L)=>L.shipping_method_id).filter((L)=>L!==null&&L!==void 0))],[X,W]=await Promise.all([$.length?D.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],G.length?D.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),Z=X.reduce((L,N)=>{return L[N.id]=N,L},{}),Y=W.reduce((L,N)=>{return L[N.id]=N,L},{});return J.map((L)=>({...L,shipping_zone:L.shipping_zone_id?Z[L.shipping_zone_id]:[],shipping_method:L.shipping_method_id?Y[L.shipping_method_id]:[]}))}async function xX(J){try{return await D.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function Y4(J,$){try{return await D.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function n$(J){if(!J?.countryCode)return null;try{let $=await D.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let G=null;for(let X of $){let W=1;if(J.region&&X.regions&&FX(X.regions,J.region))W=2;if(J.postalCode&&X.postal_codes&&FX(X.postal_codes,J.postalCode))W=3;if(!G||W>G.score)G={id:X.id,score:W}}return G?.id??null}catch{return null}}async function VX(J,$){let G=await n$($);if(G==null)return;return Y4(J,G)}async function MX(J,$){return await n$($)===J}function FX(J,$){if(!J||!$)return!1;let G=$.trim().toUpperCase();for(let X of J.split(/[,|;]/))if(X.trim().toUpperCase()===G)return!0;return!1}async function zX(){try{return(await D.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function BX(J){try{return await D.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:UX}=globalThis.Bun;import{db as L4}from"@stacksjs/database";import{db as u0}from"@stacksjs/database";async function AX(){return await u0.selectFrom("shipping_zones").selectAll().execute()}async function i$(J){return await u0.selectFrom("shipping_zones").where("id","=",J).selectAll().executeTakeFirst()}function _X(){try{return u0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping zone options: ${J.message}`);throw J}}async function OX(){try{return await u0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping zones: ${J.message}`);throw J}}async function RX(J){try{return await u0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class j extends TypeError{constructor(J){super(J);this.name="ShippingRateInputError"}}function n0(J,$,G){return Number(J[G]??$?.[G])}async function K0(J,$){let G=n0(J,$,"shipping_method_id"),X=n0(J,$,"shipping_zone_id"),W=n0(J,$,"weight_from"),Z=n0(J,$,"weight_to"),Y=n0(J,$,"rate");if(!Number.isSafeInteger(G)||G<1)throw new j("Shipping method must be a positive integer.");if(!Number.isSafeInteger(X)||X<1)throw new j("Shipping zone must be a positive integer.");if(!Number.isFinite(W)||W<0)throw new j("Weight from must be a non-negative number.");if(!Number.isFinite(Z)||Z<W)throw new j("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(Y)||Y<0)throw new j("Rate must be a non-negative integer in minor currency units.");let[L,N]=await Promise.all([l$(G),i$(X)]);if(!L)throw new j(`Shipping method ${G} was not found.`);if(!N)throw new j(`Shipping zone ${X} was not found.`);if(Number(N.shipping_method_id)!==G)throw new j(`Shipping zone ${X} is not assigned to shipping method ${G}.`)}async function PX(J){try{let $=i(J),G=Number($.shipping_method_id),X=Number($.shipping_zone_id);await K0($);let W=UX(),Z={...$,shipping_method_id:G,shipping_zone_id:X,uuid:W};await L4.insertInto("shipping_rates").values(Z).executeTakeFirst();let Y=await L4.selectFrom("shipping_rates").where("uuid","=",W).selectAll().executeTakeFirst();if(!Y)throw Error("Failed to resolve created shipping rate");return Y}catch($){if($ instanceof j)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function SX(J){if(!J.length)return 0;try{for(let X of J){let W=i(X);await K0(W)}let $=J.map((X)=>({...i(X),uuid:UX()})),G=await L4.insertInto("shipping_rates").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof j)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as i0}from"@stacksjs/database";import{formatDate as o$}from"@stacksjs/orm";async function wX(J,$){try{if(!J)throw Error("Shipping rate ID is required for update");let G=await i0.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=i($);await K0(X,G);let W=await i0.updateTable("shipping_rates").set({...X,updated_at:o$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!W)return;return W}catch(G){if(G instanceof j)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function TX(J){if(!J.length)return 0;try{let $=0;for(let{id:G,data:X}of J){let W=await i0.updateTable("shipping_rates").set({...i(X),updated_at:o$(new Date)}).where("id","=",G).executeTakeFirst();if(F(W)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function EX(J,$){try{let G=await i0.updateTable("shipping_rates").set({...i($),updated_at:o$(new Date)}).where("shipping_zone_id","=",J).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 fX(J,$){try{let G=await i0.updateTable("shipping_rates").set({...i($),updated_at:o$(new Date)}).where("shipping_method_id","=",J).executeTakeFirst();return F(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var G1={};z(G1,{startStop:()=>jX,startRoute:()=>IX,routeTrackingChannel:()=>N4,recordDriverPing:()=>qX,orderTrackingChannel:()=>r,isWithin:()=>TG,hasCoordinates:()=>m0,failStop:()=>hX,estimateSecondsRemaining:()=>I$,emitDeliveryStarted:()=>e$,emitDeliveryPosition:()=>d$,emitDeliveryNearby:()=>r$,emitDeliveryFailed:()=>J1,emitDeliveryCompleted:()=>$1,emitDeliveryAssigned:()=>a$,emitDeliveryArrived:()=>t$,distanceInMeters:()=>e,completeStop:()=>CX,broadcastToChannel:()=>o,bearingInDegrees:()=>h$,assignStop:()=>kX,NEARBY_RADIUS_METERS:()=>K4,ARRIVAL_RADIUS_METERS:()=>F4});function r(J){return`order.${J}`}function N4(J){return`delivery-route.${J}`}async function U0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function o(J,$,G){try{let X=await import("@stacksjs/realtime").catch(()=>null);if(!X)return;let W=X.channel;if(typeof W!=="function")return;await W(J).broadcast($,G,"private")}catch{}}async function d$(J,$,G){await Promise.all([...J.map((X)=>o(r(X),"delivery:position",G)),$==null?Promise.resolve():o(N4($),"delivery:position",G)])}async function a$(J){if(await U0("delivery:assigned",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:assigned",{stop:J})}async function e$(J){if(await U0("delivery:started",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:started",{stop:J})}async function r$(J,$,G){if(await U0("delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G}),J.order_id!=null)await o(r(J.order_id),"delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G})}async function t$(J){if(await U0("delivery:arrived",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:arrived",{stop:J})}async function $1(J){if(await U0("delivery:completed",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:completed",{stop:J})}async function J1(J,$){await U0("delivery:failed",{stop:J,reason:$})}var{randomUUIDv7:HW}=globalThis.Bun;import{db as y}from"@stacksjs/database";var K4=400,F4=60,xW=250;async function qX(J){let $=J.recordedAt??new Date().toISOString(),G=typeof J.accuracy!=="number"||J.accuracy<=xW,X=await y.selectFrom("drivers").where("id","=",J.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!X)throw Error(`Unknown driver: ${J.driverId}`);let W=m0(X)?{latitude:X.latitude,longitude:X.longitude}:null,Z=typeof J.heading==="number"?J.heading:W?h$(W,J):null,Y=await VW(J.driverId),L=Y?await MW(Y.id):null,N=null,K=null,Q=!1,H=!1,x=L&&m0({latitude:L.latitude??void 0,longitude:L.longitude??void 0})?{latitude:L.latitude,longitude:L.longitude}:null;if(G&&L&&x)N=Math.round(e(J,x)),K=I$(N,J.speed??0),H=N<=F4&&L.arrived_at==null,Q=!H&&N<=K4&&L.status==="en_route"&&L.notified_nearby_at==null;let _=await zW({driverId:J.driverId,routeId:Y?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Z,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$});if(G)await y.updateTable("drivers").set({latitude:J.latitude,longitude:J.longitude,heading:Z,speed:J.speed??0,last_ping_at:$}).where("id","=",J.driverId).execute();if(L&&(N!=null||K!=null))await y.updateTable("delivery_stops").set({eta_at:K==null?L.eta_at:new Date(Date.now()+K*1000).toISOString()}).where("id","=",L.id).execute();if(G)await d$(L?.order_id==null?[]:[L.order_id],Y?.id??null,{driverId:J.driverId,routeId:Y?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Z,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$,distanceToStopMeters:N,etaSeconds:K});if(Q&&L)await y.updateTable("delivery_stops").set({notified_nearby_at:$}).where("id","=",L.id).execute(),await r$(L,N,K);if(H&&L)await y.updateTable("delivery_stops").set({status:"arrived",arrived_at:$}).where("id","=",L.id).execute(),await t$({...L,status:"arrived",arrived_at:$});return{pingId:_,routeId:Y?.id??null,stopId:L?.id??null,distanceToStopMeters:N,etaSeconds:K,crossedNearby:Q,crossedArrival:H}}async function VW(J){return await y.selectFrom("delivery_routes").where("driver_id","=",J).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function MW(J){let $=await y.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return $.find((G)=>G.status==="en_route")??$.find((G)=>G.status==="arrived")??$[0]??null}async function zW(J){let $=HW();return await y.insertInto("driver_pings").values({uuid:$,driver_id:J.driverId,delivery_route_id:J.routeId,latitude:J.latitude,longitude:J.longitude,heading:J.heading,speed:J.speed??0,accuracy:J.accuracy,recorded_at:J.recordedAt}).executeTakeFirst(),(await y.selectFrom("driver_pings").where("uuid","=",$).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:BW}=globalThis.Bun;import{db as E}from"@stacksjs/database";async function kX(J){let $=BW(),G=J.sequence??await _W(J.deliveryRouteId);await E.insertInto("delivery_stops").values({uuid:$,delivery_route_id:J.deliveryRouteId,order_id:J.orderId??null,sequence:G,status:"pending",address:J.address,latitude:J.latitude??null,longitude:J.longitude??null,recipient_name:J.recipientName??null,recipient_phone:J.recipientPhone??null,eta_at:J.etaAt??null}).executeTakeFirst();let X=await RW($);if(X)await a$(X);return X??{}}async function jX(J){await E.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",J).execute();let $=await H4(J);if(!$)return null;if($.order_id!=null)await Q4($.order_id,"OUT_FOR_DELIVERY");return await e$($),$}async function CX(J,$){let G=new Date().toISOString();await E.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await OW(J)?{}:{arrived_at:G},...$?{notes:$}:{}}).where("id","=",J).execute();let X=await H4(J);if(!X)return null;if(X.order_id!=null)await Q4(X.order_id,"DELIVERED");return await $1(X),await gX(X.delivery_route_id),X}async function hX(J,$){await E.updateTable("delivery_stops").set({status:"failed",notes:$}).where("id","=",J).execute();let G=await H4(J);if(!G)return null;if(G.order_id!=null)await Q4(G.order_id,"SHIPPED");return await J1(G,$),await gX(G.delivery_route_id),G}async function IX(J){await E.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",J).execute()}async function gX(J){if(J==null)return;if(await E.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let G=await E.selectFrom("delivery_routes").where("id","=",J).select(["driver_id"]).executeTakeFirst();if(await E.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",J).execute(),G?.driver_id!=null)await E.updateTable("drivers").set({status:"active"}).where("id","=",G.driver_id).execute()}async function Q4(J,$){let G=await E.selectFrom("orders").where("id","=",J).select(["id","status"]).executeTakeFirst();if(!G)return;let X=await Promise.resolve().then(() => (V0(),xJ)),{canTransition:W,emitForStatus:Z}=X,Y=AW(G.status,$,W);if(Y.length===0){let{log:L}=await import("@stacksjs/logging").catch(()=>({log:null}));L?.warn(`[delivery] refused to move order ${J} from ${G.status} to ${$}: no legal transition`);return}for(let L of Y)await E.updateTable("orders").set({status:L}).where("id","=",J).execute(),await Z(L,{...G,status:L})}function AW(J,$,G){if(J===$)return[];if(G(J,$))return[$];for(let X of["PROCESSING","SHIPPED"]){if(X===J||X===$)continue;if(G(J,X)&&G(X,$))return[X,$]}return[]}async function _W(J){return(await E.selectFrom("delivery_stops").where("delivery_route_id","=",J).select(["sequence"]).execute()).reduce((G,X)=>Math.max(G,X.sequence??0),0)+1}async function OW(J){return(await E.selectFrom("delivery_stops").where("id","=",J).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function H4(J){return await E.selectFrom("delivery_stops").where("id","=",J).selectAll().executeTakeFirst()??null}async function RW(J){return await E.selectFrom("delivery_stops").where("uuid","=",J).selectAll().executeTakeFirst()??null}var Y1={};z(Y1,{updateStatus:()=>uX,updateRegionsAndPostalCodes:()=>iX,updateCountries:()=>nX,update:()=>cX,store:()=>pX,softDelete:()=>DX,getZonesByCountry:()=>RX,getActiveShippingZones:()=>OX,formatZoneOptions:()=>_X,fetchById:()=>i$,fetchAll:()=>AX,destroy:()=>vX,bulkStore:()=>lX,bulkSoftDelete:()=>bX,bulkDestroy:()=>yX});import{db as X1}from"@stacksjs/database";async function vX(J){try{let $=await X1.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function DX(J){try{let $=await X1.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function yX(J){if(!J.length)return 0;try{let $=await X1.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function bX(J){if(!J.length)return 0;try{let $=await X1.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:mX}=globalThis.Bun;import{db as x4}from"@stacksjs/database";async function pX(J){try{let $=mX(),G={...v0(J),uuid:$};await x4.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await x4.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping zone");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function lX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...v0(X),uuid:mX()})),G=await x4.insertInto("shipping_zones").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as W1}from"@stacksjs/database";import{formatDate as Z1}from"@stacksjs/orm";async function cX(J,$){try{if(!J)throw Error("Shipping zone ID is required for update");let G=await W1.updateTable("shipping_zones").set({...v0($),updated_at:Z1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone: ${G.message}`);throw G}}async function uX(J,$){try{let G=await W1.updateTable("shipping_zones").set({status:$,updated_at:Z1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone status: ${G.message}`);throw G}}async function nX(J,$){try{let G=await W1.updateTable("shipping_zones").set({countries:$,updated_at:Z1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone countries");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${G.message}`);throw G}}async function iX(J,$,G){try{let X={updated_at:Z1(new Date)};if($!==void 0)X.regions=$;if(G!==void 0)X.postal_codes=G;let W=await W1.updateTable("shipping_zones").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!W)throw Error("Failed to update regions and postal codes");return W}catch(X){if(X instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${X.message}`);throw X}}var UW={digital:k$,drivers:C$,geocoding:v$,licenses:b$,methods:c$,rates:s$,routes:f$,tracking:G1,zones:Y1},PW=UW;var M4={};z(M4,{updateStatus:()=>W9,updateRate:()=>Z9,updateDefaultStatus:()=>Y9,update:()=>X9,store:()=>J9,fetchById:()=>eX,fetchAll:()=>rX,destroy:()=>sX,bulkStore:()=>G9,bulkDestroy:()=>dX});import{db as oX}from"@stacksjs/database";async function sX(J){try{let $=await oX.deleteFrom("tax_rates").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function dX(J){if(!J.length)return 0;try{let $=await oX.deleteFrom("tax_rates").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as aX}from"@stacksjs/database";async function eX(J){return await aX.selectFrom("tax_rates").where("id","=",J).selectAll().executeTakeFirst()}async function rX(){return await aX.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:tX}=globalThis.Bun;import{db as $9}from"@stacksjs/database";async function J9(J){try{return await $9.transaction(async($)=>{let G={...J,uuid:tX()};if(G.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let X=await $.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function G9(J){if(!J.length)return 0;try{return await $9.transaction(async($)=>{let G=0;for(let X of J){let W={...X,uuid:tX()};if(W.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(W).executeTakeFirst())G++}return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as L1}from"@stacksjs/database";import{formatDate as N1}from"@stacksjs/orm";async function X9(J,$){try{if(!J)throw Error("Tax rate ID is required for update");return await L1.transaction(async(G)=>{let X=await G.selectFrom("tax_rates").select("is_default").where("id","=",J).executeTakeFirst();if(!X)return;let W=$.is_default??Boolean(X.is_default),Z=N1(new Date);if(W)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Z}).where("id","!=",J).execute();let Y=await G.updateTable("tax_rates").set({...$,updated_at:Z}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function W9(J,$){try{let G=await L1.updateTable("tax_rates").set({status:$,updated_at:N1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update tax rate status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate status: ${G.message}`);throw G}}async function Z9(J,$){try{let G=await L1.updateTable("tax_rates").set({rate:$,updated_at:N1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update rate information");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update rate information: ${G.message}`);throw G}}async function Y9(J,$){try{return await L1.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",J).executeTakeFirst())return!1;let W=N1(new Date);if($)await G.updateTable("tax_rates").set({is_default:!1,updated_at:W}).where("id","!=",J).execute();return await G.updateTable("tax_rates").set({is_default:$,updated_at:W}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var R4={};z(R4,{restaurant:()=>S0,products:()=>F1,default:()=>hW});var F1={};z(F1,{updateStatus:()=>T9,updatePartySize:()=>E9,update:()=>K1,store:()=>S9,fetchWaiting:()=>B9,fetchPurchasedBetweenDates:()=>M9,fetchNotifiedBetweenDates:()=>V9,fetchCountByStatus:()=>A9,fetchCountBySource:()=>F9,fetchCountByQuantity:()=>H9,fetchCountByDateGrouped:()=>R9,fetchCountByDate:()=>Q9,fetchCountByAllQuantities:()=>x9,fetchCountBetweenDates:()=>O9,fetchConversionRates:()=>_9,fetchCancelledBetweenDates:()=>z9,fetchById:()=>o0,fetchAll:()=>K9,destroy:()=>L9,bulkStore:()=>w9,bulkDestroy:()=>N9});import{db as z4}from"@stacksjs/database";async function L9(J){try{let $=await z4.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await z4.deleteFrom("waitlist_products").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function N9(J){if(!J.length)return 0;try{let $=await z4.deleteFrom("waitlist_products").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as w}from"@stacksjs/orm";async function o0(J){return await A.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function K9(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function F9(J,$){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(J&&$){let W=w(J),Z=w($);G=G.where("created_at",">=",W).where("created_at","<=",Z)}return(await G.execute()).reduce((W,{source:Z,count:Y})=>{return W[Z]=Y,W},{})}async function Q9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=w($),W=w(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",W).executeTakeFirst())?.count??0}async function H9(J){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",J).executeTakeFirst())?.count??0}async function x9(J,$){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(J&&$){let W=w(J),Z=w($);G=G.where("created_at",">=",W).where("created_at","<=",Z)}return(await G.execute()).reduce((W,{quantity:Z,count:Y})=>{return W[Z]=Y,W},{})}async function V9(J,$){let G=w(J),X=w($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",X).whereNotNull("notified_at").execute()}async function M9(J,$){let G=w(J),X=w($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",X).whereNotNull("purchased_at").execute()}async function z9(J,$){let G=w(J),X=w($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",X).whereNotNull("cancelled_at").execute()}async function B9(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function A9(J,$,G){let X=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",J);if($&&G){let Z=w($),Y=w(G);X=X.where("created_at",">=",Z).where("created_at","<=",Y)}return(await X.executeTakeFirst())?.count??0}async function _9(J,$){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(J&&$){let N=w(J),K=w($);G=G.where("created_at",">=",N).where("created_at","<=",K)}let X=await G.execute(),W=X.reduce((N,{count:K})=>N+K,0),Z=X.find((N)=>N.status==="purchased")?.count??0,Y=W>0?Z/W*100:0,L=X.reduce((N,{status:K,count:Q})=>{return N[K]={count:Q,percentage:W>0?Q/W*100:0},N},{});return{totalConversionRate:Y,statusBreakdown:L}}async function O9(J,$){let G=w(J),X=w($);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 R9(J,$){let G=A.selectFrom("waitlist_products").select(["created_at"]);if(J&&$){let Z=w(J),Y=w($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}let W=(await G.execute()).reduce((Z,{created_at:Y})=>{let L=(Y||"").split("T")[0]||"unknown";return Z[L]=(Z[L]||0)+1,Z},{});return Object.entries(W).map(([Z,Y])=>({date:Z,count:Y})).sort((Z,Y)=>Z.date.localeCompare(Y.date))}var{randomUUIDv7:P9}=globalThis.Bun;import{db as B4}from"@stacksjs/database";import{formatDate as U9}from"@stacksjs/orm";var SW={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function wW(J){return typeof J==="number"||J instanceof Date?U9(J):J}function s0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,W])=>W!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let W of["notified_at","purchased_at","cancelled_at"])if(G[W]!==void 0)G[W]=wW(G[W]);let X=SW[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=U9(new Date);return G}async function S9(J){try{let $=P9(),G={...s0(J),uuid:$,status:J.status||"waiting"};await B4.insertInto("waitlist_products").values(G).executeTakeFirst();let X=await B4.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create waitlist product");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function w9(J){if(!J.length)return 0;try{let $=J.map((X)=>({...s0(X),status:X.status||"waiting",uuid:P9()})),G=await B4.insertInto("waitlist_products").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as TW}from"@stacksjs/database";import{formatDate as EW}from"@stacksjs/orm";async function K1(J,$){try{if(!J)throw Error("Waitlist product ID is required for update");let G=await o0(J);if(!G)return;await TW.updateTable("waitlist_products").set({...s0($,G),updated_at:EW(new Date)}).where("id","=",J).execute();let X=await o0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update waitlist product: ${G.message}`);throw G}}async function T9(J,$){return await K1(J,{status:$})}async function E9(J,$){return await K1(J,{quantity:$})}var S0={};z(S0,{updateWaitTimes:()=>t9,updateStatus:()=>e9,updateQueuePosition:()=>$3,updatePartySize:()=>r9,update:()=>P0,store:()=>d9,fetchWaitingWithQuotedTimes:()=>m9,fetchWaitingWithPartySizes:()=>p9,fetchWaiting:()=>D9,fetchTimeSeriesStats:()=>o9,fetchTablesTurnedToday:()=>l9,fetchSeatingRate:()=>c9,fetchSeatedStats:()=>i9,fetchSeatedBetweenDates:()=>v9,fetchNoShowStats:()=>u9,fetchCurrentWaitTimes:()=>n9,fetchCountByTablePreference:()=>j9,fetchCountByPartySize:()=>h9,fetchCountByDate:()=>C9,fetchCountByAllPartySizes:()=>I9,fetchConversionRates:()=>y9,fetchById:()=>d0,fetchBetweenDates:()=>g9,fetchAverageWaitTimes:()=>b9,fetchAll:()=>k9,destroy:()=>f9,bulkStore:()=>a9,bulkDestroy:()=>q9});import{db as A4}from"@stacksjs/database";async function f9(J){try{let $=await A4.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await A4.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function q9(J){if(!J.length)return 0;try{let $=await A4.deleteFrom("waitlist_restaurants").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as M}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function d0(J){return await M.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function k9(){return await M.selectFrom("waitlist_restaurants").selectAll().execute()}async function j9(){return(await M.selectFrom("waitlist_restaurants").select(["table_preference",M.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:G,count:X})=>{return $[G]=X,$},{})}async function C9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),W=g(G);return(await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",W).executeTakeFirst())?.count??0}async function h9(J){return(await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function I9(){return(await M.selectFrom("waitlist_restaurants").select(["party_size",M.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:G,count:X})=>{return $[G]=X,$},{})}async function g9(J,$){let G=g(J),X=g($);return await M.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",X).execute()}async function v9(J,$){let G=g(J),X=g($);return await M.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",X).where("status","=","seated").execute()}async function D9(){return await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function y9(){let J=await M.selectFrom("waitlist_restaurants").select(["status",M.fn.count("id").as("count")]).groupBy("status").execute(),$=J.reduce((Z,{count:Y})=>Z+Y,0),G=J.find((Z)=>Z.status==="seated")?.count??0,X=$>0?Number(G)/$*100:0,W=J.reduce((Z,{status:Y,count:L})=>{return Z[Y]={count:L,percentage:$>0?L/$*100:0},Z},{});return{totalConversionRate:X,statusBreakdown:W}}async function b9(){let J=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:J?.avg_quoted_wait_time??0,averageActualWaitTime:J?.avg_actual_wait_time??0}}async function m9(){let J=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((X,W)=>X+(W.quoted_wait_time??0),0),G=J.length>0?$/J.length:0;return{entries:J,totalQuotedWaitTime:$,averageQuotedWaitTime:G}}async function p9(){let J=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((W,Z)=>W+Z.party_size,0),G=J.length>0?$/J.length:0,X=J.reduce((W,Z)=>{return W[Z.party_size]=(W[Z.party_size]||0)+1,W},{});return{entries:J,totalPartySize:$,averagePartySize:G,partySizeBreakdown:X}}async function l9(){let J=new Date,$=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),W=g(G),Z=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",X).where("check_in_time","<=",W).execute(),Y=Z.length,L=Z.reduce((H,x)=>H+x.party_size,0),N=Y>0?L/Y:0,K=Z.reduce((H,x)=>{return H[x.table_preference]=(H[x.table_preference]||0)+1,H},{}),Q=Z.reduce((H,x)=>{return H[x.party_size]=(H[x.party_size]||0)+1,H},{});return{totalTablesTurned:Y,averagePartySize:N,totalCustomersSeated:L,breakdownByTablePreference:K,breakdownByPartySize:Q}}async function c9(J,$){let G=g(J),X=g($),W=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(),Z=W.reduce((K,{count:Q})=>K+Q,0),Y=W.find((K)=>K.status==="seated")?.count??0,L=Z>0?Number(Y)/Z*100:0,N=W.reduce((K,{status:Q,count:H})=>{return K[Q]={count:H,percentage:Z>0?H/Z*100:0},K},{});return{totalEntries:Z,seatedEntries:Y,seatingRate:L,statusBreakdown:N}}async function u9(J,$){let G=g(J),X=g($),W=M.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",X),Z=await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",X).executeTakeFirst(),Y=await W.execute(),L=Y.length,N=Z?.count&&Z.count>0?L/Z.count*100:0,K=Y.reduce((O,U)=>O+(U.quoted_wait_time??0),0),Q=L>0?K/L:0,H=Y.reduce((O,U)=>O+U.party_size,0),x=L>0?H/L:0,_=Y.reduce((O,U)=>{return O[U.table_preference]=(O[U.table_preference]||0)+1,O},{}),R=Y.reduce((O,U)=>{return O[U.party_size]=(O[U.party_size]||0)+1,O},{});return{totalNoShows:L,noShowRate:N,averageQuotedWaitTime:Q,averagePartySize:x,breakdownByTablePreference:_,breakdownByPartySize:R}}async function n9(){let J=await M.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=J.reduce((W,Z)=>W+(Z.quoted_wait_time||0),0),G=J.reduce((W,Z)=>W+(Z.actual_wait_time||0),0),X=J.length;return{averageQuoted:X>0?$/X:0,averageActual:X>0?G/X:0}}async function i9(){let J=Date.now()-86400000,$=await M.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),G=Array.from({length:24},(X,W)=>({hour:W,count:$.filter((Z)=>{return Z.seated_at===W}).length}));return{total:$.length,byHour:G}}async function o9(){return(await M.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,G)=>{let X=G.created_at;if(!$[X])$[X]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[X].total++,$[X][G.status]++,$},{})}var{randomUUIDv7:s9}=globalThis.Bun;import{db as O4}from"@stacksjs/database";import{formatDate as _4}from"@stacksjs/orm";var fW={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function qW(J){if(typeof J==="number")return _4(J<=2147483647?J*1000:J);if(J instanceof Date)return _4(J);return J}function a0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,W])=>W!==void 0));for(let W of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[W]!==void 0)G[W]=qW(G[W]);let X=fW[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=_4(new Date);return G}async function d9(J){try{let $=s9(),G={...a0(J),status:J.status||"waiting",uuid:$};await O4.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let X=await O4.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create restaurant waitlist entry");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function a9(J){if(!J.length)return 0;try{let $=J.map((X)=>({...a0(X),status:X.status||"waiting",uuid:s9()})),G=await O4.insertInto("waitlist_restaurants").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as kW}from"@stacksjs/database";import{formatDate as jW}from"@stacksjs/orm";async function P0(J,$){try{if(!J)throw Error("Restaurant waitlist entry ID is required for update");let G=await d0(J);if(!G)return;await kW.updateTable("waitlist_restaurants").set({...a0($,G),updated_at:jW(new Date)}).where("id","=",J).execute();let X=await d0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${G.message}`);throw G}}async function e9(J,$){return await P0(J,{status:$})}async function r9(J,$){return await P0(J,{party_size:$})}async function t9(J,$,G){return await P0(J,{quoted_wait_time:$,...G===void 0?{}:{actual_wait_time:G}})}async function $3(J,$){return await P0(J,{queue_position:$})}var CW={products:F1,restaurant:S0},hW=CW;var IW={coupons:Q1,customers:H1,devices:B1,errors:O1,giftCards:U1,orders:j1,payments:C1,products:b1,receipts:n1,restaurant:S0,shippings:V4,tax:M4,waitlists:R4},Hx=IW;export{R4 as waitlists,M4 as tax,V4 as shippings,S0 as restaurant,n1 as receipts,b1 as products,C1 as payments,j1 as orders,U1 as giftCards,O1 as errors,B1 as devices,Hx as default,H1 as customers,Q1 as coupons,IW as commerce};
@@ -0,0 +1,46 @@
1
+ import { formatQuery, PRECISION_RANK } from './types';
2
+ import { nominatimDriver } from './nominatim';
3
+ import type { Coordinates } from '../tracking/geo';
4
+ import type { GeocodePrecision, GeocodeQuery, GeocodeResult, GeocodingDriver, GeocodingOptions } from './types';
5
+ export type {
6
+ GeocodePrecision,
7
+ GeocodeQuery,
8
+ GeocodeResult,
9
+ GeocodingDriver,
10
+ GeocodingOptions,
11
+ } from './types';
12
+ /** Swap the provider once, at boot. */
13
+ export declare function setGeocodingDriver(driver: GeocodingDriver): void;
14
+ export declare function geocodingDriver(): GeocodingDriver;
15
+ /**
16
+ * Resolve an address to a point.
17
+ *
18
+ * Cached, because addresses repeat far more than they change: the same
19
+ * customer orders from the same flat, and half a building orders from the same
20
+ * street. A cache miss is a network round trip and, on the default provider, a
21
+ * one-second rate-limit wait, so this matters at checkout.
22
+ *
23
+ * Returns null rather than throwing when the address cannot be found or is not
24
+ * precise enough to deliver to. A provider that is down DOES throw: "we cannot
25
+ * check right now" and "that address does not exist" are different answers and
26
+ * a checkout should treat them differently.
27
+ */
28
+ export declare function geocode(query: GeocodeQuery, options?: GeocodingOptions): Promise<GeocodeResult | null>;
29
+ /**
30
+ * Is this address inside the delivery area?
31
+ *
32
+ * A radius from the fulfilling store, which is how a local delivery operation
33
+ * actually thinks about coverage, and cheap enough to run at checkout. Pass
34
+ * every store to find the one that should take the order.
35
+ *
36
+ * `ShippingZone` remains the tool for postcode or region rules; this is for
37
+ * "we deliver within five miles", which no postcode list expresses well.
38
+ */
39
+ export declare function checkCoverage(destination: Coordinates, origins: readonly Coordinates[], radiusMeters: number): CoverageCheck | null;
40
+ export declare interface CoverageCheck {
41
+ covered: boolean
42
+ distanceMeters: number
43
+ nearest: Coordinates
44
+ }
45
+ export { nominatimDriver } from './nominatim';
46
+ export { formatQuery, PRECISION_RANK } from './types';
@@ -0,0 +1,6 @@
1
+ import type { GeocodingDriver } from './types';
2
+ export declare function nominatimDriver(options?: NominatimOptions): GeocodingDriver;
3
+ export declare interface NominatimOptions {
4
+ userAgent?: string
5
+ endpoint?: string
6
+ }
@@ -0,0 +1,41 @@
1
+ /** A single line, in the order a geocoder expects to read it. */
2
+ export declare function formatQuery(query: GeocodeQuery): string;
3
+ /**
4
+ * Ordered worst to best, so a minimum can be compared numerically.
5
+ * @defaultValue `{ unknown: 0, locality: 1, postal: 2, street: 3, rooftop: 4 }`
6
+ */
7
+ export declare const PRECISION_RANK: Record<GeocodePrecision, number>;
8
+ /**
9
+ * Address to coordinates, for delivery.
10
+ *
11
+ * A delivery needs a point, not a string: without one there is nothing to
12
+ * measure a coverage radius against, nothing to draw on a tracking map, and
13
+ * nothing to compute an ETA from. Every one of those was stubbed until this
14
+ * existed.
15
+ */
16
+ export declare interface GeocodeQuery {
17
+ street: string
18
+ unit?: string
19
+ city?: string
20
+ region?: string
21
+ postalCode?: string
22
+ country?: string
23
+ }
24
+ export declare interface GeocodeResult {
25
+ latitude: number
26
+ longitude: number
27
+ formatted: string
28
+ confidence: number
29
+ precision: GeocodePrecision
30
+ provider: string
31
+ }
32
+ export declare interface GeocodingDriver {
33
+ readonly name: string
34
+ geocode: (query: GeocodeQuery) => Promise<GeocodeResult | null>
35
+ }
36
+ export declare interface GeocodingOptions {
37
+ driver?: GeocodingDriver
38
+ minimumPrecision?: GeocodePrecision
39
+ cacheSeconds?: number
40
+ }
41
+ export type GeocodePrecision = 'rooftop' | 'street' | 'postal' | 'locality' | 'unknown';
@@ -1,5 +1,6 @@
1
1
  import * as digital from './digital-deliveries/index';
2
2
  import * as drivers from './drivers/index';
3
+ import * as geocoding from './geocoding/index';
3
4
  import * as licenses from './license-keys/index';
4
5
  import * as methods from './shipping-methods/index';
5
6
  import * as rates from './shipping-rates/index';
@@ -10,6 +11,7 @@ declare const shippings: ShippingsNamespace;
10
11
  declare interface ShippingsNamespace {
11
12
  digital: typeof digital
12
13
  drivers: typeof drivers
14
+ geocoding: typeof geocoding
13
15
  licenses: typeof licenses
14
16
  methods: typeof methods
15
17
  rates: typeof rates
@@ -20,6 +22,7 @@ declare interface ShippingsNamespace {
20
22
  export {
21
23
  digital,
22
24
  drivers,
25
+ geocoding,
23
26
  licenses,
24
27
  methods,
25
28
  rates,
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/commerce",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.297",
5
+ "version": "0.70.299",
6
6
  "description": "Stacks commerce utilities.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [