@stacksjs/commerce 0.70.260 → 0.70.262
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 +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ var x3=Object.defineProperty;var H3=(N)=>N;function V3(N,$){this[N]=H3.bind(null
|
|
|
5
5
|
AND (max_uses IS NULL OR usage_count < max_uses)
|
|
6
6
|
AND is_active = 1
|
|
7
7
|
AND (start_date IS NULL OR start_date <= ?)
|
|
8
|
-
AND (end_date IS NULL OR end_date >= ?)`,[$,N,$,$]),G=typeof J?.execute==="function"?await J.execute():J;if(Number(G?.changes??G?.numUpdatedRows??G?.affectedRows??0)>0){let Z=await d(N);if(Z)return{ok:!0,coupon:Z};return{ok:!1,reason:"not-found"}}let L=await d(N);if(!L)return{ok:!1,reason:"not-found"};if(!L.isActive)return{ok:!1,reason:"inactive"};let W=!L.startDate||L.startDate<=$,Y=!L.endDate||L.endDate>=$;if(!W||!Y)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var b$={};B(b$,{update:()=>E4,store:()=>w4,fetchById:()=>p0,fetchAll:()=>S4,destroy:()=>R4,bulkDestroy:()=>_4});import{db as A4}from"@stacksjs/database";async function R4(N){try{let $=await A4.deleteFrom("customers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function _4(N){if(!N.length)return 0;try{let $=await A4.deleteFrom("customers").where("id","in",N).executeTakeFirst();return F($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as O4}from"@stacksjs/database";async function p0(N){return await O4.selectFrom("customers").where("id","=",N).selectAll().executeTakeFirst()}async function S4(){return await O4.selectFrom("customers").selectAll().execute()}import{db as O3}from"@stacksjs/database";import{HttpError as T4}from"@stacksjs/error-handling";import{isUniqueViolation as S3}from"@stacksjs/orm";async function w4(N){try{let $={...N,avatar:N.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},J=await O3.insertInto("customers").values($).executeTakeFirst();if(!J)throw Error("Failed to create customer");let G=J.insertId||Number(J.numInsertedOrUpdatedRows);return await p0(Number(G))}catch($){if($ instanceof T4)throw $;if(S3($))throw new T4(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as T3}from"@stacksjs/database";import{HttpError as U4}from"@stacksjs/error-handling";import{formatDate as w3,isUniqueViolation as U3}from"@stacksjs/orm";async function E4(N,$){try{if(!N)throw Error("Customer ID is required for update");let J=await T3.updateTable("customers").set({...$,updated_at:w3(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof U4)throw J;if(U3(J))throw new U4(409,"A customer with this email already exists");if(J instanceof Error)throw Error(`Failed to update customer: ${J.message}`);throw J}}var u$={};B(u$,{updateStatus:()=>c4,updatePrintCount:()=>n4,update:()=>l4,storePrintDevicesExport:()=>D4,store:()=>b4,getPrinterStatusCounts:()=>v4,fetchErrorsByDeviceId:()=>h4,fetchById:()=>b,fetchAll:()=>b0,exportPrintDevices:()=>m0,downloadPrintDevices:()=>y4,destroy:()=>q4,countTotalPrints:()=>j4,countPrintsByDeviceId:()=>C4,countAll:()=>k4,calculatePrinterHealth:()=>g4,calculateErrorRate:()=>I4,bulkStore:()=>m4,bulkDestroy:()=>f4});import{db as P4}from"@stacksjs/database";async function q4(N){try{let $=await P4.deleteFrom("print_devices").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function f4(N){if(!N.length)return 0;try{let $=await P4.deleteFrom("print_devices").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as E3}from"ts-spreadsheets";import{db as P}from"@stacksjs/database";async function b(N){return await P.selectFrom("print_devices").where("id","=",N).selectAll().executeTakeFirst()}async function b0(){return await P.selectFrom("print_devices").selectAll().execute()}async function k4(){let N=await P.selectFrom("print_devices").select(P.fn.count("id").as("count")).executeTakeFirst();return Number(N?.count||0)}async function j4(){let N=await P.selectFrom("print_devices").select(P.fn.sum("print_count").as("total")).executeTakeFirst();return Number(N?.total||0)}async function C4(N){return(await P.selectFrom("print_devices").select("print_count").where("id","=",N).executeTakeFirst())?.print_count??0}async function I4(){let N=await P.selectFrom("receipts").select([P.fn.count("id").as("total"),P.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!N?.total||N.total===0)return 0;return Number((N.failed_count??0)/N.total*100)}async function h4(N){return await P.selectFrom("receipts").where("print_device_id","=",N).where("status","=","failed").selectAll().execute()}async function g4(){let N=await P.selectFrom("print_devices").select([P.fn.count("id").as("total"),P.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!N?.total||N.total===0)return 0;return Number((N.online_count??0)/N.total*100)}async function v4(){return(await P.selectFrom("print_devices").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,J)=>{return $[J.status]=Number(J.count||0),$},{})}function m$(N,$,J=$){return N?.[$]??N?.[J]}function P3(N){let $=String(N||""),J=/^\d+$/.test($)?Number($):N;return new Date(J)}async function m0(N="csv"){let $=await b0(),J=q3($);return E3(J,{type:N})}function q3(N){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],J=N.map((G)=>{return[G.id,G.name,m$(G,"macAddress","mac_address"),G.location,G.terminal,G.status,P3(m$(G,"lastPing","last_ping")).toLocaleString(),m$(G,"printCount","print_count")]});return{headings:$,data:J}}async function y4(N="csv",$){let J=await m0(N),G=`print_devices_export_${new Date().toISOString().split("T")[0]}.${N}`;return J.download($||G)}async function D4(N="csv",$){let J=await m0(N),G=`print_devices_export_${new Date().toISOString().split("T")[0]}.${N}`;J.store($||G)}var{randomUUIDv7:p4}=globalThis.Bun;import{db as l$}from"@stacksjs/database";async function b4(N){try{let $=p4(),J={last_ping:0,print_count:0,...N,uuid:$};return await l$.insertInto("print_devices").values(J).executeTakeFirst(),await l$.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function m4(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={last_ping:0,print_count:0,...J,uuid:p4()};await l$.insertInto("print_devices").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${J.message}`);throw J}}import{db as c$}from"@stacksjs/database";import{formatDate as n$}from"@stacksjs/orm";async function l4(N,$){if(!await b(N))return;try{return await c$.updateTable("print_devices").set({...$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print device: ${G.message}`);throw G}}async function c4(N,$){if(!await b(N))throw Error(`Print device with ID ${N} not found`);try{return await c$.updateTable("print_devices").set({status:$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print device status: ${G.message}`);throw G}}async function n4(N,$){if(!await b(N))throw Error(`Print device with ID ${N} not found`);try{return await c$.updateTable("print_devices").set({print_count:$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print count: ${G.message}`);throw G}}var s$={};B(s$,{update:()=>r4,unresolveGroup:()=>GN,resolveGroup:()=>NN,ignoreGroup:()=>JN,fetchTimeline:()=>t4,fetchStats:()=>e4,fetchGrouped:()=>d4,fetchById:()=>s4,fetchByGroup:()=>a4,fetchAll:()=>c0,destroyGroup:()=>o4,destroy:()=>u4,bulkUpdateStatus:()=>$N,bulkDestroy:()=>i4});import{db as i$}from"@stacksjs/database";import{log as o$}from"@stacksjs/logging";async function u4(N){try{return await i$.deleteFrom("errors").where("id","=",N).execute(),!0}catch($){return o$.error("[commerce/errors] destroy failed",{id:N,error:$}),!1}}async function i4(N){try{return await i$.deleteFrom("errors").where("id","in",N).execute(),!0}catch($){return o$.error("[commerce/errors] bulkDestroy failed",{count:N.length,error:$}),!1}}async function o4(N,$){try{return await i$.deleteFrom("errors").where("type","=",N).where("message","=",$).execute(),!0}catch(J){return o$.error("[commerce/errors] destroyGroup failed",{type:N,message:$,error:J}),!1}}import{db as l0}from"@stacksjs/database";async function s4(N){return await l0.selectFrom("errors").where("id","=",N).selectAll().executeTakeFirst()}async function c0(){return await l0.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function d4(){let N=await l0.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let G of N){let X=`${G.type}:${G.message}`;if(!$.has(X))$.set(X,{errors:[],firstSeen:new Date(G.created_at),lastSeen:new Date(G.created_at)});let L=$.get(X);L.errors.push(G);let W=new Date(G.created_at);if(W<L.firstSeen)L.firstSeen=W;if(W>L.lastSeen)L.lastSeen=W}let J=[];for(let[G,X]of $){let L=X.errors[0];if(!L)continue;let W=X.errors.find((Z)=>Z.status!==null)?.status,Y="unresolved";if(W===1)Y="resolved";else if(W===2)Y="ignored";J.push({id:L.id,type:L.type,message:L.message,stack:L.stack,status:Y,count:X.errors.length,first_seen:X.firstSeen.toISOString(),last_seen:X.lastSeen.toISOString(),error_ids:X.errors.map((Z)=>Z.id)})}return J.sort((G,X)=>new Date(X.last_seen).getTime()-new Date(G.last_seen).getTime()),J}async function a4(N,$){return await l0.selectFrom("errors").where("type","=",N).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function e4(){let N=await c0(),$=new Date,J=new Date($.getTime()-86400000),G=new Date($.getTime()-172800000),X=N.filter((Y)=>new Date(Y.created_at)>=J).length,L=N.filter((Y)=>{let Z=new Date(Y.created_at);return Z>=G&&Z<J}).length,W=L===0?X>0?100:0:Math.round((X-L)/L*100);return{total:N.length,unresolved:N.filter((Y)=>Y.status===null||Y.status===0).length,resolved:N.filter((Y)=>Y.status===1).length,ignored:N.filter((Y)=>Y.status===2).length,last_24h:X,trend:W}}async function t4(){let N=await c0(),$=new Date,J=[];for(let G=23;G>=0;G--){let X=new Date($.getTime()-G*60*60*1000);X.setMinutes(0,0,0);let L=new Date(X.getTime()+3600000),W=N.filter((Y)=>{let Z=new Date(Y.created_at);return Z>=X&&Z<L}).length;J.push({hour:X.toISOString(),count:W})}return J}import{db as x0}from"@stacksjs/database";import{sql as H0}from"@stacksjs/database";import{log as V0}from"@stacksjs/logging";async function r4(N,$){try{return await x0.updateTable("errors").set({...$,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("id","=",N).execute(),!0}catch(J){return V0.error("[commerce/errors] update failed",{id:N,error:J}),!1}}async function $N(N,$){try{return await x0.updateTable("errors").set({status:$,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("id","in",N).execute(),!0}catch(J){return V0.error("[commerce/errors] bulkUpdateStatus failed",{count:N.length,status:$,error:J}),!1}}async function NN(N,$){try{return await x0.updateTable("errors").set({status:1,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] resolveGroup failed",{type:N,message:$,error:J}),!1}}async function JN(N,$){try{return await x0.updateTable("errors").set({status:2,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] ignoreGroup failed",{type:N,message:$,error:J}),!1}}async function GN(N,$){try{return await x0.updateTable("errors").set({status:0,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] unresolveGroup failed",{type:N,message:$,error:J}),!1}}var a$={};B(a$,{updateBalance:()=>SN,update:()=>ON,store:()=>BN,fetchTotalValue:()=>FN,fetchTotalCurrentBalance:()=>KN,fetchStats:()=>WN,fetchById:()=>a,fetchByCode:()=>d$,fetchAll:()=>XN,fetchActive:()=>LN,destroy:()=>xN,compareActiveGiftCards:()=>ZN,checkBalance:()=>YN,calculateGiftCardValues:()=>MN,bulkDestroy:()=>HN});import{db as QN}from"@stacksjs/database";import{formatDate as NL}from"@stacksjs/orm";import{db as T,sql as j}from"@stacksjs/database";import{formatDate as u,toTimestamp as G0}from"@stacksjs/orm";import{aggregateFunctions as f3,db as k3}from"@stacksjs/database";async function I(N,$,J){let G=k3.selectFrom(N);if(J)G=J(G);G=G.select(Object.entries($).map(([W,Y])=>{let Z=Y.column??"id",M=f3[Y.kind](Z);if(Y.filter)M=M.filterWhere(Y.filter.column,Y.filter.op,Y.filter.value);return M.as(W)}));let X=await G.executeTakeFirst(),L={};for(let W of Object.keys($)){let Y=X?.[W];L[W]=typeof Y==="number"?Y:Number(Y??0)||0}return L}async function XN(){return await T.selectFrom("gift_cards").selectAll().execute()}async function a(N){return await T.selectFrom("gift_cards").where("id","=",N).selectAll().executeTakeFirst()}async function d$(N){return await T.selectFrom("gift_cards").where("code","=",N).selectAll().executeTakeFirst()}async function LN(){return await T.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function WN(){let{count:N}=await I("gift_cards",{count:{kind:"count"}}),$=G0(new Date),J=await T.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal($)} OR expiry_date IS NULL)`).select(T.fn.count("id").as("count")).executeTakeFirst(),G=await T.selectFrom("gift_cards").select(["status",T.fn.count("id").as("count")]).groupBy("status").execute(),{count:X}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance < 0.25`)),{count:L}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:W}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance > 0.75`)),Y=new Date;Y.setDate(Y.getDate()+30);let Z=await T.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",G0(Y)).where("expiry_date",">=",$).selectAll().limit(5).execute(),M=await T.selectFrom("gift_cards").where("last_used_date","is not",null).selectAll().limit(5).execute();return{total:N,active:Number(J?.count||0),by_status:G.map((K)=>({status:K.status,count:Number(K.count)})),by_balance:{low:X,medium:L,high:W},expiring_soon:Z,recently_used:M}}async function YN(N){let $=await d$(N);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function ZN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await T.selectFrom("gift_cards").select(T.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0($))} OR expiry_date IS NULL)`).where("created_at",">=",u(J)).where("created_at","<=",u($)).executeTakeFirst(),W=await T.selectFrom("gift_cards").select(T.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0(X))} OR expiry_date IS NULL)`).where("created_at",">=",u(X)).where("created_at","<=",u(G)).executeTakeFirst(),Y=Number(L?.count||0),Z=Number(W?.count||0),M=Y-Z,K=Z!==0?M/Z*100:Y>0?100:0;return{current_period:Y,previous_period:Z,difference:M,percentage_change:K,days_range:N}}async function MN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await T.selectFrom("gift_cards").select([T.fn.sum("initial_balance").as("total_initial"),T.fn.sum("current_balance").as("total_balance"),T.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0($))} OR expiry_date IS NULL)`).where("created_at",">=",u(J)).where("created_at","<=",u($)).executeTakeFirst(),W=await T.selectFrom("gift_cards").select([T.fn.sum("initial_balance").as("total_initial"),T.fn.sum("current_balance").as("total_balance"),T.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0(X))} OR expiry_date IS NULL)`).where("created_at",">=",u(X)).where("created_at","<=",u(G)).executeTakeFirst(),Y=Number(L?.total_initial||0),Z=Number(L?.total_balance||0),M=Number(L?.card_count||0),K=Number(W?.total_initial||0),Q=Number(W?.total_balance||0),x=Number(W?.card_count||0),R=Y>0?(Y-Z)/Y*100:0,O=K>0?(K-Q)/K*100:0,_=M>0?Y/M:0,S=M>0?Z/M:0,D=Y-K,o=Z-Q,s=M-x,J0=K!==0?D/K*100:Y>0?100:0,p=Q!==0?o/Q*100:Z>0?100:0,Q3=x!==0?s/x*100:M>0?100:0;return{current_period:{total_initial_value:Y,total_remaining_balance:Z,utilization_rate:R,card_count:M,average_initial_value:_,average_remaining_balance:S},previous_period:{total_initial_value:K,total_remaining_balance:Q,utilization_rate:O,card_count:x},comparison:{initial_value:{difference:D,percentage:Math.abs(J0),is_increase:D>=0},balance:{difference:o,percentage:Math.abs(p),is_increase:o>=0},card_count:{difference:s,percentage:Math.abs(Q3),is_increase:s>=0}},days_range:N}}async function FN(){let{total_value:N}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:N}}async function KN(){let{total_balance:N}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:N}}async function xN(N){let $=await QN.deleteFrom("gift_cards").where("id","=",N).executeTakeFirst();return F($)>0}async function HN(N){if(!N.length)return 0;let $=await QN.deleteFrom("gift_cards").where("id","in",N).executeTakeFirst();return F($)}var{randomUUIDv7:j3}=globalThis.Bun;import{db as VN}from"@stacksjs/database";import{HttpError as zN}from"@stacksjs/error-handling";import{isUniqueViolation as C3}from"@stacksjs/orm";async function BN(N){let $=N,J={...N,current_balance:$.current_balance??$.initial_balance,status:N.status||"ACTIVE",is_active:$.is_active??!0,uuid:j3()};try{let G=await VN.insertInto("gift_cards").values(J).executeTakeFirst(),X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows);if(X)return await VN.selectFrom("gift_cards").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof zN)throw G;if(C3(G))throw new zN(409,"A gift card with this code already exists");if(G instanceof Error)throw Error(`Failed to create gift card: ${G.message}`);throw G}}import{db as RN}from"@stacksjs/database";import{HttpError as AN}from"@stacksjs/error-handling";import{formatDate as _N,isUniqueViolation as I3}from"@stacksjs/orm";async function ON(N,$){if(!await a(N))return;try{return await RN.updateTable("gift_cards").set({...$,updated_at:_N(new Date)}).where("id","=",N).execute(),await a(N)}catch(G){if(G instanceof AN)throw G;if(I3(G))throw new AN(409,"A gift card with this code already exists");if(G instanceof Error)throw Error(`Failed to update gift card: ${G.message}`);throw G}}async function SN(N,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let J=_N(new Date),G=await RN.unsafe(`UPDATE gift_cards
|
|
8
|
+
AND (end_date IS NULL OR end_date >= ?)`,[$,N,$,$]),G=typeof J?.execute==="function"?await J.execute():J;if(Number(G?.changes??G?.numUpdatedRows??G?.affectedRows??0)>0){let Z=await d(N);if(Z)return{ok:!0,coupon:Z};return{ok:!1,reason:"not-found"}}let L=await d(N);if(!L)return{ok:!1,reason:"not-found"};if(!L.isActive)return{ok:!1,reason:"inactive"};let W=!L.startDate||L.startDate<=$,Y=!L.endDate||L.endDate>=$;if(!W||!Y)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var b$={};B(b$,{update:()=>E4,store:()=>w4,fetchById:()=>p0,fetchAll:()=>S4,destroy:()=>R4,bulkDestroy:()=>_4});import{db as A4}from"@stacksjs/database";async function R4(N){try{let $=await A4.deleteFrom("customers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function _4(N){if(!N.length)return 0;try{let $=await A4.deleteFrom("customers").where("id","in",N).executeTakeFirst();return F($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as O4}from"@stacksjs/database";async function p0(N){return await O4.selectFrom("customers").where("id","=",N).selectAll().executeTakeFirst()}async function S4(){return await O4.selectFrom("customers").selectAll().execute()}import{db as O3}from"@stacksjs/database";import{HttpError as T4}from"@stacksjs/error-handling";import{isUniqueViolation as S3}from"@stacksjs/orm";async function w4(N){try{let $={...N,avatar:N.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},J=await O3.insertInto("customers").values($).executeTakeFirst();if(!J)throw Error("Failed to create customer");let G=J.insertId||Number(J.numInsertedOrUpdatedRows);return await p0(Number(G))}catch($){if($ instanceof T4)throw $;if(S3($))throw new T4(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as T3}from"@stacksjs/database";import{HttpError as U4}from"@stacksjs/error-handling";import{formatDate as w3,isUniqueViolation as U3}from"@stacksjs/orm";async function E4(N,$){try{if(!N)throw Error("Customer ID is required for update");let J=await T3.updateTable("customers").set({...$,updated_at:w3(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof U4)throw J;if(U3(J))throw new U4(409,"A customer with this email already exists");if(J instanceof Error)throw Error(`Failed to update customer: ${J.message}`);throw J}}var u$={};B(u$,{updateStatus:()=>c4,updatePrintCount:()=>n4,update:()=>l4,storePrintDevicesExport:()=>D4,store:()=>b4,getPrinterStatusCounts:()=>v4,fetchErrorsByDeviceId:()=>h4,fetchById:()=>b,fetchAll:()=>b0,exportPrintDevices:()=>m0,downloadPrintDevices:()=>y4,destroy:()=>q4,countTotalPrints:()=>j4,countPrintsByDeviceId:()=>C4,countAll:()=>k4,calculatePrinterHealth:()=>g4,calculateErrorRate:()=>I4,bulkStore:()=>m4,bulkDestroy:()=>f4});import{db as P4}from"@stacksjs/database";async function q4(N){try{let $=await P4.deleteFrom("print_devices").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function f4(N){if(!N.length)return 0;try{let $=await P4.deleteFrom("print_devices").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as E3}from"ts-spreadsheets";import{db as P}from"@stacksjs/database";async function b(N){return await P.selectFrom("print_devices").where("id","=",N).selectAll().executeTakeFirst()}async function b0(){return await P.selectFrom("print_devices").selectAll().execute()}async function k4(){let N=await P.selectFrom("print_devices").select(P.fn.count("id").as("count")).executeTakeFirst();return Number(N?.count||0)}async function j4(){let N=await P.selectFrom("print_devices").select(P.fn.sum("print_count").as("total")).executeTakeFirst();return Number(N?.total||0)}async function C4(N){return(await P.selectFrom("print_devices").select("print_count").where("id","=",N).executeTakeFirst())?.print_count??0}async function I4(){let N=await P.selectFrom("receipts").select([P.fn.count("id").as("total"),P.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!N?.total||N.total===0)return 0;return Number((N.failed_count??0)/N.total*100)}async function h4(N){return await P.selectFrom("receipts").where("print_device_id","=",N).where("status","=","failed").selectAll().execute()}async function g4(){let N=await P.selectFrom("print_devices").select([P.fn.count("id").as("total"),P.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!N?.total||N.total===0)return 0;return Number((N.online_count??0)/N.total*100)}async function v4(){return(await P.selectFrom("print_devices").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,J)=>{return $[J.status]=Number(J.count||0),$},{})}function m$(N,$,J=$){return N?.[$]??N?.[J]}function P3(N){let $=String(N||""),J=/^\d+$/.test($)?Number($):N;return new Date(J)}async function m0(N="csv"){let $=await b0(),J=q3($);return E3(J,{type:N})}function q3(N){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],J=N.map((G)=>{return[G.id,G.name,m$(G,"macAddress","mac_address"),G.location,G.terminal,G.status,P3(m$(G,"lastPing","last_ping")).toLocaleString(),m$(G,"printCount","print_count")]});return{headings:$,data:J}}async function y4(N="csv",$){let J=await m0(N),G=`print_devices_export_${new Date().toISOString().split("T")[0]}.${N}`;return J.download($||G)}async function D4(N="csv",$){let J=await m0(N),G=`print_devices_export_${new Date().toISOString().split("T")[0]}.${N}`;J.store($||G)}var{randomUUIDv7:p4}=globalThis.Bun;import{db as l$}from"@stacksjs/database";async function b4(N){try{let $=p4(),J={last_ping:0,print_count:0,...N,uuid:$};return await l$.insertInto("print_devices").values(J).executeTakeFirst(),await l$.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function m4(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={last_ping:0,print_count:0,...J,uuid:p4()};await l$.insertInto("print_devices").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${J.message}`);throw J}}import{db as c$}from"@stacksjs/database";import{formatDate as n$}from"@stacksjs/orm";async function l4(N,$){if(!await b(N))return;try{return await c$.updateTable("print_devices").set({...$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print device: ${G.message}`);throw G}}async function c4(N,$){if(!await b(N))throw Error(`Print device with ID ${N} not found`);try{return await c$.updateTable("print_devices").set({status:$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print device status: ${G.message}`);throw G}}async function n4(N,$){if(!await b(N))throw Error(`Print device with ID ${N} not found`);try{return await c$.updateTable("print_devices").set({print_count:$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print count: ${G.message}`);throw G}}var s$={};B(s$,{update:()=>r4,unresolveGroup:()=>GN,resolveGroup:()=>NN,ignoreGroup:()=>JN,fetchTimeline:()=>t4,fetchStats:()=>e4,fetchGrouped:()=>d4,fetchById:()=>s4,fetchByGroup:()=>a4,fetchAll:()=>c0,destroyGroup:()=>o4,destroy:()=>u4,bulkUpdateStatus:()=>$N,bulkDestroy:()=>i4});import{db as i$}from"@stacksjs/database";import{log as o$}from"@stacksjs/logging";async function u4(N){try{return await i$.deleteFrom("errors").where("id","=",N).execute(),!0}catch($){return o$.error("[commerce/errors] destroy failed",{id:N,error:$}),!1}}async function i4(N){try{return await i$.deleteFrom("errors").where("id","in",N).execute(),!0}catch($){return o$.error("[commerce/errors] bulkDestroy failed",{count:N.length,error:$}),!1}}async function o4(N,$){try{return await i$.deleteFrom("errors").where("type","=",N).where("message","=",$).execute(),!0}catch(J){return o$.error("[commerce/errors] destroyGroup failed",{type:N,message:$,error:J}),!1}}import{db as l0}from"@stacksjs/database";async function s4(N){return await l0.selectFrom("errors").where("id","=",N).selectAll().executeTakeFirst()}async function c0(){return await l0.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function d4(){let N=await l0.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let G of N){let X=`${G.type}:${G.message}`;if(!$.has(X))$.set(X,{errors:[],firstSeen:new Date(G.created_at),lastSeen:new Date(G.created_at)});let L=$.get(X);L.errors.push(G);let W=new Date(G.created_at);if(W<L.firstSeen)L.firstSeen=W;if(W>L.lastSeen)L.lastSeen=W}let J=[];for(let[G,X]of $){let L=X.errors[0];if(!L)continue;let W=X.errors.find((Z)=>Z.status!==null)?.status,Y="unresolved";if(W===1)Y="resolved";else if(W===2)Y="ignored";J.push({id:L.id,type:L.type,message:L.message,stack:L.stack,status:Y,count:X.errors.length,first_seen:X.firstSeen.toISOString(),last_seen:X.lastSeen.toISOString(),error_ids:X.errors.map((Z)=>Z.id)})}return J.sort((G,X)=>new Date(X.last_seen).getTime()-new Date(G.last_seen).getTime()),J}async function a4(N,$){return await l0.selectFrom("errors").where("type","=",N).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function e4(){let N=await c0(),$=new Date,J=new Date($.getTime()-86400000),G=new Date($.getTime()-172800000),X=N.filter((Y)=>new Date(Y.created_at)>=J).length,L=N.filter((Y)=>{let Z=new Date(Y.created_at);return Z>=G&&Z<J}).length,W=L===0?X>0?100:0:Math.round((X-L)/L*100);return{total:N.length,unresolved:N.filter((Y)=>Y.status===null||Y.status===0).length,resolved:N.filter((Y)=>Y.status===1).length,ignored:N.filter((Y)=>Y.status===2).length,last_24h:X,trend:W}}async function t4(){let N=await c0(),$=new Date,J=[];for(let G=23;G>=0;G--){let X=new Date($.getTime()-G*60*60*1000);X.setMinutes(0,0,0);let L=new Date(X.getTime()+3600000),W=N.filter((Y)=>{let Z=new Date(Y.created_at);return Z>=X&&Z<L}).length;J.push({hour:X.toISOString(),count:W})}return J}import{db as x0}from"@stacksjs/database";import{sql as H0}from"@stacksjs/database";import{log as V0}from"@stacksjs/logging";async function r4(N,$){try{return await x0.updateTable("errors").set({...$,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("id","=",N).execute(),!0}catch(J){return V0.error("[commerce/errors] update failed",{id:N,error:J}),!1}}async function $N(N,$){try{return await x0.updateTable("errors").set({status:$,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("id","in",N).execute(),!0}catch(J){return V0.error("[commerce/errors] bulkUpdateStatus failed",{count:N.length,status:$,error:J}),!1}}async function NN(N,$){try{return await x0.updateTable("errors").set({status:1,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] resolveGroup failed",{type:N,message:$,error:J}),!1}}async function JN(N,$){try{return await x0.updateTable("errors").set({status:2,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] ignoreGroup failed",{type:N,message:$,error:J}),!1}}async function GN(N,$){try{return await x0.updateTable("errors").set({status:0,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] unresolveGroup failed",{type:N,message:$,error:J}),!1}}var a$={};B(a$,{updateBalance:()=>SN,update:()=>ON,store:()=>BN,fetchTotalValue:()=>FN,fetchTotalCurrentBalance:()=>KN,fetchStats:()=>WN,fetchById:()=>a,fetchByCode:()=>d$,fetchAll:()=>XN,fetchActive:()=>LN,destroy:()=>xN,compareActiveGiftCards:()=>ZN,checkBalance:()=>YN,calculateGiftCardValues:()=>MN,bulkDestroy:()=>HN});import{db as QN}from"@stacksjs/database";import{formatDate as NL}from"@stacksjs/orm";import{db as T,sql as j}from"@stacksjs/database";import{formatDate as u,toTimestamp as G0}from"@stacksjs/orm";import{aggregateFunctions as f3,db as k3}from"@stacksjs/database";async function I(N,$,J){let G=k3.selectFrom(N);if(J)G=J(G);G=G.select(Object.entries($).map(([W,Y])=>{let Z=Y.column??"id",M=f3[Y.kind](Z);if(Y.filter)M=M.filterWhere(Y.filter.column,Y.filter.op,Y.filter.value);return M.as(W)}));let X=await G.executeTakeFirst(),L={};for(let W of Object.keys($)){let Y=X?.[W];L[W]=typeof Y==="number"?Y:Number(Y??0)||0}return L}async function XN(){return await T.selectFrom("gift_cards").selectAll().execute()}async function a(N){return await T.selectFrom("gift_cards").where("id","=",N).selectAll().executeTakeFirst()}async function d$(N){return await T.selectFrom("gift_cards").where("code","=",N).selectAll().executeTakeFirst()}async function LN(){return await T.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function WN(){let{count:N}=await I("gift_cards",{count:{kind:"count"}}),$=G0(new Date),J=await T.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal($)} OR expiry_date IS NULL)`).select(T.fn.count("id").as("count")).executeTakeFirst(),G=await T.selectFrom("gift_cards").select(["status",T.fn.count("id").as("count")]).groupBy("status").execute(),{count:X}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance < 0.25`)),{count:L}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:W}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance > 0.75`)),Y=new Date;Y.setDate(Y.getDate()+30);let Z=await T.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",G0(Y)).where("expiry_date",">=",$).selectAll().limit(5).execute(),M=await T.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:N,active:Number(J?.count||0),by_status:G.map((K)=>({status:K.status,count:Number(K.count)})),by_balance:{low:X,medium:L,high:W},expiring_soon:Z,recently_used:M}}async function YN(N){let $=await d$(N);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function ZN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await T.selectFrom("gift_cards").select(T.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0($))} OR expiry_date IS NULL)`).where("created_at",">=",u(J)).where("created_at","<=",u($)).executeTakeFirst(),W=await T.selectFrom("gift_cards").select(T.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0(X))} OR expiry_date IS NULL)`).where("created_at",">=",u(X)).where("created_at","<=",u(G)).executeTakeFirst(),Y=Number(L?.count||0),Z=Number(W?.count||0),M=Y-Z,K=Z!==0?M/Z*100:Y>0?100:0;return{current_period:Y,previous_period:Z,difference:M,percentage_change:K,days_range:N}}async function MN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await T.selectFrom("gift_cards").select([T.fn.sum("initial_balance").as("total_initial"),T.fn.sum("current_balance").as("total_balance"),T.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0($))} OR expiry_date IS NULL)`).where("created_at",">=",u(J)).where("created_at","<=",u($)).executeTakeFirst(),W=await T.selectFrom("gift_cards").select([T.fn.sum("initial_balance").as("total_initial"),T.fn.sum("current_balance").as("total_balance"),T.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0(X))} OR expiry_date IS NULL)`).where("created_at",">=",u(X)).where("created_at","<=",u(G)).executeTakeFirst(),Y=Number(L?.total_initial||0),Z=Number(L?.total_balance||0),M=Number(L?.card_count||0),K=Number(W?.total_initial||0),Q=Number(W?.total_balance||0),x=Number(W?.card_count||0),R=Y>0?(Y-Z)/Y*100:0,O=K>0?(K-Q)/K*100:0,_=M>0?Y/M:0,S=M>0?Z/M:0,D=Y-K,o=Z-Q,s=M-x,J0=K!==0?D/K*100:Y>0?100:0,p=Q!==0?o/Q*100:Z>0?100:0,Q3=x!==0?s/x*100:M>0?100:0;return{current_period:{total_initial_value:Y,total_remaining_balance:Z,utilization_rate:R,card_count:M,average_initial_value:_,average_remaining_balance:S},previous_period:{total_initial_value:K,total_remaining_balance:Q,utilization_rate:O,card_count:x},comparison:{initial_value:{difference:D,percentage:Math.abs(J0),is_increase:D>=0},balance:{difference:o,percentage:Math.abs(p),is_increase:o>=0},card_count:{difference:s,percentage:Math.abs(Q3),is_increase:s>=0}},days_range:N}}async function FN(){let{total_value:N}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:N}}async function KN(){let{total_balance:N}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:N}}async function xN(N){let $=await QN.deleteFrom("gift_cards").where("id","=",N).executeTakeFirst();return F($)>0}async function HN(N){if(!N.length)return 0;let $=await QN.deleteFrom("gift_cards").where("id","in",N).executeTakeFirst();return F($)}var{randomUUIDv7:j3}=globalThis.Bun;import{db as VN}from"@stacksjs/database";import{HttpError as zN}from"@stacksjs/error-handling";import{isUniqueViolation as C3}from"@stacksjs/orm";async function BN(N){let $=N,J={...N,current_balance:$.current_balance??$.initial_balance,status:N.status||"ACTIVE",is_active:$.is_active??!0,uuid:j3()};try{let G=await VN.insertInto("gift_cards").values(J).executeTakeFirst(),X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows);if(X)return await VN.selectFrom("gift_cards").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof zN)throw G;if(C3(G))throw new zN(409,"A gift card with this code already exists");if(G instanceof Error)throw Error(`Failed to create gift card: ${G.message}`);throw G}}import{db as RN}from"@stacksjs/database";import{HttpError as AN}from"@stacksjs/error-handling";import{formatDate as _N,isUniqueViolation as I3}from"@stacksjs/orm";async function ON(N,$){if(!await a(N))return;try{return await RN.updateTable("gift_cards").set({...$,updated_at:_N(new Date)}).where("id","=",N).execute(),await a(N)}catch(G){if(G instanceof AN)throw G;if(I3(G))throw new AN(409,"A gift card with this code already exists");if(G instanceof Error)throw Error(`Failed to update gift card: ${G.message}`);throw G}}async function SN(N,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let J=_N(new Date),G=await RN.unsafe(`UPDATE gift_cards
|
|
9
9
|
SET current_balance = current_balance + ?,
|
|
10
10
|
last_used_date = ?,
|
|
11
11
|
status = CASE WHEN current_balance + ? = 0 THEN 'USED' ELSE 'ACTIVE' END,
|
|
@@ -24,4 +24,4 @@ var x3=Object.defineProperty;var H3=(N)=>N;function V3(N,$){this[N]=H3.bind(null
|
|
|
24
24
|
updated_at = ${G(3)}
|
|
25
25
|
WHERE id = ${G(4)}
|
|
26
26
|
AND status IN ('completed', 'succeeded', 'partiallyRefunded')
|
|
27
|
-
AND COALESCE(refund_amount, 0) + ${G(5)} <= amount`,[$,$,X,N,$]),W=typeof L?.execute==="function"?await L.execute():L;if(Number(W?.numUpdatedRows??W?.[0]?.numUpdatedRows??W?.numAffectedRows??W?.affectedRows??W?.[0]?.affectedRows??W?.changes??0)>0){let x=await t(N);if(x)return x;throw Error(`Payment with ID ${N} disappeared during refund`)}let Z=await t(N);if(!Z)throw Error(`Payment with ID ${N} not found`);let M=String(Z.status||"");if(!a3.has(M))throw Error(`Payment status ${M||"unknown"} cannot be refunded`);let K=Z,Q=Number(Z.amount||0)-Number(K.refundAmount??K.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${Q} minor units`)}var V1={};B(V1,{variants:()=>Z$,units:()=>Y$,reviews:()=>X$,manufacturers:()=>G$,items:()=>J$,default:()=>YX,categories:()=>N$});var N$={};B(N$,{updateParent:()=>C2,updateDisplayOrder:()=>k2,updateActiveStatus:()=>j2,update:()=>f2,store:()=>F1,removeChildCategories:()=>w2,remove:()=>S2,findOrCreateByName:()=>q2,fetchStats:()=>R2,fetchRootCategories:()=>z2,fetchChildCategories:()=>B2,fetchCategoryTree:()=>O2,fetchByName:()=>H2,fetchById:()=>f,fetchByDisplayOrder:()=>A2,fetchAll:()=>M1,fetchActive:()=>V2,deactivateChildCategories:()=>E2,deactivate:()=>U2,compareCategoryGrowth:()=>_2,bulkRemove:()=>T2});import{db as W0}from"@stacksjs/database";import{db as w}from"@stacksjs/database";import{formatDate as A0}from"@stacksjs/orm";async function M1(){return await w.selectFrom("categories").selectAll().execute()}async function f(N){return await w.selectFrom("categories").where("id","=",N).selectAll().executeTakeFirst()}async function H2(N){return await w.selectFrom("categories").where("name","=",N).selectAll().executeTakeFirst()}async function V2(){return await w.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function z2(){return await w.selectFrom("categories").where("parent_category_id","is",null).where("is_active","=",!0).selectAll().execute()}async function B2(N){return await w.selectFrom("categories").where("parent_category_id","=",N).where("is_active","=",!0).selectAll().execute()}async function A2(N=!0){let $=w.selectFrom("categories").where("is_active","=",!0).selectAll();if(N)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function R2(){let N=await w.selectFrom("categories").select(w.fn.count("id").as("count")).executeTakeFirst(),$=await w.selectFrom("categories").where("is_active","=",!0).select(w.fn.count("id").as("count")).executeTakeFirst(),J=await w.selectFrom("categories").where("parent_category_id","is",null).select(w.fn.count("id").as("count")).executeTakeFirst(),G=await w.selectFrom("categories").where("image_url","is not",null).select(w.fn.count("id").as("count")).executeTakeFirst(),X=new Date;X.setDate(X.getDate()-30);let L=A0(X),W=await w.selectFrom("categories").where("created_at",">=",L).selectAll().limit(5).execute(),Y=await w.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").where("c.parent_category_id","is not",null).select(["c.parent_category_id","parent.name as parent_name",w.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(N?.count||0),active:Number($?.count||0),root_categories:Number(J?.count||0),child_categories:Number(N?.count||0)-Number(J?.count||0),with_images:Number(G?.count||0),recently_added:W,top_parent_categories:Y.map((Z)=>({id:String(Z.parent_category_id||""),name:String(Z.parent_name||""),child_count:Number(Z.child_count)}))}}async function _2(N=30){let $=new Date,J=A0($),G=new Date;G.setDate($.getDate()-N);let X=A0(G),L=new Date(G);L.setDate(L.getDate()-1);let W=A0(L),Y=new Date(L);Y.setDate(L.getDate()-N);let Z=A0(Y),M=await w.selectFrom("categories").select(w.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",J).executeTakeFirst(),K=await w.selectFrom("categories").select(w.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",W).executeTakeFirst(),Q=Number(M?.count||0),x=Number(K?.count||0),R=Q-x,O=x!==0?R/x*100:Q>0?100:0;return{current_period:Q,previous_period:x,difference:R,percentage_change:O,days_range:N}}async function O2(){let N=await M1(),$=new Map;N.forEach((X)=>{$.set(X.id,{...X,children:[]})});let J=[];N.forEach((X)=>{let L=$.get(X.id);if(X.parent_category_id){let W=$.get(X.parent_category_id);if(W)W.children.push(L)}else J.push(L)}),J.sort((X,L)=>X.display_order-L.display_order);let G=(X)=>{X.sort((L,W)=>L.display_order-W.display_order),X.forEach((L)=>{if(L.children.length>0)G(L.children)})};return G(J),J}async function S2(N){let $=await W0.deleteFrom("categories").where("id","=",N).executeTakeFirst();return F($)>0}async function T2(N){if(!N.length)return 0;let $=await W0.deleteFrom("categories").where("id","in",N).executeTakeFirst();return F($)}async function w2(N){let $=await W0.deleteFrom("categories").where("parent_category_id","=",N).executeTakeFirst();return F($)}async function U2(N){if(!await f(N))throw Error(`Category with ID ${N} not found`);return!!await W0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",N).executeTakeFirst()}async function E2(N){let $=await W0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",N).execute();return Number($.length)||0}var{randomUUIDv7:e3}=globalThis.Bun;import{db as P2}from"@stacksjs/database";import{HttpError as r0}from"@stacksjs/error-handling";import{isUniqueViolation as t3}from"@stacksjs/orm";import{slug as r3}from"@stacksjs/strings";async function F1(N){try{let $=N.parent_category_id?Number(N.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new r0(422,"Parent category ID must be a positive integer");if($&&!await f($))throw new r0(422,`Parent category with ID ${N.parent_category_id} not found`);let J={...N,uuid:e3(),is_active:N.is_active??!0,parent_category_id:N.parent_category_id||null},G=await P2.insertInto("categories").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create category");return G}catch($){if($ instanceof r0)throw $;if(t3($))throw new r0(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function q2(N){if(!N.name)throw Error("Name is required");let $=await P2.selectFrom("categories").selectAll().where("name","=",N.name).executeTakeFirst();if($)return $;let J={name:N.name,slug:r3(N.name),is_active:N.is_active??!0,display_order:0};return await F1(J)}import{db as R0}from"@stacksjs/database";import{HttpError as Y0}from"@stacksjs/error-handling";import{formatDate as $$,isUniqueViolation as $X}from"@stacksjs/orm";async function f2(N,$){if(!await f(N))return;if(Object.hasOwn($,"parent_category_id")){let G=$.parent_category_id?Number($.parent_category_id):void 0;if(G!==void 0&&(!Number.isSafeInteger(G)||G<=0))throw new Y0(422,"Parent category ID must be a positive integer");if(G===N)throw new Y0(422,"A category cannot be its own parent");if(G&&!await f(G))throw new Y0(422,`Parent category with ID ${$.parent_category_id} not found`);if(G&&await I2(N,String(G)))throw new Y0(422,"This operation would create a circular category hierarchy")}try{let G=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},X=await R0.updateTable("categories").set({...$,...G,updated_at:$$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!X)return;return X}catch(G){if(G instanceof Y0)throw G;if($X(G))throw new Y0(409,"A category with this name or slug already exists");if(G instanceof Error)throw Error(`Failed to update category: ${G.message}`);throw G}}async function k2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);try{return await R0.updateTable("categories").set({display_order:$,updated_at:$$(new Date)}).where("id","=",N).execute(),await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category display order: ${G.message}`);throw G}}async function j2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);try{return await R0.updateTable("categories").set({is_active:$,updated_at:$$(new Date)}).where("id","=",N).execute(),await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category active status: ${G.message}`);throw G}}async function C2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);if($){let G=Number($);if(G===N)throw Error("A category cannot be its own parent");if(!await f(G))throw Error(`Parent category with ID ${$} not found`);if(await I2(N,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let G={updated_at:$$(new Date)};if($===null)await R0.updateTable("categories").set({...G,parent_category_id:null}).where("id","=",N).execute();else await R0.updateTable("categories").set({...G,parent_category_id:$}).where("id","=",N).execute();return await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category parent: ${G.message}`);throw G}}async function I2(N,$){let J=Number($),G=new Set;while(J){if(G.has(J))return!0;if(J===N)return!0;G.add(J);let X=await f(J),L=X?.parent_category_id??X?.parentCategoryId;if(!X||!L)return!1;J=Number(L)}return!1}var J$={};B(J$,{updateInventory:()=>u2,updateAvailability:()=>n2,update:()=>c2,store:()=>m2,fetchTopProducts:()=>D2,fetchById:()=>l,fetchAll:()=>y2,destroy:()=>g2,bulkStore:()=>l2,bulkDestroy:()=>v2});import{db as h2}from"@stacksjs/database";async function g2(N){try{let $=await h2.deleteFrom("products").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function v2(N){if(!N.length)return 0;try{let $=await h2.deleteFrom("products").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as i,sql as NX}from"@stacksjs/database";async function l(N){let $=await i.selectFrom("products").where("id","=",N).selectAll().executeTakeFirst();if($){let J=null,G=null;if($.manufacturer_id)J=await i.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)G=await i.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:J,category:G}}return}async function y2(){let N=await i.selectFrom("products").selectAll().execute(),$=N.map((M)=>M.manufacturer_id).filter((M)=>M!==null&&M!==void 0),J=N.map((M)=>M.category_id).filter((M)=>M!==null&&M!==void 0),G=i.selectFrom("manufacturers"),X=i.selectFrom("categories");if($.length>0)G=G.where("id","in",$);if(J.length>0)X=X.where("id","in",J);let L=await G.selectAll().execute(),W=await X.selectAll().execute(),Y=L.reduce((M,K)=>{return M[K.id]=K,M},{}),Z=W.reduce((M,K)=>{return M[K.id]=K,M},{});return N.map((M)=>({...M,manufacturer:M.manufacturer_id?Y[M.manufacturer_id]:null,category:M.category_id?Z[M.category_id]:null}))}async function D2(N=5){try{return(await i.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",i.fn.sum("order_items.quantity").as("units_sold"),NX`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(N).execute()).map((J)=>({id:Number(J.id),name:String(J.name??"Unnamed product"),units_sold:Number(J.units_sold??0),revenue:Number(J.revenue??0),inventory_count:Number(J.inventory_count??0)}))}catch($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:p2}=globalThis.Bun;import{db as b2}from"@stacksjs/database";async function m2(N){try{let $={...N,uuid:p2()},J=await b2.insertInto("products").values($).executeTakeFirst();if(!J)throw Error("Failed to create product item");let G=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows),X=await l(G);if(!X)throw Error("Failed to create product item");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function l2(N){if(!N.length)return 0;let $=0;try{return await b2.transaction().execute(async(J)=>{for(let G of N){let X={...G,uuid:p2()};await J.insertInto("products").values(X).execute(),$++}}),$}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product items in bulk: ${J.message}`);throw J}}import{db as K1}from"@stacksjs/database";import{formatDate as Q1}from"@stacksjs/orm";async function c2(N,$){try{if(!N)throw Error("Product item ID is required for update");let J=await K1.updateTable("products").set({...$,updated_at:Q1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product item: ${J.message}`);throw J}}async function n2(N,$){if(!await l(N))throw Error(`Product item with ID ${N} not found`);try{return await K1.updateTable("products").set({is_available:$,updated_at:Q1(new Date)}).where("id","=",N).execute(),await l(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item availability: ${G.message}`);throw G}}async function u2(N,$){let J=await l(N);if(!J)throw Error(`Product item with ID ${N} not found`);let G={updated_at:Q1(new Date)};if($!==void 0)G.inventory_count=$;if(Object.keys(G).length===1)return J;try{return await K1.updateTable("products").set(G).where("id","=",N).execute(),await l(N)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update inventory information: ${X.message}`);throw X}}var G$={};B(G$,{updateFeaturedStatus:()=>Z7,updateByUuid:()=>M7,update:()=>Y7,store:()=>X7,fetchWithProductCount:()=>$7,fetchFeatured:()=>t2,fetchByUuid:()=>e2,fetchById:()=>a2,fetchByCountry:()=>r2,fetchAll:()=>d2,destroy:()=>o2,bulkStore:()=>L7,bulkDestroy:()=>s2});import{db as i2}from"@stacksjs/database";async function o2(N){try{let $=await i2.deleteFrom("manufacturers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function s2(N){if(!N.length)return 0;try{let $=await i2.deleteFrom("manufacturers").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as c}from"@stacksjs/database";function d2(){return c.selectFrom("manufacturers").selectAll().execute()}async function a2(N){return await c.selectFrom("manufacturers").where("id","=",N).selectAll().executeTakeFirst()}async function e2(N){return await c.selectFrom("manufacturers").where("uuid","=",N).selectAll().executeTakeFirst()}async function t2(N=10){return await c.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(N).execute()}async function r2(N,$={}){let J=$.page||1,G=$.limit||2,X=await c.selectFrom("manufacturers").select(c.fn.count("id").as("total")).where("country","=",N).executeTakeFirst(),L=Number(X?.total||0),W=await c.selectFrom("manufacturers").selectAll().where("country","=",N).limit(G).offset((J-1)*G).execute(),Y=Math.ceil(L/G);return{data:W,paging:{total_records:L,page:J,total_pages:Y},next_cursor:J<Y?J+1:null}}async function $7(N={}){let $=c.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(N.country)$=$.where("m.country","=",N.country);if(N.featured!==void 0)$=$.where("m.featured","=",N.featured);return $=$.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",c.fn.count("p.id").as("product_count")]).groupBy("m.id"),$.execute()}var{randomUUIDv7:J7}=globalThis.Bun;import{db as G7}from"@stacksjs/database";import{HttpError as N7}from"@stacksjs/error-handling";import{isUniqueViolation as JX}from"@stacksjs/orm";async function X7(N){try{let $={...N,uuid:J7(),featured:N.featured??!1},J=await G7.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create manufacturer");return J}catch($){if($ instanceof N7)throw $;if(JX($))throw new N7(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function L7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:J7(),featured:J.featured??!1};await G7.insertInto("manufacturers").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${J.message}`);throw J}}import{db as x1}from"@stacksjs/database";import{HttpError as W7}from"@stacksjs/error-handling";import{formatDate as H1,isUniqueViolation as GX}from"@stacksjs/orm";async function Y7(N,$){try{if(!N)throw Error("Manufacturer ID is required for update");let J=await x1.updateTable("manufacturers").set({...$,updated_at:H1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof W7)throw J;if(GX(J))throw new W7(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to update manufacturer: ${J.message}`);throw J}}async function Z7(N,$){try{let J=await x1.updateTable("manufacturers").set({featured:$,updated_at:H1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update manufacturer featured status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${J.message}`);throw J}}async function M7(N,$){try{let J=await x1.updateTable("manufacturers").set({...$,updated_at:H1(new Date)}).where("uuid","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update manufacturer");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update manufacturer: ${J.message}`);throw J}}var X$={};B(X$,{updateVotes:()=>T7,update:()=>S7,store:()=>R7,fetchMostHelpfulByProductId:()=>A7,fetchByUserId:()=>z7,fetchByProductId:()=>V7,fetchById:()=>x7,fetchApprovedByProductId:()=>B7,fetchAll:()=>H7,destroy:()=>K7,bulkDestroy:()=>Q7});import{db as F7}from"@stacksjs/database";async function K7(N){try{let $=await F7.deleteFrom("reviews").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function Q7(N){if(!N.length)return 0;try{let $=await F7.deleteFrom("reviews").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as Z0}from"@stacksjs/database";async function x7(N){return await Z0.selectFrom("reviews").where("id","=",N).selectAll().executeTakeFirst()}async function H7(){return await Z0.selectFrom("reviews").selectAll().execute()}async function V7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).selectAll().execute()}async function z7(N){return await Z0.selectFrom("reviews").where("customer_id","=",N).selectAll().execute()}async function B7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).where("is_approved","=",!0).selectAll().execute()}async function A7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:XX}=globalThis.Bun;import{db as LX}from"@stacksjs/database";async function R7(N){try{let $={...N,uuid:XX(),is_verified_purchase:N.is_verified_purchase??!1,is_approved:N.is_approved??!1,helpful_votes:N.helpful_votes??0,unhelpful_votes:N.unhelpful_votes??0,is_featured:N.is_featured??!1},J=await LX.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create review");return J}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${$.message}`)}throw $}}import{db as _7}from"@stacksjs/database";import{formatDate as O7}from"@stacksjs/orm";async function S7(N,$){try{if(!N)throw Error("Review ID is required for update");let J=await _7.updateTable("reviews").set({...$,updated_at:O7(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update review: ${J.message}`);throw J}}async function T7(N,$,J=!0){try{let G=$==="helpful"?"helpful_votes":"unhelpful_votes",X=J?`COALESCE("${G}", 0) + 1`:`MAX(COALESCE("${G}", 0) - 1, 0)`,L=await _7.unsafe(`UPDATE "reviews" SET "${G}" = ${X}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[O7(new Date),N]).execute(),W=Array.isArray(L)?L[0]:L;if(!W)throw Error("Failed to update review votes");return W}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review votes: ${G.message}`);throw G}}var Y$={};B(Y$,{updateDefaultStatus:()=>y7,update:()=>g7,store:()=>j7,getDefaultUnit:()=>h7,formatUnitOptions:()=>I7,fetchById:()=>q7,fetchAll:()=>f7,destroy:()=>U7,bulkUpdate:()=>v7,bulkStore:()=>C7,bulkDestroy:()=>E7});import{db as w7}from"@stacksjs/database";async function U7(N){try{let $=await w7.deleteFrom("product_units").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function E7(N){if(!N.length)return 0;try{let $=await w7.deleteFrom("product_units").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as P7}from"@stacksjs/database";async function q7(N){return await P7.selectFrom("product_units").where("id","=",N).selectAll().executeTakeFirst()}async function f7(){return await P7.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:k7}=globalThis.Bun;import{db as _0}from"@stacksjs/database";async function j7(N){try{return await _0.transaction(async($)=>{let J={...N,uuid:k7()},G=await $.insertInto("product_units").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product unit");if(J.is_default&&J.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",G.id).execute();return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function C7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:k7()},X=await _0.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(G.is_default&&G.type&&X)await _0.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product units in bulk: ${J.message}`);throw J}}function I7(N){try{let $=_0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(N)$=$.where("type","=",N);return $=$.orderBy("name"),$.execute().then((J)=>J.map((G)=>({id:String(G.id),name:G.name,abbreviation:G.abbreviation,is_default:G.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function h7(N){try{return await _0.selectFrom("product_units").selectAll().where("type","=",N).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as L$}from"@stacksjs/database";import{formatDate as W$}from"@stacksjs/orm";async function g7(N,$){try{if(!N)throw Error("Product unit ID is required for update");return await L$.transaction(async(J)=>{let G=await J.selectFrom("product_units").select(["type","is_default"]).where("id","=",N).executeTakeFirst();if(!G)return;let X=$.type??G.type;if(($.is_default??Boolean(G.is_default))&&X)await J.updateTable("product_units").set({is_default:!1,updated_at:W$(new Date)}).where("type","=",X).where("id","!=",N).execute();let W=await J.updateTable("product_units").set({...$,updated_at:W$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!W)return;return W})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product unit: ${J.message}`);throw J}}async function v7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G=J;if(!G.id)continue;let X=G.data&&typeof G.data==="object"?G.data:{...G};delete X.id;let L=await L$.updateTable("product_units").set({...X,updated_at:W$(new Date)}).where("id","=",G.id).executeTakeFirst(),W=X;if(W.is_default===!0&&W.type)await L$.updateTable("product_units").set({is_default:!1}).where("type","=",W.type).where("id","!=",G.id).execute();if(Number(L.numUpdatedRows)>0)$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product units in bulk: ${J.message}`);throw J}}async function y7(N,$){try{return await L$.transaction(async(J)=>{let G=await J.selectFrom("product_units").select("type").where("id","=",N).executeTakeFirst();if(!G)return!1;let X=W$(new Date);if($&&G.type)await J.updateTable("product_units").set({is_default:!1,updated_at:X}).where("type","=",G.type).where("id","!=",N).execute();return await J.updateTable("product_units").set({is_default:$,updated_at:X}).where("id","=",N).execute(),!0})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product unit default status: ${J.message}`);throw J}}var Z$={};B(Z$,{update:()=>t7,store:()=>i7,generateVariantCombinations:()=>d7,formatVariantOptions:()=>s7,fetchById:()=>l7,fetchAll:()=>c7,destroy:()=>p7,bulkUpdate:()=>r7,bulkStore:()=>o7,bulkDestroy:()=>b7});import{db as D7}from"@stacksjs/database";async function p7(N){try{let $=await D7.deleteFrom("product_variants").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function b7(N){if(!N.length)return 0;try{let $=await D7.deleteFrom("product_variants").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as m7}from"@stacksjs/database";async function l7(N){return await m7.selectFrom("product_variants").where("id","=",N).selectAll().executeTakeFirst()}async function c7(){return await m7.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:n7}=globalThis.Bun;import{db as u7}from"@stacksjs/database";async function i7(N){try{let $={...N,uuid:n7()},J=await u7.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create product variant");return J}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function o7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:n7()};await u7.insertInto("product_variants").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${J.message}`);throw J}}function s7(N){if(!N||!N.length)return JSON.stringify([]);let $=N.map((J)=>J.trim()).filter(Boolean);return JSON.stringify($)}function d7(N){let $=Object.keys(N);if(!$.length)return[];function J(G,X){if(G===$.length)return[X];let L=$[G],W=N[L]??[],Y=[];for(let Z of W){let M={...X,[L]:Z};Y.push(...J(G+1,M))}return Y}return J(0,{})}import{db as a7}from"@stacksjs/database";import{formatDate as e7}from"@stacksjs/orm";async function t7(N,$){try{let J=await a7.updateTable("product_variants").set({...$,updated_at:e7(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product variant: ${J.message}`);throw J}}async function r7(N){if(!N.length)return 0;let $=0;try{for(let J of N){if(!J.id)continue;let G=await a7.updateTable("product_variants").set({...J,updated_at:e7(new Date)}).where("id","=",J.id).executeTakeFirst();if(Number(G.numUpdatedRows)>0)$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${J.message}`);throw J}}var WX={categories:N$,items:J$,manufacturers:G$,reviews:X$,units:Y$,variants:Z$},YX=WX;var O1={};B(O1,{updateStatus:()=>xJ,updatePrintJob:()=>HJ,update:()=>QJ,store:()=>FJ,fetchSuccessRate:()=>LJ,fetchPrintsPerHour:()=>ZJ,fetchPrintTimeStats:()=>YJ,fetchPrintJobStats:()=>XJ,fetchPageStats:()=>WJ,fetchById:()=>M0,fetchAll:()=>GJ,destroy:()=>NJ,bulkStore:()=>KJ,bulkDestroy:()=>JJ});import{db as $J}from"@stacksjs/database";async function NJ(N){try{let $=await $J.deleteFrom("receipts").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function JJ(N){if(!N.length)return 0;try{let $=await $J.deleteFrom("receipts").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as z1}from"@stacksjs/database";import{formatDate as ZX}from"@stacksjs/orm";function y(N){return ZX(N)}function MX(N){if(N instanceof Date)return Number.isNaN(N.getTime())?null:N;if(typeof N==="number"){let G=new Date(N<=2147483647?N*1000:N);return Number.isNaN(G.getTime())?null:G}let $=String(N||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let G=new Date(Number($)*1000);return Number.isNaN(G.getTime())?null:G}let J=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(J.getTime())?null:J}async function M0(N){return await z1.selectFrom("receipts").where("id","=",N).selectAll().executeTakeFirst()}async function GJ(){return await z1.selectFrom("receipts").selectAll().execute()}async function XJ(N,$){let J=y(N),G=y($),X=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{total:X.total,success:X.success,failed:X.failed,warning:X.warning,averageSize:Math.round(X.averageSize),averagePages:Math.round(X.averagePages),averageDuration:Math.round(X.averageDuration)}}async function LJ(N,$){let J=y(N),G=y($),X=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(W)=>W.where("timestamp",">=",J).where("timestamp","<=",G));return{successRate:X.total>0?Math.round(X.success/X.total*100):0,total:X.total,success:X.success,failed:X.failed,warning:X.warning}}async function WJ(N,$){let J=y(N),G=y($),X=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{totalPages:X.totalPages,averagePagesPerReceipt:Math.round(X.averagePagesPerReceipt),totalReceipts:X.totalReceipts}}async function YJ(N,$){let J=y(N),G=y($),X=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{averageDuration:Math.round(X.averageDuration),minDuration:X.minDuration,maxDuration:X.maxDuration,totalJobs:X.totalJobs}}async function ZJ(N,$){let J=typeof N==="number"?N:N.getTime(),G=typeof $==="number"?$:$.getTime(),X=y(N),L=y($),W=await z1.selectFrom("receipts").where("timestamp",">=",X).where("timestamp","<=",L).selectAll().execute(),Y=W.length,Z=Math.ceil((G-J)/3600000),M=Z>0?Math.round(Y/Z):0,K=Array.from({length:24},(Q,x)=>({hour:x,count:0}));return W.forEach((Q)=>{let x=MX(Q.timestamp);if(!x)return;K[x.getHours()].count++}),{totalPrints:Y,totalHours:Z,printsPerHour:M,hourlyBreakdown:K}}var{randomUUIDv7:MJ}=globalThis.Bun;import{db as A1}from"@stacksjs/database";import{formatDate as B1}from"@stacksjs/orm";function O0(N){try{if(typeof N==="number")return B1(N<=2147483647?N*1000:N);if(typeof N==="string"&&/^\d{10}$/.test(N))return B1(Number(N)*1000);return B1(N)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function FJ(N){try{let $=MJ(),J={...N,timestamp:O0(N.timestamp),uuid:$};await A1.insertInto("receipts").values(J).executeTakeFirst();let G=await A1.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create receipt");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function KJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...G,timestamp:O0(G.timestamp),uuid:MJ()})),J=await A1.insertInto("receipts").values($).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows??J.numAffectedRows??J.affectedRows??J.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as R1}from"@stacksjs/database";import{formatDate as _1}from"@stacksjs/orm";async function QJ(N,$){try{if(!N)throw Error("Receipt ID is required for update");let J={...$,...$.timestamp===void 0?{}:{timestamp:O0($.timestamp)},updated_at:_1(new Date)};await R1.updateTable("receipts").set(J).where("id","=",N).execute();let G=await M0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update receipt: ${J.message}`);throw J}}async function xJ(N,$){try{await R1.updateTable("receipts").set({status:$,updated_at:_1(new Date)}).where("id","=",N).execute();let J=await M0(N);if(!J)throw Error("Failed to update receipt status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update receipt status: ${J.message}`);throw J}}async function HJ(N,$,J,G){try{let X={updated_at:_1(new Date)};if($!==void 0)X.size=$;if(J!==void 0)X.pages=J;if(G!==void 0)X.duration=G;await R1.updateTable("receipts").set(X).where("id","=",N).execute();let L=await M0(N);if(!L)throw Error("Failed to update receipt job information");return L}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt job information: ${X.message}`);throw X}}var p1={};B(p1,{zones:()=>h$,routes:()=>H$,rates:()=>k$,methods:()=>U$,licenses:()=>O$,drivers:()=>A$,digital:()=>z$,default:()=>VX});var H$={};B(H$,{validateDeliveryRouteWrite:()=>F0,updateStops:()=>wJ,updateMetrics:()=>UJ,updateLastActive:()=>SJ,update:()=>TJ,store:()=>OJ,fetchById:()=>F$,fetchByDriver:()=>_J,fetchAll:()=>AJ,fetchActive:()=>RJ,destroy:()=>zJ,bulkDestroy:()=>BJ,DeliveryRouteInputError:()=>C});import{db as VJ}from"@stacksjs/database";async function zJ(N){try{let $=await VJ.deleteFrom("delivery_routes").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function BJ(N){if(!N.length)return 0;try{let $=await VJ.deleteFrom("delivery_routes").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as M$}from"@stacksjs/database";async function F$(N){return await M$.selectFrom("delivery_routes").where("id","=",N).selectAll().executeTakeFirst()}async function AJ(){return await M$.selectFrom("delivery_routes").selectAll().execute()}async function RJ(){return await M$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function _J(N){return await M$.selectFrom("delivery_routes").where("driver","=",N).selectAll().execute()}var{randomUUIDv7:QX}=globalThis.Bun;import{db as S1}from"@stacksjs/database";function r(N,$){let J={};for(let[G,X]of Object.entries($))for(let L of X){if(!Object.prototype.hasOwnProperty.call(N,L)||N[L]===void 0)continue;J[G]=N[L];break}return J}function S0(N){return r(N,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function n(N){return r(N,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function T0(N){return r(N,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function w0(N){return r(N,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function U0(N){return r(N,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function E0(N){return r(N,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function K$(N){return r(N,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as FX}from"@stacksjs/database";class C extends TypeError{constructor(N){super(N);this.name="DeliveryRouteInputError"}}function Q$(N,$,J){return Number(N[J]??$?.[J])}function KX(N,$){let J=N.last_active??$?.last_active;if(J instanceof Date)return J.getTime();if(typeof J==="number")return J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return Number(J);return Number.NaN}async function F0(N,$){let J=Q$(N,$,"driver_id"),G=Q$(N,$,"stops"),X=Q$(N,$,"delivery_time"),L=Q$(N,$,"total_distance"),W=KX(N,$);if(!Number.isSafeInteger(J)||J<1)throw new C("Driver must be a positive integer.");if(!Number.isSafeInteger(G)||G<0)throw new C("Stops must be a non-negative integer.");if(!Number.isSafeInteger(X)||X<0)throw new C("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(L)||L<0)throw new C("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(W)||W<0)throw new C("Last active must be a valid Unix timestamp.");let Y=await FX.selectFrom("drivers").where("id","=",J).select(["id","name","vehicle_number"]).executeTakeFirst();if(!Y)throw new C(`Driver ${J} was not found.`);return{...N,driver_id:Number(Y.id),driver:Y.name,vehicle:Y.vehicle_number}}async function OJ(N){try{let $=QX(),J=K$(N),X={...await F0(J),uuid:$};await S1.insertInto("delivery_routes").values(X).executeTakeFirst();let L=await S1.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!L)throw Error("Failed to create delivery route");return L}catch($){if($ instanceof C)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function SJ(N){try{await S1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",N).execute();let $=await F$(N);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as x$}from"@stacksjs/database";import{formatDate as T1}from"@stacksjs/orm";async function TJ(N,$){try{if(!N)throw Error("Delivery route ID is required for update");let J=await x$.selectFrom("delivery_routes").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=K$($),X=await F0(G,J),L=await x$.updateTable("delivery_routes").set({...X,updated_at:T1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!L)return;return L}catch(J){if(J instanceof C)throw J;if(J instanceof Error)throw TypeError(`Failed to update delivery route: ${J.message}`);throw J}}async function wJ(N,$){try{let J=await x$.updateTable("delivery_routes").set({stops:$,updated_at:T1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update delivery route stops");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route stops: ${J.message}`);throw J}}async function UJ(N,$,J){try{let G={updated_at:T1(new Date)};if($!==void 0)G.delivery_time=$;if(J!==void 0)G.total_distance=J;let X=await x$.updateTable("delivery_routes").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery metrics");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery metrics: ${G.message}`);throw G}}var z$={};B(z$,{updateStatus:()=>yJ,updateDeliverySettings:()=>DJ,update:()=>vJ,store:()=>hJ,softDelete:()=>PJ,fetchById:()=>jJ,fetchAll:()=>CJ,destroy:()=>EJ,bulkStore:()=>gJ,bulkSoftDelete:()=>fJ,bulkDestroy:()=>qJ});import{db as V$}from"@stacksjs/database";async function EJ(N){try{let $=await V$.deleteFrom("digital_deliveries").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function PJ(N){try{let $=await V$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function qJ(N){if(!N.length)return 0;try{let $=await V$.deleteFrom("digital_deliveries").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function fJ(N){if(!N.length)return 0;try{let $=await V$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as kJ}from"@stacksjs/database";async function jJ(N){return await kJ.selectFrom("digital_deliveries").where("id","=",N).selectAll().executeTakeFirst()}async function CJ(){return await kJ.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:IJ}=globalThis.Bun;import{db as w1}from"@stacksjs/database";async function hJ(N){try{let $=IJ(),J={...w0(N),uuid:$};await w1.insertInto("digital_deliveries").values(J).executeTakeFirst();let G=await w1.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created digital delivery");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function gJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...w0(G),uuid:IJ()})),J=await w1.insertInto("digital_deliveries").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as U1}from"@stacksjs/database";import{formatDate as E1}from"@stacksjs/orm";async function vJ(N,$){try{if(!N)throw Error("Digital delivery ID is required for update");let J=await U1.updateTable("digital_deliveries").set({...w0($),updated_at:E1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update digital delivery: ${J.message}`);throw J}}async function yJ(N,$){try{let J=await U1.updateTable("digital_deliveries").set({status:$,updated_at:E1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update digital delivery status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update digital delivery status: ${J.message}`);throw J}}async function DJ(N,$,J,G,X){try{let L={updated_at:E1(new Date)};if($!==void 0)L.download_limit=$;if(J!==void 0)L.expiry_days=J;if(G!==void 0)L.requires_login=G;if(X!==void 0)L.automatic_delivery=X;let W=await U1.updateTable("digital_deliveries").set(L).where("id","=",N).returningAll().executeTakeFirst();if(!W)throw Error("Failed to update delivery settings");return W}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery settings: ${L.message}`);throw L}}var A$={};B(A$,{updateStatus:()=>sJ,updateContact:()=>dJ,update:()=>oJ,store:()=>uJ,fetchById:()=>B$,fetchAll:()=>bJ,destroy:()=>lJ,bulkStore:()=>iJ,bulkDestroy:()=>cJ});import{db as mJ}from"@stacksjs/database";import{db as pJ}from"@stacksjs/database";async function B$(N){return await pJ.selectFrom("drivers").where("id","=",N).selectAll().executeTakeFirst()}async function bJ(){return await pJ.selectFrom("drivers").selectAll().execute()}async function lJ(N){try{let $=await mJ.deleteFrom("drivers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function cJ(N){if(!N.length)return 0;let $=0;try{return await mJ.transaction().execute(async(J)=>{for(let G of N)if(await B$(G))await J.deleteFrom("drivers").where("id","=",G).execute(),$++}),$}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${J.message}`);throw J}}var{randomUUIDv7:nJ}=globalThis.Bun;import{db as P1}from"@stacksjs/database";async function uJ(N){try{let $=nJ(),J={...E0(N),uuid:$};await P1.insertInto("drivers").values(J).executeTakeFirst();let G=await P1.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created driver");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function iJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...E0(G),uuid:nJ()})),J=await P1.insertInto("drivers").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as q1}from"@stacksjs/database";import{formatDate as f1}from"@stacksjs/orm";async function oJ(N,$){try{if(!N)throw Error("Driver ID is required for update");let J=await q1.updateTable("drivers").set({...E0($),updated_at:f1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update driver: ${J.message}`);throw J}}async function sJ(N,$){try{let J=await q1.updateTable("drivers").set({status:$,updated_at:f1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update driver status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update driver status: ${J.message}`);throw J}}async function dJ(N,$){try{let J={updated_at:f1(new Date)};if($!==void 0)J.phone=$;let G=await q1.updateTable("drivers").set(J).where("id","=",N).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update contact information");return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update contact information: ${J.message}`);throw J}}var O$={};B(O$,{validateLicenseKeyWrite:()=>$0,updateStatus:()=>M6,updateExpiration:()=>F6,update:()=>Z6,store:()=>W6,softDelete:()=>eJ,fetchById:()=>N6,fetchAll:()=>J6,destroy:()=>aJ,bulkStore:()=>Y6,bulkSoftDelete:()=>rJ,bulkDestroy:()=>tJ,LicenseKeyInputError:()=>E});import{db as R$}from"@stacksjs/database";async function aJ(N){try{let $=await R$.deleteFrom("license_keys").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function eJ(N){try{let $=await R$.updateTable("license_keys").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function tJ(N){if(!N.length)return 0;try{let $=await R$.deleteFrom("license_keys").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function rJ(N){if(!N.length)return 0;try{let $=await R$.updateTable("license_keys").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as $6}from"@stacksjs/database";async function N6(N){return await $6.selectFrom("license_keys").where("id","=",N).selectAll().executeTakeFirst()}async function J6(){return await $6.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:L6}=globalThis.Bun;import{db as C1}from"@stacksjs/database";import{db as k1}from"@stacksjs/database";var G6=["Standard License","Premium License","Enterprise License"],X6=["active","inactive","unassigned"];class E extends TypeError{constructor(N){super(N);this.name="LicenseKeyInputError"}}function P0(N,$,J){return N[J]!==void 0?N[J]:$?.[J]}function j1(N,$,J,G){let X=P0(N,$,J);if(X===void 0||X===null||X==="")return null;let L=Number(X);if(!Number.isSafeInteger(L)||L<1)throw new E(`${G} must be a positive integer or null.`);return L}function xX(N){if(typeof N==="number")return N>2147483647?Math.floor(N/1000):N;if(typeof N==="string"&&/^\d{10,13}$/.test(N))return N.length===13?Math.floor(Number(N)/1000):Number(N);if(typeof N==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(N)?`${N.replace(" ","T")}Z`:N;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function $0(N,$){let J=String(P0(N,$,"key")||"").trim().toUpperCase(),G=String(P0(N,$,"template")||""),X=String(P0(N,$,"status")||""),L=xX(P0(N,$,"expiry_date")),W=j1(N,$,"customer_id","Customer"),Y=j1(N,$,"product_id","Product"),Z=j1(N,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(J))throw new E("License key must use five groups of four uppercase letters or numbers.");if(!G6.includes(G))throw new E(`Template must be one of: ${G6.join(", ")}.`);if(!X6.includes(X))throw new E(`Status must be one of: ${X6.join(", ")}.`);if(!Number.isSafeInteger(L)||L<0||L>2147483647)throw new E("Expiry date must be a Unix timestamp between 1970 and 2038.");let[M,K,Q]=await Promise.all([W?k1.selectFrom("customers").where("id","=",W).select("id").executeTakeFirst():null,Y?k1.selectFrom("products").where("id","=",Y).select("id").executeTakeFirst():null,Z?k1.selectFrom("orders").where("id","=",Z).select(["id","customer_id"]).executeTakeFirst():null]);if(W&&!M)throw new E(`Customer ${W} was not found.`);if(Y&&!K)throw new E(`Product ${Y} was not found.`);if(Z&&!Q)throw new E(`Order ${Z} was not found.`);if(W&&Q?.customer_id&&Number(Q.customer_id)!==W)throw new E(`Order ${Z} belongs to Customer ${Q.customer_id}, not Customer ${W}.`);return{...N,key:J,template:G,expiry_date:L,status:X,customer_id:W,product_id:Y,order_id:Z}}async function W6(N){try{let $=L6(),J=U0(N),G={...await $0(J),uuid:$};await C1.insertInto("license_keys").values(G).executeTakeFirst();let X=await C1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created license key");return X}catch($){if($ instanceof E)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function Y6(N){if(!N.length)return 0;try{let $=await Promise.all(N.map(async(G)=>({...await $0(U0(G)),uuid:L6()}))),J=await C1.insertInto("license_keys").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof E)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as _$}from"@stacksjs/database";import{formatDate as I1}from"@stacksjs/orm";async function Z6(N,$){try{if(!N)throw Error("License key ID is required for update");let J=await _$.selectFrom("license_keys").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=U0($),X=await $0(G,J),L=await _$.updateTable("license_keys").set({...X,updated_at:I1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!L)return;return L}catch(J){if(J instanceof E)throw J;if(J instanceof Error){if(J.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${J.message}`)}throw J}}async function M6(N,$){try{let J=await _$.updateTable("license_keys").set({status:$,updated_at:I1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update license key status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update license key status: ${J.message}`);throw J}}async function F6(N,$){try{let J={updated_at:I1(new Date)};if($!==void 0)J.expiry_date=$;let G=await _$.updateTable("license_keys").set(J).where("id","=",N).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update expiration information");return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update expiration information: ${J.message}`);throw J}}var U$={};B(U$,{updateStatus:()=>S6,updatePricing:()=>T6,update:()=>O6,store:()=>B6,softDelete:()=>Q6,getActiveShippingMethods:()=>_6,formatShippingOptions:()=>R6,fetchById:()=>w$,fetchAll:()=>V6,destroy:()=>K6,bulkStore:()=>A6,bulkSoftDelete:()=>H6,bulkDestroy:()=>x6});import{db as S$}from"@stacksjs/database";async function K6(N){try{let $=await S$.deleteFrom("shipping_methods").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function Q6(N){try{let $=await S$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function x6(N){if(!N.length)return 0;try{let $=await S$.deleteFrom("shipping_methods").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function H6(N){if(!N.length)return 0;try{let $=await S$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as T$}from"@stacksjs/database";async function w$(N){let $=await T$.selectFrom("shipping_methods").where("id","=",N).selectAll().executeTakeFirst();if($){let J=await T$.selectFrom("shipping_zones").where("shipping_method_id","=",N).selectAll().execute();return{...$,shippingZones:J}}return}async function V6(){let N=await T$.selectFrom("shipping_methods").selectAll().execute();if(N.length===0)return[];let $=[...new Set(N.map((L)=>L.id))],X=(await T$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((L,W)=>{let Y=W.shipping_method_id;if(Y!==null&&Y!==void 0){if(!L[Y])L[Y]=[];L[Y].push(W)}return L},{});return N.map((L)=>({...L,shipping_zones:X[L.id]||[]}))}var{randomUUIDv7:z6}=globalThis.Bun;import{db as q0}from"@stacksjs/database";async function B6(N){try{let $=z6(),J={...S0(N),uuid:$};await q0.insertInto("shipping_methods").values(J).executeTakeFirst();let G=await q0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created shipping method");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function A6(N){if(!N.length)return 0;try{let $=N.map((G)=>({...S0(G),uuid:z6()})),J=await q0.insertInto("shipping_methods").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function R6(){try{return q0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping options: ${N.message}`);throw N}}async function _6(){try{return await q0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to get active shipping methods: ${N.message}`);throw N}}import{db as h1}from"@stacksjs/database";import{formatDate as g1}from"@stacksjs/orm";async function O6(N,$){try{if(!N)throw Error("Shipping method ID is required for update");let J=await h1.updateTable("shipping_methods").set({...S0($),updated_at:g1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping method: ${J.message}`);throw J}}async function S6(N,$){try{let J=await h1.updateTable("shipping_methods").set({status:$,updated_at:g1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping method status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping method status: ${J.message}`);throw J}}async function T6(N,$,J){try{let G={updated_at:g1(new Date)};if($!==void 0)G.base_rate=$;if(J!==void 0)G.free_shipping=J;let X=await h1.updateTable("shipping_methods").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update pricing information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update pricing information: ${G.message}`);throw G}}var k$={};B(k$,{validateZoneMatchesAddress:()=>I6,validateShippingRateWrite:()=>N0,updateByZone:()=>u6,updateByMethod:()=>i6,update:()=>c6,store:()=>m6,resolveZoneForAddress:()=>P$,getShippingRatesByMethod:()=>g6,getRatesByZone:()=>j6,getRateByWeightAndZone:()=>v1,getRateByWeightAndAddress:()=>C6,formatShippingRateOptions:()=>h6,fetchById:()=>f6,fetchAll:()=>k6,destroyByZone:()=>E6,destroyByMethod:()=>P6,destroy:()=>w6,bulkUpdate:()=>n6,bulkStore:()=>l6,bulkDestroy:()=>U6,ShippingRateInputError:()=>k});import{db as E$}from"@stacksjs/database";async function w6(N){try{let $=await E$.deleteFrom("shipping_rates").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function U6(N){if(!N.length)return 0;try{let $=await E$.deleteFrom("shipping_rates").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function E6(N){try{let $=await E$.deleteFrom("shipping_rates").where("shipping_zone_id","=",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function P6(N){try{let $=await E$.deleteFrom("shipping_rates").where("shipping_method_id","=",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as v}from"@stacksjs/database";async function f6(N){let $=await v.selectFrom("shipping_rates").where("id","=",N).selectAll().executeTakeFirst();if($){let J=null,G=null;if($.shipping_zone_id)J=await v.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)G=await v.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:J,shipping_method:G}}return}async function k6(){let N=await v.selectFrom("shipping_rates").selectAll().execute();if(N.length===0)return[];let $=[...new Set(N.map((Y)=>Y.shipping_zone_id).filter((Y)=>Y!==null&&Y!==void 0))],J=[...new Set(N.map((Y)=>Y.shipping_method_id).filter((Y)=>Y!==null&&Y!==void 0))],[G,X]=await Promise.all([$.length?v.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],J.length?v.selectFrom("shipping_methods").where("id","in",J).selectAll().execute():[]]),L=G.reduce((Y,Z)=>{return Y[Z.id]=Z,Y},{}),W=X.reduce((Y,Z)=>{return Y[Z.id]=Z,Y},{});return N.map((Y)=>({...Y,shipping_zone:Y.shipping_zone_id?L[Y.shipping_zone_id]:[],shipping_method:Y.shipping_method_id?W[Y.shipping_method_id]:[]}))}async function j6(N){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",N).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function v1(N,$){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",N).where("weight_to",">=",N).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${J.message}`);throw J}}async function P$(N){if(!N?.countryCode)return null;try{let $=await v.selectFrom("shipping_zones").selectAll().where("countries","like",`%${N.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let J=null;for(let G of $){let X=1;if(N.region&&G.regions&&q6(G.regions,N.region))X=2;if(N.postalCode&&G.postal_codes&&q6(G.postal_codes,N.postalCode))X=3;if(!J||X>J.score)J={id:G.id,score:X}}return J?.id??null}catch{return null}}async function C6(N,$){let J=await P$($);if(J==null)return;return v1(N,J)}async function I6(N,$){return await P$($)===N}function q6(N,$){if(!N||!$)return!1;let J=$.trim().toUpperCase();for(let G of N.split(/[,|;]/))if(G.trim().toUpperCase()===J)return!0;return!1}async function h6(){try{return(await v.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping rate options: ${N.message}`);throw N}}async function g6(N){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",N).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:b6}=globalThis.Bun;import{db as y1}from"@stacksjs/database";import{db as f0}from"@stacksjs/database";async function v6(){return await f0.selectFrom("shipping_zones").selectAll().execute()}async function q$(N){return await f0.selectFrom("shipping_zones").where("id","=",N).selectAll().executeTakeFirst()}function y6(){try{return f0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping zone options: ${N.message}`);throw N}}async function D6(){try{return await f0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to get active shipping zones: ${N.message}`);throw N}}async function p6(N){try{return await f0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${N}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class k extends TypeError{constructor(N){super(N);this.name="ShippingRateInputError"}}function k0(N,$,J){return Number(N[J]??$?.[J])}async function N0(N,$){let J=k0(N,$,"shipping_method_id"),G=k0(N,$,"shipping_zone_id"),X=k0(N,$,"weight_from"),L=k0(N,$,"weight_to"),W=k0(N,$,"rate");if(!Number.isSafeInteger(J)||J<1)throw new k("Shipping method must be a positive integer.");if(!Number.isSafeInteger(G)||G<1)throw new k("Shipping zone must be a positive integer.");if(!Number.isFinite(X)||X<0)throw new k("Weight from must be a non-negative number.");if(!Number.isFinite(L)||L<X)throw new k("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(W)||W<0)throw new k("Rate must be a non-negative integer in minor currency units.");let[Y,Z]=await Promise.all([w$(J),q$(G)]);if(!Y)throw new k(`Shipping method ${J} was not found.`);if(!Z)throw new k(`Shipping zone ${G} was not found.`);if(Number(Z.shipping_method_id)!==J)throw new k(`Shipping zone ${G} is not assigned to shipping method ${J}.`)}async function m6(N){try{let $=n(N),J=Number($.shipping_method_id),G=Number($.shipping_zone_id);await N0($);let X=b6(),L={...$,shipping_method_id:J,shipping_zone_id:G,uuid:X};await y1.insertInto("shipping_rates").values(L).executeTakeFirst();let W=await y1.selectFrom("shipping_rates").where("uuid","=",X).selectAll().executeTakeFirst();if(!W)throw Error("Failed to resolve created shipping rate");return W}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function l6(N){if(!N.length)return 0;try{for(let G of N){let X=n(G);await N0(X)}let $=N.map((G)=>({...n(G),uuid:b6()})),J=await y1.insertInto("shipping_rates").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as j0}from"@stacksjs/database";import{formatDate as f$}from"@stacksjs/orm";async function c6(N,$){try{if(!N)throw Error("Shipping rate ID is required for update");let J=await j0.selectFrom("shipping_rates").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=n($);await N0(G,J);let X=await j0.updateTable("shipping_rates").set({...G,updated_at:f$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!X)return;return X}catch(J){if(J instanceof k)throw J;if(J instanceof Error)throw TypeError(`Failed to update shipping rate: ${J.message}`);throw J}}async function n6(N){if(!N.length)return 0;try{let $=0;for(let{id:J,data:G}of N){let X=await j0.updateTable("shipping_rates").set({...n(G),updated_at:f$(new Date)}).where("id","=",J).executeTakeFirst();if(F(X)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function u6(N,$){try{let J=await j0.updateTable("shipping_rates").set({...n($),updated_at:f$(new Date)}).where("shipping_zone_id","=",N).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${J.message}`);throw J}}async function i6(N,$){try{let J=await j0.updateTable("shipping_rates").set({...n($),updated_at:f$(new Date)}).where("shipping_method_id","=",N).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${J.message}`);throw J}}var h$={};B(h$,{updateStatus:()=>NG,updateRegionsAndPostalCodes:()=>GG,updateCountries:()=>JG,update:()=>$G,store:()=>t6,softDelete:()=>s6,getZonesByCountry:()=>p6,getActiveShippingZones:()=>D6,formatZoneOptions:()=>y6,fetchById:()=>q$,fetchAll:()=>v6,destroy:()=>o6,bulkStore:()=>r6,bulkSoftDelete:()=>a6,bulkDestroy:()=>d6});import{db as j$}from"@stacksjs/database";async function o6(N){try{let $=await j$.deleteFrom("shipping_zones").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function s6(N){try{let $=await j$.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function d6(N){if(!N.length)return 0;try{let $=await j$.deleteFrom("shipping_zones").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function a6(N){if(!N.length)return 0;try{let $=await j$.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:e6}=globalThis.Bun;import{db as D1}from"@stacksjs/database";async function t6(N){try{let $=e6(),J={...T0(N),uuid:$};await D1.insertInto("shipping_zones").values(J).executeTakeFirst();let G=await D1.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created shipping zone");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function r6(N){if(!N.length)return 0;try{let $=N.map((G)=>({...T0(G),uuid:e6()})),J=await D1.insertInto("shipping_zones").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as C$}from"@stacksjs/database";import{formatDate as I$}from"@stacksjs/orm";async function $G(N,$){try{if(!N)throw Error("Shipping zone ID is required for update");let J=await C$.updateTable("shipping_zones").set({...T0($),updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone: ${J.message}`);throw J}}async function NG(N,$){try{let J=await C$.updateTable("shipping_zones").set({status:$,updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping zone status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone status: ${J.message}`);throw J}}async function JG(N,$){try{let J=await C$.updateTable("shipping_zones").set({countries:$,updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping zone countries");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${J.message}`);throw J}}async function GG(N,$,J){try{let G={updated_at:I$(new Date)};if($!==void 0)G.regions=$;if(J!==void 0)G.postal_codes=J;let X=await C$.updateTable("shipping_zones").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update regions and postal codes");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${G.message}`);throw G}}var HX={digital:z$,drivers:A$,licenses:O$,methods:U$,rates:k$,routes:H$,zones:h$},VX=HX;var b1={};B(b1,{updateStatus:()=>VG,updateRate:()=>zG,updateDefaultStatus:()=>BG,update:()=>HG,store:()=>QG,fetchById:()=>ZG,fetchAll:()=>MG,destroy:()=>LG,bulkStore:()=>xG,bulkDestroy:()=>WG});import{db as XG}from"@stacksjs/database";async function LG(N){try{let $=await XG.deleteFrom("tax_rates").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function WG(N){if(!N.length)return 0;try{let $=await XG.deleteFrom("tax_rates").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as YG}from"@stacksjs/database";async function ZG(N){return await YG.selectFrom("tax_rates").where("id","=",N).selectAll().executeTakeFirst()}async function MG(){return await YG.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:FG}=globalThis.Bun;import{db as KG}from"@stacksjs/database";async function QG(N){try{return await KG.transaction(async($)=>{let J={...N,uuid:FG()};if(J.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let G=await $.insertInto("tax_rates").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create tax rate");return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function xG(N){if(!N.length)return 0;try{return await KG.transaction(async($)=>{let J=0;for(let G of N){let X={...G,uuid:FG()};if(X.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(X).executeTakeFirst())J++}return J})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as g$}from"@stacksjs/database";import{formatDate as v$}from"@stacksjs/orm";async function HG(N,$){try{if(!N)throw Error("Tax rate ID is required for update");return await g$.transaction(async(J)=>{let G=await J.selectFrom("tax_rates").select("is_default").where("id","=",N).executeTakeFirst();if(!G)return;let X=$.is_default??Boolean(G.is_default),L=v$(new Date);if(X)await J.updateTable("tax_rates").set({is_default:!1,updated_at:L}).where("id","!=",N).execute();let W=await J.updateTable("tax_rates").set({...$,updated_at:L}).where("id","=",N).returningAll().executeTakeFirst();if(!W)return;return W})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate: ${J.message}`);throw J}}async function VG(N,$){try{let J=await g$.updateTable("tax_rates").set({status:$,updated_at:v$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update tax rate status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate status: ${J.message}`);throw J}}async function zG(N,$){try{let J=await g$.updateTable("tax_rates").set({rate:$,updated_at:v$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update rate information");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update rate information: ${J.message}`);throw J}}async function BG(N,$){try{return await g$.transaction(async(J)=>{if(!await J.selectFrom("tax_rates").select("id").where("id","=",N).executeTakeFirst())return!1;let X=v$(new Date);if($)await J.updateTable("tax_rates").set({is_default:!1,updated_at:X}).where("id","!=",N).execute();return await J.updateTable("tax_rates").set({is_default:$,updated_at:X}).where("id","=",N).execute(),!0})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate default status: ${J.message}`);throw J}}var i1={};B(i1,{restaurant:()=>Q0,products:()=>D$,default:()=>UX});var D$={};B(D$,{updateStatus:()=>yG,updatePartySize:()=>DG,update:()=>y$,store:()=>gG,fetchWaiting:()=>qG,fetchPurchasedBetweenDates:()=>EG,fetchNotifiedBetweenDates:()=>UG,fetchCountByStatus:()=>fG,fetchCountBySource:()=>OG,fetchCountByQuantity:()=>TG,fetchCountByDateGrouped:()=>CG,fetchCountByDate:()=>SG,fetchCountByAllQuantities:()=>wG,fetchCountBetweenDates:()=>jG,fetchConversionRates:()=>kG,fetchCancelledBetweenDates:()=>PG,fetchById:()=>C0,fetchAll:()=>_G,destroy:()=>AG,bulkStore:()=>vG,bulkDestroy:()=>RG});import{db as m1}from"@stacksjs/database";async function AG(N){try{let $=await m1.selectFrom("waitlist_products").where("id","=",N).selectAll().executeTakeFirst();if(!$)return;return await m1.deleteFrom("waitlist_products").where("id","=",N).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function RG(N){if(!N.length)return 0;try{let $=await m1.deleteFrom("waitlist_products").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as U}from"@stacksjs/orm";async function C0(N){return await A.selectFrom("waitlist_products").where("id","=",N).selectAll().executeTakeFirst()}async function _G(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function OG(N,$){let J=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(N&&$){let X=U(N),L=U($);J=J.where("created_at",">=",X).where("created_at","<=",L)}return(await J.execute()).reduce((X,{source:L,count:W})=>{return X[L]=W,X},{})}async function SG(N=new Date){let $=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=U($),X=U(J);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function TG(N){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",N).executeTakeFirst())?.count??0}async function wG(N,$){let J=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(N&&$){let X=U(N),L=U($);J=J.where("created_at",">=",X).where("created_at","<=",L)}return(await J.execute()).reduce((X,{quantity:L,count:W})=>{return X[L]=W,X},{})}async function UG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",J).where("notified_at","<=",G).where("notified_at","is not",null).execute()}async function EG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",J).where("purchased_at","<=",G).where("purchased_at","is not",null).execute()}async function PG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",J).where("cancelled_at","<=",G).where("cancelled_at","is not",null).execute()}async function qG(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function fG(N,$,J){let G=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",N);if($&&J){let L=U($),W=U(J);G=G.where("created_at",">=",L).where("created_at","<=",W)}return(await G.executeTakeFirst())?.count??0}async function kG(N,$){let J=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(N&&$){let Z=U(N),M=U($);J=J.where("created_at",">=",Z).where("created_at","<=",M)}let G=await J.execute(),X=G.reduce((Z,{count:M})=>Z+M,0),L=G.find((Z)=>Z.status==="purchased")?.count??0,W=X>0?L/X*100:0,Y=G.reduce((Z,{status:M,count:K})=>{return Z[M]={count:K,percentage:X>0?K/X*100:0},Z},{});return{totalConversionRate:W,statusBreakdown:Y}}async function jG(N,$){let J=U(N),G=U($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",J).where("created_at","<=",G).executeTakeFirst())?.count??0}async function CG(N,$){let J=A.selectFrom("waitlist_products").select(["created_at"]);if(N&&$){let L=U(N),W=U($);J=J.where("created_at",">=",L).where("created_at","<=",W)}let X=(await J.execute()).reduce((L,{created_at:W})=>{let Y=(W||"").split("T")[0]||"unknown";return L[Y]=(L[Y]||0)+1,L},{});return Object.entries(X).map(([L,W])=>({date:L,count:W})).sort((L,W)=>L.date.localeCompare(W.date))}var{randomUUIDv7:hG}=globalThis.Bun;import{db as l1}from"@stacksjs/database";import{formatDate as IG}from"@stacksjs/orm";var zX={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function BX(N){return typeof N==="number"||N instanceof Date?IG(N):N}function I0(N,$={}){let J=Object.fromEntries(Object.entries(N).filter(([,X])=>X!==void 0));if(J.quantity===void 0&&J.party_size!==void 0)J.quantity=J.party_size;delete J.party_size;for(let X of["notified_at","purchased_at","cancelled_at"])if(J[X]!==void 0)J[X]=BX(J[X]);let G=zX[J.status];if(G&&J[G]===void 0&&!$[G])J[G]=IG(new Date);return J}async function gG(N){try{let $=hG(),J={...I0(N),uuid:$,status:N.status||"waiting"};await l1.insertInto("waitlist_products").values(J).executeTakeFirst();let G=await l1.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create waitlist product");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function vG(N){if(!N.length)return 0;try{let $=N.map((G)=>({...I0(G),status:G.status||"waiting",uuid:hG()})),J=await l1.insertInto("waitlist_products").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as AX}from"@stacksjs/database";import{formatDate as RX}from"@stacksjs/orm";async function y$(N,$){try{if(!N)throw Error("Waitlist product ID is required for update");let J=await C0(N);if(!J)return;await AX.updateTable("waitlist_products").set({...I0($,J),updated_at:RX(new Date)}).where("id","=",N).execute();let G=await C0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update waitlist product: ${J.message}`);throw J}}async function yG(N,$){return await y$(N,{status:$})}async function DG(N,$){return await y$(N,{quantity:$})}var Q0={};B(Q0,{updateWaitTimes:()=>F3,updateStatus:()=>Z3,updateQueuePosition:()=>K3,updatePartySize:()=>M3,update:()=>K0,store:()=>W3,fetchWaitingWithQuotedTimes:()=>eG,fetchWaitingWithPartySizes:()=>tG,fetchWaiting:()=>sG,fetchTimeSeriesStats:()=>X3,fetchTablesTurnedToday:()=>rG,fetchSeatingRate:()=>$3,fetchSeatedStats:()=>G3,fetchSeatedBetweenDates:()=>oG,fetchNoShowStats:()=>N3,fetchCurrentWaitTimes:()=>J3,fetchCountByTablePreference:()=>lG,fetchCountByPartySize:()=>nG,fetchCountByDate:()=>cG,fetchCountByAllPartySizes:()=>uG,fetchConversionRates:()=>dG,fetchById:()=>h0,fetchBetweenDates:()=>iG,fetchAverageWaitTimes:()=>aG,fetchAll:()=>mG,destroy:()=>pG,bulkStore:()=>Y3,bulkDestroy:()=>bG});import{db as c1}from"@stacksjs/database";async function pG(N){try{let $=await c1.selectFrom("waitlist_restaurants").where("id","=",N).selectAll().executeTakeFirst();if(!$)return;return await c1.deleteFrom("waitlist_restaurants").where("id","=",N).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function bG(N){if(!N.length)return 0;try{let $=await c1.deleteFrom("waitlist_restaurants").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as V}from"@stacksjs/database";import{formatDate as h}from"@stacksjs/orm";async function h0(N){return await V.selectFrom("waitlist_restaurants").where("id","=",N).selectAll().executeTakeFirst()}async function mG(){return await V.selectFrom("waitlist_restaurants").selectAll().execute()}async function lG(){return(await V.selectFrom("waitlist_restaurants").select(["table_preference",V.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:J,count:G})=>{return $[J]=G,$},{})}async function cG(N=new Date){let $=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=h($),X=h(J);return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function nG(N){return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("party_size","=",N).executeTakeFirst())?.count??0}async function uG(){return(await V.selectFrom("waitlist_restaurants").select(["party_size",V.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:J,count:G})=>{return $[J]=G,$},{})}async function iG(N,$){let J=h(N),G=h($);return await V.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",J).where("created_at","<=",G).execute()}async function oG(N,$){let J=h(N),G=h($);return await V.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",J).where("check_in_time","<=",G).where("status","=","seated").execute()}async function sG(){return await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function dG(){let N=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),$=N.reduce((L,{count:W})=>L+W,0),J=N.find((L)=>L.status==="seated")?.count??0,G=$>0?Number(J)/$*100:0,X=N.reduce((L,{status:W,count:Y})=>{return L[W]={count:Y,percentage:$>0?Y/$*100:0},L},{});return{totalConversionRate:G,statusBreakdown:X}}async function aG(){let N=await V.selectFrom("waitlist_restaurants").select([V.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),V.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:N?.avg_quoted_wait_time??0,averageActualWaitTime:N?.avg_actual_wait_time??0}}async function eG(){let N=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=N.reduce((G,X)=>G+(X.quoted_wait_time??0),0),J=N.length>0?$/N.length:0;return{entries:N,totalQuotedWaitTime:$,averageQuotedWaitTime:J}}async function tG(){let N=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=N.reduce((X,L)=>X+L.party_size,0),J=N.length>0?$/N.length:0,G=N.reduce((X,L)=>{return X[L.party_size]=(X[L.party_size]||0)+1,X},{});return{entries:N,totalPartySize:$,averagePartySize:J,partySizeBreakdown:G}}async function rG(){let N=new Date,$=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=h($),X=h(J),L=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",G).where("check_in_time","<=",X).execute(),W=L.length,Y=L.reduce((Q,x)=>Q+x.party_size,0),Z=W>0?Y/W:0,M=L.reduce((Q,x)=>{return Q[x.table_preference]=(Q[x.table_preference]||0)+1,Q},{}),K=L.reduce((Q,x)=>{return Q[x.party_size]=(Q[x.party_size]||0)+1,Q},{});return{totalTablesTurned:W,averagePartySize:Z,totalCustomersSeated:Y,breakdownByTablePreference:M,breakdownByPartySize:K}}async function $3(N,$){let J=h(N),G=h($),X=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).where("check_in_time",">=",J).where("check_in_time","<=",G).groupBy("status").execute(),L=X.reduce((M,{count:K})=>M+K,0),W=X.find((M)=>M.status==="seated")?.count??0,Y=L>0?Number(W)/L*100:0,Z=X.reduce((M,{status:K,count:Q})=>{return M[K]={count:Q,percentage:L>0?Q/L*100:0},M},{});return{totalEntries:L,seatedEntries:W,seatingRate:Y,statusBreakdown:Z}}async function N3(N,$){let J=h(N),G=h($),X=V.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",J).where("check_in_time","<=",G),L=await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("check_in_time",">=",J).where("check_in_time","<=",G).executeTakeFirst(),W=await X.execute(),Y=W.length,Z=L?.count&&L.count>0?Y/L.count*100:0,M=W.reduce((_,S)=>_+(S.quoted_wait_time??0),0),K=Y>0?M/Y:0,Q=W.reduce((_,S)=>_+S.party_size,0),x=Y>0?Q/Y:0,R=W.reduce((_,S)=>{return _[S.table_preference]=(_[S.table_preference]||0)+1,_},{}),O=W.reduce((_,S)=>{return _[S.party_size]=(_[S.party_size]||0)+1,_},{});return{totalNoShows:Y,noShowRate:Z,averageQuotedWaitTime:K,averagePartySize:x,breakdownByTablePreference:R,breakdownByPartySize:O}}async function J3(){let N=await V.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=N.reduce((X,L)=>X+(L.quoted_wait_time||0),0),J=N.reduce((X,L)=>X+(L.actual_wait_time||0),0),G=N.length;return{averageQuoted:G>0?$/G:0,averageActual:G>0?J/G:0}}async function G3(){let N=Date.now()-86400000,$=await V.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",N).execute(),J=Array.from({length:24},(G,X)=>({hour:X,count:$.filter((L)=>{return L.seated_at===X}).length}));return{total:$.length,byHour:J}}async function X3(){return(await V.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,J)=>{let G=J.created_at;if(!$[G])$[G]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[G].total++,$[G][J.status]++,$},{})}var{randomUUIDv7:L3}=globalThis.Bun;import{db as u1}from"@stacksjs/database";import{formatDate as n1}from"@stacksjs/orm";var _X={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function OX(N){if(typeof N==="number")return n1(N<=2147483647?N*1000:N);if(N instanceof Date)return n1(N);return N}function g0(N,$={}){let J=Object.fromEntries(Object.entries(N).filter(([,X])=>X!==void 0));for(let X of["check_in_time","seated_at","no_show_at","cancelled_at"])if(J[X]!==void 0)J[X]=OX(J[X]);let G=_X[J.status];if(G&&J[G]===void 0&&!$[G])J[G]=n1(new Date);return J}async function W3(N){try{let $=L3(),J={...g0(N),status:N.status||"waiting",uuid:$};await u1.insertInto("waitlist_restaurants").values(J).executeTakeFirst();let G=await u1.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create restaurant waitlist entry");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function Y3(N){if(!N.length)return 0;try{let $=N.map((G)=>({...g0(G),status:G.status||"waiting",uuid:L3()})),J=await u1.insertInto("waitlist_restaurants").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as SX}from"@stacksjs/database";import{formatDate as TX}from"@stacksjs/orm";async function K0(N,$){try{if(!N)throw Error("Restaurant waitlist entry ID is required for update");let J=await h0(N);if(!J)return;await SX.updateTable("waitlist_restaurants").set({...g0($,J),updated_at:TX(new Date)}).where("id","=",N).execute();let G=await h0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${J.message}`);throw J}}async function Z3(N,$){return await K0(N,{status:$})}async function M3(N,$){return await K0(N,{party_size:$})}async function F3(N,$,J){return await K0(N,{quoted_wait_time:$,...J===void 0?{}:{actual_wait_time:J}})}async function K3(N,$){return await K0(N,{queue_position:$})}var wX={products:D$,restaurant:Q0},UX=wX;var EX={coupons:p$,customers:b$,devices:u$,errors:s$,giftCards:a$,orders:Y1,payments:Z1,products:V1,receipts:O1,restaurant:Q0,shippings:p1,tax:b1,waitlists:i1},vK=EX;export{i1 as waitlists,b1 as tax,p1 as shippings,Q0 as restaurant,O1 as receipts,V1 as products,Z1 as payments,Y1 as orders,a$ as giftCards,s$ as errors,u$ as devices,vK as default,b$ as customers,p$ as coupons,EX as commerce};
|
|
27
|
+
AND COALESCE(refund_amount, 0) + ${G(5)} <= amount`,[$,$,X,N,$]),W=typeof L?.execute==="function"?await L.execute():L;if(Number(W?.numUpdatedRows??W?.[0]?.numUpdatedRows??W?.numAffectedRows??W?.affectedRows??W?.[0]?.affectedRows??W?.changes??0)>0){let x=await t(N);if(x)return x;throw Error(`Payment with ID ${N} disappeared during refund`)}let Z=await t(N);if(!Z)throw Error(`Payment with ID ${N} not found`);let M=String(Z.status||"");if(!a3.has(M))throw Error(`Payment status ${M||"unknown"} cannot be refunded`);let K=Z,Q=Number(Z.amount||0)-Number(K.refundAmount??K.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${Q} minor units`)}var V1={};B(V1,{variants:()=>Z$,units:()=>Y$,reviews:()=>X$,manufacturers:()=>G$,items:()=>J$,default:()=>YX,categories:()=>N$});var N$={};B(N$,{updateParent:()=>C2,updateDisplayOrder:()=>k2,updateActiveStatus:()=>j2,update:()=>f2,store:()=>F1,removeChildCategories:()=>w2,remove:()=>S2,findOrCreateByName:()=>q2,fetchStats:()=>R2,fetchRootCategories:()=>z2,fetchChildCategories:()=>B2,fetchCategoryTree:()=>O2,fetchByName:()=>H2,fetchById:()=>f,fetchByDisplayOrder:()=>A2,fetchAll:()=>M1,fetchActive:()=>V2,deactivateChildCategories:()=>E2,deactivate:()=>U2,compareCategoryGrowth:()=>_2,bulkRemove:()=>T2});import{db as W0}from"@stacksjs/database";import{db as w}from"@stacksjs/database";import{formatDate as A0}from"@stacksjs/orm";async function M1(){return await w.selectFrom("categories").selectAll().execute()}async function f(N){return await w.selectFrom("categories").where("id","=",N).selectAll().executeTakeFirst()}async function H2(N){return await w.selectFrom("categories").where("name","=",N).selectAll().executeTakeFirst()}async function V2(){return await w.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function z2(){return await w.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function B2(N){return await w.selectFrom("categories").where("parent_category_id","=",N).where("is_active","=",!0).selectAll().execute()}async function A2(N=!0){let $=w.selectFrom("categories").where("is_active","=",!0).selectAll();if(N)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function R2(){let N=await w.selectFrom("categories").select(w.fn.count("id").as("count")).executeTakeFirst(),$=await w.selectFrom("categories").where("is_active","=",!0).select(w.fn.count("id").as("count")).executeTakeFirst(),J=await w.selectFrom("categories").whereNull("parent_category_id").select(w.fn.count("id").as("count")).executeTakeFirst(),G=await w.selectFrom("categories").whereNotNull("image_url").select(w.fn.count("id").as("count")).executeTakeFirst(),X=new Date;X.setDate(X.getDate()-30);let L=A0(X),W=await w.selectFrom("categories").where("created_at",">=",L).selectAll().limit(5).execute(),Y=await w.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",w.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(N?.count||0),active:Number($?.count||0),root_categories:Number(J?.count||0),child_categories:Number(N?.count||0)-Number(J?.count||0),with_images:Number(G?.count||0),recently_added:W,top_parent_categories:Y.map((Z)=>({id:String(Z.parent_category_id||""),name:String(Z.parent_name||""),child_count:Number(Z.child_count)}))}}async function _2(N=30){let $=new Date,J=A0($),G=new Date;G.setDate($.getDate()-N);let X=A0(G),L=new Date(G);L.setDate(L.getDate()-1);let W=A0(L),Y=new Date(L);Y.setDate(L.getDate()-N);let Z=A0(Y),M=await w.selectFrom("categories").select(w.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",J).executeTakeFirst(),K=await w.selectFrom("categories").select(w.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",W).executeTakeFirst(),Q=Number(M?.count||0),x=Number(K?.count||0),R=Q-x,O=x!==0?R/x*100:Q>0?100:0;return{current_period:Q,previous_period:x,difference:R,percentage_change:O,days_range:N}}async function O2(){let N=await M1(),$=new Map;N.forEach((X)=>{$.set(X.id,{...X,children:[]})});let J=[];N.forEach((X)=>{let L=$.get(X.id);if(X.parent_category_id){let W=$.get(X.parent_category_id);if(W)W.children.push(L)}else J.push(L)}),J.sort((X,L)=>X.display_order-L.display_order);let G=(X)=>{X.sort((L,W)=>L.display_order-W.display_order),X.forEach((L)=>{if(L.children.length>0)G(L.children)})};return G(J),J}async function S2(N){let $=await W0.deleteFrom("categories").where("id","=",N).executeTakeFirst();return F($)>0}async function T2(N){if(!N.length)return 0;let $=await W0.deleteFrom("categories").where("id","in",N).executeTakeFirst();return F($)}async function w2(N){let $=await W0.deleteFrom("categories").where("parent_category_id","=",N).executeTakeFirst();return F($)}async function U2(N){if(!await f(N))throw Error(`Category with ID ${N} not found`);return!!await W0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",N).executeTakeFirst()}async function E2(N){let $=await W0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",N).execute();return Number($.length)||0}var{randomUUIDv7:e3}=globalThis.Bun;import{db as P2}from"@stacksjs/database";import{HttpError as r0}from"@stacksjs/error-handling";import{isUniqueViolation as t3}from"@stacksjs/orm";import{slug as r3}from"@stacksjs/strings";async function F1(N){try{let $=N.parent_category_id?Number(N.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new r0(422,"Parent category ID must be a positive integer");if($&&!await f($))throw new r0(422,`Parent category with ID ${N.parent_category_id} not found`);let J={...N,uuid:e3(),is_active:N.is_active??!0,parent_category_id:N.parent_category_id||null},G=await P2.insertInto("categories").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create category");return G}catch($){if($ instanceof r0)throw $;if(t3($))throw new r0(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function q2(N){if(!N.name)throw Error("Name is required");let $=await P2.selectFrom("categories").selectAll().where("name","=",N.name).executeTakeFirst();if($)return $;let J={name:N.name,slug:r3(N.name),is_active:N.is_active??!0,display_order:0};return await F1(J)}import{db as R0}from"@stacksjs/database";import{HttpError as Y0}from"@stacksjs/error-handling";import{formatDate as $$,isUniqueViolation as $X}from"@stacksjs/orm";async function f2(N,$){if(!await f(N))return;if(Object.hasOwn($,"parent_category_id")){let G=$.parent_category_id?Number($.parent_category_id):void 0;if(G!==void 0&&(!Number.isSafeInteger(G)||G<=0))throw new Y0(422,"Parent category ID must be a positive integer");if(G===N)throw new Y0(422,"A category cannot be its own parent");if(G&&!await f(G))throw new Y0(422,`Parent category with ID ${$.parent_category_id} not found`);if(G&&await I2(N,String(G)))throw new Y0(422,"This operation would create a circular category hierarchy")}try{let G=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},X=await R0.updateTable("categories").set({...$,...G,updated_at:$$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!X)return;return X}catch(G){if(G instanceof Y0)throw G;if($X(G))throw new Y0(409,"A category with this name or slug already exists");if(G instanceof Error)throw Error(`Failed to update category: ${G.message}`);throw G}}async function k2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);try{return await R0.updateTable("categories").set({display_order:$,updated_at:$$(new Date)}).where("id","=",N).execute(),await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category display order: ${G.message}`);throw G}}async function j2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);try{return await R0.updateTable("categories").set({is_active:$,updated_at:$$(new Date)}).where("id","=",N).execute(),await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category active status: ${G.message}`);throw G}}async function C2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);if($){let G=Number($);if(G===N)throw Error("A category cannot be its own parent");if(!await f(G))throw Error(`Parent category with ID ${$} not found`);if(await I2(N,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let G={updated_at:$$(new Date)};if($===null)await R0.updateTable("categories").set({...G,parent_category_id:null}).where("id","=",N).execute();else await R0.updateTable("categories").set({...G,parent_category_id:$}).where("id","=",N).execute();return await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category parent: ${G.message}`);throw G}}async function I2(N,$){let J=Number($),G=new Set;while(J){if(G.has(J))return!0;if(J===N)return!0;G.add(J);let X=await f(J),L=X?.parent_category_id??X?.parentCategoryId;if(!X||!L)return!1;J=Number(L)}return!1}var J$={};B(J$,{updateInventory:()=>u2,updateAvailability:()=>n2,update:()=>c2,store:()=>m2,fetchTopProducts:()=>D2,fetchById:()=>l,fetchAll:()=>y2,destroy:()=>g2,bulkStore:()=>l2,bulkDestroy:()=>v2});import{db as h2}from"@stacksjs/database";async function g2(N){try{let $=await h2.deleteFrom("products").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function v2(N){if(!N.length)return 0;try{let $=await h2.deleteFrom("products").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as i,sql as NX}from"@stacksjs/database";async function l(N){let $=await i.selectFrom("products").where("id","=",N).selectAll().executeTakeFirst();if($){let J=null,G=null;if($.manufacturer_id)J=await i.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)G=await i.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:J,category:G}}return}async function y2(){let N=await i.selectFrom("products").selectAll().execute(),$=N.map((M)=>M.manufacturer_id).filter((M)=>M!==null&&M!==void 0),J=N.map((M)=>M.category_id).filter((M)=>M!==null&&M!==void 0),G=i.selectFrom("manufacturers"),X=i.selectFrom("categories");if($.length>0)G=G.where("id","in",$);if(J.length>0)X=X.where("id","in",J);let L=await G.selectAll().execute(),W=await X.selectAll().execute(),Y=L.reduce((M,K)=>{return M[K.id]=K,M},{}),Z=W.reduce((M,K)=>{return M[K.id]=K,M},{});return N.map((M)=>({...M,manufacturer:M.manufacturer_id?Y[M.manufacturer_id]:null,category:M.category_id?Z[M.category_id]:null}))}async function D2(N=5){try{return(await i.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",i.fn.sum("order_items.quantity").as("units_sold"),NX`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(N).execute()).map((J)=>({id:Number(J.id),name:String(J.name??"Unnamed product"),units_sold:Number(J.units_sold??0),revenue:Number(J.revenue??0),inventory_count:Number(J.inventory_count??0)}))}catch($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:p2}=globalThis.Bun;import{db as b2}from"@stacksjs/database";async function m2(N){try{let $={...N,uuid:p2()},J=await b2.insertInto("products").values($).executeTakeFirst();if(!J)throw Error("Failed to create product item");let G=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows),X=await l(G);if(!X)throw Error("Failed to create product item");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function l2(N){if(!N.length)return 0;let $=0;try{return await b2.transaction().execute(async(J)=>{for(let G of N){let X={...G,uuid:p2()};await J.insertInto("products").values(X).execute(),$++}}),$}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product items in bulk: ${J.message}`);throw J}}import{db as K1}from"@stacksjs/database";import{formatDate as Q1}from"@stacksjs/orm";async function c2(N,$){try{if(!N)throw Error("Product item ID is required for update");let J=await K1.updateTable("products").set({...$,updated_at:Q1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product item: ${J.message}`);throw J}}async function n2(N,$){if(!await l(N))throw Error(`Product item with ID ${N} not found`);try{return await K1.updateTable("products").set({is_available:$,updated_at:Q1(new Date)}).where("id","=",N).execute(),await l(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item availability: ${G.message}`);throw G}}async function u2(N,$){let J=await l(N);if(!J)throw Error(`Product item with ID ${N} not found`);let G={updated_at:Q1(new Date)};if($!==void 0)G.inventory_count=$;if(Object.keys(G).length===1)return J;try{return await K1.updateTable("products").set(G).where("id","=",N).execute(),await l(N)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update inventory information: ${X.message}`);throw X}}var G$={};B(G$,{updateFeaturedStatus:()=>Z7,updateByUuid:()=>M7,update:()=>Y7,store:()=>X7,fetchWithProductCount:()=>$7,fetchFeatured:()=>t2,fetchByUuid:()=>e2,fetchById:()=>a2,fetchByCountry:()=>r2,fetchAll:()=>d2,destroy:()=>o2,bulkStore:()=>L7,bulkDestroy:()=>s2});import{db as i2}from"@stacksjs/database";async function o2(N){try{let $=await i2.deleteFrom("manufacturers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function s2(N){if(!N.length)return 0;try{let $=await i2.deleteFrom("manufacturers").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as c}from"@stacksjs/database";function d2(){return c.selectFrom("manufacturers").selectAll().execute()}async function a2(N){return await c.selectFrom("manufacturers").where("id","=",N).selectAll().executeTakeFirst()}async function e2(N){return await c.selectFrom("manufacturers").where("uuid","=",N).selectAll().executeTakeFirst()}async function t2(N=10){return await c.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(N).execute()}async function r2(N,$={}){let J=$.page||1,G=$.limit||2,X=await c.selectFrom("manufacturers").select(c.fn.count("id").as("total")).where("country","=",N).executeTakeFirst(),L=Number(X?.total||0),W=await c.selectFrom("manufacturers").selectAll().where("country","=",N).limit(G).offset((J-1)*G).execute(),Y=Math.ceil(L/G);return{data:W,paging:{total_records:L,page:J,total_pages:Y},next_cursor:J<Y?J+1:null}}async function $7(N={}){let $=c.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(N.country)$=$.where("m.country","=",N.country);if(N.featured!==void 0)$=$.where("m.featured","=",N.featured);return $=$.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",c.fn.count("p.id").as("product_count")]).groupBy("m.id"),$.execute()}var{randomUUIDv7:J7}=globalThis.Bun;import{db as G7}from"@stacksjs/database";import{HttpError as N7}from"@stacksjs/error-handling";import{isUniqueViolation as JX}from"@stacksjs/orm";async function X7(N){try{let $={...N,uuid:J7(),featured:N.featured??!1},J=await G7.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create manufacturer");return J}catch($){if($ instanceof N7)throw $;if(JX($))throw new N7(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function L7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:J7(),featured:J.featured??!1};await G7.insertInto("manufacturers").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${J.message}`);throw J}}import{db as x1}from"@stacksjs/database";import{HttpError as W7}from"@stacksjs/error-handling";import{formatDate as H1,isUniqueViolation as GX}from"@stacksjs/orm";async function Y7(N,$){try{if(!N)throw Error("Manufacturer ID is required for update");let J=await x1.updateTable("manufacturers").set({...$,updated_at:H1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof W7)throw J;if(GX(J))throw new W7(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to update manufacturer: ${J.message}`);throw J}}async function Z7(N,$){try{let J=await x1.updateTable("manufacturers").set({featured:$,updated_at:H1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update manufacturer featured status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${J.message}`);throw J}}async function M7(N,$){try{let J=await x1.updateTable("manufacturers").set({...$,updated_at:H1(new Date)}).where("uuid","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update manufacturer");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update manufacturer: ${J.message}`);throw J}}var X$={};B(X$,{updateVotes:()=>T7,update:()=>S7,store:()=>R7,fetchMostHelpfulByProductId:()=>A7,fetchByUserId:()=>z7,fetchByProductId:()=>V7,fetchById:()=>x7,fetchApprovedByProductId:()=>B7,fetchAll:()=>H7,destroy:()=>K7,bulkDestroy:()=>Q7});import{db as F7}from"@stacksjs/database";async function K7(N){try{let $=await F7.deleteFrom("reviews").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function Q7(N){if(!N.length)return 0;try{let $=await F7.deleteFrom("reviews").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as Z0}from"@stacksjs/database";async function x7(N){return await Z0.selectFrom("reviews").where("id","=",N).selectAll().executeTakeFirst()}async function H7(){return await Z0.selectFrom("reviews").selectAll().execute()}async function V7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).selectAll().execute()}async function z7(N){return await Z0.selectFrom("reviews").where("customer_id","=",N).selectAll().execute()}async function B7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).where("is_approved","=",!0).selectAll().execute()}async function A7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:XX}=globalThis.Bun;import{db as LX}from"@stacksjs/database";async function R7(N){try{let $={...N,uuid:XX(),is_verified_purchase:N.is_verified_purchase??!1,is_approved:N.is_approved??!1,helpful_votes:N.helpful_votes??0,unhelpful_votes:N.unhelpful_votes??0,is_featured:N.is_featured??!1},J=await LX.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create review");return J}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${$.message}`)}throw $}}import{db as _7}from"@stacksjs/database";import{formatDate as O7}from"@stacksjs/orm";async function S7(N,$){try{if(!N)throw Error("Review ID is required for update");let J=await _7.updateTable("reviews").set({...$,updated_at:O7(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update review: ${J.message}`);throw J}}async function T7(N,$,J=!0){try{let G=$==="helpful"?"helpful_votes":"unhelpful_votes",X=J?`COALESCE("${G}", 0) + 1`:`MAX(COALESCE("${G}", 0) - 1, 0)`,L=await _7.unsafe(`UPDATE "reviews" SET "${G}" = ${X}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[O7(new Date),N]).execute(),W=Array.isArray(L)?L[0]:L;if(!W)throw Error("Failed to update review votes");return W}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review votes: ${G.message}`);throw G}}var Y$={};B(Y$,{updateDefaultStatus:()=>y7,update:()=>g7,store:()=>j7,getDefaultUnit:()=>h7,formatUnitOptions:()=>I7,fetchById:()=>q7,fetchAll:()=>f7,destroy:()=>U7,bulkUpdate:()=>v7,bulkStore:()=>C7,bulkDestroy:()=>E7});import{db as w7}from"@stacksjs/database";async function U7(N){try{let $=await w7.deleteFrom("product_units").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function E7(N){if(!N.length)return 0;try{let $=await w7.deleteFrom("product_units").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as P7}from"@stacksjs/database";async function q7(N){return await P7.selectFrom("product_units").where("id","=",N).selectAll().executeTakeFirst()}async function f7(){return await P7.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:k7}=globalThis.Bun;import{db as _0}from"@stacksjs/database";async function j7(N){try{return await _0.transaction(async($)=>{let J={...N,uuid:k7()},G=await $.insertInto("product_units").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product unit");if(J.is_default&&J.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",G.id).execute();return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function C7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:k7()},X=await _0.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(G.is_default&&G.type&&X)await _0.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product units in bulk: ${J.message}`);throw J}}function I7(N){try{let $=_0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(N)$=$.where("type","=",N);return $=$.orderBy("name"),$.execute().then((J)=>J.map((G)=>({id:String(G.id),name:G.name,abbreviation:G.abbreviation,is_default:G.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function h7(N){try{return await _0.selectFrom("product_units").selectAll().where("type","=",N).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as L$}from"@stacksjs/database";import{formatDate as W$}from"@stacksjs/orm";async function g7(N,$){try{if(!N)throw Error("Product unit ID is required for update");return await L$.transaction(async(J)=>{let G=await J.selectFrom("product_units").select(["type","is_default"]).where("id","=",N).executeTakeFirst();if(!G)return;let X=$.type??G.type;if(($.is_default??Boolean(G.is_default))&&X)await J.updateTable("product_units").set({is_default:!1,updated_at:W$(new Date)}).where("type","=",X).where("id","!=",N).execute();let W=await J.updateTable("product_units").set({...$,updated_at:W$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!W)return;return W})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product unit: ${J.message}`);throw J}}async function v7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G=J;if(!G.id)continue;let X=G.data&&typeof G.data==="object"?G.data:{...G};delete X.id;let L=await L$.updateTable("product_units").set({...X,updated_at:W$(new Date)}).where("id","=",G.id).executeTakeFirst(),W=X;if(W.is_default===!0&&W.type)await L$.updateTable("product_units").set({is_default:!1}).where("type","=",W.type).where("id","!=",G.id).execute();if(Number(L.numUpdatedRows)>0)$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product units in bulk: ${J.message}`);throw J}}async function y7(N,$){try{return await L$.transaction(async(J)=>{let G=await J.selectFrom("product_units").select("type").where("id","=",N).executeTakeFirst();if(!G)return!1;let X=W$(new Date);if($&&G.type)await J.updateTable("product_units").set({is_default:!1,updated_at:X}).where("type","=",G.type).where("id","!=",N).execute();return await J.updateTable("product_units").set({is_default:$,updated_at:X}).where("id","=",N).execute(),!0})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product unit default status: ${J.message}`);throw J}}var Z$={};B(Z$,{update:()=>t7,store:()=>i7,generateVariantCombinations:()=>d7,formatVariantOptions:()=>s7,fetchById:()=>l7,fetchAll:()=>c7,destroy:()=>p7,bulkUpdate:()=>r7,bulkStore:()=>o7,bulkDestroy:()=>b7});import{db as D7}from"@stacksjs/database";async function p7(N){try{let $=await D7.deleteFrom("product_variants").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function b7(N){if(!N.length)return 0;try{let $=await D7.deleteFrom("product_variants").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as m7}from"@stacksjs/database";async function l7(N){return await m7.selectFrom("product_variants").where("id","=",N).selectAll().executeTakeFirst()}async function c7(){return await m7.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:n7}=globalThis.Bun;import{db as u7}from"@stacksjs/database";async function i7(N){try{let $={...N,uuid:n7()},J=await u7.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create product variant");return J}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function o7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:n7()};await u7.insertInto("product_variants").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${J.message}`);throw J}}function s7(N){if(!N||!N.length)return JSON.stringify([]);let $=N.map((J)=>J.trim()).filter(Boolean);return JSON.stringify($)}function d7(N){let $=Object.keys(N);if(!$.length)return[];function J(G,X){if(G===$.length)return[X];let L=$[G],W=N[L]??[],Y=[];for(let Z of W){let M={...X,[L]:Z};Y.push(...J(G+1,M))}return Y}return J(0,{})}import{db as a7}from"@stacksjs/database";import{formatDate as e7}from"@stacksjs/orm";async function t7(N,$){try{let J=await a7.updateTable("product_variants").set({...$,updated_at:e7(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product variant: ${J.message}`);throw J}}async function r7(N){if(!N.length)return 0;let $=0;try{for(let J of N){if(!J.id)continue;let G=await a7.updateTable("product_variants").set({...J,updated_at:e7(new Date)}).where("id","=",J.id).executeTakeFirst();if(Number(G.numUpdatedRows)>0)$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${J.message}`);throw J}}var WX={categories:N$,items:J$,manufacturers:G$,reviews:X$,units:Y$,variants:Z$},YX=WX;var O1={};B(O1,{updateStatus:()=>xJ,updatePrintJob:()=>HJ,update:()=>QJ,store:()=>FJ,fetchSuccessRate:()=>LJ,fetchPrintsPerHour:()=>ZJ,fetchPrintTimeStats:()=>YJ,fetchPrintJobStats:()=>XJ,fetchPageStats:()=>WJ,fetchById:()=>M0,fetchAll:()=>GJ,destroy:()=>NJ,bulkStore:()=>KJ,bulkDestroy:()=>JJ});import{db as $J}from"@stacksjs/database";async function NJ(N){try{let $=await $J.deleteFrom("receipts").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function JJ(N){if(!N.length)return 0;try{let $=await $J.deleteFrom("receipts").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as z1}from"@stacksjs/database";import{formatDate as ZX}from"@stacksjs/orm";function y(N){return ZX(N)}function MX(N){if(N instanceof Date)return Number.isNaN(N.getTime())?null:N;if(typeof N==="number"){let G=new Date(N<=2147483647?N*1000:N);return Number.isNaN(G.getTime())?null:G}let $=String(N||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let G=new Date(Number($)*1000);return Number.isNaN(G.getTime())?null:G}let J=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(J.getTime())?null:J}async function M0(N){return await z1.selectFrom("receipts").where("id","=",N).selectAll().executeTakeFirst()}async function GJ(){return await z1.selectFrom("receipts").selectAll().execute()}async function XJ(N,$){let J=y(N),G=y($),X=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{total:X.total,success:X.success,failed:X.failed,warning:X.warning,averageSize:Math.round(X.averageSize),averagePages:Math.round(X.averagePages),averageDuration:Math.round(X.averageDuration)}}async function LJ(N,$){let J=y(N),G=y($),X=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(W)=>W.where("timestamp",">=",J).where("timestamp","<=",G));return{successRate:X.total>0?Math.round(X.success/X.total*100):0,total:X.total,success:X.success,failed:X.failed,warning:X.warning}}async function WJ(N,$){let J=y(N),G=y($),X=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{totalPages:X.totalPages,averagePagesPerReceipt:Math.round(X.averagePagesPerReceipt),totalReceipts:X.totalReceipts}}async function YJ(N,$){let J=y(N),G=y($),X=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{averageDuration:Math.round(X.averageDuration),minDuration:X.minDuration,maxDuration:X.maxDuration,totalJobs:X.totalJobs}}async function ZJ(N,$){let J=typeof N==="number"?N:N.getTime(),G=typeof $==="number"?$:$.getTime(),X=y(N),L=y($),W=await z1.selectFrom("receipts").where("timestamp",">=",X).where("timestamp","<=",L).selectAll().execute(),Y=W.length,Z=Math.ceil((G-J)/3600000),M=Z>0?Math.round(Y/Z):0,K=Array.from({length:24},(Q,x)=>({hour:x,count:0}));return W.forEach((Q)=>{let x=MX(Q.timestamp);if(!x)return;K[x.getHours()].count++}),{totalPrints:Y,totalHours:Z,printsPerHour:M,hourlyBreakdown:K}}var{randomUUIDv7:MJ}=globalThis.Bun;import{db as A1}from"@stacksjs/database";import{formatDate as B1}from"@stacksjs/orm";function O0(N){try{if(typeof N==="number")return B1(N<=2147483647?N*1000:N);if(typeof N==="string"&&/^\d{10}$/.test(N))return B1(Number(N)*1000);return B1(N)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function FJ(N){try{let $=MJ(),J={...N,timestamp:O0(N.timestamp),uuid:$};await A1.insertInto("receipts").values(J).executeTakeFirst();let G=await A1.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create receipt");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function KJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...G,timestamp:O0(G.timestamp),uuid:MJ()})),J=await A1.insertInto("receipts").values($).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows??J.numAffectedRows??J.affectedRows??J.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as R1}from"@stacksjs/database";import{formatDate as _1}from"@stacksjs/orm";async function QJ(N,$){try{if(!N)throw Error("Receipt ID is required for update");let J={...$,...$.timestamp===void 0?{}:{timestamp:O0($.timestamp)},updated_at:_1(new Date)};await R1.updateTable("receipts").set(J).where("id","=",N).execute();let G=await M0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update receipt: ${J.message}`);throw J}}async function xJ(N,$){try{await R1.updateTable("receipts").set({status:$,updated_at:_1(new Date)}).where("id","=",N).execute();let J=await M0(N);if(!J)throw Error("Failed to update receipt status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update receipt status: ${J.message}`);throw J}}async function HJ(N,$,J,G){try{let X={updated_at:_1(new Date)};if($!==void 0)X.size=$;if(J!==void 0)X.pages=J;if(G!==void 0)X.duration=G;await R1.updateTable("receipts").set(X).where("id","=",N).execute();let L=await M0(N);if(!L)throw Error("Failed to update receipt job information");return L}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt job information: ${X.message}`);throw X}}var p1={};B(p1,{zones:()=>h$,routes:()=>H$,rates:()=>k$,methods:()=>U$,licenses:()=>O$,drivers:()=>A$,digital:()=>z$,default:()=>VX});var H$={};B(H$,{validateDeliveryRouteWrite:()=>F0,updateStops:()=>wJ,updateMetrics:()=>UJ,updateLastActive:()=>SJ,update:()=>TJ,store:()=>OJ,fetchById:()=>F$,fetchByDriver:()=>_J,fetchAll:()=>AJ,fetchActive:()=>RJ,destroy:()=>zJ,bulkDestroy:()=>BJ,DeliveryRouteInputError:()=>C});import{db as VJ}from"@stacksjs/database";async function zJ(N){try{let $=await VJ.deleteFrom("delivery_routes").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function BJ(N){if(!N.length)return 0;try{let $=await VJ.deleteFrom("delivery_routes").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as M$}from"@stacksjs/database";async function F$(N){return await M$.selectFrom("delivery_routes").where("id","=",N).selectAll().executeTakeFirst()}async function AJ(){return await M$.selectFrom("delivery_routes").selectAll().execute()}async function RJ(){return await M$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function _J(N){return await M$.selectFrom("delivery_routes").where("driver","=",N).selectAll().execute()}var{randomUUIDv7:QX}=globalThis.Bun;import{db as S1}from"@stacksjs/database";function r(N,$){let J={};for(let[G,X]of Object.entries($))for(let L of X){if(!Object.prototype.hasOwnProperty.call(N,L)||N[L]===void 0)continue;J[G]=N[L];break}return J}function S0(N){return r(N,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function n(N){return r(N,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function T0(N){return r(N,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function w0(N){return r(N,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function U0(N){return r(N,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function E0(N){return r(N,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function K$(N){return r(N,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as FX}from"@stacksjs/database";class C extends TypeError{constructor(N){super(N);this.name="DeliveryRouteInputError"}}function Q$(N,$,J){return Number(N[J]??$?.[J])}function KX(N,$){let J=N.last_active??$?.last_active;if(J instanceof Date)return J.getTime();if(typeof J==="number")return J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return Number(J);return Number.NaN}async function F0(N,$){let J=Q$(N,$,"driver_id"),G=Q$(N,$,"stops"),X=Q$(N,$,"delivery_time"),L=Q$(N,$,"total_distance"),W=KX(N,$);if(!Number.isSafeInteger(J)||J<1)throw new C("Driver must be a positive integer.");if(!Number.isSafeInteger(G)||G<0)throw new C("Stops must be a non-negative integer.");if(!Number.isSafeInteger(X)||X<0)throw new C("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(L)||L<0)throw new C("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(W)||W<0)throw new C("Last active must be a valid Unix timestamp.");let Y=await FX.selectFrom("drivers").where("id","=",J).select(["id","name","vehicle_number"]).executeTakeFirst();if(!Y)throw new C(`Driver ${J} was not found.`);return{...N,driver_id:Number(Y.id),driver:Y.name,vehicle:Y.vehicle_number}}async function OJ(N){try{let $=QX(),J=K$(N),X={...await F0(J),uuid:$};await S1.insertInto("delivery_routes").values(X).executeTakeFirst();let L=await S1.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!L)throw Error("Failed to create delivery route");return L}catch($){if($ instanceof C)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function SJ(N){try{await S1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",N).execute();let $=await F$(N);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as x$}from"@stacksjs/database";import{formatDate as T1}from"@stacksjs/orm";async function TJ(N,$){try{if(!N)throw Error("Delivery route ID is required for update");let J=await x$.selectFrom("delivery_routes").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=K$($),X=await F0(G,J),L=await x$.updateTable("delivery_routes").set({...X,updated_at:T1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!L)return;return L}catch(J){if(J instanceof C)throw J;if(J instanceof Error)throw TypeError(`Failed to update delivery route: ${J.message}`);throw J}}async function wJ(N,$){try{let J=await x$.updateTable("delivery_routes").set({stops:$,updated_at:T1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update delivery route stops");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route stops: ${J.message}`);throw J}}async function UJ(N,$,J){try{let G={updated_at:T1(new Date)};if($!==void 0)G.delivery_time=$;if(J!==void 0)G.total_distance=J;let X=await x$.updateTable("delivery_routes").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery metrics");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery metrics: ${G.message}`);throw G}}var z$={};B(z$,{updateStatus:()=>yJ,updateDeliverySettings:()=>DJ,update:()=>vJ,store:()=>hJ,softDelete:()=>PJ,fetchById:()=>jJ,fetchAll:()=>CJ,destroy:()=>EJ,bulkStore:()=>gJ,bulkSoftDelete:()=>fJ,bulkDestroy:()=>qJ});import{db as V$}from"@stacksjs/database";async function EJ(N){try{let $=await V$.deleteFrom("digital_deliveries").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function PJ(N){try{let $=await V$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function qJ(N){if(!N.length)return 0;try{let $=await V$.deleteFrom("digital_deliveries").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function fJ(N){if(!N.length)return 0;try{let $=await V$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as kJ}from"@stacksjs/database";async function jJ(N){return await kJ.selectFrom("digital_deliveries").where("id","=",N).selectAll().executeTakeFirst()}async function CJ(){return await kJ.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:IJ}=globalThis.Bun;import{db as w1}from"@stacksjs/database";async function hJ(N){try{let $=IJ(),J={...w0(N),uuid:$};await w1.insertInto("digital_deliveries").values(J).executeTakeFirst();let G=await w1.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created digital delivery");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function gJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...w0(G),uuid:IJ()})),J=await w1.insertInto("digital_deliveries").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as U1}from"@stacksjs/database";import{formatDate as E1}from"@stacksjs/orm";async function vJ(N,$){try{if(!N)throw Error("Digital delivery ID is required for update");let J=await U1.updateTable("digital_deliveries").set({...w0($),updated_at:E1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update digital delivery: ${J.message}`);throw J}}async function yJ(N,$){try{let J=await U1.updateTable("digital_deliveries").set({status:$,updated_at:E1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update digital delivery status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update digital delivery status: ${J.message}`);throw J}}async function DJ(N,$,J,G,X){try{let L={updated_at:E1(new Date)};if($!==void 0)L.download_limit=$;if(J!==void 0)L.expiry_days=J;if(G!==void 0)L.requires_login=G;if(X!==void 0)L.automatic_delivery=X;let W=await U1.updateTable("digital_deliveries").set(L).where("id","=",N).returningAll().executeTakeFirst();if(!W)throw Error("Failed to update delivery settings");return W}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery settings: ${L.message}`);throw L}}var A$={};B(A$,{updateStatus:()=>sJ,updateContact:()=>dJ,update:()=>oJ,store:()=>uJ,fetchById:()=>B$,fetchAll:()=>bJ,destroy:()=>lJ,bulkStore:()=>iJ,bulkDestroy:()=>cJ});import{db as mJ}from"@stacksjs/database";import{db as pJ}from"@stacksjs/database";async function B$(N){return await pJ.selectFrom("drivers").where("id","=",N).selectAll().executeTakeFirst()}async function bJ(){return await pJ.selectFrom("drivers").selectAll().execute()}async function lJ(N){try{let $=await mJ.deleteFrom("drivers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function cJ(N){if(!N.length)return 0;let $=0;try{return await mJ.transaction().execute(async(J)=>{for(let G of N)if(await B$(G))await J.deleteFrom("drivers").where("id","=",G).execute(),$++}),$}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${J.message}`);throw J}}var{randomUUIDv7:nJ}=globalThis.Bun;import{db as P1}from"@stacksjs/database";async function uJ(N){try{let $=nJ(),J={...E0(N),uuid:$};await P1.insertInto("drivers").values(J).executeTakeFirst();let G=await P1.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created driver");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function iJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...E0(G),uuid:nJ()})),J=await P1.insertInto("drivers").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as q1}from"@stacksjs/database";import{formatDate as f1}from"@stacksjs/orm";async function oJ(N,$){try{if(!N)throw Error("Driver ID is required for update");let J=await q1.updateTable("drivers").set({...E0($),updated_at:f1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update driver: ${J.message}`);throw J}}async function sJ(N,$){try{let J=await q1.updateTable("drivers").set({status:$,updated_at:f1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update driver status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update driver status: ${J.message}`);throw J}}async function dJ(N,$){try{let J={updated_at:f1(new Date)};if($!==void 0)J.phone=$;let G=await q1.updateTable("drivers").set(J).where("id","=",N).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update contact information");return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update contact information: ${J.message}`);throw J}}var O$={};B(O$,{validateLicenseKeyWrite:()=>$0,updateStatus:()=>M6,updateExpiration:()=>F6,update:()=>Z6,store:()=>W6,softDelete:()=>eJ,fetchById:()=>N6,fetchAll:()=>J6,destroy:()=>aJ,bulkStore:()=>Y6,bulkSoftDelete:()=>rJ,bulkDestroy:()=>tJ,LicenseKeyInputError:()=>E});import{db as R$}from"@stacksjs/database";async function aJ(N){try{let $=await R$.deleteFrom("license_keys").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function eJ(N){try{let $=await R$.updateTable("license_keys").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function tJ(N){if(!N.length)return 0;try{let $=await R$.deleteFrom("license_keys").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function rJ(N){if(!N.length)return 0;try{let $=await R$.updateTable("license_keys").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as $6}from"@stacksjs/database";async function N6(N){return await $6.selectFrom("license_keys").where("id","=",N).selectAll().executeTakeFirst()}async function J6(){return await $6.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:L6}=globalThis.Bun;import{db as C1}from"@stacksjs/database";import{db as k1}from"@stacksjs/database";var G6=["Standard License","Premium License","Enterprise License"],X6=["active","inactive","unassigned"];class E extends TypeError{constructor(N){super(N);this.name="LicenseKeyInputError"}}function P0(N,$,J){return N[J]!==void 0?N[J]:$?.[J]}function j1(N,$,J,G){let X=P0(N,$,J);if(X===void 0||X===null||X==="")return null;let L=Number(X);if(!Number.isSafeInteger(L)||L<1)throw new E(`${G} must be a positive integer or null.`);return L}function xX(N){if(typeof N==="number")return N>2147483647?Math.floor(N/1000):N;if(typeof N==="string"&&/^\d{10,13}$/.test(N))return N.length===13?Math.floor(Number(N)/1000):Number(N);if(typeof N==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(N)?`${N.replace(" ","T")}Z`:N;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function $0(N,$){let J=String(P0(N,$,"key")||"").trim().toUpperCase(),G=String(P0(N,$,"template")||""),X=String(P0(N,$,"status")||""),L=xX(P0(N,$,"expiry_date")),W=j1(N,$,"customer_id","Customer"),Y=j1(N,$,"product_id","Product"),Z=j1(N,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(J))throw new E("License key must use five groups of four uppercase letters or numbers.");if(!G6.includes(G))throw new E(`Template must be one of: ${G6.join(", ")}.`);if(!X6.includes(X))throw new E(`Status must be one of: ${X6.join(", ")}.`);if(!Number.isSafeInteger(L)||L<0||L>2147483647)throw new E("Expiry date must be a Unix timestamp between 1970 and 2038.");let[M,K,Q]=await Promise.all([W?k1.selectFrom("customers").where("id","=",W).select("id").executeTakeFirst():null,Y?k1.selectFrom("products").where("id","=",Y).select("id").executeTakeFirst():null,Z?k1.selectFrom("orders").where("id","=",Z).select(["id","customer_id"]).executeTakeFirst():null]);if(W&&!M)throw new E(`Customer ${W} was not found.`);if(Y&&!K)throw new E(`Product ${Y} was not found.`);if(Z&&!Q)throw new E(`Order ${Z} was not found.`);if(W&&Q?.customer_id&&Number(Q.customer_id)!==W)throw new E(`Order ${Z} belongs to Customer ${Q.customer_id}, not Customer ${W}.`);return{...N,key:J,template:G,expiry_date:L,status:X,customer_id:W,product_id:Y,order_id:Z}}async function W6(N){try{let $=L6(),J=U0(N),G={...await $0(J),uuid:$};await C1.insertInto("license_keys").values(G).executeTakeFirst();let X=await C1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created license key");return X}catch($){if($ instanceof E)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function Y6(N){if(!N.length)return 0;try{let $=await Promise.all(N.map(async(G)=>({...await $0(U0(G)),uuid:L6()}))),J=await C1.insertInto("license_keys").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof E)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as _$}from"@stacksjs/database";import{formatDate as I1}from"@stacksjs/orm";async function Z6(N,$){try{if(!N)throw Error("License key ID is required for update");let J=await _$.selectFrom("license_keys").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=U0($),X=await $0(G,J),L=await _$.updateTable("license_keys").set({...X,updated_at:I1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!L)return;return L}catch(J){if(J instanceof E)throw J;if(J instanceof Error){if(J.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${J.message}`)}throw J}}async function M6(N,$){try{let J=await _$.updateTable("license_keys").set({status:$,updated_at:I1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update license key status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update license key status: ${J.message}`);throw J}}async function F6(N,$){try{let J={updated_at:I1(new Date)};if($!==void 0)J.expiry_date=$;let G=await _$.updateTable("license_keys").set(J).where("id","=",N).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update expiration information");return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update expiration information: ${J.message}`);throw J}}var U$={};B(U$,{updateStatus:()=>S6,updatePricing:()=>T6,update:()=>O6,store:()=>B6,softDelete:()=>Q6,getActiveShippingMethods:()=>_6,formatShippingOptions:()=>R6,fetchById:()=>w$,fetchAll:()=>V6,destroy:()=>K6,bulkStore:()=>A6,bulkSoftDelete:()=>H6,bulkDestroy:()=>x6});import{db as S$}from"@stacksjs/database";async function K6(N){try{let $=await S$.deleteFrom("shipping_methods").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function Q6(N){try{let $=await S$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function x6(N){if(!N.length)return 0;try{let $=await S$.deleteFrom("shipping_methods").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function H6(N){if(!N.length)return 0;try{let $=await S$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as T$}from"@stacksjs/database";async function w$(N){let $=await T$.selectFrom("shipping_methods").where("id","=",N).selectAll().executeTakeFirst();if($){let J=await T$.selectFrom("shipping_zones").where("shipping_method_id","=",N).selectAll().execute();return{...$,shippingZones:J}}return}async function V6(){let N=await T$.selectFrom("shipping_methods").selectAll().execute();if(N.length===0)return[];let $=[...new Set(N.map((L)=>L.id))],X=(await T$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((L,W)=>{let Y=W.shipping_method_id;if(Y!==null&&Y!==void 0){if(!L[Y])L[Y]=[];L[Y].push(W)}return L},{});return N.map((L)=>({...L,shipping_zones:X[L.id]||[]}))}var{randomUUIDv7:z6}=globalThis.Bun;import{db as q0}from"@stacksjs/database";async function B6(N){try{let $=z6(),J={...S0(N),uuid:$};await q0.insertInto("shipping_methods").values(J).executeTakeFirst();let G=await q0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created shipping method");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function A6(N){if(!N.length)return 0;try{let $=N.map((G)=>({...S0(G),uuid:z6()})),J=await q0.insertInto("shipping_methods").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function R6(){try{return q0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping options: ${N.message}`);throw N}}async function _6(){try{return await q0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to get active shipping methods: ${N.message}`);throw N}}import{db as h1}from"@stacksjs/database";import{formatDate as g1}from"@stacksjs/orm";async function O6(N,$){try{if(!N)throw Error("Shipping method ID is required for update");let J=await h1.updateTable("shipping_methods").set({...S0($),updated_at:g1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping method: ${J.message}`);throw J}}async function S6(N,$){try{let J=await h1.updateTable("shipping_methods").set({status:$,updated_at:g1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping method status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping method status: ${J.message}`);throw J}}async function T6(N,$,J){try{let G={updated_at:g1(new Date)};if($!==void 0)G.base_rate=$;if(J!==void 0)G.free_shipping=J;let X=await h1.updateTable("shipping_methods").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update pricing information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update pricing information: ${G.message}`);throw G}}var k$={};B(k$,{validateZoneMatchesAddress:()=>I6,validateShippingRateWrite:()=>N0,updateByZone:()=>u6,updateByMethod:()=>i6,update:()=>c6,store:()=>m6,resolveZoneForAddress:()=>P$,getShippingRatesByMethod:()=>g6,getRatesByZone:()=>j6,getRateByWeightAndZone:()=>v1,getRateByWeightAndAddress:()=>C6,formatShippingRateOptions:()=>h6,fetchById:()=>f6,fetchAll:()=>k6,destroyByZone:()=>E6,destroyByMethod:()=>P6,destroy:()=>w6,bulkUpdate:()=>n6,bulkStore:()=>l6,bulkDestroy:()=>U6,ShippingRateInputError:()=>k});import{db as E$}from"@stacksjs/database";async function w6(N){try{let $=await E$.deleteFrom("shipping_rates").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function U6(N){if(!N.length)return 0;try{let $=await E$.deleteFrom("shipping_rates").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function E6(N){try{let $=await E$.deleteFrom("shipping_rates").where("shipping_zone_id","=",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function P6(N){try{let $=await E$.deleteFrom("shipping_rates").where("shipping_method_id","=",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as v}from"@stacksjs/database";async function f6(N){let $=await v.selectFrom("shipping_rates").where("id","=",N).selectAll().executeTakeFirst();if($){let J=null,G=null;if($.shipping_zone_id)J=await v.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)G=await v.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:J,shipping_method:G}}return}async function k6(){let N=await v.selectFrom("shipping_rates").selectAll().execute();if(N.length===0)return[];let $=[...new Set(N.map((Y)=>Y.shipping_zone_id).filter((Y)=>Y!==null&&Y!==void 0))],J=[...new Set(N.map((Y)=>Y.shipping_method_id).filter((Y)=>Y!==null&&Y!==void 0))],[G,X]=await Promise.all([$.length?v.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],J.length?v.selectFrom("shipping_methods").where("id","in",J).selectAll().execute():[]]),L=G.reduce((Y,Z)=>{return Y[Z.id]=Z,Y},{}),W=X.reduce((Y,Z)=>{return Y[Z.id]=Z,Y},{});return N.map((Y)=>({...Y,shipping_zone:Y.shipping_zone_id?L[Y.shipping_zone_id]:[],shipping_method:Y.shipping_method_id?W[Y.shipping_method_id]:[]}))}async function j6(N){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",N).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function v1(N,$){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",N).where("weight_to",">=",N).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${J.message}`);throw J}}async function P$(N){if(!N?.countryCode)return null;try{let $=await v.selectFrom("shipping_zones").selectAll().where("countries","like",`%${N.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let J=null;for(let G of $){let X=1;if(N.region&&G.regions&&q6(G.regions,N.region))X=2;if(N.postalCode&&G.postal_codes&&q6(G.postal_codes,N.postalCode))X=3;if(!J||X>J.score)J={id:G.id,score:X}}return J?.id??null}catch{return null}}async function C6(N,$){let J=await P$($);if(J==null)return;return v1(N,J)}async function I6(N,$){return await P$($)===N}function q6(N,$){if(!N||!$)return!1;let J=$.trim().toUpperCase();for(let G of N.split(/[,|;]/))if(G.trim().toUpperCase()===J)return!0;return!1}async function h6(){try{return(await v.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping rate options: ${N.message}`);throw N}}async function g6(N){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",N).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:b6}=globalThis.Bun;import{db as y1}from"@stacksjs/database";import{db as f0}from"@stacksjs/database";async function v6(){return await f0.selectFrom("shipping_zones").selectAll().execute()}async function q$(N){return await f0.selectFrom("shipping_zones").where("id","=",N).selectAll().executeTakeFirst()}function y6(){try{return f0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping zone options: ${N.message}`);throw N}}async function D6(){try{return await f0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to get active shipping zones: ${N.message}`);throw N}}async function p6(N){try{return await f0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${N}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class k extends TypeError{constructor(N){super(N);this.name="ShippingRateInputError"}}function k0(N,$,J){return Number(N[J]??$?.[J])}async function N0(N,$){let J=k0(N,$,"shipping_method_id"),G=k0(N,$,"shipping_zone_id"),X=k0(N,$,"weight_from"),L=k0(N,$,"weight_to"),W=k0(N,$,"rate");if(!Number.isSafeInteger(J)||J<1)throw new k("Shipping method must be a positive integer.");if(!Number.isSafeInteger(G)||G<1)throw new k("Shipping zone must be a positive integer.");if(!Number.isFinite(X)||X<0)throw new k("Weight from must be a non-negative number.");if(!Number.isFinite(L)||L<X)throw new k("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(W)||W<0)throw new k("Rate must be a non-negative integer in minor currency units.");let[Y,Z]=await Promise.all([w$(J),q$(G)]);if(!Y)throw new k(`Shipping method ${J} was not found.`);if(!Z)throw new k(`Shipping zone ${G} was not found.`);if(Number(Z.shipping_method_id)!==J)throw new k(`Shipping zone ${G} is not assigned to shipping method ${J}.`)}async function m6(N){try{let $=n(N),J=Number($.shipping_method_id),G=Number($.shipping_zone_id);await N0($);let X=b6(),L={...$,shipping_method_id:J,shipping_zone_id:G,uuid:X};await y1.insertInto("shipping_rates").values(L).executeTakeFirst();let W=await y1.selectFrom("shipping_rates").where("uuid","=",X).selectAll().executeTakeFirst();if(!W)throw Error("Failed to resolve created shipping rate");return W}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function l6(N){if(!N.length)return 0;try{for(let G of N){let X=n(G);await N0(X)}let $=N.map((G)=>({...n(G),uuid:b6()})),J=await y1.insertInto("shipping_rates").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as j0}from"@stacksjs/database";import{formatDate as f$}from"@stacksjs/orm";async function c6(N,$){try{if(!N)throw Error("Shipping rate ID is required for update");let J=await j0.selectFrom("shipping_rates").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=n($);await N0(G,J);let X=await j0.updateTable("shipping_rates").set({...G,updated_at:f$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!X)return;return X}catch(J){if(J instanceof k)throw J;if(J instanceof Error)throw TypeError(`Failed to update shipping rate: ${J.message}`);throw J}}async function n6(N){if(!N.length)return 0;try{let $=0;for(let{id:J,data:G}of N){let X=await j0.updateTable("shipping_rates").set({...n(G),updated_at:f$(new Date)}).where("id","=",J).executeTakeFirst();if(F(X)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function u6(N,$){try{let J=await j0.updateTable("shipping_rates").set({...n($),updated_at:f$(new Date)}).where("shipping_zone_id","=",N).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${J.message}`);throw J}}async function i6(N,$){try{let J=await j0.updateTable("shipping_rates").set({...n($),updated_at:f$(new Date)}).where("shipping_method_id","=",N).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${J.message}`);throw J}}var h$={};B(h$,{updateStatus:()=>NG,updateRegionsAndPostalCodes:()=>GG,updateCountries:()=>JG,update:()=>$G,store:()=>t6,softDelete:()=>s6,getZonesByCountry:()=>p6,getActiveShippingZones:()=>D6,formatZoneOptions:()=>y6,fetchById:()=>q$,fetchAll:()=>v6,destroy:()=>o6,bulkStore:()=>r6,bulkSoftDelete:()=>a6,bulkDestroy:()=>d6});import{db as j$}from"@stacksjs/database";async function o6(N){try{let $=await j$.deleteFrom("shipping_zones").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function s6(N){try{let $=await j$.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function d6(N){if(!N.length)return 0;try{let $=await j$.deleteFrom("shipping_zones").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function a6(N){if(!N.length)return 0;try{let $=await j$.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:e6}=globalThis.Bun;import{db as D1}from"@stacksjs/database";async function t6(N){try{let $=e6(),J={...T0(N),uuid:$};await D1.insertInto("shipping_zones").values(J).executeTakeFirst();let G=await D1.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created shipping zone");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function r6(N){if(!N.length)return 0;try{let $=N.map((G)=>({...T0(G),uuid:e6()})),J=await D1.insertInto("shipping_zones").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as C$}from"@stacksjs/database";import{formatDate as I$}from"@stacksjs/orm";async function $G(N,$){try{if(!N)throw Error("Shipping zone ID is required for update");let J=await C$.updateTable("shipping_zones").set({...T0($),updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone: ${J.message}`);throw J}}async function NG(N,$){try{let J=await C$.updateTable("shipping_zones").set({status:$,updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping zone status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone status: ${J.message}`);throw J}}async function JG(N,$){try{let J=await C$.updateTable("shipping_zones").set({countries:$,updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping zone countries");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${J.message}`);throw J}}async function GG(N,$,J){try{let G={updated_at:I$(new Date)};if($!==void 0)G.regions=$;if(J!==void 0)G.postal_codes=J;let X=await C$.updateTable("shipping_zones").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update regions and postal codes");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${G.message}`);throw G}}var HX={digital:z$,drivers:A$,licenses:O$,methods:U$,rates:k$,routes:H$,zones:h$},VX=HX;var b1={};B(b1,{updateStatus:()=>VG,updateRate:()=>zG,updateDefaultStatus:()=>BG,update:()=>HG,store:()=>QG,fetchById:()=>ZG,fetchAll:()=>MG,destroy:()=>LG,bulkStore:()=>xG,bulkDestroy:()=>WG});import{db as XG}from"@stacksjs/database";async function LG(N){try{let $=await XG.deleteFrom("tax_rates").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function WG(N){if(!N.length)return 0;try{let $=await XG.deleteFrom("tax_rates").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as YG}from"@stacksjs/database";async function ZG(N){return await YG.selectFrom("tax_rates").where("id","=",N).selectAll().executeTakeFirst()}async function MG(){return await YG.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:FG}=globalThis.Bun;import{db as KG}from"@stacksjs/database";async function QG(N){try{return await KG.transaction(async($)=>{let J={...N,uuid:FG()};if(J.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let G=await $.insertInto("tax_rates").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create tax rate");return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function xG(N){if(!N.length)return 0;try{return await KG.transaction(async($)=>{let J=0;for(let G of N){let X={...G,uuid:FG()};if(X.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(X).executeTakeFirst())J++}return J})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as g$}from"@stacksjs/database";import{formatDate as v$}from"@stacksjs/orm";async function HG(N,$){try{if(!N)throw Error("Tax rate ID is required for update");return await g$.transaction(async(J)=>{let G=await J.selectFrom("tax_rates").select("is_default").where("id","=",N).executeTakeFirst();if(!G)return;let X=$.is_default??Boolean(G.is_default),L=v$(new Date);if(X)await J.updateTable("tax_rates").set({is_default:!1,updated_at:L}).where("id","!=",N).execute();let W=await J.updateTable("tax_rates").set({...$,updated_at:L}).where("id","=",N).returningAll().executeTakeFirst();if(!W)return;return W})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate: ${J.message}`);throw J}}async function VG(N,$){try{let J=await g$.updateTable("tax_rates").set({status:$,updated_at:v$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update tax rate status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate status: ${J.message}`);throw J}}async function zG(N,$){try{let J=await g$.updateTable("tax_rates").set({rate:$,updated_at:v$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update rate information");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update rate information: ${J.message}`);throw J}}async function BG(N,$){try{return await g$.transaction(async(J)=>{if(!await J.selectFrom("tax_rates").select("id").where("id","=",N).executeTakeFirst())return!1;let X=v$(new Date);if($)await J.updateTable("tax_rates").set({is_default:!1,updated_at:X}).where("id","!=",N).execute();return await J.updateTable("tax_rates").set({is_default:$,updated_at:X}).where("id","=",N).execute(),!0})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate default status: ${J.message}`);throw J}}var i1={};B(i1,{restaurant:()=>Q0,products:()=>D$,default:()=>UX});var D$={};B(D$,{updateStatus:()=>yG,updatePartySize:()=>DG,update:()=>y$,store:()=>gG,fetchWaiting:()=>qG,fetchPurchasedBetweenDates:()=>EG,fetchNotifiedBetweenDates:()=>UG,fetchCountByStatus:()=>fG,fetchCountBySource:()=>OG,fetchCountByQuantity:()=>TG,fetchCountByDateGrouped:()=>CG,fetchCountByDate:()=>SG,fetchCountByAllQuantities:()=>wG,fetchCountBetweenDates:()=>jG,fetchConversionRates:()=>kG,fetchCancelledBetweenDates:()=>PG,fetchById:()=>C0,fetchAll:()=>_G,destroy:()=>AG,bulkStore:()=>vG,bulkDestroy:()=>RG});import{db as m1}from"@stacksjs/database";async function AG(N){try{let $=await m1.selectFrom("waitlist_products").where("id","=",N).selectAll().executeTakeFirst();if(!$)return;return await m1.deleteFrom("waitlist_products").where("id","=",N).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function RG(N){if(!N.length)return 0;try{let $=await m1.deleteFrom("waitlist_products").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as U}from"@stacksjs/orm";async function C0(N){return await A.selectFrom("waitlist_products").where("id","=",N).selectAll().executeTakeFirst()}async function _G(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function OG(N,$){let J=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(N&&$){let X=U(N),L=U($);J=J.where("created_at",">=",X).where("created_at","<=",L)}return(await J.execute()).reduce((X,{source:L,count:W})=>{return X[L]=W,X},{})}async function SG(N=new Date){let $=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=U($),X=U(J);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function TG(N){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",N).executeTakeFirst())?.count??0}async function wG(N,$){let J=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(N&&$){let X=U(N),L=U($);J=J.where("created_at",">=",X).where("created_at","<=",L)}return(await J.execute()).reduce((X,{quantity:L,count:W})=>{return X[L]=W,X},{})}async function UG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",J).where("notified_at","<=",G).whereNotNull("notified_at").execute()}async function EG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",J).where("purchased_at","<=",G).whereNotNull("purchased_at").execute()}async function PG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",J).where("cancelled_at","<=",G).whereNotNull("cancelled_at").execute()}async function qG(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function fG(N,$,J){let G=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",N);if($&&J){let L=U($),W=U(J);G=G.where("created_at",">=",L).where("created_at","<=",W)}return(await G.executeTakeFirst())?.count??0}async function kG(N,$){let J=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(N&&$){let Z=U(N),M=U($);J=J.where("created_at",">=",Z).where("created_at","<=",M)}let G=await J.execute(),X=G.reduce((Z,{count:M})=>Z+M,0),L=G.find((Z)=>Z.status==="purchased")?.count??0,W=X>0?L/X*100:0,Y=G.reduce((Z,{status:M,count:K})=>{return Z[M]={count:K,percentage:X>0?K/X*100:0},Z},{});return{totalConversionRate:W,statusBreakdown:Y}}async function jG(N,$){let J=U(N),G=U($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",J).where("created_at","<=",G).executeTakeFirst())?.count??0}async function CG(N,$){let J=A.selectFrom("waitlist_products").select(["created_at"]);if(N&&$){let L=U(N),W=U($);J=J.where("created_at",">=",L).where("created_at","<=",W)}let X=(await J.execute()).reduce((L,{created_at:W})=>{let Y=(W||"").split("T")[0]||"unknown";return L[Y]=(L[Y]||0)+1,L},{});return Object.entries(X).map(([L,W])=>({date:L,count:W})).sort((L,W)=>L.date.localeCompare(W.date))}var{randomUUIDv7:hG}=globalThis.Bun;import{db as l1}from"@stacksjs/database";import{formatDate as IG}from"@stacksjs/orm";var zX={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function BX(N){return typeof N==="number"||N instanceof Date?IG(N):N}function I0(N,$={}){let J=Object.fromEntries(Object.entries(N).filter(([,X])=>X!==void 0));if(J.quantity===void 0&&J.party_size!==void 0)J.quantity=J.party_size;delete J.party_size;for(let X of["notified_at","purchased_at","cancelled_at"])if(J[X]!==void 0)J[X]=BX(J[X]);let G=zX[J.status];if(G&&J[G]===void 0&&!$[G])J[G]=IG(new Date);return J}async function gG(N){try{let $=hG(),J={...I0(N),uuid:$,status:N.status||"waiting"};await l1.insertInto("waitlist_products").values(J).executeTakeFirst();let G=await l1.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create waitlist product");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function vG(N){if(!N.length)return 0;try{let $=N.map((G)=>({...I0(G),status:G.status||"waiting",uuid:hG()})),J=await l1.insertInto("waitlist_products").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as AX}from"@stacksjs/database";import{formatDate as RX}from"@stacksjs/orm";async function y$(N,$){try{if(!N)throw Error("Waitlist product ID is required for update");let J=await C0(N);if(!J)return;await AX.updateTable("waitlist_products").set({...I0($,J),updated_at:RX(new Date)}).where("id","=",N).execute();let G=await C0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update waitlist product: ${J.message}`);throw J}}async function yG(N,$){return await y$(N,{status:$})}async function DG(N,$){return await y$(N,{quantity:$})}var Q0={};B(Q0,{updateWaitTimes:()=>F3,updateStatus:()=>Z3,updateQueuePosition:()=>K3,updatePartySize:()=>M3,update:()=>K0,store:()=>W3,fetchWaitingWithQuotedTimes:()=>eG,fetchWaitingWithPartySizes:()=>tG,fetchWaiting:()=>sG,fetchTimeSeriesStats:()=>X3,fetchTablesTurnedToday:()=>rG,fetchSeatingRate:()=>$3,fetchSeatedStats:()=>G3,fetchSeatedBetweenDates:()=>oG,fetchNoShowStats:()=>N3,fetchCurrentWaitTimes:()=>J3,fetchCountByTablePreference:()=>lG,fetchCountByPartySize:()=>nG,fetchCountByDate:()=>cG,fetchCountByAllPartySizes:()=>uG,fetchConversionRates:()=>dG,fetchById:()=>h0,fetchBetweenDates:()=>iG,fetchAverageWaitTimes:()=>aG,fetchAll:()=>mG,destroy:()=>pG,bulkStore:()=>Y3,bulkDestroy:()=>bG});import{db as c1}from"@stacksjs/database";async function pG(N){try{let $=await c1.selectFrom("waitlist_restaurants").where("id","=",N).selectAll().executeTakeFirst();if(!$)return;return await c1.deleteFrom("waitlist_restaurants").where("id","=",N).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function bG(N){if(!N.length)return 0;try{let $=await c1.deleteFrom("waitlist_restaurants").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as V}from"@stacksjs/database";import{formatDate as h}from"@stacksjs/orm";async function h0(N){return await V.selectFrom("waitlist_restaurants").where("id","=",N).selectAll().executeTakeFirst()}async function mG(){return await V.selectFrom("waitlist_restaurants").selectAll().execute()}async function lG(){return(await V.selectFrom("waitlist_restaurants").select(["table_preference",V.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:J,count:G})=>{return $[J]=G,$},{})}async function cG(N=new Date){let $=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=h($),X=h(J);return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function nG(N){return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("party_size","=",N).executeTakeFirst())?.count??0}async function uG(){return(await V.selectFrom("waitlist_restaurants").select(["party_size",V.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:J,count:G})=>{return $[J]=G,$},{})}async function iG(N,$){let J=h(N),G=h($);return await V.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",J).where("created_at","<=",G).execute()}async function oG(N,$){let J=h(N),G=h($);return await V.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",J).where("check_in_time","<=",G).where("status","=","seated").execute()}async function sG(){return await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function dG(){let N=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),$=N.reduce((L,{count:W})=>L+W,0),J=N.find((L)=>L.status==="seated")?.count??0,G=$>0?Number(J)/$*100:0,X=N.reduce((L,{status:W,count:Y})=>{return L[W]={count:Y,percentage:$>0?Y/$*100:0},L},{});return{totalConversionRate:G,statusBreakdown:X}}async function aG(){let N=await V.selectFrom("waitlist_restaurants").select([V.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),V.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:N?.avg_quoted_wait_time??0,averageActualWaitTime:N?.avg_actual_wait_time??0}}async function eG(){let N=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=N.reduce((G,X)=>G+(X.quoted_wait_time??0),0),J=N.length>0?$/N.length:0;return{entries:N,totalQuotedWaitTime:$,averageQuotedWaitTime:J}}async function tG(){let N=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=N.reduce((X,L)=>X+L.party_size,0),J=N.length>0?$/N.length:0,G=N.reduce((X,L)=>{return X[L.party_size]=(X[L.party_size]||0)+1,X},{});return{entries:N,totalPartySize:$,averagePartySize:J,partySizeBreakdown:G}}async function rG(){let N=new Date,$=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=h($),X=h(J),L=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",G).where("check_in_time","<=",X).execute(),W=L.length,Y=L.reduce((Q,x)=>Q+x.party_size,0),Z=W>0?Y/W:0,M=L.reduce((Q,x)=>{return Q[x.table_preference]=(Q[x.table_preference]||0)+1,Q},{}),K=L.reduce((Q,x)=>{return Q[x.party_size]=(Q[x.party_size]||0)+1,Q},{});return{totalTablesTurned:W,averagePartySize:Z,totalCustomersSeated:Y,breakdownByTablePreference:M,breakdownByPartySize:K}}async function $3(N,$){let J=h(N),G=h($),X=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).where("check_in_time",">=",J).where("check_in_time","<=",G).groupBy("status").execute(),L=X.reduce((M,{count:K})=>M+K,0),W=X.find((M)=>M.status==="seated")?.count??0,Y=L>0?Number(W)/L*100:0,Z=X.reduce((M,{status:K,count:Q})=>{return M[K]={count:Q,percentage:L>0?Q/L*100:0},M},{});return{totalEntries:L,seatedEntries:W,seatingRate:Y,statusBreakdown:Z}}async function N3(N,$){let J=h(N),G=h($),X=V.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",J).where("check_in_time","<=",G),L=await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("check_in_time",">=",J).where("check_in_time","<=",G).executeTakeFirst(),W=await X.execute(),Y=W.length,Z=L?.count&&L.count>0?Y/L.count*100:0,M=W.reduce((_,S)=>_+(S.quoted_wait_time??0),0),K=Y>0?M/Y:0,Q=W.reduce((_,S)=>_+S.party_size,0),x=Y>0?Q/Y:0,R=W.reduce((_,S)=>{return _[S.table_preference]=(_[S.table_preference]||0)+1,_},{}),O=W.reduce((_,S)=>{return _[S.party_size]=(_[S.party_size]||0)+1,_},{});return{totalNoShows:Y,noShowRate:Z,averageQuotedWaitTime:K,averagePartySize:x,breakdownByTablePreference:R,breakdownByPartySize:O}}async function J3(){let N=await V.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=N.reduce((X,L)=>X+(L.quoted_wait_time||0),0),J=N.reduce((X,L)=>X+(L.actual_wait_time||0),0),G=N.length;return{averageQuoted:G>0?$/G:0,averageActual:G>0?J/G:0}}async function G3(){let N=Date.now()-86400000,$=await V.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",N).execute(),J=Array.from({length:24},(G,X)=>({hour:X,count:$.filter((L)=>{return L.seated_at===X}).length}));return{total:$.length,byHour:J}}async function X3(){return(await V.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,J)=>{let G=J.created_at;if(!$[G])$[G]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[G].total++,$[G][J.status]++,$},{})}var{randomUUIDv7:L3}=globalThis.Bun;import{db as u1}from"@stacksjs/database";import{formatDate as n1}from"@stacksjs/orm";var _X={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function OX(N){if(typeof N==="number")return n1(N<=2147483647?N*1000:N);if(N instanceof Date)return n1(N);return N}function g0(N,$={}){let J=Object.fromEntries(Object.entries(N).filter(([,X])=>X!==void 0));for(let X of["check_in_time","seated_at","no_show_at","cancelled_at"])if(J[X]!==void 0)J[X]=OX(J[X]);let G=_X[J.status];if(G&&J[G]===void 0&&!$[G])J[G]=n1(new Date);return J}async function W3(N){try{let $=L3(),J={...g0(N),status:N.status||"waiting",uuid:$};await u1.insertInto("waitlist_restaurants").values(J).executeTakeFirst();let G=await u1.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create restaurant waitlist entry");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function Y3(N){if(!N.length)return 0;try{let $=N.map((G)=>({...g0(G),status:G.status||"waiting",uuid:L3()})),J=await u1.insertInto("waitlist_restaurants").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as SX}from"@stacksjs/database";import{formatDate as TX}from"@stacksjs/orm";async function K0(N,$){try{if(!N)throw Error("Restaurant waitlist entry ID is required for update");let J=await h0(N);if(!J)return;await SX.updateTable("waitlist_restaurants").set({...g0($,J),updated_at:TX(new Date)}).where("id","=",N).execute();let G=await h0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${J.message}`);throw J}}async function Z3(N,$){return await K0(N,{status:$})}async function M3(N,$){return await K0(N,{party_size:$})}async function F3(N,$,J){return await K0(N,{quoted_wait_time:$,...J===void 0?{}:{actual_wait_time:J}})}async function K3(N,$){return await K0(N,{queue_position:$})}var wX={products:D$,restaurant:Q0},UX=wX;var EX={coupons:p$,customers:b$,devices:u$,errors:s$,giftCards:a$,orders:Y1,payments:Z1,products:V1,receipts:O1,restaurant:Q0,shippings:p1,tax:b1,waitlists:i1},vK=EX;export{i1 as waitlists,b1 as tax,p1 as shippings,Q0 as restaurant,O1 as receipts,V1 as products,Z1 as payments,Y1 as orders,a$ as giftCards,s$ as errors,u$ as devices,vK as default,b$ as customers,p$ as coupons,EX as commerce};
|