@stacksjs/commerce 0.70.353 → 0.70.355

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 K3=Object.defineProperty;var W3=(J)=>J;function F3(J,$){this[J]=W3.bind(null,$)}var z=(J,$)=>{for(var G in $)K3(J,G,{get:$[G],enumerable:!0,configurable:!0,set:F3.bind($,G)})};var Q3=(J,$)=>()=>(J&&($=J(J=0)),$);var J0=import.meta.require;var MJ={};z(MJ,{emitOrderShipped:()=>K$,emitOrderRefunded:()=>M0,emitOrderPaid:()=>d,emitOrderOutForDelivery:()=>HJ,emitOrderDelivered:()=>W$,emitOrderCreated:()=>f0,emitOrderCancelled:()=>H0,emitForStatus:()=>j0,canTransition:()=>w0});function w0(J,$){if(J===$)return!0;return h3[J]?.includes($)??!1}async function Z0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function f0(J){await Z0("order:created",{order:J})}async function d(J,$){await Z0("order:paid",{order:J,payment:$})}async function K$(J){await Z0("order:shipped",{order:J})}async function HJ(J){await Z0("order:out_for_delivery",{order:J})}async function W$(J){await Z0("order:delivered",{order:J})}async function H0(J,$){await Z0("order:cancelled",{order:J,reason:$})}async function M0(J,$){await Z0("order:refunded",{order:J,refundAmount:$})}async function j0(J,$){switch(J){case"PROCESSING":return d($);case"SHIPPED":return K$($);case"OUT_FOR_DELIVERY":return HJ($);case"DELIVERED":return W$($);case"CANCELLED":return H0($);case"REFUNDED":return M0($);case"PENDING":default:}}var h3;var x0=Q3(()=>{h3={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 N4={};z(N4,{update:()=>u1,store:()=>m1,redeem:()=>n1,getActiveCouponsMoMChange:()=>v1,fetchTopRedeemedCoupons:()=>I1,fetchStats:()=>j1,fetchRedemptionTrend:()=>g1,fetchRedemptionStats:()=>h1,fetchCouponCountsByType:()=>C1,fetchCouponCounts:()=>k1,fetchConversionRate:()=>D1,fetchById:()=>G0,fetchByCode:()=>w1,fetchAll:()=>q1,fetchActive:()=>f1,deleteExpiredCoupons:()=>S1,deleteCoupons:()=>P1,deleteCoupon:()=>U1});import{db as e0}from"@stacksjs/database";import{formatDate as N3}from"@stacksjs/orm";function Q(J){if(typeof J==="number")return Number.isFinite(J)?J:0;if(typeof J==="bigint")return Number(J);if(!J||typeof J!=="object")return 0;let $=J;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[G]!==void 0&&$[G]!==null)return Q($[G]);if(Array.isArray(J))return J.reduce((G,X)=>G+Q(X),0);return 0}async function U1(J){let $=await e0.deleteFrom("coupons").where("id","=",J).executeTakeFirst();return Q($)>0}async function P1(J){if(!J.length)return 0;return(await e0.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function S1(){let J=N3(new Date),$=await e0.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return Q($)}import{db as x}from"@stacksjs/database";import{extractDate as T1,formatDate as E1}from"@stacksjs/orm";import{camelCase as H3}from"@stacksjs/strings";function t0(J){let $=Object.fromEntries(Object.entries(J).map(([G,X])=>[H3(G),X]));if($.endDate)$.endDate=T1(new Date($.endDate));if($.startDate)$.startDate=T1(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function q1(){return(await x.selectFrom("coupons").selectAll().execute()).map(t0)}async function G0(J){let $=await x.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function w1(J){let $=await x.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function f1(){let J=E1(new Date);return(await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map(t0)}async function j1(){let J=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).executeTakeFirst(),$=E1(new Date),G=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(x.fn.count("id").as("count")).executeTakeFirst(),X=await x.selectFrom("coupons").select(["discount_type",x.fn.count("id").as("count")]).groupBy("discount_type").execute(),Z=await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),Y=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",$).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(J?.count||0),active:Number(G?.count||0),by_type:X,most_used:Z,upcoming:Y}}async function k1(){let J=new Date,$=new Date(J);$.setDate(J.getDate()-7);let G=new Date(J);G.setMonth(J.getMonth()-1);let X=new Date(J);X.setFullYear(J.getFullYear()-1);let Z=await r0(null,null,J),Y=await r0($,null,J),L=await r0(G,null,J),K=await r0(X,null,J);return{week:Y,month:L,year:K,all_time:Z}}async function r0(J,$,G){let X=x.selectFrom("coupons");if(J)X=X.where("created_at",">=",J.toISOString());if($)X=X.where("created_at","<=",$.toISOString());let Z=await X.select(x.fn.count("id").as("count")).executeTakeFirst(),Y=x.selectFrom("coupons");if(J)Y=Y.where("created_at",">=",J.toISOString());if($)Y=Y.where("created_at","<=",$.toISOString());Y=Y.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let L=await Y.select(x.fn.count("id").as("count")).executeTakeFirst(),K=Number(Z?.count||0),W=Number(L?.count||0),F=K-W;return{total:K,active:W,inactive:F}}async function C1(){let J=new Date,$=await x.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:X}of $){let Z=await x.selectFrom("coupons").where("discount_type","=",X).select(x.fn.count("id").as("count")).executeTakeFirst(),Y=await x.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),L=Number(Z?.count||0),K=Number(Y?.count||0);G[X]={total:L,active:K,inactive:L-K}}return G}async function h1(){let J=await x.selectFrom("coupons").select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,G=new Date($);G.setDate($.getDate()-7);let X=new Date($);X.setMonth($.getMonth()-1);let Z=new Date($);Z.setFullYear($.getFullYear()-1);let Y=await x.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await x.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),K=await x.selectFrom("coupons").where("updated_at",">=",Z.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await x.selectFrom("coupons").select(["discount_type",x.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),F={};return W.forEach((N)=>{F[N.discount_type]=Number(N.total||0)}),{total:Number(J?.total||0),week:Number(Y?.total||0),month:Number(L?.total||0),year:Number(K?.total||0),by_type:F}}async function I1(J=5){return await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(J).execute()}async function g1(J=30){let $=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-J);let X=await x.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),Z={};return X.forEach((Y)=>{let L=Y.updated_at?new Date(Y.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!Z[L])Z[L]=0;Z[L]+=Y?.usage_count||0}),Object.entries(Z).map(([Y,L])=>({date:Y,count:L}))}async function D1(){let J=new Date,$=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),G=await x.selectFrom("coupons").where("usage_count",">",0).select(x.fn.count("id").as("count")).executeTakeFirst(),X=Number($?.count||0),Z=Number(G?.count||0);return{rate:X>0?Z/X*100:0,total_active:X,total_redeemed:Z}}async function v1(){let J=new Date,$=new Date(J.getFullYear(),J.getMonth(),1),G=new Date(J.getFullYear(),J.getMonth()-1,1),X=new Date(J.getFullYear(),J.getMonth(),0),Z=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),Y=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",G).executeTakeFirst(),L=Number(Z?.count||0),K=Number(Y?.count||0),W=L-K,F=K!==0?W/K*100:L>0?100:0;return{current_month:L,previous_month:K,difference:W,percentage_change:F}}var{randomUUIDv7:M3}=globalThis.Bun;import{db as y1}from"@stacksjs/database";import{HttpError as b1}from"@stacksjs/error-handling";import{isUniqueViolation as x3}from"@stacksjs/orm";async function m1(J){try{let $=M3();return await y1.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await y1.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof b1)throw $;if(x3($))throw new b1(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as l1}from"@stacksjs/database";import{HttpError as p1}from"@stacksjs/error-handling";import{formatDate as c1,isUniqueViolation as V3}from"@stacksjs/orm";async function u1(J,$){if(!await G0(J))return;try{return await l1.updateTable("coupons").set({...$,updated_at:c1(new Date)}).where("id","=",J).execute(),await G0(J)}catch(X){if(X instanceof p1)throw X;if(V3(X))throw new p1(409,"A coupon with this code already exists");if(X instanceof Error)throw Error(`Failed to update coupon: ${X.message}`);throw X}}async function n1(J){let $=c1(new Date),G=await l1.unsafe(`UPDATE coupons
2
+ var Q3=Object.defineProperty;var N3=(J)=>J;function H3(J,$){this[J]=N3.bind(null,$)}var z=(J,$)=>{for(var G in $)Q3(J,G,{get:$[G],enumerable:!0,configurable:!0,set:H3.bind($,G)})};var M3=(J,$)=>()=>(J&&($=J(J=0)),$);var J0=import.meta.require;var VJ={};z(VJ,{emitOrderShipped:()=>K$,emitOrderRefunded:()=>M0,emitOrderPaid:()=>d,emitOrderOutForDelivery:()=>xJ,emitOrderDelivered:()=>W$,emitOrderCreated:()=>j0,emitOrderCancelled:()=>H0,emitForStatus:()=>f0,canTransition:()=>w0});function w0(J,$){if(J===$)return!0;return D3[J]?.includes($)??!1}async function Z0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function j0(J){await Z0("order:created",{order:J})}async function d(J,$){await Z0("order:paid",{order:J,payment:$})}async function K$(J){await Z0("order:shipped",{order:J})}async function xJ(J){await Z0("order:out_for_delivery",{order:J})}async function W$(J){await Z0("order:delivered",{order:J})}async function H0(J,$){await Z0("order:cancelled",{order:J,reason:$})}async function M0(J,$){await Z0("order:refunded",{order:J,refundAmount:$})}async function f0(J,$){switch(J){case"PROCESSING":return d($);case"SHIPPED":return K$($);case"OUT_FOR_DELIVERY":return xJ($);case"DELIVERED":return W$($);case"CANCELLED":return H0($);case"REFUNDED":return M0($);case"PENDING":default:}}var D3;var x0=M3(()=>{D3={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 N4={};z(N4,{update:()=>i1,store:()=>l1,redeem:()=>o1,getActiveCouponsMoMChange:()=>b1,fetchTopRedeemedCoupons:()=>D1,fetchStats:()=>C1,fetchRedemptionTrend:()=>v1,fetchRedemptionStats:()=>g1,fetchCouponCountsByType:()=>h1,fetchCouponCounts:()=>I1,fetchConversionRate:()=>y1,fetchById:()=>G0,fetchByCode:()=>f1,fetchAll:()=>j1,fetchActive:()=>k1,deleteExpiredCoupons:()=>E1,deleteCoupons:()=>T1,deleteCoupon:()=>S1});import{db as e0}from"@stacksjs/database";import{formatDate as x3}from"@stacksjs/orm";function Q(J){if(typeof J==="number")return Number.isFinite(J)?J:0;if(typeof J==="bigint")return Number(J);if(!J||typeof J!=="object")return 0;let $=J;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[G]!==void 0&&$[G]!==null)return Q($[G]);if(Array.isArray(J))return J.reduce((G,X)=>G+Q(X),0);return 0}async function S1(J){let $=await e0.deleteFrom("coupons").where("id","=",J).executeTakeFirst();return Q($)>0}async function T1(J){if(!J.length)return 0;return(await e0.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function E1(){let J=x3(new Date),$=await e0.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return Q($)}import{db as x}from"@stacksjs/database";import{extractDate as q1,formatDate as w1}from"@stacksjs/orm";import{camelCase as V3}from"@stacksjs/strings";function t0(J){let $=Object.fromEntries(Object.entries(J).map(([G,X])=>[V3(G),X]));if($.endDate)$.endDate=q1(new Date($.endDate));if($.startDate)$.startDate=q1(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function j1(){return(await x.selectFrom("coupons").selectAll().execute()).map(t0)}async function G0(J){let $=await x.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function f1(J){let $=await x.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function k1(){let J=w1(new Date);return(await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map(t0)}async function C1(){let J=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).executeTakeFirst(),$=w1(new Date),G=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(x.fn.count("id").as("count")).executeTakeFirst(),X=await x.selectFrom("coupons").select(["discount_type",x.fn.count("id").as("count")]).groupBy("discount_type").execute(),Z=await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),Y=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",$).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(J?.count||0),active:Number(G?.count||0),by_type:X,most_used:Z,upcoming:Y}}async function I1(){let J=new Date,$=new Date(J);$.setDate(J.getDate()-7);let G=new Date(J);G.setMonth(J.getMonth()-1);let X=new Date(J);X.setFullYear(J.getFullYear()-1);let Z=await r0(null,null,J),Y=await r0($,null,J),L=await r0(G,null,J),K=await r0(X,null,J);return{week:Y,month:L,year:K,all_time:Z}}async function r0(J,$,G){let X=x.selectFrom("coupons");if(J)X=X.where("created_at",">=",J.toISOString());if($)X=X.where("created_at","<=",$.toISOString());let Z=await X.select(x.fn.count("id").as("count")).executeTakeFirst(),Y=x.selectFrom("coupons");if(J)Y=Y.where("created_at",">=",J.toISOString());if($)Y=Y.where("created_at","<=",$.toISOString());Y=Y.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let L=await Y.select(x.fn.count("id").as("count")).executeTakeFirst(),K=Number(Z?.count||0),W=Number(L?.count||0),F=K-W;return{total:K,active:W,inactive:F}}async function h1(){let J=new Date,$=await x.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:X}of $){let Z=await x.selectFrom("coupons").where("discount_type","=",X).select(x.fn.count("id").as("count")).executeTakeFirst(),Y=await x.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),L=Number(Z?.count||0),K=Number(Y?.count||0);G[X]={total:L,active:K,inactive:L-K}}return G}async function g1(){let J=await x.selectFrom("coupons").select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,G=new Date($);G.setDate($.getDate()-7);let X=new Date($);X.setMonth($.getMonth()-1);let Z=new Date($);Z.setFullYear($.getFullYear()-1);let Y=await x.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await x.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),K=await x.selectFrom("coupons").where("updated_at",">=",Z.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await x.selectFrom("coupons").select(["discount_type",x.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),F={};return W.forEach((N)=>{F[N.discount_type]=Number(N.total||0)}),{total:Number(J?.total||0),week:Number(Y?.total||0),month:Number(L?.total||0),year:Number(K?.total||0),by_type:F}}async function D1(J=5){return await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(J).execute()}async function v1(J=30){let $=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-J);let X=await x.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),Z={};return X.forEach((Y)=>{let L=Y.updated_at?new Date(Y.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!Z[L])Z[L]=0;Z[L]+=Y?.usage_count||0}),Object.entries(Z).map(([Y,L])=>({date:Y,count:L}))}async function y1(){let J=new Date,$=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),G=await x.selectFrom("coupons").where("usage_count",">",0).select(x.fn.count("id").as("count")).executeTakeFirst(),X=Number($?.count||0),Z=Number(G?.count||0);return{rate:X>0?Z/X*100:0,total_active:X,total_redeemed:Z}}async function b1(){let J=new Date,$=new Date(J.getFullYear(),J.getMonth(),1),G=new Date(J.getFullYear(),J.getMonth()-1,1),X=new Date(J.getFullYear(),J.getMonth(),0),Z=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),Y=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",G).executeTakeFirst(),L=Number(Z?.count||0),K=Number(Y?.count||0),W=L-K,F=K!==0?W/K*100:L>0?100:0;return{current_month:L,previous_month:K,difference:W,percentage_change:F}}var{randomUUIDv7:z3}=globalThis.Bun;import{db as m1}from"@stacksjs/database";import{HttpError as p1}from"@stacksjs/error-handling";import{isUniqueViolation as B3}from"@stacksjs/orm";async function l1(J){try{let $=z3();return await m1.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await m1.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof p1)throw $;if(B3($))throw new p1(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as u1}from"@stacksjs/database";import{HttpError as c1}from"@stacksjs/error-handling";import{formatDate as n1,isUniqueViolation as A3}from"@stacksjs/orm";async function i1(J,$){if(!await G0(J))return;try{return await u1.updateTable("coupons").set({...$,updated_at:n1(new Date)}).where("id","=",J).execute(),await G0(J)}catch(X){if(X instanceof c1)throw X;if(A3(X))throw new c1(409,"A coupon with this code already exists");if(X instanceof Error)throw Error(`Failed to update coupon: ${X.message}`);throw X}}async function o1(J){let $=n1(new Date),G=await u1.unsafe(`UPDATE coupons
3
3
  SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ?
4
4
  WHERE id = ?
5
5
  AND (max_uses IS NULL OR usage_count < max_uses)
6
6
  AND is_active = 1
7
7
  AND (start_date IS NULL OR start_date <= ?)
8
- AND (end_date IS NULL OR end_date >= ?)`,[$,J,$,$]),X=typeof G?.execute==="function"?await G.execute():G;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0){let W=await G0(J);if(W)return{ok:!0,coupon:W};return{ok:!1,reason:"not-found"}}let Y=await G0(J);if(!Y)return{ok:!1,reason:"not-found"};if(!Y.isActive)return{ok:!1,reason:"inactive"};let L=!Y.startDate||Y.startDate<=$,K=!Y.endDate||Y.endDate>=$;if(!L||!K)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var H4={};z(H4,{update:()=>$7,store:()=>r1,fetchById:()=>$$,fetchAll:()=>a1,destroy:()=>o1,bulkDestroy:()=>s1});import{db as i1}from"@stacksjs/database";async function o1(J){try{let $=await i1.deleteFrom("customers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function s1(J){if(!J.length)return 0;try{let $=await i1.deleteFrom("customers").where("id","in",J).executeTakeFirst();return Q($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as d1}from"@stacksjs/database";async function $$(J){return await d1.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function a1(){return await d1.selectFrom("customers").selectAll().execute()}import{db as z3}from"@stacksjs/database";import{HttpError as e1}from"@stacksjs/error-handling";import{isUniqueViolation as B3}from"@stacksjs/orm";async function r1(J){try{let $={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await z3.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 e1)throw $;if(B3($))throw new e1(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as A3}from"@stacksjs/database";import{HttpError as t1}from"@stacksjs/error-handling";import{formatDate as O3,isUniqueViolation as _3}from"@stacksjs/orm";async function $7(J,$){try{if(!J)throw Error("Customer ID is required for update");let G=await A3.updateTable("customers").set({...$,updated_at:O3(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof t1)throw G;if(_3(G))throw new t1(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var B4={};z(B4,{updateStatus:()=>B7,updatePrintCount:()=>A7,update:()=>z7,storePrintDevicesExport:()=>H7,store:()=>x7,getPrinterStatusCounts:()=>Q7,fetchErrorsByDeviceId:()=>W7,fetchById:()=>l,fetchAll:()=>J$,exportPrintDevices:()=>G$,downloadPrintDevices:()=>N7,destroy:()=>G7,countTotalPrints:()=>Y7,countPrintsByDeviceId:()=>L7,countAll:()=>Z7,calculatePrinterHealth:()=>F7,calculateErrorRate:()=>K7,bulkStore:()=>V7,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 Q($)>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 Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as R3}from"ts-spreadsheets";import{db as w}from"@stacksjs/database";async function l(J){return await w.selectFrom("print_devices").where("id","=",J).selectAll().executeTakeFirst()}async function J$(){return await w.selectFrom("print_devices").selectAll().execute()}async function Z7(){let J=await w.selectFrom("print_devices").select(w.fn.count("id").as("count")).executeTakeFirst();return Number(J?.count||0)}async function Y7(){let J=await w.selectFrom("print_devices").select(w.fn.sum("print_count").as("total")).executeTakeFirst();return Number(J?.total||0)}async function L7(J){return(await w.selectFrom("print_devices").select("print_count").where("id","=",J).executeTakeFirst())?.print_count??0}async function K7(){let J=await w.selectFrom("receipts").select([w.fn.count("id").as("total"),w.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 W7(J){return await w.selectFrom("receipts").where("print_device_id","=",J).where("status","=","failed").selectAll().execute()}async function F7(){let J=await w.selectFrom("print_devices").select([w.fn.count("id").as("total"),w.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 Q7(){return(await w.selectFrom("print_devices").select(["status",w.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,G)=>{return $[G.status]=Number(G.count||0),$},{})}function M4(J,$,G=$){return J?.[$]??J?.[G]}function U3(J){let $=String(J||""),G=/^\d+$/.test($)?Number($):J;return new Date(G)}async function G$(J="csv"){let $=await J$(),G=P3($);return R3(G,{type:J})}function P3(J){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=J.map((X)=>{return[X.id,X.name,M4(X,"macAddress","mac_address"),X.location,X.terminal,X.status,U3(M4(X,"lastPing","last_ping")).toLocaleString(),M4(X,"printCount","print_count")]});return{headings:$,data:G}}async function N7(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:M7}=globalThis.Bun;import{db as x4}from"@stacksjs/database";async function x7(J){try{let $=M7(),G={last_ping:0,print_count:0,...J,uuid:$};return await x4.insertInto("print_devices").values(G).executeTakeFirst(),await x4.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function V7(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={last_ping:0,print_count:0,...G,uuid:M7()};await x4.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 V4}from"@stacksjs/database";import{formatDate as z4}from"@stacksjs/orm";async function z7(J,$){if(!await l(J))return;try{return await V4.updateTable("print_devices").set({...$,updated_at:z4(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 V4.updateTable("print_devices").set({status:$,updated_at:z4(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 V4.updateTable("print_devices").set({print_count:$,updated_at:z4(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 _4={};z(_4,{update:()=>q7,unresolveGroup:()=>k7,resolveGroup:()=>f7,ignoreGroup:()=>j7,fetchTimeline:()=>E7,fetchStats:()=>T7,fetchGrouped:()=>P7,fetchById:()=>U7,fetchByGroup:()=>S7,fetchAll:()=>Z$,destroyGroup:()=>R7,destroy:()=>O7,bulkUpdateStatus:()=>w7,bulkDestroy:()=>_7});import{db as A4}from"@stacksjs/database";import{log as O4}from"@stacksjs/logging";async function O7(J){try{return await A4.deleteFrom("errors").where("id","=",J).execute(),!0}catch($){return O4.error("[commerce/errors] destroy failed",{id:J,error:$}),!1}}async function _7(J){try{return await A4.deleteFrom("errors").where("id","in",J).execute(),!0}catch($){return O4.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:$}),!1}}async function R7(J,$){try{return await A4.deleteFrom("errors").where("type","=",J).where("message","=",$).execute(),!0}catch(G){return O4.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 Z$(){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 Z=`${X.type}:${X.message}`;if(!$.has(Z))$.set(Z,{errors:[],firstSeen:new Date(X.created_at),lastSeen:new Date(X.created_at)});let Y=$.get(Z);Y.errors.push(X);let L=new Date(X.created_at);if(L<Y.firstSeen)Y.firstSeen=L;if(L>Y.lastSeen)Y.lastSeen=L}let G=[];for(let[X,Z]of $){let Y=Z.errors[0];if(!Y)continue;let L=Z.errors.find((W)=>W.status!==null)?.status,K="unresolved";if(L===1)K="resolved";else if(L===2)K="ignored";G.push({id:Y.id,type:Y.type,message:Y.message,stack:Y.stack,status:K,count:Z.errors.length,first_seen:Z.firstSeen.toISOString(),last_seen:Z.lastSeen.toISOString(),error_ids:Z.errors.map((W)=>W.id)})}return G.sort((X,Z)=>new Date(Z.last_seen).getTime()-new Date(X.last_seen).getTime()),G}async function S7(J,$){return await X$.selectFrom("errors").where("type","=",J).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function T7(){let J=await Z$(),$=new Date,G=new Date($.getTime()-86400000),X=new Date($.getTime()-172800000),Z=J.filter((K)=>new Date(K.created_at)>=G).length,Y=J.filter((K)=>{let W=new Date(K.created_at);return W>=X&&W<G}).length,L=Y===0?Z>0?100:0:Math.round((Z-Y)/Y*100);return{total:J.length,unresolved:J.filter((K)=>K.status===null||K.status===0).length,resolved:J.filter((K)=>K.status===1).length,ignored:J.filter((K)=>K.status===2).length,last_24h:Z,trend:L}}async function E7(){let J=await Z$(),$=new Date,G=[];for(let X=23;X>=0;X--){let Z=new Date($.getTime()-X*60*60*1000);Z.setMinutes(0,0,0);let Y=new Date(Z.getTime()+3600000),L=J.filter((K)=>{let W=new Date(K.created_at);return W>=Z&&W<Y}).length;G.push({hour:Z.toISOString(),count:L})}return G}import{db as T0}from"@stacksjs/database";import{sql as E0}from"@stacksjs/database";import{log as q0}from"@stacksjs/logging";async function q7(J,$){try{return await T0.updateTable("errors").set({...$,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(G){return q0.error("[commerce/errors] update failed",{id:J,error:G}),!1}}async function w7(J,$){try{return await T0.updateTable("errors").set({status:$,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("id","in",J).execute(),!0}catch(G){return q0.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:$,error:G}),!1}}async function f7(J,$){try{return await T0.updateTable("errors").set({status:1,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return q0.error("[commerce/errors] resolveGroup failed",{type:J,message:$,error:G}),!1}}async function j7(J,$){try{return await T0.updateTable("errors").set({status:2,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return q0.error("[commerce/errors] ignoreGroup failed",{type:J,message:$,error:G}),!1}}async function k7(J,$){try{return await T0.updateTable("errors").set({status:0,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return q0.error("[commerce/errors] unresolveGroup failed",{type:J,message:$,error:G}),!1}}var U4={};z(U4,{updateBalance:()=>a7,update:()=>d7,store:()=>n7,fetchTotalValue:()=>y7,fetchTotalCurrentBalance:()=>b7,fetchStats:()=>I7,fetchById:()=>X0,fetchByCode:()=>R4,fetchAll:()=>C7,fetchActive:()=>h7,destroy:()=>p7,compareActiveGiftCards:()=>D7,checkBalance:()=>g7,calculateGiftCardValues:()=>v7,bulkDestroy:()=>l7});import{db as m7}from"@stacksjs/database";import{formatDate as V5}from"@stacksjs/orm";import{db as P,sql as C}from"@stacksjs/database";import{formatDate as s,toTimestamp as N0}from"@stacksjs/orm";import{aggregateFunctions as S3,db as T3}from"@stacksjs/database";async function I(J,$,G){let X=T3.selectFrom(J);if(G)X=G(X);X=X.select(Object.entries($).map(([L,K])=>{let W=K.column??"id",F=S3[K.kind](W);if(K.filter)F=F.filterWhere(K.filter.column,K.filter.op,K.filter.value);return F.as(L)}));let Z=await X.executeTakeFirst(),Y={};for(let L of Object.keys($)){let K=Z?.[L];Y[L]=typeof K==="number"?K:Number(K??0)||0}return Y}async function 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 R4(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"}}),$=N0(new Date),G=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal($)} OR expiry_date IS NULL)`).select(P.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("gift_cards").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute(),{count:Z}=await I("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:Y}=await I("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:L}=await I("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance > 0.75`)),K=new Date;K.setDate(K.getDate()+30);let W=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",N0(K)).where("expiry_date",">=",$).selectAll().limit(5).execute(),F=await P.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:J,active:Number(G?.count||0),by_status:X.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:Z,medium:Y,high:L},expiring_soon:W,recently_used:F}}async function g7(J){let $=await R4(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 D7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),L=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",s(Z)).where("created_at","<=",s(X)).executeTakeFirst(),K=Number(Y?.count||0),W=Number(L?.count||0),F=K-W,N=W!==0?F/W*100:K>0?100:0;return{current_period:K,previous_period:W,difference:F,percentage_change:N,days_range:J}}async function v7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),L=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",s(Z)).where("created_at","<=",s(X)).executeTakeFirst(),K=Number(Y?.total_initial||0),W=Number(Y?.total_balance||0),F=Number(Y?.card_count||0),N=Number(L?.total_initial||0),H=Number(L?.total_balance||0),M=Number(L?.card_count||0),O=K>0?(K-W)/K*100:0,R=N>0?(N-H)/N*100:0,_=F>0?K/F:0,U=F>0?W/F:0,m=K-N,t=W-H,$0=F-M,Q0=N!==0?m/N*100:K>0?100:0,p=H!==0?t/H*100:W>0?100:0,L3=M!==0?$0/M*100:F>0?100:0;return{current_period:{total_initial_value:K,total_remaining_balance:W,utilization_rate:O,card_count:F,average_initial_value:_,average_remaining_balance:U},previous_period:{total_initial_value:N,total_remaining_balance:H,utilization_rate:R,card_count:M},comparison:{initial_value:{difference:m,percentage:Math.abs(Q0),is_increase:m>=0},balance:{difference:t,percentage:Math.abs(p),is_increase:t>=0},card_count:{difference:$0,percentage:Math.abs(L3),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 Q($)>0}async function l7(J){if(!J.length)return 0;let $=await m7.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return Q($)}var{randomUUIDv7:E3}=globalThis.Bun;import{db as c7}from"@stacksjs/database";import{HttpError as u7}from"@stacksjs/error-handling";import{isUniqueViolation as q3}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:E3()};try{let X=await c7.insertInto("gift_cards").values(G).executeTakeFirst(),Z=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if(Z)return await c7.selectFrom("gift_cards").where("id","=",Z).selectAll().executeTakeFirst();return}catch(X){if(X instanceof u7)throw X;if(q3(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 w3}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(w3(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
8
+ AND (end_date IS NULL OR end_date >= ?)`,[$,J,$,$]),X=typeof G?.execute==="function"?await G.execute():G;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0){let W=await G0(J);if(W)return{ok:!0,coupon:W};return{ok:!1,reason:"not-found"}}let Y=await G0(J);if(!Y)return{ok:!1,reason:"not-found"};if(!Y.isActive)return{ok:!1,reason:"inactive"};let L=!Y.startDate||Y.startDate<=$,K=!Y.endDate||Y.endDate>=$;if(!L||!K)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var H4={};z(H4,{update:()=>G7,store:()=>$7,fetchById:()=>$$,fetchAll:()=>r1,destroy:()=>d1,bulkDestroy:()=>a1});import{db as s1}from"@stacksjs/database";async function d1(J){try{let $=await s1.deleteFrom("customers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function a1(J){if(!J.length)return 0;try{let $=await s1.deleteFrom("customers").where("id","in",J).executeTakeFirst();return Q($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as e1}from"@stacksjs/database";async function $$(J){return await e1.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function r1(){return await e1.selectFrom("customers").selectAll().execute()}import{db as O3}from"@stacksjs/database";import{HttpError as t1}from"@stacksjs/error-handling";import{isUniqueViolation as _3}from"@stacksjs/orm";async function $7(J){try{let $={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await O3.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 t1)throw $;if(_3($))throw new t1(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as R3}from"@stacksjs/database";import{HttpError as J7}from"@stacksjs/error-handling";import{formatDate as U3,isUniqueViolation as P3}from"@stacksjs/orm";async function G7(J,$){try{if(!J)throw Error("Customer ID is required for update");let G=await R3.updateTable("customers").set({...$,updated_at:U3(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof J7)throw G;if(P3(G))throw new J7(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var B4={};z(B4,{updateStatus:()=>O7,updatePrintCount:()=>_7,update:()=>A7,storePrintDevicesExport:()=>x7,store:()=>z7,getPrinterStatusCounts:()=>H7,fetchErrorsByDeviceId:()=>Q7,fetchById:()=>l,fetchAll:()=>J$,exportPrintDevices:()=>G$,downloadPrintDevices:()=>M7,destroy:()=>Z7,countTotalPrints:()=>K7,countPrintsByDeviceId:()=>W7,countAll:()=>L7,calculatePrinterHealth:()=>N7,calculateErrorRate:()=>F7,bulkStore:()=>B7,bulkDestroy:()=>Y7});import{db as X7}from"@stacksjs/database";async function Z7(J){try{let $=await X7.deleteFrom("print_devices").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function Y7(J){if(!J.length)return 0;try{let $=await X7.deleteFrom("print_devices").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as S3}from"ts-spreadsheets";import{db as w}from"@stacksjs/database";async function l(J){return await w.selectFrom("print_devices").where("id","=",J).selectAll().executeTakeFirst()}async function J$(){return await w.selectFrom("print_devices").selectAll().execute()}async function L7(){let J=await w.selectFrom("print_devices").select(w.fn.count("id").as("count")).executeTakeFirst();return Number(J?.count||0)}async function K7(){let J=await w.selectFrom("print_devices").select(w.fn.sum("print_count").as("total")).executeTakeFirst();return Number(J?.total||0)}async function W7(J){return(await w.selectFrom("print_devices").select("print_count").where("id","=",J).executeTakeFirst())?.print_count??0}async function F7(){let J=await w.selectFrom("receipts").select([w.fn.count("id").as("total"),w.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 Q7(J){return await w.selectFrom("receipts").where("print_device_id","=",J).where("status","=","failed").selectAll().execute()}async function N7(){let J=await w.selectFrom("print_devices").select([w.fn.count("id").as("total"),w.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 H7(){return(await w.selectFrom("print_devices").select(["status",w.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,G)=>{return $[G.status]=Number(G.count||0),$},{})}function M4(J,$,G=$){return J?.[$]??J?.[G]}function T3(J){let $=String(J||""),G=/^\d+$/.test($)?Number($):J;return new Date(G)}async function G$(J="csv"){let $=await J$(),G=E3($);return S3(G,{type:J})}function E3(J){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=J.map((X)=>{return[X.id,X.name,M4(X,"macAddress","mac_address"),X.location,X.terminal,X.status,T3(M4(X,"lastPing","last_ping")).toLocaleString(),M4(X,"printCount","print_count")]});return{headings:$,data:G}}async function M7(J="csv",$){let G=await G$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function x7(J="csv",$){let G=await G$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}var{randomUUIDv7:V7}=globalThis.Bun;import{db as x4}from"@stacksjs/database";async function z7(J){try{let $=V7(),G={last_ping:0,print_count:0,...J,uuid:$};return await x4.insertInto("print_devices").values(G).executeTakeFirst(),await x4.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function B7(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={last_ping:0,print_count:0,...G,uuid:V7()};await x4.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 V4}from"@stacksjs/database";import{formatDate as z4}from"@stacksjs/orm";async function A7(J,$){if(!await l(J))return;try{return await V4.updateTable("print_devices").set({...$,updated_at:z4(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 O7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await V4.updateTable("print_devices").set({status:$,updated_at:z4(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 _7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await V4.updateTable("print_devices").set({print_count:$,updated_at:z4(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 _4={};z(_4,{update:()=>j7,unresolveGroup:()=>I7,resolveGroup:()=>k7,ignoreGroup:()=>C7,fetchTimeline:()=>w7,fetchStats:()=>q7,fetchGrouped:()=>T7,fetchById:()=>S7,fetchByGroup:()=>E7,fetchAll:()=>Z$,destroyGroup:()=>P7,destroy:()=>R7,bulkUpdateStatus:()=>f7,bulkDestroy:()=>U7});import{db as A4}from"@stacksjs/database";import{log as O4}from"@stacksjs/logging";async function R7(J){try{return await A4.deleteFrom("errors").where("id","=",J).execute(),!0}catch($){return O4.error("[commerce/errors] destroy failed",{id:J,error:$}),!1}}async function U7(J){try{return await A4.deleteFrom("errors").where("id","in",J).execute(),!0}catch($){return O4.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:$}),!1}}async function P7(J,$){try{return await A4.deleteFrom("errors").where("type","=",J).where("message","=",$).execute(),!0}catch(G){return O4.error("[commerce/errors] destroyGroup failed",{type:J,message:$,error:G}),!1}}import{db as X$}from"@stacksjs/database";async function S7(J){return await X$.selectFrom("errors").where("id","=",J).selectAll().executeTakeFirst()}async function Z$(){return await X$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function T7(){let J=await X$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let X of J){let Z=`${X.type}:${X.message}`;if(!$.has(Z))$.set(Z,{errors:[],firstSeen:new Date(X.created_at),lastSeen:new Date(X.created_at)});let Y=$.get(Z);Y.errors.push(X);let L=new Date(X.created_at);if(L<Y.firstSeen)Y.firstSeen=L;if(L>Y.lastSeen)Y.lastSeen=L}let G=[];for(let[X,Z]of $){let Y=Z.errors[0];if(!Y)continue;let L=Z.errors.find((W)=>W.status!==null)?.status,K="unresolved";if(L===1)K="resolved";else if(L===2)K="ignored";G.push({id:Y.id,type:Y.type,message:Y.message,stack:Y.stack,status:K,count:Z.errors.length,first_seen:Z.firstSeen.toISOString(),last_seen:Z.lastSeen.toISOString(),error_ids:Z.errors.map((W)=>W.id)})}return G.sort((X,Z)=>new Date(Z.last_seen).getTime()-new Date(X.last_seen).getTime()),G}async function E7(J,$){return await X$.selectFrom("errors").where("type","=",J).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function q7(){let J=await Z$(),$=new Date,G=new Date($.getTime()-86400000),X=new Date($.getTime()-172800000),Z=J.filter((K)=>new Date(K.created_at)>=G).length,Y=J.filter((K)=>{let W=new Date(K.created_at);return W>=X&&W<G}).length,L=Y===0?Z>0?100:0:Math.round((Z-Y)/Y*100);return{total:J.length,unresolved:J.filter((K)=>K.status===null||K.status===0).length,resolved:J.filter((K)=>K.status===1).length,ignored:J.filter((K)=>K.status===2).length,last_24h:Z,trend:L}}async function w7(){let J=await Z$(),$=new Date,G=[];for(let X=23;X>=0;X--){let Z=new Date($.getTime()-X*60*60*1000);Z.setMinutes(0,0,0);let Y=new Date(Z.getTime()+3600000),L=J.filter((K)=>{let W=new Date(K.created_at);return W>=Z&&W<Y}).length;G.push({hour:Z.toISOString(),count:L})}return G}import{db as T0}from"@stacksjs/database";import{sql as E0}from"@stacksjs/database";import{log as q0}from"@stacksjs/logging";async function j7(J,$){try{return await T0.updateTable("errors").set({...$,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(G){return q0.error("[commerce/errors] update failed",{id:J,error:G}),!1}}async function f7(J,$){try{return await T0.updateTable("errors").set({status:$,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("id","in",J).execute(),!0}catch(G){return q0.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:$,error:G}),!1}}async function k7(J,$){try{return await T0.updateTable("errors").set({status:1,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return q0.error("[commerce/errors] resolveGroup failed",{type:J,message:$,error:G}),!1}}async function C7(J,$){try{return await T0.updateTable("errors").set({status:2,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return q0.error("[commerce/errors] ignoreGroup failed",{type:J,message:$,error:G}),!1}}async function I7(J,$){try{return await T0.updateTable("errors").set({status:0,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return q0.error("[commerce/errors] unresolveGroup failed",{type:J,message:$,error:G}),!1}}var U4={};z(U4,{updateBalance:()=>r7,update:()=>e7,store:()=>o7,fetchTotalValue:()=>m7,fetchTotalCurrentBalance:()=>p7,fetchStats:()=>D7,fetchById:()=>X0,fetchByCode:()=>R4,fetchAll:()=>h7,fetchActive:()=>g7,destroy:()=>c7,compareActiveGiftCards:()=>y7,checkBalance:()=>v7,calculateGiftCardValues:()=>b7,bulkDestroy:()=>u7});import{db as l7}from"@stacksjs/database";import{formatDate as _5}from"@stacksjs/orm";import{db as P,sql as C}from"@stacksjs/database";import{formatDate as s,toTimestamp as N0}from"@stacksjs/orm";import{aggregateFunctions as q3,db as w3}from"@stacksjs/database";async function h(J,$,G){let X=w3.selectFrom(J);if(G)X=G(X);X=X.select(Object.entries($).map(([L,K])=>{let W=K.column??"id",F=q3[K.kind](W);if(K.filter)F=F.filterWhere(K.filter.column,K.filter.op,K.filter.value);return F.as(L)}));let Z=await X.executeTakeFirst(),Y={};for(let L of Object.keys($)){let K=Z?.[L];Y[L]=typeof K==="number"?K:Number(K??0)||0}return Y}async function h7(){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 R4(J){return await P.selectFrom("gift_cards").where("code","=",J).selectAll().executeTakeFirst()}async function g7(){return await P.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function D7(){let{count:J}=await h("gift_cards",{count:{kind:"count"}}),$=N0(new Date),G=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal($)} OR expiry_date IS NULL)`).select(P.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("gift_cards").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute(),{count:Z}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:Y}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:L}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance > 0.75`)),K=new Date;K.setDate(K.getDate()+30);let W=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",N0(K)).where("expiry_date",">=",$).selectAll().limit(5).execute(),F=await P.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:J,active:Number(G?.count||0),by_status:X.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:Z,medium:Y,high:L},expiring_soon:W,recently_used:F}}async function v7(J){let $=await R4(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 y7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),L=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",s(Z)).where("created_at","<=",s(X)).executeTakeFirst(),K=Number(Y?.count||0),W=Number(L?.count||0),F=K-W,N=W!==0?F/W*100:K>0?100:0;return{current_period:K,previous_period:W,difference:F,percentage_change:N,days_range:J}}async function b7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),L=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",s(Z)).where("created_at","<=",s(X)).executeTakeFirst(),K=Number(Y?.total_initial||0),W=Number(Y?.total_balance||0),F=Number(Y?.card_count||0),N=Number(L?.total_initial||0),H=Number(L?.total_balance||0),M=Number(L?.card_count||0),O=K>0?(K-W)/K*100:0,R=N>0?(N-H)/N*100:0,_=F>0?K/F:0,U=F>0?W/F:0,m=K-N,t=W-H,$0=F-M,Q0=N!==0?m/N*100:K>0?100:0,p=H!==0?t/H*100:W>0?100:0,F3=M!==0?$0/M*100:F>0?100:0;return{current_period:{total_initial_value:K,total_remaining_balance:W,utilization_rate:O,card_count:F,average_initial_value:_,average_remaining_balance:U},previous_period:{total_initial_value:N,total_remaining_balance:H,utilization_rate:R,card_count:M},comparison:{initial_value:{difference:m,percentage:Math.abs(Q0),is_increase:m>=0},balance:{difference:t,percentage:Math.abs(p),is_increase:t>=0},card_count:{difference:$0,percentage:Math.abs(F3),is_increase:$0>=0}},days_range:J}}async function m7(){let{total_value:J}=await h("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:J}}async function p7(){let{total_balance:J}=await h("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:J}}async function c7(J){let $=await l7.deleteFrom("gift_cards").where("id","=",J).executeTakeFirst();return Q($)>0}async function u7(J){if(!J.length)return 0;let $=await l7.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return Q($)}var{randomUUIDv7:j3}=globalThis.Bun;import{db as n7}from"@stacksjs/database";import{HttpError as i7}from"@stacksjs/error-handling";import{isUniqueViolation as f3}from"@stacksjs/orm";async function o7(J){let $=J,G={...J,current_balance:$.current_balance??$.initial_balance,status:J.status||"ACTIVE",is_active:$.is_active??!0,uuid:j3()};try{let X=await n7.insertInto("gift_cards").values(G).executeTakeFirst(),Z=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if(Z)return await n7.selectFrom("gift_cards").where("id","=",Z).selectAll().executeTakeFirst();return}catch(X){if(X instanceof i7)throw X;if(f3(X))throw new i7(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 d7}from"@stacksjs/database";import{HttpError as s7}from"@stacksjs/error-handling";import{formatDate as a7,isUniqueViolation as k3}from"@stacksjs/orm";async function e7(J,$){if(!await X0(J))return;try{return await d7.updateTable("gift_cards").set({...$,updated_at:a7(new Date)}).where("id","=",J).execute(),await X0(J)}catch(X){if(X instanceof s7)throw X;if(k3(X))throw new s7(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 r7(J,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let G=a7(new Date),X=await d7.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 K3=Object.defineProperty;var W3=(J)=>J;function F3(J,$){this[J]=W3.bind(null
13
13
  WHERE id = ?
14
14
  AND is_active = 1
15
15
  AND status = 'ACTIVE'
16
- AND current_balance + ? >= 0`,[$,G,$,G,J,$]),Z=typeof X?.execute==="function"?await X.execute():X;if(Number(Z?.changes??Z?.numUpdatedRows??Z?.affectedRows??0)>0)return await X0(J);let L=await X0(J);if(!L)throw Error(`Gift card with ID ${J} not found`);if(!L.is_active||L.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var k4={};z(k4,{validateQuantityBounds:()=>j4,validateCouponStacking:()=>qJ,validateCartQuantities:()=>wJ,updateStatus:()=>RJ,updateDeliveryInfo:()=>UJ,update:()=>_J,storeOrdersExport:()=>XJ,store:()=>NJ,softDelete:()=>r7,registerCommerceWebhookHandlers:()=>SJ,recomputeOrderTotals:()=>EJ,placeOrder:()=>OJ,handlePaymentIntentSucceeded:()=>q4,handlePaymentIntentFailed:()=>w4,handleChargeRefunded:()=>f4,findOrderByIdempotencyKey:()=>Q$,fetchStats:()=>YJ,fetchDailyOrderTrends:()=>WJ,fetchById:()=>c,fetchAll:()=>ZJ,exportOrders:()=>L$,emitOrderShipped:()=>K$,emitOrderRefunded:()=>M0,emitOrderPaid:()=>d,emitOrderDelivered:()=>W$,emitOrderCreated:()=>f0,emitOrderCancelled:()=>H0,emitForStatus:()=>j0,downloadOrders:()=>GJ,destroy:()=>e7,compareOrdersByPeriod:()=>LJ,cleanupAbandonedCarts:()=>fJ,canTransition:()=>w0,calculateOrderMetrics:()=>KJ,bulkSoftDelete:()=>$J,bulkDestroy:()=>t7});import{db as Y$}from"@stacksjs/database";async function e7(J){try{let $=await Y$.deleteFrom("orders").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function r7(J){try{let $=await Y$.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 Y$.deleteFrom("orders").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}async function $J(J){if(!J.length)return 0;try{let $=await Y$.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 f3}from"ts-spreadsheets";async function L$(J="csv"){let $=await j3(),G=k3($);return f3(G,{type:J})}async function j3(){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((Y)=>Y.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((Y,L)=>{if(!L.order_id)return Y;if(!Y[L.order_id])Y[L.order_id]={totalItems:0,totalPrice:0};return Y[L.order_id].totalItems+=L.quantity,Y[L.order_id].totalPrice+=L.price*L.quantity,Y},{});return J.map((Y)=>{let L=X[Y.id]||{totalItems:0,totalPrice:0};return{...Y,totalItems:L.totalItems,totalPrice:L.totalPrice}})}function k3(J){let $=["Order ID","Customer","Date","Total","Status","Items"],G=J.map((X)=>{let Z=X.order_items?.map((Y)=>`${Y.product?.name} (Qty: ${Y.quantity}, Price: $${Y.price})`).join(" | ")||"No Items";return[X.id,X.customer?.name||"N/A",X.created_at,X.total_amount,X.status,Z]});return{headings:$,data:G}}async function GJ(J="csv",$){let G=await L$(J),X=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function XJ(J="csv",$){let G=await L$(J),X=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}import{db as B}from"@stacksjs/database";async function ZJ(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 Z=await B.selectFrom("order_items").where("order_id","=",X.id).selectAll().execute();return{...X,items:Z}}))}async function c(J){return await B.selectFrom("orders").where("id","=",J).selectAll().executeTakeFirst()}async function YJ(){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(),Z=await Promise.all(X.map(async(L)=>{let K=await B.selectFrom("order_items").where("order_id","=",L.id).selectAll().execute();return{...L,items:K}})),Y=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:Z,revenue:Number(Y?.total||0)}}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 Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),L=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),K=Number(Y?.count||0),W=Number(L?.count||0),F=K-W,N=W!==0?F/W*100:K>0?100:0;return{current_period:K,previous_period:W,difference:F,percentage_change:N,days_range:J}}async function KJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await 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(),L=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),K=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("status").execute(),W=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(),F=Number(Y?.total_orders||0),N=Number(Y?.total_revenue||0),H=F>0?N/F:0,M=Number(L?.total_orders||0),O=Number(L?.total_revenue||0),R=M>0?O/M:0,_=F-M,U=N-O,m=H-R,t=M!==0?_/M*100:F>0?100:0,$0=O!==0?U/O*100:N>0?100:0,Q0=R!==0?m/R*100:H>0?100:0;return{current_period:{total_orders:F,total_revenue:N,average_order_value:H,orders_by_status:K.map((p)=>({status:p.status,count:Number(p.count)})),orders_by_type:W.map((p)=>({order_type:p.order_type,count:Number(p.count)}))},previous_period:{total_orders:M,total_revenue:O,average_order_value:R},comparison:{orders:{difference:_,percentage:Math.abs(t),is_increase:_>=0},revenue:{difference:U,percentage:Math.abs($0),is_increase:U>=0},average_order_value:{difference:m,percentage:Math.abs(Q0),is_increase:m>=0}},days_range:J}}async function WJ(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(),Z=new Map;for(let Y of X){let L=(Y.created_at||"").split("T")[0]||"unknown",K=Z.get(L)||{order_count:0,revenue:0};K.order_count++,K.revenue+=Number(Y.total_amount||0),Z.set(L,K)}return Array.from(Z.entries()).map(([Y,L])=>({date:Y,order_count:L.order_count,revenue:L.revenue}))}var{randomUUIDv7:C3}=globalThis.Bun;import{db as FJ}from"@stacksjs/database";import{formatDate as QJ}from"@stacksjs/orm";async function NJ(J){let $={...J,status:J.status||"PENDING",uuid:C3(),created_at:QJ(new Date),updated_at:QJ(new Date)};try{let G=await FJ.insertInto("orders").values($).executeTakeFirst(),X=Number(G?.insertId)||Number(G?.numInsertedOrUpdatedRows);if(X)return await FJ.selectFrom("orders").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof Error)throw Error(`Failed to create order: ${G.message}`);throw G}}x0();var{randomUUIDv7:VJ}=globalThis.Bun;import{db as F$}from"@stacksjs/database";import{formatDate as v3,isUniqueViolation as zJ}from"@stacksjs/orm";import{sqlHelpers as I3}from"@stacksjs/database";import{env as g3}from"@stacksjs/env";function D3(J,$,G,X){let Z=I3(J).param;return{query:`UPDATE products
16
+ AND current_balance + ? >= 0`,[$,G,$,G,J,$]),Z=typeof X?.execute==="function"?await X.execute():X;if(Number(Z?.changes??Z?.numUpdatedRows??Z?.affectedRows??0)>0)return await X0(J);let L=await X0(J);if(!L)throw Error(`Gift card with ID ${J} not found`);if(!L.is_active||L.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var k4={};z(k4,{validateQuantityBounds:()=>f4,validateCouponStacking:()=>jJ,validateCartQuantities:()=>fJ,updateStatus:()=>PJ,updateDeliveryInfo:()=>SJ,update:()=>UJ,storeOrdersExport:()=>YJ,store:()=>MJ,softDelete:()=>$J,registerCommerceWebhookHandlers:()=>EJ,recomputeOrderTotals:()=>wJ,placeOrder:()=>RJ,handlePaymentIntentSucceeded:()=>q4,handlePaymentIntentFailed:()=>w4,handleChargeRefunded:()=>j4,findOrderByIdempotencyKey:()=>Q$,fetchStats:()=>KJ,fetchDailyOrderTrends:()=>QJ,fetchById:()=>c,fetchAll:()=>LJ,exportOrders:()=>L$,emitOrderShipped:()=>K$,emitOrderRefunded:()=>M0,emitOrderPaid:()=>d,emitOrderDelivered:()=>W$,emitOrderCreated:()=>j0,emitOrderCancelled:()=>H0,emitForStatus:()=>f0,downloadOrders:()=>ZJ,destroy:()=>t7,compareOrdersByPeriod:()=>WJ,cleanupAbandonedCarts:()=>kJ,canTransition:()=>w0,calculateOrderMetrics:()=>FJ,bulkSoftDelete:()=>GJ,bulkDestroy:()=>JJ});import{db as Y$}from"@stacksjs/database";async function t7(J){try{let $=await Y$.deleteFrom("orders").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function $J(J){try{let $=await Y$.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 JJ(J){if(!J.length)return 0;try{let $=await Y$.deleteFrom("orders").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}async function GJ(J){if(!J.length)return 0;try{let $=await Y$.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 XJ}from"@stacksjs/database";import{createSpreadsheet as C3}from"ts-spreadsheets";async function L$(J="csv"){let $=await I3(),G=h3($);return C3(G,{type:J})}async function I3(){let J=await XJ.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),$=J.map((Y)=>Y.id);if($.length===0)return[];let X=(await XJ.selectFrom("order_items").where("order_items.order_id","in",$).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((Y,L)=>{if(!L.order_id)return Y;if(!Y[L.order_id])Y[L.order_id]={totalItems:0,totalPrice:0};return Y[L.order_id].totalItems+=L.quantity,Y[L.order_id].totalPrice+=L.price*L.quantity,Y},{});return J.map((Y)=>{let L=X[Y.id]||{totalItems:0,totalPrice:0};return{...Y,totalItems:L.totalItems,totalPrice:L.totalPrice}})}function h3(J){let $=["Order ID","Customer","Date","Total","Status","Items"],G=J.map((X)=>{let Z=X.order_items?.map((Y)=>`${Y.product?.name} (Qty: ${Y.quantity}, Price: $${Y.price})`).join(" | ")||"No Items";return[X.id,X.customer?.name||"N/A",X.created_at,X.total_amount,X.status,Z]});return{headings:$,data:G}}async function ZJ(J="csv",$){let G=await L$(J),X=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function YJ(J="csv",$){let G=await L$(J),X=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}import{db as B}from"@stacksjs/database";async function LJ(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 Z=await B.selectFrom("order_items").where("order_id","=",X.id).selectAll().execute();return{...X,items:Z}}))}async function c(J){return await B.selectFrom("orders").where("id","=",J).selectAll().executeTakeFirst()}async function KJ(){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(),Z=await Promise.all(X.map(async(L)=>{let K=await B.selectFrom("order_items").where("order_id","=",L.id).selectAll().execute();return{...L,items:K}})),Y=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:Z,revenue:Number(Y?.total||0)}}async function WJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),L=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),K=Number(Y?.count||0),W=Number(L?.count||0),F=K-W,N=W!==0?F/W*100:K>0?100:0;return{current_period:K,previous_period:W,difference:F,percentage_change:N,days_range:J}}async function FJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await 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(),L=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),K=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("status").execute(),W=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(),F=Number(Y?.total_orders||0),N=Number(Y?.total_revenue||0),H=F>0?N/F:0,M=Number(L?.total_orders||0),O=Number(L?.total_revenue||0),R=M>0?O/M:0,_=F-M,U=N-O,m=H-R,t=M!==0?_/M*100:F>0?100:0,$0=O!==0?U/O*100:N>0?100:0,Q0=R!==0?m/R*100:H>0?100:0;return{current_period:{total_orders:F,total_revenue:N,average_order_value:H,orders_by_status:K.map((p)=>({status:p.status,count:Number(p.count)})),orders_by_type:W.map((p)=>({order_type:p.order_type,count:Number(p.count)}))},previous_period:{total_orders:M,total_revenue:O,average_order_value:R},comparison:{orders:{difference:_,percentage:Math.abs(t),is_increase:_>=0},revenue:{difference:U,percentage:Math.abs($0),is_increase:U>=0},average_order_value:{difference:m,percentage:Math.abs(Q0),is_increase:m>=0}},days_range:J}}async function QJ(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(),Z=new Map;for(let Y of X){let L=(Y.created_at||"").split("T")[0]||"unknown",K=Z.get(L)||{order_count:0,revenue:0};K.order_count++,K.revenue+=Number(Y.total_amount||0),Z.set(L,K)}return Array.from(Z.entries()).map(([Y,L])=>({date:Y,order_count:L.order_count,revenue:L.revenue}))}var{randomUUIDv7:g3}=globalThis.Bun;import{db as NJ}from"@stacksjs/database";import{formatDate as HJ}from"@stacksjs/orm";async function MJ(J){let $={...J,status:J.status||"PENDING",uuid:g3(),created_at:HJ(new Date),updated_at:HJ(new Date)};try{let G=await NJ.insertInto("orders").values($).executeTakeFirst(),X=Number(G?.insertId)||Number(G?.numInsertedOrUpdatedRows);if(X)return await NJ.selectFrom("orders").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof Error)throw Error(`Failed to create order: ${G.message}`);throw G}}x0();var{randomUUIDv7:BJ}=globalThis.Bun;import{db as F$}from"@stacksjs/database";import{formatDate as m3,isUniqueViolation as AJ}from"@stacksjs/orm";import{sqlHelpers as v3}from"@stacksjs/database";import{env as y3}from"@stacksjs/env";function b3(J,$,G,X){let Z=v3(J).param;return{query:`UPDATE products
17
17
  SET inventory_count = inventory_count + ${Z(1)},
18
18
  updated_at = ${Z(2)}
19
19
  WHERE id = ${Z(3)}
20
- AND inventory_count + ${Z(4)} >= 0`,parameters:[G,X,$,G]}}async function xJ(J,$,G,X){let Z=D3(g3.DB_CONNECTION||"sqlite",$,G,X),Y=await J.unsafe(Z.query,Z.parameters),L=typeof Y?.execute==="function"?await Y.execute():Y;return Q(L)}var 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 Q$(J){try{let $=await F$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await F$.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 OJ(J){if(J.idempotencyKey){let $=await Q$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await F$.transaction(async(G)=>{let X=v3(new Date),Z=VJ(),Y={...J.order,status:J.order.status||"PENDING",uuid:Z,created_at:X,updated_at:X};await G.insertInto("orders").values(Y).executeTakeFirst();let L=await G.selectFrom("orders").where("uuid","=",Z).selectAll().executeTakeFirst(),K=Number(L?.id);if(!Number.isSafeInteger(K)||K<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let W;if(J.items&&J.items.length>0){let H=J.items.map((M)=>{if(!Number.isInteger(M.productId)||M.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(M.quantity)||M.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(M.price)||M.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:K,product_id:M.productId,quantity:M.quantity,price:M.price,special_instructions:M.specialInstructions||null,created_at:X,updated_at:X}});await G.insertInto("order_items").values(H).execute(),W=await G.selectFrom("order_items").where("order_id","=",K).selectAll().execute()}let F;if(J.payment)try{let H=VJ();if(await G.insertInto("payments").values({...J.payment,order_id:K,uuid:H,created_at:X,updated_at:X}).executeTakeFirst(),F=await G.selectFrom("payments").where("uuid","=",H).selectAll().executeTakeFirst(),!F)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(H){if(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:M,delta:O}=J.inventory[H];if(!Number.isFinite(O)||O===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await xJ(G,M,O,X))throw Object.assign(Error(`inventory adjust failed for product ${M}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:K,created_at:X}).execute()}catch(H){if(zJ(H))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!AJ(H))throw H}let N=await G.selectFrom("orders").where("id","=",K).selectAll().executeTakeFirst();if(!N)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:N,items:W,payment:F}});if(f0($.order),$.payment)d($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&J.idempotencyKey){let G=await Q$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}x0();import{db as P4}from"@stacksjs/database";import{formatDate as S4}from"@stacksjs/orm";x0();async function _J(J,$){if(!await c(J))return;try{return await P4.updateTable("orders").set({...$,updated_at:S4(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(!w0(X,$))throw Error(`[commerce/orders] illegal status transition ${X} \u2192 ${$}`);try{await P4.updateTable("orders").set({status:$,updated_at:S4(new Date)}).where("id","=",J).execute();let Z=await c(J);if(Z)j0($,Z);return Z}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update order status: ${Z.message}`);throw Z}}async function UJ(J,$,G){let X=await c(J);if(!X)throw Error(`Order with ID ${J} not found`);let Z={updated_at:S4(new Date)};if($!==void 0)Z.delivery_address=$;if(G!==void 0)Z.estimated_delivery_time=G;if(Object.keys(Z).length===1)return X;try{return await P4.updateTable("orders").set(Z).where("id","=",J).execute(),await c(J)}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery information: ${Y.message}`);throw Y}}x0();import{db as V0}from"@stacksjs/database";import{formatDate as N$}from"@stacksjs/orm";async function T4(J){let $=await V0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await V0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var PJ=!1;function y3(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 E4(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:N$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(y3(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 q4(J){let G=J.data.object?.id;if(!G)return;await V0.transaction(async(Z)=>{if(!await E4(J.id,Z))return;let L=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let K=N$(new Date);await Z.updateTable("payments").set({status:"succeeded",updated_at:K}).where("id","=",L.id).execute();let W=await Z.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(W&&W.status==="PENDING")await Z.updateTable("orders").set({status:"PROCESSING",updated_at:K}).where("id","=",W.id).execute()});let X=await T4(G);if(X)await d(X)}async function w4(J){let $=J.data.object,G=$?.id;if(!G)return;let Z=$?.last_payment_error?.message??"payment failed";await V0.transaction(async(L)=>{if(!await E4(J.id,L))return;let W=await L.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!W)return;let F=N$(new Date);await L.updateTable("payments").set({status:"failed",failure_reason:Z,updated_at:F}).where("id","=",W.id).execute();let N=await L.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await L.updateTable("orders").set({status:"CANCELLED",updated_at:F}).where("id","=",N.id).execute()});let Y=await T4(G);if(Y)await H0(Y,Z)}async function f4(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let X=$?.amount_refunded??0;await V0.transaction(async(Y)=>{if(!await E4(J.id,Y))return;let K=await Y.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!K)return;let W=N$(new Date);await Y.updateTable("payments").set({status:"refunded",refund_amount:X,updated_at:W}).where("id","=",K.id).execute();let F=await Y.selectFrom("orders").where("id","=",K.order_id).selectAll().executeTakeFirst();if(F&&F.status!=="REFUNDED")await Y.updateTable("orders").set({status:"REFUNDED",updated_at:W}).where("id","=",F.id).execute()});let Z=await T4(G);if(Z)await M0(Z,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:q4,failed:w4}),G({refunded:f4}),()=>{}}import{db as TJ}from"@stacksjs/database";async function b3(J){if(J.length===0)return new Map;let $=await TJ.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),G=new Map;for(let X of $){let Z=Number(X.price);if(Number.isFinite(Z))G.set(X.id,Math.round(Z))}return G}async function m3(J){try{let $=await TJ.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),G=Number($?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function EJ(J){let $=J.items.map((R)=>R.productId),G=await b3($),X=J.taxRateId!=null?await m3(J.taxRateId):0,Z=0,Y=[];for(let R of J.items){let _=R.unitPriceCents??G.get(R.productId)??0,U=Math.round(_*R.quantity);Z+=U,Y.push({productId:R.productId,quantity:R.quantity,unitPriceCents:_,lineCents:U})}let L=Math.max(0,J.discountCents??0),K=Math.max(0,Z-L),W=Math.round(K*X),F=Math.max(0,J.shippingCents??0),N=Z-L+W+F,H=J.maxDriftCents??5,M=!1,O=0;if(J.clientTotalCents!=null)O=Math.abs(N-J.clientTotalCents),M=O>H;return{subtotalCents:Z,discountCents:L,taxCents:W,shippingCents:F,totalCents:N,resolvedItems:Y,priceChanged:M,diffCents:O}}import{db as H$}from"@stacksjs/database";function qJ(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 j4(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,Z=G.max_order_qty??null;if(X!=null&&$<X)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:X};if(Z!=null&&$>Z)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:Z};return{ok:!0,productId:J,quantity:$}}async function wJ(J){for(let G of J){let X=await j4(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 fJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,Z=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let Y=await H$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[Z,Z,G]),L=typeof Y?.execute==="function"?await Y.execute():Y;return{deleted:Number(L?.changes??L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??0),cutoffAt:Z}}catch{try{let Y=await H$.selectFrom("carts").where("updated_at","<",Z).select(["id"]).limit(G).execute();if(Y.length===0)return{deleted:0,cutoffAt:Z};let L=Y.map((F)=>F.id),K=await H$.deleteFrom("carts").where("id","in",L).execute();return{deleted:Number(K?.numDeletedRows??K?.[0]?.numDeletedRows??K?.affectedRows??Y.length),cutoffAt:Z}}catch{return{deleted:0,cutoffAt:Z}}}}var C4={};z(C4,{update:()=>lJ,store:()=>bJ,recordRefund:()=>cJ,fetchPaymentStatsByMethod:()=>gJ,fetchPaymentStats:()=>IJ,fetchMonthlyPaymentTrends:()=>DJ,fetchById:()=>Y0,fetchAll:()=>hJ,destroy:()=>kJ,bulkDestroy:()=>CJ});import{db as jJ}from"@stacksjs/database";async function kJ(J){try{let $=await jJ.deleteFrom("payments").where("id","=",J).executeTakeFirst();return Q($)>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 jJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as f}from"@stacksjs/database";import{formatDate as D}from"@stacksjs/orm";async function hJ(){return await f.selectFrom("payments").selectAll().execute()}async function Y0(J){return await f.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 Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await f.selectFrom("payments").select([f.fn.count("id").as("transaction_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").executeTakeFirst(),L=await f.selectFrom("payments").select([f.fn.count("id").as("transaction_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(Z)).where("created_at","<=",D(X)).where("status","=","completed").executeTakeFirst(),K=await f.selectFrom("payments").select(f.fn.count("id").as("count")).where("created_at",">=",D(G)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(Y?.transaction_count||0),F=Number(Y?.total_revenue||0),N=W>0?F/W:0,H=Number(L?.transaction_count||0),M=Number(L?.total_revenue||0),O=H>0?M/H:0,R=W-H,_=F-M,U=N-O,m=H>0?R/H*100:W>0?100:0,t=M>0?_/M*100:F>0?100:0,$0=O>0?U/O*100:N>0?100:0,Q0=Number(K?.count||0),p=Q0>0?W/Q0*100:0;return{total_transactions:W,total_revenue:F,average_transaction:N,successful_rate:p,comparison:{transactions:{difference:R,percentage:Math.abs(m),is_increase:R>=0},revenue:{difference:_,percentage:Math.abs(t),is_increase:_>=0},average:{difference:U,percentage:Math.abs($0),is_increase:U>=0}}}}async function gJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=await f.selectFrom("payments").select([f.fn.count("id").as("total_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").executeTakeFirst(),Z=Number(X?.total_count||0),Y=await f.selectFrom("payments").select(["method",f.fn.count("id").as("count"),f.fn.sum("amount").as("revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").groupBy("method").execute(),L={};return Y.forEach((K)=>{let W=Number(K.count||0),F=Number(K.revenue||0),N=Z>0?W/Z*100:0;L[K.method]={count:W,revenue:F,percentage_of_total:N}}),L}async function DJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await f.selectFrom("payments").selectAll().where("created_at",">=",D($)).where("status","=","completed").execute(),X={};for(let Y of G){let L=Y.created_at?new Date(Y.created_at):new Date,K=L.getFullYear(),W=L.getMonth()+1,F=`${K}-${String(W).padStart(2,"0")}`;if(!X[F])X[F]={year:K,month:W,transactions:0,revenue:0};X[F].transactions++,X[F].revenue+=Number(Y.amount||0)}return Object.keys(X).sort().map((Y)=>{let L=X[Y],K=L.transactions,W=L.revenue,F=K>0?W/K:0;return{month:new Date(L.year,L.month-1,1).toLocaleString("default",{month:"short"}),year:L.year,transactions:K,revenue:W,average:F}})}var{randomUUIDv7:p3}=globalThis.Bun;import{db as vJ}from"@stacksjs/database";import{HttpError as yJ}from"@stacksjs/error-handling";import{isUniqueViolation as l3}from"@stacksjs/orm";async function bJ(J){let $=p3(),G={...J,status:J.status||"pending",currency:J.currency||"USD",uuid:$};try{return await vJ.insertInto("payments").values(G).executeTakeFirst(),await vJ.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(X){if(X instanceof yJ)throw X;if(l3(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 c3}from"@stacksjs/database";import{env as u3}from"@stacksjs/env";import{formatDate as pJ}from"@stacksjs/orm";async function lJ(J,$){if(!await Y0(J))return;try{return await mJ.updateTable("payments").set({...$,updated_at:pJ(new Date)}).where("id","=",J).execute(),await Y0(J)}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${X.message}`)}throw X}}var n3=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=c3(u3.DB_CONNECTION||"sqlite").param,Z=pJ(new Date),Y=await mJ.unsafe(`UPDATE payments
20
+ AND inventory_count + ${Z(4)} >= 0`,parameters:[G,X,$,G]}}async function zJ(J,$,G,X){let Z=b3(y3.DB_CONNECTION||"sqlite",$,G,X),Y=await J.unsafe(Z.query,Z.parameters),L=typeof Y?.execute==="function"?await Y.execute():Y;return Q(L)}var OJ=!1;function _J(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 Q$(J){try{let $=await F$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await F$.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(_J($)){if(!OJ)OJ=!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 RJ(J){if(J.idempotencyKey){let $=await Q$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await F$.transaction(async(G)=>{let X=m3(new Date),Z=BJ(),Y={...J.order,status:J.order.status||"PENDING",uuid:Z,created_at:X,updated_at:X};await G.insertInto("orders").values(Y).executeTakeFirst();let L=await G.selectFrom("orders").where("uuid","=",Z).selectAll().executeTakeFirst(),K=Number(L?.id);if(!Number.isSafeInteger(K)||K<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let W;if(J.items&&J.items.length>0){let H=J.items.map((M)=>{if(!Number.isInteger(M.productId)||M.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(M.quantity)||M.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(M.price)||M.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:K,product_id:M.productId,quantity:M.quantity,price:M.price,special_instructions:M.specialInstructions||null,created_at:X,updated_at:X}});await G.insertInto("order_items").values(H).execute(),W=await G.selectFrom("order_items").where("order_id","=",K).selectAll().execute()}let F;if(J.payment)try{let H=BJ();if(await G.insertInto("payments").values({...J.payment,order_id:K,uuid:H,created_at:X,updated_at:X}).executeTakeFirst(),F=await G.selectFrom("payments").where("uuid","=",H).selectAll().executeTakeFirst(),!F)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(H){if(AJ(H))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(H,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(J.inventory&&J.inventory.length>0)for(let H=0;H<J.inventory.length;H++){let{id:M,delta:O}=J.inventory[H];if(!Number.isFinite(O)||O===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await zJ(G,M,O,X))throw Object.assign(Error(`inventory adjust failed for product ${M}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:K,created_at:X}).execute()}catch(H){if(AJ(H))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!_J(H))throw H}let N=await G.selectFrom("orders").where("id","=",K).selectAll().executeTakeFirst();if(!N)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:N,items:W,payment:F}});if(j0($.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 Q$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}x0();import{db as P4}from"@stacksjs/database";import{formatDate as S4}from"@stacksjs/orm";x0();async function UJ(J,$){if(!await c(J))return;try{return await P4.updateTable("orders").set({...$,updated_at:S4(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 PJ(J,$){let G=await c(J);if(!G)throw Error(`Order with ID ${J} not found`);let X=G.status??"PENDING";if(!w0(X,$))throw Error(`[commerce/orders] illegal status transition ${X} \u2192 ${$}`);try{await P4.updateTable("orders").set({status:$,updated_at:S4(new Date)}).where("id","=",J).execute();let Z=await c(J);if(Z)f0($,Z);return Z}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update order status: ${Z.message}`);throw Z}}async function SJ(J,$,G){let X=await c(J);if(!X)throw Error(`Order with ID ${J} not found`);let Z={updated_at:S4(new Date)};if($!==void 0)Z.delivery_address=$;if(G!==void 0)Z.estimated_delivery_time=G;if(Object.keys(Z).length===1)return X;try{return await P4.updateTable("orders").set(Z).where("id","=",J).execute(),await c(J)}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery information: ${Y.message}`);throw Y}}x0();import{db as V0}from"@stacksjs/database";import{formatDate as N$}from"@stacksjs/orm";async function T4(J){let $=await V0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await V0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var TJ=!1;function p3(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 E4(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:N$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(p3(G)){if(!TJ)TJ=!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 q4(J){let G=J.data.object?.id;if(!G)return;await V0.transaction(async(Z)=>{if(!await E4(J.id,Z))return;let L=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let K=N$(new Date);await Z.updateTable("payments").set({status:"succeeded",updated_at:K}).where("id","=",L.id).execute();let W=await Z.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(W&&W.status==="PENDING")await Z.updateTable("orders").set({status:"PROCESSING",updated_at:K}).where("id","=",W.id).execute()});let X=await T4(G);if(X)await d(X)}async function w4(J){let $=J.data.object,G=$?.id;if(!G)return;let Z=$?.last_payment_error?.message??"payment failed";await V0.transaction(async(L)=>{if(!await E4(J.id,L))return;let W=await L.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!W)return;let F=N$(new Date);await L.updateTable("payments").set({status:"failed",failure_reason:Z,updated_at:F}).where("id","=",W.id).execute();let N=await L.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await L.updateTable("orders").set({status:"CANCELLED",updated_at:F}).where("id","=",N.id).execute()});let Y=await T4(G);if(Y)await H0(Y,Z)}async function j4(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let X=$?.amount_refunded??0;await V0.transaction(async(Y)=>{if(!await E4(J.id,Y))return;let K=await Y.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!K)return;let W=N$(new Date);await Y.updateTable("payments").set({status:"refunded",refund_amount:X,updated_at:W}).where("id","=",K.id).execute();let F=await Y.selectFrom("orders").where("id","=",K.order_id).selectAll().executeTakeFirst();if(F&&F.status!=="REFUNDED")await Y.updateTable("orders").set({status:"REFUNDED",updated_at:W}).where("id","=",F.id).execute()});let Z=await T4(G);if(Z)await M0(Z,X)}async function EJ(){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:q4,failed:w4}),G({refunded:j4}),()=>{}}import{db as qJ}from"@stacksjs/database";async function l3(J){if(J.length===0)return new Map;let $=await qJ.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),G=new Map;for(let X of $){let Z=Number(X.price);if(Number.isFinite(Z))G.set(X.id,Math.round(Z))}return G}async function c3(J){try{let $=await qJ.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),G=Number($?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function wJ(J){let $=J.items.map((R)=>R.productId),G=await l3($),X=J.taxRateId!=null?await c3(J.taxRateId):0,Z=0,Y=[];for(let R of J.items){let _=R.unitPriceCents??G.get(R.productId)??0,U=Math.round(_*R.quantity);Z+=U,Y.push({productId:R.productId,quantity:R.quantity,unitPriceCents:_,lineCents:U})}let L=Math.max(0,J.discountCents??0),K=Math.max(0,Z-L),W=Math.round(K*X),F=Math.max(0,J.shippingCents??0),N=Z-L+W+F,H=J.maxDriftCents??5,M=!1,O=0;if(J.clientTotalCents!=null)O=Math.abs(N-J.clientTotalCents),M=O>H;return{subtotalCents:Z,discountCents:L,taxCents:W,shippingCents:F,totalCents:N,resolvedItems:Y,priceChanged:M,diffCents:O}}import{db as H$}from"@stacksjs/database";function jJ(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 f4(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,Z=G.max_order_qty??null;if(X!=null&&$<X)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:X};if(Z!=null&&$>Z)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:Z};return{ok:!0,productId:J,quantity:$}}async function fJ(J){for(let G of J){let X=await f4(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 kJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,Z=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let Y=await H$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[Z,Z,G]),L=typeof Y?.execute==="function"?await Y.execute():Y;return{deleted:Number(L?.changes??L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??0),cutoffAt:Z}}catch{try{let Y=await H$.selectFrom("carts").where("updated_at","<",Z).select(["id"]).limit(G).execute();if(Y.length===0)return{deleted:0,cutoffAt:Z};let L=Y.map((F)=>F.id),K=await H$.deleteFrom("carts").where("id","in",L).execute();return{deleted:Number(K?.numDeletedRows??K?.[0]?.numDeletedRows??K?.affectedRows??Y.length),cutoffAt:Z}}catch{return{deleted:0,cutoffAt:Z}}}}var C4={};z(C4,{update:()=>uJ,store:()=>pJ,recordRefund:()=>nJ,fetchPaymentStatsByMethod:()=>vJ,fetchPaymentStats:()=>DJ,fetchMonthlyPaymentTrends:()=>yJ,fetchById:()=>Y0,fetchAll:()=>gJ,destroy:()=>IJ,bulkDestroy:()=>hJ});import{db as CJ}from"@stacksjs/database";async function IJ(J){try{let $=await CJ.deleteFrom("payments").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function hJ(J){if(!J.length)return 0;try{let $=await CJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as j}from"@stacksjs/database";import{formatDate as D}from"@stacksjs/orm";async function gJ(){return await j.selectFrom("payments").selectAll().execute()}async function Y0(J){return await j.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function DJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await j.selectFrom("payments").select([j.fn.count("id").as("transaction_count"),j.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").executeTakeFirst(),L=await j.selectFrom("payments").select([j.fn.count("id").as("transaction_count"),j.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(Z)).where("created_at","<=",D(X)).where("status","=","completed").executeTakeFirst(),K=await j.selectFrom("payments").select(j.fn.count("id").as("count")).where("created_at",">=",D(G)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(Y?.transaction_count||0),F=Number(Y?.total_revenue||0),N=W>0?F/W:0,H=Number(L?.transaction_count||0),M=Number(L?.total_revenue||0),O=H>0?M/H:0,R=W-H,_=F-M,U=N-O,m=H>0?R/H*100:W>0?100:0,t=M>0?_/M*100:F>0?100:0,$0=O>0?U/O*100:N>0?100:0,Q0=Number(K?.count||0),p=Q0>0?W/Q0*100:0;return{total_transactions:W,total_revenue:F,average_transaction:N,successful_rate:p,comparison:{transactions:{difference:R,percentage:Math.abs(m),is_increase:R>=0},revenue:{difference:_,percentage:Math.abs(t),is_increase:_>=0},average:{difference:U,percentage:Math.abs($0),is_increase:U>=0}}}}async function vJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=await j.selectFrom("payments").select([j.fn.count("id").as("total_count"),j.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").executeTakeFirst(),Z=Number(X?.total_count||0),Y=await j.selectFrom("payments").select(["method",j.fn.count("id").as("count"),j.fn.sum("amount").as("revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").groupBy("method").execute(),L={};return Y.forEach((K)=>{let W=Number(K.count||0),F=Number(K.revenue||0),N=Z>0?W/Z*100:0;L[K.method]={count:W,revenue:F,percentage_of_total:N}}),L}async function yJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await j.selectFrom("payments").selectAll().where("created_at",">=",D($)).where("status","=","completed").execute(),X={};for(let Y of G){let L=Y.created_at?new Date(Y.created_at):new Date,K=L.getFullYear(),W=L.getMonth()+1,F=`${K}-${String(W).padStart(2,"0")}`;if(!X[F])X[F]={year:K,month:W,transactions:0,revenue:0};X[F].transactions++,X[F].revenue+=Number(Y.amount||0)}return Object.keys(X).sort().map((Y)=>{let L=X[Y],K=L.transactions,W=L.revenue,F=K>0?W/K:0;return{month:new Date(L.year,L.month-1,1).toLocaleString("default",{month:"short"}),year:L.year,transactions:K,revenue:W,average:F}})}var{randomUUIDv7:u3}=globalThis.Bun;import{db as bJ}from"@stacksjs/database";import{HttpError as mJ}from"@stacksjs/error-handling";import{isUniqueViolation as n3}from"@stacksjs/orm";async function pJ(J){let $=u3(),G={...J,status:J.status||"pending",currency:J.currency||"USD",uuid:$};try{return await bJ.insertInto("payments").values(G).executeTakeFirst(),await bJ.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(X){if(X instanceof mJ)throw X;if(n3(X))throw new mJ(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 lJ,sqlHelpers as i3}from"@stacksjs/database";import{env as o3}from"@stacksjs/env";import{formatDate as cJ}from"@stacksjs/orm";async function uJ(J,$){if(!await Y0(J))return;try{return await lJ.updateTable("payments").set({...$,updated_at:cJ(new Date)}).where("id","=",J).execute(),await Y0(J)}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${X.message}`)}throw X}}var s3=new Set(["completed","succeeded","partiallyRefunded"]);async function nJ(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=i3(o3.DB_CONNECTION||"sqlite").param,Z=cJ(new Date),Y=await lJ.unsafe(`UPDATE payments
21
21
  SET refund_amount = COALESCE(refund_amount, 0) + ${X(1)},
22
22
  status = CASE WHEN COALESCE(refund_amount, 0) + ${X(2)} = amount
23
23
  THEN 'refunded' ELSE 'partiallyRefunded' END,
24
24
  updated_at = ${X(3)}
25
25
  WHERE id = ${X(4)}
26
26
  AND status IN ('completed', 'succeeded', 'partiallyRefunded')
27
- AND COALESCE(refund_amount, 0) + ${X(5)} <= amount`,[$,$,Z,J,$]),L=typeof Y?.execute==="function"?await Y.execute():Y;if(Number(L?.numUpdatedRows??L?.[0]?.numUpdatedRows??L?.numAffectedRows??L?.affectedRows??L?.[0]?.affectedRows??L?.changes??0)>0){let M=await Y0(J);if(M)return M;throw Error(`Payment with ID ${J} disappeared during refund`)}let W=await Y0(J);if(!W)throw Error(`Payment with ID ${J} not found`);let F=String(W.status||"");if(!n3.has(F))throw Error(`Payment status ${F||"unknown"} cannot be refunded`);let N=W,H=Number(W.amount||0)-Number(N.refundAmount??N.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${H} minor units`)}var b4={};z(b4,{variants:()=>U$,units:()=>R$,reviews:()=>A$,manufacturers:()=>B$,items:()=>z$,default:()=>XZ,categories:()=>V$});var V$={};z(V$,{updateParent:()=>W6,updateDisplayOrder:()=>L6,updateActiveStatus:()=>K6,update:()=>Y6,store:()=>I4,removeChildCategories:()=>$6,remove:()=>rJ,findOrCreateByName:()=>Z6,fetchStats:()=>dJ,fetchRootCategories:()=>iJ,fetchChildCategories:()=>oJ,fetchCategoryTree:()=>eJ,fetchByName:()=>uJ,fetchById:()=>j,fetchByDisplayOrder:()=>sJ,fetchAll:()=>h4,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 k0}from"@stacksjs/orm";async function h4(){return await S.selectFrom("categories").selectAll().execute()}async function j(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(),Z=new Date;Z.setDate(Z.getDate()-30);let Y=k0(Z),L=await S.selectFrom("categories").where("created_at",">=",Y).selectAll().limit(5).execute(),K=await S.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",S.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number($?.count||0),root_categories:Number(G?.count||0),child_categories:Number(J?.count||0)-Number(G?.count||0),with_images:Number(X?.count||0),recently_added:L,top_parent_categories:K.map((W)=>({id:String(W.parent_category_id||""),name:String(W.parent_name||""),child_count:Number(W.child_count)}))}}async function aJ(J=30){let $=new Date,G=k0($),X=new Date;X.setDate($.getDate()-J);let Z=k0(X),Y=new Date(X);Y.setDate(Y.getDate()-1);let L=k0(Y),K=new Date(Y);K.setDate(Y.getDate()-J);let W=k0(K),F=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",G).executeTakeFirst(),N=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",W).where("created_at","<=",L).executeTakeFirst(),H=Number(F?.count||0),M=Number(N?.count||0),O=H-M,R=M!==0?O/M*100:H>0?100:0;return{current_period:H,previous_period:M,difference:O,percentage_change:R,days_range:J}}async function eJ(){let J=await h4(),$=new Map;J.forEach((Z)=>{$.set(Z.id,{...Z,children:[]})});let G=[];J.forEach((Z)=>{let Y=$.get(Z.id);if(Z.parent_category_id){let L=$.get(Z.parent_category_id);if(L)L.children.push(Y)}else G.push(Y)}),G.sort((Z,Y)=>Z.display_order-Y.display_order);let X=(Z)=>{Z.sort((Y,L)=>Y.display_order-L.display_order),Z.forEach((Y)=>{if(Y.children.length>0)X(Y.children)})};return X(G),G}async function rJ(J){let $=await z0.deleteFrom("categories").where("id","=",J).executeTakeFirst();return Q($)>0}async function tJ(J){if(!J.length)return 0;let $=await z0.deleteFrom("categories").where("id","in",J).executeTakeFirst();return Q($)}async function $6(J){let $=await z0.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return Q($)}async function J6(J){if(!await j(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:i3}=globalThis.Bun;import{db as X6}from"@stacksjs/database";import{HttpError as M$}from"@stacksjs/error-handling";import{isUniqueViolation as o3}from"@stacksjs/orm";import{slug as s3}from"@stacksjs/strings";async function I4(J){try{let $=J.parent_category_id?Number(J.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new M$(422,"Parent category ID must be a positive integer");if($&&!await j($))throw new M$(422,`Parent category with ID ${J.parent_category_id} not found`);let G={...J,uuid:i3(),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 M$)throw $;if(o3($))throw new M$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function Z6(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:s3(J.name),is_active:J.is_active??!0,display_order:0};return await I4(G)}import{db as C0}from"@stacksjs/database";import{HttpError as B0}from"@stacksjs/error-handling";import{formatDate as x$,isUniqueViolation as d3}from"@stacksjs/orm";async function Y6(J,$){if(!await j(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 j(X))throw new B0(422,`Parent category with ID ${$.parent_category_id} not found`);if(X&&await F6(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}:{},Z=await C0.updateTable("categories").set({...$,...X,updated_at:x$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(X){if(X instanceof B0)throw X;if(d3(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 L6(J,$){if(!await j(J))throw Error(`Category with ID ${J} not found`);try{return await C0.updateTable("categories").set({display_order:$,updated_at:x$(new Date)}).where("id","=",J).execute(),await j(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category display order: ${X.message}`);throw X}}async function K6(J,$){if(!await j(J))throw Error(`Category with ID ${J} not found`);try{return await C0.updateTable("categories").set({is_active:$,updated_at:x$(new Date)}).where("id","=",J).execute(),await j(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function W6(J,$){if(!await j(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 j(X))throw Error(`Parent category with ID ${$} not found`);if(await F6(J,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let X={updated_at:x$(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 j(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category parent: ${X.message}`);throw X}}async function F6(J,$){let G=Number($),X=new Set;while(G){if(X.has(G))return!0;if(G===J)return!0;X.add(G);let Z=await j(G),Y=Z?.parent_category_id??Z?.parentCategoryId;if(!Z||!Y)return!1;G=Number(Y)}return!1}var z$={};z(z$,{updateInventory:()=>R6,updateAvailability:()=>_6,update:()=>O6,store:()=>B6,fetchTopProducts:()=>x6,fetchById:()=>u,fetchAll:()=>M6,destroy:()=>N6,bulkStore:()=>A6,bulkDestroy:()=>H6});import{db as Q6}from"@stacksjs/database";async function N6(J){try{let $=await Q6.deleteFrom("products").where("id","=",J).executeTakeFirst();return Q($)>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 Q6.deleteFrom("products").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as a,sql as a3}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 M6(){let J=await a.selectFrom("products").selectAll().execute(),$=J.map((F)=>F.manufacturer_id).filter((F)=>F!==null&&F!==void 0),G=J.map((F)=>F.category_id).filter((F)=>F!==null&&F!==void 0),X=a.selectFrom("manufacturers"),Z=a.selectFrom("categories");if($.length>0)X=X.where("id","in",$);if(G.length>0)Z=Z.where("id","in",G);let Y=await X.selectAll().execute(),L=await Z.selectAll().execute(),K=Y.reduce((F,N)=>{return F[N.id]=N,F},{}),W=L.reduce((F,N)=>{return F[N.id]=N,F},{});return J.map((F)=>({...F,manufacturer:F.manufacturer_id?K[F.manufacturer_id]:null,category:F.category_id?W[F.category_id]:null}))}async function x6(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"),a3`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:V6}=globalThis.Bun;import{db as z6}from"@stacksjs/database";async function B6(J){try{let $={...J,uuid:V6()},G=await z6.insertInto("products").values($).executeTakeFirst();if(!G)throw Error("Failed to create product item");let X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),Z=await u(X);if(!Z)throw Error("Failed to create product item");return Z}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function A6(J){if(!J.length)return 0;let $=0;try{return await z6.transaction().execute(async(G)=>{for(let X of J){let Z={...X,uuid:V6()};await G.insertInto("products").values(Z).execute(),$++}}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as g4}from"@stacksjs/database";import{formatDate as D4}from"@stacksjs/orm";async function O6(J,$){try{if(!J)throw Error("Product item ID is required for update");let G=await g4.updateTable("products").set({...$,updated_at:D4(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 _6(J,$){if(!await u(J))throw Error(`Product item with ID ${J} not found`);try{return await g4.updateTable("products").set({is_available:$,updated_at:D4(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:D4(new Date)};if($!==void 0)X.inventory_count=$;if(Object.keys(X).length===1)return G;try{return await g4.updateTable("products").set(X).where("id","=",J).execute(),await u(J)}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update inventory information: ${Z.message}`);throw Z}}var B$={};z(B$,{updateFeaturedStatus:()=>y6,updateByUuid:()=>b6,update:()=>v6,store:()=>I6,fetchWithProductCount:()=>j6,fetchFeatured:()=>w6,fetchByUuid:()=>q6,fetchById:()=>E6,fetchByCountry:()=>f6,fetchAll:()=>T6,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 Q($)>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 Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as n}from"@stacksjs/database";function T6(){return n.selectFrom("manufacturers").selectAll().execute()}async function E6(J){return await n.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function q6(J){return await n.selectFrom("manufacturers").where("uuid","=",J).selectAll().executeTakeFirst()}async function w6(J=10){return await n.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(J).execute()}async function f6(J,$={}){let G=$.page||1,X=$.limit||2,Z=await n.selectFrom("manufacturers").select(n.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),Y=Number(Z?.total||0),L=await n.selectFrom("manufacturers").selectAll().where("country","=",J).limit(X).offset((G-1)*X).execute(),K=Math.ceil(Y/X);return{data:L,paging:{total_records:Y,page:G,total_pages:K},next_cursor:G<K?G+1:null}}async function j6(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 k6}from"@stacksjs/error-handling";import{isUniqueViolation as e3}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 k6)throw $;if(e3($))throw new k6(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 v4}from"@stacksjs/database";import{HttpError as D6}from"@stacksjs/error-handling";import{formatDate as y4,isUniqueViolation as r3}from"@stacksjs/orm";async function v6(J,$){try{if(!J)throw Error("Manufacturer ID is required for update");let G=await v4.updateTable("manufacturers").set({...$,updated_at:y4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof D6)throw G;if(r3(G))throw new D6(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 v4.updateTable("manufacturers").set({featured:$,updated_at:y4(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 v4.updateTable("manufacturers").set({...$,updated_at:y4(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:()=>Z2,update:()=>X2,store:()=>$2,fetchStatsByProductIds:()=>t6,fetchStats:()=>r6,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 Q($)>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 Q($)}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()}import{db as d6}from"@stacksjs/database";function a6(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function e6(J){let $=a6();$.total=J.length;let G=0;for(let X of J){if(X.rating===null||X.rating===void 0){$.commentsOnly++;continue}let Z=Number(X.rating);if(Number.isNaN(Z)){$.commentsOnly++;continue}$.rated++,G+=Z;let Y=Math.min(5,Math.max(1,Math.round(Z)));$.distribution[Y]++}if($.rated>0)$.average=Math.round(G/$.rated*10)/10;return $}async function r6(J){let $=await d6.selectFrom("reviews").select(["rating"]).where("product_id","=",J).where("is_approved","=",!0).execute();return e6($)}async function t6(J){let $=new Map;for(let Z of J)$.set(Z,a6());if(J.length===0)return $;let G=await d6.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",J).where("is_approved","=",!0).execute(),X=new Map;for(let Z of G){let Y=X.get(Z.product_id);if(Y)Y.push({rating:Z.rating});else X.set(Z.product_id,[{rating:Z.rating}])}for(let[Z,Y]of X)$.set(Z,e6(Y));return $}var{randomUUIDv7:t3}=globalThis.Bun;import{db as $Z}from"@stacksjs/database";function JZ(J){let $=J.rating!==void 0&&J.rating!==null,G=typeof J.content==="string"&&J.content.trim().length>0,X=typeof J.title==="string"&&J.title.trim().length>0;return!$&&!G&&!X}async function $2(J){try{if(JZ(J))throw Error("A review needs a rating or something written: both were empty");let $={...J,uuid:t3(),rating:J.rating??null,is_verified_purchase:J.is_verified_purchase??!1,is_approved:J.is_approved??!1,helpful_votes:J.helpful_votes??0,unhelpful_votes:J.unhelpful_votes??0,is_featured:J.is_featured??!1},G=await $Z.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 J2}from"@stacksjs/database";import{formatDate as G2}from"@stacksjs/orm";async function X2(J,$){try{if(!J)throw Error("Review ID is required for update");let G=await J2.updateTable("reviews").set({...$,updated_at:G2(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 Z2(J,$,G=!0){try{let X=$==="helpful"?"helpful_votes":"unhelpful_votes",Z=G?`COALESCE("${X}", 0) + 1`:`MAX(COALESCE("${X}", 0) - 1, 0)`,Y=await J2.unsafe(`UPDATE "reviews" SET "${X}" = ${Z}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[G2(new Date),J]).execute(),L=Array.isArray(Y)?Y[0]:Y;if(!L)throw Error("Failed to update review votes");return L}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var R$={};z(R$,{updateDefaultStatus:()=>A2,update:()=>z2,store:()=>H2,getDefaultUnit:()=>V2,formatUnitOptions:()=>x2,fetchById:()=>F2,fetchAll:()=>Q2,destroy:()=>L2,bulkUpdate:()=>B2,bulkStore:()=>M2,bulkDestroy:()=>K2});import{db as Y2}from"@stacksjs/database";async function L2(J){try{let $=await Y2.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function K2(J){if(!J.length)return 0;try{let $=await Y2.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as W2}from"@stacksjs/database";async function F2(J){return await W2.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function Q2(){return await W2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:N2}=globalThis.Bun;import{db as h0}from"@stacksjs/database";async function H2(J){try{return await h0.transaction(async($)=>{let G={...J,uuid:N2()},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 M2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:N2()},Z=await h0.insertInto("product_units").values(X).returningAll().executeTakeFirst();if(X.is_default&&X.type&&Z)await h0.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",Z.id).execute();$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function x2(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 V2(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 O$}from"@stacksjs/database";import{formatDate as _$}from"@stacksjs/orm";async function z2(J,$){try{if(!J)throw Error("Product unit ID is required for update");return await O$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",J).executeTakeFirst();if(!X)return;let Z=$.type??X.type;if(($.is_default??Boolean(X.is_default))&&Z)await G.updateTable("product_units").set({is_default:!1,updated_at:_$(new Date)}).where("type","=",Z).where("id","!=",J).execute();let L=await G.updateTable("product_units").set({...$,updated_at:_$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!L)return;return L})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function B2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X=G;if(!X.id)continue;let Z=X.data&&typeof X.data==="object"?X.data:{...X};delete Z.id;let Y=await O$.updateTable("product_units").set({...Z,updated_at:_$(new Date)}).where("id","=",X.id).executeTakeFirst(),L=Z;if(L.is_default===!0&&L.type)await O$.updateTable("product_units").set({is_default:!1}).where("type","=",L.type).where("id","!=",X.id).execute();if(Number(Y.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function A2(J,$){try{return await O$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!X)return!1;let Z=_$(new Date);if($&&X.type)await G.updateTable("product_units").set({is_default:!1,updated_at:Z}).where("type","=",X.type).where("id","!=",J).execute();return await G.updateTable("product_units").set({is_default:$,updated_at:Z}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var U$={};z(U$,{update:()=>h2,store:()=>q2,generateVariantCombinations:()=>j2,formatVariantOptions:()=>f2,fetchById:()=>P2,fetchAll:()=>S2,destroy:()=>_2,bulkUpdate:()=>I2,bulkStore:()=>w2,bulkDestroy:()=>R2});import{db as O2}from"@stacksjs/database";async function _2(J){try{let $=await O2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function R2(J){if(!J.length)return 0;try{let $=await O2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as U2}from"@stacksjs/database";async function P2(J){return await U2.selectFrom("product_variants").where("id","=",J).selectAll().executeTakeFirst()}async function S2(){return await U2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:T2}=globalThis.Bun;import{db as E2}from"@stacksjs/database";async function q2(J){try{let $={...J,uuid:T2()},G=await E2.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 w2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:T2()};await E2.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 f2(J){if(!J||!J.length)return JSON.stringify([]);let $=J.map((G)=>G.trim()).filter(Boolean);return JSON.stringify($)}function j2(J){let $=Object.keys(J);if(!$.length)return[];function G(X,Z){if(X===$.length)return[Z];let Y=$[X],L=J[Y]??[],K=[];for(let W of L){let F={...Z,[Y]:W};K.push(...G(X+1,F))}return K}return G(0,{})}import{db as k2}from"@stacksjs/database";import{formatDate as C2}from"@stacksjs/orm";async function h2(J,$){try{let G=await k2.updateTable("product_variants").set({...$,updated_at:C2(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 I2(J){if(!J.length)return 0;let $=0;try{for(let G of J){if(!G.id)continue;let X=await k2.updateTable("product_variants").set({...G,updated_at:C2(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 GZ={categories:V$,items:z$,manufacturers:B$,reviews:A$,units:R$,variants:U$},XZ=GZ;var n4={};z(n4,{updateStatus:()=>s2,updatePrintJob:()=>d2,update:()=>o2,store:()=>n2,fetchSuccessRate:()=>m2,fetchPrintsPerHour:()=>c2,fetchPrintTimeStats:()=>l2,fetchPrintJobStats:()=>b2,fetchPageStats:()=>p2,fetchById:()=>O0,fetchAll:()=>y2,destroy:()=>D2,bulkStore:()=>i2,bulkDestroy:()=>v2});import{db as g2}from"@stacksjs/database";async function D2(J){try{let $=await g2.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function v2(J){if(!J.length)return 0;try{let $=await g2.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as m4}from"@stacksjs/database";import{formatDate as ZZ}from"@stacksjs/orm";function b(J){return ZZ(J)}function YZ(J){if(J instanceof Date)return Number.isNaN(J.getTime())?null:J;if(typeof J==="number"){let X=new Date(J<=2147483647?J*1000:J);return Number.isNaN(X.getTime())?null:X}let $=String(J||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let X=new Date(Number($)*1000);return Number.isNaN(X.getTime())?null:X}let G=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function O0(J){return await m4.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function y2(){return await m4.selectFrom("receipts").selectAll().execute()}async function b2(J,$){let G=b(J),X=b($),Z=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning,averageSize:Math.round(Z.averageSize),averagePages:Math.round(Z.averagePages),averageDuration:Math.round(Z.averageDuration)}}async function m2(J,$){let G=b(J),X=b($),Z=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(L)=>L.where("timestamp",">=",G).where("timestamp","<=",X));return{successRate:Z.total>0?Math.round(Z.success/Z.total*100):0,total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning}}async function p2(J,$){let G=b(J),X=b($),Z=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{totalPages:Z.totalPages,averagePagesPerReceipt:Math.round(Z.averagePagesPerReceipt),totalReceipts:Z.totalReceipts}}async function l2(J,$){let G=b(J),X=b($),Z=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{averageDuration:Math.round(Z.averageDuration),minDuration:Z.minDuration,maxDuration:Z.maxDuration,totalJobs:Z.totalJobs}}async function c2(J,$){let G=typeof J==="number"?J:J.getTime(),X=typeof $==="number"?$:$.getTime(),Z=b(J),Y=b($),L=await m4.selectFrom("receipts").where("timestamp",">=",Z).where("timestamp","<=",Y).selectAll().execute(),K=L.length,W=Math.ceil((X-G)/3600000),F=W>0?Math.round(K/W):0,N=Array.from({length:24},(H,M)=>({hour:M,count:0}));return L.forEach((H)=>{let M=YZ(H.timestamp);if(!M)return;N[M.getHours()].count++}),{totalPrints:K,totalHours:W,printsPerHour:F,hourlyBreakdown:N}}var{randomUUIDv7:u2}=globalThis.Bun;import{db as l4}from"@stacksjs/database";import{formatDate as p4}from"@stacksjs/orm";function I0(J){try{if(typeof J==="number")return p4(J<=2147483647?J*1000:J);if(typeof J==="string"&&/^\d{10}$/.test(J))return p4(Number(J)*1000);return p4(J)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function n2(J){try{let $=u2(),G={...J,timestamp:I0(J.timestamp),uuid:$};await l4.insertInto("receipts").values(G).executeTakeFirst();let X=await l4.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 i2(J){if(!J.length)return 0;try{let $=J.map((X)=>({...X,timestamp:I0(X.timestamp),uuid:u2()})),G=await l4.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 c4}from"@stacksjs/database";import{formatDate as u4}from"@stacksjs/orm";async function o2(J,$){try{if(!J)throw Error("Receipt ID is required for update");let G={...$,...$.timestamp===void 0?{}:{timestamp:I0($.timestamp)},updated_at:u4(new Date)};await c4.updateTable("receipts").set(G).where("id","=",J).execute();let X=await O0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function s2(J,$){try{await c4.updateTable("receipts").set({status:$,updated_at:u4(new Date)}).where("id","=",J).execute();let G=await O0(J);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function d2(J,$,G,X){try{let Z={updated_at:u4(new Date)};if($!==void 0)Z.size=$;if(G!==void 0)Z.pages=G;if(X!==void 0)Z.duration=X;await c4.updateTable("receipts").set(Z).where("id","=",J).execute();let Y=await O0(J);if(!Y)throw Error("Failed to update receipt job information");return Y}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update receipt job information: ${Z.message}`);throw Z}}var x1={};z(x1,{zones:()=>L4,tracking:()=>G4,routes:()=>w$,rates:()=>s$,methods:()=>c$,licenses:()=>b$,geocoding:()=>D$,drivers:()=>C$,digital:()=>j$,default:()=>fZ});var w$={};z(w$,{validateDeliveryRouteWrite:()=>_0,updateStops:()=>YG,updateMetrics:()=>LG,updateLastActive:()=>XG,update:()=>ZG,store:()=>GG,fetchById:()=>S$,fetchByDriver:()=>JG,fetchAll:()=>t2,fetchActive:()=>$G,destroy:()=>e2,bulkDestroy:()=>r2,DeliveryRouteInputError:()=>h});import{db as a2}from"@stacksjs/database";async function e2(J){try{let $=await a2.deleteFrom("delivery_routes").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function r2(J){if(!J.length)return 0;try{let $=await a2.deleteFrom("delivery_routes").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as P$}from"@stacksjs/database";async function S$(J){return await P$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function t2(){return await P$.selectFrom("delivery_routes").selectAll().execute()}async function $G(){return await P$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function JG(J){return await P$.selectFrom("delivery_routes").where("driver","=",J).selectAll().execute()}var{randomUUIDv7:WZ}=globalThis.Bun;import{db as i4}from"@stacksjs/database";function L0(J,$){let G={};for(let[X,Z]of Object.entries($))for(let Y of Z){if(!Object.prototype.hasOwnProperty.call(J,Y)||J[Y]===void 0)continue;G[X]=J[Y];break}return G}function g0(J){return L0(J,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function i(J){return L0(J,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function D0(J){return L0(J,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function v0(J){return L0(J,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function y0(J){return L0(J,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function b0(J){return L0(J,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function T$(J){return L0(J,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as LZ}from"@stacksjs/database";class h extends TypeError{constructor(J){super(J);this.name="DeliveryRouteInputError"}}function E$(J,$,G){return Number(J[G]??$?.[G])}function KZ(J,$){let G=J.last_active??$?.last_active;if(G===void 0||G===null)return Date.now();if(G instanceof Date)return G.getTime();if(typeof G==="number")return G;if(typeof G==="string"&&/^\d{10,13}$/.test(G))return Number(G);return Number.NaN}async function _0(J,$){let G=E$(J,$,"driver_id"),X=E$(J,$,"stops"),Z=E$(J,$,"delivery_time"),Y=E$(J,$,"total_distance"),L=KZ(J,$);if(!Number.isSafeInteger(G)||G<1)throw new h("Driver must be a positive integer.");if(!Number.isSafeInteger(X)||X<0)throw new h("Stops must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new h("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(Y)||Y<0)throw new h("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(L)||L<0)throw new h("Last active must be a valid Unix timestamp.");let K=await LZ.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!K)throw new h(`Driver ${G} was not found.`);return{...J,driver_id:Number(K.id),driver:K.name,vehicle:K.vehicle_number,last_active:L}}async function GG(J){try{let $=WZ(),G=T$(J),Z={...await _0(G),uuid:$};await i4.insertInto("delivery_routes").values(Z).executeTakeFirst();let Y=await i4.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!Y)throw Error("Failed to create delivery route");return Y}catch($){if($ instanceof h)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function XG(J){try{await i4.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 q$}from"@stacksjs/database";import{formatDate as o4}from"@stacksjs/orm";async function ZG(J,$){try{if(!J)throw Error("Delivery route ID is required for update");let G=await q$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=T$($),Z=await _0(X,G),Y=await q$.updateTable("delivery_routes").set({...Z,updated_at:o4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof h)throw G;if(G instanceof Error)throw TypeError(`Failed to update delivery route: ${G.message}`);throw G}}async function YG(J,$){try{let G=await q$.updateTable("delivery_routes").set({stops:$,updated_at:o4(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 LG(J,$,G){try{let X={updated_at:o4(new Date)};if($!==void 0)X.delivery_time=$;if(G!==void 0)X.total_distance=G;let Z=await q$.updateTable("delivery_routes").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update delivery metrics");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery metrics: ${X.message}`);throw X}}var j$={};z(j$,{updateStatus:()=>AG,updateDeliverySettings:()=>OG,update:()=>BG,store:()=>VG,softDelete:()=>WG,fetchById:()=>HG,fetchAll:()=>MG,destroy:()=>KG,bulkStore:()=>zG,bulkSoftDelete:()=>QG,bulkDestroy:()=>FG});import{db as f$}from"@stacksjs/database";async function KG(J){try{let $=await f$.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function WG(J){try{let $=await f$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function FG(J){if(!J.length)return 0;try{let $=await f$.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function QG(J){if(!J.length)return 0;try{let $=await f$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as NG}from"@stacksjs/database";async function HG(J){return await NG.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function MG(){return await NG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:xG}=globalThis.Bun;import{db as s4}from"@stacksjs/database";async function VG(J){try{let $=xG(),G={...v0(J),uuid:$};await s4.insertInto("digital_deliveries").values(G).executeTakeFirst();let X=await s4.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 zG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...v0(X),uuid:xG()})),G=await s4.insertInto("digital_deliveries").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as d4}from"@stacksjs/database";import{formatDate as a4}from"@stacksjs/orm";async function BG(J,$){try{if(!J)throw Error("Digital delivery ID is required for update");let G=await d4.updateTable("digital_deliveries").set({...v0($),updated_at:a4(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 AG(J,$){try{let G=await d4.updateTable("digital_deliveries").set({status:$,updated_at:a4(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 OG(J,$,G,X,Z){try{let Y={updated_at:a4(new Date)};if($!==void 0)Y.download_limit=$;if(G!==void 0)Y.expiry_days=G;if(X!==void 0)Y.requires_login=X;if(Z!==void 0)Y.automatic_delivery=Z;let L=await d4.updateTable("digital_deliveries").set(Y).where("id","=",J).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update delivery settings");return L}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery settings: ${Y.message}`);throw Y}}var C$={};z(C$,{updateStatus:()=>fG,updateContact:()=>jG,update:()=>wG,store:()=>EG,fetchById:()=>k$,fetchAll:()=>RG,destroy:()=>PG,bulkStore:()=>qG,bulkDestroy:()=>SG});import{db as UG}from"@stacksjs/database";import{db as _G}from"@stacksjs/database";async function k$(J){return await _G.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function RG(){return await _G.selectFrom("drivers").selectAll().execute()}async function PG(J){try{let $=await UG.deleteFrom("drivers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function SG(J){if(!J.length)return 0;let $=0;try{return await UG.transaction().execute(async(G)=>{for(let X of J)if(await k$(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:TG}=globalThis.Bun;import{db as e4}from"@stacksjs/database";async function EG(J){try{let $=TG(),G={...b0(J),uuid:$};await e4.insertInto("drivers").values(G).executeTakeFirst();let X=await e4.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created driver");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function qG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...b0(X),uuid:TG()})),G=await e4.insertInto("drivers").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as r4}from"@stacksjs/database";import{formatDate as t4}from"@stacksjs/orm";async function wG(J,$){try{if(!J)throw Error("Driver ID is required for update");let G=await r4.updateTable("drivers").set({...b0($),updated_at:t4(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 fG(J,$){try{let G=await r4.updateTable("drivers").set({status:$,updated_at:t4(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 jG(J,$){try{let G={updated_at:t4(new Date)};if($!==void 0)G.phone=$;let X=await r4.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 D$={};z(D$,{setGeocodingDriver:()=>HZ,nominatimDriver:()=>g$,geocodingDriver:()=>DG,geocode:()=>MZ,formatQuery:()=>R0,checkCoverage:()=>xZ,PRECISION_RANK:()=>p0});var K0=(J)=>J*Math.PI/180;function e(J,$){let G=K0($.latitude-J.latitude),X=K0($.longitude-J.longitude),Z=K0(J.latitude),Y=K0($.latitude),L=Math.sin(G/2)**2+Math.sin(X/2)**2*Math.cos(Z)*Math.cos(Y);return 12742017.6*Math.asin(Math.sqrt(L))}function h$(J,$){let G=K0(J.latitude),X=K0($.latitude),Z=K0($.longitude-J.longitude),Y=Math.sin(Z)*Math.cos(X),L=Math.cos(G)*Math.sin(X)-Math.sin(G)*Math.cos(X)*Math.cos(Z);return(Math.atan2(Y,L)*180/Math.PI+360)%360}function I$(J,$,G={}){let X=G.detourFactor??1.35,Z=G.minimumSeconds??30;if(!Number.isFinite($)||$<=0.5)return null;let Y=J*X/$;return Math.max(Z,Math.round(Y))}function kG(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 FZ="https://nominatim.openstreetmap.org/search",CG=1000,hG=0,IG=Promise.resolve();async function QZ(J){let $=IG.then(async()=>{let G=Date.now()-hG;if(G<CG)await Bun.sleep(CG-G);return hG=Date.now(),J()});return IG=$.then(()=>{return},()=>{return}),$}function NZ(J){let $=J.address??{},G=String(J.addresstype??""),X=String(J.type??""),Z=String(J.category??J.class??"");if($.house_number||X==="house"||X==="building"||G==="building")return"rooftop";if($.road||Z==="highway"||G==="road")return"street";if(G==="postcode"||$.postcode&&!$.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(G))return"locality";return"unknown"}function g$(J={}){let $=J.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,G=J.endpoint??FZ;return{name:"nominatim",async geocode(X){let Z=R0(X);if(!Z)return null;let Y=new URL(G);if(Y.searchParams.set("q",Z),Y.searchParams.set("format","jsonv2"),Y.searchParams.set("limit","1"),Y.searchParams.set("addressdetails","1"),X.country)Y.searchParams.set("countrycodes",X.country.toLowerCase());let L=await QZ(()=>fetch(Y,{headers:{"user-agent":$,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!L.ok)throw Error(`Nominatim responded ${L.status}`);let W=(await L.json())?.[0];if(!W)return null;let F=Number(W.lat),N=Number(W.lon);if(!Number.isFinite(F)||!Number.isFinite(N))return null;let H=NZ(W);return{latitude:F,longitude:N,formatted:String(W.display_name??Z),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[H],precision:H,provider:"nominatim"}}}}var gG=null;function HZ(J){gG=J}function DG(){return gG??g$()}async function MZ(J,$={}){let G=$.driver??DG(),X=$.minimumPrecision??"street",Z=`geocode:${G.name}:${R0(J).toLowerCase()}`,Y=await VZ(Z);if(Y!==void 0)return Y;let L=await G.geocode(J),K=L&&p0[L.precision]>=p0[X]?L:null;return await zZ(Z,K,K?$.cacheSeconds??2592000:600),K}function xZ(J,$,G){if($.length===0)return null;let X=$[0],Z=e(J,X);for(let Y of $.slice(1)){let L=e(J,Y);if(L<Z)Z=L,X=Y}return{covered:Z<=G,distanceMeters:Math.round(Z),nearest:X}}async function VZ(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 zZ(J,$,G){try{let Z=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!Z)return;await Z.set(J,$===null?"null":JSON.stringify($),G)}catch{}}var b$={};z(b$,{validateLicenseKeyWrite:()=>W0,updateStatus:()=>aG,updateExpiration:()=>eG,update:()=>dG,store:()=>oG,softDelete:()=>yG,fetchById:()=>lG,fetchAll:()=>cG,destroy:()=>vG,bulkStore:()=>sG,bulkSoftDelete:()=>mG,bulkDestroy:()=>bG,LicenseKeyInputError:()=>E});import{db as v$}from"@stacksjs/database";async function vG(J){try{let $=await v$.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function yG(J){try{let $=await v$.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function bG(J){if(!J.length)return 0;try{let $=await v$.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function mG(J){if(!J.length)return 0;try{let $=await v$.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as pG}from"@stacksjs/database";async function lG(J){return await pG.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst()}async function cG(){return await pG.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:iG}=globalThis.Bun;import{db as G1}from"@stacksjs/database";import{db as $1}from"@stacksjs/database";var uG=["Standard License","Premium License","Enterprise License"],nG=["active","inactive","unassigned"];class E extends TypeError{constructor(J){super(J);this.name="LicenseKeyInputError"}}function l0(J,$,G){return J[G]!==void 0?J[G]:$?.[G]}function J1(J,$,G,X){let Z=l0(J,$,G);if(Z===void 0||Z===null||Z==="")return null;let Y=Number(Z);if(!Number.isSafeInteger(Y)||Y<1)throw new E(`${X} must be a positive integer or null.`);return Y}function BZ(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(l0(J,$,"key")||"").trim().toUpperCase(),X=String(l0(J,$,"template")||""),Z=String(l0(J,$,"status")||""),Y=BZ(l0(J,$,"expiry_date")),L=J1(J,$,"customer_id","Customer"),K=J1(J,$,"product_id","Product"),W=J1(J,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new E("License key must use five groups of four uppercase letters or numbers.");if(!uG.includes(X))throw new E(`Template must be one of: ${uG.join(", ")}.`);if(!nG.includes(Z))throw new E(`Status must be one of: ${nG.join(", ")}.`);if(!Number.isSafeInteger(Y)||Y<0||Y>2147483647)throw new E("Expiry date must be a Unix timestamp between 1970 and 2038.");let[F,N,H]=await Promise.all([L?$1.selectFrom("customers").where("id","=",L).select("id").executeTakeFirst():null,K?$1.selectFrom("products").where("id","=",K).select("id").executeTakeFirst():null,W?$1.selectFrom("orders").where("id","=",W).select(["id","customer_id"]).executeTakeFirst():null]);if(L&&!F)throw new E(`Customer ${L} was not found.`);if(K&&!N)throw new E(`Product ${K} was not found.`);if(W&&!H)throw new E(`Order ${W} was not found.`);if(L&&H?.customer_id&&Number(H.customer_id)!==L)throw new E(`Order ${W} belongs to Customer ${H.customer_id}, not Customer ${L}.`);return{...J,key:G,template:X,expiry_date:Y,status:Z,customer_id:L,product_id:K,order_id:W}}async function oG(J){try{let $=iG(),G=y0(J),X={...await W0(G),uuid:$};await G1.insertInto("license_keys").values(X).executeTakeFirst();let Z=await G1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created license key");return Z}catch($){if($ instanceof E)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function sG(J){if(!J.length)return 0;try{let $=await Promise.all(J.map(async(X)=>({...await W0(y0(X)),uuid:iG()}))),G=await G1.insertInto("license_keys").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof E)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as y$}from"@stacksjs/database";import{formatDate as X1}from"@stacksjs/orm";async function dG(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($),Z=await W0(X,G),Y=await y$.updateTable("license_keys").set({...Z,updated_at:X1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof E)throw G;if(G instanceof Error){if(G.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${G.message}`)}throw G}}async function aG(J,$){try{let G=await y$.updateTable("license_keys").set({status:$,updated_at:X1(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 eG(J,$){try{let G={updated_at:X1(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:()=>FX,updatePricing:()=>QX,update:()=>WX,store:()=>ZX,softDelete:()=>tG,getActiveShippingMethods:()=>KX,formatShippingOptions:()=>LX,fetchById:()=>l$,fetchAll:()=>GX,destroy:()=>rG,bulkStore:()=>YX,bulkSoftDelete:()=>JX,bulkDestroy:()=>$X});import{db as m$}from"@stacksjs/database";async function rG(J){try{let $=await m$.deleteFrom("shipping_methods").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function tG(J){try{let $=await m$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function $X(J){if(!J.length)return 0;try{let $=await m$.deleteFrom("shipping_methods").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function JX(J){if(!J.length)return 0;try{let $=await m$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as 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 GX(){let J=await p$.selectFrom("shipping_methods").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((Y)=>Y.id))],Z=(await p$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((Y,L)=>{let K=L.shipping_method_id;if(K!==null&&K!==void 0){if(!Y[K])Y[K]=[];Y[K].push(L)}return Y},{});return J.map((Y)=>({...Y,shipping_zones:Z[Y.id]||[]}))}var{randomUUIDv7:XX}=globalThis.Bun;import{db as c0}from"@stacksjs/database";async function ZX(J){try{let $=XX(),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 YX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...g0(X),uuid:XX()})),G=await c0.insertInto("shipping_methods").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function LX(){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 KX(){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 Z1}from"@stacksjs/database";import{formatDate as Y1}from"@stacksjs/orm";async function WX(J,$){try{if(!J)throw Error("Shipping method ID is required for update");let G=await Z1.updateTable("shipping_methods").set({...g0($),updated_at:Y1(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 FX(J,$){try{let G=await Z1.updateTable("shipping_methods").set({status:$,updated_at:Y1(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 QX(J,$,G){try{let X={updated_at:Y1(new Date)};if($!==void 0)X.base_rate=$;if(G!==void 0)X.free_shipping=G;let Z=await Z1.updateTable("shipping_methods").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update pricing information");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update pricing information: ${X.message}`);throw X}}var s$={};z(s$,{validateZoneMatchesAddress:()=>_X,validateShippingRateWrite:()=>F0,updateByZone:()=>CX,updateByMethod:()=>hX,update:()=>jX,store:()=>wX,resolveZoneForAddress:()=>n$,getShippingRatesByMethod:()=>UX,getRatesByZone:()=>AX,getRateByWeightAndZone:()=>L1,getRateByWeightAndAddress:()=>OX,formatShippingRateOptions:()=>RX,fetchById:()=>zX,fetchAll:()=>BX,destroyByZone:()=>MX,destroyByMethod:()=>xX,destroy:()=>NX,bulkUpdate:()=>kX,bulkStore:()=>fX,bulkDestroy:()=>HX,ShippingRateInputError:()=>k});import{db as u$}from"@stacksjs/database";async function NX(J){try{let $=await u$.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function HX(J){if(!J.length)return 0;try{let $=await u$.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function MX(J){try{let $=await u$.deleteFrom("shipping_rates").where("shipping_zone_id","=",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function xX(J){try{let $=await u$.deleteFrom("shipping_rates").where("shipping_method_id","=",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as v}from"@stacksjs/database";async function zX(J){let $=await v.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.shipping_zone_id)G=await v.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)X=await v.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:G,shipping_method:X}}return}async function BX(){let J=await v.selectFrom("shipping_rates").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((K)=>K.shipping_zone_id).filter((K)=>K!==null&&K!==void 0))],G=[...new Set(J.map((K)=>K.shipping_method_id).filter((K)=>K!==null&&K!==void 0))],[X,Z]=await Promise.all([$.length?v.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],G.length?v.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),Y=X.reduce((K,W)=>{return K[W.id]=W,K},{}),L=Z.reduce((K,W)=>{return K[W.id]=W,K},{});return J.map((K)=>({...K,shipping_zone:K.shipping_zone_id?Y[K.shipping_zone_id]:[],shipping_method:K.shipping_method_id?L[K.shipping_method_id]:[]}))}async function AX(J){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function L1(J,$){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function n$(J){if(!J?.countryCode)return null;try{let $=await v.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let G=null;for(let X of $){let Z=1;if(J.region&&X.regions&&VX(X.regions,J.region))Z=2;if(J.postalCode&&X.postal_codes&&VX(X.postal_codes,J.postalCode))Z=3;if(!G||Z>G.score)G={id:X.id,score:Z}}return G?.id??null}catch{return null}}async function OX(J,$){let G=await n$($);if(G==null)return;return L1(J,G)}async function _X(J,$){return await n$($)===J}function VX(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 RX(){try{return(await v.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function UX(J){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:qX}=globalThis.Bun;import{db as K1}from"@stacksjs/database";import{db as u0}from"@stacksjs/database";async function PX(){return await u0.selectFrom("shipping_zones").selectAll().execute()}async function i$(J){return await u0.selectFrom("shipping_zones").where("id","=",J).selectAll().executeTakeFirst()}function SX(){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 TX(){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 EX(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 k extends TypeError{constructor(J){super(J);this.name="ShippingRateInputError"}}function n0(J,$,G){return Number(J[G]??$?.[G])}async function F0(J,$){let G=n0(J,$,"shipping_method_id"),X=n0(J,$,"shipping_zone_id"),Z=n0(J,$,"weight_from"),Y=n0(J,$,"weight_to"),L=n0(J,$,"rate");if(!Number.isSafeInteger(G)||G<1)throw new k("Shipping method must be a positive integer.");if(!Number.isSafeInteger(X)||X<1)throw new k("Shipping zone must be a positive integer.");if(!Number.isFinite(Z)||Z<0)throw new k("Weight from must be a non-negative number.");if(!Number.isFinite(Y)||Y<Z)throw new k("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(L)||L<0)throw new k("Rate must be a non-negative integer in minor currency units.");let[K,W]=await Promise.all([l$(G),i$(X)]);if(!K)throw new k(`Shipping method ${G} was not found.`);if(!W)throw new k(`Shipping zone ${X} was not found.`);if(Number(W.shipping_method_id)!==G)throw new k(`Shipping zone ${X} is not assigned to shipping method ${G}.`)}async function wX(J){try{let $=i(J),G=Number($.shipping_method_id),X=Number($.shipping_zone_id);await F0($);let Z=qX(),Y={...$,shipping_method_id:G,shipping_zone_id:X,uuid:Z};await K1.insertInto("shipping_rates").values(Y).executeTakeFirst();let L=await K1.selectFrom("shipping_rates").where("uuid","=",Z).selectAll().executeTakeFirst();if(!L)throw Error("Failed to resolve created shipping rate");return L}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function fX(J){if(!J.length)return 0;try{for(let X of J){let Z=i(X);await F0(Z)}let $=J.map((X)=>({...i(X),uuid:qX()})),G=await K1.insertInto("shipping_rates").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as i0}from"@stacksjs/database";import{formatDate as o$}from"@stacksjs/orm";async function jX(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 F0(X,G);let Z=await i0.updateTable("shipping_rates").set({...X,updated_at:o$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(G){if(G instanceof k)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function kX(J){if(!J.length)return 0;try{let $=0;for(let{id:G,data:X}of J){let Z=await i0.updateTable("shipping_rates").set({...i(X),updated_at:o$(new Date)}).where("id","=",G).executeTakeFirst();if(Q(Z)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function CX(J,$){try{let G=await i0.updateTable("shipping_rates").set({...i($),updated_at:o$(new Date)}).where("shipping_zone_id","=",J).executeTakeFirst();return Q(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${G.message}`);throw G}}async function hX(J,$){try{let G=await i0.updateTable("shipping_rates").set({...i($),updated_at:o$(new Date)}).where("shipping_method_id","=",J).executeTakeFirst();return Q(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var G4={};z(G4,{startStop:()=>DX,startRoute:()=>bX,routeTrackingChannel:()=>W1,recordDriverPing:()=>IX,orderTrackingChannel:()=>r,isWithin:()=>kG,hasCoordinates:()=>m0,failStop:()=>yX,estimateSecondsRemaining:()=>I$,emitDeliveryStarted:()=>e$,emitDeliveryPosition:()=>d$,emitDeliveryNearby:()=>r$,emitDeliveryFailed:()=>J4,emitDeliveryCompleted:()=>$4,emitDeliveryAssigned:()=>a$,emitDeliveryArrived:()=>t$,distanceInMeters:()=>e,completeStop:()=>vX,broadcastToChannel:()=>o,bearingInDegrees:()=>h$,assignStop:()=>gX,NEARBY_RADIUS_METERS:()=>F1,ARRIVAL_RADIUS_METERS:()=>Q1});function r(J){return`order.${J}`}function W1(J){return`delivery-route.${J}`}async function U0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function o(J,$,G){try{let X=await import("@stacksjs/realtime").catch(()=>null);if(!X)return;let Z=X.channel;if(typeof Z!=="function")return;await Z(J).broadcast($,G,"private")}catch{}}async function d$(J,$,G){await Promise.all([...J.map((X)=>o(r(X),"delivery:position",G)),$==null?Promise.resolve():o(W1($),"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 $4(J){if(await U0("delivery:completed",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:completed",{stop:J})}async function J4(J,$){await U0("delivery:failed",{stop:J,reason:$})}var{randomUUIDv7:AZ}=globalThis.Bun;import{db as y}from"@stacksjs/database";var F1=400,Q1=60,OZ=250;async function IX(J){let $=J.recordedAt??new Date().toISOString(),G=typeof J.accuracy!=="number"||J.accuracy<=OZ,X=await y.selectFrom("drivers").where("id","=",J.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!X)throw Error(`Unknown driver: ${J.driverId}`);let Z=m0(X)?{latitude:X.latitude,longitude:X.longitude}:null,Y=typeof J.heading==="number"?J.heading:Z?h$(Z,J):null,L=await _Z(J.driverId),K=L?await RZ(L.id):null,W=null,F=null,N=!1,H=!1,M=K&&m0({latitude:K.latitude??void 0,longitude:K.longitude??void 0})?{latitude:K.latitude,longitude:K.longitude}:null;if(G&&K&&M)W=Math.round(e(J,M)),F=I$(W,J.speed??0),H=W<=Q1&&K.arrived_at==null,N=!H&&W<=F1&&K.status==="en_route"&&K.notified_nearby_at==null;let O=await UZ({driverId:J.driverId,routeId:L?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$});if(G)await y.updateTable("drivers").set({latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??0,last_ping_at:$}).where("id","=",J.driverId).execute();if(K&&(W!=null||F!=null))await y.updateTable("delivery_stops").set({eta_at:F==null?K.eta_at:new Date(Date.now()+F*1000).toISOString()}).where("id","=",K.id).execute();if(G)await d$(K?.order_id==null?[]:[K.order_id],L?.id??null,{driverId:J.driverId,routeId:L?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$,distanceToStopMeters:W,etaSeconds:F});if(N&&K)await y.updateTable("delivery_stops").set({notified_nearby_at:$}).where("id","=",K.id).execute(),await r$(K,W,F);if(H&&K)await y.updateTable("delivery_stops").set({status:"arrived",arrived_at:$}).where("id","=",K.id).execute(),await t$({...K,status:"arrived",arrived_at:$});return{pingId:O,routeId:L?.id??null,stopId:K?.id??null,distanceToStopMeters:W,etaSeconds:F,crossedNearby:N,crossedArrival:H}}async function _Z(J){return await y.selectFrom("delivery_routes").where("driver_id","=",J).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function RZ(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 UZ(J){let $=AZ();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:PZ}=globalThis.Bun;import{db as q}from"@stacksjs/database";async function gX(J){let $=PZ(),G=J.sequence??await TZ(J.deliveryRouteId);await q.insertInto("delivery_stops").values({uuid:$,delivery_route_id:J.deliveryRouteId,order_id:J.orderId??null,sequence:G,status:"pending",address:J.address,latitude:J.latitude??null,longitude:J.longitude??null,recipient_name:J.recipientName??null,recipient_phone:J.recipientPhone??null,eta_at:J.etaAt??null}).executeTakeFirst();let X=await qZ($);if(X)await a$(X);return X??{}}async function DX(J){await q.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",J).execute();let $=await H1(J);if(!$)return null;if($.order_id!=null)await N1($.order_id,"OUT_FOR_DELIVERY");return await e$($),$}async function vX(J,$){let G=new Date().toISOString();await q.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await EZ(J)?{}:{arrived_at:G},...$?{notes:$}:{}}).where("id","=",J).execute();let X=await H1(J);if(!X)return null;if(X.order_id!=null)await N1(X.order_id,"DELIVERED");return await $4(X),await mX(X.delivery_route_id),X}async function yX(J,$){await q.updateTable("delivery_stops").set({status:"failed",notes:$}).where("id","=",J).execute();let G=await H1(J);if(!G)return null;if(G.order_id!=null)await N1(G.order_id,"SHIPPED");return await J4(G,$),await mX(G.delivery_route_id),G}async function bX(J){await q.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",J).execute()}async function mX(J){if(J==null)return;if(await q.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let G=await q.selectFrom("delivery_routes").where("id","=",J).select(["driver_id"]).executeTakeFirst();if(await q.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",J).execute(),G?.driver_id!=null)await q.updateTable("drivers").set({status:"active"}).where("id","=",G.driver_id).execute()}async function N1(J,$){let G=await q.selectFrom("orders").where("id","=",J).select(["id","status"]).executeTakeFirst();if(!G)return;let X=await Promise.resolve().then(() => (x0(),MJ)),{canTransition:Z,emitForStatus:Y}=X,L=SZ(G.status,$,Z);if(L.length===0){let{log:K}=await import("@stacksjs/logging").catch(()=>({log:null}));K?.warn(`[delivery] refused to move order ${J} from ${G.status} to ${$}: no legal transition`);return}for(let K of L)await q.updateTable("orders").set({status:K}).where("id","=",J).execute(),await Y(K,{...G,status:K})}function SZ(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 TZ(J){return(await q.selectFrom("delivery_stops").where("delivery_route_id","=",J).select(["sequence"]).execute()).reduce((G,X)=>Math.max(G,X.sequence??0),0)+1}async function EZ(J){return(await q.selectFrom("delivery_stops").where("id","=",J).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function H1(J){return await q.selectFrom("delivery_stops").where("id","=",J).selectAll().executeTakeFirst()??null}async function qZ(J){return await q.selectFrom("delivery_stops").where("uuid","=",J).selectAll().executeTakeFirst()??null}var L4={};z(L4,{updateStatus:()=>dX,updateRegionsAndPostalCodes:()=>eX,updateCountries:()=>aX,update:()=>sX,store:()=>iX,softDelete:()=>lX,getZonesByCountry:()=>EX,getActiveShippingZones:()=>TX,formatZoneOptions:()=>SX,fetchById:()=>i$,fetchAll:()=>PX,destroy:()=>pX,bulkStore:()=>oX,bulkSoftDelete:()=>uX,bulkDestroy:()=>cX});import{db as X4}from"@stacksjs/database";async function pX(J){try{let $=await X4.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function lX(J){try{let $=await X4.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function cX(J){if(!J.length)return 0;try{let $=await X4.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function uX(J){if(!J.length)return 0;try{let $=await X4.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:nX}=globalThis.Bun;import{db as M1}from"@stacksjs/database";async function iX(J){try{let $=nX(),G={...D0(J),uuid:$};await M1.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await M1.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 oX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...D0(X),uuid:nX()})),G=await M1.insertInto("shipping_zones").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as Z4}from"@stacksjs/database";import{formatDate as Y4}from"@stacksjs/orm";async function sX(J,$){try{if(!J)throw Error("Shipping zone ID is required for update");let G=await Z4.updateTable("shipping_zones").set({...D0($),updated_at:Y4(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 dX(J,$){try{let G=await Z4.updateTable("shipping_zones").set({status:$,updated_at:Y4(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 aX(J,$){try{let G=await Z4.updateTable("shipping_zones").set({countries:$,updated_at:Y4(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 eX(J,$,G){try{let X={updated_at:Y4(new Date)};if($!==void 0)X.regions=$;if(G!==void 0)X.postal_codes=G;let Z=await Z4.updateTable("shipping_zones").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update regions and postal codes");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${X.message}`);throw X}}var wZ={digital:j$,drivers:C$,geocoding:D$,licenses:b$,methods:c$,rates:s$,routes:w$,tracking:G4,zones:L4},fZ=wZ;var V1={};z(V1,{updateStatus:()=>F9,updateRate:()=>Q9,updateDefaultStatus:()=>N9,update:()=>W9,store:()=>L9,fetchById:()=>G9,fetchAll:()=>X9,destroy:()=>tX,bulkStore:()=>K9,bulkDestroy:()=>$9});import{db as rX}from"@stacksjs/database";async function tX(J){try{let $=await rX.deleteFrom("tax_rates").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function $9(J){if(!J.length)return 0;try{let $=await rX.deleteFrom("tax_rates").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as J9}from"@stacksjs/database";async function G9(J){return await J9.selectFrom("tax_rates").where("id","=",J).selectAll().executeTakeFirst()}async function X9(){return await J9.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:Z9}=globalThis.Bun;import{db as Y9}from"@stacksjs/database";async function L9(J){try{return await Y9.transaction(async($)=>{let G={...J,uuid:Z9()};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 K9(J){if(!J.length)return 0;try{return await Y9.transaction(async($)=>{let G=0;for(let X of J){let Z={...X,uuid:Z9()};if(Z.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(Z).executeTakeFirst())G++}return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as K4}from"@stacksjs/database";import{formatDate as W4}from"@stacksjs/orm";async function W9(J,$){try{if(!J)throw Error("Tax rate ID is required for update");return await K4.transaction(async(G)=>{let X=await G.selectFrom("tax_rates").select("is_default").where("id","=",J).executeTakeFirst();if(!X)return;let Z=$.is_default??Boolean(X.is_default),Y=W4(new Date);if(Z)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Y}).where("id","!=",J).execute();let L=await G.updateTable("tax_rates").set({...$,updated_at:Y}).where("id","=",J).returningAll().executeTakeFirst();if(!L)return;return L})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function F9(J,$){try{let G=await K4.updateTable("tax_rates").set({status:$,updated_at:W4(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 Q9(J,$){try{let G=await K4.updateTable("tax_rates").set({rate:$,updated_at:W4(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 N9(J,$){try{return await K4.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",J).executeTakeFirst())return!1;let Z=W4(new Date);if($)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Z}).where("id","!=",J).execute();return await G.updateTable("tax_rates").set({is_default:$,updated_at:Z}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var R1={};z(R1,{restaurant:()=>S0,products:()=>Q4,default:()=>bZ});var Q4={};z(Q4,{updateStatus:()=>k9,updatePartySize:()=>C9,update:()=>F4,store:()=>f9,fetchWaiting:()=>U9,fetchPurchasedBetweenDates:()=>_9,fetchNotifiedBetweenDates:()=>O9,fetchCountByStatus:()=>P9,fetchCountBySource:()=>V9,fetchCountByQuantity:()=>B9,fetchCountByDateGrouped:()=>E9,fetchCountByDate:()=>z9,fetchCountByAllQuantities:()=>A9,fetchCountBetweenDates:()=>T9,fetchConversionRates:()=>S9,fetchCancelledBetweenDates:()=>R9,fetchById:()=>o0,fetchAll:()=>x9,destroy:()=>H9,bulkStore:()=>j9,bulkDestroy:()=>M9});import{db as z1}from"@stacksjs/database";async function H9(J){try{let $=await z1.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await z1.deleteFrom("waitlist_products").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function M9(J){if(!J.length)return 0;try{let $=await z1.deleteFrom("waitlist_products").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as T}from"@stacksjs/orm";async function o0(J){return await A.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function x9(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function V9(J,$){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(J&&$){let Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{source:Y,count:L})=>{return Z[Y]=L,Z},{})}async function z9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=T($),Z=T(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function B9(J){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",J).executeTakeFirst())?.count??0}async function A9(J,$){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(J&&$){let Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{quantity:Y,count:L})=>{return Z[Y]=L,Z},{})}async function O9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",X).whereNotNull("notified_at").execute()}async function _9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",X).whereNotNull("purchased_at").execute()}async function R9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",X).whereNotNull("cancelled_at").execute()}async function U9(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function P9(J,$,G){let X=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",J);if($&&G){let Y=T($),L=T(G);X=X.where("created_at",">=",Y).where("created_at","<=",L)}return(await X.executeTakeFirst())?.count??0}async function S9(J,$){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(J&&$){let W=T(J),F=T($);G=G.where("created_at",">=",W).where("created_at","<=",F)}let X=await G.execute(),Z=X.reduce((W,{count:F})=>W+F,0),Y=X.find((W)=>W.status==="purchased")?.count??0,L=Z>0?Y/Z*100:0,K=X.reduce((W,{status:F,count:N})=>{return W[F]={count:N,percentage:Z>0?N/Z*100:0},W},{});return{totalConversionRate:L,statusBreakdown:K}}async function T9(J,$){let G=T(J),X=T($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function E9(J,$){let G=A.selectFrom("waitlist_products").select(["created_at"]);if(J&&$){let Y=T(J),L=T($);G=G.where("created_at",">=",Y).where("created_at","<=",L)}let Z=(await G.execute()).reduce((Y,{created_at:L})=>{let K=(L||"").split("T")[0]||"unknown";return Y[K]=(Y[K]||0)+1,Y},{});return Object.entries(Z).map(([Y,L])=>({date:Y,count:L})).sort((Y,L)=>Y.date.localeCompare(L.date))}var{randomUUIDv7:w9}=globalThis.Bun;import{db as B1}from"@stacksjs/database";import{formatDate as q9}from"@stacksjs/orm";var jZ={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function kZ(J){return typeof J==="number"||J instanceof Date?q9(J):J}function s0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,Z])=>Z!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let Z of["notified_at","purchased_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=kZ(G[Z]);let X=jZ[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=q9(new Date);return G}async function f9(J){try{let $=w9(),G={...s0(J),uuid:$,status:J.status||"waiting"};await B1.insertInto("waitlist_products").values(G).executeTakeFirst();let X=await B1.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 j9(J){if(!J.length)return 0;try{let $=J.map((X)=>({...s0(X),status:X.status||"waiting",uuid:w9()})),G=await B1.insertInto("waitlist_products").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as CZ}from"@stacksjs/database";import{formatDate as hZ}from"@stacksjs/orm";async function F4(J,$){try{if(!J)throw Error("Waitlist product ID is required for update");let G=await o0(J);if(!G)return;await CZ.updateTable("waitlist_products").set({...s0($,G),updated_at:hZ(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 k9(J,$){return await F4(J,{status:$})}async function C9(J,$){return await F4(J,{quantity:$})}var S0={};z(S0,{updateWaitTimes:()=>Z3,updateStatus:()=>G3,updateQueuePosition:()=>Y3,updatePartySize:()=>X3,update:()=>P0,store:()=>$3,fetchWaitingWithQuotedTimes:()=>n9,fetchWaitingWithPartySizes:()=>i9,fetchWaiting:()=>l9,fetchTimeSeriesStats:()=>r9,fetchTablesTurnedToday:()=>o9,fetchSeatingRate:()=>s9,fetchSeatedStats:()=>e9,fetchSeatedBetweenDates:()=>p9,fetchNoShowStats:()=>d9,fetchCurrentWaitTimes:()=>a9,fetchCountByTablePreference:()=>D9,fetchCountByPartySize:()=>y9,fetchCountByDate:()=>v9,fetchCountByAllPartySizes:()=>b9,fetchConversionRates:()=>c9,fetchById:()=>d0,fetchBetweenDates:()=>m9,fetchAverageWaitTimes:()=>u9,fetchAll:()=>g9,destroy:()=>h9,bulkStore:()=>J3,bulkDestroy:()=>I9});import{db as A1}from"@stacksjs/database";async function h9(J){try{let $=await A1.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await A1.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function I9(J){if(!J.length)return 0;try{let $=await A1.deleteFrom("waitlist_restaurants").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as V}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function d0(J){return await V.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function g9(){return await V.selectFrom("waitlist_restaurants").selectAll().execute()}async function D9(){return(await V.selectFrom("waitlist_restaurants").select(["table_preference",V.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:G,count:X})=>{return $[G]=X,$},{})}async function v9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),Z=g(G);return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function y9(J){return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function b9(){return(await V.selectFrom("waitlist_restaurants").select(["party_size",V.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:G,count:X})=>{return $[G]=X,$},{})}async function m9(J,$){let G=g(J),X=g($);return await V.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",X).execute()}async function p9(J,$){let G=g(J),X=g($);return await V.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",X).where("status","=","seated").execute()}async function l9(){return await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function c9(){let J=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),$=J.reduce((Y,{count:L})=>Y+L,0),G=J.find((Y)=>Y.status==="seated")?.count??0,X=$>0?Number(G)/$*100:0,Z=J.reduce((Y,{status:L,count:K})=>{return Y[L]={count:K,percentage:$>0?K/$*100:0},Y},{});return{totalConversionRate:X,statusBreakdown:Z}}async function u9(){let J=await V.selectFrom("waitlist_restaurants").select([V.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),V.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 n9(){let J=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((X,Z)=>X+(Z.quoted_wait_time??0),0),G=J.length>0?$/J.length:0;return{entries:J,totalQuotedWaitTime:$,averageQuotedWaitTime:G}}async function i9(){let J=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((Z,Y)=>Z+Y.party_size,0),G=J.length>0?$/J.length:0,X=J.reduce((Z,Y)=>{return Z[Y.party_size]=(Z[Y.party_size]||0)+1,Z},{});return{entries:J,totalPartySize:$,averagePartySize:G,partySizeBreakdown:X}}async function o9(){let J=new Date,$=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),Z=g(G),Y=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",X).where("check_in_time","<=",Z).execute(),L=Y.length,K=Y.reduce((H,M)=>H+M.party_size,0),W=L>0?K/L:0,F=Y.reduce((H,M)=>{return H[M.table_preference]=(H[M.table_preference]||0)+1,H},{}),N=Y.reduce((H,M)=>{return H[M.party_size]=(H[M.party_size]||0)+1,H},{});return{totalTablesTurned:L,averagePartySize:W,totalCustomersSeated:K,breakdownByTablePreference:F,breakdownByPartySize:N}}async function s9(J,$){let G=g(J),X=g($),Z=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).where("check_in_time",">=",G).where("check_in_time","<=",X).groupBy("status").execute(),Y=Z.reduce((F,{count:N})=>F+N,0),L=Z.find((F)=>F.status==="seated")?.count??0,K=Y>0?Number(L)/Y*100:0,W=Z.reduce((F,{status:N,count:H})=>{return F[N]={count:H,percentage:Y>0?H/Y*100:0},F},{});return{totalEntries:Y,seatedEntries:L,seatingRate:K,statusBreakdown:W}}async function d9(J,$){let G=g(J),X=g($),Z=V.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",X),Y=await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",X).executeTakeFirst(),L=await Z.execute(),K=L.length,W=Y?.count&&Y.count>0?K/Y.count*100:0,F=L.reduce((_,U)=>_+(U.quoted_wait_time??0),0),N=K>0?F/K:0,H=L.reduce((_,U)=>_+U.party_size,0),M=K>0?H/K:0,O=L.reduce((_,U)=>{return _[U.table_preference]=(_[U.table_preference]||0)+1,_},{}),R=L.reduce((_,U)=>{return _[U.party_size]=(_[U.party_size]||0)+1,_},{});return{totalNoShows:K,noShowRate:W,averageQuotedWaitTime:N,averagePartySize:M,breakdownByTablePreference:O,breakdownByPartySize:R}}async function a9(){let J=await V.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=J.reduce((Z,Y)=>Z+(Y.quoted_wait_time||0),0),G=J.reduce((Z,Y)=>Z+(Y.actual_wait_time||0),0),X=J.length;return{averageQuoted:X>0?$/X:0,averageActual:X>0?G/X:0}}async function e9(){let J=Date.now()-86400000,$=await V.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),G=Array.from({length:24},(X,Z)=>({hour:Z,count:$.filter((Y)=>{return Y.seated_at===Z}).length}));return{total:$.length,byHour:G}}async function r9(){return(await V.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:t9}=globalThis.Bun;import{db as _1}from"@stacksjs/database";import{formatDate as O1}from"@stacksjs/orm";var IZ={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function gZ(J){if(typeof J==="number")return O1(J<=2147483647?J*1000:J);if(J instanceof Date)return O1(J);return J}function a0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,Z])=>Z!==void 0));for(let Z of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=gZ(G[Z]);let X=IZ[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=O1(new Date);return G}async function $3(J){try{let $=t9(),G={...a0(J),status:J.status||"waiting",uuid:$};await _1.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let X=await _1.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 J3(J){if(!J.length)return 0;try{let $=J.map((X)=>({...a0(X),status:X.status||"waiting",uuid:t9()})),G=await _1.insertInto("waitlist_restaurants").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as DZ}from"@stacksjs/database";import{formatDate as vZ}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 DZ.updateTable("waitlist_restaurants").set({...a0($,G),updated_at:vZ(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 G3(J,$){return await P0(J,{status:$})}async function X3(J,$){return await P0(J,{party_size:$})}async function Z3(J,$,G){return await P0(J,{quoted_wait_time:$,...G===void 0?{}:{actual_wait_time:G}})}async function Y3(J,$){return await P0(J,{queue_position:$})}var yZ={products:Q4,restaurant:S0},bZ=yZ;var mZ={coupons:N4,customers:H4,devices:B4,errors:_4,giftCards:U4,orders:k4,payments:C4,products:b4,receipts:n4,restaurant:S0,shippings:x1,tax:V1,waitlists:R1},R8=mZ;export{R1 as waitlists,V1 as tax,x1 as shippings,S0 as restaurant,n4 as receipts,b4 as products,C4 as payments,k4 as orders,U4 as giftCards,_4 as errors,B4 as devices,R8 as default,H4 as customers,N4 as coupons,mZ as commerce};
27
+ AND COALESCE(refund_amount, 0) + ${X(5)} <= amount`,[$,$,Z,J,$]),L=typeof Y?.execute==="function"?await Y.execute():Y;if(Number(L?.numUpdatedRows??L?.[0]?.numUpdatedRows??L?.numAffectedRows??L?.affectedRows??L?.[0]?.affectedRows??L?.changes??0)>0){let M=await Y0(J);if(M)return M;throw Error(`Payment with ID ${J} disappeared during refund`)}let W=await Y0(J);if(!W)throw Error(`Payment with ID ${J} not found`);let F=String(W.status||"");if(!s3.has(F))throw Error(`Payment status ${F||"unknown"} cannot be refunded`);let N=W,H=Number(W.amount||0)-Number(N.refundAmount??N.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${H} minor units`)}var b4={};z(b4,{variants:()=>U$,units:()=>R$,reviews:()=>A$,manufacturers:()=>B$,items:()=>z$,default:()=>LZ,categories:()=>V$});var V$={};z(V$,{updateParent:()=>Q6,updateDisplayOrder:()=>W6,updateActiveStatus:()=>F6,update:()=>K6,store:()=>h4,removeChildCategories:()=>G6,remove:()=>$6,findOrCreateByName:()=>L6,fetchStats:()=>eJ,fetchRootCategories:()=>sJ,fetchChildCategories:()=>dJ,fetchCategoryTree:()=>tJ,fetchByName:()=>iJ,fetchById:()=>f,fetchByDisplayOrder:()=>aJ,fetchAll:()=>I4,fetchActive:()=>oJ,deactivateChildCategories:()=>Z6,deactivate:()=>X6,compareCategoryGrowth:()=>rJ,bulkRemove:()=>J6});import{db as z0}from"@stacksjs/database";import{db as S}from"@stacksjs/database";import{formatDate as k0}from"@stacksjs/orm";async function I4(){return await S.selectFrom("categories").selectAll().execute()}async function f(J){return await S.selectFrom("categories").where("id","=",J).selectAll().executeTakeFirst()}async function iJ(J){return await S.selectFrom("categories").where("name","=",J).selectAll().executeTakeFirst()}async function oJ(){return await S.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function sJ(){return await S.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function dJ(J){return await S.selectFrom("categories").where("parent_category_id","=",J).where("is_active","=",!0).selectAll().execute()}async function aJ(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 eJ(){let J=await S.selectFrom("categories").select(S.fn.count("id").as("count")).executeTakeFirst(),$=await S.selectFrom("categories").where("is_active","=",!0).select(S.fn.count("id").as("count")).executeTakeFirst(),G=await S.selectFrom("categories").whereNull("parent_category_id").select(S.fn.count("id").as("count")).executeTakeFirst(),X=await S.selectFrom("categories").whereNotNull("image_url").select(S.fn.count("id").as("count")).executeTakeFirst(),Z=new Date;Z.setDate(Z.getDate()-30);let Y=k0(Z),L=await S.selectFrom("categories").where("created_at",">=",Y).selectAll().limit(5).execute(),K=await S.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",S.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number($?.count||0),root_categories:Number(G?.count||0),child_categories:Number(J?.count||0)-Number(G?.count||0),with_images:Number(X?.count||0),recently_added:L,top_parent_categories:K.map((W)=>({id:String(W.parent_category_id||""),name:String(W.parent_name||""),child_count:Number(W.child_count)}))}}async function rJ(J=30){let $=new Date,G=k0($),X=new Date;X.setDate($.getDate()-J);let Z=k0(X),Y=new Date(X);Y.setDate(Y.getDate()-1);let L=k0(Y),K=new Date(Y);K.setDate(Y.getDate()-J);let W=k0(K),F=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",G).executeTakeFirst(),N=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",W).where("created_at","<=",L).executeTakeFirst(),H=Number(F?.count||0),M=Number(N?.count||0),O=H-M,R=M!==0?O/M*100:H>0?100:0;return{current_period:H,previous_period:M,difference:O,percentage_change:R,days_range:J}}async function tJ(){let J=await I4(),$=new Map;J.forEach((Z)=>{$.set(Z.id,{...Z,children:[]})});let G=[];J.forEach((Z)=>{let Y=$.get(Z.id);if(Z.parent_category_id){let L=$.get(Z.parent_category_id);if(L)L.children.push(Y)}else G.push(Y)}),G.sort((Z,Y)=>Z.display_order-Y.display_order);let X=(Z)=>{Z.sort((Y,L)=>Y.display_order-L.display_order),Z.forEach((Y)=>{if(Y.children.length>0)X(Y.children)})};return X(G),G}async function $6(J){let $=await z0.deleteFrom("categories").where("id","=",J).executeTakeFirst();return Q($)>0}async function J6(J){if(!J.length)return 0;let $=await z0.deleteFrom("categories").where("id","in",J).executeTakeFirst();return Q($)}async function G6(J){let $=await z0.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return Q($)}async function X6(J){if(!await f(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 Z6(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:d3}=globalThis.Bun;import{db as Y6}from"@stacksjs/database";import{HttpError as M$}from"@stacksjs/error-handling";import{isUniqueViolation as a3}from"@stacksjs/orm";import{slug as e3}from"@stacksjs/strings";async function h4(J){try{let $=J.parent_category_id?Number(J.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new M$(422,"Parent category ID must be a positive integer");if($&&!await f($))throw new M$(422,`Parent category with ID ${J.parent_category_id} not found`);let G={...J,uuid:d3(),is_active:J.is_active??!0,parent_category_id:J.parent_category_id||null},X=await Y6.insertInto("categories").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create category");return X}catch($){if($ instanceof M$)throw $;if(a3($))throw new M$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function L6(J){if(!J.name)throw Error("Name is required");let $=await Y6.selectFrom("categories").selectAll().where("name","=",J.name).executeTakeFirst();if($)return $;let G={name:J.name,slug:e3(J.name),is_active:J.is_active??!0,display_order:0};return await h4(G)}import{db as C0}from"@stacksjs/database";import{HttpError as B0}from"@stacksjs/error-handling";import{formatDate as x$,isUniqueViolation as r3}from"@stacksjs/orm";async function K6(J,$){if(!await f(J))return;if(Object.hasOwn($,"parent_category_id")){let X=$.parent_category_id?Number($.parent_category_id):void 0;if(X!==void 0&&(!Number.isSafeInteger(X)||X<=0))throw new 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 f(X))throw new B0(422,`Parent category with ID ${$.parent_category_id} not found`);if(X&&await N6(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}:{},Z=await C0.updateTable("categories").set({...$,...X,updated_at:x$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(X){if(X instanceof B0)throw X;if(r3(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 W6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);try{return await C0.updateTable("categories").set({display_order:$,updated_at:x$(new Date)}).where("id","=",J).execute(),await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category display order: ${X.message}`);throw X}}async function F6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);try{return await C0.updateTable("categories").set({is_active:$,updated_at:x$(new Date)}).where("id","=",J).execute(),await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function Q6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);if($){let X=Number($);if(X===J)throw Error("A category cannot be its own parent");if(!await f(X))throw Error(`Parent category with ID ${$} not found`);if(await N6(J,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let X={updated_at:x$(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 f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category parent: ${X.message}`);throw X}}async function N6(J,$){let G=Number($),X=new Set;while(G){if(X.has(G))return!0;if(G===J)return!0;X.add(G);let Z=await f(G),Y=Z?.parent_category_id??Z?.parentCategoryId;if(!Z||!Y)return!1;G=Number(Y)}return!1}var z$={};z(z$,{updateInventory:()=>P6,updateAvailability:()=>U6,update:()=>R6,store:()=>O6,fetchTopProducts:()=>z6,fetchById:()=>u,fetchAll:()=>V6,destroy:()=>M6,bulkStore:()=>_6,bulkDestroy:()=>x6});import{db as H6}from"@stacksjs/database";async function M6(J){try{let $=await H6.deleteFrom("products").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function x6(J){if(!J.length)return 0;try{let $=await H6.deleteFrom("products").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as a,sql as t3}from"@stacksjs/database";async function u(J){let $=await a.selectFrom("products").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.manufacturer_id)G=await a.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)X=await a.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:G,category:X}}return}async function V6(){let J=await a.selectFrom("products").selectAll().execute(),$=J.map((F)=>F.manufacturer_id).filter((F)=>F!==null&&F!==void 0),G=J.map((F)=>F.category_id).filter((F)=>F!==null&&F!==void 0),X=a.selectFrom("manufacturers"),Z=a.selectFrom("categories");if($.length>0)X=X.where("id","in",$);if(G.length>0)Z=Z.where("id","in",G);let Y=await X.selectAll().execute(),L=await Z.selectAll().execute(),K=Y.reduce((F,N)=>{return F[N.id]=N,F},{}),W=L.reduce((F,N)=>{return F[N.id]=N,F},{});return J.map((F)=>({...F,manufacturer:F.manufacturer_id?K[F.manufacturer_id]:null,category:F.category_id?W[F.category_id]:null}))}async function z6(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"),t3`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:B6}=globalThis.Bun;import{db as A6}from"@stacksjs/database";async function O6(J){try{let $={...J,uuid:B6()},G=await A6.insertInto("products").values($).executeTakeFirst();if(!G)throw Error("Failed to create product item");let X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),Z=await u(X);if(!Z)throw Error("Failed to create product item");return Z}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function _6(J){if(!J.length)return 0;let $=0;try{return await A6.transaction().execute(async(G)=>{for(let X of J){let Z={...X,uuid:B6()};await G.insertInto("products").values(Z).execute(),$++}}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as g4}from"@stacksjs/database";import{formatDate as D4}from"@stacksjs/orm";async function R6(J,$){try{if(!J)throw Error("Product item ID is required for update");let G=await g4.updateTable("products").set({...$,updated_at:D4(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 U6(J,$){if(!await u(J))throw Error(`Product item with ID ${J} not found`);try{return await g4.updateTable("products").set({is_available:$,updated_at:D4(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 P6(J,$){let G=await u(J);if(!G)throw Error(`Product item with ID ${J} not found`);let X={updated_at:D4(new Date)};if($!==void 0)X.inventory_count=$;if(Object.keys(X).length===1)return G;try{return await g4.updateTable("products").set(X).where("id","=",J).execute(),await u(J)}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update inventory information: ${Z.message}`);throw Z}}var B$={};z(B$,{updateFeaturedStatus:()=>m6,updateByUuid:()=>p6,update:()=>b6,store:()=>D6,fetchWithProductCount:()=>C6,fetchFeatured:()=>f6,fetchByUuid:()=>j6,fetchById:()=>w6,fetchByCountry:()=>k6,fetchAll:()=>q6,destroy:()=>T6,bulkStore:()=>v6,bulkDestroy:()=>E6});import{db as S6}from"@stacksjs/database";async function T6(J){try{let $=await S6.deleteFrom("manufacturers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function E6(J){if(!J.length)return 0;try{let $=await S6.deleteFrom("manufacturers").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as n}from"@stacksjs/database";function q6(){return n.selectFrom("manufacturers").selectAll().execute()}async function w6(J){return await n.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function j6(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 k6(J,$={}){let G=$.page||1,X=$.limit||2,Z=await n.selectFrom("manufacturers").select(n.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),Y=Number(Z?.total||0),L=await n.selectFrom("manufacturers").selectAll().where("country","=",J).limit(X).offset((G-1)*X).execute(),K=Math.ceil(Y/X);return{data:L,paging:{total_records:Y,page:G,total_pages:K},next_cursor:G<K?G+1:null}}async function C6(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:h6}=globalThis.Bun;import{db as g6}from"@stacksjs/database";import{HttpError as I6}from"@stacksjs/error-handling";import{isUniqueViolation as $Z}from"@stacksjs/orm";async function D6(J){try{let $={...J,uuid:h6(),featured:J.featured??!1},G=await g6.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch($){if($ instanceof I6)throw $;if($Z($))throw new I6(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function v6(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:h6(),featured:G.featured??!1};await g6.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 v4}from"@stacksjs/database";import{HttpError as y6}from"@stacksjs/error-handling";import{formatDate as y4,isUniqueViolation as JZ}from"@stacksjs/orm";async function b6(J,$){try{if(!J)throw Error("Manufacturer ID is required for update");let G=await v4.updateTable("manufacturers").set({...$,updated_at:y4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof y6)throw G;if(JZ(G))throw new y6(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function m6(J,$){try{let G=await v4.updateTable("manufacturers").set({featured:$,updated_at:y4(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 p6(J,$){try{let G=await v4.updateTable("manufacturers").set({...$,updated_at:y4(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:()=>L2,update:()=>Y2,store:()=>G2,fetchStatsByProductIds:()=>J2,fetchStats:()=>$2,fetchMostHelpfulByProductId:()=>a6,fetchByUserId:()=>s6,fetchByProductId:()=>o6,fetchById:()=>n6,fetchApprovedByProductId:()=>d6,fetchAll:()=>i6,destroy:()=>c6,bulkDestroy:()=>u6});import{db as l6}from"@stacksjs/database";async function c6(J){try{let $=await l6.deleteFrom("reviews").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function u6(J){if(!J.length)return 0;try{let $=await l6.deleteFrom("reviews").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as A0}from"@stacksjs/database";async function n6(J){return await A0.selectFrom("reviews").where("id","=",J).selectAll().executeTakeFirst()}async function i6(){return await A0.selectFrom("reviews").selectAll().execute()}async function o6(J){return await A0.selectFrom("reviews").where("product_id","=",J).selectAll().execute()}async function s6(J){return await A0.selectFrom("reviews").where("customer_id","=",J).selectAll().execute()}async function d6(J){return await A0.selectFrom("reviews").where("product_id","=",J).where("is_approved","=",!0).selectAll().execute()}async function a6(J){return await A0.selectFrom("reviews").where("product_id","=",J).orderBy("helpful_votes","desc").selectAll().execute()}import{db as e6}from"@stacksjs/database";function r6(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function t6(J){let $=r6();$.total=J.length;let G=0;for(let X of J){if(X.rating===null||X.rating===void 0){$.commentsOnly++;continue}let Z=Number(X.rating);if(Number.isNaN(Z)){$.commentsOnly++;continue}$.rated++,G+=Z;let Y=Math.min(5,Math.max(1,Math.round(Z)));$.distribution[Y]++}if($.rated>0)$.average=Math.round(G/$.rated*10)/10;return $}async function $2(J){let $=await e6.selectFrom("reviews").select(["rating"]).where("product_id","=",J).where("is_approved","=",!0).execute();return t6($)}async function J2(J){let $=new Map;for(let Z of J)$.set(Z,r6());if(J.length===0)return $;let G=await e6.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",J).where("is_approved","=",!0).execute(),X=new Map;for(let Z of G){let Y=X.get(Z.product_id);if(Y)Y.push({rating:Z.rating});else X.set(Z.product_id,[{rating:Z.rating}])}for(let[Z,Y]of X)$.set(Z,t6(Y));return $}var{randomUUIDv7:GZ}=globalThis.Bun;import{db as XZ}from"@stacksjs/database";function ZZ(J){let $=J.rating!==void 0&&J.rating!==null,G=typeof J.content==="string"&&J.content.trim().length>0,X=typeof J.title==="string"&&J.title.trim().length>0;return!$&&!G&&!X}async function G2(J){try{if(ZZ(J))throw Error("A review needs a rating or something written: both were empty");let $={...J,uuid:GZ(),rating:J.rating??null,is_verified_purchase:J.is_verified_purchase??!1,is_approved:J.is_approved??!1,helpful_votes:J.helpful_votes??0,unhelpful_votes:J.unhelpful_votes??0,is_featured:J.is_featured??!1},G=await XZ.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 X2}from"@stacksjs/database";import{formatDate as Z2}from"@stacksjs/orm";async function Y2(J,$){try{if(!J)throw Error("Review ID is required for update");let G=await X2.updateTable("reviews").set({...$,updated_at:Z2(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 L2(J,$,G=!0){try{let X=$==="helpful"?"helpful_votes":"unhelpful_votes",Z=G?`COALESCE("${X}", 0) + 1`:`MAX(COALESCE("${X}", 0) - 1, 0)`,Y=await X2.unsafe(`UPDATE "reviews" SET "${X}" = ${Z}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[Z2(new Date),J]).execute(),L=Array.isArray(Y)?Y[0]:Y;if(!L)throw Error("Failed to update review votes");return L}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var R$={};z(R$,{updateDefaultStatus:()=>_2,update:()=>A2,store:()=>x2,getDefaultUnit:()=>B2,formatUnitOptions:()=>z2,fetchById:()=>N2,fetchAll:()=>H2,destroy:()=>W2,bulkUpdate:()=>O2,bulkStore:()=>V2,bulkDestroy:()=>F2});import{db as K2}from"@stacksjs/database";async function W2(J){try{let $=await K2.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function F2(J){if(!J.length)return 0;try{let $=await K2.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as Q2}from"@stacksjs/database";async function N2(J){return await Q2.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function H2(){return await Q2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:M2}=globalThis.Bun;import{db as I0}from"@stacksjs/database";async function x2(J){try{return await I0.transaction(async($)=>{let G={...J,uuid:M2()},X=await $.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(G.is_default&&G.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();return X})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function V2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:M2()},Z=await I0.insertInto("product_units").values(X).returningAll().executeTakeFirst();if(X.is_default&&X.type&&Z)await I0.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",Z.id).execute();$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function z2(J){try{let $=I0.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 B2(J){try{return await I0.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 O$}from"@stacksjs/database";import{formatDate as _$}from"@stacksjs/orm";async function A2(J,$){try{if(!J)throw Error("Product unit ID is required for update");return await O$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",J).executeTakeFirst();if(!X)return;let Z=$.type??X.type;if(($.is_default??Boolean(X.is_default))&&Z)await G.updateTable("product_units").set({is_default:!1,updated_at:_$(new Date)}).where("type","=",Z).where("id","!=",J).execute();let L=await G.updateTable("product_units").set({...$,updated_at:_$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!L)return;return L})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function O2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X=G;if(!X.id)continue;let Z=X.data&&typeof X.data==="object"?X.data:{...X};delete Z.id;let Y=await O$.updateTable("product_units").set({...Z,updated_at:_$(new Date)}).where("id","=",X.id).executeTakeFirst(),L=Z;if(L.is_default===!0&&L.type)await O$.updateTable("product_units").set({is_default:!1}).where("type","=",L.type).where("id","!=",X.id).execute();if(Number(Y.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function _2(J,$){try{return await O$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!X)return!1;let Z=_$(new Date);if($&&X.type)await G.updateTable("product_units").set({is_default:!1,updated_at:Z}).where("type","=",X.type).where("id","!=",J).execute();return await G.updateTable("product_units").set({is_default:$,updated_at:Z}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var U$={};z(U$,{update:()=>g2,store:()=>j2,generateVariantCombinations:()=>C2,formatVariantOptions:()=>k2,fetchById:()=>T2,fetchAll:()=>E2,destroy:()=>U2,bulkUpdate:()=>D2,bulkStore:()=>f2,bulkDestroy:()=>P2});import{db as R2}from"@stacksjs/database";async function U2(J){try{let $=await R2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function P2(J){if(!J.length)return 0;try{let $=await R2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as S2}from"@stacksjs/database";async function T2(J){return await S2.selectFrom("product_variants").where("id","=",J).selectAll().executeTakeFirst()}async function E2(){return await S2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:q2}=globalThis.Bun;import{db as w2}from"@stacksjs/database";async function j2(J){try{let $={...J,uuid:q2()},G=await w2.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 f2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:q2()};await w2.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 k2(J){if(!J||!J.length)return JSON.stringify([]);let $=J.map((G)=>G.trim()).filter(Boolean);return JSON.stringify($)}function C2(J){let $=Object.keys(J);if(!$.length)return[];function G(X,Z){if(X===$.length)return[Z];let Y=$[X],L=J[Y]??[],K=[];for(let W of L){let F={...Z,[Y]:W};K.push(...G(X+1,F))}return K}return G(0,{})}import{db as I2}from"@stacksjs/database";import{formatDate as h2}from"@stacksjs/orm";async function g2(J,$){try{let G=await I2.updateTable("product_variants").set({...$,updated_at:h2(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 D2(J){if(!J.length)return 0;let $=0;try{for(let G of J){if(!G.id)continue;let X=await I2.updateTable("product_variants").set({...G,updated_at:h2(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 YZ={categories:V$,items:z$,manufacturers:B$,reviews:A$,units:R$,variants:U$},LZ=YZ;var n4={};z(n4,{updateStatus:()=>a2,updatePrintJob:()=>e2,update:()=>d2,store:()=>o2,fetchSuccessRate:()=>l2,fetchPrintsPerHour:()=>n2,fetchPrintTimeStats:()=>u2,fetchPrintJobStats:()=>p2,fetchPageStats:()=>c2,fetchById:()=>O0,fetchAll:()=>m2,destroy:()=>y2,bulkStore:()=>s2,bulkDestroy:()=>b2});import{db as v2}from"@stacksjs/database";async function y2(J){try{let $=await v2.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function b2(J){if(!J.length)return 0;try{let $=await v2.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as m4}from"@stacksjs/database";import{formatDate as KZ}from"@stacksjs/orm";function b(J){return KZ(J)}function WZ(J){if(J instanceof Date)return Number.isNaN(J.getTime())?null:J;if(typeof J==="number"){let X=new Date(J<=2147483647?J*1000:J);return Number.isNaN(X.getTime())?null:X}let $=String(J||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let X=new Date(Number($)*1000);return Number.isNaN(X.getTime())?null:X}let G=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function O0(J){return await m4.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function m2(){return await m4.selectFrom("receipts").selectAll().execute()}async function p2(J,$){let G=b(J),X=b($),Z=await h("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning,averageSize:Math.round(Z.averageSize),averagePages:Math.round(Z.averagePages),averageDuration:Math.round(Z.averageDuration)}}async function l2(J,$){let G=b(J),X=b($),Z=await h("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(L)=>L.where("timestamp",">=",G).where("timestamp","<=",X));return{successRate:Z.total>0?Math.round(Z.success/Z.total*100):0,total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning}}async function c2(J,$){let G=b(J),X=b($),Z=await h("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{totalPages:Z.totalPages,averagePagesPerReceipt:Math.round(Z.averagePagesPerReceipt),totalReceipts:Z.totalReceipts}}async function u2(J,$){let G=b(J),X=b($),Z=await h("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{averageDuration:Math.round(Z.averageDuration),minDuration:Z.minDuration,maxDuration:Z.maxDuration,totalJobs:Z.totalJobs}}async function n2(J,$){let G=typeof J==="number"?J:J.getTime(),X=typeof $==="number"?$:$.getTime(),Z=b(J),Y=b($),L=await m4.selectFrom("receipts").where("timestamp",">=",Z).where("timestamp","<=",Y).selectAll().execute(),K=L.length,W=Math.ceil((X-G)/3600000),F=W>0?Math.round(K/W):0,N=Array.from({length:24},(H,M)=>({hour:M,count:0}));return L.forEach((H)=>{let M=WZ(H.timestamp);if(!M)return;N[M.getHours()].count++}),{totalPrints:K,totalHours:W,printsPerHour:F,hourlyBreakdown:N}}var{randomUUIDv7:i2}=globalThis.Bun;import{db as l4}from"@stacksjs/database";import{formatDate as p4}from"@stacksjs/orm";function h0(J){try{if(typeof J==="number")return p4(J<=2147483647?J*1000:J);if(typeof J==="string"&&/^\d{10}$/.test(J))return p4(Number(J)*1000);return p4(J)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function o2(J){try{let $=i2(),G={...J,timestamp:h0(J.timestamp),uuid:$};await l4.insertInto("receipts").values(G).executeTakeFirst();let X=await l4.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 s2(J){if(!J.length)return 0;try{let $=J.map((X)=>({...X,timestamp:h0(X.timestamp),uuid:i2()})),G=await l4.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 c4}from"@stacksjs/database";import{formatDate as u4}from"@stacksjs/orm";async function d2(J,$){try{if(!J)throw Error("Receipt ID is required for update");let G={...$,...$.timestamp===void 0?{}:{timestamp:h0($.timestamp)},updated_at:u4(new Date)};await c4.updateTable("receipts").set(G).where("id","=",J).execute();let X=await O0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function a2(J,$){try{await c4.updateTable("receipts").set({status:$,updated_at:u4(new Date)}).where("id","=",J).execute();let G=await O0(J);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function e2(J,$,G,X){try{let Z={updated_at:u4(new Date)};if($!==void 0)Z.size=$;if(G!==void 0)Z.pages=G;if(X!==void 0)Z.duration=X;await c4.updateTable("receipts").set(Z).where("id","=",J).execute();let Y=await O0(J);if(!Y)throw Error("Failed to update receipt job information");return Y}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update receipt job information: ${Z.message}`);throw Z}}var x1={};z(x1,{zones:()=>L4,tracking:()=>G4,routes:()=>w$,rates:()=>s$,methods:()=>c$,licenses:()=>b$,geocoding:()=>D$,drivers:()=>C$,digital:()=>f$,default:()=>CZ});var w$={};z(w$,{validateDeliveryRouteWrite:()=>_0,updateStops:()=>KG,updateMetrics:()=>WG,updateLastActive:()=>YG,update:()=>LG,store:()=>ZG,fetchById:()=>S$,fetchByDriver:()=>XG,fetchAll:()=>JG,fetchActive:()=>GG,destroy:()=>t2,bulkDestroy:()=>$G,DeliveryRouteInputError:()=>I});import{db as r2}from"@stacksjs/database";async function t2(J){try{let $=await r2.deleteFrom("delivery_routes").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function $G(J){if(!J.length)return 0;try{let $=await r2.deleteFrom("delivery_routes").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as P$}from"@stacksjs/database";async function S$(J){return await P$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function JG(){return await P$.selectFrom("delivery_routes").selectAll().execute()}async function GG(){return await P$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function XG(J){return await P$.selectFrom("delivery_routes").where("driver","=",J).selectAll().execute()}var{randomUUIDv7:NZ}=globalThis.Bun;import{db as i4}from"@stacksjs/database";function L0(J,$){let G={};for(let[X,Z]of Object.entries($))for(let Y of Z){if(!Object.prototype.hasOwnProperty.call(J,Y)||J[Y]===void 0)continue;G[X]=J[Y];break}return G}function g0(J){return L0(J,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function i(J){return L0(J,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function D0(J){return L0(J,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function v0(J){return L0(J,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function y0(J){return L0(J,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function b0(J){return L0(J,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function T$(J){return L0(J,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as FZ}from"@stacksjs/database";class I extends TypeError{constructor(J){super(J);this.name="DeliveryRouteInputError"}}function E$(J,$,G){return Number(J[G]??$?.[G])}function QZ(J,$){let G=J.last_active??$?.last_active;if(G===void 0||G===null)return Date.now();if(G instanceof Date)return G.getTime();if(typeof G==="number")return G;if(typeof G==="string"&&/^\d{10,13}$/.test(G))return Number(G);return Number.NaN}async function _0(J,$){let G=E$(J,$,"driver_id"),X=E$(J,$,"stops"),Z=E$(J,$,"delivery_time"),Y=E$(J,$,"total_distance"),L=QZ(J,$);if(!Number.isSafeInteger(G)||G<1)throw new I("Driver must be a positive integer.");if(!Number.isSafeInteger(X)||X<0)throw new I("Stops must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new I("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(Y)||Y<0)throw new I("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(L)||L<0)throw new I("Last active must be a valid Unix timestamp.");let K=await FZ.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!K)throw new I(`Driver ${G} was not found.`);return{...J,driver_id:Number(K.id),driver:K.name,vehicle:K.vehicle_number,last_active:L}}async function ZG(J){try{let $=NZ(),G=T$(J),Z={...await _0(G),uuid:$};await i4.insertInto("delivery_routes").values(Z).executeTakeFirst();let Y=await i4.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!Y)throw Error("Failed to create delivery route");return Y}catch($){if($ instanceof I)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function YG(J){try{await i4.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 q$}from"@stacksjs/database";import{formatDate as o4}from"@stacksjs/orm";async function LG(J,$){try{if(!J)throw Error("Delivery route ID is required for update");let G=await q$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=T$($),Z=await _0(X,G),Y=await q$.updateTable("delivery_routes").set({...Z,updated_at:o4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof I)throw G;if(G instanceof Error)throw TypeError(`Failed to update delivery route: ${G.message}`);throw G}}async function KG(J,$){try{let G=await q$.updateTable("delivery_routes").set({stops:$,updated_at:o4(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 WG(J,$,G){try{let X={updated_at:o4(new Date)};if($!==void 0)X.delivery_time=$;if(G!==void 0)X.total_distance=G;let Z=await q$.updateTable("delivery_routes").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update delivery metrics");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery metrics: ${X.message}`);throw X}}var f$={};z(f$,{updateStatus:()=>_G,updateDeliverySettings:()=>RG,update:()=>OG,store:()=>BG,softDelete:()=>QG,fetchById:()=>xG,fetchAll:()=>VG,destroy:()=>FG,bulkStore:()=>AG,bulkSoftDelete:()=>HG,bulkDestroy:()=>NG});import{db as j$}from"@stacksjs/database";async function FG(J){try{let $=await j$.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function QG(J){try{let $=await j$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function NG(J){if(!J.length)return 0;try{let $=await j$.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function HG(J){if(!J.length)return 0;try{let $=await j$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as MG}from"@stacksjs/database";async function xG(J){return await MG.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function VG(){return await MG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:zG}=globalThis.Bun;import{db as s4}from"@stacksjs/database";async function BG(J){try{let $=zG(),G={...v0(J),uuid:$};await s4.insertInto("digital_deliveries").values(G).executeTakeFirst();let X=await s4.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 AG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...v0(X),uuid:zG()})),G=await s4.insertInto("digital_deliveries").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as d4}from"@stacksjs/database";import{formatDate as a4}from"@stacksjs/orm";async function OG(J,$){try{if(!J)throw Error("Digital delivery ID is required for update");let G=await d4.updateTable("digital_deliveries").set({...v0($),updated_at:a4(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 _G(J,$){try{let G=await d4.updateTable("digital_deliveries").set({status:$,updated_at:a4(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 RG(J,$,G,X,Z){try{let Y={updated_at:a4(new Date)};if($!==void 0)Y.download_limit=$;if(G!==void 0)Y.expiry_days=G;if(X!==void 0)Y.requires_login=X;if(Z!==void 0)Y.automatic_delivery=Z;let L=await d4.updateTable("digital_deliveries").set(Y).where("id","=",J).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update delivery settings");return L}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery settings: ${Y.message}`);throw Y}}var C$={};z(C$,{updateStatus:()=>kG,updateContact:()=>CG,update:()=>fG,store:()=>wG,fetchById:()=>k$,fetchAll:()=>PG,destroy:()=>TG,bulkStore:()=>jG,bulkDestroy:()=>EG});import{db as SG}from"@stacksjs/database";import{db as UG}from"@stacksjs/database";async function k$(J){return await UG.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function PG(){return await UG.selectFrom("drivers").selectAll().execute()}async function TG(J){try{let $=await SG.deleteFrom("drivers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function EG(J){if(!J.length)return 0;let $=0;try{return await SG.transaction().execute(async(G)=>{for(let X of J)if(await k$(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:qG}=globalThis.Bun;import{db as e4}from"@stacksjs/database";async function wG(J){try{let $=qG(),G={...b0(J),uuid:$};await e4.insertInto("drivers").values(G).executeTakeFirst();let X=await e4.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created driver");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function jG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...b0(X),uuid:qG()})),G=await e4.insertInto("drivers").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as r4}from"@stacksjs/database";import{formatDate as t4}from"@stacksjs/orm";async function fG(J,$){try{if(!J)throw Error("Driver ID is required for update");let G=await r4.updateTable("drivers").set({...b0($),updated_at:t4(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 kG(J,$){try{let G=await r4.updateTable("drivers").set({status:$,updated_at:t4(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 CG(J,$){try{let G={updated_at:t4(new Date)};if($!==void 0)G.phone=$;let X=await r4.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 D$={};z(D$,{setGeocodingDriver:()=>VZ,nominatimDriver:()=>g$,geocodingDriver:()=>yG,geocode:()=>zZ,formatQuery:()=>R0,checkCoverage:()=>BZ,PRECISION_RANK:()=>p0});var K0=(J)=>J*Math.PI/180;function e(J,$){let G=K0($.latitude-J.latitude),X=K0($.longitude-J.longitude),Z=K0(J.latitude),Y=K0($.latitude),L=Math.sin(G/2)**2+Math.sin(X/2)**2*Math.cos(Z)*Math.cos(Y);return 12742017.6*Math.asin(Math.sqrt(L))}function I$(J,$){let G=K0(J.latitude),X=K0($.latitude),Z=K0($.longitude-J.longitude),Y=Math.sin(Z)*Math.cos(X),L=Math.cos(G)*Math.sin(X)-Math.sin(G)*Math.cos(X)*Math.cos(Z);return(Math.atan2(Y,L)*180/Math.PI+360)%360}function h$(J,$,G={}){let X=G.detourFactor??1.35,Z=G.minimumSeconds??30;if(!Number.isFinite($)||$<=0.5)return null;let Y=J*X/$;return Math.max(Z,Math.round(Y))}function IG(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 HZ="https://nominatim.openstreetmap.org/search",hG=1000,gG=0,DG=Promise.resolve();async function MZ(J){let $=DG.then(async()=>{let G=Date.now()-gG;if(G<hG)await Bun.sleep(hG-G);return gG=Date.now(),J()});return DG=$.then(()=>{return},()=>{return}),$}function xZ(J){let $=J.address??{},G=String(J.addresstype??""),X=String(J.type??""),Z=String(J.category??J.class??"");if($.house_number||X==="house"||X==="building"||G==="building")return"rooftop";if($.road||Z==="highway"||G==="road")return"street";if(G==="postcode"||$.postcode&&!$.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(G))return"locality";return"unknown"}function g$(J={}){let $=J.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,G=J.endpoint??HZ;return{name:"nominatim",async geocode(X){let Z=R0(X);if(!Z)return null;let Y=new URL(G);if(Y.searchParams.set("q",Z),Y.searchParams.set("format","jsonv2"),Y.searchParams.set("limit","1"),Y.searchParams.set("addressdetails","1"),X.country)Y.searchParams.set("countrycodes",X.country.toLowerCase());let L=await MZ(()=>fetch(Y,{headers:{"user-agent":$,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!L.ok)throw Error(`Nominatim responded ${L.status}`);let W=(await L.json())?.[0];if(!W)return null;let F=Number(W.lat),N=Number(W.lon);if(!Number.isFinite(F)||!Number.isFinite(N))return null;let H=xZ(W);return{latitude:F,longitude:N,formatted:String(W.display_name??Z),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[H],precision:H,provider:"nominatim"}}}}var vG=null;function VZ(J){vG=J}function yG(){return vG??g$()}async function zZ(J,$={}){let G=$.driver??yG(),X=$.minimumPrecision??"street",Z=`geocode:${G.name}:${R0(J).toLowerCase()}`,Y=await AZ(Z);if(Y!==void 0)return Y;let L=await G.geocode(J),K=L&&p0[L.precision]>=p0[X]?L:null;return await OZ(Z,K,K?$.cacheSeconds??2592000:600),K}function BZ(J,$,G){if($.length===0)return null;let X=$[0],Z=e(J,X);for(let Y of $.slice(1)){let L=e(J,Y);if(L<Z)Z=L,X=Y}return{covered:Z<=G,distanceMeters:Math.round(Z),nearest:X}}async function AZ(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 OZ(J,$,G){try{let Z=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!Z)return;await Z.set(J,$===null?"null":JSON.stringify($),G)}catch{}}var b$={};z(b$,{validateLicenseKeyWrite:()=>W0,updateStatus:()=>rG,updateExpiration:()=>tG,update:()=>eG,store:()=>dG,softDelete:()=>mG,fetchById:()=>uG,fetchAll:()=>nG,destroy:()=>bG,bulkStore:()=>aG,bulkSoftDelete:()=>lG,bulkDestroy:()=>pG,LicenseKeyInputError:()=>E});import{db as v$}from"@stacksjs/database";async function bG(J){try{let $=await v$.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function mG(J){try{let $=await v$.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function pG(J){if(!J.length)return 0;try{let $=await v$.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function lG(J){if(!J.length)return 0;try{let $=await v$.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as cG}from"@stacksjs/database";async function uG(J){return await cG.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst()}async function nG(){return await cG.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:sG}=globalThis.Bun;import{db as G1}from"@stacksjs/database";import{db as $1}from"@stacksjs/database";var iG=["Standard License","Premium License","Enterprise License"],oG=["active","inactive","unassigned"];class E extends TypeError{constructor(J){super(J);this.name="LicenseKeyInputError"}}function l0(J,$,G){return J[G]!==void 0?J[G]:$?.[G]}function J1(J,$,G,X){let Z=l0(J,$,G);if(Z===void 0||Z===null||Z==="")return null;let Y=Number(Z);if(!Number.isSafeInteger(Y)||Y<1)throw new E(`${X} must be a positive integer or null.`);return Y}function _Z(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(l0(J,$,"key")||"").trim().toUpperCase(),X=String(l0(J,$,"template")||""),Z=String(l0(J,$,"status")||""),Y=_Z(l0(J,$,"expiry_date")),L=J1(J,$,"customer_id","Customer"),K=J1(J,$,"product_id","Product"),W=J1(J,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new E("License key must use five groups of four uppercase letters or numbers.");if(!iG.includes(X))throw new E(`Template must be one of: ${iG.join(", ")}.`);if(!oG.includes(Z))throw new E(`Status must be one of: ${oG.join(", ")}.`);if(!Number.isSafeInteger(Y)||Y<0||Y>2147483647)throw new E("Expiry date must be a Unix timestamp between 1970 and 2038.");let[F,N,H]=await Promise.all([L?$1.selectFrom("customers").where("id","=",L).select("id").executeTakeFirst():null,K?$1.selectFrom("products").where("id","=",K).select("id").executeTakeFirst():null,W?$1.selectFrom("orders").where("id","=",W).select(["id","customer_id"]).executeTakeFirst():null]);if(L&&!F)throw new E(`Customer ${L} was not found.`);if(K&&!N)throw new E(`Product ${K} was not found.`);if(W&&!H)throw new E(`Order ${W} was not found.`);if(L&&H?.customer_id&&Number(H.customer_id)!==L)throw new E(`Order ${W} belongs to Customer ${H.customer_id}, not Customer ${L}.`);return{...J,key:G,template:X,expiry_date:Y,status:Z,customer_id:L,product_id:K,order_id:W}}async function dG(J){try{let $=sG(),G=y0(J),X={...await W0(G),uuid:$};await G1.insertInto("license_keys").values(X).executeTakeFirst();let Z=await G1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created license key");return Z}catch($){if($ instanceof E)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function aG(J){if(!J.length)return 0;try{let $=await Promise.all(J.map(async(X)=>({...await W0(y0(X)),uuid:sG()}))),G=await G1.insertInto("license_keys").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof E)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as y$}from"@stacksjs/database";import{formatDate as X1}from"@stacksjs/orm";async function eG(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($),Z=await W0(X,G),Y=await y$.updateTable("license_keys").set({...Z,updated_at:X1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof E)throw G;if(G instanceof Error){if(G.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${G.message}`)}throw G}}async function rG(J,$){try{let G=await y$.updateTable("license_keys").set({status:$,updated_at:X1(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 tG(J,$){try{let G={updated_at:X1(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:()=>NX,updatePricing:()=>HX,update:()=>QX,store:()=>LX,softDelete:()=>JX,getActiveShippingMethods:()=>FX,formatShippingOptions:()=>WX,fetchById:()=>l$,fetchAll:()=>ZX,destroy:()=>$X,bulkStore:()=>KX,bulkSoftDelete:()=>XX,bulkDestroy:()=>GX});import{db as m$}from"@stacksjs/database";async function $X(J){try{let $=await m$.deleteFrom("shipping_methods").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function JX(J){try{let $=await m$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function GX(J){if(!J.length)return 0;try{let $=await m$.deleteFrom("shipping_methods").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function XX(J){if(!J.length)return 0;try{let $=await m$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as 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 ZX(){let J=await p$.selectFrom("shipping_methods").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((Y)=>Y.id))],Z=(await p$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((Y,L)=>{let K=L.shipping_method_id;if(K!==null&&K!==void 0){if(!Y[K])Y[K]=[];Y[K].push(L)}return Y},{});return J.map((Y)=>({...Y,shipping_zones:Z[Y.id]||[]}))}var{randomUUIDv7:YX}=globalThis.Bun;import{db as c0}from"@stacksjs/database";async function LX(J){try{let $=YX(),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 KX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...g0(X),uuid:YX()})),G=await c0.insertInto("shipping_methods").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function WX(){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 FX(){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 Z1}from"@stacksjs/database";import{formatDate as Y1}from"@stacksjs/orm";async function QX(J,$){try{if(!J)throw Error("Shipping method ID is required for update");let G=await Z1.updateTable("shipping_methods").set({...g0($),updated_at:Y1(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 NX(J,$){try{let G=await Z1.updateTable("shipping_methods").set({status:$,updated_at:Y1(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 HX(J,$,G){try{let X={updated_at:Y1(new Date)};if($!==void 0)X.base_rate=$;if(G!==void 0)X.free_shipping=G;let Z=await Z1.updateTable("shipping_methods").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update pricing information");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update pricing information: ${X.message}`);throw X}}var s$={};z(s$,{validateZoneMatchesAddress:()=>UX,validateShippingRateWrite:()=>F0,updateByZone:()=>hX,updateByMethod:()=>gX,update:()=>CX,store:()=>fX,resolveZoneForAddress:()=>n$,getShippingRatesByMethod:()=>SX,getRatesByZone:()=>_X,getRateByWeightAndZone:()=>L1,getRateByWeightAndAddress:()=>RX,formatShippingRateOptions:()=>PX,fetchById:()=>AX,fetchAll:()=>OX,destroyByZone:()=>VX,destroyByMethod:()=>zX,destroy:()=>MX,bulkUpdate:()=>IX,bulkStore:()=>kX,bulkDestroy:()=>xX,ShippingRateInputError:()=>k});import{db as u$}from"@stacksjs/database";async function MX(J){try{let $=await u$.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function xX(J){if(!J.length)return 0;try{let $=await u$.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function VX(J){try{let $=await u$.deleteFrom("shipping_rates").where("shipping_zone_id","=",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function zX(J){try{let $=await u$.deleteFrom("shipping_rates").where("shipping_method_id","=",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as v}from"@stacksjs/database";async function AX(J){let $=await v.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.shipping_zone_id)G=await v.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)X=await v.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:G,shipping_method:X}}return}async function OX(){let J=await v.selectFrom("shipping_rates").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((K)=>K.shipping_zone_id).filter((K)=>K!==null&&K!==void 0))],G=[...new Set(J.map((K)=>K.shipping_method_id).filter((K)=>K!==null&&K!==void 0))],[X,Z]=await Promise.all([$.length?v.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],G.length?v.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),Y=X.reduce((K,W)=>{return K[W.id]=W,K},{}),L=Z.reduce((K,W)=>{return K[W.id]=W,K},{});return J.map((K)=>({...K,shipping_zone:K.shipping_zone_id?Y[K.shipping_zone_id]:[],shipping_method:K.shipping_method_id?L[K.shipping_method_id]:[]}))}async function _X(J){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function L1(J,$){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function n$(J){if(!J?.countryCode)return null;try{let $=await v.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let G=null;for(let X of $){let Z=1;if(J.region&&X.regions&&BX(X.regions,J.region))Z=2;if(J.postalCode&&X.postal_codes&&BX(X.postal_codes,J.postalCode))Z=3;if(!G||Z>G.score)G={id:X.id,score:Z}}return G?.id??null}catch{return null}}async function RX(J,$){let G=await n$($);if(G==null)return;return L1(J,G)}async function UX(J,$){return await n$($)===J}function BX(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 PX(){try{return(await v.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function SX(J){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:jX}=globalThis.Bun;import{db as K1}from"@stacksjs/database";import{db as u0}from"@stacksjs/database";async function TX(){return await u0.selectFrom("shipping_zones").selectAll().execute()}async function i$(J){return await u0.selectFrom("shipping_zones").where("id","=",J).selectAll().executeTakeFirst()}function EX(){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 qX(){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 wX(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 k extends TypeError{constructor(J){super(J);this.name="ShippingRateInputError"}}function n0(J,$,G){return Number(J[G]??$?.[G])}async function F0(J,$){let G=n0(J,$,"shipping_method_id"),X=n0(J,$,"shipping_zone_id"),Z=n0(J,$,"weight_from"),Y=n0(J,$,"weight_to"),L=n0(J,$,"rate");if(!Number.isSafeInteger(G)||G<1)throw new k("Shipping method must be a positive integer.");if(!Number.isSafeInteger(X)||X<1)throw new k("Shipping zone must be a positive integer.");if(!Number.isFinite(Z)||Z<0)throw new k("Weight from must be a non-negative number.");if(!Number.isFinite(Y)||Y<Z)throw new k("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(L)||L<0)throw new k("Rate must be a non-negative integer in minor currency units.");let[K,W]=await Promise.all([l$(G),i$(X)]);if(!K)throw new k(`Shipping method ${G} was not found.`);if(!W)throw new k(`Shipping zone ${X} was not found.`);if(Number(W.shipping_method_id)!==G)throw new k(`Shipping zone ${X} is not assigned to shipping method ${G}.`)}async function fX(J){try{let $=i(J),G=Number($.shipping_method_id),X=Number($.shipping_zone_id);await F0($);let Z=jX(),Y={...$,shipping_method_id:G,shipping_zone_id:X,uuid:Z};await K1.insertInto("shipping_rates").values(Y).executeTakeFirst();let L=await K1.selectFrom("shipping_rates").where("uuid","=",Z).selectAll().executeTakeFirst();if(!L)throw Error("Failed to resolve created shipping rate");return L}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function kX(J){if(!J.length)return 0;try{for(let X of J){let Z=i(X);await F0(Z)}let $=J.map((X)=>({...i(X),uuid:jX()})),G=await K1.insertInto("shipping_rates").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as i0}from"@stacksjs/database";import{formatDate as o$}from"@stacksjs/orm";async function CX(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 F0(X,G);let Z=await i0.updateTable("shipping_rates").set({...X,updated_at:o$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(G){if(G instanceof k)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function IX(J){if(!J.length)return 0;try{let $=0;for(let{id:G,data:X}of J){let Z=await i0.updateTable("shipping_rates").set({...i(X),updated_at:o$(new Date)}).where("id","=",G).executeTakeFirst();if(Q(Z)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function hX(J,$){try{let G=await i0.updateTable("shipping_rates").set({...i($),updated_at:o$(new Date)}).where("shipping_zone_id","=",J).executeTakeFirst();return Q(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${G.message}`);throw G}}async function gX(J,$){try{let G=await i0.updateTable("shipping_rates").set({...i($),updated_at:o$(new Date)}).where("shipping_method_id","=",J).executeTakeFirst();return Q(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var G4={};z(G4,{startStop:()=>yX,startRoute:()=>pX,routeTrackingChannel:()=>W1,recordDriverPing:()=>DX,orderTrackingChannel:()=>r,isWithin:()=>IG,hasCoordinates:()=>m0,failStop:()=>mX,estimateSecondsRemaining:()=>h$,emitDeliveryStarted:()=>e$,emitDeliveryPosition:()=>d$,emitDeliveryNearby:()=>r$,emitDeliveryFailed:()=>J4,emitDeliveryCompleted:()=>$4,emitDeliveryAssigned:()=>a$,emitDeliveryArrived:()=>t$,distanceInMeters:()=>e,completeStop:()=>bX,broadcastToChannel:()=>o,bearingInDegrees:()=>I$,assignStop:()=>vX,NEARBY_RADIUS_METERS:()=>F1,ARRIVAL_RADIUS_METERS:()=>Q1});function r(J){return`order.${J}`}function W1(J){return`delivery-route.${J}`}async function U0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function o(J,$,G){try{let X=await import("@stacksjs/realtime").catch(()=>null);if(!X)return;let Z=X.channel;if(typeof Z!=="function")return;await Z(J).broadcast($,G,"private")}catch{}}async function d$(J,$,G){await Promise.all([...J.map((X)=>o(r(X),"delivery:position",G)),$==null?Promise.resolve():o(W1($),"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 $4(J){if(await U0("delivery:completed",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:completed",{stop:J})}async function J4(J,$){await U0("delivery:failed",{stop:J,reason:$})}var{randomUUIDv7:RZ}=globalThis.Bun;import{db as y}from"@stacksjs/database";var F1=400,Q1=60,UZ=250;async function DX(J){let $=J.recordedAt??new Date().toISOString(),G=typeof J.accuracy!=="number"||J.accuracy<=UZ,X=await y.selectFrom("drivers").where("id","=",J.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!X)throw Error(`Unknown driver: ${J.driverId}`);let Z=m0(X)?{latitude:X.latitude,longitude:X.longitude}:null,Y=typeof J.heading==="number"?J.heading:Z?I$(Z,J):null,L=await PZ(J.driverId),K=L?await SZ(L.id):null,W=null,F=null,N=!1,H=!1,M=K&&m0({latitude:K.latitude??void 0,longitude:K.longitude??void 0})?{latitude:K.latitude,longitude:K.longitude}:null;if(G&&K&&M)W=Math.round(e(J,M)),F=h$(W,J.speed??0),H=W<=Q1&&K.arrived_at==null,N=!H&&W<=F1&&K.status==="en_route"&&K.notified_nearby_at==null;let O=await TZ({driverId:J.driverId,routeId:L?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$});if(G)await y.updateTable("drivers").set({latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??0,last_ping_at:$}).where("id","=",J.driverId).execute();if(K&&(W!=null||F!=null))await y.updateTable("delivery_stops").set({eta_at:F==null?K.eta_at:new Date(Date.now()+F*1000).toISOString()}).where("id","=",K.id).execute();if(G)await d$(K?.order_id==null?[]:[K.order_id],L?.id??null,{driverId:J.driverId,routeId:L?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$,distanceToStopMeters:W,etaSeconds:F});if(N&&K)await y.updateTable("delivery_stops").set({notified_nearby_at:$}).where("id","=",K.id).execute(),await r$(K,W,F);if(H&&K)await y.updateTable("delivery_stops").set({status:"arrived",arrived_at:$}).where("id","=",K.id).execute(),await t$({...K,status:"arrived",arrived_at:$});return{pingId:O,routeId:L?.id??null,stopId:K?.id??null,distanceToStopMeters:W,etaSeconds:F,crossedNearby:N,crossedArrival:H}}async function PZ(J){return await y.selectFrom("delivery_routes").where("driver_id","=",J).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function SZ(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 TZ(J){let $=RZ();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:EZ}=globalThis.Bun;import{db as q}from"@stacksjs/database";async function vX(J){let $=EZ(),G=J.sequence??await wZ(J.deliveryRouteId);await q.insertInto("delivery_stops").values({uuid:$,delivery_route_id:J.deliveryRouteId,order_id:J.orderId??null,sequence:G,status:"pending",address:J.address,latitude:J.latitude??null,longitude:J.longitude??null,recipient_name:J.recipientName??null,recipient_phone:J.recipientPhone??null,eta_at:J.etaAt??null}).executeTakeFirst();let X=await fZ($);if(X)await a$(X);return X??{}}async function yX(J){await q.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",J).execute();let $=await H1(J);if(!$)return null;if($.order_id!=null)await N1($.order_id,"OUT_FOR_DELIVERY");return await e$($),$}async function bX(J,$){let G=new Date().toISOString();await q.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await jZ(J)?{}:{arrived_at:G},...$?{notes:$}:{}}).where("id","=",J).execute();let X=await H1(J);if(!X)return null;if(X.order_id!=null)await N1(X.order_id,"DELIVERED");return await $4(X),await lX(X.delivery_route_id),X}async function mX(J,$){await q.updateTable("delivery_stops").set({status:"failed",notes:$}).where("id","=",J).execute();let G=await H1(J);if(!G)return null;if(G.order_id!=null)await N1(G.order_id,"SHIPPED");return await J4(G,$),await lX(G.delivery_route_id),G}async function pX(J){await q.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",J).execute()}async function lX(J){if(J==null)return;if(await q.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let G=await q.selectFrom("delivery_routes").where("id","=",J).select(["driver_id"]).executeTakeFirst();if(await q.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",J).execute(),G?.driver_id!=null)await q.updateTable("drivers").set({status:"active"}).where("id","=",G.driver_id).execute()}async function N1(J,$){let G=await q.selectFrom("orders").where("id","=",J).select(["id","status"]).executeTakeFirst();if(!G)return;let X=await Promise.resolve().then(() => (x0(),VJ)),{canTransition:Z,emitForStatus:Y}=X,L=qZ(G.status,$,Z);if(L.length===0){let{log:K}=await import("@stacksjs/logging").catch(()=>({log:null}));K?.warn(`[delivery] refused to move order ${J} from ${G.status} to ${$}: no legal transition`);return}for(let K of L)await q.updateTable("orders").set({status:K}).where("id","=",J).execute(),await Y(K,{...G,status:K})}function qZ(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 wZ(J){return(await q.selectFrom("delivery_stops").where("delivery_route_id","=",J).select(["sequence"]).execute()).reduce((G,X)=>Math.max(G,X.sequence??0),0)+1}async function jZ(J){return(await q.selectFrom("delivery_stops").where("id","=",J).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function H1(J){return await q.selectFrom("delivery_stops").where("id","=",J).selectAll().executeTakeFirst()??null}async function fZ(J){return await q.selectFrom("delivery_stops").where("uuid","=",J).selectAll().executeTakeFirst()??null}var L4={};z(L4,{updateStatus:()=>eX,updateRegionsAndPostalCodes:()=>tX,updateCountries:()=>rX,update:()=>aX,store:()=>sX,softDelete:()=>uX,getZonesByCountry:()=>wX,getActiveShippingZones:()=>qX,formatZoneOptions:()=>EX,fetchById:()=>i$,fetchAll:()=>TX,destroy:()=>cX,bulkStore:()=>dX,bulkSoftDelete:()=>iX,bulkDestroy:()=>nX});import{db as X4}from"@stacksjs/database";async function cX(J){try{let $=await X4.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function uX(J){try{let $=await X4.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function nX(J){if(!J.length)return 0;try{let $=await X4.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function iX(J){if(!J.length)return 0;try{let $=await X4.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:oX}=globalThis.Bun;import{db as M1}from"@stacksjs/database";async function sX(J){try{let $=oX(),G={...D0(J),uuid:$};await M1.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await M1.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 dX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...D0(X),uuid:oX()})),G=await M1.insertInto("shipping_zones").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as Z4}from"@stacksjs/database";import{formatDate as Y4}from"@stacksjs/orm";async function aX(J,$){try{if(!J)throw Error("Shipping zone ID is required for update");let G=await Z4.updateTable("shipping_zones").set({...D0($),updated_at:Y4(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 eX(J,$){try{let G=await Z4.updateTable("shipping_zones").set({status:$,updated_at:Y4(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 rX(J,$){try{let G=await Z4.updateTable("shipping_zones").set({countries:$,updated_at:Y4(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 tX(J,$,G){try{let X={updated_at:Y4(new Date)};if($!==void 0)X.regions=$;if(G!==void 0)X.postal_codes=G;let Z=await Z4.updateTable("shipping_zones").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update regions and postal codes");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${X.message}`);throw X}}var kZ={digital:f$,drivers:C$,geocoding:D$,licenses:b$,methods:c$,rates:s$,routes:w$,tracking:G4,zones:L4},CZ=kZ;var B1={};z(B1,{updateStatus:()=>H9,updateRate:()=>M9,updateDefaultStatus:()=>x9,update:()=>N9,taxFor:()=>$9,store:()=>F9,fetchById:()=>Y9,fetchAll:()=>L9,destroy:()=>G9,bulkStore:()=>Q9,bulkDestroy:()=>X9,breakdownFor:()=>z1,activeTaxRates:()=>V1});import{db as IZ}from"@stacksjs/database";function hZ(J){let $=Number(J);return Number.isFinite($)?$/100:0}async function V1(J={}){let $=IZ.selectFrom("tax_rates").where("status","=","active").selectAll();if(J.country)$=$.where("country","=",J.country);let G=await $.execute();if(!J.codes?.length)return G;let X=new Set(J.codes);return G.filter((Z)=>X.has(String(Z.code??"")))}function z1(J,$,G={}){let X=Math.max(0,Math.round(J)),Z=[],Y=0,L=0;for(let K of $){let W=hZ(K.rate),F=Math.round(X*W),N=Boolean(G.exempt&&K.exemptible);if(N)L+=F;else Y+=F;Z.push({id:Number(K.id),code:String(K.code??""),name:String(K.name??""),rate:W,amount:N?0:F,exempted:N})}return{taxable:X,components:Z,tax:Y,exempted:L}}async function $9(J,$={}){return z1(J,await V1($),$)}import{db as J9}from"@stacksjs/database";async function G9(J){try{let $=await J9.deleteFrom("tax_rates").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function X9(J){if(!J.length)return 0;try{let $=await J9.deleteFrom("tax_rates").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as Z9}from"@stacksjs/database";async function Y9(J){return await Z9.selectFrom("tax_rates").where("id","=",J).selectAll().executeTakeFirst()}async function L9(){return await Z9.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:K9}=globalThis.Bun;import{db as W9}from"@stacksjs/database";async function F9(J){try{return await W9.transaction(async($)=>{let G={...J,uuid:K9()};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 Q9(J){if(!J.length)return 0;try{return await W9.transaction(async($)=>{let G=0;for(let X of J){let Z={...X,uuid:K9()};if(Z.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(Z).executeTakeFirst())G++}return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as K4}from"@stacksjs/database";import{formatDate as W4}from"@stacksjs/orm";async function N9(J,$){try{if(!J)throw Error("Tax rate ID is required for update");return await K4.transaction(async(G)=>{let X=await G.selectFrom("tax_rates").select("is_default").where("id","=",J).executeTakeFirst();if(!X)return;let Z=$.is_default??Boolean(X.is_default),Y=W4(new Date);if(Z)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Y}).where("id","!=",J).execute();let L=await G.updateTable("tax_rates").set({...$,updated_at:Y}).where("id","=",J).returningAll().executeTakeFirst();if(!L)return;return L})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function H9(J,$){try{let G=await K4.updateTable("tax_rates").set({status:$,updated_at:W4(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 M9(J,$){try{let G=await K4.updateTable("tax_rates").set({rate:$,updated_at:W4(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 x9(J,$){try{return await K4.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",J).executeTakeFirst())return!1;let Z=W4(new Date);if($)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Z}).where("id","!=",J).execute();return await G.updateTable("tax_rates").set({is_default:$,updated_at:Z}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var P1={};z(P1,{restaurant:()=>S0,products:()=>Q4,default:()=>uZ});var Q4={};z(Q4,{updateStatus:()=>h9,updatePartySize:()=>g9,update:()=>F4,store:()=>C9,fetchWaiting:()=>T9,fetchPurchasedBetweenDates:()=>P9,fetchNotifiedBetweenDates:()=>U9,fetchCountByStatus:()=>E9,fetchCountBySource:()=>A9,fetchCountByQuantity:()=>_9,fetchCountByDateGrouped:()=>j9,fetchCountByDate:()=>O9,fetchCountByAllQuantities:()=>R9,fetchCountBetweenDates:()=>w9,fetchConversionRates:()=>q9,fetchCancelledBetweenDates:()=>S9,fetchById:()=>o0,fetchAll:()=>B9,destroy:()=>V9,bulkStore:()=>I9,bulkDestroy:()=>z9});import{db as A1}from"@stacksjs/database";async function V9(J){try{let $=await A1.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await A1.deleteFrom("waitlist_products").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function z9(J){if(!J.length)return 0;try{let $=await A1.deleteFrom("waitlist_products").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as T}from"@stacksjs/orm";async function o0(J){return await A.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function B9(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function A9(J,$){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(J&&$){let Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{source:Y,count:L})=>{return Z[Y]=L,Z},{})}async function O9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=T($),Z=T(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function _9(J){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",J).executeTakeFirst())?.count??0}async function R9(J,$){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(J&&$){let Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{quantity:Y,count:L})=>{return Z[Y]=L,Z},{})}async function U9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",X).whereNotNull("notified_at").execute()}async function P9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",X).whereNotNull("purchased_at").execute()}async function S9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",X).whereNotNull("cancelled_at").execute()}async function T9(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function E9(J,$,G){let X=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",J);if($&&G){let Y=T($),L=T(G);X=X.where("created_at",">=",Y).where("created_at","<=",L)}return(await X.executeTakeFirst())?.count??0}async function q9(J,$){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(J&&$){let W=T(J),F=T($);G=G.where("created_at",">=",W).where("created_at","<=",F)}let X=await G.execute(),Z=X.reduce((W,{count:F})=>W+F,0),Y=X.find((W)=>W.status==="purchased")?.count??0,L=Z>0?Y/Z*100:0,K=X.reduce((W,{status:F,count:N})=>{return W[F]={count:N,percentage:Z>0?N/Z*100:0},W},{});return{totalConversionRate:L,statusBreakdown:K}}async function w9(J,$){let G=T(J),X=T($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function j9(J,$){let G=A.selectFrom("waitlist_products").select(["created_at"]);if(J&&$){let Y=T(J),L=T($);G=G.where("created_at",">=",Y).where("created_at","<=",L)}let Z=(await G.execute()).reduce((Y,{created_at:L})=>{let K=(L||"").split("T")[0]||"unknown";return Y[K]=(Y[K]||0)+1,Y},{});return Object.entries(Z).map(([Y,L])=>({date:Y,count:L})).sort((Y,L)=>Y.date.localeCompare(L.date))}var{randomUUIDv7:k9}=globalThis.Bun;import{db as O1}from"@stacksjs/database";import{formatDate as f9}from"@stacksjs/orm";var gZ={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function DZ(J){return typeof J==="number"||J instanceof Date?f9(J):J}function s0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,Z])=>Z!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let Z of["notified_at","purchased_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=DZ(G[Z]);let X=gZ[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=f9(new Date);return G}async function C9(J){try{let $=k9(),G={...s0(J),uuid:$,status:J.status||"waiting"};await O1.insertInto("waitlist_products").values(G).executeTakeFirst();let X=await O1.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 I9(J){if(!J.length)return 0;try{let $=J.map((X)=>({...s0(X),status:X.status||"waiting",uuid:k9()})),G=await O1.insertInto("waitlist_products").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as vZ}from"@stacksjs/database";import{formatDate as yZ}from"@stacksjs/orm";async function F4(J,$){try{if(!J)throw Error("Waitlist product ID is required for update");let G=await o0(J);if(!G)return;await vZ.updateTable("waitlist_products").set({...s0($,G),updated_at:yZ(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 h9(J,$){return await F4(J,{status:$})}async function g9(J,$){return await F4(J,{quantity:$})}var S0={};z(S0,{updateWaitTimes:()=>K3,updateStatus:()=>Y3,updateQueuePosition:()=>W3,updatePartySize:()=>L3,update:()=>P0,store:()=>X3,fetchWaitingWithQuotedTimes:()=>s9,fetchWaitingWithPartySizes:()=>d9,fetchWaiting:()=>n9,fetchTimeSeriesStats:()=>J3,fetchTablesTurnedToday:()=>a9,fetchSeatingRate:()=>e9,fetchSeatedStats:()=>$3,fetchSeatedBetweenDates:()=>u9,fetchNoShowStats:()=>r9,fetchCurrentWaitTimes:()=>t9,fetchCountByTablePreference:()=>b9,fetchCountByPartySize:()=>p9,fetchCountByDate:()=>m9,fetchCountByAllPartySizes:()=>l9,fetchConversionRates:()=>i9,fetchById:()=>d0,fetchBetweenDates:()=>c9,fetchAverageWaitTimes:()=>o9,fetchAll:()=>y9,destroy:()=>D9,bulkStore:()=>Z3,bulkDestroy:()=>v9});import{db as _1}from"@stacksjs/database";async function D9(J){try{let $=await _1.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await _1.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function v9(J){if(!J.length)return 0;try{let $=await _1.deleteFrom("waitlist_restaurants").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as V}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function d0(J){return await V.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function y9(){return await V.selectFrom("waitlist_restaurants").selectAll().execute()}async function b9(){return(await V.selectFrom("waitlist_restaurants").select(["table_preference",V.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:G,count:X})=>{return $[G]=X,$},{})}async function m9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),Z=g(G);return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function p9(J){return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function l9(){return(await V.selectFrom("waitlist_restaurants").select(["party_size",V.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:G,count:X})=>{return $[G]=X,$},{})}async function c9(J,$){let G=g(J),X=g($);return await V.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",X).execute()}async function u9(J,$){let G=g(J),X=g($);return await V.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",X).where("status","=","seated").execute()}async function n9(){return await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function i9(){let J=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),$=J.reduce((Y,{count:L})=>Y+L,0),G=J.find((Y)=>Y.status==="seated")?.count??0,X=$>0?Number(G)/$*100:0,Z=J.reduce((Y,{status:L,count:K})=>{return Y[L]={count:K,percentage:$>0?K/$*100:0},Y},{});return{totalConversionRate:X,statusBreakdown:Z}}async function o9(){let J=await V.selectFrom("waitlist_restaurants").select([V.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),V.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 s9(){let J=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((X,Z)=>X+(Z.quoted_wait_time??0),0),G=J.length>0?$/J.length:0;return{entries:J,totalQuotedWaitTime:$,averageQuotedWaitTime:G}}async function d9(){let J=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((Z,Y)=>Z+Y.party_size,0),G=J.length>0?$/J.length:0,X=J.reduce((Z,Y)=>{return Z[Y.party_size]=(Z[Y.party_size]||0)+1,Z},{});return{entries:J,totalPartySize:$,averagePartySize:G,partySizeBreakdown:X}}async function a9(){let J=new Date,$=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),Z=g(G),Y=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",X).where("check_in_time","<=",Z).execute(),L=Y.length,K=Y.reduce((H,M)=>H+M.party_size,0),W=L>0?K/L:0,F=Y.reduce((H,M)=>{return H[M.table_preference]=(H[M.table_preference]||0)+1,H},{}),N=Y.reduce((H,M)=>{return H[M.party_size]=(H[M.party_size]||0)+1,H},{});return{totalTablesTurned:L,averagePartySize:W,totalCustomersSeated:K,breakdownByTablePreference:F,breakdownByPartySize:N}}async function e9(J,$){let G=g(J),X=g($),Z=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).where("check_in_time",">=",G).where("check_in_time","<=",X).groupBy("status").execute(),Y=Z.reduce((F,{count:N})=>F+N,0),L=Z.find((F)=>F.status==="seated")?.count??0,K=Y>0?Number(L)/Y*100:0,W=Z.reduce((F,{status:N,count:H})=>{return F[N]={count:H,percentage:Y>0?H/Y*100:0},F},{});return{totalEntries:Y,seatedEntries:L,seatingRate:K,statusBreakdown:W}}async function r9(J,$){let G=g(J),X=g($),Z=V.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",X),Y=await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",X).executeTakeFirst(),L=await Z.execute(),K=L.length,W=Y?.count&&Y.count>0?K/Y.count*100:0,F=L.reduce((_,U)=>_+(U.quoted_wait_time??0),0),N=K>0?F/K:0,H=L.reduce((_,U)=>_+U.party_size,0),M=K>0?H/K:0,O=L.reduce((_,U)=>{return _[U.table_preference]=(_[U.table_preference]||0)+1,_},{}),R=L.reduce((_,U)=>{return _[U.party_size]=(_[U.party_size]||0)+1,_},{});return{totalNoShows:K,noShowRate:W,averageQuotedWaitTime:N,averagePartySize:M,breakdownByTablePreference:O,breakdownByPartySize:R}}async function t9(){let J=await V.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=J.reduce((Z,Y)=>Z+(Y.quoted_wait_time||0),0),G=J.reduce((Z,Y)=>Z+(Y.actual_wait_time||0),0),X=J.length;return{averageQuoted:X>0?$/X:0,averageActual:X>0?G/X:0}}async function $3(){let J=Date.now()-86400000,$=await V.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),G=Array.from({length:24},(X,Z)=>({hour:Z,count:$.filter((Y)=>{return Y.seated_at===Z}).length}));return{total:$.length,byHour:G}}async function J3(){return(await V.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:G3}=globalThis.Bun;import{db as U1}from"@stacksjs/database";import{formatDate as R1}from"@stacksjs/orm";var bZ={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function mZ(J){if(typeof J==="number")return R1(J<=2147483647?J*1000:J);if(J instanceof Date)return R1(J);return J}function a0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,Z])=>Z!==void 0));for(let Z of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=mZ(G[Z]);let X=bZ[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=R1(new Date);return G}async function X3(J){try{let $=G3(),G={...a0(J),status:J.status||"waiting",uuid:$};await U1.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let X=await U1.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 Z3(J){if(!J.length)return 0;try{let $=J.map((X)=>({...a0(X),status:X.status||"waiting",uuid:G3()})),G=await U1.insertInto("waitlist_restaurants").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as pZ}from"@stacksjs/database";import{formatDate as lZ}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 pZ.updateTable("waitlist_restaurants").set({...a0($,G),updated_at:lZ(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 Y3(J,$){return await P0(J,{status:$})}async function L3(J,$){return await P0(J,{party_size:$})}async function K3(J,$,G){return await P0(J,{quoted_wait_time:$,...G===void 0?{}:{actual_wait_time:G}})}async function W3(J,$){return await P0(J,{queue_position:$})}var cZ={products:Q4,restaurant:S0},uZ=cZ;var nZ={coupons:N4,customers:H4,devices:B4,errors:_4,giftCards:U4,orders:k4,payments:C4,products:b4,receipts:n4,restaurant:S0,shippings:x1,tax:B1,waitlists:P1},j8=nZ;export{P1 as waitlists,B1 as tax,x1 as shippings,S0 as restaurant,n4 as receipts,b4 as products,C4 as payments,k4 as orders,U4 as giftCards,_4 as errors,B4 as devices,j8 as default,H4 as customers,N4 as coupons,nZ as commerce};
@@ -0,0 +1,44 @@
1
+ /** Every active rate, in the order they should be listed. */
2
+ export declare function activeTaxRates(options?: BreakdownOptions): Promise<any[]>;
3
+ /**
4
+ * Tax on `taxable` cents, itemised.
5
+ *
6
+ * Each component is rounded on its own rather than the total being rounded
7
+ * once. That is what a receipt has to show — the parts have to add up to the
8
+ * figure charged, and a single rounding at the end leaves a line that is a
9
+ * cent out from the sum above it.
10
+ *
11
+ * Every component is applied to `taxable` directly. Jurisdictions that compound
12
+ * — where one tax forms part of the base for another — need an explicit order,
13
+ * and that is a bigger claim than this should make quietly; an app that needs
14
+ * it should compose two calls.
15
+ */
16
+ export declare function breakdownFor(taxable: number, rates: any[], options?: BreakdownOptions): TaxBreakdown;
17
+ /**
18
+ * Read the active rates and apply them.
19
+ *
20
+ * The convenience form. An app that already holds the rates — a checkout
21
+ * pricing several bags, say — should fetch once and call {@link breakdownFor}
22
+ * per bag rather than querying each time.
23
+ */
24
+ export declare function taxFor(taxable: number, options?: BreakdownOptions): Promise<TaxBreakdown>;
25
+ /** One component, as it applied to this sale. */
26
+ export declare interface TaxComponent {
27
+ id: number
28
+ code: string
29
+ name: string
30
+ rate: number
31
+ amount: number
32
+ exempted: boolean
33
+ }
34
+ export declare interface TaxBreakdown {
35
+ taxable: number
36
+ components: TaxComponent[]
37
+ tax: number
38
+ exempted: number
39
+ }
40
+ export declare interface BreakdownOptions {
41
+ exempt?: boolean
42
+ codes?: string[]
43
+ country?: string
44
+ }
@@ -1,4 +1,11 @@
1
+ export type { BreakdownOptions, TaxBreakdown, TaxComponent } from './breakdown';
1
2
  export type { TaxRateWriteData } from './types';
3
+ // Functions from breakdown.ts
4
+ export {
5
+ activeTaxRates,
6
+ breakdownFor,
7
+ taxFor,
8
+ } from './breakdown';
2
9
  // Functions from destroy.ts
3
10
  export {
4
11
  bulkDestroy,
@@ -6,5 +6,7 @@ export declare interface TaxRateWriteData {
6
6
  region?: string | null
7
7
  status?: 'active' | 'inactive'
8
8
  is_default?: boolean
9
+ code?: string
10
+ exemptible?: boolean
9
11
  uuid?: string
10
12
  }
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.353",
5
+ "version": "0.70.355",
6
6
  "description": "Stacks commerce utilities.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [