@stacksjs/commerce 0.70.78 → 0.70.80
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 +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var R9=Object.defineProperty;var U9=(G)=>G;function T9(G,J){this[G]=U9.bind(null,J)}var Q=(G,J)=>{for(var X in J)R9(G,X,{get:J[X],enumerable:!0,configurable:!0,set:T9.bind(J,X)})};var QX=import.meta.require;var FG={};Q(FG,{update:()=>gX,store:()=>fX,redeem:()=>yX,getActiveCouponsMoMChange:()=>CX,fetchTopRedeemedCoupons:()=>jX,fetchStats:()=>TX,fetchRedemptionTrend:()=>kX,fetchRedemptionStats:()=>PX,fetchCouponCountsByType:()=>qX,fetchCouponCounts:()=>SX,fetchConversionRate:()=>wX,fetchById:()=>l,fetchByCode:()=>RX,fetchAll:()=>OX,fetchActive:()=>UX,deleteExpiredCoupons:()=>AX,deleteCoupons:()=>BX,deleteCoupon:()=>VX});import{db as LJ}from"@stacksjs/database";import{formatDate as S9}from"@stacksjs/orm";async function VX(G){return!!await LJ.deleteFrom("coupons").where("id","=",G).executeTakeFirst()}async function BX(G){if(!G.length)return 0;return(await LJ.deleteFrom("coupons").where("id","in",G).execute()).length||0}async function AX(){let G=S9(new Date),J=await LJ.deleteFrom("coupons").where("end_date","<",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}import{db as V}from"@stacksjs/database";import{extractDate as zX,formatDate as EX}from"@stacksjs/orm";function EJ(G){let J={...G};if(J.endDate)J.endDate=zX(new Date(J.endDate));if(J.startDate)J.startDate=zX(new Date(J.startDate));if(J.isActive!==void 0)J.isActive=Boolean(J.isActive);return J}async function OX(){return(await V.selectFrom("coupons").selectAll().execute()).map(EJ)}async function l(G){let J=await V.selectFrom("coupons").where("id","=",G).selectAll().executeTakeFirst();if(J)return EJ(J);return}async function RX(G){let J=await V.selectFrom("coupons").where("code","=",G).selectAll().executeTakeFirst();if(J)return EJ(J);return}async function UX(){let G=EX(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).selectAll().execute()).map(EJ)}async function TX(){let G=await V.selectFrom("coupons").select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),J=EX(new Date),X=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),$=await V.selectFrom("coupons").select(["discount_type",(Y)=>Y.fn.count("id").as("count")]).groupBy("discount_type").execute(),K=await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),L=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",J).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(G?.count||0),active:Number(X?.count||0),by_type:$,most_used:K,upcoming:L}}async function SX(){let G=new Date,J=new Date(G);J.setDate(G.getDate()-7);let X=new Date(G);X.setMonth(G.getMonth()-1);let $=new Date(G);$.setFullYear(G.getFullYear()-1);let K=await zJ(null,null,G),L=await zJ(J,null,G),Y=await zJ(X,null,G),W=await zJ($,null,G);return{week:L,month:Y,year:W,all_time:K}}async function zJ(G,J,X){let $=V.selectFrom("coupons");if(G)$=$.where("created_at",">=",G.toISOString());if(J)$=$.where("created_at","<=",J.toISOString());let K=await $.select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),L=V.selectFrom("coupons");if(G)L=L.where("created_at",">=",G.toISOString());if(J)L=L.where("created_at","<=",J.toISOString());L=L.where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",X);let Y=await L.select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),W=Number(K?.count||0),M=Number(Y?.count||0),Z=W-M;return{total:W,active:M,inactive:Z}}async function qX(){let G=new Date,J=await V.selectFrom("coupons").select("discount_type").distinct().execute(),X={};for(let{discount_type:$}of J){let K=await V.selectFrom("coupons").where("discount_type","=",$).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),L=await V.selectFrom("coupons").where("discount_type","=",$).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),Y=Number(K?.count||0),W=Number(L?.count||0);X[$]={total:Y,active:W,inactive:Y-W}}return X}async function PX(){let G=await V.selectFrom("coupons").select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),J=new Date,X=new Date(J);X.setDate(J.getDate()-7);let $=new Date(J);$.setMonth(J.getMonth()-1);let K=new Date(J);K.setFullYear(J.getFullYear()-1);let L=await V.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await V.selectFrom("coupons").where("updated_at",">=",$.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await V.selectFrom("coupons").where("updated_at",">=",K.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),M=await V.selectFrom("coupons").select(["discount_type",(N)=>N.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),Z={};return M.forEach((N)=>{Z[N.discount_type]=Number(N.total||0)}),{total:Number(G?.total||0),week:Number(L?.total||0),month:Number(Y?.total||0),year:Number(W?.total||0),by_type:Z}}async function jX(G=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(G).execute()}async function kX(G=30){let J=new Date().toISOString(),X=new Date;X.setDate(X.getDate()-G);let $=await V.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",X.toISOString()).where("updated_at","<=",J).where("usage_count",">",0).orderBy("updated_at","desc").execute(),K={};return $.forEach((L)=>{let Y=L.updated_at?new Date(L.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!K[Y])K[Y]=0;K[Y]+=L?.usage_count||0}),Object.entries(K).map(([L,Y])=>({date:L,count:Y}))}async function wX(){let G=new Date,J=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),X=await V.selectFrom("coupons").where("usage_count",">",0).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),$=Number(J?.count||0),K=Number(X?.count||0);return{rate:$>0?K/$*100:0,total_active:$,total_redeemed:K}}async function CX(){let G=new Date,J=new Date(G.getFullYear(),G.getMonth(),1),X=new Date(G.getFullYear(),G.getMonth()-1,1),$=new Date(G.getFullYear(),G.getMonth(),0),K=await V.selectFrom("coupons").select((N)=>N.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",J).executeTakeFirst(),L=await V.selectFrom("coupons").select((N)=>N.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",X).executeTakeFirst(),Y=Number(K?.count||0),W=Number(L?.count||0),M=Y-W,Z=W!==0?M/W*100:Y>0?100:0;return{current_month:Y,previous_month:W,difference:M,percentage_change:Z}}import{db as _X}from"@stacksjs/database";import{HttpError as IX}from"@stacksjs/error-handling";import{isUniqueViolation as q9}from"@stacksjs/orm";async function fX(G){try{let J=await _X.insertInto("coupons").values(G).executeTakeFirst(),X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows);if(X)return await _X.selectFrom("coupons").where("id","=",X).selectAll().executeTakeFirst();return}catch(J){if(J instanceof IX)throw J;if(q9(J))throw new IX(409,"A coupon with this code already exists");if(J instanceof Error)throw Error(`Failed to create coupon: ${J.message}`);throw J}}import{db as HG}from"@stacksjs/database";import{HttpError as vX}from"@stacksjs/error-handling";import{formatDate as hX,isUniqueViolation as P9}from"@stacksjs/orm";async function gX(G,J){if(!await l(G))throw Error(`Coupon with ID ${G} not found`);try{await HG.updateTable("coupons").set({...J,updated_at:hX(new Date)}).where("id","=",G).execute();let $=await l(G);if($){let K=$;K.is_active=Boolean(K.is_active)}return $}catch($){if($ instanceof vX)throw $;if(P9($))throw new vX(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to update coupon: ${$.message}`);throw $}}async function yX(G){let J=hX(new Date),X=await HG.updateTable("coupons").set({usage_count:HG.raw("COALESCE(usage_count, 0) + 1"),updated_at:J}).where("id","=",G).where((W)=>W.or([W("max_uses","is",null),W.cmpr("usage_count","<",W.ref("max_uses"))])).where("is_active","=",1).where((W)=>W.or([W("start_date","is",null),W.cmpr("start_date","<=",J)])).where((W)=>W.or([W("end_date","is",null),W.cmpr("end_date",">=",J)])).executeTakeFirst();if(Number(X?.numUpdatedRows??X?.affectedRows??0)>0){let W=await l(G);if(W){let M=W;return M.is_active=Boolean(M.is_active),{ok:!0,coupon:W}}return{ok:!1,reason:"not-found"}}let K=await l(G);if(!K)return{ok:!1,reason:"not-found"};if(!K.is_active)return{ok:!1,reason:"inactive"};let L=!K.start_date||K.start_date<=J,Y=!K.end_date||K.end_date>=J;if(!L||!Y)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var VG={};Q(VG,{update:()=>nX,store:()=>cX,fetchById:()=>t,fetchAll:()=>pX,destroy:()=>mX,bulkDestroy:()=>bX});import{db as QG}from"@stacksjs/database";import{db as DX}from"@stacksjs/database";async function t(G){return await DX.selectFrom("customers").where("id","=",G).selectAll().executeTakeFirst()}async function pX(){return await DX.selectFrom("customers").selectAll().execute()}async function mX(G){try{if(!await t(G))throw Error(`Customer with ID ${G} not found`);return(await QG.deleteFrom("customers").where("id","=",G).executeTakeFirst()).numDeletedRows>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customer: ${J.message}`);throw J}}async function bX(G){if(!G.length)return 0;try{let J=await QG.deleteFrom("customers").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${J.message}`);throw J}}import{db as j9}from"@stacksjs/database";import{HttpError as lX}from"@stacksjs/error-handling";import{isUniqueViolation as k9}from"@stacksjs/orm";async function cX(G){try{let J={...G,avatar:G.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},X=await j9.insertInto("customers").values(J).executeTakeFirst();if(!X)throw Error("Failed to create customer");let $=X.insertId||Number(X.numInsertedOrUpdatedRows);return await t(Number($))}catch(J){if(J instanceof lX)throw J;if(k9(J))throw new lX(409,"A customer with this email already exists");if(J instanceof Error)throw Error(`Failed to create customer: ${J.message}`);throw J}}import{db as w9}from"@stacksjs/database";import{HttpError as uX}from"@stacksjs/error-handling";import{formatDate as C9,isUniqueViolation as _9}from"@stacksjs/orm";async function nX(G,J){try{if(!G)throw Error("Customer ID is required for update");let X=await w9.updateTable("customers").set({...J,updated_at:C9(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update customer");return X}catch(X){if(X instanceof uX)throw X;if(_9(X))throw new uX(409,"A customer with this email already exists");if(X instanceof Error)throw Error(`Failed to update customer: ${X.message}`);throw X}}var EG={};Q(EG,{updateStatus:()=>X6,updatePrintCount:()=>$6,update:()=>G6,storePrintDevicesExport:()=>tX,store:()=>eX,fetchById:()=>f,fetchAll:()=>OJ,exportPrintDevices:()=>RJ,downloadPrintDevices:()=>aX,destroy:()=>iX,bulkStore:()=>J6,bulkDestroy:()=>sX});import{db as oX}from"@stacksjs/database";async function iX(G){try{let J=await oX.deleteFrom("print_devices").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print device: ${J.message}`);throw J}}async function sX(G){if(!G.length)return 0;try{let J=await oX.deleteFrom("print_devices").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print devices: ${J.message}`);throw J}}import{createSpreadsheet as I9}from"ts-spreadsheets";import{db as dX}from"@stacksjs/database";async function f(G){return await dX.selectFrom("print_devices").where("id","=",G).selectAll().executeTakeFirst()}async function OJ(){return await dX.selectFrom("print_devices").selectAll().execute()}async function RJ(G="csv"){let J=await OJ(),X=f9(J);return I9(X,{type:G})}function f9(G){let J=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],X=G.map(($)=>{return[$.id,$.name,$.macAddress,$.location,$.terminal,$.status,new Date($.lastPing).toLocaleString(),$.printCount]});return{headings:J,data:X}}async function aX(G="csv",J){let X=await RJ(G),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;return X.download(J||$)}async function tX(G="csv",J){let X=await RJ(G),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;X.store(J||$)}var{randomUUIDv7:rX}=globalThis.Bun;import{db as BG}from"@stacksjs/database";async function eX(G){try{let J={...G,uuid:rX()},X=await BG.insertInto("print_devices").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await BG.selectFrom("print_devices").where("id","=",$).selectAll().executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print device: ${J.message}`);throw J}}async function J6(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:rX()};await BG.insertInto("print_devices").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${X.message}`);throw X}}import{db as AG}from"@stacksjs/database";import{formatDate as zG}from"@stacksjs/orm";async function G6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await AG.updateTable("print_devices").set({...J,updated_at:zG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device: ${$.message}`);throw $}}async function X6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await AG.updateTable("print_devices").set({status:J,updated_at:zG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device status: ${$.message}`);throw $}}async function $6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await AG.updateTable("print_devices").set({print_count:J,updated_at:zG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print count: ${$.message}`);throw $}}var UG={};Q(UG,{update:()=>H6,unresolveGroup:()=>B6,resolveGroup:()=>Q6,ignoreGroup:()=>V6,fetchTimeline:()=>x6,fetchStats:()=>N6,fetchGrouped:()=>Z6,fetchById:()=>W6,fetchByGroup:()=>M6,fetchAll:()=>TJ,destroyGroup:()=>Y6,destroy:()=>K6,bulkUpdateStatus:()=>F6,bulkDestroy:()=>L6});import{db as OG}from"@stacksjs/database";import{log as RG}from"@stacksjs/logging";async function K6(G){try{return await OG.deleteFrom("errors").where("id","=",G).execute(),!0}catch(J){return RG.error("[commerce/errors] destroy failed",{id:G,error:J}),!1}}async function L6(G){try{return await OG.deleteFrom("errors").where("id","in",G).execute(),!0}catch(J){return RG.error("[commerce/errors] bulkDestroy failed",{count:G.length,error:J}),!1}}async function Y6(G,J){try{return await OG.deleteFrom("errors").where("type","=",G).where("message","=",J).execute(),!0}catch(X){return RG.error("[commerce/errors] destroyGroup failed",{type:G,message:J,error:X}),!1}}import{db as UJ}from"@stacksjs/database";async function W6(G){return await UJ.selectFrom("errors").where("id","=",G).selectAll().executeTakeFirst()}async function TJ(){return await UJ.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function Z6(){let G=await UJ.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),J=new Map;for(let $ of G){let K=`${$.type}:${$.message}`;if(!J.has(K))J.set(K,{errors:[],firstSeen:new Date($.created_at),lastSeen:new Date($.created_at)});let L=J.get(K);L.errors.push($);let Y=new Date($.created_at);if(Y<L.firstSeen)L.firstSeen=Y;if(Y>L.lastSeen)L.lastSeen=Y}let X=[];for(let[$,K]of J){let L=K.errors[0];if(!L)continue;let Y=K.errors.find((M)=>M.status!==null)?.status,W="unresolved";if(Y===1)W="resolved";else if(Y===2)W="ignored";X.push({id:L.id,type:L.type,message:L.message,stack:L.stack,status:W,count:K.errors.length,first_seen:K.firstSeen.toISOString(),last_seen:K.lastSeen.toISOString(),error_ids:K.errors.map((M)=>M.id)})}return X.sort(($,K)=>new Date(K.last_seen).getTime()-new Date($.last_seen).getTime()),X}async function M6(G,J){return await UJ.selectFrom("errors").where("type","=",G).where("message","=",J).selectAll().orderBy("created_at","desc").execute()}async function N6(){let G=await TJ(),J=new Date,X=new Date(J.getTime()-86400000),$=new Date(J.getTime()-172800000),K=G.filter((W)=>new Date(W.created_at)>=X).length,L=G.filter((W)=>{let M=new Date(W.created_at);return M>=$&&M<X}).length,Y=L===0?K>0?100:0:Math.round((K-L)/L*100);return{total:G.length,unresolved:G.filter((W)=>W.status===null||W.status===0).length,resolved:G.filter((W)=>W.status===1).length,ignored:G.filter((W)=>W.status===2).length,last_24h:K,trend:Y}}async function x6(){let G=await TJ(),J=new Date,X=[];for(let $=23;$>=0;$--){let K=new Date(J.getTime()-$*60*60*1000);K.setMinutes(0,0,0);let L=new Date(K.getTime()+3600000),Y=G.filter((W)=>{let M=new Date(W.created_at);return M>=K&&M<L}).length;X.push({hour:K.toISOString(),count:Y})}return X}import{db as YJ}from"@stacksjs/database";import{sql as WJ}from"@stacksjs/database";import{log as ZJ}from"@stacksjs/logging";async function H6(G,J){try{return await YJ.updateTable("errors").set({...J,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("id","=",G).execute(),!0}catch(X){return ZJ.error("[commerce/errors] update failed",{id:G,error:X}),!1}}async function F6(G,J){try{return await YJ.updateTable("errors").set({status:J,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("id","in",G).execute(),!0}catch(X){return ZJ.error("[commerce/errors] bulkUpdateStatus failed",{count:G.length,status:J,error:X}),!1}}async function Q6(G,J){try{return await YJ.updateTable("errors").set({status:1,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return ZJ.error("[commerce/errors] resolveGroup failed",{type:G,message:J,error:X}),!1}}async function V6(G,J){try{return await YJ.updateTable("errors").set({status:2,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return ZJ.error("[commerce/errors] ignoreGroup failed",{type:G,message:J,error:X}),!1}}async function B6(G,J){try{return await YJ.updateTable("errors").set({status:0,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return ZJ.error("[commerce/errors] unresolveGroup failed",{type:G,message:J,error:X}),!1}}var PG={};Q(PG,{updateBalance:()=>f6,update:()=>I6,store:()=>w6,fetchTotalValue:()=>T6,fetchTotalCurrentBalance:()=>S6,fetchStats:()=>E6,fetchById:()=>v,fetchByCode:()=>SG,fetchAll:()=>A6,fetchActive:()=>z6,destroy:()=>q6,compareActiveGiftCards:()=>R6,checkBalance:()=>O6,calculateGiftCardValues:()=>U6,bulkDestroy:()=>P6});import{db as qG}from"@stacksjs/database";import{formatDate as hL}from"@stacksjs/orm";import{db as j,sql as TG}from"@stacksjs/database";import{formatDate as D,toTimestamp as r}from"@stacksjs/orm";import{db as v9}from"@stacksjs/database";async function y(G,J,X){let $=v9.selectFrom(G);if(X)$=X($);$=$.select((Y)=>Object.entries(J).map(([W,M])=>{let Z=M.column??"id",N=Y.fn[M.kind](Z);if(M.filter){let x=M.filter;N=N.filterWhere(x.column,x.op,x.value)}return N.as(W)}));let K=await $.executeTakeFirst(),L={};for(let Y of Object.keys(J)){let W=K?.[Y];L[Y]=typeof W==="number"?W:Number(W??0)||0}return L}async function A6(){return await j.selectFrom("gift_cards").selectAll().execute()}async function v(G){return await j.selectFrom("gift_cards").where("id","=",G).selectAll().executeTakeFirst()}async function SG(G){return await j.selectFrom("gift_cards").where("code","=",G).selectAll().executeTakeFirst()}async function z6(){return await j.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function E6(){let{count:G}=await y("gift_cards",{count:{kind:"count"}}),J=r(new Date),X=await j.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where((N)=>N.or([N("expiry_date",">=",J),N("expiry_date","is",null)])).select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),$=await j.selectFrom("gift_cards").select(["status",(N)=>N.fn.count("id").as("count")]).groupBy("status").execute(),{count:K}=await y("gift_cards",{count:{kind:"count"}},(N)=>N.where((x)=>TG`${x.ref("current_balance")} / ${x.ref("initial_balance")} < 0.25`)),{count:L}=await y("gift_cards",{count:{kind:"count"}},(N)=>N.where((x)=>TG`${x.ref("current_balance")} / ${x.ref("initial_balance")} >= 0.25 AND ${x.ref("current_balance")} / ${x.ref("initial_balance")} <= 0.75`)),{count:Y}=await y("gift_cards",{count:{kind:"count"}},(N)=>N.where((x)=>TG`${x.ref("current_balance")} / ${x.ref("initial_balance")} > 0.75`)),W=new Date;W.setDate(W.getDate()+30);let M=await j.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",r(W)).where("expiry_date",">=",J).selectAll().limit(5).execute(),Z=await j.selectFrom("gift_cards").where("last_used_date","is not",null).selectAll().limit(5).execute();return{total:G,active:Number(X?.count||0),by_status:$.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:K,medium:L,high:Y},expiring_soon:M,recently_used:Z}}async function O6(G){let J=await SG(G);if(!J)return{valid:!1,message:"Gift card not found"};if(!J.isActive||J.status!=="ACTIVE")return{valid:!1,balance:J.currentBalance,currency:J.currency,message:`Gift card is ${J.status.toLowerCase()}`};if(J.expiryDate){if(new Date(J.expiryDate)<new Date)return{valid:!1,balance:J.currentBalance,currency:J.currency,message:"Gift card has expired"}}return{valid:!0,balance:J.currentBalance,currency:J.currency}}async function R6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await j.selectFrom("gift_cards").select((x)=>x.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").where((x)=>x.or([x("expiry_date",">=",r(J)),x("expiry_date","is",null)])).where("created_at",">=",D(X)).where("created_at","<=",D(J)).executeTakeFirst(),Y=await j.selectFrom("gift_cards").select((x)=>x.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").where((x)=>x.or([x("expiry_date",">=",r(K)),x("expiry_date","is",null)])).where("created_at",">=",D(K)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(L?.count||0),M=Number(Y?.count||0),Z=W-M,N=M!==0?Z/M*100:W>0?100:0;return{current_period:W,previous_period:M,difference:Z,percentage_change:N,days_range:G}}async function U6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await j.selectFrom("gift_cards").select((q)=>[q.fn.sum("initial_balance").as("total_initial"),q.fn.sum("current_balance").as("total_balance"),q.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").where((q)=>q.or([q("expiry_date",">=",r(J)),q("expiry_date","is",null)])).where("created_at",">=",D(X)).where("created_at","<=",D(J)).executeTakeFirst(),Y=await j.selectFrom("gift_cards").select((q)=>[q.fn.sum("initial_balance").as("total_initial"),q.fn.sum("current_balance").as("total_balance"),q.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").where((q)=>q.or([q("expiry_date",">=",r(K)),q("expiry_date","is",null)])).where("created_at",">=",D(K)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(L?.total_initial||0),M=Number(L?.total_balance||0),Z=Number(L?.card_count||0),N=Number(Y?.total_initial||0),x=Number(Y?.total_balance||0),H=Number(Y?.card_count||0),E=W>0?(W-M)/W*100:0,B=N>0?(N-x)/N*100:0,F=Z>0?W/Z:0,A=Z>0?M/Z:0,_=W-N,m=M-x,b=Z-H,a=N!==0?_/N*100:W>0?100:0,R=x!==0?m/x*100:M>0?100:0,I=H!==0?b/H*100:Z>0?100:0;return{current_period:{total_initial_value:W,total_remaining_balance:M,utilization_rate:E,card_count:Z,average_initial_value:F,average_remaining_balance:A},previous_period:{total_initial_value:N,total_remaining_balance:x,utilization_rate:B,card_count:H},comparison:{initial_value:{difference:_,percentage:Math.abs(a),is_increase:_>=0},balance:{difference:m,percentage:Math.abs(R),is_increase:m>=0},card_count:{difference:b,percentage:Math.abs(I),is_increase:b>=0}},days_range:G}}async function T6(){let{total_value:G}=await y("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:G}}async function S6(){let{total_balance:G}=await y("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:G}}async function q6(G){if(!await v(G))throw Error(`Gift card with ID ${G} not found`);return!!await qG.deleteFrom("gift_cards").where("id","=",G).executeTakeFirst()}async function P6(G){if(!G.length)return 0;let J=await qG.deleteFrom("gift_cards").where("id","in",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}var{randomUUIDv7:h9}=globalThis.Bun;import{db as j6}from"@stacksjs/database";import{HttpError as k6}from"@stacksjs/error-handling";import{isUniqueViolation as g9}from"@stacksjs/orm";async function w6(G){let J=G,X={...G,current_balance:J.current_balance??J.initial_balance,status:G.status||"ACTIVE",is_active:J.is_active??!0,uuid:h9()};try{let $=await j6.insertInto("gift_cards").values(X).executeTakeFirst(),K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);if(K)return await j6.selectFrom("gift_cards").where("id","=",K).selectAll().executeTakeFirst();return}catch($){if($ instanceof k6)throw $;if(g9($))throw new k6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to create gift card: ${$.message}`);throw $}}import{db as SJ}from"@stacksjs/database";import{HttpError as C6}from"@stacksjs/error-handling";import{formatDate as _6,isUniqueViolation as y9}from"@stacksjs/orm";async function I6(G,J){if(!await v(G))throw Error(`Gift card with ID ${G} not found`);try{return await SJ.updateTable("gift_cards").set({...J,updated_at:_6(new Date)}).where("id","=",G).execute(),await v(G)}catch($){if($ instanceof C6)throw $;if(y9($))throw new C6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to update gift card: ${$.message}`);throw $}}async function f6(G,J){let X=_6(new Date),$=await SJ.updateTable("gift_cards").set({current_balance:SJ.raw(`current_balance + ${J}`),last_used_date:X,status:SJ.raw(`CASE WHEN current_balance + ${J} = 0 THEN 'USED' ELSE 'ACTIVE' END`),updated_at:X}).where("id","=",G).where("is_active","=",1).where("status","=","ACTIVE").where((Y)=>Y.cmpr(Y.raw(`current_balance + ${J}`),">=",0)).executeTakeFirst();if(Number($?.numUpdatedRows??$?.affectedRows??0)>0)return await v(G);let L=await v(G);if(!L)throw Error(`Gift card with ID ${G} not found`);if(!L.is_active||L.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var yG={};Q(yG,{validateQuantityBounds:()=>gG,validateCouponStacking:()=>L$,validateCartQuantities:()=>Y$,updateStatus:()=>e6,updateDeliveryInfo:()=>J$,update:()=>r6,storeOrdersExport:()=>m6,store:()=>s6,softDelete:()=>h6,registerCommerceWebhookHandlers:()=>X$,recomputeOrderTotals:()=>K$,placeOrder:()=>t6,handlePaymentIntentSucceeded:()=>fG,handlePaymentIntentFailed:()=>vG,handleChargeRefunded:()=>hG,fetchStats:()=>l6,fetchDailyOrderTrends:()=>n6,fetchById:()=>h,fetchAll:()=>b6,exportOrders:()=>PJ,emitOrderShipped:()=>jG,emitOrderRefunded:()=>NJ,emitOrderPaid:()=>c,emitOrderDelivered:()=>kG,emitOrderCreated:()=>kJ,emitOrderCancelled:()=>MJ,emitForStatus:()=>wJ,downloadOrders:()=>p6,destroy:()=>v6,compareOrdersByPeriod:()=>c6,cleanupAbandonedCarts:()=>W$,canTransition:()=>jJ,calculateOrderMetrics:()=>u6,bulkSoftDelete:()=>y6,bulkDestroy:()=>g6});import{db as qJ}from"@stacksjs/database";async function v6(G){try{let J=await qJ.deleteFrom("orders").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function h6(G){try{let J=await qJ.updateTable("orders").set({status:"CANCELED"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete order: ${J.message}`);throw J}}async function g6(G){if(!G.length)return 0;try{let J=await qJ.deleteFrom("orders").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}async function y6(G){if(!G.length)return 0;try{let J=await qJ.updateTable("orders").set({status:"CANCELED"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete orders: ${J.message}`);throw J}}import{db as D6}from"@stacksjs/database";import{createSpreadsheet as D9}from"ts-spreadsheets";async function PJ(G="csv"){let J=await p9(),X=m9(J);return D9(X,{type:G})}async function p9(){let G=await D6.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),J=G.map((L)=>L.id);if(J.length===0)return[];let $=(await D6.selectFrom("order_items").where("order_items.order_id","in",J).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((L,Y)=>{if(!Y.order_id)return L;if(!L[Y.order_id])L[Y.order_id]={totalItems:0,totalPrice:0};return L[Y.order_id].totalItems+=Y.quantity,L[Y.order_id].totalPrice+=Y.price*Y.quantity,L},{});return G.map((L)=>{let Y=$[L.id]||{totalItems:0,totalPrice:0};return{...L,totalItems:Y.totalItems,totalPrice:Y.totalPrice}})}function m9(G){let J=["Order ID","Customer","Date","Total","Status","Items"],X=G.map(($)=>{let K=$.order_items?.map((L)=>`${L.product?.name} (Qty: ${L.quantity}, Price: $${L.price})`).join(" | ")||"No Items";return[$.id,$.customer?.name||"N/A",$.created_at,$.total_amount,$.status,K]});return{headings:J,data:X}}async function p6(G="csv",J){let X=await PJ(G),$=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;return X.download(J||$)}async function m6(G="csv",J){let X=await PJ(G),$=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;X.store(J||$)}import{db as S}from"@stacksjs/database";async function b6(G){let J=S.selectFrom("orders").selectAll().orderBy("created_at","desc");if(G)J=J.limit(G);let X=await J.execute();return await Promise.all(X.map(async($)=>{let K=await S.selectFrom("order_items").where("order_id","=",$.id).selectAll().execute();return{...$,items:K}}))}async function h(G){return await S.selectFrom("orders").where("id","=",G).selectAll().executeTakeFirst()}async function l6(){let G=await S.selectFrom("orders").select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),J=await S.selectFrom("orders").select(["status",(Y)=>Y.fn.count("id").as("count")]).groupBy("status").execute(),X=await S.selectFrom("orders").select(["order_type",(Y)=>Y.fn.count("id").as("count")]).groupBy("order_type").execute(),$=await S.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),K=await Promise.all($.map(async(Y)=>{let W=await S.selectFrom("order_items").where("order_id","=",Y.id).selectAll().execute();return{...Y,items:W}})),L=await S.selectFrom("orders").select((Y)=>Y.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(G?.count||0),by_status:J,by_type:X,recent:K,revenue:Number(L?.total||0)}}async function c6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await S.selectFrom("orders").select((x)=>x.fn.count("id").as("count")).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),Y=await S.selectFrom("orders").select((x)=>x.fn.count("id").as("count")).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=Number(L?.count||0),M=Number(Y?.count||0),Z=W-M,N=M!==0?Z/M*100:W>0?100:0;return{current_period:W,previous_period:M,difference:Z,percentage_change:N,days_range:G}}async function u6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await S.selectFrom("orders").select((R)=>[R.fn.count("id").as("total_orders"),R.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),Y=await S.selectFrom("orders").select((R)=>[R.fn.count("id").as("total_orders"),R.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=await S.selectFrom("orders").select(["status",(R)=>R.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).groupBy("status").execute(),M=await S.selectFrom("orders").select(["order_type",(R)=>R.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).groupBy("order_type").execute(),Z=Number(L?.total_orders||0),N=Number(L?.total_revenue||0),x=Z>0?N/Z:0,H=Number(Y?.total_orders||0),E=Number(Y?.total_revenue||0),B=H>0?E/H:0,F=Z-H,A=N-E,_=x-B,m=H!==0?F/H*100:Z>0?100:0,b=E!==0?A/E*100:N>0?100:0,a=B!==0?_/B*100:x>0?100:0;return{current_period:{total_orders:Z,total_revenue:N,average_order_value:x,orders_by_status:W.map((R)=>({status:R.status,count:Number(R.count)})),orders_by_type:M.map((R)=>({order_type:R.order_type,count:Number(R.count)}))},previous_period:{total_orders:H,total_revenue:E,average_order_value:B},comparison:{orders:{difference:F,percentage:Math.abs(m),is_increase:F>=0},revenue:{difference:A,percentage:Math.abs(b),is_increase:A>=0},average_order_value:{difference:_,percentage:Math.abs(a),is_increase:_>=0}},days_range:G}}async function n6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await S.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).orderBy("created_at","asc").execute(),K=new Map;for(let L of $){let Y=(L.created_at||"").split("T")[0]||"unknown",W=K.get(Y)||{order_count:0,revenue:0};W.order_count++,W.revenue+=Number(L.total_amount||0),K.set(Y,W)}return Array.from(K.entries()).map(([L,Y])=>({date:L,order_count:Y.order_count,revenue:Y.revenue}))}var{randomUUIDv7:b9}=globalThis.Bun;import{db as o6}from"@stacksjs/database";import{formatDate as i6}from"@stacksjs/orm";async function s6(G){let J={...G,status:G.status||"PENDING",uuid:b9(),created_at:i6(new Date),updated_at:i6(new Date)};try{let X=await o6.insertInto("orders").values(J).executeTakeFirst(),$=Number(X?.insertId)||Number(X?.numInsertedOrUpdatedRows);if($)return await o6.selectFrom("orders").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof Error)throw Error(`Failed to create order: ${X.message}`);throw X}}var{randomUUIDv7:c9}=globalThis.Bun;import{db as CJ}from"@stacksjs/database";import{formatDate as u9}from"@stacksjs/orm";import{sql as d6}from"@stacksjs/database";var l9={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","CANCELLED","REFUNDED"],SHIPPED:["DELIVERED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]};function jJ(G,J){if(G===J)return!0;return l9[G]?.includes(J)??!1}async function e(G,J){try{let X=await import("@stacksjs/events").catch(()=>null);if(!X)return;let $=X.dispatch;if(typeof $!=="function")return;$(G,J)}catch{}}async function kJ(G){await e("order:created",{order:G})}async function c(G,J){await e("order:paid",{order:G,payment:J})}async function jG(G){await e("order:shipped",{order:G})}async function kG(G){await e("order:delivered",{order:G})}async function MJ(G,J){await e("order:cancelled",{order:G,reason:J})}async function NJ(G,J){await e("order:refunded",{order:G,refundAmount:J})}async function wJ(G,J){switch(G){case"PROCESSING":return c(J);case"SHIPPED":return jG(J);case"DELIVERED":return kG(J);case"CANCELLED":return MJ(J);case"REFUNDED":return NJ(J);case"PENDING":default:}}var a6=!1;async function n9(G){try{let J=await CJ.selectFrom("order_idempotency").where("idempotency_key","=",G).selectAll().executeTakeFirst();if(!J)return null;return await CJ.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}catch(J){if(J?.message?.includes("no such table")||J?.message?.includes("doesn't exist")){if(!a6)a6=!0,console.warn("[commerce/orders] order_idempotency table missing \u2014 idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw J}}async function t6(G){if(G.idempotencyKey){let J=await n9(G.idempotencyKey);if(J)return{ok:!0,order:J}}try{let J=await CJ.transaction(async(X)=>{let $=u9(new Date),K={...G.order,status:G.order.status||"PENDING",uuid:c9(),created_at:$,updated_at:$},L=await X.insertInto("orders").values(K).executeTakeFirst(),Y=Number(L?.insertId)||Number(L?.numInsertedOrUpdatedRows);if(!Y)throw Object.assign(Error("order insert returned no id"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let W;if(G.payment)try{let Z=await X.insertInto("payments").values({...G.payment,order_id:Y,created_at:$,updated_at:$}).executeTakeFirst(),N=Number(Z?.insertId)||Number(Z?.numInsertedOrUpdatedRows);if(N)W=await X.selectFrom("payments").where("id","=",N).selectAll().executeTakeFirst()}catch(Z){if(Z?.message?.includes("UNIQUE constraint")||Z?.message?.includes("Duplicate entry"))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(Z,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(G.inventory&&G.inventory.length>0)for(let Z=0;Z<G.inventory.length;Z++){let{id:N,delta:x}=G.inventory[Z];if(!Number.isFinite(x)||x===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});let H=await X.updateTable("products").set({inventory_count:d6`inventory_count + ${x}`,updated_at:$}).where("id","=",N).where(d6`inventory_count + ${x}`,">=",0).execute();if(!Number(H?.numUpdatedRows??H?.[0]?.numUpdatedRows??H?.numAffectedRows??0))throw Object.assign(Error(`inventory adjust failed for product ${N}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(G.idempotencyKey)try{await X.insertInto("order_idempotency").values({idempotency_key:G.idempotencyKey,order_id:Y,created_at:$}).execute()}catch(Z){if(Z?.message?.includes("UNIQUE constraint")||Z?.message?.includes("Duplicate entry"))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!(Z?.message?.includes("no such table")||Z?.message?.includes("doesn't exist")))throw Z}let M=await X.selectFrom("orders").where("id","=",Y).selectAll().executeTakeFirst();if(!M)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:M,payment:W}});if(kJ(J.order),J.payment)c(J.order,J.payment);return{ok:!0,order:J.order,payment:J.payment}}catch(J){if(J?.__placeFail)return{ok:!1,reason:J.reason,failedAt:J.failedAt,error:J};throw J}}import{db as wG}from"@stacksjs/database";import{formatDate as CG}from"@stacksjs/orm";async function r6(G,J){if(!await h(G))throw Error(`Order with ID ${G} not found`);try{return await wG.updateTable("orders").set({...J,updated_at:CG(new Date)}).where("id","=",G).execute(),await h(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update order: ${$.message}`);throw $}}async function e6(G,J){let X=await h(G);if(!X)throw Error(`Order with ID ${G} not found`);let $=X.status??"PENDING";if(!jJ($,J))throw Error(`[commerce/orders] illegal status transition ${$} \u2192 ${J}`);try{await wG.updateTable("orders").set({status:J,updated_at:CG(new Date)}).where("id","=",G).execute();let K=await h(G);if(K)wJ(J,K);return K}catch(K){if(K instanceof Error)throw TypeError(`Failed to update order status: ${K.message}`);throw K}}async function J$(G,J,X){let $=await h(G);if(!$)throw Error(`Order with ID ${G} not found`);let K={updated_at:CG(new Date)};if(J!==void 0)K.delivery_address=J;if(X!==void 0)K.estimated_delivery_time=X;if(Object.keys(K).length===1)return $;try{return await wG.updateTable("orders").set(K).where("id","=",G).execute(),await h(G)}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery information: ${L.message}`);throw L}}import{db as JJ}from"@stacksjs/database";import{formatDate as _J}from"@stacksjs/orm";async function _G(G){let J=await JJ.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!J)return null;return await JJ.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}var G$=!1;async function IG(G,J){try{return await J.insertInto("stripe_webhook_events").values({event_id:G,processed_at:_J(new Date)}).execute(),!0}catch(X){if(X?.message?.includes("UNIQUE constraint")||X?.message?.includes("Duplicate entry"))return!1;if(X?.message?.includes("no such table")||X?.message?.includes("doesn't exist")){if(!G$)G$=!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 X}}async function fG(G){let X=G.data.object?.id;if(!X)return;await JJ.transaction(async(K)=>{if(!await IG(G.id,K))return;let Y=await K.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!Y)return;let W=_J(new Date);await K.updateTable("payments").set({status:"succeeded",updated_at:W}).where("id","=",Y.id).execute();let M=await K.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(M&&M.status==="PENDING")await K.updateTable("orders").set({status:"PROCESSING",updated_at:W}).where("id","=",M.id).execute()});let $=await _G(X);if($)await c($)}async function vG(G){let J=G.data.object,X=J?.id;if(!X)return;let K=J?.last_payment_error?.message??"payment failed";await JJ.transaction(async(Y)=>{if(!await IG(G.id,Y))return;let M=await Y.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!M)return;let Z=_J(new Date);await Y.updateTable("payments").set({status:"failed",failure_reason:K,updated_at:Z}).where("id","=",M.id).execute();let N=await Y.selectFrom("orders").where("id","=",M.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await Y.updateTable("orders").set({status:"CANCELLED",updated_at:Z}).where("id","=",N.id).execute()});let L=await _G(X);if(L)await MJ(L,K)}async function hG(G){let J=G.data.object,X=J?.payment_intent;if(!X)return;let $=J?.amount_refunded??0;await JJ.transaction(async(L)=>{if(!await IG(G.id,L))return;let W=await L.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!W)return;let M=_J(new Date);await L.updateTable("payments").set({status:"refunded",refund_amount:$,updated_at:M}).where("id","=",W.id).execute();let Z=await L.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(Z&&Z.status!=="REFUNDED")await L.updateTable("orders").set({status:"REFUNDED",updated_at:M}).where("id","=",Z.id).execute()});let K=await _G(X);if(K)await NJ(K,$)}async function X$(){let G=await import("@stacksjs/payments").catch(()=>null);if(!G)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:J,onCharge:X}=G;if(typeof J!=="function"||typeof X!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return J({succeeded:fG,failed:vG}),X({refunded:hG}),()=>{}}import{db as $$}from"@stacksjs/database";async function o9(G){if(G.length===0)return new Map;let J=await $$.selectFrom("products").where("id","in",G).select(["id","price"]).execute(),X=new Map;for(let $ of J){let K=Number($.price);if(Number.isFinite(K))X.set($.id,Math.round(K))}return X}async function i9(G){try{let J=await $$.selectFrom("tax_rates").where("id","=",G).select(["rate"]).executeTakeFirst(),X=Number(J?.rate??0);return Number.isFinite(X)?X:0}catch{return 0}}async function K$(G){let J=G.items.map((B)=>B.productId),X=await o9(J),$=G.taxRateId!=null?await i9(G.taxRateId):0,K=0,L=[];for(let B of G.items){let F=B.unitPriceCents??X.get(B.productId)??0,A=Math.round(F*B.quantity);K+=A,L.push({productId:B.productId,quantity:B.quantity,unitPriceCents:F,lineCents:A})}let Y=Math.max(0,G.discountCents??0),W=Math.max(0,K-Y),M=Math.round(W*$),Z=Math.max(0,G.shippingCents??0),N=K-Y+M+Z,x=G.maxDriftCents??5,H=!1,E=0;if(G.clientTotalCents!=null)E=Math.abs(N-G.clientTotalCents),H=E>x;return{subtotalCents:K,discountCents:Y,taxCents:M,shippingCents:Z,totalCents:N,resolvedItems:L,priceChanged:H,diffCents:E}}import{db as IJ}from"@stacksjs/database";function L$(G,J={}){let X=G.length;if(X<=1)return{ok:!0,count:X};if(!J.allowMultiple)return{ok:!1,count:X,reason:"multiple-not-allowed"};let $=J.maxStacked??Number.POSITIVE_INFINITY;if(X>$)return{ok:!1,count:X,reason:"exceeds-max-stacked"};return{ok:!0,count:X}}async function gG(G,J){if(!Number.isFinite(J)||J<=0)return{ok:!1,productId:G,quantity:J,reason:"non-positive"};let X;try{X=await IJ.selectFrom("products").where("id","=",G).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:G,quantity:J}}if(!X)return{ok:!1,productId:G,quantity:J,reason:"product-missing"};let $=X.min_order_qty??null,K=X.max_order_qty??null;if($!=null&&J<$)return{ok:!1,productId:G,quantity:J,reason:"below-min",bound:$};if(K!=null&&J>K)return{ok:!1,productId:G,quantity:J,reason:"above-max",bound:K};return{ok:!0,productId:G,quantity:J}}async function Y$(G){for(let X of G){let $=await gG(X.productId,X.quantity);if(!$.ok)return $}let J=G[G.length-1]??{productId:0,quantity:0};return{ok:!0,productId:J.productId,quantity:J.quantity}}async function W$(G={}){let J=G.olderThanDays??30,X=G.limit??1000,K=new Date(Date.now()-J*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let L=await IJ.deleteFrom("carts").where("updated_at","<",K).where("id","in",(W)=>W.selectFrom("carts").select("id").where("updated_at","<",K).limit(X)).execute();return{deleted:Number(L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??0),cutoffAt:K}}catch{try{let L=await IJ.selectFrom("carts").where("updated_at","<",K).select(["id"]).limit(X).execute();if(L.length===0)return{deleted:0,cutoffAt:K};let Y=L.map((Z)=>Z.id),W=await IJ.deleteFrom("carts").where("id","in",Y).execute();return{deleted:Number(W?.numDeletedRows??W?.[0]?.numDeletedRows??W?.affectedRows??L.length),cutoffAt:K}}catch{return{deleted:0,cutoffAt:K}}}}var DG={};Q(DG,{update:()=>z$,store:()=>A$,fetchPaymentStatsByMethod:()=>F$,fetchPaymentStats:()=>H$,fetchMonthlyPaymentTrends:()=>Q$,fetchById:()=>xJ,fetchAll:()=>x$,destroy:()=>M$,bulkDestroy:()=>N$});import{db as Z$}from"@stacksjs/database";async function M$(G){try{let J=await Z$.deleteFrom("payments").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payment: ${J.message}`);throw J}}async function N$(G){if(!G.length)return 0;try{let J=await Z$.deleteFrom("payments").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payments: ${J.message}`);throw J}}import{db as p}from"@stacksjs/database";import{formatDate as w}from"@stacksjs/orm";async function x$(){return await p.selectFrom("payments").selectAll().execute()}async function xJ(G){return await p.selectFrom("payments").selectAll().where("id","=",G).executeTakeFirst()}async function H$(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await p.selectFrom("payments").select((I)=>[I.fn.count("id").as("transaction_count"),I.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").executeTakeFirst(),Y=await p.selectFrom("payments").select((I)=>[I.fn.count("id").as("transaction_count"),I.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(K)).where("created_at","<=",w($)).where("status","=","completed").executeTakeFirst(),W=await p.selectFrom("payments").select((I)=>I.fn.count("id").as("count")).where("created_at",">=",w(X)).where("created_at","<=",w(J)).executeTakeFirst(),M=Number(L?.transaction_count||0),Z=Number(L?.total_revenue||0),N=M>0?Z/M:0,x=Number(Y?.transaction_count||0),H=Number(Y?.total_revenue||0),E=x>0?H/x:0,B=M-x,F=Z-H,A=N-E,_=x>0?B/x*100:M>0?100:0,m=H>0?F/H*100:Z>0?100:0,b=E>0?A/E*100:N>0?100:0,a=Number(W?.count||0),R=a>0?M/a*100:0;return{total_transactions:M,total_revenue:Z,average_transaction:N,successful_rate:R,comparison:{transactions:{difference:B,percentage:Math.abs(_),is_increase:B>=0},revenue:{difference:F,percentage:Math.abs(m),is_increase:F>=0},average:{difference:A,percentage:Math.abs(b),is_increase:A>=0}}}}async function F$(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await p.selectFrom("payments").select((W)=>[W.fn.count("id").as("total_count"),W.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").executeTakeFirst(),K=Number($?.total_count||0),L=await p.selectFrom("payments").select(["method",(W)=>W.fn.count("id").as("count"),(W)=>W.fn.sum("amount").as("revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").groupBy("method").execute(),Y={};return L.forEach((W)=>{let M=Number(W.count||0),Z=Number(W.revenue||0),N=K>0?M/K*100:0;Y[W.method]={count:M,revenue:Z,percentage_of_total:N}}),Y}async function Q$(){let G=new Date,J=new Date(G);J.setMonth(G.getMonth()-11),J.setDate(1);let X=await p.selectFrom("payments").selectAll().where("created_at",">=",w(J)).where("status","=","completed").execute(),$={};for(let L of X){let Y=L.created_at?new Date(L.created_at):new Date,W=Y.getFullYear(),M=Y.getMonth()+1,Z=`${W}-${String(M).padStart(2,"0")}`;if(!$[Z])$[Z]={year:W,month:M,transactions:0,revenue:0};$[Z].transactions++,$[Z].revenue+=Number(L.amount||0)}return Object.keys($).sort().map((L)=>{let Y=$[L],W=Y.transactions,M=Y.revenue,Z=W>0?M/W:0;return{month:new Date(Y.year,Y.month-1,1).toLocaleString("default",{month:"short"}),year:Y.year,transactions:W,revenue:M,average:Z}})}var{randomUUIDv7:s9}=globalThis.Bun;import{db as V$}from"@stacksjs/database";import{HttpError as B$}from"@stacksjs/error-handling";import{isUniqueViolation as d9}from"@stacksjs/orm";async function A$(G){let J={...G,status:G.status||"PENDING",currency:G.currency||"USD",uuid:s9()};try{let X=await V$.insertInto("payments").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if($)return await V$.selectFrom("payments").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof B$)throw X;if(d9(X))throw new B$(409,"A payment with this transaction ID already exists");if(X instanceof Error){if(X.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${X.message}`)}throw X}}import{db as a9}from"@stacksjs/database";import{formatDate as t9}from"@stacksjs/orm";async function z$(G,J){if(!await xJ(G))throw Error(`Payment with ID ${G} not found`);try{return await a9.updateTable("payments").set({...J,updated_at:t9(new Date)}).where("id","=",G).execute(),await xJ(G)}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry")&&$.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${$.message}`)}throw $}}var oG={};Q(oG,{variants:()=>pJ,units:()=>DJ,reviews:()=>yJ,manufacturers:()=>gJ,items:()=>hJ,default:()=>LK,categories:()=>vJ});var vJ={};Q(vJ,{updateParent:()=>y$,updateDisplayOrder:()=>h$,updateActiveStatus:()=>g$,update:()=>v$,store:()=>mG,removeChildCategories:()=>w$,remove:()=>j$,findOrCreateByName:()=>f$,fetchStats:()=>S$,fetchRootCategories:()=>R$,fetchChildCategories:()=>U$,fetchCategoryTree:()=>P$,fetchByName:()=>E$,fetchById:()=>U,fetchByDisplayOrder:()=>T$,fetchAll:()=>pG,fetchActive:()=>O$,deactivateChildCategories:()=>_$,deactivate:()=>C$,compareCategoryGrowth:()=>q$,bulkRemove:()=>k$});import{db as u}from"@stacksjs/database";import{db as P}from"@stacksjs/database";import{formatDate as HJ}from"@stacksjs/orm";async function pG(){return await P.selectFrom("categories").selectAll().execute()}async function U(G){return await P.selectFrom("categories").where("id","=",G).selectAll().executeTakeFirst()}async function E$(G){return await P.selectFrom("categories").where("name","=",G).selectAll().executeTakeFirst()}async function O$(){return await P.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function R$(){return await P.selectFrom("categories").where("parent_category_id","is",null).where("is_active","=",!0).selectAll().execute()}async function U$(G){return await P.selectFrom("categories").where("parent_category_id","=",G).where("is_active","=",!0).selectAll().execute()}async function T$(G=!0){let J=P.selectFrom("categories").where("is_active","=",!0).selectAll();if(G)return await J.orderBy("display_order","asc").execute();else return await J.orderBy("display_order","desc").execute()}async function S$(){let G=await P.selectFrom("categories").select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),J=await P.selectFrom("categories").where("is_active","=",!0).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("categories").where("parent_category_id","is",null).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),$=await P.selectFrom("categories").where("image_url","is not",null).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),K=new Date;K.setDate(K.getDate()-30);let L=HJ(K),Y=await P.selectFrom("categories").where("created_at",">=",L).selectAll().limit(5).execute(),W=await P.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").where("c.parent_category_id","is not",null).select(["c.parent_category_id","parent.name as parent_name",(M)=>M.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(G?.count||0),active:Number(J?.count||0),root_categories:Number(X?.count||0),child_categories:Number(G?.count||0)-Number(X?.count||0),with_images:Number($?.count||0),recently_added:Y,top_parent_categories:W.map((M)=>({id:String(M.parent_category_id||""),name:String(M.parent_name||""),child_count:Number(M.child_count)}))}}async function q$(G=30){let J=new Date,X=HJ(J),$=new Date;$.setDate(J.getDate()-G);let K=HJ($),L=new Date($);L.setDate(L.getDate()-1);let Y=HJ(L),W=new Date(L);W.setDate(L.getDate()-G);let M=HJ(W),Z=await P.selectFrom("categories").select((F)=>F.fn.count("id").as("count")).where("created_at",">=",K).where("created_at","<=",X).executeTakeFirst(),N=await P.selectFrom("categories").select((F)=>F.fn.count("id").as("count")).where("created_at",">=",M).where("created_at","<=",Y).executeTakeFirst(),x=Number(Z?.count||0),H=Number(N?.count||0),E=x-H,B=H!==0?E/H*100:x>0?100:0;return{current_period:x,previous_period:H,difference:E,percentage_change:B,days_range:G}}async function P$(){let G=await pG(),J=new Map;G.forEach((K)=>{J.set(K.id,{...K,children:[]})});let X=[];G.forEach((K)=>{let L=J.get(K.id);if(K.parent_category_id){let Y=J.get(K.parent_category_id);if(Y)Y.children.push(L)}else X.push(L)}),X.sort((K,L)=>K.display_order-L.display_order);let $=(K)=>{K.sort((L,Y)=>L.display_order-Y.display_order),K.forEach((L)=>{if(L.children.length>0)$(L.children)})};return $(X),X}async function j$(G){if(!await U(G))throw Error(`Category with ID ${G} not found`);return!!await u.deleteFrom("categories").where("id","=",G).executeTakeFirst()}async function k$(G){if(!G.length)return 0;let J=await u.deleteFrom("categories").where("id","in",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}async function w$(G){let J=await u.deleteFrom("categories").where("parent_category_id","=",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}async function C$(G){if(!await U(G))throw Error(`Category with ID ${G} not found`);return!!await u.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",G).executeTakeFirst()}async function _$(G){let J=await u.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",G).execute();return Number(J.length)||0}import{db as I$}from"@stacksjs/database";import{slug as r9}from"@stacksjs/strings";async function mG(G){try{let J={...G,slug:G.name?.toLowerCase().replace(/\s+/g,"-")||"",categorizable_type:"product",display_order:0},X=await I$.insertInto("categories").values(J).executeTakeFirst();if(!X)throw Error("Failed to create category");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await U($);if(!K)throw Error("Failed to create category");return K}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry")&&J.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to create category: ${J.message}`)}throw J}}async function f$(G){if(!G.name)throw Error("Name is required");let J=await I$.selectFrom("categories").selectAll().where("name","=",G.name).executeTakeFirst();if(J)return J;let X={name:G.name,slug:r9(G.name),is_active:G.is_active??!0,categorizable_type:G.categorizable_type??"default",display_order:0};return await mG(X)}import{db as FJ}from"@stacksjs/database";import{formatDate as fJ}from"@stacksjs/orm";async function v$(G,J){await J.validate();let X=await U(G);if(!X)throw Error(`Category with ID ${G} not found`);let $={name:J.get("name"),description:J.get("description"),imageUrl:J.get("imageUrl"),isActive:J.get("isActive"),parentCategoryId:J.get("parentCategoryId"),displayOrder:J.get("displayOrder"),updated_at:fJ(new Date)};if(Object.keys($).length===0)return X;try{return await FJ.updateTable("categories").set($).where("id","=",G).execute(),await U(G)}catch(K){if(K instanceof Error){if(K.message.includes("Duplicate entry")&&K.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to update category: ${K.message}`)}throw K}}async function h$(G,J){if(!await U(G))throw Error(`Category with ID ${G} not found`);try{return await FJ.updateTable("categories").set({display_order:J,updated_at:fJ(new Date)}).where("id","=",G).execute(),await U(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category display order: ${$.message}`);throw $}}async function g$(G,J){if(!await U(G))throw Error(`Category with ID ${G} not found`);try{return await FJ.updateTable("categories").set({is_active:J,updated_at:fJ(new Date)}).where("id","=",G).execute(),await U(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category active status: ${$.message}`);throw $}}async function y$(G,J){if(!await U(G))throw Error(`Category with ID ${G} not found`);if(J){let $=Number(J);if($===G)throw Error("A category cannot be its own parent");if(!await U($))throw Error(`Parent category with ID ${J} not found`);if(await e9(G,J))throw Error("This operation would create a circular reference in the category hierarchy")}try{let $={updated_at:fJ(new Date)};if(J===null)await FJ.updateTable("categories").set({...$,parent_category_id:void 0}).where("id","=",G).execute();else await FJ.updateTable("categories").set({...$,parent_category_id:J}).where("id","=",G).execute();return await U(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category parent: ${$.message}`);throw $}}async function e9(G,J){let X=Number(J),$=new Set;while(X){if($.has(X))return!0;if(X===G)return!0;$.add(X);let K=await U(X);if(!K||!K.parentCategoryId)return!1;X=Number(K.parentCategoryId)}return!1}var hJ={};Q(hJ,{updateInventory:()=>d$,updateAvailability:()=>s$,update:()=>i$,store:()=>n$,fetchTopProducts:()=>l$,fetchById:()=>g,fetchAll:()=>b$,destroy:()=>p$,bulkStore:()=>o$,bulkDestroy:()=>m$});import{db as D$}from"@stacksjs/database";async function p$(G){try{let J=await D$.deleteFrom("products").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product item: ${J.message}`);throw J}}async function m$(G){if(!G.length)return 0;try{let J=await D$.deleteFrom("products").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product items: ${J.message}`);throw J}}import{db as n}from"@stacksjs/database";async function g(G){let J=await n.selectFrom("products").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=null,$=null;if(J.manufacturer_id)X=await n.selectFrom("manufacturers").where("id","=",J.manufacturer_id).selectAll().executeTakeFirst();if(J.category_id)$=await n.selectFrom("categories").where("id","=",J.category_id).selectAll().executeTakeFirst();return{...J,manufacturer:X,category:$}}return}async function b$(){let G=await n.selectFrom("products").selectAll().execute(),J=G.map((Z)=>Z.manufacturer_id).filter((Z)=>Z!==null&&Z!==void 0),X=G.map((Z)=>Z.category_id).filter((Z)=>Z!==null&&Z!==void 0),$=n.selectFrom("manufacturers"),K=n.selectFrom("categories");if(J.length>0)$=$.where("id","in",J);if(X.length>0)K=K.where("id","in",X);let L=await $.selectAll().execute(),Y=await K.selectAll().execute(),W=L.reduce((Z,N)=>{return Z[N.id]=N,Z},{}),M=Y.reduce((Z,N)=>{return Z[N.id]=N,Z},{});return G.map((Z)=>({...Z,manufacturer:Z.manufacturer_id?W[Z.manufacturer_id]:null,category:Z.category_id?M[Z.category_id]:null}))}async function l$(G=5){try{return(await n.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",(X)=>X.fn.sum("order_items.quantity").as("units_sold"),(X)=>X.raw("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(G).execute()).map((X)=>({id:Number(X.id),name:String(X.name??"Unnamed product"),units_sold:Number(X.units_sold??0),revenue:Number(X.revenue??0),inventory_count:Number(X.inventory_count??0)}))}catch(J){if(J instanceof Error)throw TypeError(`Failed to fetch top products: ${J.message}`);throw J}}var{randomUUIDv7:c$}=globalThis.Bun;import{db as u$}from"@stacksjs/database";async function n$(G){try{let J={...G,uuid:c$()},X=await u$.insertInto("products").values(J).executeTakeFirst();if(!X)throw Error("Failed to create product item");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await g($);if(!K)throw Error("Failed to create product item");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product item: ${J.message}`);throw J}}async function o$(G){if(!G.length)return 0;let J=0;try{return await u$.transaction().execute(async(X)=>{for(let $ of G){let K={...$,uuid:c$()};await X.insertInto("products").values(K).execute(),J++}}),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product items in bulk: ${X.message}`);throw X}}import{db as bG,sql as _0}from"@stacksjs/database";import{formatDate as lG}from"@stacksjs/orm";async function i$(G,J){try{if(!G)throw Error("Product item ID is required for update");let X=await bG.updateTable("products").set({...J,updated_at:lG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product item");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item: ${X.message}`);throw X}}async function s$(G,J){if(!await g(G))throw Error(`Product item with ID ${G} not found`);try{return await bG.updateTable("products").set({is_available:J,updated_at:lG(new Date)}).where("id","=",G).execute(),await g(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update product item availability: ${$.message}`);throw $}}async function d$(G,J){let X=await g(G);if(!X)throw Error(`Product item with ID ${G} not found`);let $={updated_at:lG(new Date)};if(J!==void 0)$.inventory_count=J;if(Object.keys($).length===1)return X;try{return await bG.updateTable("products").set($).where("id","=",G).execute(),await g(G)}catch(K){if(K instanceof Error)throw TypeError(`Failed to update inventory information: ${K.message}`);throw K}}var gJ={};Q(gJ,{updateFeaturedStatus:()=>H2,updateByUuid:()=>F2,update:()=>x2,store:()=>Z2,fetchWithProductCount:()=>K2,fetchFeatured:()=>X2,fetchByUuid:()=>G2,fetchById:()=>J2,fetchByCountry:()=>$2,fetchAll:()=>e$,destroy:()=>t$,bulkStore:()=>M2,bulkDestroy:()=>r$});import{db as a$}from"@stacksjs/database";async function t$(G){try{let J=await a$.deleteFrom("manufacturers").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function r$(G){if(!G.length)return 0;try{let J=await a$.deleteFrom("manufacturers").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}import{db as o}from"@stacksjs/database";function e$(){return o.selectFrom("manufacturers").selectAll().execute()}async function J2(G){return await o.selectFrom("manufacturers").where("id","=",G).selectAll().executeTakeFirst()}async function G2(G){return await o.selectFrom("manufacturers").where("uuid","=",G).selectAll().executeTakeFirst()}async function X2(G=10){return await o.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(G).execute()}async function $2(G,J={}){let X=J.page||1,$=J.limit||2,K=await o.selectFrom("manufacturers").select((M)=>M.fn.count("id").as("total")).where("country","=",G).executeTakeFirst(),L=Number(K?.total||0),Y=await o.selectFrom("manufacturers").selectAll().where("country","=",G).limit($).offset((X-1)*$).execute(),W=Math.ceil(L/$);return{data:Y,paging:{total_records:L,page:X,total_pages:W},next_cursor:X<W?X+1:null}}async function K2(G={}){let J=o.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(G.country)J=J.where("m.country","=",G.country);if(G.featured!==void 0)J=J.where("m.featured","=",G.featured);return J=J.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",(X)=>X.fn.count("p.id").as("product_count")]).groupBy("m.id"),J.execute()}var{randomUUIDv7:Y2}=globalThis.Bun;import{db as W2}from"@stacksjs/database";import{HttpError as L2}from"@stacksjs/error-handling";import{isUniqueViolation as JK}from"@stacksjs/orm";async function Z2(G){try{let J={...G,uuid:Y2(),featured:G.featured??!1},X=await W2.insertInto("manufacturers").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create manufacturer");return X}catch(J){if(J instanceof L2)throw J;if(JK(J))throw new L2(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to create manufacturer: ${J.message}`);throw J}}async function M2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:Y2(),featured:X.featured??!1};await W2.insertInto("manufacturers").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${X.message}`);throw X}}import{db as cG}from"@stacksjs/database";import{HttpError as N2}from"@stacksjs/error-handling";import{formatDate as uG,isUniqueViolation as GK}from"@stacksjs/orm";async function x2(G,J){try{if(!G)throw Error("Manufacturer ID is required for update");let X=await cG.updateTable("manufacturers").set({...J,updated_at:uG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error(`Manufacturer with ID ${G} not found`);return X}catch(X){if(X instanceof N2)throw X;if(GK(X))throw new N2(409,"A manufacturer with this name already exists");if(X instanceof Error)throw Error(`Failed to update manufacturer: ${X.message}`);throw X}}async function H2(G,J){try{let X=await cG.updateTable("manufacturers").set({featured:J,updated_at:uG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update manufacturer featured status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${X.message}`);throw X}}async function F2(G,J){try{let X=await cG.updateTable("manufacturers").set({...J,updated_at:uG(new Date)}).where("uuid","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update manufacturer");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update manufacturer: ${X.message}`);throw X}}var yJ={};Q(yJ,{updateVotes:()=>j2,update:()=>P2,store:()=>T2,fetchMostHelpfulByProductId:()=>U2,fetchByUserId:()=>O2,fetchByProductId:()=>E2,fetchById:()=>A2,fetchApprovedByProductId:()=>R2,fetchAll:()=>z2,destroy:()=>V2,bulkDestroy:()=>B2});import{db as Q2}from"@stacksjs/database";async function V2(G){try{let J=await Q2.deleteFrom("reviews").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function B2(G){if(!G.length)return 0;try{let J=await Q2.deleteFrom("reviews").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}import{db as GJ}from"@stacksjs/database";async function A2(G){return await GJ.selectFrom("reviews").where("id","=",G).selectAll().executeTakeFirst()}async function z2(){return await GJ.selectFrom("reviews").selectAll().execute()}async function E2(G){return await GJ.selectFrom("reviews").where("product_id","=",G).selectAll().execute()}async function O2(G){return await GJ.selectFrom("reviews").where("customer_id","=",G).selectAll().execute()}async function R2(G){return await GJ.selectFrom("reviews").where("product_id","=",G).where("is_approved","=",!0).selectAll().execute()}async function U2(G){return await GJ.selectFrom("reviews").where("product_id","=",G).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:XK}=globalThis.Bun;import{db as $K}from"@stacksjs/database";async function T2(G){try{let J={...G,uuid:XK(),is_verified_purchase:G.is_verified_purchase??!1,is_approved:G.is_approved??!1,helpful_votes:G.helpful_votes??0,unhelpful_votes:G.unhelpful_votes??0,is_featured:G.is_featured??!1},X=await $K.insertInto("reviews").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create review");return X}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${J.message}`)}throw J}}import{db as S2}from"@stacksjs/database";import{formatDate as q2}from"@stacksjs/orm";async function P2(G,J){try{if(!G)throw Error("Review ID is required for update");let X=await S2.updateTable("reviews").set({...J,updated_at:q2(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update review");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review: ${X.message}`);throw X}}async function j2(G,J,X=!0){try{let $=J==="helpful"?"helpful_votes":"unhelpful_votes",K=X?`COALESCE("${$}", 0) + 1`:`MAX(COALESCE("${$}", 0) - 1, 0)`,L=await S2.unsafe(`UPDATE "reviews" SET "${$}" = ${K}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[q2(new Date),G]).execute(),Y=Array.isArray(L)?L[0]:L;if(!Y)throw Error("Failed to update review votes");return Y}catch($){if($ instanceof Error)throw TypeError(`Failed to update review votes: ${$.message}`);throw $}}var DJ={};Q(DJ,{updateDefaultStatus:()=>b2,update:()=>p2,store:()=>h2,getDefaultUnit:()=>D2,formatUnitOptions:()=>y2,fetchById:()=>I2,fetchAll:()=>f2,destroy:()=>w2,bulkUpdate:()=>m2,bulkStore:()=>g2,bulkDestroy:()=>C2});import{db as k2}from"@stacksjs/database";async function w2(G){try{let J=await k2.deleteFrom("product_units").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product unit: ${J.message}`);throw J}}async function C2(G){if(!G.length)return 0;try{let J=await k2.deleteFrom("product_units").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product units: ${J.message}`);throw J}}import{db as _2}from"@stacksjs/database";async function I2(G){return await _2.selectFrom("product_units").where("id","=",G).selectAll().executeTakeFirst()}async function f2(){return await _2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:v2}=globalThis.Bun;import{db as XJ}from"@stacksjs/database";async function h2(G){try{let J={...G,uuid:v2()},X=await XJ.insertInto("product_units").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(J.is_default)await XJ.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",X.id).execute();return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product unit: ${J.message}`);throw J}}async function g2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:v2()},K=await XJ.insertInto("product_units").values($).returningAll().executeTakeFirst();if($.is_default&&K)await XJ.updateTable("product_units").set({is_default:!1}).where("type","=",$.type).where("id","!=",K.id).execute();J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product units in bulk: ${X.message}`);throw X}}function y2(G){try{let J=XJ.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(G)J=J.where("type","=",G);return J=J.orderBy("name"),J.execute().then((X)=>X.map(($)=>({id:String($.id),name:$.name,abbreviation:$.abbreviation,is_default:$.is_default})))}catch(J){if(J instanceof Error)throw TypeError(`Failed to format unit options: ${J.message}`);throw J}}async function D2(G){try{return await XJ.selectFrom("product_units").selectAll().where("type","=",G).where("is_default","=",!0).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get default unit: ${J.message}`);throw J}}import{db as i}from"@stacksjs/database";import{formatDate as nG}from"@stacksjs/orm";async function p2(G,J){try{if(!G)throw Error("Product unit ID is required for update");let X=await i.updateTable("product_units").set({...J,updated_at:nG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product unit");if(J.is_default===!0&&J.type)await i.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",G).execute();return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product unit: ${X.message}`);throw X}}async function m2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $=X;if(!$.id)continue;let K=$.data&&typeof $.data==="object"?$.data:{...$};delete K.id;let L=await i.updateTable("product_units").set({...K,updated_at:nG(new Date)}).where("id","=",$.id).executeTakeFirst(),Y=K;if(Y.is_default===!0&&Y.type)await i.updateTable("product_units").set({is_default:!1}).where("type","=",Y.type).where("id","!=",$.id).execute();if(Number(L.numUpdatedRows)>0)J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product units in bulk: ${X.message}`);throw X}}async function b2(G,J){try{let X=await i.selectFrom("product_units").select("type").where("id","=",G).executeTakeFirst();if(!X)return!1;let $=await i.updateTable("product_units").set({is_default:J,updated_at:nG(new Date)}).where("id","=",G).executeTakeFirst();if(J&&X.type)await i.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",G).execute();return Number($.numUpdatedRows)>0}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product unit default status: ${X.message}`);throw X}}var pJ={};Q(pJ,{update:()=>X4,store:()=>a2,generateVariantCombinations:()=>e2,formatVariantOptions:()=>r2,fetchById:()=>o2,fetchAll:()=>i2,destroy:()=>c2,bulkUpdate:()=>$4,bulkStore:()=>t2,bulkDestroy:()=>u2});import{db as l2}from"@stacksjs/database";async function c2(G){try{let J=await l2.deleteFrom("product_variants").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variant: ${J.message}`);throw J}}async function u2(G){if(!G.length)return 0;try{let J=await l2.deleteFrom("product_variants").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variants: ${J.message}`);throw J}}import{db as n2}from"@stacksjs/database";async function o2(G){return await n2.selectFrom("product_variants").where("id","=",G).selectAll().executeTakeFirst()}async function i2(){return await n2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:s2}=globalThis.Bun;import{db as d2}from"@stacksjs/database";async function a2(G){try{let J={...G,uuid:s2()},X=await d2.insertInto("product_variants").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product variant");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variant: ${J.message}`);throw J}}async function t2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:s2()};await d2.insertInto("product_variants").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${X.message}`);throw X}}function r2(G){if(!G||!G.length)return JSON.stringify([]);let J=G.map((X)=>X.trim()).filter(Boolean);return JSON.stringify(J)}function e2(G){let J=Object.keys(G);if(!J.length)return[];function X($,K){if($===J.length)return[K];let L=J[$],Y=G[L]??[],W=[];for(let M of Y){let Z={...K,[L]:M};W.push(...X($+1,Z))}return W}return X(0,{})}import{db as J4}from"@stacksjs/database";import{formatDate as G4}from"@stacksjs/orm";async function X4(G,J){try{let X=await J4.updateTable("product_variants").set({...J,updated_at:G4(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product variant");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product variant: ${X.message}`);throw X}}async function $4(G){if(!G.length)return 0;let J=0;try{for(let X of G){if(!X.id)continue;let $=await J4.updateTable("product_variants").set({...X,updated_at:G4(new Date)}).where("id","=",X.id).executeTakeFirst();if(Number($.numUpdatedRows)>0)J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${X.message}`);throw X}}var KK={categories:vJ,items:hJ,manufacturers:gJ,reviews:yJ,units:DJ,variants:pJ},LK=KK;var dG={};Q(dG,{updateStatus:()=>V4,updatePrintJob:()=>B4,update:()=>Q4,store:()=>H4,fetchById:()=>Z4,fetchAll:()=>M4,destroy:()=>L4,bulkStore:()=>F4,bulkDestroy:()=>Y4});import{db as K4}from"@stacksjs/database";async function L4(G){try{let J=await K4.deleteFrom("receipts").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print log: ${J.message}`);throw J}}async function Y4(G){if(!G.length)return 0;try{let J=await K4.deleteFrom("receipts").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete receipts: ${J.message}`);throw J}}import{db as W4}from"@stacksjs/database";async function Z4(G){return await W4.selectFrom("receipts").where("id","=",G).selectAll().executeTakeFirst()}async function M4(){return await W4.selectFrom("receipts").selectAll().execute()}var{randomUUIDv7:N4}=globalThis.Bun;import{db as x4}from"@stacksjs/database";async function H4(G){try{let J={...G,uuid:N4()},X=await x4.insertInto("receipts").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipt: ${J.message}`);throw J}}async function F4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:N4()})),X=await x4.insertInto("receipts").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${J.message}`);throw J}}import{db as iG}from"@stacksjs/database";import{formatDate as sG}from"@stacksjs/orm";async function Q4(G,J){try{if(!G)throw Error("Receipt ID is required for update");let X=await iG.updateTable("receipts").set({...J,updated_at:sG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update receipt");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt: ${X.message}`);throw X}}async function V4(G,J){try{let X=await iG.updateTable("receipts").set({status:J,updated_at:sG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update receipt status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt status: ${X.message}`);throw X}}async function B4(G,J,X,$){try{let K={updated_at:sG(new Date)};if(J!==void 0)K.size=J;if(X!==void 0)K.pages=X;if($!==void 0)K.duration=$;let L=await iG.updateTable("receipts").set(K).where("id","=",G).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update receipt job information");return L}catch(K){if(K instanceof Error)throw TypeError(`Failed to update receipt job information: ${K.message}`);throw K}}var WX={};Q(WX,{zones:()=>ZG,routes:()=>bJ,rates:()=>KG,methods:()=>rJ,licenses:()=>sJ,drivers:()=>nJ,digital:()=>uJ,default:()=>ZK});var bJ={};Q(bJ,{updateStops:()=>k4,updateMetrics:()=>w4,updateLastActive:()=>P4,update:()=>j4,store:()=>q4,fetchById:()=>O4,fetchByDriver:()=>T4,fetchAll:()=>R4,fetchActive:()=>U4,destroy:()=>z4,bulkDestroy:()=>E4});import{db as A4}from"@stacksjs/database";async function z4(G){try{let J=await A4.deleteFrom("delivery_routes").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery route: ${J.message}`);throw J}}async function E4(G){if(!G.length)return 0;try{let J=await A4.deleteFrom("delivery_routes").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery routes: ${J.message}`);throw J}}import{db as mJ}from"@stacksjs/database";async function O4(G){return await mJ.selectFrom("delivery_routes").where("id","=",G).selectAll().executeTakeFirst()}async function R4(){return await mJ.selectFrom("delivery_routes").selectAll().execute()}async function U4(){return await mJ.selectFrom("delivery_routes").where("last_active","<=",new Date(Date.now()-86400000)).selectAll().execute()}async function T4(G){return await mJ.selectFrom("delivery_routes").where("driver","=",G).selectAll().execute()}var{randomUUIDv7:YK}=globalThis.Bun;import{db as S4}from"@stacksjs/database";async function q4(G){try{let J={...G,uuid:YK()},X=await S4.insertInto("delivery_routes").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create delivery route");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create delivery route: ${J.message}`);throw J}}async function P4(G){try{let J=await S4.updateTable("delivery_routes").set({last_active:new Date().toISOString(),updated_at:new Date().toISOString()}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update delivery route last active");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route last active: ${J.message}`);throw J}}import{db as aG}from"@stacksjs/database";import{formatDate as tG}from"@stacksjs/orm";async function j4(G,J){try{if(!G)throw Error("Delivery route ID is required for update");let X=await aG.updateTable("delivery_routes").set({...J,updated_at:tG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery route");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery route: ${X.message}`);throw X}}async function k4(G,J){try{let X=await aG.updateTable("delivery_routes").set({stops:J,updated_at:tG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery route stops");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery route stops: ${X.message}`);throw X}}async function w4(G,J,X){try{let $={updated_at:tG(new Date)};if(J!==void 0)$.delivery_time=J;if(X!==void 0)$.total_distance=X;let K=await aG.updateTable("delivery_routes").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update delivery metrics");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery metrics: ${$.message}`);throw $}}var uJ={};Q(uJ,{updateStatus:()=>b4,updateDeliverySettings:()=>l4,update:()=>m4,store:()=>D4,softDelete:()=>_4,fetchById:()=>cJ,fetchAll:()=>h4,destroy:()=>C4,bulkStore:()=>p4,bulkSoftDelete:()=>f4,bulkDestroy:()=>I4});import{db as lJ}from"@stacksjs/database";async function C4(G){try{let J=await lJ.deleteFrom("digital_deliveries").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital delivery: ${J.message}`);throw J}}async function _4(G){try{let J=await lJ.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${J.message}`);throw J}}async function I4(G){if(!G.length)return 0;try{let J=await lJ.deleteFrom("digital_deliveries").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${J.message}`);throw J}}async function f4(G){if(!G.length)return 0;try{let J=await lJ.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${J.message}`);throw J}}import{db as v4}from"@stacksjs/database";async function cJ(G){return await v4.selectFrom("digital_deliveries").where("id","=",G).selectAll().executeTakeFirst()}async function h4(){return await v4.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:g4}=globalThis.Bun;import{db as y4}from"@stacksjs/database";async function D4(G){try{let J={...G,uuid:g4()},X=await y4.insertInto("digital_deliveries").values(J).executeTakeFirst();if(!X)throw Error("Failed to create digital delivery");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await cJ($);if(!K)throw Error("Failed to create digital delivery");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital delivery: ${J.message}`);throw J}}async function p4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:g4()})),X=await y4.insertInto("digital_deliveries").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${J.message}`);throw J}}import{db as rG}from"@stacksjs/database";import{formatDate as eG}from"@stacksjs/orm";async function m4(G,J){try{if(!G)throw Error("Digital delivery ID is required for update");let X=await rG.updateTable("digital_deliveries").set({...J,updated_at:eG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update digital delivery");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update digital delivery: ${X.message}`);throw X}}async function b4(G,J){try{let X=await rG.updateTable("digital_deliveries").set({status:J,updated_at:eG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update digital delivery status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update digital delivery status: ${X.message}`);throw X}}async function l4(G,J,X,$,K){try{let L={updated_at:eG(new Date)};if(J!==void 0)L.download_limit=J;if(X!==void 0)L.expiry_days=X;if($!==void 0)L.requires_login=$;if(K!==void 0)L.automatic_delivery=K;let Y=await rG.updateTable("digital_deliveries").set(L).where("id","=",G).returningAll().executeTakeFirst();if(!Y)throw Error("Failed to update delivery settings");return Y}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery settings: ${L.message}`);throw L}}var nJ={};Q(nJ,{updateStatus:()=>e4,updateContact:()=>J7,update:()=>r4,store:()=>a4,fetchById:()=>QJ,fetchAll:()=>u4,destroy:()=>o4,bulkStore:()=>t4,bulkDestroy:()=>i4});import{db as n4}from"@stacksjs/database";import{db as c4}from"@stacksjs/database";async function QJ(G){return await c4.selectFrom("drivers").where("id","=",G).selectAll().executeTakeFirst()}async function u4(){return await c4.selectFrom("drivers").selectAll().execute()}async function o4(G){let J=await QJ(G);if(!J)throw Error(`Driver with ID ${G} not found`);try{return await n4.deleteFrom("drivers").where("id","=",G).execute(),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to delete driver: ${X.message}`);throw X}}async function i4(G){if(!G.length)return 0;let J=0;try{return await n4.transaction().execute(async(X)=>{for(let $ of G)if(await QJ($))await X.deleteFrom("drivers").where("id","=",$).execute(),J++}),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${X.message}`);throw X}}var{randomUUIDv7:s4}=globalThis.Bun;import{db as d4}from"@stacksjs/database";async function a4(G){try{let J={...G,uuid:s4()},X=await d4.insertInto("drivers").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create driver");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create driver: ${J.message}`);throw J}}async function t4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:s4()})),X=await d4.insertInto("drivers").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${J.message}`);throw J}}import{db as JX}from"@stacksjs/database";import{formatDate as GX}from"@stacksjs/orm";async function r4(G,J){try{if(!G)throw Error("Driver ID is required for update");let X=await JX.updateTable("drivers").set({...J,updated_at:GX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update driver");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update driver: ${X.message}`);throw X}}async function e4(G,J){try{let X=await JX.updateTable("drivers").set({status:J,updated_at:GX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update driver status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update driver status: ${X.message}`);throw X}}async function J7(G,J){try{let X={updated_at:GX(new Date)};if(J!==void 0)X.phone=J;let $=await JX.updateTable("drivers").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update contact information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update contact information: ${X.message}`);throw X}}var sJ={};Q(sJ,{updateStatus:()=>H7,updateExpiration:()=>F7,update:()=>x7,store:()=>M7,softDelete:()=>X7,fetchById:()=>iJ,fetchAll:()=>Y7,destroy:()=>G7,bulkStore:()=>N7,bulkSoftDelete:()=>K7,bulkDestroy:()=>$7});import{db as oJ}from"@stacksjs/database";async function G7(G){try{let J=await oJ.deleteFrom("license_keys").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license key: ${J.message}`);throw J}}async function X7(G){try{let J=await oJ.updateTable("license_keys").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license key: ${J.message}`);throw J}}async function $7(G){if(!G.length)return 0;try{let J=await oJ.deleteFrom("license_keys").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license keys: ${J.message}`);throw J}}async function K7(G){if(!G.length)return 0;try{let J=await oJ.updateTable("license_keys").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license keys: ${J.message}`);throw J}}import{db as L7}from"@stacksjs/database";async function iJ(G){return await L7.selectFrom("license_keys").where("id","=",G).selectAll().executeTakeFirst()}async function Y7(){return await L7.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:W7}=globalThis.Bun;import{db as Z7}from"@stacksjs/database";async function M7(G){try{let J={...G,uuid:W7()},X=await Z7.insertInto("license_keys").values(J).executeTakeFirst();if(!X)throw Error("Failed to create license key");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await iJ($);if(!K)throw Error("Failed to create license key");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create license key: ${J.message}`);throw J}}async function N7(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:W7()})),X=await Z7.insertInto("license_keys").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${J.message}`);throw J}}import{db as XX}from"@stacksjs/database";import{formatDate as $X}from"@stacksjs/orm";async function x7(G,J){try{if(!G)throw Error("License key ID is required for update");let X=await XX.updateTable("license_keys").set({...J,updated_at:$X(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update license key");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update license key: ${X.message}`);throw X}}async function H7(G,J){try{let X=await XX.updateTable("license_keys").set({status:J,updated_at:$X(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update license key status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update license key status: ${X.message}`);throw X}}async function F7(G,J){try{let X={updated_at:$X(new Date)};if(J!==void 0)X.expiry_date=J;let $=await XX.updateTable("license_keys").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update expiration information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update expiration information: ${X.message}`);throw X}}var rJ={};Q(rJ,{updateStatus:()=>q7,updatePricing:()=>P7,update:()=>S7,store:()=>O7,softDelete:()=>V7,getActiveShippingMethods:()=>T7,formatShippingOptions:()=>U7,fetchById:()=>s,fetchAll:()=>z7,destroy:()=>Q7,bulkStore:()=>R7,bulkSoftDelete:()=>A7,bulkDestroy:()=>B7});import{db as dJ}from"@stacksjs/database";async function Q7(G){try{let J=await dJ.deleteFrom("shipping_methods").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping method: ${J.message}`);throw J}}async function V7(G){try{let J=await dJ.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${J.message}`);throw J}}async function B7(G){if(!G.length)return 0;try{let J=await dJ.deleteFrom("shipping_methods").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping methods: ${J.message}`);throw J}}async function A7(G){if(!G.length)return 0;try{let J=await dJ.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${J.message}`);throw J}}import{db as aJ}from"@stacksjs/database";async function s(G){let J=await aJ.selectFrom("shipping_methods").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=await aJ.selectFrom("shipping_zones").where("shipping_method_id","=",G).selectAll().execute();return{...J,shippingZones:X}}return}async function z7(){let G=await aJ.selectFrom("shipping_methods").selectAll().execute(),J=G.map((L)=>L.id),X=aJ.selectFrom("shipping_zones");if(J.length>0)X=X.where("shipping_method_id","in",J);let K=(await X.selectAll().execute()).reduce((L,Y)=>{let W=Y.shipping_method_id;if(W!==null&&W!==void 0){if(!L[W])L[W]=[];L[W].push(Y)}return L},{});return G.map((L)=>({...L,shipping_zones:K[L.id]||[]}))}var{randomUUIDv7:E7}=globalThis.Bun;import{db as tJ}from"@stacksjs/database";async function O7(G){try{let J=G,X={name:G.name,description:G.description,base_rate:J.base_rate,free_shipping:J.free_shipping,status:G.status,uuid:E7()},$=await tJ.insertInto("shipping_methods").values(X).executeTakeFirst();if(!$)throw Error("Failed to create shipping method");let K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);return await s(K)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping method: ${J.message}`);throw J}}async function R7(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:E7()})),X=await tJ.insertInto("shipping_methods").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${J.message}`);throw J}}function U7(){try{return tJ.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping options: ${G.message}`);throw G}}async function T7(){try{return await tJ.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get active shipping methods: ${G.message}`);throw G}}import{db as KX}from"@stacksjs/database";import{formatDate as LX}from"@stacksjs/orm";async function S7(G,J){try{if(!G)throw Error("Shipping method ID is required for update");let X=await KX.updateTable("shipping_methods").set({...J,updated_at:LX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping method");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping method: ${X.message}`);throw X}}async function q7(G,J){try{let X=await KX.updateTable("shipping_methods").set({status:J,updated_at:LX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping method status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping method status: ${X.message}`);throw X}}async function P7(G,J,X){try{let $={updated_at:LX(new Date)};if(J!==void 0)$.base_rate=J;if(X!==void 0)$.free_shipping=X;let K=await KX.updateTable("shipping_methods").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update pricing information");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update pricing information: ${$.message}`);throw $}}var KG={};Q(KG,{validateZoneMatchesAddress:()=>h7,updateByZone:()=>s7,updateByMethod:()=>d7,update:()=>o7,store:()=>u7,resolveZoneForAddress:()=>GG,getShippingRatesByMethod:()=>y7,getRatesByZone:()=>f7,getRateByWeightAndZone:()=>YX,getRateByWeightAndAddress:()=>v7,formatShippingRateOptions:()=>g7,fetchById:()=>JG,fetchAll:()=>I7,destroyByZone:()=>w7,destroyByMethod:()=>C7,destroy:()=>j7,bulkUpdate:()=>i7,bulkStore:()=>n7,bulkDestroy:()=>k7});import{db as eJ}from"@stacksjs/database";async function j7(G){try{let J=await eJ.deleteFrom("shipping_rates").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rate: ${J.message}`);throw J}}async function k7(G){if(!G.length)return 0;try{let J=await eJ.deleteFrom("shipping_rates").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates: ${J.message}`);throw J}}async function w7(G){try{let J=await eJ.deleteFrom("shipping_rates").where("zone","=",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${J.message}`);throw J}}async function C7(G){try{let J=await eJ.deleteFrom("shipping_rates").where("method","=",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${J.message}`);throw J}}import{db as C}from"@stacksjs/database";async function JG(G){let J=await C.selectFrom("shipping_rates").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=null,$=null;if(J.shipping_zone_id)X=await C.selectFrom("shipping_zones").where("id","=",J.shipping_zone_id).selectAll().executeTakeFirst();if(J.shipping_method_id)$=await C.selectFrom("shipping_methods").where("id","=",J.shipping_method_id).selectAll().executeTakeFirst();return{...J,shipping_zone:X,shipping_method:$}}return}async function I7(){let G=await C.selectFrom("shipping_rates").selectAll().execute(),J=G.map((Z)=>Z.shipping_zone_id).filter((Z)=>Z!==null&&Z!==void 0),X=G.map((Z)=>Z.shipping_method_id).filter((Z)=>Z!==null&&Z!==void 0),$=C.selectFrom("shipping_zones"),K=C.selectFrom("shipping_methods");if(J.length>0)$=$.where("id","in",J);if(X.length>0)K=K.where("id","in",X);let L=await $.selectAll().execute(),Y=await K.selectAll().execute(),W=L.reduce((Z,N)=>{return Z[N.id]=N,Z},{}),M=Y.reduce((Z,N)=>{return Z[N.id]=N,Z},{});return G.map((Z)=>({...Z,shipping_zone:Z.shipping_zone_id?W[Z.shipping_zone_id]:[],shipping_method:Z.shipping_method_id?M[Z.shipping_method_id]:[]}))}async function f7(G){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",G).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${J.message}`);throw J}}async function YX(G,J){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).where("weight_from","<=",G).where("weight_to",">=",G).executeTakeFirst()}catch(X){if(X instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${X.message}`);throw X}}async function GG(G){if(!G?.countryCode)return null;try{let J=await C.selectFrom("shipping_zones").selectAll().where("countries","like",`%${G.countryCode}%`).where("status","=","active").execute();if(J.length===0)return null;let X=null;for(let $ of J){let K=1;if(G.region&&$.regions&&_7($.regions,G.region))K=2;if(G.postalCode&&$.postal_codes&&_7($.postal_codes,G.postalCode))K=3;if(!X||K>X.score)X={id:$.id,score:K}}return X?.id??null}catch{return null}}async function v7(G,J){let X=await GG(J);if(X==null)return;return YX(G,X)}async function h7(G,J){return await GG(J)===G}function _7(G,J){if(!G||!J)return!1;let X=J.trim().toUpperCase();for(let $ of G.split(/[,|;]/))if($.trim().toUpperCase()===X)return!0;return!1}async function g7(){try{return(await C.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((J)=>J.shipping_method_id!==null&&J.shipping_method_id!==void 0&&J.shipping_zone_id!==null&&J.shipping_zone_id!==void 0)}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping rate options: ${G.message}`);throw G}}async function y7(G){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",G).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${J.message}`);throw J}}var{randomUUIDv7:l7}=globalThis.Bun;import{db as c7}from"@stacksjs/database";import{db as VJ}from"@stacksjs/database";async function D7(){return await VJ.selectFrom("shipping_zones").selectAll().execute()}async function d(G){return await VJ.selectFrom("shipping_zones").where("id","=",G).selectAll().executeTakeFirst()}function p7(){try{return VJ.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping zone options: ${G.message}`);throw G}}async function m7(){try{return await VJ.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get active shipping zones: ${G.message}`);throw G}}async function b7(G){try{return await VJ.selectFrom("shipping_zones").selectAll().where("countries","like",`%${G}%`).where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${J.message}`);throw J}}async function u7(G){try{let J=await s(Number(G.shippingmethod_id)),X=await d(Number(G.shippingzone_id)),$={weightFrom:G.weightFrom,weightTo:G.weightTo,rate:G.rate,shippingmethod_id:J?.id,shippingzone_id:X?.id,uuid:l7()},K=await c7.insertInto("shipping_rates").values($).executeTakeFirst();if(!K)throw Error("Failed to create shipping rate");let L=Number(K.insertId)||Number(K.numInsertedOrUpdatedRows);return await JG(L)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping rate: ${J.message}`);throw J}}async function n7(G){if(!G.length)return 0;try{for(let $ of G){let K=await s(Number($.shippingmethod_id)),L=await d(Number($.shippingzone_id));if(!K)console.warn(`Shipping method with ID "${$.shippingmethod_id}" not found for bulk insert`);if(!L)console.warn(`Shipping zone with ID "${$.shippingzone_id}" not found for bulk insert`)}let J=G.map(($)=>({weightFrom:$.weightFrom,weightTo:$.weightTo,rate:$.rate,shippingmethod_id:$.shippingmethod_id,shippingzone_id:$.shippingzone_id,uuid:l7()})),X=await c7.insertInto("shipping_rates").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${J.message}`);throw J}}import{db as XG}from"@stacksjs/database";import{formatDate as $G}from"@stacksjs/orm";async function o7(G,J){try{if(!G)throw Error("Shipping rate ID is required for update");let X=await XG.updateTable("shipping_rates").set({...J,updated_at:$G(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping rate");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rate: ${X.message}`);throw X}}async function i7(G){if(!G.length)return 0;try{let J=0;for(let{id:X,data:$}of G){let K=await XG.updateTable("shipping_rates").set({...$,updated_at:$G(new Date)}).where("id","=",X).executeTakeFirst();if(Number(K.numUpdatedRows)>0)J++}return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${J.message}`);throw J}}async function s7(G,J){try{let X=await XG.updateTable("shipping_rates").set({...J,updated_at:$G(new Date)}).where("zone_id","=",G).executeTakeFirst();return Number(X.numUpdatedRows)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${X.message}`);throw X}}async function d7(G,J){try{let X=await XG.updateTable("shipping_rates").set({...J,updated_at:$G(new Date)}).where("method","=",G).executeTakeFirst();return Number(X.numUpdatedRows)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${X.message}`);throw X}}var ZG={};Q(ZG,{updateStatus:()=>L1,updateRegionsAndPostalCodes:()=>W1,updateCountries:()=>Y1,update:()=>K1,store:()=>X1,softDelete:()=>t7,getZonesByCountry:()=>b7,getActiveShippingZones:()=>m7,formatZoneOptions:()=>p7,fetchById:()=>d,fetchAll:()=>D7,destroy:()=>a7,bulkStore:()=>$1,bulkSoftDelete:()=>e7,bulkDestroy:()=>r7});import{db as LG}from"@stacksjs/database";async function a7(G){try{let J=await LG.deleteFrom("shipping_zones").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zone: ${J.message}`);throw J}}async function t7(G){try{let J=await LG.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${J.message}`);throw J}}async function r7(G){if(!G.length)return 0;try{let J=await LG.deleteFrom("shipping_zones").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zones: ${J.message}`);throw J}}async function e7(G){if(!G.length)return 0;try{let J=await LG.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${J.message}`);throw J}}var{randomUUIDv7:J1}=globalThis.Bun;import{db as G1}from"@stacksjs/database";async function X1(G){try{let J={...G,uuid:J1()},X=await G1.insertInto("shipping_zones").values(J).executeTakeFirst();if(!X)throw Error("Failed to create shipping zone");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await d($)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zone: ${J.message}`);throw J}}async function $1(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:J1()})),X=await G1.insertInto("shipping_zones").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${J.message}`);throw J}}import{db as YG}from"@stacksjs/database";import{formatDate as WG}from"@stacksjs/orm";async function K1(G,J){try{if(!G)throw Error("Shipping zone ID is required for update");let X=await YG.updateTable("shipping_zones").set({...J,updated_at:WG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone: ${X.message}`);throw X}}async function L1(G,J){try{let X=await YG.updateTable("shipping_zones").set({status:J,updated_at:WG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone status: ${X.message}`);throw X}}async function Y1(G,J){try{let X=await YG.updateTable("shipping_zones").set({countries:J,updated_at:WG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone countries");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${X.message}`);throw X}}async function W1(G,J,X){try{let $={updated_at:WG(new Date)};if(J!==void 0)$.regions=J;if(X!==void 0)$.postal_codes=X;let K=await YG.updateTable("shipping_zones").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update regions and postal codes");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${$.message}`);throw $}}var WK={digital:uJ,drivers:nJ,licenses:sJ,methods:rJ,rates:KG,routes:bJ,zones:ZG},ZK=WK;var NX={};Q(NX,{updateStatus:()=>E1,updateRate:()=>O1,update:()=>z1,store:()=>B1,fetchById:()=>H1,fetchAll:()=>F1,destroy:()=>M1,bulkStore:()=>A1,bulkDestroy:()=>N1});import{db as Z1}from"@stacksjs/database";async function M1(G){try{let J=await Z1.deleteFrom("tax_rates").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rate: ${J.message}`);throw J}}async function N1(G){if(!G.length)return 0;try{let J=await Z1.deleteFrom("tax_rates").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rates: ${J.message}`);throw J}}import{db as x1}from"@stacksjs/database";async function H1(G){return await x1.selectFrom("tax_rates").where("id","=",G).selectAll().executeTakeFirst()}async function F1(){return await x1.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:Q1}=globalThis.Bun;import{db as V1}from"@stacksjs/database";async function B1(G){try{let J={...G,uuid:Q1()},X=await V1.insertInto("tax_rates").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rate: ${J.message}`);throw J}}async function A1(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:Q1()})),X=await V1.insertInto("tax_rates").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${J.message}`);throw J}}import{db as ZX}from"@stacksjs/database";import{formatDate as MX}from"@stacksjs/orm";async function z1(G,J){try{if(!G)throw Error("Tax rate ID is required for update");let X=J,$=await ZX.updateTable("tax_rates").set({name:J.name,rate:J.rate,type:J.type,country:J.country,region:J.region,status:J.status,is_default:X.is_default,updated_at:MX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update tax rate");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update tax rate: ${X.message}`);throw X}}async function E1(G,J){try{let X=await ZX.updateTable("tax_rates").set({status:J,updated_at:MX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update tax rate status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update tax rate status: ${X.message}`);throw X}}async function O1(G,J){try{let X=await ZX.updateTable("tax_rates").set({rate:J,updated_at:MX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update rate information");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update rate information: ${X.message}`);throw X}}var FX={};Q(FX,{restaurant:()=>KJ,products:()=>NG,default:()=>NK});var NG={};Q(NG,{updateStatus:()=>l1,updatePartySize:()=>c1,update:()=>b1,store:()=>p1,fetchWaiting:()=>I1,fetchPurchasedBetweenDates:()=>C1,fetchNotifiedBetweenDates:()=>w1,fetchCountByStatus:()=>f1,fetchCountBySource:()=>q1,fetchCountByQuantity:()=>j1,fetchCountByDateGrouped:()=>g1,fetchCountByDate:()=>P1,fetchCountByAllQuantities:()=>k1,fetchCountBetweenDates:()=>h1,fetchConversionRates:()=>v1,fetchCancelledBetweenDates:()=>_1,fetchById:()=>T1,fetchAll:()=>S1,destroy:()=>R1,bulkStore:()=>m1,bulkDestroy:()=>U1});import{db as MG}from"@stacksjs/database";async function R1(G){try{let J=await MG.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst();if(!J)return;return await MG.deleteFrom("waitlist_products").where("id","=",G).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist product: ${J.message}`);throw J}}async function U1(G){if(!G.length)return 0;try{return(await MG.deleteFrom("waitlist_products").where("id","in",G).execute()).length||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${J.message}`);throw J}}import{db as T}from"@stacksjs/database";import{formatDate as O}from"@stacksjs/orm";async function T1(G){return await T.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst()}async function S1(){return await T.selectFrom("waitlist_products").selectAll().execute()}async function q1(G,J){let X=T.selectFrom("waitlist_products").select(["source",(K)=>K.fn.count("id").as("count")]).groupBy("source");if(G&&J){let K=O(G),L=O(J);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.execute()).reduce((K,{source:L,count:Y})=>{return K[L]=Y,K},{})}async function P1(G=new Date){let J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=O(J),K=O(X);return(await T.selectFrom("waitlist_products").select((Y)=>Y.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function j1(G){return(await T.selectFrom("waitlist_products").select((X)=>X.fn.count("id").as("count")).where("quantity","=",G).executeTakeFirst())?.count??0}async function k1(G,J){let X=T.selectFrom("waitlist_products").select(["quantity",(K)=>K.fn.count("id").as("count")]).groupBy("quantity");if(G&&J){let K=O(G),L=O(J);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.execute()).reduce((K,{quantity:L,count:Y})=>{return K[L]=Y,K},{})}async function w1(G,J){let X=O(G),$=O(J);return await T.selectFrom("waitlist_products").selectAll().where("notified_at",">=",X).where("notified_at","<=",$).where("notified_at","is not",null).execute()}async function C1(G,J){let X=O(G),$=O(J);return await T.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",X).where("purchased_at","<=",$).where("purchased_at","is not",null).execute()}async function _1(G,J){let X=O(G),$=O(J);return await T.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",X).where("cancelled_at","<=",$).where("cancelled_at","is not",null).execute()}async function I1(){return await T.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function f1(G,J,X){let $=T.selectFrom("waitlist_products").select((L)=>L.fn.count("id").as("count")).where("status","=",G);if(J&&X){let L=O(J),Y=O(X);$=$.where("created_at",">=",L).where("created_at","<=",Y)}return(await $.executeTakeFirst())?.count??0}async function v1(G,J){let X=T.selectFrom("waitlist_products").select(["status",(M)=>M.fn.count("id").as("count")]).groupBy("status");if(G&&J){let M=O(G),Z=O(J);X=X.where("created_at",">=",M).where("created_at","<=",Z)}let $=await X.execute(),K=$.reduce((M,{count:Z})=>M+Z,0),L=$.find((M)=>M.status==="purchased")?.count??0,Y=K>0?L/K*100:0,W=$.reduce((M,{status:Z,count:N})=>{return M[Z]={count:N,percentage:K>0?N/K*100:0},M},{});return{totalConversionRate:Y,statusBreakdown:W}}async function h1(G,J){let X=O(G),$=O(J);return(await T.selectFrom("waitlist_products").select((L)=>L.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",$).executeTakeFirst())?.count??0}async function g1(G,J){let X=T.selectFrom("waitlist_products").select(["created_at"]);if(G&&J){let L=O(G),Y=O(J);X=X.where("created_at",">=",L).where("created_at","<=",Y)}let K=(await X.execute()).reduce((L,{created_at:Y})=>{let W=(Y||"").split("T")[0]||"unknown";return L[W]=(L[W]||0)+1,L},{});return Object.entries(K).map(([L,Y])=>({date:L,count:Y})).sort((L,Y)=>L.date.localeCompare(Y.date))}var{randomUUIDv7:y1}=globalThis.Bun;import{db as D1}from"@stacksjs/database";import{formatDate as $J}from"@stacksjs/orm";async function p1(G){try{let J=G,X={name:G.name,email:G.email,phone:G.phone,quantity:G.quantity??J.party_size,notification_preference:J.notification_preference,source:G.source,notes:G.notes,product_id:G.product_id,customer_id:G.customer_id,uuid:y1(),status:G.status||"waiting"};if(G.notified_at!==void 0)X.notified_at=typeof G.notified_at==="number"?$J(G.notified_at):G.notified_at;if(G.purchased_at!==void 0)X.purchased_at=typeof G.purchased_at==="number"?$J(G.purchased_at):G.purchased_at;if(G.cancelled_at!==void 0)X.cancelled_at=typeof G.cancelled_at==="number"?$J(G.cancelled_at):G.cancelled_at;let $=await D1.insertInto("waitlist_products").values(X).returningAll().executeTakeFirst();if(!$)throw Error("Failed to create waitlist product");return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist product: ${J.message}`);throw J}}async function m1(G){if(!G.length)return 0;try{let J=G.map(($)=>{let K=$,L={name:$.name,email:$.email,phone:$.phone,quantity:$.quantity??K.party_size,notification_preference:K.notification_preference,source:$.source,notes:$.notes,product_id:$.product_id,customer_id:$.customer_id,uuid:y1(),status:$.status||"waiting"};if($.notified_at!==void 0)L.notified_at=typeof $.notified_at==="number"?$J($.notified_at):$.notified_at;if($.purchased_at!==void 0)L.purchased_at=typeof $.purchased_at==="number"?$J($.purchased_at):$.purchased_at;if($.cancelled_at!==void 0)L.cancelled_at=typeof $.cancelled_at==="number"?$J($.cancelled_at):$.cancelled_at;return L}),X=await D1.insertInto("waitlist_products").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${J.message}`);throw J}}import{db as xX}from"@stacksjs/database";import{formatDate as HX}from"@stacksjs/orm";async function b1(G,J){try{if(!G)throw Error("Waitlist product ID is required for update");let X=J,$=await xX.updateTable("waitlist_products").set({name:J.name,email:J.email,phone:J.phone,quantity:J.quantity??X.party_size,notification_preference:X.notification_preference,source:J.source,notes:J.notes,status:J.status,product_id:J.product_id,customer_id:J.customer_id,notified_at:X.notified_at,purchased_at:X.purchased_at,cancelled_at:X.cancelled_at,updated_at:HX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update waitlist product");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update waitlist product: ${X.message}`);throw X}}async function l1(G,J){try{let X=await xX.updateTable("waitlist_products").set({status:J,updated_at:HX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update waitlist product status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update waitlist product status: ${X.message}`);throw X}}async function c1(G,J){try{let X=await xX.updateTable("waitlist_products").set({quantity:J,updated_at:HX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update party size");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update party size: ${X.message}`);throw X}}var KJ={};Q(KJ,{updateWaitTimes:()=>E9,updateStatus:()=>A9,updateQueuePosition:()=>O9,updatePartySize:()=>z9,update:()=>B9,store:()=>Q9,fetchWaitingWithQuotedTimes:()=>$9,fetchWaitingWithPartySizes:()=>K9,fetchWaiting:()=>J9,fetchTimeSeriesStats:()=>N9,fetchTablesTurnedToday:()=>L9,fetchSeatingRate:()=>Y9,fetchSeatedStats:()=>M9,fetchSeatedBetweenDates:()=>e1,fetchNoShowStats:()=>W9,fetchCurrentWaitTimes:()=>Z9,fetchCountByTablePreference:()=>s1,fetchCountByPartySize:()=>a1,fetchCountByDate:()=>d1,fetchCountByAllPartySizes:()=>t1,fetchConversionRates:()=>G9,fetchById:()=>o1,fetchBetweenDates:()=>r1,fetchAverageWaitTimes:()=>X9,fetchAll:()=>i1,destroy:()=>u1,bulkStore:()=>V9,bulkDestroy:()=>n1});import{db as xG}from"@stacksjs/database";async function u1(G){try{let J=await xG.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst();if(!J)return;return await xG.deleteFrom("waitlist_restaurants").where("id","=",G).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${J.message}`);throw J}}async function n1(G){if(!G.length)return 0;try{return(await xG.deleteFrom("waitlist_restaurants").where("id","in",G).execute()).length||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as z}from"@stacksjs/database";import{formatDate as k}from"@stacksjs/orm";async function o1(G){return await z.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst()}async function i1(){return await z.selectFrom("waitlist_restaurants").selectAll().execute()}async function s1(){return(await z.selectFrom("waitlist_restaurants").select(["table_preference",(J)=>J.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((J,{table_preference:X,count:$})=>{return J[X]=$,J},{})}async function d1(G=new Date){let J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=k(J),K=k(X);return(await z.selectFrom("waitlist_restaurants").select((Y)=>Y.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function a1(G){return(await z.selectFrom("waitlist_restaurants").select((X)=>X.fn.count("id").as("count")).where("party_size","=",G).executeTakeFirst())?.count??0}async function t1(){return(await z.selectFrom("waitlist_restaurants").select(["party_size",(J)=>J.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((J,{party_size:X,count:$})=>{return J[X]=$,J},{})}async function r1(G,J){let X=k(G),$=k(J);return await z.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",X).where("created_at","<=",$).execute()}async function e1(G,J){let X=k(G),$=k(J);return await z.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",X).where("check_in_time","<=",$).where("status","=","seated").execute()}async function J9(){return await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function G9(){let G=await z.selectFrom("waitlist_restaurants").select(["status",(L)=>L.fn.count("id").as("count")]).groupBy("status").execute(),J=G.reduce((L,{count:Y})=>L+Y,0),X=G.find((L)=>L.status==="seated")?.count??0,$=J>0?Number(X)/J*100:0,K=G.reduce((L,{status:Y,count:W})=>{return L[Y]={count:W,percentage:J>0?W/J*100:0},L},{});return{totalConversionRate:$,statusBreakdown:K}}async function X9(){let G=await z.selectFrom("waitlist_restaurants").select([(J)=>J.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),(J)=>J.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:G?.avg_quoted_wait_time??0,averageActualWaitTime:G?.avg_actual_wait_time??0}}async function $9(){let G=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=G.reduce(($,K)=>$+(K.quoted_wait_time??0),0),X=G.length>0?J/G.length:0;return{entries:G,totalQuotedWaitTime:J,averageQuotedWaitTime:X}}async function K9(){let G=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=G.reduce((K,L)=>K+L.party_size,0),X=G.length>0?J/G.length:0,$=G.reduce((K,L)=>{return K[L.party_size]=(K[L.party_size]||0)+1,K},{});return{entries:G,totalPartySize:J,averagePartySize:X,partySizeBreakdown:$}}async function L9(){let G=new Date,J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=k(J),K=k(X),L=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",$).where("check_in_time","<=",K).execute(),Y=L.length,W=L.reduce((x,H)=>x+H.party_size,0),M=Y>0?W/Y:0,Z=L.reduce((x,H)=>{return x[H.table_preference]=(x[H.table_preference]||0)+1,x},{}),N=L.reduce((x,H)=>{return x[H.party_size]=(x[H.party_size]||0)+1,x},{});return{totalTablesTurned:Y,averagePartySize:M,totalCustomersSeated:W,breakdownByTablePreference:Z,breakdownByPartySize:N}}async function Y9(G,J){let X=k(G),$=k(J),K=await z.selectFrom("waitlist_restaurants").select(["status",(Z)=>Z.fn.count("id").as("count")]).where("check_in_time",">=",X).where("check_in_time","<=",$).groupBy("status").execute(),L=K.reduce((Z,{count:N})=>Z+N,0),Y=K.find((Z)=>Z.status==="seated")?.count??0,W=L>0?Number(Y)/L*100:0,M=K.reduce((Z,{status:N,count:x})=>{return Z[N]={count:x,percentage:L>0?x/L*100:0},Z},{});return{totalEntries:L,seatedEntries:Y,seatingRate:W,statusBreakdown:M}}async function W9(G,J){let X=k(G),$=k(J),K=z.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",X).where("check_in_time","<=",$),L=await z.selectFrom("waitlist_restaurants").select((F)=>F.fn.count("id").as("count")).where("check_in_time",">=",X).where("check_in_time","<=",$).executeTakeFirst(),Y=await K.execute(),W=Y.length,M=L?.count&&L.count>0?W/L.count*100:0,Z=Y.reduce((F,A)=>F+(A.quoted_wait_time??0),0),N=W>0?Z/W:0,x=Y.reduce((F,A)=>F+A.party_size,0),H=W>0?x/W:0,E=Y.reduce((F,A)=>{return F[A.table_preference]=(F[A.table_preference]||0)+1,F},{}),B=Y.reduce((F,A)=>{return F[A.party_size]=(F[A.party_size]||0)+1,F},{});return{totalNoShows:W,noShowRate:M,averageQuotedWaitTime:N,averagePartySize:H,breakdownByTablePreference:E,breakdownByPartySize:B}}async function Z9(){let G=await z.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),J=G.reduce((K,L)=>K+(L.quoted_wait_time||0),0),X=G.reduce((K,L)=>K+(L.actual_wait_time||0),0),$=G.length;return{averageQuoted:$>0?J/$:0,averageActual:$>0?X/$:0}}async function M9(){let G=Date.now()-86400000,J=await z.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",G).execute(),X=Array.from({length:24},($,K)=>({hour:K,count:J.filter((L)=>{return L.seated_at===K}).length}));return{total:J.length,byHour:X}}async function N9(){return(await z.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((J,X)=>{let $=X.created_at;if(!J[$])J[$]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return J[$].total++,J[$][X.status]++,J},{})}var{randomUUIDv7:x9}=globalThis.Bun;import{db as H9}from"@stacksjs/database";import{formatDate as F9}from"@stacksjs/orm";async function Q9(G){try{let J=G,X={name:G.name,email:G.email,phone:G.phone,party_size:J.party_size,check_in_time:typeof J.check_in_time==="number"?F9(J.check_in_time):J.check_in_time,table_preference:J.table_preference,status:G.status||"waiting",quoted_wait_time:G.quoted_wait_time,actual_wait_time:G.actual_wait_time,queue_position:G.queue_position,customer_id:G.customer_id,uuid:x9()},$={};for(let[Y,W]of Object.entries(X))if(W!==void 0)$[Y]=W;let K=await H9.insertInto("waitlist_restaurants").values($).returningAll().executeTakeFirst();if(!K)throw Error("Failed to create restaurant waitlist entry");let L={...K};for(let Y of Object.keys(L))if(L[Y]===null)L[Y]=void 0;return L}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${J.message}`);throw J}}async function V9(G){if(!G.length)return 0;try{let J=G.map(($)=>{let K=$;return{name:$.name,email:$.email,phone:$.phone,party_size:K.party_size,check_in_time:typeof K.check_in_time==="number"?F9(K.check_in_time):K.check_in_time,table_preference:K.table_preference,status:$.status||"waiting",quoted_wait_time:$.quoted_wait_time,actual_wait_time:$.actual_wait_time,queue_position:$.queue_position,customer_id:$.customer_id,uuid:x9()}}),X=await H9.insertInto("waitlist_restaurants").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as BJ}from"@stacksjs/database";import{formatDate as AJ}from"@stacksjs/orm";async function B9(G,J){try{if(!G)throw Error("Restaurant waitlist entry ID is required for update");let X=J,$=await BJ.updateTable("waitlist_restaurants").set({name:J.name,email:J.email,phone:J.phone,party_size:X.party_size,check_in_time:X.check_in_time?Math.floor(new Date(X.check_in_time).getTime()/1000):void 0,table_preference:X.table_preference,status:J.status,quoted_wait_time:J.quoted_wait_time,actual_wait_time:J.actual_wait_time,queue_position:J.queue_position,customer_id:J.customer_id,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update restaurant waitlist entry");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${X.message}`);throw X}}async function A9(G,J){try{let X=await BJ.updateTable("waitlist_restaurants").set({status:J,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update restaurant waitlist entry status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry status: ${X.message}`);throw X}}async function z9(G,J){try{let X=await BJ.updateTable("waitlist_restaurants").set({party_size:J,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update party size");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update party size: ${X.message}`);throw X}}async function E9(G,J,X){try{let $=await BJ.updateTable("waitlist_restaurants").set({quoted_wait_time:J,actual_wait_time:X,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update wait times");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update wait times: ${$.message}`);throw $}}async function O9(G,J){try{let X=await BJ.updateTable("waitlist_restaurants").set({queue_position:J,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update queue position");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update queue position: ${X.message}`);throw X}}var MK={products:NG,restaurant:KJ},NK=MK;var xK={coupons:FG,customers:VG,devices:EG,errors:UG,giftCards:PG,orders:yG,payments:DG,products:oG,receipts:dG,restaurant:KJ,shippings:WX,tax:NX,waitlists:FX},aZ=xK;export{FX as waitlists,NX as tax,WX as shippings,KJ as restaurant,dG as receipts,oG as products,DG as payments,yG as orders,PG as giftCards,UG as errors,EG as devices,aZ as default,VG as customers,FG as coupons,xK as commerce};
|
|
2
|
+
var U9=Object.defineProperty;var T9=(G)=>G;function S9(G,J){this[G]=T9.bind(null,J)}var Q=(G,J)=>{for(var X in J)U9(G,X,{get:J[X],enumerable:!0,configurable:!0,set:S9.bind(J,X)})};var QX=import.meta.require;var FG={};Q(FG,{update:()=>gX,store:()=>fX,redeem:()=>yX,getActiveCouponsMoMChange:()=>CX,fetchTopRedeemedCoupons:()=>jX,fetchStats:()=>TX,fetchRedemptionTrend:()=>kX,fetchRedemptionStats:()=>PX,fetchCouponCountsByType:()=>qX,fetchCouponCounts:()=>SX,fetchConversionRate:()=>wX,fetchById:()=>l,fetchByCode:()=>RX,fetchAll:()=>OX,fetchActive:()=>UX,deleteExpiredCoupons:()=>AX,deleteCoupons:()=>BX,deleteCoupon:()=>VX});import{db as LJ}from"@stacksjs/database";import{formatDate as q9}from"@stacksjs/orm";async function VX(G){return!!await LJ.deleteFrom("coupons").where("id","=",G).executeTakeFirst()}async function BX(G){if(!G.length)return 0;return(await LJ.deleteFrom("coupons").where("id","in",G).execute()).length||0}async function AX(){let G=q9(new Date),J=await LJ.deleteFrom("coupons").where("end_date","<",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}import{db as V}from"@stacksjs/database";import{extractDate as zX,formatDate as EX}from"@stacksjs/orm";function EJ(G){let J={...G};if(J.endDate)J.endDate=zX(new Date(J.endDate));if(J.startDate)J.startDate=zX(new Date(J.startDate));if(J.isActive!==void 0)J.isActive=Boolean(J.isActive);return J}async function OX(){return(await V.selectFrom("coupons").selectAll().execute()).map(EJ)}async function l(G){let J=await V.selectFrom("coupons").where("id","=",G).selectAll().executeTakeFirst();if(J)return EJ(J);return}async function RX(G){let J=await V.selectFrom("coupons").where("code","=",G).selectAll().executeTakeFirst();if(J)return EJ(J);return}async function UX(){let G=EX(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).selectAll().execute()).map(EJ)}async function TX(){let G=await V.selectFrom("coupons").select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),J=EX(new Date),X=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),$=await V.selectFrom("coupons").select(["discount_type",(Y)=>Y.fn.count("id").as("count")]).groupBy("discount_type").execute(),K=await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),L=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",J).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(G?.count||0),active:Number(X?.count||0),by_type:$,most_used:K,upcoming:L}}async function SX(){let G=new Date,J=new Date(G);J.setDate(G.getDate()-7);let X=new Date(G);X.setMonth(G.getMonth()-1);let $=new Date(G);$.setFullYear(G.getFullYear()-1);let K=await zJ(null,null,G),L=await zJ(J,null,G),Y=await zJ(X,null,G),W=await zJ($,null,G);return{week:L,month:Y,year:W,all_time:K}}async function zJ(G,J,X){let $=V.selectFrom("coupons");if(G)$=$.where("created_at",">=",G.toISOString());if(J)$=$.where("created_at","<=",J.toISOString());let K=await $.select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),L=V.selectFrom("coupons");if(G)L=L.where("created_at",">=",G.toISOString());if(J)L=L.where("created_at","<=",J.toISOString());L=L.where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",X);let Y=await L.select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),W=Number(K?.count||0),M=Number(Y?.count||0),Z=W-M;return{total:W,active:M,inactive:Z}}async function qX(){let G=new Date,J=await V.selectFrom("coupons").select("discount_type").distinct().execute(),X={};for(let{discount_type:$}of J){let K=await V.selectFrom("coupons").where("discount_type","=",$).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),L=await V.selectFrom("coupons").where("discount_type","=",$).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),Y=Number(K?.count||0),W=Number(L?.count||0);X[$]={total:Y,active:W,inactive:Y-W}}return X}async function PX(){let G=await V.selectFrom("coupons").select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),J=new Date,X=new Date(J);X.setDate(J.getDate()-7);let $=new Date(J);$.setMonth(J.getMonth()-1);let K=new Date(J);K.setFullYear(J.getFullYear()-1);let L=await V.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await V.selectFrom("coupons").where("updated_at",">=",$.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await V.selectFrom("coupons").where("updated_at",">=",K.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),M=await V.selectFrom("coupons").select(["discount_type",(N)=>N.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),Z={};return M.forEach((N)=>{Z[N.discount_type]=Number(N.total||0)}),{total:Number(G?.total||0),week:Number(L?.total||0),month:Number(Y?.total||0),year:Number(W?.total||0),by_type:Z}}async function jX(G=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(G).execute()}async function kX(G=30){let J=new Date().toISOString(),X=new Date;X.setDate(X.getDate()-G);let $=await V.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",X.toISOString()).where("updated_at","<=",J).where("usage_count",">",0).orderBy("updated_at","desc").execute(),K={};return $.forEach((L)=>{let Y=L.updated_at?new Date(L.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!K[Y])K[Y]=0;K[Y]+=L?.usage_count||0}),Object.entries(K).map(([L,Y])=>({date:L,count:Y}))}async function wX(){let G=new Date,J=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),X=await V.selectFrom("coupons").where("usage_count",">",0).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),$=Number(J?.count||0),K=Number(X?.count||0);return{rate:$>0?K/$*100:0,total_active:$,total_redeemed:K}}async function CX(){let G=new Date,J=new Date(G.getFullYear(),G.getMonth(),1),X=new Date(G.getFullYear(),G.getMonth()-1,1),$=new Date(G.getFullYear(),G.getMonth(),0),K=await V.selectFrom("coupons").select((N)=>N.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",J).executeTakeFirst(),L=await V.selectFrom("coupons").select((N)=>N.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",X).executeTakeFirst(),Y=Number(K?.count||0),W=Number(L?.count||0),M=Y-W,Z=W!==0?M/W*100:Y>0?100:0;return{current_month:Y,previous_month:W,difference:M,percentage_change:Z}}import{db as _X}from"@stacksjs/database";import{HttpError as IX}from"@stacksjs/error-handling";import{isUniqueViolation as P9}from"@stacksjs/orm";async function fX(G){try{let J=await _X.insertInto("coupons").values(G).executeTakeFirst(),X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows);if(X)return await _X.selectFrom("coupons").where("id","=",X).selectAll().executeTakeFirst();return}catch(J){if(J instanceof IX)throw J;if(P9(J))throw new IX(409,"A coupon with this code already exists");if(J instanceof Error)throw Error(`Failed to create coupon: ${J.message}`);throw J}}import{db as HG}from"@stacksjs/database";import{HttpError as vX}from"@stacksjs/error-handling";import{formatDate as hX,isUniqueViolation as j9}from"@stacksjs/orm";async function gX(G,J){if(!await l(G))throw Error(`Coupon with ID ${G} not found`);try{await HG.updateTable("coupons").set({...J,updated_at:hX(new Date)}).where("id","=",G).execute();let $=await l(G);if($){let K=$;K.is_active=Boolean(K.is_active)}return $}catch($){if($ instanceof vX)throw $;if(j9($))throw new vX(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to update coupon: ${$.message}`);throw $}}async function yX(G){let J=hX(new Date),X=await HG.updateTable("coupons").set({usage_count:HG.raw("COALESCE(usage_count, 0) + 1"),updated_at:J}).where("id","=",G).where((W)=>W.or([W("max_uses","is",null),W.cmpr("usage_count","<",W.ref("max_uses"))])).where("is_active","=",1).where((W)=>W.or([W("start_date","is",null),W.cmpr("start_date","<=",J)])).where((W)=>W.or([W("end_date","is",null),W.cmpr("end_date",">=",J)])).executeTakeFirst();if(Number(X?.numUpdatedRows??X?.affectedRows??0)>0){let W=await l(G);if(W){let M=W;return M.is_active=Boolean(M.is_active),{ok:!0,coupon:W}}return{ok:!1,reason:"not-found"}}let K=await l(G);if(!K)return{ok:!1,reason:"not-found"};if(!K.is_active)return{ok:!1,reason:"inactive"};let L=!K.start_date||K.start_date<=J,Y=!K.end_date||K.end_date>=J;if(!L||!Y)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var VG={};Q(VG,{update:()=>nX,store:()=>cX,fetchById:()=>t,fetchAll:()=>pX,destroy:()=>mX,bulkDestroy:()=>bX});import{db as QG}from"@stacksjs/database";import{db as DX}from"@stacksjs/database";async function t(G){return await DX.selectFrom("customers").where("id","=",G).selectAll().executeTakeFirst()}async function pX(){return await DX.selectFrom("customers").selectAll().execute()}async function mX(G){try{if(!await t(G))throw Error(`Customer with ID ${G} not found`);return(await QG.deleteFrom("customers").where("id","=",G).executeTakeFirst()).numDeletedRows>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customer: ${J.message}`);throw J}}async function bX(G){if(!G.length)return 0;try{let J=await QG.deleteFrom("customers").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${J.message}`);throw J}}import{db as k9}from"@stacksjs/database";import{HttpError as lX}from"@stacksjs/error-handling";import{isUniqueViolation as w9}from"@stacksjs/orm";async function cX(G){try{let J={...G,avatar:G.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},X=await k9.insertInto("customers").values(J).executeTakeFirst();if(!X)throw Error("Failed to create customer");let $=X.insertId||Number(X.numInsertedOrUpdatedRows);return await t(Number($))}catch(J){if(J instanceof lX)throw J;if(w9(J))throw new lX(409,"A customer with this email already exists");if(J instanceof Error)throw Error(`Failed to create customer: ${J.message}`);throw J}}import{db as C9}from"@stacksjs/database";import{HttpError as uX}from"@stacksjs/error-handling";import{formatDate as _9,isUniqueViolation as I9}from"@stacksjs/orm";async function nX(G,J){try{if(!G)throw Error("Customer ID is required for update");let X=await C9.updateTable("customers").set({...J,updated_at:_9(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update customer");return X}catch(X){if(X instanceof uX)throw X;if(I9(X))throw new uX(409,"A customer with this email already exists");if(X instanceof Error)throw Error(`Failed to update customer: ${X.message}`);throw X}}var EG={};Q(EG,{updateStatus:()=>X6,updatePrintCount:()=>$6,update:()=>G6,storePrintDevicesExport:()=>tX,store:()=>eX,fetchById:()=>f,fetchAll:()=>OJ,exportPrintDevices:()=>RJ,downloadPrintDevices:()=>aX,destroy:()=>iX,bulkStore:()=>J6,bulkDestroy:()=>sX});import{db as oX}from"@stacksjs/database";async function iX(G){try{let J=await oX.deleteFrom("print_devices").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print device: ${J.message}`);throw J}}async function sX(G){if(!G.length)return 0;try{let J=await oX.deleteFrom("print_devices").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print devices: ${J.message}`);throw J}}import{createSpreadsheet as f9}from"ts-spreadsheets";import{db as dX}from"@stacksjs/database";async function f(G){return await dX.selectFrom("print_devices").where("id","=",G).selectAll().executeTakeFirst()}async function OJ(){return await dX.selectFrom("print_devices").selectAll().execute()}async function RJ(G="csv"){let J=await OJ(),X=v9(J);return f9(X,{type:G})}function v9(G){let J=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],X=G.map(($)=>{return[$.id,$.name,$.macAddress,$.location,$.terminal,$.status,new Date($.lastPing).toLocaleString(),$.printCount]});return{headings:J,data:X}}async function aX(G="csv",J){let X=await RJ(G),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;return X.download(J||$)}async function tX(G="csv",J){let X=await RJ(G),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;X.store(J||$)}var{randomUUIDv7:rX}=globalThis.Bun;import{db as BG}from"@stacksjs/database";async function eX(G){try{let J={...G,uuid:rX()},X=await BG.insertInto("print_devices").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await BG.selectFrom("print_devices").where("id","=",$).selectAll().executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print device: ${J.message}`);throw J}}async function J6(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:rX()};await BG.insertInto("print_devices").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${X.message}`);throw X}}import{db as AG}from"@stacksjs/database";import{formatDate as zG}from"@stacksjs/orm";async function G6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await AG.updateTable("print_devices").set({...J,updated_at:zG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device: ${$.message}`);throw $}}async function X6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await AG.updateTable("print_devices").set({status:J,updated_at:zG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device status: ${$.message}`);throw $}}async function $6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await AG.updateTable("print_devices").set({print_count:J,updated_at:zG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print count: ${$.message}`);throw $}}var UG={};Q(UG,{update:()=>H6,unresolveGroup:()=>B6,resolveGroup:()=>Q6,ignoreGroup:()=>V6,fetchTimeline:()=>x6,fetchStats:()=>N6,fetchGrouped:()=>Z6,fetchById:()=>W6,fetchByGroup:()=>M6,fetchAll:()=>TJ,destroyGroup:()=>Y6,destroy:()=>K6,bulkUpdateStatus:()=>F6,bulkDestroy:()=>L6});import{db as OG}from"@stacksjs/database";import{log as RG}from"@stacksjs/logging";async function K6(G){try{return await OG.deleteFrom("errors").where("id","=",G).execute(),!0}catch(J){return RG.error("[commerce/errors] destroy failed",{id:G,error:J}),!1}}async function L6(G){try{return await OG.deleteFrom("errors").where("id","in",G).execute(),!0}catch(J){return RG.error("[commerce/errors] bulkDestroy failed",{count:G.length,error:J}),!1}}async function Y6(G,J){try{return await OG.deleteFrom("errors").where("type","=",G).where("message","=",J).execute(),!0}catch(X){return RG.error("[commerce/errors] destroyGroup failed",{type:G,message:J,error:X}),!1}}import{db as UJ}from"@stacksjs/database";async function W6(G){return await UJ.selectFrom("errors").where("id","=",G).selectAll().executeTakeFirst()}async function TJ(){return await UJ.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function Z6(){let G=await UJ.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),J=new Map;for(let $ of G){let K=`${$.type}:${$.message}`;if(!J.has(K))J.set(K,{errors:[],firstSeen:new Date($.created_at),lastSeen:new Date($.created_at)});let L=J.get(K);L.errors.push($);let Y=new Date($.created_at);if(Y<L.firstSeen)L.firstSeen=Y;if(Y>L.lastSeen)L.lastSeen=Y}let X=[];for(let[$,K]of J){let L=K.errors[0];if(!L)continue;let Y=K.errors.find((M)=>M.status!==null)?.status,W="unresolved";if(Y===1)W="resolved";else if(Y===2)W="ignored";X.push({id:L.id,type:L.type,message:L.message,stack:L.stack,status:W,count:K.errors.length,first_seen:K.firstSeen.toISOString(),last_seen:K.lastSeen.toISOString(),error_ids:K.errors.map((M)=>M.id)})}return X.sort(($,K)=>new Date(K.last_seen).getTime()-new Date($.last_seen).getTime()),X}async function M6(G,J){return await UJ.selectFrom("errors").where("type","=",G).where("message","=",J).selectAll().orderBy("created_at","desc").execute()}async function N6(){let G=await TJ(),J=new Date,X=new Date(J.getTime()-86400000),$=new Date(J.getTime()-172800000),K=G.filter((W)=>new Date(W.created_at)>=X).length,L=G.filter((W)=>{let M=new Date(W.created_at);return M>=$&&M<X}).length,Y=L===0?K>0?100:0:Math.round((K-L)/L*100);return{total:G.length,unresolved:G.filter((W)=>W.status===null||W.status===0).length,resolved:G.filter((W)=>W.status===1).length,ignored:G.filter((W)=>W.status===2).length,last_24h:K,trend:Y}}async function x6(){let G=await TJ(),J=new Date,X=[];for(let $=23;$>=0;$--){let K=new Date(J.getTime()-$*60*60*1000);K.setMinutes(0,0,0);let L=new Date(K.getTime()+3600000),Y=G.filter((W)=>{let M=new Date(W.created_at);return M>=K&&M<L}).length;X.push({hour:K.toISOString(),count:Y})}return X}import{db as YJ}from"@stacksjs/database";import{sql as WJ}from"@stacksjs/database";import{log as ZJ}from"@stacksjs/logging";async function H6(G,J){try{return await YJ.updateTable("errors").set({...J,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("id","=",G).execute(),!0}catch(X){return ZJ.error("[commerce/errors] update failed",{id:G,error:X}),!1}}async function F6(G,J){try{return await YJ.updateTable("errors").set({status:J,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("id","in",G).execute(),!0}catch(X){return ZJ.error("[commerce/errors] bulkUpdateStatus failed",{count:G.length,status:J,error:X}),!1}}async function Q6(G,J){try{return await YJ.updateTable("errors").set({status:1,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return ZJ.error("[commerce/errors] resolveGroup failed",{type:G,message:J,error:X}),!1}}async function V6(G,J){try{return await YJ.updateTable("errors").set({status:2,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return ZJ.error("[commerce/errors] ignoreGroup failed",{type:G,message:J,error:X}),!1}}async function B6(G,J){try{return await YJ.updateTable("errors").set({status:0,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return ZJ.error("[commerce/errors] unresolveGroup failed",{type:G,message:J,error:X}),!1}}var PG={};Q(PG,{updateBalance:()=>f6,update:()=>I6,store:()=>w6,fetchTotalValue:()=>T6,fetchTotalCurrentBalance:()=>S6,fetchStats:()=>E6,fetchById:()=>v,fetchByCode:()=>SG,fetchAll:()=>A6,fetchActive:()=>z6,destroy:()=>q6,compareActiveGiftCards:()=>R6,checkBalance:()=>O6,calculateGiftCardValues:()=>U6,bulkDestroy:()=>P6});import{db as qG}from"@stacksjs/database";import{formatDate as yL}from"@stacksjs/orm";import{db as j,sql as TG}from"@stacksjs/database";import{formatDate as D,toTimestamp as r}from"@stacksjs/orm";import{db as h9}from"@stacksjs/database";async function y(G,J,X){let $=h9.selectFrom(G);if(X)$=X($);$=$.select((Y)=>Object.entries(J).map(([W,M])=>{let Z=M.column??"id",N=Y.fn[M.kind](Z);if(M.filter){let x=M.filter;N=N.filterWhere(x.column,x.op,x.value)}return N.as(W)}));let K=await $.executeTakeFirst(),L={};for(let Y of Object.keys(J)){let W=K?.[Y];L[Y]=typeof W==="number"?W:Number(W??0)||0}return L}async function A6(){return await j.selectFrom("gift_cards").selectAll().execute()}async function v(G){return await j.selectFrom("gift_cards").where("id","=",G).selectAll().executeTakeFirst()}async function SG(G){return await j.selectFrom("gift_cards").where("code","=",G).selectAll().executeTakeFirst()}async function z6(){return await j.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function E6(){let{count:G}=await y("gift_cards",{count:{kind:"count"}}),J=r(new Date),X=await j.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where((N)=>N.or([N("expiry_date",">=",J),N("expiry_date","is",null)])).select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),$=await j.selectFrom("gift_cards").select(["status",(N)=>N.fn.count("id").as("count")]).groupBy("status").execute(),{count:K}=await y("gift_cards",{count:{kind:"count"}},(N)=>N.where((x)=>TG`${x.ref("current_balance")} / ${x.ref("initial_balance")} < 0.25`)),{count:L}=await y("gift_cards",{count:{kind:"count"}},(N)=>N.where((x)=>TG`${x.ref("current_balance")} / ${x.ref("initial_balance")} >= 0.25 AND ${x.ref("current_balance")} / ${x.ref("initial_balance")} <= 0.75`)),{count:Y}=await y("gift_cards",{count:{kind:"count"}},(N)=>N.where((x)=>TG`${x.ref("current_balance")} / ${x.ref("initial_balance")} > 0.75`)),W=new Date;W.setDate(W.getDate()+30);let M=await j.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",r(W)).where("expiry_date",">=",J).selectAll().limit(5).execute(),Z=await j.selectFrom("gift_cards").where("last_used_date","is not",null).selectAll().limit(5).execute();return{total:G,active:Number(X?.count||0),by_status:$.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:K,medium:L,high:Y},expiring_soon:M,recently_used:Z}}async function O6(G){let J=await SG(G);if(!J)return{valid:!1,message:"Gift card not found"};if(!J.isActive||J.status!=="ACTIVE")return{valid:!1,balance:J.currentBalance,currency:J.currency,message:`Gift card is ${J.status.toLowerCase()}`};if(J.expiryDate){if(new Date(J.expiryDate)<new Date)return{valid:!1,balance:J.currentBalance,currency:J.currency,message:"Gift card has expired"}}return{valid:!0,balance:J.currentBalance,currency:J.currency}}async function R6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await j.selectFrom("gift_cards").select((x)=>x.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").where((x)=>x.or([x("expiry_date",">=",r(J)),x("expiry_date","is",null)])).where("created_at",">=",D(X)).where("created_at","<=",D(J)).executeTakeFirst(),Y=await j.selectFrom("gift_cards").select((x)=>x.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").where((x)=>x.or([x("expiry_date",">=",r(K)),x("expiry_date","is",null)])).where("created_at",">=",D(K)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(L?.count||0),M=Number(Y?.count||0),Z=W-M,N=M!==0?Z/M*100:W>0?100:0;return{current_period:W,previous_period:M,difference:Z,percentage_change:N,days_range:G}}async function U6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await j.selectFrom("gift_cards").select((q)=>[q.fn.sum("initial_balance").as("total_initial"),q.fn.sum("current_balance").as("total_balance"),q.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").where((q)=>q.or([q("expiry_date",">=",r(J)),q("expiry_date","is",null)])).where("created_at",">=",D(X)).where("created_at","<=",D(J)).executeTakeFirst(),Y=await j.selectFrom("gift_cards").select((q)=>[q.fn.sum("initial_balance").as("total_initial"),q.fn.sum("current_balance").as("total_balance"),q.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").where((q)=>q.or([q("expiry_date",">=",r(K)),q("expiry_date","is",null)])).where("created_at",">=",D(K)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(L?.total_initial||0),M=Number(L?.total_balance||0),Z=Number(L?.card_count||0),N=Number(Y?.total_initial||0),x=Number(Y?.total_balance||0),H=Number(Y?.card_count||0),E=W>0?(W-M)/W*100:0,B=N>0?(N-x)/N*100:0,F=Z>0?W/Z:0,A=Z>0?M/Z:0,_=W-N,m=M-x,b=Z-H,a=N!==0?_/N*100:W>0?100:0,R=x!==0?m/x*100:M>0?100:0,I=H!==0?b/H*100:Z>0?100:0;return{current_period:{total_initial_value:W,total_remaining_balance:M,utilization_rate:E,card_count:Z,average_initial_value:F,average_remaining_balance:A},previous_period:{total_initial_value:N,total_remaining_balance:x,utilization_rate:B,card_count:H},comparison:{initial_value:{difference:_,percentage:Math.abs(a),is_increase:_>=0},balance:{difference:m,percentage:Math.abs(R),is_increase:m>=0},card_count:{difference:b,percentage:Math.abs(I),is_increase:b>=0}},days_range:G}}async function T6(){let{total_value:G}=await y("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:G}}async function S6(){let{total_balance:G}=await y("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:G}}async function q6(G){if(!await v(G))throw Error(`Gift card with ID ${G} not found`);return!!await qG.deleteFrom("gift_cards").where("id","=",G).executeTakeFirst()}async function P6(G){if(!G.length)return 0;let J=await qG.deleteFrom("gift_cards").where("id","in",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}var{randomUUIDv7:g9}=globalThis.Bun;import{db as j6}from"@stacksjs/database";import{HttpError as k6}from"@stacksjs/error-handling";import{isUniqueViolation as y9}from"@stacksjs/orm";async function w6(G){let J=G,X={...G,current_balance:J.current_balance??J.initial_balance,status:G.status||"ACTIVE",is_active:J.is_active??!0,uuid:g9()};try{let $=await j6.insertInto("gift_cards").values(X).executeTakeFirst(),K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);if(K)return await j6.selectFrom("gift_cards").where("id","=",K).selectAll().executeTakeFirst();return}catch($){if($ instanceof k6)throw $;if(y9($))throw new k6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to create gift card: ${$.message}`);throw $}}import{db as SJ}from"@stacksjs/database";import{HttpError as C6}from"@stacksjs/error-handling";import{formatDate as _6,isUniqueViolation as D9}from"@stacksjs/orm";async function I6(G,J){if(!await v(G))throw Error(`Gift card with ID ${G} not found`);try{return await SJ.updateTable("gift_cards").set({...J,updated_at:_6(new Date)}).where("id","=",G).execute(),await v(G)}catch($){if($ instanceof C6)throw $;if(D9($))throw new C6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to update gift card: ${$.message}`);throw $}}async function f6(G,J){let X=_6(new Date),$=await SJ.updateTable("gift_cards").set({current_balance:SJ.raw(`current_balance + ${J}`),last_used_date:X,status:SJ.raw(`CASE WHEN current_balance + ${J} = 0 THEN 'USED' ELSE 'ACTIVE' END`),updated_at:X}).where("id","=",G).where("is_active","=",1).where("status","=","ACTIVE").where((Y)=>Y.cmpr(Y.raw(`current_balance + ${J}`),">=",0)).executeTakeFirst();if(Number($?.numUpdatedRows??$?.affectedRows??0)>0)return await v(G);let L=await v(G);if(!L)throw Error(`Gift card with ID ${G} not found`);if(!L.is_active||L.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var yG={};Q(yG,{validateQuantityBounds:()=>gG,validateCouponStacking:()=>Y$,validateCartQuantities:()=>W$,updateStatus:()=>J$,updateDeliveryInfo:()=>G$,update:()=>e6,storeOrdersExport:()=>m6,store:()=>s6,softDelete:()=>h6,registerCommerceWebhookHandlers:()=>$$,recomputeOrderTotals:()=>L$,placeOrder:()=>r6,handlePaymentIntentSucceeded:()=>fG,handlePaymentIntentFailed:()=>vG,handleChargeRefunded:()=>hG,fetchStats:()=>l6,fetchDailyOrderTrends:()=>n6,fetchById:()=>h,fetchAll:()=>b6,exportOrders:()=>PJ,emitOrderShipped:()=>jG,emitOrderRefunded:()=>NJ,emitOrderPaid:()=>c,emitOrderDelivered:()=>kG,emitOrderCreated:()=>kJ,emitOrderCancelled:()=>MJ,emitForStatus:()=>wJ,downloadOrders:()=>p6,destroy:()=>v6,compareOrdersByPeriod:()=>c6,cleanupAbandonedCarts:()=>Z$,canTransition:()=>jJ,calculateOrderMetrics:()=>u6,bulkSoftDelete:()=>y6,bulkDestroy:()=>g6});import{db as qJ}from"@stacksjs/database";async function v6(G){try{let J=await qJ.deleteFrom("orders").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function h6(G){try{let J=await qJ.updateTable("orders").set({status:"CANCELED"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete order: ${J.message}`);throw J}}async function g6(G){if(!G.length)return 0;try{let J=await qJ.deleteFrom("orders").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}async function y6(G){if(!G.length)return 0;try{let J=await qJ.updateTable("orders").set({status:"CANCELED"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete orders: ${J.message}`);throw J}}import{db as D6}from"@stacksjs/database";import{createSpreadsheet as p9}from"ts-spreadsheets";async function PJ(G="csv"){let J=await m9(),X=b9(J);return p9(X,{type:G})}async function m9(){let G=await D6.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),J=G.map((L)=>L.id);if(J.length===0)return[];let $=(await D6.selectFrom("order_items").where("order_items.order_id","in",J).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((L,Y)=>{if(!Y.order_id)return L;if(!L[Y.order_id])L[Y.order_id]={totalItems:0,totalPrice:0};return L[Y.order_id].totalItems+=Y.quantity,L[Y.order_id].totalPrice+=Y.price*Y.quantity,L},{});return G.map((L)=>{let Y=$[L.id]||{totalItems:0,totalPrice:0};return{...L,totalItems:Y.totalItems,totalPrice:Y.totalPrice}})}function b9(G){let J=["Order ID","Customer","Date","Total","Status","Items"],X=G.map(($)=>{let K=$.order_items?.map((L)=>`${L.product?.name} (Qty: ${L.quantity}, Price: $${L.price})`).join(" | ")||"No Items";return[$.id,$.customer?.name||"N/A",$.created_at,$.total_amount,$.status,K]});return{headings:J,data:X}}async function p6(G="csv",J){let X=await PJ(G),$=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;return X.download(J||$)}async function m6(G="csv",J){let X=await PJ(G),$=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;X.store(J||$)}import{db as S}from"@stacksjs/database";async function b6(G){let J=S.selectFrom("orders").selectAll().orderBy("created_at","desc");if(G)J=J.limit(G);let X=await J.execute();return await Promise.all(X.map(async($)=>{let K=await S.selectFrom("order_items").where("order_id","=",$.id).selectAll().execute();return{...$,items:K}}))}async function h(G){return await S.selectFrom("orders").where("id","=",G).selectAll().executeTakeFirst()}async function l6(){let G=await S.selectFrom("orders").select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),J=await S.selectFrom("orders").select(["status",(Y)=>Y.fn.count("id").as("count")]).groupBy("status").execute(),X=await S.selectFrom("orders").select(["order_type",(Y)=>Y.fn.count("id").as("count")]).groupBy("order_type").execute(),$=await S.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),K=await Promise.all($.map(async(Y)=>{let W=await S.selectFrom("order_items").where("order_id","=",Y.id).selectAll().execute();return{...Y,items:W}})),L=await S.selectFrom("orders").select((Y)=>Y.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(G?.count||0),by_status:J,by_type:X,recent:K,revenue:Number(L?.total||0)}}async function c6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await S.selectFrom("orders").select((x)=>x.fn.count("id").as("count")).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),Y=await S.selectFrom("orders").select((x)=>x.fn.count("id").as("count")).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=Number(L?.count||0),M=Number(Y?.count||0),Z=W-M,N=M!==0?Z/M*100:W>0?100:0;return{current_period:W,previous_period:M,difference:Z,percentage_change:N,days_range:G}}async function u6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await S.selectFrom("orders").select((R)=>[R.fn.count("id").as("total_orders"),R.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),Y=await S.selectFrom("orders").select((R)=>[R.fn.count("id").as("total_orders"),R.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=await S.selectFrom("orders").select(["status",(R)=>R.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).groupBy("status").execute(),M=await S.selectFrom("orders").select(["order_type",(R)=>R.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).groupBy("order_type").execute(),Z=Number(L?.total_orders||0),N=Number(L?.total_revenue||0),x=Z>0?N/Z:0,H=Number(Y?.total_orders||0),E=Number(Y?.total_revenue||0),B=H>0?E/H:0,F=Z-H,A=N-E,_=x-B,m=H!==0?F/H*100:Z>0?100:0,b=E!==0?A/E*100:N>0?100:0,a=B!==0?_/B*100:x>0?100:0;return{current_period:{total_orders:Z,total_revenue:N,average_order_value:x,orders_by_status:W.map((R)=>({status:R.status,count:Number(R.count)})),orders_by_type:M.map((R)=>({order_type:R.order_type,count:Number(R.count)}))},previous_period:{total_orders:H,total_revenue:E,average_order_value:B},comparison:{orders:{difference:F,percentage:Math.abs(m),is_increase:F>=0},revenue:{difference:A,percentage:Math.abs(b),is_increase:A>=0},average_order_value:{difference:_,percentage:Math.abs(a),is_increase:_>=0}},days_range:G}}async function n6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await S.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).orderBy("created_at","asc").execute(),K=new Map;for(let L of $){let Y=(L.created_at||"").split("T")[0]||"unknown",W=K.get(Y)||{order_count:0,revenue:0};W.order_count++,W.revenue+=Number(L.total_amount||0),K.set(Y,W)}return Array.from(K.entries()).map(([L,Y])=>({date:L,order_count:Y.order_count,revenue:Y.revenue}))}var{randomUUIDv7:l9}=globalThis.Bun;import{db as o6}from"@stacksjs/database";import{formatDate as i6}from"@stacksjs/orm";async function s6(G){let J={...G,status:G.status||"PENDING",uuid:l9(),created_at:i6(new Date),updated_at:i6(new Date)};try{let X=await o6.insertInto("orders").values(J).executeTakeFirst(),$=Number(X?.insertId)||Number(X?.numInsertedOrUpdatedRows);if($)return await o6.selectFrom("orders").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof Error)throw Error(`Failed to create order: ${X.message}`);throw X}}var{randomUUIDv7:u9}=globalThis.Bun;import{db as CJ}from"@stacksjs/database";import{formatDate as n9}from"@stacksjs/orm";import{sql as d6}from"@stacksjs/database";var c9={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","CANCELLED","REFUNDED"],SHIPPED:["DELIVERED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]};function jJ(G,J){if(G===J)return!0;return c9[G]?.includes(J)??!1}async function e(G,J){try{let X=await import("@stacksjs/events").catch(()=>null);if(!X)return;let $=X.dispatch;if(typeof $!=="function")return;$(G,J)}catch{}}async function kJ(G){await e("order:created",{order:G})}async function c(G,J){await e("order:paid",{order:G,payment:J})}async function jG(G){await e("order:shipped",{order:G})}async function kG(G){await e("order:delivered",{order:G})}async function MJ(G,J){await e("order:cancelled",{order:G,reason:J})}async function NJ(G,J){await e("order:refunded",{order:G,refundAmount:J})}async function wJ(G,J){switch(G){case"PROCESSING":return c(J);case"SHIPPED":return jG(J);case"DELIVERED":return kG(J);case"CANCELLED":return MJ(J);case"REFUNDED":return NJ(J);case"PENDING":default:}}var a6=!1;function t6(G){let J=G,X=J?.message??"";return J?.code==="42P01"||X.includes("no such table")||X.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(X)}async function o9(G){try{let J=await CJ.selectFrom("order_idempotency").where("idempotency_key","=",G).selectAll().executeTakeFirst();if(!J)return null;return await CJ.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}catch(J){if(t6(J)){if(!a6)a6=!0,console.warn("[commerce/orders] order_idempotency table missing \u2014 idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw J}}async function r6(G){if(G.idempotencyKey){let J=await o9(G.idempotencyKey);if(J)return{ok:!0,order:J}}try{let J=await CJ.transaction(async(X)=>{let $=n9(new Date),K={...G.order,status:G.order.status||"PENDING",uuid:u9(),created_at:$,updated_at:$},L=await X.insertInto("orders").values(K).executeTakeFirst(),Y=Number(L?.insertId)||Number(L?.numInsertedOrUpdatedRows);if(!Y)throw Object.assign(Error("order insert returned no id"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let W;if(G.payment)try{let Z=await X.insertInto("payments").values({...G.payment,order_id:Y,created_at:$,updated_at:$}).executeTakeFirst(),N=Number(Z?.insertId)||Number(Z?.numInsertedOrUpdatedRows);if(N)W=await X.selectFrom("payments").where("id","=",N).selectAll().executeTakeFirst()}catch(Z){if(Z?.message?.includes("UNIQUE constraint")||Z?.message?.includes("Duplicate entry"))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(Z,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(G.inventory&&G.inventory.length>0)for(let Z=0;Z<G.inventory.length;Z++){let{id:N,delta:x}=G.inventory[Z];if(!Number.isFinite(x)||x===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});let H=await X.updateTable("products").set({inventory_count:d6`inventory_count + ${x}`,updated_at:$}).where("id","=",N).where(d6`inventory_count + ${x}`,">=",0).execute();if(!Number(H?.numUpdatedRows??H?.[0]?.numUpdatedRows??H?.numAffectedRows??0))throw Object.assign(Error(`inventory adjust failed for product ${N}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(G.idempotencyKey)try{await X.insertInto("order_idempotency").values({idempotency_key:G.idempotencyKey,order_id:Y,created_at:$}).execute()}catch(Z){if(Z?.message?.includes("UNIQUE constraint")||Z?.message?.includes("Duplicate entry"))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!t6(Z))throw Z}let M=await X.selectFrom("orders").where("id","=",Y).selectAll().executeTakeFirst();if(!M)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:M,payment:W}});if(kJ(J.order),J.payment)c(J.order,J.payment);return{ok:!0,order:J.order,payment:J.payment}}catch(J){if(J?.__placeFail)return{ok:!1,reason:J.reason,failedAt:J.failedAt,error:J};throw J}}import{db as wG}from"@stacksjs/database";import{formatDate as CG}from"@stacksjs/orm";async function e6(G,J){if(!await h(G))throw Error(`Order with ID ${G} not found`);try{return await wG.updateTable("orders").set({...J,updated_at:CG(new Date)}).where("id","=",G).execute(),await h(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update order: ${$.message}`);throw $}}async function J$(G,J){let X=await h(G);if(!X)throw Error(`Order with ID ${G} not found`);let $=X.status??"PENDING";if(!jJ($,J))throw Error(`[commerce/orders] illegal status transition ${$} \u2192 ${J}`);try{await wG.updateTable("orders").set({status:J,updated_at:CG(new Date)}).where("id","=",G).execute();let K=await h(G);if(K)wJ(J,K);return K}catch(K){if(K instanceof Error)throw TypeError(`Failed to update order status: ${K.message}`);throw K}}async function G$(G,J,X){let $=await h(G);if(!$)throw Error(`Order with ID ${G} not found`);let K={updated_at:CG(new Date)};if(J!==void 0)K.delivery_address=J;if(X!==void 0)K.estimated_delivery_time=X;if(Object.keys(K).length===1)return $;try{return await wG.updateTable("orders").set(K).where("id","=",G).execute(),await h(G)}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery information: ${L.message}`);throw L}}import{db as JJ}from"@stacksjs/database";import{formatDate as _J}from"@stacksjs/orm";async function _G(G){let J=await JJ.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!J)return null;return await JJ.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}var X$=!1;function i9(G){let J=G,X=J?.message??"";return J?.code==="42P01"||X.includes("no such table")||X.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(X)}async function IG(G,J){try{return await J.insertInto("stripe_webhook_events").values({event_id:G,processed_at:_J(new Date)}).execute(),!0}catch(X){if(X?.message?.includes("UNIQUE constraint")||X?.message?.includes("Duplicate entry"))return!1;if(i9(X)){if(!X$)X$=!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 X}}async function fG(G){let X=G.data.object?.id;if(!X)return;await JJ.transaction(async(K)=>{if(!await IG(G.id,K))return;let Y=await K.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!Y)return;let W=_J(new Date);await K.updateTable("payments").set({status:"succeeded",updated_at:W}).where("id","=",Y.id).execute();let M=await K.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(M&&M.status==="PENDING")await K.updateTable("orders").set({status:"PROCESSING",updated_at:W}).where("id","=",M.id).execute()});let $=await _G(X);if($)await c($)}async function vG(G){let J=G.data.object,X=J?.id;if(!X)return;let K=J?.last_payment_error?.message??"payment failed";await JJ.transaction(async(Y)=>{if(!await IG(G.id,Y))return;let M=await Y.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!M)return;let Z=_J(new Date);await Y.updateTable("payments").set({status:"failed",failure_reason:K,updated_at:Z}).where("id","=",M.id).execute();let N=await Y.selectFrom("orders").where("id","=",M.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await Y.updateTable("orders").set({status:"CANCELLED",updated_at:Z}).where("id","=",N.id).execute()});let L=await _G(X);if(L)await MJ(L,K)}async function hG(G){let J=G.data.object,X=J?.payment_intent;if(!X)return;let $=J?.amount_refunded??0;await JJ.transaction(async(L)=>{if(!await IG(G.id,L))return;let W=await L.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!W)return;let M=_J(new Date);await L.updateTable("payments").set({status:"refunded",refund_amount:$,updated_at:M}).where("id","=",W.id).execute();let Z=await L.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(Z&&Z.status!=="REFUNDED")await L.updateTable("orders").set({status:"REFUNDED",updated_at:M}).where("id","=",Z.id).execute()});let K=await _G(X);if(K)await NJ(K,$)}async function $$(){let G=await import("@stacksjs/payments").catch(()=>null);if(!G)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:J,onCharge:X}=G;if(typeof J!=="function"||typeof X!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return J({succeeded:fG,failed:vG}),X({refunded:hG}),()=>{}}import{db as K$}from"@stacksjs/database";async function s9(G){if(G.length===0)return new Map;let J=await K$.selectFrom("products").where("id","in",G).select(["id","price"]).execute(),X=new Map;for(let $ of J){let K=Number($.price);if(Number.isFinite(K))X.set($.id,Math.round(K))}return X}async function d9(G){try{let J=await K$.selectFrom("tax_rates").where("id","=",G).select(["rate"]).executeTakeFirst(),X=Number(J?.rate??0);return Number.isFinite(X)?X:0}catch{return 0}}async function L$(G){let J=G.items.map((B)=>B.productId),X=await s9(J),$=G.taxRateId!=null?await d9(G.taxRateId):0,K=0,L=[];for(let B of G.items){let F=B.unitPriceCents??X.get(B.productId)??0,A=Math.round(F*B.quantity);K+=A,L.push({productId:B.productId,quantity:B.quantity,unitPriceCents:F,lineCents:A})}let Y=Math.max(0,G.discountCents??0),W=Math.max(0,K-Y),M=Math.round(W*$),Z=Math.max(0,G.shippingCents??0),N=K-Y+M+Z,x=G.maxDriftCents??5,H=!1,E=0;if(G.clientTotalCents!=null)E=Math.abs(N-G.clientTotalCents),H=E>x;return{subtotalCents:K,discountCents:Y,taxCents:M,shippingCents:Z,totalCents:N,resolvedItems:L,priceChanged:H,diffCents:E}}import{db as IJ}from"@stacksjs/database";function Y$(G,J={}){let X=G.length;if(X<=1)return{ok:!0,count:X};if(!J.allowMultiple)return{ok:!1,count:X,reason:"multiple-not-allowed"};let $=J.maxStacked??Number.POSITIVE_INFINITY;if(X>$)return{ok:!1,count:X,reason:"exceeds-max-stacked"};return{ok:!0,count:X}}async function gG(G,J){if(!Number.isFinite(J)||J<=0)return{ok:!1,productId:G,quantity:J,reason:"non-positive"};let X;try{X=await IJ.selectFrom("products").where("id","=",G).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:G,quantity:J}}if(!X)return{ok:!1,productId:G,quantity:J,reason:"product-missing"};let $=X.min_order_qty??null,K=X.max_order_qty??null;if($!=null&&J<$)return{ok:!1,productId:G,quantity:J,reason:"below-min",bound:$};if(K!=null&&J>K)return{ok:!1,productId:G,quantity:J,reason:"above-max",bound:K};return{ok:!0,productId:G,quantity:J}}async function W$(G){for(let X of G){let $=await gG(X.productId,X.quantity);if(!$.ok)return $}let J=G[G.length-1]??{productId:0,quantity:0};return{ok:!0,productId:J.productId,quantity:J.quantity}}async function Z$(G={}){let J=G.olderThanDays??30,X=G.limit??1000,K=new Date(Date.now()-J*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let L=await IJ.deleteFrom("carts").where("updated_at","<",K).where("id","in",(W)=>W.selectFrom("carts").select("id").where("updated_at","<",K).limit(X)).execute();return{deleted:Number(L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??0),cutoffAt:K}}catch{try{let L=await IJ.selectFrom("carts").where("updated_at","<",K).select(["id"]).limit(X).execute();if(L.length===0)return{deleted:0,cutoffAt:K};let Y=L.map((Z)=>Z.id),W=await IJ.deleteFrom("carts").where("id","in",Y).execute();return{deleted:Number(W?.numDeletedRows??W?.[0]?.numDeletedRows??W?.affectedRows??L.length),cutoffAt:K}}catch{return{deleted:0,cutoffAt:K}}}}var DG={};Q(DG,{update:()=>E$,store:()=>z$,fetchPaymentStatsByMethod:()=>Q$,fetchPaymentStats:()=>F$,fetchMonthlyPaymentTrends:()=>V$,fetchById:()=>xJ,fetchAll:()=>H$,destroy:()=>N$,bulkDestroy:()=>x$});import{db as M$}from"@stacksjs/database";async function N$(G){try{let J=await M$.deleteFrom("payments").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payment: ${J.message}`);throw J}}async function x$(G){if(!G.length)return 0;try{let J=await M$.deleteFrom("payments").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payments: ${J.message}`);throw J}}import{db as p}from"@stacksjs/database";import{formatDate as w}from"@stacksjs/orm";async function H$(){return await p.selectFrom("payments").selectAll().execute()}async function xJ(G){return await p.selectFrom("payments").selectAll().where("id","=",G).executeTakeFirst()}async function F$(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await p.selectFrom("payments").select((I)=>[I.fn.count("id").as("transaction_count"),I.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").executeTakeFirst(),Y=await p.selectFrom("payments").select((I)=>[I.fn.count("id").as("transaction_count"),I.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(K)).where("created_at","<=",w($)).where("status","=","completed").executeTakeFirst(),W=await p.selectFrom("payments").select((I)=>I.fn.count("id").as("count")).where("created_at",">=",w(X)).where("created_at","<=",w(J)).executeTakeFirst(),M=Number(L?.transaction_count||0),Z=Number(L?.total_revenue||0),N=M>0?Z/M:0,x=Number(Y?.transaction_count||0),H=Number(Y?.total_revenue||0),E=x>0?H/x:0,B=M-x,F=Z-H,A=N-E,_=x>0?B/x*100:M>0?100:0,m=H>0?F/H*100:Z>0?100:0,b=E>0?A/E*100:N>0?100:0,a=Number(W?.count||0),R=a>0?M/a*100:0;return{total_transactions:M,total_revenue:Z,average_transaction:N,successful_rate:R,comparison:{transactions:{difference:B,percentage:Math.abs(_),is_increase:B>=0},revenue:{difference:F,percentage:Math.abs(m),is_increase:F>=0},average:{difference:A,percentage:Math.abs(b),is_increase:A>=0}}}}async function Q$(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await p.selectFrom("payments").select((W)=>[W.fn.count("id").as("total_count"),W.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").executeTakeFirst(),K=Number($?.total_count||0),L=await p.selectFrom("payments").select(["method",(W)=>W.fn.count("id").as("count"),(W)=>W.fn.sum("amount").as("revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").groupBy("method").execute(),Y={};return L.forEach((W)=>{let M=Number(W.count||0),Z=Number(W.revenue||0),N=K>0?M/K*100:0;Y[W.method]={count:M,revenue:Z,percentage_of_total:N}}),Y}async function V$(){let G=new Date,J=new Date(G);J.setMonth(G.getMonth()-11),J.setDate(1);let X=await p.selectFrom("payments").selectAll().where("created_at",">=",w(J)).where("status","=","completed").execute(),$={};for(let L of X){let Y=L.created_at?new Date(L.created_at):new Date,W=Y.getFullYear(),M=Y.getMonth()+1,Z=`${W}-${String(M).padStart(2,"0")}`;if(!$[Z])$[Z]={year:W,month:M,transactions:0,revenue:0};$[Z].transactions++,$[Z].revenue+=Number(L.amount||0)}return Object.keys($).sort().map((L)=>{let Y=$[L],W=Y.transactions,M=Y.revenue,Z=W>0?M/W:0;return{month:new Date(Y.year,Y.month-1,1).toLocaleString("default",{month:"short"}),year:Y.year,transactions:W,revenue:M,average:Z}})}var{randomUUIDv7:a9}=globalThis.Bun;import{db as B$}from"@stacksjs/database";import{HttpError as A$}from"@stacksjs/error-handling";import{isUniqueViolation as t9}from"@stacksjs/orm";async function z$(G){let J={...G,status:G.status||"PENDING",currency:G.currency||"USD",uuid:a9()};try{let X=await B$.insertInto("payments").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if($)return await B$.selectFrom("payments").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof A$)throw X;if(t9(X))throw new A$(409,"A payment with this transaction ID already exists");if(X instanceof Error){if(X.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${X.message}`)}throw X}}import{db as r9}from"@stacksjs/database";import{formatDate as e9}from"@stacksjs/orm";async function E$(G,J){if(!await xJ(G))throw Error(`Payment with ID ${G} not found`);try{return await r9.updateTable("payments").set({...J,updated_at:e9(new Date)}).where("id","=",G).execute(),await xJ(G)}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry")&&$.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${$.message}`)}throw $}}var oG={};Q(oG,{variants:()=>pJ,units:()=>DJ,reviews:()=>yJ,manufacturers:()=>gJ,items:()=>hJ,default:()=>WK,categories:()=>vJ});var vJ={};Q(vJ,{updateParent:()=>D$,updateDisplayOrder:()=>g$,updateActiveStatus:()=>y$,update:()=>h$,store:()=>mG,removeChildCategories:()=>C$,remove:()=>k$,findOrCreateByName:()=>v$,fetchStats:()=>q$,fetchRootCategories:()=>U$,fetchChildCategories:()=>T$,fetchCategoryTree:()=>j$,fetchByName:()=>O$,fetchById:()=>U,fetchByDisplayOrder:()=>S$,fetchAll:()=>pG,fetchActive:()=>R$,deactivateChildCategories:()=>I$,deactivate:()=>_$,compareCategoryGrowth:()=>P$,bulkRemove:()=>w$});import{db as u}from"@stacksjs/database";import{db as P}from"@stacksjs/database";import{formatDate as HJ}from"@stacksjs/orm";async function pG(){return await P.selectFrom("categories").selectAll().execute()}async function U(G){return await P.selectFrom("categories").where("id","=",G).selectAll().executeTakeFirst()}async function O$(G){return await P.selectFrom("categories").where("name","=",G).selectAll().executeTakeFirst()}async function R$(){return await P.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function U$(){return await P.selectFrom("categories").where("parent_category_id","is",null).where("is_active","=",!0).selectAll().execute()}async function T$(G){return await P.selectFrom("categories").where("parent_category_id","=",G).where("is_active","=",!0).selectAll().execute()}async function S$(G=!0){let J=P.selectFrom("categories").where("is_active","=",!0).selectAll();if(G)return await J.orderBy("display_order","asc").execute();else return await J.orderBy("display_order","desc").execute()}async function q$(){let G=await P.selectFrom("categories").select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),J=await P.selectFrom("categories").where("is_active","=",!0).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("categories").where("parent_category_id","is",null).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),$=await P.selectFrom("categories").where("image_url","is not",null).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),K=new Date;K.setDate(K.getDate()-30);let L=HJ(K),Y=await P.selectFrom("categories").where("created_at",">=",L).selectAll().limit(5).execute(),W=await P.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").where("c.parent_category_id","is not",null).select(["c.parent_category_id","parent.name as parent_name",(M)=>M.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(G?.count||0),active:Number(J?.count||0),root_categories:Number(X?.count||0),child_categories:Number(G?.count||0)-Number(X?.count||0),with_images:Number($?.count||0),recently_added:Y,top_parent_categories:W.map((M)=>({id:String(M.parent_category_id||""),name:String(M.parent_name||""),child_count:Number(M.child_count)}))}}async function P$(G=30){let J=new Date,X=HJ(J),$=new Date;$.setDate(J.getDate()-G);let K=HJ($),L=new Date($);L.setDate(L.getDate()-1);let Y=HJ(L),W=new Date(L);W.setDate(L.getDate()-G);let M=HJ(W),Z=await P.selectFrom("categories").select((F)=>F.fn.count("id").as("count")).where("created_at",">=",K).where("created_at","<=",X).executeTakeFirst(),N=await P.selectFrom("categories").select((F)=>F.fn.count("id").as("count")).where("created_at",">=",M).where("created_at","<=",Y).executeTakeFirst(),x=Number(Z?.count||0),H=Number(N?.count||0),E=x-H,B=H!==0?E/H*100:x>0?100:0;return{current_period:x,previous_period:H,difference:E,percentage_change:B,days_range:G}}async function j$(){let G=await pG(),J=new Map;G.forEach((K)=>{J.set(K.id,{...K,children:[]})});let X=[];G.forEach((K)=>{let L=J.get(K.id);if(K.parent_category_id){let Y=J.get(K.parent_category_id);if(Y)Y.children.push(L)}else X.push(L)}),X.sort((K,L)=>K.display_order-L.display_order);let $=(K)=>{K.sort((L,Y)=>L.display_order-Y.display_order),K.forEach((L)=>{if(L.children.length>0)$(L.children)})};return $(X),X}async function k$(G){if(!await U(G))throw Error(`Category with ID ${G} not found`);return!!await u.deleteFrom("categories").where("id","=",G).executeTakeFirst()}async function w$(G){if(!G.length)return 0;let J=await u.deleteFrom("categories").where("id","in",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}async function C$(G){let J=await u.deleteFrom("categories").where("parent_category_id","=",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}async function _$(G){if(!await U(G))throw Error(`Category with ID ${G} not found`);return!!await u.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",G).executeTakeFirst()}async function I$(G){let J=await u.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",G).execute();return Number(J.length)||0}import{db as f$}from"@stacksjs/database";import{slug as JK}from"@stacksjs/strings";async function mG(G){try{let J={...G,slug:G.name?.toLowerCase().replace(/\s+/g,"-")||"",categorizable_type:"product",display_order:0},X=await f$.insertInto("categories").values(J).executeTakeFirst();if(!X)throw Error("Failed to create category");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await U($);if(!K)throw Error("Failed to create category");return K}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry")&&J.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to create category: ${J.message}`)}throw J}}async function v$(G){if(!G.name)throw Error("Name is required");let J=await f$.selectFrom("categories").selectAll().where("name","=",G.name).executeTakeFirst();if(J)return J;let X={name:G.name,slug:JK(G.name),is_active:G.is_active??!0,categorizable_type:G.categorizable_type??"default",display_order:0};return await mG(X)}import{db as FJ}from"@stacksjs/database";import{formatDate as fJ}from"@stacksjs/orm";async function h$(G,J){await J.validate();let X=await U(G);if(!X)throw Error(`Category with ID ${G} not found`);let $={name:J.get("name"),description:J.get("description"),imageUrl:J.get("imageUrl"),isActive:J.get("isActive"),parentCategoryId:J.get("parentCategoryId"),displayOrder:J.get("displayOrder"),updated_at:fJ(new Date)};if(Object.keys($).length===0)return X;try{return await FJ.updateTable("categories").set($).where("id","=",G).execute(),await U(G)}catch(K){if(K instanceof Error){if(K.message.includes("Duplicate entry")&&K.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to update category: ${K.message}`)}throw K}}async function g$(G,J){if(!await U(G))throw Error(`Category with ID ${G} not found`);try{return await FJ.updateTable("categories").set({display_order:J,updated_at:fJ(new Date)}).where("id","=",G).execute(),await U(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category display order: ${$.message}`);throw $}}async function y$(G,J){if(!await U(G))throw Error(`Category with ID ${G} not found`);try{return await FJ.updateTable("categories").set({is_active:J,updated_at:fJ(new Date)}).where("id","=",G).execute(),await U(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category active status: ${$.message}`);throw $}}async function D$(G,J){if(!await U(G))throw Error(`Category with ID ${G} not found`);if(J){let $=Number(J);if($===G)throw Error("A category cannot be its own parent");if(!await U($))throw Error(`Parent category with ID ${J} not found`);if(await GK(G,J))throw Error("This operation would create a circular reference in the category hierarchy")}try{let $={updated_at:fJ(new Date)};if(J===null)await FJ.updateTable("categories").set({...$,parent_category_id:void 0}).where("id","=",G).execute();else await FJ.updateTable("categories").set({...$,parent_category_id:J}).where("id","=",G).execute();return await U(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category parent: ${$.message}`);throw $}}async function GK(G,J){let X=Number(J),$=new Set;while(X){if($.has(X))return!0;if(X===G)return!0;$.add(X);let K=await U(X);if(!K||!K.parentCategoryId)return!1;X=Number(K.parentCategoryId)}return!1}var hJ={};Q(hJ,{updateInventory:()=>a$,updateAvailability:()=>d$,update:()=>s$,store:()=>o$,fetchTopProducts:()=>c$,fetchById:()=>g,fetchAll:()=>l$,destroy:()=>m$,bulkStore:()=>i$,bulkDestroy:()=>b$});import{db as p$}from"@stacksjs/database";async function m$(G){try{let J=await p$.deleteFrom("products").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product item: ${J.message}`);throw J}}async function b$(G){if(!G.length)return 0;try{let J=await p$.deleteFrom("products").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product items: ${J.message}`);throw J}}import{db as n}from"@stacksjs/database";async function g(G){let J=await n.selectFrom("products").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=null,$=null;if(J.manufacturer_id)X=await n.selectFrom("manufacturers").where("id","=",J.manufacturer_id).selectAll().executeTakeFirst();if(J.category_id)$=await n.selectFrom("categories").where("id","=",J.category_id).selectAll().executeTakeFirst();return{...J,manufacturer:X,category:$}}return}async function l$(){let G=await n.selectFrom("products").selectAll().execute(),J=G.map((Z)=>Z.manufacturer_id).filter((Z)=>Z!==null&&Z!==void 0),X=G.map((Z)=>Z.category_id).filter((Z)=>Z!==null&&Z!==void 0),$=n.selectFrom("manufacturers"),K=n.selectFrom("categories");if(J.length>0)$=$.where("id","in",J);if(X.length>0)K=K.where("id","in",X);let L=await $.selectAll().execute(),Y=await K.selectAll().execute(),W=L.reduce((Z,N)=>{return Z[N.id]=N,Z},{}),M=Y.reduce((Z,N)=>{return Z[N.id]=N,Z},{});return G.map((Z)=>({...Z,manufacturer:Z.manufacturer_id?W[Z.manufacturer_id]:null,category:Z.category_id?M[Z.category_id]:null}))}async function c$(G=5){try{return(await n.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",(X)=>X.fn.sum("order_items.quantity").as("units_sold"),(X)=>X.raw("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(G).execute()).map((X)=>({id:Number(X.id),name:String(X.name??"Unnamed product"),units_sold:Number(X.units_sold??0),revenue:Number(X.revenue??0),inventory_count:Number(X.inventory_count??0)}))}catch(J){if(J instanceof Error)throw TypeError(`Failed to fetch top products: ${J.message}`);throw J}}var{randomUUIDv7:u$}=globalThis.Bun;import{db as n$}from"@stacksjs/database";async function o$(G){try{let J={...G,uuid:u$()},X=await n$.insertInto("products").values(J).executeTakeFirst();if(!X)throw Error("Failed to create product item");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await g($);if(!K)throw Error("Failed to create product item");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product item: ${J.message}`);throw J}}async function i$(G){if(!G.length)return 0;let J=0;try{return await n$.transaction().execute(async(X)=>{for(let $ of G){let K={...$,uuid:u$()};await X.insertInto("products").values(K).execute(),J++}}),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product items in bulk: ${X.message}`);throw X}}import{db as bG,sql as f0}from"@stacksjs/database";import{formatDate as lG}from"@stacksjs/orm";async function s$(G,J){try{if(!G)throw Error("Product item ID is required for update");let X=await bG.updateTable("products").set({...J,updated_at:lG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product item");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item: ${X.message}`);throw X}}async function d$(G,J){if(!await g(G))throw Error(`Product item with ID ${G} not found`);try{return await bG.updateTable("products").set({is_available:J,updated_at:lG(new Date)}).where("id","=",G).execute(),await g(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update product item availability: ${$.message}`);throw $}}async function a$(G,J){let X=await g(G);if(!X)throw Error(`Product item with ID ${G} not found`);let $={updated_at:lG(new Date)};if(J!==void 0)$.inventory_count=J;if(Object.keys($).length===1)return X;try{return await bG.updateTable("products").set($).where("id","=",G).execute(),await g(G)}catch(K){if(K instanceof Error)throw TypeError(`Failed to update inventory information: ${K.message}`);throw K}}var gJ={};Q(gJ,{updateFeaturedStatus:()=>F2,updateByUuid:()=>Q2,update:()=>H2,store:()=>M2,fetchWithProductCount:()=>L2,fetchFeatured:()=>$2,fetchByUuid:()=>X2,fetchById:()=>G2,fetchByCountry:()=>K2,fetchAll:()=>J2,destroy:()=>r$,bulkStore:()=>N2,bulkDestroy:()=>e$});import{db as t$}from"@stacksjs/database";async function r$(G){try{let J=await t$.deleteFrom("manufacturers").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function e$(G){if(!G.length)return 0;try{let J=await t$.deleteFrom("manufacturers").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}import{db as o}from"@stacksjs/database";function J2(){return o.selectFrom("manufacturers").selectAll().execute()}async function G2(G){return await o.selectFrom("manufacturers").where("id","=",G).selectAll().executeTakeFirst()}async function X2(G){return await o.selectFrom("manufacturers").where("uuid","=",G).selectAll().executeTakeFirst()}async function $2(G=10){return await o.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(G).execute()}async function K2(G,J={}){let X=J.page||1,$=J.limit||2,K=await o.selectFrom("manufacturers").select((M)=>M.fn.count("id").as("total")).where("country","=",G).executeTakeFirst(),L=Number(K?.total||0),Y=await o.selectFrom("manufacturers").selectAll().where("country","=",G).limit($).offset((X-1)*$).execute(),W=Math.ceil(L/$);return{data:Y,paging:{total_records:L,page:X,total_pages:W},next_cursor:X<W?X+1:null}}async function L2(G={}){let J=o.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(G.country)J=J.where("m.country","=",G.country);if(G.featured!==void 0)J=J.where("m.featured","=",G.featured);return J=J.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",(X)=>X.fn.count("p.id").as("product_count")]).groupBy("m.id"),J.execute()}var{randomUUIDv7:W2}=globalThis.Bun;import{db as Z2}from"@stacksjs/database";import{HttpError as Y2}from"@stacksjs/error-handling";import{isUniqueViolation as XK}from"@stacksjs/orm";async function M2(G){try{let J={...G,uuid:W2(),featured:G.featured??!1},X=await Z2.insertInto("manufacturers").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create manufacturer");return X}catch(J){if(J instanceof Y2)throw J;if(XK(J))throw new Y2(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to create manufacturer: ${J.message}`);throw J}}async function N2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:W2(),featured:X.featured??!1};await Z2.insertInto("manufacturers").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${X.message}`);throw X}}import{db as cG}from"@stacksjs/database";import{HttpError as x2}from"@stacksjs/error-handling";import{formatDate as uG,isUniqueViolation as $K}from"@stacksjs/orm";async function H2(G,J){try{if(!G)throw Error("Manufacturer ID is required for update");let X=await cG.updateTable("manufacturers").set({...J,updated_at:uG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error(`Manufacturer with ID ${G} not found`);return X}catch(X){if(X instanceof x2)throw X;if($K(X))throw new x2(409,"A manufacturer with this name already exists");if(X instanceof Error)throw Error(`Failed to update manufacturer: ${X.message}`);throw X}}async function F2(G,J){try{let X=await cG.updateTable("manufacturers").set({featured:J,updated_at:uG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update manufacturer featured status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${X.message}`);throw X}}async function Q2(G,J){try{let X=await cG.updateTable("manufacturers").set({...J,updated_at:uG(new Date)}).where("uuid","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update manufacturer");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update manufacturer: ${X.message}`);throw X}}var yJ={};Q(yJ,{updateVotes:()=>k2,update:()=>j2,store:()=>S2,fetchMostHelpfulByProductId:()=>T2,fetchByUserId:()=>R2,fetchByProductId:()=>O2,fetchById:()=>z2,fetchApprovedByProductId:()=>U2,fetchAll:()=>E2,destroy:()=>B2,bulkDestroy:()=>A2});import{db as V2}from"@stacksjs/database";async function B2(G){try{let J=await V2.deleteFrom("reviews").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function A2(G){if(!G.length)return 0;try{let J=await V2.deleteFrom("reviews").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}import{db as GJ}from"@stacksjs/database";async function z2(G){return await GJ.selectFrom("reviews").where("id","=",G).selectAll().executeTakeFirst()}async function E2(){return await GJ.selectFrom("reviews").selectAll().execute()}async function O2(G){return await GJ.selectFrom("reviews").where("product_id","=",G).selectAll().execute()}async function R2(G){return await GJ.selectFrom("reviews").where("customer_id","=",G).selectAll().execute()}async function U2(G){return await GJ.selectFrom("reviews").where("product_id","=",G).where("is_approved","=",!0).selectAll().execute()}async function T2(G){return await GJ.selectFrom("reviews").where("product_id","=",G).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:KK}=globalThis.Bun;import{db as LK}from"@stacksjs/database";async function S2(G){try{let J={...G,uuid:KK(),is_verified_purchase:G.is_verified_purchase??!1,is_approved:G.is_approved??!1,helpful_votes:G.helpful_votes??0,unhelpful_votes:G.unhelpful_votes??0,is_featured:G.is_featured??!1},X=await LK.insertInto("reviews").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create review");return X}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${J.message}`)}throw J}}import{db as q2}from"@stacksjs/database";import{formatDate as P2}from"@stacksjs/orm";async function j2(G,J){try{if(!G)throw Error("Review ID is required for update");let X=await q2.updateTable("reviews").set({...J,updated_at:P2(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update review");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review: ${X.message}`);throw X}}async function k2(G,J,X=!0){try{let $=J==="helpful"?"helpful_votes":"unhelpful_votes",K=X?`COALESCE("${$}", 0) + 1`:`MAX(COALESCE("${$}", 0) - 1, 0)`,L=await q2.unsafe(`UPDATE "reviews" SET "${$}" = ${K}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[P2(new Date),G]).execute(),Y=Array.isArray(L)?L[0]:L;if(!Y)throw Error("Failed to update review votes");return Y}catch($){if($ instanceof Error)throw TypeError(`Failed to update review votes: ${$.message}`);throw $}}var DJ={};Q(DJ,{updateDefaultStatus:()=>l2,update:()=>m2,store:()=>g2,getDefaultUnit:()=>p2,formatUnitOptions:()=>D2,fetchById:()=>f2,fetchAll:()=>v2,destroy:()=>C2,bulkUpdate:()=>b2,bulkStore:()=>y2,bulkDestroy:()=>_2});import{db as w2}from"@stacksjs/database";async function C2(G){try{let J=await w2.deleteFrom("product_units").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product unit: ${J.message}`);throw J}}async function _2(G){if(!G.length)return 0;try{let J=await w2.deleteFrom("product_units").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product units: ${J.message}`);throw J}}import{db as I2}from"@stacksjs/database";async function f2(G){return await I2.selectFrom("product_units").where("id","=",G).selectAll().executeTakeFirst()}async function v2(){return await I2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:h2}=globalThis.Bun;import{db as XJ}from"@stacksjs/database";async function g2(G){try{let J={...G,uuid:h2()},X=await XJ.insertInto("product_units").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(J.is_default)await XJ.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",X.id).execute();return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product unit: ${J.message}`);throw J}}async function y2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:h2()},K=await XJ.insertInto("product_units").values($).returningAll().executeTakeFirst();if($.is_default&&K)await XJ.updateTable("product_units").set({is_default:!1}).where("type","=",$.type).where("id","!=",K.id).execute();J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product units in bulk: ${X.message}`);throw X}}function D2(G){try{let J=XJ.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(G)J=J.where("type","=",G);return J=J.orderBy("name"),J.execute().then((X)=>X.map(($)=>({id:String($.id),name:$.name,abbreviation:$.abbreviation,is_default:$.is_default})))}catch(J){if(J instanceof Error)throw TypeError(`Failed to format unit options: ${J.message}`);throw J}}async function p2(G){try{return await XJ.selectFrom("product_units").selectAll().where("type","=",G).where("is_default","=",!0).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get default unit: ${J.message}`);throw J}}import{db as i}from"@stacksjs/database";import{formatDate as nG}from"@stacksjs/orm";async function m2(G,J){try{if(!G)throw Error("Product unit ID is required for update");let X=await i.updateTable("product_units").set({...J,updated_at:nG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product unit");if(J.is_default===!0&&J.type)await i.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",G).execute();return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product unit: ${X.message}`);throw X}}async function b2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $=X;if(!$.id)continue;let K=$.data&&typeof $.data==="object"?$.data:{...$};delete K.id;let L=await i.updateTable("product_units").set({...K,updated_at:nG(new Date)}).where("id","=",$.id).executeTakeFirst(),Y=K;if(Y.is_default===!0&&Y.type)await i.updateTable("product_units").set({is_default:!1}).where("type","=",Y.type).where("id","!=",$.id).execute();if(Number(L.numUpdatedRows)>0)J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product units in bulk: ${X.message}`);throw X}}async function l2(G,J){try{let X=await i.selectFrom("product_units").select("type").where("id","=",G).executeTakeFirst();if(!X)return!1;let $=await i.updateTable("product_units").set({is_default:J,updated_at:nG(new Date)}).where("id","=",G).executeTakeFirst();if(J&&X.type)await i.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",G).execute();return Number($.numUpdatedRows)>0}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product unit default status: ${X.message}`);throw X}}var pJ={};Q(pJ,{update:()=>$4,store:()=>t2,generateVariantCombinations:()=>J4,formatVariantOptions:()=>e2,fetchById:()=>i2,fetchAll:()=>s2,destroy:()=>u2,bulkUpdate:()=>K4,bulkStore:()=>r2,bulkDestroy:()=>n2});import{db as c2}from"@stacksjs/database";async function u2(G){try{let J=await c2.deleteFrom("product_variants").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variant: ${J.message}`);throw J}}async function n2(G){if(!G.length)return 0;try{let J=await c2.deleteFrom("product_variants").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variants: ${J.message}`);throw J}}import{db as o2}from"@stacksjs/database";async function i2(G){return await o2.selectFrom("product_variants").where("id","=",G).selectAll().executeTakeFirst()}async function s2(){return await o2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:d2}=globalThis.Bun;import{db as a2}from"@stacksjs/database";async function t2(G){try{let J={...G,uuid:d2()},X=await a2.insertInto("product_variants").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product variant");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variant: ${J.message}`);throw J}}async function r2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:d2()};await a2.insertInto("product_variants").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${X.message}`);throw X}}function e2(G){if(!G||!G.length)return JSON.stringify([]);let J=G.map((X)=>X.trim()).filter(Boolean);return JSON.stringify(J)}function J4(G){let J=Object.keys(G);if(!J.length)return[];function X($,K){if($===J.length)return[K];let L=J[$],Y=G[L]??[],W=[];for(let M of Y){let Z={...K,[L]:M};W.push(...X($+1,Z))}return W}return X(0,{})}import{db as G4}from"@stacksjs/database";import{formatDate as X4}from"@stacksjs/orm";async function $4(G,J){try{let X=await G4.updateTable("product_variants").set({...J,updated_at:X4(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product variant");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product variant: ${X.message}`);throw X}}async function K4(G){if(!G.length)return 0;let J=0;try{for(let X of G){if(!X.id)continue;let $=await G4.updateTable("product_variants").set({...X,updated_at:X4(new Date)}).where("id","=",X.id).executeTakeFirst();if(Number($.numUpdatedRows)>0)J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${X.message}`);throw X}}var YK={categories:vJ,items:hJ,manufacturers:gJ,reviews:yJ,units:DJ,variants:pJ},WK=YK;var dG={};Q(dG,{updateStatus:()=>B4,updatePrintJob:()=>A4,update:()=>V4,store:()=>F4,fetchById:()=>M4,fetchAll:()=>N4,destroy:()=>Y4,bulkStore:()=>Q4,bulkDestroy:()=>W4});import{db as L4}from"@stacksjs/database";async function Y4(G){try{let J=await L4.deleteFrom("receipts").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print log: ${J.message}`);throw J}}async function W4(G){if(!G.length)return 0;try{let J=await L4.deleteFrom("receipts").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete receipts: ${J.message}`);throw J}}import{db as Z4}from"@stacksjs/database";async function M4(G){return await Z4.selectFrom("receipts").where("id","=",G).selectAll().executeTakeFirst()}async function N4(){return await Z4.selectFrom("receipts").selectAll().execute()}var{randomUUIDv7:x4}=globalThis.Bun;import{db as H4}from"@stacksjs/database";async function F4(G){try{let J={...G,uuid:x4()},X=await H4.insertInto("receipts").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipt: ${J.message}`);throw J}}async function Q4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:x4()})),X=await H4.insertInto("receipts").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${J.message}`);throw J}}import{db as iG}from"@stacksjs/database";import{formatDate as sG}from"@stacksjs/orm";async function V4(G,J){try{if(!G)throw Error("Receipt ID is required for update");let X=await iG.updateTable("receipts").set({...J,updated_at:sG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update receipt");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt: ${X.message}`);throw X}}async function B4(G,J){try{let X=await iG.updateTable("receipts").set({status:J,updated_at:sG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update receipt status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt status: ${X.message}`);throw X}}async function A4(G,J,X,$){try{let K={updated_at:sG(new Date)};if(J!==void 0)K.size=J;if(X!==void 0)K.pages=X;if($!==void 0)K.duration=$;let L=await iG.updateTable("receipts").set(K).where("id","=",G).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update receipt job information");return L}catch(K){if(K instanceof Error)throw TypeError(`Failed to update receipt job information: ${K.message}`);throw K}}var WX={};Q(WX,{zones:()=>ZG,routes:()=>bJ,rates:()=>KG,methods:()=>rJ,licenses:()=>sJ,drivers:()=>nJ,digital:()=>uJ,default:()=>NK});var bJ={};Q(bJ,{updateStops:()=>w4,updateMetrics:()=>C4,updateLastActive:()=>j4,update:()=>k4,store:()=>P4,fetchById:()=>R4,fetchByDriver:()=>S4,fetchAll:()=>U4,fetchActive:()=>T4,destroy:()=>E4,bulkDestroy:()=>O4});import{db as z4}from"@stacksjs/database";async function E4(G){try{let J=await z4.deleteFrom("delivery_routes").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery route: ${J.message}`);throw J}}async function O4(G){if(!G.length)return 0;try{let J=await z4.deleteFrom("delivery_routes").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery routes: ${J.message}`);throw J}}import{db as mJ}from"@stacksjs/database";async function R4(G){return await mJ.selectFrom("delivery_routes").where("id","=",G).selectAll().executeTakeFirst()}async function U4(){return await mJ.selectFrom("delivery_routes").selectAll().execute()}async function T4(){return await mJ.selectFrom("delivery_routes").where("last_active","<=",new Date(Date.now()-86400000)).selectAll().execute()}async function S4(G){return await mJ.selectFrom("delivery_routes").where("driver","=",G).selectAll().execute()}var{randomUUIDv7:ZK}=globalThis.Bun;import{db as q4}from"@stacksjs/database";async function P4(G){try{let J={...G,uuid:ZK()},X=await q4.insertInto("delivery_routes").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create delivery route");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create delivery route: ${J.message}`);throw J}}async function j4(G){try{let J=await q4.updateTable("delivery_routes").set({last_active:new Date().toISOString(),updated_at:new Date().toISOString()}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update delivery route last active");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route last active: ${J.message}`);throw J}}import{db as aG}from"@stacksjs/database";import{formatDate as tG}from"@stacksjs/orm";async function k4(G,J){try{if(!G)throw Error("Delivery route ID is required for update");let X=await aG.updateTable("delivery_routes").set({...J,updated_at:tG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery route");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery route: ${X.message}`);throw X}}async function w4(G,J){try{let X=await aG.updateTable("delivery_routes").set({stops:J,updated_at:tG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery route stops");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery route stops: ${X.message}`);throw X}}async function C4(G,J,X){try{let $={updated_at:tG(new Date)};if(J!==void 0)$.delivery_time=J;if(X!==void 0)$.total_distance=X;let K=await aG.updateTable("delivery_routes").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update delivery metrics");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery metrics: ${$.message}`);throw $}}var uJ={};Q(uJ,{updateStatus:()=>l4,updateDeliverySettings:()=>c4,update:()=>b4,store:()=>p4,softDelete:()=>I4,fetchById:()=>cJ,fetchAll:()=>g4,destroy:()=>_4,bulkStore:()=>m4,bulkSoftDelete:()=>v4,bulkDestroy:()=>f4});import{db as lJ}from"@stacksjs/database";async function _4(G){try{let J=await lJ.deleteFrom("digital_deliveries").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital delivery: ${J.message}`);throw J}}async function I4(G){try{let J=await lJ.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${J.message}`);throw J}}async function f4(G){if(!G.length)return 0;try{let J=await lJ.deleteFrom("digital_deliveries").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${J.message}`);throw J}}async function v4(G){if(!G.length)return 0;try{let J=await lJ.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${J.message}`);throw J}}import{db as h4}from"@stacksjs/database";async function cJ(G){return await h4.selectFrom("digital_deliveries").where("id","=",G).selectAll().executeTakeFirst()}async function g4(){return await h4.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:y4}=globalThis.Bun;import{db as D4}from"@stacksjs/database";async function p4(G){try{let J={...G,uuid:y4()},X=await D4.insertInto("digital_deliveries").values(J).executeTakeFirst();if(!X)throw Error("Failed to create digital delivery");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await cJ($);if(!K)throw Error("Failed to create digital delivery");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital delivery: ${J.message}`);throw J}}async function m4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:y4()})),X=await D4.insertInto("digital_deliveries").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${J.message}`);throw J}}import{db as rG}from"@stacksjs/database";import{formatDate as eG}from"@stacksjs/orm";async function b4(G,J){try{if(!G)throw Error("Digital delivery ID is required for update");let X=await rG.updateTable("digital_deliveries").set({...J,updated_at:eG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update digital delivery");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update digital delivery: ${X.message}`);throw X}}async function l4(G,J){try{let X=await rG.updateTable("digital_deliveries").set({status:J,updated_at:eG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update digital delivery status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update digital delivery status: ${X.message}`);throw X}}async function c4(G,J,X,$,K){try{let L={updated_at:eG(new Date)};if(J!==void 0)L.download_limit=J;if(X!==void 0)L.expiry_days=X;if($!==void 0)L.requires_login=$;if(K!==void 0)L.automatic_delivery=K;let Y=await rG.updateTable("digital_deliveries").set(L).where("id","=",G).returningAll().executeTakeFirst();if(!Y)throw Error("Failed to update delivery settings");return Y}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery settings: ${L.message}`);throw L}}var nJ={};Q(nJ,{updateStatus:()=>J7,updateContact:()=>G7,update:()=>e4,store:()=>t4,fetchById:()=>QJ,fetchAll:()=>n4,destroy:()=>i4,bulkStore:()=>r4,bulkDestroy:()=>s4});import{db as o4}from"@stacksjs/database";import{db as u4}from"@stacksjs/database";async function QJ(G){return await u4.selectFrom("drivers").where("id","=",G).selectAll().executeTakeFirst()}async function n4(){return await u4.selectFrom("drivers").selectAll().execute()}async function i4(G){let J=await QJ(G);if(!J)throw Error(`Driver with ID ${G} not found`);try{return await o4.deleteFrom("drivers").where("id","=",G).execute(),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to delete driver: ${X.message}`);throw X}}async function s4(G){if(!G.length)return 0;let J=0;try{return await o4.transaction().execute(async(X)=>{for(let $ of G)if(await QJ($))await X.deleteFrom("drivers").where("id","=",$).execute(),J++}),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${X.message}`);throw X}}var{randomUUIDv7:d4}=globalThis.Bun;import{db as a4}from"@stacksjs/database";async function t4(G){try{let J={...G,uuid:d4()},X=await a4.insertInto("drivers").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create driver");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create driver: ${J.message}`);throw J}}async function r4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:d4()})),X=await a4.insertInto("drivers").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${J.message}`);throw J}}import{db as JX}from"@stacksjs/database";import{formatDate as GX}from"@stacksjs/orm";async function e4(G,J){try{if(!G)throw Error("Driver ID is required for update");let X=await JX.updateTable("drivers").set({...J,updated_at:GX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update driver");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update driver: ${X.message}`);throw X}}async function J7(G,J){try{let X=await JX.updateTable("drivers").set({status:J,updated_at:GX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update driver status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update driver status: ${X.message}`);throw X}}async function G7(G,J){try{let X={updated_at:GX(new Date)};if(J!==void 0)X.phone=J;let $=await JX.updateTable("drivers").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update contact information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update contact information: ${X.message}`);throw X}}var sJ={};Q(sJ,{updateStatus:()=>F7,updateExpiration:()=>Q7,update:()=>H7,store:()=>N7,softDelete:()=>$7,fetchById:()=>iJ,fetchAll:()=>W7,destroy:()=>X7,bulkStore:()=>x7,bulkSoftDelete:()=>L7,bulkDestroy:()=>K7});import{db as oJ}from"@stacksjs/database";async function X7(G){try{let J=await oJ.deleteFrom("license_keys").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license key: ${J.message}`);throw J}}async function $7(G){try{let J=await oJ.updateTable("license_keys").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license key: ${J.message}`);throw J}}async function K7(G){if(!G.length)return 0;try{let J=await oJ.deleteFrom("license_keys").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license keys: ${J.message}`);throw J}}async function L7(G){if(!G.length)return 0;try{let J=await oJ.updateTable("license_keys").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license keys: ${J.message}`);throw J}}import{db as Y7}from"@stacksjs/database";async function iJ(G){return await Y7.selectFrom("license_keys").where("id","=",G).selectAll().executeTakeFirst()}async function W7(){return await Y7.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:Z7}=globalThis.Bun;import{db as M7}from"@stacksjs/database";async function N7(G){try{let J={...G,uuid:Z7()},X=await M7.insertInto("license_keys").values(J).executeTakeFirst();if(!X)throw Error("Failed to create license key");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await iJ($);if(!K)throw Error("Failed to create license key");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create license key: ${J.message}`);throw J}}async function x7(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:Z7()})),X=await M7.insertInto("license_keys").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${J.message}`);throw J}}import{db as XX}from"@stacksjs/database";import{formatDate as $X}from"@stacksjs/orm";async function H7(G,J){try{if(!G)throw Error("License key ID is required for update");let X=await XX.updateTable("license_keys").set({...J,updated_at:$X(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update license key");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update license key: ${X.message}`);throw X}}async function F7(G,J){try{let X=await XX.updateTable("license_keys").set({status:J,updated_at:$X(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update license key status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update license key status: ${X.message}`);throw X}}async function Q7(G,J){try{let X={updated_at:$X(new Date)};if(J!==void 0)X.expiry_date=J;let $=await XX.updateTable("license_keys").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update expiration information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update expiration information: ${X.message}`);throw X}}var rJ={};Q(rJ,{updateStatus:()=>P7,updatePricing:()=>j7,update:()=>q7,store:()=>R7,softDelete:()=>B7,getActiveShippingMethods:()=>S7,formatShippingOptions:()=>T7,fetchById:()=>s,fetchAll:()=>E7,destroy:()=>V7,bulkStore:()=>U7,bulkSoftDelete:()=>z7,bulkDestroy:()=>A7});import{db as dJ}from"@stacksjs/database";async function V7(G){try{let J=await dJ.deleteFrom("shipping_methods").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping method: ${J.message}`);throw J}}async function B7(G){try{let J=await dJ.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${J.message}`);throw J}}async function A7(G){if(!G.length)return 0;try{let J=await dJ.deleteFrom("shipping_methods").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping methods: ${J.message}`);throw J}}async function z7(G){if(!G.length)return 0;try{let J=await dJ.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${J.message}`);throw J}}import{db as aJ}from"@stacksjs/database";async function s(G){let J=await aJ.selectFrom("shipping_methods").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=await aJ.selectFrom("shipping_zones").where("shipping_method_id","=",G).selectAll().execute();return{...J,shippingZones:X}}return}async function E7(){let G=await aJ.selectFrom("shipping_methods").selectAll().execute(),J=G.map((L)=>L.id),X=aJ.selectFrom("shipping_zones");if(J.length>0)X=X.where("shipping_method_id","in",J);let K=(await X.selectAll().execute()).reduce((L,Y)=>{let W=Y.shipping_method_id;if(W!==null&&W!==void 0){if(!L[W])L[W]=[];L[W].push(Y)}return L},{});return G.map((L)=>({...L,shipping_zones:K[L.id]||[]}))}var{randomUUIDv7:O7}=globalThis.Bun;import{db as tJ}from"@stacksjs/database";async function R7(G){try{let J=G,X={name:G.name,description:G.description,base_rate:J.base_rate,free_shipping:J.free_shipping,status:G.status,uuid:O7()},$=await tJ.insertInto("shipping_methods").values(X).executeTakeFirst();if(!$)throw Error("Failed to create shipping method");let K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);return await s(K)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping method: ${J.message}`);throw J}}async function U7(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:O7()})),X=await tJ.insertInto("shipping_methods").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${J.message}`);throw J}}function T7(){try{return tJ.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping options: ${G.message}`);throw G}}async function S7(){try{return await tJ.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get active shipping methods: ${G.message}`);throw G}}import{db as KX}from"@stacksjs/database";import{formatDate as LX}from"@stacksjs/orm";async function q7(G,J){try{if(!G)throw Error("Shipping method ID is required for update");let X=await KX.updateTable("shipping_methods").set({...J,updated_at:LX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping method");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping method: ${X.message}`);throw X}}async function P7(G,J){try{let X=await KX.updateTable("shipping_methods").set({status:J,updated_at:LX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping method status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping method status: ${X.message}`);throw X}}async function j7(G,J,X){try{let $={updated_at:LX(new Date)};if(J!==void 0)$.base_rate=J;if(X!==void 0)$.free_shipping=X;let K=await KX.updateTable("shipping_methods").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update pricing information");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update pricing information: ${$.message}`);throw $}}var KG={};Q(KG,{validateZoneMatchesAddress:()=>g7,updateByZone:()=>d7,updateByMethod:()=>a7,update:()=>i7,store:()=>n7,resolveZoneForAddress:()=>GG,getShippingRatesByMethod:()=>D7,getRatesByZone:()=>v7,getRateByWeightAndZone:()=>YX,getRateByWeightAndAddress:()=>h7,formatShippingRateOptions:()=>y7,fetchById:()=>JG,fetchAll:()=>f7,destroyByZone:()=>C7,destroyByMethod:()=>_7,destroy:()=>k7,bulkUpdate:()=>s7,bulkStore:()=>o7,bulkDestroy:()=>w7});import{db as eJ}from"@stacksjs/database";async function k7(G){try{let J=await eJ.deleteFrom("shipping_rates").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rate: ${J.message}`);throw J}}async function w7(G){if(!G.length)return 0;try{let J=await eJ.deleteFrom("shipping_rates").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates: ${J.message}`);throw J}}async function C7(G){try{let J=await eJ.deleteFrom("shipping_rates").where("zone","=",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${J.message}`);throw J}}async function _7(G){try{let J=await eJ.deleteFrom("shipping_rates").where("method","=",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${J.message}`);throw J}}import{db as C}from"@stacksjs/database";async function JG(G){let J=await C.selectFrom("shipping_rates").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=null,$=null;if(J.shipping_zone_id)X=await C.selectFrom("shipping_zones").where("id","=",J.shipping_zone_id).selectAll().executeTakeFirst();if(J.shipping_method_id)$=await C.selectFrom("shipping_methods").where("id","=",J.shipping_method_id).selectAll().executeTakeFirst();return{...J,shipping_zone:X,shipping_method:$}}return}async function f7(){let G=await C.selectFrom("shipping_rates").selectAll().execute(),J=G.map((Z)=>Z.shipping_zone_id).filter((Z)=>Z!==null&&Z!==void 0),X=G.map((Z)=>Z.shipping_method_id).filter((Z)=>Z!==null&&Z!==void 0),$=C.selectFrom("shipping_zones"),K=C.selectFrom("shipping_methods");if(J.length>0)$=$.where("id","in",J);if(X.length>0)K=K.where("id","in",X);let L=await $.selectAll().execute(),Y=await K.selectAll().execute(),W=L.reduce((Z,N)=>{return Z[N.id]=N,Z},{}),M=Y.reduce((Z,N)=>{return Z[N.id]=N,Z},{});return G.map((Z)=>({...Z,shipping_zone:Z.shipping_zone_id?W[Z.shipping_zone_id]:[],shipping_method:Z.shipping_method_id?M[Z.shipping_method_id]:[]}))}async function v7(G){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",G).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${J.message}`);throw J}}async function YX(G,J){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).where("weight_from","<=",G).where("weight_to",">=",G).executeTakeFirst()}catch(X){if(X instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${X.message}`);throw X}}async function GG(G){if(!G?.countryCode)return null;try{let J=await C.selectFrom("shipping_zones").selectAll().where("countries","like",`%${G.countryCode}%`).where("status","=","active").execute();if(J.length===0)return null;let X=null;for(let $ of J){let K=1;if(G.region&&$.regions&&I7($.regions,G.region))K=2;if(G.postalCode&&$.postal_codes&&I7($.postal_codes,G.postalCode))K=3;if(!X||K>X.score)X={id:$.id,score:K}}return X?.id??null}catch{return null}}async function h7(G,J){let X=await GG(J);if(X==null)return;return YX(G,X)}async function g7(G,J){return await GG(J)===G}function I7(G,J){if(!G||!J)return!1;let X=J.trim().toUpperCase();for(let $ of G.split(/[,|;]/))if($.trim().toUpperCase()===X)return!0;return!1}async function y7(){try{return(await C.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((J)=>J.shipping_method_id!==null&&J.shipping_method_id!==void 0&&J.shipping_zone_id!==null&&J.shipping_zone_id!==void 0)}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping rate options: ${G.message}`);throw G}}async function D7(G){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",G).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${J.message}`);throw J}}var{randomUUIDv7:c7}=globalThis.Bun;import{db as u7}from"@stacksjs/database";import{db as VJ}from"@stacksjs/database";async function p7(){return await VJ.selectFrom("shipping_zones").selectAll().execute()}async function d(G){return await VJ.selectFrom("shipping_zones").where("id","=",G).selectAll().executeTakeFirst()}function m7(){try{return VJ.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping zone options: ${G.message}`);throw G}}async function b7(){try{return await VJ.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get active shipping zones: ${G.message}`);throw G}}async function l7(G){try{return await VJ.selectFrom("shipping_zones").selectAll().where("countries","like",`%${G}%`).where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${J.message}`);throw J}}async function n7(G){try{let J=await s(Number(G.shippingmethod_id)),X=await d(Number(G.shippingzone_id)),$={weightFrom:G.weightFrom,weightTo:G.weightTo,rate:G.rate,shippingmethod_id:J?.id,shippingzone_id:X?.id,uuid:c7()},K=await u7.insertInto("shipping_rates").values($).executeTakeFirst();if(!K)throw Error("Failed to create shipping rate");let L=Number(K.insertId)||Number(K.numInsertedOrUpdatedRows);return await JG(L)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping rate: ${J.message}`);throw J}}async function o7(G){if(!G.length)return 0;try{for(let $ of G){let K=await s(Number($.shippingmethod_id)),L=await d(Number($.shippingzone_id));if(!K)console.warn(`Shipping method with ID "${$.shippingmethod_id}" not found for bulk insert`);if(!L)console.warn(`Shipping zone with ID "${$.shippingzone_id}" not found for bulk insert`)}let J=G.map(($)=>({weightFrom:$.weightFrom,weightTo:$.weightTo,rate:$.rate,shippingmethod_id:$.shippingmethod_id,shippingzone_id:$.shippingzone_id,uuid:c7()})),X=await u7.insertInto("shipping_rates").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${J.message}`);throw J}}import{db as XG}from"@stacksjs/database";import{formatDate as $G}from"@stacksjs/orm";async function i7(G,J){try{if(!G)throw Error("Shipping rate ID is required for update");let X=await XG.updateTable("shipping_rates").set({...J,updated_at:$G(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping rate");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rate: ${X.message}`);throw X}}async function s7(G){if(!G.length)return 0;try{let J=0;for(let{id:X,data:$}of G){let K=await XG.updateTable("shipping_rates").set({...$,updated_at:$G(new Date)}).where("id","=",X).executeTakeFirst();if(Number(K.numUpdatedRows)>0)J++}return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${J.message}`);throw J}}async function d7(G,J){try{let X=await XG.updateTable("shipping_rates").set({...J,updated_at:$G(new Date)}).where("zone_id","=",G).executeTakeFirst();return Number(X.numUpdatedRows)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${X.message}`);throw X}}async function a7(G,J){try{let X=await XG.updateTable("shipping_rates").set({...J,updated_at:$G(new Date)}).where("method","=",G).executeTakeFirst();return Number(X.numUpdatedRows)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${X.message}`);throw X}}var ZG={};Q(ZG,{updateStatus:()=>Y1,updateRegionsAndPostalCodes:()=>Z1,updateCountries:()=>W1,update:()=>L1,store:()=>$1,softDelete:()=>r7,getZonesByCountry:()=>l7,getActiveShippingZones:()=>b7,formatZoneOptions:()=>m7,fetchById:()=>d,fetchAll:()=>p7,destroy:()=>t7,bulkStore:()=>K1,bulkSoftDelete:()=>J1,bulkDestroy:()=>e7});import{db as LG}from"@stacksjs/database";async function t7(G){try{let J=await LG.deleteFrom("shipping_zones").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zone: ${J.message}`);throw J}}async function r7(G){try{let J=await LG.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${J.message}`);throw J}}async function e7(G){if(!G.length)return 0;try{let J=await LG.deleteFrom("shipping_zones").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zones: ${J.message}`);throw J}}async function J1(G){if(!G.length)return 0;try{let J=await LG.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${J.message}`);throw J}}var{randomUUIDv7:G1}=globalThis.Bun;import{db as X1}from"@stacksjs/database";async function $1(G){try{let J={...G,uuid:G1()},X=await X1.insertInto("shipping_zones").values(J).executeTakeFirst();if(!X)throw Error("Failed to create shipping zone");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await d($)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zone: ${J.message}`);throw J}}async function K1(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:G1()})),X=await X1.insertInto("shipping_zones").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${J.message}`);throw J}}import{db as YG}from"@stacksjs/database";import{formatDate as WG}from"@stacksjs/orm";async function L1(G,J){try{if(!G)throw Error("Shipping zone ID is required for update");let X=await YG.updateTable("shipping_zones").set({...J,updated_at:WG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone: ${X.message}`);throw X}}async function Y1(G,J){try{let X=await YG.updateTable("shipping_zones").set({status:J,updated_at:WG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone status: ${X.message}`);throw X}}async function W1(G,J){try{let X=await YG.updateTable("shipping_zones").set({countries:J,updated_at:WG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone countries");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${X.message}`);throw X}}async function Z1(G,J,X){try{let $={updated_at:WG(new Date)};if(J!==void 0)$.regions=J;if(X!==void 0)$.postal_codes=X;let K=await YG.updateTable("shipping_zones").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update regions and postal codes");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${$.message}`);throw $}}var MK={digital:uJ,drivers:nJ,licenses:sJ,methods:rJ,rates:KG,routes:bJ,zones:ZG},NK=MK;var NX={};Q(NX,{updateStatus:()=>O1,updateRate:()=>R1,update:()=>E1,store:()=>A1,fetchById:()=>F1,fetchAll:()=>Q1,destroy:()=>N1,bulkStore:()=>z1,bulkDestroy:()=>x1});import{db as M1}from"@stacksjs/database";async function N1(G){try{let J=await M1.deleteFrom("tax_rates").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rate: ${J.message}`);throw J}}async function x1(G){if(!G.length)return 0;try{let J=await M1.deleteFrom("tax_rates").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rates: ${J.message}`);throw J}}import{db as H1}from"@stacksjs/database";async function F1(G){return await H1.selectFrom("tax_rates").where("id","=",G).selectAll().executeTakeFirst()}async function Q1(){return await H1.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:V1}=globalThis.Bun;import{db as B1}from"@stacksjs/database";async function A1(G){try{let J={...G,uuid:V1()},X=await B1.insertInto("tax_rates").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rate: ${J.message}`);throw J}}async function z1(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:V1()})),X=await B1.insertInto("tax_rates").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${J.message}`);throw J}}import{db as ZX}from"@stacksjs/database";import{formatDate as MX}from"@stacksjs/orm";async function E1(G,J){try{if(!G)throw Error("Tax rate ID is required for update");let X=J,$=await ZX.updateTable("tax_rates").set({name:J.name,rate:J.rate,type:J.type,country:J.country,region:J.region,status:J.status,is_default:X.is_default,updated_at:MX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update tax rate");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update tax rate: ${X.message}`);throw X}}async function O1(G,J){try{let X=await ZX.updateTable("tax_rates").set({status:J,updated_at:MX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update tax rate status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update tax rate status: ${X.message}`);throw X}}async function R1(G,J){try{let X=await ZX.updateTable("tax_rates").set({rate:J,updated_at:MX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update rate information");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update rate information: ${X.message}`);throw X}}var FX={};Q(FX,{restaurant:()=>KJ,products:()=>NG,default:()=>HK});var NG={};Q(NG,{updateStatus:()=>c1,updatePartySize:()=>u1,update:()=>l1,store:()=>m1,fetchWaiting:()=>f1,fetchPurchasedBetweenDates:()=>_1,fetchNotifiedBetweenDates:()=>C1,fetchCountByStatus:()=>v1,fetchCountBySource:()=>P1,fetchCountByQuantity:()=>k1,fetchCountByDateGrouped:()=>y1,fetchCountByDate:()=>j1,fetchCountByAllQuantities:()=>w1,fetchCountBetweenDates:()=>g1,fetchConversionRates:()=>h1,fetchCancelledBetweenDates:()=>I1,fetchById:()=>S1,fetchAll:()=>q1,destroy:()=>U1,bulkStore:()=>b1,bulkDestroy:()=>T1});import{db as MG}from"@stacksjs/database";async function U1(G){try{let J=await MG.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst();if(!J)return;return await MG.deleteFrom("waitlist_products").where("id","=",G).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist product: ${J.message}`);throw J}}async function T1(G){if(!G.length)return 0;try{return(await MG.deleteFrom("waitlist_products").where("id","in",G).execute()).length||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${J.message}`);throw J}}import{db as T}from"@stacksjs/database";import{formatDate as O}from"@stacksjs/orm";async function S1(G){return await T.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst()}async function q1(){return await T.selectFrom("waitlist_products").selectAll().execute()}async function P1(G,J){let X=T.selectFrom("waitlist_products").select(["source",(K)=>K.fn.count("id").as("count")]).groupBy("source");if(G&&J){let K=O(G),L=O(J);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.execute()).reduce((K,{source:L,count:Y})=>{return K[L]=Y,K},{})}async function j1(G=new Date){let J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=O(J),K=O(X);return(await T.selectFrom("waitlist_products").select((Y)=>Y.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function k1(G){return(await T.selectFrom("waitlist_products").select((X)=>X.fn.count("id").as("count")).where("quantity","=",G).executeTakeFirst())?.count??0}async function w1(G,J){let X=T.selectFrom("waitlist_products").select(["quantity",(K)=>K.fn.count("id").as("count")]).groupBy("quantity");if(G&&J){let K=O(G),L=O(J);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.execute()).reduce((K,{quantity:L,count:Y})=>{return K[L]=Y,K},{})}async function C1(G,J){let X=O(G),$=O(J);return await T.selectFrom("waitlist_products").selectAll().where("notified_at",">=",X).where("notified_at","<=",$).where("notified_at","is not",null).execute()}async function _1(G,J){let X=O(G),$=O(J);return await T.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",X).where("purchased_at","<=",$).where("purchased_at","is not",null).execute()}async function I1(G,J){let X=O(G),$=O(J);return await T.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",X).where("cancelled_at","<=",$).where("cancelled_at","is not",null).execute()}async function f1(){return await T.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function v1(G,J,X){let $=T.selectFrom("waitlist_products").select((L)=>L.fn.count("id").as("count")).where("status","=",G);if(J&&X){let L=O(J),Y=O(X);$=$.where("created_at",">=",L).where("created_at","<=",Y)}return(await $.executeTakeFirst())?.count??0}async function h1(G,J){let X=T.selectFrom("waitlist_products").select(["status",(M)=>M.fn.count("id").as("count")]).groupBy("status");if(G&&J){let M=O(G),Z=O(J);X=X.where("created_at",">=",M).where("created_at","<=",Z)}let $=await X.execute(),K=$.reduce((M,{count:Z})=>M+Z,0),L=$.find((M)=>M.status==="purchased")?.count??0,Y=K>0?L/K*100:0,W=$.reduce((M,{status:Z,count:N})=>{return M[Z]={count:N,percentage:K>0?N/K*100:0},M},{});return{totalConversionRate:Y,statusBreakdown:W}}async function g1(G,J){let X=O(G),$=O(J);return(await T.selectFrom("waitlist_products").select((L)=>L.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",$).executeTakeFirst())?.count??0}async function y1(G,J){let X=T.selectFrom("waitlist_products").select(["created_at"]);if(G&&J){let L=O(G),Y=O(J);X=X.where("created_at",">=",L).where("created_at","<=",Y)}let K=(await X.execute()).reduce((L,{created_at:Y})=>{let W=(Y||"").split("T")[0]||"unknown";return L[W]=(L[W]||0)+1,L},{});return Object.entries(K).map(([L,Y])=>({date:L,count:Y})).sort((L,Y)=>L.date.localeCompare(Y.date))}var{randomUUIDv7:D1}=globalThis.Bun;import{db as p1}from"@stacksjs/database";import{formatDate as $J}from"@stacksjs/orm";async function m1(G){try{let J=G,X={name:G.name,email:G.email,phone:G.phone,quantity:G.quantity??J.party_size,notification_preference:J.notification_preference,source:G.source,notes:G.notes,product_id:G.product_id,customer_id:G.customer_id,uuid:D1(),status:G.status||"waiting"};if(G.notified_at!==void 0)X.notified_at=typeof G.notified_at==="number"?$J(G.notified_at):G.notified_at;if(G.purchased_at!==void 0)X.purchased_at=typeof G.purchased_at==="number"?$J(G.purchased_at):G.purchased_at;if(G.cancelled_at!==void 0)X.cancelled_at=typeof G.cancelled_at==="number"?$J(G.cancelled_at):G.cancelled_at;let $=await p1.insertInto("waitlist_products").values(X).returningAll().executeTakeFirst();if(!$)throw Error("Failed to create waitlist product");return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist product: ${J.message}`);throw J}}async function b1(G){if(!G.length)return 0;try{let J=G.map(($)=>{let K=$,L={name:$.name,email:$.email,phone:$.phone,quantity:$.quantity??K.party_size,notification_preference:K.notification_preference,source:$.source,notes:$.notes,product_id:$.product_id,customer_id:$.customer_id,uuid:D1(),status:$.status||"waiting"};if($.notified_at!==void 0)L.notified_at=typeof $.notified_at==="number"?$J($.notified_at):$.notified_at;if($.purchased_at!==void 0)L.purchased_at=typeof $.purchased_at==="number"?$J($.purchased_at):$.purchased_at;if($.cancelled_at!==void 0)L.cancelled_at=typeof $.cancelled_at==="number"?$J($.cancelled_at):$.cancelled_at;return L}),X=await p1.insertInto("waitlist_products").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${J.message}`);throw J}}import{db as xX}from"@stacksjs/database";import{formatDate as HX}from"@stacksjs/orm";async function l1(G,J){try{if(!G)throw Error("Waitlist product ID is required for update");let X=J,$=await xX.updateTable("waitlist_products").set({name:J.name,email:J.email,phone:J.phone,quantity:J.quantity??X.party_size,notification_preference:X.notification_preference,source:J.source,notes:J.notes,status:J.status,product_id:J.product_id,customer_id:J.customer_id,notified_at:X.notified_at,purchased_at:X.purchased_at,cancelled_at:X.cancelled_at,updated_at:HX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update waitlist product");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update waitlist product: ${X.message}`);throw X}}async function c1(G,J){try{let X=await xX.updateTable("waitlist_products").set({status:J,updated_at:HX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update waitlist product status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update waitlist product status: ${X.message}`);throw X}}async function u1(G,J){try{let X=await xX.updateTable("waitlist_products").set({quantity:J,updated_at:HX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update party size");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update party size: ${X.message}`);throw X}}var KJ={};Q(KJ,{updateWaitTimes:()=>O9,updateStatus:()=>z9,updateQueuePosition:()=>R9,updatePartySize:()=>E9,update:()=>A9,store:()=>V9,fetchWaitingWithQuotedTimes:()=>K9,fetchWaitingWithPartySizes:()=>L9,fetchWaiting:()=>G9,fetchTimeSeriesStats:()=>x9,fetchTablesTurnedToday:()=>Y9,fetchSeatingRate:()=>W9,fetchSeatedStats:()=>N9,fetchSeatedBetweenDates:()=>J9,fetchNoShowStats:()=>Z9,fetchCurrentWaitTimes:()=>M9,fetchCountByTablePreference:()=>d1,fetchCountByPartySize:()=>t1,fetchCountByDate:()=>a1,fetchCountByAllPartySizes:()=>r1,fetchConversionRates:()=>X9,fetchById:()=>i1,fetchBetweenDates:()=>e1,fetchAverageWaitTimes:()=>$9,fetchAll:()=>s1,destroy:()=>n1,bulkStore:()=>B9,bulkDestroy:()=>o1});import{db as xG}from"@stacksjs/database";async function n1(G){try{let J=await xG.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst();if(!J)return;return await xG.deleteFrom("waitlist_restaurants").where("id","=",G).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${J.message}`);throw J}}async function o1(G){if(!G.length)return 0;try{return(await xG.deleteFrom("waitlist_restaurants").where("id","in",G).execute()).length||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as z}from"@stacksjs/database";import{formatDate as k}from"@stacksjs/orm";async function i1(G){return await z.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst()}async function s1(){return await z.selectFrom("waitlist_restaurants").selectAll().execute()}async function d1(){return(await z.selectFrom("waitlist_restaurants").select(["table_preference",(J)=>J.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((J,{table_preference:X,count:$})=>{return J[X]=$,J},{})}async function a1(G=new Date){let J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=k(J),K=k(X);return(await z.selectFrom("waitlist_restaurants").select((Y)=>Y.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function t1(G){return(await z.selectFrom("waitlist_restaurants").select((X)=>X.fn.count("id").as("count")).where("party_size","=",G).executeTakeFirst())?.count??0}async function r1(){return(await z.selectFrom("waitlist_restaurants").select(["party_size",(J)=>J.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((J,{party_size:X,count:$})=>{return J[X]=$,J},{})}async function e1(G,J){let X=k(G),$=k(J);return await z.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",X).where("created_at","<=",$).execute()}async function J9(G,J){let X=k(G),$=k(J);return await z.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",X).where("check_in_time","<=",$).where("status","=","seated").execute()}async function G9(){return await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function X9(){let G=await z.selectFrom("waitlist_restaurants").select(["status",(L)=>L.fn.count("id").as("count")]).groupBy("status").execute(),J=G.reduce((L,{count:Y})=>L+Y,0),X=G.find((L)=>L.status==="seated")?.count??0,$=J>0?Number(X)/J*100:0,K=G.reduce((L,{status:Y,count:W})=>{return L[Y]={count:W,percentage:J>0?W/J*100:0},L},{});return{totalConversionRate:$,statusBreakdown:K}}async function $9(){let G=await z.selectFrom("waitlist_restaurants").select([(J)=>J.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),(J)=>J.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:G?.avg_quoted_wait_time??0,averageActualWaitTime:G?.avg_actual_wait_time??0}}async function K9(){let G=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=G.reduce(($,K)=>$+(K.quoted_wait_time??0),0),X=G.length>0?J/G.length:0;return{entries:G,totalQuotedWaitTime:J,averageQuotedWaitTime:X}}async function L9(){let G=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=G.reduce((K,L)=>K+L.party_size,0),X=G.length>0?J/G.length:0,$=G.reduce((K,L)=>{return K[L.party_size]=(K[L.party_size]||0)+1,K},{});return{entries:G,totalPartySize:J,averagePartySize:X,partySizeBreakdown:$}}async function Y9(){let G=new Date,J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=k(J),K=k(X),L=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",$).where("check_in_time","<=",K).execute(),Y=L.length,W=L.reduce((x,H)=>x+H.party_size,0),M=Y>0?W/Y:0,Z=L.reduce((x,H)=>{return x[H.table_preference]=(x[H.table_preference]||0)+1,x},{}),N=L.reduce((x,H)=>{return x[H.party_size]=(x[H.party_size]||0)+1,x},{});return{totalTablesTurned:Y,averagePartySize:M,totalCustomersSeated:W,breakdownByTablePreference:Z,breakdownByPartySize:N}}async function W9(G,J){let X=k(G),$=k(J),K=await z.selectFrom("waitlist_restaurants").select(["status",(Z)=>Z.fn.count("id").as("count")]).where("check_in_time",">=",X).where("check_in_time","<=",$).groupBy("status").execute(),L=K.reduce((Z,{count:N})=>Z+N,0),Y=K.find((Z)=>Z.status==="seated")?.count??0,W=L>0?Number(Y)/L*100:0,M=K.reduce((Z,{status:N,count:x})=>{return Z[N]={count:x,percentage:L>0?x/L*100:0},Z},{});return{totalEntries:L,seatedEntries:Y,seatingRate:W,statusBreakdown:M}}async function Z9(G,J){let X=k(G),$=k(J),K=z.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",X).where("check_in_time","<=",$),L=await z.selectFrom("waitlist_restaurants").select((F)=>F.fn.count("id").as("count")).where("check_in_time",">=",X).where("check_in_time","<=",$).executeTakeFirst(),Y=await K.execute(),W=Y.length,M=L?.count&&L.count>0?W/L.count*100:0,Z=Y.reduce((F,A)=>F+(A.quoted_wait_time??0),0),N=W>0?Z/W:0,x=Y.reduce((F,A)=>F+A.party_size,0),H=W>0?x/W:0,E=Y.reduce((F,A)=>{return F[A.table_preference]=(F[A.table_preference]||0)+1,F},{}),B=Y.reduce((F,A)=>{return F[A.party_size]=(F[A.party_size]||0)+1,F},{});return{totalNoShows:W,noShowRate:M,averageQuotedWaitTime:N,averagePartySize:H,breakdownByTablePreference:E,breakdownByPartySize:B}}async function M9(){let G=await z.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),J=G.reduce((K,L)=>K+(L.quoted_wait_time||0),0),X=G.reduce((K,L)=>K+(L.actual_wait_time||0),0),$=G.length;return{averageQuoted:$>0?J/$:0,averageActual:$>0?X/$:0}}async function N9(){let G=Date.now()-86400000,J=await z.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",G).execute(),X=Array.from({length:24},($,K)=>({hour:K,count:J.filter((L)=>{return L.seated_at===K}).length}));return{total:J.length,byHour:X}}async function x9(){return(await z.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((J,X)=>{let $=X.created_at;if(!J[$])J[$]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return J[$].total++,J[$][X.status]++,J},{})}var{randomUUIDv7:H9}=globalThis.Bun;import{db as F9}from"@stacksjs/database";import{formatDate as Q9}from"@stacksjs/orm";async function V9(G){try{let J=G,X={name:G.name,email:G.email,phone:G.phone,party_size:J.party_size,check_in_time:typeof J.check_in_time==="number"?Q9(J.check_in_time):J.check_in_time,table_preference:J.table_preference,status:G.status||"waiting",quoted_wait_time:G.quoted_wait_time,actual_wait_time:G.actual_wait_time,queue_position:G.queue_position,customer_id:G.customer_id,uuid:H9()},$={};for(let[Y,W]of Object.entries(X))if(W!==void 0)$[Y]=W;let K=await F9.insertInto("waitlist_restaurants").values($).returningAll().executeTakeFirst();if(!K)throw Error("Failed to create restaurant waitlist entry");let L={...K};for(let Y of Object.keys(L))if(L[Y]===null)L[Y]=void 0;return L}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${J.message}`);throw J}}async function B9(G){if(!G.length)return 0;try{let J=G.map(($)=>{let K=$;return{name:$.name,email:$.email,phone:$.phone,party_size:K.party_size,check_in_time:typeof K.check_in_time==="number"?Q9(K.check_in_time):K.check_in_time,table_preference:K.table_preference,status:$.status||"waiting",quoted_wait_time:$.quoted_wait_time,actual_wait_time:$.actual_wait_time,queue_position:$.queue_position,customer_id:$.customer_id,uuid:H9()}}),X=await F9.insertInto("waitlist_restaurants").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as BJ}from"@stacksjs/database";import{formatDate as AJ}from"@stacksjs/orm";async function A9(G,J){try{if(!G)throw Error("Restaurant waitlist entry ID is required for update");let X=J,$=await BJ.updateTable("waitlist_restaurants").set({name:J.name,email:J.email,phone:J.phone,party_size:X.party_size,check_in_time:X.check_in_time?Math.floor(new Date(X.check_in_time).getTime()/1000):void 0,table_preference:X.table_preference,status:J.status,quoted_wait_time:J.quoted_wait_time,actual_wait_time:J.actual_wait_time,queue_position:J.queue_position,customer_id:J.customer_id,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update restaurant waitlist entry");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${X.message}`);throw X}}async function z9(G,J){try{let X=await BJ.updateTable("waitlist_restaurants").set({status:J,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update restaurant waitlist entry status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry status: ${X.message}`);throw X}}async function E9(G,J){try{let X=await BJ.updateTable("waitlist_restaurants").set({party_size:J,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update party size");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update party size: ${X.message}`);throw X}}async function O9(G,J,X){try{let $=await BJ.updateTable("waitlist_restaurants").set({quoted_wait_time:J,actual_wait_time:X,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update wait times");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update wait times: ${$.message}`);throw $}}async function R9(G,J){try{let X=await BJ.updateTable("waitlist_restaurants").set({queue_position:J,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update queue position");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update queue position: ${X.message}`);throw X}}var xK={products:NG,restaurant:KJ},HK=xK;var FK={coupons:FG,customers:VG,devices:EG,errors:UG,giftCards:PG,orders:yG,payments:DG,products:oG,receipts:dG,restaurant:KJ,shippings:WX,tax:NX,waitlists:FX},rZ=FK;export{FX as waitlists,NX as tax,WX as shippings,KJ as restaurant,dG as receipts,oG as products,DG as payments,yG as orders,PG as giftCards,UG as errors,EG as devices,rZ as default,VG as customers,FG as coupons,FK as commerce};
|