@stacksjs/commerce 0.70.296 → 0.70.298
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 oX=Object.defineProperty;var sX=(J)=>J;function dX(J,$){this[J]=sX.bind(null,$)}var z=(J,$)=>{for(var G in $)oX(J,G,{get:$[G],enumerable:!0,configurable:!0,set:dX.bind($,G)})};var aX=(J,$)=>()=>(J&&($=J(J=0)),$);var s0=import.meta.require;var KJ={};z(KJ,{emitOrderShipped:()=>W$,emitOrderRefunded:()=>Q0,emitOrderPaid:()=>d,emitOrderOutForDelivery:()=>LJ,emitOrderDelivered:()=>Z$,emitOrderCreated:()=>w0,emitOrderCancelled:()=>F0,emitForStatus:()=>q0,canTransition:()=>P0});function P0(J,$){if(J===$)return!0;return _9[J]?.includes($)??!1}async function G0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let N=G.dispatch;if(typeof N!=="function")return;N(J,$)}catch{}}async function w0(J){await G0("order:created",{order:J})}async function d(J,$){await G0("order:paid",{order:J,payment:$})}async function W$(J){await G0("order:shipped",{order:J})}async function LJ(J){await G0("order:out_for_delivery",{order:J})}async function Z$(J){await G0("order:delivered",{order:J})}async function F0(J,$){await G0("order:cancelled",{order:J,reason:$})}async function Q0(J,$){await G0("order:refunded",{order:J,refundAmount:$})}async function q0(J,$){switch(J){case"PROCESSING":return d($);case"SHIPPED":return W$($);case"OUT_FOR_DELIVERY":return LJ($);case"DELIVERED":return Z$($);case"CANCELLED":return F0($);case"REFUNDED":return Q0($);case"PENDING":default:}}var _9;var M0=aX(()=>{_9={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","OUT_FOR_DELIVERY","CANCELLED","REFUNDED"],SHIPPED:["OUT_FOR_DELIVERY","DELIVERED","REFUNDED"],OUT_FOR_DELIVERY:["DELIVERED","SHIPPED","CANCELLED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]}});var Y1={};z(Y1,{update:()=>m4,store:()=>v4,redeem:()=>p4,getActiveCouponsMoMChange:()=>h4,fetchTopRedeemedCoupons:()=>k4,fetchStats:()=>w4,fetchRedemptionTrend:()=>j4,fetchRedemptionStats:()=>E4,fetchCouponCountsByType:()=>f4,fetchCouponCounts:()=>q4,fetchConversionRate:()=>C4,fetchById:()=>$0,fetchByCode:()=>T4,fetchAll:()=>U4,fetchActive:()=>P4,deleteExpiredCoupons:()=>R4,deleteCoupons:()=>_4,deleteCoupon:()=>A4});import{db as d0}from"@stacksjs/database";import{formatDate as eX}from"@stacksjs/orm";function F(J){if(typeof J==="number")return Number.isFinite(J)?J:0;if(typeof J==="bigint")return Number(J);if(!J||typeof J!=="object")return 0;let $=J;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[G]!==void 0&&$[G]!==null)return F($[G]);if(Array.isArray(J))return J.reduce((G,N)=>G+F(N),0);return 0}async function A4(J){let $=await d0.deleteFrom("coupons").where("id","=",J).executeTakeFirst();return F($)>0}async function _4(J){if(!J.length)return 0;return(await d0.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function R4(){let J=eX(new Date),$=await d0.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return F($)}import{db as V}from"@stacksjs/database";import{extractDate as O4,formatDate as S4}from"@stacksjs/orm";import{camelCase as rX}from"@stacksjs/strings";function e0(J){let $=Object.fromEntries(Object.entries(J).map(([G,N])=>[rX(G),N]));if($.endDate)$.endDate=O4(new Date($.endDate));if($.startDate)$.startDate=O4(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function U4(){return(await V.selectFrom("coupons").selectAll().execute()).map(e0)}async function $0(J){let $=await V.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return e0($);return}async function T4(J){let $=await V.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return e0($);return}async function P4(){let J=S4(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map(e0)}async function w4(){let J=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).executeTakeFirst(),$=S4(new Date),G=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(V.fn.count("id").as("count")).executeTakeFirst(),N=await V.selectFrom("coupons").select(["discount_type",V.fn.count("id").as("count")]).groupBy("discount_type").execute(),X=await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),W=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",$).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(J?.count||0),active:Number(G?.count||0),by_type:N,most_used:X,upcoming:W}}async function q4(){let J=new Date,$=new Date(J);$.setDate(J.getDate()-7);let G=new Date(J);G.setMonth(J.getMonth()-1);let N=new Date(J);N.setFullYear(J.getFullYear()-1);let X=await a0(null,null,J),W=await a0($,null,J),Z=await a0(G,null,J),Y=await a0(N,null,J);return{week:W,month:Z,year:Y,all_time:X}}async function a0(J,$,G){let N=V.selectFrom("coupons");if(J)N=N.where("created_at",">=",J.toISOString());if($)N=N.where("created_at","<=",$.toISOString());let X=await N.select(V.fn.count("id").as("count")).executeTakeFirst(),W=V.selectFrom("coupons");if(J)W=W.where("created_at",">=",J.toISOString());if($)W=W.where("created_at","<=",$.toISOString());W=W.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let Z=await W.select(V.fn.count("id").as("count")).executeTakeFirst(),Y=Number(X?.count||0),L=Number(Z?.count||0),K=Y-L;return{total:Y,active:L,inactive:K}}async function f4(){let J=new Date,$=await V.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:N}of $){let X=await V.selectFrom("coupons").where("discount_type","=",N).select(V.fn.count("id").as("count")).executeTakeFirst(),W=await V.selectFrom("coupons").where("discount_type","=",N).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(V.fn.count("id").as("count")).executeTakeFirst(),Z=Number(X?.count||0),Y=Number(W?.count||0);G[N]={total:Z,active:Y,inactive:Z-Y}}return G}async function E4(){let J=await V.selectFrom("coupons").select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,G=new Date($);G.setDate($.getDate()-7);let N=new Date($);N.setMonth($.getMonth()-1);let X=new Date($);X.setFullYear($.getFullYear()-1);let W=await V.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),Z=await V.selectFrom("coupons").where("updated_at",">=",N.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await V.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(V.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await V.selectFrom("coupons").select(["discount_type",V.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),K={};return L.forEach((Q)=>{K[Q.discount_type]=Number(Q.total||0)}),{total:Number(J?.total||0),week:Number(W?.total||0),month:Number(Z?.total||0),year:Number(Y?.total||0),by_type:K}}async function k4(J=5){return await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(J).execute()}async function j4(J=30){let $=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-J);let N=await V.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",G.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),X={};return N.forEach((W)=>{let Z=W.updated_at?new Date(W.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!X[Z])X[Z]=0;X[Z]+=W?.usage_count||0}),Object.entries(X).map(([W,Z])=>({date:W,count:Z}))}async function C4(){let J=new Date,$=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(V.fn.count("id").as("count")).executeTakeFirst(),G=await V.selectFrom("coupons").where("usage_count",">",0).select(V.fn.count("id").as("count")).executeTakeFirst(),N=Number($?.count||0),X=Number(G?.count||0);return{rate:N>0?X/N*100:0,total_active:N,total_redeemed:X}}async function h4(){let J=new Date,$=new Date(J.getFullYear(),J.getMonth(),1),G=new Date(J.getFullYear(),J.getMonth()-1,1),N=new Date(J.getFullYear(),J.getMonth(),0),X=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),W=await V.selectFrom("coupons").select(V.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",G).executeTakeFirst(),Z=Number(X?.count||0),Y=Number(W?.count||0),L=Z-Y,K=Y!==0?L/Y*100:Z>0?100:0;return{current_month:Z,previous_month:Y,difference:L,percentage_change:K}}var{randomUUIDv7:tX}=globalThis.Bun;import{db as I4}from"@stacksjs/database";import{HttpError as g4}from"@stacksjs/error-handling";import{isUniqueViolation as $9}from"@stacksjs/orm";async function v4(J){try{let $=tX();return await I4.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await I4.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof g4)throw $;if($9($))throw new g4(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as D4}from"@stacksjs/database";import{HttpError as y4}from"@stacksjs/error-handling";import{formatDate as b4,isUniqueViolation as J9}from"@stacksjs/orm";async function m4(J,$){if(!await $0(J))return;try{return await D4.updateTable("coupons").set({...$,updated_at:b4(new Date)}).where("id","=",J).execute(),await $0(J)}catch(N){if(N instanceof y4)throw N;if(J9(N))throw new y4(409,"A coupon with this code already exists");if(N instanceof Error)throw Error(`Failed to update coupon: ${N.message}`);throw N}}async function p4(J){let $=b4(new Date),G=await D4.unsafe(`UPDATE coupons
|
|
2
|
+
var oX=Object.defineProperty;var sX=(J)=>J;function dX(J,$){this[J]=sX.bind(null,$)}var z=(J,$)=>{for(var G in $)oX(J,G,{get:$[G],enumerable:!0,configurable:!0,set:dX.bind($,G)})};var aX=(J,$)=>()=>(J&&($=J(J=0)),$);var S0=import.meta.require;var KJ={};z(KJ,{emitOrderShipped:()=>W$,emitOrderRefunded:()=>Q0,emitOrderPaid:()=>d,emitOrderOutForDelivery:()=>YJ,emitOrderDelivered:()=>Z$,emitOrderCreated:()=>T0,emitOrderCancelled:()=>F0,emitForStatus:()=>E0,canTransition:()=>q0});function q0(J,$){if(J===$)return!0;return _9[J]?.includes($)??!1}async function G0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let N=G.dispatch;if(typeof N!=="function")return;N(J,$)}catch{}}async function T0(J){await G0("order:created",{order:J})}async function d(J,$){await G0("order:paid",{order:J,payment:$})}async function W$(J){await G0("order:shipped",{order:J})}async function YJ(J){await G0("order:out_for_delivery",{order:J})}async function Z$(J){await G0("order:delivered",{order:J})}async function F0(J,$){await G0("order:cancelled",{order:J,reason:$})}async function Q0(J,$){await G0("order:refunded",{order:J,refundAmount:$})}async function E0(J,$){switch(J){case"PROCESSING":return d($);case"SHIPPED":return W$($);case"OUT_FOR_DELIVERY":return YJ($);case"DELIVERED":return Z$($);case"CANCELLED":return F0($);case"REFUNDED":return Q0($);case"PENDING":default:}}var _9;var M0=aX(()=>{_9={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","OUT_FOR_DELIVERY","CANCELLED","REFUNDED"],SHIPPED:["OUT_FOR_DELIVERY","DELIVERED","REFUNDED"],OUT_FOR_DELIVERY:["DELIVERED","SHIPPED","CANCELLED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]}});var L1={};z(L1,{update:()=>m4,store:()=>v4,redeem:()=>p4,getActiveCouponsMoMChange:()=>h4,fetchTopRedeemedCoupons:()=>k4,fetchStats:()=>q4,fetchRedemptionTrend:()=>j4,fetchRedemptionStats:()=>f4,fetchCouponCountsByType:()=>E4,fetchCouponCounts:()=>T4,fetchConversionRate:()=>C4,fetchById:()=>$0,fetchByCode:()=>w4,fetchAll:()=>U4,fetchActive:()=>P4,deleteExpiredCoupons:()=>R4,deleteCoupons:()=>_4,deleteCoupon:()=>A4});import{db as d0}from"@stacksjs/database";import{formatDate as eX}from"@stacksjs/orm";function F(J){if(typeof J==="number")return Number.isFinite(J)?J:0;if(typeof J==="bigint")return Number(J);if(!J||typeof J!=="object")return 0;let $=J;for(let G of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[G]!==void 0&&$[G]!==null)return F($[G]);if(Array.isArray(J))return J.reduce((G,N)=>G+F(N),0);return 0}async function A4(J){let $=await d0.deleteFrom("coupons").where("id","=",J).executeTakeFirst();return F($)>0}async function _4(J){if(!J.length)return 0;return(await d0.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function R4(){let J=eX(new Date),$=await d0.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return F($)}import{db as x}from"@stacksjs/database";import{extractDate as O4,formatDate as S4}from"@stacksjs/orm";import{camelCase as rX}from"@stacksjs/strings";function e0(J){let $=Object.fromEntries(Object.entries(J).map(([G,N])=>[rX(G),N]));if($.endDate)$.endDate=O4(new Date($.endDate));if($.startDate)$.startDate=O4(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function U4(){return(await x.selectFrom("coupons").selectAll().execute()).map(e0)}async function $0(J){let $=await x.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if($)return e0($);return}async function w4(J){let $=await x.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if($)return e0($);return}async function P4(){let J=S4(new Date);return(await x.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map(e0)}async function q4(){let J=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).executeTakeFirst(),$=S4(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(),N=await x.selectFrom("coupons").select(["discount_type",x.fn.count("id").as("count")]).groupBy("discount_type").execute(),X=await x.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),W=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:N,most_used:X,upcoming:W}}async function T4(){let J=new Date,$=new Date(J);$.setDate(J.getDate()-7);let G=new Date(J);G.setMonth(J.getMonth()-1);let N=new Date(J);N.setFullYear(J.getFullYear()-1);let X=await a0(null,null,J),W=await a0($,null,J),Z=await a0(G,null,J),L=await a0(N,null,J);return{week:W,month:Z,year:L,all_time:X}}async function a0(J,$,G){let N=x.selectFrom("coupons");if(J)N=N.where("created_at",">=",J.toISOString());if($)N=N.where("created_at","<=",$.toISOString());let X=await N.select(x.fn.count("id").as("count")).executeTakeFirst(),W=x.selectFrom("coupons");if(J)W=W.where("created_at",">=",J.toISOString());if($)W=W.where("created_at","<=",$.toISOString());W=W.where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G);let Z=await W.select(x.fn.count("id").as("count")).executeTakeFirst(),L=Number(X?.count||0),Y=Number(Z?.count||0),K=L-Y;return{total:L,active:Y,inactive:K}}async function E4(){let J=new Date,$=await x.selectFrom("coupons").select("discount_type").distinct().execute(),G={};for(let{discount_type:N}of $){let X=await x.selectFrom("coupons").where("discount_type","=",N).select(x.fn.count("id").as("count")).executeTakeFirst(),W=await x.selectFrom("coupons").where("discount_type","=",N).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(x.fn.count("id").as("count")).executeTakeFirst(),Z=Number(X?.count||0),L=Number(W?.count||0);G[N]={total:Z,active:L,inactive:Z-L}}return G}async function f4(){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 N=new Date($);N.setMonth($.getMonth()-1);let X=new Date($);X.setFullYear($.getFullYear()-1);let W=await x.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(x.fn.sum("usage_count").as("total")).executeTakeFirst(),Z=await x.selectFrom("coupons").where("updated_at",">=",N.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(),Y=await x.selectFrom("coupons").select(["discount_type",x.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),K={};return Y.forEach((Q)=>{K[Q.discount_type]=Number(Q.total||0)}),{total:Number(J?.total||0),week:Number(W?.total||0),month:Number(Z?.total||0),year:Number(L?.total||0),by_type:K}}async function k4(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 j4(J=30){let $=new Date().toISOString(),G=new Date;G.setDate(G.getDate()-J);let N=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(),X={};return N.forEach((W)=>{let Z=W.updated_at?new Date(W.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!X[Z])X[Z]=0;X[Z]+=W?.usage_count||0}),Object.entries(X).map(([W,Z])=>({date:W,count:Z}))}async function C4(){let J=new Date,$=await 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(),N=Number($?.count||0),X=Number(G?.count||0);return{rate:N>0?X/N*100:0,total_active:N,total_redeemed:X}}async function h4(){let J=new Date,$=new Date(J.getFullYear(),J.getMonth(),1),G=new Date(J.getFullYear(),J.getMonth()-1,1),N=new Date(J.getFullYear(),J.getMonth(),0),X=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",$).executeTakeFirst(),W=await x.selectFrom("coupons").select(x.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",G).executeTakeFirst(),Z=Number(X?.count||0),L=Number(W?.count||0),Y=Z-L,K=L!==0?Y/L*100:Z>0?100:0;return{current_month:Z,previous_month:L,difference:Y,percentage_change:K}}var{randomUUIDv7:tX}=globalThis.Bun;import{db as I4}from"@stacksjs/database";import{HttpError as g4}from"@stacksjs/error-handling";import{isUniqueViolation as $9}from"@stacksjs/orm";async function v4(J){try{let $=tX();return await I4.insertInto("coupons").values({...J,uuid:$}).executeTakeFirst(),await I4.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof g4)throw $;if($9($))throw new g4(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as D4}from"@stacksjs/database";import{HttpError as y4}from"@stacksjs/error-handling";import{formatDate as b4,isUniqueViolation as J9}from"@stacksjs/orm";async function m4(J,$){if(!await $0(J))return;try{return await D4.updateTable("coupons").set({...$,updated_at:b4(new Date)}).where("id","=",J).execute(),await $0(J)}catch(N){if(N instanceof y4)throw N;if(J9(N))throw new y4(409,"A coupon with this code already exists");if(N instanceof Error)throw Error(`Failed to update coupon: ${N.message}`);throw N}}async function p4(J){let $=b4(new Date),G=await D4.unsafe(`UPDATE coupons
|
|
3
3
|
SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ?
|
|
4
4
|
WHERE id = ?
|
|
5
5
|
AND (max_uses IS NULL OR usage_count < max_uses)
|
|
6
6
|
AND is_active = 1
|
|
7
7
|
AND (start_date IS NULL OR start_date <= ?)
|
|
8
|
-
AND (end_date IS NULL OR end_date >= ?)`,[$,J,$,$]),N=typeof G?.execute==="function"?await G.execute():G;if(Number(N?.changes??N?.numUpdatedRows??N?.affectedRows??0)>0){let L=await $0(J);if(L)return{ok:!0,coupon:L};return{ok:!1,reason:"not-found"}}let W=await $0(J);if(!W)return{ok:!1,reason:"not-found"};if(!W.isActive)return{ok:!1,reason:"inactive"};let Z=!W.startDate||W.startDate<=$,Y=!W.endDate||W.endDate>=$;if(!Z||!Y)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var L1={};z(L1,{update:()=>a4,store:()=>s4,fetchById:()=>r0,fetchAll:()=>i4,destroy:()=>c4,bulkDestroy:()=>u4});import{db as l4}from"@stacksjs/database";async function c4(J){try{let $=await l4.deleteFrom("customers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function u4(J){if(!J.length)return 0;try{let $=await l4.deleteFrom("customers").where("id","in",J).executeTakeFirst();return F($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as n4}from"@stacksjs/database";async function r0(J){return await n4.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function i4(){return await n4.selectFrom("customers").selectAll().execute()}import{db as G9}from"@stacksjs/database";import{HttpError as o4}from"@stacksjs/error-handling";import{isUniqueViolation as N9}from"@stacksjs/orm";async function s4(J){try{let $={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await G9.insertInto("customers").values($).executeTakeFirst();if(!G)throw Error("Failed to create customer");let N=G.insertId||Number(G.numInsertedOrUpdatedRows);return await r0(Number(N))}catch($){if($ instanceof o4)throw $;if(N9($))throw new o4(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as X9}from"@stacksjs/database";import{HttpError as d4}from"@stacksjs/error-handling";import{formatDate as W9,isUniqueViolation as Z9}from"@stacksjs/orm";async function a4(J,$){try{if(!J)throw Error("Customer ID is required for update");let G=await X9.updateTable("customers").set({...$,updated_at:W9(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof d4)throw G;if(Z9(G))throw new d4(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var H1={};z(H1,{updateStatus:()=>H7,updatePrintCount:()=>V7,update:()=>M7,storePrintDevicesExport:()=>L7,store:()=>F7,getPrinterStatusCounts:()=>Z7,fetchErrorsByDeviceId:()=>X7,fetchById:()=>l,fetchAll:()=>t0,exportPrintDevices:()=>$$,downloadPrintDevices:()=>Y7,destroy:()=>r4,countTotalPrints:()=>J7,countPrintsByDeviceId:()=>G7,countAll:()=>$7,calculatePrinterHealth:()=>W7,calculateErrorRate:()=>N7,bulkStore:()=>Q7,bulkDestroy:()=>t4});import{db as e4}from"@stacksjs/database";async function r4(J){try{let $=await e4.deleteFrom("print_devices").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function t4(J){if(!J.length)return 0;try{let $=await e4.deleteFrom("print_devices").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as Y9}from"ts-spreadsheets";import{db as q}from"@stacksjs/database";async function l(J){return await q.selectFrom("print_devices").where("id","=",J).selectAll().executeTakeFirst()}async function t0(){return await q.selectFrom("print_devices").selectAll().execute()}async function $7(){let J=await q.selectFrom("print_devices").select(q.fn.count("id").as("count")).executeTakeFirst();return Number(J?.count||0)}async function J7(){let J=await q.selectFrom("print_devices").select(q.fn.sum("print_count").as("total")).executeTakeFirst();return Number(J?.total||0)}async function G7(J){return(await q.selectFrom("print_devices").select("print_count").where("id","=",J).executeTakeFirst())?.print_count??0}async function N7(){let J=await q.selectFrom("receipts").select([q.fn.count("id").as("total"),q.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.failed_count??0)/J.total*100)}async function X7(J){return await q.selectFrom("receipts").where("print_device_id","=",J).where("status","=","failed").selectAll().execute()}async function W7(){let J=await q.selectFrom("print_devices").select([q.fn.count("id").as("total"),q.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.online_count??0)/J.total*100)}async function Z7(){return(await q.selectFrom("print_devices").select(["status",q.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,G)=>{return $[G.status]=Number(G.count||0),$},{})}function K1(J,$,G=$){return J?.[$]??J?.[G]}function L9(J){let $=String(J||""),G=/^\d+$/.test($)?Number($):J;return new Date(G)}async function $$(J="csv"){let $=await t0(),G=K9($);return Y9(G,{type:J})}function K9(J){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=J.map((N)=>{return[N.id,N.name,K1(N,"macAddress","mac_address"),N.location,N.terminal,N.status,L9(K1(N,"lastPing","last_ping")).toLocaleString(),K1(N,"printCount","print_count")]});return{headings:$,data:G}}async function Y7(J="csv",$){let G=await $$(J),N=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||N)}async function L7(J="csv",$){let G=await $$(J),N=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||N)}var{randomUUIDv7:K7}=globalThis.Bun;import{db as F1}from"@stacksjs/database";async function F7(J){try{let $=K7(),G={last_ping:0,print_count:0,...J,uuid:$};return await F1.insertInto("print_devices").values(G).executeTakeFirst(),await F1.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function Q7(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={last_ping:0,print_count:0,...G,uuid:K7()};await F1.insertInto("print_devices").values(N).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as Q1}from"@stacksjs/database";import{formatDate as M1}from"@stacksjs/orm";async function M7(J,$){if(!await l(J))return;try{return await Q1.updateTable("print_devices").set({...$,updated_at:M1(new Date)}).where("id","=",J).execute(),await l(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update print device: ${N.message}`);throw N}}async function H7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await Q1.updateTable("print_devices").set({status:$,updated_at:M1(new Date)}).where("id","=",J).execute(),await l(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update print device status: ${N.message}`);throw N}}async function V7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await Q1.updateTable("print_devices").set({print_count:$,updated_at:M1(new Date)}).where("id","=",J).execute(),await l(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update print count: ${N.message}`);throw N}}var z1={};z(z1,{update:()=>U7,unresolveGroup:()=>q7,resolveGroup:()=>P7,ignoreGroup:()=>w7,fetchTimeline:()=>S7,fetchStats:()=>O7,fetchGrouped:()=>_7,fetchById:()=>A7,fetchByGroup:()=>R7,fetchAll:()=>G$,destroyGroup:()=>B7,destroy:()=>x7,bulkUpdateStatus:()=>T7,bulkDestroy:()=>z7});import{db as V1}from"@stacksjs/database";import{log as x1}from"@stacksjs/logging";async function x7(J){try{return await V1.deleteFrom("errors").where("id","=",J).execute(),!0}catch($){return x1.error("[commerce/errors] destroy failed",{id:J,error:$}),!1}}async function z7(J){try{return await V1.deleteFrom("errors").where("id","in",J).execute(),!0}catch($){return x1.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:$}),!1}}async function B7(J,$){try{return await V1.deleteFrom("errors").where("type","=",J).where("message","=",$).execute(),!0}catch(G){return x1.error("[commerce/errors] destroyGroup failed",{type:J,message:$,error:G}),!1}}import{db as J$}from"@stacksjs/database";async function A7(J){return await J$.selectFrom("errors").where("id","=",J).selectAll().executeTakeFirst()}async function G$(){return await J$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function _7(){let J=await J$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let N of J){let X=`${N.type}:${N.message}`;if(!$.has(X))$.set(X,{errors:[],firstSeen:new Date(N.created_at),lastSeen:new Date(N.created_at)});let W=$.get(X);W.errors.push(N);let Z=new Date(N.created_at);if(Z<W.firstSeen)W.firstSeen=Z;if(Z>W.lastSeen)W.lastSeen=Z}let G=[];for(let[N,X]of $){let W=X.errors[0];if(!W)continue;let Z=X.errors.find((L)=>L.status!==null)?.status,Y="unresolved";if(Z===1)Y="resolved";else if(Z===2)Y="ignored";G.push({id:W.id,type:W.type,message:W.message,stack:W.stack,status:Y,count:X.errors.length,first_seen:X.firstSeen.toISOString(),last_seen:X.lastSeen.toISOString(),error_ids:X.errors.map((L)=>L.id)})}return G.sort((N,X)=>new Date(X.last_seen).getTime()-new Date(N.last_seen).getTime()),G}async function R7(J,$){return await J$.selectFrom("errors").where("type","=",J).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function O7(){let J=await G$(),$=new Date,G=new Date($.getTime()-86400000),N=new Date($.getTime()-172800000),X=J.filter((Y)=>new Date(Y.created_at)>=G).length,W=J.filter((Y)=>{let L=new Date(Y.created_at);return L>=N&&L<G}).length,Z=W===0?X>0?100:0:Math.round((X-W)/W*100);return{total:J.length,unresolved:J.filter((Y)=>Y.status===null||Y.status===0).length,resolved:J.filter((Y)=>Y.status===1).length,ignored:J.filter((Y)=>Y.status===2).length,last_24h:X,trend:Z}}async function S7(){let J=await G$(),$=new Date,G=[];for(let N=23;N>=0;N--){let X=new Date($.getTime()-N*60*60*1000);X.setMinutes(0,0,0);let W=new Date(X.getTime()+3600000),Z=J.filter((Y)=>{let L=new Date(Y.created_at);return L>=X&&L<W}).length;G.push({hour:X.toISOString(),count:Z})}return G}import{db as S0}from"@stacksjs/database";import{sql as U0}from"@stacksjs/database";import{log as T0}from"@stacksjs/logging";async function U7(J,$){try{return await S0.updateTable("errors").set({...$,updated_at:U0.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(G){return T0.error("[commerce/errors] update failed",{id:J,error:G}),!1}}async function T7(J,$){try{return await S0.updateTable("errors").set({status:$,updated_at:U0.raw("CURRENT_TIMESTAMP")}).where("id","in",J).execute(),!0}catch(G){return T0.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:$,error:G}),!1}}async function P7(J,$){try{return await S0.updateTable("errors").set({status:1,updated_at:U0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return T0.error("[commerce/errors] resolveGroup failed",{type:J,message:$,error:G}),!1}}async function w7(J,$){try{return await S0.updateTable("errors").set({status:2,updated_at:U0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return T0.error("[commerce/errors] ignoreGroup failed",{type:J,message:$,error:G}),!1}}async function q7(J,$){try{return await S0.updateTable("errors").set({status:0,updated_at:U0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return T0.error("[commerce/errors] unresolveGroup failed",{type:J,message:$,error:G}),!1}}var A1={};z(A1,{updateBalance:()=>i7,update:()=>n7,store:()=>p7,fetchTotalValue:()=>I7,fetchTotalCurrentBalance:()=>g7,fetchStats:()=>k7,fetchById:()=>J0,fetchByCode:()=>B1,fetchAll:()=>f7,fetchActive:()=>E7,destroy:()=>y7,compareActiveGiftCards:()=>C7,checkBalance:()=>j7,calculateGiftCardValues:()=>h7,bulkDestroy:()=>D7});import{db as v7}from"@stacksjs/database";import{formatDate as nW}from"@stacksjs/orm";import{db as U,sql as C}from"@stacksjs/database";import{formatDate as s,toTimestamp as K0}from"@stacksjs/orm";import{aggregateFunctions as F9,db as Q9}from"@stacksjs/database";async function I(J,$,G){let N=Q9.selectFrom(J);if(G)N=G(N);N=N.select(Object.entries($).map(([Z,Y])=>{let L=Y.column??"id",K=F9[Y.kind](L);if(Y.filter)K=K.filterWhere(Y.filter.column,Y.filter.op,Y.filter.value);return K.as(Z)}));let X=await N.executeTakeFirst(),W={};for(let Z of Object.keys($)){let Y=X?.[Z];W[Z]=typeof Y==="number"?Y:Number(Y??0)||0}return W}async function f7(){return await U.selectFrom("gift_cards").selectAll().execute()}async function J0(J){return await U.selectFrom("gift_cards").where("id","=",J).selectAll().executeTakeFirst()}async function B1(J){return await U.selectFrom("gift_cards").where("code","=",J).selectAll().executeTakeFirst()}async function E7(){return await U.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function k7(){let{count:J}=await I("gift_cards",{count:{kind:"count"}}),$=K0(new Date),G=await U.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal($)} OR expiry_date IS NULL)`).select(U.fn.count("id").as("count")).executeTakeFirst(),N=await U.selectFrom("gift_cards").select(["status",U.fn.count("id").as("count")]).groupBy("status").execute(),{count:X}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:W}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:Z}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance > 0.75`)),Y=new Date;Y.setDate(Y.getDate()+30);let L=await U.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",K0(Y)).where("expiry_date",">=",$).selectAll().limit(5).execute(),K=await U.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:J,active:Number(G?.count||0),by_status:N.map((Q)=>({status:Q.status,count:Number(Q.count)})),by_balance:{low:X,medium:W,high:Z},expiring_soon:L,recently_used:K}}async function j7(J){let $=await B1(J);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function C7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await U.selectFrom("gift_cards").select(U.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),Z=await U.selectFrom("gift_cards").select(U.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0(X))} OR expiry_date IS NULL)`).where("created_at",">=",s(X)).where("created_at","<=",s(N)).executeTakeFirst(),Y=Number(W?.count||0),L=Number(Z?.count||0),K=Y-L,Q=L!==0?K/L*100:Y>0?100:0;return{current_period:Y,previous_period:L,difference:K,percentage_change:Q,days_range:J}}async function h7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await U.selectFrom("gift_cards").select([U.fn.sum("initial_balance").as("total_initial"),U.fn.sum("current_balance").as("total_balance"),U.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),Z=await U.selectFrom("gift_cards").select([U.fn.sum("initial_balance").as("total_initial"),U.fn.sum("current_balance").as("total_balance"),U.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0(X))} OR expiry_date IS NULL)`).where("created_at",">=",s(X)).where("created_at","<=",s(N)).executeTakeFirst(),Y=Number(W?.total_initial||0),L=Number(W?.total_balance||0),K=Number(W?.card_count||0),Q=Number(Z?.total_initial||0),M=Number(Z?.total_balance||0),H=Number(Z?.card_count||0),_=Y>0?(Y-L)/Y*100:0,O=Q>0?(Q-M)/Q*100:0,R=K>0?Y/K:0,S=K>0?L/K:0,m=Y-Q,r=L-M,t=K-H,L0=Q!==0?m/Q*100:Y>0?100:0,p=M!==0?r/M*100:L>0?100:0,iX=H!==0?t/H*100:K>0?100:0;return{current_period:{total_initial_value:Y,total_remaining_balance:L,utilization_rate:_,card_count:K,average_initial_value:R,average_remaining_balance:S},previous_period:{total_initial_value:Q,total_remaining_balance:M,utilization_rate:O,card_count:H},comparison:{initial_value:{difference:m,percentage:Math.abs(L0),is_increase:m>=0},balance:{difference:r,percentage:Math.abs(p),is_increase:r>=0},card_count:{difference:t,percentage:Math.abs(iX),is_increase:t>=0}},days_range:J}}async function I7(){let{total_value:J}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:J}}async function g7(){let{total_balance:J}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:J}}async function y7(J){let $=await v7.deleteFrom("gift_cards").where("id","=",J).executeTakeFirst();return F($)>0}async function D7(J){if(!J.length)return 0;let $=await v7.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return F($)}var{randomUUIDv7:M9}=globalThis.Bun;import{db as b7}from"@stacksjs/database";import{HttpError as m7}from"@stacksjs/error-handling";import{isUniqueViolation as H9}from"@stacksjs/orm";async function p7(J){let $=J,G={...J,current_balance:$.current_balance??$.initial_balance,status:J.status||"ACTIVE",is_active:$.is_active??!0,uuid:M9()};try{let N=await b7.insertInto("gift_cards").values(G).executeTakeFirst(),X=Number(N.insertId)||Number(N.numInsertedOrUpdatedRows);if(X)return await b7.selectFrom("gift_cards").where("id","=",X).selectAll().executeTakeFirst();return}catch(N){if(N instanceof m7)throw N;if(H9(N))throw new m7(409,"A gift card with this code already exists");if(N instanceof Error)throw Error(`Failed to create gift card: ${N.message}`);throw N}}import{db as c7}from"@stacksjs/database";import{HttpError as l7}from"@stacksjs/error-handling";import{formatDate as u7,isUniqueViolation as V9}from"@stacksjs/orm";async function n7(J,$){if(!await J0(J))return;try{return await c7.updateTable("gift_cards").set({...$,updated_at:u7(new Date)}).where("id","=",J).execute(),await J0(J)}catch(N){if(N instanceof l7)throw N;if(V9(N))throw new l7(409,"A gift card with this code already exists");if(N instanceof Error)throw Error(`Failed to update gift card: ${N.message}`);throw N}}async function i7(J,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let G=u7(new Date),N=await c7.unsafe(`UPDATE gift_cards
|
|
8
|
+
AND (end_date IS NULL OR end_date >= ?)`,[$,J,$,$]),N=typeof G?.execute==="function"?await G.execute():G;if(Number(N?.changes??N?.numUpdatedRows??N?.affectedRows??0)>0){let Y=await $0(J);if(Y)return{ok:!0,coupon:Y};return{ok:!1,reason:"not-found"}}let W=await $0(J);if(!W)return{ok:!1,reason:"not-found"};if(!W.isActive)return{ok:!1,reason:"inactive"};let Z=!W.startDate||W.startDate<=$,L=!W.endDate||W.endDate>=$;if(!Z||!L)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var Y1={};z(Y1,{update:()=>a4,store:()=>s4,fetchById:()=>r0,fetchAll:()=>i4,destroy:()=>c4,bulkDestroy:()=>u4});import{db as l4}from"@stacksjs/database";async function c4(J){try{let $=await l4.deleteFrom("customers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function u4(J){if(!J.length)return 0;try{let $=await l4.deleteFrom("customers").where("id","in",J).executeTakeFirst();return F($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as n4}from"@stacksjs/database";async function r0(J){return await n4.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function i4(){return await n4.selectFrom("customers").selectAll().execute()}import{db as G9}from"@stacksjs/database";import{HttpError as o4}from"@stacksjs/error-handling";import{isUniqueViolation as N9}from"@stacksjs/orm";async function s4(J){try{let $={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},G=await G9.insertInto("customers").values($).executeTakeFirst();if(!G)throw Error("Failed to create customer");let N=G.insertId||Number(G.numInsertedOrUpdatedRows);return await r0(Number(N))}catch($){if($ instanceof o4)throw $;if(N9($))throw new o4(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as X9}from"@stacksjs/database";import{HttpError as d4}from"@stacksjs/error-handling";import{formatDate as W9,isUniqueViolation as Z9}from"@stacksjs/orm";async function a4(J,$){try{if(!J)throw Error("Customer ID is required for update");let G=await X9.updateTable("customers").set({...$,updated_at:W9(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof d4)throw G;if(Z9(G))throw new d4(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to update customer: ${G.message}`);throw G}}var H1={};z(H1,{updateStatus:()=>H7,updatePrintCount:()=>x7,update:()=>M7,storePrintDevicesExport:()=>Y7,store:()=>F7,getPrinterStatusCounts:()=>Z7,fetchErrorsByDeviceId:()=>X7,fetchById:()=>l,fetchAll:()=>t0,exportPrintDevices:()=>$$,downloadPrintDevices:()=>L7,destroy:()=>r4,countTotalPrints:()=>J7,countPrintsByDeviceId:()=>G7,countAll:()=>$7,calculatePrinterHealth:()=>W7,calculateErrorRate:()=>N7,bulkStore:()=>Q7,bulkDestroy:()=>t4});import{db as e4}from"@stacksjs/database";async function r4(J){try{let $=await e4.deleteFrom("print_devices").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function t4(J){if(!J.length)return 0;try{let $=await e4.deleteFrom("print_devices").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as L9}from"ts-spreadsheets";import{db as E}from"@stacksjs/database";async function l(J){return await E.selectFrom("print_devices").where("id","=",J).selectAll().executeTakeFirst()}async function t0(){return await E.selectFrom("print_devices").selectAll().execute()}async function $7(){let J=await E.selectFrom("print_devices").select(E.fn.count("id").as("count")).executeTakeFirst();return Number(J?.count||0)}async function J7(){let J=await E.selectFrom("print_devices").select(E.fn.sum("print_count").as("total")).executeTakeFirst();return Number(J?.total||0)}async function G7(J){return(await E.selectFrom("print_devices").select("print_count").where("id","=",J).executeTakeFirst())?.print_count??0}async function N7(){let J=await E.selectFrom("receipts").select([E.fn.count("id").as("total"),E.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.failed_count??0)/J.total*100)}async function X7(J){return await E.selectFrom("receipts").where("print_device_id","=",J).where("status","=","failed").selectAll().execute()}async function W7(){let J=await E.selectFrom("print_devices").select([E.fn.count("id").as("total"),E.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!J?.total||J.total===0)return 0;return Number((J.online_count??0)/J.total*100)}async function Z7(){return(await E.selectFrom("print_devices").select(["status",E.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,G)=>{return $[G.status]=Number(G.count||0),$},{})}function K1(J,$,G=$){return J?.[$]??J?.[G]}function Y9(J){let $=String(J||""),G=/^\d+$/.test($)?Number($):J;return new Date(G)}async function $$(J="csv"){let $=await t0(),G=K9($);return L9(G,{type:J})}function K9(J){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],G=J.map((N)=>{return[N.id,N.name,K1(N,"macAddress","mac_address"),N.location,N.terminal,N.status,Y9(K1(N,"lastPing","last_ping")).toLocaleString(),K1(N,"printCount","print_count")]});return{headings:$,data:G}}async function L7(J="csv",$){let G=await $$(J),N=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||N)}async function Y7(J="csv",$){let G=await $$(J),N=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||N)}var{randomUUIDv7:K7}=globalThis.Bun;import{db as F1}from"@stacksjs/database";async function F7(J){try{let $=K7(),G={last_ping:0,print_count:0,...J,uuid:$};return await F1.insertInto("print_devices").values(G).executeTakeFirst(),await F1.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function Q7(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={last_ping:0,print_count:0,...G,uuid:K7()};await F1.insertInto("print_devices").values(N).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${G.message}`);throw G}}import{db as Q1}from"@stacksjs/database";import{formatDate as M1}from"@stacksjs/orm";async function M7(J,$){if(!await l(J))return;try{return await Q1.updateTable("print_devices").set({...$,updated_at:M1(new Date)}).where("id","=",J).execute(),await l(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update print device: ${N.message}`);throw N}}async function H7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await Q1.updateTable("print_devices").set({status:$,updated_at:M1(new Date)}).where("id","=",J).execute(),await l(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update print device status: ${N.message}`);throw N}}async function x7(J,$){if(!await l(J))throw Error(`Print device with ID ${J} not found`);try{return await Q1.updateTable("print_devices").set({print_count:$,updated_at:M1(new Date)}).where("id","=",J).execute(),await l(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update print count: ${N.message}`);throw N}}var z1={};z(z1,{update:()=>U7,unresolveGroup:()=>T7,resolveGroup:()=>P7,ignoreGroup:()=>q7,fetchTimeline:()=>S7,fetchStats:()=>O7,fetchGrouped:()=>_7,fetchById:()=>A7,fetchByGroup:()=>R7,fetchAll:()=>G$,destroyGroup:()=>B7,destroy:()=>V7,bulkUpdateStatus:()=>w7,bulkDestroy:()=>z7});import{db as x1}from"@stacksjs/database";import{log as V1}from"@stacksjs/logging";async function V7(J){try{return await x1.deleteFrom("errors").where("id","=",J).execute(),!0}catch($){return V1.error("[commerce/errors] destroy failed",{id:J,error:$}),!1}}async function z7(J){try{return await x1.deleteFrom("errors").where("id","in",J).execute(),!0}catch($){return V1.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:$}),!1}}async function B7(J,$){try{return await x1.deleteFrom("errors").where("type","=",J).where("message","=",$).execute(),!0}catch(G){return V1.error("[commerce/errors] destroyGroup failed",{type:J,message:$,error:G}),!1}}import{db as J$}from"@stacksjs/database";async function A7(J){return await J$.selectFrom("errors").where("id","=",J).selectAll().executeTakeFirst()}async function G$(){return await J$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function _7(){let J=await J$.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let N of J){let X=`${N.type}:${N.message}`;if(!$.has(X))$.set(X,{errors:[],firstSeen:new Date(N.created_at),lastSeen:new Date(N.created_at)});let W=$.get(X);W.errors.push(N);let Z=new Date(N.created_at);if(Z<W.firstSeen)W.firstSeen=Z;if(Z>W.lastSeen)W.lastSeen=Z}let G=[];for(let[N,X]of $){let W=X.errors[0];if(!W)continue;let Z=X.errors.find((Y)=>Y.status!==null)?.status,L="unresolved";if(Z===1)L="resolved";else if(Z===2)L="ignored";G.push({id:W.id,type:W.type,message:W.message,stack:W.stack,status:L,count:X.errors.length,first_seen:X.firstSeen.toISOString(),last_seen:X.lastSeen.toISOString(),error_ids:X.errors.map((Y)=>Y.id)})}return G.sort((N,X)=>new Date(X.last_seen).getTime()-new Date(N.last_seen).getTime()),G}async function R7(J,$){return await J$.selectFrom("errors").where("type","=",J).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function O7(){let J=await G$(),$=new Date,G=new Date($.getTime()-86400000),N=new Date($.getTime()-172800000),X=J.filter((L)=>new Date(L.created_at)>=G).length,W=J.filter((L)=>{let Y=new Date(L.created_at);return Y>=N&&Y<G}).length,Z=W===0?X>0?100:0:Math.round((X-W)/W*100);return{total:J.length,unresolved:J.filter((L)=>L.status===null||L.status===0).length,resolved:J.filter((L)=>L.status===1).length,ignored:J.filter((L)=>L.status===2).length,last_24h:X,trend:Z}}async function S7(){let J=await G$(),$=new Date,G=[];for(let N=23;N>=0;N--){let X=new Date($.getTime()-N*60*60*1000);X.setMinutes(0,0,0);let W=new Date(X.getTime()+3600000),Z=J.filter((L)=>{let Y=new Date(L.created_at);return Y>=X&&Y<W}).length;G.push({hour:X.toISOString(),count:Z})}return G}import{db as U0}from"@stacksjs/database";import{sql as w0}from"@stacksjs/database";import{log as P0}from"@stacksjs/logging";async function U7(J,$){try{return await U0.updateTable("errors").set({...$,updated_at:w0.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(G){return P0.error("[commerce/errors] update failed",{id:J,error:G}),!1}}async function w7(J,$){try{return await U0.updateTable("errors").set({status:$,updated_at:w0.raw("CURRENT_TIMESTAMP")}).where("id","in",J).execute(),!0}catch(G){return P0.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:$,error:G}),!1}}async function P7(J,$){try{return await U0.updateTable("errors").set({status:1,updated_at:w0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return P0.error("[commerce/errors] resolveGroup failed",{type:J,message:$,error:G}),!1}}async function q7(J,$){try{return await U0.updateTable("errors").set({status:2,updated_at:w0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return P0.error("[commerce/errors] ignoreGroup failed",{type:J,message:$,error:G}),!1}}async function T7(J,$){try{return await U0.updateTable("errors").set({status:0,updated_at:w0.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",$).execute(),!0}catch(G){return P0.error("[commerce/errors] unresolveGroup failed",{type:J,message:$,error:G}),!1}}var A1={};z(A1,{updateBalance:()=>i7,update:()=>n7,store:()=>p7,fetchTotalValue:()=>I7,fetchTotalCurrentBalance:()=>g7,fetchStats:()=>k7,fetchById:()=>J0,fetchByCode:()=>B1,fetchAll:()=>E7,fetchActive:()=>f7,destroy:()=>y7,compareActiveGiftCards:()=>C7,checkBalance:()=>j7,calculateGiftCardValues:()=>h7,bulkDestroy:()=>D7});import{db as v7}from"@stacksjs/database";import{formatDate as iW}from"@stacksjs/orm";import{db as U,sql as C}from"@stacksjs/database";import{formatDate as s,toTimestamp as K0}from"@stacksjs/orm";import{aggregateFunctions as F9,db as Q9}from"@stacksjs/database";async function I(J,$,G){let N=Q9.selectFrom(J);if(G)N=G(N);N=N.select(Object.entries($).map(([Z,L])=>{let Y=L.column??"id",K=F9[L.kind](Y);if(L.filter)K=K.filterWhere(L.filter.column,L.filter.op,L.filter.value);return K.as(Z)}));let X=await N.executeTakeFirst(),W={};for(let Z of Object.keys($)){let L=X?.[Z];W[Z]=typeof L==="number"?L:Number(L??0)||0}return W}async function E7(){return await U.selectFrom("gift_cards").selectAll().execute()}async function J0(J){return await U.selectFrom("gift_cards").where("id","=",J).selectAll().executeTakeFirst()}async function B1(J){return await U.selectFrom("gift_cards").where("code","=",J).selectAll().executeTakeFirst()}async function f7(){return await U.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function k7(){let{count:J}=await I("gift_cards",{count:{kind:"count"}}),$=K0(new Date),G=await U.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal($)} OR expiry_date IS NULL)`).select(U.fn.count("id").as("count")).executeTakeFirst(),N=await U.selectFrom("gift_cards").select(["status",U.fn.count("id").as("count")]).groupBy("status").execute(),{count:X}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance < 0.25`)),{count:W}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:Z}=await I("gift_cards",{count:{kind:"count"}},(Q)=>Q.whereRaw(C`current_balance / initial_balance > 0.75`)),L=new Date;L.setDate(L.getDate()+30);let Y=await U.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",K0(L)).where("expiry_date",">=",$).selectAll().limit(5).execute(),K=await U.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:J,active:Number(G?.count||0),by_status:N.map((Q)=>({status:Q.status,count:Number(Q.count)})),by_balance:{low:X,medium:W,high:Z},expiring_soon:Y,recently_used:K}}async function j7(J){let $=await B1(J);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function C7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await U.selectFrom("gift_cards").select(U.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),Z=await U.selectFrom("gift_cards").select(U.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0(X))} OR expiry_date IS NULL)`).where("created_at",">=",s(X)).where("created_at","<=",s(N)).executeTakeFirst(),L=Number(W?.count||0),Y=Number(Z?.count||0),K=L-Y,Q=Y!==0?K/Y*100:L>0?100:0;return{current_period:L,previous_period:Y,difference:K,percentage_change:Q,days_range:J}}async function h7(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await U.selectFrom("gift_cards").select([U.fn.sum("initial_balance").as("total_initial"),U.fn.sum("current_balance").as("total_balance"),U.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0($))} OR expiry_date IS NULL)`).where("created_at",">=",s(G)).where("created_at","<=",s($)).executeTakeFirst(),Z=await U.selectFrom("gift_cards").select([U.fn.sum("initial_balance").as("total_initial"),U.fn.sum("current_balance").as("total_balance"),U.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(C`(expiry_date >= ${C.literal(K0(X))} OR expiry_date IS NULL)`).where("created_at",">=",s(X)).where("created_at","<=",s(N)).executeTakeFirst(),L=Number(W?.total_initial||0),Y=Number(W?.total_balance||0),K=Number(W?.card_count||0),Q=Number(Z?.total_initial||0),M=Number(Z?.total_balance||0),H=Number(Z?.card_count||0),_=L>0?(L-Y)/L*100:0,O=Q>0?(Q-M)/Q*100:0,R=K>0?L/K:0,S=K>0?Y/K:0,m=L-Q,r=Y-M,t=K-H,Y0=Q!==0?m/Q*100:L>0?100:0,p=M!==0?r/M*100:Y>0?100:0,iX=H!==0?t/H*100:K>0?100:0;return{current_period:{total_initial_value:L,total_remaining_balance:Y,utilization_rate:_,card_count:K,average_initial_value:R,average_remaining_balance:S},previous_period:{total_initial_value:Q,total_remaining_balance:M,utilization_rate:O,card_count:H},comparison:{initial_value:{difference:m,percentage:Math.abs(Y0),is_increase:m>=0},balance:{difference:r,percentage:Math.abs(p),is_increase:r>=0},card_count:{difference:t,percentage:Math.abs(iX),is_increase:t>=0}},days_range:J}}async function I7(){let{total_value:J}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:J}}async function g7(){let{total_balance:J}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:J}}async function y7(J){let $=await v7.deleteFrom("gift_cards").where("id","=",J).executeTakeFirst();return F($)>0}async function D7(J){if(!J.length)return 0;let $=await v7.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return F($)}var{randomUUIDv7:M9}=globalThis.Bun;import{db as b7}from"@stacksjs/database";import{HttpError as m7}from"@stacksjs/error-handling";import{isUniqueViolation as H9}from"@stacksjs/orm";async function p7(J){let $=J,G={...J,current_balance:$.current_balance??$.initial_balance,status:J.status||"ACTIVE",is_active:$.is_active??!0,uuid:M9()};try{let N=await b7.insertInto("gift_cards").values(G).executeTakeFirst(),X=Number(N.insertId)||Number(N.numInsertedOrUpdatedRows);if(X)return await b7.selectFrom("gift_cards").where("id","=",X).selectAll().executeTakeFirst();return}catch(N){if(N instanceof m7)throw N;if(H9(N))throw new m7(409,"A gift card with this code already exists");if(N instanceof Error)throw Error(`Failed to create gift card: ${N.message}`);throw N}}import{db as c7}from"@stacksjs/database";import{HttpError as l7}from"@stacksjs/error-handling";import{formatDate as u7,isUniqueViolation as x9}from"@stacksjs/orm";async function n7(J,$){if(!await J0(J))return;try{return await c7.updateTable("gift_cards").set({...$,updated_at:u7(new Date)}).where("id","=",J).execute(),await J0(J)}catch(N){if(N instanceof l7)throw N;if(x9(N))throw new l7(409,"A gift card with this code already exists");if(N instanceof Error)throw Error(`Failed to update gift card: ${N.message}`);throw N}}async function i7(J,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let G=u7(new Date),N=await c7.unsafe(`UPDATE gift_cards
|
|
9
9
|
SET current_balance = current_balance + ?,
|
|
10
10
|
last_used_date = ?,
|
|
11
11
|
status = CASE WHEN current_balance + ? = 0 THEN 'USED' ELSE 'ACTIVE' END,
|
|
@@ -13,15 +13,15 @@ var oX=Object.defineProperty;var sX=(J)=>J;function dX(J,$){this[J]=sX.bind(null
|
|
|
13
13
|
WHERE id = ?
|
|
14
14
|
AND is_active = 1
|
|
15
15
|
AND status = 'ACTIVE'
|
|
16
|
-
AND current_balance + ? >= 0`,[$,G,$,G,J,$]),X=typeof N?.execute==="function"?await N.execute():N;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0)return await J0(J);let Z=await J0(J);if(!Z)throw Error(`Gift card with ID ${J} not found`);if(!Z.is_active||Z.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var
|
|
16
|
+
AND current_balance + ? >= 0`,[$,G,$,G,J,$]),X=typeof N?.execute==="function"?await N.execute():N;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0)return await J0(J);let Z=await J0(J);if(!Z)throw Error(`Gift card with ID ${J} not found`);if(!Z.is_active||Z.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var T1={};z(T1,{validateQuantityBounds:()=>q1,validateCouponStacking:()=>UJ,validateCartQuantities:()=>wJ,updateStatus:()=>BJ,updateDeliveryInfo:()=>AJ,update:()=>zJ,storeOrdersExport:()=>t7,store:()=>LJ,softDelete:()=>s7,registerCommerceWebhookHandlers:()=>RJ,recomputeOrderTotals:()=>SJ,placeOrder:()=>VJ,handlePaymentIntentSucceeded:()=>U1,handlePaymentIntentFailed:()=>w1,handleChargeRefunded:()=>P1,findOrderByIdempotencyKey:()=>Y$,fetchStats:()=>JJ,fetchDailyOrderTrends:()=>XJ,fetchById:()=>c,fetchAll:()=>$J,exportOrders:()=>X$,emitOrderShipped:()=>W$,emitOrderRefunded:()=>Q0,emitOrderPaid:()=>d,emitOrderDelivered:()=>Z$,emitOrderCreated:()=>T0,emitOrderCancelled:()=>F0,emitForStatus:()=>E0,downloadOrders:()=>r7,destroy:()=>o7,compareOrdersByPeriod:()=>GJ,cleanupAbandonedCarts:()=>PJ,canTransition:()=>q0,calculateOrderMetrics:()=>NJ,bulkSoftDelete:()=>a7,bulkDestroy:()=>d7});import{db as N$}from"@stacksjs/database";async function o7(J){try{let $=await N$.deleteFrom("orders").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function s7(J){try{let $=await N$.updateTable("orders").set({status:"CANCELED"}).where("id","=",J).executeTakeFirst();return Number($.numUpdatedRows)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete order: ${$.message}`);throw $}}async function d7(J){if(!J.length)return 0;try{let $=await N$.deleteFrom("orders").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}async function a7(J){if(!J.length)return 0;try{let $=await N$.updateTable("orders").set({status:"CANCELED"}).where("id","in",J).executeTakeFirst();return Number($.numUpdatedRows)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete orders: ${$.message}`);throw $}}import{db as e7}from"@stacksjs/database";import{createSpreadsheet as V9}from"ts-spreadsheets";async function X$(J="csv"){let $=await z9(),G=B9($);return V9(G,{type:J})}async function z9(){let J=await e7.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),$=J.map((W)=>W.id);if($.length===0)return[];let N=(await e7.selectFrom("order_items").where("order_items.order_id","in",$).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((W,Z)=>{if(!Z.order_id)return W;if(!W[Z.order_id])W[Z.order_id]={totalItems:0,totalPrice:0};return W[Z.order_id].totalItems+=Z.quantity,W[Z.order_id].totalPrice+=Z.price*Z.quantity,W},{});return J.map((W)=>{let Z=N[W.id]||{totalItems:0,totalPrice:0};return{...W,totalItems:Z.totalItems,totalPrice:Z.totalPrice}})}function B9(J){let $=["Order ID","Customer","Date","Total","Status","Items"],G=J.map((N)=>{let X=N.order_items?.map((W)=>`${W.product?.name} (Qty: ${W.quantity}, Price: $${W.price})`).join(" | ")||"No Items";return[N.id,N.customer?.name||"N/A",N.created_at,N.total_amount,N.status,X]});return{headings:$,data:G}}async function r7(J="csv",$){let G=await X$(J),N=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||N)}async function t7(J="csv",$){let G=await X$(J),N=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||N)}import{db as B}from"@stacksjs/database";async function $J(J){let $=B.selectFrom("orders").selectAll().orderBy("created_at","desc");if(J)$=$.limit(J);let G=await $.execute();return await Promise.all(G.map(async(N)=>{let X=await B.selectFrom("order_items").where("order_id","=",N.id).selectAll().execute();return{...N,items:X}}))}async function c(J){return await B.selectFrom("orders").where("id","=",J).selectAll().executeTakeFirst()}async function JJ(){let J=await B.selectFrom("orders").select(B.fn.count("id").as("count")).executeTakeFirst(),$=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).groupBy("status").execute(),G=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).groupBy("order_type").execute(),N=await B.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),X=await Promise.all(N.map(async(Z)=>{let L=await B.selectFrom("order_items").where("order_id","=",Z.id).selectAll().execute();return{...Z,items:L}})),W=await B.selectFrom("orders").select(B.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(J?.count||0),by_status:$,by_type:G,recent:X,revenue:Number(W?.total||0)}}async function GJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),Z=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",X.toISOString()).where("created_at","<=",N.toISOString()).executeTakeFirst(),L=Number(W?.count||0),Y=Number(Z?.count||0),K=L-Y,Q=Y!==0?K/Y*100:L>0?100:0;return{current_period:L,previous_period:Y,difference:K,percentage_change:Q,days_range:J}}async function NJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),Z=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",X.toISOString()).where("created_at","<=",N.toISOString()).executeTakeFirst(),L=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("status").execute(),Y=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("order_type").execute(),K=Number(W?.total_orders||0),Q=Number(W?.total_revenue||0),M=K>0?Q/K:0,H=Number(Z?.total_orders||0),_=Number(Z?.total_revenue||0),O=H>0?_/H:0,R=K-H,S=Q-_,m=M-O,r=H!==0?R/H*100:K>0?100:0,t=_!==0?S/_*100:Q>0?100:0,Y0=O!==0?m/O*100:M>0?100:0;return{current_period:{total_orders:K,total_revenue:Q,average_order_value:M,orders_by_status:L.map((p)=>({status:p.status,count:Number(p.count)})),orders_by_type:Y.map((p)=>({order_type:p.order_type,count:Number(p.count)}))},previous_period:{total_orders:H,total_revenue:_,average_order_value:O},comparison:{orders:{difference:R,percentage:Math.abs(r),is_increase:R>=0},revenue:{difference:S,percentage:Math.abs(t),is_increase:S>=0},average_order_value:{difference:m,percentage:Math.abs(Y0),is_increase:m>=0}},days_range:J}}async function XJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=await B.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).orderBy("created_at","asc").execute(),X=new Map;for(let W of N){let Z=(W.created_at||"").split("T")[0]||"unknown",L=X.get(Z)||{order_count:0,revenue:0};L.order_count++,L.revenue+=Number(W.total_amount||0),X.set(Z,L)}return Array.from(X.entries()).map(([W,Z])=>({date:W,order_count:Z.order_count,revenue:Z.revenue}))}var{randomUUIDv7:A9}=globalThis.Bun;import{db as WJ}from"@stacksjs/database";import{formatDate as ZJ}from"@stacksjs/orm";async function LJ(J){let $={...J,status:J.status||"PENDING",uuid:A9(),created_at:ZJ(new Date),updated_at:ZJ(new Date)};try{let G=await WJ.insertInto("orders").values($).executeTakeFirst(),N=Number(G?.insertId)||Number(G?.numInsertedOrUpdatedRows);if(N)return await WJ.selectFrom("orders").where("id","=",N).selectAll().executeTakeFirst();return}catch(G){if(G instanceof Error)throw Error(`Failed to create order: ${G.message}`);throw G}}M0();var{randomUUIDv7:QJ}=globalThis.Bun;import{db as L$}from"@stacksjs/database";import{formatDate as U9,isUniqueViolation as MJ}from"@stacksjs/orm";import{sqlHelpers as R9}from"@stacksjs/database";import{env as O9}from"@stacksjs/env";function S9(J,$,G,N){let X=R9(J).param;return{query:`UPDATE products
|
|
17
17
|
SET inventory_count = inventory_count + ${X(1)},
|
|
18
18
|
updated_at = ${X(2)}
|
|
19
19
|
WHERE id = ${X(3)}
|
|
20
|
-
AND inventory_count + ${X(4)} >= 0`,parameters:[G,N,$,G]}}async function FJ(J,$,G,N){let X=S9(O9.DB_CONNECTION||"sqlite",$,G,N),W=await J.unsafe(X.query,X.parameters),Z=typeof W?.execute==="function"?await W.execute():W;return F(Z)}var HJ=!1;function VJ(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function L$(J){try{let $=await Y$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await Y$.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(VJ($)){if(!HJ)HJ=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw $}}async function xJ(J){if(J.idempotencyKey){let $=await L$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await Y$.transaction(async(G)=>{let N=U9(new Date),X=QJ(),W={...J.order,status:J.order.status||"PENDING",uuid:X,created_at:N,updated_at:N};await G.insertInto("orders").values(W).executeTakeFirst();let Z=await G.selectFrom("orders").where("uuid","=",X).selectAll().executeTakeFirst(),Y=Number(Z?.id);if(!Number.isSafeInteger(Y)||Y<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let L;if(J.items&&J.items.length>0){let M=J.items.map((H)=>{if(!Number.isInteger(H.productId)||H.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(H.quantity)||H.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(H.price)||H.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:Y,product_id:H.productId,quantity:H.quantity,price:H.price,special_instructions:H.specialInstructions||null,created_at:N,updated_at:N}});await G.insertInto("order_items").values(M).execute(),L=await G.selectFrom("order_items").where("order_id","=",Y).selectAll().execute()}let K;if(J.payment)try{let M=QJ();if(await G.insertInto("payments").values({...J.payment,order_id:Y,uuid:M,created_at:N,updated_at:N}).executeTakeFirst(),K=await G.selectFrom("payments").where("uuid","=",M).selectAll().executeTakeFirst(),!K)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(M){if(MJ(M))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(M,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(J.inventory&&J.inventory.length>0)for(let M=0;M<J.inventory.length;M++){let{id:H,delta:_}=J.inventory[M];if(!Number.isFinite(_)||_===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await FJ(G,H,_,N))throw Object.assign(Error(`inventory adjust failed for product ${H}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:Y,created_at:N}).execute()}catch(M){if(MJ(M))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!VJ(M))throw M}let Q=await G.selectFrom("orders").where("id","=",Y).selectAll().executeTakeFirst();if(!Q)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:Q,items:L,payment:K}});if(w0($.order),$.payment)d($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&J.idempotencyKey){let G=await L$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}M0();import{db as _1}from"@stacksjs/database";import{formatDate as R1}from"@stacksjs/orm";M0();async function zJ(J,$){if(!await c(J))return;try{return await _1.updateTable("orders").set({...$,updated_at:R1(new Date)}).where("id","=",J).execute(),await c(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update order: ${N.message}`);throw N}}async function BJ(J,$){let G=await c(J);if(!G)throw Error(`Order with ID ${J} not found`);let N=G.status??"PENDING";if(!P0(N,$))throw Error(`[commerce/orders] illegal status transition ${N} \u2192 ${$}`);try{await _1.updateTable("orders").set({status:$,updated_at:R1(new Date)}).where("id","=",J).execute();let X=await c(J);if(X)q0($,X);return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order status: ${X.message}`);throw X}}async function AJ(J,$,G){let N=await c(J);if(!N)throw Error(`Order with ID ${J} not found`);let X={updated_at:R1(new Date)};if($!==void 0)X.delivery_address=$;if(G!==void 0)X.estimated_delivery_time=G;if(Object.keys(X).length===1)return N;try{return await _1.updateTable("orders").set(X).where("id","=",J).execute(),await c(J)}catch(W){if(W instanceof Error)throw TypeError(`Failed to update delivery information: ${W.message}`);throw W}}M0();import{db as H0}from"@stacksjs/database";import{formatDate as K$}from"@stacksjs/orm";async function O1(J){let $=await H0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await H0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var _J=!1;function T9(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function S1(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:K$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(T9(G)){if(!_J)_J=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw G}}async function U1(J){let G=J.data.object?.id;if(!G)return;await H0.transaction(async(X)=>{if(!await S1(J.id,X))return;let Z=await X.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Z)return;let Y=K$(new Date);await X.updateTable("payments").set({status:"succeeded",updated_at:Y}).where("id","=",Z.id).execute();let L=await X.selectFrom("orders").where("id","=",Z.order_id).selectAll().executeTakeFirst();if(L&&L.status==="PENDING")await X.updateTable("orders").set({status:"PROCESSING",updated_at:Y}).where("id","=",L.id).execute()});let N=await O1(G);if(N)await d(N)}async function T1(J){let $=J.data.object,G=$?.id;if(!G)return;let X=$?.last_payment_error?.message??"payment failed";await H0.transaction(async(Z)=>{if(!await S1(J.id,Z))return;let L=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let K=K$(new Date);await Z.updateTable("payments").set({status:"failed",failure_reason:X,updated_at:K}).where("id","=",L.id).execute();let Q=await Z.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(Q&&Q.status==="PENDING")await Z.updateTable("orders").set({status:"CANCELLED",updated_at:K}).where("id","=",Q.id).execute()});let W=await O1(G);if(W)await F0(W,X)}async function P1(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let N=$?.amount_refunded??0;await H0.transaction(async(W)=>{if(!await S1(J.id,W))return;let Y=await W.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Y)return;let L=K$(new Date);await W.updateTable("payments").set({status:"refunded",refund_amount:N,updated_at:L}).where("id","=",Y.id).execute();let K=await W.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(K&&K.status!=="REFUNDED")await W.updateTable("orders").set({status:"REFUNDED",updated_at:L}).where("id","=",K.id).execute()});let X=await O1(G);if(X)await Q0(X,N)}async function RJ(){let J=await import("@stacksjs/payments").catch(()=>null);if(!J)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:G}=J;if(typeof $!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:U1,failed:T1}),G({refunded:P1}),()=>{}}import{db as OJ}from"@stacksjs/database";async function P9(J){if(J.length===0)return new Map;let $=await OJ.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),G=new Map;for(let N of $){let X=Number(N.price);if(Number.isFinite(X))G.set(N.id,Math.round(X))}return G}async function w9(J){try{let $=await OJ.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),G=Number($?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function SJ(J){let $=J.items.map((O)=>O.productId),G=await P9($),N=J.taxRateId!=null?await w9(J.taxRateId):0,X=0,W=[];for(let O of J.items){let R=O.unitPriceCents??G.get(O.productId)??0,S=Math.round(R*O.quantity);X+=S,W.push({productId:O.productId,quantity:O.quantity,unitPriceCents:R,lineCents:S})}let Z=Math.max(0,J.discountCents??0),Y=Math.max(0,X-Z),L=Math.round(Y*N),K=Math.max(0,J.shippingCents??0),Q=X-Z+L+K,M=J.maxDriftCents??5,H=!1,_=0;if(J.clientTotalCents!=null)_=Math.abs(Q-J.clientTotalCents),H=_>M;return{subtotalCents:X,discountCents:Z,taxCents:L,shippingCents:K,totalCents:Q,resolvedItems:W,priceChanged:H,diffCents:_}}import{db as F$}from"@stacksjs/database";function UJ(J,$={}){let G=J.length;if(G<=1)return{ok:!0,count:G};if(!$.allowMultiple)return{ok:!1,count:G,reason:"multiple-not-allowed"};let N=$.maxStacked??Number.POSITIVE_INFINITY;if(G>N)return{ok:!1,count:G,reason:"exceeds-max-stacked"};return{ok:!0,count:G}}async function w1(J,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:J,quantity:$,reason:"non-positive"};let G;try{G=await F$.selectFrom("products").where("id","=",J).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:J,quantity:$}}if(!G)return{ok:!1,productId:J,quantity:$,reason:"product-missing"};let N=G.min_order_qty??null,X=G.max_order_qty??null;if(N!=null&&$<N)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:N};if(X!=null&&$>X)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:X};return{ok:!0,productId:J,quantity:$}}async function TJ(J){for(let G of J){let N=await w1(G.productId,G.quantity);if(!N.ok)return N}let $=J[J.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function PJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,X=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let W=await F$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[X,X,G]),Z=typeof W?.execute==="function"?await W.execute():W;return{deleted:Number(Z?.changes??Z?.numDeletedRows??Z?.[0]?.numDeletedRows??Z?.affectedRows??0),cutoffAt:X}}catch{try{let W=await F$.selectFrom("carts").where("updated_at","<",X).select(["id"]).limit(G).execute();if(W.length===0)return{deleted:0,cutoffAt:X};let Z=W.map((K)=>K.id),Y=await F$.deleteFrom("carts").where("id","in",Z).execute();return{deleted:Number(Y?.numDeletedRows??Y?.[0]?.numDeletedRows??Y?.affectedRows??W.length),cutoffAt:X}}catch{return{deleted:0,cutoffAt:X}}}}var f1={};z(f1,{update:()=>DJ,store:()=>gJ,recordRefund:()=>bJ,fetchPaymentStatsByMethod:()=>jJ,fetchPaymentStats:()=>kJ,fetchMonthlyPaymentTrends:()=>CJ,fetchById:()=>N0,fetchAll:()=>EJ,destroy:()=>qJ,bulkDestroy:()=>fJ});import{db as wJ}from"@stacksjs/database";async function qJ(J){try{let $=await wJ.deleteFrom("payments").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function fJ(J){if(!J.length)return 0;try{let $=await wJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as f}from"@stacksjs/database";import{formatDate as v}from"@stacksjs/orm";async function EJ(){return await f.selectFrom("payments").selectAll().execute()}async function N0(J){return await f.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function kJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await f.selectFrom("payments").select([f.fn.count("id").as("transaction_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),Z=await f.selectFrom("payments").select([f.fn.count("id").as("transaction_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(X)).where("created_at","<=",v(N)).where("status","=","completed").executeTakeFirst(),Y=await f.selectFrom("payments").select(f.fn.count("id").as("count")).where("created_at",">=",v(G)).where("created_at","<=",v($)).executeTakeFirst(),L=Number(W?.transaction_count||0),K=Number(W?.total_revenue||0),Q=L>0?K/L:0,M=Number(Z?.transaction_count||0),H=Number(Z?.total_revenue||0),_=M>0?H/M:0,O=L-M,R=K-H,S=Q-_,m=M>0?O/M*100:L>0?100:0,r=H>0?R/H*100:K>0?100:0,t=_>0?S/_*100:Q>0?100:0,L0=Number(Y?.count||0),p=L0>0?L/L0*100:0;return{total_transactions:L,total_revenue:K,average_transaction:Q,successful_rate:p,comparison:{transactions:{difference:O,percentage:Math.abs(m),is_increase:O>=0},revenue:{difference:R,percentage:Math.abs(r),is_increase:R>=0},average:{difference:S,percentage:Math.abs(t),is_increase:S>=0}}}}async function jJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=await f.selectFrom("payments").select([f.fn.count("id").as("total_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),X=Number(N?.total_count||0),W=await f.selectFrom("payments").select(["method",f.fn.count("id").as("count"),f.fn.sum("amount").as("revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").groupBy("method").execute(),Z={};return W.forEach((Y)=>{let L=Number(Y.count||0),K=Number(Y.revenue||0),Q=X>0?L/X*100:0;Z[Y.method]={count:L,revenue:K,percentage_of_total:Q}}),Z}async function CJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await f.selectFrom("payments").selectAll().where("created_at",">=",v($)).where("status","=","completed").execute(),N={};for(let W of G){let Z=W.created_at?new Date(W.created_at):new Date,Y=Z.getFullYear(),L=Z.getMonth()+1,K=`${Y}-${String(L).padStart(2,"0")}`;if(!N[K])N[K]={year:Y,month:L,transactions:0,revenue:0};N[K].transactions++,N[K].revenue+=Number(W.amount||0)}return Object.keys(N).sort().map((W)=>{let Z=N[W],Y=Z.transactions,L=Z.revenue,K=Y>0?L/Y:0;return{month:new Date(Z.year,Z.month-1,1).toLocaleString("default",{month:"short"}),year:Z.year,transactions:Y,revenue:L,average:K}})}var{randomUUIDv7:q9}=globalThis.Bun;import{db as hJ}from"@stacksjs/database";import{HttpError as IJ}from"@stacksjs/error-handling";import{isUniqueViolation as f9}from"@stacksjs/orm";async function gJ(J){let $=q9(),G={...J,status:J.status||"pending",currency:J.currency||"USD",uuid:$};try{return await hJ.insertInto("payments").values(G).executeTakeFirst(),await hJ.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(N){if(N instanceof IJ)throw N;if(f9(N))throw new IJ(409,"A payment with this transaction ID already exists");if(N instanceof Error){if(N.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${N.message}`)}throw N}}import{db as vJ,sqlHelpers as E9}from"@stacksjs/database";import{env as k9}from"@stacksjs/env";import{formatDate as yJ}from"@stacksjs/orm";async function DJ(J,$){if(!await N0(J))return;try{return await vJ.updateTable("payments").set({...$,updated_at:yJ(new Date)}).where("id","=",J).execute(),await N0(J)}catch(N){if(N instanceof Error){if(N.message.includes("Duplicate entry")&&N.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${N.message}`)}throw N}}var j9=new Set(["completed","succeeded","partiallyRefunded"]);async function bJ(J,$){if(!Number.isSafeInteger(J)||J<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger($)||$<=0)throw TypeError("Refund amount must be a positive integer in minor units");let N=E9(k9.DB_CONNECTION||"sqlite").param,X=yJ(new Date),W=await vJ.unsafe(`UPDATE payments
|
|
20
|
+
AND inventory_count + ${X(4)} >= 0`,parameters:[G,N,$,G]}}async function FJ(J,$,G,N){let X=S9(O9.DB_CONNECTION||"sqlite",$,G,N),W=await J.unsafe(X.query,X.parameters),Z=typeof W?.execute==="function"?await W.execute():W;return F(Z)}var HJ=!1;function xJ(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 Y$(J){try{let $=await L$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await L$.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(xJ($)){if(!HJ)HJ=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw $}}async function VJ(J){if(J.idempotencyKey){let $=await Y$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await L$.transaction(async(G)=>{let N=U9(new Date),X=QJ(),W={...J.order,status:J.order.status||"PENDING",uuid:X,created_at:N,updated_at:N};await G.insertInto("orders").values(W).executeTakeFirst();let Z=await G.selectFrom("orders").where("uuid","=",X).selectAll().executeTakeFirst(),L=Number(Z?.id);if(!Number.isSafeInteger(L)||L<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let Y;if(J.items&&J.items.length>0){let M=J.items.map((H)=>{if(!Number.isInteger(H.productId)||H.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(H.quantity)||H.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(H.price)||H.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:L,product_id:H.productId,quantity:H.quantity,price:H.price,special_instructions:H.specialInstructions||null,created_at:N,updated_at:N}});await G.insertInto("order_items").values(M).execute(),Y=await G.selectFrom("order_items").where("order_id","=",L).selectAll().execute()}let K;if(J.payment)try{let M=QJ();if(await G.insertInto("payments").values({...J.payment,order_id:L,uuid:M,created_at:N,updated_at:N}).executeTakeFirst(),K=await G.selectFrom("payments").where("uuid","=",M).selectAll().executeTakeFirst(),!K)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(M){if(MJ(M))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(M,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(J.inventory&&J.inventory.length>0)for(let M=0;M<J.inventory.length;M++){let{id:H,delta:_}=J.inventory[M];if(!Number.isFinite(_)||_===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await FJ(G,H,_,N))throw Object.assign(Error(`inventory adjust failed for product ${H}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:L,created_at:N}).execute()}catch(M){if(MJ(M))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!xJ(M))throw M}let Q=await G.selectFrom("orders").where("id","=",L).selectAll().executeTakeFirst();if(!Q)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:Q,items:Y,payment:K}});if(T0($.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 Y$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}M0();import{db as _1}from"@stacksjs/database";import{formatDate as R1}from"@stacksjs/orm";M0();async function zJ(J,$){if(!await c(J))return;try{return await _1.updateTable("orders").set({...$,updated_at:R1(new Date)}).where("id","=",J).execute(),await c(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update order: ${N.message}`);throw N}}async function BJ(J,$){let G=await c(J);if(!G)throw Error(`Order with ID ${J} not found`);let N=G.status??"PENDING";if(!q0(N,$))throw Error(`[commerce/orders] illegal status transition ${N} \u2192 ${$}`);try{await _1.updateTable("orders").set({status:$,updated_at:R1(new Date)}).where("id","=",J).execute();let X=await c(J);if(X)E0($,X);return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order status: ${X.message}`);throw X}}async function AJ(J,$,G){let N=await c(J);if(!N)throw Error(`Order with ID ${J} not found`);let X={updated_at:R1(new Date)};if($!==void 0)X.delivery_address=$;if(G!==void 0)X.estimated_delivery_time=G;if(Object.keys(X).length===1)return N;try{return await _1.updateTable("orders").set(X).where("id","=",J).execute(),await c(J)}catch(W){if(W instanceof Error)throw TypeError(`Failed to update delivery information: ${W.message}`);throw W}}M0();import{db as H0}from"@stacksjs/database";import{formatDate as K$}from"@stacksjs/orm";async function O1(J){let $=await H0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await H0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var _J=!1;function w9(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function S1(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:K$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(w9(G)){if(!_J)_J=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw G}}async function U1(J){let G=J.data.object?.id;if(!G)return;await H0.transaction(async(X)=>{if(!await S1(J.id,X))return;let Z=await X.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Z)return;let L=K$(new Date);await X.updateTable("payments").set({status:"succeeded",updated_at:L}).where("id","=",Z.id).execute();let Y=await X.selectFrom("orders").where("id","=",Z.order_id).selectAll().executeTakeFirst();if(Y&&Y.status==="PENDING")await X.updateTable("orders").set({status:"PROCESSING",updated_at:L}).where("id","=",Y.id).execute()});let N=await O1(G);if(N)await d(N)}async function w1(J){let $=J.data.object,G=$?.id;if(!G)return;let X=$?.last_payment_error?.message??"payment failed";await H0.transaction(async(Z)=>{if(!await S1(J.id,Z))return;let Y=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Y)return;let K=K$(new Date);await Z.updateTable("payments").set({status:"failed",failure_reason:X,updated_at:K}).where("id","=",Y.id).execute();let Q=await Z.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(Q&&Q.status==="PENDING")await Z.updateTable("orders").set({status:"CANCELLED",updated_at:K}).where("id","=",Q.id).execute()});let W=await O1(G);if(W)await F0(W,X)}async function P1(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let N=$?.amount_refunded??0;await H0.transaction(async(W)=>{if(!await S1(J.id,W))return;let L=await W.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let Y=K$(new Date);await W.updateTable("payments").set({status:"refunded",refund_amount:N,updated_at:Y}).where("id","=",L.id).execute();let K=await W.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(K&&K.status!=="REFUNDED")await W.updateTable("orders").set({status:"REFUNDED",updated_at:Y}).where("id","=",K.id).execute()});let X=await O1(G);if(X)await Q0(X,N)}async function RJ(){let J=await import("@stacksjs/payments").catch(()=>null);if(!J)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:G}=J;if(typeof $!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:U1,failed:w1}),G({refunded:P1}),()=>{}}import{db as OJ}from"@stacksjs/database";async function P9(J){if(J.length===0)return new Map;let $=await OJ.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),G=new Map;for(let N of $){let X=Number(N.price);if(Number.isFinite(X))G.set(N.id,Math.round(X))}return G}async function q9(J){try{let $=await OJ.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),G=Number($?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function SJ(J){let $=J.items.map((O)=>O.productId),G=await P9($),N=J.taxRateId!=null?await q9(J.taxRateId):0,X=0,W=[];for(let O of J.items){let R=O.unitPriceCents??G.get(O.productId)??0,S=Math.round(R*O.quantity);X+=S,W.push({productId:O.productId,quantity:O.quantity,unitPriceCents:R,lineCents:S})}let Z=Math.max(0,J.discountCents??0),L=Math.max(0,X-Z),Y=Math.round(L*N),K=Math.max(0,J.shippingCents??0),Q=X-Z+Y+K,M=J.maxDriftCents??5,H=!1,_=0;if(J.clientTotalCents!=null)_=Math.abs(Q-J.clientTotalCents),H=_>M;return{subtotalCents:X,discountCents:Z,taxCents:Y,shippingCents:K,totalCents:Q,resolvedItems:W,priceChanged:H,diffCents:_}}import{db as F$}from"@stacksjs/database";function UJ(J,$={}){let G=J.length;if(G<=1)return{ok:!0,count:G};if(!$.allowMultiple)return{ok:!1,count:G,reason:"multiple-not-allowed"};let N=$.maxStacked??Number.POSITIVE_INFINITY;if(G>N)return{ok:!1,count:G,reason:"exceeds-max-stacked"};return{ok:!0,count:G}}async function q1(J,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:J,quantity:$,reason:"non-positive"};let G;try{G=await F$.selectFrom("products").where("id","=",J).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:J,quantity:$}}if(!G)return{ok:!1,productId:J,quantity:$,reason:"product-missing"};let N=G.min_order_qty??null,X=G.max_order_qty??null;if(N!=null&&$<N)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:N};if(X!=null&&$>X)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:X};return{ok:!0,productId:J,quantity:$}}async function wJ(J){for(let G of J){let N=await q1(G.productId,G.quantity);if(!N.ok)return N}let $=J[J.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function PJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,X=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let W=await F$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[X,X,G]),Z=typeof W?.execute==="function"?await W.execute():W;return{deleted:Number(Z?.changes??Z?.numDeletedRows??Z?.[0]?.numDeletedRows??Z?.affectedRows??0),cutoffAt:X}}catch{try{let W=await F$.selectFrom("carts").where("updated_at","<",X).select(["id"]).limit(G).execute();if(W.length===0)return{deleted:0,cutoffAt:X};let Z=W.map((K)=>K.id),L=await F$.deleteFrom("carts").where("id","in",Z).execute();return{deleted:Number(L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??W.length),cutoffAt:X}}catch{return{deleted:0,cutoffAt:X}}}}var E1={};z(E1,{update:()=>DJ,store:()=>gJ,recordRefund:()=>bJ,fetchPaymentStatsByMethod:()=>jJ,fetchPaymentStats:()=>kJ,fetchMonthlyPaymentTrends:()=>CJ,fetchById:()=>N0,fetchAll:()=>fJ,destroy:()=>TJ,bulkDestroy:()=>EJ});import{db as qJ}from"@stacksjs/database";async function TJ(J){try{let $=await qJ.deleteFrom("payments").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function EJ(J){if(!J.length)return 0;try{let $=await qJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as f}from"@stacksjs/database";import{formatDate as v}from"@stacksjs/orm";async function fJ(){return await f.selectFrom("payments").selectAll().execute()}async function N0(J){return await f.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function kJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await f.selectFrom("payments").select([f.fn.count("id").as("transaction_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),Z=await f.selectFrom("payments").select([f.fn.count("id").as("transaction_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(X)).where("created_at","<=",v(N)).where("status","=","completed").executeTakeFirst(),L=await f.selectFrom("payments").select(f.fn.count("id").as("count")).where("created_at",">=",v(G)).where("created_at","<=",v($)).executeTakeFirst(),Y=Number(W?.transaction_count||0),K=Number(W?.total_revenue||0),Q=Y>0?K/Y:0,M=Number(Z?.transaction_count||0),H=Number(Z?.total_revenue||0),_=M>0?H/M:0,O=Y-M,R=K-H,S=Q-_,m=M>0?O/M*100:Y>0?100:0,r=H>0?R/H*100:K>0?100:0,t=_>0?S/_*100:Q>0?100:0,Y0=Number(L?.count||0),p=Y0>0?Y/Y0*100:0;return{total_transactions:Y,total_revenue:K,average_transaction:Q,successful_rate:p,comparison:{transactions:{difference:O,percentage:Math.abs(m),is_increase:O>=0},revenue:{difference:R,percentage:Math.abs(r),is_increase:R>=0},average:{difference:S,percentage:Math.abs(t),is_increase:S>=0}}}}async function jJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=await f.selectFrom("payments").select([f.fn.count("id").as("total_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),X=Number(N?.total_count||0),W=await f.selectFrom("payments").select(["method",f.fn.count("id").as("count"),f.fn.sum("amount").as("revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").groupBy("method").execute(),Z={};return W.forEach((L)=>{let Y=Number(L.count||0),K=Number(L.revenue||0),Q=X>0?Y/X*100:0;Z[L.method]={count:Y,revenue:K,percentage_of_total:Q}}),Z}async function CJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await f.selectFrom("payments").selectAll().where("created_at",">=",v($)).where("status","=","completed").execute(),N={};for(let W of G){let Z=W.created_at?new Date(W.created_at):new Date,L=Z.getFullYear(),Y=Z.getMonth()+1,K=`${L}-${String(Y).padStart(2,"0")}`;if(!N[K])N[K]={year:L,month:Y,transactions:0,revenue:0};N[K].transactions++,N[K].revenue+=Number(W.amount||0)}return Object.keys(N).sort().map((W)=>{let Z=N[W],L=Z.transactions,Y=Z.revenue,K=L>0?Y/L:0;return{month:new Date(Z.year,Z.month-1,1).toLocaleString("default",{month:"short"}),year:Z.year,transactions:L,revenue:Y,average:K}})}var{randomUUIDv7:T9}=globalThis.Bun;import{db as hJ}from"@stacksjs/database";import{HttpError as IJ}from"@stacksjs/error-handling";import{isUniqueViolation as E9}from"@stacksjs/orm";async function gJ(J){let $=T9(),G={...J,status:J.status||"pending",currency:J.currency||"USD",uuid:$};try{return await hJ.insertInto("payments").values(G).executeTakeFirst(),await hJ.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(N){if(N instanceof IJ)throw N;if(E9(N))throw new IJ(409,"A payment with this transaction ID already exists");if(N instanceof Error){if(N.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${N.message}`)}throw N}}import{db as vJ,sqlHelpers as f9}from"@stacksjs/database";import{env as k9}from"@stacksjs/env";import{formatDate as yJ}from"@stacksjs/orm";async function DJ(J,$){if(!await N0(J))return;try{return await vJ.updateTable("payments").set({...$,updated_at:yJ(new Date)}).where("id","=",J).execute(),await N0(J)}catch(N){if(N instanceof Error){if(N.message.includes("Duplicate entry")&&N.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${N.message}`)}throw N}}var j9=new Set(["completed","succeeded","partiallyRefunded"]);async function bJ(J,$){if(!Number.isSafeInteger(J)||J<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger($)||$<=0)throw TypeError("Refund amount must be a positive integer in minor units");let N=f9(k9.DB_CONNECTION||"sqlite").param,X=yJ(new Date),W=await vJ.unsafe(`UPDATE payments
|
|
21
21
|
SET refund_amount = COALESCE(refund_amount, 0) + ${N(1)},
|
|
22
22
|
status = CASE WHEN COALESCE(refund_amount, 0) + ${N(2)} = amount
|
|
23
23
|
THEN 'refunded' ELSE 'partiallyRefunded' END,
|
|
24
24
|
updated_at = ${N(3)}
|
|
25
25
|
WHERE id = ${N(4)}
|
|
26
26
|
AND status IN ('completed', 'succeeded', 'partiallyRefunded')
|
|
27
|
-
AND COALESCE(refund_amount, 0) + ${N(5)} <= amount`,[$,$,X,J,$]),Z=typeof W?.execute==="function"?await W.execute():W;if(Number(Z?.numUpdatedRows??Z?.[0]?.numUpdatedRows??Z?.numAffectedRows??Z?.affectedRows??Z?.[0]?.affectedRows??Z?.changes??0)>0){let H=await N0(J);if(H)return H;throw Error(`Payment with ID ${J} disappeared during refund`)}let L=await N0(J);if(!L)throw Error(`Payment with ID ${J} not found`);let K=String(L.status||"");if(!j9.has(K))throw Error(`Payment status ${K||"unknown"} cannot be refunded`);let Q=L,M=Number(L.amount||0)-Number(Q.refundAmount??Q.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${M} minor units`)}var g1={};z(g1,{variants:()=>R$,units:()=>_$,reviews:()=>z$,manufacturers:()=>x$,items:()=>V$,default:()=>l9,categories:()=>H$});var H$={};z(H$,{updateParent:()=>X6,updateDisplayOrder:()=>G6,updateActiveStatus:()=>N6,update:()=>J6,store:()=>k1,removeChildCategories:()=>aJ,remove:()=>sJ,findOrCreateByName:()=>$6,fetchStats:()=>nJ,fetchRootCategories:()=>lJ,fetchChildCategories:()=>cJ,fetchCategoryTree:()=>oJ,fetchByName:()=>mJ,fetchById:()=>E,fetchByDisplayOrder:()=>uJ,fetchAll:()=>E1,fetchActive:()=>pJ,deactivateChildCategories:()=>rJ,deactivate:()=>eJ,compareCategoryGrowth:()=>iJ,bulkRemove:()=>dJ});import{db as V0}from"@stacksjs/database";import{db as T}from"@stacksjs/database";import{formatDate as f0}from"@stacksjs/orm";async function E1(){return await T.selectFrom("categories").selectAll().execute()}async function E(J){return await T.selectFrom("categories").where("id","=",J).selectAll().executeTakeFirst()}async function mJ(J){return await T.selectFrom("categories").where("name","=",J).selectAll().executeTakeFirst()}async function pJ(){return await T.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function lJ(){return await T.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function cJ(J){return await T.selectFrom("categories").where("parent_category_id","=",J).where("is_active","=",!0).selectAll().execute()}async function uJ(J=!0){let $=T.selectFrom("categories").where("is_active","=",!0).selectAll();if(J)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function nJ(){let J=await T.selectFrom("categories").select(T.fn.count("id").as("count")).executeTakeFirst(),$=await T.selectFrom("categories").where("is_active","=",!0).select(T.fn.count("id").as("count")).executeTakeFirst(),G=await T.selectFrom("categories").whereNull("parent_category_id").select(T.fn.count("id").as("count")).executeTakeFirst(),N=await T.selectFrom("categories").whereNotNull("image_url").select(T.fn.count("id").as("count")).executeTakeFirst(),X=new Date;X.setDate(X.getDate()-30);let W=f0(X),Z=await T.selectFrom("categories").where("created_at",">=",W).selectAll().limit(5).execute(),Y=await T.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",T.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number($?.count||0),root_categories:Number(G?.count||0),child_categories:Number(J?.count||0)-Number(G?.count||0),with_images:Number(N?.count||0),recently_added:Z,top_parent_categories:Y.map((L)=>({id:String(L.parent_category_id||""),name:String(L.parent_name||""),child_count:Number(L.child_count)}))}}async function iJ(J=30){let $=new Date,G=f0($),N=new Date;N.setDate($.getDate()-J);let X=f0(N),W=new Date(N);W.setDate(W.getDate()-1);let Z=f0(W),Y=new Date(W);Y.setDate(W.getDate()-J);let L=f0(Y),K=await T.selectFrom("categories").select(T.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",G).executeTakeFirst(),Q=await T.selectFrom("categories").select(T.fn.count("id").as("count")).where("created_at",">=",L).where("created_at","<=",Z).executeTakeFirst(),M=Number(K?.count||0),H=Number(Q?.count||0),_=M-H,O=H!==0?_/H*100:M>0?100:0;return{current_period:M,previous_period:H,difference:_,percentage_change:O,days_range:J}}async function oJ(){let J=await E1(),$=new Map;J.forEach((X)=>{$.set(X.id,{...X,children:[]})});let G=[];J.forEach((X)=>{let W=$.get(X.id);if(X.parent_category_id){let Z=$.get(X.parent_category_id);if(Z)Z.children.push(W)}else G.push(W)}),G.sort((X,W)=>X.display_order-W.display_order);let N=(X)=>{X.sort((W,Z)=>W.display_order-Z.display_order),X.forEach((W)=>{if(W.children.length>0)N(W.children)})};return N(G),G}async function sJ(J){let $=await V0.deleteFrom("categories").where("id","=",J).executeTakeFirst();return F($)>0}async function dJ(J){if(!J.length)return 0;let $=await V0.deleteFrom("categories").where("id","in",J).executeTakeFirst();return F($)}async function aJ(J){let $=await V0.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return F($)}async function eJ(J){if(!await E(J))throw Error(`Category with ID ${J} not found`);return!!await V0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",J).executeTakeFirst()}async function rJ(J){let $=await V0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",J).execute();return Number($.length)||0}var{randomUUIDv7:C9}=globalThis.Bun;import{db as tJ}from"@stacksjs/database";import{HttpError as Q$}from"@stacksjs/error-handling";import{isUniqueViolation as h9}from"@stacksjs/orm";import{slug as I9}from"@stacksjs/strings";async function k1(J){try{let $=J.parent_category_id?Number(J.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new Q$(422,"Parent category ID must be a positive integer");if($&&!await E($))throw new Q$(422,`Parent category with ID ${J.parent_category_id} not found`);let G={...J,uuid:C9(),is_active:J.is_active??!0,parent_category_id:J.parent_category_id||null},N=await tJ.insertInto("categories").values(G).returningAll().executeTakeFirst();if(!N)throw Error("Failed to create category");return N}catch($){if($ instanceof Q$)throw $;if(h9($))throw new Q$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function $6(J){if(!J.name)throw Error("Name is required");let $=await tJ.selectFrom("categories").selectAll().where("name","=",J.name).executeTakeFirst();if($)return $;let G={name:J.name,slug:I9(J.name),is_active:J.is_active??!0,display_order:0};return await k1(G)}import{db as E0}from"@stacksjs/database";import{HttpError as x0}from"@stacksjs/error-handling";import{formatDate as M$,isUniqueViolation as g9}from"@stacksjs/orm";async function J6(J,$){if(!await E(J))return;if(Object.hasOwn($,"parent_category_id")){let N=$.parent_category_id?Number($.parent_category_id):void 0;if(N!==void 0&&(!Number.isSafeInteger(N)||N<=0))throw new x0(422,"Parent category ID must be a positive integer");if(N===J)throw new x0(422,"A category cannot be its own parent");if(N&&!await E(N))throw new x0(422,`Parent category with ID ${$.parent_category_id} not found`);if(N&&await W6(J,String(N)))throw new x0(422,"This operation would create a circular category hierarchy")}try{let N=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},X=await E0.updateTable("categories").set({...$,...N,updated_at:M$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)return;return X}catch(N){if(N instanceof x0)throw N;if(g9(N))throw new x0(409,"A category with this name or slug already exists");if(N instanceof Error)throw Error(`Failed to update category: ${N.message}`);throw N}}async function G6(J,$){if(!await E(J))throw Error(`Category with ID ${J} not found`);try{return await E0.updateTable("categories").set({display_order:$,updated_at:M$(new Date)}).where("id","=",J).execute(),await E(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update category display order: ${N.message}`);throw N}}async function N6(J,$){if(!await E(J))throw Error(`Category with ID ${J} not found`);try{return await E0.updateTable("categories").set({is_active:$,updated_at:M$(new Date)}).where("id","=",J).execute(),await E(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update category active status: ${N.message}`);throw N}}async function X6(J,$){if(!await E(J))throw Error(`Category with ID ${J} not found`);if($){let N=Number($);if(N===J)throw Error("A category cannot be its own parent");if(!await E(N))throw Error(`Parent category with ID ${$} not found`);if(await W6(J,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let N={updated_at:M$(new Date)};if($===null)await E0.updateTable("categories").set({...N,parent_category_id:null}).where("id","=",J).execute();else await E0.updateTable("categories").set({...N,parent_category_id:$}).where("id","=",J).execute();return await E(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update category parent: ${N.message}`);throw N}}async function W6(J,$){let G=Number($),N=new Set;while(G){if(N.has(G))return!0;if(G===J)return!0;N.add(G);let X=await E(G),W=X?.parent_category_id??X?.parentCategoryId;if(!X||!W)return!1;G=Number(W)}return!1}var V$={};z(V$,{updateInventory:()=>B6,updateAvailability:()=>z6,update:()=>x6,store:()=>H6,fetchTopProducts:()=>F6,fetchById:()=>u,fetchAll:()=>K6,destroy:()=>Y6,bulkStore:()=>V6,bulkDestroy:()=>L6});import{db as Z6}from"@stacksjs/database";async function Y6(J){try{let $=await Z6.deleteFrom("products").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function L6(J){if(!J.length)return 0;try{let $=await Z6.deleteFrom("products").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as a,sql as v9}from"@stacksjs/database";async function u(J){let $=await a.selectFrom("products").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,N=null;if($.manufacturer_id)G=await a.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)N=await a.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:G,category:N}}return}async function K6(){let J=await a.selectFrom("products").selectAll().execute(),$=J.map((K)=>K.manufacturer_id).filter((K)=>K!==null&&K!==void 0),G=J.map((K)=>K.category_id).filter((K)=>K!==null&&K!==void 0),N=a.selectFrom("manufacturers"),X=a.selectFrom("categories");if($.length>0)N=N.where("id","in",$);if(G.length>0)X=X.where("id","in",G);let W=await N.selectAll().execute(),Z=await X.selectAll().execute(),Y=W.reduce((K,Q)=>{return K[Q.id]=Q,K},{}),L=Z.reduce((K,Q)=>{return K[Q.id]=Q,K},{});return J.map((K)=>({...K,manufacturer:K.manufacturer_id?Y[K.manufacturer_id]:null,category:K.category_id?L[K.category_id]:null}))}async function F6(J=5){try{return(await a.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",a.fn.sum("order_items.quantity").as("units_sold"),v9`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(J).execute()).map((G)=>({id:Number(G.id),name:String(G.name??"Unnamed product"),units_sold:Number(G.units_sold??0),revenue:Number(G.revenue??0),inventory_count:Number(G.inventory_count??0)}))}catch($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:Q6}=globalThis.Bun;import{db as M6}from"@stacksjs/database";async function H6(J){try{let $={...J,uuid:Q6()},G=await M6.insertInto("products").values($).executeTakeFirst();if(!G)throw Error("Failed to create product item");let N=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),X=await u(N);if(!X)throw Error("Failed to create product item");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function V6(J){if(!J.length)return 0;let $=0;try{return await M6.transaction().execute(async(G)=>{for(let N of J){let X={...N,uuid:Q6()};await G.insertInto("products").values(X).execute(),$++}}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as j1}from"@stacksjs/database";import{formatDate as C1}from"@stacksjs/orm";async function x6(J,$){try{if(!J)throw Error("Product item ID is required for update");let G=await j1.updateTable("products").set({...$,updated_at:C1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item: ${G.message}`);throw G}}async function z6(J,$){if(!await u(J))throw Error(`Product item with ID ${J} not found`);try{return await j1.updateTable("products").set({is_available:$,updated_at:C1(new Date)}).where("id","=",J).execute(),await u(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update product item availability: ${N.message}`);throw N}}async function B6(J,$){let G=await u(J);if(!G)throw Error(`Product item with ID ${J} not found`);let N={updated_at:C1(new Date)};if($!==void 0)N.inventory_count=$;if(Object.keys(N).length===1)return G;try{return await j1.updateTable("products").set(N).where("id","=",J).execute(),await u(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update inventory information: ${X.message}`);throw X}}var x$={};z(x$,{updateFeaturedStatus:()=>I6,updateByUuid:()=>g6,update:()=>h6,store:()=>k6,fetchWithProductCount:()=>w6,fetchFeatured:()=>T6,fetchByUuid:()=>U6,fetchById:()=>S6,fetchByCountry:()=>P6,fetchAll:()=>O6,destroy:()=>_6,bulkStore:()=>j6,bulkDestroy:()=>R6});import{db as A6}from"@stacksjs/database";async function _6(J){try{let $=await A6.deleteFrom("manufacturers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function R6(J){if(!J.length)return 0;try{let $=await A6.deleteFrom("manufacturers").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as n}from"@stacksjs/database";function O6(){return n.selectFrom("manufacturers").selectAll().execute()}async function S6(J){return await n.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function U6(J){return await n.selectFrom("manufacturers").where("uuid","=",J).selectAll().executeTakeFirst()}async function T6(J=10){return await n.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(J).execute()}async function P6(J,$={}){let G=$.page||1,N=$.limit||2,X=await n.selectFrom("manufacturers").select(n.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),W=Number(X?.total||0),Z=await n.selectFrom("manufacturers").selectAll().where("country","=",J).limit(N).offset((G-1)*N).execute(),Y=Math.ceil(W/N);return{data:Z,paging:{total_records:W,page:G,total_pages:Y},next_cursor:G<Y?G+1:null}}async function w6(J={}){let $=n.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(J.country)$=$.where("m.country","=",J.country);if(J.featured!==void 0)$=$.where("m.featured","=",J.featured);return $=$.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",n.fn.count("p.id").as("product_count")]).groupBy("m.id"),$.execute()}var{randomUUIDv7:f6}=globalThis.Bun;import{db as E6}from"@stacksjs/database";import{HttpError as q6}from"@stacksjs/error-handling";import{isUniqueViolation as y9}from"@stacksjs/orm";async function k6(J){try{let $={...J,uuid:f6(),featured:J.featured??!1},G=await E6.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch($){if($ instanceof q6)throw $;if(y9($))throw new q6(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function j6(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={...G,uuid:f6(),featured:G.featured??!1};await E6.insertInto("manufacturers").values(N).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${G.message}`);throw G}}import{db as h1}from"@stacksjs/database";import{HttpError as C6}from"@stacksjs/error-handling";import{formatDate as I1,isUniqueViolation as D9}from"@stacksjs/orm";async function h6(J,$){try{if(!J)throw Error("Manufacturer ID is required for update");let G=await h1.updateTable("manufacturers").set({...$,updated_at:I1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof C6)throw G;if(D9(G))throw new C6(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function I6(J,$){try{let G=await h1.updateTable("manufacturers").set({featured:$,updated_at:I1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer featured status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${G.message}`);throw G}}async function g6(J,$){try{let G=await h1.updateTable("manufacturers").set({...$,updated_at:I1(new Date)}).where("uuid","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer: ${G.message}`);throw G}}var z$={};z(z$,{updateVotes:()=>d6,update:()=>s6,store:()=>n6,fetchMostHelpfulByProductId:()=>u6,fetchByUserId:()=>l6,fetchByProductId:()=>p6,fetchById:()=>b6,fetchApprovedByProductId:()=>c6,fetchAll:()=>m6,destroy:()=>y6,bulkDestroy:()=>D6});import{db as v6}from"@stacksjs/database";async function y6(J){try{let $=await v6.deleteFrom("reviews").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function D6(J){if(!J.length)return 0;try{let $=await v6.deleteFrom("reviews").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as z0}from"@stacksjs/database";async function b6(J){return await z0.selectFrom("reviews").where("id","=",J).selectAll().executeTakeFirst()}async function m6(){return await z0.selectFrom("reviews").selectAll().execute()}async function p6(J){return await z0.selectFrom("reviews").where("product_id","=",J).selectAll().execute()}async function l6(J){return await z0.selectFrom("reviews").where("customer_id","=",J).selectAll().execute()}async function c6(J){return await z0.selectFrom("reviews").where("product_id","=",J).where("is_approved","=",!0).selectAll().execute()}async function u6(J){return await z0.selectFrom("reviews").where("product_id","=",J).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:b9}=globalThis.Bun;import{db as m9}from"@stacksjs/database";async function n6(J){try{let $={...J,uuid:b9(),is_verified_purchase:J.is_verified_purchase??!1,is_approved:J.is_approved??!1,helpful_votes:J.helpful_votes??0,unhelpful_votes:J.unhelpful_votes??0,is_featured:J.is_featured??!1},G=await m9.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create review");return G}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${$.message}`)}throw $}}import{db as i6}from"@stacksjs/database";import{formatDate as o6}from"@stacksjs/orm";async function s6(J,$){try{if(!J)throw Error("Review ID is required for update");let G=await i6.updateTable("reviews").set({...$,updated_at:o6(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review: ${G.message}`);throw G}}async function d6(J,$,G=!0){try{let N=$==="helpful"?"helpful_votes":"unhelpful_votes",X=G?`COALESCE("${N}", 0) + 1`:`MAX(COALESCE("${N}", 0) - 1, 0)`,W=await i6.unsafe(`UPDATE "reviews" SET "${N}" = ${X}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[o6(new Date),J]).execute(),Z=Array.isArray(W)?W[0]:W;if(!Z)throw Error("Failed to update review votes");return Z}catch(N){if(N instanceof Error)throw TypeError(`Failed to update review votes: ${N.message}`);throw N}}var _$={};z(_$,{updateDefaultStatus:()=>K2,update:()=>Y2,store:()=>N2,getDefaultUnit:()=>Z2,formatUnitOptions:()=>W2,fetchById:()=>$2,fetchAll:()=>J2,destroy:()=>e6,bulkUpdate:()=>L2,bulkStore:()=>X2,bulkDestroy:()=>r6});import{db as a6}from"@stacksjs/database";async function e6(J){try{let $=await a6.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function r6(J){if(!J.length)return 0;try{let $=await a6.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as t6}from"@stacksjs/database";async function $2(J){return await t6.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function J2(){return await t6.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:G2}=globalThis.Bun;import{db as k0}from"@stacksjs/database";async function N2(J){try{return await k0.transaction(async($)=>{let G={...J,uuid:G2()},N=await $.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!N)throw Error("Failed to create product unit");if(G.is_default&&G.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",N.id).execute();return N})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function X2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={...G,uuid:G2()},X=await k0.insertInto("product_units").values(N).returningAll().executeTakeFirst();if(N.is_default&&N.type&&X)await k0.updateTable("product_units").set({is_default:!1}).where("type","=",N.type).where("id","!=",X.id).execute();$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function W2(J){try{let $=k0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(J)$=$.where("type","=",J);return $=$.orderBy("name"),$.execute().then((G)=>G.map((N)=>({id:String(N.id),name:N.name,abbreviation:N.abbreviation,is_default:N.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function Z2(J){try{return await k0.selectFrom("product_units").selectAll().where("type","=",J).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as B$}from"@stacksjs/database";import{formatDate as A$}from"@stacksjs/orm";async function Y2(J,$){try{if(!J)throw Error("Product unit ID is required for update");return await B$.transaction(async(G)=>{let N=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",J).executeTakeFirst();if(!N)return;let X=$.type??N.type;if(($.is_default??Boolean(N.is_default))&&X)await G.updateTable("product_units").set({is_default:!1,updated_at:A$(new Date)}).where("type","=",X).where("id","!=",J).execute();let Z=await G.updateTable("product_units").set({...$,updated_at:A$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function L2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N=G;if(!N.id)continue;let X=N.data&&typeof N.data==="object"?N.data:{...N};delete X.id;let W=await B$.updateTable("product_units").set({...X,updated_at:A$(new Date)}).where("id","=",N.id).executeTakeFirst(),Z=X;if(Z.is_default===!0&&Z.type)await B$.updateTable("product_units").set({is_default:!1}).where("type","=",Z.type).where("id","!=",N.id).execute();if(Number(W.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function K2(J,$){try{return await B$.transaction(async(G)=>{let N=await G.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!N)return!1;let X=A$(new Date);if($&&N.type)await G.updateTable("product_units").set({is_default:!1,updated_at:X}).where("type","=",N.type).where("id","!=",J).execute();return await G.updateTable("product_units").set({is_default:$,updated_at:X}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var R$={};z(R$,{update:()=>T2,store:()=>A2,generateVariantCombinations:()=>O2,formatVariantOptions:()=>R2,fetchById:()=>V2,fetchAll:()=>x2,destroy:()=>Q2,bulkUpdate:()=>P2,bulkStore:()=>_2,bulkDestroy:()=>M2});import{db as F2}from"@stacksjs/database";async function Q2(J){try{let $=await F2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function M2(J){if(!J.length)return 0;try{let $=await F2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as H2}from"@stacksjs/database";async function V2(J){return await H2.selectFrom("product_variants").where("id","=",J).selectAll().executeTakeFirst()}async function x2(){return await H2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:z2}=globalThis.Bun;import{db as B2}from"@stacksjs/database";async function A2(J){try{let $={...J,uuid:z2()},G=await B2.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product variant");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function _2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={...G,uuid:z2()};await B2.insertInto("product_variants").values(N).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${G.message}`);throw G}}function R2(J){if(!J||!J.length)return JSON.stringify([]);let $=J.map((G)=>G.trim()).filter(Boolean);return JSON.stringify($)}function O2(J){let $=Object.keys(J);if(!$.length)return[];function G(N,X){if(N===$.length)return[X];let W=$[N],Z=J[W]??[],Y=[];for(let L of Z){let K={...X,[W]:L};Y.push(...G(N+1,K))}return Y}return G(0,{})}import{db as S2}from"@stacksjs/database";import{formatDate as U2}from"@stacksjs/orm";async function T2(J,$){try{let G=await S2.updateTable("product_variants").set({...$,updated_at:U2(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variant: ${G.message}`);throw G}}async function P2(J){if(!J.length)return 0;let $=0;try{for(let G of J){if(!G.id)continue;let N=await S2.updateTable("product_variants").set({...G,updated_at:U2(new Date)}).where("id","=",G.id).executeTakeFirst();if(Number(N.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${G.message}`);throw G}}var p9={categories:H$,items:V$,manufacturers:x$,reviews:z$,units:_$,variants:R$},l9=p9;var p1={};z(p1,{updateStatus:()=>b2,updatePrintJob:()=>m2,update:()=>D2,store:()=>v2,fetchSuccessRate:()=>j2,fetchPrintsPerHour:()=>I2,fetchPrintTimeStats:()=>h2,fetchPrintJobStats:()=>k2,fetchPageStats:()=>C2,fetchById:()=>B0,fetchAll:()=>E2,destroy:()=>q2,bulkStore:()=>y2,bulkDestroy:()=>f2});import{db as w2}from"@stacksjs/database";async function q2(J){try{let $=await w2.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function f2(J){if(!J.length)return 0;try{let $=await w2.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as v1}from"@stacksjs/database";import{formatDate as c9}from"@stacksjs/orm";function b(J){return c9(J)}function u9(J){if(J instanceof Date)return Number.isNaN(J.getTime())?null:J;if(typeof J==="number"){let N=new Date(J<=2147483647?J*1000:J);return Number.isNaN(N.getTime())?null:N}let $=String(J||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let N=new Date(Number($)*1000);return Number.isNaN(N.getTime())?null:N}let G=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function B0(J){return await v1.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function E2(){return await v1.selectFrom("receipts").selectAll().execute()}async function k2(J,$){let G=b(J),N=b($),X=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(W)=>W.where("timestamp",">=",G).where("timestamp","<=",N));return{total:X.total,success:X.success,failed:X.failed,warning:X.warning,averageSize:Math.round(X.averageSize),averagePages:Math.round(X.averagePages),averageDuration:Math.round(X.averageDuration)}}async function j2(J,$){let G=b(J),N=b($),X=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(Z)=>Z.where("timestamp",">=",G).where("timestamp","<=",N));return{successRate:X.total>0?Math.round(X.success/X.total*100):0,total:X.total,success:X.success,failed:X.failed,warning:X.warning}}async function C2(J,$){let G=b(J),N=b($),X=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(W)=>W.where("timestamp",">=",G).where("timestamp","<=",N));return{totalPages:X.totalPages,averagePagesPerReceipt:Math.round(X.averagePagesPerReceipt),totalReceipts:X.totalReceipts}}async function h2(J,$){let G=b(J),N=b($),X=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(W)=>W.where("timestamp",">=",G).where("timestamp","<=",N));return{averageDuration:Math.round(X.averageDuration),minDuration:X.minDuration,maxDuration:X.maxDuration,totalJobs:X.totalJobs}}async function I2(J,$){let G=typeof J==="number"?J:J.getTime(),N=typeof $==="number"?$:$.getTime(),X=b(J),W=b($),Z=await v1.selectFrom("receipts").where("timestamp",">=",X).where("timestamp","<=",W).selectAll().execute(),Y=Z.length,L=Math.ceil((N-G)/3600000),K=L>0?Math.round(Y/L):0,Q=Array.from({length:24},(M,H)=>({hour:H,count:0}));return Z.forEach((M)=>{let H=u9(M.timestamp);if(!H)return;Q[H.getHours()].count++}),{totalPrints:Y,totalHours:L,printsPerHour:K,hourlyBreakdown:Q}}var{randomUUIDv7:g2}=globalThis.Bun;import{db as D1}from"@stacksjs/database";import{formatDate as y1}from"@stacksjs/orm";function j0(J){try{if(typeof J==="number")return y1(J<=2147483647?J*1000:J);if(typeof J==="string"&&/^\d{10}$/.test(J))return y1(Number(J)*1000);return y1(J)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function v2(J){try{let $=g2(),G={...J,timestamp:j0(J.timestamp),uuid:$};await D1.insertInto("receipts").values(G).executeTakeFirst();let N=await D1.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to create receipt");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function y2(J){if(!J.length)return 0;try{let $=J.map((N)=>({...N,timestamp:j0(N.timestamp),uuid:g2()})),G=await D1.insertInto("receipts").values($).executeTakeFirst();return Number(G.numInsertedOrUpdatedRows??G.numAffectedRows??G.affectedRows??G.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as b1}from"@stacksjs/database";import{formatDate as m1}from"@stacksjs/orm";async function D2(J,$){try{if(!J)throw Error("Receipt ID is required for update");let G={...$,...$.timestamp===void 0?{}:{timestamp:j0($.timestamp)},updated_at:m1(new Date)};await b1.updateTable("receipts").set(G).where("id","=",J).execute();let N=await B0(J);if(!N)return;return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function b2(J,$){try{await b1.updateTable("receipts").set({status:$,updated_at:m1(new Date)}).where("id","=",J).execute();let G=await B0(J);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function m2(J,$,G,N){try{let X={updated_at:m1(new Date)};if($!==void 0)X.size=$;if(G!==void 0)X.pages=G;if(N!==void 0)X.duration=N;await b1.updateTable("receipts").set(X).where("id","=",J).execute();let W=await B0(J);if(!W)throw Error("Failed to update receipt job information");return W}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt job information: ${X.message}`);throw X}}var F4={};z(F4,{zones:()=>G1,tracking:()=>r$,routes:()=>w$,rates:()=>l$,methods:()=>y$,licenses:()=>h$,drivers:()=>k$,digital:()=>f$,default:()=>W3});var w$={};z(w$,{validateDeliveryRouteWrite:()=>A0,updateStops:()=>a2,updateMetrics:()=>e2,updateLastActive:()=>s2,update:()=>d2,store:()=>o2,fetchById:()=>S$,fetchByDriver:()=>i2,fetchAll:()=>u2,fetchActive:()=>n2,destroy:()=>l2,bulkDestroy:()=>c2,DeliveryRouteInputError:()=>h});import{db as p2}from"@stacksjs/database";async function l2(J){try{let $=await p2.deleteFrom("delivery_routes").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function c2(J){if(!J.length)return 0;try{let $=await p2.deleteFrom("delivery_routes").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as O$}from"@stacksjs/database";async function S$(J){return await O$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function u2(){return await O$.selectFrom("delivery_routes").selectAll().execute()}async function n2(){return await O$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function i2(J){return await O$.selectFrom("delivery_routes").where("driver","=",J).selectAll().execute()}var{randomUUIDv7:o9}=globalThis.Bun;import{db as l1}from"@stacksjs/database";function X0(J,$){let G={};for(let[N,X]of Object.entries($))for(let W of X){if(!Object.prototype.hasOwnProperty.call(J,W)||J[W]===void 0)continue;G[N]=J[W];break}return G}function C0(J){return X0(J,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function i(J){return X0(J,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function h0(J){return X0(J,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function I0(J){return X0(J,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function g0(J){return X0(J,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function v0(J){return X0(J,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function U$(J){return X0(J,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as n9}from"@stacksjs/database";class h extends TypeError{constructor(J){super(J);this.name="DeliveryRouteInputError"}}function T$(J,$,G){return Number(J[G]??$?.[G])}function i9(J,$){let G=J.last_active??$?.last_active;if(G instanceof Date)return G.getTime();if(typeof G==="number")return G;if(typeof G==="string"&&/^\d{10,13}$/.test(G))return Number(G);return Number.NaN}async function A0(J,$){let G=T$(J,$,"driver_id"),N=T$(J,$,"stops"),X=T$(J,$,"delivery_time"),W=T$(J,$,"total_distance"),Z=i9(J,$);if(!Number.isSafeInteger(G)||G<1)throw new h("Driver must be a positive integer.");if(!Number.isSafeInteger(N)||N<0)throw new h("Stops must be a non-negative integer.");if(!Number.isSafeInteger(X)||X<0)throw new h("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(W)||W<0)throw new h("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new h("Last active must be a valid Unix timestamp.");let Y=await n9.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!Y)throw new h(`Driver ${G} was not found.`);return{...J,driver_id:Number(Y.id),driver:Y.name,vehicle:Y.vehicle_number}}async function o2(J){try{let $=o9(),G=U$(J),X={...await A0(G),uuid:$};await l1.insertInto("delivery_routes").values(X).executeTakeFirst();let W=await l1.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!W)throw Error("Failed to create delivery route");return W}catch($){if($ instanceof h)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function s2(J){try{await l1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",J).execute();let $=await S$(J);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as P$}from"@stacksjs/database";import{formatDate as c1}from"@stacksjs/orm";async function d2(J,$){try{if(!J)throw Error("Delivery route ID is required for update");let G=await P$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let N=U$($),X=await A0(N,G),W=await P$.updateTable("delivery_routes").set({...X,updated_at:c1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!W)return;return W}catch(G){if(G instanceof h)throw G;if(G instanceof Error)throw TypeError(`Failed to update delivery route: ${G.message}`);throw G}}async function a2(J,$){try{let G=await P$.updateTable("delivery_routes").set({stops:$,updated_at:c1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update delivery route stops");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery route stops: ${G.message}`);throw G}}async function e2(J,$,G){try{let N={updated_at:c1(new Date)};if($!==void 0)N.delivery_time=$;if(G!==void 0)N.total_distance=G;let X=await P$.updateTable("delivery_routes").set(N).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery metrics");return X}catch(N){if(N instanceof Error)throw TypeError(`Failed to update delivery metrics: ${N.message}`);throw N}}var f$={};z(f$,{updateStatus:()=>KG,updateDeliverySettings:()=>FG,update:()=>LG,store:()=>ZG,softDelete:()=>t2,fetchById:()=>NG,fetchAll:()=>XG,destroy:()=>r2,bulkStore:()=>YG,bulkSoftDelete:()=>JG,bulkDestroy:()=>$G});import{db as q$}from"@stacksjs/database";async function r2(J){try{let $=await q$.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function t2(J){try{let $=await q$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function $G(J){if(!J.length)return 0;try{let $=await q$.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function JG(J){if(!J.length)return 0;try{let $=await q$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as GG}from"@stacksjs/database";async function NG(J){return await GG.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function XG(){return await GG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:WG}=globalThis.Bun;import{db as u1}from"@stacksjs/database";async function ZG(J){try{let $=WG(),G={...I0(J),uuid:$};await u1.insertInto("digital_deliveries").values(G).executeTakeFirst();let N=await u1.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created digital delivery");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function YG(J){if(!J.length)return 0;try{let $=J.map((N)=>({...I0(N),uuid:WG()})),G=await u1.insertInto("digital_deliveries").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as n1}from"@stacksjs/database";import{formatDate as i1}from"@stacksjs/orm";async function LG(J,$){try{if(!J)throw Error("Digital delivery ID is required for update");let G=await n1.updateTable("digital_deliveries").set({...I0($),updated_at:i1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery: ${G.message}`);throw G}}async function KG(J,$){try{let G=await n1.updateTable("digital_deliveries").set({status:$,updated_at:i1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update digital delivery status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery status: ${G.message}`);throw G}}async function FG(J,$,G,N,X){try{let W={updated_at:i1(new Date)};if($!==void 0)W.download_limit=$;if(G!==void 0)W.expiry_days=G;if(N!==void 0)W.requires_login=N;if(X!==void 0)W.automatic_delivery=X;let Z=await n1.updateTable("digital_deliveries").set(W).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update delivery settings");return Z}catch(W){if(W instanceof Error)throw TypeError(`Failed to update delivery settings: ${W.message}`);throw W}}var k$={};z(k$,{updateStatus:()=>RG,updateContact:()=>OG,update:()=>_G,store:()=>BG,fetchById:()=>E$,fetchAll:()=>MG,destroy:()=>VG,bulkStore:()=>AG,bulkDestroy:()=>xG});import{db as HG}from"@stacksjs/database";import{db as QG}from"@stacksjs/database";async function E$(J){return await QG.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function MG(){return await QG.selectFrom("drivers").selectAll().execute()}async function VG(J){try{let $=await HG.deleteFrom("drivers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function xG(J){if(!J.length)return 0;let $=0;try{return await HG.transaction().execute(async(G)=>{for(let N of J)if(await E$(N))await G.deleteFrom("drivers").where("id","=",N).execute(),$++}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${G.message}`);throw G}}var{randomUUIDv7:zG}=globalThis.Bun;import{db as o1}from"@stacksjs/database";async function BG(J){try{let $=zG(),G={...v0(J),uuid:$};await o1.insertInto("drivers").values(G).executeTakeFirst();let N=await o1.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created driver");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function AG(J){if(!J.length)return 0;try{let $=J.map((N)=>({...v0(N),uuid:zG()})),G=await o1.insertInto("drivers").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as s1}from"@stacksjs/database";import{formatDate as d1}from"@stacksjs/orm";async function _G(J,$){try{if(!J)throw Error("Driver ID is required for update");let G=await s1.updateTable("drivers").set({...v0($),updated_at:d1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver: ${G.message}`);throw G}}async function RG(J,$){try{let G=await s1.updateTable("drivers").set({status:$,updated_at:d1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update driver status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver status: ${G.message}`);throw G}}async function OG(J,$){try{let G={updated_at:d1(new Date)};if($!==void 0)G.phone=$;let N=await s1.updateTable("drivers").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!N)throw Error("Failed to update contact information");return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update contact information: ${G.message}`);throw G}}var h$={};z(h$,{validateLicenseKeyWrite:()=>W0,updateStatus:()=>gG,updateExpiration:()=>vG,update:()=>IG,store:()=>CG,softDelete:()=>UG,fetchById:()=>qG,fetchAll:()=>fG,destroy:()=>SG,bulkStore:()=>hG,bulkSoftDelete:()=>PG,bulkDestroy:()=>TG,LicenseKeyInputError:()=>w});import{db as j$}from"@stacksjs/database";async function SG(J){try{let $=await j$.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function UG(J){try{let $=await j$.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function TG(J){if(!J.length)return 0;try{let $=await j$.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function PG(J){if(!J.length)return 0;try{let $=await j$.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as wG}from"@stacksjs/database";async function qG(J){return await wG.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst()}async function fG(){return await wG.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:jG}=globalThis.Bun;import{db as r1}from"@stacksjs/database";import{db as a1}from"@stacksjs/database";var EG=["Standard License","Premium License","Enterprise License"],kG=["active","inactive","unassigned"];class w extends TypeError{constructor(J){super(J);this.name="LicenseKeyInputError"}}function y0(J,$,G){return J[G]!==void 0?J[G]:$?.[G]}function e1(J,$,G,N){let X=y0(J,$,G);if(X===void 0||X===null||X==="")return null;let W=Number(X);if(!Number.isSafeInteger(W)||W<1)throw new w(`${N} must be a positive integer or null.`);return W}function s9(J){if(typeof J==="number")return J>2147483647?Math.floor(J/1000):J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return J.length===13?Math.floor(Number(J)/1000):Number(J);if(typeof J==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(J)?`${J.replace(" ","T")}Z`:J;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function W0(J,$){let G=String(y0(J,$,"key")||"").trim().toUpperCase(),N=String(y0(J,$,"template")||""),X=String(y0(J,$,"status")||""),W=s9(y0(J,$,"expiry_date")),Z=e1(J,$,"customer_id","Customer"),Y=e1(J,$,"product_id","Product"),L=e1(J,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new w("License key must use five groups of four uppercase letters or numbers.");if(!EG.includes(N))throw new w(`Template must be one of: ${EG.join(", ")}.`);if(!kG.includes(X))throw new w(`Status must be one of: ${kG.join(", ")}.`);if(!Number.isSafeInteger(W)||W<0||W>2147483647)throw new w("Expiry date must be a Unix timestamp between 1970 and 2038.");let[K,Q,M]=await Promise.all([Z?a1.selectFrom("customers").where("id","=",Z).select("id").executeTakeFirst():null,Y?a1.selectFrom("products").where("id","=",Y).select("id").executeTakeFirst():null,L?a1.selectFrom("orders").where("id","=",L).select(["id","customer_id"]).executeTakeFirst():null]);if(Z&&!K)throw new w(`Customer ${Z} was not found.`);if(Y&&!Q)throw new w(`Product ${Y} was not found.`);if(L&&!M)throw new w(`Order ${L} was not found.`);if(Z&&M?.customer_id&&Number(M.customer_id)!==Z)throw new w(`Order ${L} belongs to Customer ${M.customer_id}, not Customer ${Z}.`);return{...J,key:G,template:N,expiry_date:W,status:X,customer_id:Z,product_id:Y,order_id:L}}async function CG(J){try{let $=jG(),G=g0(J),N={...await W0(G),uuid:$};await r1.insertInto("license_keys").values(N).executeTakeFirst();let X=await r1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created license key");return X}catch($){if($ instanceof w)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new w("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function hG(J){if(!J.length)return 0;try{let $=await Promise.all(J.map(async(N)=>({...await W0(g0(N)),uuid:jG()}))),G=await r1.insertInto("license_keys").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof w)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as C$}from"@stacksjs/database";import{formatDate as t1}from"@stacksjs/orm";async function IG(J,$){try{if(!J)throw Error("License key ID is required for update");let G=await C$.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let N=g0($),X=await W0(N,G),W=await C$.updateTable("license_keys").set({...X,updated_at:t1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!W)return;return W}catch(G){if(G instanceof w)throw G;if(G instanceof Error){if(G.message.includes("UNIQUE constraint failed: license_keys.key"))throw new w("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${G.message}`)}throw G}}async function gG(J,$){try{let G=await C$.updateTable("license_keys").set({status:$,updated_at:t1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update license key status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update license key status: ${G.message}`);throw G}}async function vG(J,$){try{let G={updated_at:t1(new Date)};if($!==void 0)G.expiry_date=$;let N=await C$.updateTable("license_keys").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!N)throw Error("Failed to update expiration information");return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update expiration information: ${G.message}`);throw G}}var y$={};z(y$,{updateStatus:()=>sG,updatePricing:()=>dG,update:()=>oG,store:()=>cG,softDelete:()=>DG,getActiveShippingMethods:()=>iG,formatShippingOptions:()=>nG,fetchById:()=>v$,fetchAll:()=>pG,destroy:()=>yG,bulkStore:()=>uG,bulkSoftDelete:()=>mG,bulkDestroy:()=>bG});import{db as I$}from"@stacksjs/database";async function yG(J){try{let $=await I$.deleteFrom("shipping_methods").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function DG(J){try{let $=await I$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function bG(J){if(!J.length)return 0;try{let $=await I$.deleteFrom("shipping_methods").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function mG(J){if(!J.length)return 0;try{let $=await I$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as g$}from"@stacksjs/database";async function v$(J){let $=await g$.selectFrom("shipping_methods").where("id","=",J).selectAll().executeTakeFirst();if($){let G=await g$.selectFrom("shipping_zones").where("shipping_method_id","=",J).selectAll().execute();return{...$,shippingZones:G}}return}async function pG(){let J=await g$.selectFrom("shipping_methods").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((W)=>W.id))],X=(await g$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((W,Z)=>{let Y=Z.shipping_method_id;if(Y!==null&&Y!==void 0){if(!W[Y])W[Y]=[];W[Y].push(Z)}return W},{});return J.map((W)=>({...W,shipping_zones:X[W.id]||[]}))}var{randomUUIDv7:lG}=globalThis.Bun;import{db as D0}from"@stacksjs/database";async function cG(J){try{let $=lG(),G={...C0(J),uuid:$};await D0.insertInto("shipping_methods").values(G).executeTakeFirst();let N=await D0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created shipping method");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function uG(J){if(!J.length)return 0;try{let $=J.map((N)=>({...C0(N),uuid:lG()})),G=await D0.insertInto("shipping_methods").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function nG(){try{return D0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping options: ${J.message}`);throw J}}async function iG(){try{return await D0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping methods: ${J.message}`);throw J}}import{db as $4}from"@stacksjs/database";import{formatDate as J4}from"@stacksjs/orm";async function oG(J,$){try{if(!J)throw Error("Shipping method ID is required for update");let G=await $4.updateTable("shipping_methods").set({...C0($),updated_at:J4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method: ${G.message}`);throw G}}async function sG(J,$){try{let G=await $4.updateTable("shipping_methods").set({status:$,updated_at:J4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping method status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method status: ${G.message}`);throw G}}async function dG(J,$,G){try{let N={updated_at:J4(new Date)};if($!==void 0)N.base_rate=$;if(G!==void 0)N.free_shipping=G;let X=await $4.updateTable("shipping_methods").set(N).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update pricing information");return X}catch(N){if(N instanceof Error)throw TypeError(`Failed to update pricing information: ${N.message}`);throw N}}var l$={};z(l$,{validateZoneMatchesAddress:()=>WN,validateShippingRateWrite:()=>Z0,updateByZone:()=>BN,updateByMethod:()=>AN,update:()=>xN,store:()=>HN,resolveZoneForAddress:()=>b$,getShippingRatesByMethod:()=>YN,getRatesByZone:()=>NN,getRateByWeightAndZone:()=>G4,getRateByWeightAndAddress:()=>XN,formatShippingRateOptions:()=>ZN,fetchById:()=>JN,fetchAll:()=>GN,destroyByZone:()=>rG,destroyByMethod:()=>tG,destroy:()=>aG,bulkUpdate:()=>zN,bulkStore:()=>VN,bulkDestroy:()=>eG,ShippingRateInputError:()=>j});import{db as D$}from"@stacksjs/database";async function aG(J){try{let $=await D$.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function eG(J){if(!J.length)return 0;try{let $=await D$.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function rG(J){try{let $=await D$.deleteFrom("shipping_rates").where("shipping_zone_id","=",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function tG(J){try{let $=await D$.deleteFrom("shipping_rates").where("shipping_method_id","=",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as y}from"@stacksjs/database";async function JN(J){let $=await y.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,N=null;if($.shipping_zone_id)G=await y.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)N=await y.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:G,shipping_method:N}}return}async function GN(){let J=await y.selectFrom("shipping_rates").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((Y)=>Y.shipping_zone_id).filter((Y)=>Y!==null&&Y!==void 0))],G=[...new Set(J.map((Y)=>Y.shipping_method_id).filter((Y)=>Y!==null&&Y!==void 0))],[N,X]=await Promise.all([$.length?y.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],G.length?y.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),W=N.reduce((Y,L)=>{return Y[L.id]=L,Y},{}),Z=X.reduce((Y,L)=>{return Y[L.id]=L,Y},{});return J.map((Y)=>({...Y,shipping_zone:Y.shipping_zone_id?W[Y.shipping_zone_id]:[],shipping_method:Y.shipping_method_id?Z[Y.shipping_method_id]:[]}))}async function NN(J){try{return await y.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function G4(J,$){try{return await y.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function b$(J){if(!J?.countryCode)return null;try{let $=await y.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let G=null;for(let N of $){let X=1;if(J.region&&N.regions&&$N(N.regions,J.region))X=2;if(J.postalCode&&N.postal_codes&&$N(N.postal_codes,J.postalCode))X=3;if(!G||X>G.score)G={id:N.id,score:X}}return G?.id??null}catch{return null}}async function XN(J,$){let G=await b$($);if(G==null)return;return G4(J,G)}async function WN(J,$){return await b$($)===J}function $N(J,$){if(!J||!$)return!1;let G=$.trim().toUpperCase();for(let N of J.split(/[,|;]/))if(N.trim().toUpperCase()===G)return!0;return!1}async function ZN(){try{return(await y.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function YN(J){try{return await y.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:MN}=globalThis.Bun;import{db as N4}from"@stacksjs/database";import{db as b0}from"@stacksjs/database";async function LN(){return await b0.selectFrom("shipping_zones").selectAll().execute()}async function m$(J){return await b0.selectFrom("shipping_zones").where("id","=",J).selectAll().executeTakeFirst()}function KN(){try{return b0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping zone options: ${J.message}`);throw J}}async function FN(){try{return await b0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping zones: ${J.message}`);throw J}}async function QN(J){try{return await b0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class j extends TypeError{constructor(J){super(J);this.name="ShippingRateInputError"}}function m0(J,$,G){return Number(J[G]??$?.[G])}async function Z0(J,$){let G=m0(J,$,"shipping_method_id"),N=m0(J,$,"shipping_zone_id"),X=m0(J,$,"weight_from"),W=m0(J,$,"weight_to"),Z=m0(J,$,"rate");if(!Number.isSafeInteger(G)||G<1)throw new j("Shipping method must be a positive integer.");if(!Number.isSafeInteger(N)||N<1)throw new j("Shipping zone must be a positive integer.");if(!Number.isFinite(X)||X<0)throw new j("Weight from must be a non-negative number.");if(!Number.isFinite(W)||W<X)throw new j("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(Z)||Z<0)throw new j("Rate must be a non-negative integer in minor currency units.");let[Y,L]=await Promise.all([v$(G),m$(N)]);if(!Y)throw new j(`Shipping method ${G} was not found.`);if(!L)throw new j(`Shipping zone ${N} was not found.`);if(Number(L.shipping_method_id)!==G)throw new j(`Shipping zone ${N} is not assigned to shipping method ${G}.`)}async function HN(J){try{let $=i(J),G=Number($.shipping_method_id),N=Number($.shipping_zone_id);await Z0($);let X=MN(),W={...$,shipping_method_id:G,shipping_zone_id:N,uuid:X};await N4.insertInto("shipping_rates").values(W).executeTakeFirst();let Z=await N4.selectFrom("shipping_rates").where("uuid","=",X).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created shipping rate");return Z}catch($){if($ instanceof j)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function VN(J){if(!J.length)return 0;try{for(let N of J){let X=i(N);await Z0(X)}let $=J.map((N)=>({...i(N),uuid:MN()})),G=await N4.insertInto("shipping_rates").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof j)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as p0}from"@stacksjs/database";import{formatDate as p$}from"@stacksjs/orm";async function xN(J,$){try{if(!J)throw Error("Shipping rate ID is required for update");let G=await p0.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let N=i($);await Z0(N,G);let X=await p0.updateTable("shipping_rates").set({...N,updated_at:p$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)return;return X}catch(G){if(G instanceof j)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function zN(J){if(!J.length)return 0;try{let $=0;for(let{id:G,data:N}of J){let X=await p0.updateTable("shipping_rates").set({...i(N),updated_at:p$(new Date)}).where("id","=",G).executeTakeFirst();if(F(X)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function BN(J,$){try{let G=await p0.updateTable("shipping_rates").set({...i($),updated_at:p$(new Date)}).where("shipping_zone_id","=",J).executeTakeFirst();return F(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${G.message}`);throw G}}async function AN(J,$){try{let G=await p0.updateTable("shipping_rates").set({...i($),updated_at:p$(new Date)}).where("shipping_method_id","=",J).executeTakeFirst();return F(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var r$={};z(r$,{startStop:()=>SN,startRoute:()=>PN,routeTrackingChannel:()=>X4,recordDriverPing:()=>RN,orderTrackingChannel:()=>e,isWithin:()=>_N,hasCoordinates:()=>c0,failStop:()=>TN,estimateSecondsRemaining:()=>e$,emitDeliveryStarted:()=>n$,emitDeliveryPosition:()=>c$,emitDeliveryNearby:()=>i$,emitDeliveryFailed:()=>d$,emitDeliveryCompleted:()=>s$,emitDeliveryAssigned:()=>u$,emitDeliveryArrived:()=>o$,distanceInMeters:()=>l0,completeStop:()=>UN,broadcastToChannel:()=>o,bearingInDegrees:()=>a$,assignStop:()=>ON,NEARBY_RADIUS_METERS:()=>W4,ARRIVAL_RADIUS_METERS:()=>Z4});function e(J){return`order.${J}`}function X4(J){return`delivery-route.${J}`}async function _0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let N=G.dispatch;if(typeof N!=="function")return;N(J,$)}catch{}}async function o(J,$,G){try{let N=await import("@stacksjs/realtime").catch(()=>null);if(!N)return;let X=N.channel;if(typeof X!=="function")return;await X(J).broadcast($,G,"private")}catch{}}async function c$(J,$,G){await Promise.all([...J.map((N)=>o(e(N),"delivery:position",G)),$==null?Promise.resolve():o(X4($),"delivery:position",G)])}async function u$(J){if(await _0("delivery:assigned",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:assigned",{stop:J})}async function n$(J){if(await _0("delivery:started",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:started",{stop:J})}async function i$(J,$,G){if(await _0("delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G}),J.order_id!=null)await o(e(J.order_id),"delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G})}async function o$(J){if(await _0("delivery:arrived",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:arrived",{stop:J})}async function s$(J){if(await _0("delivery:completed",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:completed",{stop:J})}async function d$(J,$){await _0("delivery:failed",{stop:J,reason:$})}var Y0=(J)=>J*Math.PI/180;function l0(J,$){let G=Y0($.latitude-J.latitude),N=Y0($.longitude-J.longitude),X=Y0(J.latitude),W=Y0($.latitude),Z=Math.sin(G/2)**2+Math.sin(N/2)**2*Math.cos(X)*Math.cos(W);return 12742017.6*Math.asin(Math.sqrt(Z))}function a$(J,$){let G=Y0(J.latitude),N=Y0($.latitude),X=Y0($.longitude-J.longitude),W=Math.sin(X)*Math.cos(N),Z=Math.cos(G)*Math.sin(N)-Math.sin(G)*Math.cos(N)*Math.cos(X);return(Math.atan2(W,Z)*180/Math.PI+360)%360}function e$(J,$,G={}){let N=G.detourFactor??1.35,X=G.minimumSeconds??30;if(!Number.isFinite($)||$<=0.5)return null;let W=J*N/$;return Math.max(X,Math.round(W))}function _N(J,$,G){return l0(J,$)<=G}function c0(J){return typeof J?.latitude==="number"&&typeof J?.longitude==="number"&&Number.isFinite(J.latitude)&&Number.isFinite(J.longitude)}var{randomUUIDv7:d9}=globalThis.Bun;import{db as D}from"@stacksjs/database";var W4=400,Z4=60,a9=250;async function RN(J){let $=J.recordedAt??new Date().toISOString(),G=typeof J.accuracy!=="number"||J.accuracy<=a9,N=await D.selectFrom("drivers").where("id","=",J.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!N)throw Error(`Unknown driver: ${J.driverId}`);let X=c0(N)?{latitude:N.latitude,longitude:N.longitude}:null,W=typeof J.heading==="number"?J.heading:X?a$(X,J):null,Z=await e9(J.driverId),Y=Z?await r9(Z.id):null,L=null,K=null,Q=!1,M=!1,H=Y&&c0({latitude:Y.latitude??void 0,longitude:Y.longitude??void 0})?{latitude:Y.latitude,longitude:Y.longitude}:null;if(G&&Y&&H)L=Math.round(l0(J,H)),K=e$(L,J.speed??0),M=L<=Z4&&Y.arrived_at==null,Q=!M&&L<=W4&&Y.status==="en_route"&&Y.notified_nearby_at==null;let _=await t9({driverId:J.driverId,routeId:Z?.id??null,latitude:J.latitude,longitude:J.longitude,heading:W,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$});if(G)await D.updateTable("drivers").set({latitude:J.latitude,longitude:J.longitude,heading:W,speed:J.speed??0,last_ping_at:$}).where("id","=",J.driverId).execute();if(Y&&(L!=null||K!=null))await D.updateTable("delivery_stops").set({eta_at:K==null?Y.eta_at:new Date(Date.now()+K*1000).toISOString()}).where("id","=",Y.id).execute();if(G)await c$(Y?.order_id==null?[]:[Y.order_id],Z?.id??null,{driverId:J.driverId,routeId:Z?.id??null,latitude:J.latitude,longitude:J.longitude,heading:W,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$,distanceToStopMeters:L,etaSeconds:K});if(Q&&Y)await D.updateTable("delivery_stops").set({notified_nearby_at:$}).where("id","=",Y.id).execute(),await i$(Y,L,K);if(M&&Y)await D.updateTable("delivery_stops").set({status:"arrived",arrived_at:$}).where("id","=",Y.id).execute(),await o$({...Y,status:"arrived",arrived_at:$});return{pingId:_,routeId:Z?.id??null,stopId:Y?.id??null,distanceToStopMeters:L,etaSeconds:K,crossedNearby:Q,crossedArrival:M}}async function e9(J){return await D.selectFrom("delivery_routes").where("driver_id","=",J).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function r9(J){let $=await D.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return $.find((G)=>G.status==="en_route")??$.find((G)=>G.status==="arrived")??$[0]??null}async function t9(J){let $=d9();return await D.insertInto("driver_pings").values({uuid:$,driver_id:J.driverId,delivery_route_id:J.routeId,latitude:J.latitude,longitude:J.longitude,heading:J.heading,speed:J.speed??0,accuracy:J.accuracy,recorded_at:J.recordedAt}).executeTakeFirst(),(await D.selectFrom("driver_pings").where("uuid","=",$).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:$3}=globalThis.Bun;import{db as k}from"@stacksjs/database";async function ON(J){let $=$3(),G=J.sequence??await J3(J.deliveryRouteId);await k.insertInto("delivery_stops").values({uuid:$,delivery_route_id:J.deliveryRouteId,order_id:J.orderId??null,sequence:G,status:"pending",address:J.address,latitude:J.latitude??null,longitude:J.longitude??null,recipient_name:J.recipientName??null,recipient_phone:J.recipientPhone??null,eta_at:J.etaAt??null}).executeTakeFirst();let N=await N3($);if(N)await u$(N);return N??{}}async function SN(J){await k.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",J).execute();let $=await L4(J);if(!$)return null;if($.order_id!=null)await Y4($.order_id,"OUT_FOR_DELIVERY");return await n$($),$}async function UN(J,$){let G=new Date().toISOString();await k.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await G3(J)?{}:{arrived_at:G},...$?{notes:$}:{}}).where("id","=",J).execute();let N=await L4(J);if(!N)return null;if(N.order_id!=null)await Y4(N.order_id,"DELIVERED");return await s$(N),await wN(N.delivery_route_id),N}async function TN(J,$){await k.updateTable("delivery_stops").set({status:"failed",notes:$}).where("id","=",J).execute();let G=await L4(J);if(!G)return null;if(G.order_id!=null)await Y4(G.order_id,"SHIPPED");return await d$(G,$),await wN(G.delivery_route_id),G}async function PN(J){await k.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",J).execute()}async function wN(J){if(J==null)return;if(await k.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;await k.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",J).execute()}async function Y4(J,$){let G=await k.selectFrom("orders").where("id","=",J).select(["id","status"]).executeTakeFirst();if(!G)return;let{canTransition:N,emitForStatus:X}=await Promise.resolve().then(() => (M0(),KJ));if(!N(G.status,$))return;await k.updateTable("orders").set({status:$}).where("id","=",J).execute(),await X($,{...G,status:$})}async function J3(J){return(await k.selectFrom("delivery_stops").where("delivery_route_id","=",J).select(["sequence"]).execute()).reduce((G,N)=>Math.max(G,N.sequence??0),0)+1}async function G3(J){return(await k.selectFrom("delivery_stops").where("id","=",J).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function L4(J){return await k.selectFrom("delivery_stops").where("id","=",J).selectAll().executeTakeFirst()??null}async function N3(J){return await k.selectFrom("delivery_stops").where("uuid","=",J).selectAll().executeTakeFirst()??null}var G1={};z(G1,{updateStatus:()=>gN,updateRegionsAndPostalCodes:()=>yN,updateCountries:()=>vN,update:()=>IN,store:()=>CN,softDelete:()=>fN,getZonesByCountry:()=>QN,getActiveShippingZones:()=>FN,formatZoneOptions:()=>KN,fetchById:()=>m$,fetchAll:()=>LN,destroy:()=>qN,bulkStore:()=>hN,bulkSoftDelete:()=>kN,bulkDestroy:()=>EN});import{db as t$}from"@stacksjs/database";async function qN(J){try{let $=await t$.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function fN(J){try{let $=await t$.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function EN(J){if(!J.length)return 0;try{let $=await t$.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function kN(J){if(!J.length)return 0;try{let $=await t$.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:jN}=globalThis.Bun;import{db as K4}from"@stacksjs/database";async function CN(J){try{let $=jN(),G={...h0(J),uuid:$};await K4.insertInto("shipping_zones").values(G).executeTakeFirst();let N=await K4.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created shipping zone");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function hN(J){if(!J.length)return 0;try{let $=J.map((N)=>({...h0(N),uuid:jN()})),G=await K4.insertInto("shipping_zones").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as $1}from"@stacksjs/database";import{formatDate as J1}from"@stacksjs/orm";async function IN(J,$){try{if(!J)throw Error("Shipping zone ID is required for update");let G=await $1.updateTable("shipping_zones").set({...h0($),updated_at:J1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone: ${G.message}`);throw G}}async function gN(J,$){try{let G=await $1.updateTable("shipping_zones").set({status:$,updated_at:J1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone status: ${G.message}`);throw G}}async function vN(J,$){try{let G=await $1.updateTable("shipping_zones").set({countries:$,updated_at:J1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone countries");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${G.message}`);throw G}}async function yN(J,$,G){try{let N={updated_at:J1(new Date)};if($!==void 0)N.regions=$;if(G!==void 0)N.postal_codes=G;let X=await $1.updateTable("shipping_zones").set(N).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update regions and postal codes");return X}catch(N){if(N instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${N.message}`);throw N}}var X3={digital:f$,drivers:k$,licenses:h$,methods:y$,rates:l$,routes:w$,tracking:r$,zones:G1},W3=X3;var Q4={};z(Q4,{updateStatus:()=>dN,updateRate:()=>aN,updateDefaultStatus:()=>eN,update:()=>sN,store:()=>iN,fetchById:()=>lN,fetchAll:()=>cN,destroy:()=>bN,bulkStore:()=>oN,bulkDestroy:()=>mN});import{db as DN}from"@stacksjs/database";async function bN(J){try{let $=await DN.deleteFrom("tax_rates").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function mN(J){if(!J.length)return 0;try{let $=await DN.deleteFrom("tax_rates").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as pN}from"@stacksjs/database";async function lN(J){return await pN.selectFrom("tax_rates").where("id","=",J).selectAll().executeTakeFirst()}async function cN(){return await pN.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:uN}=globalThis.Bun;import{db as nN}from"@stacksjs/database";async function iN(J){try{return await nN.transaction(async($)=>{let G={...J,uuid:uN()};if(G.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let N=await $.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!N)throw Error("Failed to create tax rate");return N})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function oN(J){if(!J.length)return 0;try{return await nN.transaction(async($)=>{let G=0;for(let N of J){let X={...N,uuid:uN()};if(X.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(X).executeTakeFirst())G++}return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as N1}from"@stacksjs/database";import{formatDate as X1}from"@stacksjs/orm";async function sN(J,$){try{if(!J)throw Error("Tax rate ID is required for update");return await N1.transaction(async(G)=>{let N=await G.selectFrom("tax_rates").select("is_default").where("id","=",J).executeTakeFirst();if(!N)return;let X=$.is_default??Boolean(N.is_default),W=X1(new Date);if(X)await G.updateTable("tax_rates").set({is_default:!1,updated_at:W}).where("id","!=",J).execute();let Z=await G.updateTable("tax_rates").set({...$,updated_at:W}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function dN(J,$){try{let G=await N1.updateTable("tax_rates").set({status:$,updated_at:X1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update tax rate status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate status: ${G.message}`);throw G}}async function aN(J,$){try{let G=await N1.updateTable("tax_rates").set({rate:$,updated_at:X1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update rate information");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update rate information: ${G.message}`);throw G}}async function eN(J,$){try{return await N1.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",J).executeTakeFirst())return!1;let X=X1(new Date);if($)await G.updateTable("tax_rates").set({is_default:!1,updated_at:X}).where("id","!=",J).execute();return await G.updateTable("tax_rates").set({is_default:$,updated_at:X}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var B4={};z(B4,{restaurant:()=>O0,products:()=>Z1,default:()=>x3});var Z1={};z(Z1,{updateStatus:()=>BX,updatePartySize:()=>AX,update:()=>W1,store:()=>xX,fetchWaiting:()=>LX,fetchPurchasedBetweenDates:()=>ZX,fetchNotifiedBetweenDates:()=>WX,fetchCountByStatus:()=>KX,fetchCountBySource:()=>JX,fetchCountByQuantity:()=>NX,fetchCountByDateGrouped:()=>MX,fetchCountByDate:()=>GX,fetchCountByAllQuantities:()=>XX,fetchCountBetweenDates:()=>QX,fetchConversionRates:()=>FX,fetchCancelledBetweenDates:()=>YX,fetchById:()=>u0,fetchAll:()=>$X,destroy:()=>rN,bulkStore:()=>zX,bulkDestroy:()=>tN});import{db as M4}from"@stacksjs/database";async function rN(J){try{let $=await M4.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await M4.deleteFrom("waitlist_products").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function tN(J){if(!J.length)return 0;try{let $=await M4.deleteFrom("waitlist_products").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as P}from"@stacksjs/orm";async function u0(J){return await A.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function $X(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function JX(J,$){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(J&&$){let X=P(J),W=P($);G=G.where("created_at",">=",X).where("created_at","<=",W)}return(await G.execute()).reduce((X,{source:W,count:Z})=>{return X[W]=Z,X},{})}async function GX(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let N=P($),X=P(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",N).where("created_at","<=",X).executeTakeFirst())?.count??0}async function NX(J){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",J).executeTakeFirst())?.count??0}async function XX(J,$){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(J&&$){let X=P(J),W=P($);G=G.where("created_at",">=",X).where("created_at","<=",W)}return(await G.execute()).reduce((X,{quantity:W,count:Z})=>{return X[W]=Z,X},{})}async function WX(J,$){let G=P(J),N=P($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",N).whereNotNull("notified_at").execute()}async function ZX(J,$){let G=P(J),N=P($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",N).whereNotNull("purchased_at").execute()}async function YX(J,$){let G=P(J),N=P($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",N).whereNotNull("cancelled_at").execute()}async function LX(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function KX(J,$,G){let N=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",J);if($&&G){let W=P($),Z=P(G);N=N.where("created_at",">=",W).where("created_at","<=",Z)}return(await N.executeTakeFirst())?.count??0}async function FX(J,$){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(J&&$){let L=P(J),K=P($);G=G.where("created_at",">=",L).where("created_at","<=",K)}let N=await G.execute(),X=N.reduce((L,{count:K})=>L+K,0),W=N.find((L)=>L.status==="purchased")?.count??0,Z=X>0?W/X*100:0,Y=N.reduce((L,{status:K,count:Q})=>{return L[K]={count:Q,percentage:X>0?Q/X*100:0},L},{});return{totalConversionRate:Z,statusBreakdown:Y}}async function QX(J,$){let G=P(J),N=P($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",N).executeTakeFirst())?.count??0}async function MX(J,$){let G=A.selectFrom("waitlist_products").select(["created_at"]);if(J&&$){let W=P(J),Z=P($);G=G.where("created_at",">=",W).where("created_at","<=",Z)}let X=(await G.execute()).reduce((W,{created_at:Z})=>{let Y=(Z||"").split("T")[0]||"unknown";return W[Y]=(W[Y]||0)+1,W},{});return Object.entries(X).map(([W,Z])=>({date:W,count:Z})).sort((W,Z)=>W.date.localeCompare(Z.date))}var{randomUUIDv7:VX}=globalThis.Bun;import{db as H4}from"@stacksjs/database";import{formatDate as HX}from"@stacksjs/orm";var Z3={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Y3(J){return typeof J==="number"||J instanceof Date?HX(J):J}function n0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,X])=>X!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let X of["notified_at","purchased_at","cancelled_at"])if(G[X]!==void 0)G[X]=Y3(G[X]);let N=Z3[G.status];if(N&&G[N]===void 0&&!$[N])G[N]=HX(new Date);return G}async function xX(J){try{let $=VX(),G={...n0(J),uuid:$,status:J.status||"waiting"};await H4.insertInto("waitlist_products").values(G).executeTakeFirst();let N=await H4.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to create waitlist product");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function zX(J){if(!J.length)return 0;try{let $=J.map((N)=>({...n0(N),status:N.status||"waiting",uuid:VX()})),G=await H4.insertInto("waitlist_products").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as L3}from"@stacksjs/database";import{formatDate as K3}from"@stacksjs/orm";async function W1(J,$){try{if(!J)throw Error("Waitlist product ID is required for update");let G=await u0(J);if(!G)return;await L3.updateTable("waitlist_products").set({...n0($,G),updated_at:K3(new Date)}).where("id","=",J).execute();let N=await u0(J);if(!N)return;return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update waitlist product: ${G.message}`);throw G}}async function BX(J,$){return await W1(J,{status:$})}async function AX(J,$){return await W1(J,{quantity:$})}var O0={};z(O0,{updateWaitTimes:()=>uX,updateStatus:()=>lX,updateQueuePosition:()=>nX,updatePartySize:()=>cX,update:()=>R0,store:()=>mX,fetchWaitingWithQuotedTimes:()=>jX,fetchWaitingWithPartySizes:()=>CX,fetchWaiting:()=>fX,fetchTimeSeriesStats:()=>DX,fetchTablesTurnedToday:()=>hX,fetchSeatingRate:()=>IX,fetchSeatedStats:()=>yX,fetchSeatedBetweenDates:()=>qX,fetchNoShowStats:()=>gX,fetchCurrentWaitTimes:()=>vX,fetchCountByTablePreference:()=>SX,fetchCountByPartySize:()=>TX,fetchCountByDate:()=>UX,fetchCountByAllPartySizes:()=>PX,fetchConversionRates:()=>EX,fetchById:()=>i0,fetchBetweenDates:()=>wX,fetchAverageWaitTimes:()=>kX,fetchAll:()=>OX,destroy:()=>_X,bulkStore:()=>pX,bulkDestroy:()=>RX});import{db as V4}from"@stacksjs/database";async function _X(J){try{let $=await V4.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await V4.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function RX(J){if(!J.length)return 0;try{let $=await V4.deleteFrom("waitlist_restaurants").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as x}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function i0(J){return await x.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function OX(){return await x.selectFrom("waitlist_restaurants").selectAll().execute()}async function SX(){return(await x.selectFrom("waitlist_restaurants").select(["table_preference",x.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:G,count:N})=>{return $[G]=N,$},{})}async function UX(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let N=g($),X=g(G);return(await x.selectFrom("waitlist_restaurants").select(x.fn.count("id").as("count")).where("created_at",">=",N).where("created_at","<=",X).executeTakeFirst())?.count??0}async function TX(J){return(await x.selectFrom("waitlist_restaurants").select(x.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function PX(){return(await x.selectFrom("waitlist_restaurants").select(["party_size",x.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:G,count:N})=>{return $[G]=N,$},{})}async function wX(J,$){let G=g(J),N=g($);return await x.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",N).execute()}async function qX(J,$){let G=g(J),N=g($);return await x.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",N).where("status","=","seated").execute()}async function fX(){return await x.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function EX(){let J=await x.selectFrom("waitlist_restaurants").select(["status",x.fn.count("id").as("count")]).groupBy("status").execute(),$=J.reduce((W,{count:Z})=>W+Z,0),G=J.find((W)=>W.status==="seated")?.count??0,N=$>0?Number(G)/$*100:0,X=J.reduce((W,{status:Z,count:Y})=>{return W[Z]={count:Y,percentage:$>0?Y/$*100:0},W},{});return{totalConversionRate:N,statusBreakdown:X}}async function kX(){let J=await x.selectFrom("waitlist_restaurants").select([x.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),x.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:J?.avg_quoted_wait_time??0,averageActualWaitTime:J?.avg_actual_wait_time??0}}async function jX(){let J=await x.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((N,X)=>N+(X.quoted_wait_time??0),0),G=J.length>0?$/J.length:0;return{entries:J,totalQuotedWaitTime:$,averageQuotedWaitTime:G}}async function CX(){let J=await x.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((X,W)=>X+W.party_size,0),G=J.length>0?$/J.length:0,N=J.reduce((X,W)=>{return X[W.party_size]=(X[W.party_size]||0)+1,X},{});return{entries:J,totalPartySize:$,averagePartySize:G,partySizeBreakdown:N}}async function hX(){let J=new Date,$=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let N=g($),X=g(G),W=await x.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",N).where("check_in_time","<=",X).execute(),Z=W.length,Y=W.reduce((M,H)=>M+H.party_size,0),L=Z>0?Y/Z:0,K=W.reduce((M,H)=>{return M[H.table_preference]=(M[H.table_preference]||0)+1,M},{}),Q=W.reduce((M,H)=>{return M[H.party_size]=(M[H.party_size]||0)+1,M},{});return{totalTablesTurned:Z,averagePartySize:L,totalCustomersSeated:Y,breakdownByTablePreference:K,breakdownByPartySize:Q}}async function IX(J,$){let G=g(J),N=g($),X=await x.selectFrom("waitlist_restaurants").select(["status",x.fn.count("id").as("count")]).where("check_in_time",">=",G).where("check_in_time","<=",N).groupBy("status").execute(),W=X.reduce((K,{count:Q})=>K+Q,0),Z=X.find((K)=>K.status==="seated")?.count??0,Y=W>0?Number(Z)/W*100:0,L=X.reduce((K,{status:Q,count:M})=>{return K[Q]={count:M,percentage:W>0?M/W*100:0},K},{});return{totalEntries:W,seatedEntries:Z,seatingRate:Y,statusBreakdown:L}}async function gX(J,$){let G=g(J),N=g($),X=x.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",N),W=await x.selectFrom("waitlist_restaurants").select(x.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",N).executeTakeFirst(),Z=await X.execute(),Y=Z.length,L=W?.count&&W.count>0?Y/W.count*100:0,K=Z.reduce((R,S)=>R+(S.quoted_wait_time??0),0),Q=Y>0?K/Y:0,M=Z.reduce((R,S)=>R+S.party_size,0),H=Y>0?M/Y:0,_=Z.reduce((R,S)=>{return R[S.table_preference]=(R[S.table_preference]||0)+1,R},{}),O=Z.reduce((R,S)=>{return R[S.party_size]=(R[S.party_size]||0)+1,R},{});return{totalNoShows:Y,noShowRate:L,averageQuotedWaitTime:Q,averagePartySize:H,breakdownByTablePreference:_,breakdownByPartySize:O}}async function vX(){let J=await x.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=J.reduce((X,W)=>X+(W.quoted_wait_time||0),0),G=J.reduce((X,W)=>X+(W.actual_wait_time||0),0),N=J.length;return{averageQuoted:N>0?$/N:0,averageActual:N>0?G/N:0}}async function yX(){let J=Date.now()-86400000,$=await x.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),G=Array.from({length:24},(N,X)=>({hour:X,count:$.filter((W)=>{return W.seated_at===X}).length}));return{total:$.length,byHour:G}}async function DX(){return(await x.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,G)=>{let N=G.created_at;if(!$[N])$[N]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[N].total++,$[N][G.status]++,$},{})}var{randomUUIDv7:bX}=globalThis.Bun;import{db as z4}from"@stacksjs/database";import{formatDate as x4}from"@stacksjs/orm";var F3={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function Q3(J){if(typeof J==="number")return x4(J<=2147483647?J*1000:J);if(J instanceof Date)return x4(J);return J}function o0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,X])=>X!==void 0));for(let X of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[X]!==void 0)G[X]=Q3(G[X]);let N=F3[G.status];if(N&&G[N]===void 0&&!$[N])G[N]=x4(new Date);return G}async function mX(J){try{let $=bX(),G={...o0(J),status:J.status||"waiting",uuid:$};await z4.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let N=await z4.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to create restaurant waitlist entry");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function pX(J){if(!J.length)return 0;try{let $=J.map((N)=>({...o0(N),status:N.status||"waiting",uuid:bX()})),G=await z4.insertInto("waitlist_restaurants").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as M3}from"@stacksjs/database";import{formatDate as H3}from"@stacksjs/orm";async function R0(J,$){try{if(!J)throw Error("Restaurant waitlist entry ID is required for update");let G=await i0(J);if(!G)return;await M3.updateTable("waitlist_restaurants").set({...o0($,G),updated_at:H3(new Date)}).where("id","=",J).execute();let N=await i0(J);if(!N)return;return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${G.message}`);throw G}}async function lX(J,$){return await R0(J,{status:$})}async function cX(J,$){return await R0(J,{party_size:$})}async function uX(J,$,G){return await R0(J,{quoted_wait_time:$,...G===void 0?{}:{actual_wait_time:G}})}async function nX(J,$){return await R0(J,{queue_position:$})}var V3={products:Z1,restaurant:O0},x3=V3;var z3={coupons:Y1,customers:L1,devices:H1,errors:z1,giftCards:A1,orders:q1,payments:f1,products:g1,receipts:p1,restaurant:O0,shippings:F4,tax:Q4,waitlists:B4},mM=z3;export{B4 as waitlists,Q4 as tax,F4 as shippings,O0 as restaurant,p1 as receipts,g1 as products,f1 as payments,q1 as orders,A1 as giftCards,z1 as errors,H1 as devices,mM as default,L1 as customers,Y1 as coupons,z3 as commerce};
|
|
27
|
+
AND COALESCE(refund_amount, 0) + ${N(5)} <= amount`,[$,$,X,J,$]),Z=typeof W?.execute==="function"?await W.execute():W;if(Number(Z?.numUpdatedRows??Z?.[0]?.numUpdatedRows??Z?.numAffectedRows??Z?.affectedRows??Z?.[0]?.affectedRows??Z?.changes??0)>0){let H=await N0(J);if(H)return H;throw Error(`Payment with ID ${J} disappeared during refund`)}let Y=await N0(J);if(!Y)throw Error(`Payment with ID ${J} not found`);let K=String(Y.status||"");if(!j9.has(K))throw Error(`Payment status ${K||"unknown"} cannot be refunded`);let Q=Y,M=Number(Y.amount||0)-Number(Q.refundAmount??Q.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${M} minor units`)}var g1={};z(g1,{variants:()=>R$,units:()=>_$,reviews:()=>z$,manufacturers:()=>V$,items:()=>x$,default:()=>l9,categories:()=>H$});var H$={};z(H$,{updateParent:()=>X6,updateDisplayOrder:()=>G6,updateActiveStatus:()=>N6,update:()=>J6,store:()=>k1,removeChildCategories:()=>aJ,remove:()=>sJ,findOrCreateByName:()=>$6,fetchStats:()=>nJ,fetchRootCategories:()=>lJ,fetchChildCategories:()=>cJ,fetchCategoryTree:()=>oJ,fetchByName:()=>mJ,fetchById:()=>k,fetchByDisplayOrder:()=>uJ,fetchAll:()=>f1,fetchActive:()=>pJ,deactivateChildCategories:()=>rJ,deactivate:()=>eJ,compareCategoryGrowth:()=>iJ,bulkRemove:()=>dJ});import{db as x0}from"@stacksjs/database";import{db as w}from"@stacksjs/database";import{formatDate as f0}from"@stacksjs/orm";async function f1(){return await w.selectFrom("categories").selectAll().execute()}async function k(J){return await w.selectFrom("categories").where("id","=",J).selectAll().executeTakeFirst()}async function mJ(J){return await w.selectFrom("categories").where("name","=",J).selectAll().executeTakeFirst()}async function pJ(){return await w.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function lJ(){return await w.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function cJ(J){return await w.selectFrom("categories").where("parent_category_id","=",J).where("is_active","=",!0).selectAll().execute()}async function uJ(J=!0){let $=w.selectFrom("categories").where("is_active","=",!0).selectAll();if(J)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function nJ(){let J=await w.selectFrom("categories").select(w.fn.count("id").as("count")).executeTakeFirst(),$=await w.selectFrom("categories").where("is_active","=",!0).select(w.fn.count("id").as("count")).executeTakeFirst(),G=await w.selectFrom("categories").whereNull("parent_category_id").select(w.fn.count("id").as("count")).executeTakeFirst(),N=await w.selectFrom("categories").whereNotNull("image_url").select(w.fn.count("id").as("count")).executeTakeFirst(),X=new Date;X.setDate(X.getDate()-30);let W=f0(X),Z=await w.selectFrom("categories").where("created_at",">=",W).selectAll().limit(5).execute(),L=await w.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",w.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number($?.count||0),root_categories:Number(G?.count||0),child_categories:Number(J?.count||0)-Number(G?.count||0),with_images:Number(N?.count||0),recently_added:Z,top_parent_categories:L.map((Y)=>({id:String(Y.parent_category_id||""),name:String(Y.parent_name||""),child_count:Number(Y.child_count)}))}}async function iJ(J=30){let $=new Date,G=f0($),N=new Date;N.setDate($.getDate()-J);let X=f0(N),W=new Date(N);W.setDate(W.getDate()-1);let Z=f0(W),L=new Date(W);L.setDate(W.getDate()-J);let Y=f0(L),K=await w.selectFrom("categories").select(w.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",G).executeTakeFirst(),Q=await w.selectFrom("categories").select(w.fn.count("id").as("count")).where("created_at",">=",Y).where("created_at","<=",Z).executeTakeFirst(),M=Number(K?.count||0),H=Number(Q?.count||0),_=M-H,O=H!==0?_/H*100:M>0?100:0;return{current_period:M,previous_period:H,difference:_,percentage_change:O,days_range:J}}async function oJ(){let J=await f1(),$=new Map;J.forEach((X)=>{$.set(X.id,{...X,children:[]})});let G=[];J.forEach((X)=>{let W=$.get(X.id);if(X.parent_category_id){let Z=$.get(X.parent_category_id);if(Z)Z.children.push(W)}else G.push(W)}),G.sort((X,W)=>X.display_order-W.display_order);let N=(X)=>{X.sort((W,Z)=>W.display_order-Z.display_order),X.forEach((W)=>{if(W.children.length>0)N(W.children)})};return N(G),G}async function sJ(J){let $=await x0.deleteFrom("categories").where("id","=",J).executeTakeFirst();return F($)>0}async function dJ(J){if(!J.length)return 0;let $=await x0.deleteFrom("categories").where("id","in",J).executeTakeFirst();return F($)}async function aJ(J){let $=await x0.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return F($)}async function eJ(J){if(!await k(J))throw Error(`Category with ID ${J} not found`);return!!await x0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",J).executeTakeFirst()}async function rJ(J){let $=await x0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",J).execute();return Number($.length)||0}var{randomUUIDv7:C9}=globalThis.Bun;import{db as tJ}from"@stacksjs/database";import{HttpError as Q$}from"@stacksjs/error-handling";import{isUniqueViolation as h9}from"@stacksjs/orm";import{slug as I9}from"@stacksjs/strings";async function k1(J){try{let $=J.parent_category_id?Number(J.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new Q$(422,"Parent category ID must be a positive integer");if($&&!await k($))throw new Q$(422,`Parent category with ID ${J.parent_category_id} not found`);let G={...J,uuid:C9(),is_active:J.is_active??!0,parent_category_id:J.parent_category_id||null},N=await tJ.insertInto("categories").values(G).returningAll().executeTakeFirst();if(!N)throw Error("Failed to create category");return N}catch($){if($ instanceof Q$)throw $;if(h9($))throw new Q$(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function $6(J){if(!J.name)throw Error("Name is required");let $=await tJ.selectFrom("categories").selectAll().where("name","=",J.name).executeTakeFirst();if($)return $;let G={name:J.name,slug:I9(J.name),is_active:J.is_active??!0,display_order:0};return await k1(G)}import{db as k0}from"@stacksjs/database";import{HttpError as V0}from"@stacksjs/error-handling";import{formatDate as M$,isUniqueViolation as g9}from"@stacksjs/orm";async function J6(J,$){if(!await k(J))return;if(Object.hasOwn($,"parent_category_id")){let N=$.parent_category_id?Number($.parent_category_id):void 0;if(N!==void 0&&(!Number.isSafeInteger(N)||N<=0))throw new V0(422,"Parent category ID must be a positive integer");if(N===J)throw new V0(422,"A category cannot be its own parent");if(N&&!await k(N))throw new V0(422,`Parent category with ID ${$.parent_category_id} not found`);if(N&&await W6(J,String(N)))throw new V0(422,"This operation would create a circular category hierarchy")}try{let N=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},X=await k0.updateTable("categories").set({...$,...N,updated_at:M$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)return;return X}catch(N){if(N instanceof V0)throw N;if(g9(N))throw new V0(409,"A category with this name or slug already exists");if(N instanceof Error)throw Error(`Failed to update category: ${N.message}`);throw N}}async function G6(J,$){if(!await k(J))throw Error(`Category with ID ${J} not found`);try{return await k0.updateTable("categories").set({display_order:$,updated_at:M$(new Date)}).where("id","=",J).execute(),await k(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update category display order: ${N.message}`);throw N}}async function N6(J,$){if(!await k(J))throw Error(`Category with ID ${J} not found`);try{return await k0.updateTable("categories").set({is_active:$,updated_at:M$(new Date)}).where("id","=",J).execute(),await k(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update category active status: ${N.message}`);throw N}}async function X6(J,$){if(!await k(J))throw Error(`Category with ID ${J} not found`);if($){let N=Number($);if(N===J)throw Error("A category cannot be its own parent");if(!await k(N))throw Error(`Parent category with ID ${$} not found`);if(await W6(J,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let N={updated_at:M$(new Date)};if($===null)await k0.updateTable("categories").set({...N,parent_category_id:null}).where("id","=",J).execute();else await k0.updateTable("categories").set({...N,parent_category_id:$}).where("id","=",J).execute();return await k(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update category parent: ${N.message}`);throw N}}async function W6(J,$){let G=Number($),N=new Set;while(G){if(N.has(G))return!0;if(G===J)return!0;N.add(G);let X=await k(G),W=X?.parent_category_id??X?.parentCategoryId;if(!X||!W)return!1;G=Number(W)}return!1}var x$={};z(x$,{updateInventory:()=>B6,updateAvailability:()=>z6,update:()=>V6,store:()=>H6,fetchTopProducts:()=>F6,fetchById:()=>u,fetchAll:()=>K6,destroy:()=>L6,bulkStore:()=>x6,bulkDestroy:()=>Y6});import{db as Z6}from"@stacksjs/database";async function L6(J){try{let $=await Z6.deleteFrom("products").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function Y6(J){if(!J.length)return 0;try{let $=await Z6.deleteFrom("products").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as a,sql as v9}from"@stacksjs/database";async function u(J){let $=await a.selectFrom("products").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,N=null;if($.manufacturer_id)G=await a.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)N=await a.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:G,category:N}}return}async function K6(){let J=await a.selectFrom("products").selectAll().execute(),$=J.map((K)=>K.manufacturer_id).filter((K)=>K!==null&&K!==void 0),G=J.map((K)=>K.category_id).filter((K)=>K!==null&&K!==void 0),N=a.selectFrom("manufacturers"),X=a.selectFrom("categories");if($.length>0)N=N.where("id","in",$);if(G.length>0)X=X.where("id","in",G);let W=await N.selectAll().execute(),Z=await X.selectAll().execute(),L=W.reduce((K,Q)=>{return K[Q.id]=Q,K},{}),Y=Z.reduce((K,Q)=>{return K[Q.id]=Q,K},{});return J.map((K)=>({...K,manufacturer:K.manufacturer_id?L[K.manufacturer_id]:null,category:K.category_id?Y[K.category_id]:null}))}async function F6(J=5){try{return(await a.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",a.fn.sum("order_items.quantity").as("units_sold"),v9`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(J).execute()).map((G)=>({id:Number(G.id),name:String(G.name??"Unnamed product"),units_sold:Number(G.units_sold??0),revenue:Number(G.revenue??0),inventory_count:Number(G.inventory_count??0)}))}catch($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:Q6}=globalThis.Bun;import{db as M6}from"@stacksjs/database";async function H6(J){try{let $={...J,uuid:Q6()},G=await M6.insertInto("products").values($).executeTakeFirst();if(!G)throw Error("Failed to create product item");let N=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows),X=await u(N);if(!X)throw Error("Failed to create product item");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function x6(J){if(!J.length)return 0;let $=0;try{return await M6.transaction().execute(async(G)=>{for(let N of J){let X={...N,uuid:Q6()};await G.insertInto("products").values(X).execute(),$++}}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product items in bulk: ${G.message}`);throw G}}import{db as j1}from"@stacksjs/database";import{formatDate as C1}from"@stacksjs/orm";async function V6(J,$){try{if(!J)throw Error("Product item ID is required for update");let G=await j1.updateTable("products").set({...$,updated_at:C1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item: ${G.message}`);throw G}}async function z6(J,$){if(!await u(J))throw Error(`Product item with ID ${J} not found`);try{return await j1.updateTable("products").set({is_available:$,updated_at:C1(new Date)}).where("id","=",J).execute(),await u(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update product item availability: ${N.message}`);throw N}}async function B6(J,$){let G=await u(J);if(!G)throw Error(`Product item with ID ${J} not found`);let N={updated_at:C1(new Date)};if($!==void 0)N.inventory_count=$;if(Object.keys(N).length===1)return G;try{return await j1.updateTable("products").set(N).where("id","=",J).execute(),await u(J)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update inventory information: ${X.message}`);throw X}}var V$={};z(V$,{updateFeaturedStatus:()=>I6,updateByUuid:()=>g6,update:()=>h6,store:()=>k6,fetchWithProductCount:()=>q6,fetchFeatured:()=>w6,fetchByUuid:()=>U6,fetchById:()=>S6,fetchByCountry:()=>P6,fetchAll:()=>O6,destroy:()=>_6,bulkStore:()=>j6,bulkDestroy:()=>R6});import{db as A6}from"@stacksjs/database";async function _6(J){try{let $=await A6.deleteFrom("manufacturers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function R6(J){if(!J.length)return 0;try{let $=await A6.deleteFrom("manufacturers").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as n}from"@stacksjs/database";function O6(){return n.selectFrom("manufacturers").selectAll().execute()}async function S6(J){return await n.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function U6(J){return await n.selectFrom("manufacturers").where("uuid","=",J).selectAll().executeTakeFirst()}async function w6(J=10){return await n.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(J).execute()}async function P6(J,$={}){let G=$.page||1,N=$.limit||2,X=await n.selectFrom("manufacturers").select(n.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),W=Number(X?.total||0),Z=await n.selectFrom("manufacturers").selectAll().where("country","=",J).limit(N).offset((G-1)*N).execute(),L=Math.ceil(W/N);return{data:Z,paging:{total_records:W,page:G,total_pages:L},next_cursor:G<L?G+1:null}}async function q6(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:E6}=globalThis.Bun;import{db as f6}from"@stacksjs/database";import{HttpError as T6}from"@stacksjs/error-handling";import{isUniqueViolation as y9}from"@stacksjs/orm";async function k6(J){try{let $={...J,uuid:E6(),featured:J.featured??!1},G=await f6.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create manufacturer");return G}catch($){if($ instanceof T6)throw $;if(y9($))throw new T6(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function j6(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={...G,uuid:E6(),featured:G.featured??!1};await f6.insertInto("manufacturers").values(N).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${G.message}`);throw G}}import{db as h1}from"@stacksjs/database";import{HttpError as C6}from"@stacksjs/error-handling";import{formatDate as I1,isUniqueViolation as D9}from"@stacksjs/orm";async function h6(J,$){try{if(!J)throw Error("Manufacturer ID is required for update");let G=await h1.updateTable("manufacturers").set({...$,updated_at:I1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof C6)throw G;if(D9(G))throw new C6(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to update manufacturer: ${G.message}`);throw G}}async function I6(J,$){try{let G=await h1.updateTable("manufacturers").set({featured:$,updated_at:I1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer featured status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${G.message}`);throw G}}async function g6(J,$){try{let G=await h1.updateTable("manufacturers").set({...$,updated_at:I1(new Date)}).where("uuid","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update manufacturer");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update manufacturer: ${G.message}`);throw G}}var z$={};z(z$,{updateVotes:()=>d6,update:()=>s6,store:()=>n6,fetchMostHelpfulByProductId:()=>u6,fetchByUserId:()=>l6,fetchByProductId:()=>p6,fetchById:()=>b6,fetchApprovedByProductId:()=>c6,fetchAll:()=>m6,destroy:()=>y6,bulkDestroy:()=>D6});import{db as v6}from"@stacksjs/database";async function y6(J){try{let $=await v6.deleteFrom("reviews").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function D6(J){if(!J.length)return 0;try{let $=await v6.deleteFrom("reviews").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as z0}from"@stacksjs/database";async function b6(J){return await z0.selectFrom("reviews").where("id","=",J).selectAll().executeTakeFirst()}async function m6(){return await z0.selectFrom("reviews").selectAll().execute()}async function p6(J){return await z0.selectFrom("reviews").where("product_id","=",J).selectAll().execute()}async function l6(J){return await z0.selectFrom("reviews").where("customer_id","=",J).selectAll().execute()}async function c6(J){return await z0.selectFrom("reviews").where("product_id","=",J).where("is_approved","=",!0).selectAll().execute()}async function u6(J){return await z0.selectFrom("reviews").where("product_id","=",J).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:b9}=globalThis.Bun;import{db as m9}from"@stacksjs/database";async function n6(J){try{let $={...J,uuid:b9(),is_verified_purchase:J.is_verified_purchase??!1,is_approved:J.is_approved??!1,helpful_votes:J.helpful_votes??0,unhelpful_votes:J.unhelpful_votes??0,is_featured:J.is_featured??!1},G=await m9.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create review");return G}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${$.message}`)}throw $}}import{db as i6}from"@stacksjs/database";import{formatDate as o6}from"@stacksjs/orm";async function s6(J,$){try{if(!J)throw Error("Review ID is required for update");let G=await i6.updateTable("reviews").set({...$,updated_at:o6(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review: ${G.message}`);throw G}}async function d6(J,$,G=!0){try{let N=$==="helpful"?"helpful_votes":"unhelpful_votes",X=G?`COALESCE("${N}", 0) + 1`:`MAX(COALESCE("${N}", 0) - 1, 0)`,W=await i6.unsafe(`UPDATE "reviews" SET "${N}" = ${X}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[o6(new Date),J]).execute(),Z=Array.isArray(W)?W[0]:W;if(!Z)throw Error("Failed to update review votes");return Z}catch(N){if(N instanceof Error)throw TypeError(`Failed to update review votes: ${N.message}`);throw N}}var _$={};z(_$,{updateDefaultStatus:()=>K2,update:()=>L2,store:()=>N2,getDefaultUnit:()=>Z2,formatUnitOptions:()=>W2,fetchById:()=>$2,fetchAll:()=>J2,destroy:()=>e6,bulkUpdate:()=>Y2,bulkStore:()=>X2,bulkDestroy:()=>r6});import{db as a6}from"@stacksjs/database";async function e6(J){try{let $=await a6.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function r6(J){if(!J.length)return 0;try{let $=await a6.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as t6}from"@stacksjs/database";async function $2(J){return await t6.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function J2(){return await t6.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:G2}=globalThis.Bun;import{db as j0}from"@stacksjs/database";async function N2(J){try{return await j0.transaction(async($)=>{let G={...J,uuid:G2()},N=await $.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!N)throw Error("Failed to create product unit");if(G.is_default&&G.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",N.id).execute();return N})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function X2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={...G,uuid:G2()},X=await j0.insertInto("product_units").values(N).returningAll().executeTakeFirst();if(N.is_default&&N.type&&X)await j0.updateTable("product_units").set({is_default:!1}).where("type","=",N.type).where("id","!=",X.id).execute();$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product units in bulk: ${G.message}`);throw G}}function W2(J){try{let $=j0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(J)$=$.where("type","=",J);return $=$.orderBy("name"),$.execute().then((G)=>G.map((N)=>({id:String(N.id),name:N.name,abbreviation:N.abbreviation,is_default:N.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function Z2(J){try{return await j0.selectFrom("product_units").selectAll().where("type","=",J).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as B$}from"@stacksjs/database";import{formatDate as A$}from"@stacksjs/orm";async function L2(J,$){try{if(!J)throw Error("Product unit ID is required for update");return await B$.transaction(async(G)=>{let N=await G.selectFrom("product_units").select(["type","is_default"]).where("id","=",J).executeTakeFirst();if(!N)return;let X=$.type??N.type;if(($.is_default??Boolean(N.is_default))&&X)await G.updateTable("product_units").set({is_default:!1,updated_at:A$(new Date)}).where("type","=",X).where("id","!=",J).execute();let Z=await G.updateTable("product_units").set({...$,updated_at:A$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit: ${G.message}`);throw G}}async function Y2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N=G;if(!N.id)continue;let X=N.data&&typeof N.data==="object"?N.data:{...N};delete X.id;let W=await B$.updateTable("product_units").set({...X,updated_at:A$(new Date)}).where("id","=",N.id).executeTakeFirst(),Z=X;if(Z.is_default===!0&&Z.type)await B$.updateTable("product_units").set({is_default:!1}).where("type","=",Z.type).where("id","!=",N.id).execute();if(Number(W.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product units in bulk: ${G.message}`);throw G}}async function K2(J,$){try{return await B$.transaction(async(G)=>{let N=await G.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!N)return!1;let X=A$(new Date);if($&&N.type)await G.updateTable("product_units").set({is_default:!1,updated_at:X}).where("type","=",N.type).where("id","!=",J).execute();return await G.updateTable("product_units").set({is_default:$,updated_at:X}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product unit default status: ${G.message}`);throw G}}var R$={};z(R$,{update:()=>w2,store:()=>A2,generateVariantCombinations:()=>O2,formatVariantOptions:()=>R2,fetchById:()=>x2,fetchAll:()=>V2,destroy:()=>Q2,bulkUpdate:()=>P2,bulkStore:()=>_2,bulkDestroy:()=>M2});import{db as F2}from"@stacksjs/database";async function Q2(J){try{let $=await F2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function M2(J){if(!J.length)return 0;try{let $=await F2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as H2}from"@stacksjs/database";async function x2(J){return await H2.selectFrom("product_variants").where("id","=",J).selectAll().executeTakeFirst()}async function V2(){return await H2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:z2}=globalThis.Bun;import{db as B2}from"@stacksjs/database";async function A2(J){try{let $={...J,uuid:z2()},G=await B2.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product variant");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function _2(J){if(!J.length)return 0;let $=0;try{for(let G of J){let N={...G,uuid:z2()};await B2.insertInto("product_variants").values(N).execute(),$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${G.message}`);throw G}}function R2(J){if(!J||!J.length)return JSON.stringify([]);let $=J.map((G)=>G.trim()).filter(Boolean);return JSON.stringify($)}function O2(J){let $=Object.keys(J);if(!$.length)return[];function G(N,X){if(N===$.length)return[X];let W=$[N],Z=J[W]??[],L=[];for(let Y of Z){let K={...X,[W]:Y};L.push(...G(N+1,K))}return L}return G(0,{})}import{db as S2}from"@stacksjs/database";import{formatDate as U2}from"@stacksjs/orm";async function w2(J,$){try{let G=await S2.updateTable("product_variants").set({...$,updated_at:U2(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variant: ${G.message}`);throw G}}async function P2(J){if(!J.length)return 0;let $=0;try{for(let G of J){if(!G.id)continue;let N=await S2.updateTable("product_variants").set({...G,updated_at:U2(new Date)}).where("id","=",G.id).executeTakeFirst();if(Number(N.numUpdatedRows)>0)$++}return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${G.message}`);throw G}}var p9={categories:H$,items:x$,manufacturers:V$,reviews:z$,units:_$,variants:R$},l9=p9;var p1={};z(p1,{updateStatus:()=>b2,updatePrintJob:()=>m2,update:()=>D2,store:()=>v2,fetchSuccessRate:()=>j2,fetchPrintsPerHour:()=>I2,fetchPrintTimeStats:()=>h2,fetchPrintJobStats:()=>k2,fetchPageStats:()=>C2,fetchById:()=>B0,fetchAll:()=>f2,destroy:()=>T2,bulkStore:()=>y2,bulkDestroy:()=>E2});import{db as q2}from"@stacksjs/database";async function T2(J){try{let $=await q2.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function E2(J){if(!J.length)return 0;try{let $=await q2.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as v1}from"@stacksjs/database";import{formatDate as c9}from"@stacksjs/orm";function b(J){return c9(J)}function u9(J){if(J instanceof Date)return Number.isNaN(J.getTime())?null:J;if(typeof J==="number"){let N=new Date(J<=2147483647?J*1000:J);return Number.isNaN(N.getTime())?null:N}let $=String(J||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let N=new Date(Number($)*1000);return Number.isNaN(N.getTime())?null:N}let G=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(G.getTime())?null:G}async function B0(J){return await v1.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function f2(){return await v1.selectFrom("receipts").selectAll().execute()}async function k2(J,$){let G=b(J),N=b($),X=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(W)=>W.where("timestamp",">=",G).where("timestamp","<=",N));return{total:X.total,success:X.success,failed:X.failed,warning:X.warning,averageSize:Math.round(X.averageSize),averagePages:Math.round(X.averagePages),averageDuration:Math.round(X.averageDuration)}}async function j2(J,$){let G=b(J),N=b($),X=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(Z)=>Z.where("timestamp",">=",G).where("timestamp","<=",N));return{successRate:X.total>0?Math.round(X.success/X.total*100):0,total:X.total,success:X.success,failed:X.failed,warning:X.warning}}async function C2(J,$){let G=b(J),N=b($),X=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(W)=>W.where("timestamp",">=",G).where("timestamp","<=",N));return{totalPages:X.totalPages,averagePagesPerReceipt:Math.round(X.averagePagesPerReceipt),totalReceipts:X.totalReceipts}}async function h2(J,$){let G=b(J),N=b($),X=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(W)=>W.where("timestamp",">=",G).where("timestamp","<=",N));return{averageDuration:Math.round(X.averageDuration),minDuration:X.minDuration,maxDuration:X.maxDuration,totalJobs:X.totalJobs}}async function I2(J,$){let G=typeof J==="number"?J:J.getTime(),N=typeof $==="number"?$:$.getTime(),X=b(J),W=b($),Z=await v1.selectFrom("receipts").where("timestamp",">=",X).where("timestamp","<=",W).selectAll().execute(),L=Z.length,Y=Math.ceil((N-G)/3600000),K=Y>0?Math.round(L/Y):0,Q=Array.from({length:24},(M,H)=>({hour:H,count:0}));return Z.forEach((M)=>{let H=u9(M.timestamp);if(!H)return;Q[H.getHours()].count++}),{totalPrints:L,totalHours:Y,printsPerHour:K,hourlyBreakdown:Q}}var{randomUUIDv7:g2}=globalThis.Bun;import{db as D1}from"@stacksjs/database";import{formatDate as y1}from"@stacksjs/orm";function C0(J){try{if(typeof J==="number")return y1(J<=2147483647?J*1000:J);if(typeof J==="string"&&/^\d{10}$/.test(J))return y1(Number(J)*1000);return y1(J)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function v2(J){try{let $=g2(),G={...J,timestamp:C0(J.timestamp),uuid:$};await D1.insertInto("receipts").values(G).executeTakeFirst();let N=await D1.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to create receipt");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function y2(J){if(!J.length)return 0;try{let $=J.map((N)=>({...N,timestamp:C0(N.timestamp),uuid:g2()})),G=await D1.insertInto("receipts").values($).executeTakeFirst();return Number(G.numInsertedOrUpdatedRows??G.numAffectedRows??G.affectedRows??G.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as b1}from"@stacksjs/database";import{formatDate as m1}from"@stacksjs/orm";async function D2(J,$){try{if(!J)throw Error("Receipt ID is required for update");let G={...$,...$.timestamp===void 0?{}:{timestamp:C0($.timestamp)},updated_at:m1(new Date)};await b1.updateTable("receipts").set(G).where("id","=",J).execute();let N=await B0(J);if(!N)return;return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt: ${G.message}`);throw G}}async function b2(J,$){try{await b1.updateTable("receipts").set({status:$,updated_at:m1(new Date)}).where("id","=",J).execute();let G=await B0(J);if(!G)throw Error("Failed to update receipt status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update receipt status: ${G.message}`);throw G}}async function m2(J,$,G,N){try{let X={updated_at:m1(new Date)};if($!==void 0)X.size=$;if(G!==void 0)X.pages=G;if(N!==void 0)X.duration=N;await b1.updateTable("receipts").set(X).where("id","=",J).execute();let W=await B0(J);if(!W)throw Error("Failed to update receipt job information");return W}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt job information: ${X.message}`);throw X}}var F4={};z(F4,{zones:()=>G1,tracking:()=>r$,routes:()=>q$,rates:()=>l$,methods:()=>y$,licenses:()=>h$,drivers:()=>k$,digital:()=>E$,default:()=>Z3});var q$={};z(q$,{validateDeliveryRouteWrite:()=>A0,updateStops:()=>a2,updateMetrics:()=>e2,updateLastActive:()=>s2,update:()=>d2,store:()=>o2,fetchById:()=>S$,fetchByDriver:()=>i2,fetchAll:()=>u2,fetchActive:()=>n2,destroy:()=>l2,bulkDestroy:()=>c2,DeliveryRouteInputError:()=>h});import{db as p2}from"@stacksjs/database";async function l2(J){try{let $=await p2.deleteFrom("delivery_routes").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function c2(J){if(!J.length)return 0;try{let $=await p2.deleteFrom("delivery_routes").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as O$}from"@stacksjs/database";async function S$(J){return await O$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function u2(){return await O$.selectFrom("delivery_routes").selectAll().execute()}async function n2(){return await O$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function i2(J){return await O$.selectFrom("delivery_routes").where("driver","=",J).selectAll().execute()}var{randomUUIDv7:o9}=globalThis.Bun;import{db as l1}from"@stacksjs/database";function X0(J,$){let G={};for(let[N,X]of Object.entries($))for(let W of X){if(!Object.prototype.hasOwnProperty.call(J,W)||J[W]===void 0)continue;G[N]=J[W];break}return G}function h0(J){return X0(J,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function i(J){return X0(J,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function I0(J){return X0(J,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function g0(J){return X0(J,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function v0(J){return X0(J,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function y0(J){return X0(J,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function U$(J){return X0(J,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as n9}from"@stacksjs/database";class h extends TypeError{constructor(J){super(J);this.name="DeliveryRouteInputError"}}function w$(J,$,G){return Number(J[G]??$?.[G])}function i9(J,$){let G=J.last_active??$?.last_active;if(G instanceof Date)return G.getTime();if(typeof G==="number")return G;if(typeof G==="string"&&/^\d{10,13}$/.test(G))return Number(G);return Number.NaN}async function A0(J,$){let G=w$(J,$,"driver_id"),N=w$(J,$,"stops"),X=w$(J,$,"delivery_time"),W=w$(J,$,"total_distance"),Z=i9(J,$);if(!Number.isSafeInteger(G)||G<1)throw new h("Driver must be a positive integer.");if(!Number.isSafeInteger(N)||N<0)throw new h("Stops must be a non-negative integer.");if(!Number.isSafeInteger(X)||X<0)throw new h("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(W)||W<0)throw new h("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(Z)||Z<0)throw new h("Last active must be a valid Unix timestamp.");let L=await n9.selectFrom("drivers").where("id","=",G).select(["id","name","vehicle_number"]).executeTakeFirst();if(!L)throw new h(`Driver ${G} was not found.`);return{...J,driver_id:Number(L.id),driver:L.name,vehicle:L.vehicle_number}}async function o2(J){try{let $=o9(),G=U$(J),X={...await A0(G),uuid:$};await l1.insertInto("delivery_routes").values(X).executeTakeFirst();let W=await l1.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!W)throw Error("Failed to create delivery route");return W}catch($){if($ instanceof h)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function s2(J){try{await l1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",J).execute();let $=await S$(J);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as P$}from"@stacksjs/database";import{formatDate as c1}from"@stacksjs/orm";async function d2(J,$){try{if(!J)throw Error("Delivery route ID is required for update");let G=await P$.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let N=U$($),X=await A0(N,G),W=await P$.updateTable("delivery_routes").set({...X,updated_at:c1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!W)return;return W}catch(G){if(G instanceof h)throw G;if(G instanceof Error)throw TypeError(`Failed to update delivery route: ${G.message}`);throw G}}async function a2(J,$){try{let G=await P$.updateTable("delivery_routes").set({stops:$,updated_at:c1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update delivery route stops");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery route stops: ${G.message}`);throw G}}async function e2(J,$,G){try{let N={updated_at:c1(new Date)};if($!==void 0)N.delivery_time=$;if(G!==void 0)N.total_distance=G;let X=await P$.updateTable("delivery_routes").set(N).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery metrics");return X}catch(N){if(N instanceof Error)throw TypeError(`Failed to update delivery metrics: ${N.message}`);throw N}}var E$={};z(E$,{updateStatus:()=>KG,updateDeliverySettings:()=>FG,update:()=>YG,store:()=>ZG,softDelete:()=>t2,fetchById:()=>NG,fetchAll:()=>XG,destroy:()=>r2,bulkStore:()=>LG,bulkSoftDelete:()=>JG,bulkDestroy:()=>$G});import{db as T$}from"@stacksjs/database";async function r2(J){try{let $=await T$.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function t2(J){try{let $=await T$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function $G(J){if(!J.length)return 0;try{let $=await T$.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function JG(J){if(!J.length)return 0;try{let $=await T$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as GG}from"@stacksjs/database";async function NG(J){return await GG.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function XG(){return await GG.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:WG}=globalThis.Bun;import{db as u1}from"@stacksjs/database";async function ZG(J){try{let $=WG(),G={...g0(J),uuid:$};await u1.insertInto("digital_deliveries").values(G).executeTakeFirst();let N=await u1.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created digital delivery");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function LG(J){if(!J.length)return 0;try{let $=J.map((N)=>({...g0(N),uuid:WG()})),G=await u1.insertInto("digital_deliveries").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as n1}from"@stacksjs/database";import{formatDate as i1}from"@stacksjs/orm";async function YG(J,$){try{if(!J)throw Error("Digital delivery ID is required for update");let G=await n1.updateTable("digital_deliveries").set({...g0($),updated_at:i1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery: ${G.message}`);throw G}}async function KG(J,$){try{let G=await n1.updateTable("digital_deliveries").set({status:$,updated_at:i1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update digital delivery status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update digital delivery status: ${G.message}`);throw G}}async function FG(J,$,G,N,X){try{let W={updated_at:i1(new Date)};if($!==void 0)W.download_limit=$;if(G!==void 0)W.expiry_days=G;if(N!==void 0)W.requires_login=N;if(X!==void 0)W.automatic_delivery=X;let Z=await n1.updateTable("digital_deliveries").set(W).where("id","=",J).returningAll().executeTakeFirst();if(!Z)throw Error("Failed to update delivery settings");return Z}catch(W){if(W instanceof Error)throw TypeError(`Failed to update delivery settings: ${W.message}`);throw W}}var k$={};z(k$,{updateStatus:()=>RG,updateContact:()=>OG,update:()=>_G,store:()=>BG,fetchById:()=>f$,fetchAll:()=>MG,destroy:()=>xG,bulkStore:()=>AG,bulkDestroy:()=>VG});import{db as HG}from"@stacksjs/database";import{db as QG}from"@stacksjs/database";async function f$(J){return await QG.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function MG(){return await QG.selectFrom("drivers").selectAll().execute()}async function xG(J){try{let $=await HG.deleteFrom("drivers").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function VG(J){if(!J.length)return 0;let $=0;try{return await HG.transaction().execute(async(G)=>{for(let N of J)if(await f$(N))await G.deleteFrom("drivers").where("id","=",N).execute(),$++}),$}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${G.message}`);throw G}}var{randomUUIDv7:zG}=globalThis.Bun;import{db as o1}from"@stacksjs/database";async function BG(J){try{let $=zG(),G={...y0(J),uuid:$};await o1.insertInto("drivers").values(G).executeTakeFirst();let N=await o1.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created driver");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function AG(J){if(!J.length)return 0;try{let $=J.map((N)=>({...y0(N),uuid:zG()})),G=await o1.insertInto("drivers").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as s1}from"@stacksjs/database";import{formatDate as d1}from"@stacksjs/orm";async function _G(J,$){try{if(!J)throw Error("Driver ID is required for update");let G=await s1.updateTable("drivers").set({...y0($),updated_at:d1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver: ${G.message}`);throw G}}async function RG(J,$){try{let G=await s1.updateTable("drivers").set({status:$,updated_at:d1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update driver status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update driver status: ${G.message}`);throw G}}async function OG(J,$){try{let G={updated_at:d1(new Date)};if($!==void 0)G.phone=$;let N=await s1.updateTable("drivers").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!N)throw Error("Failed to update contact information");return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update contact information: ${G.message}`);throw G}}var h$={};z(h$,{validateLicenseKeyWrite:()=>W0,updateStatus:()=>gG,updateExpiration:()=>vG,update:()=>IG,store:()=>CG,softDelete:()=>UG,fetchById:()=>TG,fetchAll:()=>EG,destroy:()=>SG,bulkStore:()=>hG,bulkSoftDelete:()=>PG,bulkDestroy:()=>wG,LicenseKeyInputError:()=>q});import{db as j$}from"@stacksjs/database";async function SG(J){try{let $=await j$.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function UG(J){try{let $=await j$.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function wG(J){if(!J.length)return 0;try{let $=await j$.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function PG(J){if(!J.length)return 0;try{let $=await j$.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as qG}from"@stacksjs/database";async function TG(J){return await qG.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst()}async function EG(){return await qG.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:jG}=globalThis.Bun;import{db as r1}from"@stacksjs/database";import{db as a1}from"@stacksjs/database";var fG=["Standard License","Premium License","Enterprise License"],kG=["active","inactive","unassigned"];class q extends TypeError{constructor(J){super(J);this.name="LicenseKeyInputError"}}function D0(J,$,G){return J[G]!==void 0?J[G]:$?.[G]}function e1(J,$,G,N){let X=D0(J,$,G);if(X===void 0||X===null||X==="")return null;let W=Number(X);if(!Number.isSafeInteger(W)||W<1)throw new q(`${N} must be a positive integer or null.`);return W}function s9(J){if(typeof J==="number")return J>2147483647?Math.floor(J/1000):J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return J.length===13?Math.floor(Number(J)/1000):Number(J);if(typeof J==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(J)?`${J.replace(" ","T")}Z`:J;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function W0(J,$){let G=String(D0(J,$,"key")||"").trim().toUpperCase(),N=String(D0(J,$,"template")||""),X=String(D0(J,$,"status")||""),W=s9(D0(J,$,"expiry_date")),Z=e1(J,$,"customer_id","Customer"),L=e1(J,$,"product_id","Product"),Y=e1(J,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(G))throw new q("License key must use five groups of four uppercase letters or numbers.");if(!fG.includes(N))throw new q(`Template must be one of: ${fG.join(", ")}.`);if(!kG.includes(X))throw new q(`Status must be one of: ${kG.join(", ")}.`);if(!Number.isSafeInteger(W)||W<0||W>2147483647)throw new q("Expiry date must be a Unix timestamp between 1970 and 2038.");let[K,Q,M]=await Promise.all([Z?a1.selectFrom("customers").where("id","=",Z).select("id").executeTakeFirst():null,L?a1.selectFrom("products").where("id","=",L).select("id").executeTakeFirst():null,Y?a1.selectFrom("orders").where("id","=",Y).select(["id","customer_id"]).executeTakeFirst():null]);if(Z&&!K)throw new q(`Customer ${Z} was not found.`);if(L&&!Q)throw new q(`Product ${L} was not found.`);if(Y&&!M)throw new q(`Order ${Y} was not found.`);if(Z&&M?.customer_id&&Number(M.customer_id)!==Z)throw new q(`Order ${Y} belongs to Customer ${M.customer_id}, not Customer ${Z}.`);return{...J,key:G,template:N,expiry_date:W,status:X,customer_id:Z,product_id:L,order_id:Y}}async function CG(J){try{let $=jG(),G=v0(J),N={...await W0(G),uuid:$};await r1.insertInto("license_keys").values(N).executeTakeFirst();let X=await r1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created license key");return X}catch($){if($ instanceof q)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new q("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function hG(J){if(!J.length)return 0;try{let $=await Promise.all(J.map(async(N)=>({...await W0(v0(N)),uuid:jG()}))),G=await r1.insertInto("license_keys").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof q)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as C$}from"@stacksjs/database";import{formatDate as t1}from"@stacksjs/orm";async function IG(J,$){try{if(!J)throw Error("License key ID is required for update");let G=await C$.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let N=v0($),X=await W0(N,G),W=await C$.updateTable("license_keys").set({...X,updated_at:t1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!W)return;return W}catch(G){if(G instanceof q)throw G;if(G instanceof Error){if(G.message.includes("UNIQUE constraint failed: license_keys.key"))throw new q("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${G.message}`)}throw G}}async function gG(J,$){try{let G=await C$.updateTable("license_keys").set({status:$,updated_at:t1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update license key status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update license key status: ${G.message}`);throw G}}async function vG(J,$){try{let G={updated_at:t1(new Date)};if($!==void 0)G.expiry_date=$;let N=await C$.updateTable("license_keys").set(G).where("id","=",J).returningAll().executeTakeFirst();if(!N)throw Error("Failed to update expiration information");return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update expiration information: ${G.message}`);throw G}}var y$={};z(y$,{updateStatus:()=>sG,updatePricing:()=>dG,update:()=>oG,store:()=>cG,softDelete:()=>DG,getActiveShippingMethods:()=>iG,formatShippingOptions:()=>nG,fetchById:()=>v$,fetchAll:()=>pG,destroy:()=>yG,bulkStore:()=>uG,bulkSoftDelete:()=>mG,bulkDestroy:()=>bG});import{db as I$}from"@stacksjs/database";async function yG(J){try{let $=await I$.deleteFrom("shipping_methods").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function DG(J){try{let $=await I$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function bG(J){if(!J.length)return 0;try{let $=await I$.deleteFrom("shipping_methods").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function mG(J){if(!J.length)return 0;try{let $=await I$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as g$}from"@stacksjs/database";async function v$(J){let $=await g$.selectFrom("shipping_methods").where("id","=",J).selectAll().executeTakeFirst();if($){let G=await g$.selectFrom("shipping_zones").where("shipping_method_id","=",J).selectAll().execute();return{...$,shippingZones:G}}return}async function pG(){let J=await g$.selectFrom("shipping_methods").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((W)=>W.id))],X=(await g$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((W,Z)=>{let L=Z.shipping_method_id;if(L!==null&&L!==void 0){if(!W[L])W[L]=[];W[L].push(Z)}return W},{});return J.map((W)=>({...W,shipping_zones:X[W.id]||[]}))}var{randomUUIDv7:lG}=globalThis.Bun;import{db as b0}from"@stacksjs/database";async function cG(J){try{let $=lG(),G={...h0(J),uuid:$};await b0.insertInto("shipping_methods").values(G).executeTakeFirst();let N=await b0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created shipping method");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function uG(J){if(!J.length)return 0;try{let $=J.map((N)=>({...h0(N),uuid:lG()})),G=await b0.insertInto("shipping_methods").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function nG(){try{return b0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping options: ${J.message}`);throw J}}async function iG(){try{return await b0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping methods: ${J.message}`);throw J}}import{db as $4}from"@stacksjs/database";import{formatDate as J4}from"@stacksjs/orm";async function oG(J,$){try{if(!J)throw Error("Shipping method ID is required for update");let G=await $4.updateTable("shipping_methods").set({...h0($),updated_at:J4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method: ${G.message}`);throw G}}async function sG(J,$){try{let G=await $4.updateTable("shipping_methods").set({status:$,updated_at:J4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping method status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping method status: ${G.message}`);throw G}}async function dG(J,$,G){try{let N={updated_at:J4(new Date)};if($!==void 0)N.base_rate=$;if(G!==void 0)N.free_shipping=G;let X=await $4.updateTable("shipping_methods").set(N).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update pricing information");return X}catch(N){if(N instanceof Error)throw TypeError(`Failed to update pricing information: ${N.message}`);throw N}}var l$={};z(l$,{validateZoneMatchesAddress:()=>WN,validateShippingRateWrite:()=>Z0,updateByZone:()=>BN,updateByMethod:()=>AN,update:()=>VN,store:()=>HN,resolveZoneForAddress:()=>b$,getShippingRatesByMethod:()=>LN,getRatesByZone:()=>NN,getRateByWeightAndZone:()=>G4,getRateByWeightAndAddress:()=>XN,formatShippingRateOptions:()=>ZN,fetchById:()=>JN,fetchAll:()=>GN,destroyByZone:()=>rG,destroyByMethod:()=>tG,destroy:()=>aG,bulkUpdate:()=>zN,bulkStore:()=>xN,bulkDestroy:()=>eG,ShippingRateInputError:()=>j});import{db as D$}from"@stacksjs/database";async function aG(J){try{let $=await D$.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function eG(J){if(!J.length)return 0;try{let $=await D$.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function rG(J){try{let $=await D$.deleteFrom("shipping_rates").where("shipping_zone_id","=",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function tG(J){try{let $=await D$.deleteFrom("shipping_rates").where("shipping_method_id","=",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as y}from"@stacksjs/database";async function JN(J){let $=await y.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if($){let G=null,N=null;if($.shipping_zone_id)G=await y.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)N=await y.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:G,shipping_method:N}}return}async function GN(){let J=await y.selectFrom("shipping_rates").selectAll().execute();if(J.length===0)return[];let $=[...new Set(J.map((L)=>L.shipping_zone_id).filter((L)=>L!==null&&L!==void 0))],G=[...new Set(J.map((L)=>L.shipping_method_id).filter((L)=>L!==null&&L!==void 0))],[N,X]=await Promise.all([$.length?y.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],G.length?y.selectFrom("shipping_methods").where("id","in",G).selectAll().execute():[]]),W=N.reduce((L,Y)=>{return L[Y.id]=Y,L},{}),Z=X.reduce((L,Y)=>{return L[Y.id]=Y,L},{});return J.map((L)=>({...L,shipping_zone:L.shipping_zone_id?W[L.shipping_zone_id]:[],shipping_method:L.shipping_method_id?Z[L.shipping_method_id]:[]}))}async function NN(J){try{return await y.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function G4(J,$){try{return await y.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${G.message}`);throw G}}async function b$(J){if(!J?.countryCode)return null;try{let $=await y.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let G=null;for(let N of $){let X=1;if(J.region&&N.regions&&$N(N.regions,J.region))X=2;if(J.postalCode&&N.postal_codes&&$N(N.postal_codes,J.postalCode))X=3;if(!G||X>G.score)G={id:N.id,score:X}}return G?.id??null}catch{return null}}async function XN(J,$){let G=await b$($);if(G==null)return;return G4(J,G)}async function WN(J,$){return await b$($)===J}function $N(J,$){if(!J||!$)return!1;let G=$.trim().toUpperCase();for(let N of J.split(/[,|;]/))if(N.trim().toUpperCase()===G)return!0;return!1}async function ZN(){try{return(await y.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function LN(J){try{return await y.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:MN}=globalThis.Bun;import{db as N4}from"@stacksjs/database";import{db as m0}from"@stacksjs/database";async function YN(){return await m0.selectFrom("shipping_zones").selectAll().execute()}async function m$(J){return await m0.selectFrom("shipping_zones").where("id","=",J).selectAll().executeTakeFirst()}function KN(){try{return m0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping zone options: ${J.message}`);throw J}}async function FN(){try{return await m0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping zones: ${J.message}`);throw J}}async function QN(J){try{return await m0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class j extends TypeError{constructor(J){super(J);this.name="ShippingRateInputError"}}function p0(J,$,G){return Number(J[G]??$?.[G])}async function Z0(J,$){let G=p0(J,$,"shipping_method_id"),N=p0(J,$,"shipping_zone_id"),X=p0(J,$,"weight_from"),W=p0(J,$,"weight_to"),Z=p0(J,$,"rate");if(!Number.isSafeInteger(G)||G<1)throw new j("Shipping method must be a positive integer.");if(!Number.isSafeInteger(N)||N<1)throw new j("Shipping zone must be a positive integer.");if(!Number.isFinite(X)||X<0)throw new j("Weight from must be a non-negative number.");if(!Number.isFinite(W)||W<X)throw new j("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(Z)||Z<0)throw new j("Rate must be a non-negative integer in minor currency units.");let[L,Y]=await Promise.all([v$(G),m$(N)]);if(!L)throw new j(`Shipping method ${G} was not found.`);if(!Y)throw new j(`Shipping zone ${N} was not found.`);if(Number(Y.shipping_method_id)!==G)throw new j(`Shipping zone ${N} is not assigned to shipping method ${G}.`)}async function HN(J){try{let $=i(J),G=Number($.shipping_method_id),N=Number($.shipping_zone_id);await Z0($);let X=MN(),W={...$,shipping_method_id:G,shipping_zone_id:N,uuid:X};await N4.insertInto("shipping_rates").values(W).executeTakeFirst();let Z=await N4.selectFrom("shipping_rates").where("uuid","=",X).selectAll().executeTakeFirst();if(!Z)throw Error("Failed to resolve created shipping rate");return Z}catch($){if($ instanceof j)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function xN(J){if(!J.length)return 0;try{for(let N of J){let X=i(N);await Z0(X)}let $=J.map((N)=>({...i(N),uuid:MN()})),G=await N4.insertInto("shipping_rates").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof j)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as l0}from"@stacksjs/database";import{formatDate as p$}from"@stacksjs/orm";async function VN(J,$){try{if(!J)throw Error("Shipping rate ID is required for update");let G=await l0.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;let N=i($);await Z0(N,G);let X=await l0.updateTable("shipping_rates").set({...N,updated_at:p$(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)return;return X}catch(G){if(G instanceof j)throw G;if(G instanceof Error)throw TypeError(`Failed to update shipping rate: ${G.message}`);throw G}}async function zN(J){if(!J.length)return 0;try{let $=0;for(let{id:G,data:N}of J){let X=await l0.updateTable("shipping_rates").set({...i(N),updated_at:p$(new Date)}).where("id","=",G).executeTakeFirst();if(F(X)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function BN(J,$){try{let G=await l0.updateTable("shipping_rates").set({...i($),updated_at:p$(new Date)}).where("shipping_zone_id","=",J).executeTakeFirst();return F(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${G.message}`);throw G}}async function AN(J,$){try{let G=await l0.updateTable("shipping_rates").set({...i($),updated_at:p$(new Date)}).where("shipping_method_id","=",J).executeTakeFirst();return F(G)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${G.message}`);throw G}}var r$={};z(r$,{startStop:()=>SN,startRoute:()=>PN,routeTrackingChannel:()=>X4,recordDriverPing:()=>RN,orderTrackingChannel:()=>e,isWithin:()=>_N,hasCoordinates:()=>u0,failStop:()=>wN,estimateSecondsRemaining:()=>e$,emitDeliveryStarted:()=>n$,emitDeliveryPosition:()=>c$,emitDeliveryNearby:()=>i$,emitDeliveryFailed:()=>d$,emitDeliveryCompleted:()=>s$,emitDeliveryAssigned:()=>u$,emitDeliveryArrived:()=>o$,distanceInMeters:()=>c0,completeStop:()=>UN,broadcastToChannel:()=>o,bearingInDegrees:()=>a$,assignStop:()=>ON,NEARBY_RADIUS_METERS:()=>W4,ARRIVAL_RADIUS_METERS:()=>Z4});function e(J){return`order.${J}`}function X4(J){return`delivery-route.${J}`}async function _0(J,$){try{let G=await import("@stacksjs/events").catch(()=>null);if(!G)return;let N=G.dispatch;if(typeof N!=="function")return;N(J,$)}catch{}}async function o(J,$,G){try{let N=await import("@stacksjs/realtime").catch(()=>null);if(!N)return;let X=N.channel;if(typeof X!=="function")return;await X(J).broadcast($,G,"private")}catch{}}async function c$(J,$,G){await Promise.all([...J.map((N)=>o(e(N),"delivery:position",G)),$==null?Promise.resolve():o(X4($),"delivery:position",G)])}async function u$(J){if(await _0("delivery:assigned",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:assigned",{stop:J})}async function n$(J){if(await _0("delivery:started",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:started",{stop:J})}async function i$(J,$,G){if(await _0("delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G}),J.order_id!=null)await o(e(J.order_id),"delivery:nearby",{stop:J,distanceMeters:$,etaSeconds:G})}async function o$(J){if(await _0("delivery:arrived",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:arrived",{stop:J})}async function s$(J){if(await _0("delivery:completed",{stop:J}),J.order_id!=null)await o(e(J.order_id),"delivery:completed",{stop:J})}async function d$(J,$){await _0("delivery:failed",{stop:J,reason:$})}var L0=(J)=>J*Math.PI/180;function c0(J,$){let G=L0($.latitude-J.latitude),N=L0($.longitude-J.longitude),X=L0(J.latitude),W=L0($.latitude),Z=Math.sin(G/2)**2+Math.sin(N/2)**2*Math.cos(X)*Math.cos(W);return 12742017.6*Math.asin(Math.sqrt(Z))}function a$(J,$){let G=L0(J.latitude),N=L0($.latitude),X=L0($.longitude-J.longitude),W=Math.sin(X)*Math.cos(N),Z=Math.cos(G)*Math.sin(N)-Math.sin(G)*Math.cos(N)*Math.cos(X);return(Math.atan2(W,Z)*180/Math.PI+360)%360}function e$(J,$,G={}){let N=G.detourFactor??1.35,X=G.minimumSeconds??30;if(!Number.isFinite($)||$<=0.5)return null;let W=J*N/$;return Math.max(X,Math.round(W))}function _N(J,$,G){return c0(J,$)<=G}function u0(J){return typeof J?.latitude==="number"&&typeof J?.longitude==="number"&&Number.isFinite(J.latitude)&&Number.isFinite(J.longitude)}var{randomUUIDv7:d9}=globalThis.Bun;import{db as D}from"@stacksjs/database";var W4=400,Z4=60,a9=250;async function RN(J){let $=J.recordedAt??new Date().toISOString(),G=typeof J.accuracy!=="number"||J.accuracy<=a9,N=await D.selectFrom("drivers").where("id","=",J.driverId).select(["id","latitude","longitude"]).executeTakeFirst();if(!N)throw Error(`Unknown driver: ${J.driverId}`);let X=u0(N)?{latitude:N.latitude,longitude:N.longitude}:null,W=typeof J.heading==="number"?J.heading:X?a$(X,J):null,Z=await e9(J.driverId),L=Z?await r9(Z.id):null,Y=null,K=null,Q=!1,M=!1,H=L&&u0({latitude:L.latitude??void 0,longitude:L.longitude??void 0})?{latitude:L.latitude,longitude:L.longitude}:null;if(G&&L&&H)Y=Math.round(c0(J,H)),K=e$(Y,J.speed??0),M=Y<=Z4&&L.arrived_at==null,Q=!M&&Y<=W4&&L.status==="en_route"&&L.notified_nearby_at==null;let _=await t9({driverId:J.driverId,routeId:Z?.id??null,latitude:J.latitude,longitude:J.longitude,heading:W,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$});if(G)await D.updateTable("drivers").set({latitude:J.latitude,longitude:J.longitude,heading:W,speed:J.speed??0,last_ping_at:$}).where("id","=",J.driverId).execute();if(L&&(Y!=null||K!=null))await D.updateTable("delivery_stops").set({eta_at:K==null?L.eta_at:new Date(Date.now()+K*1000).toISOString()}).where("id","=",L.id).execute();if(G)await c$(L?.order_id==null?[]:[L.order_id],Z?.id??null,{driverId:J.driverId,routeId:Z?.id??null,latitude:J.latitude,longitude:J.longitude,heading:W,speed:J.speed??null,accuracy:J.accuracy??null,recordedAt:$,distanceToStopMeters:Y,etaSeconds:K});if(Q&&L)await D.updateTable("delivery_stops").set({notified_nearby_at:$}).where("id","=",L.id).execute(),await i$(L,Y,K);if(M&&L)await D.updateTable("delivery_stops").set({status:"arrived",arrived_at:$}).where("id","=",L.id).execute(),await o$({...L,status:"arrived",arrived_at:$});return{pingId:_,routeId:Z?.id??null,stopId:L?.id??null,distanceToStopMeters:Y,etaSeconds:K,crossedNearby:Q,crossedArrival:M}}async function e9(J){return await D.selectFrom("delivery_routes").where("driver_id","=",J).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function r9(J){let $=await D.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return $.find((G)=>G.status==="en_route")??$.find((G)=>G.status==="arrived")??$[0]??null}async function t9(J){let $=d9();return await D.insertInto("driver_pings").values({uuid:$,driver_id:J.driverId,delivery_route_id:J.routeId,latitude:J.latitude,longitude:J.longitude,heading:J.heading,speed:J.speed??0,accuracy:J.accuracy,recorded_at:J.recordedAt}).executeTakeFirst(),(await D.selectFrom("driver_pings").where("uuid","=",$).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:$3}=globalThis.Bun;import{db as T}from"@stacksjs/database";async function ON(J){let $=$3(),G=J.sequence??await G3(J.deliveryRouteId);await T.insertInto("delivery_stops").values({uuid:$,delivery_route_id:J.deliveryRouteId,order_id:J.orderId??null,sequence:G,status:"pending",address:J.address,latitude:J.latitude??null,longitude:J.longitude??null,recipient_name:J.recipientName??null,recipient_phone:J.recipientPhone??null,eta_at:J.etaAt??null}).executeTakeFirst();let N=await X3($);if(N)await u$(N);return N??{}}async function SN(J){await T.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",J).execute();let $=await Y4(J);if(!$)return null;if($.order_id!=null)await L4($.order_id,"OUT_FOR_DELIVERY");return await n$($),$}async function UN(J,$){let G=new Date().toISOString();await T.updateTable("delivery_stops").set({status:"completed",completed_at:G,...await N3(J)?{}:{arrived_at:G},...$?{notes:$}:{}}).where("id","=",J).execute();let N=await Y4(J);if(!N)return null;if(N.order_id!=null)await L4(N.order_id,"DELIVERED");return await s$(N),await qN(N.delivery_route_id),N}async function wN(J,$){await T.updateTable("delivery_stops").set({status:"failed",notes:$}).where("id","=",J).execute();let G=await Y4(J);if(!G)return null;if(G.order_id!=null)await L4(G.order_id,"SHIPPED");return await d$(G,$),await qN(G.delivery_route_id),G}async function PN(J){await T.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",J).execute()}async function qN(J){if(J==null)return;if(await T.selectFrom("delivery_stops").where("delivery_route_id","=",J).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let G=await T.selectFrom("delivery_routes").where("id","=",J).select(["driver_id"]).executeTakeFirst();if(await T.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",J).execute(),G?.driver_id!=null)await T.updateTable("drivers").set({status:"active"}).where("id","=",G.driver_id).execute()}async function L4(J,$){let G=await T.selectFrom("orders").where("id","=",J).select(["id","status"]).executeTakeFirst();if(!G)return;let N=await Promise.resolve().then(() => (M0(),KJ)),{canTransition:X,emitForStatus:W}=N,Z=J3(G.status,$,X);if(Z.length===0){let{log:L}=await import("@stacksjs/logging").catch(()=>({log:null}));L?.warn(`[delivery] refused to move order ${J} from ${G.status} to ${$}: no legal transition`);return}for(let L of Z)await T.updateTable("orders").set({status:L}).where("id","=",J).execute(),await W(L,{...G,status:L})}function J3(J,$,G){if(J===$)return[];if(G(J,$))return[$];for(let N of["PROCESSING","SHIPPED"]){if(N===J||N===$)continue;if(G(J,N)&&G(N,$))return[N,$]}return[]}async function G3(J){return(await T.selectFrom("delivery_stops").where("delivery_route_id","=",J).select(["sequence"]).execute()).reduce((G,N)=>Math.max(G,N.sequence??0),0)+1}async function N3(J){return(await T.selectFrom("delivery_stops").where("id","=",J).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function Y4(J){return await T.selectFrom("delivery_stops").where("id","=",J).selectAll().executeTakeFirst()??null}async function X3(J){return await T.selectFrom("delivery_stops").where("uuid","=",J).selectAll().executeTakeFirst()??null}var G1={};z(G1,{updateStatus:()=>gN,updateRegionsAndPostalCodes:()=>yN,updateCountries:()=>vN,update:()=>IN,store:()=>CN,softDelete:()=>EN,getZonesByCountry:()=>QN,getActiveShippingZones:()=>FN,formatZoneOptions:()=>KN,fetchById:()=>m$,fetchAll:()=>YN,destroy:()=>TN,bulkStore:()=>hN,bulkSoftDelete:()=>kN,bulkDestroy:()=>fN});import{db as t$}from"@stacksjs/database";async function TN(J){try{let $=await t$.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function EN(J){try{let $=await t$.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function fN(J){if(!J.length)return 0;try{let $=await t$.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function kN(J){if(!J.length)return 0;try{let $=await t$.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:jN}=globalThis.Bun;import{db as K4}from"@stacksjs/database";async function CN(J){try{let $=jN(),G={...I0(J),uuid:$};await K4.insertInto("shipping_zones").values(G).executeTakeFirst();let N=await K4.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to resolve created shipping zone");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function hN(J){if(!J.length)return 0;try{let $=J.map((N)=>({...I0(N),uuid:jN()})),G=await K4.insertInto("shipping_zones").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as $1}from"@stacksjs/database";import{formatDate as J1}from"@stacksjs/orm";async function IN(J,$){try{if(!J)throw Error("Shipping zone ID is required for update");let G=await $1.updateTable("shipping_zones").set({...I0($),updated_at:J1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)return;return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone: ${G.message}`);throw G}}async function gN(J,$){try{let G=await $1.updateTable("shipping_zones").set({status:$,updated_at:J1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone status: ${G.message}`);throw G}}async function vN(J,$){try{let G=await $1.updateTable("shipping_zones").set({countries:$,updated_at:J1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update shipping zone countries");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${G.message}`);throw G}}async function yN(J,$,G){try{let N={updated_at:J1(new Date)};if($!==void 0)N.regions=$;if(G!==void 0)N.postal_codes=G;let X=await $1.updateTable("shipping_zones").set(N).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update regions and postal codes");return X}catch(N){if(N instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${N.message}`);throw N}}var W3={digital:E$,drivers:k$,licenses:h$,methods:y$,rates:l$,routes:q$,tracking:r$,zones:G1},Z3=W3;var Q4={};z(Q4,{updateStatus:()=>dN,updateRate:()=>aN,updateDefaultStatus:()=>eN,update:()=>sN,store:()=>iN,fetchById:()=>lN,fetchAll:()=>cN,destroy:()=>bN,bulkStore:()=>oN,bulkDestroy:()=>mN});import{db as DN}from"@stacksjs/database";async function bN(J){try{let $=await DN.deleteFrom("tax_rates").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function mN(J){if(!J.length)return 0;try{let $=await DN.deleteFrom("tax_rates").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as pN}from"@stacksjs/database";async function lN(J){return await pN.selectFrom("tax_rates").where("id","=",J).selectAll().executeTakeFirst()}async function cN(){return await pN.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:uN}=globalThis.Bun;import{db as nN}from"@stacksjs/database";async function iN(J){try{return await nN.transaction(async($)=>{let G={...J,uuid:uN()};if(G.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let N=await $.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!N)throw Error("Failed to create tax rate");return N})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function oN(J){if(!J.length)return 0;try{return await nN.transaction(async($)=>{let G=0;for(let N of J){let X={...N,uuid:uN()};if(X.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(X).executeTakeFirst())G++}return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as N1}from"@stacksjs/database";import{formatDate as X1}from"@stacksjs/orm";async function sN(J,$){try{if(!J)throw Error("Tax rate ID is required for update");return await N1.transaction(async(G)=>{let N=await G.selectFrom("tax_rates").select("is_default").where("id","=",J).executeTakeFirst();if(!N)return;let X=$.is_default??Boolean(N.is_default),W=X1(new Date);if(X)await G.updateTable("tax_rates").set({is_default:!1,updated_at:W}).where("id","!=",J).execute();let Z=await G.updateTable("tax_rates").set({...$,updated_at:W}).where("id","=",J).returningAll().executeTakeFirst();if(!Z)return;return Z})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate: ${G.message}`);throw G}}async function dN(J,$){try{let G=await N1.updateTable("tax_rates").set({status:$,updated_at:X1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update tax rate status");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate status: ${G.message}`);throw G}}async function aN(J,$){try{let G=await N1.updateTable("tax_rates").set({rate:$,updated_at:X1(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update rate information");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update rate information: ${G.message}`);throw G}}async function eN(J,$){try{return await N1.transaction(async(G)=>{if(!await G.selectFrom("tax_rates").select("id").where("id","=",J).executeTakeFirst())return!1;let X=X1(new Date);if($)await G.updateTable("tax_rates").set({is_default:!1,updated_at:X}).where("id","!=",J).execute();return await G.updateTable("tax_rates").set({is_default:$,updated_at:X}).where("id","=",J).execute(),!0})}catch(G){if(G instanceof Error)throw TypeError(`Failed to update tax rate default status: ${G.message}`);throw G}}var B4={};z(B4,{restaurant:()=>O0,products:()=>Z1,default:()=>z3});var Z1={};z(Z1,{updateStatus:()=>BX,updatePartySize:()=>AX,update:()=>W1,store:()=>VX,fetchWaiting:()=>YX,fetchPurchasedBetweenDates:()=>ZX,fetchNotifiedBetweenDates:()=>WX,fetchCountByStatus:()=>KX,fetchCountBySource:()=>JX,fetchCountByQuantity:()=>NX,fetchCountByDateGrouped:()=>MX,fetchCountByDate:()=>GX,fetchCountByAllQuantities:()=>XX,fetchCountBetweenDates:()=>QX,fetchConversionRates:()=>FX,fetchCancelledBetweenDates:()=>LX,fetchById:()=>n0,fetchAll:()=>$X,destroy:()=>rN,bulkStore:()=>zX,bulkDestroy:()=>tN});import{db as M4}from"@stacksjs/database";async function rN(J){try{let $=await M4.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await M4.deleteFrom("waitlist_products").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function tN(J){if(!J.length)return 0;try{let $=await M4.deleteFrom("waitlist_products").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as P}from"@stacksjs/orm";async function n0(J){return await A.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function $X(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function JX(J,$){let G=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(J&&$){let X=P(J),W=P($);G=G.where("created_at",">=",X).where("created_at","<=",W)}return(await G.execute()).reduce((X,{source:W,count:Z})=>{return X[W]=Z,X},{})}async function GX(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let N=P($),X=P(G);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",N).where("created_at","<=",X).executeTakeFirst())?.count??0}async function NX(J){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",J).executeTakeFirst())?.count??0}async function XX(J,$){let G=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(J&&$){let X=P(J),W=P($);G=G.where("created_at",">=",X).where("created_at","<=",W)}return(await G.execute()).reduce((X,{quantity:W,count:Z})=>{return X[W]=Z,X},{})}async function WX(J,$){let G=P(J),N=P($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",G).where("notified_at","<=",N).whereNotNull("notified_at").execute()}async function ZX(J,$){let G=P(J),N=P($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",G).where("purchased_at","<=",N).whereNotNull("purchased_at").execute()}async function LX(J,$){let G=P(J),N=P($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",G).where("cancelled_at","<=",N).whereNotNull("cancelled_at").execute()}async function YX(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function KX(J,$,G){let N=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",J);if($&&G){let W=P($),Z=P(G);N=N.where("created_at",">=",W).where("created_at","<=",Z)}return(await N.executeTakeFirst())?.count??0}async function FX(J,$){let G=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(J&&$){let Y=P(J),K=P($);G=G.where("created_at",">=",Y).where("created_at","<=",K)}let N=await G.execute(),X=N.reduce((Y,{count:K})=>Y+K,0),W=N.find((Y)=>Y.status==="purchased")?.count??0,Z=X>0?W/X*100:0,L=N.reduce((Y,{status:K,count:Q})=>{return Y[K]={count:Q,percentage:X>0?Q/X*100:0},Y},{});return{totalConversionRate:Z,statusBreakdown:L}}async function QX(J,$){let G=P(J),N=P($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",N).executeTakeFirst())?.count??0}async function MX(J,$){let G=A.selectFrom("waitlist_products").select(["created_at"]);if(J&&$){let W=P(J),Z=P($);G=G.where("created_at",">=",W).where("created_at","<=",Z)}let X=(await G.execute()).reduce((W,{created_at:Z})=>{let L=(Z||"").split("T")[0]||"unknown";return W[L]=(W[L]||0)+1,W},{});return Object.entries(X).map(([W,Z])=>({date:W,count:Z})).sort((W,Z)=>W.date.localeCompare(Z.date))}var{randomUUIDv7:xX}=globalThis.Bun;import{db as H4}from"@stacksjs/database";import{formatDate as HX}from"@stacksjs/orm";var L3={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Y3(J){return typeof J==="number"||J instanceof Date?HX(J):J}function i0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,X])=>X!==void 0));if(G.quantity===void 0&&G.party_size!==void 0)G.quantity=G.party_size;delete G.party_size;for(let X of["notified_at","purchased_at","cancelled_at"])if(G[X]!==void 0)G[X]=Y3(G[X]);let N=L3[G.status];if(N&&G[N]===void 0&&!$[N])G[N]=HX(new Date);return G}async function VX(J){try{let $=xX(),G={...i0(J),uuid:$,status:J.status||"waiting"};await H4.insertInto("waitlist_products").values(G).executeTakeFirst();let N=await H4.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to create waitlist product");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function zX(J){if(!J.length)return 0;try{let $=J.map((N)=>({...i0(N),status:N.status||"waiting",uuid:xX()})),G=await H4.insertInto("waitlist_products").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as K3}from"@stacksjs/database";import{formatDate as F3}from"@stacksjs/orm";async function W1(J,$){try{if(!J)throw Error("Waitlist product ID is required for update");let G=await n0(J);if(!G)return;await K3.updateTable("waitlist_products").set({...i0($,G),updated_at:F3(new Date)}).where("id","=",J).execute();let N=await n0(J);if(!N)return;return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update waitlist product: ${G.message}`);throw G}}async function BX(J,$){return await W1(J,{status:$})}async function AX(J,$){return await W1(J,{quantity:$})}var O0={};z(O0,{updateWaitTimes:()=>uX,updateStatus:()=>lX,updateQueuePosition:()=>nX,updatePartySize:()=>cX,update:()=>R0,store:()=>mX,fetchWaitingWithQuotedTimes:()=>jX,fetchWaitingWithPartySizes:()=>CX,fetchWaiting:()=>EX,fetchTimeSeriesStats:()=>DX,fetchTablesTurnedToday:()=>hX,fetchSeatingRate:()=>IX,fetchSeatedStats:()=>yX,fetchSeatedBetweenDates:()=>TX,fetchNoShowStats:()=>gX,fetchCurrentWaitTimes:()=>vX,fetchCountByTablePreference:()=>SX,fetchCountByPartySize:()=>wX,fetchCountByDate:()=>UX,fetchCountByAllPartySizes:()=>PX,fetchConversionRates:()=>fX,fetchById:()=>o0,fetchBetweenDates:()=>qX,fetchAverageWaitTimes:()=>kX,fetchAll:()=>OX,destroy:()=>_X,bulkStore:()=>pX,bulkDestroy:()=>RX});import{db as x4}from"@stacksjs/database";async function _X(J){try{let $=await x4.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!$)return;return await x4.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function RX(J){if(!J.length)return 0;try{let $=await x4.deleteFrom("waitlist_restaurants").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as V}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function o0(J){return await V.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function OX(){return await V.selectFrom("waitlist_restaurants").selectAll().execute()}async function SX(){return(await V.selectFrom("waitlist_restaurants").select(["table_preference",V.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:G,count:N})=>{return $[G]=N,$},{})}async function UX(J=new Date){let $=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let N=g($),X=g(G);return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("created_at",">=",N).where("created_at","<=",X).executeTakeFirst())?.count??0}async function wX(J){return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function PX(){return(await V.selectFrom("waitlist_restaurants").select(["party_size",V.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:G,count:N})=>{return $[G]=N,$},{})}async function qX(J,$){let G=g(J),N=g($);return await V.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",G).where("created_at","<=",N).execute()}async function TX(J,$){let G=g(J),N=g($);return await V.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",G).where("check_in_time","<=",N).where("status","=","seated").execute()}async function EX(){return await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function fX(){let J=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),$=J.reduce((W,{count:Z})=>W+Z,0),G=J.find((W)=>W.status==="seated")?.count??0,N=$>0?Number(G)/$*100:0,X=J.reduce((W,{status:Z,count:L})=>{return W[Z]={count:L,percentage:$>0?L/$*100:0},W},{});return{totalConversionRate:N,statusBreakdown:X}}async function kX(){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 jX(){let J=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((N,X)=>N+(X.quoted_wait_time??0),0),G=J.length>0?$/J.length:0;return{entries:J,totalQuotedWaitTime:$,averageQuotedWaitTime:G}}async function CX(){let J=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=J.reduce((X,W)=>X+W.party_size,0),G=J.length>0?$/J.length:0,N=J.reduce((X,W)=>{return X[W.party_size]=(X[W.party_size]||0)+1,X},{});return{entries:J,totalPartySize:$,averagePartySize:G,partySizeBreakdown:N}}async function hX(){let J=new Date,$=new Date(J);$.setHours(0,0,0,0);let G=new Date(J);G.setHours(23,59,59,999);let N=g($),X=g(G),W=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",N).where("check_in_time","<=",X).execute(),Z=W.length,L=W.reduce((M,H)=>M+H.party_size,0),Y=Z>0?L/Z:0,K=W.reduce((M,H)=>{return M[H.table_preference]=(M[H.table_preference]||0)+1,M},{}),Q=W.reduce((M,H)=>{return M[H.party_size]=(M[H.party_size]||0)+1,M},{});return{totalTablesTurned:Z,averagePartySize:Y,totalCustomersSeated:L,breakdownByTablePreference:K,breakdownByPartySize:Q}}async function IX(J,$){let G=g(J),N=g($),X=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).where("check_in_time",">=",G).where("check_in_time","<=",N).groupBy("status").execute(),W=X.reduce((K,{count:Q})=>K+Q,0),Z=X.find((K)=>K.status==="seated")?.count??0,L=W>0?Number(Z)/W*100:0,Y=X.reduce((K,{status:Q,count:M})=>{return K[Q]={count:M,percentage:W>0?M/W*100:0},K},{});return{totalEntries:W,seatedEntries:Z,seatingRate:L,statusBreakdown:Y}}async function gX(J,$){let G=g(J),N=g($),X=V.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",G).where("check_in_time","<=",N),W=await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("check_in_time",">=",G).where("check_in_time","<=",N).executeTakeFirst(),Z=await X.execute(),L=Z.length,Y=W?.count&&W.count>0?L/W.count*100:0,K=Z.reduce((R,S)=>R+(S.quoted_wait_time??0),0),Q=L>0?K/L:0,M=Z.reduce((R,S)=>R+S.party_size,0),H=L>0?M/L:0,_=Z.reduce((R,S)=>{return R[S.table_preference]=(R[S.table_preference]||0)+1,R},{}),O=Z.reduce((R,S)=>{return R[S.party_size]=(R[S.party_size]||0)+1,R},{});return{totalNoShows:L,noShowRate:Y,averageQuotedWaitTime:Q,averagePartySize:H,breakdownByTablePreference:_,breakdownByPartySize:O}}async function vX(){let J=await V.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=J.reduce((X,W)=>X+(W.quoted_wait_time||0),0),G=J.reduce((X,W)=>X+(W.actual_wait_time||0),0),N=J.length;return{averageQuoted:N>0?$/N:0,averageActual:N>0?G/N:0}}async function yX(){let J=Date.now()-86400000,$=await V.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),G=Array.from({length:24},(N,X)=>({hour:X,count:$.filter((W)=>{return W.seated_at===X}).length}));return{total:$.length,byHour:G}}async function DX(){return(await V.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,G)=>{let N=G.created_at;if(!$[N])$[N]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[N].total++,$[N][G.status]++,$},{})}var{randomUUIDv7:bX}=globalThis.Bun;import{db as z4}from"@stacksjs/database";import{formatDate as V4}from"@stacksjs/orm";var Q3={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function M3(J){if(typeof J==="number")return V4(J<=2147483647?J*1000:J);if(J instanceof Date)return V4(J);return J}function s0(J,$={}){let G=Object.fromEntries(Object.entries(J).filter(([,X])=>X!==void 0));for(let X of["check_in_time","seated_at","no_show_at","cancelled_at"])if(G[X]!==void 0)G[X]=M3(G[X]);let N=Q3[G.status];if(N&&G[N]===void 0&&!$[N])G[N]=V4(new Date);return G}async function mX(J){try{let $=bX(),G={...s0(J),status:J.status||"waiting",uuid:$};await z4.insertInto("waitlist_restaurants").values(G).executeTakeFirst();let N=await z4.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!N)throw Error("Failed to create restaurant waitlist entry");return N}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function pX(J){if(!J.length)return 0;try{let $=J.map((N)=>({...s0(N),status:N.status||"waiting",uuid:bX()})),G=await z4.insertInto("waitlist_restaurants").values($).executeTakeFirst();return F(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as H3}from"@stacksjs/database";import{formatDate as x3}from"@stacksjs/orm";async function R0(J,$){try{if(!J)throw Error("Restaurant waitlist entry ID is required for update");let G=await o0(J);if(!G)return;await H3.updateTable("waitlist_restaurants").set({...s0($,G),updated_at:x3(new Date)}).where("id","=",J).execute();let N=await o0(J);if(!N)return;return N}catch(G){if(G instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${G.message}`);throw G}}async function lX(J,$){return await R0(J,{status:$})}async function cX(J,$){return await R0(J,{party_size:$})}async function uX(J,$,G){return await R0(J,{quoted_wait_time:$,...G===void 0?{}:{actual_wait_time:G}})}async function nX(J,$){return await R0(J,{queue_position:$})}var V3={products:Z1,restaurant:O0},z3=V3;var B3={coupons:L1,customers:Y1,devices:H1,errors:z1,giftCards:A1,orders:T1,payments:E1,products:g1,receipts:p1,restaurant:O0,shippings:F4,tax:Q4,waitlists:B4},pM=B3;export{B4 as waitlists,Q4 as tax,F4 as shippings,O0 as restaurant,p1 as receipts,g1 as products,E1 as payments,T1 as orders,A1 as giftCards,z1 as errors,H1 as devices,pM as default,Y1 as customers,L1 as coupons,B3 as commerce};
|