@stacksjs/commerce 0.70.327 → 0.70.329
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 +8 -8
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var L3=Object.defineProperty;var N3=(J)=>J;function K3(J,$){this[J]=N3.bind(null,$)}var z=(J,$)=>{for(var G in $)L3(J,G,{get:$[G],enumerable:!0,configurable:!0,set:K3.bind($,G)})};var F3=(J,$)=>()=>(J&&($=J(J=0)),$);var J0=import.meta.require;var xJ={};z(xJ,{emitOrderShipped:()=>L$,emitOrderRefunded:()=>x0,emitOrderPaid:()=>d,emitOrderOutForDelivery:()=>HJ,emitOrderDelivered:()=>N$,emitOrderCreated:()=>q0,emitOrderCancelled:()=>H0,emitForStatus:()=>j0,canTransition:()=>w0});function w0(J,$){if(J===$)return!0;return h3[J]?.includes($)??!1}async function W0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function q0(J){await W0("order:created",{order:J})}async function d(J,$){await W0("order:paid",{order:J,payment:$})}async function L$(J){await W0("order:shipped",{order:J})}async function HJ(J){await W0("order:out_for_delivery",{order:J})}async function N$(J){await W0("order:delivered",{order:J})}async function H0(J,$){await W0("order:cancelled",{order:J,reason:$})}async function x0(J,$){await W0("order:refunded",{order:J,refundAmount:$})}async function j0(J,$){switch(J){case"PROCESSING":return d($);case"SHIPPED":return L$($);case"OUT_FOR_DELIVERY":return HJ($);case"DELIVERED":return N$($);case"CANCELLED":return H0($);case"REFUNDED":return x0($);case"PENDING":default:}}var h3;var V0=F3(()=>{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 Q1={};z(Q1,{update:()=>u4,store:()=>m4,redeem:()=>n4,getActiveCouponsMoMChange:()=>D4,fetchTopRedeemedCoupons:()=>I4,fetchStats:()=>j4,fetchRedemptionTrend:()=>g4,fetchRedemptionStats:()=>h4,fetchCouponCountsByType:()=>C4,fetchCouponCounts:()=>k4,fetchConversionRate:()=>v4,fetchById:()=>G0,fetchByCode:()=>w4,fetchAll:()=>f4,fetchActive:()=>q4,deleteExpiredCoupons:()=>S4,deleteCoupons:()=>P4,deleteCoupon:()=>U4});import{db as e0}from"@stacksjs/database";import{formatDate as Q3}from"@stacksjs/orm";function F(J){if(typeof J==="number")return Number.isFinite(J)?J:0;if(typeof J==="bigint")return Number(J);if(!J||typeof J!=="object")return 0;let $=J;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[G]!==void 0&&$[G]!==null)return F($[G]);if(Array.isArray(J))return J.reduce((G,X)=>G+F(X),0);return 0}async function U4(J){let $=await e0.deleteFrom("coupons").where("id","=",J).executeTakeFirst();return F($)>0}async function P4(J){if(!J.length)return 0;return(await e0.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function S4(){let J=Q3(new Date),$=await e0.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return F($)}import{db as V}from"@stacksjs/database";import{extractDate as T4,formatDate as E4}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=T4(new Date($.endDate));if($.startDate)$.startDate=T4(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function f4(){return(await V.selectFrom("coupons").selectAll().execute()).map(t0)}async function G0(J){let $=await V.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function w4(J){let $=await V.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function q4(){let J=E4(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map(t0)}async function j4(){let J=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).executeTakeFirst(),$=E4(new Date),G=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(V.fn.count("id").as("count")).executeTakeFirst(),X=await V.selectFrom("coupons").select(["discount_type",V.fn.count("id").as("count")]).groupBy("discount_type").execute(),W=await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),Z=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",$).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(J?.count||0),active:Number(G?.count||0),by_type:X,most_used:W,upcoming:Z}}async function k4(){let J=new Date,$=new Date(J);$.setDate(J.getDate()-7);let G=new Date(J);G.setMonth(J.getMonth()-1);let X=new Date(J);X.setFullYear(J.getFullYear()-1);let W=await r0(null,null,J),Z=await r0($,null,J),Y=await r0(G,null,J),L=await r0(X,null,J);return{week:Z,month:Y,year:L,all_time:W}}async function r0(J,$,G){let X=V.selectFrom("coupons");if(J)X=X.where("created_at",">=",J.toISOString());if($)X=X.where("created_at","<=",$.toISOString());let W=await X.select(V.fn.count("id").as("count")).executeTakeFirst(),Z=V.selectFrom("coupons");if(J)Z=Z.where("created_at",">=",J.toISOString());if($)Z=Z.where("created_at","<=",$.toISOString());Z=Z.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let Y=await Z.select(V.fn.count("id").as("count")).executeTakeFirst(),L=Number(W?.count||0),N=Number(Y?.count||0),K=L-N;return{total:L,active:N,inactive:K}}async function C4(){let J=new Date,$=await V.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:X}of $){let W=await V.selectFrom("coupons").where("discount_type","=",X).select(V.fn.count("id").as("count")).executeTakeFirst(),Z=await V.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(V.fn.count("id").as("count")).executeTakeFirst(),Y=Number(W?.count||0),L=Number(Z?.count||0);G[X]={total:Y,active:L,inactive:Y-L}}return G}async function h4(){let J=await V.selectFrom("coupons").select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,G=new Date($);G.setDate($.getDate()-7);let X=new Date($);X.setMonth($.getMonth()-1);let W=new Date($);W.setFullYear($.getFullYear()-1);let Z=await V.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await V.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await V.selectFrom("coupons").where("updated_at",">=",W.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),N=await V.selectFrom("coupons").select(["discount_type",V.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),K={};return N.forEach((Q)=>{K[Q.discount_type]=Number(Q.total||0)}),{total:Number(J?.total||0),week:Number(Z?.total||0),month:Number(Y?.total||0),year:Number(L?.total||0),by_type:K}}async function I4(J=5){return await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(J).execute()}async function g4(J=30){let $=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-J);let X=await V.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),W={};return X.forEach((Z)=>{let Y=Z.updated_at?new Date(Z.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!W[Y])W[Y]=0;W[Y]+=Z?.usage_count||0}),Object.entries(W).map(([Z,Y])=>({date:Z,count:Y}))}async function v4(){let J=new Date,$=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(V.fn.count("id").as("count")).executeTakeFirst(),G=await V.selectFrom("coupons").where("usage_count",">",0).select(V.fn.count("id").as("count")).executeTakeFirst(),X=Number($?.count||0),W=Number(G?.count||0);return{rate:X>0?W/X*100:0,total_active:X,total_redeemed:W}}async function D4(){let J=new Date,$=new Date(J.getFullYear(),J.getMonth(),1),G=new Date(J.getFullYear(),J.getMonth()-1,1),X=new Date(J.getFullYear(),J.getMonth(),0),W=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),Z=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",G).executeTakeFirst(),Y=Number(W?.count||0),L=Number(Z?.count||0),N=Y-L,K=L!==0?N/L*100:Y>0?100:0;return{current_month:Y,previous_month:L,difference:N,percentage_change:K}}var{randomUUIDv7:x3}=globalThis.Bun;import{db as y4}from"@stacksjs/database";import{HttpError as b4}from"@stacksjs/error-handling";import{isUniqueViolation as V3}from"@stacksjs/orm";async function m4(J){try{let $=x3();return await y4.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await y4.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof b4)throw $;if(V3($))throw new b4(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as l4}from"@stacksjs/database";import{HttpError as p4}from"@stacksjs/error-handling";import{formatDate as c4,isUniqueViolation as M3}from"@stacksjs/orm";async function u4(J,$){if(!await G0(J))return;try{return await l4.updateTable("coupons").set({...$,updated_at:c4(new Date)}).where("id","=",J).execute(),await G0(J)}catch(X){if(X instanceof p4)throw X;if(M3(X))throw new p4(409,"A coupon with this code already exists");if(X instanceof Error)throw Error(`Failed to update coupon: ${X.message}`);throw X}}async function n4(J){let $=c4(new Date),G=await l4.unsafe(`UPDATE coupons
|
|
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 xJ={};z(xJ,{emitOrderShipped:()=>K$,emitOrderRefunded:()=>x0,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 x0(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 x0($);case"PENDING":default:}}var h3;var M0=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 M}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 M.selectFrom("coupons").selectAll().execute()).map(t0)}async function G0(J){let $=await M.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function w1(J){let $=await M.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function f1(){let J=E1(new Date);return(await M.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map(t0)}async function j1(){let J=await M.selectFrom("coupons").select(M.fn.count("id").as("count")).executeTakeFirst(),$=E1(new Date),G=await M.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(M.fn.count("id").as("count")).executeTakeFirst(),X=await M.selectFrom("coupons").select(["discount_type",M.fn.count("id").as("count")]).groupBy("discount_type").execute(),Z=await M.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),Y=await M.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=M.selectFrom("coupons");if(J)X=X.where("created_at",">=",J.toISOString());if($)X=X.where("created_at","<=",$.toISOString());let Z=await X.select(M.fn.count("id").as("count")).executeTakeFirst(),Y=M.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(M.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 M.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:X}of $){let Z=await M.selectFrom("coupons").where("discount_type","=",X).select(M.fn.count("id").as("count")).executeTakeFirst(),Y=await M.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(M.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 M.selectFrom("coupons").select(M.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 M.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(M.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await M.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(M.fn.sum("usage_count").as("total")).executeTakeFirst(),K=await M.selectFrom("coupons").where("updated_at",">=",Z.toISOString()).select(M.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await M.selectFrom("coupons").select(["discount_type",M.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 M.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 M.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 M.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(M.fn.count("id").as("count")).executeTakeFirst(),G=await M.selectFrom("coupons").where("usage_count",">",0).select(M.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 M.selectFrom("coupons").select(M.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),Y=await M.selectFrom("coupons").select(M.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:x3}=globalThis.Bun;import{db as y1}from"@stacksjs/database";import{HttpError as b1}from"@stacksjs/error-handling";import{isUniqueViolation as M3}from"@stacksjs/orm";async function m1(J){try{let $=x3();return await y1.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await y1.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof b1)throw $;if(M3($))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
|
|
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 N=await G0(J);if(N)return{ok:!0,coupon:N};return{ok:!1,reason:"not-found"}}let Z=await G0(J);if(!Z)return{ok:!1,reason:"not-found"};if(!Z.isActive)return{ok:!1,reason:"inactive"};let Y=!Z.startDate||Z.startDate<=$,L=!Z.endDate||Z.endDate>=$;if(!Y||!L)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var H1={};z(H1,{update:()=>$7,store:()=>r4,fetchById:()=>$$,fetchAll:()=>a4,destroy:()=>o4,bulkDestroy:()=>s4});import{db as i4}from"@stacksjs/database";async function o4(J){try{let $=await i4.deleteFrom("customers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function s4(J){if(!J.length)return 0;try{let $=await i4.deleteFrom("customers").where("id","in",J).executeTakeFirst();return F($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as d4}from"@stacksjs/database";async function $$(J){return await d4.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function a4(){return await d4.selectFrom("customers").selectAll().execute()}import{db as z3}from"@stacksjs/database";import{HttpError as e4}from"@stacksjs/error-handling";import{isUniqueViolation as B3}from"@stacksjs/orm";async function r4(J){try{let $={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await 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 e4)throw $;if(B3($))throw new e4(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as A3}from"@stacksjs/database";import{HttpError as t4}from"@stacksjs/error-handling";import{formatDate as _3,isUniqueViolation as O3}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:_3(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof t4)throw G;if(O3(G))throw new t4(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var B1={};z(B1,{updateStatus:()=>B7,updatePrintCount:()=>A7,update:()=>z7,storePrintDevicesExport:()=>H7,store:()=>V7,getPrinterStatusCounts:()=>F7,fetchErrorsByDeviceId:()=>N7,fetchById:()=>l,fetchAll:()=>J$,exportPrintDevices:()=>G$,downloadPrintDevices:()=>Q7,destroy:()=>G7,countTotalPrints:()=>Z7,countPrintsByDeviceId:()=>Y7,countAll:()=>W7,calculatePrinterHealth:()=>K7,calculateErrorRate:()=>L7,bulkStore:()=>M7,bulkDestroy:()=>X7});import{db as J7}from"@stacksjs/database";async function G7(J){try{let $=await J7.deleteFrom("print_devices").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function X7(J){if(!J.length)return 0;try{let $=await J7.deleteFrom("print_devices").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as 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 W7(){let J=await w.selectFrom("print_devices").select(w.fn.count("id").as("count")).executeTakeFirst();return Number(J?.count||0)}async function Z7(){let J=await w.selectFrom("print_devices").select(w.fn.sum("print_count").as("total")).executeTakeFirst();return Number(J?.total||0)}async function Y7(J){return(await w.selectFrom("print_devices").select("print_count").where("id","=",J).executeTakeFirst())?.print_count??0}async function L7(){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 N7(J){return await w.selectFrom("receipts").where("print_device_id","=",J).where("status","=","failed").selectAll().execute()}async function K7(){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 F7(){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 x1(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,x1(X,"macAddress","mac_address"),X.location,X.terminal,X.status,U3(x1(X,"lastPing","last_ping")).toLocaleString(),x1(X,"printCount","print_count")]});return{headings:$,data:G}}async function Q7(J="csv",$){let G=await G$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function H7(J="csv",$){let G=await G$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}var{randomUUIDv7:x7}=globalThis.Bun;import{db as V1}from"@stacksjs/database";async function V7(J){try{let $=x7(),G={last_ping:0,print_count:0,...J,uuid:$};return await V1.insertInto("print_devices").values(G).executeTakeFirst(),await V1.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function M7(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={last_ping:0,print_count:0,...G,uuid:x7()};await V1.insertInto("print_devices").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as M1}from"@stacksjs/database";import{formatDate as z1}from"@stacksjs/orm";async function z7(J,$){if(!await l(J))return;try{return await M1.updateTable("print_devices").set({...$,updated_at:z1(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device: ${X.message}`);throw X}}async function B7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await M1.updateTable("print_devices").set({status:$,updated_at:z1(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device status: ${X.message}`);throw X}}async function A7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await M1.updateTable("print_devices").set({print_count:$,updated_at:z1(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print count: ${X.message}`);throw X}}var O1={};z(O1,{update:()=>f7,unresolveGroup:()=>k7,resolveGroup:()=>q7,ignoreGroup:()=>j7,fetchTimeline:()=>E7,fetchStats:()=>T7,fetchGrouped:()=>P7,fetchById:()=>U7,fetchByGroup:()=>S7,fetchAll:()=>W$,destroyGroup:()=>R7,destroy:()=>_7,bulkUpdateStatus:()=>w7,bulkDestroy:()=>O7});import{db as A1}from"@stacksjs/database";import{log as _1}from"@stacksjs/logging";async function _7(J){try{return await A1.deleteFrom("errors").where("id","=",J).execute(),!0}catch($){return _1.error("[commerce/errors] destroy failed",{id:J,error:$}),!1}}async function O7(J){try{return await A1.deleteFrom("errors").where("id","in",J).execute(),!0}catch($){return _1.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:$}),!1}}async function R7(J,$){try{return await A1.deleteFrom("errors").where("type","=",J).where("message","=",$).execute(),!0}catch(G){return _1.error("[commerce/errors] destroyGroup failed",{type:J,message:$,error:G}),!1}}import{db as X$}from"@stacksjs/database";async function U7(J){return await X$.selectFrom("errors").where("id","=",J).selectAll().executeTakeFirst()}async function W$(){return await X$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function P7(){let J=await X$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let X of J){let W=`${X.type}:${X.message}`;if(!$.has(W))$.set(W,{errors:[],firstSeen:new Date(X.created_at),lastSeen:new Date(X.created_at)});let Z=$.get(W);Z.errors.push(X);let Y=new Date(X.created_at);if(Y<Z.firstSeen)Z.firstSeen=Y;if(Y>Z.lastSeen)Z.lastSeen=Y}let G=[];for(let[X,W]of $){let Z=W.errors[0];if(!Z)continue;let Y=W.errors.find((N)=>N.status!==null)?.status,L="unresolved";if(Y===1)L="resolved";else if(Y===2)L="ignored";G.push({id:Z.id,type:Z.type,message:Z.message,stack:Z.stack,status:L,count:W.errors.length,first_seen:W.firstSeen.toISOString(),last_seen:W.lastSeen.toISOString(),error_ids:W.errors.map((N)=>N.id)})}return G.sort((X,W)=>new Date(W.last_seen).getTime()-new Date(X.last_seen).getTime()),G}async function S7(J,$){return await X$.selectFrom("errors").where("type","=",J).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function T7(){let J=await W$(),$=new Date,G=new Date($.getTime()-86400000),X=new Date($.getTime()-172800000),W=J.filter((L)=>new Date(L.created_at)>=G).length,Z=J.filter((L)=>{let N=new Date(L.created_at);return N>=X&&N<G}).length,Y=Z===0?W>0?100:0:Math.round((W-Z)/Z*100);return{total:J.length,unresolved:J.filter((L)=>L.status===null||L.status===0).length,resolved:J.filter((L)=>L.status===1).length,ignored:J.filter((L)=>L.status===2).length,last_24h:W,trend:Y}}async function E7(){let J=await W$(),$=new Date,G=[];for(let X=23;X>=0;X--){let W=new Date($.getTime()-X*60*60*1000);W.setMinutes(0,0,0);let Z=new Date(W.getTime()+3600000),Y=J.filter((L)=>{let N=new Date(L.created_at);return N>=W&&N<Z}).length;G.push({hour:W.toISOString(),count:Y})}return G}import{db as T0}from"@stacksjs/database";import{sql as E0}from"@stacksjs/database";import{log as f0}from"@stacksjs/logging";async function f7(J,$){try{return await T0.updateTable("errors").set({...$,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(G){return f0.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 f0.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:$,error:G}),!1}}async function q7(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 f0.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 f0.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 f0.error("[commerce/errors] unresolveGroup failed",{type:J,message:$,error:G}),!1}}var U1={};z(U1,{updateBalance:()=>a7,update:()=>d7,store:()=>n7,fetchTotalValue:()=>y7,fetchTotalCurrentBalance:()=>b7,fetchStats:()=>I7,fetchById:()=>X0,fetchByCode:()=>R1,fetchAll:()=>C7,fetchActive:()=>h7,destroy:()=>p7,compareActiveGiftCards:()=>v7,checkBalance:()=>g7,calculateGiftCardValues:()=>D7,bulkDestroy:()=>l7});import{db as m7}from"@stacksjs/database";import{formatDate as MY}from"@stacksjs/orm";import{db as P,sql as C}from"@stacksjs/database";import{formatDate as s,toTimestamp as Q0}from"@stacksjs/orm";import{aggregateFunctions as 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(([Y,L])=>{let N=L.column??"id",K=S3[L.kind](N);if(L.filter)K=K.filterWhere(L.filter.column,L.filter.op,L.filter.value);return K.as(Y)}));let W=await X.executeTakeFirst(),Z={};for(let Y of Object.keys($)){let L=W?.[Y];Z[Y]=typeof L==="number"?L:Number(L??0)||0}return Z}async function C7(){return await P.selectFrom("gift_cards").selectAll().execute()}async function X0(J){return await P.selectFrom("gift_cards").where("id","=",J).selectAll().executeTakeFirst()}async function R1(J){return await P.selectFrom("gift_cards").where("code","=",J).selectAll().executeTakeFirst()}async function h7(){return await P.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function I7(){let{count:J}=await I("gift_cards",{count:{kind:"count"}}),$=Q0(new Date),G=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal($)} OR expiry_date IS NULL)`).select(P.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("gift_cards").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute(),{count:W}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:Z}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:Y}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance > 0.75`)),L=new Date;L.setDate(L.getDate()+30);let N=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",Q0(L)).where("expiry_date",">=",$).selectAll().limit(5).execute(),K=await P.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:J,active:Number(G?.count||0),by_status:X.map((Q)=>({status:Q.status,count:Number(Q.count)})),by_balance:{low:W,medium:Z,high:Y},expiring_soon:N,recently_used:K}}async function g7(J){let $=await R1(J);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function v7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let W=new Date(X);W.setDate(X.getDate()-J);let Z=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(Q0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),Y=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(Q0(W))} OR expiry_date IS NULL)`).where("created_at",">=",s(W)).where("created_at","<=",s(X)).executeTakeFirst(),L=Number(Z?.count||0),N=Number(Y?.count||0),K=L-N,Q=N!==0?K/N*100:L>0?100:0;return{current_period:L,previous_period:N,difference:K,percentage_change:Q,days_range:J}}async function D7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let W=new Date(X);W.setDate(X.getDate()-J);let Z=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(Q0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),Y=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(Q0(W))} OR expiry_date IS NULL)`).where("created_at",">=",s(W)).where("created_at","<=",s(X)).executeTakeFirst(),L=Number(Z?.total_initial||0),N=Number(Z?.total_balance||0),K=Number(Z?.card_count||0),Q=Number(Y?.total_initial||0),H=Number(Y?.total_balance||0),x=Number(Y?.card_count||0),_=L>0?(L-N)/L*100:0,R=Q>0?(Q-H)/Q*100:0,O=K>0?L/K:0,U=K>0?N/K:0,m=L-Q,t=N-H,$0=K-x,F0=Q!==0?m/Q*100:L>0?100:0,p=H!==0?t/H*100:N>0?100:0,Y3=x!==0?$0/x*100:K>0?100:0;return{current_period:{total_initial_value:L,total_remaining_balance:N,utilization_rate:_,card_count:K,average_initial_value:O,average_remaining_balance:U},previous_period:{total_initial_value:Q,total_remaining_balance:H,utilization_rate:R,card_count:x},comparison:{initial_value:{difference:m,percentage:Math.abs(F0),is_increase:m>=0},balance:{difference:t,percentage:Math.abs(p),is_increase:t>=0},card_count:{difference:$0,percentage:Math.abs(Y3),is_increase:$0>=0}},days_range:J}}async function y7(){let{total_value:J}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:J}}async function b7(){let{total_balance:J}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:J}}async function p7(J){let $=await m7.deleteFrom("gift_cards").where("id","=",J).executeTakeFirst();return F($)>0}async function l7(J){if(!J.length)return 0;let $=await m7.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return F($)}var{randomUUIDv7:E3}=globalThis.Bun;import{db as c7}from"@stacksjs/database";import{HttpError as u7}from"@stacksjs/error-handling";import{isUniqueViolation as f3}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(),W=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if(W)return await c7.selectFrom("gift_cards").where("id","=",W).selectAll().executeTakeFirst();return}catch(X){if(X instanceof u7)throw X;if(f3(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:()=>$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:()=>M7,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 x4(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,x4(X,"macAddress","mac_address"),X.location,X.terminal,X.status,U3(x4(X,"lastPing","last_ping")).toLocaleString(),x4(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:x7}=globalThis.Bun;import{db as M4}from"@stacksjs/database";async function M7(J){try{let $=x7(),G={last_ping:0,print_count:0,...J,uuid:$};return await M4.insertInto("print_devices").values(G).executeTakeFirst(),await M4.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:x7()};await M4.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),x=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-x,Q0=N!==0?m/N*100:K>0?100:0,p=H!==0?t/H*100:W>0?100:0,L3=x!==0?$0/x*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:x},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
|
|
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 L3=Object.defineProperty;var N3=(J)=>J;function K3(J,$){this[J]=N3.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,$]),
|
|
17
|
-
SET inventory_count = inventory_count + ${
|
|
18
|
-
updated_at = ${
|
|
19
|
-
WHERE id = ${
|
|
20
|
-
AND inventory_count + ${W(4)} >= 0`,parameters:[G,X,$,G]}}async function VJ(J,$,G,X){let W=v3(g3.DB_CONNECTION||"sqlite",$,G,X),Z=await J.unsafe(W.query,W.parameters),Y=typeof Z?.execute==="function"?await Z.execute():Z;return F(Y)}var BJ=!1;function AJ(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function F$(J){try{let $=await K$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await K$.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(AJ($)){if(!BJ)BJ=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw $}}async function _J(J){if(J.idempotencyKey){let $=await F$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await K$.transaction(async(G)=>{let X=D3(new Date),W=MJ(),Z={...J.order,status:J.order.status||"PENDING",uuid:W,created_at:X,updated_at:X};await G.insertInto("orders").values(Z).executeTakeFirst();let Y=await G.selectFrom("orders").where("uuid","=",W).selectAll().executeTakeFirst(),L=Number(Y?.id);if(!Number.isSafeInteger(L)||L<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let N;if(J.items&&J.items.length>0){let H=J.items.map((x)=>{if(!Number.isInteger(x.productId)||x.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(x.quantity)||x.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(x.price)||x.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:L,product_id:x.productId,quantity:x.quantity,price:x.price,special_instructions:x.specialInstructions||null,created_at:X,updated_at:X}});await G.insertInto("order_items").values(H).execute(),N=await G.selectFrom("order_items").where("order_id","=",L).selectAll().execute()}let K;if(J.payment)try{let H=MJ();if(await G.insertInto("payments").values({...J.payment,order_id:L,uuid:H,created_at:X,updated_at:X}).executeTakeFirst(),K=await G.selectFrom("payments").where("uuid","=",H).selectAll().executeTakeFirst(),!K)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(H){if(zJ(H))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(H,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(J.inventory&&J.inventory.length>0)for(let H=0;H<J.inventory.length;H++){let{id:x,delta:_}=J.inventory[H];if(!Number.isFinite(_)||_===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await VJ(G,x,_,X))throw Object.assign(Error(`inventory adjust failed for product ${x}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:L,created_at:X}).execute()}catch(H){if(zJ(H))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!AJ(H))throw H}let Q=await G.selectFrom("orders").where("id","=",L).selectAll().executeTakeFirst();if(!Q)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:Q,items:N,payment:K}});if(q0($.order),$.payment)d($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&J.idempotencyKey){let G=await F$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}V0();import{db as P1}from"@stacksjs/database";import{formatDate as S1}from"@stacksjs/orm";V0();async function OJ(J,$){if(!await c(J))return;try{return await P1.updateTable("orders").set({...$,updated_at:S1(new Date)}).where("id","=",J).execute(),await c(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order: ${X.message}`);throw X}}async function RJ(J,$){let G=await c(J);if(!G)throw Error(`Order with ID ${J} not found`);let X=G.status??"PENDING";if(!w0(X,$))throw Error(`[commerce/orders] illegal status transition ${X} \u2192 ${$}`);try{await P1.updateTable("orders").set({status:$,updated_at:S1(new Date)}).where("id","=",J).execute();let W=await c(J);if(W)j0($,W);return W}catch(W){if(W instanceof Error)throw TypeError(`Failed to update order status: ${W.message}`);throw W}}async function UJ(J,$,G){let X=await c(J);if(!X)throw Error(`Order with ID ${J} not found`);let W={updated_at:S1(new Date)};if($!==void 0)W.delivery_address=$;if(G!==void 0)W.estimated_delivery_time=G;if(Object.keys(W).length===1)return X;try{return await P1.updateTable("orders").set(W).where("id","=",J).execute(),await c(J)}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update delivery information: ${Z.message}`);throw Z}}V0();import{db as M0}from"@stacksjs/database";import{formatDate as Q$}from"@stacksjs/orm";async function T1(J){let $=await M0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await M0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var PJ=!1;function 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 E1(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:Q$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(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 f1(J){let G=J.data.object?.id;if(!G)return;await M0.transaction(async(W)=>{if(!await E1(J.id,W))return;let Y=await W.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Y)return;let L=Q$(new Date);await W.updateTable("payments").set({status:"succeeded",updated_at:L}).where("id","=",Y.id).execute();let N=await W.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await W.updateTable("orders").set({status:"PROCESSING",updated_at:L}).where("id","=",N.id).execute()});let X=await T1(G);if(X)await d(X)}async function w1(J){let $=J.data.object,G=$?.id;if(!G)return;let W=$?.last_payment_error?.message??"payment failed";await M0.transaction(async(Y)=>{if(!await E1(J.id,Y))return;let N=await Y.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!N)return;let K=Q$(new Date);await Y.updateTable("payments").set({status:"failed",failure_reason:W,updated_at:K}).where("id","=",N.id).execute();let Q=await Y.selectFrom("orders").where("id","=",N.order_id).selectAll().executeTakeFirst();if(Q&&Q.status==="PENDING")await Y.updateTable("orders").set({status:"CANCELLED",updated_at:K}).where("id","=",Q.id).execute()});let Z=await T1(G);if(Z)await H0(Z,W)}async function q1(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let X=$?.amount_refunded??0;await M0.transaction(async(Z)=>{if(!await E1(J.id,Z))return;let L=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let N=Q$(new Date);await Z.updateTable("payments").set({status:"refunded",refund_amount:X,updated_at:N}).where("id","=",L.id).execute();let K=await Z.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(K&&K.status!=="REFUNDED")await Z.updateTable("orders").set({status:"REFUNDED",updated_at:N}).where("id","=",K.id).execute()});let W=await T1(G);if(W)await x0(W,X)}async function SJ(){let J=await import("@stacksjs/payments").catch(()=>null);if(!J)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:G}=J;if(typeof $!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:f1,failed:w1}),G({refunded:q1}),()=>{}}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 W=Number(X.price);if(Number.isFinite(W))G.set(X.id,Math.round(W))}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,W=0,Z=[];for(let R of J.items){let O=R.unitPriceCents??G.get(R.productId)??0,U=Math.round(O*R.quantity);W+=U,Z.push({productId:R.productId,quantity:R.quantity,unitPriceCents:O,lineCents:U})}let Y=Math.max(0,J.discountCents??0),L=Math.max(0,W-Y),N=Math.round(L*X),K=Math.max(0,J.shippingCents??0),Q=W-Y+N+K,H=J.maxDriftCents??5,x=!1,_=0;if(J.clientTotalCents!=null)_=Math.abs(Q-J.clientTotalCents),x=_>H;return{subtotalCents:W,discountCents:Y,taxCents:N,shippingCents:K,totalCents:Q,resolvedItems:Z,priceChanged:x,diffCents:_}}import{db as H$}from"@stacksjs/database";function fJ(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 j1(J,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:J,quantity:$,reason:"non-positive"};let G;try{G=await H$.selectFrom("products").where("id","=",J).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:J,quantity:$}}if(!G)return{ok:!1,productId:J,quantity:$,reason:"product-missing"};let X=G.min_order_qty??null,W=G.max_order_qty??null;if(X!=null&&$<X)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:X};if(W!=null&&$>W)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:W};return{ok:!0,productId:J,quantity:$}}async function wJ(J){for(let G of J){let X=await j1(G.productId,G.quantity);if(!X.ok)return X}let $=J[J.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function qJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,W=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let Z=await H$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[W,W,G]),Y=typeof Z?.execute==="function"?await Z.execute():Z;return{deleted:Number(Y?.changes??Y?.numDeletedRows??Y?.[0]?.numDeletedRows??Y?.affectedRows??0),cutoffAt:W}}catch{try{let Z=await H$.selectFrom("carts").where("updated_at","<",W).select(["id"]).limit(G).execute();if(Z.length===0)return{deleted:0,cutoffAt:W};let Y=Z.map((K)=>K.id),L=await H$.deleteFrom("carts").where("id","in",Y).execute();return{deleted:Number(L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??Z.length),cutoffAt:W}}catch{return{deleted:0,cutoffAt:W}}}}var C1={};z(C1,{update:()=>lJ,store:()=>bJ,recordRefund:()=>cJ,fetchPaymentStatsByMethod:()=>gJ,fetchPaymentStats:()=>IJ,fetchMonthlyPaymentTrends:()=>vJ,fetchById:()=>Z0,fetchAll:()=>hJ,destroy:()=>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 F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function CJ(J){if(!J.length)return 0;try{let $=await jJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as q}from"@stacksjs/database";import{formatDate as v}from"@stacksjs/orm";async function hJ(){return await q.selectFrom("payments").selectAll().execute()}async function Z0(J){return await q.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function IJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let W=new Date(X);W.setDate(X.getDate()-J);let Z=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),Y=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(W)).where("created_at","<=",v(X)).where("status","=","completed").executeTakeFirst(),L=await q.selectFrom("payments").select(q.fn.count("id").as("count")).where("created_at",">=",v(G)).where("created_at","<=",v($)).executeTakeFirst(),N=Number(Z?.transaction_count||0),K=Number(Z?.total_revenue||0),Q=N>0?K/N:0,H=Number(Y?.transaction_count||0),x=Number(Y?.total_revenue||0),_=H>0?x/H:0,R=N-H,O=K-x,U=Q-_,m=H>0?R/H*100:N>0?100:0,t=x>0?O/x*100:K>0?100:0,$0=_>0?U/_*100:Q>0?100:0,F0=Number(L?.count||0),p=F0>0?N/F0*100:0;return{total_transactions:N,total_revenue:K,average_transaction:Q,successful_rate:p,comparison:{transactions:{difference:R,percentage:Math.abs(m),is_increase:R>=0},revenue:{difference:O,percentage:Math.abs(t),is_increase:O>=0},average:{difference:U,percentage:Math.abs($0),is_increase:U>=0}}}}async function gJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=await q.selectFrom("payments").select([q.fn.count("id").as("total_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),W=Number(X?.total_count||0),Z=await q.selectFrom("payments").select(["method",q.fn.count("id").as("count"),q.fn.sum("amount").as("revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").groupBy("method").execute(),Y={};return Z.forEach((L)=>{let N=Number(L.count||0),K=Number(L.revenue||0),Q=W>0?N/W*100:0;Y[L.method]={count:N,revenue:K,percentage_of_total:Q}}),Y}async function vJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await q.selectFrom("payments").selectAll().where("created_at",">=",v($)).where("status","=","completed").execute(),X={};for(let Z of G){let Y=Z.created_at?new Date(Z.created_at):new Date,L=Y.getFullYear(),N=Y.getMonth()+1,K=`${L}-${String(N).padStart(2,"0")}`;if(!X[K])X[K]={year:L,month:N,transactions:0,revenue:0};X[K].transactions++,X[K].revenue+=Number(Z.amount||0)}return Object.keys(X).sort().map((Z)=>{let Y=X[Z],L=Y.transactions,N=Y.revenue,K=L>0?N/L:0;return{month:new Date(Y.year,Y.month-1,1).toLocaleString("default",{month:"short"}),year:Y.year,transactions:L,revenue:N,average:K}})}var{randomUUIDv7:p3}=globalThis.Bun;import{db as DJ}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 DJ.insertInto("payments").values(G).executeTakeFirst(),await DJ.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 Z0(J))return;try{return await mJ.updateTable("payments").set({...$,updated_at:pJ(new Date)}).where("id","=",J).execute(),await Z0(J)}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${X.message}`)}throw X}}var 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,W=pJ(new Date),Z=await mJ.unsafe(`UPDATE payments
|
|
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:()=>x0,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,x=Number(L?.total_orders||0),O=Number(L?.total_revenue||0),R=x>0?O/x:0,_=F-x,U=N-O,m=H-R,t=x!==0?_/x*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:x,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}}M0();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
|
|
17
|
+
SET inventory_count = inventory_count + ${Z(1)},
|
|
18
|
+
updated_at = ${Z(2)}
|
|
19
|
+
WHERE id = ${Z(3)}
|
|
20
|
+
AND inventory_count + ${Z(4)} >= 0`,parameters:[G,X,$,G]}}async function MJ(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((x)=>{if(!Number.isInteger(x.productId)||x.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(x.quantity)||x.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(x.price)||x.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:K,product_id:x.productId,quantity:x.quantity,price:x.price,special_instructions:x.specialInstructions||null,created_at:X,updated_at:X}});await G.insertInto("order_items").values(H).execute(),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:x,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 MJ(G,x,O,X))throw Object.assign(Error(`inventory adjust failed for product ${x}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id: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 $}}M0();import{db as P4}from"@stacksjs/database";import{formatDate as S4}from"@stacksjs/orm";M0();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}}M0();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 x0(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,x=!1,O=0;if(J.clientTotalCents!=null)O=Math.abs(N-J.clientTotalCents),x=O>H;return{subtotalCents:Z,discountCents:L,taxCents:W,shippingCents:F,totalCents:N,resolvedItems:Y,priceChanged:x,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),x=Number(L?.total_revenue||0),O=H>0?x/H:0,R=W-H,_=F-x,U=N-O,m=H>0?R/H*100:W>0?100:0,t=x>0?_/x*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
|
|
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`,[$,$,W,J,$]),Y=typeof Z?.execute==="function"?await Z.execute():Z;if(Number(Y?.numUpdatedRows??Y?.[0]?.numUpdatedRows??Y?.numAffectedRows??Y?.affectedRows??Y?.[0]?.affectedRows??Y?.changes??0)>0){let x=await Z0(J);if(x)return x;throw Error(`Payment with ID ${J} disappeared during refund`)}let N=await Z0(J);if(!N)throw Error(`Payment with ID ${J} not found`);let K=String(N.status||"");if(!n3.has(K))throw Error(`Payment status ${K||"unknown"} cannot be refunded`);let Q=N,H=Number(N.amount||0)-Number(Q.refundAmount??Q.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${H} minor units`)}var b1={};z(b1,{variants:()=>U$,units:()=>R$,reviews:()=>A$,manufacturers:()=>B$,items:()=>z$,default:()=>XW,categories:()=>M$});var M$={};z(M$,{updateParent:()=>N6,updateDisplayOrder:()=>Y6,updateActiveStatus:()=>L6,update:()=>Z6,store:()=>I1,removeChildCategories:()=>$6,remove:()=>rJ,findOrCreateByName:()=>W6,fetchStats:()=>dJ,fetchRootCategories:()=>iJ,fetchChildCategories:()=>oJ,fetchCategoryTree:()=>eJ,fetchByName:()=>uJ,fetchById:()=>j,fetchByDisplayOrder:()=>sJ,fetchAll:()=>h1,fetchActive:()=>nJ,deactivateChildCategories:()=>G6,deactivate:()=>J6,compareCategoryGrowth:()=>aJ,bulkRemove:()=>tJ});import{db as z0}from"@stacksjs/database";import{db as S}from"@stacksjs/database";import{formatDate as k0}from"@stacksjs/orm";async function h1(){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(),W=new Date;W.setDate(W.getDate()-30);let Z=k0(W),Y=await S.selectFrom("categories").where("created_at",">=",Z).selectAll().limit(5).execute(),L=await S.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",S.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number($?.count||0),root_categories:Number(G?.count||0),child_categories:Number(J?.count||0)-Number(G?.count||0),with_images:Number(X?.count||0),recently_added:Y,top_parent_categories:L.map((N)=>({id:String(N.parent_category_id||""),name:String(N.parent_name||""),child_count:Number(N.child_count)}))}}async function aJ(J=30){let $=new Date,G=k0($),X=new Date;X.setDate($.getDate()-J);let W=k0(X),Z=new Date(X);Z.setDate(Z.getDate()-1);let Y=k0(Z),L=new Date(Z);L.setDate(Z.getDate()-J);let N=k0(L),K=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",W).where("created_at","<=",G).executeTakeFirst(),Q=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",N).where("created_at","<=",Y).executeTakeFirst(),H=Number(K?.count||0),x=Number(Q?.count||0),_=H-x,R=x!==0?_/x*100:H>0?100:0;return{current_period:H,previous_period:x,difference:_,percentage_change:R,days_range:J}}async function eJ(){let J=await h1(),$=new Map;J.forEach((W)=>{$.set(W.id,{...W,children:[]})});let G=[];J.forEach((W)=>{let Z=$.get(W.id);if(W.parent_category_id){let Y=$.get(W.parent_category_id);if(Y)Y.children.push(Z)}else G.push(Z)}),G.sort((W,Z)=>W.display_order-Z.display_order);let X=(W)=>{W.sort((Z,Y)=>Z.display_order-Y.display_order),W.forEach((Z)=>{if(Z.children.length>0)X(Z.children)})};return X(G),G}async function rJ(J){let $=await z0.deleteFrom("categories").where("id","=",J).executeTakeFirst();return F($)>0}async function tJ(J){if(!J.length)return 0;let $=await z0.deleteFrom("categories").where("id","in",J).executeTakeFirst();return F($)}async function $6(J){let $=await z0.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return F($)}async function J6(J){if(!await 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 x$}from"@stacksjs/error-handling";import{isUniqueViolation as o3}from"@stacksjs/orm";import{slug as s3}from"@stacksjs/strings";async function I1(J){try{let $=J.parent_category_id?Number(J.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new x$(422,"Parent category ID must be a positive integer");if($&&!await j($))throw new x$(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 x$)throw $;if(o3($))throw new x$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function W6(J){if(!J.name)throw Error("Name is required");let $=await X6.selectFrom("categories").selectAll().where("name","=",J.name).executeTakeFirst();if($)return $;let G={name:J.name,slug:s3(J.name),is_active:J.is_active??!0,display_order:0};return await I1(G)}import{db as C0}from"@stacksjs/database";import{HttpError as B0}from"@stacksjs/error-handling";import{formatDate as V$,isUniqueViolation as d3}from"@stacksjs/orm";async function Z6(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 K6(J,String(X)))throw new B0(422,"This operation would create a circular category hierarchy")}try{let X=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},W=await C0.updateTable("categories").set({...$,...X,updated_at:V$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!W)return;return W}catch(X){if(X instanceof B0)throw X;if(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 Y6(J,$){if(!await j(J))throw Error(`Category with ID ${J} not found`);try{return await C0.updateTable("categories").set({display_order:$,updated_at:V$(new Date)}).where("id","=",J).execute(),await j(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category display order: ${X.message}`);throw X}}async function L6(J,$){if(!await j(J))throw Error(`Category with ID ${J} not found`);try{return await C0.updateTable("categories").set({is_active:$,updated_at:V$(new Date)}).where("id","=",J).execute(),await j(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function N6(J,$){if(!await 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 K6(J,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let X={updated_at:V$(new Date)};if($===null)await C0.updateTable("categories").set({...X,parent_category_id:null}).where("id","=",J).execute();else await C0.updateTable("categories").set({...X,parent_category_id:$}).where("id","=",J).execute();return await j(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category parent: ${X.message}`);throw X}}async function K6(J,$){let G=Number($),X=new Set;while(G){if(X.has(G))return!0;if(G===J)return!0;X.add(G);let W=await j(G),Z=W?.parent_category_id??W?.parentCategoryId;if(!W||!Z)return!1;G=Number(Z)}return!1}var z$={};z(z$,{updateInventory:()=>R6,updateAvailability:()=>O6,update:()=>_6,store:()=>B6,fetchTopProducts:()=>V6,fetchById:()=>u,fetchAll:()=>x6,destroy:()=>Q6,bulkStore:()=>A6,bulkDestroy:()=>H6});import{db as F6}from"@stacksjs/database";async function Q6(J){try{let $=await F6.deleteFrom("products").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function H6(J){if(!J.length)return 0;try{let $=await F6.deleteFrom("products").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as a,sql as 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 x6(){let J=await a.selectFrom("products").selectAll().execute(),$=J.map((K)=>K.manufacturer_id).filter((K)=>K!==null&&K!==void 0),G=J.map((K)=>K.category_id).filter((K)=>K!==null&&K!==void 0),X=a.selectFrom("manufacturers"),W=a.selectFrom("categories");if($.length>0)X=X.where("id","in",$);if(G.length>0)W=W.where("id","in",G);let Z=await X.selectAll().execute(),Y=await W.selectAll().execute(),L=Z.reduce((K,Q)=>{return K[Q.id]=Q,K},{}),N=Y.reduce((K,Q)=>{return K[Q.id]=Q,K},{});return J.map((K)=>({...K,manufacturer:K.manufacturer_id?L[K.manufacturer_id]:null,category:K.category_id?N[K.category_id]:null}))}async function V6(J=5){try{return(await a.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",a.fn.sum("order_items.quantity").as("units_sold"),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:M6}=globalThis.Bun;import{db as z6}from"@stacksjs/database";async function B6(J){try{let $={...J,uuid:M6()},G=await z6.insertInto("products").values($).executeTakeFirst();if(!G)throw Error("Failed to create product item");let X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),W=await u(X);if(!W)throw Error("Failed to create product item");return W}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function A6(J){if(!J.length)return 0;let $=0;try{return await z6.transaction().execute(async(G)=>{for(let X of J){let W={...X,uuid:M6()};await G.insertInto("products").values(W).execute(),$++}}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as g1}from"@stacksjs/database";import{formatDate as v1}from"@stacksjs/orm";async function _6(J,$){try{if(!J)throw Error("Product item ID is required for update");let G=await g1.updateTable("products").set({...$,updated_at:v1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item: ${G.message}`);throw G}}async function O6(J,$){if(!await u(J))throw Error(`Product item with ID ${J} not found`);try{return await g1.updateTable("products").set({is_available:$,updated_at:v1(new Date)}).where("id","=",J).execute(),await u(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item availability: ${X.message}`);throw X}}async function R6(J,$){let G=await u(J);if(!G)throw Error(`Product item with ID ${J} not found`);let X={updated_at:v1(new Date)};if($!==void 0)X.inventory_count=$;if(Object.keys(X).length===1)return G;try{return await g1.updateTable("products").set(X).where("id","=",J).execute(),await u(J)}catch(W){if(W instanceof Error)throw TypeError(`Failed to update inventory information: ${W.message}`);throw W}}var B$={};z(B$,{updateFeaturedStatus:()=>y6,updateByUuid:()=>b6,update:()=>D6,store:()=>I6,fetchWithProductCount:()=>j6,fetchFeatured:()=>w6,fetchByUuid:()=>f6,fetchById:()=>E6,fetchByCountry:()=>q6,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 F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function S6(J){if(!J.length)return 0;try{let $=await U6.deleteFrom("manufacturers").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as n}from"@stacksjs/database";function T6(){return n.selectFrom("manufacturers").selectAll().execute()}async function E6(J){return await n.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function f6(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 q6(J,$={}){let G=$.page||1,X=$.limit||2,W=await n.selectFrom("manufacturers").select(n.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),Z=Number(W?.total||0),Y=await n.selectFrom("manufacturers").selectAll().where("country","=",J).limit(X).offset((G-1)*X).execute(),L=Math.ceil(Z/X);return{data:Y,paging:{total_records:Z,page:G,total_pages:L},next_cursor:G<L?G+1:null}}async function 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 D1}from"@stacksjs/database";import{HttpError as v6}from"@stacksjs/error-handling";import{formatDate as y1,isUniqueViolation as r3}from"@stacksjs/orm";async function D6(J,$){try{if(!J)throw Error("Manufacturer ID is required for update");let G=await D1.updateTable("manufacturers").set({...$,updated_at:y1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof v6)throw G;if(r3(G))throw new v6(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function y6(J,$){try{let G=await D1.updateTable("manufacturers").set({featured:$,updated_at:y1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer featured status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${G.message}`);throw G}}async function b6(J,$){try{let G=await D1.updateTable("manufacturers").set({...$,updated_at:y1(new Date)}).where("uuid","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer: ${G.message}`);throw G}}var A$={};z(A$,{updateVotes:()=>W2,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 F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function l6(J){if(!J.length)return 0;try{let $=await m6.deleteFrom("reviews").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as A0}from"@stacksjs/database";async function c6(J){return await A0.selectFrom("reviews").where("id","=",J).selectAll().executeTakeFirst()}async function u6(){return await A0.selectFrom("reviews").selectAll().execute()}async function n6(J){return await A0.selectFrom("reviews").where("product_id","=",J).selectAll().execute()}async function i6(J){return await A0.selectFrom("reviews").where("customer_id","=",J).selectAll().execute()}async function o6(J){return await A0.selectFrom("reviews").where("product_id","=",J).where("is_approved","=",!0).selectAll().execute()}async function s6(J){return await A0.selectFrom("reviews").where("product_id","=",J).orderBy("helpful_votes","desc").selectAll().execute()}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 W=Number(X.rating);if(Number.isNaN(W)){$.commentsOnly++;continue}$.rated++,G+=W;let Z=Math.min(5,Math.max(1,Math.round(W)));$.distribution[Z]++}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 W of J)$.set(W,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 W of G){let Z=X.get(W.product_id);if(Z)Z.push({rating:W.rating});else X.set(W.product_id,[{rating:W.rating}])}for(let[W,Z]of X)$.set(W,e6(Z));return $}var{randomUUIDv7:t3}=globalThis.Bun;import{db as $W}from"@stacksjs/database";function JW(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(JW(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 $W.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 W2(J,$,G=!0){try{let X=$==="helpful"?"helpful_votes":"unhelpful_votes",W=G?`COALESCE("${X}", 0) + 1`:`MAX(COALESCE("${X}", 0) - 1, 0)`,Z=await J2.unsafe(`UPDATE "reviews" SET "${X}" = ${W}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[G2(new Date),J]).execute(),Y=Array.isArray(Z)?Z[0]:Z;if(!Y)throw Error("Failed to update review votes");return Y}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var R$={};z(R$,{updateDefaultStatus:()=>A2,update:()=>z2,store:()=>H2,getDefaultUnit:()=>M2,formatUnitOptions:()=>V2,fetchById:()=>K2,fetchAll:()=>F2,destroy:()=>Y2,bulkUpdate:()=>B2,bulkStore:()=>x2,bulkDestroy:()=>L2});import{db as Z2}from"@stacksjs/database";async function Y2(J){try{let $=await Z2.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function L2(J){if(!J.length)return 0;try{let $=await Z2.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as N2}from"@stacksjs/database";async function K2(J){return await N2.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function F2(){return await N2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:Q2}=globalThis.Bun;import{db as h0}from"@stacksjs/database";async function H2(J){try{return await h0.transaction(async($)=>{let G={...J,uuid:Q2()},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 x2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:Q2()},W=await h0.insertInto("product_units").values(X).returningAll().executeTakeFirst();if(X.is_default&&X.type&&W)await h0.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",W.id).execute();$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function V2(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 M2(J){try{return await h0.selectFrom("product_units").selectAll().where("type","=",J).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as _$}from"@stacksjs/database";import{formatDate as O$}from"@stacksjs/orm";async function z2(J,$){try{if(!J)throw Error("Product unit ID is required for update");return await _$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",J).executeTakeFirst();if(!X)return;let W=$.type??X.type;if(($.is_default??Boolean(X.is_default))&&W)await G.updateTable("product_units").set({is_default:!1,updated_at:O$(new Date)}).where("type","=",W).where("id","!=",J).execute();let Y=await G.updateTable("product_units").set({...$,updated_at:O$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function B2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X=G;if(!X.id)continue;let W=X.data&&typeof X.data==="object"?X.data:{...X};delete W.id;let Z=await _$.updateTable("product_units").set({...W,updated_at:O$(new Date)}).where("id","=",X.id).executeTakeFirst(),Y=W;if(Y.is_default===!0&&Y.type)await _$.updateTable("product_units").set({is_default:!1}).where("type","=",Y.type).where("id","!=",X.id).execute();if(Number(Z.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function A2(J,$){try{return await _$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!X)return!1;let W=O$(new Date);if($&&X.type)await G.updateTable("product_units").set({is_default:!1,updated_at:W}).where("type","=",X.type).where("id","!=",J).execute();return await G.updateTable("product_units").set({is_default:$,updated_at:W}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var U$={};z(U$,{update:()=>h2,store:()=>f2,generateVariantCombinations:()=>j2,formatVariantOptions:()=>q2,fetchById:()=>P2,fetchAll:()=>S2,destroy:()=>O2,bulkUpdate:()=>I2,bulkStore:()=>w2,bulkDestroy:()=>R2});import{db as _2}from"@stacksjs/database";async function O2(J){try{let $=await _2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function R2(J){if(!J.length)return 0;try{let $=await _2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as 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 f2(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 q2(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,W){if(X===$.length)return[W];let Z=$[X],Y=J[Z]??[],L=[];for(let N of Y){let K={...W,[Z]:N};L.push(...G(X+1,K))}return L}return G(0,{})}import{db as 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 GW={categories:M$,items:z$,manufacturers:B$,reviews:A$,units:R$,variants:U$},XW=GW;var n1={};z(n1,{updateStatus:()=>s2,updatePrintJob:()=>d2,update:()=>o2,store:()=>n2,fetchSuccessRate:()=>m2,fetchPrintsPerHour:()=>c2,fetchPrintTimeStats:()=>l2,fetchPrintJobStats:()=>b2,fetchPageStats:()=>p2,fetchById:()=>_0,fetchAll:()=>y2,destroy:()=>v2,bulkStore:()=>i2,bulkDestroy:()=>D2});import{db as g2}from"@stacksjs/database";async function v2(J){try{let $=await g2.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function D2(J){if(!J.length)return 0;try{let $=await g2.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as m1}from"@stacksjs/database";import{formatDate as WW}from"@stacksjs/orm";function b(J){return WW(J)}function ZW(J){if(J instanceof Date)return Number.isNaN(J.getTime())?null:J;if(typeof J==="number"){let X=new Date(J<=2147483647?J*1000:J);return Number.isNaN(X.getTime())?null:X}let $=String(J||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let X=new Date(Number($)*1000);return Number.isNaN(X.getTime())?null:X}let G=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function _0(J){return await m1.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function y2(){return await m1.selectFrom("receipts").selectAll().execute()}async function b2(J,$){let G=b(J),X=b($),W=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(Z)=>Z.where("timestamp",">=",G).where("timestamp","<=",X));return{total:W.total,success:W.success,failed:W.failed,warning:W.warning,averageSize:Math.round(W.averageSize),averagePages:Math.round(W.averagePages),averageDuration:Math.round(W.averageDuration)}}async function m2(J,$){let G=b(J),X=b($),W=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{successRate:W.total>0?Math.round(W.success/W.total*100):0,total:W.total,success:W.success,failed:W.failed,warning:W.warning}}async function p2(J,$){let G=b(J),X=b($),W=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(Z)=>Z.where("timestamp",">=",G).where("timestamp","<=",X));return{totalPages:W.totalPages,averagePagesPerReceipt:Math.round(W.averagePagesPerReceipt),totalReceipts:W.totalReceipts}}async function l2(J,$){let G=b(J),X=b($),W=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(Z)=>Z.where("timestamp",">=",G).where("timestamp","<=",X));return{averageDuration:Math.round(W.averageDuration),minDuration:W.minDuration,maxDuration:W.maxDuration,totalJobs:W.totalJobs}}async function c2(J,$){let G=typeof J==="number"?J:J.getTime(),X=typeof $==="number"?$:$.getTime(),W=b(J),Z=b($),Y=await m1.selectFrom("receipts").where("timestamp",">=",W).where("timestamp","<=",Z).selectAll().execute(),L=Y.length,N=Math.ceil((X-G)/3600000),K=N>0?Math.round(L/N):0,Q=Array.from({length:24},(H,x)=>({hour:x,count:0}));return Y.forEach((H)=>{let x=ZW(H.timestamp);if(!x)return;Q[x.getHours()].count++}),{totalPrints:L,totalHours:N,printsPerHour:K,hourlyBreakdown:Q}}var{randomUUIDv7:u2}=globalThis.Bun;import{db as l1}from"@stacksjs/database";import{formatDate as p1}from"@stacksjs/orm";function I0(J){try{if(typeof J==="number")return p1(J<=2147483647?J*1000:J);if(typeof J==="string"&&/^\d{10}$/.test(J))return p1(Number(J)*1000);return p1(J)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function n2(J){try{let $=u2(),G={...J,timestamp:I0(J.timestamp),uuid:$};await l1.insertInto("receipts").values(G).executeTakeFirst();let X=await l1.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function i2(J){if(!J.length)return 0;try{let $=J.map((X)=>({...X,timestamp:I0(X.timestamp),uuid:u2()})),G=await l1.insertInto("receipts").values($).executeTakeFirst();return Number(G.numInsertedOrUpdatedRows??G.numAffectedRows??G.affectedRows??G.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as c1}from"@stacksjs/database";import{formatDate as u1}from"@stacksjs/orm";async function o2(J,$){try{if(!J)throw Error("Receipt ID is required for update");let G={...$,...$.timestamp===void 0?{}:{timestamp:I0($.timestamp)},updated_at:u1(new Date)};await c1.updateTable("receipts").set(G).where("id","=",J).execute();let X=await _0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function s2(J,$){try{await c1.updateTable("receipts").set({status:$,updated_at:u1(new Date)}).where("id","=",J).execute();let G=await _0(J);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function d2(J,$,G,X){try{let W={updated_at:u1(new Date)};if($!==void 0)W.size=$;if(G!==void 0)W.pages=G;if(X!==void 0)W.duration=X;await c1.updateTable("receipts").set(W).where("id","=",J).execute();let Z=await _0(J);if(!Z)throw Error("Failed to update receipt job information");return Z}catch(W){if(W instanceof Error)throw TypeError(`Failed to update receipt job information: ${W.message}`);throw W}}var V4={};z(V4,{zones:()=>Y1,tracking:()=>G1,routes:()=>w$,rates:()=>s$,methods:()=>c$,licenses:()=>b$,geocoding:()=>v$,drivers:()=>C$,digital:()=>j$,default:()=>qW});var w$={};z(w$,{validateDeliveryRouteWrite:()=>O0,updateStops:()=>ZG,updateMetrics:()=>YG,updateLastActive:()=>XG,update:()=>WG,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 F($)>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 F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as P$}from"@stacksjs/database";async function S$(J){return await P$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function 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:NW}=globalThis.Bun;import{db as i1}from"@stacksjs/database";function Y0(J,$){let G={};for(let[X,W]of Object.entries($))for(let Z of W){if(!Object.prototype.hasOwnProperty.call(J,Z)||J[Z]===void 0)continue;G[X]=J[Z];break}return G}function g0(J){return Y0(J,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function i(J){return Y0(J,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function v0(J){return Y0(J,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function D0(J){return Y0(J,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function y0(J){return Y0(J,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function b0(J){return Y0(J,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function T$(J){return Y0(J,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as YW}from"@stacksjs/database";class h extends TypeError{constructor(J){super(J);this.name="DeliveryRouteInputError"}}function E$(J,$,G){return Number(J[G]??$?.[G])}function LW(J,$){let G=J.last_active??$?.last_active;if(G instanceof Date)return G.getTime();if(typeof G==="number")return G;if(typeof G==="string"&&/^\d{10,13}$/.test(G))return Number(G);return Number.NaN}async function O0(J,$){let G=E$(J,$,"driver_id"),X=E$(J,$,"stops"),W=E$(J,$,"delivery_time"),Z=E$(J,$,"total_distance"),Y=LW(J,$);if(!Number.isSafeInteger(G)||G<1)throw new h("Driver must be a positive integer.");if(!Number.isSafeInteger(X)||X<0)throw new h("Stops must be a non-negative integer.");if(!Number.isSafeInteger(W)||W<0)throw new h("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new h("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(Y)||Y<0)throw new h("Last active must be a valid Unix timestamp.");let L=await YW.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!L)throw new h(`Driver ${G} was not found.`);return{...J,driver_id:Number(L.id),driver:L.name,vehicle:L.vehicle_number}}async function GG(J){try{let $=NW(),G=T$(J),W={...await O0(G),uuid:$};await i1.insertInto("delivery_routes").values(W).executeTakeFirst();let Z=await i1.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to create delivery route");return Z}catch($){if($ instanceof h)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function XG(J){try{await i1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",J).execute();let $=await S$(J);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as f$}from"@stacksjs/database";import{formatDate as o1}from"@stacksjs/orm";async function WG(J,$){try{if(!J)throw Error("Delivery route ID is required for update");let G=await f$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=T$($),W=await O0(X,G),Z=await f$.updateTable("delivery_routes").set({...W,updated_at:o1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(G){if(G instanceof h)throw G;if(G instanceof Error)throw TypeError(`Failed to update delivery route: ${G.message}`);throw G}}async function ZG(J,$){try{let G=await f$.updateTable("delivery_routes").set({stops:$,updated_at:o1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update delivery route stops");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery route stops: ${G.message}`);throw G}}async function YG(J,$,G){try{let X={updated_at:o1(new Date)};if($!==void 0)X.delivery_time=$;if(G!==void 0)X.total_distance=G;let W=await f$.updateTable("delivery_routes").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!W)throw Error("Failed to update delivery metrics");return W}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery metrics: ${X.message}`);throw X}}var j$={};z(j$,{updateStatus:()=>AG,updateDeliverySettings:()=>_G,update:()=>BG,store:()=>MG,softDelete:()=>NG,fetchById:()=>HG,fetchAll:()=>xG,destroy:()=>LG,bulkStore:()=>zG,bulkSoftDelete:()=>FG,bulkDestroy:()=>KG});import{db as q$}from"@stacksjs/database";async function LG(J){try{let $=await q$.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function NG(J){try{let $=await q$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function KG(J){if(!J.length)return 0;try{let $=await q$.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function FG(J){if(!J.length)return 0;try{let $=await q$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as QG}from"@stacksjs/database";async function HG(J){return await QG.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function xG(){return await QG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:VG}=globalThis.Bun;import{db as s1}from"@stacksjs/database";async function MG(J){try{let $=VG(),G={...D0(J),uuid:$};await s1.insertInto("digital_deliveries").values(G).executeTakeFirst();let X=await s1.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created digital delivery");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function zG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...D0(X),uuid:VG()})),G=await s1.insertInto("digital_deliveries").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as d1}from"@stacksjs/database";import{formatDate as a1}from"@stacksjs/orm";async function BG(J,$){try{if(!J)throw Error("Digital delivery ID is required for update");let G=await d1.updateTable("digital_deliveries").set({...D0($),updated_at:a1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery: ${G.message}`);throw G}}async function AG(J,$){try{let G=await d1.updateTable("digital_deliveries").set({status:$,updated_at:a1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update digital delivery status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery status: ${G.message}`);throw G}}async function _G(J,$,G,X,W){try{let Z={updated_at:a1(new Date)};if($!==void 0)Z.download_limit=$;if(G!==void 0)Z.expiry_days=G;if(X!==void 0)Z.requires_login=X;if(W!==void 0)Z.automatic_delivery=W;let Y=await d1.updateTable("digital_deliveries").set(Z).where("id","=",J).returningAll().executeTakeFirst();if(!Y)throw Error("Failed to update delivery settings");return Y}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update delivery settings: ${Z.message}`);throw Z}}var C$={};z(C$,{updateStatus:()=>qG,updateContact:()=>jG,update:()=>wG,store:()=>EG,fetchById:()=>k$,fetchAll:()=>RG,destroy:()=>PG,bulkStore:()=>fG,bulkDestroy:()=>SG});import{db as UG}from"@stacksjs/database";import{db as OG}from"@stacksjs/database";async function k$(J){return await OG.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function RG(){return await OG.selectFrom("drivers").selectAll().execute()}async function PG(J){try{let $=await UG.deleteFrom("drivers").where("id","=",J).executeTakeFirst();return F($)>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 e1}from"@stacksjs/database";async function EG(J){try{let $=TG(),G={...b0(J),uuid:$};await e1.insertInto("drivers").values(G).executeTakeFirst();let X=await e1.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created driver");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function fG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...b0(X),uuid:TG()})),G=await e1.insertInto("drivers").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as r1}from"@stacksjs/database";import{formatDate as t1}from"@stacksjs/orm";async function wG(J,$){try{if(!J)throw Error("Driver ID is required for update");let G=await r1.updateTable("drivers").set({...b0($),updated_at:t1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver: ${G.message}`);throw G}}async function qG(J,$){try{let G=await r1.updateTable("drivers").set({status:$,updated_at:t1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update driver status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver status: ${G.message}`);throw G}}async function jG(J,$){try{let G={updated_at:t1(new Date)};if($!==void 0)G.phone=$;let X=await r1.updateTable("drivers").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update contact information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update contact information: ${G.message}`);throw G}}var v$={};z(v$,{setGeocodingDriver:()=>HW,nominatimDriver:()=>g$,geocodingDriver:()=>vG,geocode:()=>xW,formatQuery:()=>R0,checkCoverage:()=>VW,PRECISION_RANK:()=>p0});var L0=(J)=>J*Math.PI/180;function e(J,$){let G=L0($.latitude-J.latitude),X=L0($.longitude-J.longitude),W=L0(J.latitude),Z=L0($.latitude),Y=Math.sin(G/2)**2+Math.sin(X/2)**2*Math.cos(W)*Math.cos(Z);return 12742017.6*Math.asin(Math.sqrt(Y))}function h$(J,$){let G=L0(J.latitude),X=L0($.latitude),W=L0($.longitude-J.longitude),Z=Math.sin(W)*Math.cos(X),Y=Math.cos(G)*Math.sin(X)-Math.sin(G)*Math.cos(X)*Math.cos(W);return(Math.atan2(Z,Y)*180/Math.PI+360)%360}function I$(J,$,G={}){let X=G.detourFactor??1.35,W=G.minimumSeconds??30;if(!Number.isFinite($)||$<=0.5)return null;let Z=J*X/$;return Math.max(W,Math.round(Z))}function 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 KW="https://nominatim.openstreetmap.org/search",CG=1000,hG=0,IG=Promise.resolve();async function FW(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 QW(J){let $=J.address??{},G=String(J.addresstype??""),X=String(J.type??""),W=String(J.category??J.class??"");if($.house_number||X==="house"||X==="building"||G==="building")return"rooftop";if($.road||W==="highway"||G==="road")return"street";if(G==="postcode"||$.postcode&&!$.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(G))return"locality";return"unknown"}function g$(J={}){let $=J.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,G=J.endpoint??KW;return{name:"nominatim",async geocode(X){let W=R0(X);if(!W)return null;let Z=new URL(G);if(Z.searchParams.set("q",W),Z.searchParams.set("format","jsonv2"),Z.searchParams.set("limit","1"),Z.searchParams.set("addressdetails","1"),X.country)Z.searchParams.set("countrycodes",X.country.toLowerCase());let Y=await FW(()=>fetch(Z,{headers:{"user-agent":$,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!Y.ok)throw Error(`Nominatim responded ${Y.status}`);let N=(await Y.json())?.[0];if(!N)return null;let K=Number(N.lat),Q=Number(N.lon);if(!Number.isFinite(K)||!Number.isFinite(Q))return null;let H=QW(N);return{latitude:K,longitude:Q,formatted:String(N.display_name??W),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[H],precision:H,provider:"nominatim"}}}}var gG=null;function HW(J){gG=J}function vG(){return gG??g$()}async function xW(J,$={}){let G=$.driver??vG(),X=$.minimumPrecision??"street",W=`geocode:${G.name}:${R0(J).toLowerCase()}`,Z=await MW(W);if(Z!==void 0)return Z;let Y=await G.geocode(J),L=Y&&p0[Y.precision]>=p0[X]?Y:null;return await zW(W,L,L?$.cacheSeconds??2592000:600),L}function VW(J,$,G){if($.length===0)return null;let X=$[0],W=e(J,X);for(let Z of $.slice(1)){let Y=e(J,Z);if(Y<W)W=Y,X=Z}return{covered:W<=G,distanceMeters:Math.round(W),nearest:X}}async function MW(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 zW(J,$,G){try{let W=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!W)return;await W.set(J,$===null?"null":JSON.stringify($),G)}catch{}}var b$={};z(b$,{validateLicenseKeyWrite:()=>N0,updateStatus:()=>aG,updateExpiration:()=>eG,update:()=>dG,store:()=>oG,softDelete:()=>yG,fetchById:()=>lG,fetchAll:()=>cG,destroy:()=>DG,bulkStore:()=>sG,bulkSoftDelete:()=>mG,bulkDestroy:()=>bG,LicenseKeyInputError:()=>E});import{db as D$}from"@stacksjs/database";async function DG(J){try{let $=await D$.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function yG(J){try{let $=await D$.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function bG(J){if(!J.length)return 0;try{let $=await D$.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function mG(J){if(!J.length)return 0;try{let $=await D$.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as 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 G4}from"@stacksjs/database";import{db as $4}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 J4(J,$,G,X){let W=l0(J,$,G);if(W===void 0||W===null||W==="")return null;let Z=Number(W);if(!Number.isSafeInteger(Z)||Z<1)throw new E(`${X} must be a positive integer or null.`);return Z}function BW(J){if(typeof J==="number")return J>2147483647?Math.floor(J/1000):J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return J.length===13?Math.floor(Number(J)/1000):Number(J);if(typeof J==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(J)?`${J.replace(" ","T")}Z`:J;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function N0(J,$){let G=String(l0(J,$,"key")||"").trim().toUpperCase(),X=String(l0(J,$,"template")||""),W=String(l0(J,$,"status")||""),Z=BW(l0(J,$,"expiry_date")),Y=J4(J,$,"customer_id","Customer"),L=J4(J,$,"product_id","Product"),N=J4(J,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new 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(W))throw new E(`Status must be one of: ${nG.join(", ")}.`);if(!Number.isSafeInteger(Z)||Z<0||Z>2147483647)throw new E("Expiry date must be a Unix timestamp between 1970 and 2038.");let[K,Q,H]=await Promise.all([Y?$4.selectFrom("customers").where("id","=",Y).select("id").executeTakeFirst():null,L?$4.selectFrom("products").where("id","=",L).select("id").executeTakeFirst():null,N?$4.selectFrom("orders").where("id","=",N).select(["id","customer_id"]).executeTakeFirst():null]);if(Y&&!K)throw new E(`Customer ${Y} was not found.`);if(L&&!Q)throw new E(`Product ${L} was not found.`);if(N&&!H)throw new E(`Order ${N} was not found.`);if(Y&&H?.customer_id&&Number(H.customer_id)!==Y)throw new E(`Order ${N} belongs to Customer ${H.customer_id}, not Customer ${Y}.`);return{...J,key:G,template:X,expiry_date:Z,status:W,customer_id:Y,product_id:L,order_id:N}}async function oG(J){try{let $=iG(),G=y0(J),X={...await N0(G),uuid:$};await G4.insertInto("license_keys").values(X).executeTakeFirst();let W=await G4.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!W)throw Error("Failed to resolve created license key");return W}catch($){if($ instanceof 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 N0(y0(X)),uuid:iG()}))),G=await G4.insertInto("license_keys").values($).executeTakeFirst();return F(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 X4}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($),W=await N0(X,G),Z=await y$.updateTable("license_keys").set({...W,updated_at:X4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(G){if(G instanceof 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:X4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update license key status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update license key status: ${G.message}`);throw G}}async function eG(J,$){try{let G={updated_at:X4(new Date)};if($!==void 0)G.expiry_date=$;let X=await y$.updateTable("license_keys").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update expiration information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update expiration information: ${G.message}`);throw G}}var c$={};z(c$,{updateStatus:()=>KX,updatePricing:()=>FX,update:()=>NX,store:()=>WX,softDelete:()=>tG,getActiveShippingMethods:()=>LX,formatShippingOptions:()=>YX,fetchById:()=>l$,fetchAll:()=>GX,destroy:()=>rG,bulkStore:()=>ZX,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 F($)>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 F($)>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 F($)}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 F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as p$}from"@stacksjs/database";async function l$(J){let $=await p$.selectFrom("shipping_methods").where("id","=",J).selectAll().executeTakeFirst();if($){let G=await p$.selectFrom("shipping_zones").where("shipping_method_id","=",J).selectAll().execute();return{...$,shippingZones:G}}return}async function GX(){let J=await p$.selectFrom("shipping_methods").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((Z)=>Z.id))],W=(await p$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((Z,Y)=>{let L=Y.shipping_method_id;if(L!==null&&L!==void 0){if(!Z[L])Z[L]=[];Z[L].push(Y)}return Z},{});return J.map((Z)=>({...Z,shipping_zones:W[Z.id]||[]}))}var{randomUUIDv7:XX}=globalThis.Bun;import{db as c0}from"@stacksjs/database";async function WX(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 ZX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...g0(X),uuid:XX()})),G=await c0.insertInto("shipping_methods").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function YX(){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 LX(){try{return await c0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping methods: ${J.message}`);throw J}}import{db as W4}from"@stacksjs/database";import{formatDate as Z4}from"@stacksjs/orm";async function NX(J,$){try{if(!J)throw Error("Shipping method ID is required for update");let G=await W4.updateTable("shipping_methods").set({...g0($),updated_at:Z4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method: ${G.message}`);throw G}}async function KX(J,$){try{let G=await W4.updateTable("shipping_methods").set({status:$,updated_at:Z4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping method status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method status: ${G.message}`);throw G}}async function FX(J,$,G){try{let X={updated_at:Z4(new Date)};if($!==void 0)X.base_rate=$;if(G!==void 0)X.free_shipping=G;let W=await W4.updateTable("shipping_methods").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!W)throw Error("Failed to update pricing information");return W}catch(X){if(X instanceof Error)throw TypeError(`Failed to update pricing information: ${X.message}`);throw X}}var s$={};z(s$,{validateZoneMatchesAddress:()=>OX,validateShippingRateWrite:()=>K0,updateByZone:()=>CX,updateByMethod:()=>hX,update:()=>jX,store:()=>wX,resolveZoneForAddress:()=>n$,getShippingRatesByMethod:()=>UX,getRatesByZone:()=>AX,getRateByWeightAndZone:()=>Y4,getRateByWeightAndAddress:()=>_X,formatShippingRateOptions:()=>RX,fetchById:()=>zX,fetchAll:()=>BX,destroyByZone:()=>xX,destroyByMethod:()=>VX,destroy:()=>QX,bulkUpdate:()=>kX,bulkStore:()=>qX,bulkDestroy:()=>HX,ShippingRateInputError:()=>k});import{db as u$}from"@stacksjs/database";async function QX(J){try{let $=await u$.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function HX(J){if(!J.length)return 0;try{let $=await u$.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function xX(J){try{let $=await u$.deleteFrom("shipping_rates").where("shipping_zone_id","=",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function VX(J){try{let $=await u$.deleteFrom("shipping_rates").where("shipping_method_id","=",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as D}from"@stacksjs/database";async function zX(J){let $=await D.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.shipping_zone_id)G=await D.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)X=await D.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:G,shipping_method:X}}return}async function BX(){let J=await D.selectFrom("shipping_rates").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((L)=>L.shipping_zone_id).filter((L)=>L!==null&&L!==void 0))],G=[...new Set(J.map((L)=>L.shipping_method_id).filter((L)=>L!==null&&L!==void 0))],[X,W]=await Promise.all([$.length?D.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],G.length?D.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),Z=X.reduce((L,N)=>{return L[N.id]=N,L},{}),Y=W.reduce((L,N)=>{return L[N.id]=N,L},{});return J.map((L)=>({...L,shipping_zone:L.shipping_zone_id?Z[L.shipping_zone_id]:[],shipping_method:L.shipping_method_id?Y[L.shipping_method_id]:[]}))}async function AX(J){try{return await D.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function Y4(J,$){try{return await D.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function n$(J){if(!J?.countryCode)return null;try{let $=await D.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let G=null;for(let X of $){let W=1;if(J.region&&X.regions&&MX(X.regions,J.region))W=2;if(J.postalCode&&X.postal_codes&&MX(X.postal_codes,J.postalCode))W=3;if(!G||W>G.score)G={id:X.id,score:W}}return G?.id??null}catch{return null}}async function _X(J,$){let G=await n$($);if(G==null)return;return Y4(J,G)}async function OX(J,$){return await n$($)===J}function MX(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 D.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function UX(J){try{return await D.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:fX}=globalThis.Bun;import{db as L4}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 K0(J,$){let G=n0(J,$,"shipping_method_id"),X=n0(J,$,"shipping_zone_id"),W=n0(J,$,"weight_from"),Z=n0(J,$,"weight_to"),Y=n0(J,$,"rate");if(!Number.isSafeInteger(G)||G<1)throw new 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(W)||W<0)throw new k("Weight from must be a non-negative number.");if(!Number.isFinite(Z)||Z<W)throw new k("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(Y)||Y<0)throw new k("Rate must be a non-negative integer in minor currency units.");let[L,N]=await Promise.all([l$(G),i$(X)]);if(!L)throw new k(`Shipping method ${G} was not found.`);if(!N)throw new k(`Shipping zone ${X} was not found.`);if(Number(N.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 K0($);let W=fX(),Z={...$,shipping_method_id:G,shipping_zone_id:X,uuid:W};await L4.insertInto("shipping_rates").values(Z).executeTakeFirst();let Y=await L4.selectFrom("shipping_rates").where("uuid","=",W).selectAll().executeTakeFirst();if(!Y)throw Error("Failed to resolve created shipping rate");return Y}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function qX(J){if(!J.length)return 0;try{for(let X of J){let W=i(X);await K0(W)}let $=J.map((X)=>({...i(X),uuid:fX()})),G=await L4.insertInto("shipping_rates").values($).executeTakeFirst();return F(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 K0(X,G);let W=await i0.updateTable("shipping_rates").set({...X,updated_at:o$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!W)return;return W}catch(G){if(G instanceof 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 W=await i0.updateTable("shipping_rates").set({...i(X),updated_at:o$(new Date)}).where("id","=",G).executeTakeFirst();if(F(W)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function CX(J,$){try{let G=await i0.updateTable("shipping_rates").set({...i($),updated_at:o$(new Date)}).where("shipping_zone_id","=",J).executeTakeFirst();return F(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${G.message}`);throw G}}async function hX(J,$){try{let G=await i0.updateTable("shipping_rates").set({...i($),updated_at:o$(new Date)}).where("shipping_method_id","=",J).executeTakeFirst();return F(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var G1={};z(G1,{startStop:()=>vX,startRoute:()=>bX,routeTrackingChannel:()=>N4,recordDriverPing:()=>IX,orderTrackingChannel:()=>r,isWithin:()=>kG,hasCoordinates:()=>m0,failStop:()=>yX,estimateSecondsRemaining:()=>I$,emitDeliveryStarted:()=>e$,emitDeliveryPosition:()=>d$,emitDeliveryNearby:()=>r$,emitDeliveryFailed:()=>J1,emitDeliveryCompleted:()=>$1,emitDeliveryAssigned:()=>a$,emitDeliveryArrived:()=>t$,distanceInMeters:()=>e,completeStop:()=>DX,broadcastToChannel:()=>o,bearingInDegrees:()=>h$,assignStop:()=>gX,NEARBY_RADIUS_METERS:()=>K4,ARRIVAL_RADIUS_METERS:()=>F4});function r(J){return`order.${J}`}function N4(J){return`delivery-route.${J}`}async function U0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function o(J,$,G){try{let X=await import("@stacksjs/realtime").catch(()=>null);if(!X)return;let W=X.channel;if(typeof W!=="function")return;await W(J).broadcast($,G,"private")}catch{}}async function d$(J,$,G){await Promise.all([...J.map((X)=>o(r(X),"delivery:position",G)),$==null?Promise.resolve():o(N4($),"delivery:position",G)])}async function a$(J){if(await U0("delivery:assigned",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:assigned",{stop:J})}async function e$(J){if(await U0("delivery:started",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:started",{stop:J})}async function r$(J,$,G){if(await U0("delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G}),J.order_id!=null)await o(r(J.order_id),"delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G})}async function t$(J){if(await U0("delivery:arrived",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:arrived",{stop:J})}async function $1(J){if(await U0("delivery:completed",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:completed",{stop:J})}async function J1(J,$){await U0("delivery:failed",{stop:J,reason:$})}var{randomUUIDv7:AW}=globalThis.Bun;import{db as y}from"@stacksjs/database";var K4=400,F4=60,_W=250;async function IX(J){let $=J.recordedAt??new Date().toISOString(),G=typeof J.accuracy!=="number"||J.accuracy<=_W,X=await y.selectFrom("drivers").where("id","=",J.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!X)throw Error(`Unknown driver: ${J.driverId}`);let W=m0(X)?{latitude:X.latitude,longitude:X.longitude}:null,Z=typeof J.heading==="number"?J.heading:W?h$(W,J):null,Y=await OW(J.driverId),L=Y?await RW(Y.id):null,N=null,K=null,Q=!1,H=!1,x=L&&m0({latitude:L.latitude??void 0,longitude:L.longitude??void 0})?{latitude:L.latitude,longitude:L.longitude}:null;if(G&&L&&x)N=Math.round(e(J,x)),K=I$(N,J.speed??0),H=N<=F4&&L.arrived_at==null,Q=!H&&N<=K4&&L.status==="en_route"&&L.notified_nearby_at==null;let _=await UW({driverId:J.driverId,routeId:Y?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Z,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$});if(G)await y.updateTable("drivers").set({latitude:J.latitude,longitude:J.longitude,heading:Z,speed:J.speed??0,last_ping_at:$}).where("id","=",J.driverId).execute();if(L&&(N!=null||K!=null))await y.updateTable("delivery_stops").set({eta_at:K==null?L.eta_at:new Date(Date.now()+K*1000).toISOString()}).where("id","=",L.id).execute();if(G)await d$(L?.order_id==null?[]:[L.order_id],Y?.id??null,{driverId:J.driverId,routeId:Y?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Z,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$,distanceToStopMeters:N,etaSeconds:K});if(Q&&L)await y.updateTable("delivery_stops").set({notified_nearby_at:$}).where("id","=",L.id).execute(),await r$(L,N,K);if(H&&L)await y.updateTable("delivery_stops").set({status:"arrived",arrived_at:$}).where("id","=",L.id).execute(),await t$({...L,status:"arrived",arrived_at:$});return{pingId:_,routeId:Y?.id??null,stopId:L?.id??null,distanceToStopMeters:N,etaSeconds:K,crossedNearby:Q,crossedArrival:H}}async function OW(J){return await y.selectFrom("delivery_routes").where("driver_id","=",J).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function RW(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 UW(J){let $=AW();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:PW}=globalThis.Bun;import{db as f}from"@stacksjs/database";async function gX(J){let $=PW(),G=J.sequence??await TW(J.deliveryRouteId);await f.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 fW($);if(X)await a$(X);return X??{}}async function vX(J){await f.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",J).execute();let $=await H4(J);if(!$)return null;if($.order_id!=null)await Q4($.order_id,"OUT_FOR_DELIVERY");return await e$($),$}async function DX(J,$){let G=new Date().toISOString();await f.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await EW(J)?{}:{arrived_at:G},...$?{notes:$}:{}}).where("id","=",J).execute();let X=await H4(J);if(!X)return null;if(X.order_id!=null)await Q4(X.order_id,"DELIVERED");return await $1(X),await mX(X.delivery_route_id),X}async function yX(J,$){await f.updateTable("delivery_stops").set({status:"failed",notes:$}).where("id","=",J).execute();let G=await H4(J);if(!G)return null;if(G.order_id!=null)await Q4(G.order_id,"SHIPPED");return await J1(G,$),await mX(G.delivery_route_id),G}async function bX(J){await f.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 f.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let G=await f.selectFrom("delivery_routes").where("id","=",J).select(["driver_id"]).executeTakeFirst();if(await f.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",J).execute(),G?.driver_id!=null)await f.updateTable("drivers").set({status:"active"}).where("id","=",G.driver_id).execute()}async function Q4(J,$){let G=await f.selectFrom("orders").where("id","=",J).select(["id","status"]).executeTakeFirst();if(!G)return;let X=await Promise.resolve().then(() => (V0(),xJ)),{canTransition:W,emitForStatus:Z}=X,Y=SW(G.status,$,W);if(Y.length===0){let{log:L}=await import("@stacksjs/logging").catch(()=>({log:null}));L?.warn(`[delivery] refused to move order ${J} from ${G.status} to ${$}: no legal transition`);return}for(let L of Y)await f.updateTable("orders").set({status:L}).where("id","=",J).execute(),await Z(L,{...G,status:L})}function SW(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 TW(J){return(await f.selectFrom("delivery_stops").where("delivery_route_id","=",J).select(["sequence"]).execute()).reduce((G,X)=>Math.max(G,X.sequence??0),0)+1}async function EW(J){return(await f.selectFrom("delivery_stops").where("id","=",J).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function H4(J){return await f.selectFrom("delivery_stops").where("id","=",J).selectAll().executeTakeFirst()??null}async function fW(J){return await f.selectFrom("delivery_stops").where("uuid","=",J).selectAll().executeTakeFirst()??null}var Y1={};z(Y1,{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 X1}from"@stacksjs/database";async function pX(J){try{let $=await X1.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function lX(J){try{let $=await X1.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function cX(J){if(!J.length)return 0;try{let $=await X1.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function uX(J){if(!J.length)return 0;try{let $=await X1.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:nX}=globalThis.Bun;import{db as x4}from"@stacksjs/database";async function iX(J){try{let $=nX(),G={...v0(J),uuid:$};await x4.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await x4.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping zone");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function oX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...v0(X),uuid:nX()})),G=await x4.insertInto("shipping_zones").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as W1}from"@stacksjs/database";import{formatDate as Z1}from"@stacksjs/orm";async function sX(J,$){try{if(!J)throw Error("Shipping zone ID is required for update");let G=await W1.updateTable("shipping_zones").set({...v0($),updated_at:Z1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone: ${G.message}`);throw G}}async function dX(J,$){try{let G=await W1.updateTable("shipping_zones").set({status:$,updated_at:Z1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone status: ${G.message}`);throw G}}async function aX(J,$){try{let G=await W1.updateTable("shipping_zones").set({countries:$,updated_at:Z1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone countries");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${G.message}`);throw G}}async function eX(J,$,G){try{let X={updated_at:Z1(new Date)};if($!==void 0)X.regions=$;if(G!==void 0)X.postal_codes=G;let W=await W1.updateTable("shipping_zones").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!W)throw Error("Failed to update regions and postal codes");return W}catch(X){if(X instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${X.message}`);throw X}}var wW={digital:j$,drivers:C$,geocoding:v$,licenses:b$,methods:c$,rates:s$,routes:w$,tracking:G1,zones:Y1},qW=wW;var M4={};z(M4,{updateStatus:()=>K9,updateRate:()=>F9,updateDefaultStatus:()=>Q9,update:()=>N9,store:()=>Y9,fetchById:()=>G9,fetchAll:()=>X9,destroy:()=>tX,bulkStore:()=>L9,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 F($)>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 F($)}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:W9}=globalThis.Bun;import{db as Z9}from"@stacksjs/database";async function Y9(J){try{return await Z9.transaction(async($)=>{let G={...J,uuid:W9()};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 L9(J){if(!J.length)return 0;try{return await Z9.transaction(async($)=>{let G=0;for(let X of J){let W={...X,uuid:W9()};if(W.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(W).executeTakeFirst())G++}return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as L1}from"@stacksjs/database";import{formatDate as N1}from"@stacksjs/orm";async function N9(J,$){try{if(!J)throw Error("Tax rate ID is required for update");return await L1.transaction(async(G)=>{let X=await G.selectFrom("tax_rates").select("is_default").where("id","=",J).executeTakeFirst();if(!X)return;let W=$.is_default??Boolean(X.is_default),Z=N1(new Date);if(W)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Z}).where("id","!=",J).execute();let Y=await G.updateTable("tax_rates").set({...$,updated_at:Z}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function K9(J,$){try{let G=await L1.updateTable("tax_rates").set({status:$,updated_at:N1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update tax rate status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate status: ${G.message}`);throw G}}async function F9(J,$){try{let G=await L1.updateTable("tax_rates").set({rate:$,updated_at:N1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update rate information");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update rate information: ${G.message}`);throw G}}async function Q9(J,$){try{return await L1.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",J).executeTakeFirst())return!1;let W=N1(new Date);if($)await G.updateTable("tax_rates").set({is_default:!1,updated_at:W}).where("id","!=",J).execute();return await G.updateTable("tax_rates").set({is_default:$,updated_at:W}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var R4={};z(R4,{restaurant:()=>S0,products:()=>F1,default:()=>bW});var F1={};z(F1,{updateStatus:()=>k9,updatePartySize:()=>C9,update:()=>K1,store:()=>q9,fetchWaiting:()=>U9,fetchPurchasedBetweenDates:()=>O9,fetchNotifiedBetweenDates:()=>_9,fetchCountByStatus:()=>P9,fetchCountBySource:()=>M9,fetchCountByQuantity:()=>B9,fetchCountByDateGrouped:()=>E9,fetchCountByDate:()=>z9,fetchCountByAllQuantities:()=>A9,fetchCountBetweenDates:()=>T9,fetchConversionRates:()=>S9,fetchCancelledBetweenDates:()=>R9,fetchById:()=>o0,fetchAll:()=>V9,destroy:()=>H9,bulkStore:()=>j9,bulkDestroy:()=>x9});import{db as z4}from"@stacksjs/database";async function H9(J){try{let $=await z4.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await z4.deleteFrom("waitlist_products").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function x9(J){if(!J.length)return 0;try{let $=await z4.deleteFrom("waitlist_products").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as T}from"@stacksjs/orm";async function o0(J){return await A.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function V9(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function M9(J,$){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(J&&$){let W=T(J),Z=T($);G=G.where("created_at",">=",W).where("created_at","<=",Z)}return(await G.execute()).reduce((W,{source:Z,count:Y})=>{return W[Z]=Y,W},{})}async function 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($),W=T(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",W).executeTakeFirst())?.count??0}async function 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 W=T(J),Z=T($);G=G.where("created_at",">=",W).where("created_at","<=",Z)}return(await G.execute()).reduce((W,{quantity:Z,count:Y})=>{return W[Z]=Y,W},{})}async function _9(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 O9(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 Z=T($),Y=T(G);X=X.where("created_at",">=",Z).where("created_at","<=",Y)}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 N=T(J),K=T($);G=G.where("created_at",">=",N).where("created_at","<=",K)}let X=await G.execute(),W=X.reduce((N,{count:K})=>N+K,0),Z=X.find((N)=>N.status==="purchased")?.count??0,Y=W>0?Z/W*100:0,L=X.reduce((N,{status:K,count:Q})=>{return N[K]={count:Q,percentage:W>0?Q/W*100:0},N},{});return{totalConversionRate:Y,statusBreakdown:L}}async function 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 Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}let W=(await G.execute()).reduce((Z,{created_at:Y})=>{let L=(Y||"").split("T")[0]||"unknown";return Z[L]=(Z[L]||0)+1,Z},{});return Object.entries(W).map(([Z,Y])=>({date:Z,count:Y})).sort((Z,Y)=>Z.date.localeCompare(Y.date))}var{randomUUIDv7:w9}=globalThis.Bun;import{db as B4}from"@stacksjs/database";import{formatDate as f9}from"@stacksjs/orm";var jW={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function kW(J){return typeof J==="number"||J instanceof Date?f9(J):J}function s0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,W])=>W!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let W of["notified_at","purchased_at","cancelled_at"])if(G[W]!==void 0)G[W]=kW(G[W]);let X=jW[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=f9(new Date);return G}async function q9(J){try{let $=w9(),G={...s0(J),uuid:$,status:J.status||"waiting"};await B4.insertInto("waitlist_products").values(G).executeTakeFirst();let X=await B4.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create waitlist product");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function j9(J){if(!J.length)return 0;try{let $=J.map((X)=>({...s0(X),status:X.status||"waiting",uuid:w9()})),G=await B4.insertInto("waitlist_products").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as CW}from"@stacksjs/database";import{formatDate as hW}from"@stacksjs/orm";async function K1(J,$){try{if(!J)throw Error("Waitlist product ID is required for update");let G=await o0(J);if(!G)return;await CW.updateTable("waitlist_products").set({...s0($,G),updated_at:hW(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 K1(J,{status:$})}async function C9(J,$){return await K1(J,{quantity:$})}var S0={};z(S0,{updateWaitTimes:()=>W3,updateStatus:()=>G3,updateQueuePosition:()=>Z3,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:()=>v9,fetchCountByPartySize:()=>y9,fetchCountByDate:()=>D9,fetchCountByAllPartySizes:()=>b9,fetchConversionRates:()=>c9,fetchById:()=>d0,fetchBetweenDates:()=>m9,fetchAverageWaitTimes:()=>u9,fetchAll:()=>g9,destroy:()=>h9,bulkStore:()=>J3,bulkDestroy:()=>I9});import{db as A4}from"@stacksjs/database";async function h9(J){try{let $=await A4.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await A4.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function I9(J){if(!J.length)return 0;try{let $=await A4.deleteFrom("waitlist_restaurants").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as M}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function d0(J){return await M.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function g9(){return await M.selectFrom("waitlist_restaurants").selectAll().execute()}async function v9(){return(await M.selectFrom("waitlist_restaurants").select(["table_preference",M.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:G,count:X})=>{return $[G]=X,$},{})}async function D9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),W=g(G);return(await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",W).executeTakeFirst())?.count??0}async function y9(J){return(await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function b9(){return(await M.selectFrom("waitlist_restaurants").select(["party_size",M.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:G,count:X})=>{return $[G]=X,$},{})}async function m9(J,$){let G=g(J),X=g($);return await M.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",X).execute()}async function p9(J,$){let G=g(J),X=g($);return await M.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",X).where("status","=","seated").execute()}async function l9(){return await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function c9(){let J=await M.selectFrom("waitlist_restaurants").select(["status",M.fn.count("id").as("count")]).groupBy("status").execute(),$=J.reduce((Z,{count:Y})=>Z+Y,0),G=J.find((Z)=>Z.status==="seated")?.count??0,X=$>0?Number(G)/$*100:0,W=J.reduce((Z,{status:Y,count:L})=>{return Z[Y]={count:L,percentage:$>0?L/$*100:0},Z},{});return{totalConversionRate:X,statusBreakdown:W}}async function u9(){let J=await M.selectFrom("waitlist_restaurants").select([M.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),M.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:J?.avg_quoted_wait_time??0,averageActualWaitTime:J?.avg_actual_wait_time??0}}async function n9(){let J=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((X,W)=>X+(W.quoted_wait_time??0),0),G=J.length>0?$/J.length:0;return{entries:J,totalQuotedWaitTime:$,averageQuotedWaitTime:G}}async function i9(){let J=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((W,Z)=>W+Z.party_size,0),G=J.length>0?$/J.length:0,X=J.reduce((W,Z)=>{return W[Z.party_size]=(W[Z.party_size]||0)+1,W},{});return{entries:J,totalPartySize:$,averagePartySize:G,partySizeBreakdown:X}}async function 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($),W=g(G),Z=await M.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",X).where("check_in_time","<=",W).execute(),Y=Z.length,L=Z.reduce((H,x)=>H+x.party_size,0),N=Y>0?L/Y:0,K=Z.reduce((H,x)=>{return H[x.table_preference]=(H[x.table_preference]||0)+1,H},{}),Q=Z.reduce((H,x)=>{return H[x.party_size]=(H[x.party_size]||0)+1,H},{});return{totalTablesTurned:Y,averagePartySize:N,totalCustomersSeated:L,breakdownByTablePreference:K,breakdownByPartySize:Q}}async function s9(J,$){let G=g(J),X=g($),W=await M.selectFrom("waitlist_restaurants").select(["status",M.fn.count("id").as("count")]).where("check_in_time",">=",G).where("check_in_time","<=",X).groupBy("status").execute(),Z=W.reduce((K,{count:Q})=>K+Q,0),Y=W.find((K)=>K.status==="seated")?.count??0,L=Z>0?Number(Y)/Z*100:0,N=W.reduce((K,{status:Q,count:H})=>{return K[Q]={count:H,percentage:Z>0?H/Z*100:0},K},{});return{totalEntries:Z,seatedEntries:Y,seatingRate:L,statusBreakdown:N}}async function d9(J,$){let G=g(J),X=g($),W=M.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",X),Z=await M.selectFrom("waitlist_restaurants").select(M.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",X).executeTakeFirst(),Y=await W.execute(),L=Y.length,N=Z?.count&&Z.count>0?L/Z.count*100:0,K=Y.reduce((O,U)=>O+(U.quoted_wait_time??0),0),Q=L>0?K/L:0,H=Y.reduce((O,U)=>O+U.party_size,0),x=L>0?H/L:0,_=Y.reduce((O,U)=>{return O[U.table_preference]=(O[U.table_preference]||0)+1,O},{}),R=Y.reduce((O,U)=>{return O[U.party_size]=(O[U.party_size]||0)+1,O},{});return{totalNoShows:L,noShowRate:N,averageQuotedWaitTime:Q,averagePartySize:x,breakdownByTablePreference:_,breakdownByPartySize:R}}async function a9(){let J=await M.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=J.reduce((W,Z)=>W+(Z.quoted_wait_time||0),0),G=J.reduce((W,Z)=>W+(Z.actual_wait_time||0),0),X=J.length;return{averageQuoted:X>0?$/X:0,averageActual:X>0?G/X:0}}async function e9(){let J=Date.now()-86400000,$=await M.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),G=Array.from({length:24},(X,W)=>({hour:W,count:$.filter((Z)=>{return Z.seated_at===W}).length}));return{total:$.length,byHour:G}}async function r9(){return(await M.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,G)=>{let X=G.created_at;if(!$[X])$[X]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[X].total++,$[X][G.status]++,$},{})}var{randomUUIDv7:t9}=globalThis.Bun;import{db as O4}from"@stacksjs/database";import{formatDate as _4}from"@stacksjs/orm";var IW={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function gW(J){if(typeof J==="number")return _4(J<=2147483647?J*1000:J);if(J instanceof Date)return _4(J);return J}function a0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,W])=>W!==void 0));for(let W of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[W]!==void 0)G[W]=gW(G[W]);let X=IW[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=_4(new Date);return G}async function $3(J){try{let $=t9(),G={...a0(J),status:J.status||"waiting",uuid:$};await O4.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let X=await O4.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create restaurant waitlist entry");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function J3(J){if(!J.length)return 0;try{let $=J.map((X)=>({...a0(X),status:X.status||"waiting",uuid:t9()})),G=await O4.insertInto("waitlist_restaurants").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as vW}from"@stacksjs/database";import{formatDate as DW}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 vW.updateTable("waitlist_restaurants").set({...a0($,G),updated_at:DW(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 W3(J,$,G){return await P0(J,{quoted_wait_time:$,...G===void 0?{}:{actual_wait_time:G}})}async function Z3(J,$){return await P0(J,{queue_position:$})}var yW={products:F1,restaurant:S0},bW=yW;var mW={coupons:Q1,customers:H1,devices:B1,errors:O1,giftCards:U1,orders:k1,payments:C1,products:b1,receipts:n1,restaurant:S0,shippings:V4,tax:M4,waitlists:R4},Rx=mW;export{R4 as waitlists,M4 as tax,V4 as shippings,S0 as restaurant,n1 as receipts,b1 as products,C1 as payments,k1 as orders,U1 as giftCards,O1 as errors,B1 as devices,Rx as default,H1 as customers,Q1 as coupons,mW 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 x=await Y0(J);if(x)return x;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),x=Number(N?.count||0),O=H-x,R=x!==0?O/x*100:H>0?100:0;return{current_period:H,previous_period:x,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 x$}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 x$(422,"Parent category ID must be a positive integer");if($&&!await j($))throw new x$(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 x$)throw $;if(o3($))throw new x$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function 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 M$,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:M$(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:M$(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:M$(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:M$(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:()=>M6,fetchById:()=>u,fetchAll:()=>x6,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 x6(){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 M6(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:()=>M2,fetchById:()=>F2,fetchAll:()=>Q2,destroy:()=>L2,bulkUpdate:()=>B2,bulkStore:()=>x2,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 x2(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 M2(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,x)=>({hour:x,count:0}));return L.forEach((H)=>{let x=YZ(H.timestamp);if(!x)return;N[x.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 M1={};z(M1,{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:()=>xG,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 xG(){return await NG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:MG}=globalThis.Bun;import{db as s4}from"@stacksjs/database";async function VG(J){try{let $=MG(),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:MG()})),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:()=>xZ,formatQuery:()=>R0,checkCoverage:()=>MZ,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 xZ(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 MZ(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:()=>xX,destroyByMethod:()=>MX,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 xX(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 MX(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,x=K&&m0({latitude:K.latitude??void 0,longitude:K.longitude??void 0})?{latitude:K.latitude,longitude:K.longitude}:null;if(G&&K&&x)W=Math.round(e(J,x)),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(() => (M0(),xJ)),{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 x1}from"@stacksjs/database";async function iX(J){try{let $=nX(),G={...D0(J),uuid:$};await x1.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await x1.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping zone");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function oX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...D0(X),uuid:nX()})),G=await x1.insertInto("shipping_zones").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as 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:()=>M9,destroy:()=>H9,bulkStore:()=>j9,bulkDestroy:()=>x9});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 x9(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 M9(){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,x)=>H+x.party_size,0),W=L>0?K/L:0,F=Y.reduce((H,x)=>{return H[x.table_preference]=(H[x.table_preference]||0)+1,H},{}),N=Y.reduce((H,x)=>{return H[x.party_size]=(H[x.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),x=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:x,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:M1,tax:V1,waitlists:R1},R8=mZ;export{R1 as waitlists,V1 as tax,M1 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};
|