@stacksjs/commerce 0.70.112 → 0.70.114
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 +15 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,2 +1,16 @@
|
|
|
1
1
|
// @bun
|
|
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:()=>b,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 b(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 b(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 b(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 b(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 b(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 y,toTimestamp as r}from"@stacksjs/orm";import{db as h9}from"@stacksjs/database";async function l(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 l("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 l("gift_cards",{count:{kind:"count"}},(N)=>N.where((x)=>TG`${x.ref("current_balance")} / ${x.ref("initial_balance")} < 0.25`)),{count:L}=await l("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 l("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",">=",y(X)).where("created_at","<=",y(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",">=",y(K)).where("created_at","<=",y($)).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",">=",y(X)).where("created_at","<=",y(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",">=",y(K)).where("created_at","<=",y($)).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,p=M-x,m=Z-H,a=N!==0?_/N*100:W>0?100:0,R=x!==0?p/x*100:M>0?100:0,I=H!==0?m/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:p,percentage:Math.abs(R),is_increase:p>=0},card_count:{difference:m,percentage:Math.abs(I),is_increase:m>=0}},days_range:G}}async function T6(){let{total_value:G}=await l("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:G}}async function S6(){let{total_balance:G}=await l("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,p=H!==0?F/H*100:Z>0?100:0,m=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(p),is_increase:F>=0},revenue:{difference:A,percentage:Math.abs(m),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 D}from"@stacksjs/database";import{formatDate as w}from"@stacksjs/orm";async function H$(){return await D.selectFrom("payments").selectAll().execute()}async function xJ(G){return await D.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 D.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 D.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 D.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,p=H>0?F/H*100:Z>0?100:0,m=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(p),is_increase:F>=0},average:{difference:A,percentage:Math.abs(m),is_increase:A>=0}}}}async function Q$(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await D.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 D.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 D.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},tZ=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,tZ as default,VG as customers,FG as coupons,FK as commerce};
|
|
2
|
+
var R9=Object.defineProperty;var U9=(G)=>G;function T9(G,J){this[G]=U9.bind(null,J)}var B=(G,J)=>{for(var X in J)R9(G,X,{get:J[X],enumerable:!0,configurable:!0,set:T9.bind(J,X)})};var NX=import.meta.require;var NG={};B(NG,{update:()=>fX,store:()=>wX,redeem:()=>vX,getActiveCouponsMoMChange:()=>qX,fetchTopRedeemedCoupons:()=>TX,fetchStats:()=>EX,fetchRedemptionTrend:()=>SX,fetchRedemptionStats:()=>UX,fetchCouponCountsByType:()=>RX,fetchCouponCounts:()=>OX,fetchConversionRate:()=>PX,fetchById:()=>l,fetchByCode:()=>AX,fetchAll:()=>BX,fetchActive:()=>zX,deleteExpiredCoupons:()=>FX,deleteCoupons:()=>HX,deleteCoupon:()=>xX});import{db as KJ}from"@stacksjs/database";import{formatDate as S9}from"@stacksjs/orm";async function xX(G){return!!await KJ.deleteFrom("coupons").where("id","=",G).executeTakeFirst()}async function HX(G){if(!G.length)return 0;return(await KJ.deleteFrom("coupons").where("id","in",G).execute()).length||0}async function FX(){let G=S9(new Date),J=await KJ.deleteFrom("coupons").where("end_date","<",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}import{db as H}from"@stacksjs/database";import{extractDate as QX,formatDate as VX}from"@stacksjs/orm";import{camelCase as P9}from"@stacksjs/strings";function zJ(G){let J=Object.fromEntries(Object.entries(G).map(([X,$])=>[P9(X),$]));if(J.endDate)J.endDate=QX(new Date(J.endDate));if(J.startDate)J.startDate=QX(new Date(J.startDate));if(J.isActive!==void 0)J.isActive=Boolean(J.isActive);return J}async function BX(){return(await H.selectFrom("coupons").selectAll().execute()).map(zJ)}async function l(G){let J=await H.selectFrom("coupons").where("id","=",G).selectAll().executeTakeFirst();if(J)return zJ(J);return}async function AX(G){let J=await H.selectFrom("coupons").where("code","=",G).selectAll().executeTakeFirst();if(J)return zJ(J);return}async function zX(){let G=VX(new Date);return(await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).selectAll().execute()).map(zJ)}async function EX(){let G=await H.selectFrom("coupons").select(H.fn.count("id").as("count")).executeTakeFirst(),J=VX(new Date),X=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(H.fn.count("id").as("count")).executeTakeFirst(),$=await H.selectFrom("coupons").select(["discount_type",H.fn.count("id").as("count")]).groupBy("discount_type").execute(),K=await H.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),L=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",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 OX(){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 AJ(null,null,G),L=await AJ(J,null,G),Y=await AJ(X,null,G),W=await AJ($,null,G);return{week:L,month:Y,year:W,all_time:K}}async function AJ(G,J,X){let $=H.selectFrom("coupons");if(G)$=$.where("created_at",">=",G.toISOString());if(J)$=$.where("created_at","<=",J.toISOString());let K=await $.select(H.fn.count("id").as("count")).executeTakeFirst(),L=H.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(H.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 RX(){let G=new Date,J=await H.selectFrom("coupons").select("discount_type").distinct().execute(),X={};for(let{discount_type:$}of J){let K=await H.selectFrom("coupons").where("discount_type","=",$).select(H.fn.count("id").as("count")).executeTakeFirst(),L=await H.selectFrom("coupons").where("discount_type","=",$).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select(H.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 UX(){let G=await H.selectFrom("coupons").select(H.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 H.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await H.selectFrom("coupons").where("updated_at",">=",$.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await H.selectFrom("coupons").where("updated_at",">=",K.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),M=await H.selectFrom("coupons").select(["discount_type",H.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 TX(G=5){return await H.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(G).execute()}async function SX(G=30){let J=new Date().toISOString(),X=new Date;X.setDate(X.getDate()-G);let $=await H.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 PX(){let G=new Date,J=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select(H.fn.count("id").as("count")).executeTakeFirst(),X=await H.selectFrom("coupons").where("usage_count",">",0).select(H.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 qX(){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 H.selectFrom("coupons").select(H.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",J).executeTakeFirst(),L=await H.selectFrom("coupons").select(H.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 jX}from"@stacksjs/database";import{HttpError as kX}from"@stacksjs/error-handling";import{isUniqueViolation as q9}from"@stacksjs/orm";async function wX(G){try{let J=await jX.insertInto("coupons").values(G).executeTakeFirst(),X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows);if(X)return await jX.selectFrom("coupons").where("id","=",X).selectAll().executeTakeFirst();return}catch(J){if(J instanceof kX)throw J;if(q9(J))throw new kX(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 _X}from"@stacksjs/database";import{HttpError as CX}from"@stacksjs/error-handling";import{formatDate as IX,isUniqueViolation as j9}from"@stacksjs/orm";async function fX(G,J){if(!await l(G))throw Error(`Coupon with ID ${G} not found`);try{return await _X.updateTable("coupons").set({...J,updated_at:IX(new Date)}).where("id","=",G).execute(),await l(G)}catch($){if($ instanceof CX)throw $;if(j9($))throw new CX(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to update coupon: ${$.message}`);throw $}}async function vX(G){let J=IX(new Date),X=await _X.unsafe(`UPDATE coupons
|
|
3
|
+
SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ?
|
|
4
|
+
WHERE id = ?
|
|
5
|
+
AND (max_uses IS NULL OR usage_count < max_uses)
|
|
6
|
+
AND is_active = 1
|
|
7
|
+
AND (start_date IS NULL OR start_date <= ?)
|
|
8
|
+
AND (end_date IS NULL OR end_date >= ?)`,[J,G,J,J]),$=typeof X?.execute==="function"?await X.execute():X;if(Number($?.changes??$?.numUpdatedRows??$?.affectedRows??0)>0){let M=await l(G);if(M)return{ok:!0,coupon:M};return{ok:!1,reason:"not-found"}}let L=await l(G);if(!L)return{ok:!1,reason:"not-found"};if(!L.isActive)return{ok:!1,reason:"inactive"};let Y=!L.startDate||L.startDate<=J,W=!L.endDate||L.endDate>=J;if(!Y||!W)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var HG={};B(HG,{update:()=>lX,store:()=>bX,fetchById:()=>a,fetchAll:()=>gX,destroy:()=>yX,bulkDestroy:()=>DX});import{db as xG}from"@stacksjs/database";import{db as hX}from"@stacksjs/database";async function a(G){return await hX.selectFrom("customers").where("id","=",G).selectAll().executeTakeFirst()}async function gX(){return await hX.selectFrom("customers").selectAll().execute()}async function yX(G){try{if(!await a(G))throw Error(`Customer with ID ${G} not found`);return(await xG.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 DX(G){if(!G.length)return 0;try{let J=await xG.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 pX}from"@stacksjs/error-handling";import{isUniqueViolation as w9}from"@stacksjs/orm";async function bX(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 a(Number($))}catch(J){if(J instanceof pX)throw J;if(w9(J))throw new pX(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 mX}from"@stacksjs/error-handling";import{formatDate as _9,isUniqueViolation as I9}from"@stacksjs/orm";async function lX(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 mX)throw X;if(I9(X))throw new mX(409,"A customer with this email already exists");if(X instanceof Error)throw Error(`Failed to update customer: ${X.message}`);throw X}}var BG={};B(BG,{updateStatus:()=>eX,updatePrintCount:()=>J6,update:()=>rX,storePrintDevicesExport:()=>sX,store:()=>aX,fetchById:()=>f,fetchAll:()=>EJ,exportPrintDevices:()=>OJ,downloadPrintDevices:()=>iX,destroy:()=>uX,bulkStore:()=>tX,bulkDestroy:()=>nX});import{db as cX}from"@stacksjs/database";async function uX(G){try{let J=await cX.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 nX(G){if(!G.length)return 0;try{let J=await cX.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 oX}from"@stacksjs/database";async function f(G){return await oX.selectFrom("print_devices").where("id","=",G).selectAll().executeTakeFirst()}async function EJ(){return await oX.selectFrom("print_devices").selectAll().execute()}async function OJ(G="csv"){let J=await EJ(),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 iX(G="csv",J){let X=await OJ(G),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;return X.download(J||$)}async function sX(G="csv",J){let X=await OJ(G),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;X.store(J||$)}var{randomUUIDv7:dX}=globalThis.Bun;import{db as FG}from"@stacksjs/database";async function aX(G){try{let J={...G,uuid:dX()},X=await FG.insertInto("print_devices").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await FG.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 tX(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:dX()};await FG.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 QG}from"@stacksjs/database";import{formatDate as VG}from"@stacksjs/orm";async function rX(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await QG.updateTable("print_devices").set({...J,updated_at:VG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device: ${$.message}`);throw $}}async function eX(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await QG.updateTable("print_devices").set({status:J,updated_at:VG(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 J6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await QG.updateTable("print_devices").set({print_count:J,updated_at:VG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print count: ${$.message}`);throw $}}var EG={};B(EG,{update:()=>M6,unresolveGroup:()=>F6,resolveGroup:()=>x6,ignoreGroup:()=>H6,fetchTimeline:()=>Z6,fetchStats:()=>W6,fetchGrouped:()=>L6,fetchById:()=>K6,fetchByGroup:()=>Y6,fetchAll:()=>UJ,destroyGroup:()=>$6,destroy:()=>G6,bulkUpdateStatus:()=>N6,bulkDestroy:()=>X6});import{db as AG}from"@stacksjs/database";import{log as zG}from"@stacksjs/logging";async function G6(G){try{return await AG.deleteFrom("errors").where("id","=",G).execute(),!0}catch(J){return zG.error("[commerce/errors] destroy failed",{id:G,error:J}),!1}}async function X6(G){try{return await AG.deleteFrom("errors").where("id","in",G).execute(),!0}catch(J){return zG.error("[commerce/errors] bulkDestroy failed",{count:G.length,error:J}),!1}}async function $6(G,J){try{return await AG.deleteFrom("errors").where("type","=",G).where("message","=",J).execute(),!0}catch(X){return zG.error("[commerce/errors] destroyGroup failed",{type:G,message:J,error:X}),!1}}import{db as RJ}from"@stacksjs/database";async function K6(G){return await RJ.selectFrom("errors").where("id","=",G).selectAll().executeTakeFirst()}async function UJ(){return await RJ.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function L6(){let G=await RJ.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 Y6(G,J){return await RJ.selectFrom("errors").where("type","=",G).where("message","=",J).selectAll().orderBy("created_at","desc").execute()}async function W6(){let G=await UJ(),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 Z6(){let G=await UJ(),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 LJ}from"@stacksjs/database";import{sql as YJ}from"@stacksjs/database";import{log as WJ}from"@stacksjs/logging";async function M6(G,J){try{return await LJ.updateTable("errors").set({...J,updated_at:YJ.raw("CURRENT_TIMESTAMP")}).where("id","=",G).execute(),!0}catch(X){return WJ.error("[commerce/errors] update failed",{id:G,error:X}),!1}}async function N6(G,J){try{return await LJ.updateTable("errors").set({status:J,updated_at:YJ.raw("CURRENT_TIMESTAMP")}).where("id","in",G).execute(),!0}catch(X){return WJ.error("[commerce/errors] bulkUpdateStatus failed",{count:G.length,status:J,error:X}),!1}}async function x6(G,J){try{return await LJ.updateTable("errors").set({status:1,updated_at:YJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return WJ.error("[commerce/errors] resolveGroup failed",{type:G,message:J,error:X}),!1}}async function H6(G,J){try{return await LJ.updateTable("errors").set({status:2,updated_at:YJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return WJ.error("[commerce/errors] ignoreGroup failed",{type:G,message:J,error:X}),!1}}async function F6(G,J){try{return await LJ.updateTable("errors").set({status:0,updated_at:YJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return WJ.error("[commerce/errors] unresolveGroup failed",{type:G,message:J,error:X}),!1}}var UG={};B(UG,{updateBalance:()=>_6,update:()=>C6,store:()=>q6,fetchTotalValue:()=>O6,fetchTotalCurrentBalance:()=>R6,fetchStats:()=>B6,fetchById:()=>v,fetchByCode:()=>OG,fetchAll:()=>Q6,fetchActive:()=>V6,destroy:()=>U6,compareActiveGiftCards:()=>z6,checkBalance:()=>A6,calculateGiftCardValues:()=>E6,bulkDestroy:()=>T6});import{db as RG}from"@stacksjs/database";import{formatDate as bL}from"@stacksjs/orm";import{db as R,sql as j}from"@stacksjs/database";import{formatDate as D,toTimestamp as t}from"@stacksjs/orm";import{aggregateFunctions as h9,db as g9}from"@stacksjs/database";async function c(G,J,X){let $=g9.selectFrom(G);if(X)$=X($);$=$.select(Object.entries(J).map(([Y,W])=>{let M=W.column??"id",Z=h9[W.kind](M);if(W.filter)Z=Z.filterWhere(W.filter.column,W.filter.op,W.filter.value);return Z.as(Y)}));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 Q6(){return await R.selectFrom("gift_cards").selectAll().execute()}async function v(G){return await R.selectFrom("gift_cards").where("id","=",G).selectAll().executeTakeFirst()}async function OG(G){return await R.selectFrom("gift_cards").where("code","=",G).selectAll().executeTakeFirst()}async function V6(){return await R.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function B6(){let{count:G}=await c("gift_cards",{count:{kind:"count"}}),J=t(new Date),X=await R.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(J)} OR expiry_date IS NULL)`).select(R.fn.count("id").as("count")).executeTakeFirst(),$=await R.selectFrom("gift_cards").select(["status",R.fn.count("id").as("count")]).groupBy("status").execute(),{count:K}=await c("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(j`current_balance / initial_balance < 0.25`)),{count:L}=await c("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(j`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:Y}=await c("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(j`current_balance / initial_balance > 0.75`)),W=new Date;W.setDate(W.getDate()+30);let M=await R.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",t(W)).where("expiry_date",">=",J).selectAll().limit(5).execute(),Z=await R.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 A6(G){let J=await OG(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 z6(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 R.selectFrom("gift_cards").select(R.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(t(J))} OR expiry_date IS NULL)`).where("created_at",">=",D(X)).where("created_at","<=",D(J)).executeTakeFirst(),Y=await R.selectFrom("gift_cards").select(R.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(t(K))} OR 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 E6(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 R.selectFrom("gift_cards").select([R.fn.sum("initial_balance").as("total_initial"),R.fn.sum("current_balance").as("total_balance"),R.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(t(J))} OR expiry_date IS NULL)`).where("created_at",">=",D(X)).where("created_at","<=",D(J)).executeTakeFirst(),Y=await R.selectFrom("gift_cards").select([R.fn.sum("initial_balance").as("total_initial"),R.fn.sum("current_balance").as("total_balance"),R.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(t(K))} OR 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),F=Number(Y?.card_count||0),T=W>0?(W-M)/W*100:0,E=N>0?(N-x)/N*100:0,z=Z>0?W/Z:0,O=Z>0?M/Z:0,_=W-N,b=M-x,m=Z-F,d=N!==0?_/N*100:W>0?100:0,I=x!==0?b/x*100:M>0?100:0,O9=F!==0?m/F*100:Z>0?100:0;return{current_period:{total_initial_value:W,total_remaining_balance:M,utilization_rate:T,card_count:Z,average_initial_value:z,average_remaining_balance:O},previous_period:{total_initial_value:N,total_remaining_balance:x,utilization_rate:E,card_count:F},comparison:{initial_value:{difference:_,percentage:Math.abs(d),is_increase:_>=0},balance:{difference:b,percentage:Math.abs(I),is_increase:b>=0},card_count:{difference:m,percentage:Math.abs(O9),is_increase:m>=0}},days_range:G}}async function O6(){let{total_value:G}=await c("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:G}}async function R6(){let{total_balance:G}=await c("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:G}}async function U6(G){if(!await v(G))throw Error(`Gift card with ID ${G} not found`);return!!await RG.deleteFrom("gift_cards").where("id","=",G).executeTakeFirst()}async function T6(G){if(!G.length)return 0;let J=await RG.deleteFrom("gift_cards").where("id","in",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}var{randomUUIDv7:y9}=globalThis.Bun;import{db as S6}from"@stacksjs/database";import{HttpError as P6}from"@stacksjs/error-handling";import{isUniqueViolation as D9}from"@stacksjs/orm";async function q6(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:y9()};try{let $=await S6.insertInto("gift_cards").values(X).executeTakeFirst(),K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);if(K)return await S6.selectFrom("gift_cards").where("id","=",K).selectAll().executeTakeFirst();return}catch($){if($ instanceof P6)throw $;if(D9($))throw new P6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to create gift card: ${$.message}`);throw $}}import{db as k6}from"@stacksjs/database";import{HttpError as j6}from"@stacksjs/error-handling";import{formatDate as w6,isUniqueViolation as p9}from"@stacksjs/orm";async function C6(G,J){if(!await v(G))throw Error(`Gift card with ID ${G} not found`);try{return await k6.updateTable("gift_cards").set({...J,updated_at:w6(new Date)}).where("id","=",G).execute(),await v(G)}catch($){if($ instanceof j6)throw $;if(p9($))throw new j6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to update gift card: ${$.message}`);throw $}}async function _6(G,J){if(!Number.isFinite(J))throw Error(`Gift card balance adjustment must be a finite number, got ${J}`);let X=w6(new Date),$=await k6.unsafe(`UPDATE gift_cards
|
|
9
|
+
SET current_balance = current_balance + ?,
|
|
10
|
+
last_used_date = ?,
|
|
11
|
+
status = CASE WHEN current_balance + ? = 0 THEN 'USED' ELSE 'ACTIVE' END,
|
|
12
|
+
updated_at = ?
|
|
13
|
+
WHERE id = ?
|
|
14
|
+
AND is_active = 1
|
|
15
|
+
AND status = 'ACTIVE'
|
|
16
|
+
AND current_balance + ? >= 0`,[J,X,J,X,G,J]),K=typeof $?.execute==="function"?await $.execute():$;if(Number(K?.changes??K?.numUpdatedRows??K?.affectedRows??0)>0)return await v(G);let Y=await v(G);if(!Y)throw Error(`Gift card with ID ${G} not found`);if(!Y.is_active||Y.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var fG={};B(fG,{validateQuantityBounds:()=>IG,validateCouponStacking:()=>K$,validateCartQuantities:()=>L$,updateStatus:()=>r6,updateDeliveryInfo:()=>e6,update:()=>t6,storeOrdersExport:()=>D6,store:()=>o6,softDelete:()=>f6,registerCommerceWebhookHandlers:()=>G$,recomputeOrderTotals:()=>$$,placeOrder:()=>a6,handlePaymentIntentSucceeded:()=>wG,handlePaymentIntentFailed:()=>CG,handleChargeRefunded:()=>_G,fetchStats:()=>b6,fetchDailyOrderTrends:()=>c6,fetchById:()=>h,fetchAll:()=>p6,exportOrders:()=>SJ,emitOrderShipped:()=>TG,emitOrderRefunded:()=>MJ,emitOrderPaid:()=>u,emitOrderDelivered:()=>SG,emitOrderCreated:()=>qJ,emitOrderCancelled:()=>ZJ,emitForStatus:()=>jJ,downloadOrders:()=>y6,destroy:()=>I6,compareOrdersByPeriod:()=>m6,cleanupAbandonedCarts:()=>Y$,canTransition:()=>PJ,calculateOrderMetrics:()=>l6,bulkSoftDelete:()=>h6,bulkDestroy:()=>v6});import{db as TJ}from"@stacksjs/database";async function I6(G){try{let J=await TJ.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 f6(G){try{let J=await TJ.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 v6(G){if(!G.length)return 0;try{let J=await TJ.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 h6(G){if(!G.length)return 0;try{let J=await TJ.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 g6}from"@stacksjs/database";import{createSpreadsheet as b9}from"ts-spreadsheets";async function SJ(G="csv"){let J=await m9(),X=l9(J);return b9(X,{type:G})}async function m9(){let G=await g6.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 g6.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 l9(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 y6(G="csv",J){let X=await SJ(G),$=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;return X.download(J||$)}async function D6(G="csv",J){let X=await SJ(G),$=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;X.store(J||$)}import{db as V}from"@stacksjs/database";async function p6(G){let J=V.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 V.selectFrom("order_items").where("order_id","=",$.id).selectAll().execute();return{...$,items:K}}))}async function h(G){return await V.selectFrom("orders").where("id","=",G).selectAll().executeTakeFirst()}async function b6(){let G=await V.selectFrom("orders").select(V.fn.count("id").as("count")).executeTakeFirst(),J=await V.selectFrom("orders").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),X=await V.selectFrom("orders").select(["order_type",V.fn.count("id").as("count")]).groupBy("order_type").execute(),$=await V.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),K=await Promise.all($.map(async(Y)=>{let W=await V.selectFrom("order_items").where("order_id","=",Y.id).selectAll().execute();return{...Y,items:W}})),L=await V.selectFrom("orders").select(V.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 m6(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 V.selectFrom("orders").select(V.fn.count("id").as("count")).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),Y=await V.selectFrom("orders").select(V.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 l6(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 V.selectFrom("orders").select([V.fn.count("id").as("total_orders"),V.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),Y=await V.selectFrom("orders").select([V.fn.count("id").as("total_orders"),V.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=await V.selectFrom("orders").select(["status",V.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).groupBy("status").execute(),M=await V.selectFrom("orders").select(["order_type",V.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,F=Number(Y?.total_orders||0),T=Number(Y?.total_revenue||0),E=F>0?T/F:0,z=Z-F,O=N-T,_=x-E,b=F!==0?z/F*100:Z>0?100:0,m=T!==0?O/T*100:N>0?100:0,d=E!==0?_/E*100:x>0?100:0;return{current_period:{total_orders:Z,total_revenue:N,average_order_value:x,orders_by_status:W.map((I)=>({status:I.status,count:Number(I.count)})),orders_by_type:M.map((I)=>({order_type:I.order_type,count:Number(I.count)}))},previous_period:{total_orders:F,total_revenue:T,average_order_value:E},comparison:{orders:{difference:z,percentage:Math.abs(b),is_increase:z>=0},revenue:{difference:O,percentage:Math.abs(m),is_increase:O>=0},average_order_value:{difference:_,percentage:Math.abs(d),is_increase:_>=0}},days_range:G}}async function c6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await V.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:c9}=globalThis.Bun;import{db as u6}from"@stacksjs/database";import{formatDate as n6}from"@stacksjs/orm";async function o6(G){let J={...G,status:G.status||"PENDING",uuid:c9(),created_at:n6(new Date),updated_at:n6(new Date)};try{let X=await u6.insertInto("orders").values(J).executeTakeFirst(),$=Number(X?.insertId)||Number(X?.numInsertedOrUpdatedRows);if($)return await u6.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:n9}=globalThis.Bun;import{db as kJ}from"@stacksjs/database";import{formatDate as o9}from"@stacksjs/orm";import{sql as i6}from"@stacksjs/database";var u9={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","CANCELLED","REFUNDED"],SHIPPED:["DELIVERED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]};function PJ(G,J){if(G===J)return!0;return u9[G]?.includes(J)??!1}async function r(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 qJ(G){await r("order:created",{order:G})}async function u(G,J){await r("order:paid",{order:G,payment:J})}async function TG(G){await r("order:shipped",{order:G})}async function SG(G){await r("order:delivered",{order:G})}async function ZJ(G,J){await r("order:cancelled",{order:G,reason:J})}async function MJ(G,J){await r("order:refunded",{order:G,refundAmount:J})}async function jJ(G,J){switch(G){case"PROCESSING":return u(J);case"SHIPPED":return TG(J);case"DELIVERED":return SG(J);case"CANCELLED":return ZJ(J);case"REFUNDED":return MJ(J);case"PENDING":default:}}var s6=!1;function d6(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 i9(G){try{let J=await kJ.selectFrom("order_idempotency").where("idempotency_key","=",G).selectAll().executeTakeFirst();if(!J)return null;return await kJ.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}catch(J){if(d6(J)){if(!s6)s6=!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 a6(G){if(G.idempotencyKey){let J=await i9(G.idempotencyKey);if(J)return{ok:!0,order:J}}try{let J=await kJ.transaction(async(X)=>{let $=o9(new Date),K={...G.order,status:G.order.status||"PENDING",uuid:n9(),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 F=await X.updateTable("products").set({inventory_count:i6`inventory_count + ${x}`,updated_at:$}).where("id","=",N).where(i6`inventory_count + ${x}`,">=",0).execute();if(!Number(F?.numUpdatedRows??F?.[0]?.numUpdatedRows??F?.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(!d6(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(qJ(J.order),J.payment)u(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 PG}from"@stacksjs/database";import{formatDate as qG}from"@stacksjs/orm";async function t6(G,J){if(!await h(G))throw Error(`Order with ID ${G} not found`);try{return await PG.updateTable("orders").set({...J,updated_at:qG(new Date)}).where("id","=",G).execute(),await h(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update order: ${$.message}`);throw $}}async function r6(G,J){let X=await h(G);if(!X)throw Error(`Order with ID ${G} not found`);let $=X.status??"PENDING";if(!PJ($,J))throw Error(`[commerce/orders] illegal status transition ${$} \u2192 ${J}`);try{await PG.updateTable("orders").set({status:J,updated_at:qG(new Date)}).where("id","=",G).execute();let K=await h(G);if(K)jJ(J,K);return K}catch(K){if(K instanceof Error)throw TypeError(`Failed to update order status: ${K.message}`);throw K}}async function e6(G,J,X){let $=await h(G);if(!$)throw Error(`Order with ID ${G} not found`);let K={updated_at:qG(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 PG.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 e}from"@stacksjs/database";import{formatDate as wJ}from"@stacksjs/orm";async function jG(G){let J=await e.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!J)return null;return await e.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}var J$=!1;function s9(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 kG(G,J){try{return await J.insertInto("stripe_webhook_events").values({event_id:G,processed_at:wJ(new Date)}).execute(),!0}catch(X){if(X?.message?.includes("UNIQUE constraint")||X?.message?.includes("Duplicate entry"))return!1;if(s9(X)){if(!J$)J$=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw X}}async function wG(G){let X=G.data.object?.id;if(!X)return;await e.transaction(async(K)=>{if(!await kG(G.id,K))return;let Y=await K.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!Y)return;let W=wJ(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 jG(X);if($)await u($)}async function CG(G){let J=G.data.object,X=J?.id;if(!X)return;let K=J?.last_payment_error?.message??"payment failed";await e.transaction(async(Y)=>{if(!await kG(G.id,Y))return;let M=await Y.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!M)return;let Z=wJ(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 jG(X);if(L)await ZJ(L,K)}async function _G(G){let J=G.data.object,X=J?.payment_intent;if(!X)return;let $=J?.amount_refunded??0;await e.transaction(async(L)=>{if(!await kG(G.id,L))return;let W=await L.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!W)return;let M=wJ(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 jG(X);if(K)await MJ(K,$)}async function G$(){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:wG,failed:CG}),X({refunded:_G}),()=>{}}import{db as X$}from"@stacksjs/database";async function d9(G){if(G.length===0)return new Map;let J=await X$.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 a9(G){try{let J=await X$.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 $$(G){let J=G.items.map((E)=>E.productId),X=await d9(J),$=G.taxRateId!=null?await a9(G.taxRateId):0,K=0,L=[];for(let E of G.items){let z=E.unitPriceCents??X.get(E.productId)??0,O=Math.round(z*E.quantity);K+=O,L.push({productId:E.productId,quantity:E.quantity,unitPriceCents:z,lineCents:O})}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,F=!1,T=0;if(G.clientTotalCents!=null)T=Math.abs(N-G.clientTotalCents),F=T>x;return{subtotalCents:K,discountCents:Y,taxCents:M,shippingCents:Z,totalCents:N,resolvedItems:L,priceChanged:F,diffCents:T}}import{db as CJ}from"@stacksjs/database";function K$(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 IG(G,J){if(!Number.isFinite(J)||J<=0)return{ok:!1,productId:G,quantity:J,reason:"non-positive"};let X;try{X=await CJ.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 L$(G){for(let X of G){let $=await IG(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 Y$(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 CJ.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[K,K,X]),Y=typeof L?.execute==="function"?await L.execute():L;return{deleted:Number(Y?.changes??Y?.numDeletedRows??Y?.[0]?.numDeletedRows??Y?.affectedRows??0),cutoffAt:K}}catch{try{let L=await CJ.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 CJ.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 vG={};B(vG,{update:()=>A$,store:()=>B$,fetchPaymentStatsByMethod:()=>H$,fetchPaymentStats:()=>x$,fetchMonthlyPaymentTrends:()=>F$,fetchById:()=>NJ,fetchAll:()=>N$,destroy:()=>Z$,bulkDestroy:()=>M$});import{db as W$}from"@stacksjs/database";async function Z$(G){try{let J=await W$.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 M$(G){if(!G.length)return 0;try{let J=await W$.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 q}from"@stacksjs/database";import{formatDate as w}from"@stacksjs/orm";async function N$(){return await q.selectFrom("payments").selectAll().execute()}async function NJ(G){return await q.selectFrom("payments").selectAll().where("id","=",G).executeTakeFirst()}async function x$(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 q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").executeTakeFirst(),Y=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(K)).where("created_at","<=",w($)).where("status","=","completed").executeTakeFirst(),W=await q.selectFrom("payments").select(q.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),F=Number(Y?.total_revenue||0),T=x>0?F/x:0,E=M-x,z=Z-F,O=N-T,_=x>0?E/x*100:M>0?100:0,b=F>0?z/F*100:Z>0?100:0,m=T>0?O/T*100:N>0?100:0,d=Number(W?.count||0),I=d>0?M/d*100:0;return{total_transactions:M,total_revenue:Z,average_transaction:N,successful_rate:I,comparison:{transactions:{difference:E,percentage:Math.abs(_),is_increase:E>=0},revenue:{difference:z,percentage:Math.abs(b),is_increase:z>=0},average:{difference:O,percentage:Math.abs(m),is_increase:O>=0}}}}async function H$(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await q.selectFrom("payments").select([q.fn.count("id").as("total_count"),q.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 q.selectFrom("payments").select(["method",q.fn.count("id").as("count"),q.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 F$(){let G=new Date,J=new Date(G);J.setMonth(G.getMonth()-11),J.setDate(1);let X=await q.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:t9}=globalThis.Bun;import{db as Q$}from"@stacksjs/database";import{HttpError as V$}from"@stacksjs/error-handling";import{isUniqueViolation as r9}from"@stacksjs/orm";async function B$(G){let J={...G,status:G.status||"PENDING",currency:G.currency||"USD",uuid:t9()};try{let X=await Q$.insertInto("payments").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if($)return await Q$.selectFrom("payments").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof V$)throw X;if(r9(X))throw new V$(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 e9}from"@stacksjs/database";import{formatDate as JK}from"@stacksjs/orm";async function A$(G,J){if(!await NJ(G))throw Error(`Payment with ID ${G} not found`);try{return await e9.updateTable("payments").set({...J,updated_at:JK(new Date)}).where("id","=",G).execute(),await NJ(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 lG={};B(lG,{variants:()=>yJ,units:()=>gJ,reviews:()=>hJ,manufacturers:()=>vJ,items:()=>fJ,default:()=>MK,categories:()=>IJ});var IJ={};B(IJ,{updateParent:()=>g$,updateDisplayOrder:()=>v$,updateActiveStatus:()=>h$,update:()=>f$,store:()=>gG,removeChildCategories:()=>k$,remove:()=>q$,findOrCreateByName:()=>I$,fetchStats:()=>T$,fetchRootCategories:()=>O$,fetchChildCategories:()=>R$,fetchCategoryTree:()=>P$,fetchByName:()=>z$,fetchById:()=>P,fetchByDisplayOrder:()=>U$,fetchAll:()=>hG,fetchActive:()=>E$,deactivateChildCategories:()=>C$,deactivate:()=>w$,compareCategoryGrowth:()=>S$,bulkRemove:()=>j$});import{db as n}from"@stacksjs/database";import{db as U}from"@stacksjs/database";import{formatDate as xJ}from"@stacksjs/orm";async function hG(){return await U.selectFrom("categories").selectAll().execute()}async function P(G){return await U.selectFrom("categories").where("id","=",G).selectAll().executeTakeFirst()}async function z$(G){return await U.selectFrom("categories").where("name","=",G).selectAll().executeTakeFirst()}async function E$(){return await U.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function O$(){return await U.selectFrom("categories").where("parent_category_id","is",null).where("is_active","=",!0).selectAll().execute()}async function R$(G){return await U.selectFrom("categories").where("parent_category_id","=",G).where("is_active","=",!0).selectAll().execute()}async function U$(G=!0){let J=U.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 T$(){let G=await U.selectFrom("categories").select(U.fn.count("id").as("count")).executeTakeFirst(),J=await U.selectFrom("categories").where("is_active","=",!0).select(U.fn.count("id").as("count")).executeTakeFirst(),X=await U.selectFrom("categories").where("parent_category_id","is",null).select(U.fn.count("id").as("count")).executeTakeFirst(),$=await U.selectFrom("categories").where("image_url","is not",null).select(U.fn.count("id").as("count")).executeTakeFirst(),K=new Date;K.setDate(K.getDate()-30);let L=xJ(K),Y=await U.selectFrom("categories").where("created_at",">=",L).selectAll().limit(5).execute(),W=await U.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",U.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 S$(G=30){let J=new Date,X=xJ(J),$=new Date;$.setDate(J.getDate()-G);let K=xJ($),L=new Date($);L.setDate(L.getDate()-1);let Y=xJ(L),W=new Date(L);W.setDate(L.getDate()-G);let M=xJ(W),Z=await U.selectFrom("categories").select(U.fn.count("id").as("count")).where("created_at",">=",K).where("created_at","<=",X).executeTakeFirst(),N=await U.selectFrom("categories").select(U.fn.count("id").as("count")).where("created_at",">=",M).where("created_at","<=",Y).executeTakeFirst(),x=Number(Z?.count||0),F=Number(N?.count||0),T=x-F,E=F!==0?T/F*100:x>0?100:0;return{current_period:x,previous_period:F,difference:T,percentage_change:E,days_range:G}}async function P$(){let G=await hG(),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 q$(G){if(!await P(G))throw Error(`Category with ID ${G} not found`);return!!await n.deleteFrom("categories").where("id","=",G).executeTakeFirst()}async function j$(G){if(!G.length)return 0;let J=await n.deleteFrom("categories").where("id","in",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}async function k$(G){let J=await n.deleteFrom("categories").where("parent_category_id","=",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}async function w$(G){if(!await P(G))throw Error(`Category with ID ${G} not found`);return!!await n.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",G).executeTakeFirst()}async function C$(G){let J=await n.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 _$}from"@stacksjs/database";import{slug as GK}from"@stacksjs/strings";async function gG(G){try{let J={...G,slug:G.name?.toLowerCase().replace(/\s+/g,"-")||"",categorizable_type:"product",display_order:0},X=await _$.insertInto("categories").values(J).executeTakeFirst();if(!X)throw Error("Failed to create category");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await P($);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 I$(G){if(!G.name)throw Error("Name is required");let J=await _$.selectFrom("categories").selectAll().where("name","=",G.name).executeTakeFirst();if(J)return J;let X={name:G.name,slug:GK(G.name),is_active:G.is_active??!0,categorizable_type:G.categorizable_type??"default",display_order:0};return await gG(X)}import{db as HJ}from"@stacksjs/database";import{formatDate as _J}from"@stacksjs/orm";async function f$(G,J){await J.validate();let X=await P(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:_J(new Date)};if(Object.keys($).length===0)return X;try{return await HJ.updateTable("categories").set($).where("id","=",G).execute(),await P(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 v$(G,J){if(!await P(G))throw Error(`Category with ID ${G} not found`);try{return await HJ.updateTable("categories").set({display_order:J,updated_at:_J(new Date)}).where("id","=",G).execute(),await P(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category display order: ${$.message}`);throw $}}async function h$(G,J){if(!await P(G))throw Error(`Category with ID ${G} not found`);try{return await HJ.updateTable("categories").set({is_active:J,updated_at:_J(new Date)}).where("id","=",G).execute(),await P(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category active status: ${$.message}`);throw $}}async function g$(G,J){if(!await P(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 P($))throw Error(`Parent category with ID ${J} not found`);if(await XK(G,J))throw Error("This operation would create a circular reference in the category hierarchy")}try{let $={updated_at:_J(new Date)};if(J===null)await HJ.updateTable("categories").set({...$,parent_category_id:void 0}).where("id","=",G).execute();else await HJ.updateTable("categories").set({...$,parent_category_id:J}).where("id","=",G).execute();return await P(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category parent: ${$.message}`);throw $}}async function XK(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 P(X);if(!K||!K.parentCategoryId)return!1;X=Number(K.parentCategoryId)}return!1}var fJ={};B(fJ,{updateInventory:()=>s$,updateAvailability:()=>i$,update:()=>o$,store:()=>u$,fetchTopProducts:()=>m$,fetchById:()=>g,fetchAll:()=>b$,destroy:()=>D$,bulkStore:()=>n$,bulkDestroy:()=>p$});import{db as y$}from"@stacksjs/database";async function D$(G){try{let J=await y$.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 p$(G){if(!G.length)return 0;try{let J=await y$.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 p,sql as $K}from"@stacksjs/database";async function g(G){let J=await p.selectFrom("products").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=null,$=null;if(J.manufacturer_id)X=await p.selectFrom("manufacturers").where("id","=",J.manufacturer_id).selectAll().executeTakeFirst();if(J.category_id)$=await p.selectFrom("categories").where("id","=",J.category_id).selectAll().executeTakeFirst();return{...J,manufacturer:X,category:$}}return}async function b$(){let G=await p.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),$=p.selectFrom("manufacturers"),K=p.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 m$(G=5){try{return(await p.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",p.fn.sum("order_items.quantity").as("units_sold"),$K`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:l$}=globalThis.Bun;import{db as c$}from"@stacksjs/database";async function u$(G){try{let J={...G,uuid:l$()},X=await c$.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 n$(G){if(!G.length)return 0;let J=0;try{return await c$.transaction().execute(async(X)=>{for(let $ of G){let K={...$,uuid:l$()};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 yG,sql as h0}from"@stacksjs/database";import{formatDate as DG}from"@stacksjs/orm";async function o$(G,J){try{if(!G)throw Error("Product item ID is required for update");let X=await yG.updateTable("products").set({...J,updated_at:DG(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 i$(G,J){if(!await g(G))throw Error(`Product item with ID ${G} not found`);try{return await yG.updateTable("products").set({is_available:J,updated_at:DG(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 s$(G,J){let X=await g(G);if(!X)throw Error(`Product item with ID ${G} not found`);let $={updated_at:DG(new Date)};if(J!==void 0)$.inventory_count=J;if(Object.keys($).length===1)return X;try{return await yG.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 vJ={};B(vJ,{updateFeaturedStatus:()=>x2,updateByUuid:()=>H2,update:()=>N2,store:()=>W2,fetchWithProductCount:()=>$2,fetchFeatured:()=>G2,fetchByUuid:()=>J2,fetchById:()=>e$,fetchByCountry:()=>X2,fetchAll:()=>r$,destroy:()=>a$,bulkStore:()=>Z2,bulkDestroy:()=>t$});import{db as d$}from"@stacksjs/database";async function a$(G){try{let J=await d$.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 t$(G){if(!G.length)return 0;try{let J=await d$.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 y}from"@stacksjs/database";function r$(){return y.selectFrom("manufacturers").selectAll().execute()}async function e$(G){return await y.selectFrom("manufacturers").where("id","=",G).selectAll().executeTakeFirst()}async function J2(G){return await y.selectFrom("manufacturers").where("uuid","=",G).selectAll().executeTakeFirst()}async function G2(G=10){return await y.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(G).execute()}async function X2(G,J={}){let X=J.page||1,$=J.limit||2,K=await y.selectFrom("manufacturers").select(y.fn.count("id").as("total")).where("country","=",G).executeTakeFirst(),L=Number(K?.total||0),Y=await y.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 $2(G={}){let J=y.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",y.fn.count("p.id").as("product_count")]).groupBy("m.id"),J.execute()}var{randomUUIDv7:L2}=globalThis.Bun;import{db as Y2}from"@stacksjs/database";import{HttpError as K2}from"@stacksjs/error-handling";import{isUniqueViolation as KK}from"@stacksjs/orm";async function W2(G){try{let J={...G,uuid:L2(),featured:G.featured??!1},X=await Y2.insertInto("manufacturers").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create manufacturer");return X}catch(J){if(J instanceof K2)throw J;if(KK(J))throw new K2(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to create manufacturer: ${J.message}`);throw J}}async function Z2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:L2(),featured:X.featured??!1};await Y2.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 pG}from"@stacksjs/database";import{HttpError as M2}from"@stacksjs/error-handling";import{formatDate as bG,isUniqueViolation as LK}from"@stacksjs/orm";async function N2(G,J){try{if(!G)throw Error("Manufacturer ID is required for update");let X=await pG.updateTable("manufacturers").set({...J,updated_at:bG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error(`Manufacturer with ID ${G} not found`);return X}catch(X){if(X instanceof M2)throw X;if(LK(X))throw new M2(409,"A manufacturer with this name already exists");if(X instanceof Error)throw Error(`Failed to update manufacturer: ${X.message}`);throw X}}async function x2(G,J){try{let X=await pG.updateTable("manufacturers").set({featured:J,updated_at:bG(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 H2(G,J){try{let X=await pG.updateTable("manufacturers").set({...J,updated_at:bG(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 hJ={};B(hJ,{updateVotes:()=>q2,update:()=>P2,store:()=>U2,fetchMostHelpfulByProductId:()=>R2,fetchByUserId:()=>E2,fetchByProductId:()=>z2,fetchById:()=>B2,fetchApprovedByProductId:()=>O2,fetchAll:()=>A2,destroy:()=>Q2,bulkDestroy:()=>V2});import{db as F2}from"@stacksjs/database";async function Q2(G){try{let J=await F2.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 V2(G){if(!G.length)return 0;try{let J=await F2.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 JJ}from"@stacksjs/database";async function B2(G){return await JJ.selectFrom("reviews").where("id","=",G).selectAll().executeTakeFirst()}async function A2(){return await JJ.selectFrom("reviews").selectAll().execute()}async function z2(G){return await JJ.selectFrom("reviews").where("product_id","=",G).selectAll().execute()}async function E2(G){return await JJ.selectFrom("reviews").where("customer_id","=",G).selectAll().execute()}async function O2(G){return await JJ.selectFrom("reviews").where("product_id","=",G).where("is_approved","=",!0).selectAll().execute()}async function R2(G){return await JJ.selectFrom("reviews").where("product_id","=",G).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:YK}=globalThis.Bun;import{db as WK}from"@stacksjs/database";async function U2(G){try{let J={...G,uuid:YK(),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 WK.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 T2}from"@stacksjs/database";import{formatDate as S2}from"@stacksjs/orm";async function P2(G,J){try{if(!G)throw Error("Review ID is required for update");let X=await T2.updateTable("reviews").set({...J,updated_at:S2(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 q2(G,J,X=!0){try{let $=J==="helpful"?"helpful_votes":"unhelpful_votes",K=X?`COALESCE("${$}", 0) + 1`:`MAX(COALESCE("${$}", 0) - 1, 0)`,L=await T2.unsafe(`UPDATE "reviews" SET "${$}" = ${K}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[S2(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 gJ={};B(gJ,{updateDefaultStatus:()=>b2,update:()=>D2,store:()=>v2,getDefaultUnit:()=>y2,formatUnitOptions:()=>g2,fetchById:()=>_2,fetchAll:()=>I2,destroy:()=>k2,bulkUpdate:()=>p2,bulkStore:()=>h2,bulkDestroy:()=>w2});import{db as j2}from"@stacksjs/database";async function k2(G){try{let J=await j2.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 w2(G){if(!G.length)return 0;try{let J=await j2.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 C2}from"@stacksjs/database";async function _2(G){return await C2.selectFrom("product_units").where("id","=",G).selectAll().executeTakeFirst()}async function I2(){return await C2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:f2}=globalThis.Bun;import{db as GJ}from"@stacksjs/database";async function v2(G){try{let J={...G,uuid:f2()},X=await GJ.insertInto("product_units").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(J.is_default)await GJ.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 h2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:f2()},K=await GJ.insertInto("product_units").values($).returningAll().executeTakeFirst();if($.is_default&&K)await GJ.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 g2(G){try{let J=GJ.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 y2(G){try{return await GJ.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 o}from"@stacksjs/database";import{formatDate as mG}from"@stacksjs/orm";async function D2(G,J){try{if(!G)throw Error("Product unit ID is required for update");let X=await o.updateTable("product_units").set({...J,updated_at:mG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product unit");if(J.is_default===!0&&J.type)await o.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 p2(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 o.updateTable("product_units").set({...K,updated_at:mG(new Date)}).where("id","=",$.id).executeTakeFirst(),Y=K;if(Y.is_default===!0&&Y.type)await o.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 o.selectFrom("product_units").select("type").where("id","=",G).executeTakeFirst();if(!X)return!1;let $=await o.updateTable("product_units").set({is_default:J,updated_at:mG(new Date)}).where("id","=",G).executeTakeFirst();if(J&&X.type)await o.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 yJ={};B(yJ,{update:()=>G4,store:()=>d2,generateVariantCombinations:()=>r2,formatVariantOptions:()=>t2,fetchById:()=>n2,fetchAll:()=>o2,destroy:()=>l2,bulkUpdate:()=>X4,bulkStore:()=>a2,bulkDestroy:()=>c2});import{db as m2}from"@stacksjs/database";async function l2(G){try{let J=await m2.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 c2(G){if(!G.length)return 0;try{let J=await m2.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 u2}from"@stacksjs/database";async function n2(G){return await u2.selectFrom("product_variants").where("id","=",G).selectAll().executeTakeFirst()}async function o2(){return await u2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:i2}=globalThis.Bun;import{db as s2}from"@stacksjs/database";async function d2(G){try{let J={...G,uuid:i2()},X=await s2.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 a2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:i2()};await s2.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 t2(G){if(!G||!G.length)return JSON.stringify([]);let J=G.map((X)=>X.trim()).filter(Boolean);return JSON.stringify(J)}function r2(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 e2}from"@stacksjs/database";import{formatDate as J4}from"@stacksjs/orm";async function G4(G,J){try{let X=await e2.updateTable("product_variants").set({...J,updated_at:J4(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 X4(G){if(!G.length)return 0;let J=0;try{for(let X of G){if(!X.id)continue;let $=await e2.updateTable("product_variants").set({...X,updated_at:J4(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 ZK={categories:IJ,items:fJ,manufacturers:vJ,reviews:hJ,units:gJ,variants:yJ},MK=ZK;var nG={};B(nG,{updateStatus:()=>Q4,updatePrintJob:()=>V4,update:()=>F4,store:()=>x4,fetchById:()=>W4,fetchAll:()=>Z4,destroy:()=>K4,bulkStore:()=>H4,bulkDestroy:()=>L4});import{db as $4}from"@stacksjs/database";async function K4(G){try{let J=await $4.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 L4(G){if(!G.length)return 0;try{let J=await $4.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 Y4}from"@stacksjs/database";async function W4(G){return await Y4.selectFrom("receipts").where("id","=",G).selectAll().executeTakeFirst()}async function Z4(){return await Y4.selectFrom("receipts").selectAll().execute()}var{randomUUIDv7:M4}=globalThis.Bun;import{db as N4}from"@stacksjs/database";async function x4(G){try{let J={...G,uuid:M4()},X=await N4.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 H4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:M4()})),X=await N4.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 cG}from"@stacksjs/database";import{formatDate as uG}from"@stacksjs/orm";async function F4(G,J){try{if(!G)throw Error("Receipt ID is required for update");let X=await cG.updateTable("receipts").set({...J,updated_at:uG(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 Q4(G,J){try{let X=await cG.updateTable("receipts").set({status:J,updated_at:uG(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 V4(G,J,X,$){try{let K={updated_at:uG(new Date)};if(J!==void 0)K.size=J;if(X!==void 0)K.pages=X;if($!==void 0)K.duration=$;let L=await cG.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 $X={};B($X,{zones:()=>YG,routes:()=>pJ,rates:()=>XG,methods:()=>aJ,licenses:()=>oJ,drivers:()=>cJ,digital:()=>lJ,default:()=>HK});var pJ={};B(pJ,{updateStops:()=>j4,updateMetrics:()=>k4,updateLastActive:()=>P4,update:()=>q4,store:()=>S4,fetchById:()=>E4,fetchByDriver:()=>U4,fetchAll:()=>O4,fetchActive:()=>R4,destroy:()=>A4,bulkDestroy:()=>z4});import{db as B4}from"@stacksjs/database";async function A4(G){try{let J=await B4.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 z4(G){if(!G.length)return 0;try{let J=await B4.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 DJ}from"@stacksjs/database";async function E4(G){return await DJ.selectFrom("delivery_routes").where("id","=",G).selectAll().executeTakeFirst()}async function O4(){return await DJ.selectFrom("delivery_routes").selectAll().execute()}async function R4(){return await DJ.selectFrom("delivery_routes").where("last_active","<=",new Date(Date.now()-86400000)).selectAll().execute()}async function U4(G){return await DJ.selectFrom("delivery_routes").where("driver","=",G).selectAll().execute()}var{randomUUIDv7:NK}=globalThis.Bun;import{db as T4}from"@stacksjs/database";async function S4(G){try{let J={...G,uuid:NK()},X=await T4.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 T4.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 oG}from"@stacksjs/database";import{formatDate as iG}from"@stacksjs/orm";async function q4(G,J){try{if(!G)throw Error("Delivery route ID is required for update");let X=await oG.updateTable("delivery_routes").set({...J,updated_at:iG(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 j4(G,J){try{let X=await oG.updateTable("delivery_routes").set({stops:J,updated_at:iG(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 k4(G,J,X){try{let $={updated_at:iG(new Date)};if(J!==void 0)$.delivery_time=J;if(X!==void 0)$.total_distance=X;let K=await oG.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 lJ={};B(lJ,{updateStatus:()=>b4,updateDeliverySettings:()=>m4,update:()=>p4,store:()=>y4,softDelete:()=>C4,fetchById:()=>mJ,fetchAll:()=>v4,destroy:()=>w4,bulkStore:()=>D4,bulkSoftDelete:()=>I4,bulkDestroy:()=>_4});import{db as bJ}from"@stacksjs/database";async function w4(G){try{let J=await bJ.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 C4(G){try{let J=await bJ.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 _4(G){if(!G.length)return 0;try{let J=await bJ.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 I4(G){if(!G.length)return 0;try{let J=await bJ.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 f4}from"@stacksjs/database";async function mJ(G){return await f4.selectFrom("digital_deliveries").where("id","=",G).selectAll().executeTakeFirst()}async function v4(){return await f4.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:h4}=globalThis.Bun;import{db as g4}from"@stacksjs/database";async function y4(G){try{let J={...G,uuid:h4()},X=await g4.insertInto("digital_deliveries").values(J).executeTakeFirst();if(!X)throw Error("Failed to create digital delivery");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await mJ($);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 D4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:h4()})),X=await g4.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 sG}from"@stacksjs/database";import{formatDate as dG}from"@stacksjs/orm";async function p4(G,J){try{if(!G)throw Error("Digital delivery ID is required for update");let X=await sG.updateTable("digital_deliveries").set({...J,updated_at:dG(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 sG.updateTable("digital_deliveries").set({status:J,updated_at:dG(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 m4(G,J,X,$,K){try{let L={updated_at:dG(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 sG.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 cJ={};B(cJ,{updateStatus:()=>r4,updateContact:()=>e4,update:()=>t4,store:()=>d4,fetchById:()=>FJ,fetchAll:()=>c4,destroy:()=>n4,bulkStore:()=>a4,bulkDestroy:()=>o4});import{db as u4}from"@stacksjs/database";import{db as l4}from"@stacksjs/database";async function FJ(G){return await l4.selectFrom("drivers").where("id","=",G).selectAll().executeTakeFirst()}async function c4(){return await l4.selectFrom("drivers").selectAll().execute()}async function n4(G){let J=await FJ(G);if(!J)throw Error(`Driver with ID ${G} not found`);try{return await u4.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 o4(G){if(!G.length)return 0;let J=0;try{return await u4.transaction().execute(async(X)=>{for(let $ of G)if(await FJ($))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:i4}=globalThis.Bun;import{db as s4}from"@stacksjs/database";async function d4(G){try{let J={...G,uuid:i4()},X=await s4.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 a4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:i4()})),X=await s4.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 aG}from"@stacksjs/database";import{formatDate as tG}from"@stacksjs/orm";async function t4(G,J){try{if(!G)throw Error("Driver ID is required for update");let X=await aG.updateTable("drivers").set({...J,updated_at:tG(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 r4(G,J){try{let X=await aG.updateTable("drivers").set({status:J,updated_at:tG(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 e4(G,J){try{let X={updated_at:tG(new Date)};if(J!==void 0)X.phone=J;let $=await aG.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 oJ={};B(oJ,{updateStatus:()=>x7,updateExpiration:()=>H7,update:()=>N7,store:()=>Z7,softDelete:()=>G7,fetchById:()=>nJ,fetchAll:()=>L7,destroy:()=>J7,bulkStore:()=>M7,bulkSoftDelete:()=>$7,bulkDestroy:()=>X7});import{db as uJ}from"@stacksjs/database";async function J7(G){try{let J=await uJ.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 G7(G){try{let J=await uJ.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 X7(G){if(!G.length)return 0;try{let J=await uJ.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 $7(G){if(!G.length)return 0;try{let J=await uJ.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 K7}from"@stacksjs/database";async function nJ(G){return await K7.selectFrom("license_keys").where("id","=",G).selectAll().executeTakeFirst()}async function L7(){return await K7.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:Y7}=globalThis.Bun;import{db as W7}from"@stacksjs/database";async function Z7(G){try{let J={...G,uuid:Y7()},X=await W7.insertInto("license_keys").values(J).executeTakeFirst();if(!X)throw Error("Failed to create license key");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await nJ($);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 M7(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:Y7()})),X=await W7.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 rG}from"@stacksjs/database";import{formatDate as eG}from"@stacksjs/orm";async function N7(G,J){try{if(!G)throw Error("License key ID is required for update");let X=await rG.updateTable("license_keys").set({...J,updated_at:eG(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 x7(G,J){try{let X=await rG.updateTable("license_keys").set({status:J,updated_at:eG(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 H7(G,J){try{let X={updated_at:eG(new Date)};if(J!==void 0)X.expiry_date=J;let $=await rG.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 aJ={};B(aJ,{updateStatus:()=>S7,updatePricing:()=>P7,update:()=>T7,store:()=>E7,softDelete:()=>Q7,getActiveShippingMethods:()=>U7,formatShippingOptions:()=>R7,fetchById:()=>i,fetchAll:()=>A7,destroy:()=>F7,bulkStore:()=>O7,bulkSoftDelete:()=>B7,bulkDestroy:()=>V7});import{db as iJ}from"@stacksjs/database";async function F7(G){try{let J=await iJ.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 Q7(G){try{let J=await iJ.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 V7(G){if(!G.length)return 0;try{let J=await iJ.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 B7(G){if(!G.length)return 0;try{let J=await iJ.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 sJ}from"@stacksjs/database";async function i(G){let J=await sJ.selectFrom("shipping_methods").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=await sJ.selectFrom("shipping_zones").where("shipping_method_id","=",G).selectAll().execute();return{...J,shippingZones:X}}return}async function A7(){let G=await sJ.selectFrom("shipping_methods").selectAll().execute(),J=G.map((L)=>L.id),X=sJ.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:z7}=globalThis.Bun;import{db as dJ}from"@stacksjs/database";async function E7(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:z7()},$=await dJ.insertInto("shipping_methods").values(X).executeTakeFirst();if(!$)throw Error("Failed to create shipping method");let K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);return await i(K)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping method: ${J.message}`);throw J}}async function O7(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:z7()})),X=await dJ.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 R7(){try{return dJ.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 U7(){try{return await dJ.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 JX}from"@stacksjs/database";import{formatDate as GX}from"@stacksjs/orm";async function T7(G,J){try{if(!G)throw Error("Shipping method ID is required for update");let X=await JX.updateTable("shipping_methods").set({...J,updated_at:GX(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 S7(G,J){try{let X=await JX.updateTable("shipping_methods").set({status:J,updated_at:GX(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:GX(new Date)};if(J!==void 0)$.base_rate=J;if(X!==void 0)$.free_shipping=X;let K=await JX.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 XG={};B(XG,{validateZoneMatchesAddress:()=>v7,updateByZone:()=>i7,updateByMethod:()=>s7,update:()=>n7,store:()=>c7,resolveZoneForAddress:()=>eJ,getShippingRatesByMethod:()=>g7,getRatesByZone:()=>I7,getRateByWeightAndZone:()=>XX,getRateByWeightAndAddress:()=>f7,formatShippingRateOptions:()=>h7,fetchById:()=>rJ,fetchAll:()=>_7,destroyByZone:()=>k7,destroyByMethod:()=>w7,destroy:()=>q7,bulkUpdate:()=>o7,bulkStore:()=>u7,bulkDestroy:()=>j7});import{db as tJ}from"@stacksjs/database";async function q7(G){try{let J=await tJ.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 j7(G){if(!G.length)return 0;try{let J=await tJ.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 k7(G){try{let J=await tJ.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 w7(G){try{let J=await tJ.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 rJ(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 _7(){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 I7(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 XX(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 eJ(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&&C7($.regions,G.region))K=2;if(G.postalCode&&$.postal_codes&&C7($.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 f7(G,J){let X=await eJ(J);if(X==null)return;return XX(G,X)}async function v7(G,J){return await eJ(J)===G}function C7(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 h7(){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 g7(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:m7}=globalThis.Bun;import{db as l7}from"@stacksjs/database";import{db as QJ}from"@stacksjs/database";async function y7(){return await QJ.selectFrom("shipping_zones").selectAll().execute()}async function s(G){return await QJ.selectFrom("shipping_zones").where("id","=",G).selectAll().executeTakeFirst()}function D7(){try{return QJ.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 p7(){try{return await QJ.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 QJ.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 c7(G){try{let J=await i(Number(G.shippingmethod_id)),X=await s(Number(G.shippingzone_id)),$={weightFrom:G.weightFrom,weightTo:G.weightTo,rate:G.rate,shippingmethod_id:J?.id,shippingzone_id:X?.id,uuid:m7()},K=await l7.insertInto("shipping_rates").values($).executeTakeFirst();if(!K)throw Error("Failed to create shipping rate");let L=Number(K.insertId)||Number(K.numInsertedOrUpdatedRows);return await rJ(L)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping rate: ${J.message}`);throw J}}async function u7(G){if(!G.length)return 0;try{for(let $ of G){let K=await i(Number($.shippingmethod_id)),L=await s(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:m7()})),X=await l7.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 JG}from"@stacksjs/database";import{formatDate as GG}from"@stacksjs/orm";async function n7(G,J){try{if(!G)throw Error("Shipping rate ID is required for update");let X=await JG.updateTable("shipping_rates").set({...J,updated_at:GG(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 o7(G){if(!G.length)return 0;try{let J=0;for(let{id:X,data:$}of G){let K=await JG.updateTable("shipping_rates").set({...$,updated_at:GG(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 i7(G,J){try{let X=await JG.updateTable("shipping_rates").set({...J,updated_at:GG(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 s7(G,J){try{let X=await JG.updateTable("shipping_rates").set({...J,updated_at:GG(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 YG={};B(YG,{updateStatus:()=>K1,updateRegionsAndPostalCodes:()=>Y1,updateCountries:()=>L1,update:()=>$1,store:()=>G1,softDelete:()=>a7,getZonesByCountry:()=>b7,getActiveShippingZones:()=>p7,formatZoneOptions:()=>D7,fetchById:()=>s,fetchAll:()=>y7,destroy:()=>d7,bulkStore:()=>X1,bulkSoftDelete:()=>r7,bulkDestroy:()=>t7});import{db as $G}from"@stacksjs/database";async function d7(G){try{let J=await $G.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 a7(G){try{let J=await $G.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 t7(G){if(!G.length)return 0;try{let J=await $G.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 r7(G){if(!G.length)return 0;try{let J=await $G.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:e7}=globalThis.Bun;import{db as J1}from"@stacksjs/database";async function G1(G){try{let J={...G,uuid:e7()},X=await J1.insertInto("shipping_zones").values(J).executeTakeFirst();if(!X)throw Error("Failed to create shipping zone");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await s($)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zone: ${J.message}`);throw J}}async function X1(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:e7()})),X=await J1.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 KG}from"@stacksjs/database";import{formatDate as LG}from"@stacksjs/orm";async function $1(G,J){try{if(!G)throw Error("Shipping zone ID is required for update");let X=await KG.updateTable("shipping_zones").set({...J,updated_at:LG(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 K1(G,J){try{let X=await KG.updateTable("shipping_zones").set({status:J,updated_at:LG(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 L1(G,J){try{let X=await KG.updateTable("shipping_zones").set({countries:J,updated_at:LG(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 Y1(G,J,X){try{let $={updated_at:LG(new Date)};if(J!==void 0)$.regions=J;if(X!==void 0)$.postal_codes=X;let K=await KG.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 xK={digital:lJ,drivers:cJ,licenses:oJ,methods:aJ,rates:XG,routes:pJ,zones:YG},HK=xK;var YX={};B(YX,{updateStatus:()=>z1,updateRate:()=>E1,update:()=>A1,store:()=>V1,fetchById:()=>x1,fetchAll:()=>H1,destroy:()=>Z1,bulkStore:()=>B1,bulkDestroy:()=>M1});import{db as W1}from"@stacksjs/database";async function Z1(G){try{let J=await W1.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 M1(G){if(!G.length)return 0;try{let J=await W1.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 N1}from"@stacksjs/database";async function x1(G){return await N1.selectFrom("tax_rates").where("id","=",G).selectAll().executeTakeFirst()}async function H1(){return await N1.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:F1}=globalThis.Bun;import{db as Q1}from"@stacksjs/database";async function V1(G){try{let J={...G,uuid:F1()},X=await Q1.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 B1(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:F1()})),X=await Q1.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 KX}from"@stacksjs/database";import{formatDate as LX}from"@stacksjs/orm";async function A1(G,J){try{if(!G)throw Error("Tax rate ID is required for update");let X=J,$=await KX.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:LX(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 z1(G,J){try{let X=await KX.updateTable("tax_rates").set({status:J,updated_at:LX(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 E1(G,J){try{let X=await KX.updateTable("tax_rates").set({rate:J,updated_at:LX(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 MX={};B(MX,{restaurant:()=>$J,products:()=>ZG,default:()=>QK});var ZG={};B(ZG,{updateStatus:()=>m1,updatePartySize:()=>l1,update:()=>b1,store:()=>D1,fetchWaiting:()=>_1,fetchPurchasedBetweenDates:()=>w1,fetchNotifiedBetweenDates:()=>k1,fetchCountByStatus:()=>I1,fetchCountBySource:()=>S1,fetchCountByQuantity:()=>q1,fetchCountByDateGrouped:()=>h1,fetchCountByDate:()=>P1,fetchCountByAllQuantities:()=>j1,fetchCountBetweenDates:()=>v1,fetchConversionRates:()=>f1,fetchCancelledBetweenDates:()=>C1,fetchById:()=>U1,fetchAll:()=>T1,destroy:()=>O1,bulkStore:()=>p1,bulkDestroy:()=>R1});import{db as WG}from"@stacksjs/database";async function O1(G){try{let J=await WG.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst();if(!J)return;return await WG.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 R1(G){if(!G.length)return 0;try{return(await WG.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 A}from"@stacksjs/database";import{formatDate as S}from"@stacksjs/orm";async function U1(G){return await A.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst()}async function T1(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function S1(G,J){let X=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(G&&J){let K=S(G),L=S(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 $=S(J),K=S(X);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function q1(G){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",G).executeTakeFirst())?.count??0}async function j1(G,J){let X=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(G&&J){let K=S(G),L=S(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 k1(G,J){let X=S(G),$=S(J);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",X).where("notified_at","<=",$).where("notified_at","is not",null).execute()}async function w1(G,J){let X=S(G),$=S(J);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",X).where("purchased_at","<=",$).where("purchased_at","is not",null).execute()}async function C1(G,J){let X=S(G),$=S(J);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",X).where("cancelled_at","<=",$).where("cancelled_at","is not",null).execute()}async function _1(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function I1(G,J,X){let $=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",G);if(J&&X){let L=S(J),Y=S(X);$=$.where("created_at",">=",L).where("created_at","<=",Y)}return(await $.executeTakeFirst())?.count??0}async function f1(G,J){let X=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(G&&J){let M=S(G),Z=S(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 v1(G,J){let X=S(G),$=S(J);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",$).executeTakeFirst())?.count??0}async function h1(G,J){let X=A.selectFrom("waitlist_products").select(["created_at"]);if(G&&J){let L=S(G),Y=S(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:g1}=globalThis.Bun;import{db as y1}from"@stacksjs/database";import{formatDate as XJ}from"@stacksjs/orm";async function D1(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:g1(),status:G.status||"waiting"};if(G.notified_at!==void 0)X.notified_at=typeof G.notified_at==="number"?XJ(G.notified_at):G.notified_at;if(G.purchased_at!==void 0)X.purchased_at=typeof G.purchased_at==="number"?XJ(G.purchased_at):G.purchased_at;if(G.cancelled_at!==void 0)X.cancelled_at=typeof G.cancelled_at==="number"?XJ(G.cancelled_at):G.cancelled_at;let $=await y1.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 p1(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:g1(),status:$.status||"waiting"};if($.notified_at!==void 0)L.notified_at=typeof $.notified_at==="number"?XJ($.notified_at):$.notified_at;if($.purchased_at!==void 0)L.purchased_at=typeof $.purchased_at==="number"?XJ($.purchased_at):$.purchased_at;if($.cancelled_at!==void 0)L.cancelled_at=typeof $.cancelled_at==="number"?XJ($.cancelled_at):$.cancelled_at;return L}),X=await y1.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 WX}from"@stacksjs/database";import{formatDate as ZX}from"@stacksjs/orm";async function b1(G,J){try{if(!G)throw Error("Waitlist product ID is required for update");let X=J,$=await WX.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:ZX(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 m1(G,J){try{let X=await WX.updateTable("waitlist_products").set({status:J,updated_at:ZX(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 l1(G,J){try{let X=await WX.updateTable("waitlist_products").set({quantity:J,updated_at:ZX(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 $J={};B($J,{updateWaitTimes:()=>z9,updateStatus:()=>B9,updateQueuePosition:()=>E9,updatePartySize:()=>A9,update:()=>V9,store:()=>F9,fetchWaitingWithQuotedTimes:()=>X9,fetchWaitingWithPartySizes:()=>$9,fetchWaiting:()=>e1,fetchTimeSeriesStats:()=>M9,fetchTablesTurnedToday:()=>K9,fetchSeatingRate:()=>L9,fetchSeatedStats:()=>Z9,fetchSeatedBetweenDates:()=>r1,fetchNoShowStats:()=>Y9,fetchCurrentWaitTimes:()=>W9,fetchCountByTablePreference:()=>i1,fetchCountByPartySize:()=>d1,fetchCountByDate:()=>s1,fetchCountByAllPartySizes:()=>a1,fetchConversionRates:()=>J9,fetchById:()=>n1,fetchBetweenDates:()=>t1,fetchAverageWaitTimes:()=>G9,fetchAll:()=>o1,destroy:()=>c1,bulkStore:()=>Q9,bulkDestroy:()=>u1});import{db as MG}from"@stacksjs/database";async function c1(G){try{let J=await MG.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst();if(!J)return;return await MG.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 u1(G){if(!G.length)return 0;try{return(await MG.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 Q}from"@stacksjs/database";import{formatDate as k}from"@stacksjs/orm";async function n1(G){return await Q.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst()}async function o1(){return await Q.selectFrom("waitlist_restaurants").selectAll().execute()}async function i1(){return(await Q.selectFrom("waitlist_restaurants").select(["table_preference",Q.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((J,{table_preference:X,count:$})=>{return J[X]=$,J},{})}async function s1(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 Q.selectFrom("waitlist_restaurants").select(Q.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function d1(G){return(await Q.selectFrom("waitlist_restaurants").select(Q.fn.count("id").as("count")).where("party_size","=",G).executeTakeFirst())?.count??0}async function a1(){return(await Q.selectFrom("waitlist_restaurants").select(["party_size",Q.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((J,{party_size:X,count:$})=>{return J[X]=$,J},{})}async function t1(G,J){let X=k(G),$=k(J);return await Q.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",X).where("created_at","<=",$).execute()}async function r1(G,J){let X=k(G),$=k(J);return await Q.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",X).where("check_in_time","<=",$).where("status","=","seated").execute()}async function e1(){return await Q.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function J9(){let G=await Q.selectFrom("waitlist_restaurants").select(["status",Q.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 G9(){let G=await Q.selectFrom("waitlist_restaurants").select([Q.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),Q.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 X9(){let G=await Q.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 $9(){let G=await Q.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 K9(){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 Q.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",$).where("check_in_time","<=",K).execute(),Y=L.length,W=L.reduce((x,F)=>x+F.party_size,0),M=Y>0?W/Y:0,Z=L.reduce((x,F)=>{return x[F.table_preference]=(x[F.table_preference]||0)+1,x},{}),N=L.reduce((x,F)=>{return x[F.party_size]=(x[F.party_size]||0)+1,x},{});return{totalTablesTurned:Y,averagePartySize:M,totalCustomersSeated:W,breakdownByTablePreference:Z,breakdownByPartySize:N}}async function L9(G,J){let X=k(G),$=k(J),K=await Q.selectFrom("waitlist_restaurants").select(["status",Q.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 Y9(G,J){let X=k(G),$=k(J),K=Q.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",X).where("check_in_time","<=",$),L=await Q.selectFrom("waitlist_restaurants").select(Q.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((z,O)=>z+(O.quoted_wait_time??0),0),N=W>0?Z/W:0,x=Y.reduce((z,O)=>z+O.party_size,0),F=W>0?x/W:0,T=Y.reduce((z,O)=>{return z[O.table_preference]=(z[O.table_preference]||0)+1,z},{}),E=Y.reduce((z,O)=>{return z[O.party_size]=(z[O.party_size]||0)+1,z},{});return{totalNoShows:W,noShowRate:M,averageQuotedWaitTime:N,averagePartySize:F,breakdownByTablePreference:T,breakdownByPartySize:E}}async function W9(){let G=await Q.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 Z9(){let G=Date.now()-86400000,J=await Q.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 M9(){return(await Q.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:N9}=globalThis.Bun;import{db as x9}from"@stacksjs/database";import{formatDate as H9}from"@stacksjs/orm";async function F9(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"?H9(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:N9()},$={};for(let[Y,W]of Object.entries(X))if(W!==void 0)$[Y]=W;let K=await x9.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 Q9(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"?H9(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:N9()}}),X=await x9.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 VJ}from"@stacksjs/database";import{formatDate as BJ}from"@stacksjs/orm";async function V9(G,J){try{if(!G)throw Error("Restaurant waitlist entry ID is required for update");let X=J,$=await VJ.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:BJ(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 B9(G,J){try{let X=await VJ.updateTable("waitlist_restaurants").set({status:J,updated_at:BJ(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 A9(G,J){try{let X=await VJ.updateTable("waitlist_restaurants").set({party_size:J,updated_at:BJ(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 z9(G,J,X){try{let $=await VJ.updateTable("waitlist_restaurants").set({quoted_wait_time:J,actual_wait_time:X,updated_at:BJ(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 E9(G,J){try{let X=await VJ.updateTable("waitlist_restaurants").set({queue_position:J,updated_at:BJ(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 FK={products:ZG,restaurant:$J},QK=FK;var VK={coupons:NG,customers:HG,devices:BG,errors:EG,giftCards:UG,orders:fG,payments:vG,products:lG,receipts:nG,restaurant:$J,shippings:$X,tax:YX,waitlists:MX},eZ=VK;export{MX as waitlists,YX as tax,$X as shippings,$J as restaurant,nG as receipts,lG as products,vG as payments,fG as orders,UG as giftCards,EG as errors,BG as devices,eZ as default,HG as customers,NG as coupons,VK as commerce};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/commerce",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.70.
|
|
5
|
+
"version": "0.70.114",
|
|
6
6
|
"description": "Stacks commerce utilities.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -56,6 +56,6 @@
|
|
|
56
56
|
"ts-spreadsheets": "^0.2.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
|
-
"better-dx": "
|
|
59
|
+
"better-dx": "catalog:"
|
|
60
60
|
}
|
|
61
61
|
}
|