@stacksjs/commerce 0.70.294 → 0.70.297
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 +9 -9
- package/dist/orders/events.d.ts +9 -1
- package/dist/shippings/index.d.ts +3 -0
- package/dist/shippings/tracking/events.d.ts +48 -0
- package/dist/shippings/tracking/geo.d.ts +38 -0
- package/dist/shippings/tracking/index.d.ts +43 -0
- package/dist/shippings/tracking/ping.d.ts +37 -0
- package/dist/shippings/tracking/stops.d.ts +44 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var x3=Object.defineProperty;var H3=(N)=>N;function V3(N,$){this[N]=H3.bind(null,$)}var B=(N,$)=>{for(var J in $)x3(N,J,{get:$[J],enumerable:!0,configurable:!0,set:V3.bind($,J)})};var o1=import.meta.require;var p$={};B(p$,{update:()=>z4,store:()=>Q4,redeem:()=>B4,getActiveCouponsMoMChange:()=>M4,fetchTopRedeemedCoupons:()=>W4,fetchStats:()=>J4,fetchRedemptionTrend:()=>Y4,fetchRedemptionStats:()=>L4,fetchCouponCountsByType:()=>X4,fetchCouponCounts:()=>G4,fetchConversionRate:()=>Z4,fetchById:()=>d,fetchByCode:()=>$4,fetchAll:()=>r1,fetchActive:()=>N4,deleteExpiredCoupons:()=>a1,deleteCoupons:()=>d1,deleteCoupon:()=>s1});import{db as v0}from"@stacksjs/database";import{formatDate as z3}from"@stacksjs/orm";function F(N){if(typeof N==="number")return Number.isFinite(N)?N:0;if(typeof N==="bigint")return Number(N);if(!N||typeof N!=="object")return 0;let $=N;for(let J of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[J]!==void 0&&$[J]!==null)return F($[J]);if(Array.isArray(N))return N.reduce((J,G)=>J+F(G),0);return 0}async function s1(N){let $=await v0.deleteFrom("coupons").where("id","=",N).executeTakeFirst();return F($)>0}async function d1(N){if(!N.length)return 0;return(await v0.deleteFrom("coupons").where("id","in",N).execute()).length||0}async function a1(){let N=z3(new Date),$=await v0.deleteFrom("coupons").where("end_date","<",N).executeTakeFirst();return F($)}import{db as H}from"@stacksjs/database";import{extractDate as e1,formatDate as t1}from"@stacksjs/orm";import{camelCase as B3}from"@stacksjs/strings";function D0(N){let $=Object.fromEntries(Object.entries(N).map(([J,G])=>[B3(J),G]));if($.endDate)$.endDate=e1(new Date($.endDate));if($.startDate)$.startDate=e1(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function r1(){return(await H.selectFrom("coupons").selectAll().execute()).map(D0)}async function d(N){let $=await H.selectFrom("coupons").where("id","=",N).selectAll().executeTakeFirst();if($)return D0($);return}async function $4(N){let $=await H.selectFrom("coupons").where("code","=",N).selectAll().executeTakeFirst();if($)return D0($);return}async function N4(){let N=t1(new Date);return(await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",N).selectAll().execute()).map(D0)}async function J4(){let N=await H.selectFrom("coupons").select(H.fn.count("id").as("count")).executeTakeFirst(),$=t1(new Date),J=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(H.fn.count("id").as("count")).executeTakeFirst(),G=await H.selectFrom("coupons").select(["discount_type",H.fn.count("id").as("count")]).groupBy("discount_type").execute(),X=await H.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),L=await H.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(N?.count||0),active:Number(J?.count||0),by_type:G,most_used:X,upcoming:L}}async function G4(){let N=new Date,$=new Date(N);$.setDate(N.getDate()-7);let J=new Date(N);J.setMonth(N.getMonth()-1);let G=new Date(N);G.setFullYear(N.getFullYear()-1);let X=await y0(null,null,N),L=await y0($,null,N),W=await y0(J,null,N),Y=await y0(G,null,N);return{week:L,month:W,year:Y,all_time:X}}async function y0(N,$,J){let G=H.selectFrom("coupons");if(N)G=G.where("created_at",">=",N.toISOString());if($)G=G.where("created_at","<=",$.toISOString());let X=await G.select(H.fn.count("id").as("count")).executeTakeFirst(),L=H.selectFrom("coupons");if(N)L=L.where("created_at",">=",N.toISOString());if($)L=L.where("created_at","<=",$.toISOString());L=L.where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J);let W=await L.select(H.fn.count("id").as("count")).executeTakeFirst(),Y=Number(X?.count||0),Z=Number(W?.count||0),M=Y-Z;return{total:Y,active:Z,inactive:M}}async function X4(){let N=new Date,$=await H.selectFrom("coupons").select("discount_type").distinct().execute(),J={};for(let{discount_type:G}of $){let X=await H.selectFrom("coupons").where("discount_type","=",G).select(H.fn.count("id").as("count")).executeTakeFirst(),L=await H.selectFrom("coupons").where("discount_type","=",G).where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",N).select(H.fn.count("id").as("count")).executeTakeFirst(),W=Number(X?.count||0),Y=Number(L?.count||0);J[G]={total:W,active:Y,inactive:W-Y}}return J}async function L4(){let N=await H.selectFrom("coupons").select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,J=new Date($);J.setDate($.getDate()-7);let G=new Date($);G.setMonth($.getMonth()-1);let X=new Date($);X.setFullYear($.getFullYear()-1);let L=await H.selectFrom("coupons").where("updated_at",">=",J.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await H.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await H.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),Z=await H.selectFrom("coupons").select(["discount_type",H.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),M={};return Z.forEach((K)=>{M[K.discount_type]=Number(K.total||0)}),{total:Number(N?.total||0),week:Number(L?.total||0),month:Number(W?.total||0),year:Number(Y?.total||0),by_type:M}}async function W4(N=5){return await H.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(N).execute()}async function Y4(N=30){let $=new Date().toISOString(),J=new Date;J.setDate(J.getDate()-N);let G=await H.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",J.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),X={};return G.forEach((L)=>{let W=L.updated_at?new Date(L.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!X[W])X[W]=0;X[W]+=L?.usage_count||0}),Object.entries(X).map(([L,W])=>({date:L,count:W}))}async function Z4(){let N=new Date,$=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",N).select(H.fn.count("id").as("count")).executeTakeFirst(),J=await H.selectFrom("coupons").where("usage_count",">",0).select(H.fn.count("id").as("count")).executeTakeFirst(),G=Number($?.count||0),X=Number(J?.count||0);return{rate:G>0?X/G*100:0,total_active:G,total_redeemed:X}}async function M4(){let N=new Date,$=new Date(N.getFullYear(),N.getMonth(),1),J=new Date(N.getFullYear(),N.getMonth()-1,1),G=new Date(N.getFullYear(),N.getMonth(),0),X=await H.selectFrom("coupons").select(H.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",$).executeTakeFirst(),L=await H.selectFrom("coupons").select(H.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",J).executeTakeFirst(),W=Number(X?.count||0),Y=Number(L?.count||0),Z=W-Y,M=Y!==0?Z/Y*100:W>0?100:0;return{current_month:W,previous_month:Y,difference:Z,percentage_change:M}}var{randomUUIDv7:A3}=globalThis.Bun;import{db as F4}from"@stacksjs/database";import{HttpError as K4}from"@stacksjs/error-handling";import{isUniqueViolation as R3}from"@stacksjs/orm";async function Q4(N){try{let $=A3();return await F4.insertInto("coupons").values({...N,uuid:$}).executeTakeFirst(),await F4.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof K4)throw $;if(R3($))throw new K4(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as H4}from"@stacksjs/database";import{HttpError as x4}from"@stacksjs/error-handling";import{formatDate as V4,isUniqueViolation as _3}from"@stacksjs/orm";async function z4(N,$){if(!await d(N))return;try{return await H4.updateTable("coupons").set({...$,updated_at:V4(new Date)}).where("id","=",N).execute(),await d(N)}catch(G){if(G instanceof x4)throw G;if(_3(G))throw new x4(409,"A coupon with this code already exists");if(G instanceof Error)throw Error(`Failed to update coupon: ${G.message}`);throw G}}async function B4(N){let $=V4(new Date),J=await H4.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:()=>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
|
|
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 >= ?)`,[$,N,$,$]),G=typeof J?.execute==="function"?await J.execute():J;if(Number(G?.changes??G?.numUpdatedRows??G?.affectedRows??0)>0){let Z=await d(N);if(Z)return{ok:!0,coupon:Z};return{ok:!1,reason:"not-found"}}let L=await d(N);if(!L)return{ok:!1,reason:"not-found"};if(!L.isActive)return{ok:!1,reason:"inactive"};let W=!L.startDate||L.startDate<=$,Y=!L.endDate||L.endDate>=$;if(!W||!Y)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var b$={};B(b$,{update:()=>E4,store:()=>w4,fetchById:()=>p0,fetchAll:()=>S4,destroy:()=>R4,bulkDestroy:()=>_4});import{db as A4}from"@stacksjs/database";async function R4(N){try{let $=await A4.deleteFrom("customers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function _4(N){if(!N.length)return 0;try{let $=await A4.deleteFrom("customers").where("id","in",N).executeTakeFirst();return F($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as O4}from"@stacksjs/database";async function p0(N){return await O4.selectFrom("customers").where("id","=",N).selectAll().executeTakeFirst()}async function S4(){return await O4.selectFrom("customers").selectAll().execute()}import{db as O3}from"@stacksjs/database";import{HttpError as T4}from"@stacksjs/error-handling";import{isUniqueViolation as S3}from"@stacksjs/orm";async function w4(N){try{let $={...N,avatar:N.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},J=await O3.insertInto("customers").values($).executeTakeFirst();if(!J)throw Error("Failed to create customer");let G=J.insertId||Number(J.numInsertedOrUpdatedRows);return await p0(Number(G))}catch($){if($ instanceof T4)throw $;if(S3($))throw new T4(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as T3}from"@stacksjs/database";import{HttpError as U4}from"@stacksjs/error-handling";import{formatDate as w3,isUniqueViolation as U3}from"@stacksjs/orm";async function E4(N,$){try{if(!N)throw Error("Customer ID is required for update");let J=await T3.updateTable("customers").set({...$,updated_at:w3(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof U4)throw J;if(U3(J))throw new U4(409,"A customer with this email already exists");if(J instanceof Error)throw Error(`Failed to update customer: ${J.message}`);throw J}}var u$={};B(u$,{updateStatus:()=>c4,updatePrintCount:()=>n4,update:()=>l4,storePrintDevicesExport:()=>D4,store:()=>b4,getPrinterStatusCounts:()=>v4,fetchErrorsByDeviceId:()=>h4,fetchById:()=>b,fetchAll:()=>b0,exportPrintDevices:()=>m0,downloadPrintDevices:()=>y4,destroy:()=>q4,countTotalPrints:()=>j4,countPrintsByDeviceId:()=>C4,countAll:()=>k4,calculatePrinterHealth:()=>g4,calculateErrorRate:()=>I4,bulkStore:()=>m4,bulkDestroy:()=>f4});import{db as P4}from"@stacksjs/database";async function q4(N){try{let $=await P4.deleteFrom("print_devices").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function f4(N){if(!N.length)return 0;try{let $=await P4.deleteFrom("print_devices").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as E3}from"ts-spreadsheets";import{db as P}from"@stacksjs/database";async function b(N){return await P.selectFrom("print_devices").where("id","=",N).selectAll().executeTakeFirst()}async function b0(){return await P.selectFrom("print_devices").selectAll().execute()}async function k4(){let N=await P.selectFrom("print_devices").select(P.fn.count("id").as("count")).executeTakeFirst();return Number(N?.count||0)}async function j4(){let N=await P.selectFrom("print_devices").select(P.fn.sum("print_count").as("total")).executeTakeFirst();return Number(N?.total||0)}async function C4(N){return(await P.selectFrom("print_devices").select("print_count").where("id","=",N).executeTakeFirst())?.print_count??0}async function I4(){let N=await P.selectFrom("receipts").select([P.fn.count("id").as("total"),P.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!N?.total||N.total===0)return 0;return Number((N.failed_count??0)/N.total*100)}async function h4(N){return await P.selectFrom("receipts").where("print_device_id","=",N).where("status","=","failed").selectAll().execute()}async function g4(){let N=await P.selectFrom("print_devices").select([P.fn.count("id").as("total"),P.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!N?.total||N.total===0)return 0;return Number((N.online_count??0)/N.total*100)}async function v4(){return(await P.selectFrom("print_devices").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,J)=>{return $[J.status]=Number(J.count||0),$},{})}function m$(N,$,J=$){return N?.[$]??N?.[J]}function P3(N){let $=String(N||""),J=/^\d+$/.test($)?Number($):N;return new Date(J)}async function m0(N="csv"){let $=await b0(),J=q3($);return E3(J,{type:N})}function q3(N){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],J=N.map((G)=>{return[G.id,G.name,m$(G,"macAddress","mac_address"),G.location,G.terminal,G.status,P3(m$(G,"lastPing","last_ping")).toLocaleString(),m$(G,"printCount","print_count")]});return{headings:$,data:J}}async function y4(N="csv",$){let J=await m0(N),G=`print_devices_export_${new Date().toISOString().split("T")[0]}.${N}`;return J.download($||G)}async function D4(N="csv",$){let J=await m0(N),G=`print_devices_export_${new Date().toISOString().split("T")[0]}.${N}`;J.store($||G)}var{randomUUIDv7:p4}=globalThis.Bun;import{db as l$}from"@stacksjs/database";async function b4(N){try{let $=p4(),J={last_ping:0,print_count:0,...N,uuid:$};return await l$.insertInto("print_devices").values(J).executeTakeFirst(),await l$.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function m4(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={last_ping:0,print_count:0,...J,uuid:p4()};await l$.insertInto("print_devices").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${J.message}`);throw J}}import{db as c$}from"@stacksjs/database";import{formatDate as n$}from"@stacksjs/orm";async function l4(N,$){if(!await b(N))return;try{return await c$.updateTable("print_devices").set({...$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print device: ${G.message}`);throw G}}async function c4(N,$){if(!await b(N))throw Error(`Print device with ID ${N} not found`);try{return await c$.updateTable("print_devices").set({status:$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print device status: ${G.message}`);throw G}}async function n4(N,$){if(!await b(N))throw Error(`Print device with ID ${N} not found`);try{return await c$.updateTable("print_devices").set({print_count:$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print count: ${G.message}`);throw G}}var s$={};B(s$,{update:()=>r4,unresolveGroup:()=>GN,resolveGroup:()=>NN,ignoreGroup:()=>JN,fetchTimeline:()=>t4,fetchStats:()=>e4,fetchGrouped:()=>d4,fetchById:()=>s4,fetchByGroup:()=>a4,fetchAll:()=>c0,destroyGroup:()=>o4,destroy:()=>u4,bulkUpdateStatus:()=>$N,bulkDestroy:()=>i4});import{db as i$}from"@stacksjs/database";import{log as o$}from"@stacksjs/logging";async function u4(N){try{return await i$.deleteFrom("errors").where("id","=",N).execute(),!0}catch($){return o$.error("[commerce/errors] destroy failed",{id:N,error:$}),!1}}async function i4(N){try{return await i$.deleteFrom("errors").where("id","in",N).execute(),!0}catch($){return o$.error("[commerce/errors] bulkDestroy failed",{count:N.length,error:$}),!1}}async function o4(N,$){try{return await i$.deleteFrom("errors").where("type","=",N).where("message","=",$).execute(),!0}catch(J){return o$.error("[commerce/errors] destroyGroup failed",{type:N,message:$,error:J}),!1}}import{db as l0}from"@stacksjs/database";async function s4(N){return await l0.selectFrom("errors").where("id","=",N).selectAll().executeTakeFirst()}async function c0(){return await l0.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function d4(){let N=await l0.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let G of N){let X=`${G.type}:${G.message}`;if(!$.has(X))$.set(X,{errors:[],firstSeen:new Date(G.created_at),lastSeen:new Date(G.created_at)});let L=$.get(X);L.errors.push(G);let W=new Date(G.created_at);if(W<L.firstSeen)L.firstSeen=W;if(W>L.lastSeen)L.lastSeen=W}let J=[];for(let[G,X]of $){let L=X.errors[0];if(!L)continue;let W=X.errors.find((Z)=>Z.status!==null)?.status,Y="unresolved";if(W===1)Y="resolved";else if(W===2)Y="ignored";J.push({id:L.id,type:L.type,message:L.message,stack:L.stack,status:Y,count:X.errors.length,first_seen:X.firstSeen.toISOString(),last_seen:X.lastSeen.toISOString(),error_ids:X.errors.map((Z)=>Z.id)})}return J.sort((G,X)=>new Date(X.last_seen).getTime()-new Date(G.last_seen).getTime()),J}async function a4(N,$){return await l0.selectFrom("errors").where("type","=",N).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function e4(){let N=await c0(),$=new Date,J=new Date($.getTime()-86400000),G=new Date($.getTime()-172800000),X=N.filter((Y)=>new Date(Y.created_at)>=J).length,L=N.filter((Y)=>{let Z=new Date(Y.created_at);return Z>=G&&Z<J}).length,W=L===0?X>0?100:0:Math.round((X-L)/L*100);return{total:N.length,unresolved:N.filter((Y)=>Y.status===null||Y.status===0).length,resolved:N.filter((Y)=>Y.status===1).length,ignored:N.filter((Y)=>Y.status===2).length,last_24h:X,trend:W}}async function t4(){let N=await c0(),$=new Date,J=[];for(let G=23;G>=0;G--){let X=new Date($.getTime()-G*60*60*1000);X.setMinutes(0,0,0);let L=new Date(X.getTime()+3600000),W=N.filter((Y)=>{let Z=new Date(Y.created_at);return Z>=X&&Z<L}).length;J.push({hour:X.toISOString(),count:W})}return J}import{db as x0}from"@stacksjs/database";import{sql as H0}from"@stacksjs/database";import{log as V0}from"@stacksjs/logging";async function r4(N,$){try{return await x0.updateTable("errors").set({...$,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("id","=",N).execute(),!0}catch(J){return V0.error("[commerce/errors] update failed",{id:N,error:J}),!1}}async function $N(N,$){try{return await x0.updateTable("errors").set({status:$,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("id","in",N).execute(),!0}catch(J){return V0.error("[commerce/errors] bulkUpdateStatus failed",{count:N.length,status:$,error:J}),!1}}async function NN(N,$){try{return await x0.updateTable("errors").set({status:1,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] resolveGroup failed",{type:N,message:$,error:J}),!1}}async function JN(N,$){try{return await x0.updateTable("errors").set({status:2,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] ignoreGroup failed",{type:N,message:$,error:J}),!1}}async function GN(N,$){try{return await x0.updateTable("errors").set({status:0,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] unresolveGroup failed",{type:N,message:$,error:J}),!1}}var a$={};B(a$,{updateBalance:()=>SN,update:()=>ON,store:()=>BN,fetchTotalValue:()=>FN,fetchTotalCurrentBalance:()=>KN,fetchStats:()=>WN,fetchById:()=>a,fetchByCode:()=>d$,fetchAll:()=>XN,fetchActive:()=>LN,destroy:()=>xN,compareActiveGiftCards:()=>ZN,checkBalance:()=>YN,calculateGiftCardValues:()=>MN,bulkDestroy:()=>HN});import{db as QN}from"@stacksjs/database";import{formatDate as NL}from"@stacksjs/orm";import{db as T,sql as j}from"@stacksjs/database";import{formatDate as u,toTimestamp as G0}from"@stacksjs/orm";import{aggregateFunctions as f3,db as k3}from"@stacksjs/database";async function I(N,$,J){let G=k3.selectFrom(N);if(J)G=J(G);G=G.select(Object.entries($).map(([W,Y])=>{let Z=Y.column??"id",M=f3[Y.kind](Z);if(Y.filter)M=M.filterWhere(Y.filter.column,Y.filter.op,Y.filter.value);return M.as(W)}));let X=await G.executeTakeFirst(),L={};for(let W of Object.keys($)){let Y=X?.[W];L[W]=typeof Y==="number"?Y:Number(Y??0)||0}return L}async function XN(){return await T.selectFrom("gift_cards").selectAll().execute()}async function a(N){return await T.selectFrom("gift_cards").where("id","=",N).selectAll().executeTakeFirst()}async function d$(N){return await T.selectFrom("gift_cards").where("code","=",N).selectAll().executeTakeFirst()}async function LN(){return await T.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function WN(){let{count:N}=await I("gift_cards",{count:{kind:"count"}}),$=G0(new Date),J=await T.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal($)} OR expiry_date IS NULL)`).select(T.fn.count("id").as("count")).executeTakeFirst(),G=await T.selectFrom("gift_cards").select(["status",T.fn.count("id").as("count")]).groupBy("status").execute(),{count:X}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance < 0.25`)),{count:L}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:W}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance > 0.75`)),Y=new Date;Y.setDate(Y.getDate()+30);let Z=await T.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",G0(Y)).where("expiry_date",">=",$).selectAll().limit(5).execute(),M=await T.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:N,active:Number(J?.count||0),by_status:G.map((K)=>({status:K.status,count:Number(K.count)})),by_balance:{low:X,medium:L,high:W},expiring_soon:Z,recently_used:M}}async function YN(N){let $=await d$(N);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 ZN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await T.selectFrom("gift_cards").select(T.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0($))} OR expiry_date IS NULL)`).where("created_at",">=",u(J)).where("created_at","<=",u($)).executeTakeFirst(),W=await T.selectFrom("gift_cards").select(T.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0(X))} OR expiry_date IS NULL)`).where("created_at",">=",u(X)).where("created_at","<=",u(G)).executeTakeFirst(),Y=Number(L?.count||0),Z=Number(W?.count||0),M=Y-Z,K=Z!==0?M/Z*100:Y>0?100:0;return{current_period:Y,previous_period:Z,difference:M,percentage_change:K,days_range:N}}async function MN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await T.selectFrom("gift_cards").select([T.fn.sum("initial_balance").as("total_initial"),T.fn.sum("current_balance").as("total_balance"),T.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0($))} OR expiry_date IS NULL)`).where("created_at",">=",u(J)).where("created_at","<=",u($)).executeTakeFirst(),W=await T.selectFrom("gift_cards").select([T.fn.sum("initial_balance").as("total_initial"),T.fn.sum("current_balance").as("total_balance"),T.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0(X))} OR expiry_date IS NULL)`).where("created_at",">=",u(X)).where("created_at","<=",u(G)).executeTakeFirst(),Y=Number(L?.total_initial||0),Z=Number(L?.total_balance||0),M=Number(L?.card_count||0),K=Number(W?.total_initial||0),Q=Number(W?.total_balance||0),x=Number(W?.card_count||0),R=Y>0?(Y-Z)/Y*100:0,O=K>0?(K-Q)/K*100:0,_=M>0?Y/M:0,S=M>0?Z/M:0,D=Y-K,o=Z-Q,s=M-x,J0=K!==0?D/K*100:Y>0?100:0,p=Q!==0?o/Q*100:Z>0?100:0,Q3=x!==0?s/x*100:M>0?100:0;return{current_period:{total_initial_value:Y,total_remaining_balance:Z,utilization_rate:R,card_count:M,average_initial_value:_,average_remaining_balance:S},previous_period:{total_initial_value:K,total_remaining_balance:Q,utilization_rate:O,card_count:x},comparison:{initial_value:{difference:D,percentage:Math.abs(J0),is_increase:D>=0},balance:{difference:o,percentage:Math.abs(p),is_increase:o>=0},card_count:{difference:s,percentage:Math.abs(Q3),is_increase:s>=0}},days_range:N}}async function FN(){let{total_value:N}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:N}}async function KN(){let{total_balance:N}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:N}}async function xN(N){let $=await QN.deleteFrom("gift_cards").where("id","=",N).executeTakeFirst();return F($)>0}async function HN(N){if(!N.length)return 0;let $=await QN.deleteFrom("gift_cards").where("id","in",N).executeTakeFirst();return F($)}var{randomUUIDv7:j3}=globalThis.Bun;import{db as VN}from"@stacksjs/database";import{HttpError as zN}from"@stacksjs/error-handling";import{isUniqueViolation as C3}from"@stacksjs/orm";async function BN(N){let $=N,J={...N,current_balance:$.current_balance??$.initial_balance,status:N.status||"ACTIVE",is_active:$.is_active??!0,uuid:j3()};try{let G=await VN.insertInto("gift_cards").values(J).executeTakeFirst(),X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows);if(X)return await VN.selectFrom("gift_cards").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof zN)throw G;if(C3(G))throw new zN(409,"A gift card with this code already exists");if(G instanceof Error)throw Error(`Failed to create gift card: ${G.message}`);throw G}}import{db as RN}from"@stacksjs/database";import{HttpError as AN}from"@stacksjs/error-handling";import{formatDate as _N,isUniqueViolation as I3}from"@stacksjs/orm";async function ON(N,$){if(!await a(N))return;try{return await RN.updateTable("gift_cards").set({...$,updated_at:_N(new Date)}).where("id","=",N).execute(),await a(N)}catch(G){if(G instanceof AN)throw G;if(I3(G))throw new AN(409,"A gift card with this code already exists");if(G instanceof Error)throw Error(`Failed to update gift card: ${G.message}`);throw G}}async function SN(N,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let J=_N(new Date),G=await RN.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 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
|
|
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 x3=Object.defineProperty;var H3=(N)=>N;function V3(N,$){this[N]=H3.bind(null
|
|
|
13
13
|
WHERE id = ?
|
|
14
14
|
AND is_active = 1
|
|
15
15
|
AND status = 'ACTIVE'
|
|
16
|
-
AND current_balance + ? >= 0`,[$,
|
|
16
|
+
AND current_balance + ? >= 0`,[$,G,$,G,J,$]),X=typeof N?.execute==="function"?await N.execute():N;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0)return await J0(J);let Z=await J0(J);if(!Z)throw Error(`Gift card with ID ${J} not found`);if(!Z.is_active||Z.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var q1={};z(q1,{validateQuantityBounds:()=>w1,validateCouponStacking:()=>UJ,validateCartQuantities:()=>TJ,updateStatus:()=>BJ,updateDeliveryInfo:()=>AJ,update:()=>zJ,storeOrdersExport:()=>t7,store:()=>YJ,softDelete:()=>s7,registerCommerceWebhookHandlers:()=>RJ,recomputeOrderTotals:()=>SJ,placeOrder:()=>xJ,handlePaymentIntentSucceeded:()=>U1,handlePaymentIntentFailed:()=>T1,handleChargeRefunded:()=>P1,findOrderByIdempotencyKey:()=>L$,fetchStats:()=>JJ,fetchDailyOrderTrends:()=>XJ,fetchById:()=>c,fetchAll:()=>$J,exportOrders:()=>X$,emitOrderShipped:()=>W$,emitOrderRefunded:()=>Q0,emitOrderPaid:()=>d,emitOrderDelivered:()=>Z$,emitOrderCreated:()=>w0,emitOrderCancelled:()=>F0,emitForStatus:()=>q0,downloadOrders:()=>r7,destroy:()=>o7,compareOrdersByPeriod:()=>GJ,cleanupAbandonedCarts:()=>PJ,canTransition:()=>P0,calculateOrderMetrics:()=>NJ,bulkSoftDelete:()=>a7,bulkDestroy:()=>d7});import{db as N$}from"@stacksjs/database";async function o7(J){try{let $=await N$.deleteFrom("orders").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function s7(J){try{let $=await N$.updateTable("orders").set({status:"CANCELED"}).where("id","=",J).executeTakeFirst();return Number($.numUpdatedRows)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete order: ${$.message}`);throw $}}async function d7(J){if(!J.length)return 0;try{let $=await N$.deleteFrom("orders").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}async function a7(J){if(!J.length)return 0;try{let $=await N$.updateTable("orders").set({status:"CANCELED"}).where("id","in",J).executeTakeFirst();return Number($.numUpdatedRows)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete orders: ${$.message}`);throw $}}import{db as e7}from"@stacksjs/database";import{createSpreadsheet as x9}from"ts-spreadsheets";async function X$(J="csv"){let $=await z9(),G=B9($);return x9(G,{type:J})}async function z9(){let J=await e7.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),$=J.map((W)=>W.id);if($.length===0)return[];let N=(await e7.selectFrom("order_items").where("order_items.order_id","in",$).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((W,Z)=>{if(!Z.order_id)return W;if(!W[Z.order_id])W[Z.order_id]={totalItems:0,totalPrice:0};return W[Z.order_id].totalItems+=Z.quantity,W[Z.order_id].totalPrice+=Z.price*Z.quantity,W},{});return J.map((W)=>{let Z=N[W.id]||{totalItems:0,totalPrice:0};return{...W,totalItems:Z.totalItems,totalPrice:Z.totalPrice}})}function B9(J){let $=["Order ID","Customer","Date","Total","Status","Items"],G=J.map((N)=>{let X=N.order_items?.map((W)=>`${W.product?.name} (Qty: ${W.quantity}, Price: $${W.price})`).join(" | ")||"No Items";return[N.id,N.customer?.name||"N/A",N.created_at,N.total_amount,N.status,X]});return{headings:$,data:G}}async function r7(J="csv",$){let G=await X$(J),N=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;return G.download($||N)}async function t7(J="csv",$){let G=await X$(J),N=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;G.store($||N)}import{db as B}from"@stacksjs/database";async function $J(J){let $=B.selectFrom("orders").selectAll().orderBy("created_at","desc");if(J)$=$.limit(J);let G=await $.execute();return await Promise.all(G.map(async(N)=>{let X=await B.selectFrom("order_items").where("order_id","=",N.id).selectAll().execute();return{...N,items:X}}))}async function c(J){return await B.selectFrom("orders").where("id","=",J).selectAll().executeTakeFirst()}async function JJ(){let J=await B.selectFrom("orders").select(B.fn.count("id").as("count")).executeTakeFirst(),$=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).groupBy("status").execute(),G=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).groupBy("order_type").execute(),N=await B.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),X=await Promise.all(N.map(async(Z)=>{let Y=await B.selectFrom("order_items").where("order_id","=",Z.id).selectAll().execute();return{...Z,items:Y}})),W=await B.selectFrom("orders").select(B.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(J?.count||0),by_status:$,by_type:G,recent:X,revenue:Number(W?.total||0)}}async function GJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),Z=await B.selectFrom("orders").select(B.fn.count("id").as("count")).where("created_at",">=",X.toISOString()).where("created_at","<=",N.toISOString()).executeTakeFirst(),Y=Number(W?.count||0),L=Number(Z?.count||0),K=Y-L,Q=L!==0?K/L*100:Y>0?100:0;return{current_period:Y,previous_period:L,difference:K,percentage_change:Q,days_range:J}}async function NJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),Z=await B.selectFrom("orders").select([B.fn.count("id").as("total_orders"),B.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",X.toISOString()).where("created_at","<=",N.toISOString()).executeTakeFirst(),Y=await B.selectFrom("orders").select(["status",B.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("status").execute(),L=await B.selectFrom("orders").select(["order_type",B.fn.count("id").as("count")]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).groupBy("order_type").execute(),K=Number(W?.total_orders||0),Q=Number(W?.total_revenue||0),M=K>0?Q/K:0,H=Number(Z?.total_orders||0),_=Number(Z?.total_revenue||0),O=H>0?_/H:0,R=K-H,S=Q-_,m=M-O,r=H!==0?R/H*100:K>0?100:0,t=_!==0?S/_*100:Q>0?100:0,L0=O!==0?m/O*100:M>0?100:0;return{current_period:{total_orders:K,total_revenue:Q,average_order_value:M,orders_by_status:Y.map((p)=>({status:p.status,count:Number(p.count)})),orders_by_type:L.map((p)=>({order_type:p.order_type,count:Number(p.count)}))},previous_period:{total_orders:H,total_revenue:_,average_order_value:O},comparison:{orders:{difference:R,percentage:Math.abs(r),is_increase:R>=0},revenue:{difference:S,percentage:Math.abs(t),is_increase:S>=0},average_order_value:{difference:m,percentage:Math.abs(L0),is_increase:m>=0}},days_range:J}}async function XJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=await B.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",G.toISOString()).where("created_at","<=",$.toISOString()).orderBy("created_at","asc").execute(),X=new Map;for(let W of N){let Z=(W.created_at||"").split("T")[0]||"unknown",Y=X.get(Z)||{order_count:0,revenue:0};Y.order_count++,Y.revenue+=Number(W.total_amount||0),X.set(Z,Y)}return Array.from(X.entries()).map(([W,Z])=>({date:W,order_count:Z.order_count,revenue:Z.revenue}))}var{randomUUIDv7:A9}=globalThis.Bun;import{db as WJ}from"@stacksjs/database";import{formatDate as ZJ}from"@stacksjs/orm";async function YJ(J){let $={...J,status:J.status||"PENDING",uuid:A9(),created_at:ZJ(new Date),updated_at:ZJ(new Date)};try{let G=await WJ.insertInto("orders").values($).executeTakeFirst(),N=Number(G?.insertId)||Number(G?.numInsertedOrUpdatedRows);if(N)return await WJ.selectFrom("orders").where("id","=",N).selectAll().executeTakeFirst();return}catch(G){if(G instanceof Error)throw Error(`Failed to create order: ${G.message}`);throw G}}M0();var{randomUUIDv7:QJ}=globalThis.Bun;import{db as Y$}from"@stacksjs/database";import{formatDate as U9,isUniqueViolation as MJ}from"@stacksjs/orm";import{sqlHelpers as R9}from"@stacksjs/database";import{env as O9}from"@stacksjs/env";function S9(J,$,G,N){let X=R9(J).param;return{query:`UPDATE products
|
|
17
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:[J,G,$,J]}}async function DN(N,$,J,G){let X=m3(b3.DB_CONNECTION||"sqlite",$,J,G),L=await N.unsafe(X.query,X.parameters),W=typeof L?.execute==="function"?await L.execute():L;return F(W)}var mN=!1;function lN(N){let $=N,J=$?.message??"";return $?.code==="42P01"||J.includes("no such table")||J.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(J)}async function a0(N){try{let $=await d0.selectFrom("order_idempotency").where("idempotency_key","=",N).selectAll().executeTakeFirst();if(!$)return null;return await d0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(lN($)){if(!mN)mN=!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 cN(N){if(N.idempotencyKey){let $=await a0(N.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await d0.transaction(async(J)=>{let G=l3(new Date),X=pN(),L={...N.order,status:N.order.status||"PENDING",uuid:X,created_at:G,updated_at:G};await J.insertInto("orders").values(L).executeTakeFirst();let W=await J.selectFrom("orders").where("uuid","=",X).selectAll().executeTakeFirst(),Y=Number(W?.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 Z;if(N.items&&N.items.length>0){let Q=N.items.map((x)=>{if(!Number.isInteger(x.productId)||x.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(x.quantity)||x.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(x.price)||x.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:Y,product_id:x.productId,quantity:x.quantity,price:x.price,special_instructions:x.specialInstructions||null,created_at:G,updated_at:G}});await J.insertInto("order_items").values(Q).execute(),Z=await J.selectFrom("order_items").where("order_id","=",Y).selectAll().execute()}let M;if(N.payment)try{let Q=pN();if(await J.insertInto("payments").values({...N.payment,order_id:Y,uuid:Q,created_at:G,updated_at:G}).executeTakeFirst(),M=await J.selectFrom("payments").where("uuid","=",Q).selectAll().executeTakeFirst(),!M)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(Q){if(bN(Q))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(Q,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(N.inventory&&N.inventory.length>0)for(let Q=0;Q<N.inventory.length;Q++){let{id:x,delta:R}=N.inventory[Q];if(!Number.isFinite(R)||R===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await DN(J,x,R,G))throw Object.assign(Error(`inventory adjust failed for product ${x}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(N.idempotencyKey)try{await J.insertInto("order_idempotency").values({idempotency_key:N.idempotencyKey,order_id:Y,created_at:G}).execute()}catch(Q){if(bN(Q))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!lN(Q))throw Q}let K=await J.selectFrom("orders").where("id","=",Y).selectAll().executeTakeFirst();if(!K)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:K,items:Z,payment:M}});if(o0($.order),$.payment)e($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&N.idempotencyKey){let J=await a0(N.idempotencyKey);if(J)return{ok:!0,order:J}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}import{db as r$}from"@stacksjs/database";import{formatDate as $1}from"@stacksjs/orm";async function nN(N,$){if(!await m(N))return;try{return await r$.updateTable("orders").set({...$,updated_at:$1(new Date)}).where("id","=",N).execute(),await m(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update order: ${G.message}`);throw G}}async function uN(N,$){let J=await m(N);if(!J)throw Error(`Order with ID ${N} not found`);let G=J.status??"PENDING";if(!i0(G,$))throw Error(`[commerce/orders] illegal status transition ${G} \u2192 ${$}`);try{await r$.updateTable("orders").set({status:$,updated_at:$1(new Date)}).where("id","=",N).execute();let X=await m(N);if(X)s0($,X);return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order status: ${X.message}`);throw X}}async function iN(N,$,J){let G=await m(N);if(!G)throw Error(`Order with ID ${N} not found`);let X={updated_at:$1(new Date)};if($!==void 0)X.delivery_address=$;if(J!==void 0)X.estimated_delivery_time=J;if(Object.keys(X).length===1)return G;try{return await r$.updateTable("orders").set(X).where("id","=",N).execute(),await m(N)}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery information: ${L.message}`);throw L}}import{db as L0}from"@stacksjs/database";import{formatDate as e0}from"@stacksjs/orm";async function N1(N){let $=await L0.selectFrom("payments").where("transaction_id","=",N).selectAll().executeTakeFirst();if(!$)return null;return await L0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var oN=!1;function c3(N){let $=N,J=$?.message??"";return $?.code==="42P01"||J.includes("no such table")||J.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(J)}async function J1(N,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:N,processed_at:e0(new Date)}).execute(),!0}catch(J){if(J?.message?.includes("UNIQUE constraint")||J?.message?.includes("Duplicate entry"))return!1;if(c3(J)){if(!oN)oN=!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 J}}async function G1(N){let J=N.data.object?.id;if(!J)return;await L0.transaction(async(X)=>{if(!await J1(N.id,X))return;let W=await X.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!W)return;let Y=e0(new Date);await X.updateTable("payments").set({status:"succeeded",updated_at:Y}).where("id","=",W.id).execute();let Z=await X.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(Z&&Z.status==="PENDING")await X.updateTable("orders").set({status:"PROCESSING",updated_at:Y}).where("id","=",Z.id).execute()});let G=await N1(J);if(G)await e(G)}async function X1(N){let $=N.data.object,J=$?.id;if(!J)return;let X=$?.last_payment_error?.message??"payment failed";await L0.transaction(async(W)=>{if(!await J1(N.id,W))return;let Z=await W.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!Z)return;let M=e0(new Date);await W.updateTable("payments").set({status:"failed",failure_reason:X,updated_at:M}).where("id","=",Z.id).execute();let K=await W.selectFrom("orders").where("id","=",Z.order_id).selectAll().executeTakeFirst();if(K&&K.status==="PENDING")await W.updateTable("orders").set({status:"CANCELLED",updated_at:M}).where("id","=",K.id).execute()});let L=await N1(J);if(L)await z0(L,X)}async function L1(N){let $=N.data.object,J=$?.payment_intent;if(!J)return;let G=$?.amount_refunded??0;await L0.transaction(async(L)=>{if(!await J1(N.id,L))return;let Y=await L.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!Y)return;let Z=e0(new Date);await L.updateTable("payments").set({status:"refunded",refund_amount:G,updated_at:Z}).where("id","=",Y.id).execute();let M=await L.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(M&&M.status!=="REFUNDED")await L.updateTable("orders").set({status:"REFUNDED",updated_at:Z}).where("id","=",M.id).execute()});let X=await N1(J);if(X)await B0(X,G)}async function sN(){let N=await import("@stacksjs/payments").catch(()=>null);if(!N)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:J}=N;if(typeof $!=="function"||typeof J!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:G1,failed:X1}),J({refunded:L1}),()=>{}}import{db as dN}from"@stacksjs/database";async function n3(N){if(N.length===0)return new Map;let $=await dN.selectFrom("products").where("id","in",N).select(["id","price"]).execute(),J=new Map;for(let G of $){let X=Number(G.price);if(Number.isFinite(X))J.set(G.id,Math.round(X))}return J}async function u3(N){try{let $=await dN.selectFrom("tax_rates").where("id","=",N).select(["rate"]).executeTakeFirst(),J=Number($?.rate??0);return Number.isFinite(J)?J:0}catch{return 0}}async function aN(N){let $=N.items.map((O)=>O.productId),J=await n3($),G=N.taxRateId!=null?await u3(N.taxRateId):0,X=0,L=[];for(let O of N.items){let _=O.unitPriceCents??J.get(O.productId)??0,S=Math.round(_*O.quantity);X+=S,L.push({productId:O.productId,quantity:O.quantity,unitPriceCents:_,lineCents:S})}let W=Math.max(0,N.discountCents??0),Y=Math.max(0,X-W),Z=Math.round(Y*G),M=Math.max(0,N.shippingCents??0),K=X-W+Z+M,Q=N.maxDriftCents??5,x=!1,R=0;if(N.clientTotalCents!=null)R=Math.abs(K-N.clientTotalCents),x=R>Q;return{subtotalCents:X,discountCents:W,taxCents:Z,shippingCents:M,totalCents:K,resolvedItems:L,priceChanged:x,diffCents:R}}import{db as t0}from"@stacksjs/database";function eN(N,$={}){let J=N.length;if(J<=1)return{ok:!0,count:J};if(!$.allowMultiple)return{ok:!1,count:J,reason:"multiple-not-allowed"};let G=$.maxStacked??Number.POSITIVE_INFINITY;if(J>G)return{ok:!1,count:J,reason:"exceeds-max-stacked"};return{ok:!0,count:J}}async function W1(N,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:N,quantity:$,reason:"non-positive"};let J;try{J=await t0.selectFrom("products").where("id","=",N).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:N,quantity:$}}if(!J)return{ok:!1,productId:N,quantity:$,reason:"product-missing"};let G=J.min_order_qty??null,X=J.max_order_qty??null;if(G!=null&&$<G)return{ok:!1,productId:N,quantity:$,reason:"below-min",bound:G};if(X!=null&&$>X)return{ok:!1,productId:N,quantity:$,reason:"above-max",bound:X};return{ok:!0,productId:N,quantity:$}}async function tN(N){for(let J of N){let G=await W1(J.productId,J.quantity);if(!G.ok)return G}let $=N[N.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function rN(N={}){let $=N.olderThanDays??30,J=N.limit??1000,X=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let L=await t0.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[X,X,J]),W=typeof L?.execute==="function"?await L.execute():L;return{deleted:Number(W?.changes??W?.numDeletedRows??W?.[0]?.numDeletedRows??W?.affectedRows??0),cutoffAt:X}}catch{try{let L=await t0.selectFrom("carts").where("updated_at","<",X).select(["id"]).limit(J).execute();if(L.length===0)return{deleted:0,cutoffAt:X};let W=L.map((M)=>M.id),Y=await t0.deleteFrom("carts").where("id","in",W).execute();return{deleted:Number(Y?.numDeletedRows??Y?.[0]?.numDeletedRows??Y?.affectedRows??L.length),cutoffAt:X}}catch{return{deleted:0,cutoffAt:X}}}}var Z1={};B(Z1,{update:()=>Q2,store:()=>M2,recordRefund:()=>x2,fetchPaymentStatsByMethod:()=>L2,fetchPaymentStats:()=>X2,fetchMonthlyPaymentTrends:()=>W2,fetchById:()=>t,fetchAll:()=>G2,destroy:()=>N2,bulkDestroy:()=>J2});import{db as $2}from"@stacksjs/database";async function N2(N){try{let $=await $2.deleteFrom("payments").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function J2(N){if(!N.length)return 0;try{let $=await $2.deleteFrom("payments").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as q}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function G2(){return await q.selectFrom("payments").selectAll().execute()}async function t(N){return await q.selectFrom("payments").selectAll().where("id","=",N).executeTakeFirst()}async function X2(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",g(J)).where("created_at","<=",g($)).where("status","=","completed").executeTakeFirst(),W=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",g(X)).where("created_at","<=",g(G)).where("status","=","completed").executeTakeFirst(),Y=await q.selectFrom("payments").select(q.fn.count("id").as("count")).where("created_at",">=",g(J)).where("created_at","<=",g($)).executeTakeFirst(),Z=Number(L?.transaction_count||0),M=Number(L?.total_revenue||0),K=Z>0?M/Z:0,Q=Number(W?.transaction_count||0),x=Number(W?.total_revenue||0),R=Q>0?x/Q:0,O=Z-Q,_=M-x,S=K-R,D=Q>0?O/Q*100:Z>0?100:0,o=x>0?_/x*100:M>0?100:0,s=R>0?S/R*100:K>0?100:0,J0=Number(Y?.count||0),p=J0>0?Z/J0*100:0;return{total_transactions:Z,total_revenue:M,average_transaction:K,successful_rate:p,comparison:{transactions:{difference:O,percentage:Math.abs(D),is_increase:O>=0},revenue:{difference:_,percentage:Math.abs(o),is_increase:_>=0},average:{difference:S,percentage:Math.abs(s),is_increase:S>=0}}}}async function L2(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=await q.selectFrom("payments").select([q.fn.count("id").as("total_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",g(J)).where("created_at","<=",g($)).where("status","=","completed").executeTakeFirst(),X=Number(G?.total_count||0),L=await q.selectFrom("payments").select(["method",q.fn.count("id").as("count"),q.fn.sum("amount").as("revenue")]).where("created_at",">=",g(J)).where("created_at","<=",g($)).where("status","=","completed").groupBy("method").execute(),W={};return L.forEach((Y)=>{let Z=Number(Y.count||0),M=Number(Y.revenue||0),K=X>0?Z/X*100:0;W[Y.method]={count:Z,revenue:M,percentage_of_total:K}}),W}async function W2(){let N=new Date,$=new Date(N);$.setMonth(N.getMonth()-11),$.setDate(1);let J=await q.selectFrom("payments").selectAll().where("created_at",">=",g($)).where("status","=","completed").execute(),G={};for(let L of J){let W=L.created_at?new Date(L.created_at):new Date,Y=W.getFullYear(),Z=W.getMonth()+1,M=`${Y}-${String(Z).padStart(2,"0")}`;if(!G[M])G[M]={year:Y,month:Z,transactions:0,revenue:0};G[M].transactions++,G[M].revenue+=Number(L.amount||0)}return Object.keys(G).sort().map((L)=>{let W=G[L],Y=W.transactions,Z=W.revenue,M=Y>0?Z/Y:0;return{month:new Date(W.year,W.month-1,1).toLocaleString("default",{month:"short"}),year:W.year,transactions:Y,revenue:Z,average:M}})}var{randomUUIDv7:i3}=globalThis.Bun;import{db as Y2}from"@stacksjs/database";import{HttpError as Z2}from"@stacksjs/error-handling";import{isUniqueViolation as o3}from"@stacksjs/orm";async function M2(N){let $=i3(),J={...N,status:N.status||"pending",currency:N.currency||"USD",uuid:$};try{return await Y2.insertInto("payments").values(J).executeTakeFirst(),await Y2.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(G){if(G instanceof Z2)throw G;if(o3(G))throw new Z2(409,"A payment with this transaction ID already exists");if(G instanceof Error){if(G.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${G.message}`)}throw G}}import{db as F2,sqlHelpers as s3}from"@stacksjs/database";import{env as d3}from"@stacksjs/env";import{formatDate as K2}from"@stacksjs/orm";async function Q2(N,$){if(!await t(N))return;try{return await F2.updateTable("payments").set({...$,updated_at:K2(new Date)}).where("id","=",N).execute(),await t(N)}catch(G){if(G instanceof Error){if(G.message.includes("Duplicate entry")&&G.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${G.message}`)}throw G}}var a3=new Set(["completed","succeeded","partiallyRefunded"]);async function x2(N,$){if(!Number.isSafeInteger(N)||N<=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 G=s3(d3.DB_CONNECTION||"sqlite").param,X=K2(new Date),L=await F2.unsafe(`UPDATE payments
|
|
21
|
-
SET refund_amount = COALESCE(refund_amount, 0) + ${
|
|
22
|
-
status = CASE WHEN COALESCE(refund_amount, 0) + ${
|
|
20
|
+
AND inventory_count + ${X(4)} >= 0`,parameters:[G,N,$,G]}}async function FJ(J,$,G,N){let X=S9(O9.DB_CONNECTION||"sqlite",$,G,N),W=await J.unsafe(X.query,X.parameters),Z=typeof W?.execute==="function"?await W.execute():W;return F(Z)}var HJ=!1;function VJ(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function L$(J){try{let $=await Y$.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!$)return null;return await Y$.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(VJ($)){if(!HJ)HJ=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw $}}async function xJ(J){if(J.idempotencyKey){let $=await L$(J.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await Y$.transaction(async(G)=>{let N=U9(new Date),X=QJ(),W={...J.order,status:J.order.status||"PENDING",uuid:X,created_at:N,updated_at:N};await G.insertInto("orders").values(W).executeTakeFirst();let Z=await G.selectFrom("orders").where("uuid","=",X).selectAll().executeTakeFirst(),Y=Number(Z?.id);if(!Number.isSafeInteger(Y)||Y<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let L;if(J.items&&J.items.length>0){let M=J.items.map((H)=>{if(!Number.isInteger(H.productId)||H.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(H.quantity)||H.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(H.price)||H.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:Y,product_id:H.productId,quantity:H.quantity,price:H.price,special_instructions:H.specialInstructions||null,created_at:N,updated_at:N}});await G.insertInto("order_items").values(M).execute(),L=await G.selectFrom("order_items").where("order_id","=",Y).selectAll().execute()}let K;if(J.payment)try{let M=QJ();if(await G.insertInto("payments").values({...J.payment,order_id:Y,uuid:M,created_at:N,updated_at:N}).executeTakeFirst(),K=await G.selectFrom("payments").where("uuid","=",M).selectAll().executeTakeFirst(),!K)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(M){if(MJ(M))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(M,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(J.inventory&&J.inventory.length>0)for(let M=0;M<J.inventory.length;M++){let{id:H,delta:_}=J.inventory[M];if(!Number.isFinite(_)||_===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await FJ(G,H,_,N))throw Object.assign(Error(`inventory adjust failed for product ${H}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await G.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:Y,created_at:N}).execute()}catch(M){if(MJ(M))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!VJ(M))throw M}let Q=await G.selectFrom("orders").where("id","=",Y).selectAll().executeTakeFirst();if(!Q)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:Q,items:L,payment:K}});if(w0($.order),$.payment)d($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&J.idempotencyKey){let G=await L$(J.idempotencyKey);if(G)return{ok:!0,order:G}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}M0();import{db as _1}from"@stacksjs/database";import{formatDate as R1}from"@stacksjs/orm";M0();async function zJ(J,$){if(!await c(J))return;try{return await _1.updateTable("orders").set({...$,updated_at:R1(new Date)}).where("id","=",J).execute(),await c(J)}catch(N){if(N instanceof Error)throw TypeError(`Failed to update order: ${N.message}`);throw N}}async function BJ(J,$){let G=await c(J);if(!G)throw Error(`Order with ID ${J} not found`);let N=G.status??"PENDING";if(!P0(N,$))throw Error(`[commerce/orders] illegal status transition ${N} \u2192 ${$}`);try{await _1.updateTable("orders").set({status:$,updated_at:R1(new Date)}).where("id","=",J).execute();let X=await c(J);if(X)q0($,X);return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order status: ${X.message}`);throw X}}async function AJ(J,$,G){let N=await c(J);if(!N)throw Error(`Order with ID ${J} not found`);let X={updated_at:R1(new Date)};if($!==void 0)X.delivery_address=$;if(G!==void 0)X.estimated_delivery_time=G;if(Object.keys(X).length===1)return N;try{return await _1.updateTable("orders").set(X).where("id","=",J).execute(),await c(J)}catch(W){if(W instanceof Error)throw TypeError(`Failed to update delivery information: ${W.message}`);throw W}}M0();import{db as H0}from"@stacksjs/database";import{formatDate as K$}from"@stacksjs/orm";async function O1(J){let $=await H0.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!$)return null;return await H0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var _J=!1;function T9(J){let $=J,G=$?.message??"";return $?.code==="42P01"||G.includes("no such table")||G.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(G)}async function S1(J,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:J,processed_at:K$(new Date)}).execute(),!0}catch(G){if(G?.message?.includes("UNIQUE constraint")||G?.message?.includes("Duplicate entry"))return!1;if(T9(G)){if(!_J)_J=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw G}}async function U1(J){let G=J.data.object?.id;if(!G)return;await H0.transaction(async(X)=>{if(!await S1(J.id,X))return;let Z=await X.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Z)return;let Y=K$(new Date);await X.updateTable("payments").set({status:"succeeded",updated_at:Y}).where("id","=",Z.id).execute();let L=await X.selectFrom("orders").where("id","=",Z.order_id).selectAll().executeTakeFirst();if(L&&L.status==="PENDING")await X.updateTable("orders").set({status:"PROCESSING",updated_at:Y}).where("id","=",L.id).execute()});let N=await O1(G);if(N)await d(N)}async function T1(J){let $=J.data.object,G=$?.id;if(!G)return;let X=$?.last_payment_error?.message??"payment failed";await H0.transaction(async(Z)=>{if(!await S1(J.id,Z))return;let L=await Z.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!L)return;let K=K$(new Date);await Z.updateTable("payments").set({status:"failed",failure_reason:X,updated_at:K}).where("id","=",L.id).execute();let Q=await Z.selectFrom("orders").where("id","=",L.order_id).selectAll().executeTakeFirst();if(Q&&Q.status==="PENDING")await Z.updateTable("orders").set({status:"CANCELLED",updated_at:K}).where("id","=",Q.id).execute()});let W=await O1(G);if(W)await F0(W,X)}async function P1(J){let $=J.data.object,G=$?.payment_intent;if(!G)return;let N=$?.amount_refunded??0;await H0.transaction(async(W)=>{if(!await S1(J.id,W))return;let Y=await W.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!Y)return;let L=K$(new Date);await W.updateTable("payments").set({status:"refunded",refund_amount:N,updated_at:L}).where("id","=",Y.id).execute();let K=await W.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(K&&K.status!=="REFUNDED")await W.updateTable("orders").set({status:"REFUNDED",updated_at:L}).where("id","=",K.id).execute()});let X=await O1(G);if(X)await Q0(X,N)}async function RJ(){let J=await import("@stacksjs/payments").catch(()=>null);if(!J)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:G}=J;if(typeof $!=="function"||typeof G!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:U1,failed:T1}),G({refunded:P1}),()=>{}}import{db as OJ}from"@stacksjs/database";async function P9(J){if(J.length===0)return new Map;let $=await OJ.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),G=new Map;for(let N of $){let X=Number(N.price);if(Number.isFinite(X))G.set(N.id,Math.round(X))}return G}async function w9(J){try{let $=await OJ.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),G=Number($?.rate??0);return Number.isFinite(G)?G:0}catch{return 0}}async function SJ(J){let $=J.items.map((O)=>O.productId),G=await P9($),N=J.taxRateId!=null?await w9(J.taxRateId):0,X=0,W=[];for(let O of J.items){let R=O.unitPriceCents??G.get(O.productId)??0,S=Math.round(R*O.quantity);X+=S,W.push({productId:O.productId,quantity:O.quantity,unitPriceCents:R,lineCents:S})}let Z=Math.max(0,J.discountCents??0),Y=Math.max(0,X-Z),L=Math.round(Y*N),K=Math.max(0,J.shippingCents??0),Q=X-Z+L+K,M=J.maxDriftCents??5,H=!1,_=0;if(J.clientTotalCents!=null)_=Math.abs(Q-J.clientTotalCents),H=_>M;return{subtotalCents:X,discountCents:Z,taxCents:L,shippingCents:K,totalCents:Q,resolvedItems:W,priceChanged:H,diffCents:_}}import{db as F$}from"@stacksjs/database";function UJ(J,$={}){let G=J.length;if(G<=1)return{ok:!0,count:G};if(!$.allowMultiple)return{ok:!1,count:G,reason:"multiple-not-allowed"};let N=$.maxStacked??Number.POSITIVE_INFINITY;if(G>N)return{ok:!1,count:G,reason:"exceeds-max-stacked"};return{ok:!0,count:G}}async function w1(J,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:J,quantity:$,reason:"non-positive"};let G;try{G=await F$.selectFrom("products").where("id","=",J).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:J,quantity:$}}if(!G)return{ok:!1,productId:J,quantity:$,reason:"product-missing"};let N=G.min_order_qty??null,X=G.max_order_qty??null;if(N!=null&&$<N)return{ok:!1,productId:J,quantity:$,reason:"below-min",bound:N};if(X!=null&&$>X)return{ok:!1,productId:J,quantity:$,reason:"above-max",bound:X};return{ok:!0,productId:J,quantity:$}}async function TJ(J){for(let G of J){let N=await w1(G.productId,G.quantity);if(!N.ok)return N}let $=J[J.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function PJ(J={}){let $=J.olderThanDays??30,G=J.limit??1000,X=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let W=await F$.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[X,X,G]),Z=typeof W?.execute==="function"?await W.execute():W;return{deleted:Number(Z?.changes??Z?.numDeletedRows??Z?.[0]?.numDeletedRows??Z?.affectedRows??0),cutoffAt:X}}catch{try{let W=await F$.selectFrom("carts").where("updated_at","<",X).select(["id"]).limit(G).execute();if(W.length===0)return{deleted:0,cutoffAt:X};let Z=W.map((K)=>K.id),Y=await F$.deleteFrom("carts").where("id","in",Z).execute();return{deleted:Number(Y?.numDeletedRows??Y?.[0]?.numDeletedRows??Y?.affectedRows??W.length),cutoffAt:X}}catch{return{deleted:0,cutoffAt:X}}}}var f1={};z(f1,{update:()=>DJ,store:()=>gJ,recordRefund:()=>bJ,fetchPaymentStatsByMethod:()=>jJ,fetchPaymentStats:()=>kJ,fetchMonthlyPaymentTrends:()=>CJ,fetchById:()=>N0,fetchAll:()=>EJ,destroy:()=>qJ,bulkDestroy:()=>fJ});import{db as wJ}from"@stacksjs/database";async function qJ(J){try{let $=await wJ.deleteFrom("payments").where("id","=",J).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function fJ(J){if(!J.length)return 0;try{let $=await wJ.deleteFrom("payments").where("id","in",J).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as f}from"@stacksjs/database";import{formatDate as v}from"@stacksjs/orm";async function EJ(){return await f.selectFrom("payments").selectAll().execute()}async function N0(J){return await f.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function kJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=new Date(G);N.setDate(N.getDate()-1);let X=new Date(N);X.setDate(N.getDate()-J);let W=await f.selectFrom("payments").select([f.fn.count("id").as("transaction_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),Z=await f.selectFrom("payments").select([f.fn.count("id").as("transaction_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(X)).where("created_at","<=",v(N)).where("status","=","completed").executeTakeFirst(),Y=await f.selectFrom("payments").select(f.fn.count("id").as("count")).where("created_at",">=",v(G)).where("created_at","<=",v($)).executeTakeFirst(),L=Number(W?.transaction_count||0),K=Number(W?.total_revenue||0),Q=L>0?K/L:0,M=Number(Z?.transaction_count||0),H=Number(Z?.total_revenue||0),_=M>0?H/M:0,O=L-M,R=K-H,S=Q-_,m=M>0?O/M*100:L>0?100:0,r=H>0?R/H*100:K>0?100:0,t=_>0?S/_*100:Q>0?100:0,L0=Number(Y?.count||0),p=L0>0?L/L0*100:0;return{total_transactions:L,total_revenue:K,average_transaction:Q,successful_rate:p,comparison:{transactions:{difference:O,percentage:Math.abs(m),is_increase:O>=0},revenue:{difference:R,percentage:Math.abs(r),is_increase:R>=0},average:{difference:S,percentage:Math.abs(t),is_increase:S>=0}}}}async function jJ(J=30){let $=new Date,G=new Date($);G.setDate($.getDate()-J);let N=await f.selectFrom("payments").select([f.fn.count("id").as("total_count"),f.fn.sum("amount").as("total_revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").executeTakeFirst(),X=Number(N?.total_count||0),W=await f.selectFrom("payments").select(["method",f.fn.count("id").as("count"),f.fn.sum("amount").as("revenue")]).where("created_at",">=",v(G)).where("created_at","<=",v($)).where("status","=","completed").groupBy("method").execute(),Z={};return W.forEach((Y)=>{let L=Number(Y.count||0),K=Number(Y.revenue||0),Q=X>0?L/X*100:0;Z[Y.method]={count:L,revenue:K,percentage_of_total:Q}}),Z}async function CJ(){let J=new Date,$=new Date(J);$.setMonth(J.getMonth()-11),$.setDate(1);let G=await f.selectFrom("payments").selectAll().where("created_at",">=",v($)).where("status","=","completed").execute(),N={};for(let W of G){let Z=W.created_at?new Date(W.created_at):new Date,Y=Z.getFullYear(),L=Z.getMonth()+1,K=`${Y}-${String(L).padStart(2,"0")}`;if(!N[K])N[K]={year:Y,month:L,transactions:0,revenue:0};N[K].transactions++,N[K].revenue+=Number(W.amount||0)}return Object.keys(N).sort().map((W)=>{let Z=N[W],Y=Z.transactions,L=Z.revenue,K=Y>0?L/Y:0;return{month:new Date(Z.year,Z.month-1,1).toLocaleString("default",{month:"short"}),year:Z.year,transactions:Y,revenue:L,average:K}})}var{randomUUIDv7:q9}=globalThis.Bun;import{db as hJ}from"@stacksjs/database";import{HttpError as IJ}from"@stacksjs/error-handling";import{isUniqueViolation as f9}from"@stacksjs/orm";async function gJ(J){let $=q9(),G={...J,status:J.status||"pending",currency:J.currency||"USD",uuid:$};try{return await hJ.insertInto("payments").values(G).executeTakeFirst(),await hJ.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(N){if(N instanceof IJ)throw N;if(f9(N))throw new IJ(409,"A payment with this transaction ID already exists");if(N instanceof Error){if(N.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${N.message}`)}throw N}}import{db as vJ,sqlHelpers as E9}from"@stacksjs/database";import{env as k9}from"@stacksjs/env";import{formatDate as yJ}from"@stacksjs/orm";async function DJ(J,$){if(!await N0(J))return;try{return await vJ.updateTable("payments").set({...$,updated_at:yJ(new Date)}).where("id","=",J).execute(),await N0(J)}catch(N){if(N instanceof Error){if(N.message.includes("Duplicate entry")&&N.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${N.message}`)}throw N}}var j9=new Set(["completed","succeeded","partiallyRefunded"]);async function bJ(J,$){if(!Number.isSafeInteger(J)||J<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger($)||$<=0)throw TypeError("Refund amount must be a positive integer in minor units");let N=E9(k9.DB_CONNECTION||"sqlite").param,X=yJ(new Date),W=await vJ.unsafe(`UPDATE payments
|
|
21
|
+
SET refund_amount = COALESCE(refund_amount, 0) + ${N(1)},
|
|
22
|
+
status = CASE WHEN COALESCE(refund_amount, 0) + ${N(2)} = amount
|
|
23
23
|
THEN 'refunded' ELSE 'partiallyRefunded' END,
|
|
24
|
-
updated_at = ${
|
|
25
|
-
WHERE id = ${
|
|
24
|
+
updated_at = ${N(3)}
|
|
25
|
+
WHERE id = ${N(4)}
|
|
26
26
|
AND status IN ('completed', 'succeeded', 'partiallyRefunded')
|
|
27
|
-
AND COALESCE(refund_amount, 0) + ${G(5)} <= amount`,[$,$,X,N,$]),W=typeof L?.execute==="function"?await L.execute():L;if(Number(W?.numUpdatedRows??W?.[0]?.numUpdatedRows??W?.numAffectedRows??W?.affectedRows??W?.[0]?.affectedRows??W?.changes??0)>0){let x=await t(N);if(x)return x;throw Error(`Payment with ID ${N} disappeared during refund`)}let Z=await t(N);if(!Z)throw Error(`Payment with ID ${N} not found`);let M=String(Z.status||"");if(!a3.has(M))throw Error(`Payment status ${M||"unknown"} cannot be refunded`);let K=Z,Q=Number(Z.amount||0)-Number(K.refundAmount??K.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${Q} minor units`)}var V1={};B(V1,{variants:()=>Z$,units:()=>Y$,reviews:()=>X$,manufacturers:()=>G$,items:()=>J$,default:()=>YX,categories:()=>N$});var N$={};B(N$,{updateParent:()=>C2,updateDisplayOrder:()=>k2,updateActiveStatus:()=>j2,update:()=>f2,store:()=>F1,removeChildCategories:()=>w2,remove:()=>S2,findOrCreateByName:()=>q2,fetchStats:()=>R2,fetchRootCategories:()=>z2,fetchChildCategories:()=>B2,fetchCategoryTree:()=>O2,fetchByName:()=>H2,fetchById:()=>f,fetchByDisplayOrder:()=>A2,fetchAll:()=>M1,fetchActive:()=>V2,deactivateChildCategories:()=>E2,deactivate:()=>U2,compareCategoryGrowth:()=>_2,bulkRemove:()=>T2});import{db as W0}from"@stacksjs/database";import{db as w}from"@stacksjs/database";import{formatDate as A0}from"@stacksjs/orm";async function M1(){return await w.selectFrom("categories").selectAll().execute()}async function f(N){return await w.selectFrom("categories").where("id","=",N).selectAll().executeTakeFirst()}async function H2(N){return await w.selectFrom("categories").where("name","=",N).selectAll().executeTakeFirst()}async function V2(){return await w.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function z2(){return await w.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function B2(N){return await w.selectFrom("categories").where("parent_category_id","=",N).where("is_active","=",!0).selectAll().execute()}async function A2(N=!0){let $=w.selectFrom("categories").where("is_active","=",!0).selectAll();if(N)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function R2(){let N=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(),J=await w.selectFrom("categories").whereNull("parent_category_id").select(w.fn.count("id").as("count")).executeTakeFirst(),G=await w.selectFrom("categories").whereNotNull("image_url").select(w.fn.count("id").as("count")).executeTakeFirst(),X=new Date;X.setDate(X.getDate()-30);let L=A0(X),W=await w.selectFrom("categories").where("created_at",">=",L).selectAll().limit(5).execute(),Y=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(N?.count||0),active:Number($?.count||0),root_categories:Number(J?.count||0),child_categories:Number(N?.count||0)-Number(J?.count||0),with_images:Number(G?.count||0),recently_added:W,top_parent_categories:Y.map((Z)=>({id:String(Z.parent_category_id||""),name:String(Z.parent_name||""),child_count:Number(Z.child_count)}))}}async function _2(N=30){let $=new Date,J=A0($),G=new Date;G.setDate($.getDate()-N);let X=A0(G),L=new Date(G);L.setDate(L.getDate()-1);let W=A0(L),Y=new Date(L);Y.setDate(L.getDate()-N);let Z=A0(Y),M=await w.selectFrom("categories").select(w.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",J).executeTakeFirst(),K=await w.selectFrom("categories").select(w.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",W).executeTakeFirst(),Q=Number(M?.count||0),x=Number(K?.count||0),R=Q-x,O=x!==0?R/x*100:Q>0?100:0;return{current_period:Q,previous_period:x,difference:R,percentage_change:O,days_range:N}}async function O2(){let N=await M1(),$=new Map;N.forEach((X)=>{$.set(X.id,{...X,children:[]})});let J=[];N.forEach((X)=>{let L=$.get(X.id);if(X.parent_category_id){let W=$.get(X.parent_category_id);if(W)W.children.push(L)}else J.push(L)}),J.sort((X,L)=>X.display_order-L.display_order);let G=(X)=>{X.sort((L,W)=>L.display_order-W.display_order),X.forEach((L)=>{if(L.children.length>0)G(L.children)})};return G(J),J}async function S2(N){let $=await W0.deleteFrom("categories").where("id","=",N).executeTakeFirst();return F($)>0}async function T2(N){if(!N.length)return 0;let $=await W0.deleteFrom("categories").where("id","in",N).executeTakeFirst();return F($)}async function w2(N){let $=await W0.deleteFrom("categories").where("parent_category_id","=",N).executeTakeFirst();return F($)}async function U2(N){if(!await f(N))throw Error(`Category with ID ${N} not found`);return!!await W0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",N).executeTakeFirst()}async function E2(N){let $=await W0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",N).execute();return Number($.length)||0}var{randomUUIDv7:e3}=globalThis.Bun;import{db as P2}from"@stacksjs/database";import{HttpError as r0}from"@stacksjs/error-handling";import{isUniqueViolation as t3}from"@stacksjs/orm";import{slug as r3}from"@stacksjs/strings";async function F1(N){try{let $=N.parent_category_id?Number(N.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new r0(422,"Parent category ID must be a positive integer");if($&&!await f($))throw new r0(422,`Parent category with ID ${N.parent_category_id} not found`);let J={...N,uuid:e3(),is_active:N.is_active??!0,parent_category_id:N.parent_category_id||null},G=await P2.insertInto("categories").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create category");return G}catch($){if($ instanceof r0)throw $;if(t3($))throw new r0(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function q2(N){if(!N.name)throw Error("Name is required");let $=await P2.selectFrom("categories").selectAll().where("name","=",N.name).executeTakeFirst();if($)return $;let J={name:N.name,slug:r3(N.name),is_active:N.is_active??!0,display_order:0};return await F1(J)}import{db as R0}from"@stacksjs/database";import{HttpError as Y0}from"@stacksjs/error-handling";import{formatDate as $$,isUniqueViolation as $X}from"@stacksjs/orm";async function f2(N,$){if(!await f(N))return;if(Object.hasOwn($,"parent_category_id")){let G=$.parent_category_id?Number($.parent_category_id):void 0;if(G!==void 0&&(!Number.isSafeInteger(G)||G<=0))throw new Y0(422,"Parent category ID must be a positive integer");if(G===N)throw new Y0(422,"A category cannot be its own parent");if(G&&!await f(G))throw new Y0(422,`Parent category with ID ${$.parent_category_id} not found`);if(G&&await I2(N,String(G)))throw new Y0(422,"This operation would create a circular category hierarchy")}try{let G=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},X=await R0.updateTable("categories").set({...$,...G,updated_at:$$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!X)return;return X}catch(G){if(G instanceof Y0)throw G;if($X(G))throw new Y0(409,"A category with this name or slug already exists");if(G instanceof Error)throw Error(`Failed to update category: ${G.message}`);throw G}}async function k2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);try{return await R0.updateTable("categories").set({display_order:$,updated_at:$$(new Date)}).where("id","=",N).execute(),await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category display order: ${G.message}`);throw G}}async function j2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);try{return await R0.updateTable("categories").set({is_active:$,updated_at:$$(new Date)}).where("id","=",N).execute(),await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category active status: ${G.message}`);throw G}}async function C2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);if($){let G=Number($);if(G===N)throw Error("A category cannot be its own parent");if(!await f(G))throw Error(`Parent category with ID ${$} not found`);if(await I2(N,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let G={updated_at:$$(new Date)};if($===null)await R0.updateTable("categories").set({...G,parent_category_id:null}).where("id","=",N).execute();else await R0.updateTable("categories").set({...G,parent_category_id:$}).where("id","=",N).execute();return await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category parent: ${G.message}`);throw G}}async function I2(N,$){let J=Number($),G=new Set;while(J){if(G.has(J))return!0;if(J===N)return!0;G.add(J);let X=await f(J),L=X?.parent_category_id??X?.parentCategoryId;if(!X||!L)return!1;J=Number(L)}return!1}var J$={};B(J$,{updateInventory:()=>u2,updateAvailability:()=>n2,update:()=>c2,store:()=>m2,fetchTopProducts:()=>D2,fetchById:()=>l,fetchAll:()=>y2,destroy:()=>g2,bulkStore:()=>l2,bulkDestroy:()=>v2});import{db as h2}from"@stacksjs/database";async function g2(N){try{let $=await h2.deleteFrom("products").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function v2(N){if(!N.length)return 0;try{let $=await h2.deleteFrom("products").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as i,sql as NX}from"@stacksjs/database";async function l(N){let $=await i.selectFrom("products").where("id","=",N).selectAll().executeTakeFirst();if($){let J=null,G=null;if($.manufacturer_id)J=await i.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)G=await i.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:J,category:G}}return}async function y2(){let N=await i.selectFrom("products").selectAll().execute(),$=N.map((M)=>M.manufacturer_id).filter((M)=>M!==null&&M!==void 0),J=N.map((M)=>M.category_id).filter((M)=>M!==null&&M!==void 0),G=i.selectFrom("manufacturers"),X=i.selectFrom("categories");if($.length>0)G=G.where("id","in",$);if(J.length>0)X=X.where("id","in",J);let L=await G.selectAll().execute(),W=await X.selectAll().execute(),Y=L.reduce((M,K)=>{return M[K.id]=K,M},{}),Z=W.reduce((M,K)=>{return M[K.id]=K,M},{});return N.map((M)=>({...M,manufacturer:M.manufacturer_id?Y[M.manufacturer_id]:null,category:M.category_id?Z[M.category_id]:null}))}async function D2(N=5){try{return(await i.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",i.fn.sum("order_items.quantity").as("units_sold"),NX`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(N).execute()).map((J)=>({id:Number(J.id),name:String(J.name??"Unnamed product"),units_sold:Number(J.units_sold??0),revenue:Number(J.revenue??0),inventory_count:Number(J.inventory_count??0)}))}catch($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:p2}=globalThis.Bun;import{db as b2}from"@stacksjs/database";async function m2(N){try{let $={...N,uuid:p2()},J=await b2.insertInto("products").values($).executeTakeFirst();if(!J)throw Error("Failed to create product item");let G=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows),X=await l(G);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 l2(N){if(!N.length)return 0;let $=0;try{return await b2.transaction().execute(async(J)=>{for(let G of N){let X={...G,uuid:p2()};await J.insertInto("products").values(X).execute(),$++}}),$}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product items in bulk: ${J.message}`);throw J}}import{db as K1}from"@stacksjs/database";import{formatDate as Q1}from"@stacksjs/orm";async function c2(N,$){try{if(!N)throw Error("Product item ID is required for update");let J=await K1.updateTable("products").set({...$,updated_at:Q1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product item: ${J.message}`);throw J}}async function n2(N,$){if(!await l(N))throw Error(`Product item with ID ${N} not found`);try{return await K1.updateTable("products").set({is_available:$,updated_at:Q1(new Date)}).where("id","=",N).execute(),await l(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item availability: ${G.message}`);throw G}}async function u2(N,$){let J=await l(N);if(!J)throw Error(`Product item with ID ${N} not found`);let G={updated_at:Q1(new Date)};if($!==void 0)G.inventory_count=$;if(Object.keys(G).length===1)return J;try{return await K1.updateTable("products").set(G).where("id","=",N).execute(),await l(N)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update inventory information: ${X.message}`);throw X}}var G$={};B(G$,{updateFeaturedStatus:()=>Z7,updateByUuid:()=>M7,update:()=>Y7,store:()=>X7,fetchWithProductCount:()=>$7,fetchFeatured:()=>t2,fetchByUuid:()=>e2,fetchById:()=>a2,fetchByCountry:()=>r2,fetchAll:()=>d2,destroy:()=>o2,bulkStore:()=>L7,bulkDestroy:()=>s2});import{db as i2}from"@stacksjs/database";async function o2(N){try{let $=await i2.deleteFrom("manufacturers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function s2(N){if(!N.length)return 0;try{let $=await i2.deleteFrom("manufacturers").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as c}from"@stacksjs/database";function d2(){return c.selectFrom("manufacturers").selectAll().execute()}async function a2(N){return await c.selectFrom("manufacturers").where("id","=",N).selectAll().executeTakeFirst()}async function e2(N){return await c.selectFrom("manufacturers").where("uuid","=",N).selectAll().executeTakeFirst()}async function t2(N=10){return await c.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(N).execute()}async function r2(N,$={}){let J=$.page||1,G=$.limit||2,X=await c.selectFrom("manufacturers").select(c.fn.count("id").as("total")).where("country","=",N).executeTakeFirst(),L=Number(X?.total||0),W=await c.selectFrom("manufacturers").selectAll().where("country","=",N).limit(G).offset((J-1)*G).execute(),Y=Math.ceil(L/G);return{data:W,paging:{total_records:L,page:J,total_pages:Y},next_cursor:J<Y?J+1:null}}async function $7(N={}){let $=c.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(N.country)$=$.where("m.country","=",N.country);if(N.featured!==void 0)$=$.where("m.featured","=",N.featured);return $=$.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",c.fn.count("p.id").as("product_count")]).groupBy("m.id"),$.execute()}var{randomUUIDv7:J7}=globalThis.Bun;import{db as G7}from"@stacksjs/database";import{HttpError as N7}from"@stacksjs/error-handling";import{isUniqueViolation as JX}from"@stacksjs/orm";async function X7(N){try{let $={...N,uuid:J7(),featured:N.featured??!1},J=await G7.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create manufacturer");return J}catch($){if($ instanceof N7)throw $;if(JX($))throw new N7(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function L7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:J7(),featured:J.featured??!1};await G7.insertInto("manufacturers").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${J.message}`);throw J}}import{db as x1}from"@stacksjs/database";import{HttpError as W7}from"@stacksjs/error-handling";import{formatDate as H1,isUniqueViolation as GX}from"@stacksjs/orm";async function Y7(N,$){try{if(!N)throw Error("Manufacturer ID is required for update");let J=await x1.updateTable("manufacturers").set({...$,updated_at:H1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof W7)throw J;if(GX(J))throw new W7(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to update manufacturer: ${J.message}`);throw J}}async function Z7(N,$){try{let J=await x1.updateTable("manufacturers").set({featured:$,updated_at:H1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update manufacturer featured status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${J.message}`);throw J}}async function M7(N,$){try{let J=await x1.updateTable("manufacturers").set({...$,updated_at:H1(new Date)}).where("uuid","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update manufacturer");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update manufacturer: ${J.message}`);throw J}}var X$={};B(X$,{updateVotes:()=>T7,update:()=>S7,store:()=>R7,fetchMostHelpfulByProductId:()=>A7,fetchByUserId:()=>z7,fetchByProductId:()=>V7,fetchById:()=>x7,fetchApprovedByProductId:()=>B7,fetchAll:()=>H7,destroy:()=>K7,bulkDestroy:()=>Q7});import{db as F7}from"@stacksjs/database";async function K7(N){try{let $=await F7.deleteFrom("reviews").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function Q7(N){if(!N.length)return 0;try{let $=await F7.deleteFrom("reviews").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as Z0}from"@stacksjs/database";async function x7(N){return await Z0.selectFrom("reviews").where("id","=",N).selectAll().executeTakeFirst()}async function H7(){return await Z0.selectFrom("reviews").selectAll().execute()}async function V7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).selectAll().execute()}async function z7(N){return await Z0.selectFrom("reviews").where("customer_id","=",N).selectAll().execute()}async function B7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).where("is_approved","=",!0).selectAll().execute()}async function A7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:XX}=globalThis.Bun;import{db as LX}from"@stacksjs/database";async function R7(N){try{let $={...N,uuid:XX(),is_verified_purchase:N.is_verified_purchase??!1,is_approved:N.is_approved??!1,helpful_votes:N.helpful_votes??0,unhelpful_votes:N.unhelpful_votes??0,is_featured:N.is_featured??!1},J=await LX.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create review");return J}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 _7}from"@stacksjs/database";import{formatDate as O7}from"@stacksjs/orm";async function S7(N,$){try{if(!N)throw Error("Review ID is required for update");let J=await _7.updateTable("reviews").set({...$,updated_at:O7(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update review: ${J.message}`);throw J}}async function T7(N,$,J=!0){try{let G=$==="helpful"?"helpful_votes":"unhelpful_votes",X=J?`COALESCE("${G}", 0) + 1`:`MAX(COALESCE("${G}", 0) - 1, 0)`,L=await _7.unsafe(`UPDATE "reviews" SET "${G}" = ${X}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[O7(new Date),N]).execute(),W=Array.isArray(L)?L[0]:L;if(!W)throw Error("Failed to update review votes");return W}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review votes: ${G.message}`);throw G}}var Y$={};B(Y$,{updateDefaultStatus:()=>y7,update:()=>g7,store:()=>j7,getDefaultUnit:()=>h7,formatUnitOptions:()=>I7,fetchById:()=>q7,fetchAll:()=>f7,destroy:()=>U7,bulkUpdate:()=>v7,bulkStore:()=>C7,bulkDestroy:()=>E7});import{db as w7}from"@stacksjs/database";async function U7(N){try{let $=await w7.deleteFrom("product_units").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function E7(N){if(!N.length)return 0;try{let $=await w7.deleteFrom("product_units").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as P7}from"@stacksjs/database";async function q7(N){return await P7.selectFrom("product_units").where("id","=",N).selectAll().executeTakeFirst()}async function f7(){return await P7.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:k7}=globalThis.Bun;import{db as _0}from"@stacksjs/database";async function j7(N){try{return await _0.transaction(async($)=>{let J={...N,uuid:k7()},G=await $.insertInto("product_units").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product unit");if(J.is_default&&J.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",G.id).execute();return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function C7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:k7()},X=await _0.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(G.is_default&&G.type&&X)await _0.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product units in bulk: ${J.message}`);throw J}}function I7(N){try{let $=_0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(N)$=$.where("type","=",N);return $=$.orderBy("name"),$.execute().then((J)=>J.map((G)=>({id:String(G.id),name:G.name,abbreviation:G.abbreviation,is_default:G.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function h7(N){try{return await _0.selectFrom("product_units").selectAll().where("type","=",N).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as L$}from"@stacksjs/database";import{formatDate as W$}from"@stacksjs/orm";async function g7(N,$){try{if(!N)throw Error("Product unit ID is required for update");return await L$.transaction(async(J)=>{let G=await J.selectFrom("product_units").select(["type","is_default"]).where("id","=",N).executeTakeFirst();if(!G)return;let X=$.type??G.type;if(($.is_default??Boolean(G.is_default))&&X)await J.updateTable("product_units").set({is_default:!1,updated_at:W$(new Date)}).where("type","=",X).where("id","!=",N).execute();let W=await J.updateTable("product_units").set({...$,updated_at:W$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!W)return;return W})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product unit: ${J.message}`);throw J}}async function v7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G=J;if(!G.id)continue;let X=G.data&&typeof G.data==="object"?G.data:{...G};delete X.id;let L=await L$.updateTable("product_units").set({...X,updated_at:W$(new Date)}).where("id","=",G.id).executeTakeFirst(),W=X;if(W.is_default===!0&&W.type)await L$.updateTable("product_units").set({is_default:!1}).where("type","=",W.type).where("id","!=",G.id).execute();if(Number(L.numUpdatedRows)>0)$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product units in bulk: ${J.message}`);throw J}}async function y7(N,$){try{return await L$.transaction(async(J)=>{let G=await J.selectFrom("product_units").select("type").where("id","=",N).executeTakeFirst();if(!G)return!1;let X=W$(new Date);if($&&G.type)await J.updateTable("product_units").set({is_default:!1,updated_at:X}).where("type","=",G.type).where("id","!=",N).execute();return await J.updateTable("product_units").set({is_default:$,updated_at:X}).where("id","=",N).execute(),!0})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product unit default status: ${J.message}`);throw J}}var Z$={};B(Z$,{update:()=>t7,store:()=>i7,generateVariantCombinations:()=>d7,formatVariantOptions:()=>s7,fetchById:()=>l7,fetchAll:()=>c7,destroy:()=>p7,bulkUpdate:()=>r7,bulkStore:()=>o7,bulkDestroy:()=>b7});import{db as D7}from"@stacksjs/database";async function p7(N){try{let $=await D7.deleteFrom("product_variants").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function b7(N){if(!N.length)return 0;try{let $=await D7.deleteFrom("product_variants").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as m7}from"@stacksjs/database";async function l7(N){return await m7.selectFrom("product_variants").where("id","=",N).selectAll().executeTakeFirst()}async function c7(){return await m7.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:n7}=globalThis.Bun;import{db as u7}from"@stacksjs/database";async function i7(N){try{let $={...N,uuid:n7()},J=await u7.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create product variant");return J}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function o7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:n7()};await u7.insertInto("product_variants").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${J.message}`);throw J}}function s7(N){if(!N||!N.length)return JSON.stringify([]);let $=N.map((J)=>J.trim()).filter(Boolean);return JSON.stringify($)}function d7(N){let $=Object.keys(N);if(!$.length)return[];function J(G,X){if(G===$.length)return[X];let L=$[G],W=N[L]??[],Y=[];for(let Z of W){let M={...X,[L]:Z};Y.push(...J(G+1,M))}return Y}return J(0,{})}import{db as a7}from"@stacksjs/database";import{formatDate as e7}from"@stacksjs/orm";async function t7(N,$){try{let J=await a7.updateTable("product_variants").set({...$,updated_at:e7(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product variant: ${J.message}`);throw J}}async function r7(N){if(!N.length)return 0;let $=0;try{for(let J of N){if(!J.id)continue;let G=await a7.updateTable("product_variants").set({...J,updated_at:e7(new Date)}).where("id","=",J.id).executeTakeFirst();if(Number(G.numUpdatedRows)>0)$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${J.message}`);throw J}}var WX={categories:N$,items:J$,manufacturers:G$,reviews:X$,units:Y$,variants:Z$},YX=WX;var O1={};B(O1,{updateStatus:()=>xJ,updatePrintJob:()=>HJ,update:()=>QJ,store:()=>FJ,fetchSuccessRate:()=>LJ,fetchPrintsPerHour:()=>ZJ,fetchPrintTimeStats:()=>YJ,fetchPrintJobStats:()=>XJ,fetchPageStats:()=>WJ,fetchById:()=>M0,fetchAll:()=>GJ,destroy:()=>NJ,bulkStore:()=>KJ,bulkDestroy:()=>JJ});import{db as $J}from"@stacksjs/database";async function NJ(N){try{let $=await $J.deleteFrom("receipts").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function JJ(N){if(!N.length)return 0;try{let $=await $J.deleteFrom("receipts").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as z1}from"@stacksjs/database";import{formatDate as ZX}from"@stacksjs/orm";function y(N){return ZX(N)}function MX(N){if(N instanceof Date)return Number.isNaN(N.getTime())?null:N;if(typeof N==="number"){let G=new Date(N<=2147483647?N*1000:N);return Number.isNaN(G.getTime())?null:G}let $=String(N||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let G=new Date(Number($)*1000);return Number.isNaN(G.getTime())?null:G}let J=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(J.getTime())?null:J}async function M0(N){return await z1.selectFrom("receipts").where("id","=",N).selectAll().executeTakeFirst()}async function GJ(){return await z1.selectFrom("receipts").selectAll().execute()}async function XJ(N,$){let J=y(N),G=y($),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"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));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 LJ(N,$){let J=y(N),G=y($),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"}}},(W)=>W.where("timestamp",">=",J).where("timestamp","<=",G));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 WJ(N,$){let J=y(N),G=y($),X=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{totalPages:X.totalPages,averagePagesPerReceipt:Math.round(X.averagePagesPerReceipt),totalReceipts:X.totalReceipts}}async function YJ(N,$){let J=y(N),G=y($),X=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{averageDuration:Math.round(X.averageDuration),minDuration:X.minDuration,maxDuration:X.maxDuration,totalJobs:X.totalJobs}}async function ZJ(N,$){let J=typeof N==="number"?N:N.getTime(),G=typeof $==="number"?$:$.getTime(),X=y(N),L=y($),W=await z1.selectFrom("receipts").where("timestamp",">=",X).where("timestamp","<=",L).selectAll().execute(),Y=W.length,Z=Math.ceil((G-J)/3600000),M=Z>0?Math.round(Y/Z):0,K=Array.from({length:24},(Q,x)=>({hour:x,count:0}));return W.forEach((Q)=>{let x=MX(Q.timestamp);if(!x)return;K[x.getHours()].count++}),{totalPrints:Y,totalHours:Z,printsPerHour:M,hourlyBreakdown:K}}var{randomUUIDv7:MJ}=globalThis.Bun;import{db as A1}from"@stacksjs/database";import{formatDate as B1}from"@stacksjs/orm";function O0(N){try{if(typeof N==="number")return B1(N<=2147483647?N*1000:N);if(typeof N==="string"&&/^\d{10}$/.test(N))return B1(Number(N)*1000);return B1(N)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function FJ(N){try{let $=MJ(),J={...N,timestamp:O0(N.timestamp),uuid:$};await A1.insertInto("receipts").values(J).executeTakeFirst();let G=await A1.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create receipt");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function KJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...G,timestamp:O0(G.timestamp),uuid:MJ()})),J=await A1.insertInto("receipts").values($).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows??J.numAffectedRows??J.affectedRows??J.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as R1}from"@stacksjs/database";import{formatDate as _1}from"@stacksjs/orm";async function QJ(N,$){try{if(!N)throw Error("Receipt ID is required for update");let J={...$,...$.timestamp===void 0?{}:{timestamp:O0($.timestamp)},updated_at:_1(new Date)};await R1.updateTable("receipts").set(J).where("id","=",N).execute();let G=await M0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update receipt: ${J.message}`);throw J}}async function xJ(N,$){try{await R1.updateTable("receipts").set({status:$,updated_at:_1(new Date)}).where("id","=",N).execute();let J=await M0(N);if(!J)throw Error("Failed to update receipt status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update receipt status: ${J.message}`);throw J}}async function HJ(N,$,J,G){try{let X={updated_at:_1(new Date)};if($!==void 0)X.size=$;if(J!==void 0)X.pages=J;if(G!==void 0)X.duration=G;await R1.updateTable("receipts").set(X).where("id","=",N).execute();let L=await M0(N);if(!L)throw Error("Failed to update receipt job information");return L}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt job information: ${X.message}`);throw X}}var p1={};B(p1,{zones:()=>h$,routes:()=>H$,rates:()=>k$,methods:()=>U$,licenses:()=>O$,drivers:()=>A$,digital:()=>z$,default:()=>VX});var H$={};B(H$,{validateDeliveryRouteWrite:()=>F0,updateStops:()=>wJ,updateMetrics:()=>UJ,updateLastActive:()=>SJ,update:()=>TJ,store:()=>OJ,fetchById:()=>F$,fetchByDriver:()=>_J,fetchAll:()=>AJ,fetchActive:()=>RJ,destroy:()=>zJ,bulkDestroy:()=>BJ,DeliveryRouteInputError:()=>C});import{db as VJ}from"@stacksjs/database";async function zJ(N){try{let $=await VJ.deleteFrom("delivery_routes").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function BJ(N){if(!N.length)return 0;try{let $=await VJ.deleteFrom("delivery_routes").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as M$}from"@stacksjs/database";async function F$(N){return await M$.selectFrom("delivery_routes").where("id","=",N).selectAll().executeTakeFirst()}async function AJ(){return await M$.selectFrom("delivery_routes").selectAll().execute()}async function RJ(){return await M$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function _J(N){return await M$.selectFrom("delivery_routes").where("driver","=",N).selectAll().execute()}var{randomUUIDv7:QX}=globalThis.Bun;import{db as S1}from"@stacksjs/database";function r(N,$){let J={};for(let[G,X]of Object.entries($))for(let L of X){if(!Object.prototype.hasOwnProperty.call(N,L)||N[L]===void 0)continue;J[G]=N[L];break}return J}function S0(N){return r(N,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function n(N){return r(N,{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 T0(N){return r(N,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function w0(N){return r(N,{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 U0(N){return r(N,{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 E0(N){return r(N,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function K$(N){return r(N,{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 FX}from"@stacksjs/database";class C extends TypeError{constructor(N){super(N);this.name="DeliveryRouteInputError"}}function Q$(N,$,J){return Number(N[J]??$?.[J])}function KX(N,$){let J=N.last_active??$?.last_active;if(J instanceof Date)return J.getTime();if(typeof J==="number")return J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return Number(J);return Number.NaN}async function F0(N,$){let J=Q$(N,$,"driver_id"),G=Q$(N,$,"stops"),X=Q$(N,$,"delivery_time"),L=Q$(N,$,"total_distance"),W=KX(N,$);if(!Number.isSafeInteger(J)||J<1)throw new C("Driver must be a positive integer.");if(!Number.isSafeInteger(G)||G<0)throw new C("Stops must be a non-negative integer.");if(!Number.isSafeInteger(X)||X<0)throw new C("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(L)||L<0)throw new C("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(W)||W<0)throw new C("Last active must be a valid Unix timestamp.");let Y=await FX.selectFrom("drivers").where("id","=",J).select(["id","name","vehicle_number"]).executeTakeFirst();if(!Y)throw new C(`Driver ${J} was not found.`);return{...N,driver_id:Number(Y.id),driver:Y.name,vehicle:Y.vehicle_number}}async function OJ(N){try{let $=QX(),J=K$(N),X={...await F0(J),uuid:$};await S1.insertInto("delivery_routes").values(X).executeTakeFirst();let L=await S1.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!L)throw Error("Failed to create delivery route");return L}catch($){if($ instanceof C)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function SJ(N){try{await S1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",N).execute();let $=await F$(N);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 x$}from"@stacksjs/database";import{formatDate as T1}from"@stacksjs/orm";async function TJ(N,$){try{if(!N)throw Error("Delivery route ID is required for update");let J=await x$.selectFrom("delivery_routes").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=K$($),X=await F0(G,J),L=await x$.updateTable("delivery_routes").set({...X,updated_at:T1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!L)return;return L}catch(J){if(J instanceof C)throw J;if(J instanceof Error)throw TypeError(`Failed to update delivery route: ${J.message}`);throw J}}async function wJ(N,$){try{let J=await x$.updateTable("delivery_routes").set({stops:$,updated_at:T1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update delivery route stops");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route stops: ${J.message}`);throw J}}async function UJ(N,$,J){try{let G={updated_at:T1(new Date)};if($!==void 0)G.delivery_time=$;if(J!==void 0)G.total_distance=J;let X=await x$.updateTable("delivery_routes").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery metrics");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery metrics: ${G.message}`);throw G}}var z$={};B(z$,{updateStatus:()=>yJ,updateDeliverySettings:()=>DJ,update:()=>vJ,store:()=>hJ,softDelete:()=>PJ,fetchById:()=>jJ,fetchAll:()=>CJ,destroy:()=>EJ,bulkStore:()=>gJ,bulkSoftDelete:()=>fJ,bulkDestroy:()=>qJ});import{db as V$}from"@stacksjs/database";async function EJ(N){try{let $=await V$.deleteFrom("digital_deliveries").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function PJ(N){try{let $=await V$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function qJ(N){if(!N.length)return 0;try{let $=await V$.deleteFrom("digital_deliveries").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function fJ(N){if(!N.length)return 0;try{let $=await V$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as kJ}from"@stacksjs/database";async function jJ(N){return await kJ.selectFrom("digital_deliveries").where("id","=",N).selectAll().executeTakeFirst()}async function CJ(){return await kJ.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:IJ}=globalThis.Bun;import{db as w1}from"@stacksjs/database";async function hJ(N){try{let $=IJ(),J={...w0(N),uuid:$};await w1.insertInto("digital_deliveries").values(J).executeTakeFirst();let G=await w1.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created digital delivery");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function gJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...w0(G),uuid:IJ()})),J=await w1.insertInto("digital_deliveries").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as U1}from"@stacksjs/database";import{formatDate as E1}from"@stacksjs/orm";async function vJ(N,$){try{if(!N)throw Error("Digital delivery ID is required for update");let J=await U1.updateTable("digital_deliveries").set({...w0($),updated_at:E1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update digital delivery: ${J.message}`);throw J}}async function yJ(N,$){try{let J=await U1.updateTable("digital_deliveries").set({status:$,updated_at:E1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update digital delivery status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update digital delivery status: ${J.message}`);throw J}}async function DJ(N,$,J,G,X){try{let L={updated_at:E1(new Date)};if($!==void 0)L.download_limit=$;if(J!==void 0)L.expiry_days=J;if(G!==void 0)L.requires_login=G;if(X!==void 0)L.automatic_delivery=X;let W=await U1.updateTable("digital_deliveries").set(L).where("id","=",N).returningAll().executeTakeFirst();if(!W)throw Error("Failed to update delivery settings");return W}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery settings: ${L.message}`);throw L}}var A$={};B(A$,{updateStatus:()=>sJ,updateContact:()=>dJ,update:()=>oJ,store:()=>uJ,fetchById:()=>B$,fetchAll:()=>bJ,destroy:()=>lJ,bulkStore:()=>iJ,bulkDestroy:()=>cJ});import{db as mJ}from"@stacksjs/database";import{db as pJ}from"@stacksjs/database";async function B$(N){return await pJ.selectFrom("drivers").where("id","=",N).selectAll().executeTakeFirst()}async function bJ(){return await pJ.selectFrom("drivers").selectAll().execute()}async function lJ(N){try{let $=await mJ.deleteFrom("drivers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function cJ(N){if(!N.length)return 0;let $=0;try{return await mJ.transaction().execute(async(J)=>{for(let G of N)if(await B$(G))await J.deleteFrom("drivers").where("id","=",G).execute(),$++}),$}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${J.message}`);throw J}}var{randomUUIDv7:nJ}=globalThis.Bun;import{db as P1}from"@stacksjs/database";async function uJ(N){try{let $=nJ(),J={...E0(N),uuid:$};await P1.insertInto("drivers").values(J).executeTakeFirst();let G=await P1.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created driver");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function iJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...E0(G),uuid:nJ()})),J=await P1.insertInto("drivers").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as q1}from"@stacksjs/database";import{formatDate as f1}from"@stacksjs/orm";async function oJ(N,$){try{if(!N)throw Error("Driver ID is required for update");let J=await q1.updateTable("drivers").set({...E0($),updated_at:f1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update driver: ${J.message}`);throw J}}async function sJ(N,$){try{let J=await q1.updateTable("drivers").set({status:$,updated_at:f1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update driver status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update driver status: ${J.message}`);throw J}}async function dJ(N,$){try{let J={updated_at:f1(new Date)};if($!==void 0)J.phone=$;let G=await q1.updateTable("drivers").set(J).where("id","=",N).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update contact information");return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update contact information: ${J.message}`);throw J}}var O$={};B(O$,{validateLicenseKeyWrite:()=>$0,updateStatus:()=>M6,updateExpiration:()=>F6,update:()=>Z6,store:()=>W6,softDelete:()=>eJ,fetchById:()=>N6,fetchAll:()=>J6,destroy:()=>aJ,bulkStore:()=>Y6,bulkSoftDelete:()=>rJ,bulkDestroy:()=>tJ,LicenseKeyInputError:()=>E});import{db as R$}from"@stacksjs/database";async function aJ(N){try{let $=await R$.deleteFrom("license_keys").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function eJ(N){try{let $=await R$.updateTable("license_keys").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function tJ(N){if(!N.length)return 0;try{let $=await R$.deleteFrom("license_keys").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function rJ(N){if(!N.length)return 0;try{let $=await R$.updateTable("license_keys").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as $6}from"@stacksjs/database";async function N6(N){return await $6.selectFrom("license_keys").where("id","=",N).selectAll().executeTakeFirst()}async function J6(){return await $6.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:L6}=globalThis.Bun;import{db as C1}from"@stacksjs/database";import{db as k1}from"@stacksjs/database";var G6=["Standard License","Premium License","Enterprise License"],X6=["active","inactive","unassigned"];class E extends TypeError{constructor(N){super(N);this.name="LicenseKeyInputError"}}function P0(N,$,J){return N[J]!==void 0?N[J]:$?.[J]}function j1(N,$,J,G){let X=P0(N,$,J);if(X===void 0||X===null||X==="")return null;let L=Number(X);if(!Number.isSafeInteger(L)||L<1)throw new E(`${G} must be a positive integer or null.`);return L}function xX(N){if(typeof N==="number")return N>2147483647?Math.floor(N/1000):N;if(typeof N==="string"&&/^\d{10,13}$/.test(N))return N.length===13?Math.floor(Number(N)/1000):Number(N);if(typeof N==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(N)?`${N.replace(" ","T")}Z`:N;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function $0(N,$){let J=String(P0(N,$,"key")||"").trim().toUpperCase(),G=String(P0(N,$,"template")||""),X=String(P0(N,$,"status")||""),L=xX(P0(N,$,"expiry_date")),W=j1(N,$,"customer_id","Customer"),Y=j1(N,$,"product_id","Product"),Z=j1(N,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(J))throw new E("License key must use five groups of four uppercase letters or numbers.");if(!G6.includes(G))throw new E(`Template must be one of: ${G6.join(", ")}.`);if(!X6.includes(X))throw new E(`Status must be one of: ${X6.join(", ")}.`);if(!Number.isSafeInteger(L)||L<0||L>2147483647)throw new E("Expiry date must be a Unix timestamp between 1970 and 2038.");let[M,K,Q]=await Promise.all([W?k1.selectFrom("customers").where("id","=",W).select("id").executeTakeFirst():null,Y?k1.selectFrom("products").where("id","=",Y).select("id").executeTakeFirst():null,Z?k1.selectFrom("orders").where("id","=",Z).select(["id","customer_id"]).executeTakeFirst():null]);if(W&&!M)throw new E(`Customer ${W} was not found.`);if(Y&&!K)throw new E(`Product ${Y} was not found.`);if(Z&&!Q)throw new E(`Order ${Z} was not found.`);if(W&&Q?.customer_id&&Number(Q.customer_id)!==W)throw new E(`Order ${Z} belongs to Customer ${Q.customer_id}, not Customer ${W}.`);return{...N,key:J,template:G,expiry_date:L,status:X,customer_id:W,product_id:Y,order_id:Z}}async function W6(N){try{let $=L6(),J=U0(N),G={...await $0(J),uuid:$};await C1.insertInto("license_keys").values(G).executeTakeFirst();let X=await C1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created license key");return X}catch($){if($ instanceof E)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function Y6(N){if(!N.length)return 0;try{let $=await Promise.all(N.map(async(G)=>({...await $0(U0(G)),uuid:L6()}))),J=await C1.insertInto("license_keys").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof E)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as _$}from"@stacksjs/database";import{formatDate as I1}from"@stacksjs/orm";async function Z6(N,$){try{if(!N)throw Error("License key ID is required for update");let J=await _$.selectFrom("license_keys").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=U0($),X=await $0(G,J),L=await _$.updateTable("license_keys").set({...X,updated_at:I1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!L)return;return L}catch(J){if(J instanceof E)throw J;if(J instanceof Error){if(J.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${J.message}`)}throw J}}async function M6(N,$){try{let J=await _$.updateTable("license_keys").set({status:$,updated_at:I1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update license key status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update license key status: ${J.message}`);throw J}}async function F6(N,$){try{let J={updated_at:I1(new Date)};if($!==void 0)J.expiry_date=$;let G=await _$.updateTable("license_keys").set(J).where("id","=",N).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update expiration information");return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update expiration information: ${J.message}`);throw J}}var U$={};B(U$,{updateStatus:()=>S6,updatePricing:()=>T6,update:()=>O6,store:()=>B6,softDelete:()=>Q6,getActiveShippingMethods:()=>_6,formatShippingOptions:()=>R6,fetchById:()=>w$,fetchAll:()=>V6,destroy:()=>K6,bulkStore:()=>A6,bulkSoftDelete:()=>H6,bulkDestroy:()=>x6});import{db as S$}from"@stacksjs/database";async function K6(N){try{let $=await S$.deleteFrom("shipping_methods").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function Q6(N){try{let $=await S$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function x6(N){if(!N.length)return 0;try{let $=await S$.deleteFrom("shipping_methods").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function H6(N){if(!N.length)return 0;try{let $=await S$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as T$}from"@stacksjs/database";async function w$(N){let $=await T$.selectFrom("shipping_methods").where("id","=",N).selectAll().executeTakeFirst();if($){let J=await T$.selectFrom("shipping_zones").where("shipping_method_id","=",N).selectAll().execute();return{...$,shippingZones:J}}return}async function V6(){let N=await T$.selectFrom("shipping_methods").selectAll().execute();if(N.length===0)return[];let $=[...new Set(N.map((L)=>L.id))],X=(await T$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((L,W)=>{let Y=W.shipping_method_id;if(Y!==null&&Y!==void 0){if(!L[Y])L[Y]=[];L[Y].push(W)}return L},{});return N.map((L)=>({...L,shipping_zones:X[L.id]||[]}))}var{randomUUIDv7:z6}=globalThis.Bun;import{db as q0}from"@stacksjs/database";async function B6(N){try{let $=z6(),J={...S0(N),uuid:$};await q0.insertInto("shipping_methods").values(J).executeTakeFirst();let G=await q0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created shipping method");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function A6(N){if(!N.length)return 0;try{let $=N.map((G)=>({...S0(G),uuid:z6()})),J=await q0.insertInto("shipping_methods").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function R6(){try{return q0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping options: ${N.message}`);throw N}}async function _6(){try{return await q0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to get active shipping methods: ${N.message}`);throw N}}import{db as h1}from"@stacksjs/database";import{formatDate as g1}from"@stacksjs/orm";async function O6(N,$){try{if(!N)throw Error("Shipping method ID is required for update");let J=await h1.updateTable("shipping_methods").set({...S0($),updated_at:g1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping method: ${J.message}`);throw J}}async function S6(N,$){try{let J=await h1.updateTable("shipping_methods").set({status:$,updated_at:g1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping method status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping method status: ${J.message}`);throw J}}async function T6(N,$,J){try{let G={updated_at:g1(new Date)};if($!==void 0)G.base_rate=$;if(J!==void 0)G.free_shipping=J;let X=await h1.updateTable("shipping_methods").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update pricing information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update pricing information: ${G.message}`);throw G}}var k$={};B(k$,{validateZoneMatchesAddress:()=>I6,validateShippingRateWrite:()=>N0,updateByZone:()=>u6,updateByMethod:()=>i6,update:()=>c6,store:()=>m6,resolveZoneForAddress:()=>P$,getShippingRatesByMethod:()=>g6,getRatesByZone:()=>j6,getRateByWeightAndZone:()=>v1,getRateByWeightAndAddress:()=>C6,formatShippingRateOptions:()=>h6,fetchById:()=>f6,fetchAll:()=>k6,destroyByZone:()=>E6,destroyByMethod:()=>P6,destroy:()=>w6,bulkUpdate:()=>n6,bulkStore:()=>l6,bulkDestroy:()=>U6,ShippingRateInputError:()=>k});import{db as E$}from"@stacksjs/database";async function w6(N){try{let $=await E$.deleteFrom("shipping_rates").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function U6(N){if(!N.length)return 0;try{let $=await E$.deleteFrom("shipping_rates").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function E6(N){try{let $=await E$.deleteFrom("shipping_rates").where("shipping_zone_id","=",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function P6(N){try{let $=await E$.deleteFrom("shipping_rates").where("shipping_method_id","=",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as v}from"@stacksjs/database";async function f6(N){let $=await v.selectFrom("shipping_rates").where("id","=",N).selectAll().executeTakeFirst();if($){let J=null,G=null;if($.shipping_zone_id)J=await v.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)G=await v.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:J,shipping_method:G}}return}async function k6(){let N=await v.selectFrom("shipping_rates").selectAll().execute();if(N.length===0)return[];let $=[...new Set(N.map((Y)=>Y.shipping_zone_id).filter((Y)=>Y!==null&&Y!==void 0))],J=[...new Set(N.map((Y)=>Y.shipping_method_id).filter((Y)=>Y!==null&&Y!==void 0))],[G,X]=await Promise.all([$.length?v.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],J.length?v.selectFrom("shipping_methods").where("id","in",J).selectAll().execute():[]]),L=G.reduce((Y,Z)=>{return Y[Z.id]=Z,Y},{}),W=X.reduce((Y,Z)=>{return Y[Z.id]=Z,Y},{});return N.map((Y)=>({...Y,shipping_zone:Y.shipping_zone_id?L[Y.shipping_zone_id]:[],shipping_method:Y.shipping_method_id?W[Y.shipping_method_id]:[]}))}async function j6(N){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",N).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function v1(N,$){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",N).where("weight_to",">=",N).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${J.message}`);throw J}}async function P$(N){if(!N?.countryCode)return null;try{let $=await v.selectFrom("shipping_zones").selectAll().where("countries","like",`%${N.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let J=null;for(let G of $){let X=1;if(N.region&&G.regions&&q6(G.regions,N.region))X=2;if(N.postalCode&&G.postal_codes&&q6(G.postal_codes,N.postalCode))X=3;if(!J||X>J.score)J={id:G.id,score:X}}return J?.id??null}catch{return null}}async function C6(N,$){let J=await P$($);if(J==null)return;return v1(N,J)}async function I6(N,$){return await P$($)===N}function q6(N,$){if(!N||!$)return!1;let J=$.trim().toUpperCase();for(let G of N.split(/[,|;]/))if(G.trim().toUpperCase()===J)return!0;return!1}async function h6(){try{return(await v.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping rate options: ${N.message}`);throw N}}async function g6(N){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",N).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:b6}=globalThis.Bun;import{db as y1}from"@stacksjs/database";import{db as f0}from"@stacksjs/database";async function v6(){return await f0.selectFrom("shipping_zones").selectAll().execute()}async function q$(N){return await f0.selectFrom("shipping_zones").where("id","=",N).selectAll().executeTakeFirst()}function y6(){try{return f0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping zone options: ${N.message}`);throw N}}async function D6(){try{return await f0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to get active shipping zones: ${N.message}`);throw N}}async function p6(N){try{return await f0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${N}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class k extends TypeError{constructor(N){super(N);this.name="ShippingRateInputError"}}function k0(N,$,J){return Number(N[J]??$?.[J])}async function N0(N,$){let J=k0(N,$,"shipping_method_id"),G=k0(N,$,"shipping_zone_id"),X=k0(N,$,"weight_from"),L=k0(N,$,"weight_to"),W=k0(N,$,"rate");if(!Number.isSafeInteger(J)||J<1)throw new k("Shipping method must be a positive integer.");if(!Number.isSafeInteger(G)||G<1)throw new k("Shipping zone must be a positive integer.");if(!Number.isFinite(X)||X<0)throw new k("Weight from must be a non-negative number.");if(!Number.isFinite(L)||L<X)throw new k("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(W)||W<0)throw new k("Rate must be a non-negative integer in minor currency units.");let[Y,Z]=await Promise.all([w$(J),q$(G)]);if(!Y)throw new k(`Shipping method ${J} was not found.`);if(!Z)throw new k(`Shipping zone ${G} was not found.`);if(Number(Z.shipping_method_id)!==J)throw new k(`Shipping zone ${G} is not assigned to shipping method ${J}.`)}async function m6(N){try{let $=n(N),J=Number($.shipping_method_id),G=Number($.shipping_zone_id);await N0($);let X=b6(),L={...$,shipping_method_id:J,shipping_zone_id:G,uuid:X};await y1.insertInto("shipping_rates").values(L).executeTakeFirst();let W=await y1.selectFrom("shipping_rates").where("uuid","=",X).selectAll().executeTakeFirst();if(!W)throw Error("Failed to resolve created shipping rate");return W}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function l6(N){if(!N.length)return 0;try{for(let G of N){let X=n(G);await N0(X)}let $=N.map((G)=>({...n(G),uuid:b6()})),J=await y1.insertInto("shipping_rates").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as j0}from"@stacksjs/database";import{formatDate as f$}from"@stacksjs/orm";async function c6(N,$){try{if(!N)throw Error("Shipping rate ID is required for update");let J=await j0.selectFrom("shipping_rates").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=n($);await N0(G,J);let X=await j0.updateTable("shipping_rates").set({...G,updated_at:f$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!X)return;return X}catch(J){if(J instanceof k)throw J;if(J instanceof Error)throw TypeError(`Failed to update shipping rate: ${J.message}`);throw J}}async function n6(N){if(!N.length)return 0;try{let $=0;for(let{id:J,data:G}of N){let X=await j0.updateTable("shipping_rates").set({...n(G),updated_at:f$(new Date)}).where("id","=",J).executeTakeFirst();if(F(X)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function u6(N,$){try{let J=await j0.updateTable("shipping_rates").set({...n($),updated_at:f$(new Date)}).where("shipping_zone_id","=",N).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${J.message}`);throw J}}async function i6(N,$){try{let J=await j0.updateTable("shipping_rates").set({...n($),updated_at:f$(new Date)}).where("shipping_method_id","=",N).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${J.message}`);throw J}}var h$={};B(h$,{updateStatus:()=>NG,updateRegionsAndPostalCodes:()=>GG,updateCountries:()=>JG,update:()=>$G,store:()=>t6,softDelete:()=>s6,getZonesByCountry:()=>p6,getActiveShippingZones:()=>D6,formatZoneOptions:()=>y6,fetchById:()=>q$,fetchAll:()=>v6,destroy:()=>o6,bulkStore:()=>r6,bulkSoftDelete:()=>a6,bulkDestroy:()=>d6});import{db as j$}from"@stacksjs/database";async function o6(N){try{let $=await j$.deleteFrom("shipping_zones").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function s6(N){try{let $=await j$.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function d6(N){if(!N.length)return 0;try{let $=await j$.deleteFrom("shipping_zones").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function a6(N){if(!N.length)return 0;try{let $=await j$.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:e6}=globalThis.Bun;import{db as D1}from"@stacksjs/database";async function t6(N){try{let $=e6(),J={...T0(N),uuid:$};await D1.insertInto("shipping_zones").values(J).executeTakeFirst();let G=await D1.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created shipping zone");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function r6(N){if(!N.length)return 0;try{let $=N.map((G)=>({...T0(G),uuid:e6()})),J=await D1.insertInto("shipping_zones").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as C$}from"@stacksjs/database";import{formatDate as I$}from"@stacksjs/orm";async function $G(N,$){try{if(!N)throw Error("Shipping zone ID is required for update");let J=await C$.updateTable("shipping_zones").set({...T0($),updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone: ${J.message}`);throw J}}async function NG(N,$){try{let J=await C$.updateTable("shipping_zones").set({status:$,updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping zone status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone status: ${J.message}`);throw J}}async function JG(N,$){try{let J=await C$.updateTable("shipping_zones").set({countries:$,updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping zone countries");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${J.message}`);throw J}}async function GG(N,$,J){try{let G={updated_at:I$(new Date)};if($!==void 0)G.regions=$;if(J!==void 0)G.postal_codes=J;let X=await C$.updateTable("shipping_zones").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update regions and postal codes");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${G.message}`);throw G}}var HX={digital:z$,drivers:A$,licenses:O$,methods:U$,rates:k$,routes:H$,zones:h$},VX=HX;var b1={};B(b1,{updateStatus:()=>VG,updateRate:()=>zG,updateDefaultStatus:()=>BG,update:()=>HG,store:()=>QG,fetchById:()=>ZG,fetchAll:()=>MG,destroy:()=>LG,bulkStore:()=>xG,bulkDestroy:()=>WG});import{db as XG}from"@stacksjs/database";async function LG(N){try{let $=await XG.deleteFrom("tax_rates").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function WG(N){if(!N.length)return 0;try{let $=await XG.deleteFrom("tax_rates").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as YG}from"@stacksjs/database";async function ZG(N){return await YG.selectFrom("tax_rates").where("id","=",N).selectAll().executeTakeFirst()}async function MG(){return await YG.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:FG}=globalThis.Bun;import{db as KG}from"@stacksjs/database";async function QG(N){try{return await KG.transaction(async($)=>{let J={...N,uuid:FG()};if(J.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let G=await $.insertInto("tax_rates").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create tax rate");return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function xG(N){if(!N.length)return 0;try{return await KG.transaction(async($)=>{let J=0;for(let G of N){let X={...G,uuid:FG()};if(X.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(X).executeTakeFirst())J++}return J})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as g$}from"@stacksjs/database";import{formatDate as v$}from"@stacksjs/orm";async function HG(N,$){try{if(!N)throw Error("Tax rate ID is required for update");return await g$.transaction(async(J)=>{let G=await J.selectFrom("tax_rates").select("is_default").where("id","=",N).executeTakeFirst();if(!G)return;let X=$.is_default??Boolean(G.is_default),L=v$(new Date);if(X)await J.updateTable("tax_rates").set({is_default:!1,updated_at:L}).where("id","!=",N).execute();let W=await J.updateTable("tax_rates").set({...$,updated_at:L}).where("id","=",N).returningAll().executeTakeFirst();if(!W)return;return W})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate: ${J.message}`);throw J}}async function VG(N,$){try{let J=await g$.updateTable("tax_rates").set({status:$,updated_at:v$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update tax rate status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate status: ${J.message}`);throw J}}async function zG(N,$){try{let J=await g$.updateTable("tax_rates").set({rate:$,updated_at:v$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update rate information");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update rate information: ${J.message}`);throw J}}async function BG(N,$){try{return await g$.transaction(async(J)=>{if(!await J.selectFrom("tax_rates").select("id").where("id","=",N).executeTakeFirst())return!1;let X=v$(new Date);if($)await J.updateTable("tax_rates").set({is_default:!1,updated_at:X}).where("id","!=",N).execute();return await J.updateTable("tax_rates").set({is_default:$,updated_at:X}).where("id","=",N).execute(),!0})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate default status: ${J.message}`);throw J}}var i1={};B(i1,{restaurant:()=>Q0,products:()=>D$,default:()=>UX});var D$={};B(D$,{updateStatus:()=>yG,updatePartySize:()=>DG,update:()=>y$,store:()=>gG,fetchWaiting:()=>qG,fetchPurchasedBetweenDates:()=>EG,fetchNotifiedBetweenDates:()=>UG,fetchCountByStatus:()=>fG,fetchCountBySource:()=>OG,fetchCountByQuantity:()=>TG,fetchCountByDateGrouped:()=>CG,fetchCountByDate:()=>SG,fetchCountByAllQuantities:()=>wG,fetchCountBetweenDates:()=>jG,fetchConversionRates:()=>kG,fetchCancelledBetweenDates:()=>PG,fetchById:()=>C0,fetchAll:()=>_G,destroy:()=>AG,bulkStore:()=>vG,bulkDestroy:()=>RG});import{db as m1}from"@stacksjs/database";async function AG(N){try{let $=await m1.selectFrom("waitlist_products").where("id","=",N).selectAll().executeTakeFirst();if(!$)return;return await m1.deleteFrom("waitlist_products").where("id","=",N).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function RG(N){if(!N.length)return 0;try{let $=await m1.deleteFrom("waitlist_products").where("id","in",N).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 U}from"@stacksjs/orm";async function C0(N){return await A.selectFrom("waitlist_products").where("id","=",N).selectAll().executeTakeFirst()}async function _G(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function OG(N,$){let J=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(N&&$){let X=U(N),L=U($);J=J.where("created_at",">=",X).where("created_at","<=",L)}return(await J.execute()).reduce((X,{source:L,count:W})=>{return X[L]=W,X},{})}async function SG(N=new Date){let $=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=U($),X=U(J);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function TG(N){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",N).executeTakeFirst())?.count??0}async function wG(N,$){let J=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(N&&$){let X=U(N),L=U($);J=J.where("created_at",">=",X).where("created_at","<=",L)}return(await J.execute()).reduce((X,{quantity:L,count:W})=>{return X[L]=W,X},{})}async function UG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",J).where("notified_at","<=",G).whereNotNull("notified_at").execute()}async function EG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",J).where("purchased_at","<=",G).whereNotNull("purchased_at").execute()}async function PG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",J).where("cancelled_at","<=",G).whereNotNull("cancelled_at").execute()}async function qG(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function fG(N,$,J){let G=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",N);if($&&J){let L=U($),W=U(J);G=G.where("created_at",">=",L).where("created_at","<=",W)}return(await G.executeTakeFirst())?.count??0}async function kG(N,$){let J=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(N&&$){let Z=U(N),M=U($);J=J.where("created_at",">=",Z).where("created_at","<=",M)}let G=await J.execute(),X=G.reduce((Z,{count:M})=>Z+M,0),L=G.find((Z)=>Z.status==="purchased")?.count??0,W=X>0?L/X*100:0,Y=G.reduce((Z,{status:M,count:K})=>{return Z[M]={count:K,percentage:X>0?K/X*100:0},Z},{});return{totalConversionRate:W,statusBreakdown:Y}}async function jG(N,$){let J=U(N),G=U($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",J).where("created_at","<=",G).executeTakeFirst())?.count??0}async function CG(N,$){let J=A.selectFrom("waitlist_products").select(["created_at"]);if(N&&$){let L=U(N),W=U($);J=J.where("created_at",">=",L).where("created_at","<=",W)}let X=(await J.execute()).reduce((L,{created_at:W})=>{let Y=(W||"").split("T")[0]||"unknown";return L[Y]=(L[Y]||0)+1,L},{});return Object.entries(X).map(([L,W])=>({date:L,count:W})).sort((L,W)=>L.date.localeCompare(W.date))}var{randomUUIDv7:hG}=globalThis.Bun;import{db as l1}from"@stacksjs/database";import{formatDate as IG}from"@stacksjs/orm";var zX={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function BX(N){return typeof N==="number"||N instanceof Date?IG(N):N}function I0(N,$={}){let J=Object.fromEntries(Object.entries(N).filter(([,X])=>X!==void 0));if(J.quantity===void 0&&J.party_size!==void 0)J.quantity=J.party_size;delete J.party_size;for(let X of["notified_at","purchased_at","cancelled_at"])if(J[X]!==void 0)J[X]=BX(J[X]);let G=zX[J.status];if(G&&J[G]===void 0&&!$[G])J[G]=IG(new Date);return J}async function gG(N){try{let $=hG(),J={...I0(N),uuid:$,status:N.status||"waiting"};await l1.insertInto("waitlist_products").values(J).executeTakeFirst();let G=await l1.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create waitlist product");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function vG(N){if(!N.length)return 0;try{let $=N.map((G)=>({...I0(G),status:G.status||"waiting",uuid:hG()})),J=await l1.insertInto("waitlist_products").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as AX}from"@stacksjs/database";import{formatDate as RX}from"@stacksjs/orm";async function y$(N,$){try{if(!N)throw Error("Waitlist product ID is required for update");let J=await C0(N);if(!J)return;await AX.updateTable("waitlist_products").set({...I0($,J),updated_at:RX(new Date)}).where("id","=",N).execute();let G=await C0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update waitlist product: ${J.message}`);throw J}}async function yG(N,$){return await y$(N,{status:$})}async function DG(N,$){return await y$(N,{quantity:$})}var Q0={};B(Q0,{updateWaitTimes:()=>F3,updateStatus:()=>Z3,updateQueuePosition:()=>K3,updatePartySize:()=>M3,update:()=>K0,store:()=>W3,fetchWaitingWithQuotedTimes:()=>eG,fetchWaitingWithPartySizes:()=>tG,fetchWaiting:()=>sG,fetchTimeSeriesStats:()=>X3,fetchTablesTurnedToday:()=>rG,fetchSeatingRate:()=>$3,fetchSeatedStats:()=>G3,fetchSeatedBetweenDates:()=>oG,fetchNoShowStats:()=>N3,fetchCurrentWaitTimes:()=>J3,fetchCountByTablePreference:()=>lG,fetchCountByPartySize:()=>nG,fetchCountByDate:()=>cG,fetchCountByAllPartySizes:()=>uG,fetchConversionRates:()=>dG,fetchById:()=>h0,fetchBetweenDates:()=>iG,fetchAverageWaitTimes:()=>aG,fetchAll:()=>mG,destroy:()=>pG,bulkStore:()=>Y3,bulkDestroy:()=>bG});import{db as c1}from"@stacksjs/database";async function pG(N){try{let $=await c1.selectFrom("waitlist_restaurants").where("id","=",N).selectAll().executeTakeFirst();if(!$)return;return await c1.deleteFrom("waitlist_restaurants").where("id","=",N).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function bG(N){if(!N.length)return 0;try{let $=await c1.deleteFrom("waitlist_restaurants").where("id","in",N).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 h}from"@stacksjs/orm";async function h0(N){return await V.selectFrom("waitlist_restaurants").where("id","=",N).selectAll().executeTakeFirst()}async function mG(){return await V.selectFrom("waitlist_restaurants").selectAll().execute()}async function lG(){return(await V.selectFrom("waitlist_restaurants").select(["table_preference",V.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:J,count:G})=>{return $[J]=G,$},{})}async function cG(N=new Date){let $=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=h($),X=h(J);return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function nG(N){return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("party_size","=",N).executeTakeFirst())?.count??0}async function uG(){return(await V.selectFrom("waitlist_restaurants").select(["party_size",V.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:J,count:G})=>{return $[J]=G,$},{})}async function iG(N,$){let J=h(N),G=h($);return await V.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",J).where("created_at","<=",G).execute()}async function oG(N,$){let J=h(N),G=h($);return await V.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",J).where("check_in_time","<=",G).where("status","=","seated").execute()}async function sG(){return await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function dG(){let N=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),$=N.reduce((L,{count:W})=>L+W,0),J=N.find((L)=>L.status==="seated")?.count??0,G=$>0?Number(J)/$*100:0,X=N.reduce((L,{status:W,count:Y})=>{return L[W]={count:Y,percentage:$>0?Y/$*100:0},L},{});return{totalConversionRate:G,statusBreakdown:X}}async function aG(){let N=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:N?.avg_quoted_wait_time??0,averageActualWaitTime:N?.avg_actual_wait_time??0}}async function eG(){let N=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=N.reduce((G,X)=>G+(X.quoted_wait_time??0),0),J=N.length>0?$/N.length:0;return{entries:N,totalQuotedWaitTime:$,averageQuotedWaitTime:J}}async function tG(){let N=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=N.reduce((X,L)=>X+L.party_size,0),J=N.length>0?$/N.length:0,G=N.reduce((X,L)=>{return X[L.party_size]=(X[L.party_size]||0)+1,X},{});return{entries:N,totalPartySize:$,averagePartySize:J,partySizeBreakdown:G}}async function rG(){let N=new Date,$=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=h($),X=h(J),L=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",G).where("check_in_time","<=",X).execute(),W=L.length,Y=L.reduce((Q,x)=>Q+x.party_size,0),Z=W>0?Y/W:0,M=L.reduce((Q,x)=>{return Q[x.table_preference]=(Q[x.table_preference]||0)+1,Q},{}),K=L.reduce((Q,x)=>{return Q[x.party_size]=(Q[x.party_size]||0)+1,Q},{});return{totalTablesTurned:W,averagePartySize:Z,totalCustomersSeated:Y,breakdownByTablePreference:M,breakdownByPartySize:K}}async function $3(N,$){let J=h(N),G=h($),X=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).where("check_in_time",">=",J).where("check_in_time","<=",G).groupBy("status").execute(),L=X.reduce((M,{count:K})=>M+K,0),W=X.find((M)=>M.status==="seated")?.count??0,Y=L>0?Number(W)/L*100:0,Z=X.reduce((M,{status:K,count:Q})=>{return M[K]={count:Q,percentage:L>0?Q/L*100:0},M},{});return{totalEntries:L,seatedEntries:W,seatingRate:Y,statusBreakdown:Z}}async function N3(N,$){let J=h(N),G=h($),X=V.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",J).where("check_in_time","<=",G),L=await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("check_in_time",">=",J).where("check_in_time","<=",G).executeTakeFirst(),W=await X.execute(),Y=W.length,Z=L?.count&&L.count>0?Y/L.count*100:0,M=W.reduce((_,S)=>_+(S.quoted_wait_time??0),0),K=Y>0?M/Y:0,Q=W.reduce((_,S)=>_+S.party_size,0),x=Y>0?Q/Y:0,R=W.reduce((_,S)=>{return _[S.table_preference]=(_[S.table_preference]||0)+1,_},{}),O=W.reduce((_,S)=>{return _[S.party_size]=(_[S.party_size]||0)+1,_},{});return{totalNoShows:Y,noShowRate:Z,averageQuotedWaitTime:K,averagePartySize:x,breakdownByTablePreference:R,breakdownByPartySize:O}}async function J3(){let N=await V.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=N.reduce((X,L)=>X+(L.quoted_wait_time||0),0),J=N.reduce((X,L)=>X+(L.actual_wait_time||0),0),G=N.length;return{averageQuoted:G>0?$/G:0,averageActual:G>0?J/G:0}}async function G3(){let N=Date.now()-86400000,$=await V.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",N).execute(),J=Array.from({length:24},(G,X)=>({hour:X,count:$.filter((L)=>{return L.seated_at===X}).length}));return{total:$.length,byHour:J}}async function X3(){return(await V.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,J)=>{let G=J.created_at;if(!$[G])$[G]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[G].total++,$[G][J.status]++,$},{})}var{randomUUIDv7:L3}=globalThis.Bun;import{db as u1}from"@stacksjs/database";import{formatDate as n1}from"@stacksjs/orm";var _X={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function OX(N){if(typeof N==="number")return n1(N<=2147483647?N*1000:N);if(N instanceof Date)return n1(N);return N}function g0(N,$={}){let J=Object.fromEntries(Object.entries(N).filter(([,X])=>X!==void 0));for(let X of["check_in_time","seated_at","no_show_at","cancelled_at"])if(J[X]!==void 0)J[X]=OX(J[X]);let G=_X[J.status];if(G&&J[G]===void 0&&!$[G])J[G]=n1(new Date);return J}async function W3(N){try{let $=L3(),J={...g0(N),status:N.status||"waiting",uuid:$};await u1.insertInto("waitlist_restaurants").values(J).executeTakeFirst();let G=await u1.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create restaurant waitlist entry");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function Y3(N){if(!N.length)return 0;try{let $=N.map((G)=>({...g0(G),status:G.status||"waiting",uuid:L3()})),J=await u1.insertInto("waitlist_restaurants").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as SX}from"@stacksjs/database";import{formatDate as TX}from"@stacksjs/orm";async function K0(N,$){try{if(!N)throw Error("Restaurant waitlist entry ID is required for update");let J=await h0(N);if(!J)return;await SX.updateTable("waitlist_restaurants").set({...g0($,J),updated_at:TX(new Date)}).where("id","=",N).execute();let G=await h0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${J.message}`);throw J}}async function Z3(N,$){return await K0(N,{status:$})}async function M3(N,$){return await K0(N,{party_size:$})}async function F3(N,$,J){return await K0(N,{quoted_wait_time:$,...J===void 0?{}:{actual_wait_time:J}})}async function K3(N,$){return await K0(N,{queue_position:$})}var wX={products:D$,restaurant:Q0},UX=wX;var EX={coupons:p$,customers:b$,devices:u$,errors:s$,giftCards:a$,orders:Y1,payments:Z1,products:V1,receipts:O1,restaurant:Q0,shippings:p1,tax:b1,waitlists:i1},vK=EX;export{i1 as waitlists,b1 as tax,p1 as shippings,Q0 as restaurant,O1 as receipts,V1 as products,Z1 as payments,Y1 as orders,a$ as giftCards,s$ as errors,u$ as devices,vK as default,b$ as customers,p$ as coupons,EX 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 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};
|
package/dist/orders/events.d.ts
CHANGED
|
@@ -10,6 +10,8 @@ export declare function emitOrderCreated(order: Record<string, unknown>): Promis
|
|
|
10
10
|
export declare function emitOrderPaid(order: Record<string, unknown>, payment?: Record<string, unknown>): Promise<void>;
|
|
11
11
|
/** Emit `order:shipped` after fulfillment marks the order shipped. */
|
|
12
12
|
export declare function emitOrderShipped(order: Record<string, unknown>): Promise<void>;
|
|
13
|
+
/** Emit `order:out_for_delivery` when the order is loaded onto a vehicle. */
|
|
14
|
+
export declare function emitOrderOutForDelivery(order: Record<string, unknown>): Promise<void>;
|
|
13
15
|
/** Emit `order:delivered` after the carrier confirms delivery. */
|
|
14
16
|
export declare function emitOrderDelivered(order: Record<string, unknown>): Promise<void>;
|
|
15
17
|
/** Emit `order:cancelled` on cancellation (pre- or post-payment). */
|
|
@@ -43,4 +45,10 @@ export declare function emitForStatus(status: OrderStatus, order: Record<string,
|
|
|
43
45
|
* Status-transition guard (stacksjs/stacks#1879 Co-4) lives here
|
|
44
46
|
* too so the rules are co-located with the events they trigger.
|
|
45
47
|
*/
|
|
46
|
-
export type OrderStatus =
|
|
48
|
+
export type OrderStatus = | 'PENDING'
|
|
49
|
+
| 'PROCESSING'
|
|
50
|
+
| 'SHIPPED'
|
|
51
|
+
| 'OUT_FOR_DELIVERY'
|
|
52
|
+
| 'DELIVERED'
|
|
53
|
+
| 'CANCELLED'
|
|
54
|
+
| 'REFUNDED';
|
|
@@ -4,6 +4,7 @@ import * as licenses from './license-keys/index';
|
|
|
4
4
|
import * as methods from './shipping-methods/index';
|
|
5
5
|
import * as rates from './shipping-rates/index';
|
|
6
6
|
import * as routes from './delivery-routes/index';
|
|
7
|
+
import * as tracking from './tracking/index';
|
|
7
8
|
import * as zones from './shipping-zones/index';
|
|
8
9
|
declare const shippings: ShippingsNamespace;
|
|
9
10
|
declare interface ShippingsNamespace {
|
|
@@ -13,6 +14,7 @@ declare interface ShippingsNamespace {
|
|
|
13
14
|
methods: typeof methods
|
|
14
15
|
rates: typeof rates
|
|
15
16
|
routes: typeof routes
|
|
17
|
+
tracking: typeof tracking
|
|
16
18
|
zones: typeof zones
|
|
17
19
|
}
|
|
18
20
|
export {
|
|
@@ -22,6 +24,7 @@ export {
|
|
|
22
24
|
methods,
|
|
23
25
|
rates,
|
|
24
26
|
routes,
|
|
27
|
+
tracking,
|
|
25
28
|
zones,
|
|
26
29
|
};
|
|
27
30
|
export default shippings;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Coordinates } from './geo';
|
|
2
|
+
/** Channel a customer's tracking page subscribes to, keyed on the order. */
|
|
3
|
+
export declare function orderTrackingChannel(orderId: number | string): string;
|
|
4
|
+
/** Channel the dispatch dashboard subscribes to for a whole route. */
|
|
5
|
+
export declare function routeTrackingChannel(routeId: number | string): string;
|
|
6
|
+
/**
|
|
7
|
+
* Best-effort broadcast to a realtime channel.
|
|
8
|
+
*
|
|
9
|
+
* Private rather than public: the payload is a named customer's address and a
|
|
10
|
+
* driver's live position. Authorisation happens in the app's websocket
|
|
11
|
+
* authenticator (`setWsAuthenticator`), which is where the tracking token is
|
|
12
|
+
* checked.
|
|
13
|
+
*/
|
|
14
|
+
export declare function broadcastToChannel(channelName: string, event: string, payload: Record<string, unknown>): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* A driver moved.
|
|
17
|
+
*
|
|
18
|
+
* Broadcast only — this fires several times a minute per active delivery and
|
|
19
|
+
* has no business waking every event listener in the application.
|
|
20
|
+
*/
|
|
21
|
+
export declare function emitDeliveryPosition(orderIds: readonly (number | string)[], routeId: number | null | undefined, payload: DeliveryPositionPayload): Promise<void>;
|
|
22
|
+
/** A stop was assigned to a route and a driver. Both paths. */
|
|
23
|
+
export declare function emitDeliveryAssigned(stop: Record<string, unknown>): Promise<void>;
|
|
24
|
+
/** The vehicle left with this order on it. Both paths. */
|
|
25
|
+
export declare function emitDeliveryStarted(stop: Record<string, unknown>): Promise<void>;
|
|
26
|
+
/**
|
|
27
|
+
* The driver came within the "nearly there" radius.
|
|
28
|
+
*
|
|
29
|
+
* The event worth sending an SMS for, and the reason the whole ingest path
|
|
30
|
+
* computes distance per ping rather than leaving it to the client.
|
|
31
|
+
*/
|
|
32
|
+
export declare function emitDeliveryNearby(stop: Record<string, unknown>, distanceMeters: number, etaSeconds: number | null): Promise<void>;
|
|
33
|
+
/** The driver reached the address. Both paths. */
|
|
34
|
+
export declare function emitDeliveryArrived(stop: Record<string, unknown>): Promise<void>;
|
|
35
|
+
/** Handover done. Both paths. */
|
|
36
|
+
export declare function emitDeliveryCompleted(stop: Record<string, unknown>): Promise<void>;
|
|
37
|
+
/** The stop could not be completed. Event bus only; there is no live view to update. */
|
|
38
|
+
export declare function emitDeliveryFailed(stop: Record<string, unknown>, reason?: string): Promise<void>;
|
|
39
|
+
export declare interface DeliveryPositionPayload extends Coordinates, Record<string, unknown> {
|
|
40
|
+
driverId: number
|
|
41
|
+
routeId?: number | null
|
|
42
|
+
heading?: number | null
|
|
43
|
+
speed?: number | null
|
|
44
|
+
accuracy?: number | null
|
|
45
|
+
recordedAt: string
|
|
46
|
+
distanceToStopMeters?: number | null
|
|
47
|
+
etaSeconds?: number | null
|
|
48
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Great-circle distance in metres.
|
|
3
|
+
*
|
|
4
|
+
* Haversine rather than Vincenty: over the few kilometres a delivery covers
|
|
5
|
+
* the difference is centimetres, and a tracking map that is 5cm out is not a
|
|
6
|
+
* tracking map that is wrong.
|
|
7
|
+
*/
|
|
8
|
+
export declare function distanceInMeters(from: Coordinates, to: Coordinates): number;
|
|
9
|
+
/**
|
|
10
|
+
* Initial bearing in degrees clockwise from true north.
|
|
11
|
+
*
|
|
12
|
+
* Used when a device reports position but no heading, which is common on
|
|
13
|
+
* phones held still: the marker still needs to point somewhere sensible, and
|
|
14
|
+
* the direction of travel between the last two fixes is that somewhere.
|
|
15
|
+
*/
|
|
16
|
+
export declare function bearingInDegrees(from: Coordinates, to: Coordinates): number;
|
|
17
|
+
/**
|
|
18
|
+
* Seconds until arrival, from remaining distance and recent speed.
|
|
19
|
+
*
|
|
20
|
+
* Straight-line distance over ground speed is a floor, not a promise: it
|
|
21
|
+
* ignores every road, light and left turn between here and there. It is
|
|
22
|
+
* multiplied by `detourFactor` to account for the fact that streets are not
|
|
23
|
+
* great circles, and clamped below by `minimumSeconds` so an ETA never reads
|
|
24
|
+
* "arriving now" from two blocks away.
|
|
25
|
+
*
|
|
26
|
+
* Returns null when the driver is stopped, because dividing by zero speed
|
|
27
|
+
* produces Infinity and showing "arriving in ∞ minutes" is worse than showing
|
|
28
|
+
* nothing.
|
|
29
|
+
*/
|
|
30
|
+
export declare function estimateSecondsRemaining(distanceMeters: number, speedMetersPerSecond: number, options?: { detourFactor?: number, minimumSeconds?: number }): number | null;
|
|
31
|
+
/** True when `point` is within `radiusMeters` of `target`. */
|
|
32
|
+
export declare function isWithin(point: Coordinates, target: Coordinates, radiusMeters: number): boolean;
|
|
33
|
+
/** Whether a pair of coordinates is usable at all. */
|
|
34
|
+
export declare function hasCoordinates(value: Partial<Coordinates> | null | undefined): value is Coordinates;
|
|
35
|
+
export declare interface Coordinates {
|
|
36
|
+
latitude: number
|
|
37
|
+
longitude: number
|
|
38
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export type { DeliveryPositionPayload } from './events';
|
|
2
|
+
export type { Coordinates } from './geo';
|
|
3
|
+
export type { DriverPingInput, DriverPingResult } from './ping';
|
|
4
|
+
export type { AssignStopInput } from './stops';
|
|
5
|
+
/**
|
|
6
|
+
* Live delivery tracking.
|
|
7
|
+
*
|
|
8
|
+
* `drivers` and `delivery-routes` are CRUD over the records. This is the part
|
|
9
|
+
* that moves: position ingest, the stop lifecycle, the geodesy the ETA is
|
|
10
|
+
* derived from, and the two fan-outs (event bus for the application, realtime
|
|
11
|
+
* channel for the browser).
|
|
12
|
+
*/
|
|
13
|
+
export {
|
|
14
|
+
broadcastToChannel,
|
|
15
|
+
emitDeliveryArrived,
|
|
16
|
+
emitDeliveryAssigned,
|
|
17
|
+
emitDeliveryCompleted,
|
|
18
|
+
emitDeliveryFailed,
|
|
19
|
+
emitDeliveryNearby,
|
|
20
|
+
emitDeliveryPosition,
|
|
21
|
+
emitDeliveryStarted,
|
|
22
|
+
orderTrackingChannel,
|
|
23
|
+
routeTrackingChannel,
|
|
24
|
+
} from './events';
|
|
25
|
+
export {
|
|
26
|
+
bearingInDegrees,
|
|
27
|
+
distanceInMeters,
|
|
28
|
+
estimateSecondsRemaining,
|
|
29
|
+
hasCoordinates,
|
|
30
|
+
isWithin,
|
|
31
|
+
} from './geo';
|
|
32
|
+
export {
|
|
33
|
+
ARRIVAL_RADIUS_METERS,
|
|
34
|
+
NEARBY_RADIUS_METERS,
|
|
35
|
+
recordDriverPing,
|
|
36
|
+
} from './ping';
|
|
37
|
+
export {
|
|
38
|
+
assignStop,
|
|
39
|
+
completeStop,
|
|
40
|
+
failStop,
|
|
41
|
+
startRoute,
|
|
42
|
+
startStop,
|
|
43
|
+
} from './stops';
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Coordinates } from './geo';
|
|
2
|
+
export declare function recordDriverPing(input: DriverPingInput): Promise<DriverPingResult>;
|
|
3
|
+
/**
|
|
4
|
+
* Driver position ingest.
|
|
5
|
+
*
|
|
6
|
+
* One entry point for "the driver's device says it is here". Everything that
|
|
7
|
+
* has to happen on a fix happens here, in one place, because splitting it
|
|
8
|
+
* across the route handler and a listener is how a tracking page ends up
|
|
9
|
+
* showing a position that the ETA disagrees with:
|
|
10
|
+
*
|
|
11
|
+
* 1. Append to the `driver_pings` series.
|
|
12
|
+
* 2. Update the driver's denormalised present position.
|
|
13
|
+
* 3. Recompute distance and ETA for the stop being served.
|
|
14
|
+
* 4. Push position to everyone watching (broadcast only).
|
|
15
|
+
* 5. Raise `delivery:nearby` and `delivery:arrived` on threshold crossings,
|
|
16
|
+
* exactly once each.
|
|
17
|
+
*/
|
|
18
|
+
/** Within this many metres of the destination, the customer is told to expect the door. */
|
|
19
|
+
export declare const NEARBY_RADIUS_METERS: 400;
|
|
20
|
+
/** Within this, the driver is treated as arrived. */
|
|
21
|
+
export declare const ARRIVAL_RADIUS_METERS: 60;
|
|
22
|
+
export declare interface DriverPingInput extends Coordinates {
|
|
23
|
+
driverId: number
|
|
24
|
+
heading?: number | null
|
|
25
|
+
speed?: number | null
|
|
26
|
+
accuracy?: number | null
|
|
27
|
+
recordedAt?: string
|
|
28
|
+
}
|
|
29
|
+
export declare interface DriverPingResult {
|
|
30
|
+
pingId: number | null
|
|
31
|
+
routeId: number | null
|
|
32
|
+
stopId: number | null
|
|
33
|
+
distanceToStopMeters: number | null
|
|
34
|
+
etaSeconds: number | null
|
|
35
|
+
crossedNearby: boolean
|
|
36
|
+
crossedArrival: boolean
|
|
37
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Put an order on a route. */
|
|
2
|
+
export declare function assignStop(input: AssignStopInput): Promise<Record<string, unknown>>;
|
|
3
|
+
/**
|
|
4
|
+
* The driver is now driving to this stop.
|
|
5
|
+
*
|
|
6
|
+
* Also moves the order to OUT_FOR_DELIVERY, which is the state the customer's
|
|
7
|
+
* tracking page and notifications key on.
|
|
8
|
+
*/
|
|
9
|
+
export declare function startStop(stopId: number): Promise<Record<string, unknown> | null>;
|
|
10
|
+
/** Handover done. Completes the stop and marks the order delivered. */
|
|
11
|
+
export declare function completeStop(stopId: number, notes?: string): Promise<Record<string, unknown> | null>;
|
|
12
|
+
/**
|
|
13
|
+
* The stop could not be completed.
|
|
14
|
+
*
|
|
15
|
+
* The order goes back to SHIPPED rather than staying OUT_FOR_DELIVERY: it is
|
|
16
|
+
* on its way back to the depot, and a customer watching a map should not be
|
|
17
|
+
* told a vehicle is still coming.
|
|
18
|
+
*/
|
|
19
|
+
export declare function failStop(stopId: number, reason: string): Promise<Record<string, unknown> | null>;
|
|
20
|
+
/** Start a route. Until this runs, pings from its driver find no active route. */
|
|
21
|
+
export declare function startRoute(routeId: number): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* Stop lifecycle.
|
|
24
|
+
*
|
|
25
|
+
* Every state change a driver makes goes through one of these, so the order's
|
|
26
|
+
* status, the stop's timestamps and the outgoing events stay in step. Writing
|
|
27
|
+
* `delivery_stops.status` directly works and is how a tracking page ends up
|
|
28
|
+
* saying "out for delivery" about an order that was delivered ten minutes ago.
|
|
29
|
+
*
|
|
30
|
+
* The order status is kept in lockstep on purpose: `OUT_FOR_DELIVERY` and
|
|
31
|
+
* `DELIVERED` are the two states a customer actually sees, and they mean the
|
|
32
|
+
* same thing as the stop being `en_route` and `completed`.
|
|
33
|
+
*/
|
|
34
|
+
export declare interface AssignStopInput {
|
|
35
|
+
deliveryRouteId: number
|
|
36
|
+
orderId?: number | null
|
|
37
|
+
sequence?: number
|
|
38
|
+
address: string
|
|
39
|
+
latitude?: number | null
|
|
40
|
+
longitude?: number | null
|
|
41
|
+
recipientName?: string | null
|
|
42
|
+
recipientPhone?: string | null
|
|
43
|
+
etaAt?: string | null
|
|
44
|
+
}
|