@stacksjs/commerce 0.70.369 → 0.70.371
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +5 -5
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var Q3=Object.defineProperty;var N3=(J)=>J;function H3(J,$){this[J]=N3.bind(null,$)}var z=(J,$)=>{for(var G in $)Q3(J,G,{get:$[G],enumerable:!0,configurable:!0,set:H3.bind($,G)})};var M3=(J,$)=>()=>(J&&($=J(J=0)),$);var J0=import.meta.require;var VJ={};z(VJ,{emitOrderShipped:()=>K$,emitOrderRefunded:()=>M0,emitOrderPaid:()=>d,emitOrderOutForDelivery:()=>xJ,emitOrderDelivered:()=>W$,emitOrderCreated:()=>j0,emitOrderCancelled:()=>H0,emitForStatus:()=>f0,canTransition:()=>w0});function w0(J,$){if(J===$)return!0;return D3[J]?.includes($)??!1}async function Z0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function j0(J){await Z0("order:created",{order:J})}async function d(J,$){await Z0("order:paid",{order:J,payment:$})}async function K$(J){await Z0("order:shipped",{order:J})}async function xJ(J){await Z0("order:out_for_delivery",{order:J})}async function W$(J){await Z0("order:delivered",{order:J})}async function H0(J,$){await Z0("order:cancelled",{order:J,reason:$})}async function M0(J,$){await Z0("order:refunded",{order:J,refundAmount:$})}async function f0(J,$){switch(J){case"PROCESSING":return d($);case"SHIPPED":return K$($);case"OUT_FOR_DELIVERY":return xJ($);case"DELIVERED":return W$($);case"CANCELLED":return H0($);case"REFUNDED":return M0($);case"PENDING":default:}}var D3;var x0=M3(()=>{D3={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","OUT_FOR_DELIVERY","CANCELLED","REFUNDED"],SHIPPED:["OUT_FOR_DELIVERY","DELIVERED","REFUNDED"],OUT_FOR_DELIVERY:["DELIVERED","SHIPPED","CANCELLED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]}});var N4={};z(N4,{update:()=>i1,store:()=>l1,redeem:()=>o1,getActiveCouponsMoMChange:()=>b1,fetchTopRedeemedCoupons:()=>D1,fetchStats:()=>C1,fetchRedemptionTrend:()=>v1,fetchRedemptionStats:()=>g1,fetchCouponCountsByType:()=>h1,fetchCouponCounts:()=>I1,fetchConversionRate:()=>y1,fetchById:()=>G0,fetchByCode:()=>f1,fetchAll:()=>j1,fetchActive:()=>k1,deleteExpiredCoupons:()=>E1,deleteCoupons:()=>T1,deleteCoupon:()=>S1});import{db as e0}from"@stacksjs/database";import{formatDate as x3}from"@stacksjs/orm";function Q(J){if(typeof J==="number")return Number.isFinite(J)?J:0;if(typeof J==="bigint")return Number(J);if(!J||typeof J!=="object")return 0;let $=J;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[G]!==void 0&&$[G]!==null)return Q($[G]);if(Array.isArray(J))return J.reduce((G,X)=>G+Q(X),0);return 0}async function S1(J){let $=await e0.deleteFrom("coupons").where("id","=",J).executeTakeFirst();return Q($)>0}async function T1(J){if(!J.length)return 0;return(await e0.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function E1(){let J=x3(new Date),$=await e0.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return Q($)}import{db as x}from"@stacksjs/database";import{extractDate as q1,formatDate as w1}from"@stacksjs/orm";import{camelCase as V3}from"@stacksjs/strings";function t0(J){let $=Object.fromEntries(Object.entries(J).map(([G,X])=>[V3(G),X]));if($.endDate)$.endDate=q1(new Date($.endDate));if($.startDate)$.startDate=q1(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function j1(){return(await x.selectFrom("coupons").selectAll().execute()).map(t0)}async function G0(J){let $=await x.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function f1(J){let $=await x.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return t0($);return}async function k1(){let J=w1(new Date);return(await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map(t0)}async function C1(){let J=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).executeTakeFirst(),$=w1(new Date),G=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(x.fn.count("id").as("count")).executeTakeFirst(),X=await x.selectFrom("coupons").select(["discount_type",x.fn.count("id").as("count")]).groupBy("discount_type").execute(),Z=await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),Y=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",$).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(J?.count||0),active:Number(G?.count||0),by_type:X,most_used:Z,upcoming:Y}}async function I1(){let J=new Date,$=new Date(J);$.setDate(J.getDate()-7);let G=new Date(J);G.setMonth(J.getMonth()-1);let X=new Date(J);X.setFullYear(J.getFullYear()-1);let Z=await r0(null,null,J),Y=await r0($,null,J),L=await r0(G,null,J),K=await r0(X,null,J);return{week:Y,month:L,year:K,all_time:Z}}async function r0(J,$,G){let X=x.selectFrom("coupons");if(J)X=X.where("created_at",">=",J.toISOString());if($)X=X.where("created_at","<=",$.toISOString());let Z=await X.select(x.fn.count("id").as("count")).executeTakeFirst(),Y=x.selectFrom("coupons");if(J)Y=Y.where("created_at",">=",J.toISOString());if($)Y=Y.where("created_at","<=",$.toISOString());Y=Y.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let L=await Y.select(x.fn.count("id").as("count")).executeTakeFirst(),K=Number(Z?.count||0),W=Number(L?.count||0),F=K-W;return{total:K,active:W,inactive:F}}async function h1(){let J=new Date,$=await x.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:X}of $){let Z=await x.selectFrom("coupons").where("discount_type","=",X).select(x.fn.count("id").as("count")).executeTakeFirst(),Y=await x.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),L=Number(Z?.count||0),K=Number(Y?.count||0);G[X]={total:L,active:K,inactive:L-K}}return G}async function g1(){let J=await x.selectFrom("coupons").select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,G=new Date($);G.setDate($.getDate()-7);let X=new Date($);X.setMonth($.getMonth()-1);let Z=new Date($);Z.setFullYear($.getFullYear()-1);let Y=await x.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await x.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),K=await x.selectFrom("coupons").where("updated_at",">=",Z.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await x.selectFrom("coupons").select(["discount_type",x.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),F={};return W.forEach((N)=>{F[N.discount_type]=Number(N.total||0)}),{total:Number(J?.total||0),week:Number(Y?.total||0),month:Number(L?.total||0),year:Number(K?.total||0),by_type:F}}async function D1(J=5){return await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(J).execute()}async function v1(J=30){let $=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-J);let X=await x.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),Z={};return X.forEach((Y)=>{let L=Y.updated_at?new Date(Y.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!Z[L])Z[L]=0;Z[L]+=Y?.usage_count||0}),Object.entries(Z).map(([Y,L])=>({date:Y,count:L}))}async function y1(){let J=new Date,$=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),G=await x.selectFrom("coupons").where("usage_count",">",0).select(x.fn.count("id").as("count")).executeTakeFirst(),X=Number($?.count||0),Z=Number(G?.count||0);return{rate:X>0?Z/X*100:0,total_active:X,total_redeemed:Z}}async function b1(){let J=new Date,$=new Date(J.getFullYear(),J.getMonth(),1),G=new Date(J.getFullYear(),J.getMonth()-1,1),X=new Date(J.getFullYear(),J.getMonth(),0),Z=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),Y=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",G).executeTakeFirst(),L=Number(Z?.count||0),K=Number(Y?.count||0),W=L-K,F=K!==0?W/K*100:L>0?100:0;return{current_month:L,previous_month:K,difference:W,percentage_change:F}}var{randomUUIDv7:z3}=globalThis.Bun;import{db as m1}from"@stacksjs/database";import{HttpError as p1}from"@stacksjs/error-handling";import{isUniqueViolation as B3}from"@stacksjs/orm";async function l1(J){try{let $=z3();return await m1.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await m1.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof p1)throw $;if(B3($))throw new p1(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as u1}from"@stacksjs/database";import{HttpError as c1}from"@stacksjs/error-handling";import{formatDate as n1,isUniqueViolation as A3}from"@stacksjs/orm";async function i1(J,$){if(!await G0(J))return;try{return await u1.updateTable("coupons").set({...$,updated_at:n1(new Date)}).where("id","=",J).execute(),await G0(J)}catch(X){if(X instanceof c1)throw X;if(A3(X))throw new c1(409,"A coupon with this code already exists");if(X instanceof Error)throw Error(`Failed to update coupon: ${X.message}`);throw X}}async function o1(J){let $=n1(new Date),G=await u1.unsafe(`UPDATE coupons
|
|
2
|
+
var H3=Object.defineProperty;var M3=(J)=>J;function x3(J,$){this[J]=M3.bind(null,$)}var B=(J,$)=>{for(var G in $)H3(J,G,{get:$[G],enumerable:!0,configurable:!0,set:x3.bind($,G)})};var z3=(J,$)=>()=>(J&&($=J(J=0)),$);var J0=import.meta.require;var VJ={};B(VJ,{emitOrderShipped:()=>W$,emitOrderRefunded:()=>M0,emitOrderPaid:()=>d,emitOrderOutForDelivery:()=>BJ,emitOrderDelivered:()=>F$,emitOrderCreated:()=>f0,emitOrderCancelled:()=>H0,emitForStatus:()=>k0,canTransition:()=>w0});function w0(J,$){if(J===$)return!0;return y3[J]?.includes($)??!1}async function Z0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function f0(J){await Z0("order:created",{order:J})}async function d(J,$){await Z0("order:paid",{order:J,payment:$})}async function W$(J){await Z0("order:shipped",{order:J})}async function BJ(J){await Z0("order:out_for_delivery",{order:J})}async function F$(J){await Z0("order:delivered",{order:J})}async function H0(J,$){await Z0("order:cancelled",{order:J,reason:$})}async function M0(J,$){await Z0("order:refunded",{order:J,refundAmount:$})}async function k0(J,$){switch(J){case"PROCESSING":return d($);case"SHIPPED":return W$($);case"OUT_FOR_DELIVERY":return BJ($);case"DELIVERED":return F$($);case"CANCELLED":return H0($);case"REFUNDED":return M0($);case"PENDING":default:}}var y3;var x0=z3(()=>{y3={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","OUT_FOR_DELIVERY","CANCELLED","REFUNDED"],SHIPPED:["OUT_FOR_DELIVERY","DELIVERED","REFUNDED"],OUT_FOR_DELIVERY:["DELIVERED","SHIPPED","CANCELLED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]}});var H4={};B(H4,{update:()=>o1,store:()=>c1,redeem:()=>s1,getActiveCouponsMoMChange:()=>m1,fetchTopRedeemedCoupons:()=>v1,fetchStats:()=>I1,fetchRedemptionTrend:()=>y1,fetchRedemptionStats:()=>D1,fetchCouponCountsByType:()=>g1,fetchCouponCounts:()=>h1,fetchConversionRate:()=>b1,fetchById:()=>G0,fetchByCode:()=>k1,fetchAll:()=>f1,fetchActive:()=>C1,deleteExpiredCoupons:()=>q1,deleteCoupons:()=>E1,deleteCoupon:()=>T1});import{db as e0}from"@stacksjs/database";import{formatDate as B3}from"@stacksjs/orm";function Q(J){if(typeof J==="number")return Number.isFinite(J)?J:0;if(typeof J==="bigint")return Number(J);if(!J||typeof J!=="object")return 0;let $=J;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[G]!==void 0&&$[G]!==null)return Q($[G]);if(Array.isArray(J))return J.reduce((G,X)=>G+Q(X),0);return 0}async function T1(J){let $=await e0.deleteFrom("coupons").where("id","=",J).executeTakeFirst();return Q($)>0}async function E1(J){if(!J.length)return 0;return(await e0.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function q1(){let J=B3(new Date),$=await e0.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return Q($)}import{db as x}from"@stacksjs/database";import{extractDate as j1,formatDate as w1}from"@stacksjs/orm";import{camelCase as V3}from"@stacksjs/strings";function $$(J){let $=Object.fromEntries(Object.entries(J).map(([G,X])=>[V3(G),X]));if($.endDate)$.endDate=j1(new Date($.endDate));if($.startDate)$.startDate=j1(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function f1(){return(await x.selectFrom("coupons").selectAll().execute()).map($$)}async function G0(J){let $=await x.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return $$($);return}async function k1(J){let $=await x.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return $$($);return}async function C1(){let J=w1(new Date);return(await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map($$)}async function I1(){let J=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).executeTakeFirst(),$=w1(new Date),G=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(x.fn.count("id").as("count")).executeTakeFirst(),X=await x.selectFrom("coupons").select(["discount_type",x.fn.count("id").as("count")]).groupBy("discount_type").execute(),Z=await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),Y=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",$).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(J?.count||0),active:Number(G?.count||0),by_type:X,most_used:Z,upcoming:Y}}async function h1(){let J=new Date,$=new Date(J);$.setDate(J.getDate()-7);let G=new Date(J);G.setMonth(J.getMonth()-1);let X=new Date(J);X.setFullYear(J.getFullYear()-1);let Z=await t0(null,null,J),Y=await t0($,null,J),L=await t0(G,null,J),K=await t0(X,null,J);return{week:Y,month:L,year:K,all_time:Z}}async function t0(J,$,G){let X=x.selectFrom("coupons");if(J)X=X.where("created_at",">=",J.toISOString());if($)X=X.where("created_at","<=",$.toISOString());let Z=await X.select(x.fn.count("id").as("count")).executeTakeFirst(),Y=x.selectFrom("coupons");if(J)Y=Y.where("created_at",">=",J.toISOString());if($)Y=Y.where("created_at","<=",$.toISOString());Y=Y.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let L=await Y.select(x.fn.count("id").as("count")).executeTakeFirst(),K=Number(Z?.count||0),W=Number(L?.count||0),F=K-W;return{total:K,active:W,inactive:F}}async function g1(){let J=new Date,$=await x.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:X}of $){let Z=await x.selectFrom("coupons").where("discount_type","=",X).select(x.fn.count("id").as("count")).executeTakeFirst(),Y=await x.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),L=Number(Z?.count||0),K=Number(Y?.count||0);G[X]={total:L,active:K,inactive:L-K}}return G}async function D1(){let J=await x.selectFrom("coupons").select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,G=new Date($);G.setDate($.getDate()-7);let X=new Date($);X.setMonth($.getMonth()-1);let Z=new Date($);Z.setFullYear($.getFullYear()-1);let Y=await x.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await x.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),K=await x.selectFrom("coupons").where("updated_at",">=",Z.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await x.selectFrom("coupons").select(["discount_type",x.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),F={};return W.forEach((N)=>{F[N.discount_type]=Number(N.total||0)}),{total:Number(J?.total||0),week:Number(Y?.total||0),month:Number(L?.total||0),year:Number(K?.total||0),by_type:F}}async function v1(J=5){return await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(J).execute()}async function y1(J=30){let $=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-J);let X=await x.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),Z={};return X.forEach((Y)=>{let L=Y.updated_at?new Date(Y.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!Z[L])Z[L]=0;Z[L]+=Y?.usage_count||0}),Object.entries(Z).map(([Y,L])=>({date:Y,count:L}))}async function b1(){let J=new Date,$=await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),G=await x.selectFrom("coupons").where("usage_count",">",0).select(x.fn.count("id").as("count")).executeTakeFirst(),X=Number($?.count||0),Z=Number(G?.count||0);return{rate:X>0?Z/X*100:0,total_active:X,total_redeemed:Z}}async function m1(){let J=new Date,$=new Date(J.getFullYear(),J.getMonth(),1),G=new Date(J.getFullYear(),J.getMonth()-1,1),X=new Date(J.getFullYear(),J.getMonth(),0),Z=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),Y=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",G).executeTakeFirst(),L=Number(Z?.count||0),K=Number(Y?.count||0),W=L-K,F=K!==0?W/K*100:L>0?100:0;return{current_month:L,previous_month:K,difference:W,percentage_change:F}}var{randomUUIDv7:A3}=globalThis.Bun;import{db as p1}from"@stacksjs/database";import{HttpError as l1}from"@stacksjs/error-handling";import{isUniqueViolation as O3}from"@stacksjs/orm";async function c1(J){try{let $=A3();return await p1.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await p1.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof l1)throw $;if(O3($))throw new l1(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as n1}from"@stacksjs/database";import{HttpError as u1}from"@stacksjs/error-handling";import{formatDate as i1,isUniqueViolation as _3}from"@stacksjs/orm";async function o1(J,$){if(!await G0(J))return;try{return await n1.updateTable("coupons").set({...$,updated_at:i1(new Date)}).where("id","=",J).execute(),await G0(J)}catch(X){if(X instanceof u1)throw X;if(_3(X))throw new u1(409,"A coupon with this code already exists");if(X instanceof Error)throw Error(`Failed to update coupon: ${X.message}`);throw X}}async function s1(J){let $=i1(new Date),G=await n1.unsafe(`UPDATE coupons
|
|
3
3
|
SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ?
|
|
4
4
|
WHERE id = ?
|
|
5
5
|
AND (max_uses IS NULL OR usage_count < max_uses)
|
|
6
6
|
AND is_active = 1
|
|
7
7
|
AND (start_date IS NULL OR start_date <= ?)
|
|
8
|
-
AND (end_date IS NULL OR end_date >= ?)`,[$,J,$,$]),X=typeof G?.execute==="function"?await G.execute():G;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0){let W=await G0(J);if(W)return{ok:!0,coupon:W};return{ok:!1,reason:"not-found"}}let Y=await G0(J);if(!Y)return{ok:!1,reason:"not-found"};if(!Y.isActive)return{ok:!1,reason:"inactive"};let L=!Y.startDate||Y.startDate<=$,K=!Y.endDate||Y.endDate>=$;if(!L||!K)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var H4={};z(H4,{update:()=>G7,store:()=>$7,fetchById:()=>$$,fetchAll:()=>r1,destroy:()=>d1,bulkDestroy:()=>a1});import{db as s1}from"@stacksjs/database";async function d1(J){try{let $=await s1.deleteFrom("customers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function a1(J){if(!J.length)return 0;try{let $=await s1.deleteFrom("customers").where("id","in",J).executeTakeFirst();return Q($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as e1}from"@stacksjs/database";async function $$(J){return await e1.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function r1(){return await e1.selectFrom("customers").selectAll().execute()}import{db as O3}from"@stacksjs/database";import{HttpError as t1}from"@stacksjs/error-handling";import{isUniqueViolation as _3}from"@stacksjs/orm";async function $7(J){try{let $={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await O3.insertInto("customers").values($).executeTakeFirst();if(!G)throw Error("Failed to create customer");let X=G.insertId||Number(G.numInsertedOrUpdatedRows);return await $$(Number(X))}catch($){if($ instanceof t1)throw $;if(_3($))throw new t1(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as R3}from"@stacksjs/database";import{HttpError as J7}from"@stacksjs/error-handling";import{formatDate as U3,isUniqueViolation as P3}from"@stacksjs/orm";async function G7(J,$){try{if(!J)throw Error("Customer ID is required for update");let G=await R3.updateTable("customers").set({...$,updated_at:U3(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof J7)throw G;if(P3(G))throw new J7(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var B4={};z(B4,{updateStatus:()=>O7,updatePrintCount:()=>_7,update:()=>A7,storePrintDevicesExport:()=>x7,store:()=>z7,getPrinterStatusCounts:()=>H7,fetchErrorsByDeviceId:()=>Q7,fetchById:()=>l,fetchAll:()=>J$,exportPrintDevices:()=>G$,downloadPrintDevices:()=>M7,destroy:()=>Z7,countTotalPrints:()=>K7,countPrintsByDeviceId:()=>W7,countAll:()=>L7,calculatePrinterHealth:()=>N7,calculateErrorRate:()=>F7,bulkStore:()=>B7,bulkDestroy:()=>Y7});import{db as X7}from"@stacksjs/database";async function Z7(J){try{let $=await X7.deleteFrom("print_devices").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function Y7(J){if(!J.length)return 0;try{let $=await X7.deleteFrom("print_devices").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as S3}from"ts-spreadsheets";import{db as w}from"@stacksjs/database";async function l(J){return await w.selectFrom("print_devices").where("id","=",J).selectAll().executeTakeFirst()}async function J$(){return await w.selectFrom("print_devices").selectAll().execute()}async function L7(){let J=await w.selectFrom("print_devices").select(w.fn.count("id").as("count")).executeTakeFirst();return Number(J?.count||0)}async function K7(){let J=await w.selectFrom("print_devices").select(w.fn.sum("print_count").as("total")).executeTakeFirst();return Number(J?.total||0)}async function W7(J){return(await w.selectFrom("print_devices").select("print_count").where("id","=",J).executeTakeFirst())?.print_count??0}async function F7(){let J=await w.selectFrom("receipts").select([w.fn.count("id").as("total"),w.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.failed_count??0)/J.total*100)}async function Q7(J){return await w.selectFrom("receipts").where("print_device_id","=",J).where("status","=","failed").selectAll().execute()}async function N7(){let J=await w.selectFrom("print_devices").select([w.fn.count("id").as("total"),w.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.online_count??0)/J.total*100)}async function H7(){return(await w.selectFrom("print_devices").select(["status",w.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,G)=>{return $[G.status]=Number(G.count||0),$},{})}function M4(J,$,G=$){return J?.[$]??J?.[G]}function T3(J){let $=String(J||""),G=/^\d+$/.test($)?Number($):J;return new Date(G)}async function G$(J="csv"){let $=await J$(),G=E3($);return S3(G,{type:J})}function E3(J){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=J.map((X)=>{return[X.id,X.name,M4(X,"macAddress","mac_address"),X.location,X.terminal,X.status,T3(M4(X,"lastPing","last_ping")).toLocaleString(),M4(X,"printCount","print_count")]});return{headings:$,data:G}}async function M7(J="csv",$){let G=await G$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function x7(J="csv",$){let G=await G$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}var{randomUUIDv7:V7}=globalThis.Bun;import{db as x4}from"@stacksjs/database";async function z7(J){try{let $=V7(),G={last_ping:0,print_count:0,...J,uuid:$};return await x4.insertInto("print_devices").values(G).executeTakeFirst(),await x4.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function B7(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={last_ping:0,print_count:0,...G,uuid:V7()};await x4.insertInto("print_devices").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as V4}from"@stacksjs/database";import{formatDate as z4}from"@stacksjs/orm";async function A7(J,$){if(!await l(J))return;try{return await V4.updateTable("print_devices").set({...$,updated_at:z4(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device: ${X.message}`);throw X}}async function O7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await V4.updateTable("print_devices").set({status:$,updated_at:z4(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device status: ${X.message}`);throw X}}async function _7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await V4.updateTable("print_devices").set({print_count:$,updated_at:z4(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print count: ${X.message}`);throw X}}var _4={};z(_4,{update:()=>j7,unresolveGroup:()=>I7,resolveGroup:()=>k7,ignoreGroup:()=>C7,fetchTimeline:()=>w7,fetchStats:()=>q7,fetchGrouped:()=>T7,fetchById:()=>S7,fetchByGroup:()=>E7,fetchAll:()=>Z$,destroyGroup:()=>P7,destroy:()=>R7,bulkUpdateStatus:()=>f7,bulkDestroy:()=>U7});import{db as A4}from"@stacksjs/database";import{log as O4}from"@stacksjs/logging";async function R7(J){try{return await A4.deleteFrom("errors").where("id","=",J).execute(),!0}catch($){return O4.error("[commerce/errors] destroy failed",{id:J,error:$}),!1}}async function U7(J){try{return await A4.deleteFrom("errors").where("id","in",J).execute(),!0}catch($){return O4.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:$}),!1}}async function P7(J,$){try{return await A4.deleteFrom("errors").where("type","=",J).where("message","=",$).execute(),!0}catch(G){return O4.error("[commerce/errors] destroyGroup failed",{type:J,message:$,error:G}),!1}}import{db as X$}from"@stacksjs/database";async function S7(J){return await X$.selectFrom("errors").where("id","=",J).selectAll().executeTakeFirst()}async function Z$(){return await X$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function T7(){let J=await X$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let X of J){let Z=`${X.type}:${X.message}`;if(!$.has(Z))$.set(Z,{errors:[],firstSeen:new Date(X.created_at),lastSeen:new Date(X.created_at)});let Y=$.get(Z);Y.errors.push(X);let L=new Date(X.created_at);if(L<Y.firstSeen)Y.firstSeen=L;if(L>Y.lastSeen)Y.lastSeen=L}let G=[];for(let[X,Z]of $){let Y=Z.errors[0];if(!Y)continue;let L=Z.errors.find((W)=>W.status!==null)?.status,K="unresolved";if(L===1)K="resolved";else if(L===2)K="ignored";G.push({id:Y.id,type:Y.type,message:Y.message,stack:Y.stack,status:K,count:Z.errors.length,first_seen:Z.firstSeen.toISOString(),last_seen:Z.lastSeen.toISOString(),error_ids:Z.errors.map((W)=>W.id)})}return G.sort((X,Z)=>new Date(Z.last_seen).getTime()-new Date(X.last_seen).getTime()),G}async function E7(J,$){return await X$.selectFrom("errors").where("type","=",J).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function q7(){let J=await Z$(),$=new Date,G=new Date($.getTime()-86400000),X=new Date($.getTime()-172800000),Z=J.filter((K)=>new Date(K.created_at)>=G).length,Y=J.filter((K)=>{let W=new Date(K.created_at);return W>=X&&W<G}).length,L=Y===0?Z>0?100:0:Math.round((Z-Y)/Y*100);return{total:J.length,unresolved:J.filter((K)=>K.status===null||K.status===0).length,resolved:J.filter((K)=>K.status===1).length,ignored:J.filter((K)=>K.status===2).length,last_24h:Z,trend:L}}async function w7(){let J=await Z$(),$=new Date,G=[];for(let X=23;X>=0;X--){let Z=new Date($.getTime()-X*60*60*1000);Z.setMinutes(0,0,0);let Y=new Date(Z.getTime()+3600000),L=J.filter((K)=>{let W=new Date(K.created_at);return W>=Z&&W<Y}).length;G.push({hour:Z.toISOString(),count:L})}return G}import{db as T0}from"@stacksjs/database";import{sql as E0}from"@stacksjs/database";import{log as q0}from"@stacksjs/logging";async function j7(J,$){try{return await T0.updateTable("errors").set({...$,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(G){return q0.error("[commerce/errors] update failed",{id:J,error:G}),!1}}async function f7(J,$){try{return await T0.updateTable("errors").set({status:$,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("id","in",J).execute(),!0}catch(G){return q0.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:$,error:G}),!1}}async function k7(J,$){try{return await T0.updateTable("errors").set({status:1,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return q0.error("[commerce/errors] resolveGroup failed",{type:J,message:$,error:G}),!1}}async function C7(J,$){try{return await T0.updateTable("errors").set({status:2,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return q0.error("[commerce/errors] ignoreGroup failed",{type:J,message:$,error:G}),!1}}async function I7(J,$){try{return await T0.updateTable("errors").set({status:0,updated_at:E0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return q0.error("[commerce/errors] unresolveGroup failed",{type:J,message:$,error:G}),!1}}var U4={};z(U4,{updateBalance:()=>r7,update:()=>e7,store:()=>o7,fetchTotalValue:()=>m7,fetchTotalCurrentBalance:()=>p7,fetchStats:()=>D7,fetchById:()=>X0,fetchByCode:()=>R4,fetchAll:()=>h7,fetchActive:()=>g7,destroy:()=>c7,compareActiveGiftCards:()=>y7,checkBalance:()=>v7,calculateGiftCardValues:()=>b7,bulkDestroy:()=>u7});import{db as l7}from"@stacksjs/database";import{formatDate as _5}from"@stacksjs/orm";import{db as P,sql as C}from"@stacksjs/database";import{formatDate as s,toTimestamp as N0}from"@stacksjs/orm";import{aggregateFunctions as q3,db as w3}from"@stacksjs/database";async function h(J,$,G){let X=w3.selectFrom(J);if(G)X=G(X);X=X.select(Object.entries($).map(([L,K])=>{let W=K.column??"id",F=q3[K.kind](W);if(K.filter)F=F.filterWhere(K.filter.column,K.filter.op,K.filter.value);return F.as(L)}));let Z=await X.executeTakeFirst(),Y={};for(let L of Object.keys($)){let K=Z?.[L];Y[L]=typeof K==="number"?K:Number(K??0)||0}return Y}async function h7(){return await P.selectFrom("gift_cards").selectAll().execute()}async function X0(J){return await P.selectFrom("gift_cards").where("id","=",J).selectAll().executeTakeFirst()}async function R4(J){return await P.selectFrom("gift_cards").where("code","=",J).selectAll().executeTakeFirst()}async function g7(){return await P.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function D7(){let{count:J}=await h("gift_cards",{count:{kind:"count"}}),$=N0(new Date),G=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal($)} OR expiry_date IS NULL)`).select(P.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("gift_cards").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute(),{count:Z}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:Y}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:L}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance > 0.75`)),K=new Date;K.setDate(K.getDate()+30);let W=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",N0(K)).where("expiry_date",">=",$).selectAll().limit(5).execute(),F=await P.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:J,active:Number(G?.count||0),by_status:X.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:Z,medium:Y,high:L},expiring_soon:W,recently_used:F}}async function v7(J){let $=await R4(J);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function y7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),L=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",s(Z)).where("created_at","<=",s(X)).executeTakeFirst(),K=Number(Y?.count||0),W=Number(L?.count||0),F=K-W,N=W!==0?F/W*100:K>0?100:0;return{current_period:K,previous_period:W,difference:F,percentage_change:N,days_range:J}}async function b7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),L=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",s(Z)).where("created_at","<=",s(X)).executeTakeFirst(),K=Number(Y?.total_initial||0),W=Number(Y?.total_balance||0),F=Number(Y?.card_count||0),N=Number(L?.total_initial||0),H=Number(L?.total_balance||0),M=Number(L?.card_count||0),O=K>0?(K-W)/K*100:0,R=N>0?(N-H)/N*100:0,_=F>0?K/F:0,U=F>0?W/F:0,m=K-N,t=W-H,$0=F-M,Q0=N!==0?m/N*100:K>0?100:0,p=H!==0?t/H*100:W>0?100:0,F3=M!==0?$0/M*100:F>0?100:0;return{current_period:{total_initial_value:K,total_remaining_balance:W,utilization_rate:O,card_count:F,average_initial_value:_,average_remaining_balance:U},previous_period:{total_initial_value:N,total_remaining_balance:H,utilization_rate:R,card_count:M},comparison:{initial_value:{difference:m,percentage:Math.abs(Q0),is_increase:m>=0},balance:{difference:t,percentage:Math.abs(p),is_increase:t>=0},card_count:{difference:$0,percentage:Math.abs(F3),is_increase:$0>=0}},days_range:J}}async function m7(){let{total_value:J}=await h("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:J}}async function p7(){let{total_balance:J}=await h("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:J}}async function c7(J){let $=await l7.deleteFrom("gift_cards").where("id","=",J).executeTakeFirst();return Q($)>0}async function u7(J){if(!J.length)return 0;let $=await l7.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return Q($)}var{randomUUIDv7:j3}=globalThis.Bun;import{db as n7}from"@stacksjs/database";import{HttpError as i7}from"@stacksjs/error-handling";import{isUniqueViolation as f3}from"@stacksjs/orm";async function o7(J){let $=J,G={...J,current_balance:$.current_balance??$.initial_balance,status:J.status||"ACTIVE",is_active:$.is_active??!0,uuid:j3()};try{let X=await n7.insertInto("gift_cards").values(G).executeTakeFirst(),Z=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if(Z)return await n7.selectFrom("gift_cards").where("id","=",Z).selectAll().executeTakeFirst();return}catch(X){if(X instanceof i7)throw X;if(f3(X))throw new i7(409,"A gift card with this code already exists");if(X instanceof Error)throw Error(`Failed to create gift card: ${X.message}`);throw X}}import{db as d7}from"@stacksjs/database";import{HttpError as s7}from"@stacksjs/error-handling";import{formatDate as a7,isUniqueViolation as k3}from"@stacksjs/orm";async function e7(J,$){if(!await X0(J))return;try{return await d7.updateTable("gift_cards").set({...$,updated_at:a7(new Date)}).where("id","=",J).execute(),await X0(J)}catch(X){if(X instanceof s7)throw X;if(k3(X))throw new s7(409,"A gift card with this code already exists");if(X instanceof Error)throw Error(`Failed to update gift card: ${X.message}`);throw X}}async function r7(J,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let G=a7(new Date),X=await d7.unsafe(`UPDATE gift_cards
|
|
8
|
+
AND (end_date IS NULL OR end_date >= ?)`,[$,J,$,$]),X=typeof G?.execute==="function"?await G.execute():G;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0){let W=await G0(J);if(W)return{ok:!0,coupon:W};return{ok:!1,reason:"not-found"}}let Y=await G0(J);if(!Y)return{ok:!1,reason:"not-found"};if(!Y.isActive)return{ok:!1,reason:"inactive"};let L=!Y.startDate||Y.startDate<=$,K=!Y.endDate||Y.endDate>=$;if(!L||!K)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var M4={};B(M4,{update:()=>X7,store:()=>J7,fetchById:()=>J$,fetchAll:()=>t1,destroy:()=>a1,bulkDestroy:()=>r1});import{db as d1}from"@stacksjs/database";async function a1(J){try{let $=await d1.deleteFrom("customers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function r1(J){if(!J.length)return 0;try{let $=await d1.deleteFrom("customers").where("id","in",J).executeTakeFirst();return Q($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as e1}from"@stacksjs/database";async function J$(J){return await e1.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function t1(){return await e1.selectFrom("customers").selectAll().execute()}import{db as R3}from"@stacksjs/database";import{HttpError as $7}from"@stacksjs/error-handling";import{isUniqueViolation as U3}from"@stacksjs/orm";async function J7(J){try{let $={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await R3.insertInto("customers").values($).executeTakeFirst();if(!G)throw Error("Failed to create customer");let X=G.insertId||Number(G.numInsertedOrUpdatedRows);return await J$(Number(X))}catch($){if($ instanceof $7)throw $;if(U3($))throw new $7(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as P3}from"@stacksjs/database";import{HttpError as G7}from"@stacksjs/error-handling";import{formatDate as S3,isUniqueViolation as T3}from"@stacksjs/orm";async function X7(J,$){try{if(!J)throw Error("Customer ID is required for update");let G=await P3.updateTable("customers").set({...$,updated_at:S3(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof G7)throw G;if(T3(G))throw new G7(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var A4={};B(A4,{updateStatus:()=>R7,updatePrintCount:()=>U7,update:()=>_7,storePrintDevicesExport:()=>B7,store:()=>A7,getPrinterStatusCounts:()=>M7,fetchErrorsByDeviceId:()=>N7,fetchById:()=>l,fetchAll:()=>G$,exportPrintDevices:()=>X$,downloadPrintDevices:()=>z7,destroy:()=>Y7,countTotalPrints:()=>W7,countPrintsByDeviceId:()=>F7,countAll:()=>K7,calculatePrinterHealth:()=>H7,calculateErrorRate:()=>Q7,bulkStore:()=>O7,bulkDestroy:()=>L7});import{db as Z7}from"@stacksjs/database";async function Y7(J){try{let $=await Z7.deleteFrom("print_devices").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function L7(J){if(!J.length)return 0;try{let $=await Z7.deleteFrom("print_devices").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as E3}from"ts-spreadsheets";import{db as j}from"@stacksjs/database";async function l(J){return await j.selectFrom("print_devices").where("id","=",J).selectAll().executeTakeFirst()}async function G$(){return await j.selectFrom("print_devices").selectAll().execute()}async function K7(){let J=await j.selectFrom("print_devices").select(j.fn.count("id").as("count")).executeTakeFirst();return Number(J?.count||0)}async function W7(){let J=await j.selectFrom("print_devices").select(j.fn.sum("print_count").as("total")).executeTakeFirst();return Number(J?.total||0)}async function F7(J){return(await j.selectFrom("print_devices").select("print_count").where("id","=",J).executeTakeFirst())?.print_count??0}async function Q7(){let J=await j.selectFrom("receipts").select([j.fn.count("id").as("total"),j.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.failed_count??0)/J.total*100)}async function N7(J){return await j.selectFrom("receipts").where("print_device_id","=",J).where("status","=","failed").selectAll().execute()}async function H7(){let J=await j.selectFrom("print_devices").select([j.fn.count("id").as("total"),j.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.online_count??0)/J.total*100)}async function M7(){return(await j.selectFrom("print_devices").select(["status",j.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,G)=>{return $[G.status]=Number(G.count||0),$},{})}function x4(J,$,G=$){let X=J;return X[String($)]??X[G]}function q3(J){if(J instanceof Date)return J;if(typeof J==="number")return new Date(J);if(typeof J==="string")return new Date(/^\d+$/.test(J)?Number(J):J);return new Date(Number.NaN)}function x7(J,$,G=$){let X=x4(J,$,G);if(typeof X==="number")return X;let Z=Number(X);return Number.isFinite(Z)?Z:0}function T0(J,$,G=$){let X=x4(J,$,G);return X==null?"":String(X)}async function X$(J="csv"){let $=await G$(),G=j3($);return E3(G,{type:J})}function j3(J){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=J.map((X)=>{return[x7(X,"id"),T0(X,"name"),T0(X,"macAddress","mac_address"),T0(X,"location"),T0(X,"terminal"),T0(X,"status"),q3(x4(X,"lastPing","last_ping")).toLocaleString(),x7(X,"printCount","print_count")]});return{headings:$,data:G}}async function z7(J="csv",$){let G=await X$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function B7(J="csv",$){let G=await X$(J),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}var{randomUUIDv7:V7}=globalThis.Bun;import{db as z4}from"@stacksjs/database";async function A7(J){try{let $=V7(),G={last_ping:0,print_count:0,...J,uuid:$};return await z4.insertInto("print_devices").values(G).executeTakeFirst(),await z4.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function O7(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={last_ping:0,print_count:0,...G,uuid:V7()};await z4.insertInto("print_devices").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as B4}from"@stacksjs/database";import{formatDate as V4}from"@stacksjs/orm";async function _7(J,$){if(!await l(J))return;try{return await B4.updateTable("print_devices").set({...$,updated_at:V4(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device: ${X.message}`);throw X}}async function R7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await B4.updateTable("print_devices").set({status:$,updated_at:V4(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device status: ${X.message}`);throw X}}async function U7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await B4.updateTable("print_devices").set({print_count:$,updated_at:V4(new Date)}).where("id","=",J).execute(),await l(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print count: ${X.message}`);throw X}}var R4={};B(R4,{update:()=>k7,unresolveGroup:()=>g7,resolveGroup:()=>I7,ignoreGroup:()=>h7,fetchTimeline:()=>f7,fetchStats:()=>w7,fetchGrouped:()=>q7,fetchById:()=>E7,fetchByGroup:()=>j7,fetchAll:()=>Y$,destroyGroup:()=>T7,destroy:()=>P7,bulkUpdateStatus:()=>C7,bulkDestroy:()=>S7});import{db as O4}from"@stacksjs/database";import{log as _4}from"@stacksjs/logging";async function P7(J){try{return await O4.deleteFrom("errors").where("id","=",J).execute(),!0}catch($){return _4.error("[commerce/errors] destroy failed",{id:J,error:$}),!1}}async function S7(J){try{return await O4.deleteFrom("errors").where("id","in",J).execute(),!0}catch($){return _4.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:$}),!1}}async function T7(J,$){try{return await O4.deleteFrom("errors").where("type","=",J).where("message","=",$).execute(),!0}catch(G){return _4.error("[commerce/errors] destroyGroup failed",{type:J,message:$,error:G}),!1}}import{db as Z$}from"@stacksjs/database";async function E7(J){return await Z$.selectFrom("errors").where("id","=",J).selectAll().executeTakeFirst()}async function Y$(){return await Z$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function q7(){let J=await Z$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let X of J){let Z=`${X.type}:${X.message}`;if(!$.has(Z))$.set(Z,{errors:[],firstSeen:new Date(X.created_at),lastSeen:new Date(X.created_at)});let Y=$.get(Z);Y.errors.push(X);let L=new Date(X.created_at);if(L<Y.firstSeen)Y.firstSeen=L;if(L>Y.lastSeen)Y.lastSeen=L}let G=[];for(let[X,Z]of $){let Y=Z.errors[0];if(!Y)continue;let L=Z.errors.find((W)=>W.status!==null)?.status,K="unresolved";if(L===1)K="resolved";else if(L===2)K="ignored";G.push({id:Y.id,type:Y.type,message:Y.message,stack:Y.stack,status:K,count:Z.errors.length,first_seen:Z.firstSeen.toISOString(),last_seen:Z.lastSeen.toISOString(),error_ids:Z.errors.map((W)=>W.id)})}return G.sort((X,Z)=>new Date(Z.last_seen).getTime()-new Date(X.last_seen).getTime()),G}async function j7(J,$){return await Z$.selectFrom("errors").where("type","=",J).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function w7(){let J=await Y$(),$=new Date,G=new Date($.getTime()-86400000),X=new Date($.getTime()-172800000),Z=J.filter((K)=>new Date(K.created_at)>=G).length,Y=J.filter((K)=>{let W=new Date(K.created_at);return W>=X&&W<G}).length,L=Y===0?Z>0?100:0:Math.round((Z-Y)/Y*100);return{total:J.length,unresolved:J.filter((K)=>K.status===null||K.status===0).length,resolved:J.filter((K)=>K.status===1).length,ignored:J.filter((K)=>K.status===2).length,last_24h:Z,trend:L}}async function f7(){let J=await Y$(),$=new Date,G=[];for(let X=23;X>=0;X--){let Z=new Date($.getTime()-X*60*60*1000);Z.setMinutes(0,0,0);let Y=new Date(Z.getTime()+3600000),L=J.filter((K)=>{let W=new Date(K.created_at);return W>=Z&&W<Y}).length;G.push({hour:Z.toISOString(),count:L})}return G}import{db as E0}from"@stacksjs/database";import{sql as q0}from"@stacksjs/database";import{log as j0}from"@stacksjs/logging";async function k7(J,$){try{return await E0.updateTable("errors").set({...$,updated_at:q0.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(G){return j0.error("[commerce/errors] update failed",{id:J,error:G}),!1}}async function C7(J,$){try{return await E0.updateTable("errors").set({status:$,updated_at:q0.raw("CURRENT_TIMESTAMP")}).where("id","in",J).execute(),!0}catch(G){return j0.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:$,error:G}),!1}}async function I7(J,$){try{return await E0.updateTable("errors").set({status:1,updated_at:q0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return j0.error("[commerce/errors] resolveGroup failed",{type:J,message:$,error:G}),!1}}async function h7(J,$){try{return await E0.updateTable("errors").set({status:2,updated_at:q0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return j0.error("[commerce/errors] ignoreGroup failed",{type:J,message:$,error:G}),!1}}async function g7(J,$){try{return await E0.updateTable("errors").set({status:0,updated_at:q0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return j0.error("[commerce/errors] unresolveGroup failed",{type:J,message:$,error:G}),!1}}var P4={};B(P4,{updateBalance:()=>$J,update:()=>t7,store:()=>d7,fetchTotalValue:()=>l7,fetchTotalCurrentBalance:()=>c7,fetchStats:()=>y7,fetchById:()=>X0,fetchByCode:()=>U4,fetchAll:()=>D7,fetchActive:()=>v7,destroy:()=>n7,compareActiveGiftCards:()=>m7,checkBalance:()=>b7,calculateGiftCardValues:()=>p7,bulkDestroy:()=>i7});import{db as u7}from"@stacksjs/database";import{formatDate as U5}from"@stacksjs/orm";import{db as P,sql as C}from"@stacksjs/database";import{formatDate as s,toTimestamp as N0}from"@stacksjs/orm";import{aggregateFunctions as w3,db as f3}from"@stacksjs/database";async function h(J,$,G){let X=f3.selectFrom(J);if(G)X=G(X);X=X.select(Object.entries($).map(([L,K])=>{let W=K.column??"id",F=w3[K.kind](W);if(K.filter)F=F.filterWhere(K.filter.column,K.filter.op,K.filter.value);return F.as(L)}));let Z=await X.executeTakeFirst(),Y={};for(let L of Object.keys($)){let K=Z?.[L];Y[L]=typeof K==="number"?K:Number(K??0)||0}return Y}async function D7(){return await P.selectFrom("gift_cards").selectAll().execute()}async function X0(J){return await P.selectFrom("gift_cards").where("id","=",J).selectAll().executeTakeFirst()}async function U4(J){return await P.selectFrom("gift_cards").where("code","=",J).selectAll().executeTakeFirst()}async function v7(){return await P.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function y7(){let{count:J}=await h("gift_cards",{count:{kind:"count"}}),$=N0(new Date),G=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal($)} OR expiry_date IS NULL)`).select(P.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("gift_cards").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute(),{count:Z}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:Y}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:L}=await h("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(C`current_balance / initial_balance > 0.75`)),K=new Date;K.setDate(K.getDate()+30);let W=await P.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",N0(K)).where("expiry_date",">=",$).selectAll().limit(5).execute(),F=await P.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:J,active:Number(G?.count||0),by_status:X.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:Z,medium:Y,high:L},expiring_soon:W,recently_used:F}}async function b7(J){let $=await U4(J);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function m7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),L=await P.selectFrom("gift_cards").select(P.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",s(Z)).where("created_at","<=",s(X)).executeTakeFirst(),K=Number(Y?.count||0),W=Number(L?.count||0),F=K-W,N=W!==0?F/W*100:K>0?100:0;return{current_period:K,previous_period:W,difference:F,percentage_change:N,days_range:J}}async function p7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),L=await P.selectFrom("gift_cards").select([P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(N0(Z))} OR expiry_date IS NULL)`).where("created_at",">=",s(Z)).where("created_at","<=",s(X)).executeTakeFirst(),K=Number(Y?.total_initial||0),W=Number(Y?.total_balance||0),F=Number(Y?.card_count||0),N=Number(L?.total_initial||0),H=Number(L?.total_balance||0),M=Number(L?.card_count||0),O=K>0?(K-W)/K*100:0,R=N>0?(N-H)/N*100:0,_=F>0?K/F:0,U=F>0?W/F:0,m=K-N,t=W-H,$0=F-M,Q0=N!==0?m/N*100:K>0?100:0,p=H!==0?t/H*100:W>0?100:0,N3=M!==0?$0/M*100:F>0?100:0;return{current_period:{total_initial_value:K,total_remaining_balance:W,utilization_rate:O,card_count:F,average_initial_value:_,average_remaining_balance:U},previous_period:{total_initial_value:N,total_remaining_balance:H,utilization_rate:R,card_count:M},comparison:{initial_value:{difference:m,percentage:Math.abs(Q0),is_increase:m>=0},balance:{difference:t,percentage:Math.abs(p),is_increase:t>=0},card_count:{difference:$0,percentage:Math.abs(N3),is_increase:$0>=0}},days_range:J}}async function l7(){let{total_value:J}=await h("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:J}}async function c7(){let{total_balance:J}=await h("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:J}}async function n7(J){let $=await u7.deleteFrom("gift_cards").where("id","=",J).executeTakeFirst();return Q($)>0}async function i7(J){if(!J.length)return 0;let $=await u7.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return Q($)}var{randomUUIDv7:k3}=globalThis.Bun;import{db as o7}from"@stacksjs/database";import{HttpError as s7}from"@stacksjs/error-handling";import{isUniqueViolation as C3}from"@stacksjs/orm";async function d7(J){let $=J,G={...J,current_balance:$.current_balance??$.initial_balance,status:J.status||"ACTIVE",is_active:$.is_active??!0,uuid:k3()};try{let X=await o7.insertInto("gift_cards").values(G).executeTakeFirst(),Z=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if(Z)return await o7.selectFrom("gift_cards").where("id","=",Z).selectAll().executeTakeFirst();return}catch(X){if(X instanceof s7)throw X;if(C3(X))throw new s7(409,"A gift card with this code already exists");if(X instanceof Error)throw Error(`Failed to create gift card: ${X.message}`);throw X}}import{db as r7}from"@stacksjs/database";import{HttpError as a7}from"@stacksjs/error-handling";import{formatDate as e7,isUniqueViolation as I3}from"@stacksjs/orm";async function t7(J,$){if(!await X0(J))return;try{return await r7.updateTable("gift_cards").set({...$,updated_at:e7(new Date)}).where("id","=",J).execute(),await X0(J)}catch(X){if(X instanceof a7)throw X;if(I3(X))throw new a7(409,"A gift card with this code already exists");if(X instanceof Error)throw Error(`Failed to update gift card: ${X.message}`);throw X}}async function $J(J,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let G=e7(new Date),X=await r7.unsafe(`UPDATE gift_cards
|
|
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 Q3=Object.defineProperty;var N3=(J)=>J;function H3(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,$]),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
|
|
16
|
+
AND current_balance + ? >= 0`,[$,G,$,G,J,$]),Z=typeof X?.execute==="function"?await X.execute():X;if(Number(Z?.changes??Z?.numUpdatedRows??Z?.affectedRows??0)>0)return await X0(J);let L=await X0(J);if(!L)throw Error(`Gift card with ID ${J} not found`);if(!L.is_active||L.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var C4={};B(C4,{validateQuantityBounds:()=>k4,validateCouponStacking:()=>kJ,validateCartQuantities:()=>CJ,updateStatus:()=>TJ,updateDeliveryInfo:()=>EJ,update:()=>SJ,storeOrdersExport:()=>KJ,store:()=>zJ,softDelete:()=>GJ,registerCommerceWebhookHandlers:()=>jJ,recomputeOrderTotals:()=>fJ,placeOrder:()=>PJ,handlePaymentIntentSucceeded:()=>j4,handlePaymentIntentFailed:()=>w4,handleChargeRefunded:()=>f4,findOrderByIdempotencyKey:()=>N$,fetchStats:()=>FJ,fetchDailyOrderTrends:()=>HJ,fetchById:()=>c,fetchAll:()=>WJ,exportOrders:()=>K$,emitOrderShipped:()=>W$,emitOrderRefunded:()=>M0,emitOrderPaid:()=>d,emitOrderDelivered:()=>F$,emitOrderCreated:()=>f0,emitOrderCancelled:()=>H0,emitForStatus:()=>k0,downloadOrders:()=>LJ,destroy:()=>JJ,compareOrdersByPeriod:()=>QJ,cleanupAbandonedCarts:()=>IJ,canTransition:()=>w0,calculateOrderMetrics:()=>NJ,bulkSoftDelete:()=>ZJ,bulkDestroy:()=>XJ});import{db as L$}from"@stacksjs/database";async function JJ(J){try{let $=await L$.deleteFrom("orders").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function GJ(J){try{let $=await L$.updateTable("orders").set({status:"CANCELED"}).where("id","=",J).executeTakeFirst();return Number($.numUpdatedRows)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete order: ${$.message}`);throw $}}async function XJ(J){if(!J.length)return 0;try{let $=await L$.deleteFrom("orders").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}async function ZJ(J){if(!J.length)return 0;try{let $=await L$.updateTable("orders").set({status:"CANCELED"}).where("id","in",J).executeTakeFirst();return Number($.numUpdatedRows)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete orders: ${$.message}`);throw $}}import{db as YJ}from"@stacksjs/database";import{createSpreadsheet as h3}from"ts-spreadsheets";async function K$(J="csv"){let $=await g3(),G=D3($);return h3(G,{type:J})}async function g3(){let J=await YJ.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),$=J.map((Y)=>Y.id);if($.length===0)return[];let X=(await YJ.selectFrom("order_items").where("order_items.order_id","in",$).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((Y,L)=>{if(!L.order_id)return Y;if(!Y[L.order_id])Y[L.order_id]={totalItems:0,totalPrice:0};return Y[L.order_id].totalItems+=L.quantity,Y[L.order_id].totalPrice+=L.price*L.quantity,Y},{});return J.map((Y)=>{let L=X[Y.id]||{totalItems:0,totalPrice:0};return{...Y,totalItems:L.totalItems,totalPrice:L.totalPrice}})}function D3(J){let $=["Order ID","Customer","Date","Total","Status","Items"],G=J.map((X)=>{let Z=X.order_items?.map((Y)=>`${Y.product?.name} (Qty: ${Y.quantity}, Price: $${Y.price})`).join(" | ")||"No Items";return[X.id,X.customer?.name||"N/A",X.created_at,X.total_amount,X.status,Z]});return{headings:$,data:G}}async function LJ(J="csv",$){let G=await K$(J),X=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||X)}async function KJ(J="csv",$){let G=await K$(J),X=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||X)}import{db as V}from"@stacksjs/database";async function WJ(J){let $=V.selectFrom("orders").selectAll().orderBy("created_at","desc");if(J)$=$.limit(J);let G=await $.execute();return await Promise.all(G.map(async(X)=>{let Z=await V.selectFrom("order_items").where("order_id","=",X.id).selectAll().execute();return{...X,items:Z}}))}async function c(J){return await V.selectFrom("orders").where("id","=",J).selectAll().executeTakeFirst()}async function FJ(){let J=await V.selectFrom("orders").select(V.fn.count("id").as("count")).executeTakeFirst(),$=await V.selectFrom("orders").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),G=await V.selectFrom("orders").select(["order_type",V.fn.count("id").as("count")]).groupBy("order_type").execute(),X=await V.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),Z=await Promise.all(X.map(async(L)=>{let K=await V.selectFrom("order_items").where("order_id","=",L.id).selectAll().execute();return{...L,items:K}})),Y=await V.selectFrom("orders").select(V.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(J?.count||0),by_status:$,by_type:G,recent:Z,revenue:Number(Y?.total||0)}}async function QJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await V.selectFrom("orders").select(V.fn.count("id").as("count")).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),L=await V.selectFrom("orders").select(V.fn.count("id").as("count")).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),K=Number(Y?.count||0),W=Number(L?.count||0),F=K-W,N=W!==0?F/W*100:K>0?100:0;return{current_period:K,previous_period:W,difference:F,percentage_change:N,days_range:J}}async function NJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await V.selectFrom("orders").select([V.fn.count("id").as("total_orders"),V.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),L=await V.selectFrom("orders").select([V.fn.count("id").as("total_orders"),V.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",Z.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),K=await V.selectFrom("orders").select(["status",V.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("status").execute(),W=await V.selectFrom("orders").select(["order_type",V.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("order_type").execute(),F=Number(Y?.total_orders||0),N=Number(Y?.total_revenue||0),H=F>0?N/F:0,M=Number(L?.total_orders||0),O=Number(L?.total_revenue||0),R=M>0?O/M:0,_=F-M,U=N-O,m=H-R,t=M!==0?_/M*100:F>0?100:0,$0=O!==0?U/O*100:N>0?100:0,Q0=R!==0?m/R*100:H>0?100:0;return{current_period:{total_orders:F,total_revenue:N,average_order_value:H,orders_by_status:K.map((p)=>({status:p.status,count:Number(p.count)})),orders_by_type:W.map((p)=>({order_type:p.order_type,count:Number(p.count)}))},previous_period:{total_orders:M,total_revenue:O,average_order_value:R},comparison:{orders:{difference:_,percentage:Math.abs(t),is_increase:_>=0},revenue:{difference:U,percentage:Math.abs($0),is_increase:U>=0},average_order_value:{difference:m,percentage:Math.abs(Q0),is_increase:m>=0}},days_range:J}}async function HJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=await V.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).orderBy("created_at","asc").execute(),Z=new Map;for(let Y of X){let L=(Y.created_at||"").split("T")[0]||"unknown",K=Z.get(L)||{order_count:0,revenue:0};K.order_count++,K.revenue+=Number(Y.total_amount||0),Z.set(L,K)}return Array.from(Z.entries()).map(([Y,L])=>({date:Y,order_count:L.order_count,revenue:L.revenue}))}var{randomUUIDv7:v3}=globalThis.Bun;import{db as MJ}from"@stacksjs/database";import{formatDate as xJ}from"@stacksjs/orm";async function zJ(J){let $={...J,status:J.status||"PENDING",uuid:v3(),created_at:xJ(new Date),updated_at:xJ(new Date)};try{let G=await MJ.insertInto("orders").values($).executeTakeFirst(),X=Number(G?.insertId)||Number(G?.numInsertedOrUpdatedRows);if(X)return await MJ.selectFrom("orders").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof Error)throw Error(`Failed to create order: ${G.message}`);throw G}}x0();var{randomUUIDv7:OJ}=globalThis.Bun;import{db as Q$}from"@stacksjs/database";import{formatDate as l3,isUniqueViolation as _J}from"@stacksjs/orm";import{sqlHelpers as b3}from"@stacksjs/database";import{env as m3}from"@stacksjs/env";function p3(J,$,G,X){let Z=b3(J).param;return{query:`UPDATE products
|
|
17
17
|
SET inventory_count = inventory_count + ${Z(1)},
|
|
18
18
|
updated_at = ${Z(2)}
|
|
19
19
|
WHERE id = ${Z(3)}
|
|
20
|
-
AND inventory_count + ${Z(4)} >= 0`,parameters:[G,X,$,G]}}async function zJ(J,$,G,X){let Z=b3(y3.DB_CONNECTION||"sqlite",$,G,X),Y=await J.unsafe(Z.query,Z.parameters),L=typeof Y?.execute==="function"?await Y.execute():Y;return Q(L)}var OJ=!1;function _J(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function Q$(J){try{let $=await F$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await F$.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(_J($)){if(!OJ)OJ=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw $}}async function RJ(J){if(J.idempotencyKey){let $=await Q$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await F$.transaction(async(G)=>{let X=m3(new Date),Z=BJ(),Y={...J.order,status:J.order.status||"PENDING",uuid:Z,created_at:X,updated_at:X};await G.insertInto("orders").values(Y).executeTakeFirst();let L=await G.selectFrom("orders").where("uuid","=",Z).selectAll().executeTakeFirst(),K=Number(L?.id);if(!Number.isSafeInteger(K)||K<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let W;if(J.items&&J.items.length>0){let H=J.items.map((M)=>{if(!Number.isInteger(M.productId)||M.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(M.quantity)||M.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(M.price)||M.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:K,product_id:M.productId,quantity:M.quantity,price:M.price,special_instructions:M.specialInstructions||null,created_at:X,updated_at:X}});await G.insertInto("order_items").values(H).execute(),W=await G.selectFrom("order_items").where("order_id","=",K).selectAll().execute()}let F;if(J.payment)try{let H=BJ();if(await G.insertInto("payments").values({...J.payment,order_id:K,uuid:H,created_at:X,updated_at:X}).executeTakeFirst(),F=await G.selectFrom("payments").where("uuid","=",H).selectAll().executeTakeFirst(),!F)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(H){if(AJ(H))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(H,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(J.inventory&&J.inventory.length>0)for(let H=0;H<J.inventory.length;H++){let{id:M,delta:O}=J.inventory[H];if(!Number.isFinite(O)||O===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await zJ(G,M,O,X))throw Object.assign(Error(`inventory adjust failed for product ${M}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:K,created_at:X}).execute()}catch(H){if(AJ(H))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!_J(H))throw H}let N=await G.selectFrom("orders").where("id","=",K).selectAll().executeTakeFirst();if(!N)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:N,items:W,payment:F}});if(j0($.order),$.payment)d($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&J.idempotencyKey){let G=await Q$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}x0();import{db as P4}from"@stacksjs/database";import{formatDate as S4}from"@stacksjs/orm";x0();async function UJ(J,$){if(!await c(J))return;try{return await P4.updateTable("orders").set({...$,updated_at:S4(new Date)}).where("id","=",J).execute(),await c(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order: ${X.message}`);throw X}}async function PJ(J,$){let G=await c(J);if(!G)throw Error(`Order with ID ${J} not found`);let X=G.status??"PENDING";if(!w0(X,$))throw Error(`[commerce/orders] illegal status transition ${X} \u2192 ${$}`);try{await P4.updateTable("orders").set({status:$,updated_at:S4(new Date)}).where("id","=",J).execute();let Z=await c(J);if(Z)f0($,Z);return Z}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update order status: ${Z.message}`);throw Z}}async function SJ(J,$,G){let X=await c(J);if(!X)throw Error(`Order with ID ${J} not found`);let Z={updated_at:S4(new Date)};if($!==void 0)Z.delivery_address=$;if(G!==void 0)Z.estimated_delivery_time=G;if(Object.keys(Z).length===1)return X;try{return await P4.updateTable("orders").set(Z).where("id","=",J).execute(),await c(J)}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery information: ${Y.message}`);throw Y}}x0();import{db as V0}from"@stacksjs/database";import{formatDate as N$}from"@stacksjs/orm";async function T4(J){let $=await V0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await V0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var TJ=!1;function p3(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function E4(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:N$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(p3(G)){if(!TJ)TJ=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw G}}async function q4(J){let G=J.data.object?.id;if(!G)return;await V0.transaction(async(Z)=>{if(!await E4(J.id,Z))return;let L=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let K=N$(new Date);await Z.updateTable("payments").set({status:"succeeded",updated_at:K}).where("id","=",L.id).execute();let W=await Z.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(W&&W.status==="PENDING")await Z.updateTable("orders").set({status:"PROCESSING",updated_at:K}).where("id","=",W.id).execute()});let X=await T4(G);if(X)await d(X)}async function w4(J){let $=J.data.object,G=$?.id;if(!G)return;let Z=$?.last_payment_error?.message??"payment failed";await V0.transaction(async(L)=>{if(!await E4(J.id,L))return;let W=await L.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!W)return;let F=N$(new Date);await L.updateTable("payments").set({status:"failed",failure_reason:Z,updated_at:F}).where("id","=",W.id).execute();let N=await L.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await L.updateTable("orders").set({status:"CANCELLED",updated_at:F}).where("id","=",N.id).execute()});let Y=await T4(G);if(Y)await H0(Y,Z)}async function j4(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let X=$?.amount_refunded??0;await V0.transaction(async(Y)=>{if(!await E4(J.id,Y))return;let K=await Y.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!K)return;let W=N$(new Date);await Y.updateTable("payments").set({status:"refunded",refund_amount:X,updated_at:W}).where("id","=",K.id).execute();let F=await Y.selectFrom("orders").where("id","=",K.order_id).selectAll().executeTakeFirst();if(F&&F.status!=="REFUNDED")await Y.updateTable("orders").set({status:"REFUNDED",updated_at:W}).where("id","=",F.id).execute()});let Z=await T4(G);if(Z)await M0(Z,X)}async function EJ(){let J=await import("@stacksjs/payments").catch(()=>null);if(!J)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:G}=J;if(typeof $!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:q4,failed:w4}),G({refunded:j4}),()=>{}}import{db as qJ}from"@stacksjs/database";async function l3(J){if(J.length===0)return new Map;let $=await qJ.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),G=new Map;for(let X of $){let Z=Number(X.price);if(Number.isFinite(Z))G.set(X.id,Math.round(Z))}return G}async function c3(J){try{let $=await qJ.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),G=Number($?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function wJ(J){let $=J.items.map((R)=>R.productId),G=await l3($),X=J.taxRateId!=null?await c3(J.taxRateId):0,Z=0,Y=[];for(let R of J.items){let _=R.unitPriceCents??G.get(R.productId)??0,U=Math.round(_*R.quantity);Z+=U,Y.push({productId:R.productId,quantity:R.quantity,unitPriceCents:_,lineCents:U})}let L=Math.max(0,J.discountCents??0),K=Math.max(0,Z-L),W=Math.round(K*X),F=Math.max(0,J.shippingCents??0),N=Z-L+W+F,H=J.maxDriftCents??5,M=!1,O=0;if(J.clientTotalCents!=null)O=Math.abs(N-J.clientTotalCents),M=O>H;return{subtotalCents:Z,discountCents:L,taxCents:W,shippingCents:F,totalCents:N,resolvedItems:Y,priceChanged:M,diffCents:O}}import{db as H$}from"@stacksjs/database";function jJ(J,$={}){let G=J.length;if(G<=1)return{ok:!0,count:G};if(!$.allowMultiple)return{ok:!1,count:G,reason:"multiple-not-allowed"};let X=$.maxStacked??Number.POSITIVE_INFINITY;if(G>X)return{ok:!1,count:G,reason:"exceeds-max-stacked"};return{ok:!0,count:G}}async function f4(J,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:J,quantity:$,reason:"non-positive"};let G;try{G=await H$.selectFrom("products").where("id","=",J).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:J,quantity:$}}if(!G)return{ok:!1,productId:J,quantity:$,reason:"product-missing"};let X=G.min_order_qty??null,Z=G.max_order_qty??null;if(X!=null&&$<X)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:X};if(Z!=null&&$>Z)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:Z};return{ok:!0,productId:J,quantity:$}}async function fJ(J){for(let G of J){let X=await f4(G.productId,G.quantity);if(!X.ok)return X}let $=J[J.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function kJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,Z=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let Y=await H$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[Z,Z,G]),L=typeof Y?.execute==="function"?await Y.execute():Y;return{deleted:Number(L?.changes??L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??0),cutoffAt:Z}}catch{try{let Y=await H$.selectFrom("carts").where("updated_at","<",Z).select(["id"]).limit(G).execute();if(Y.length===0)return{deleted:0,cutoffAt:Z};let L=Y.map((F)=>F.id),K=await H$.deleteFrom("carts").where("id","in",L).execute();return{deleted:Number(K?.numDeletedRows??K?.[0]?.numDeletedRows??K?.affectedRows??Y.length),cutoffAt:Z}}catch{return{deleted:0,cutoffAt:Z}}}}var C4={};z(C4,{update:()=>uJ,store:()=>pJ,recordRefund:()=>nJ,fetchPaymentStatsByMethod:()=>vJ,fetchPaymentStats:()=>DJ,fetchMonthlyPaymentTrends:()=>yJ,fetchById:()=>Y0,fetchAll:()=>gJ,destroy:()=>IJ,bulkDestroy:()=>hJ});import{db as CJ}from"@stacksjs/database";async function IJ(J){try{let $=await CJ.deleteFrom("payments").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function hJ(J){if(!J.length)return 0;try{let $=await CJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as j}from"@stacksjs/database";import{formatDate as D}from"@stacksjs/orm";async function gJ(){return await j.selectFrom("payments").selectAll().execute()}async function Y0(J){return await j.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function DJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await j.selectFrom("payments").select([j.fn.count("id").as("transaction_count"),j.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").executeTakeFirst(),L=await j.selectFrom("payments").select([j.fn.count("id").as("transaction_count"),j.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(Z)).where("created_at","<=",D(X)).where("status","=","completed").executeTakeFirst(),K=await j.selectFrom("payments").select(j.fn.count("id").as("count")).where("created_at",">=",D(G)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(Y?.transaction_count||0),F=Number(Y?.total_revenue||0),N=W>0?F/W:0,H=Number(L?.transaction_count||0),M=Number(L?.total_revenue||0),O=H>0?M/H:0,R=W-H,_=F-M,U=N-O,m=H>0?R/H*100:W>0?100:0,t=M>0?_/M*100:F>0?100:0,$0=O>0?U/O*100:N>0?100:0,Q0=Number(K?.count||0),p=Q0>0?W/Q0*100:0;return{total_transactions:W,total_revenue:F,average_transaction:N,successful_rate:p,comparison:{transactions:{difference:R,percentage:Math.abs(m),is_increase:R>=0},revenue:{difference:_,percentage:Math.abs(t),is_increase:_>=0},average:{difference:U,percentage:Math.abs($0),is_increase:U>=0}}}}async function vJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=await j.selectFrom("payments").select([j.fn.count("id").as("total_count"),j.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").executeTakeFirst(),Z=Number(X?.total_count||0),Y=await j.selectFrom("payments").select(["method",j.fn.count("id").as("count"),j.fn.sum("amount").as("revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").groupBy("method").execute(),L={};return Y.forEach((K)=>{let W=Number(K.count||0),F=Number(K.revenue||0),N=Z>0?W/Z*100:0;L[K.method]={count:W,revenue:F,percentage_of_total:N}}),L}async function yJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await j.selectFrom("payments").selectAll().where("created_at",">=",D($)).where("status","=","completed").execute(),X={};for(let Y of G){let L=Y.created_at?new Date(Y.created_at):new Date,K=L.getFullYear(),W=L.getMonth()+1,F=`${K}-${String(W).padStart(2,"0")}`;if(!X[F])X[F]={year:K,month:W,transactions:0,revenue:0};X[F].transactions++,X[F].revenue+=Number(Y.amount||0)}return Object.keys(X).sort().map((Y)=>{let L=X[Y],K=L.transactions,W=L.revenue,F=K>0?W/K:0;return{month:new Date(L.year,L.month-1,1).toLocaleString("default",{month:"short"}),year:L.year,transactions:K,revenue:W,average:F}})}var{randomUUIDv7:u3}=globalThis.Bun;import{db as bJ}from"@stacksjs/database";import{HttpError as mJ}from"@stacksjs/error-handling";import{isUniqueViolation as n3}from"@stacksjs/orm";async function pJ(J){let $=u3(),G={...J,status:J.status||"pending",currency:J.currency||"USD",uuid:$};try{return await bJ.insertInto("payments").values(G).executeTakeFirst(),await bJ.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(X){if(X instanceof mJ)throw X;if(n3(X))throw new mJ(409,"A payment with this transaction ID already exists");if(X instanceof Error){if(X.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${X.message}`)}throw X}}import{db as lJ,sqlHelpers as i3}from"@stacksjs/database";import{env as o3}from"@stacksjs/env";import{formatDate as cJ}from"@stacksjs/orm";async function uJ(J,$){if(!await Y0(J))return;try{return await lJ.updateTable("payments").set({...$,updated_at:cJ(new Date)}).where("id","=",J).execute(),await Y0(J)}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${X.message}`)}throw X}}var s3=new Set(["completed","succeeded","partiallyRefunded"]);async function nJ(J,$){if(!Number.isSafeInteger(J)||J<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger($)||$<=0)throw TypeError("Refund amount must be a positive integer in minor units");let X=i3(o3.DB_CONNECTION||"sqlite").param,Z=cJ(new Date),Y=await lJ.unsafe(`UPDATE payments
|
|
20
|
+
AND inventory_count + ${Z(4)} >= 0`,parameters:[G,X,$,G]}}async function AJ(J,$,G,X){let Z=p3(m3.DB_CONNECTION||"sqlite",$,G,X),Y=await J.unsafe(Z.query,Z.parameters),L=typeof Y?.execute==="function"?await Y.execute():Y;return Q(L)}var RJ=!1;function UJ(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function N$(J){try{let $=await Q$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await Q$.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(UJ($)){if(!RJ)RJ=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw $}}async function PJ(J){if(J.idempotencyKey){let $=await N$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await Q$.transaction(async(G)=>{let X=l3(new Date),Z=OJ(),Y={...J.order,status:J.order.status||"PENDING",uuid:Z,created_at:X,updated_at:X};await G.insertInto("orders").values(Y).executeTakeFirst();let L=await G.selectFrom("orders").where("uuid","=",Z).selectAll().executeTakeFirst(),K=Number(L?.id);if(!Number.isSafeInteger(K)||K<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let W;if(J.items&&J.items.length>0){let H=J.items.map((M)=>{if(!Number.isInteger(M.productId)||M.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(M.quantity)||M.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(M.price)||M.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:K,product_id:M.productId,quantity:M.quantity,price:M.price,special_instructions:M.specialInstructions||null,created_at:X,updated_at:X}});await G.insertInto("order_items").values(H).execute(),W=await G.selectFrom("order_items").where("order_id","=",K).selectAll().execute()}let F;if(J.payment)try{let H=OJ();if(await G.insertInto("payments").values({...J.payment,order_id:K,uuid:H,created_at:X,updated_at:X}).executeTakeFirst(),F=await G.selectFrom("payments").where("uuid","=",H).selectAll().executeTakeFirst(),!F)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(H){if(_J(H))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(H,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(J.inventory&&J.inventory.length>0)for(let H=0;H<J.inventory.length;H++){let{id:M,delta:O}=J.inventory[H];if(!Number.isFinite(O)||O===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await AJ(G,M,O,X))throw Object.assign(Error(`inventory adjust failed for product ${M}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:K,created_at:X}).execute()}catch(H){if(_J(H))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!UJ(H))throw H}let N=await G.selectFrom("orders").where("id","=",K).selectAll().executeTakeFirst();if(!N)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:N,items:W,payment:F}});if(f0($.order),$.payment)d($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&J.idempotencyKey){let G=await N$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}x0();import{db as S4}from"@stacksjs/database";import{formatDate as T4}from"@stacksjs/orm";x0();async function SJ(J,$){if(!await c(J))return;try{return await S4.updateTable("orders").set({...$,updated_at:T4(new Date)}).where("id","=",J).execute(),await c(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order: ${X.message}`);throw X}}async function TJ(J,$){let G=await c(J);if(!G)throw Error(`Order with ID ${J} not found`);let X=G.status??"PENDING";if(!w0(X,$))throw Error(`[commerce/orders] illegal status transition ${X} \u2192 ${$}`);try{await S4.updateTable("orders").set({status:$,updated_at:T4(new Date)}).where("id","=",J).execute();let Z=await c(J);if(Z)k0($,Z);return Z}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update order status: ${Z.message}`);throw Z}}async function EJ(J,$,G){let X=await c(J);if(!X)throw Error(`Order with ID ${J} not found`);let Z={updated_at:T4(new Date)};if($!==void 0)Z.delivery_address=$;if(G!==void 0)Z.estimated_delivery_time=G;if(Object.keys(Z).length===1)return X;try{return await S4.updateTable("orders").set(Z).where("id","=",J).execute(),await c(J)}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery information: ${Y.message}`);throw Y}}x0();import{db as z0}from"@stacksjs/database";import{formatDate as H$}from"@stacksjs/orm";async function E4(J){let $=await z0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await z0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var qJ=!1;function c3(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function q4(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:H$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(c3(G)){if(!qJ)qJ=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw G}}async function j4(J){let G=J.data.object?.id;if(!G)return;await z0.transaction(async(Z)=>{if(!await q4(J.id,Z))return;let L=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let K=H$(new Date);await Z.updateTable("payments").set({status:"succeeded",updated_at:K}).where("id","=",L.id).execute();let W=await Z.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(W&&W.status==="PENDING")await Z.updateTable("orders").set({status:"PROCESSING",updated_at:K}).where("id","=",W.id).execute()});let X=await E4(G);if(X)await d(X)}async function w4(J){let $=J.data.object,G=$?.id;if(!G)return;let Z=$?.last_payment_error?.message??"payment failed";await z0.transaction(async(L)=>{if(!await q4(J.id,L))return;let W=await L.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!W)return;let F=H$(new Date);await L.updateTable("payments").set({status:"failed",failure_reason:Z,updated_at:F}).where("id","=",W.id).execute();let N=await L.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await L.updateTable("orders").set({status:"CANCELLED",updated_at:F}).where("id","=",N.id).execute()});let Y=await E4(G);if(Y)await H0(Y,Z)}async function f4(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let X=$?.amount_refunded??0;await z0.transaction(async(Y)=>{if(!await q4(J.id,Y))return;let K=await Y.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!K)return;let W=H$(new Date);await Y.updateTable("payments").set({status:"refunded",refund_amount:X,updated_at:W}).where("id","=",K.id).execute();let F=await Y.selectFrom("orders").where("id","=",K.order_id).selectAll().executeTakeFirst();if(F&&F.status!=="REFUNDED")await Y.updateTable("orders").set({status:"REFUNDED",updated_at:W}).where("id","=",F.id).execute()});let Z=await E4(G);if(Z)await M0(Z,X)}async function jJ(){let J=await import("@stacksjs/payments").catch(()=>null);if(!J)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:G}=J;if(typeof $!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:j4,failed:w4}),G({refunded:f4}),()=>{}}import{db as wJ}from"@stacksjs/database";async function u3(J){if(J.length===0)return new Map;let $=await wJ.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),G=new Map;for(let X of $){let Z=Number(X.price);if(Number.isFinite(Z))G.set(X.id,Math.round(Z))}return G}async function n3(J){try{let $=await wJ.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),G=Number($?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function fJ(J){let $=J.items.map((R)=>R.productId),G=await u3($),X=J.taxRateId!=null?await n3(J.taxRateId):0,Z=0,Y=[];for(let R of J.items){let _=R.unitPriceCents??G.get(R.productId)??0,U=Math.round(_*R.quantity);Z+=U,Y.push({productId:R.productId,quantity:R.quantity,unitPriceCents:_,lineCents:U})}let L=Math.max(0,J.discountCents??0),K=Math.max(0,Z-L),W=Math.round(K*X),F=Math.max(0,J.shippingCents??0),N=Z-L+W+F,H=J.maxDriftCents??5,M=!1,O=0;if(J.clientTotalCents!=null)O=Math.abs(N-J.clientTotalCents),M=O>H;return{subtotalCents:Z,discountCents:L,taxCents:W,shippingCents:F,totalCents:N,resolvedItems:Y,priceChanged:M,diffCents:O}}import{db as M$}from"@stacksjs/database";function kJ(J,$={}){let G=J.length;if(G<=1)return{ok:!0,count:G};if(!$.allowMultiple)return{ok:!1,count:G,reason:"multiple-not-allowed"};let X=$.maxStacked??Number.POSITIVE_INFINITY;if(G>X)return{ok:!1,count:G,reason:"exceeds-max-stacked"};return{ok:!0,count:G}}async function k4(J,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:J,quantity:$,reason:"non-positive"};let G;try{G=await M$.selectFrom("products").where("id","=",J).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:J,quantity:$}}if(!G)return{ok:!1,productId:J,quantity:$,reason:"product-missing"};let X=G.min_order_qty??null,Z=G.max_order_qty??null;if(X!=null&&$<X)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:X};if(Z!=null&&$>Z)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:Z};return{ok:!0,productId:J,quantity:$}}async function CJ(J){for(let G of J){let X=await k4(G.productId,G.quantity);if(!X.ok)return X}let $=J[J.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function IJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,Z=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let Y=await M$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[Z,Z,G]),L=typeof Y?.execute==="function"?await Y.execute():Y;return{deleted:Number(L?.changes??L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??0),cutoffAt:Z}}catch{try{let Y=await M$.selectFrom("carts").where("updated_at","<",Z).select(["id"]).limit(G).execute();if(Y.length===0)return{deleted:0,cutoffAt:Z};let L=Y.map((F)=>F.id),K=await M$.deleteFrom("carts").where("id","in",L).execute();return{deleted:Number(K?.numDeletedRows??K?.[0]?.numDeletedRows??K?.affectedRows??Y.length),cutoffAt:Z}}catch{return{deleted:0,cutoffAt:Z}}}}var I4={};B(I4,{update:()=>iJ,store:()=>cJ,recordRefund:()=>oJ,fetchPaymentStatsByMethod:()=>bJ,fetchPaymentStats:()=>yJ,fetchMonthlyPaymentTrends:()=>mJ,fetchById:()=>Y0,fetchAll:()=>vJ,destroy:()=>gJ,bulkDestroy:()=>DJ});import{db as hJ}from"@stacksjs/database";async function gJ(J){try{let $=await hJ.deleteFrom("payments").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function DJ(J){if(!J.length)return 0;try{let $=await hJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as w}from"@stacksjs/database";import{formatDate as D}from"@stacksjs/orm";async function vJ(){return await w.selectFrom("payments").selectAll().execute()}async function Y0(J){return await w.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function yJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=new Date(G);X.setDate(X.getDate()-1);let Z=new Date(X);Z.setDate(X.getDate()-J);let Y=await w.selectFrom("payments").select([w.fn.count("id").as("transaction_count"),w.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").executeTakeFirst(),L=await w.selectFrom("payments").select([w.fn.count("id").as("transaction_count"),w.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(Z)).where("created_at","<=",D(X)).where("status","=","completed").executeTakeFirst(),K=await w.selectFrom("payments").select(w.fn.count("id").as("count")).where("created_at",">=",D(G)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(Y?.transaction_count||0),F=Number(Y?.total_revenue||0),N=W>0?F/W:0,H=Number(L?.transaction_count||0),M=Number(L?.total_revenue||0),O=H>0?M/H:0,R=W-H,_=F-M,U=N-O,m=H>0?R/H*100:W>0?100:0,t=M>0?_/M*100:F>0?100:0,$0=O>0?U/O*100:N>0?100:0,Q0=Number(K?.count||0),p=Q0>0?W/Q0*100:0;return{total_transactions:W,total_revenue:F,average_transaction:N,successful_rate:p,comparison:{transactions:{difference:R,percentage:Math.abs(m),is_increase:R>=0},revenue:{difference:_,percentage:Math.abs(t),is_increase:_>=0},average:{difference:U,percentage:Math.abs($0),is_increase:U>=0}}}}async function bJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let X=await w.selectFrom("payments").select([w.fn.count("id").as("total_count"),w.fn.sum("amount").as("total_revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").executeTakeFirst(),Z=Number(X?.total_count||0),Y=await w.selectFrom("payments").select(["method",w.fn.count("id").as("count"),w.fn.sum("amount").as("revenue")]).where("created_at",">=",D(G)).where("created_at","<=",D($)).where("status","=","completed").groupBy("method").execute(),L={};return Y.forEach((K)=>{let W=Number(K.count||0),F=Number(K.revenue||0),N=Z>0?W/Z*100:0;L[K.method]={count:W,revenue:F,percentage_of_total:N}}),L}async function mJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await w.selectFrom("payments").selectAll().where("created_at",">=",D($)).where("status","=","completed").execute(),X={};for(let Y of G){let L=Y.created_at?new Date(Y.created_at):new Date,K=L.getFullYear(),W=L.getMonth()+1,F=`${K}-${String(W).padStart(2,"0")}`;if(!X[F])X[F]={year:K,month:W,transactions:0,revenue:0};X[F].transactions++,X[F].revenue+=Number(Y.amount||0)}return Object.keys(X).sort().map((Y)=>{let L=X[Y],K=L.transactions,W=L.revenue,F=K>0?W/K:0;return{month:new Date(L.year,L.month-1,1).toLocaleString("default",{month:"short"}),year:L.year,transactions:K,revenue:W,average:F}})}var{randomUUIDv7:i3}=globalThis.Bun;import{db as pJ}from"@stacksjs/database";import{HttpError as lJ}from"@stacksjs/error-handling";import{isUniqueViolation as o3}from"@stacksjs/orm";async function cJ(J){let $=i3(),G={...J,status:J.status||"pending",currency:J.currency||"USD",uuid:$};try{return await pJ.insertInto("payments").values(G).executeTakeFirst(),await pJ.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(X){if(X instanceof lJ)throw X;if(o3(X))throw new lJ(409,"A payment with this transaction ID already exists");if(X instanceof Error){if(X.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${X.message}`)}throw X}}import{db as uJ,sqlHelpers as s3}from"@stacksjs/database";import{env as d3}from"@stacksjs/env";import{formatDate as nJ}from"@stacksjs/orm";async function iJ(J,$){if(!await Y0(J))return;try{return await uJ.updateTable("payments").set({...$,updated_at:nJ(new Date)}).where("id","=",J).execute(),await Y0(J)}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${X.message}`)}throw X}}var a3=new Set(["completed","succeeded","partiallyRefunded"]);async function oJ(J,$){if(!Number.isSafeInteger(J)||J<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger($)||$<=0)throw TypeError("Refund amount must be a positive integer in minor units");let X=s3(d3.DB_CONNECTION||"sqlite").param,Z=nJ(new Date),Y=await uJ.unsafe(`UPDATE payments
|
|
21
21
|
SET refund_amount = COALESCE(refund_amount, 0) + ${X(1)},
|
|
22
22
|
status = CASE WHEN COALESCE(refund_amount, 0) + ${X(2)} = amount
|
|
23
23
|
THEN 'refunded' ELSE 'partiallyRefunded' END,
|
|
24
24
|
updated_at = ${X(3)}
|
|
25
25
|
WHERE id = ${X(4)}
|
|
26
26
|
AND status IN ('completed', 'succeeded', 'partiallyRefunded')
|
|
27
|
-
AND COALESCE(refund_amount, 0) + ${X(5)} <= amount`,[$,$,Z,J,$]),L=typeof Y?.execute==="function"?await Y.execute():Y;if(Number(L?.numUpdatedRows??L?.[0]?.numUpdatedRows??L?.numAffectedRows??L?.affectedRows??L?.[0]?.affectedRows??L?.changes??0)>0){let M=await Y0(J);if(M)return M;throw Error(`Payment with ID ${J} disappeared during refund`)}let W=await Y0(J);if(!W)throw Error(`Payment with ID ${J} not found`);let F=String(W.status||"");if(!s3.has(F))throw Error(`Payment status ${F||"unknown"} cannot be refunded`);let N=W,H=Number(W.amount||0)-Number(N.refundAmount??N.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${H} minor units`)}var b4={};z(b4,{variants:()=>U$,units:()=>R$,reviews:()=>A$,manufacturers:()=>B$,items:()=>z$,default:()=>LZ,categories:()=>V$});var V$={};z(V$,{updateParent:()=>Q6,updateDisplayOrder:()=>W6,updateActiveStatus:()=>F6,update:()=>K6,store:()=>h4,removeChildCategories:()=>G6,remove:()=>$6,findOrCreateByName:()=>L6,fetchStats:()=>eJ,fetchRootCategories:()=>sJ,fetchChildCategories:()=>dJ,fetchCategoryTree:()=>tJ,fetchByName:()=>iJ,fetchById:()=>f,fetchByDisplayOrder:()=>aJ,fetchAll:()=>I4,fetchActive:()=>oJ,deactivateChildCategories:()=>Z6,deactivate:()=>X6,compareCategoryGrowth:()=>rJ,bulkRemove:()=>J6});import{db as z0}from"@stacksjs/database";import{db as S}from"@stacksjs/database";import{formatDate as k0}from"@stacksjs/orm";async function I4(){return await S.selectFrom("categories").selectAll().execute()}async function f(J){return await S.selectFrom("categories").where("id","=",J).selectAll().executeTakeFirst()}async function iJ(J){return await S.selectFrom("categories").where("name","=",J).selectAll().executeTakeFirst()}async function oJ(){return await S.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function sJ(){return await S.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function dJ(J){return await S.selectFrom("categories").where("parent_category_id","=",J).where("is_active","=",!0).selectAll().execute()}async function aJ(J=!0){let $=S.selectFrom("categories").where("is_active","=",!0).selectAll();if(J)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function eJ(){let J=await S.selectFrom("categories").select(S.fn.count("id").as("count")).executeTakeFirst(),$=await S.selectFrom("categories").where("is_active","=",!0).select(S.fn.count("id").as("count")).executeTakeFirst(),G=await S.selectFrom("categories").whereNull("parent_category_id").select(S.fn.count("id").as("count")).executeTakeFirst(),X=await S.selectFrom("categories").whereNotNull("image_url").select(S.fn.count("id").as("count")).executeTakeFirst(),Z=new Date;Z.setDate(Z.getDate()-30);let Y=k0(Z),L=await S.selectFrom("categories").where("created_at",">=",Y).selectAll().limit(5).execute(),K=await S.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",S.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number($?.count||0),root_categories:Number(G?.count||0),child_categories:Number(J?.count||0)-Number(G?.count||0),with_images:Number(X?.count||0),recently_added:L,top_parent_categories:K.map((W)=>({id:String(W.parent_category_id||""),name:String(W.parent_name||""),child_count:Number(W.child_count)}))}}async function rJ(J=30){let $=new Date,G=k0($),X=new Date;X.setDate($.getDate()-J);let Z=k0(X),Y=new Date(X);Y.setDate(Y.getDate()-1);let L=k0(Y),K=new Date(Y);K.setDate(Y.getDate()-J);let W=k0(K),F=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",G).executeTakeFirst(),N=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",W).where("created_at","<=",L).executeTakeFirst(),H=Number(F?.count||0),M=Number(N?.count||0),O=H-M,R=M!==0?O/M*100:H>0?100:0;return{current_period:H,previous_period:M,difference:O,percentage_change:R,days_range:J}}async function tJ(){let J=await I4(),$=new Map;J.forEach((Z)=>{$.set(Z.id,{...Z,children:[]})});let G=[];J.forEach((Z)=>{let Y=$.get(Z.id);if(Z.parent_category_id){let L=$.get(Z.parent_category_id);if(L)L.children.push(Y)}else G.push(Y)}),G.sort((Z,Y)=>Z.display_order-Y.display_order);let X=(Z)=>{Z.sort((Y,L)=>Y.display_order-L.display_order),Z.forEach((Y)=>{if(Y.children.length>0)X(Y.children)})};return X(G),G}async function $6(J){let $=await z0.deleteFrom("categories").where("id","=",J).executeTakeFirst();return Q($)>0}async function J6(J){if(!J.length)return 0;let $=await z0.deleteFrom("categories").where("id","in",J).executeTakeFirst();return Q($)}async function G6(J){let $=await z0.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return Q($)}async function X6(J){if(!await f(J))throw Error(`Category with ID ${J} not found`);return!!await z0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",J).executeTakeFirst()}async function Z6(J){let $=await z0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",J).execute();return Number($.length)||0}var{randomUUIDv7:d3}=globalThis.Bun;import{db as Y6}from"@stacksjs/database";import{HttpError as M$}from"@stacksjs/error-handling";import{isUniqueViolation as a3}from"@stacksjs/orm";import{slug as e3}from"@stacksjs/strings";async function h4(J){try{let $=J.parent_category_id?Number(J.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new M$(422,"Parent category ID must be a positive integer");if($&&!await f($))throw new M$(422,`Parent category with ID ${J.parent_category_id} not found`);let G={...J,uuid:d3(),is_active:J.is_active??!0,parent_category_id:J.parent_category_id||null},X=await Y6.insertInto("categories").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create category");return X}catch($){if($ instanceof M$)throw $;if(a3($))throw new M$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function L6(J){if(!J.name)throw Error("Name is required");let $=await Y6.selectFrom("categories").selectAll().where("name","=",J.name).executeTakeFirst();if($)return $;let G={name:J.name,slug:e3(J.name),is_active:J.is_active??!0,display_order:0};return await h4(G)}import{db as C0}from"@stacksjs/database";import{HttpError as B0}from"@stacksjs/error-handling";import{formatDate as x$,isUniqueViolation as r3}from"@stacksjs/orm";async function K6(J,$){if(!await f(J))return;if(Object.hasOwn($,"parent_category_id")){let X=$.parent_category_id?Number($.parent_category_id):void 0;if(X!==void 0&&(!Number.isSafeInteger(X)||X<=0))throw new B0(422,"Parent category ID must be a positive integer");if(X===J)throw new B0(422,"A category cannot be its own parent");if(X&&!await f(X))throw new B0(422,`Parent category with ID ${$.parent_category_id} not found`);if(X&&await N6(J,String(X)))throw new B0(422,"This operation would create a circular category hierarchy")}try{let X=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},Z=await C0.updateTable("categories").set({...$,...X,updated_at:x$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(X){if(X instanceof B0)throw X;if(r3(X))throw new B0(409,"A category with this name or slug already exists");if(X instanceof Error)throw Error(`Failed to update category: ${X.message}`);throw X}}async function W6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);try{return await C0.updateTable("categories").set({display_order:$,updated_at:x$(new Date)}).where("id","=",J).execute(),await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category display order: ${X.message}`);throw X}}async function F6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);try{return await C0.updateTable("categories").set({is_active:$,updated_at:x$(new Date)}).where("id","=",J).execute(),await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function Q6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);if($){let X=Number($);if(X===J)throw Error("A category cannot be its own parent");if(!await f(X))throw Error(`Parent category with ID ${$} not found`);if(await N6(J,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let X={updated_at:x$(new Date)};if($===null)await C0.updateTable("categories").set({...X,parent_category_id:null}).where("id","=",J).execute();else await C0.updateTable("categories").set({...X,parent_category_id:$}).where("id","=",J).execute();return await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category parent: ${X.message}`);throw X}}async function N6(J,$){let G=Number($),X=new Set;while(G){if(X.has(G))return!0;if(G===J)return!0;X.add(G);let Z=await f(G),Y=Z?.parent_category_id??Z?.parentCategoryId;if(!Z||!Y)return!1;G=Number(Y)}return!1}var z$={};z(z$,{updateInventory:()=>P6,updateAvailability:()=>U6,update:()=>R6,store:()=>O6,fetchTopProducts:()=>z6,fetchById:()=>u,fetchAll:()=>V6,destroy:()=>M6,bulkStore:()=>_6,bulkDestroy:()=>x6});import{db as H6}from"@stacksjs/database";async function M6(J){try{let $=await H6.deleteFrom("products").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function x6(J){if(!J.length)return 0;try{let $=await H6.deleteFrom("products").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as a,sql as t3}from"@stacksjs/database";async function u(J){let $=await a.selectFrom("products").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.manufacturer_id)G=await a.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)X=await a.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:G,category:X}}return}async function V6(){let J=await a.selectFrom("products").selectAll().execute(),$=J.map((F)=>F.manufacturer_id).filter((F)=>F!==null&&F!==void 0),G=J.map((F)=>F.category_id).filter((F)=>F!==null&&F!==void 0),X=a.selectFrom("manufacturers"),Z=a.selectFrom("categories");if($.length>0)X=X.where("id","in",$);if(G.length>0)Z=Z.where("id","in",G);let Y=await X.selectAll().execute(),L=await Z.selectAll().execute(),K=Y.reduce((F,N)=>{return F[N.id]=N,F},{}),W=L.reduce((F,N)=>{return F[N.id]=N,F},{});return J.map((F)=>({...F,manufacturer:F.manufacturer_id?K[F.manufacturer_id]:null,category:F.category_id?W[F.category_id]:null}))}async function z6(J=5){try{return(await a.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",a.fn.sum("order_items.quantity").as("units_sold"),t3`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(J).execute()).map((G)=>({id:Number(G.id),name:String(G.name??"Unnamed product"),units_sold:Number(G.units_sold??0),revenue:Number(G.revenue??0),inventory_count:Number(G.inventory_count??0)}))}catch($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:B6}=globalThis.Bun;import{db as A6}from"@stacksjs/database";async function O6(J){try{let $={...J,uuid:B6()},G=await A6.insertInto("products").values($).executeTakeFirst();if(!G)throw Error("Failed to create product item");let X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),Z=await u(X);if(!Z)throw Error("Failed to create product item");return Z}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function _6(J){if(!J.length)return 0;let $=0;try{return await A6.transaction().execute(async(G)=>{for(let X of J){let Z={...X,uuid:B6()};await G.insertInto("products").values(Z).execute(),$++}}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as g4}from"@stacksjs/database";import{formatDate as D4}from"@stacksjs/orm";async function R6(J,$){try{if(!J)throw Error("Product item ID is required for update");let G=await g4.updateTable("products").set({...$,updated_at:D4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item: ${G.message}`);throw G}}async function U6(J,$){if(!await u(J))throw Error(`Product item with ID ${J} not found`);try{return await g4.updateTable("products").set({is_available:$,updated_at:D4(new Date)}).where("id","=",J).execute(),await u(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item availability: ${X.message}`);throw X}}async function P6(J,$){let G=await u(J);if(!G)throw Error(`Product item with ID ${J} not found`);let X={updated_at:D4(new Date)};if($!==void 0)X.inventory_count=$;if(Object.keys(X).length===1)return G;try{return await g4.updateTable("products").set(X).where("id","=",J).execute(),await u(J)}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update inventory information: ${Z.message}`);throw Z}}var B$={};z(B$,{updateFeaturedStatus:()=>m6,updateByUuid:()=>p6,update:()=>b6,store:()=>D6,fetchWithProductCount:()=>C6,fetchFeatured:()=>f6,fetchByUuid:()=>j6,fetchById:()=>w6,fetchByCountry:()=>k6,fetchAll:()=>q6,destroy:()=>T6,bulkStore:()=>v6,bulkDestroy:()=>E6});import{db as S6}from"@stacksjs/database";async function T6(J){try{let $=await S6.deleteFrom("manufacturers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function E6(J){if(!J.length)return 0;try{let $=await S6.deleteFrom("manufacturers").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as n}from"@stacksjs/database";function q6(){return n.selectFrom("manufacturers").selectAll().execute()}async function w6(J){return await n.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function j6(J){return await n.selectFrom("manufacturers").where("uuid","=",J).selectAll().executeTakeFirst()}async function f6(J=10){return await n.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(J).execute()}async function k6(J,$={}){let G=$.page||1,X=$.limit||2,Z=await n.selectFrom("manufacturers").select(n.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),Y=Number(Z?.total||0),L=await n.selectFrom("manufacturers").selectAll().where("country","=",J).limit(X).offset((G-1)*X).execute(),K=Math.ceil(Y/X);return{data:L,paging:{total_records:Y,page:G,total_pages:K},next_cursor:G<K?G+1:null}}async function C6(J={}){let $=n.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(J.country)$=$.where("m.country","=",J.country);if(J.featured!==void 0)$=$.where("m.featured","=",J.featured);return $=$.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",n.fn.count("p.id").as("product_count")]).groupBy("m.id"),$.execute()}var{randomUUIDv7:h6}=globalThis.Bun;import{db as g6}from"@stacksjs/database";import{HttpError as I6}from"@stacksjs/error-handling";import{isUniqueViolation as $Z}from"@stacksjs/orm";async function D6(J){try{let $={...J,uuid:h6(),featured:J.featured??!1},G=await g6.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch($){if($ instanceof I6)throw $;if($Z($))throw new I6(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function v6(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:h6(),featured:G.featured??!1};await g6.insertInto("manufacturers").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${G.message}`);throw G}}import{db as v4}from"@stacksjs/database";import{HttpError as y6}from"@stacksjs/error-handling";import{formatDate as y4,isUniqueViolation as JZ}from"@stacksjs/orm";async function b6(J,$){try{if(!J)throw Error("Manufacturer ID is required for update");let G=await v4.updateTable("manufacturers").set({...$,updated_at:y4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof y6)throw G;if(JZ(G))throw new y6(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function m6(J,$){try{let G=await v4.updateTable("manufacturers").set({featured:$,updated_at:y4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer featured status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${G.message}`);throw G}}async function p6(J,$){try{let G=await v4.updateTable("manufacturers").set({...$,updated_at:y4(new Date)}).where("uuid","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer: ${G.message}`);throw G}}var A$={};z(A$,{updateVotes:()=>L2,update:()=>Y2,store:()=>G2,fetchStatsByProductIds:()=>J2,fetchStats:()=>$2,fetchMostHelpfulByProductId:()=>a6,fetchByUserId:()=>s6,fetchByProductId:()=>o6,fetchById:()=>n6,fetchApprovedByProductId:()=>d6,fetchAll:()=>i6,destroy:()=>c6,bulkDestroy:()=>u6});import{db as l6}from"@stacksjs/database";async function c6(J){try{let $=await l6.deleteFrom("reviews").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function u6(J){if(!J.length)return 0;try{let $=await l6.deleteFrom("reviews").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as A0}from"@stacksjs/database";async function n6(J){return await A0.selectFrom("reviews").where("id","=",J).selectAll().executeTakeFirst()}async function i6(){return await A0.selectFrom("reviews").selectAll().execute()}async function o6(J){return await A0.selectFrom("reviews").where("product_id","=",J).selectAll().execute()}async function s6(J){return await A0.selectFrom("reviews").where("customer_id","=",J).selectAll().execute()}async function d6(J){return await A0.selectFrom("reviews").where("product_id","=",J).where("is_approved","=",!0).selectAll().execute()}async function a6(J){return await A0.selectFrom("reviews").where("product_id","=",J).orderBy("helpful_votes","desc").selectAll().execute()}import{db as e6}from"@stacksjs/database";function r6(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function t6(J){let $=r6();$.total=J.length;let G=0;for(let X of J){if(X.rating===null||X.rating===void 0){$.commentsOnly++;continue}let Z=Number(X.rating);if(Number.isNaN(Z)){$.commentsOnly++;continue}$.rated++,G+=Z;let Y=Math.min(5,Math.max(1,Math.round(Z)));$.distribution[Y]++}if($.rated>0)$.average=Math.round(G/$.rated*10)/10;return $}async function $2(J){let $=await e6.selectFrom("reviews").select(["rating"]).where("product_id","=",J).where("is_approved","=",!0).execute();return t6($)}async function J2(J){let $=new Map;for(let Z of J)$.set(Z,r6());if(J.length===0)return $;let G=await e6.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",J).where("is_approved","=",!0).execute(),X=new Map;for(let Z of G){let Y=X.get(Z.product_id);if(Y)Y.push({rating:Z.rating});else X.set(Z.product_id,[{rating:Z.rating}])}for(let[Z,Y]of X)$.set(Z,t6(Y));return $}var{randomUUIDv7:GZ}=globalThis.Bun;import{db as XZ}from"@stacksjs/database";function ZZ(J){let $=J.rating!==void 0&&J.rating!==null,G=typeof J.content==="string"&&J.content.trim().length>0,X=typeof J.title==="string"&&J.title.trim().length>0;return!$&&!G&&!X}async function G2(J){try{if(ZZ(J))throw Error("A review needs a rating or something written: both were empty");let $={...J,uuid:GZ(),rating:J.rating??null,is_verified_purchase:J.is_verified_purchase??!1,is_approved:J.is_approved??!1,helpful_votes:J.helpful_votes??0,unhelpful_votes:J.unhelpful_votes??0,is_featured:J.is_featured??!1},G=await XZ.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create review");return G}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${$.message}`)}throw $}}import{db as X2}from"@stacksjs/database";import{formatDate as Z2}from"@stacksjs/orm";async function Y2(J,$){try{if(!J)throw Error("Review ID is required for update");let G=await X2.updateTable("reviews").set({...$,updated_at:Z2(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review: ${G.message}`);throw G}}async function L2(J,$,G=!0){try{let X=$==="helpful"?"helpful_votes":"unhelpful_votes",Z=G?`COALESCE("${X}", 0) + 1`:`MAX(COALESCE("${X}", 0) - 1, 0)`,Y=await X2.unsafe(`UPDATE "reviews" SET "${X}" = ${Z}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[Z2(new Date),J]).execute(),L=Array.isArray(Y)?Y[0]:Y;if(!L)throw Error("Failed to update review votes");return L}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var R$={};z(R$,{updateDefaultStatus:()=>_2,update:()=>A2,store:()=>x2,getDefaultUnit:()=>B2,formatUnitOptions:()=>z2,fetchById:()=>N2,fetchAll:()=>H2,destroy:()=>W2,bulkUpdate:()=>O2,bulkStore:()=>V2,bulkDestroy:()=>F2});import{db as K2}from"@stacksjs/database";async function W2(J){try{let $=await K2.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function F2(J){if(!J.length)return 0;try{let $=await K2.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as Q2}from"@stacksjs/database";async function N2(J){return await Q2.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function H2(){return await Q2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:M2}=globalThis.Bun;import{db as I0}from"@stacksjs/database";async function x2(J){try{return await I0.transaction(async($)=>{let G={...J,uuid:M2()},X=await $.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(G.is_default&&G.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();return X})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function V2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:M2()},Z=await I0.insertInto("product_units").values(X).returningAll().executeTakeFirst();if(X.is_default&&X.type&&Z)await I0.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",Z.id).execute();$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function z2(J){try{let $=I0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(J)$=$.where("type","=",J);return $=$.orderBy("name"),$.execute().then((G)=>G.map((X)=>({id:String(X.id),name:X.name,abbreviation:X.abbreviation,is_default:X.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function B2(J){try{return await I0.selectFrom("product_units").selectAll().where("type","=",J).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as O$}from"@stacksjs/database";import{formatDate as _$}from"@stacksjs/orm";async function A2(J,$){try{if(!J)throw Error("Product unit ID is required for update");return await O$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",J).executeTakeFirst();if(!X)return;let Z=$.type??X.type;if(($.is_default??Boolean(X.is_default))&&Z)await G.updateTable("product_units").set({is_default:!1,updated_at:_$(new Date)}).where("type","=",Z).where("id","!=",J).execute();let L=await G.updateTable("product_units").set({...$,updated_at:_$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!L)return;return L})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function O2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X=G;if(!X.id)continue;let Z=X.data&&typeof X.data==="object"?X.data:{...X};delete Z.id;let Y=await O$.updateTable("product_units").set({...Z,updated_at:_$(new Date)}).where("id","=",X.id).executeTakeFirst(),L=Z;if(L.is_default===!0&&L.type)await O$.updateTable("product_units").set({is_default:!1}).where("type","=",L.type).where("id","!=",X.id).execute();if(Number(Y.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function _2(J,$){try{return await O$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!X)return!1;let Z=_$(new Date);if($&&X.type)await G.updateTable("product_units").set({is_default:!1,updated_at:Z}).where("type","=",X.type).where("id","!=",J).execute();return await G.updateTable("product_units").set({is_default:$,updated_at:Z}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var U$={};z(U$,{update:()=>g2,store:()=>j2,generateVariantCombinations:()=>C2,formatVariantOptions:()=>k2,fetchById:()=>T2,fetchAll:()=>E2,destroy:()=>U2,bulkUpdate:()=>D2,bulkStore:()=>f2,bulkDestroy:()=>P2});import{db as R2}from"@stacksjs/database";async function U2(J){try{let $=await R2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function P2(J){if(!J.length)return 0;try{let $=await R2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as S2}from"@stacksjs/database";async function T2(J){return await S2.selectFrom("product_variants").where("id","=",J).selectAll().executeTakeFirst()}async function E2(){return await S2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:q2}=globalThis.Bun;import{db as w2}from"@stacksjs/database";async function j2(J){try{let $={...J,uuid:q2()},G=await w2.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product variant");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function f2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:q2()};await w2.insertInto("product_variants").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${G.message}`);throw G}}function k2(J){if(!J||!J.length)return JSON.stringify([]);let $=J.map((G)=>G.trim()).filter(Boolean);return JSON.stringify($)}function C2(J){let $=Object.keys(J);if(!$.length)return[];function G(X,Z){if(X===$.length)return[Z];let Y=$[X],L=J[Y]??[],K=[];for(let W of L){let F={...Z,[Y]:W};K.push(...G(X+1,F))}return K}return G(0,{})}import{db as I2}from"@stacksjs/database";import{formatDate as h2}from"@stacksjs/orm";async function g2(J,$){try{let G=await I2.updateTable("product_variants").set({...$,updated_at:h2(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variant: ${G.message}`);throw G}}async function D2(J){if(!J.length)return 0;let $=0;try{for(let G of J){if(!G.id)continue;let X=await I2.updateTable("product_variants").set({...G,updated_at:h2(new Date)}).where("id","=",G.id).executeTakeFirst();if(Number(X.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${G.message}`);throw G}}var YZ={categories:V$,items:z$,manufacturers:B$,reviews:A$,units:R$,variants:U$},LZ=YZ;var n4={};z(n4,{updateStatus:()=>a2,updatePrintJob:()=>e2,update:()=>d2,store:()=>o2,fetchSuccessRate:()=>l2,fetchPrintsPerHour:()=>n2,fetchPrintTimeStats:()=>u2,fetchPrintJobStats:()=>p2,fetchPageStats:()=>c2,fetchById:()=>O0,fetchAll:()=>m2,destroy:()=>y2,bulkStore:()=>s2,bulkDestroy:()=>b2});import{db as v2}from"@stacksjs/database";async function y2(J){try{let $=await v2.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function b2(J){if(!J.length)return 0;try{let $=await v2.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as m4}from"@stacksjs/database";import{formatDate as KZ}from"@stacksjs/orm";function b(J){return KZ(J)}function WZ(J){if(J instanceof Date)return Number.isNaN(J.getTime())?null:J;if(typeof J==="number"){let X=new Date(J<=2147483647?J*1000:J);return Number.isNaN(X.getTime())?null:X}let $=String(J||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let X=new Date(Number($)*1000);return Number.isNaN(X.getTime())?null:X}let G=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function O0(J){return await m4.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function m2(){return await m4.selectFrom("receipts").selectAll().execute()}async function p2(J,$){let G=b(J),X=b($),Z=await h("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning,averageSize:Math.round(Z.averageSize),averagePages:Math.round(Z.averagePages),averageDuration:Math.round(Z.averageDuration)}}async function l2(J,$){let G=b(J),X=b($),Z=await h("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(L)=>L.where("timestamp",">=",G).where("timestamp","<=",X));return{successRate:Z.total>0?Math.round(Z.success/Z.total*100):0,total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning}}async function c2(J,$){let G=b(J),X=b($),Z=await h("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{totalPages:Z.totalPages,averagePagesPerReceipt:Math.round(Z.averagePagesPerReceipt),totalReceipts:Z.totalReceipts}}async function u2(J,$){let G=b(J),X=b($),Z=await h("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{averageDuration:Math.round(Z.averageDuration),minDuration:Z.minDuration,maxDuration:Z.maxDuration,totalJobs:Z.totalJobs}}async function n2(J,$){let G=typeof J==="number"?J:J.getTime(),X=typeof $==="number"?$:$.getTime(),Z=b(J),Y=b($),L=await m4.selectFrom("receipts").where("timestamp",">=",Z).where("timestamp","<=",Y).selectAll().execute(),K=L.length,W=Math.ceil((X-G)/3600000),F=W>0?Math.round(K/W):0,N=Array.from({length:24},(H,M)=>({hour:M,count:0}));return L.forEach((H)=>{let M=WZ(H.timestamp);if(!M)return;N[M.getHours()].count++}),{totalPrints:K,totalHours:W,printsPerHour:F,hourlyBreakdown:N}}var{randomUUIDv7:i2}=globalThis.Bun;import{db as l4}from"@stacksjs/database";import{formatDate as p4}from"@stacksjs/orm";function h0(J){try{if(typeof J==="number")return p4(J<=2147483647?J*1000:J);if(typeof J==="string"&&/^\d{10}$/.test(J))return p4(Number(J)*1000);return p4(J)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function o2(J){try{let $=i2(),G={...J,timestamp:h0(J.timestamp),uuid:$};await l4.insertInto("receipts").values(G).executeTakeFirst();let X=await l4.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function s2(J){if(!J.length)return 0;try{let $=J.map((X)=>({...X,timestamp:h0(X.timestamp),uuid:i2()})),G=await l4.insertInto("receipts").values($).executeTakeFirst();return Number(G.numInsertedOrUpdatedRows??G.numAffectedRows??G.affectedRows??G.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as c4}from"@stacksjs/database";import{formatDate as u4}from"@stacksjs/orm";async function d2(J,$){try{if(!J)throw Error("Receipt ID is required for update");let G={...$,...$.timestamp===void 0?{}:{timestamp:h0($.timestamp)},updated_at:u4(new Date)};await c4.updateTable("receipts").set(G).where("id","=",J).execute();let X=await O0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function a2(J,$){try{await c4.updateTable("receipts").set({status:$,updated_at:u4(new Date)}).where("id","=",J).execute();let G=await O0(J);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function e2(J,$,G,X){try{let Z={updated_at:u4(new Date)};if($!==void 0)Z.size=$;if(G!==void 0)Z.pages=G;if(X!==void 0)Z.duration=X;await c4.updateTable("receipts").set(Z).where("id","=",J).execute();let Y=await O0(J);if(!Y)throw Error("Failed to update receipt job information");return Y}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update receipt job information: ${Z.message}`);throw Z}}var x1={};z(x1,{zones:()=>L4,tracking:()=>G4,routes:()=>w$,rates:()=>s$,methods:()=>c$,licenses:()=>b$,geocoding:()=>D$,drivers:()=>C$,digital:()=>f$,default:()=>CZ});var w$={};z(w$,{validateDeliveryRouteWrite:()=>_0,updateStops:()=>KG,updateMetrics:()=>WG,updateLastActive:()=>YG,update:()=>LG,store:()=>ZG,fetchById:()=>S$,fetchByDriver:()=>XG,fetchAll:()=>JG,fetchActive:()=>GG,destroy:()=>t2,bulkDestroy:()=>$G,DeliveryRouteInputError:()=>I});import{db as r2}from"@stacksjs/database";async function t2(J){try{let $=await r2.deleteFrom("delivery_routes").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function $G(J){if(!J.length)return 0;try{let $=await r2.deleteFrom("delivery_routes").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as P$}from"@stacksjs/database";async function S$(J){return await P$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function JG(){return await P$.selectFrom("delivery_routes").selectAll().execute()}async function GG(){return await P$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function XG(J){return await P$.selectFrom("delivery_routes").where("driver","=",J).selectAll().execute()}var{randomUUIDv7:NZ}=globalThis.Bun;import{db as i4}from"@stacksjs/database";function L0(J,$){let G={};for(let[X,Z]of Object.entries($))for(let Y of Z){if(!Object.prototype.hasOwnProperty.call(J,Y)||J[Y]===void 0)continue;G[X]=J[Y];break}return G}function g0(J){return L0(J,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function i(J){return L0(J,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function D0(J){return L0(J,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function v0(J){return L0(J,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function y0(J){return L0(J,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function b0(J){return L0(J,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function T$(J){return L0(J,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as FZ}from"@stacksjs/database";class I extends TypeError{constructor(J){super(J);this.name="DeliveryRouteInputError"}}function E$(J,$,G){return Number(J[G]??$?.[G])}function QZ(J,$){let G=J.last_active??$?.last_active;if(G===void 0||G===null)return Date.now();if(G instanceof Date)return G.getTime();if(typeof G==="number")return G;if(typeof G==="string"&&/^\d{10,13}$/.test(G))return Number(G);return Number.NaN}async function _0(J,$){let G=E$(J,$,"driver_id"),X=E$(J,$,"stops"),Z=E$(J,$,"delivery_time"),Y=E$(J,$,"total_distance"),L=QZ(J,$);if(!Number.isSafeInteger(G)||G<1)throw new I("Driver must be a positive integer.");if(!Number.isSafeInteger(X)||X<0)throw new I("Stops must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new I("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(Y)||Y<0)throw new I("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(L)||L<0)throw new I("Last active must be a valid Unix timestamp.");let K=await FZ.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!K)throw new I(`Driver ${G} was not found.`);return{...J,driver_id:Number(K.id),driver:K.name,vehicle:K.vehicle_number,last_active:L}}async function ZG(J){try{let $=NZ(),G=T$(J),Z={...await _0(G),uuid:$};await i4.insertInto("delivery_routes").values(Z).executeTakeFirst();let Y=await i4.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!Y)throw Error("Failed to create delivery route");return Y}catch($){if($ instanceof I)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function YG(J){try{await i4.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",J).execute();let $=await S$(J);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as q$}from"@stacksjs/database";import{formatDate as o4}from"@stacksjs/orm";async function LG(J,$){try{if(!J)throw Error("Delivery route ID is required for update");let G=await q$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=T$($),Z=await _0(X,G),Y=await q$.updateTable("delivery_routes").set({...Z,updated_at:o4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof I)throw G;if(G instanceof Error)throw TypeError(`Failed to update delivery route: ${G.message}`);throw G}}async function KG(J,$){try{let G=await q$.updateTable("delivery_routes").set({stops:$,updated_at:o4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update delivery route stops");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery route stops: ${G.message}`);throw G}}async function WG(J,$,G){try{let X={updated_at:o4(new Date)};if($!==void 0)X.delivery_time=$;if(G!==void 0)X.total_distance=G;let Z=await q$.updateTable("delivery_routes").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update delivery metrics");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery metrics: ${X.message}`);throw X}}var f$={};z(f$,{updateStatus:()=>_G,updateDeliverySettings:()=>RG,update:()=>OG,store:()=>BG,softDelete:()=>QG,fetchById:()=>xG,fetchAll:()=>VG,destroy:()=>FG,bulkStore:()=>AG,bulkSoftDelete:()=>HG,bulkDestroy:()=>NG});import{db as j$}from"@stacksjs/database";async function FG(J){try{let $=await j$.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function QG(J){try{let $=await j$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function NG(J){if(!J.length)return 0;try{let $=await j$.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function HG(J){if(!J.length)return 0;try{let $=await j$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as MG}from"@stacksjs/database";async function xG(J){return await MG.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function VG(){return await MG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:zG}=globalThis.Bun;import{db as s4}from"@stacksjs/database";async function BG(J){try{let $=zG(),G={...v0(J),uuid:$};await s4.insertInto("digital_deliveries").values(G).executeTakeFirst();let X=await s4.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created digital delivery");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function AG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...v0(X),uuid:zG()})),G=await s4.insertInto("digital_deliveries").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as d4}from"@stacksjs/database";import{formatDate as a4}from"@stacksjs/orm";async function OG(J,$){try{if(!J)throw Error("Digital delivery ID is required for update");let G=await d4.updateTable("digital_deliveries").set({...v0($),updated_at:a4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery: ${G.message}`);throw G}}async function _G(J,$){try{let G=await d4.updateTable("digital_deliveries").set({status:$,updated_at:a4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update digital delivery status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery status: ${G.message}`);throw G}}async function RG(J,$,G,X,Z){try{let Y={updated_at:a4(new Date)};if($!==void 0)Y.download_limit=$;if(G!==void 0)Y.expiry_days=G;if(X!==void 0)Y.requires_login=X;if(Z!==void 0)Y.automatic_delivery=Z;let L=await d4.updateTable("digital_deliveries").set(Y).where("id","=",J).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update delivery settings");return L}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery settings: ${Y.message}`);throw Y}}var C$={};z(C$,{updateStatus:()=>kG,updateContact:()=>CG,update:()=>fG,store:()=>wG,fetchById:()=>k$,fetchAll:()=>PG,destroy:()=>TG,bulkStore:()=>jG,bulkDestroy:()=>EG});import{db as SG}from"@stacksjs/database";import{db as UG}from"@stacksjs/database";async function k$(J){return await UG.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function PG(){return await UG.selectFrom("drivers").selectAll().execute()}async function TG(J){try{let $=await SG.deleteFrom("drivers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function EG(J){if(!J.length)return 0;let $=0;try{return await SG.transaction().execute(async(G)=>{for(let X of J)if(await k$(X))await G.deleteFrom("drivers").where("id","=",X).execute(),$++}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${G.message}`);throw G}}var{randomUUIDv7:qG}=globalThis.Bun;import{db as e4}from"@stacksjs/database";async function wG(J){try{let $=qG(),G={...b0(J),uuid:$};await e4.insertInto("drivers").values(G).executeTakeFirst();let X=await e4.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created driver");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function jG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...b0(X),uuid:qG()})),G=await e4.insertInto("drivers").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as r4}from"@stacksjs/database";import{formatDate as t4}from"@stacksjs/orm";async function fG(J,$){try{if(!J)throw Error("Driver ID is required for update");let G=await r4.updateTable("drivers").set({...b0($),updated_at:t4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver: ${G.message}`);throw G}}async function kG(J,$){try{let G=await r4.updateTable("drivers").set({status:$,updated_at:t4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update driver status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver status: ${G.message}`);throw G}}async function CG(J,$){try{let G={updated_at:t4(new Date)};if($!==void 0)G.phone=$;let X=await r4.updateTable("drivers").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update contact information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update contact information: ${G.message}`);throw G}}var D$={};z(D$,{setGeocodingDriver:()=>VZ,nominatimDriver:()=>g$,geocodingDriver:()=>yG,geocode:()=>zZ,formatQuery:()=>R0,checkCoverage:()=>BZ,PRECISION_RANK:()=>p0});var K0=(J)=>J*Math.PI/180;function e(J,$){let G=K0($.latitude-J.latitude),X=K0($.longitude-J.longitude),Z=K0(J.latitude),Y=K0($.latitude),L=Math.sin(G/2)**2+Math.sin(X/2)**2*Math.cos(Z)*Math.cos(Y);return 12742017.6*Math.asin(Math.sqrt(L))}function I$(J,$){let G=K0(J.latitude),X=K0($.latitude),Z=K0($.longitude-J.longitude),Y=Math.sin(Z)*Math.cos(X),L=Math.cos(G)*Math.sin(X)-Math.sin(G)*Math.cos(X)*Math.cos(Z);return(Math.atan2(Y,L)*180/Math.PI+360)%360}function h$(J,$,G={}){let X=G.detourFactor??1.35,Z=G.minimumSeconds??30;if(!Number.isFinite($)||$<=0.5)return null;let Y=J*X/$;return Math.max(Z,Math.round(Y))}function IG(J,$,G){return e(J,$)<=G}function m0(J){return typeof J?.latitude==="number"&&typeof J?.longitude==="number"&&Number.isFinite(J.latitude)&&Number.isFinite(J.longitude)}var p0={unknown:0,locality:1,postal:2,street:3,rooftop:4};function R0(J){return[J.street,J.city,J.region,J.postalCode,J.country].map(($)=>String($??"").trim()).filter(Boolean).join(", ")}var HZ="https://nominatim.openstreetmap.org/search",hG=1000,gG=0,DG=Promise.resolve();async function MZ(J){let $=DG.then(async()=>{let G=Date.now()-gG;if(G<hG)await Bun.sleep(hG-G);return gG=Date.now(),J()});return DG=$.then(()=>{return},()=>{return}),$}function xZ(J){let $=J.address??{},G=String(J.addresstype??""),X=String(J.type??""),Z=String(J.category??J.class??"");if($.house_number||X==="house"||X==="building"||G==="building")return"rooftop";if($.road||Z==="highway"||G==="road")return"street";if(G==="postcode"||$.postcode&&!$.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(G))return"locality";return"unknown"}function g$(J={}){let $=J.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,G=J.endpoint??HZ;return{name:"nominatim",async geocode(X){let Z=R0(X);if(!Z)return null;let Y=new URL(G);if(Y.searchParams.set("q",Z),Y.searchParams.set("format","jsonv2"),Y.searchParams.set("limit","1"),Y.searchParams.set("addressdetails","1"),X.country)Y.searchParams.set("countrycodes",X.country.toLowerCase());let L=await MZ(()=>fetch(Y,{headers:{"user-agent":$,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!L.ok)throw Error(`Nominatim responded ${L.status}`);let W=(await L.json())?.[0];if(!W)return null;let F=Number(W.lat),N=Number(W.lon);if(!Number.isFinite(F)||!Number.isFinite(N))return null;let H=xZ(W);return{latitude:F,longitude:N,formatted:String(W.display_name??Z),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[H],precision:H,provider:"nominatim"}}}}var vG=null;function VZ(J){vG=J}function yG(){return vG??g$()}async function zZ(J,$={}){let G=$.driver??yG(),X=$.minimumPrecision??"street",Z=`geocode:${G.name}:${R0(J).toLowerCase()}`,Y=await AZ(Z);if(Y!==void 0)return Y;let L=await G.geocode(J),K=L&&p0[L.precision]>=p0[X]?L:null;return await OZ(Z,K,K?$.cacheSeconds??2592000:600),K}function BZ(J,$,G){if($.length===0)return null;let X=$[0],Z=e(J,X);for(let Y of $.slice(1)){let L=e(J,Y);if(L<Z)Z=L,X=Y}return{covered:Z<=G,distanceMeters:Math.round(Z),nearest:X}}async function AZ(J){try{let G=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!G)return;let X=await G.get(J);if(X===null||X===void 0)return;return X==="null"?null:JSON.parse(String(X))}catch{return}}async function OZ(J,$,G){try{let Z=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!Z)return;await Z.set(J,$===null?"null":JSON.stringify($),G)}catch{}}var b$={};z(b$,{validateLicenseKeyWrite:()=>W0,updateStatus:()=>rG,updateExpiration:()=>tG,update:()=>eG,store:()=>dG,softDelete:()=>mG,fetchById:()=>uG,fetchAll:()=>nG,destroy:()=>bG,bulkStore:()=>aG,bulkSoftDelete:()=>lG,bulkDestroy:()=>pG,LicenseKeyInputError:()=>E});import{db as v$}from"@stacksjs/database";async function bG(J){try{let $=await v$.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function mG(J){try{let $=await v$.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function pG(J){if(!J.length)return 0;try{let $=await v$.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function lG(J){if(!J.length)return 0;try{let $=await v$.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as cG}from"@stacksjs/database";async function uG(J){return await cG.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst()}async function nG(){return await cG.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:sG}=globalThis.Bun;import{db as G1}from"@stacksjs/database";import{db as $1}from"@stacksjs/database";var iG=["Standard License","Premium License","Enterprise License"],oG=["active","inactive","unassigned"];class E extends TypeError{constructor(J){super(J);this.name="LicenseKeyInputError"}}function l0(J,$,G){return J[G]!==void 0?J[G]:$?.[G]}function J1(J,$,G,X){let Z=l0(J,$,G);if(Z===void 0||Z===null||Z==="")return null;let Y=Number(Z);if(!Number.isSafeInteger(Y)||Y<1)throw new E(`${X} must be a positive integer or null.`);return Y}function _Z(J){if(typeof J==="number")return J>2147483647?Math.floor(J/1000):J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return J.length===13?Math.floor(Number(J)/1000):Number(J);if(typeof J==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(J)?`${J.replace(" ","T")}Z`:J;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function W0(J,$){let G=String(l0(J,$,"key")||"").trim().toUpperCase(),X=String(l0(J,$,"template")||""),Z=String(l0(J,$,"status")||""),Y=_Z(l0(J,$,"expiry_date")),L=J1(J,$,"customer_id","Customer"),K=J1(J,$,"product_id","Product"),W=J1(J,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new E("License key must use five groups of four uppercase letters or numbers.");if(!iG.includes(X))throw new E(`Template must be one of: ${iG.join(", ")}.`);if(!oG.includes(Z))throw new E(`Status must be one of: ${oG.join(", ")}.`);if(!Number.isSafeInteger(Y)||Y<0||Y>2147483647)throw new E("Expiry date must be a Unix timestamp between 1970 and 2038.");let[F,N,H]=await Promise.all([L?$1.selectFrom("customers").where("id","=",L).select("id").executeTakeFirst():null,K?$1.selectFrom("products").where("id","=",K).select("id").executeTakeFirst():null,W?$1.selectFrom("orders").where("id","=",W).select(["id","customer_id"]).executeTakeFirst():null]);if(L&&!F)throw new E(`Customer ${L} was not found.`);if(K&&!N)throw new E(`Product ${K} was not found.`);if(W&&!H)throw new E(`Order ${W} was not found.`);if(L&&H?.customer_id&&Number(H.customer_id)!==L)throw new E(`Order ${W} belongs to Customer ${H.customer_id}, not Customer ${L}.`);return{...J,key:G,template:X,expiry_date:Y,status:Z,customer_id:L,product_id:K,order_id:W}}async function dG(J){try{let $=sG(),G=y0(J),X={...await W0(G),uuid:$};await G1.insertInto("license_keys").values(X).executeTakeFirst();let Z=await G1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created license key");return Z}catch($){if($ instanceof E)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function aG(J){if(!J.length)return 0;try{let $=await Promise.all(J.map(async(X)=>({...await W0(y0(X)),uuid:sG()}))),G=await G1.insertInto("license_keys").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof E)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as y$}from"@stacksjs/database";import{formatDate as X1}from"@stacksjs/orm";async function eG(J,$){try{if(!J)throw Error("License key ID is required for update");let G=await y$.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=y0($),Z=await W0(X,G),Y=await y$.updateTable("license_keys").set({...Z,updated_at:X1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof E)throw G;if(G instanceof Error){if(G.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${G.message}`)}throw G}}async function rG(J,$){try{let G=await y$.updateTable("license_keys").set({status:$,updated_at:X1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update license key status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update license key status: ${G.message}`);throw G}}async function tG(J,$){try{let G={updated_at:X1(new Date)};if($!==void 0)G.expiry_date=$;let X=await y$.updateTable("license_keys").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update expiration information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update expiration information: ${G.message}`);throw G}}var c$={};z(c$,{updateStatus:()=>NX,updatePricing:()=>HX,update:()=>QX,store:()=>LX,softDelete:()=>JX,getActiveShippingMethods:()=>FX,formatShippingOptions:()=>WX,fetchById:()=>l$,fetchAll:()=>ZX,destroy:()=>$X,bulkStore:()=>KX,bulkSoftDelete:()=>XX,bulkDestroy:()=>GX});import{db as m$}from"@stacksjs/database";async function $X(J){try{let $=await m$.deleteFrom("shipping_methods").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function JX(J){try{let $=await m$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function GX(J){if(!J.length)return 0;try{let $=await m$.deleteFrom("shipping_methods").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function XX(J){if(!J.length)return 0;try{let $=await m$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as p$}from"@stacksjs/database";async function l$(J){let $=await p$.selectFrom("shipping_methods").where("id","=",J).selectAll().executeTakeFirst();if($){let G=await p$.selectFrom("shipping_zones").where("shipping_method_id","=",J).selectAll().execute();return{...$,shippingZones:G}}return}async function ZX(){let J=await p$.selectFrom("shipping_methods").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((Y)=>Y.id))],Z=(await p$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((Y,L)=>{let K=L.shipping_method_id;if(K!==null&&K!==void 0){if(!Y[K])Y[K]=[];Y[K].push(L)}return Y},{});return J.map((Y)=>({...Y,shipping_zones:Z[Y.id]||[]}))}var{randomUUIDv7:YX}=globalThis.Bun;import{db as c0}from"@stacksjs/database";async function LX(J){try{let $=YX(),G={...g0(J),uuid:$};await c0.insertInto("shipping_methods").values(G).executeTakeFirst();let X=await c0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping method");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function KX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...g0(X),uuid:YX()})),G=await c0.insertInto("shipping_methods").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function WX(){try{return c0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping options: ${J.message}`);throw J}}async function FX(){try{return await c0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping methods: ${J.message}`);throw J}}import{db as Z1}from"@stacksjs/database";import{formatDate as Y1}from"@stacksjs/orm";async function QX(J,$){try{if(!J)throw Error("Shipping method ID is required for update");let G=await Z1.updateTable("shipping_methods").set({...g0($),updated_at:Y1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method: ${G.message}`);throw G}}async function NX(J,$){try{let G=await Z1.updateTable("shipping_methods").set({status:$,updated_at:Y1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping method status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method status: ${G.message}`);throw G}}async function HX(J,$,G){try{let X={updated_at:Y1(new Date)};if($!==void 0)X.base_rate=$;if(G!==void 0)X.free_shipping=G;let Z=await Z1.updateTable("shipping_methods").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update pricing information");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update pricing information: ${X.message}`);throw X}}var s$={};z(s$,{validateZoneMatchesAddress:()=>UX,validateShippingRateWrite:()=>F0,updateByZone:()=>hX,updateByMethod:()=>gX,update:()=>CX,store:()=>fX,resolveZoneForAddress:()=>n$,getShippingRatesByMethod:()=>SX,getRatesByZone:()=>_X,getRateByWeightAndZone:()=>L1,getRateByWeightAndAddress:()=>RX,formatShippingRateOptions:()=>PX,fetchById:()=>AX,fetchAll:()=>OX,destroyByZone:()=>VX,destroyByMethod:()=>zX,destroy:()=>MX,bulkUpdate:()=>IX,bulkStore:()=>kX,bulkDestroy:()=>xX,ShippingRateInputError:()=>k});import{db as u$}from"@stacksjs/database";async function MX(J){try{let $=await u$.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function xX(J){if(!J.length)return 0;try{let $=await u$.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function VX(J){try{let $=await u$.deleteFrom("shipping_rates").where("shipping_zone_id","=",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function zX(J){try{let $=await u$.deleteFrom("shipping_rates").where("shipping_method_id","=",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as v}from"@stacksjs/database";async function AX(J){let $=await v.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.shipping_zone_id)G=await v.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)X=await v.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:G,shipping_method:X}}return}async function OX(){let J=await v.selectFrom("shipping_rates").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((K)=>K.shipping_zone_id).filter((K)=>K!==null&&K!==void 0))],G=[...new Set(J.map((K)=>K.shipping_method_id).filter((K)=>K!==null&&K!==void 0))],[X,Z]=await Promise.all([$.length?v.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],G.length?v.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),Y=X.reduce((K,W)=>{return K[W.id]=W,K},{}),L=Z.reduce((K,W)=>{return K[W.id]=W,K},{});return J.map((K)=>({...K,shipping_zone:K.shipping_zone_id?Y[K.shipping_zone_id]:[],shipping_method:K.shipping_method_id?L[K.shipping_method_id]:[]}))}async function _X(J){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function L1(J,$){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function n$(J){if(!J?.countryCode)return null;try{let $=await v.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let G=null;for(let X of $){let Z=1;if(J.region&&X.regions&&BX(X.regions,J.region))Z=2;if(J.postalCode&&X.postal_codes&&BX(X.postal_codes,J.postalCode))Z=3;if(!G||Z>G.score)G={id:X.id,score:Z}}return G?.id??null}catch{return null}}async function RX(J,$){let G=await n$($);if(G==null)return;return L1(J,G)}async function UX(J,$){return await n$($)===J}function BX(J,$){if(!J||!$)return!1;let G=$.trim().toUpperCase();for(let X of J.split(/[,|;]/))if(X.trim().toUpperCase()===G)return!0;return!1}async function PX(){try{return(await v.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function SX(J){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:jX}=globalThis.Bun;import{db as K1}from"@stacksjs/database";import{db as u0}from"@stacksjs/database";async function TX(){return await u0.selectFrom("shipping_zones").selectAll().execute()}async function i$(J){return await u0.selectFrom("shipping_zones").where("id","=",J).selectAll().executeTakeFirst()}function EX(){try{return u0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping zone options: ${J.message}`);throw J}}async function qX(){try{return await u0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping zones: ${J.message}`);throw J}}async function wX(J){try{return await u0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class k extends TypeError{constructor(J){super(J);this.name="ShippingRateInputError"}}function n0(J,$,G){return Number(J[G]??$?.[G])}async function F0(J,$){let G=n0(J,$,"shipping_method_id"),X=n0(J,$,"shipping_zone_id"),Z=n0(J,$,"weight_from"),Y=n0(J,$,"weight_to"),L=n0(J,$,"rate");if(!Number.isSafeInteger(G)||G<1)throw new k("Shipping method must be a positive integer.");if(!Number.isSafeInteger(X)||X<1)throw new k("Shipping zone must be a positive integer.");if(!Number.isFinite(Z)||Z<0)throw new k("Weight from must be a non-negative number.");if(!Number.isFinite(Y)||Y<Z)throw new k("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(L)||L<0)throw new k("Rate must be a non-negative integer in minor currency units.");let[K,W]=await Promise.all([l$(G),i$(X)]);if(!K)throw new k(`Shipping method ${G} was not found.`);if(!W)throw new k(`Shipping zone ${X} was not found.`);if(Number(W.shipping_method_id)!==G)throw new k(`Shipping zone ${X} is not assigned to shipping method ${G}.`)}async function fX(J){try{let $=i(J),G=Number($.shipping_method_id),X=Number($.shipping_zone_id);await F0($);let Z=jX(),Y={...$,shipping_method_id:G,shipping_zone_id:X,uuid:Z};await K1.insertInto("shipping_rates").values(Y).executeTakeFirst();let L=await K1.selectFrom("shipping_rates").where("uuid","=",Z).selectAll().executeTakeFirst();if(!L)throw Error("Failed to resolve created shipping rate");return L}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function kX(J){if(!J.length)return 0;try{for(let X of J){let Z=i(X);await F0(Z)}let $=J.map((X)=>({...i(X),uuid:jX()})),G=await K1.insertInto("shipping_rates").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as i0}from"@stacksjs/database";import{formatDate as o$}from"@stacksjs/orm";async function CX(J,$){try{if(!J)throw Error("Shipping rate ID is required for update");let G=await i0.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=i($);await F0(X,G);let Z=await i0.updateTable("shipping_rates").set({...X,updated_at:o$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(G){if(G instanceof k)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function IX(J){if(!J.length)return 0;try{let $=0;for(let{id:G,data:X}of J){let Z=await i0.updateTable("shipping_rates").set({...i(X),updated_at:o$(new Date)}).where("id","=",G).executeTakeFirst();if(Q(Z)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function hX(J,$){try{let G=await i0.updateTable("shipping_rates").set({...i($),updated_at:o$(new Date)}).where("shipping_zone_id","=",J).executeTakeFirst();return Q(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${G.message}`);throw G}}async function gX(J,$){try{let G=await i0.updateTable("shipping_rates").set({...i($),updated_at:o$(new Date)}).where("shipping_method_id","=",J).executeTakeFirst();return Q(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var G4={};z(G4,{startStop:()=>yX,startRoute:()=>pX,routeTrackingChannel:()=>W1,recordDriverPing:()=>DX,orderTrackingChannel:()=>r,isWithin:()=>IG,hasCoordinates:()=>m0,failStop:()=>mX,estimateSecondsRemaining:()=>h$,emitDeliveryStarted:()=>e$,emitDeliveryPosition:()=>d$,emitDeliveryNearby:()=>r$,emitDeliveryFailed:()=>J4,emitDeliveryCompleted:()=>$4,emitDeliveryAssigned:()=>a$,emitDeliveryArrived:()=>t$,distanceInMeters:()=>e,completeStop:()=>bX,broadcastToChannel:()=>o,bearingInDegrees:()=>I$,assignStop:()=>vX,NEARBY_RADIUS_METERS:()=>F1,ARRIVAL_RADIUS_METERS:()=>Q1});function r(J){return`order.${J}`}function W1(J){return`delivery-route.${J}`}async function U0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function o(J,$,G){try{let X=await import("@stacksjs/realtime").catch(()=>null);if(!X)return;let Z=X.channel;if(typeof Z!=="function")return;await Z(J).broadcast($,G,"private")}catch{}}async function d$(J,$,G){await Promise.all([...J.map((X)=>o(r(X),"delivery:position",G)),$==null?Promise.resolve():o(W1($),"delivery:position",G)])}async function a$(J){if(await U0("delivery:assigned",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:assigned",{stop:J})}async function e$(J){if(await U0("delivery:started",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:started",{stop:J})}async function r$(J,$,G){if(await U0("delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G}),J.order_id!=null)await o(r(J.order_id),"delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G})}async function t$(J){if(await U0("delivery:arrived",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:arrived",{stop:J})}async function $4(J){if(await U0("delivery:completed",{stop:J}),J.order_id!=null)await o(r(J.order_id),"delivery:completed",{stop:J})}async function J4(J,$){await U0("delivery:failed",{stop:J,reason:$})}var{randomUUIDv7:RZ}=globalThis.Bun;import{db as y}from"@stacksjs/database";var F1=400,Q1=60,UZ=250;async function DX(J){let $=J.recordedAt??new Date().toISOString(),G=typeof J.accuracy!=="number"||J.accuracy<=UZ,X=await y.selectFrom("drivers").where("id","=",J.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!X)throw Error(`Unknown driver: ${J.driverId}`);let Z=m0(X)?{latitude:X.latitude,longitude:X.longitude}:null,Y=typeof J.heading==="number"?J.heading:Z?I$(Z,J):null,L=await PZ(J.driverId),K=L?await SZ(L.id):null,W=null,F=null,N=!1,H=!1,M=K&&m0({latitude:K.latitude??void 0,longitude:K.longitude??void 0})?{latitude:K.latitude,longitude:K.longitude}:null;if(G&&K&&M)W=Math.round(e(J,M)),F=h$(W,J.speed??0),H=W<=Q1&&K.arrived_at==null,N=!H&&W<=F1&&K.status==="en_route"&&K.notified_nearby_at==null;let O=await TZ({driverId:J.driverId,routeId:L?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$});if(G)await y.updateTable("drivers").set({latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??0,last_ping_at:$}).where("id","=",J.driverId).execute();if(K&&(W!=null||F!=null))await y.updateTable("delivery_stops").set({eta_at:F==null?K.eta_at:new Date(Date.now()+F*1000).toISOString()}).where("id","=",K.id).execute();if(G)await d$(K?.order_id==null?[]:[K.order_id],L?.id??null,{driverId:J.driverId,routeId:L?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$,distanceToStopMeters:W,etaSeconds:F});if(N&&K)await y.updateTable("delivery_stops").set({notified_nearby_at:$}).where("id","=",K.id).execute(),await r$(K,W,F);if(H&&K)await y.updateTable("delivery_stops").set({status:"arrived",arrived_at:$}).where("id","=",K.id).execute(),await t$({...K,status:"arrived",arrived_at:$});return{pingId:O,routeId:L?.id??null,stopId:K?.id??null,distanceToStopMeters:W,etaSeconds:F,crossedNearby:N,crossedArrival:H}}async function PZ(J){return await y.selectFrom("delivery_routes").where("driver_id","=",J).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function SZ(J){let $=await y.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return $.find((G)=>G.status==="en_route")??$.find((G)=>G.status==="arrived")??$[0]??null}async function TZ(J){let $=RZ();return await y.insertInto("driver_pings").values({uuid:$,driver_id:J.driverId,delivery_route_id:J.routeId,latitude:J.latitude,longitude:J.longitude,heading:J.heading,speed:J.speed??0,accuracy:J.accuracy,recorded_at:J.recordedAt}).executeTakeFirst(),(await y.selectFrom("driver_pings").where("uuid","=",$).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:EZ}=globalThis.Bun;import{db as q}from"@stacksjs/database";async function vX(J){let $=EZ(),G=J.sequence??await wZ(J.deliveryRouteId);await q.insertInto("delivery_stops").values({uuid:$,delivery_route_id:J.deliveryRouteId,order_id:J.orderId??null,sequence:G,status:"pending",address:J.address,latitude:J.latitude??null,longitude:J.longitude??null,recipient_name:J.recipientName??null,recipient_phone:J.recipientPhone??null,eta_at:J.etaAt??null}).executeTakeFirst();let X=await fZ($);if(X)await a$(X);return X??{}}async function yX(J){await q.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",J).execute();let $=await H1(J);if(!$)return null;if($.order_id!=null)await N1($.order_id,"OUT_FOR_DELIVERY");return await e$($),$}async function bX(J,$){let G=new Date().toISOString();await q.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await jZ(J)?{}:{arrived_at:G},...$?{notes:$}:{}}).where("id","=",J).execute();let X=await H1(J);if(!X)return null;if(X.order_id!=null)await N1(X.order_id,"DELIVERED");return await $4(X),await lX(X.delivery_route_id),X}async function mX(J,$){await q.updateTable("delivery_stops").set({status:"failed",notes:$}).where("id","=",J).execute();let G=await H1(J);if(!G)return null;if(G.order_id!=null)await N1(G.order_id,"SHIPPED");return await J4(G,$),await lX(G.delivery_route_id),G}async function pX(J){await q.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",J).execute()}async function lX(J){if(J==null)return;if(await q.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let G=await q.selectFrom("delivery_routes").where("id","=",J).select(["driver_id"]).executeTakeFirst();if(await q.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",J).execute(),G?.driver_id!=null)await q.updateTable("drivers").set({status:"active"}).where("id","=",G.driver_id).execute()}async function N1(J,$){let G=await q.selectFrom("orders").where("id","=",J).select(["id","status"]).executeTakeFirst();if(!G)return;let X=await Promise.resolve().then(() => (x0(),VJ)),{canTransition:Z,emitForStatus:Y}=X,L=qZ(G.status,$,Z);if(L.length===0){let{log:K}=await import("@stacksjs/logging").catch(()=>({log:null}));K?.warn(`[delivery] refused to move order ${J} from ${G.status} to ${$}: no legal transition`);return}for(let K of L)await q.updateTable("orders").set({status:K}).where("id","=",J).execute(),await Y(K,{...G,status:K})}function qZ(J,$,G){if(J===$)return[];if(G(J,$))return[$];for(let X of["PROCESSING","SHIPPED"]){if(X===J||X===$)continue;if(G(J,X)&&G(X,$))return[X,$]}return[]}async function wZ(J){return(await q.selectFrom("delivery_stops").where("delivery_route_id","=",J).select(["sequence"]).execute()).reduce((G,X)=>Math.max(G,X.sequence??0),0)+1}async function jZ(J){return(await q.selectFrom("delivery_stops").where("id","=",J).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function H1(J){return await q.selectFrom("delivery_stops").where("id","=",J).selectAll().executeTakeFirst()??null}async function fZ(J){return await q.selectFrom("delivery_stops").where("uuid","=",J).selectAll().executeTakeFirst()??null}var L4={};z(L4,{updateStatus:()=>eX,updateRegionsAndPostalCodes:()=>tX,updateCountries:()=>rX,update:()=>aX,store:()=>sX,softDelete:()=>uX,getZonesByCountry:()=>wX,getActiveShippingZones:()=>qX,formatZoneOptions:()=>EX,fetchById:()=>i$,fetchAll:()=>TX,destroy:()=>cX,bulkStore:()=>dX,bulkSoftDelete:()=>iX,bulkDestroy:()=>nX});import{db as X4}from"@stacksjs/database";async function cX(J){try{let $=await X4.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function uX(J){try{let $=await X4.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function nX(J){if(!J.length)return 0;try{let $=await X4.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function iX(J){if(!J.length)return 0;try{let $=await X4.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:oX}=globalThis.Bun;import{db as M1}from"@stacksjs/database";async function sX(J){try{let $=oX(),G={...D0(J),uuid:$};await M1.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await M1.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping zone");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function dX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...D0(X),uuid:oX()})),G=await M1.insertInto("shipping_zones").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as Z4}from"@stacksjs/database";import{formatDate as Y4}from"@stacksjs/orm";async function aX(J,$){try{if(!J)throw Error("Shipping zone ID is required for update");let G=await Z4.updateTable("shipping_zones").set({...D0($),updated_at:Y4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone: ${G.message}`);throw G}}async function eX(J,$){try{let G=await Z4.updateTable("shipping_zones").set({status:$,updated_at:Y4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone status: ${G.message}`);throw G}}async function rX(J,$){try{let G=await Z4.updateTable("shipping_zones").set({countries:$,updated_at:Y4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone countries");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${G.message}`);throw G}}async function tX(J,$,G){try{let X={updated_at:Y4(new Date)};if($!==void 0)X.regions=$;if(G!==void 0)X.postal_codes=G;let Z=await Z4.updateTable("shipping_zones").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update regions and postal codes");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${X.message}`);throw X}}var kZ={digital:f$,drivers:C$,geocoding:D$,licenses:b$,methods:c$,rates:s$,routes:w$,tracking:G4,zones:L4},CZ=kZ;var B1={};z(B1,{updateStatus:()=>H9,updateRate:()=>M9,updateDefaultStatus:()=>x9,update:()=>N9,taxFor:()=>$9,store:()=>F9,fetchById:()=>Y9,fetchAll:()=>L9,destroy:()=>G9,bulkStore:()=>Q9,bulkDestroy:()=>X9,breakdownFor:()=>z1,activeTaxRates:()=>V1});import{db as IZ}from"@stacksjs/database";function hZ(J){let $=Number(J);return Number.isFinite($)?$/100:0}async function V1(J={}){let $=IZ.selectFrom("tax_rates").where("status","=","active").selectAll();if(J.country)$=$.where("country","=",J.country);let G=await $.execute();if(!J.codes?.length)return G;let X=new Set(J.codes);return G.filter((Z)=>X.has(String(Z.code??"")))}function z1(J,$,G={}){let X=Math.max(0,Math.round(J)),Z=[],Y=0,L=0;for(let K of $){let W=hZ(K.rate),F=Math.round(X*W),N=Boolean(G.exempt&&K.exemptible);if(N)L+=F;else Y+=F;Z.push({id:Number(K.id),code:String(K.code??""),name:String(K.name??""),rate:W,amount:N?0:F,exempted:N})}return{taxable:X,components:Z,tax:Y,exempted:L}}async function $9(J,$={}){return z1(J,await V1($),$)}import{db as J9}from"@stacksjs/database";async function G9(J){try{let $=await J9.deleteFrom("tax_rates").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function X9(J){if(!J.length)return 0;try{let $=await J9.deleteFrom("tax_rates").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as Z9}from"@stacksjs/database";async function Y9(J){return await Z9.selectFrom("tax_rates").where("id","=",J).selectAll().executeTakeFirst()}async function L9(){return await Z9.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:K9}=globalThis.Bun;import{db as W9}from"@stacksjs/database";async function F9(J){try{return await W9.transaction(async($)=>{let G={...J,uuid:K9()};if(G.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let X=await $.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function Q9(J){if(!J.length)return 0;try{return await W9.transaction(async($)=>{let G=0;for(let X of J){let Z={...X,uuid:K9()};if(Z.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(Z).executeTakeFirst())G++}return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as K4}from"@stacksjs/database";import{formatDate as W4}from"@stacksjs/orm";async function N9(J,$){try{if(!J)throw Error("Tax rate ID is required for update");return await K4.transaction(async(G)=>{let X=await G.selectFrom("tax_rates").select("is_default").where("id","=",J).executeTakeFirst();if(!X)return;let Z=$.is_default??Boolean(X.is_default),Y=W4(new Date);if(Z)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Y}).where("id","!=",J).execute();let L=await G.updateTable("tax_rates").set({...$,updated_at:Y}).where("id","=",J).returningAll().executeTakeFirst();if(!L)return;return L})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function H9(J,$){try{let G=await K4.updateTable("tax_rates").set({status:$,updated_at:W4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update tax rate status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate status: ${G.message}`);throw G}}async function M9(J,$){try{let G=await K4.updateTable("tax_rates").set({rate:$,updated_at:W4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update rate information");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update rate information: ${G.message}`);throw G}}async function x9(J,$){try{return await K4.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",J).executeTakeFirst())return!1;let Z=W4(new Date);if($)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Z}).where("id","!=",J).execute();return await G.updateTable("tax_rates").set({is_default:$,updated_at:Z}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var P1={};z(P1,{restaurant:()=>S0,products:()=>Q4,default:()=>uZ});var Q4={};z(Q4,{updateStatus:()=>h9,updatePartySize:()=>g9,update:()=>F4,store:()=>C9,fetchWaiting:()=>T9,fetchPurchasedBetweenDates:()=>P9,fetchNotifiedBetweenDates:()=>U9,fetchCountByStatus:()=>E9,fetchCountBySource:()=>A9,fetchCountByQuantity:()=>_9,fetchCountByDateGrouped:()=>j9,fetchCountByDate:()=>O9,fetchCountByAllQuantities:()=>R9,fetchCountBetweenDates:()=>w9,fetchConversionRates:()=>q9,fetchCancelledBetweenDates:()=>S9,fetchById:()=>o0,fetchAll:()=>B9,destroy:()=>V9,bulkStore:()=>I9,bulkDestroy:()=>z9});import{db as A1}from"@stacksjs/database";async function V9(J){try{let $=await A1.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await A1.deleteFrom("waitlist_products").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function z9(J){if(!J.length)return 0;try{let $=await A1.deleteFrom("waitlist_products").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as T}from"@stacksjs/orm";async function o0(J){return await A.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function B9(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function A9(J,$){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(J&&$){let Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{source:Y,count:L})=>{return Z[Y]=L,Z},{})}async function O9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=T($),Z=T(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function _9(J){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",J).executeTakeFirst())?.count??0}async function R9(J,$){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(J&&$){let Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{quantity:Y,count:L})=>{return Z[Y]=L,Z},{})}async function U9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",X).whereNotNull("notified_at").execute()}async function P9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",X).whereNotNull("purchased_at").execute()}async function S9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",X).whereNotNull("cancelled_at").execute()}async function T9(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function E9(J,$,G){let X=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",J);if($&&G){let Y=T($),L=T(G);X=X.where("created_at",">=",Y).where("created_at","<=",L)}return(await X.executeTakeFirst())?.count??0}async function q9(J,$){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(J&&$){let W=T(J),F=T($);G=G.where("created_at",">=",W).where("created_at","<=",F)}let X=await G.execute(),Z=X.reduce((W,{count:F})=>W+F,0),Y=X.find((W)=>W.status==="purchased")?.count??0,L=Z>0?Y/Z*100:0,K=X.reduce((W,{status:F,count:N})=>{return W[F]={count:N,percentage:Z>0?N/Z*100:0},W},{});return{totalConversionRate:L,statusBreakdown:K}}async function w9(J,$){let G=T(J),X=T($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function j9(J,$){let G=A.selectFrom("waitlist_products").select(["created_at"]);if(J&&$){let Y=T(J),L=T($);G=G.where("created_at",">=",Y).where("created_at","<=",L)}let Z=(await G.execute()).reduce((Y,{created_at:L})=>{let K=(L||"").split("T")[0]||"unknown";return Y[K]=(Y[K]||0)+1,Y},{});return Object.entries(Z).map(([Y,L])=>({date:Y,count:L})).sort((Y,L)=>Y.date.localeCompare(L.date))}var{randomUUIDv7:k9}=globalThis.Bun;import{db as O1}from"@stacksjs/database";import{formatDate as f9}from"@stacksjs/orm";var gZ={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function DZ(J){return typeof J==="number"||J instanceof Date?f9(J):J}function s0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,Z])=>Z!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let Z of["notified_at","purchased_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=DZ(G[Z]);let X=gZ[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=f9(new Date);return G}async function C9(J){try{let $=k9(),G={...s0(J),uuid:$,status:J.status||"waiting"};await O1.insertInto("waitlist_products").values(G).executeTakeFirst();let X=await O1.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create waitlist product");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function I9(J){if(!J.length)return 0;try{let $=J.map((X)=>({...s0(X),status:X.status||"waiting",uuid:k9()})),G=await O1.insertInto("waitlist_products").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as vZ}from"@stacksjs/database";import{formatDate as yZ}from"@stacksjs/orm";async function F4(J,$){try{if(!J)throw Error("Waitlist product ID is required for update");let G=await o0(J);if(!G)return;await vZ.updateTable("waitlist_products").set({...s0($,G),updated_at:yZ(new Date)}).where("id","=",J).execute();let X=await o0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update waitlist product: ${G.message}`);throw G}}async function h9(J,$){return await F4(J,{status:$})}async function g9(J,$){return await F4(J,{quantity:$})}var S0={};z(S0,{updateWaitTimes:()=>K3,updateStatus:()=>Y3,updateQueuePosition:()=>W3,updatePartySize:()=>L3,update:()=>P0,store:()=>X3,fetchWaitingWithQuotedTimes:()=>s9,fetchWaitingWithPartySizes:()=>d9,fetchWaiting:()=>n9,fetchTimeSeriesStats:()=>J3,fetchTablesTurnedToday:()=>a9,fetchSeatingRate:()=>e9,fetchSeatedStats:()=>$3,fetchSeatedBetweenDates:()=>u9,fetchNoShowStats:()=>r9,fetchCurrentWaitTimes:()=>t9,fetchCountByTablePreference:()=>b9,fetchCountByPartySize:()=>p9,fetchCountByDate:()=>m9,fetchCountByAllPartySizes:()=>l9,fetchConversionRates:()=>i9,fetchById:()=>d0,fetchBetweenDates:()=>c9,fetchAverageWaitTimes:()=>o9,fetchAll:()=>y9,destroy:()=>D9,bulkStore:()=>Z3,bulkDestroy:()=>v9});import{db as _1}from"@stacksjs/database";async function D9(J){try{let $=await _1.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await _1.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function v9(J){if(!J.length)return 0;try{let $=await _1.deleteFrom("waitlist_restaurants").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as V}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function d0(J){return await V.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function y9(){return await V.selectFrom("waitlist_restaurants").selectAll().execute()}async function b9(){return(await V.selectFrom("waitlist_restaurants").select(["table_preference",V.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:G,count:X})=>{return $[G]=X,$},{})}async function m9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),Z=g(G);return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function p9(J){return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function l9(){return(await V.selectFrom("waitlist_restaurants").select(["party_size",V.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:G,count:X})=>{return $[G]=X,$},{})}async function c9(J,$){let G=g(J),X=g($);return await V.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",X).execute()}async function u9(J,$){let G=g(J),X=g($);return await V.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",X).where("status","=","seated").execute()}async function n9(){return await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function i9(){let J=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),$=J.reduce((Y,{count:L})=>Y+L,0),G=J.find((Y)=>Y.status==="seated")?.count??0,X=$>0?Number(G)/$*100:0,Z=J.reduce((Y,{status:L,count:K})=>{return Y[L]={count:K,percentage:$>0?K/$*100:0},Y},{});return{totalConversionRate:X,statusBreakdown:Z}}async function o9(){let J=await V.selectFrom("waitlist_restaurants").select([V.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),V.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:J?.avg_quoted_wait_time??0,averageActualWaitTime:J?.avg_actual_wait_time??0}}async function s9(){let J=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((X,Z)=>X+(Z.quoted_wait_time??0),0),G=J.length>0?$/J.length:0;return{entries:J,totalQuotedWaitTime:$,averageQuotedWaitTime:G}}async function d9(){let J=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((Z,Y)=>Z+Y.party_size,0),G=J.length>0?$/J.length:0,X=J.reduce((Z,Y)=>{return Z[Y.party_size]=(Z[Y.party_size]||0)+1,Z},{});return{entries:J,totalPartySize:$,averagePartySize:G,partySizeBreakdown:X}}async function a9(){let J=new Date,$=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),Z=g(G),Y=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",X).where("check_in_time","<=",Z).execute(),L=Y.length,K=Y.reduce((H,M)=>H+M.party_size,0),W=L>0?K/L:0,F=Y.reduce((H,M)=>{return H[M.table_preference]=(H[M.table_preference]||0)+1,H},{}),N=Y.reduce((H,M)=>{return H[M.party_size]=(H[M.party_size]||0)+1,H},{});return{totalTablesTurned:L,averagePartySize:W,totalCustomersSeated:K,breakdownByTablePreference:F,breakdownByPartySize:N}}async function e9(J,$){let G=g(J),X=g($),Z=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).where("check_in_time",">=",G).where("check_in_time","<=",X).groupBy("status").execute(),Y=Z.reduce((F,{count:N})=>F+N,0),L=Z.find((F)=>F.status==="seated")?.count??0,K=Y>0?Number(L)/Y*100:0,W=Z.reduce((F,{status:N,count:H})=>{return F[N]={count:H,percentage:Y>0?H/Y*100:0},F},{});return{totalEntries:Y,seatedEntries:L,seatingRate:K,statusBreakdown:W}}async function r9(J,$){let G=g(J),X=g($),Z=V.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",X),Y=await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",X).executeTakeFirst(),L=await Z.execute(),K=L.length,W=Y?.count&&Y.count>0?K/Y.count*100:0,F=L.reduce((_,U)=>_+(U.quoted_wait_time??0),0),N=K>0?F/K:0,H=L.reduce((_,U)=>_+U.party_size,0),M=K>0?H/K:0,O=L.reduce((_,U)=>{return _[U.table_preference]=(_[U.table_preference]||0)+1,_},{}),R=L.reduce((_,U)=>{return _[U.party_size]=(_[U.party_size]||0)+1,_},{});return{totalNoShows:K,noShowRate:W,averageQuotedWaitTime:N,averagePartySize:M,breakdownByTablePreference:O,breakdownByPartySize:R}}async function t9(){let J=await V.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=J.reduce((Z,Y)=>Z+(Y.quoted_wait_time||0),0),G=J.reduce((Z,Y)=>Z+(Y.actual_wait_time||0),0),X=J.length;return{averageQuoted:X>0?$/X:0,averageActual:X>0?G/X:0}}async function $3(){let J=Date.now()-86400000,$=await V.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),G=Array.from({length:24},(X,Z)=>({hour:Z,count:$.filter((Y)=>{return Y.seated_at===Z}).length}));return{total:$.length,byHour:G}}async function J3(){return(await V.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,G)=>{let X=G.created_at;if(!$[X])$[X]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[X].total++,$[X][G.status]++,$},{})}var{randomUUIDv7:G3}=globalThis.Bun;import{db as U1}from"@stacksjs/database";import{formatDate as R1}from"@stacksjs/orm";var bZ={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function mZ(J){if(typeof J==="number")return R1(J<=2147483647?J*1000:J);if(J instanceof Date)return R1(J);return J}function a0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,Z])=>Z!==void 0));for(let Z of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=mZ(G[Z]);let X=bZ[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=R1(new Date);return G}async function X3(J){try{let $=G3(),G={...a0(J),status:J.status||"waiting",uuid:$};await U1.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let X=await U1.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create restaurant waitlist entry");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function Z3(J){if(!J.length)return 0;try{let $=J.map((X)=>({...a0(X),status:X.status||"waiting",uuid:G3()})),G=await U1.insertInto("waitlist_restaurants").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as pZ}from"@stacksjs/database";import{formatDate as lZ}from"@stacksjs/orm";async function P0(J,$){try{if(!J)throw Error("Restaurant waitlist entry ID is required for update");let G=await d0(J);if(!G)return;await pZ.updateTable("waitlist_restaurants").set({...a0($,G),updated_at:lZ(new Date)}).where("id","=",J).execute();let X=await d0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${G.message}`);throw G}}async function Y3(J,$){return await P0(J,{status:$})}async function L3(J,$){return await P0(J,{party_size:$})}async function K3(J,$,G){return await P0(J,{quoted_wait_time:$,...G===void 0?{}:{actual_wait_time:G}})}async function W3(J,$){return await P0(J,{queue_position:$})}var cZ={products:Q4,restaurant:S0},uZ=cZ;var nZ={coupons:N4,customers:H4,devices:B4,errors:_4,giftCards:U4,orders:k4,payments:C4,products:b4,receipts:n4,restaurant:S0,shippings:x1,tax:B1,waitlists:P1},j8=nZ;export{P1 as waitlists,B1 as tax,x1 as shippings,S0 as restaurant,n4 as receipts,b4 as products,C4 as payments,k4 as orders,U4 as giftCards,_4 as errors,B4 as devices,j8 as default,H4 as customers,N4 as coupons,nZ as commerce};
|
|
27
|
+
AND COALESCE(refund_amount, 0) + ${X(5)} <= amount`,[$,$,Z,J,$]),L=typeof Y?.execute==="function"?await Y.execute():Y;if(Number(L?.numUpdatedRows??L?.[0]?.numUpdatedRows??L?.numAffectedRows??L?.affectedRows??L?.[0]?.affectedRows??L?.changes??0)>0){let M=await Y0(J);if(M)return M;throw Error(`Payment with ID ${J} disappeared during refund`)}let W=await Y0(J);if(!W)throw Error(`Payment with ID ${J} not found`);let F=String(W.status||"");if(!a3.has(F))throw Error(`Payment status ${F||"unknown"} cannot be refunded`);let N=W,H=Number(W.amount||0)-Number(N.refundAmount??N.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${H} minor units`)}var m4={};B(m4,{variants:()=>P$,units:()=>U$,reviews:()=>O$,manufacturers:()=>A$,items:()=>V$,default:()=>WZ,categories:()=>B$});var B$={};B(B$,{updateParent:()=>H6,updateDisplayOrder:()=>Q6,updateActiveStatus:()=>N6,update:()=>F6,store:()=>g4,removeChildCategories:()=>Z6,remove:()=>G6,findOrCreateByName:()=>W6,fetchStats:()=>tJ,fetchRootCategories:()=>aJ,fetchChildCategories:()=>rJ,fetchCategoryTree:()=>J6,fetchByName:()=>sJ,fetchById:()=>f,fetchByDisplayOrder:()=>eJ,fetchAll:()=>h4,fetchActive:()=>dJ,deactivateChildCategories:()=>L6,deactivate:()=>Y6,compareCategoryGrowth:()=>$6,bulkRemove:()=>X6});import{db as B0}from"@stacksjs/database";import{db as S}from"@stacksjs/database";import{formatDate as C0}from"@stacksjs/orm";async function h4(){return await S.selectFrom("categories").selectAll().execute()}async function f(J){return await S.selectFrom("categories").where("id","=",J).selectAll().executeTakeFirst()}async function sJ(J){return await S.selectFrom("categories").where("name","=",J).selectAll().executeTakeFirst()}async function dJ(){return await S.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function aJ(){return await S.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function rJ(J){return await S.selectFrom("categories").where("parent_category_id","=",J).where("is_active","=",!0).selectAll().execute()}async function eJ(J=!0){let $=S.selectFrom("categories").where("is_active","=",!0).selectAll();if(J)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function tJ(){let J=await S.selectFrom("categories").select(S.fn.count("id").as("count")).executeTakeFirst(),$=await S.selectFrom("categories").where("is_active","=",!0).select(S.fn.count("id").as("count")).executeTakeFirst(),G=await S.selectFrom("categories").whereNull("parent_category_id").select(S.fn.count("id").as("count")).executeTakeFirst(),X=await S.selectFrom("categories").whereNotNull("image_url").select(S.fn.count("id").as("count")).executeTakeFirst(),Z=new Date;Z.setDate(Z.getDate()-30);let Y=C0(Z),L=await S.selectFrom("categories").where("created_at",">=",Y).selectAll().limit(5).execute(),K=await S.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",S.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number($?.count||0),root_categories:Number(G?.count||0),child_categories:Number(J?.count||0)-Number(G?.count||0),with_images:Number(X?.count||0),recently_added:L,top_parent_categories:K.map((W)=>({id:String(W.parent_category_id||""),name:String(W.parent_name||""),child_count:Number(W.child_count)}))}}async function $6(J=30){let $=new Date,G=C0($),X=new Date;X.setDate($.getDate()-J);let Z=C0(X),Y=new Date(X);Y.setDate(Y.getDate()-1);let L=C0(Y),K=new Date(Y);K.setDate(Y.getDate()-J);let W=C0(K),F=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",G).executeTakeFirst(),N=await S.selectFrom("categories").select(S.fn.count("id").as("count")).where("created_at",">=",W).where("created_at","<=",L).executeTakeFirst(),H=Number(F?.count||0),M=Number(N?.count||0),O=H-M,R=M!==0?O/M*100:H>0?100:0;return{current_period:H,previous_period:M,difference:O,percentage_change:R,days_range:J}}async function J6(){let J=await h4(),$=new Map;J.forEach((Z)=>{$.set(Z.id,{...Z,children:[]})});let G=[];J.forEach((Z)=>{let Y=$.get(Z.id);if(Z.parent_category_id){let L=$.get(Z.parent_category_id);if(L)L.children.push(Y)}else G.push(Y)}),G.sort((Z,Y)=>Z.display_order-Y.display_order);let X=(Z)=>{Z.sort((Y,L)=>Y.display_order-L.display_order),Z.forEach((Y)=>{if(Y.children.length>0)X(Y.children)})};return X(G),G}async function G6(J){let $=await B0.deleteFrom("categories").where("id","=",J).executeTakeFirst();return Q($)>0}async function X6(J){if(!J.length)return 0;let $=await B0.deleteFrom("categories").where("id","in",J).executeTakeFirst();return Q($)}async function Z6(J){let $=await B0.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return Q($)}async function Y6(J){if(!await f(J))throw Error(`Category with ID ${J} not found`);return!!await B0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",J).executeTakeFirst()}async function L6(J){let $=await B0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",J).execute();return Number($.length)||0}var{randomUUIDv7:r3}=globalThis.Bun;import{db as K6}from"@stacksjs/database";import{HttpError as x$}from"@stacksjs/error-handling";import{isUniqueViolation as e3}from"@stacksjs/orm";import{slug as t3}from"@stacksjs/strings";async function g4(J){try{let $=J.parent_category_id?Number(J.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new x$(422,"Parent category ID must be a positive integer");if($&&!await f($))throw new x$(422,`Parent category with ID ${J.parent_category_id} not found`);let G={...J,uuid:r3(),is_active:J.is_active??!0,parent_category_id:J.parent_category_id||null},X=await K6.insertInto("categories").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create category");return X}catch($){if($ instanceof x$)throw $;if(e3($))throw new x$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function W6(J){if(!J.name)throw Error("Name is required");let $=await K6.selectFrom("categories").selectAll().where("name","=",J.name).executeTakeFirst();if($)return $;let G={name:J.name,slug:t3(J.name),is_active:J.is_active??!0,display_order:0};return await g4(G)}import{db as I0}from"@stacksjs/database";import{HttpError as V0}from"@stacksjs/error-handling";import{formatDate as z$,isUniqueViolation as $Z}from"@stacksjs/orm";async function F6(J,$){if(!await f(J))return;if(Object.hasOwn($,"parent_category_id")){let X=$.parent_category_id?Number($.parent_category_id):void 0;if(X!==void 0&&(!Number.isSafeInteger(X)||X<=0))throw new V0(422,"Parent category ID must be a positive integer");if(X===J)throw new V0(422,"A category cannot be its own parent");if(X&&!await f(X))throw new V0(422,`Parent category with ID ${$.parent_category_id} not found`);if(X&&await M6(J,String(X)))throw new V0(422,"This operation would create a circular category hierarchy")}try{let X=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},Z=await I0.updateTable("categories").set({...$,...X,updated_at:z$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(X){if(X instanceof V0)throw X;if($Z(X))throw new V0(409,"A category with this name or slug already exists");if(X instanceof Error)throw Error(`Failed to update category: ${X.message}`);throw X}}async function Q6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);try{return await I0.updateTable("categories").set({display_order:$,updated_at:z$(new Date)}).where("id","=",J).execute(),await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category display order: ${X.message}`);throw X}}async function N6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);try{return await I0.updateTable("categories").set({is_active:$,updated_at:z$(new Date)}).where("id","=",J).execute(),await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function H6(J,$){if(!await f(J))throw Error(`Category with ID ${J} not found`);if($){let X=Number($);if(X===J)throw Error("A category cannot be its own parent");if(!await f(X))throw Error(`Parent category with ID ${$} not found`);if(await M6(J,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let X={updated_at:z$(new Date)};if($===null)await I0.updateTable("categories").set({...X,parent_category_id:null}).where("id","=",J).execute();else await I0.updateTable("categories").set({...X,parent_category_id:$}).where("id","=",J).execute();return await f(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category parent: ${X.message}`);throw X}}async function M6(J,$){let G=Number($),X=new Set;while(G){if(X.has(G))return!0;if(G===J)return!0;X.add(G);let Z=await f(G),Y=Z?.parent_category_id??Z?.parentCategoryId;if(!Z||!Y)return!1;G=Number(Y)}return!1}var V$={};B(V$,{updateInventory:()=>T6,updateAvailability:()=>S6,update:()=>P6,store:()=>R6,fetchTopProducts:()=>A6,fetchById:()=>u,fetchAll:()=>V6,destroy:()=>z6,bulkStore:()=>U6,bulkDestroy:()=>B6});import{db as x6}from"@stacksjs/database";async function z6(J){try{let $=await x6.deleteFrom("products").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function B6(J){if(!J.length)return 0;try{let $=await x6.deleteFrom("products").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as a,sql as JZ}from"@stacksjs/database";async function u(J){let $=await a.selectFrom("products").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.manufacturer_id)G=await a.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)X=await a.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:G,category:X}}return}async function V6(){let J=await a.selectFrom("products").selectAll().execute(),$=J.map((F)=>F.manufacturer_id).filter((F)=>F!==null&&F!==void 0),G=J.map((F)=>F.category_id).filter((F)=>F!==null&&F!==void 0),X=a.selectFrom("manufacturers"),Z=a.selectFrom("categories");if($.length>0)X=X.where("id","in",$);if(G.length>0)Z=Z.where("id","in",G);let Y=await X.selectAll().execute(),L=await Z.selectAll().execute(),K=Y.reduce((F,N)=>{return F[N.id]=N,F},{}),W=L.reduce((F,N)=>{return F[N.id]=N,F},{});return J.map((F)=>({...F,manufacturer:F.manufacturer_id?K[F.manufacturer_id]:null,category:F.category_id?W[F.category_id]:null}))}async function A6(J=5){try{return(await a.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",a.fn.sum("order_items.quantity").as("units_sold"),JZ`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(J).execute()).map((G)=>({id:Number(G.id),name:String(G.name??"Unnamed product"),units_sold:Number(G.units_sold??0),revenue:Number(G.revenue??0),inventory_count:Number(G.inventory_count??0)}))}catch($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:O6}=globalThis.Bun;import{db as _6}from"@stacksjs/database";async function R6(J){try{let $={...J,uuid:O6()},G=await _6.insertInto("products").values($).executeTakeFirst();if(!G)throw Error("Failed to create product item");let X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),Z=await u(X);if(!Z)throw Error("Failed to create product item");return Z}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function U6(J){if(!J.length)return 0;let $=0;try{return await _6.transaction().execute(async(G)=>{for(let X of J){let Z={...X,uuid:O6()};await G.insertInto("products").values(Z).execute(),$++}}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as D4}from"@stacksjs/database";import{formatDate as v4}from"@stacksjs/orm";async function P6(J,$){try{if(!J)throw Error("Product item ID is required for update");let G=await D4.updateTable("products").set({...$,updated_at:v4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item: ${G.message}`);throw G}}async function S6(J,$){if(!await u(J))throw Error(`Product item with ID ${J} not found`);try{return await D4.updateTable("products").set({is_available:$,updated_at:v4(new Date)}).where("id","=",J).execute(),await u(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item availability: ${X.message}`);throw X}}async function T6(J,$){let G=await u(J);if(!G)throw Error(`Product item with ID ${J} not found`);let X={updated_at:v4(new Date)};if($!==void 0)X.inventory_count=$;if(Object.keys(X).length===1)return G;try{return await D4.updateTable("products").set(X).where("id","=",J).execute(),await u(J)}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update inventory information: ${Z.message}`);throw Z}}var A$={};B(A$,{updateFeaturedStatus:()=>l6,updateByUuid:()=>c6,update:()=>p6,store:()=>y6,fetchWithProductCount:()=>h6,fetchFeatured:()=>C6,fetchByUuid:()=>k6,fetchById:()=>f6,fetchByCountry:()=>I6,fetchAll:()=>w6,destroy:()=>q6,bulkStore:()=>b6,bulkDestroy:()=>j6});import{db as E6}from"@stacksjs/database";async function q6(J){try{let $=await E6.deleteFrom("manufacturers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function j6(J){if(!J.length)return 0;try{let $=await E6.deleteFrom("manufacturers").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as n}from"@stacksjs/database";function w6(){return n.selectFrom("manufacturers").selectAll().execute()}async function f6(J){return await n.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function k6(J){return await n.selectFrom("manufacturers").where("uuid","=",J).selectAll().executeTakeFirst()}async function C6(J=10){return await n.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(J).execute()}async function I6(J,$={}){let G=$.page||1,X=$.limit||2,Z=await n.selectFrom("manufacturers").select(n.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),Y=Number(Z?.total||0),L=await n.selectFrom("manufacturers").selectAll().where("country","=",J).limit(X).offset((G-1)*X).execute(),K=Math.ceil(Y/X);return{data:L,paging:{total_records:Y,page:G,total_pages:K},next_cursor:G<K?G+1:null}}async function h6(J={}){let $=n.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(J.country)$=$.where("m.country","=",J.country);if(J.featured!==void 0)$=$.where("m.featured","=",J.featured);return $=$.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",n.fn.count("p.id").as("product_count")]).groupBy("m.id"),$.execute()}var{randomUUIDv7:D6}=globalThis.Bun;import{db as v6}from"@stacksjs/database";import{HttpError as g6}from"@stacksjs/error-handling";import{isUniqueViolation as GZ}from"@stacksjs/orm";async function y6(J){try{let $={...J,uuid:D6(),featured:J.featured??!1},G=await v6.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch($){if($ instanceof g6)throw $;if(GZ($))throw new g6(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function b6(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:D6(),featured:G.featured??!1};await v6.insertInto("manufacturers").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${G.message}`);throw G}}import{db as y4}from"@stacksjs/database";import{HttpError as m6}from"@stacksjs/error-handling";import{formatDate as b4,isUniqueViolation as XZ}from"@stacksjs/orm";async function p6(J,$){try{if(!J)throw Error("Manufacturer ID is required for update");let G=await y4.updateTable("manufacturers").set({...$,updated_at:b4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof m6)throw G;if(XZ(G))throw new m6(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function l6(J,$){try{let G=await y4.updateTable("manufacturers").set({featured:$,updated_at:b4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer featured status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${G.message}`);throw G}}async function c6(J,$){try{let G=await y4.updateTable("manufacturers").set({...$,updated_at:b4(new Date)}).where("uuid","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer: ${G.message}`);throw G}}var O$={};B(O$,{updateVotes:()=>W2,update:()=>K2,store:()=>Z2,fetchStatsByProductIds:()=>X2,fetchStats:()=>G2,fetchMostHelpfulByProductId:()=>e6,fetchByUserId:()=>a6,fetchByProductId:()=>d6,fetchById:()=>o6,fetchApprovedByProductId:()=>r6,fetchAll:()=>s6,destroy:()=>n6,bulkDestroy:()=>i6});import{db as u6}from"@stacksjs/database";async function n6(J){try{let $=await u6.deleteFrom("reviews").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function i6(J){if(!J.length)return 0;try{let $=await u6.deleteFrom("reviews").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as A0}from"@stacksjs/database";async function o6(J){return await A0.selectFrom("reviews").where("id","=",J).selectAll().executeTakeFirst()}async function s6(){return await A0.selectFrom("reviews").selectAll().execute()}async function d6(J){return await A0.selectFrom("reviews").where("product_id","=",J).selectAll().execute()}async function a6(J){return await A0.selectFrom("reviews").where("customer_id","=",J).selectAll().execute()}async function r6(J){return await A0.selectFrom("reviews").where("product_id","=",J).where("is_approved","=",!0).selectAll().execute()}async function e6(J){return await A0.selectFrom("reviews").where("product_id","=",J).orderBy("helpful_votes","desc").selectAll().execute()}import{db as t6}from"@stacksjs/database";function $2(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function J2(J){let $=$2();$.total=J.length;let G=0;for(let X of J){if(X.rating===null||X.rating===void 0){$.commentsOnly++;continue}let Z=Number(X.rating);if(Number.isNaN(Z)){$.commentsOnly++;continue}$.rated++,G+=Z;let Y=Math.min(5,Math.max(1,Math.round(Z)));$.distribution[Y]++}if($.rated>0)$.average=Math.round(G/$.rated*10)/10;return $}async function G2(J){let $=await t6.selectFrom("reviews").select(["rating"]).where("product_id","=",J).where("is_approved","=",!0).execute();return J2($)}async function X2(J){let $=new Map;for(let Z of J)$.set(Z,$2());if(J.length===0)return $;let G=await t6.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",J).where("is_approved","=",!0).execute(),X=new Map;for(let Z of G){let Y=X.get(Z.product_id);if(Y)Y.push({rating:Z.rating});else X.set(Z.product_id,[{rating:Z.rating}])}for(let[Z,Y]of X)$.set(Z,J2(Y));return $}var{randomUUIDv7:ZZ}=globalThis.Bun;import{db as YZ}from"@stacksjs/database";function LZ(J){let $=J.rating!==void 0&&J.rating!==null,G=typeof J.content==="string"&&J.content.trim().length>0,X=typeof J.title==="string"&&J.title.trim().length>0;return!$&&!G&&!X}async function Z2(J){try{if(LZ(J))throw Error("A review needs a rating or something written: both were empty");let $={...J,uuid:ZZ(),rating:J.rating??null,is_verified_purchase:J.is_verified_purchase??!1,is_approved:J.is_approved??!1,helpful_votes:J.helpful_votes??0,unhelpful_votes:J.unhelpful_votes??0,is_featured:J.is_featured??!1},G=await YZ.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create review");return G}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${$.message}`)}throw $}}import{db as Y2}from"@stacksjs/database";import{formatDate as L2}from"@stacksjs/orm";async function K2(J,$){try{if(!J)throw Error("Review ID is required for update");let G=await Y2.updateTable("reviews").set({...$,updated_at:L2(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review: ${G.message}`);throw G}}async function W2(J,$,G=!0){try{let X=$==="helpful"?"helpful_votes":"unhelpful_votes",Z=G?`COALESCE("${X}", 0) + 1`:`MAX(COALESCE("${X}", 0) - 1, 0)`,Y=await Y2.unsafe(`UPDATE "reviews" SET "${X}" = ${Z}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[L2(new Date),J]).execute(),L=Array.isArray(Y)?Y[0]:Y;if(!L)throw Error("Failed to update review votes");return L}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var U$={};B(U$,{updateDefaultStatus:()=>U2,update:()=>_2,store:()=>B2,getDefaultUnit:()=>O2,formatUnitOptions:()=>A2,fetchById:()=>M2,fetchAll:()=>x2,destroy:()=>Q2,bulkUpdate:()=>R2,bulkStore:()=>V2,bulkDestroy:()=>N2});import{db as F2}from"@stacksjs/database";async function Q2(J){try{let $=await F2.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function N2(J){if(!J.length)return 0;try{let $=await F2.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as H2}from"@stacksjs/database";async function M2(J){return await H2.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function x2(){return await H2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:z2}=globalThis.Bun;import{db as h0}from"@stacksjs/database";async function B2(J){try{return await h0.transaction(async($)=>{let G={...J,uuid:z2()},X=await $.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(G.is_default&&G.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();return X})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function V2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:z2()},Z=await h0.insertInto("product_units").values(X).returningAll().executeTakeFirst();if(X.is_default&&X.type&&Z)await h0.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",Z.id).execute();$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function A2(J){try{let $=h0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(J)$=$.where("type","=",J);return $=$.orderBy("name"),$.execute().then((G)=>G.map((X)=>({id:String(X.id),name:X.name,abbreviation:X.abbreviation,is_default:X.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function O2(J){try{return await h0.selectFrom("product_units").selectAll().where("type","=",J).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as _$}from"@stacksjs/database";import{formatDate as R$}from"@stacksjs/orm";async function _2(J,$){try{if(!J)throw Error("Product unit ID is required for update");return await _$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",J).executeTakeFirst();if(!X)return;let Z=$.type??X.type;if(($.is_default??Boolean(X.is_default))&&Z)await G.updateTable("product_units").set({is_default:!1,updated_at:R$(new Date)}).where("type","=",Z).where("id","!=",J).execute();let L=await G.updateTable("product_units").set({...$,updated_at:R$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!L)return;return L})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function R2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X=G;if(!X.id)continue;let Z=X.data&&typeof X.data==="object"?X.data:{...X};delete Z.id;let Y=await _$.updateTable("product_units").set({...Z,updated_at:R$(new Date)}).where("id","=",X.id).executeTakeFirst(),L=Z;if(L.is_default===!0&&L.type)await _$.updateTable("product_units").set({is_default:!1}).where("type","=",L.type).where("id","!=",X.id).execute();if(Number(Y.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function U2(J,$){try{return await _$.transaction(async(G)=>{let X=await G.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!X)return!1;let Z=R$(new Date);if($&&X.type)await G.updateTable("product_units").set({is_default:!1,updated_at:Z}).where("type","=",X.type).where("id","!=",J).execute();return await G.updateTable("product_units").set({is_default:$,updated_at:Z}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var P$={};B(P$,{update:()=>v2,store:()=>k2,generateVariantCombinations:()=>h2,formatVariantOptions:()=>I2,fetchById:()=>q2,fetchAll:()=>j2,destroy:()=>S2,bulkUpdate:()=>y2,bulkStore:()=>C2,bulkDestroy:()=>T2});import{db as P2}from"@stacksjs/database";async function S2(J){try{let $=await P2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function T2(J){if(!J.length)return 0;try{let $=await P2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as E2}from"@stacksjs/database";async function q2(J){return await E2.selectFrom("product_variants").where("id","=",J).selectAll().executeTakeFirst()}async function j2(){return await E2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:w2}=globalThis.Bun;import{db as f2}from"@stacksjs/database";async function k2(J){try{let $={...J,uuid:w2()},G=await f2.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product variant");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function C2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let X={...G,uuid:w2()};await f2.insertInto("product_variants").values(X).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${G.message}`);throw G}}function I2(J){if(!J||!J.length)return JSON.stringify([]);let $=J.map((G)=>G.trim()).filter(Boolean);return JSON.stringify($)}function h2(J){let $=Object.keys(J);if(!$.length)return[];function G(X,Z){if(X===$.length)return[Z];let Y=$[X],L=J[Y]??[],K=[];for(let W of L){let F={...Z,[Y]:W};K.push(...G(X+1,F))}return K}return G(0,{})}import{db as g2}from"@stacksjs/database";import{formatDate as D2}from"@stacksjs/orm";async function v2(J,$){try{let G=await g2.updateTable("product_variants").set({...$,updated_at:D2(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variant: ${G.message}`);throw G}}async function y2(J){if(!J.length)return 0;let $=0;try{for(let G of J){if(!G.id)continue;let X=await g2.updateTable("product_variants").set({...G,updated_at:D2(new Date)}).where("id","=",G.id).executeTakeFirst();if(Number(X.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${G.message}`);throw G}}var KZ={categories:B$,items:V$,manufacturers:A$,reviews:O$,units:U$,variants:P$},WZ=KZ;var i4={};B(i4,{updateStatus:()=>e2,updatePrintJob:()=>t2,update:()=>r2,store:()=>d2,fetchSuccessRate:()=>u2,fetchPrintsPerHour:()=>o2,fetchPrintTimeStats:()=>i2,fetchPrintJobStats:()=>c2,fetchPageStats:()=>n2,fetchById:()=>O0,fetchAll:()=>l2,destroy:()=>m2,bulkStore:()=>a2,bulkDestroy:()=>p2});import{db as b2}from"@stacksjs/database";async function m2(J){try{let $=await b2.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function p2(J){if(!J.length)return 0;try{let $=await b2.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as p4}from"@stacksjs/database";import{formatDate as FZ}from"@stacksjs/orm";function b(J){return FZ(J)}function QZ(J){if(J instanceof Date)return Number.isNaN(J.getTime())?null:J;if(typeof J==="number"){let X=new Date(J<=2147483647?J*1000:J);return Number.isNaN(X.getTime())?null:X}let $=String(J||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let X=new Date(Number($)*1000);return Number.isNaN(X.getTime())?null:X}let G=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function O0(J){return await p4.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function l2(){return await p4.selectFrom("receipts").selectAll().execute()}async function c2(J,$){let G=b(J),X=b($),Z=await h("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning,averageSize:Math.round(Z.averageSize),averagePages:Math.round(Z.averagePages),averageDuration:Math.round(Z.averageDuration)}}async function u2(J,$){let G=b(J),X=b($),Z=await h("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(L)=>L.where("timestamp",">=",G).where("timestamp","<=",X));return{successRate:Z.total>0?Math.round(Z.success/Z.total*100):0,total:Z.total,success:Z.success,failed:Z.failed,warning:Z.warning}}async function n2(J,$){let G=b(J),X=b($),Z=await h("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{totalPages:Z.totalPages,averagePagesPerReceipt:Math.round(Z.averagePagesPerReceipt),totalReceipts:Z.totalReceipts}}async function i2(J,$){let G=b(J),X=b($),Z=await h("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(Y)=>Y.where("timestamp",">=",G).where("timestamp","<=",X));return{averageDuration:Math.round(Z.averageDuration),minDuration:Z.minDuration,maxDuration:Z.maxDuration,totalJobs:Z.totalJobs}}async function o2(J,$){let G=typeof J==="number"?J:J.getTime(),X=typeof $==="number"?$:$.getTime(),Z=b(J),Y=b($),L=await p4.selectFrom("receipts").where("timestamp",">=",Z).where("timestamp","<=",Y).selectAll().execute(),K=L.length,W=Math.ceil((X-G)/3600000),F=W>0?Math.round(K/W):0,N=Array.from({length:24},(H,M)=>({hour:M,count:0}));return L.forEach((H)=>{let M=QZ(H.timestamp);if(!M)return;N[M.getHours()].count++}),{totalPrints:K,totalHours:W,printsPerHour:F,hourlyBreakdown:N}}var{randomUUIDv7:s2}=globalThis.Bun;import{db as c4}from"@stacksjs/database";import{formatDate as l4}from"@stacksjs/orm";function g0(J){try{if(typeof J==="number")return l4(J<=2147483647?J*1000:J);if(typeof J==="string"&&/^\d{10}$/.test(J))return l4(Number(J)*1000);return l4(J)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function d2(J){try{let $=s2(),G={...J,timestamp:g0(J.timestamp),uuid:$};await c4.insertInto("receipts").values(G).executeTakeFirst();let X=await c4.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function a2(J){if(!J.length)return 0;try{let $=J.map((X)=>({...X,timestamp:g0(X.timestamp),uuid:s2()})),G=await c4.insertInto("receipts").values($).executeTakeFirst();return Number(G.numInsertedOrUpdatedRows??G.numAffectedRows??G.affectedRows??G.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as u4}from"@stacksjs/database";import{formatDate as n4}from"@stacksjs/orm";async function r2(J,$){try{if(!J)throw Error("Receipt ID is required for update");let G={...$,...$.timestamp===void 0?{}:{timestamp:g0($.timestamp)},updated_at:n4(new Date)};await u4.updateTable("receipts").set(G).where("id","=",J).execute();let X=await O0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function e2(J,$){try{await u4.updateTable("receipts").set({status:$,updated_at:n4(new Date)}).where("id","=",J).execute();let G=await O0(J);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function t2(J,$,G,X){try{let Z={updated_at:n4(new Date)};if($!==void 0)Z.size=$;if(G!==void 0)Z.pages=G;if(X!==void 0)Z.duration=X;await u4.updateTable("receipts").set(Z).where("id","=",J).execute();let Y=await O0(J);if(!Y)throw Error("Failed to update receipt job information");return Y}catch(Z){if(Z instanceof Error)throw TypeError(`Failed to update receipt job information: ${Z.message}`);throw Z}}var z1={};B(z1,{zones:()=>K4,tracking:()=>X4,routes:()=>w$,rates:()=>d$,methods:()=>u$,licenses:()=>m$,geocoding:()=>v$,drivers:()=>I$,digital:()=>k$,default:()=>hZ});var w$={};B(w$,{validateDeliveryRouteWrite:()=>_0,updateStops:()=>FG,updateMetrics:()=>QG,updateLastActive:()=>KG,update:()=>WG,store:()=>LG,fetchById:()=>T$,fetchByDriver:()=>YG,fetchAll:()=>XG,fetchActive:()=>ZG,destroy:()=>JG,bulkDestroy:()=>GG,DeliveryRouteInputError:()=>I});import{db as $G}from"@stacksjs/database";async function JG(J){try{let $=await $G.deleteFrom("delivery_routes").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function GG(J){if(!J.length)return 0;try{let $=await $G.deleteFrom("delivery_routes").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as S$}from"@stacksjs/database";async function T$(J){return await S$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function XG(){return await S$.selectFrom("delivery_routes").selectAll().execute()}async function ZG(){return await S$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function YG(J){return await S$.selectFrom("delivery_routes").where("driver","=",J).selectAll().execute()}var{randomUUIDv7:MZ}=globalThis.Bun;import{db as o4}from"@stacksjs/database";function L0(J,$){let G={};for(let[X,Z]of Object.entries($))for(let Y of Z){if(!Object.prototype.hasOwnProperty.call(J,Y)||J[Y]===void 0)continue;G[X]=J[Y];break}return G}function D0(J){return L0(J,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function i(J){return L0(J,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function v0(J){return L0(J,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function y0(J){return L0(J,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function b0(J){return L0(J,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function m0(J){return L0(J,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function E$(J){return L0(J,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as NZ}from"@stacksjs/database";class I extends TypeError{constructor(J){super(J);this.name="DeliveryRouteInputError"}}function q$(J,$,G){return Number(J[G]??$?.[G])}function HZ(J,$){let G=J.last_active??$?.last_active;if(G===void 0||G===null)return Date.now();if(G instanceof Date)return G.getTime();if(typeof G==="number")return G;if(typeof G==="string"&&/^\d{10,13}$/.test(G))return Number(G);return Number.NaN}async function _0(J,$){let G=q$(J,$,"driver_id"),X=q$(J,$,"stops"),Z=q$(J,$,"delivery_time"),Y=q$(J,$,"total_distance"),L=HZ(J,$);if(!Number.isSafeInteger(G)||G<1)throw new I("Driver must be a positive integer.");if(!Number.isSafeInteger(X)||X<0)throw new I("Stops must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new I("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(Y)||Y<0)throw new I("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(L)||L<0)throw new I("Last active must be a valid Unix timestamp.");let K=await NZ.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!K)throw new I(`Driver ${G} was not found.`);return{...J,driver_id:Number(K.id),driver:K.name,vehicle:K.vehicle_number,last_active:L}}async function LG(J){try{let $=MZ(),G=E$(J),Z={...await _0(G),uuid:$};await o4.insertInto("delivery_routes").values(Z).executeTakeFirst();let Y=await o4.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!Y)throw Error("Failed to create delivery route");return Y}catch($){if($ instanceof I)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function KG(J){try{await o4.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",J).execute();let $=await T$(J);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as j$}from"@stacksjs/database";import{formatDate as s4}from"@stacksjs/orm";async function WG(J,$){try{if(!J)throw Error("Delivery route ID is required for update");let G=await j$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=E$($),Z=await _0(X,G),Y=await j$.updateTable("delivery_routes").set({...Z,updated_at:s4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof I)throw G;if(G instanceof Error)throw TypeError(`Failed to update delivery route: ${G.message}`);throw G}}async function FG(J,$){try{let G=await j$.updateTable("delivery_routes").set({stops:$,updated_at:s4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update delivery route stops");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery route stops: ${G.message}`);throw G}}async function QG(J,$,G){try{let X={updated_at:s4(new Date)};if($!==void 0)X.delivery_time=$;if(G!==void 0)X.total_distance=G;let Z=await j$.updateTable("delivery_routes").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update delivery metrics");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery metrics: ${X.message}`);throw X}}var k$={};B(k$,{updateStatus:()=>UG,updateDeliverySettings:()=>PG,update:()=>RG,store:()=>OG,softDelete:()=>HG,fetchById:()=>BG,fetchAll:()=>VG,destroy:()=>NG,bulkStore:()=>_G,bulkSoftDelete:()=>xG,bulkDestroy:()=>MG});import{db as f$}from"@stacksjs/database";async function NG(J){try{let $=await f$.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function HG(J){try{let $=await f$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function MG(J){if(!J.length)return 0;try{let $=await f$.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function xG(J){if(!J.length)return 0;try{let $=await f$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as zG}from"@stacksjs/database";async function BG(J){return await zG.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function VG(){return await zG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:AG}=globalThis.Bun;import{db as d4}from"@stacksjs/database";async function OG(J){try{let $=AG(),G={...y0(J),uuid:$};await d4.insertInto("digital_deliveries").values(G).executeTakeFirst();let X=await d4.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created digital delivery");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function _G(J){if(!J.length)return 0;try{let $=J.map((X)=>({...y0(X),uuid:AG()})),G=await d4.insertInto("digital_deliveries").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as a4}from"@stacksjs/database";import{formatDate as r4}from"@stacksjs/orm";async function RG(J,$){try{if(!J)throw Error("Digital delivery ID is required for update");let G=await a4.updateTable("digital_deliveries").set({...y0($),updated_at:r4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery: ${G.message}`);throw G}}async function UG(J,$){try{let G=await a4.updateTable("digital_deliveries").set({status:$,updated_at:r4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update digital delivery status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery status: ${G.message}`);throw G}}async function PG(J,$,G,X,Z){try{let Y={updated_at:r4(new Date)};if($!==void 0)Y.download_limit=$;if(G!==void 0)Y.expiry_days=G;if(X!==void 0)Y.requires_login=X;if(Z!==void 0)Y.automatic_delivery=Z;let L=await a4.updateTable("digital_deliveries").set(Y).where("id","=",J).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update delivery settings");return L}catch(Y){if(Y instanceof Error)throw TypeError(`Failed to update delivery settings: ${Y.message}`);throw Y}}var I$={};B(I$,{updateStatus:()=>IG,updateContact:()=>hG,update:()=>CG,store:()=>fG,fetchById:()=>C$,fetchAll:()=>TG,destroy:()=>qG,bulkStore:()=>kG,bulkDestroy:()=>jG});import{db as EG}from"@stacksjs/database";import{db as SG}from"@stacksjs/database";async function C$(J){return await SG.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function TG(){return await SG.selectFrom("drivers").selectAll().execute()}async function qG(J){try{let $=await EG.deleteFrom("drivers").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function jG(J){if(!J.length)return 0;let $=0;try{return await EG.transaction().execute(async(G)=>{for(let X of J)if(await C$(X))await G.deleteFrom("drivers").where("id","=",X).execute(),$++}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${G.message}`);throw G}}var{randomUUIDv7:wG}=globalThis.Bun;import{db as e4}from"@stacksjs/database";async function fG(J){try{let $=wG(),G={...m0(J),uuid:$};await e4.insertInto("drivers").values(G).executeTakeFirst();let X=await e4.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created driver");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function kG(J){if(!J.length)return 0;try{let $=J.map((X)=>({...m0(X),uuid:wG()})),G=await e4.insertInto("drivers").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as t4}from"@stacksjs/database";import{formatDate as $1}from"@stacksjs/orm";async function CG(J,$){try{if(!J)throw Error("Driver ID is required for update");let G=await t4.updateTable("drivers").set({...m0($),updated_at:$1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver: ${G.message}`);throw G}}async function IG(J,$){try{let G=await t4.updateTable("drivers").set({status:$,updated_at:$1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update driver status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver status: ${G.message}`);throw G}}async function hG(J,$){try{let G={updated_at:$1(new Date)};if($!==void 0)G.phone=$;let X=await t4.updateTable("drivers").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update contact information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update contact information: ${G.message}`);throw G}}var v$={};B(v$,{setGeocodingDriver:()=>VZ,nominatimDriver:()=>D$,geocodingDriver:()=>mG,geocode:()=>AZ,formatQuery:()=>R0,checkCoverage:()=>OZ,PRECISION_RANK:()=>l0});var K0=(J)=>J*Math.PI/180;function r(J,$){let G=K0($.latitude-J.latitude),X=K0($.longitude-J.longitude),Z=K0(J.latitude),Y=K0($.latitude),L=Math.sin(G/2)**2+Math.sin(X/2)**2*Math.cos(Z)*Math.cos(Y);return 12742017.6*Math.asin(Math.sqrt(L))}function h$(J,$){let G=K0(J.latitude),X=K0($.latitude),Z=K0($.longitude-J.longitude),Y=Math.sin(Z)*Math.cos(X),L=Math.cos(G)*Math.sin(X)-Math.sin(G)*Math.cos(X)*Math.cos(Z);return(Math.atan2(Y,L)*180/Math.PI+360)%360}function g$(J,$,G={}){let X=G.detourFactor??1.35,Z=G.minimumSeconds??30;if(!Number.isFinite($)||$<=0.5)return null;let Y=J*X/$;return Math.max(Z,Math.round(Y))}function gG(J,$,G){return r(J,$)<=G}function p0(J){return typeof J?.latitude==="number"&&typeof J?.longitude==="number"&&Number.isFinite(J.latitude)&&Number.isFinite(J.longitude)}var l0={unknown:0,locality:1,postal:2,street:3,rooftop:4};function R0(J){return[J.street,J.city,J.region,J.postalCode,J.country].map(($)=>String($??"").trim()).filter(Boolean).join(", ")}var xZ="https://nominatim.openstreetmap.org/search",DG=1000,vG=0,yG=Promise.resolve();async function zZ(J){let $=yG.then(async()=>{let G=Date.now()-vG;if(G<DG)await Bun.sleep(DG-G);return vG=Date.now(),J()});return yG=$.then(()=>{return},()=>{return}),$}function BZ(J){let $=J.address??{},G=String(J.addresstype??""),X=String(J.type??""),Z=String(J.category??J.class??"");if($.house_number||X==="house"||X==="building"||G==="building")return"rooftop";if($.road||Z==="highway"||G==="road")return"street";if(G==="postcode"||$.postcode&&!$.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(G))return"locality";return"unknown"}function D$(J={}){let $=J.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,G=J.endpoint??xZ;return{name:"nominatim",async geocode(X){let Z=R0(X);if(!Z)return null;let Y=new URL(G);if(Y.searchParams.set("q",Z),Y.searchParams.set("format","jsonv2"),Y.searchParams.set("limit","1"),Y.searchParams.set("addressdetails","1"),X.country)Y.searchParams.set("countrycodes",X.country.toLowerCase());let L=await zZ(()=>fetch(Y,{headers:{"user-agent":$,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!L.ok)throw Error(`Nominatim responded ${L.status}`);let W=(await L.json())?.[0];if(!W)return null;let F=Number(W.lat),N=Number(W.lon);if(!Number.isFinite(F)||!Number.isFinite(N))return null;let H=BZ(W);return{latitude:F,longitude:N,formatted:String(W.display_name??Z),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[H],precision:H,provider:"nominatim"}}}}var bG=null;function VZ(J){bG=J}function mG(){return bG??D$()}async function AZ(J,$={}){let G=$.driver??mG(),X=$.minimumPrecision??"street",Z=`geocode:${G.name}:${R0(J).toLowerCase()}`,Y=await _Z(Z);if(Y!==void 0)return Y;let L=await G.geocode(J),K=L&&l0[L.precision]>=l0[X]?L:null;return await RZ(Z,K,K?$.cacheSeconds??2592000:600),K}function OZ(J,$,G){if($.length===0)return null;let X=$[0],Z=r(J,X);for(let Y of $.slice(1)){let L=r(J,Y);if(L<Z)Z=L,X=Y}return{covered:Z<=G,distanceMeters:Math.round(Z),nearest:X}}async function _Z(J){try{let G=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!G)return;let X=await G.get(J);if(X===null||X===void 0)return;return X==="null"?null:JSON.parse(String(X))}catch{return}}async function RZ(J,$,G){try{let Z=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!Z)return;await Z.set(J,$===null?"null":JSON.stringify($),G)}catch{}}var m$={};B(m$,{validateLicenseKeyWrite:()=>W0,updateStatus:()=>$X,updateExpiration:()=>JX,update:()=>tG,store:()=>rG,softDelete:()=>lG,fetchById:()=>iG,fetchAll:()=>oG,destroy:()=>pG,bulkStore:()=>eG,bulkSoftDelete:()=>uG,bulkDestroy:()=>cG,LicenseKeyInputError:()=>E});import{db as y$}from"@stacksjs/database";async function pG(J){try{let $=await y$.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function lG(J){try{let $=await y$.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function cG(J){if(!J.length)return 0;try{let $=await y$.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function uG(J){if(!J.length)return 0;try{let $=await y$.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as nG}from"@stacksjs/database";async function iG(J){return await nG.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst()}async function oG(){return await nG.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:aG}=globalThis.Bun;import{db as X1}from"@stacksjs/database";import{db as J1}from"@stacksjs/database";var sG=["Standard License","Premium License","Enterprise License"],dG=["active","inactive","unassigned"];class E extends TypeError{constructor(J){super(J);this.name="LicenseKeyInputError"}}function c0(J,$,G){return J[G]!==void 0?J[G]:$?.[G]}function G1(J,$,G,X){let Z=c0(J,$,G);if(Z===void 0||Z===null||Z==="")return null;let Y=Number(Z);if(!Number.isSafeInteger(Y)||Y<1)throw new E(`${X} must be a positive integer or null.`);return Y}function UZ(J){if(typeof J==="number")return J>2147483647?Math.floor(J/1000):J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return J.length===13?Math.floor(Number(J)/1000):Number(J);if(typeof J==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(J)?`${J.replace(" ","T")}Z`:J;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function W0(J,$){let G=String(c0(J,$,"key")||"").trim().toUpperCase(),X=String(c0(J,$,"template")||""),Z=String(c0(J,$,"status")||""),Y=UZ(c0(J,$,"expiry_date")),L=G1(J,$,"customer_id","Customer"),K=G1(J,$,"product_id","Product"),W=G1(J,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new E("License key must use five groups of four uppercase letters or numbers.");if(!sG.includes(X))throw new E(`Template must be one of: ${sG.join(", ")}.`);if(!dG.includes(Z))throw new E(`Status must be one of: ${dG.join(", ")}.`);if(!Number.isSafeInteger(Y)||Y<0||Y>2147483647)throw new E("Expiry date must be a Unix timestamp between 1970 and 2038.");let[F,N,H]=await Promise.all([L?J1.selectFrom("customers").where("id","=",L).select("id").executeTakeFirst():null,K?J1.selectFrom("products").where("id","=",K).select("id").executeTakeFirst():null,W?J1.selectFrom("orders").where("id","=",W).select(["id","customer_id"]).executeTakeFirst():null]);if(L&&!F)throw new E(`Customer ${L} was not found.`);if(K&&!N)throw new E(`Product ${K} was not found.`);if(W&&!H)throw new E(`Order ${W} was not found.`);if(L&&H?.customer_id&&Number(H.customer_id)!==L)throw new E(`Order ${W} belongs to Customer ${H.customer_id}, not Customer ${L}.`);return{...J,key:G,template:X,expiry_date:Y,status:Z,customer_id:L,product_id:K,order_id:W}}async function rG(J){try{let $=aG(),G=b0(J),X={...await W0(G),uuid:$};await X1.insertInto("license_keys").values(X).executeTakeFirst();let Z=await X1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created license key");return Z}catch($){if($ instanceof E)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function eG(J){if(!J.length)return 0;try{let $=await Promise.all(J.map(async(X)=>({...await W0(b0(X)),uuid:aG()}))),G=await X1.insertInto("license_keys").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof E)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as b$}from"@stacksjs/database";import{formatDate as Z1}from"@stacksjs/orm";async function tG(J,$){try{if(!J)throw Error("License key ID is required for update");let G=await b$.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=b0($),Z=await W0(X,G),Y=await b$.updateTable("license_keys").set({...Z,updated_at:Z1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Y)return;return Y}catch(G){if(G instanceof E)throw G;if(G instanceof Error){if(G.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${G.message}`)}throw G}}async function $X(J,$){try{let G=await b$.updateTable("license_keys").set({status:$,updated_at:Z1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update license key status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update license key status: ${G.message}`);throw G}}async function JX(J,$){try{let G={updated_at:Z1(new Date)};if($!==void 0)G.expiry_date=$;let X=await b$.updateTable("license_keys").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update expiration information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update expiration information: ${G.message}`);throw G}}var u$={};B(u$,{updateStatus:()=>MX,updatePricing:()=>xX,update:()=>HX,store:()=>WX,softDelete:()=>XX,getActiveShippingMethods:()=>NX,formatShippingOptions:()=>QX,fetchById:()=>c$,fetchAll:()=>LX,destroy:()=>GX,bulkStore:()=>FX,bulkSoftDelete:()=>YX,bulkDestroy:()=>ZX});import{db as p$}from"@stacksjs/database";async function GX(J){try{let $=await p$.deleteFrom("shipping_methods").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function XX(J){try{let $=await p$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function ZX(J){if(!J.length)return 0;try{let $=await p$.deleteFrom("shipping_methods").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function YX(J){if(!J.length)return 0;try{let $=await p$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as l$}from"@stacksjs/database";async function c$(J){let $=await l$.selectFrom("shipping_methods").where("id","=",J).selectAll().executeTakeFirst();if($){let G=await l$.selectFrom("shipping_zones").where("shipping_method_id","=",J).selectAll().execute();return{...$,shippingZones:G}}return}async function LX(){let J=await l$.selectFrom("shipping_methods").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((Y)=>Y.id))],Z=(await l$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((Y,L)=>{let K=L.shipping_method_id;if(K!==null&&K!==void 0){if(!Y[K])Y[K]=[];Y[K].push(L)}return Y},{});return J.map((Y)=>({...Y,shipping_zones:Z[Y.id]||[]}))}var{randomUUIDv7:KX}=globalThis.Bun;import{db as u0}from"@stacksjs/database";async function WX(J){try{let $=KX(),G={...D0(J),uuid:$};await u0.insertInto("shipping_methods").values(G).executeTakeFirst();let X=await u0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping method");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function FX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...D0(X),uuid:KX()})),G=await u0.insertInto("shipping_methods").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function QX(){try{return u0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping options: ${J.message}`);throw J}}async function NX(){try{return await u0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping methods: ${J.message}`);throw J}}import{db as Y1}from"@stacksjs/database";import{formatDate as L1}from"@stacksjs/orm";async function HX(J,$){try{if(!J)throw Error("Shipping method ID is required for update");let G=await Y1.updateTable("shipping_methods").set({...D0($),updated_at:L1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method: ${G.message}`);throw G}}async function MX(J,$){try{let G=await Y1.updateTable("shipping_methods").set({status:$,updated_at:L1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping method status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method status: ${G.message}`);throw G}}async function xX(J,$,G){try{let X={updated_at:L1(new Date)};if($!==void 0)X.base_rate=$;if(G!==void 0)X.free_shipping=G;let Z=await Y1.updateTable("shipping_methods").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update pricing information");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update pricing information: ${X.message}`);throw X}}var d$={};B(d$,{validateZoneMatchesAddress:()=>SX,validateShippingRateWrite:()=>F0,updateByZone:()=>DX,updateByMethod:()=>vX,update:()=>hX,store:()=>CX,resolveZoneForAddress:()=>i$,getShippingRatesByMethod:()=>EX,getRatesByZone:()=>UX,getRateByWeightAndZone:()=>K1,getRateByWeightAndAddress:()=>PX,formatShippingRateOptions:()=>TX,fetchById:()=>_X,fetchAll:()=>RX,destroyByZone:()=>VX,destroyByMethod:()=>AX,destroy:()=>zX,bulkUpdate:()=>gX,bulkStore:()=>IX,bulkDestroy:()=>BX,ShippingRateInputError:()=>k});import{db as n$}from"@stacksjs/database";async function zX(J){try{let $=await n$.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function BX(J){if(!J.length)return 0;try{let $=await n$.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function VX(J){try{let $=await n$.deleteFrom("shipping_rates").where("shipping_zone_id","=",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function AX(J){try{let $=await n$.deleteFrom("shipping_rates").where("shipping_method_id","=",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as v}from"@stacksjs/database";async function _X(J){let $=await v.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,X=null;if($.shipping_zone_id)G=await v.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)X=await v.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:G,shipping_method:X}}return}async function RX(){let J=await v.selectFrom("shipping_rates").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((K)=>K.shipping_zone_id).filter((K)=>K!==null&&K!==void 0))],G=[...new Set(J.map((K)=>K.shipping_method_id).filter((K)=>K!==null&&K!==void 0))],[X,Z]=await Promise.all([$.length?v.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],G.length?v.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),Y=X.reduce((K,W)=>{return K[W.id]=W,K},{}),L=Z.reduce((K,W)=>{return K[W.id]=W,K},{});return J.map((K)=>({...K,shipping_zone:K.shipping_zone_id?Y[K.shipping_zone_id]:[],shipping_method:K.shipping_method_id?L[K.shipping_method_id]:[]}))}async function UX(J){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function K1(J,$){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function i$(J){if(!J?.countryCode)return null;try{let $=await v.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let G=null;for(let X of $){let Z=1;if(J.region&&X.regions&&OX(X.regions,J.region))Z=2;if(J.postalCode&&X.postal_codes&&OX(X.postal_codes,J.postalCode))Z=3;if(!G||Z>G.score)G={id:X.id,score:Z}}return G?.id??null}catch{return null}}async function PX(J,$){let G=await i$($);if(G==null)return;return K1(J,G)}async function SX(J,$){return await i$($)===J}function OX(J,$){if(!J||!$)return!1;let G=$.trim().toUpperCase();for(let X of J.split(/[,|;]/))if(X.trim().toUpperCase()===G)return!0;return!1}async function TX(){try{return(await v.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function EX(J){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:kX}=globalThis.Bun;import{db as W1}from"@stacksjs/database";import{db as n0}from"@stacksjs/database";async function qX(){return await n0.selectFrom("shipping_zones").selectAll().execute()}async function o$(J){return await n0.selectFrom("shipping_zones").where("id","=",J).selectAll().executeTakeFirst()}function jX(){try{return n0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping zone options: ${J.message}`);throw J}}async function wX(){try{return await n0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping zones: ${J.message}`);throw J}}async function fX(J){try{return await n0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class k extends TypeError{constructor(J){super(J);this.name="ShippingRateInputError"}}function i0(J,$,G){return Number(J[G]??$?.[G])}async function F0(J,$){let G=i0(J,$,"shipping_method_id"),X=i0(J,$,"shipping_zone_id"),Z=i0(J,$,"weight_from"),Y=i0(J,$,"weight_to"),L=i0(J,$,"rate");if(!Number.isSafeInteger(G)||G<1)throw new k("Shipping method must be a positive integer.");if(!Number.isSafeInteger(X)||X<1)throw new k("Shipping zone must be a positive integer.");if(!Number.isFinite(Z)||Z<0)throw new k("Weight from must be a non-negative number.");if(!Number.isFinite(Y)||Y<Z)throw new k("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(L)||L<0)throw new k("Rate must be a non-negative integer in minor currency units.");let[K,W]=await Promise.all([c$(G),o$(X)]);if(!K)throw new k(`Shipping method ${G} was not found.`);if(!W)throw new k(`Shipping zone ${X} was not found.`);if(Number(W.shipping_method_id)!==G)throw new k(`Shipping zone ${X} is not assigned to shipping method ${G}.`)}async function CX(J){try{let $=i(J),G=Number($.shipping_method_id),X=Number($.shipping_zone_id);await F0($);let Z=kX(),Y={...$,shipping_method_id:G,shipping_zone_id:X,uuid:Z};await W1.insertInto("shipping_rates").values(Y).executeTakeFirst();let L=await W1.selectFrom("shipping_rates").where("uuid","=",Z).selectAll().executeTakeFirst();if(!L)throw Error("Failed to resolve created shipping rate");return L}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function IX(J){if(!J.length)return 0;try{for(let X of J){let Z=i(X);await F0(Z)}let $=J.map((X)=>({...i(X),uuid:kX()})),G=await W1.insertInto("shipping_rates").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as o0}from"@stacksjs/database";import{formatDate as s$}from"@stacksjs/orm";async function hX(J,$){try{if(!J)throw Error("Shipping rate ID is required for update");let G=await o0.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let X=i($);await F0(X,G);let Z=await o0.updateTable("shipping_rates").set({...X,updated_at:s$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z}catch(G){if(G instanceof k)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function gX(J){if(!J.length)return 0;try{let $=0;for(let{id:G,data:X}of J){let Z=await o0.updateTable("shipping_rates").set({...i(X),updated_at:s$(new Date)}).where("id","=",G).executeTakeFirst();if(Q(Z)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function DX(J,$){try{let G=await o0.updateTable("shipping_rates").set({...i($),updated_at:s$(new Date)}).where("shipping_zone_id","=",J).executeTakeFirst();return Q(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${G.message}`);throw G}}async function vX(J,$){try{let G=await o0.updateTable("shipping_rates").set({...i($),updated_at:s$(new Date)}).where("shipping_method_id","=",J).executeTakeFirst();return Q(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var X4={};B(X4,{startStop:()=>mX,startRoute:()=>cX,routeTrackingChannel:()=>F1,recordDriverPing:()=>yX,orderTrackingChannel:()=>e,isWithin:()=>gG,hasCoordinates:()=>p0,failStop:()=>lX,estimateSecondsRemaining:()=>g$,emitDeliveryStarted:()=>e$,emitDeliveryPosition:()=>a$,emitDeliveryNearby:()=>t$,emitDeliveryFailed:()=>G4,emitDeliveryCompleted:()=>J4,emitDeliveryAssigned:()=>r$,emitDeliveryArrived:()=>$4,distanceInMeters:()=>r,completeStop:()=>pX,broadcastToChannel:()=>o,bearingInDegrees:()=>h$,assignStop:()=>bX,NEARBY_RADIUS_METERS:()=>Q1,ARRIVAL_RADIUS_METERS:()=>N1});function e(J){return`order.${J}`}function F1(J){return`delivery-route.${J}`}async function U0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let X=G.dispatch;if(typeof X!=="function")return;X(J,$)}catch{}}async function o(J,$,G){try{let X=await import("@stacksjs/realtime").catch(()=>null);if(!X)return;let Z=X.channel;if(typeof Z!=="function")return;await Z(J).broadcast($,G,"private")}catch{}}async function a$(J,$,G){await Promise.all([...J.map((X)=>o(e(X),"delivery:position",G)),$==null?Promise.resolve():o(F1($),"delivery:position",G)])}async function r$(J){if(await U0("delivery:assigned",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:assigned",{stop:J})}async function e$(J){if(await U0("delivery:started",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:started",{stop:J})}async function t$(J,$,G){if(await U0("delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G}),J.order_id!=null)await o(e(J.order_id),"delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G})}async function $4(J){if(await U0("delivery:arrived",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:arrived",{stop:J})}async function J4(J){if(await U0("delivery:completed",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:completed",{stop:J})}async function G4(J,$){await U0("delivery:failed",{stop:J,reason:$})}var{randomUUIDv7:PZ}=globalThis.Bun;import{db as y}from"@stacksjs/database";var Q1=400,N1=60,SZ=250;async function yX(J){let $=J.recordedAt??new Date().toISOString(),G=typeof J.accuracy!=="number"||J.accuracy<=SZ,X=await y.selectFrom("drivers").where("id","=",J.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!X)throw Error(`Unknown driver: ${J.driverId}`);let Z=p0(X)?{latitude:X.latitude,longitude:X.longitude}:null,Y=typeof J.heading==="number"?J.heading:Z?h$(Z,J):null,L=await TZ(J.driverId),K=L?await EZ(L.id):null,W=null,F=null,N=!1,H=!1,M=K&&p0({latitude:K.latitude??void 0,longitude:K.longitude??void 0})?{latitude:K.latitude,longitude:K.longitude}:null;if(G&&K&&M)W=Math.round(r(J,M)),F=g$(W,J.speed??0),H=W<=N1&&K.arrived_at==null,N=!H&&W<=Q1&&K.status==="en_route"&&K.notified_nearby_at==null;let O=await qZ({driverId:J.driverId,routeId:L?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$});if(G)await y.updateTable("drivers").set({latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??0,last_ping_at:$}).where("id","=",J.driverId).execute();if(K&&(W!=null||F!=null))await y.updateTable("delivery_stops").set({eta_at:F==null?K.eta_at:new Date(Date.now()+F*1000).toISOString()}).where("id","=",K.id).execute();if(G)await a$(K?.order_id==null?[]:[K.order_id],L?.id??null,{driverId:J.driverId,routeId:L?.id??null,latitude:J.latitude,longitude:J.longitude,heading:Y,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$,distanceToStopMeters:W,etaSeconds:F});if(N&&K)await y.updateTable("delivery_stops").set({notified_nearby_at:$}).where("id","=",K.id).execute(),await t$(K,W,F);if(H&&K)await y.updateTable("delivery_stops").set({status:"arrived",arrived_at:$}).where("id","=",K.id).execute(),await $4({...K,status:"arrived",arrived_at:$});return{pingId:O,routeId:L?.id??null,stopId:K?.id??null,distanceToStopMeters:W,etaSeconds:F,crossedNearby:N,crossedArrival:H}}async function TZ(J){return await y.selectFrom("delivery_routes").where("driver_id","=",J).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function EZ(J){let $=await y.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return $.find((G)=>G.status==="en_route")??$.find((G)=>G.status==="arrived")??$[0]??null}async function qZ(J){let $=PZ();return await y.insertInto("driver_pings").values({uuid:$,driver_id:J.driverId,delivery_route_id:J.routeId,latitude:J.latitude,longitude:J.longitude,heading:J.heading,speed:J.speed??0,accuracy:J.accuracy,recorded_at:J.recordedAt}).executeTakeFirst(),(await y.selectFrom("driver_pings").where("uuid","=",$).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:jZ}=globalThis.Bun;import{db as q}from"@stacksjs/database";async function bX(J){let $=jZ(),G=J.sequence??await fZ(J.deliveryRouteId);await q.insertInto("delivery_stops").values({uuid:$,delivery_route_id:J.deliveryRouteId,order_id:J.orderId??null,sequence:G,status:"pending",address:J.address,latitude:J.latitude??null,longitude:J.longitude??null,recipient_name:J.recipientName??null,recipient_phone:J.recipientPhone??null,eta_at:J.etaAt??null}).executeTakeFirst();let X=await CZ($);if(X)await r$(X);return X??{}}async function mX(J){await q.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",J).execute();let $=await M1(J);if(!$)return null;if($.order_id!=null)await H1($.order_id,"OUT_FOR_DELIVERY");return await e$($),$}async function pX(J,$){let G=new Date().toISOString();await q.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await kZ(J)?{}:{arrived_at:G},...$?{notes:$}:{}}).where("id","=",J).execute();let X=await M1(J);if(!X)return null;if(X.order_id!=null)await H1(X.order_id,"DELIVERED");return await J4(X),await uX(X.delivery_route_id),X}async function lX(J,$){await q.updateTable("delivery_stops").set({status:"failed",notes:$}).where("id","=",J).execute();let G=await M1(J);if(!G)return null;if(G.order_id!=null)await H1(G.order_id,"SHIPPED");return await G4(G,$),await uX(G.delivery_route_id),G}async function cX(J){await q.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",J).execute()}async function uX(J){if(J==null)return;if(await q.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let G=await q.selectFrom("delivery_routes").where("id","=",J).select(["driver_id"]).executeTakeFirst();if(await q.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",J).execute(),G?.driver_id!=null)await q.updateTable("drivers").set({status:"active"}).where("id","=",G.driver_id).execute()}async function H1(J,$){let G=await q.selectFrom("orders").where("id","=",J).select(["id","status"]).executeTakeFirst();if(!G)return;let X=await Promise.resolve().then(() => (x0(),VJ)),{canTransition:Z,emitForStatus:Y}=X,L=wZ(G.status,$,Z);if(L.length===0){let{log:K}=await import("@stacksjs/logging").catch(()=>({log:null}));K?.warn(`[delivery] refused to move order ${J} from ${G.status} to ${$}: no legal transition`);return}for(let K of L)await q.updateTable("orders").set({status:K}).where("id","=",J).execute(),await Y(K,{...G,status:K})}function wZ(J,$,G){if(J===$)return[];if(G(J,$))return[$];for(let X of["PROCESSING","SHIPPED"]){if(X===J||X===$)continue;if(G(J,X)&&G(X,$))return[X,$]}return[]}async function fZ(J){return(await q.selectFrom("delivery_stops").where("delivery_route_id","=",J).select(["sequence"]).execute()).reduce((G,X)=>Math.max(G,X.sequence??0),0)+1}async function kZ(J){return(await q.selectFrom("delivery_stops").where("id","=",J).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function M1(J){return await q.selectFrom("delivery_stops").where("id","=",J).selectAll().executeTakeFirst()??null}async function CZ(J){return await q.selectFrom("delivery_stops").where("uuid","=",J).selectAll().executeTakeFirst()??null}var K4={};B(K4,{updateStatus:()=>tX,updateRegionsAndPostalCodes:()=>J9,updateCountries:()=>$9,update:()=>eX,store:()=>aX,softDelete:()=>iX,getZonesByCountry:()=>fX,getActiveShippingZones:()=>wX,formatZoneOptions:()=>jX,fetchById:()=>o$,fetchAll:()=>qX,destroy:()=>nX,bulkStore:()=>rX,bulkSoftDelete:()=>sX,bulkDestroy:()=>oX});import{db as Z4}from"@stacksjs/database";async function nX(J){try{let $=await Z4.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function iX(J){try{let $=await Z4.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function oX(J){if(!J.length)return 0;try{let $=await Z4.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function sX(J){if(!J.length)return 0;try{let $=await Z4.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:dX}=globalThis.Bun;import{db as x1}from"@stacksjs/database";async function aX(J){try{let $=dX(),G={...v0(J),uuid:$};await x1.insertInto("shipping_zones").values(G).executeTakeFirst();let X=await x1.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created shipping zone");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function rX(J){if(!J.length)return 0;try{let $=J.map((X)=>({...v0(X),uuid:dX()})),G=await x1.insertInto("shipping_zones").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as Y4}from"@stacksjs/database";import{formatDate as L4}from"@stacksjs/orm";async function eX(J,$){try{if(!J)throw Error("Shipping zone ID is required for update");let G=await Y4.updateTable("shipping_zones").set({...v0($),updated_at:L4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone: ${G.message}`);throw G}}async function tX(J,$){try{let G=await Y4.updateTable("shipping_zones").set({status:$,updated_at:L4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone status: ${G.message}`);throw G}}async function $9(J,$){try{let G=await Y4.updateTable("shipping_zones").set({countries:$,updated_at:L4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone countries");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${G.message}`);throw G}}async function J9(J,$,G){try{let X={updated_at:L4(new Date)};if($!==void 0)X.regions=$;if(G!==void 0)X.postal_codes=G;let Z=await Y4.updateTable("shipping_zones").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update regions and postal codes");return Z}catch(X){if(X instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${X.message}`);throw X}}var IZ={digital:k$,drivers:I$,geocoding:v$,licenses:m$,methods:u$,rates:d$,routes:w$,tracking:X4,zones:K4},hZ=IZ;var A1={};B(A1,{updateStatus:()=>x9,updateRate:()=>z9,updateDefaultStatus:()=>B9,update:()=>M9,taxFor:()=>G9,store:()=>N9,fetchById:()=>K9,fetchAll:()=>W9,destroy:()=>Z9,bulkStore:()=>H9,bulkDestroy:()=>Y9,breakdownFor:()=>V1,activeTaxRates:()=>B1});import{db as gZ}from"@stacksjs/database";function DZ(J){let $=Number(J);return Number.isFinite($)?$/100:0}async function B1(J={}){let $=gZ.selectFrom("tax_rates").where("status","=","active").selectAll();if(J.country)$=$.where("country","=",J.country);let G=await $.execute();if(!J.codes?.length)return G;let X=new Set(J.codes);return G.filter((Z)=>X.has(String(Z.code??"")))}function V1(J,$,G={}){let X=Math.max(0,Math.round(J)),Z=[],Y=0,L=0;for(let K of $){let W=DZ(K.rate),F=Math.round(X*W),N=Boolean(G.exempt&&K.exemptible);if(N)L+=F;else Y+=F;Z.push({id:Number(K.id),code:String(K.code??""),name:String(K.name??""),rate:W,amount:N?0:F,exempted:N})}return{taxable:X,components:Z,tax:Y,exempted:L}}async function G9(J,$={}){return V1(J,await B1($),$)}import{db as X9}from"@stacksjs/database";async function Z9(J){try{let $=await X9.deleteFrom("tax_rates").where("id","=",J).executeTakeFirst();return Q($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function Y9(J){if(!J.length)return 0;try{let $=await X9.deleteFrom("tax_rates").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as L9}from"@stacksjs/database";async function K9(J){return await L9.selectFrom("tax_rates").where("id","=",J).selectAll().executeTakeFirst()}async function W9(){return await L9.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:F9}=globalThis.Bun;import{db as Q9}from"@stacksjs/database";async function N9(J){try{return await Q9.transaction(async($)=>{let G={...J,uuid:F9()};if(G.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let X=await $.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function H9(J){if(!J.length)return 0;try{return await Q9.transaction(async($)=>{let G=0;for(let X of J){let Z={...X,uuid:F9()};if(Z.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(Z).executeTakeFirst())G++}return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as W4}from"@stacksjs/database";import{formatDate as F4}from"@stacksjs/orm";async function M9(J,$){try{if(!J)throw Error("Tax rate ID is required for update");return await W4.transaction(async(G)=>{let X=await G.selectFrom("tax_rates").select("is_default").where("id","=",J).executeTakeFirst();if(!X)return;let Z=$.is_default??Boolean(X.is_default),Y=F4(new Date);if(Z)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Y}).where("id","!=",J).execute();let L=await G.updateTable("tax_rates").set({...$,updated_at:Y}).where("id","=",J).returningAll().executeTakeFirst();if(!L)return;return L})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function x9(J,$){try{let G=await W4.updateTable("tax_rates").set({status:$,updated_at:F4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update tax rate status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate status: ${G.message}`);throw G}}async function z9(J,$){try{let G=await W4.updateTable("tax_rates").set({rate:$,updated_at:F4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update rate information");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update rate information: ${G.message}`);throw G}}async function B9(J,$){try{return await W4.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",J).executeTakeFirst())return!1;let Z=F4(new Date);if($)await G.updateTable("tax_rates").set({is_default:!1,updated_at:Z}).where("id","!=",J).execute();return await G.updateTable("tax_rates").set({is_default:$,updated_at:Z}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var S1={};B(S1,{restaurant:()=>S0,products:()=>N4,default:()=>iZ});var N4={};B(N4,{updateStatus:()=>D9,updatePartySize:()=>v9,update:()=>Q4,store:()=>h9,fetchWaiting:()=>q9,fetchPurchasedBetweenDates:()=>T9,fetchNotifiedBetweenDates:()=>S9,fetchCountByStatus:()=>j9,fetchCountBySource:()=>_9,fetchCountByQuantity:()=>U9,fetchCountByDateGrouped:()=>k9,fetchCountByDate:()=>R9,fetchCountByAllQuantities:()=>P9,fetchCountBetweenDates:()=>f9,fetchConversionRates:()=>w9,fetchCancelledBetweenDates:()=>E9,fetchById:()=>s0,fetchAll:()=>O9,destroy:()=>V9,bulkStore:()=>g9,bulkDestroy:()=>A9});import{db as O1}from"@stacksjs/database";async function V9(J){try{let $=await O1.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await O1.deleteFrom("waitlist_products").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function A9(J){if(!J.length)return 0;try{let $=await O1.deleteFrom("waitlist_products").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as T}from"@stacksjs/orm";async function s0(J){return await A.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function O9(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function _9(J,$){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(J&&$){let Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{source:Y,count:L})=>{return Z[Y]=L,Z},{})}async function R9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=T($),Z=T(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function U9(J){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",J).executeTakeFirst())?.count??0}async function P9(J,$){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(J&&$){let Z=T(J),Y=T($);G=G.where("created_at",">=",Z).where("created_at","<=",Y)}return(await G.execute()).reduce((Z,{quantity:Y,count:L})=>{return Z[Y]=L,Z},{})}async function S9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",X).whereNotNull("notified_at").execute()}async function T9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",X).whereNotNull("purchased_at").execute()}async function E9(J,$){let G=T(J),X=T($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",X).whereNotNull("cancelled_at").execute()}async function q9(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function j9(J,$,G){let X=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",J);if($&&G){let Y=T($),L=T(G);X=X.where("created_at",">=",Y).where("created_at","<=",L)}return(await X.executeTakeFirst())?.count??0}async function w9(J,$){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(J&&$){let W=T(J),F=T($);G=G.where("created_at",">=",W).where("created_at","<=",F)}let X=await G.execute(),Z=X.reduce((W,{count:F})=>W+F,0),Y=X.find((W)=>W.status==="purchased")?.count??0,L=Z>0?Y/Z*100:0,K=X.reduce((W,{status:F,count:N})=>{return W[F]={count:N,percentage:Z>0?N/Z*100:0},W},{});return{totalConversionRate:L,statusBreakdown:K}}async function f9(J,$){let G=T(J),X=T($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function k9(J,$){let G=A.selectFrom("waitlist_products").select(["created_at"]);if(J&&$){let Y=T(J),L=T($);G=G.where("created_at",">=",Y).where("created_at","<=",L)}let Z=(await G.execute()).reduce((Y,{created_at:L})=>{let K=(L||"").split("T")[0]||"unknown";return Y[K]=(Y[K]||0)+1,Y},{});return Object.entries(Z).map(([Y,L])=>({date:Y,count:L})).sort((Y,L)=>Y.date.localeCompare(L.date))}var{randomUUIDv7:I9}=globalThis.Bun;import{db as _1}from"@stacksjs/database";import{formatDate as C9}from"@stacksjs/orm";var vZ={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function yZ(J){return typeof J==="number"||J instanceof Date?C9(J):J}function d0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,Z])=>Z!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let Z of["notified_at","purchased_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=yZ(G[Z]);let X=vZ[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=C9(new Date);return G}async function h9(J){try{let $=I9(),G={...d0(J),uuid:$,status:J.status||"waiting"};await _1.insertInto("waitlist_products").values(G).executeTakeFirst();let X=await _1.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create waitlist product");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function g9(J){if(!J.length)return 0;try{let $=J.map((X)=>({...d0(X),status:X.status||"waiting",uuid:I9()})),G=await _1.insertInto("waitlist_products").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as bZ}from"@stacksjs/database";import{formatDate as mZ}from"@stacksjs/orm";async function Q4(J,$){try{if(!J)throw Error("Waitlist product ID is required for update");let G=await s0(J);if(!G)return;await bZ.updateTable("waitlist_products").set({...d0($,G),updated_at:mZ(new Date)}).where("id","=",J).execute();let X=await s0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update waitlist product: ${G.message}`);throw G}}async function D9(J,$){return await Q4(J,{status:$})}async function v9(J,$){return await Q4(J,{quantity:$})}var S0={};B(S0,{updateWaitTimes:()=>F3,updateStatus:()=>K3,updateQueuePosition:()=>Q3,updatePartySize:()=>W3,update:()=>P0,store:()=>Y3,fetchWaitingWithQuotedTimes:()=>a9,fetchWaitingWithPartySizes:()=>r9,fetchWaiting:()=>o9,fetchTimeSeriesStats:()=>X3,fetchTablesTurnedToday:()=>e9,fetchSeatingRate:()=>t9,fetchSeatedStats:()=>G3,fetchSeatedBetweenDates:()=>i9,fetchNoShowStats:()=>$3,fetchCurrentWaitTimes:()=>J3,fetchCountByTablePreference:()=>p9,fetchCountByPartySize:()=>c9,fetchCountByDate:()=>l9,fetchCountByAllPartySizes:()=>u9,fetchConversionRates:()=>s9,fetchById:()=>a0,fetchBetweenDates:()=>n9,fetchAverageWaitTimes:()=>d9,fetchAll:()=>m9,destroy:()=>y9,bulkStore:()=>L3,bulkDestroy:()=>b9});import{db as R1}from"@stacksjs/database";async function y9(J){try{let $=await R1.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await R1.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function b9(J){if(!J.length)return 0;try{let $=await R1.deleteFrom("waitlist_restaurants").where("id","in",J).executeTakeFirst();return Q($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as z}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function a0(J){return await z.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function m9(){return await z.selectFrom("waitlist_restaurants").selectAll().execute()}async function p9(){return(await z.selectFrom("waitlist_restaurants").select(["table_preference",z.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:G,count:X})=>{return $[G]=X,$},{})}async function l9(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),Z=g(G);return(await z.selectFrom("waitlist_restaurants").select(z.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",Z).executeTakeFirst())?.count??0}async function c9(J){return(await z.selectFrom("waitlist_restaurants").select(z.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function u9(){return(await z.selectFrom("waitlist_restaurants").select(["party_size",z.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:G,count:X})=>{return $[G]=X,$},{})}async function n9(J,$){let G=g(J),X=g($);return await z.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",X).execute()}async function i9(J,$){let G=g(J),X=g($);return await z.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",X).where("status","=","seated").execute()}async function o9(){return await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function s9(){let J=await z.selectFrom("waitlist_restaurants").select(["status",z.fn.count("id").as("count")]).groupBy("status").execute(),$=J.reduce((Y,{count:L})=>Y+L,0),G=J.find((Y)=>Y.status==="seated")?.count??0,X=$>0?Number(G)/$*100:0,Z=J.reduce((Y,{status:L,count:K})=>{return Y[L]={count:K,percentage:$>0?K/$*100:0},Y},{});return{totalConversionRate:X,statusBreakdown:Z}}async function d9(){let J=await z.selectFrom("waitlist_restaurants").select([z.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),z.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:J?.avg_quoted_wait_time??0,averageActualWaitTime:J?.avg_actual_wait_time??0}}async function a9(){let J=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((X,Z)=>X+(Z.quoted_wait_time??0),0),G=J.length>0?$/J.length:0;return{entries:J,totalQuotedWaitTime:$,averageQuotedWaitTime:G}}async function r9(){let J=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((Z,Y)=>Z+Y.party_size,0),G=J.length>0?$/J.length:0,X=J.reduce((Z,Y)=>{return Z[Y.party_size]=(Z[Y.party_size]||0)+1,Z},{});return{entries:J,totalPartySize:$,averagePartySize:G,partySizeBreakdown:X}}async function e9(){let J=new Date,$=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let X=g($),Z=g(G),Y=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",X).where("check_in_time","<=",Z).execute(),L=Y.length,K=Y.reduce((H,M)=>H+M.party_size,0),W=L>0?K/L:0,F=Y.reduce((H,M)=>{return H[M.table_preference]=(H[M.table_preference]||0)+1,H},{}),N=Y.reduce((H,M)=>{return H[M.party_size]=(H[M.party_size]||0)+1,H},{});return{totalTablesTurned:L,averagePartySize:W,totalCustomersSeated:K,breakdownByTablePreference:F,breakdownByPartySize:N}}async function t9(J,$){let G=g(J),X=g($),Z=await z.selectFrom("waitlist_restaurants").select(["status",z.fn.count("id").as("count")]).where("check_in_time",">=",G).where("check_in_time","<=",X).groupBy("status").execute(),Y=Z.reduce((F,{count:N})=>F+N,0),L=Z.find((F)=>F.status==="seated")?.count??0,K=Y>0?Number(L)/Y*100:0,W=Z.reduce((F,{status:N,count:H})=>{return F[N]={count:H,percentage:Y>0?H/Y*100:0},F},{});return{totalEntries:Y,seatedEntries:L,seatingRate:K,statusBreakdown:W}}async function $3(J,$){let G=g(J),X=g($),Z=z.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",X),Y=await z.selectFrom("waitlist_restaurants").select(z.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",X).executeTakeFirst(),L=await Z.execute(),K=L.length,W=Y?.count&&Y.count>0?K/Y.count*100:0,F=L.reduce((_,U)=>_+(U.quoted_wait_time??0),0),N=K>0?F/K:0,H=L.reduce((_,U)=>_+U.party_size,0),M=K>0?H/K:0,O=L.reduce((_,U)=>{return _[U.table_preference]=(_[U.table_preference]||0)+1,_},{}),R=L.reduce((_,U)=>{return _[U.party_size]=(_[U.party_size]||0)+1,_},{});return{totalNoShows:K,noShowRate:W,averageQuotedWaitTime:N,averagePartySize:M,breakdownByTablePreference:O,breakdownByPartySize:R}}async function J3(){let J=await z.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=J.reduce((Z,Y)=>Z+(Y.quoted_wait_time||0),0),G=J.reduce((Z,Y)=>Z+(Y.actual_wait_time||0),0),X=J.length;return{averageQuoted:X>0?$/X:0,averageActual:X>0?G/X:0}}async function G3(){let J=Date.now()-86400000,$=await z.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),G=Array.from({length:24},(X,Z)=>({hour:Z,count:$.filter((Y)=>{return Y.seated_at===Z}).length}));return{total:$.length,byHour:G}}async function X3(){return(await z.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,G)=>{let X=G.created_at;if(!$[X])$[X]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[X].total++,$[X][G.status]++,$},{})}var{randomUUIDv7:Z3}=globalThis.Bun;import{db as P1}from"@stacksjs/database";import{formatDate as U1}from"@stacksjs/orm";var pZ={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function lZ(J){if(typeof J==="number")return U1(J<=2147483647?J*1000:J);if(J instanceof Date)return U1(J);return J}function r0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,Z])=>Z!==void 0));for(let Z of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[Z]!==void 0)G[Z]=lZ(G[Z]);let X=pZ[G.status];if(X&&G[X]===void 0&&!$[X])G[X]=U1(new Date);return G}async function Y3(J){try{let $=Z3(),G={...r0(J),status:J.status||"waiting",uuid:$};await P1.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let X=await P1.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to create restaurant waitlist entry");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function L3(J){if(!J.length)return 0;try{let $=J.map((X)=>({...r0(X),status:X.status||"waiting",uuid:Z3()})),G=await P1.insertInto("waitlist_restaurants").values($).executeTakeFirst();return Q(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as cZ}from"@stacksjs/database";import{formatDate as uZ}from"@stacksjs/orm";async function P0(J,$){try{if(!J)throw Error("Restaurant waitlist entry ID is required for update");let G=await a0(J);if(!G)return;await cZ.updateTable("waitlist_restaurants").set({...r0($,G),updated_at:uZ(new Date)}).where("id","=",J).execute();let X=await a0(J);if(!X)return;return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${G.message}`);throw G}}async function K3(J,$){return await P0(J,{status:$})}async function W3(J,$){return await P0(J,{party_size:$})}async function F3(J,$,G){return await P0(J,{quoted_wait_time:$,...G===void 0?{}:{actual_wait_time:G}})}async function Q3(J,$){return await P0(J,{queue_position:$})}var nZ={products:N4,restaurant:S0},iZ=nZ;var oZ={coupons:H4,customers:M4,devices:A4,errors:R4,giftCards:P4,orders:C4,payments:I4,products:m4,receipts:i4,restaurant:S0,shippings:z1,tax:A1,waitlists:S1},k8=oZ;export{S1 as waitlists,A1 as tax,z1 as shippings,S0 as restaurant,i4 as receipts,m4 as products,I4 as payments,C4 as orders,P4 as giftCards,R4 as errors,A4 as devices,k8 as default,M4 as customers,H4 as coupons,oZ as commerce};
|