@stacksjs/commerce 0.70.45 → 0.70.53
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/LICENSE.md +21 -0
- package/dist/index.js +13 -13
- package/dist/src/coupons/index.d.ts +2 -0
- package/dist/src/coupons/update.d.ts +36 -0
- package/dist/src/gift-cards/update.d.ts +13 -1
- package/dist/src/orders/events.d.ts +46 -0
- package/dist/src/orders/guards.d.ts +93 -0
- package/dist/src/orders/index.d.ts +55 -0
- package/dist/src/orders/place-order.d.ts +18 -0
- package/dist/src/orders/totals.d.ts +24 -0
- package/dist/src/orders/update.d.ts +2 -1
- package/dist/src/orders/webhook.d.ts +31 -0
- package/dist/src/products/items/update.d.ts +37 -0
- package/dist/src/shippings/shipping-rates/fetch.d.ts +63 -2
- package/dist/src/shippings/shipping-rates/index.d.ts +6 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var f1=Object.defineProperty;var v1=(G)=>G;function g1(G,x){this[G]=v1.bind(null,x)}var B=(G,x)=>{for(var J in x)f1(G,J,{get:x[J],enumerable:!0,configurable:!0,set:g1.bind(x,J)})};var XG={};B(XG,{update:()=>QJ,store:()=>NJ,getActiveCouponsMoMChange:()=>WJ,fetchTopRedeemedCoupons:()=>YJ,fetchStats:()=>$J,fetchRedemptionTrend:()=>ZJ,fetchRedemptionStats:()=>MJ,fetchCouponCountsByType:()=>LJ,fetchCouponCounts:()=>KJ,fetchConversionRate:()=>HJ,fetchById:()=>Xx,fetchByCode:()=>JJ,fetchAll:()=>GJ,fetchActive:()=>XJ,deleteExpiredCoupons:()=>rG,deleteCoupons:()=>tG,deleteCoupon:()=>aG});import{db as Jx}from"@stacksjs/database";import{formatDate as h1}from"@stacksjs/orm";async function aG(G){return!!await Jx.deleteFrom("coupons").where("id","=",G).executeTakeFirst()}async function tG(G){if(!G.length)return 0;return(await Jx.deleteFrom("coupons").where("id","in",G).execute()).length||0}async function rG(){let G=h1(new Date),x=await Jx.deleteFrom("coupons").where("end_date","<",G).executeTakeFirst();return Number(x?.numDeletedRows)||0}import{db as V}from"@stacksjs/database";import{extractDate as eG,formatDate as xJ}from"@stacksjs/orm";function Bx(G){let x={...G};if(x.endDate)x.endDate=eG(new Date(x.endDate));if(x.startDate)x.startDate=eG(new Date(x.startDate));if(x.isActive!==void 0)x.isActive=Boolean(x.isActive);return x}async function GJ(){return(await V.selectFrom("coupons").selectAll().execute()).map(Bx)}async function Xx(G){let x=await V.selectFrom("coupons").where("id","=",G).selectAll().executeTakeFirst();if(x)return Bx(x);return}async function JJ(G){let x=await V.selectFrom("coupons").where("code","=",G).selectAll().executeTakeFirst();if(x)return Bx(x);return}async function XJ(){let G=xJ(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).selectAll().execute()).map(Bx)}async function $J(){let G=await V.selectFrom("coupons").select((L)=>L.fn.count("id").as("count")).executeTakeFirst(),x=xJ(new Date),J=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",x).where("end_date",">=",x).select((L)=>L.fn.count("id").as("count")).executeTakeFirst(),X=await V.selectFrom("coupons").select(["discount_type",(L)=>L.fn.count("id").as("count")]).groupBy("discount_type").execute(),$=await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),K=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",x).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(G?.count||0),active:Number(J?.count||0),by_type:X,most_used:$,upcoming:K}}async function KJ(){let G=new Date,x=new Date(G);x.setDate(G.getDate()-7);let J=new Date(G);J.setMonth(G.getMonth()-1);let X=new Date(G);X.setFullYear(G.getFullYear()-1);let $=await Ax(null,null,G),K=await Ax(x,null,G),L=await Ax(J,null,G),M=await Ax(X,null,G);return{week:K,month:L,year:M,all_time:$}}async function Ax(G,x,J){let X=V.selectFrom("coupons");if(G)X=X.where("created_at",">=",G.toISOString());if(x)X=X.where("created_at","<=",x.toISOString());let $=await X.select((H)=>H.fn.count("id").as("count")).executeTakeFirst(),K=V.selectFrom("coupons");if(G)K=K.where("created_at",">=",G.toISOString());if(x)K=K.where("created_at","<=",x.toISOString());K=K.where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J);let L=await K.select((H)=>H.fn.count("id").as("count")).executeTakeFirst(),M=Number($?.count||0),Z=Number(L?.count||0),Y=M-Z;return{total:M,active:Z,inactive:Y}}async function LJ(){let G=new Date,x=await V.selectFrom("coupons").select("discount_type").distinct().execute(),J={};for(let{discount_type:X}of x){let $=await V.selectFrom("coupons").where("discount_type","=",X).select((Z)=>Z.fn.count("id").as("count")).executeTakeFirst(),K=await V.selectFrom("coupons").where("discount_type","=",X).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select((Z)=>Z.fn.count("id").as("count")).executeTakeFirst(),L=Number($?.count||0),M=Number(K?.count||0);J[X]={total:L,active:M,inactive:L-M}}return J}async function MJ(){let G=await V.selectFrom("coupons").select((H)=>H.fn.sum("usage_count").as("total")).executeTakeFirst(),x=new Date,J=new Date(x);J.setDate(x.getDate()-7);let X=new Date(x);X.setMonth(x.getMonth()-1);let $=new Date(x);$.setFullYear(x.getFullYear()-1);let K=await V.selectFrom("coupons").where("updated_at",">=",J.toISOString()).select((H)=>H.fn.sum("usage_count").as("total")).executeTakeFirst(),L=await V.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select((H)=>H.fn.sum("usage_count").as("total")).executeTakeFirst(),M=await V.selectFrom("coupons").where("updated_at",">=",$.toISOString()).select((H)=>H.fn.sum("usage_count").as("total")).executeTakeFirst(),Z=await V.selectFrom("coupons").select(["discount_type",(H)=>H.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),Y={};return Z.forEach((H)=>{Y[H.discount_type]=Number(H.total||0)}),{total:Number(G?.total||0),week:Number(K?.total||0),month:Number(L?.total||0),year:Number(M?.total||0),by_type:Y}}async function YJ(G=5){return await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(G).execute()}async function ZJ(G=30){let x=new Date().toISOString(),J=new Date;J.setDate(J.getDate()-G);let X=await V.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",J.toISOString()).where("updated_at","<=",x).where("usage_count",">",0).orderBy("updated_at","desc").execute(),$={};return X.forEach((K)=>{let L=K.updated_at?new Date(K.updated_at).toISOString().split("T")[0]:"unknown-date";if(!$[L])$[L]=0;$[L]+=K?.usage_count||0}),Object.entries($).map(([K,L])=>({date:K,count:L}))}async function HJ(){let G=new Date,x=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select((L)=>L.fn.count("id").as("count")).executeTakeFirst(),J=await V.selectFrom("coupons").where("usage_count",">",0).select((L)=>L.fn.count("id").as("count")).executeTakeFirst(),X=Number(x?.count||0),$=Number(J?.count||0);return{rate:X>0?$/X*100:0,total_active:X,total_redeemed:$}}async function WJ(){let G=new Date,x=new Date(G.getFullYear(),G.getMonth(),1),J=new Date(G.getFullYear(),G.getMonth()-1,1),X=new Date(G.getFullYear(),G.getMonth(),0),$=await V.selectFrom("coupons").select((H)=>H.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",x).executeTakeFirst(),K=await V.selectFrom("coupons").select((H)=>H.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",J).executeTakeFirst(),L=Number($?.count||0),M=Number(K?.count||0),Z=L-M,Y=M!==0?Z/M*100:L>0?100:0;return{current_month:L,previous_month:M,difference:Z,percentage_change:Y}}import{db as FJ}from"@stacksjs/database";async function NJ(G){try{let x=await FJ.insertInto("coupons").values(G).executeTakeFirst(),J=Number(x.insertId)||Number(x.numInsertedOrUpdatedRows);if(J)return await FJ.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();return}catch(x){if(x instanceof Error){if(x.message.includes("Duplicate entry")&&x.message.includes("code"))throw Error("A coupon with this code already exists");throw Error(`Failed to create coupon: ${x.message}`)}throw x}}import{db as y1}from"@stacksjs/database";import{formatDate as D1}from"@stacksjs/orm";async function QJ(G,x){if(!await Xx(G))throw Error(`Coupon with ID ${G} not found`);try{await y1.updateTable("coupons").set({...x,updated_at:D1(new Date)}).where("id","=",G).execute();let X=await Xx(G);if(X){let $=X;$.is_active=Boolean($.is_active)}return X}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("code"))throw Error("A coupon with this code already exists");throw Error(`Failed to update coupon: ${X.message}`)}throw X}}var KG={};B(KG,{update:()=>EJ,store:()=>OJ,fetchById:()=>a,fetchAll:()=>BJ,destroy:()=>VJ,bulkDestroy:()=>zJ});import{db as $G}from"@stacksjs/database";import{db as AJ}from"@stacksjs/database";async function a(G){return await AJ.selectFrom("customers").where("id","=",G).selectAll().executeTakeFirst()}async function BJ(){return await AJ.selectFrom("customers").selectAll().execute()}async function VJ(G){try{if(!await a(G))throw Error(`Customer with ID ${G} not found`);return(await $G.deleteFrom("customers").where("id","=",G).executeTakeFirst()).numDeletedRows>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete customer: ${x.message}`);throw x}}async function zJ(G){if(!G.length)return 0;try{let x=await $G.deleteFrom("customers").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)||0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${x.message}`);throw x}}import{db as p1}from"@stacksjs/database";async function OJ(G){try{let x={...G,avatar:G.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},J=await p1.insertInto("customers").values(x).executeTakeFirst();if(!J)throw Error("Failed to create customer");let X=J.insertId||Number(J.numInsertedOrUpdatedRows);return await a(Number(X))}catch(x){if(x instanceof Error){if(x.message.includes("Duplicate entry")&&x.message.includes("email"))throw Error("A customer with this email already exists");throw Error(`Failed to create customer: ${x.message}`)}throw x}}import{db as m1}from"@stacksjs/database";import{formatDate as b1}from"@stacksjs/orm";async function EJ(G,x){try{if(!G)throw Error("Customer ID is required for update");let J=await m1.updateTable("customers").set({...x,updated_at:b1(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update customer");return J}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry")&&J.message.includes("email"))throw Error("A customer with this email already exists");throw Error(`Failed to update customer: ${J.message}`)}throw J}}var ZG={};B(ZG,{updateStatus:()=>_J,updatePrintCount:()=>IJ,update:()=>CJ,storePrintDevicesExport:()=>SJ,store:()=>jJ,fetchById:()=>g,fetchAll:()=>Ox,exportPrintDevices:()=>Ex,downloadPrintDevices:()=>PJ,destroy:()=>UJ,bulkStore:()=>wJ,bulkDestroy:()=>qJ});import{db as RJ}from"@stacksjs/database";async function UJ(G){try{let x=await RJ.deleteFrom("print_devices").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete print device: ${x.message}`);throw x}}async function qJ(G){if(!G.length)return 0;try{let x=await RJ.deleteFrom("print_devices").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete print devices: ${x.message}`);throw x}}import{Buffer as Vx}from"buffer";import{readFile as a4,writeFile as l1}from"fs/promises";import{gzipSync as c1}from"zlib";var k=Object.assign((G)=>({csv:()=>k.generateCSV(G),excel:()=>k.generateExcel(G),store:async(x)=>{let X=x.slice(x.lastIndexOf("."))===".csv"?"csv":"excel",$=k.generate(G,{type:X});await k.store({content:$,type:X},x)},generateCSV:()=>k.generateCSV(G),generateExcel:()=>k.generateExcel(G)}),{generate:(G,x={type:"csv"})=>{let X={csv:k.generateCSV,excel:k.generateExcel}[x.type||"csv"];if(!X)throw Error(`Unsupported spreadsheet type: ${x.type}`);let $=X(G);if($ instanceof $x)return $.getContent();return $},create:(G,x={type:"csv"})=>({content:k.generate(G,x),type:x.type||"csv"}),generateCSV:(G)=>{let x=u1(G);return new $x(x,"csv")},generateExcel:(G)=>{let x=n1(G);return new $x(x,"excel")},store:async({content:G},x)=>{try{await l1(x,G)}catch(J){throw Error(`Failed to store spreadsheet: ${J.message}`)}},download:({content:G,type:x},J)=>{let X=x==="csv"?"text/csv":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",$=new Blob([G],{type:X});return new Response($,{headers:{"Content-Type":X,"Content-Disposition":`attachment; filename="${J}"`}})}});class $x{content;type;constructor(G,x){this.content=G;this.type=x}getContent(){return this.content}download(G){return k.download({content:this.content,type:this.type},G)}store(G){return k.store({content:this.content,type:this.type},G)}}function zx(G,x={type:"csv"}){let J=k.generate(G,x);return new $x(J,x.type||"csv")}function u1(G){return[G.headings,...G.data].map((J)=>J.map((X)=>{let $=String(X);if($.includes(",")||$.includes('"')||$.includes(`
|
|
3
|
-
`))return`"${
|
|
4
|
-
`)}function
|
|
2
|
+
var P9=Object.defineProperty;var S9=(J)=>J;function j9(J,G){this[J]=S9.bind(null,G)}var V=(J,G)=>{for(var X in G)P9(J,X,{get:G[X],enumerable:!0,configurable:!0,set:j9.bind(G,X)})};var zX=import.meta.require;var BJ={};V(BJ,{update:()=>mX,store:()=>yX,redeem:()=>bX,getActiveCouponsMoMChange:()=>vX,fetchTopRedeemedCoupons:()=>wX,fetchStats:()=>jX,fetchRedemptionTrend:()=>IX,fetchRedemptionStats:()=>CX,fetchCouponCountsByType:()=>_X,fetchCouponCounts:()=>kX,fetchConversionRate:()=>fX,fetchById:()=>c,fetchByCode:()=>PX,fetchAll:()=>qX,fetchActive:()=>SX,deleteExpiredCoupons:()=>RX,deleteCoupons:()=>OX,deleteCoupon:()=>EX});import{db as YG}from"@stacksjs/database";import{formatDate as k9}from"@stacksjs/orm";async function EX(J){return!!await YG.deleteFrom("coupons").where("id","=",J).executeTakeFirst()}async function OX(J){if(!J.length)return 0;return(await YG.deleteFrom("coupons").where("id","in",J).execute()).length||0}async function RX(){let J=k9(new Date),G=await YG.deleteFrom("coupons").where("end_date","<",J).executeTakeFirst();return Number(G?.numDeletedRows)||0}import{db as z}from"@stacksjs/database";import{extractDate as UX,formatDate as TX}from"@stacksjs/orm";function RG(J){let G={...J};if(G.endDate)G.endDate=UX(new Date(G.endDate));if(G.startDate)G.startDate=UX(new Date(G.startDate));if(G.isActive!==void 0)G.isActive=Boolean(G.isActive);return G}async function qX(){return(await z.selectFrom("coupons").selectAll().execute()).map(RG)}async function c(J){let G=await z.selectFrom("coupons").where("id","=",J).selectAll().executeTakeFirst();if(G)return RG(G);return}async function PX(J){let G=await z.selectFrom("coupons").where("code","=",J).selectAll().executeTakeFirst();if(G)return RG(G);return}async function SX(){let J=TX(new Date);return(await z.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).selectAll().execute()).map(RG)}async function jX(){let J=await z.selectFrom("coupons").select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),G=TX(new Date),X=await z.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),$=await z.selectFrom("coupons").select(["discount_type",(Y)=>Y.fn.count("id").as("count")]).groupBy("discount_type").execute(),K=await z.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),L=await z.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",G).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(J?.count||0),active:Number(X?.count||0),by_type:$,most_used:K,upcoming:L}}async function kX(){let J=new Date,G=new Date(J);G.setDate(J.getDate()-7);let X=new Date(J);X.setMonth(J.getMonth()-1);let $=new Date(J);$.setFullYear(J.getFullYear()-1);let K=await OG(null,null,J),L=await OG(G,null,J),Y=await OG(X,null,J),Z=await OG($,null,J);return{week:L,month:Y,year:Z,all_time:K}}async function OG(J,G,X){let $=z.selectFrom("coupons");if(J)$=$.where("created_at",">=",J.toISOString());if(G)$=$.where("created_at","<=",G.toISOString());let K=await $.select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),L=z.selectFrom("coupons");if(J)L=L.where("created_at",">=",J.toISOString());if(G)L=L.where("created_at","<=",G.toISOString());L=L.where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",X);let Y=await L.select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),Z=Number(K?.count||0),W=Number(Y?.count||0),M=Z-W;return{total:Z,active:W,inactive:M}}async function _X(){let J=new Date,G=await z.selectFrom("coupons").select("discount_type").distinct().execute(),X={};for(let{discount_type:$}of G){let K=await z.selectFrom("coupons").where("discount_type","=",$).select((W)=>W.fn.count("id").as("count")).executeTakeFirst(),L=await z.selectFrom("coupons").where("discount_type","=",$).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select((W)=>W.fn.count("id").as("count")).executeTakeFirst(),Y=Number(K?.count||0),Z=Number(L?.count||0);X[$]={total:Y,active:Z,inactive:Y-Z}}return X}async function CX(){let J=await z.selectFrom("coupons").select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),G=new Date,X=new Date(G);X.setDate(G.getDate()-7);let $=new Date(G);$.setMonth(G.getMonth()-1);let K=new Date(G);K.setFullYear(G.getFullYear()-1);let L=await z.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await z.selectFrom("coupons").where("updated_at",">=",$.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),Z=await z.selectFrom("coupons").where("updated_at",">=",K.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await z.selectFrom("coupons").select(["discount_type",(N)=>N.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),M={};return W.forEach((N)=>{M[N.discount_type]=Number(N.total||0)}),{total:Number(J?.total||0),week:Number(L?.total||0),month:Number(Y?.total||0),year:Number(Z?.total||0),by_type:M}}async function wX(J=5){return await z.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(J).execute()}async function IX(J=30){let G=new Date().toISOString(),X=new Date;X.setDate(X.getDate()-J);let $=await z.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",X.toISOString()).where("updated_at","<=",G).where("usage_count",">",0).orderBy("updated_at","desc").execute(),K={};return $.forEach((L)=>{let Y=L.updated_at?new Date(L.updated_at).toISOString().split("T")[0]:"unknown-date";if(!K[Y])K[Y]=0;K[Y]+=L?.usage_count||0}),Object.entries(K).map(([L,Y])=>({date:L,count:Y}))}async function fX(){let J=new Date,G=await z.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),X=await z.selectFrom("coupons").where("usage_count",">",0).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),$=Number(G?.count||0),K=Number(X?.count||0);return{rate:$>0?K/$*100:0,total_active:$,total_redeemed:K}}async function vX(){let J=new Date,G=new Date(J.getFullYear(),J.getMonth(),1),X=new Date(J.getFullYear(),J.getMonth()-1,1),$=new Date(J.getFullYear(),J.getMonth(),0),K=await z.selectFrom("coupons").select((N)=>N.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",G).executeTakeFirst(),L=await z.selectFrom("coupons").select((N)=>N.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",X).executeTakeFirst(),Y=Number(K?.count||0),Z=Number(L?.count||0),W=Y-Z,M=Z!==0?W/Z*100:Y>0?100:0;return{current_month:Y,previous_month:Z,difference:W,percentage_change:M}}import{db as gX}from"@stacksjs/database";import{HttpError as hX}from"@stacksjs/error-handling";import{isUniqueViolation as _9}from"@stacksjs/orm";async function yX(J){try{let G=await gX.insertInto("coupons").values(J).executeTakeFirst(),X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows);if(X)return await gX.selectFrom("coupons").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof hX)throw G;if(_9(G))throw new hX(409,"A coupon with this code already exists");if(G instanceof Error)throw Error(`Failed to create coupon: ${G.message}`);throw G}}import{db as VJ}from"@stacksjs/database";import{HttpError as DX}from"@stacksjs/error-handling";import{formatDate as pX,isUniqueViolation as C9}from"@stacksjs/orm";async function mX(J,G){if(!await c(J))throw Error(`Coupon with ID ${J} not found`);try{await VJ.updateTable("coupons").set({...G,updated_at:pX(new Date)}).where("id","=",J).execute();let $=await c(J);if($){let K=$;K.is_active=Boolean(K.is_active)}return $}catch($){if($ instanceof DX)throw $;if(C9($))throw new DX(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to update coupon: ${$.message}`);throw $}}async function bX(J){let G=pX(new Date),X=await VJ.updateTable("coupons").set({usage_count:VJ.raw("COALESCE(usage_count, 0) + 1"),updated_at:G}).where("id","=",J).where((Z)=>Z.or([Z("max_uses","is",null),Z.cmpr("usage_count","<",Z.ref("max_uses"))])).where("is_active","=",1).where((Z)=>Z.or([Z("start_date","is",null),Z.cmpr("start_date","<=",G)])).where((Z)=>Z.or([Z("end_date","is",null),Z.cmpr("end_date",">=",G)])).executeTakeFirst();if(Number(X?.numUpdatedRows??X?.affectedRows??0)>0){let Z=await c(J);if(Z){let W=Z;return W.is_active=Boolean(W.is_active),{ok:!0,coupon:Z}}return{ok:!1,reason:"not-found"}}let K=await c(J);if(!K)return{ok:!1,reason:"not-found"};if(!K.is_active)return{ok:!1,reason:"inactive"};let L=!K.start_date||K.start_date<=G,Y=!K.end_date||K.end_date>=G;if(!L||!Y)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var EJ={};V(EJ,{update:()=>dX,store:()=>iX,fetchById:()=>r,fetchAll:()=>cX,destroy:()=>uX,bulkDestroy:()=>nX});import{db as zJ}from"@stacksjs/database";import{db as lX}from"@stacksjs/database";async function r(J){return await lX.selectFrom("customers").where("id","=",J).selectAll().executeTakeFirst()}async function cX(){return await lX.selectFrom("customers").selectAll().execute()}async function uX(J){try{if(!await r(J))throw Error(`Customer with ID ${J} not found`);return(await zJ.deleteFrom("customers").where("id","=",J).executeTakeFirst()).numDeletedRows>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete customer: ${G.message}`);throw G}}async function nX(J){if(!J.length)return 0;try{let G=await zJ.deleteFrom("customers").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)||0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${G.message}`);throw G}}import{db as w9}from"@stacksjs/database";import{HttpError as oX}from"@stacksjs/error-handling";import{isUniqueViolation as I9}from"@stacksjs/orm";async function iX(J){try{let G={...J,avatar:J.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},X=await w9.insertInto("customers").values(G).executeTakeFirst();if(!X)throw Error("Failed to create customer");let $=X.insertId||Number(X.numInsertedOrUpdatedRows);return await r(Number($))}catch(G){if(G instanceof oX)throw G;if(I9(G))throw new oX(409,"A customer with this email already exists");if(G instanceof Error)throw Error(`Failed to create customer: ${G.message}`);throw G}}import{db as f9}from"@stacksjs/database";import{HttpError as sX}from"@stacksjs/error-handling";import{formatDate as v9,isUniqueViolation as g9}from"@stacksjs/orm";async function dX(J,G){try{if(!J)throw Error("Customer ID is required for update");let X=await f9.updateTable("customers").set({...G,updated_at:v9(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update customer");return X}catch(X){if(X instanceof sX)throw X;if(g9(X))throw new sX(409,"A customer with this email already exists");if(X instanceof Error)throw Error(`Failed to update customer: ${X.message}`);throw X}}var TJ={};V(TJ,{updateStatus:()=>Y6,updatePrintCount:()=>Z6,update:()=>L6,storePrintDevicesExport:()=>J6,store:()=>$6,fetchById:()=>g,fetchAll:()=>qG,exportPrintDevices:()=>PG,downloadPrintDevices:()=>G6,destroy:()=>tX,bulkStore:()=>K6,bulkDestroy:()=>rX});import{db as aX}from"@stacksjs/database";async function tX(J){try{let G=await aX.deleteFrom("print_devices").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete print device: ${G.message}`);throw G}}async function rX(J){if(!J.length)return 0;try{let G=await aX.deleteFrom("print_devices").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete print devices: ${G.message}`);throw G}}import{Buffer as UG}from"buffer";import{readFile as ZL,writeFile as h9}from"fs/promises";import{gzipSync as y9}from"zlib";var j=Object.assign((J)=>({csv:()=>j.generateCSV(J),excel:()=>j.generateExcel(J),store:async(G)=>{let $=G.slice(G.lastIndexOf("."))===".csv"?"csv":"excel",K=j.generate(J,{type:$});await j.store({content:K,type:$},G)},generateCSV:()=>j.generateCSV(J),generateExcel:()=>j.generateExcel(J)}),{generate:(J,G={type:"csv"})=>{let $={csv:j.generateCSV,excel:j.generateExcel}[G.type||"csv"];if(!$)throw Error(`Unsupported spreadsheet type: ${G.type}`);let K=$(J);if(K instanceof ZG)return K.getContent();return K},create:(J,G={type:"csv"})=>({content:j.generate(J,G),type:G.type||"csv"}),generateCSV:(J)=>{let G=D9(J);return new ZG(G,"csv")},generateExcel:(J)=>{let G=p9(J);return new ZG(G,"excel")},store:async({content:J},G)=>{try{await h9(G,J)}catch(X){throw Error(`Failed to store spreadsheet: ${X.message}`)}},download:({content:J,type:G},X)=>{let $=G==="csv"?"text/csv":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",K=new Blob([J],{type:$});return new Response(K,{headers:{"Content-Type":$,"Content-Disposition":`attachment; filename="${X}"`}})}});class ZG{content;type;constructor(J,G){this.content=J;this.type=G}getContent(){return this.content}download(J){return j.download({content:this.content,type:this.type},J)}store(J){return j.store({content:this.content,type:this.type},J)}}function TG(J,G={type:"csv"}){let X=j.generate(J,G);return new ZG(X,G.type||"csv")}function D9(J){return[J.headings,...J.data].map((X)=>X.map(($)=>{let K=String($);if(K.includes(",")||K.includes('"')||K.includes(`
|
|
3
|
+
`))return`"${K.replace(/"/g,'""')}"`;return K}).join(",")).join(`
|
|
4
|
+
`)}function p9(J){let G=new Uint8Array(UG.from(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
5
5
|
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
|
6
6
|
<sheets>
|
|
7
7
|
<sheet name="Sheet1" sheetId="1" r:id="rId1"/>
|
|
8
8
|
</sheets>
|
|
9
|
-
</workbook>`)),
|
|
9
|
+
</workbook>`)),X=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
10
10
|
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
|
11
11
|
<sheetData>
|
|
12
|
-
${[
|
|
13
|
-
<row r="${
|
|
14
|
-
${F.map((A,
|
|
15
|
-
<c r="${String.fromCharCode(65+
|
|
12
|
+
${[J.headings,...J.data].map((F,x)=>`
|
|
13
|
+
<row r="${x+1}">
|
|
14
|
+
${F.map((A,Q)=>`
|
|
15
|
+
<c r="${String.fromCharCode(65+Q)}${x+1}" ${typeof A==="number"?'t="n"':""}>
|
|
16
16
|
<v>${typeof A==="string"?A.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"):A}</v>
|
|
17
17
|
</c>`).join("")}
|
|
18
18
|
</row>`).join("")}
|
|
19
19
|
</sheetData>
|
|
20
|
-
</worksheet
|
|
20
|
+
</worksheet>`,$=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
21
21
|
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
|
22
22
|
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
|
23
23
|
<Default Extension="xml" ContentType="application/xml"/>
|
|
24
24
|
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
|
|
25
25
|
<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
|
|
26
|
-
</Types
|
|
26
|
+
</Types>`,K=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
27
27
|
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
|
28
28
|
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
|
|
29
|
-
</Relationships>`,
|
|
29
|
+
</Relationships>`,L=[{name:"[Content_Types].xml",content:new Uint8Array(UG.from(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
30
30
|
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
|
31
31
|
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
|
32
32
|
<Default Extension="xml" ContentType="application/xml"/>
|
|
33
33
|
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
|
|
34
34
|
<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
|
|
35
|
-
</Types>`))},{name:"_rels/.rels",content:new Uint8Array(
|
|
35
|
+
</Types>`))},{name:"_rels/.rels",content:new Uint8Array(UG.from(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
36
36
|
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
|
37
37
|
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
|
|
38
|
-
</Relationships>`))},{name:"xl/workbook.xml",content:x},{name:"xl/worksheets/sheet1.xml",content:new Uint8Array(Vx.from(J))}],L=K.map((F)=>{let Q=new Uint8Array(c1(F.content)),A=new Uint8Array(30+F.name.length),N=new DataView(A.buffer);N.setUint32(0,67324752,!0),N.setUint32(4,8,!0),N.setUint32(18,Q.length,!0),N.setUint32(22,F.content.length,!0),N.setUint16(26,F.name.length,!0);let z=new TextEncoder;return A.set(z.encode(F.name),30),{header:A,compressedContent:Q}}),M=K.map((F,Q)=>{let A=new Uint8Array(46+F.name.length),N=new DataView(A.buffer);N.setUint32(0,33639248,!0),N.setUint16(4,20,!0),N.setUint16(6,8,!0),N.setUint32(8,8,!0),N.setUint32(20,L[Q].compressedContent.length-30-F.name.length,!0),N.setUint32(42,L.slice(0,Q).reduce((C,I)=>C+I.header.length+I.compressedContent.length,0),!0),N.setUint16(28,F.name.length,!0);let z=new TextEncoder;return A.set(z.encode(F.name),46),A}),Z=new Uint8Array(22),Y=L.reduce((F,{header:Q,compressedContent:A})=>F+Q.length+A.length,0)+M.reduce((F,Q)=>F+Q.length,0)+Z.length,H=new Uint8Array(Y),W=0;for(let{header:F,compressedContent:Q}of L)H.set(F,W),W+=F.length,H.set(Q,W),W+=Q.length;for(let F of M)H.set(F,W),W+=F.length;return H.set(Z,W),H}import{db as TJ}from"@stacksjs/database";async function g(G){return await TJ.selectFrom("print_devices").where("id","=",G).selectAll().executeTakeFirst()}async function Ox(){return await TJ.selectFrom("print_devices").selectAll().execute()}async function Ex(G="csv"){let x=await Ox(),J=o1(x);return zx(J,{type:G})}function o1(G){let x=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],J=G.map((X)=>{return[X.id,X.name,X.macAddress,X.location,X.terminal,X.status,new Date(X.lastPing).toLocaleString(),X.printCount]});return{headings:x,data:J}}async function PJ(G="csv",x){let J=await Ex(G),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;return J.download(x||X)}async function SJ(G="csv",x){let J=await Ex(G),X=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;J.store(x||X)}var{randomUUIDv7:kJ}=globalThis.Bun;import{db as LG}from"@stacksjs/database";async function jJ(G){try{let x={...G,uuid:kJ()},J=await LG.insertInto("print_devices").values(x).executeTakeFirst(),X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows);return await LG.selectFrom("print_devices").where("id","=",X).selectAll().executeTakeFirst()}catch(x){if(x instanceof Error)throw TypeError(`Failed to create print device: ${x.message}`);throw x}}async function wJ(G){if(!G.length)return 0;let x=0;try{for(let J of G){let X={...J,uuid:kJ()};await LG.insertInto("print_devices").values(X).execute(),x++}return x}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${J.message}`);throw J}}import{db as MG}from"@stacksjs/database";import{formatDate as YG}from"@stacksjs/orm";async function CJ(G,x){if(!await g(G))throw Error(`Print device with ID ${G} not found`);try{return await MG.updateTable("print_devices").set({...x,updated_at:YG(new Date)}).where("id","=",G).execute(),await g(G)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device: ${X.message}`);throw X}}async function _J(G,x){if(!await g(G))throw Error(`Print device with ID ${G} not found`);try{return await MG.updateTable("print_devices").set({status:x,updated_at:YG(new Date)}).where("id","=",G).execute(),await g(G)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print device status: ${X.message}`);throw X}}async function IJ(G,x){if(!await g(G))throw Error(`Print device with ID ${G} not found`);try{return await MG.updateTable("print_devices").set({print_count:x,updated_at:YG(new Date)}).where("id","=",G).execute(),await g(G)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update print count: ${X.message}`);throw X}}var FG={};B(FG,{update:()=>bJ,unresolveGroup:()=>nJ,resolveGroup:()=>cJ,ignoreGroup:()=>uJ,fetchTimeline:()=>mJ,fetchStats:()=>pJ,fetchGrouped:()=>yJ,fetchById:()=>hJ,fetchByGroup:()=>DJ,fetchAll:()=>Ux,destroyGroup:()=>gJ,destroy:()=>fJ,bulkUpdateStatus:()=>lJ,bulkDestroy:()=>vJ});import{db as HG}from"@stacksjs/database";import{log as WG}from"@stacksjs/logging";async function fJ(G){try{return await HG.deleteFrom("errors").where("id","=",G).execute(),!0}catch(x){return WG.error("[commerce/errors] destroy failed",{id:G,error:x}),!1}}async function vJ(G){try{return await HG.deleteFrom("errors").where("id","in",G).execute(),!0}catch(x){return WG.error("[commerce/errors] bulkDestroy failed",{count:G.length,error:x}),!1}}async function gJ(G,x){try{return await HG.deleteFrom("errors").where("type","=",G).where("message","=",x).execute(),!0}catch(J){return WG.error("[commerce/errors] destroyGroup failed",{type:G,message:x,error:J}),!1}}import{db as Rx}from"@stacksjs/database";async function hJ(G){return await Rx.selectFrom("errors").where("id","=",G).selectAll().executeTakeFirst()}async function Ux(){return await Rx.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function yJ(){let G=await Rx.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),x=new Map;for(let X of G){let $=`${X.type}:${X.message}`;if(!x.has($))x.set($,{errors:[],firstSeen:new Date(X.created_at),lastSeen:new Date(X.created_at)});let K=x.get($);K.errors.push(X);let L=new Date(X.created_at);if(L<K.firstSeen)K.firstSeen=L;if(L>K.lastSeen)K.lastSeen=L}let J=[];for(let[X,$]of x){let K=$.errors[0],L=$.errors.find((Z)=>Z.status!==null)?.status,M="unresolved";if(L===1)M="resolved";else if(L===2)M="ignored";J.push({id:K.id,type:K.type,message:K.message,stack:K.stack,status:M,count:$.errors.length,first_seen:$.firstSeen.toISOString(),last_seen:$.lastSeen.toISOString(),error_ids:$.errors.map((Z)=>Z.id)})}return J.sort((X,$)=>new Date($.last_seen).getTime()-new Date(X.last_seen).getTime()),J}async function DJ(G,x){return await Rx.selectFrom("errors").where("type","=",G).where("message","=",x).selectAll().orderBy("created_at","desc").execute()}async function pJ(){let G=await Ux(),x=new Date,J=new Date(x.getTime()-86400000),X=new Date(x.getTime()-172800000),$=G.filter((M)=>new Date(M.created_at)>=J).length,K=G.filter((M)=>{let Z=new Date(M.created_at);return Z>=X&&Z<J}).length,L=K===0?$>0?100:0:Math.round(($-K)/K*100);return{total:G.length,unresolved:G.filter((M)=>M.status===null||M.status===0).length,resolved:G.filter((M)=>M.status===1).length,ignored:G.filter((M)=>M.status===2).length,last_24h:$,trend:L}}async function mJ(){let G=await Ux(),x=new Date,J=[];for(let X=23;X>=0;X--){let $=new Date(x.getTime()-X*60*60*1000);$.setMinutes(0,0,0);let K=new Date($.getTime()+3600000),L=G.filter((M)=>{let Z=new Date(M.created_at);return Z>=$&&Z<K}).length;J.push({hour:$.toISOString(),count:L})}return J}import{db as Kx}from"@stacksjs/database";import{sql as Lx}from"@stacksjs/database";import{log as Mx}from"@stacksjs/logging";async function bJ(G,x){try{return await Kx.updateTable("errors").set({...x,updated_at:Lx.raw("CURRENT_TIMESTAMP")}).where("id","=",G).execute(),!0}catch(J){return Mx.error("[commerce/errors] update failed",{id:G,error:J}),!1}}async function lJ(G,x){try{return await Kx.updateTable("errors").set({status:x,updated_at:Lx.raw("CURRENT_TIMESTAMP")}).where("id","in",G).execute(),!0}catch(J){return Mx.error("[commerce/errors] bulkUpdateStatus failed",{count:G.length,status:x,error:J}),!1}}async function cJ(G,x){try{return await Kx.updateTable("errors").set({status:1,updated_at:Lx.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",x).execute(),!0}catch(J){return Mx.error("[commerce/errors] resolveGroup failed",{type:G,message:x,error:J}),!1}}async function uJ(G,x){try{return await Kx.updateTable("errors").set({status:2,updated_at:Lx.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",x).execute(),!0}catch(J){return Mx.error("[commerce/errors] ignoreGroup failed",{type:G,message:x,error:J}),!1}}async function nJ(G,x){try{return await Kx.updateTable("errors").set({status:0,updated_at:Lx.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",x).execute(),!0}catch(J){return Mx.error("[commerce/errors] unresolveGroup failed",{type:G,message:x,error:J}),!1}}var VG={};B(VG,{updateBalance:()=>LX,update:()=>KX,store:()=>XX,fetchTotalValue:()=>rJ,fetchTotalCurrentBalance:()=>eJ,fetchStats:()=>sJ,fetchById:()=>h,fetchByCode:()=>QG,fetchAll:()=>oJ,fetchActive:()=>iJ,destroy:()=>xX,compareActiveGiftCards:()=>aJ,checkBalance:()=>dJ,calculateGiftCardValues:()=>tJ,bulkDestroy:()=>GX});import{db as AG}from"@stacksjs/database";import{formatDate as y2}from"@stacksjs/orm";import{db as j,sql as NG}from"@stacksjs/database";import{formatDate as m,toTimestamp as t}from"@stacksjs/orm";import{db as i1}from"@stacksjs/database";async function p(G,x,J){let X=i1.selectFrom(G);if(J)X=J(X);X=X.select((L)=>Object.entries(x).map(([M,Z])=>{let Y=Z.column??"id",H=L.fn[Z.kind](Y);if(Z.filter){let W=Z.filter;H=H.filterWhere(W.column,W.op,W.value)}return H.as(M)}));let $=await X.executeTakeFirst(),K={};for(let L of Object.keys(x)){let M=$?.[L];K[L]=typeof M==="number"?M:Number(M??0)||0}return K}async function oJ(){return await j.selectFrom("gift_cards").selectAll().execute()}async function h(G){return await j.selectFrom("gift_cards").where("id","=",G).selectAll().executeTakeFirst()}async function QG(G){return await j.selectFrom("gift_cards").where("code","=",G).selectAll().executeTakeFirst()}async function iJ(){return await j.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function sJ(){let{count:G}=await p("gift_cards",{count:{kind:"count"}}),x=t(new Date),J=await j.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where((H)=>H.or([H("expiry_date",">=",x),H("expiry_date","is",null)])).select((H)=>H.fn.count("id").as("count")).executeTakeFirst(),X=await j.selectFrom("gift_cards").select(["status",(H)=>H.fn.count("id").as("count")]).groupBy("status").execute(),{count:$}=await p("gift_cards",{count:{kind:"count"}},(H)=>H.where((W)=>NG`${W.ref("current_balance")} / ${W.ref("initial_balance")} < 0.25`)),{count:K}=await p("gift_cards",{count:{kind:"count"}},(H)=>H.where((W)=>NG`${W.ref("current_balance")} / ${W.ref("initial_balance")} >= 0.25 AND ${W.ref("current_balance")} / ${W.ref("initial_balance")} <= 0.75`)),{count:L}=await p("gift_cards",{count:{kind:"count"}},(H)=>H.where((W)=>NG`${W.ref("current_balance")} / ${W.ref("initial_balance")} > 0.75`)),M=new Date;M.setDate(M.getDate()+30);let Z=await j.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",t(M)).where("expiry_date",">=",x).selectAll().limit(5).execute(),Y=await j.selectFrom("gift_cards").where("last_used_date","is not",null).selectAll().limit(5).execute();return{total:G,active:Number(J?.count||0),by_status:X.map((H)=>({status:H.status,count:Number(H.count)})),by_balance:{low:$,medium:K,high:L},expiring_soon:Z,recently_used:Y}}async function dJ(G){let x=await QG(G);if(!x)return{valid:!1,message:"Gift card not found"};if(!x.isActive||x.status!=="ACTIVE")return{valid:!1,balance:x.currentBalance,currency:x.currency,message:`Gift card is ${x.status.toLowerCase()}`};if(x.expiryDate){if(new Date(x.expiryDate)<new Date)return{valid:!1,balance:x.currentBalance,currency:x.currency,message:"Gift card has expired"}}return{valid:!0,balance:x.currentBalance,currency:x.currency}}async function aJ(G=30){let x=new Date,J=new Date(x);J.setDate(x.getDate()-G);let X=new Date(J);X.setDate(X.getDate()-1);let $=new Date(X);$.setDate(X.getDate()-G);let K=await j.selectFrom("gift_cards").select((W)=>W.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").where((W)=>W.or([W("expiry_date",">=",t(x)),W("expiry_date","is",null)])).where("created_at",">=",m(J)).where("created_at","<=",m(x)).executeTakeFirst(),L=await j.selectFrom("gift_cards").select((W)=>W.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").where((W)=>W.or([W("expiry_date",">=",t($)),W("expiry_date","is",null)])).where("created_at",">=",m($)).where("created_at","<=",m(X)).executeTakeFirst(),M=Number(K?.count||0),Z=Number(L?.count||0),Y=M-Z,H=Z!==0?Y/Z*100:M>0?100:0;return{current_period:M,previous_period:Z,difference:Y,percentage_change:H,days_range:G}}async function tJ(G=30){let x=new Date,J=new Date(x);J.setDate(x.getDate()-G);let X=new Date(J);X.setDate(X.getDate()-1);let $=new Date(X);$.setDate(X.getDate()-G);let K=await j.selectFrom("gift_cards").select((P)=>[P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").where((P)=>P.or([P("expiry_date",">=",t(x)),P("expiry_date","is",null)])).where("created_at",">=",m(J)).where("created_at","<=",m(x)).executeTakeFirst(),L=await j.selectFrom("gift_cards").select((P)=>[P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").where((P)=>P.or([P("expiry_date",">=",t($)),P("expiry_date","is",null)])).where("created_at",">=",m($)).where("created_at","<=",m(X)).executeTakeFirst(),M=Number(K?.total_initial||0),Z=Number(K?.total_balance||0),Y=Number(K?.card_count||0),H=Number(L?.total_initial||0),W=Number(L?.total_balance||0),F=Number(L?.card_count||0),Q=M>0?(M-Z)/M*100:0,A=H>0?(H-W)/H*100:0,N=Y>0?M/Y:0,z=Y>0?Z/Y:0,C=M-H,I=Z-W,l=Y-F,d=H!==0?C/H*100:M>0?100:0,R=W!==0?I/W*100:Z>0?100:0,v=F!==0?l/F*100:Y>0?100:0;return{current_period:{total_initial_value:M,total_remaining_balance:Z,utilization_rate:Q,card_count:Y,average_initial_value:N,average_remaining_balance:z},previous_period:{total_initial_value:H,total_remaining_balance:W,utilization_rate:A,card_count:F},comparison:{initial_value:{difference:C,percentage:Math.abs(d),is_increase:C>=0},balance:{difference:I,percentage:Math.abs(R),is_increase:I>=0},card_count:{difference:l,percentage:Math.abs(v),is_increase:l>=0}},days_range:G}}async function rJ(){let{total_value:G}=await p("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:G}}async function eJ(){let{total_balance:G}=await p("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:G}}async function xX(G){if(!await h(G))throw Error(`Gift card with ID ${G} not found`);return!!await AG.deleteFrom("gift_cards").where("id","=",G).executeTakeFirst()}async function GX(G){if(!G.length)return 0;let x=await AG.deleteFrom("gift_cards").where("id","in",G).executeTakeFirst();return Number(x?.numDeletedRows)||0}var{randomUUIDv7:s1}=globalThis.Bun;import{db as JX}from"@stacksjs/database";async function XX(G){let x=G,J={...G,current_balance:x.current_balance??x.initial_balance,status:G.status||"ACTIVE",is_active:x.is_active??!0,uuid:s1()};try{let X=await JX.insertInto("gift_cards").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if($)return await JX.selectFrom("gift_cards").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("code"))throw Error("A gift card with this code already exists");throw Error(`Failed to create gift card: ${X.message}`)}throw X}}import{db as $X}from"@stacksjs/database";import{formatDate as BG}from"@stacksjs/orm";async function KX(G,x){if(!await h(G))throw Error(`Gift card with ID ${G} not found`);try{return await $X.updateTable("gift_cards").set({...x,updated_at:BG(new Date)}).where("id","=",G).execute(),await h(G)}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("code"))throw Error("A gift card with this code already exists");throw Error(`Failed to update gift card: ${X.message}`)}throw X}}async function LX(G,x){let J=await h(G);if(!J)throw Error(`Gift card with ID ${G} not found`);if(!J.is_active||J.status!=="ACTIVE")throw Error("Gift card is not active");let X=J.current_balance+x;if(X<0)throw Error("Insufficient gift card balance");try{return await $X.updateTable("gift_cards").set({current_balance:X,last_used_date:BG(new Date),status:X===0?"USED":"ACTIVE",updated_at:BG(new Date)}).where("id","=",G).execute(),await h(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update gift card balance: ${$.message}`);throw $}}var EG={};B(EG,{updateStatus:()=>qX,updateDeliveryInfo:()=>TX,update:()=>UX,storeOrdersExport:()=>NX,store:()=>RX,softDelete:()=>YX,fetchStats:()=>AX,fetchDailyOrderTrends:()=>zX,fetchById:()=>y,fetchAll:()=>QX,exportOrders:()=>Tx,downloadOrders:()=>FX,destroy:()=>MX,compareOrdersByPeriod:()=>BX,calculateOrderMetrics:()=>VX,bulkSoftDelete:()=>HX,bulkDestroy:()=>ZX});import{db as qx}from"@stacksjs/database";async function MX(G){try{let x=await qx.deleteFrom("orders").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete order: ${x.message}`);throw x}}async function YX(G){try{let x=await qx.updateTable("orders").set({status:"CANCELED"}).where("id","=",G).executeTakeFirst();return Number(x.numUpdatedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to soft delete order: ${x.message}`);throw x}}async function ZX(G){if(!G.length)return 0;try{let x=await qx.deleteFrom("orders").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete orders: ${x.message}`);throw x}}async function HX(G){if(!G.length)return 0;try{let x=await qx.updateTable("orders").set({status:"CANCELED"}).where("id","in",G).executeTakeFirst();return Number(x.numUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to soft delete orders: ${x.message}`);throw x}}import{db as WX}from"@stacksjs/database";async function Tx(G="csv"){let x=await d1(),J=a1(x);return zx(J,{type:G})}async function d1(){let G=await WX.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),x=G.map((K)=>K.id);if(x.length===0)return[];let X=(await WX.selectFrom("order_items").where("order_items.order_id","in",x).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((K,L)=>{if(!L.order_id)return K;if(!K[L.order_id])K[L.order_id]={totalItems:0,totalPrice:0};return K[L.order_id].totalItems+=L.quantity,K[L.order_id].totalPrice+=L.price*L.quantity,K},{});return G.map((K)=>{let L=X[K.id]||{totalItems:0,totalPrice:0};return{...K,totalItems:L.totalItems,totalPrice:L.totalPrice}})}function a1(G){let x=["Order ID","Customer","Date","Total","Status","Items"],J=G.map((X)=>{let $=X.order_items?.map((K)=>`${K.product?.name} (Qty: ${K.quantity}, Price: $${K.price})`).join(" | ")||"No Items";return[X.id,X.customer?.name||"N/A",X.created_at,X.total_amount,X.status,$]});return{headings:x,data:J}}async function FX(G="csv",x){let J=await Tx(G),X=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;return J.download(x||X)}async function NX(G="csv",x){let J=await Tx(G),X=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;J.store(x||X)}import{db as T}from"@stacksjs/database";async function QX(G){let x=T.selectFrom("orders").selectAll().orderBy("created_at","desc");if(G)x=x.limit(G);let J=await x.execute();return await Promise.all(J.map(async(X)=>{let $=await T.selectFrom("order_items").where("order_id","=",X.id).selectAll().execute();return{...X,items:$}}))}async function y(G){return await T.selectFrom("orders").where("id","=",G).selectAll().executeTakeFirst()}async function AX(){let G=await T.selectFrom("orders").select((L)=>L.fn.count("id").as("count")).executeTakeFirst(),x=await T.selectFrom("orders").select(["status",(L)=>L.fn.count("id").as("count")]).groupBy("status").execute(),J=await T.selectFrom("orders").select(["order_type",(L)=>L.fn.count("id").as("count")]).groupBy("order_type").execute(),X=await T.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),$=await Promise.all(X.map(async(L)=>{let M=await T.selectFrom("order_items").where("order_id","=",L.id).selectAll().execute();return{...L,items:M}})),K=await T.selectFrom("orders").select((L)=>L.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(G?.count||0),by_status:x,by_type:J,recent:$,revenue:Number(K?.total||0)}}async function BX(G=30){let x=new Date,J=new Date(x);J.setDate(x.getDate()-G);let X=new Date(J);X.setDate(X.getDate()-1);let $=new Date(X);$.setDate(X.getDate()-G);let K=await T.selectFrom("orders").select((W)=>W.fn.count("id").as("count")).where("created_at",">=",J.toISOString()).where("created_at","<=",x.toISOString()).executeTakeFirst(),L=await T.selectFrom("orders").select((W)=>W.fn.count("id").as("count")).where("created_at",">=",$.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),M=Number(K?.count||0),Z=Number(L?.count||0),Y=M-Z,H=Z!==0?Y/Z*100:M>0?100:0;return{current_period:M,previous_period:Z,difference:Y,percentage_change:H,days_range:G}}async function VX(G=30){let x=new Date,J=new Date(x);J.setDate(x.getDate()-G);let X=new Date(J);X.setDate(X.getDate()-1);let $=new Date(X);$.setDate(X.getDate()-G);let K=await T.selectFrom("orders").select((R)=>[R.fn.count("id").as("total_orders"),R.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",J.toISOString()).where("created_at","<=",x.toISOString()).executeTakeFirst(),L=await T.selectFrom("orders").select((R)=>[R.fn.count("id").as("total_orders"),R.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",$.toISOString()).where("created_at","<=",X.toISOString()).executeTakeFirst(),M=await T.selectFrom("orders").select(["status",(R)=>R.fn.count("id").as("count")]).where("created_at",">=",J.toISOString()).where("created_at","<=",x.toISOString()).groupBy("status").execute(),Z=await T.selectFrom("orders").select(["order_type",(R)=>R.fn.count("id").as("count")]).where("created_at",">=",J.toISOString()).where("created_at","<=",x.toISOString()).groupBy("order_type").execute(),Y=Number(K?.total_orders||0),H=Number(K?.total_revenue||0),W=Y>0?H/Y:0,F=Number(L?.total_orders||0),Q=Number(L?.total_revenue||0),A=F>0?Q/F:0,N=Y-F,z=H-Q,C=W-A,I=F!==0?N/F*100:Y>0?100:0,l=Q!==0?z/Q*100:H>0?100:0,d=A!==0?C/A*100:W>0?100:0;return{current_period:{total_orders:Y,total_revenue:H,average_order_value:W,orders_by_status:M.map((R)=>({status:R.status,count:Number(R.count)})),orders_by_type:Z.map((R)=>({order_type:R.order_type,count:Number(R.count)}))},previous_period:{total_orders:F,total_revenue:Q,average_order_value:A},comparison:{orders:{difference:N,percentage:Math.abs(I),is_increase:N>=0},revenue:{difference:z,percentage:Math.abs(l),is_increase:z>=0},average_order_value:{difference:C,percentage:Math.abs(d),is_increase:C>=0}},days_range:G}}async function zX(G=30){let x=new Date,J=new Date(x);J.setDate(x.getDate()-G);let X=await T.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",J.toISOString()).where("created_at","<=",x.toISOString()).orderBy("created_at","asc").execute(),$=new Map;for(let K of X){let L=(K.created_at||"").split("T")[0]||"unknown",M=$.get(L)||{order_count:0,revenue:0};M.order_count++,M.revenue+=Number(K.total_amount||0),$.set(L,M)}return Array.from($.entries()).map(([K,L])=>({date:K,order_count:L.order_count,revenue:L.revenue}))}var{randomUUIDv7:t1}=globalThis.Bun;import{db as OX}from"@stacksjs/database";import{formatDate as EX}from"@stacksjs/orm";async function RX(G){let x={...G,status:G.status||"PENDING",uuid:t1(),created_at:EX(new Date),updated_at:EX(new Date)};try{let J=await OX.insertInto("orders").values(x).executeTakeFirst(),X=Number(J?.insertId)||Number(J?.numInsertedOrUpdatedRows);if(X)return await OX.selectFrom("orders").where("id","=",X).selectAll().executeTakeFirst();return}catch(J){if(J instanceof Error)throw Error(`Failed to create order: ${J.message}`);throw J}}import{db as zG}from"@stacksjs/database";import{formatDate as OG}from"@stacksjs/orm";async function UX(G,x){if(!await y(G))throw Error(`Order with ID ${G} not found`);try{return await zG.updateTable("orders").set({...x,updated_at:OG(new Date)}).where("id","=",G).execute(),await y(G)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order: ${X.message}`);throw X}}async function qX(G,x){if(!await y(G))throw Error(`Order with ID ${G} not found`);try{return await zG.updateTable("orders").set({status:x,updated_at:OG(new Date)}).where("id","=",G).execute(),await y(G)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order status: ${X.message}`);throw X}}async function TX(G,x,J){let X=await y(G);if(!X)throw Error(`Order with ID ${G} not found`);let $={updated_at:OG(new Date)};if(x!==void 0)$.delivery_address=x;if(J!==void 0)$.estimated_delivery_time=J;if(Object.keys($).length===1)return X;try{return await zG.updateTable("orders").set($).where("id","=",G).execute(),await y(G)}catch(K){if(K instanceof Error)throw TypeError(`Failed to update delivery information: ${K.message}`);throw K}}var RG={};B(RG,{update:()=>vX,store:()=>fX,fetchPaymentStatsByMethod:()=>CX,fetchPaymentStats:()=>wX,fetchMonthlyPaymentTrends:()=>_X,fetchById:()=>Yx,fetchAll:()=>jX,destroy:()=>SX,bulkDestroy:()=>kX});import{db as PX}from"@stacksjs/database";async function SX(G){try{let x=await PX.deleteFrom("payments").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete payment: ${x.message}`);throw x}}async function kX(G){if(!G.length)return 0;try{let x=await PX.deleteFrom("payments").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete payments: ${x.message}`);throw x}}import{db as b}from"@stacksjs/database";import{formatDate as _}from"@stacksjs/orm";async function jX(){return await b.selectFrom("payments").selectAll().execute()}async function Yx(G){return await b.selectFrom("payments").selectAll().where("id","=",G).executeTakeFirst()}async function wX(G=30){let x=new Date,J=new Date(x);J.setDate(x.getDate()-G);let X=new Date(J);X.setDate(X.getDate()-1);let $=new Date(X);$.setDate(X.getDate()-G);let K=await b.selectFrom("payments").select((v)=>[v.fn.count("id").as("transaction_count"),v.fn.sum("amount").as("total_revenue")]).where("created_at",">=",_(J)).where("created_at","<=",_(x)).where("status","=","completed").executeTakeFirst(),L=await b.selectFrom("payments").select((v)=>[v.fn.count("id").as("transaction_count"),v.fn.sum("amount").as("total_revenue")]).where("created_at",">=",_($)).where("created_at","<=",_(X)).where("status","=","completed").executeTakeFirst(),M=await b.selectFrom("payments").select((v)=>v.fn.count("id").as("count")).where("created_at",">=",_(J)).where("created_at","<=",_(x)).executeTakeFirst(),Z=Number(K?.transaction_count||0),Y=Number(K?.total_revenue||0),H=Z>0?Y/Z:0,W=Number(L?.transaction_count||0),F=Number(L?.total_revenue||0),Q=W>0?F/W:0,A=Z-W,N=Y-F,z=H-Q,C=W>0?A/W*100:Z>0?100:0,I=F>0?N/F*100:Y>0?100:0,l=Q>0?z/Q*100:H>0?100:0,d=Number(M?.count||0),R=d>0?Z/d*100:0;return{total_transactions:Z,total_revenue:Y,average_transaction:H,successful_rate:R,comparison:{transactions:{difference:A,percentage:Math.abs(C),is_increase:A>=0},revenue:{difference:N,percentage:Math.abs(I),is_increase:N>=0},average:{difference:z,percentage:Math.abs(l),is_increase:z>=0}}}}async function CX(G=30){let x=new Date,J=new Date(x);J.setDate(x.getDate()-G);let X=await b.selectFrom("payments").select((M)=>[M.fn.count("id").as("total_count"),M.fn.sum("amount").as("total_revenue")]).where("created_at",">=",_(J)).where("created_at","<=",_(x)).where("status","=","completed").executeTakeFirst(),$=Number(X?.total_count||0),K=await b.selectFrom("payments").select(["method",(M)=>M.fn.count("id").as("count"),(M)=>M.fn.sum("amount").as("revenue")]).where("created_at",">=",_(J)).where("created_at","<=",_(x)).where("status","=","completed").groupBy("method").execute(),L={};return K.forEach((M)=>{let Z=Number(M.count||0),Y=Number(M.revenue||0),H=$>0?Z/$*100:0;L[M.method]={count:Z,revenue:Y,percentage_of_total:H}}),L}async function _X(){let G=new Date,x=new Date(G);x.setMonth(G.getMonth()-11),x.setDate(1);let J=await b.selectFrom("payments").selectAll().where("created_at",">=",_(x)).where("status","=","completed").execute(),X={};for(let K of J){let L=K.created_at?new Date(K.created_at):new Date,M=L.getFullYear(),Z=L.getMonth()+1,Y=`${M}-${String(Z).padStart(2,"0")}`;if(!X[Y])X[Y]={year:M,month:Z,transactions:0,revenue:0};X[Y].transactions++,X[Y].revenue+=Number(K.amount||0)}return Object.keys(X).sort().map((K)=>{let L=X[K],M=L.transactions,Z=L.revenue,Y=M>0?Z/M:0;return{month:new Date(L.year,L.month-1,1).toLocaleString("default",{month:"short"}),year:L.year,transactions:M,revenue:Z,average:Y}})}var{randomUUIDv7:r1}=globalThis.Bun;import{db as IX}from"@stacksjs/database";async function fX(G){let x={...G,status:G.status||"PENDING",currency:G.currency||"USD",uuid:r1()};try{let J=await IX.insertInto("payments").values(x).executeTakeFirst(),X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows);if(X)return await IX.selectFrom("payments").where("id","=",X).selectAll().executeTakeFirst();return}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry")&&J.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");if(J.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${J.message}`)}throw J}}import{db as e1}from"@stacksjs/database";import{formatDate as x4}from"@stacksjs/orm";async function vX(G,x){if(!await Yx(G))throw Error(`Payment with ID ${G} not found`);try{return await e1.updateTable("payments").set({...x,updated_at:x4(new Date)}).where("id","=",G).execute(),await Yx(G)}catch(X){if(X instanceof Error){if(X.message.includes("Duplicate entry")&&X.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${X.message}`)}throw X}}var wG={};B(wG,{variants:()=>_x,units:()=>Cx,reviews:()=>wx,manufacturers:()=>jx,items:()=>kx,default:()=>M4,categories:()=>Sx});var Sx={};B(Sx,{updateParent:()=>eX,updateDisplayOrder:()=>tX,updateActiveStatus:()=>rX,update:()=>aX,store:()=>qG,removeChildCategories:()=>nX,remove:()=>cX,findOrCreateByName:()=>dX,fetchStats:()=>mX,fetchRootCategories:()=>yX,fetchChildCategories:()=>DX,fetchCategoryTree:()=>lX,fetchByName:()=>gX,fetchById:()=>U,fetchByDisplayOrder:()=>pX,fetchAll:()=>UG,fetchActive:()=>hX,deactivateChildCategories:()=>iX,deactivate:()=>oX,compareCategoryGrowth:()=>bX,bulkRemove:()=>uX});import{db as c}from"@stacksjs/database";import{db as S}from"@stacksjs/database";import{formatDate as Zx}from"@stacksjs/orm";async function UG(){return await S.selectFrom("categories").selectAll().execute()}async function U(G){return await S.selectFrom("categories").where("id","=",G).selectAll().executeTakeFirst()}async function gX(G){return await S.selectFrom("categories").where("name","=",G).selectAll().executeTakeFirst()}async function hX(){return await S.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function yX(){return await S.selectFrom("categories").where("parent_category_id","is",null).where("is_active","=",!0).selectAll().execute()}async function DX(G){return await S.selectFrom("categories").where("parent_category_id","=",G).where("is_active","=",!0).selectAll().execute()}async function pX(G=!0){let x=S.selectFrom("categories").where("is_active","=",!0).selectAll();if(G)return await x.orderBy("display_order","asc").execute();else return await x.orderBy("display_order","desc").execute()}async function mX(){let G=await S.selectFrom("categories").select((Z)=>Z.fn.count("id").as("count")).executeTakeFirst(),x=await S.selectFrom("categories").where("is_active","=",!0).select((Z)=>Z.fn.count("id").as("count")).executeTakeFirst(),J=await S.selectFrom("categories").where("parent_category_id","is",null).select((Z)=>Z.fn.count("id").as("count")).executeTakeFirst(),X=await S.selectFrom("categories").where("image_url","is not",null).select((Z)=>Z.fn.count("id").as("count")).executeTakeFirst(),$=new Date;$.setDate($.getDate()-30);let K=Zx($),L=await S.selectFrom("categories").where("created_at",">=",K).selectAll().limit(5).execute(),M=await S.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",(Z)=>Z.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(G?.count||0),active:Number(x?.count||0),root_categories:Number(J?.count||0),child_categories:Number(G?.count||0)-Number(J?.count||0),with_images:Number(X?.count||0),recently_added:L,top_parent_categories:M.map((Z)=>({id:String(Z.parent_category_id||""),name:String(Z.parent_name||""),child_count:Number(Z.child_count)}))}}async function bX(G=30){let x=new Date,J=Zx(x),X=new Date;X.setDate(x.getDate()-G);let $=Zx(X),K=new Date(X);K.setDate(K.getDate()-1);let L=Zx(K),M=new Date(K);M.setDate(K.getDate()-G);let Z=Zx(M),Y=await S.selectFrom("categories").select((N)=>N.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",J).executeTakeFirst(),H=await S.selectFrom("categories").select((N)=>N.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",L).executeTakeFirst(),W=Number(Y?.count||0),F=Number(H?.count||0),Q=W-F,A=F!==0?Q/F*100:W>0?100:0;return{current_period:W,previous_period:F,difference:Q,percentage_change:A,days_range:G}}async function lX(){let G=await UG(),x=new Map;G.forEach(($)=>{x.set($.id,{...$,children:[]})});let J=[];G.forEach(($)=>{let K=x.get($.id);if($.parent_category_id){let L=x.get($.parent_category_id);if(L)L.children.push(K)}else J.push(K)}),J.sort(($,K)=>$.display_order-K.display_order);let X=($)=>{$.sort((K,L)=>K.display_order-L.display_order),$.forEach((K)=>{if(K.children.length>0)X(K.children)})};return X(J),J}async function cX(G){if(!await U(G))throw Error(`Category with ID ${G} not found`);return!!await c.deleteFrom("categories").where("id","=",G).executeTakeFirst()}async function uX(G){if(!G.length)return 0;let x=await c.deleteFrom("categories").where("id","in",G).executeTakeFirst();return Number(x?.numDeletedRows)||0}async function nX(G){let x=await c.deleteFrom("categories").where("parent_category_id","=",G).executeTakeFirst();return Number(x?.numDeletedRows)||0}async function oX(G){if(!await U(G))throw Error(`Category with ID ${G} not found`);return!!await c.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",G).executeTakeFirst()}async function iX(G){let x=await c.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",G).execute();return Number(x.length)||0}import{db as sX}from"@stacksjs/database";import{slug as G4}from"@stacksjs/strings";async function qG(G){try{let x={...G,slug:G.name?.toLowerCase().replace(/\s+/g,"-")||"",categorizable_type:"product",display_order:0},J=await sX.insertInto("categories").values(x).executeTakeFirst();if(!J)throw Error("Failed to create category");let X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows),$=await U(X);if(!$)throw Error("Failed to create category");return $}catch(x){if(x instanceof Error){if(x.message.includes("Duplicate entry")&&x.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to create category: ${x.message}`)}throw x}}async function dX(G){if(!G.name)throw Error("Name is required");let x=await sX.selectFrom("categories").selectAll().where("name","=",G.name).executeTakeFirst();if(x)return x;let J={name:G.name,slug:G4(G.name),is_active:G.is_active??!0,categorizable_type:G.categorizable_type??"default",display_order:0};return await qG(J)}import{db as Hx}from"@stacksjs/database";import{formatDate as Px}from"@stacksjs/orm";async function aX(G,x){await x.validate();let J=await U(G);if(!J)throw Error(`Category with ID ${G} not found`);let X={name:x.get("name"),description:x.get("description"),imageUrl:x.get("imageUrl"),isActive:x.get("isActive"),parentCategoryId:x.get("parentCategoryId"),displayOrder:x.get("displayOrder"),updated_at:Px(new Date)};if(Object.keys(X).length===0)return J;try{return await Hx.updateTable("categories").set(X).where("id","=",G).execute(),await U(G)}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry")&&$.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to update category: ${$.message}`)}throw $}}async function tX(G,x){if(!await U(G))throw Error(`Category with ID ${G} not found`);try{return await Hx.updateTable("categories").set({display_order:x,updated_at:Px(new Date)}).where("id","=",G).execute(),await U(G)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category display order: ${X.message}`);throw X}}async function rX(G,x){if(!await U(G))throw Error(`Category with ID ${G} not found`);try{return await Hx.updateTable("categories").set({is_active:x,updated_at:Px(new Date)}).where("id","=",G).execute(),await U(G)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category active status: ${X.message}`);throw X}}async function eX(G,x){if(!await U(G))throw Error(`Category with ID ${G} not found`);if(x){let X=Number(x);if(X===G)throw Error("A category cannot be its own parent");if(!await U(X))throw Error(`Parent category with ID ${x} not found`);if(await J4(G,x))throw Error("This operation would create a circular reference in the category hierarchy")}try{let X={updated_at:Px(new Date)};if(x===null)await Hx.updateTable("categories").set({...X,parent_category_id:void 0}).where("id","=",G).execute();else await Hx.updateTable("categories").set({...X,parent_category_id:x}).where("id","=",G).execute();return await U(G)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update category parent: ${X.message}`);throw X}}async function J4(G,x){let J=Number(x),X=new Set;while(J){if(X.has(J))return!0;if(J===G)return!0;X.add(J);let $=await U(J);if(!$||!$.parentCategoryId)return!1;J=Number($.parentCategoryId)}return!1}var kx={};B(kx,{updateInventory:()=>W6,updateAvailability:()=>H6,update:()=>Z6,store:()=>M6,fetchTopProducts:()=>$6,fetchById:()=>D,fetchAll:()=>X6,destroy:()=>G6,bulkStore:()=>Y6,bulkDestroy:()=>J6});import{db as x6}from"@stacksjs/database";async function G6(G){try{let x=await x6.deleteFrom("products").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete product item: ${x.message}`);throw x}}async function J6(G){if(!G.length)return 0;try{let x=await x6.deleteFrom("products").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete product items: ${x.message}`);throw x}}import{db as u,sql as X4}from"@stacksjs/database";async function D(G){let x=await u.selectFrom("products").where("id","=",G).selectAll().executeTakeFirst();if(x){let J=null,X=null;if(x.manufacturer_id)J=await u.selectFrom("manufacturers").where("id","=",x.manufacturer_id).selectAll().executeTakeFirst();if(x.category_id)X=await u.selectFrom("categories").where("id","=",x.category_id).selectAll().executeTakeFirst();return{...x,manufacturer:J,category:X}}return}async function X6(){let G=await u.selectFrom("products").selectAll().execute(),x=G.map((Y)=>Y.manufacturer_id).filter((Y)=>Y!==null&&Y!==void 0),J=G.map((Y)=>Y.category_id).filter((Y)=>Y!==null&&Y!==void 0),X=u.selectFrom("manufacturers"),$=u.selectFrom("categories");if(x.length>0)X=X.where("id","in",x);if(J.length>0)$=$.where("id","in",J);let K=await X.selectAll().execute(),L=await $.selectAll().execute(),M=K.reduce((Y,H)=>{return Y[H.id]=H,Y},{}),Z=L.reduce((Y,H)=>{return Y[H.id]=H,Y},{});return G.map((Y)=>({...Y,manufacturer:Y.manufacturer_id?M[Y.manufacturer_id]:null,category:Y.category_id?Z[Y.category_id]:null}))}async function $6(G=5){try{return(await u.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",(J)=>J.fn.sum("order_items.quantity").as("units_sold"),X4`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(G).execute()).map((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(x){if(x instanceof Error)throw TypeError(`Failed to fetch top products: ${x.message}`);throw x}}var{randomUUIDv7:K6}=globalThis.Bun;import{db as L6}from"@stacksjs/database";async function M6(G){try{let x={...G,uuid:K6()},J=await L6.insertInto("products").values(x).executeTakeFirst();if(!J)throw Error("Failed to create product item");let X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows),$=await D(X);if(!$)throw Error("Failed to create product item");return $}catch(x){if(x instanceof Error)throw TypeError(`Failed to create product item: ${x.message}`);throw x}}async function Y6(G){if(!G.length)return 0;let x=0;try{return await L6.transaction().execute(async(J)=>{for(let X of G){let $={...X,uuid:K6()};await J.insertInto("products").values($).execute(),x++}}),x}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product items in bulk: ${J.message}`);throw J}}import{db as TG,sql as LL}from"@stacksjs/database";import{formatDate as PG}from"@stacksjs/orm";async function Z6(G,x){try{if(!G)throw Error("Product item ID is required for update");let J=await TG.updateTable("products").set({...x,updated_at:PG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update product item");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product item: ${J.message}`);throw J}}async function H6(G,x){if(!await D(G))throw Error(`Product item with ID ${G} not found`);try{return await TG.updateTable("products").set({is_available:x,updated_at:PG(new Date)}).where("id","=",G).execute(),await D(G)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item availability: ${X.message}`);throw X}}async function W6(G,x){let J=await D(G);if(!J)throw Error(`Product item with ID ${G} not found`);let X={updated_at:PG(new Date)};if(x!==void 0)X.inventory_count=x;if(Object.keys(X).length===1)return J;try{return await TG.updateTable("products").set(X).where("id","=",G).execute(),await D(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update inventory information: ${$.message}`);throw $}}var jx={};B(jx,{updateFeaturedStatus:()=>S6,updateByUuid:()=>k6,update:()=>P6,store:()=>q6,fetchWithProductCount:()=>E6,fetchFeatured:()=>z6,fetchByUuid:()=>V6,fetchById:()=>B6,fetchByCountry:()=>O6,fetchAll:()=>A6,destroy:()=>N6,bulkStore:()=>T6,bulkDestroy:()=>Q6});import{db as F6}from"@stacksjs/database";async function N6(G){try{let x=await F6.deleteFrom("manufacturers").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete order: ${x.message}`);throw x}}async function Q6(G){if(!G.length)return 0;try{let x=await F6.deleteFrom("manufacturers").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete orders: ${x.message}`);throw x}}import{db as n}from"@stacksjs/database";function A6(){return n.selectFrom("manufacturers").selectAll().execute()}async function B6(G){return await n.selectFrom("manufacturers").where("id","=",G).selectAll().executeTakeFirst()}async function V6(G){return await n.selectFrom("manufacturers").where("uuid","=",G).selectAll().executeTakeFirst()}async function z6(G=10){return await n.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(G).execute()}async function O6(G,x={}){let J=x.page||1,X=x.limit||2,$=await n.selectFrom("manufacturers").select((Z)=>Z.fn.count("id").as("total")).where("country","=",G).executeTakeFirst(),K=Number($?.total||0),L=await n.selectFrom("manufacturers").selectAll().where("country","=",G).limit(X).offset((J-1)*X).execute(),M=Math.ceil(K/X);return{data:L,paging:{total_records:K,page:J,total_pages:M},next_cursor:J<M?J+1:null}}async function E6(G={}){let x=n.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(G.country)x=x.where("m.country","=",G.country);if(G.featured!==void 0)x=x.where("m.featured","=",G.featured);return x=x.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",(J)=>J.fn.count("p.id").as("product_count")]).groupBy("m.id"),x.execute()}var{randomUUIDv7:R6}=globalThis.Bun;import{db as U6}from"@stacksjs/database";async function q6(G){try{let x={...G,uuid:R6(),featured:G.featured??!1},J=await U6.insertInto("manufacturers").values(x).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create manufacturer");return J}catch(x){if(x instanceof Error){if(x.message.includes("Duplicate entry"))throw Error("A manufacturer with this name already exists");throw Error(`Failed to create manufacturer: ${x.message}`)}throw x}}async function T6(G){if(!G.length)return 0;let x=0;try{for(let J of G){let X={...J,uuid:R6(),featured:J.featured??!1};await U6.insertInto("manufacturers").values(X).execute(),x++}return x}catch(J){if(J instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${J.message}`);throw J}}import{db as SG}from"@stacksjs/database";import{formatDate as kG}from"@stacksjs/orm";async function P6(G,x){try{if(!G)throw Error("Manufacturer ID is required for update");let J=await SG.updateTable("manufacturers").set({...x,updated_at:kG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error(`Manufacturer with ID ${G} not found`);return J}catch(J){if(J instanceof Error){if((J.message.includes("Duplicate entry")||J.message.includes("UNIQUE constraint failed"))&&J.message.includes("manufacturer"))throw Error("A manufacturer with this name already exists");throw Error(`Failed to update manufacturer: ${J.message}`)}throw J}}async function S6(G,x){try{let J=await SG.updateTable("manufacturers").set({featured:x,updated_at:kG(new Date)}).where("id","=",G).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 k6(G,x){try{let J=await SG.updateTable("manufacturers").set({...x,updated_at:kG(new Date)}).where("uuid","=",G).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 wx={};B(wx,{updateVotes:()=>b6,update:()=>m6,store:()=>y6,fetchMostHelpfulByProductId:()=>h6,fetchByUserId:()=>v6,fetchByProductId:()=>f6,fetchById:()=>_6,fetchApprovedByProductId:()=>g6,fetchAll:()=>I6,destroy:()=>w6,bulkDestroy:()=>C6});import{db as j6}from"@stacksjs/database";async function w6(G){try{let x=await j6.deleteFrom("reviews").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete order: ${x.message}`);throw x}}async function C6(G){if(!G.length)return 0;try{let x=await j6.deleteFrom("reviews").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete orders: ${x.message}`);throw x}}import{db as r}from"@stacksjs/database";async function _6(G){return await r.selectFrom("reviews").where("id","=",G).selectAll().executeTakeFirst()}async function I6(){return await r.selectFrom("reviews").selectAll().execute()}async function f6(G){return await r.selectFrom("reviews").where("product_id","=",G).selectAll().execute()}async function v6(G){return await r.selectFrom("reviews").where("customer_id","=",G).selectAll().execute()}async function g6(G){return await r.selectFrom("reviews").where("product_id","=",G).where("is_approved","=",!0).selectAll().execute()}async function h6(G){return await r.selectFrom("reviews").where("product_id","=",G).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:$4}=globalThis.Bun;import{db as K4}from"@stacksjs/database";async function y6(G){try{let x={...G,uuid:$4(),is_verified_purchase:G.is_verified_purchase??!1,is_approved:G.is_approved??!1,helpful_votes:G.helpful_votes??0,unhelpful_votes:G.unhelpful_votes??0,is_featured:G.is_featured??!1},J=await K4.insertInto("reviews").values(x).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create review");return J}catch(x){if(x instanceof Error){if(x.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${x.message}`)}throw x}}import{db as D6}from"@stacksjs/database";import{formatDate as p6}from"@stacksjs/orm";async function m6(G,x){try{if(!G)throw Error("Review ID is required for update");let J=await D6.updateTable("reviews").set({...x,updated_at:p6(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update review");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update review: ${J.message}`);throw J}}async function b6(G,x,J=!0){try{let X=x==="helpful"?"helpful_votes":"unhelpful_votes",$=J?`COALESCE("${X}", 0) + 1`:`MAX(COALESCE("${X}", 0) - 1, 0)`,K=await D6.unsafe(`UPDATE "reviews" SET "${X}" = ${$}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[p6(new Date),G]).execute(),L=Array.isArray(K)?K[0]:K;if(!L)throw Error("Failed to update review votes");return L}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review votes: ${X.message}`);throw X}}var Cx={};B(Cx,{updateDefaultStatus:()=>G7,update:()=>e6,store:()=>d6,getDefaultUnit:()=>r6,formatUnitOptions:()=>t6,fetchById:()=>o6,fetchAll:()=>i6,destroy:()=>c6,bulkUpdate:()=>x7,bulkStore:()=>a6,bulkDestroy:()=>u6});import{db as l6}from"@stacksjs/database";async function c6(G){try{let x=await l6.deleteFrom("product_units").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete product unit: ${x.message}`);throw x}}async function u6(G){if(!G.length)return 0;try{let x=await l6.deleteFrom("product_units").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete product units: ${x.message}`);throw x}}import{db as n6}from"@stacksjs/database";async function o6(G){return await n6.selectFrom("product_units").where("id","=",G).selectAll().executeTakeFirst()}async function i6(){return await n6.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:s6}=globalThis.Bun;import{db as e}from"@stacksjs/database";async function d6(G){try{let x={...G,uuid:s6()},J=await e.insertInto("product_units").values(x).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create product unit");if(x.is_default)await e.updateTable("product_units").set({is_default:!1}).where("type","=",x.type).where("id","!=",J.id).execute();return J}catch(x){if(x instanceof Error)throw TypeError(`Failed to create product unit: ${x.message}`);throw x}}async function a6(G){if(!G.length)return 0;let x=0;try{for(let J of G){let X={...J,uuid:s6()},$=await e.insertInto("product_units").values(X).returningAll().executeTakeFirst();if(X.is_default&&$)await e.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",$.id).execute();x++}return x}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product units in bulk: ${J.message}`);throw J}}function t6(G){try{let x=e.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(G)x=x.where("type","=",G);return x=x.orderBy("name"),x.execute().then((J)=>J.map((X)=>({id:String(X.id),name:X.name,abbreviation:X.abbreviation,is_default:X.is_default})))}catch(x){if(x instanceof Error)throw TypeError(`Failed to format unit options: ${x.message}`);throw x}}async function r6(G){try{return await e.selectFrom("product_units").selectAll().where("type","=",G).where("is_default","=",!0).executeTakeFirst()}catch(x){if(x instanceof Error)throw TypeError(`Failed to get default unit: ${x.message}`);throw x}}import{db as o}from"@stacksjs/database";import{formatDate as jG}from"@stacksjs/orm";async function e6(G,x){try{if(!G)throw Error("Product unit ID is required for update");let J=await o.updateTable("product_units").set({...x,updated_at:jG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update product unit");if(x.is_default===!0&&x.type)await o.updateTable("product_units").set({is_default:!1}).where("type","=",x.type).where("id","!=",G).execute();return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product unit: ${J.message}`);throw J}}async function x7(G){if(!G.length)return 0;let x=0;try{for(let J of G){let X=J;if(!X.id)continue;let $=X.data&&typeof X.data==="object"?X.data:{...X};delete $.id;let K=await o.updateTable("product_units").set({...$,updated_at:jG(new Date)}).where("id","=",X.id).executeTakeFirst(),L=$;if(L.is_default===!0&&L.type)await o.updateTable("product_units").set({is_default:!1}).where("type","=",L.type).where("id","!=",X.id).execute();if(Number(K.numUpdatedRows)>0)x++}return x}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product units in bulk: ${J.message}`);throw J}}async function G7(G,x){try{let J=await o.selectFrom("product_units").select("type").where("id","=",G).executeTakeFirst();if(!J)return!1;let X=await o.updateTable("product_units").set({is_default:x,updated_at:jG(new Date)}).where("id","=",G).executeTakeFirst();if(x&&J.type)await o.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",G).execute();return Number(X.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product unit default status: ${J.message}`);throw J}}var _x={};B(_x,{update:()=>B7,store:()=>H7,generateVariantCombinations:()=>N7,formatVariantOptions:()=>F7,fetchById:()=>L7,fetchAll:()=>M7,destroy:()=>X7,bulkUpdate:()=>V7,bulkStore:()=>W7,bulkDestroy:()=>$7});import{db as J7}from"@stacksjs/database";async function X7(G){try{let x=await J7.deleteFrom("product_variants").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete product variant: ${x.message}`);throw x}}async function $7(G){if(!G.length)return 0;try{let x=await J7.deleteFrom("product_variants").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete product variants: ${x.message}`);throw x}}import{db as K7}from"@stacksjs/database";async function L7(G){return await K7.selectFrom("product_variants").where("id","=",G).selectAll().executeTakeFirst()}async function M7(){return await K7.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:Y7}=globalThis.Bun;import{db as Z7}from"@stacksjs/database";async function H7(G){try{let x={...G,uuid:Y7()},J=await Z7.insertInto("product_variants").values(x).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create product variant");return J}catch(x){if(x instanceof Error)throw TypeError(`Failed to create product variant: ${x.message}`);throw x}}async function W7(G){if(!G.length)return 0;let x=0;try{for(let J of G){let X={...J,uuid:Y7()};await Z7.insertInto("product_variants").values(X).execute(),x++}return x}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${J.message}`);throw J}}function F7(G){if(!G||!G.length)return JSON.stringify([]);let x=G.map((J)=>J.trim()).filter(Boolean);return JSON.stringify(x)}function N7(G){let x=Object.keys(G);if(!x.length)return[];function J(X,$){if(X===x.length)return[$];let K=x[X],L=G[K],M=[];for(let Z of L){let Y={...$,[K]:Z};M.push(...J(X+1,Y))}return M}return J(0,{})}import{db as Q7}from"@stacksjs/database";import{formatDate as A7}from"@stacksjs/orm";async function B7(G,x){try{let J=await Q7.updateTable("product_variants").set({...x,updated_at:A7(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update product variant");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product variant: ${J.message}`);throw J}}async function V7(G){if(!G.length)return 0;let x=0;try{for(let J of G){if(!J.id)continue;let X=await Q7.updateTable("product_variants").set({...J,updated_at:A7(new Date)}).where("id","=",J.id).executeTakeFirst();if(Number(X.numUpdatedRows)>0)x++}return x}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${J.message}`);throw J}}var L4={categories:Sx,items:kx,manufacturers:jx,reviews:wx,units:Cx,variants:_x},M4=L4;var IG={};B(IG,{updateStatus:()=>w7,updatePrintJob:()=>C7,update:()=>j7,store:()=>S7,fetchById:()=>U7,fetchAll:()=>q7,destroy:()=>O7,bulkStore:()=>k7,bulkDestroy:()=>E7});import{db as z7}from"@stacksjs/database";async function O7(G){try{let x=await z7.deleteFrom("receipts").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete print log: ${x.message}`);throw x}}async function E7(G){if(!G.length)return 0;try{let x=await z7.deleteFrom("receipts").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete receipts: ${x.message}`);throw x}}import{db as R7}from"@stacksjs/database";async function U7(G){return await R7.selectFrom("receipts").where("id","=",G).selectAll().executeTakeFirst()}async function q7(){return await R7.selectFrom("receipts").selectAll().execute()}var{randomUUIDv7:T7}=globalThis.Bun;import{db as P7}from"@stacksjs/database";async function S7(G){try{let x={...G,uuid:T7()},J=await P7.insertInto("receipts").values(x).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create receipt");return J}catch(x){if(x instanceof Error)throw TypeError(`Failed to create receipt: ${x.message}`);throw x}}async function k7(G){if(!G.length)return 0;try{let x=G.map((X)=>({...X,uuid:T7()})),J=await P7.insertInto("receipts").values(x).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${x.message}`);throw x}}import{db as CG}from"@stacksjs/database";import{formatDate as _G}from"@stacksjs/orm";async function j7(G,x){try{if(!G)throw Error("Receipt ID is required for update");let J=await CG.updateTable("receipts").set({...x,updated_at:_G(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update receipt");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update receipt: ${J.message}`);throw J}}async function w7(G,x){try{let J=await CG.updateTable("receipts").set({status:x,updated_at:_G(new Date)}).where("id","=",G).returningAll().executeTakeFirst();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 C7(G,x,J,X){try{let $={updated_at:_G(new Date)};if(x!==void 0)$.size=x;if(J!==void 0)$.pages=J;if(X!==void 0)$.duration=X;let K=await CG.updateTable("receipts").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update receipt job information");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update receipt job information: ${$.message}`);throw $}}var cG={};B(cG,{zones:()=>ex,routes:()=>fx,rates:()=>dx,methods:()=>ux,licenses:()=>mx,drivers:()=>yx,digital:()=>hx,default:()=>H4});var fx={};B(fx,{updateStops:()=>l7,updateMetrics:()=>c7,updateLastActive:()=>m7,update:()=>b7,store:()=>p7,fetchById:()=>v7,fetchByDriver:()=>y7,fetchAll:()=>g7,fetchActive:()=>h7,destroy:()=>I7,bulkDestroy:()=>f7});import{db as _7}from"@stacksjs/database";async function I7(G){try{let x=await _7.deleteFrom("delivery_routes").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete delivery route: ${x.message}`);throw x}}async function f7(G){if(!G.length)return 0;try{let x=await _7.deleteFrom("delivery_routes").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete delivery routes: ${x.message}`);throw x}}import{db as Ix}from"@stacksjs/database";async function v7(G){return await Ix.selectFrom("delivery_routes").where("id","=",G).selectAll().executeTakeFirst()}async function g7(){return await Ix.selectFrom("delivery_routes").selectAll().execute()}async function h7(){return await Ix.selectFrom("delivery_routes").where("last_active","<=",new Date(Date.now()-86400000)).selectAll().execute()}async function y7(G){return await Ix.selectFrom("delivery_routes").where("driver","=",G).selectAll().execute()}var{randomUUIDv7:Y4}=globalThis.Bun;import{db as D7}from"@stacksjs/database";async function p7(G){try{let x={...G,uuid:Y4()},J=await D7.insertInto("delivery_routes").values(x).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create delivery route");return J}catch(x){if(x instanceof Error)throw TypeError(`Failed to create delivery route: ${x.message}`);throw x}}async function m7(G){try{let x=await D7.updateTable("delivery_routes").set({last_active:new Date().toISOString(),updated_at:new Date().toISOString()}).where("id","=",G).returningAll().executeTakeFirst();if(!x)throw Error("Failed to update delivery route last active");return x}catch(x){if(x instanceof Error)throw TypeError(`Failed to update delivery route last active: ${x.message}`);throw x}}import{db as fG}from"@stacksjs/database";import{formatDate as vG}from"@stacksjs/orm";async function b7(G,x){try{if(!G)throw Error("Delivery route ID is required for update");let J=await fG.updateTable("delivery_routes").set({...x,updated_at:vG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update delivery route");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route: ${J.message}`);throw J}}async function l7(G,x){try{let J=await fG.updateTable("delivery_routes").set({stops:x,updated_at:vG(new Date)}).where("id","=",G).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 c7(G,x,J){try{let X={updated_at:vG(new Date)};if(x!==void 0)X.delivery_time=x;if(J!==void 0)X.total_distance=J;let $=await fG.updateTable("delivery_routes").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update delivery metrics");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery metrics: ${X.message}`);throw X}}var hx={};B(hx,{updateStatus:()=>G9,updateDeliverySettings:()=>J9,update:()=>x9,store:()=>r7,softDelete:()=>n7,fetchById:()=>gx,fetchAll:()=>d7,destroy:()=>u7,bulkStore:()=>e7,bulkSoftDelete:()=>i7,bulkDestroy:()=>o7});import{db as vx}from"@stacksjs/database";async function u7(G){try{let x=await vx.deleteFrom("digital_deliveries").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete digital delivery: ${x.message}`);throw x}}async function n7(G){try{let x=await vx.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(x.numUpdatedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${x.message}`);throw x}}async function o7(G){if(!G.length)return 0;try{let x=await vx.deleteFrom("digital_deliveries").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${x.message}`);throw x}}async function i7(G){if(!G.length)return 0;try{let x=await vx.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(x.numUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${x.message}`);throw x}}import{db as s7}from"@stacksjs/database";async function gx(G){return await s7.selectFrom("digital_deliveries").where("id","=",G).selectAll().executeTakeFirst()}async function d7(){return await s7.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:a7}=globalThis.Bun;import{db as t7}from"@stacksjs/database";async function r7(G){try{let x={...G,uuid:a7()},J=await t7.insertInto("digital_deliveries").values(x).executeTakeFirst();if(!J)throw Error("Failed to create digital delivery");let X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows),$=await gx(X);if(!$)throw Error("Failed to create digital delivery");return $}catch(x){if(x instanceof Error)throw TypeError(`Failed to create digital delivery: ${x.message}`);throw x}}async function e7(G){if(!G.length)return 0;try{let x=G.map((X)=>({...X,uuid:a7()})),J=await t7.insertInto("digital_deliveries").values(x).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${x.message}`);throw x}}import{db as gG}from"@stacksjs/database";import{formatDate as hG}from"@stacksjs/orm";async function x9(G,x){try{if(!G)throw Error("Digital delivery ID is required for update");let J=await gG.updateTable("digital_deliveries").set({...x,updated_at:hG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update digital delivery");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update digital delivery: ${J.message}`);throw J}}async function G9(G,x){try{let J=await gG.updateTable("digital_deliveries").set({status:x,updated_at:hG(new Date)}).where("id","=",G).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 J9(G,x,J,X,$){try{let K={updated_at:hG(new Date)};if(x!==void 0)K.download_limit=x;if(J!==void 0)K.expiry_days=J;if(X!==void 0)K.requires_login=X;if($!==void 0)K.automatic_delivery=$;let L=await gG.updateTable("digital_deliveries").set(K).where("id","=",G).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update delivery settings");return L}catch(K){if(K instanceof Error)throw TypeError(`Failed to update delivery settings: ${K.message}`);throw K}}var yx={};B(yx,{updateStatus:()=>N9,updateContact:()=>Q9,update:()=>F9,store:()=>H9,fetchById:()=>Wx,fetchAll:()=>$9,destroy:()=>L9,bulkStore:()=>W9,bulkDestroy:()=>M9});import{db as K9}from"@stacksjs/database";import{db as X9}from"@stacksjs/database";async function Wx(G){return await X9.selectFrom("drivers").where("id","=",G).selectAll().executeTakeFirst()}async function $9(){return await X9.selectFrom("drivers").selectAll().execute()}async function L9(G){let x=await Wx(G);if(!x)throw Error(`Driver with ID ${G} not found`);try{return await K9.deleteFrom("drivers").where("id","=",G).execute(),x}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete driver: ${J.message}`);throw J}}async function M9(G){if(!G.length)return 0;let x=0;try{return await K9.transaction().execute(async(J)=>{for(let X of G)if(await Wx(X))await J.deleteFrom("drivers").where("id","=",X).execute(),x++}),x}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${J.message}`);throw J}}var{randomUUIDv7:Y9}=globalThis.Bun;import{db as Z9}from"@stacksjs/database";async function H9(G){try{let x={...G,uuid:Y9()},J=await Z9.insertInto("drivers").values(x).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create driver");return J}catch(x){if(x instanceof Error)throw TypeError(`Failed to create driver: ${x.message}`);throw x}}async function W9(G){if(!G.length)return 0;try{let x=G.map((X)=>({...X,uuid:Y9()})),J=await Z9.insertInto("drivers").values(x).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${x.message}`);throw x}}import{db as yG}from"@stacksjs/database";import{formatDate as DG}from"@stacksjs/orm";async function F9(G,x){try{if(!G)throw Error("Driver ID is required for update");let J=await yG.updateTable("drivers").set({...x,updated_at:DG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update driver");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update driver: ${J.message}`);throw J}}async function N9(G,x){try{let J=await yG.updateTable("drivers").set({status:x,updated_at:DG(new Date)}).where("id","=",G).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 Q9(G,x){try{let J={updated_at:DG(new Date)};if(x!==void 0)J.phone=x;let X=await yG.updateTable("drivers").set(J).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update contact information");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to update contact information: ${J.message}`);throw J}}var mx={};B(mx,{updateStatus:()=>S9,updateExpiration:()=>k9,update:()=>P9,store:()=>q9,softDelete:()=>B9,fetchById:()=>px,fetchAll:()=>E9,destroy:()=>A9,bulkStore:()=>T9,bulkSoftDelete:()=>z9,bulkDestroy:()=>V9});import{db as Dx}from"@stacksjs/database";async function A9(G){try{let x=await Dx.deleteFrom("license_keys").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete license key: ${x.message}`);throw x}}async function B9(G){try{let x=await Dx.updateTable("license_keys").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(x.numUpdatedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to soft delete license key: ${x.message}`);throw x}}async function V9(G){if(!G.length)return 0;try{let x=await Dx.deleteFrom("license_keys").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete license keys: ${x.message}`);throw x}}async function z9(G){if(!G.length)return 0;try{let x=await Dx.updateTable("license_keys").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(x.numUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to soft delete license keys: ${x.message}`);throw x}}import{db as O9}from"@stacksjs/database";async function px(G){return await O9.selectFrom("license_keys").where("id","=",G).selectAll().executeTakeFirst()}async function E9(){return await O9.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:R9}=globalThis.Bun;import{db as U9}from"@stacksjs/database";async function q9(G){try{let x={...G,uuid:R9()},J=await U9.insertInto("license_keys").values(x).executeTakeFirst();if(!J)throw Error("Failed to create license key");let X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows),$=await px(X);if(!$)throw Error("Failed to create license key");return $}catch(x){if(x instanceof Error)throw TypeError(`Failed to create license key: ${x.message}`);throw x}}async function T9(G){if(!G.length)return 0;try{let x=G.map((X)=>({...X,uuid:R9()})),J=await U9.insertInto("license_keys").values(x).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${x.message}`);throw x}}import{db as pG}from"@stacksjs/database";import{formatDate as mG}from"@stacksjs/orm";async function P9(G,x){try{if(!G)throw Error("License key ID is required for update");let J=await pG.updateTable("license_keys").set({...x,updated_at:mG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update license key");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update license key: ${J.message}`);throw J}}async function S9(G,x){try{let J=await pG.updateTable("license_keys").set({status:x,updated_at:mG(new Date)}).where("id","=",G).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 k9(G,x){try{let J={updated_at:mG(new Date)};if(x!==void 0)J.expiry_date=x;let X=await pG.updateTable("license_keys").set(J).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update expiration information");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to update expiration information: ${J.message}`);throw J}}var ux={};B(ux,{updateStatus:()=>p9,updatePricing:()=>m9,update:()=>D9,store:()=>v9,softDelete:()=>w9,getActiveShippingMethods:()=>y9,formatShippingOptions:()=>h9,fetchById:()=>i,fetchAll:()=>I9,destroy:()=>j9,bulkStore:()=>g9,bulkSoftDelete:()=>_9,bulkDestroy:()=>C9});import{db as bx}from"@stacksjs/database";async function j9(G){try{let x=await bx.deleteFrom("shipping_methods").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete shipping method: ${x.message}`);throw x}}async function w9(G){try{let x=await bx.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(x.numUpdatedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${x.message}`);throw x}}async function C9(G){if(!G.length)return 0;try{let x=await bx.deleteFrom("shipping_methods").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete shipping methods: ${x.message}`);throw x}}async function _9(G){if(!G.length)return 0;try{let x=await bx.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(x.numUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${x.message}`);throw x}}import{db as lx}from"@stacksjs/database";async function i(G){let x=await lx.selectFrom("shipping_methods").where("id","=",G).selectAll().executeTakeFirst();if(x){let J=await lx.selectFrom("shipping_zones").where("shipping_method_id","=",G).selectAll().execute();return{...x,shippingZones:J}}return}async function I9(){let G=await lx.selectFrom("shipping_methods").selectAll().execute(),x=G.map((K)=>K.id),J=lx.selectFrom("shipping_zones");if(x.length>0)J=J.where("shipping_method_id","in",x);let $=(await J.selectAll().execute()).reduce((K,L)=>{let M=L.shipping_method_id;if(M!==null&&M!==void 0){if(!K[M])K[M]=[];K[M].push(L)}return K},{});return G.map((K)=>({...K,shipping_zones:$[K.id]||[]}))}var{randomUUIDv7:f9}=globalThis.Bun;import{db as cx}from"@stacksjs/database";async function v9(G){try{let x=G,J={name:G.name,description:G.description,base_rate:x.base_rate,free_shipping:x.free_shipping,status:G.status,uuid:f9()},X=await cx.insertInto("shipping_methods").values(J).executeTakeFirst();if(!X)throw Error("Failed to create shipping method");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await i($)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create shipping method: ${x.message}`);throw x}}async function g9(G){if(!G.length)return 0;try{let x=G.map((X)=>({...X,uuid:f9()})),J=await cx.insertInto("shipping_methods").values(x).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${x.message}`);throw x}}function h9(){try{return cx.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping options: ${G.message}`);throw G}}async function y9(){try{return await cx.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get active shipping methods: ${G.message}`);throw G}}import{db as bG}from"@stacksjs/database";import{formatDate as lG}from"@stacksjs/orm";async function D9(G,x){try{if(!G)throw Error("Shipping method ID is required for update");let J=await bG.updateTable("shipping_methods").set({...x,updated_at:lG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping method");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping method: ${J.message}`);throw J}}async function p9(G,x){try{let J=await bG.updateTable("shipping_methods").set({status:x,updated_at:lG(new Date)}).where("id","=",G).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 m9(G,x,J){try{let X={updated_at:lG(new Date)};if(x!==void 0)X.base_rate=x;if(J!==void 0)X.free_shipping=J;let $=await bG.updateTable("shipping_methods").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update pricing information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update pricing information: ${X.message}`);throw X}}var dx={};B(dx,{updateByZone:()=>L$,updateByMethod:()=>M$,update:()=>$$,store:()=>J$,getShippingRatesByMethod:()=>d9,getRatesByZone:()=>o9,getRateByWeightAndZone:()=>i9,formatShippingRateOptions:()=>s9,fetchById:()=>ox,fetchAll:()=>n9,destroyByZone:()=>c9,destroyByMethod:()=>u9,destroy:()=>b9,bulkUpdate:()=>K$,bulkStore:()=>X$,bulkDestroy:()=>l9});import{db as nx}from"@stacksjs/database";async function b9(G){try{let x=await nx.deleteFrom("shipping_rates").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete shipping rate: ${x.message}`);throw x}}async function l9(G){if(!G.length)return 0;try{let x=await nx.deleteFrom("shipping_rates").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete shipping rates: ${x.message}`);throw x}}async function c9(G){try{let x=await nx.deleteFrom("shipping_rates").where("zone","=",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${x.message}`);throw x}}async function u9(G){try{let x=await nx.deleteFrom("shipping_rates").where("method","=",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${x.message}`);throw x}}import{db as f}from"@stacksjs/database";async function ox(G){let x=await f.selectFrom("shipping_rates").where("id","=",G).selectAll().executeTakeFirst();if(x){let J=null,X=null;if(x.shipping_zone_id)J=await f.selectFrom("shipping_zones").where("id","=",x.shipping_zone_id).selectAll().executeTakeFirst();if(x.shipping_method_id)X=await f.selectFrom("shipping_methods").where("id","=",x.shipping_method_id).selectAll().executeTakeFirst();return{...x,shipping_zone:J,shipping_method:X}}return}async function n9(){let G=await f.selectFrom("shipping_rates").selectAll().execute(),x=G.map((Y)=>Y.shipping_zone_id).filter((Y)=>Y!==null&&Y!==void 0),J=G.map((Y)=>Y.shipping_method_id).filter((Y)=>Y!==null&&Y!==void 0),X=f.selectFrom("shipping_zones"),$=f.selectFrom("shipping_methods");if(x.length>0)X=X.where("id","in",x);if(J.length>0)$=$.where("id","in",J);let K=await X.selectAll().execute(),L=await $.selectAll().execute(),M=K.reduce((Y,H)=>{return Y[H.id]=H,Y},{}),Z=L.reduce((Y,H)=>{return Y[H.id]=H,Y},{});return G.map((Y)=>({...Y,shipping_zone:Y.shipping_zone_id?M[Y.shipping_zone_id]:[],shipping_method:Y.shipping_method_id?Z[Y.shipping_method_id]:[]}))}async function o9(G){try{return await f.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",G).orderBy("weight_from").execute()}catch(x){if(x instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${x.message}`);throw x}}async function i9(G,x){try{return await f.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",x).where("weight_from","<=",G).where("weight_to",">=",G).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${J.message}`);throw J}}async function s9(){try{return(await f.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((x)=>x.shipping_method_id!==null&&x.shipping_method_id!==void 0&&x.shipping_zone_id!==null&&x.shipping_zone_id!==void 0)}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping rate options: ${G.message}`);throw G}}async function d9(G){try{return await f.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",G).orderBy("weight_from").execute()}catch(x){if(x instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${x.message}`);throw x}}var{randomUUIDv7:x$}=globalThis.Bun;import{db as G$}from"@stacksjs/database";import{db as Fx}from"@stacksjs/database";async function a9(){return await Fx.selectFrom("shipping_zones").selectAll().execute()}async function s(G){return await Fx.selectFrom("shipping_zones").where("id","=",G).selectAll().executeTakeFirst()}function t9(){try{return Fx.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping zone options: ${G.message}`);throw G}}async function r9(){try{return await Fx.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get active shipping zones: ${G.message}`);throw G}}async function e9(G){try{return await Fx.selectFrom("shipping_zones").selectAll().where("countries","like",`%${G}%`).where("status","=","active").orderBy("name").execute()}catch(x){if(x instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${x.message}`);throw x}}async function J$(G){try{let x=await i(Number(G.shippingmethod_id)),J=await s(Number(G.shippingzone_id)),X={weightFrom:G.weightFrom,weightTo:G.weightTo,rate:G.rate,shippingmethod_id:x?.id,shippingzone_id:J?.id,uuid:x$()},$=await G$.insertInto("shipping_rates").values(X).executeTakeFirst();if(!$)throw Error("Failed to create shipping rate");let K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);return await ox(K)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create shipping rate: ${x.message}`);throw x}}async function X$(G){if(!G.length)return 0;try{for(let X of G){let $=await i(Number(X.shippingmethod_id)),K=await s(Number(X.shippingzone_id));if(!$)console.warn(`Shipping method with ID "${X.shippingmethod_id}" not found for bulk insert`);if(!K)console.warn(`Shipping zone with ID "${X.shippingzone_id}" not found for bulk insert`)}let x=G.map((X)=>({weightFrom:X.weightFrom,weightTo:X.weightTo,rate:X.rate,shippingmethod_id:X.shippingmethod_id,shippingzone_id:X.shippingzone_id,uuid:x$()})),J=await G$.insertInto("shipping_rates").values(x).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${x.message}`);throw x}}import{db as ix}from"@stacksjs/database";import{formatDate as sx}from"@stacksjs/orm";async function $$(G,x){try{if(!G)throw Error("Shipping rate ID is required for update");let J=await ix.updateTable("shipping_rates").set({...x,updated_at:sx(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping rate");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rate: ${J.message}`);throw J}}async function K$(G){if(!G.length)return 0;try{let x=0;for(let{id:J,data:X}of G){let $=await ix.updateTable("shipping_rates").set({...X,updated_at:sx(new Date)}).where("id","=",J).executeTakeFirst();if(Number($.numUpdatedRows)>0)x++}return x}catch(x){if(x instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${x.message}`);throw x}}async function L$(G,x){try{let J=await ix.updateTable("shipping_rates").set({...x,updated_at:sx(new Date)}).where("zone_id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${J.message}`);throw J}}async function M$(G,x){try{let J=await ix.updateTable("shipping_rates").set({...x,updated_at:sx(new Date)}).where("method","=",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${J.message}`);throw J}}var ex={};B(ex,{updateStatus:()=>V$,updateRegionsAndPostalCodes:()=>O$,updateCountries:()=>z$,update:()=>B$,store:()=>Q$,softDelete:()=>Z$,getZonesByCountry:()=>e9,getActiveShippingZones:()=>r9,formatZoneOptions:()=>t9,fetchById:()=>s,fetchAll:()=>a9,destroy:()=>Y$,bulkStore:()=>A$,bulkSoftDelete:()=>W$,bulkDestroy:()=>H$});import{db as ax}from"@stacksjs/database";async function Y$(G){try{let x=await ax.deleteFrom("shipping_zones").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete shipping zone: ${x.message}`);throw x}}async function Z$(G){try{let x=await ax.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(x.numUpdatedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${x.message}`);throw x}}async function H$(G){if(!G.length)return 0;try{let x=await ax.deleteFrom("shipping_zones").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete shipping zones: ${x.message}`);throw x}}async function W$(G){if(!G.length)return 0;try{let x=await ax.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(x.numUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${x.message}`);throw x}}var{randomUUIDv7:F$}=globalThis.Bun;import{db as N$}from"@stacksjs/database";async function Q$(G){try{let x={...G,uuid:F$()},J=await N$.insertInto("shipping_zones").values(x).executeTakeFirst();if(!J)throw Error("Failed to create shipping zone");let X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows);return await s(X)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create shipping zone: ${x.message}`);throw x}}async function A$(G){if(!G.length)return 0;try{let x=G.map((X)=>({...X,uuid:F$()})),J=await N$.insertInto("shipping_zones").values(x).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${x.message}`);throw x}}import{db as tx}from"@stacksjs/database";import{formatDate as rx}from"@stacksjs/orm";async function B$(G,x){try{if(!G)throw Error("Shipping zone ID is required for update");let J=await tx.updateTable("shipping_zones").set({...x,updated_at:rx(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping zone");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone: ${J.message}`);throw J}}async function V$(G,x){try{let J=await tx.updateTable("shipping_zones").set({status:x,updated_at:rx(new Date)}).where("id","=",G).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 z$(G,x){try{let J=await tx.updateTable("shipping_zones").set({countries:x,updated_at:rx(new Date)}).where("id","=",G).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 O$(G,x,J){try{let X={updated_at:rx(new Date)};if(x!==void 0)X.regions=x;if(J!==void 0)X.postal_codes=J;let $=await tx.updateTable("shipping_zones").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update regions and postal codes");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${X.message}`);throw X}}var Z4={digital:hx,drivers:yx,licenses:mx,methods:ux,rates:dx,routes:fx,zones:ex},H4=Z4;var oG={};B(oG,{updateStatus:()=>_$,updateRate:()=>I$,update:()=>C$,store:()=>j$,fetchById:()=>T$,fetchAll:()=>P$,destroy:()=>R$,bulkStore:()=>w$,bulkDestroy:()=>U$});import{db as E$}from"@stacksjs/database";async function R$(G){try{let x=await E$.deleteFrom("tax_rates").where("id","=",G).executeTakeFirst();return Number(x.numDeletedRows)>0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete tax rate: ${x.message}`);throw x}}async function U$(G){if(!G.length)return 0;try{let x=await E$.deleteFrom("tax_rates").where("id","in",G).executeTakeFirst();return Number(x.numDeletedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete tax rates: ${x.message}`);throw x}}import{db as q$}from"@stacksjs/database";async function T$(G){return await q$.selectFrom("tax_rates").where("id","=",G).selectAll().executeTakeFirst()}async function P$(){return await q$.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:S$}=globalThis.Bun;import{db as k$}from"@stacksjs/database";async function j$(G){try{let x={...G,uuid:S$()},J=await k$.insertInto("tax_rates").values(x).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create tax rate");return J}catch(x){if(x instanceof Error)throw TypeError(`Failed to create tax rate: ${x.message}`);throw x}}async function w$(G){if(!G.length)return 0;try{let x=G.map((X)=>({...X,uuid:S$()})),J=await k$.insertInto("tax_rates").values(x).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${x.message}`);throw x}}import{db as uG}from"@stacksjs/database";import{formatDate as nG}from"@stacksjs/orm";async function C$(G,x){try{if(!G)throw Error("Tax rate ID is required for update");let J=x,X=await uG.updateTable("tax_rates").set({name:x.name,rate:x.rate,type:x.type,country:x.country,region:x.region,status:x.status,is_default:J.is_default,updated_at:nG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update tax rate");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate: ${J.message}`);throw J}}async function _$(G,x){try{let J=await uG.updateTable("tax_rates").set({status:x,updated_at:nG(new Date)}).where("id","=",G).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 I$(G,x){try{let J=await uG.updateTable("tax_rates").set({rate:x,updated_at:nG(new Date)}).where("id","=",G).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}}var dG={};B(dG,{restaurant:()=>Gx,products:()=>GG,default:()=>F4});var GG={};B(GG,{updateStatus:()=>x1,updatePartySize:()=>G1,update:()=>e$,store:()=>t$,fetchWaiting:()=>u$,fetchPurchasedBetweenDates:()=>l$,fetchNotifiedBetweenDates:()=>b$,fetchCountByStatus:()=>n$,fetchCountBySource:()=>y$,fetchCountByQuantity:()=>p$,fetchCountByDateGrouped:()=>s$,fetchCountByDate:()=>D$,fetchCountByAllQuantities:()=>m$,fetchCountBetweenDates:()=>i$,fetchConversionRates:()=>o$,fetchCancelledBetweenDates:()=>c$,fetchById:()=>g$,fetchAll:()=>h$,destroy:()=>f$,bulkStore:()=>r$,bulkDestroy:()=>v$});import{db as xG}from"@stacksjs/database";async function f$(G){try{let x=await xG.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst();if(!x)return;return await xG.deleteFrom("waitlist_products").where("id","=",G).execute(),x}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete waitlist product: ${x.message}`);throw x}}async function v$(G){if(!G.length)return 0;try{return(await xG.deleteFrom("waitlist_products").where("id","in",G).execute()).length||0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${x.message}`);throw x}}import{db as q}from"@stacksjs/database";import{formatDate as E}from"@stacksjs/orm";async function g$(G){return await q.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst()}async function h$(){return await q.selectFrom("waitlist_products").selectAll().execute()}async function y$(G,x){let J=q.selectFrom("waitlist_products").select(["source",($)=>$.fn.count("id").as("count")]).groupBy("source");if(G&&x){let $=E(G),K=E(x);J=J.where("created_at",">=",$).where("created_at","<=",K)}return(await J.execute()).reduce(($,{source:K,count:L})=>{return $[K]=L,$},{})}async function D$(G=new Date){let x=new Date(G);x.setHours(0,0,0,0);let J=new Date(G);J.setHours(23,59,59,999);let X=E(x),$=E(J);return(await q.selectFrom("waitlist_products").select((L)=>L.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",$).executeTakeFirst())?.count??0}async function p$(G){return(await q.selectFrom("waitlist_products").select((J)=>J.fn.count("id").as("count")).where("quantity","=",G).executeTakeFirst())?.count??0}async function m$(G,x){let J=q.selectFrom("waitlist_products").select(["quantity",($)=>$.fn.count("id").as("count")]).groupBy("quantity");if(G&&x){let $=E(G),K=E(x);J=J.where("created_at",">=",$).where("created_at","<=",K)}return(await J.execute()).reduce(($,{quantity:K,count:L})=>{return $[K]=L,$},{})}async function b$(G,x){let J=E(G),X=E(x);return await q.selectFrom("waitlist_products").selectAll().where("notified_at",">=",J).where("notified_at","<=",X).where("notified_at","is not",null).execute()}async function l$(G,x){let J=E(G),X=E(x);return await q.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",J).where("purchased_at","<=",X).where("purchased_at","is not",null).execute()}async function c$(G,x){let J=E(G),X=E(x);return await q.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",J).where("cancelled_at","<=",X).where("cancelled_at","is not",null).execute()}async function u$(){return await q.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function n$(G,x,J){let X=q.selectFrom("waitlist_products").select((K)=>K.fn.count("id").as("count")).where("status","=",G);if(x&&J){let K=E(x),L=E(J);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.executeTakeFirst())?.count??0}async function o$(G,x){let J=q.selectFrom("waitlist_products").select(["status",(Z)=>Z.fn.count("id").as("count")]).groupBy("status");if(G&&x){let Z=E(G),Y=E(x);J=J.where("created_at",">=",Z).where("created_at","<=",Y)}let X=await J.execute(),$=X.reduce((Z,{count:Y})=>Z+Y,0),K=X.find((Z)=>Z.status==="purchased")?.count??0,L=$>0?K/$*100:0,M=X.reduce((Z,{status:Y,count:H})=>{return Z[Y]={count:H,percentage:$>0?H/$*100:0},Z},{});return{totalConversionRate:L,statusBreakdown:M}}async function i$(G,x){let J=E(G),X=E(x);return(await q.selectFrom("waitlist_products").select((K)=>K.fn.count("id").as("count")).where("created_at",">=",J).where("created_at","<=",X).executeTakeFirst())?.count??0}async function s$(G,x){let J=q.selectFrom("waitlist_products").select(["created_at"]);if(G&&x){let K=E(G),L=E(x);J=J.where("created_at",">=",K).where("created_at","<=",L)}let $=(await J.execute()).reduce((K,{created_at:L})=>{let M=(L||"").split("T")[0]||"unknown";return K[M]=(K[M]||0)+1,K},{});return Object.entries($).map(([K,L])=>({date:K,count:L})).sort((K,L)=>K.date.localeCompare(L.date))}var{randomUUIDv7:d$}=globalThis.Bun;import{db as a$}from"@stacksjs/database";import{formatDate as xx}from"@stacksjs/orm";async function t$(G){try{let x=G,J={name:G.name,email:G.email,phone:G.phone,quantity:G.quantity??x.party_size,notification_preference:x.notification_preference,source:G.source,notes:G.notes,product_id:G.product_id,customer_id:G.customer_id,uuid:d$(),status:G.status||"waiting"};if(G.notified_at!==void 0)J.notified_at=typeof G.notified_at==="number"?xx(G.notified_at):G.notified_at;if(G.purchased_at!==void 0)J.purchased_at=typeof G.purchased_at==="number"?xx(G.purchased_at):G.purchased_at;if(G.cancelled_at!==void 0)J.cancelled_at=typeof G.cancelled_at==="number"?xx(G.cancelled_at):G.cancelled_at;let X=await a$.insertInto("waitlist_products").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create waitlist product");return X}catch(x){if(x instanceof Error)throw TypeError(`Failed to create waitlist product: ${x.message}`);throw x}}async function r$(G){if(!G.length)return 0;try{let x=G.map((X)=>{let $=X,K={name:X.name,email:X.email,phone:X.phone,quantity:X.quantity??$.party_size,notification_preference:$.notification_preference,source:X.source,notes:X.notes,product_id:X.product_id,customer_id:X.customer_id,uuid:d$(),status:X.status||"waiting"};if(X.notified_at!==void 0)K.notified_at=typeof X.notified_at==="number"?xx(X.notified_at):X.notified_at;if(X.purchased_at!==void 0)K.purchased_at=typeof X.purchased_at==="number"?xx(X.purchased_at):X.purchased_at;if(X.cancelled_at!==void 0)K.cancelled_at=typeof X.cancelled_at==="number"?xx(X.cancelled_at):X.cancelled_at;return K}),J=await a$.insertInto("waitlist_products").values(x).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${x.message}`);throw x}}import{db as iG}from"@stacksjs/database";import{formatDate as sG}from"@stacksjs/orm";async function e$(G,x){try{if(!G)throw Error("Waitlist product ID is required for update");let J=x,X=await iG.updateTable("waitlist_products").set({name:x.name,email:x.email,phone:x.phone,quantity:x.quantity??J.party_size,notification_preference:J.notification_preference,source:x.source,notes:x.notes,status:x.status,product_id:x.product_id,customer_id:x.customer_id,notified_at:J.notified_at,purchased_at:J.purchased_at,cancelled_at:J.cancelled_at,updated_at:sG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update waitlist product");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to update waitlist product: ${J.message}`);throw J}}async function x1(G,x){try{let J=await iG.updateTable("waitlist_products").set({status:x,updated_at:sG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update waitlist product status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update waitlist product status: ${J.message}`);throw J}}async function G1(G,x){try{let J=await iG.updateTable("waitlist_products").set({quantity:x,updated_at:sG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update party size");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update party size: ${J.message}`);throw J}}var Gx={};B(Gx,{updateWaitTimes:()=>_1,updateStatus:()=>w1,updateQueuePosition:()=>I1,updatePartySize:()=>C1,update:()=>j1,store:()=>S1,fetchWaitingWithQuotedTimes:()=>A1,fetchWaitingWithPartySizes:()=>B1,fetchWaiting:()=>F1,fetchTimeSeriesStats:()=>U1,fetchTablesTurnedToday:()=>V1,fetchSeatingRate:()=>z1,fetchSeatedStats:()=>R1,fetchSeatedBetweenDates:()=>W1,fetchNoShowStats:()=>O1,fetchCurrentWaitTimes:()=>E1,fetchCountByTablePreference:()=>L1,fetchCountByPartySize:()=>Y1,fetchCountByDate:()=>M1,fetchCountByAllPartySizes:()=>Z1,fetchConversionRates:()=>N1,fetchById:()=>$1,fetchBetweenDates:()=>H1,fetchAverageWaitTimes:()=>Q1,fetchAll:()=>K1,destroy:()=>J1,bulkStore:()=>k1,bulkDestroy:()=>X1});import{db as JG}from"@stacksjs/database";async function J1(G){try{let x=await JG.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst();if(!x)return;return await JG.deleteFrom("waitlist_restaurants").where("id","=",G).execute(),x}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${x.message}`);throw x}}async function X1(G){if(!G.length)return 0;try{return(await JG.deleteFrom("waitlist_restaurants").where("id","in",G).execute()).length||0}catch(x){if(x instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${x.message}`);throw x}}import{db as O}from"@stacksjs/database";import{formatDate as w}from"@stacksjs/orm";async function $1(G){return await O.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst()}async function K1(){return await O.selectFrom("waitlist_restaurants").selectAll().execute()}async function L1(){return(await O.selectFrom("waitlist_restaurants").select(["table_preference",(x)=>x.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((x,{table_preference:J,count:X})=>{return x[J]=X,x},{})}async function M1(G=new Date){let x=new Date(G);x.setHours(0,0,0,0);let J=new Date(G);J.setHours(23,59,59,999);let X=w(x),$=w(J);return(await O.selectFrom("waitlist_restaurants").select((L)=>L.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",$).executeTakeFirst())?.count??0}async function Y1(G){return(await O.selectFrom("waitlist_restaurants").select((J)=>J.fn.count("id").as("count")).where("party_size","=",G).executeTakeFirst())?.count??0}async function Z1(){return(await O.selectFrom("waitlist_restaurants").select(["party_size",(x)=>x.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((x,{party_size:J,count:X})=>{return x[J]=X,x},{})}async function H1(G,x){let J=w(G),X=w(x);return await O.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",J).where("created_at","<=",X).execute()}async function W1(G,x){let J=w(G),X=w(x);return await O.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",J).where("check_in_time","<=",X).where("status","=","seated").execute()}async function F1(){return await O.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function N1(){let G=await O.selectFrom("waitlist_restaurants").select(["status",(K)=>K.fn.count("id").as("count")]).groupBy("status").execute(),x=G.reduce((K,{count:L})=>K+L,0),J=G.find((K)=>K.status==="seated")?.count??0,X=x>0?Number(J)/x*100:0,$=G.reduce((K,{status:L,count:M})=>{return K[L]={count:M,percentage:x>0?M/x*100:0},K},{});return{totalConversionRate:X,statusBreakdown:$}}async function Q1(){let G=await O.selectFrom("waitlist_restaurants").select([(x)=>x.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),(x)=>x.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:G?.avg_quoted_wait_time??0,averageActualWaitTime:G?.avg_actual_wait_time??0}}async function A1(){let G=await O.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),x=G.reduce((X,$)=>X+($.quoted_wait_time??0),0),J=G.length>0?x/G.length:0;return{entries:G,totalQuotedWaitTime:x,averageQuotedWaitTime:J}}async function B1(){let G=await O.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),x=G.reduce(($,K)=>$+K.party_size,0),J=G.length>0?x/G.length:0,X=G.reduce(($,K)=>{return $[K.party_size]=($[K.party_size]||0)+1,$},{});return{entries:G,totalPartySize:x,averagePartySize:J,partySizeBreakdown:X}}async function V1(){let G=new Date,x=new Date(G);x.setHours(0,0,0,0);let J=new Date(G);J.setHours(23,59,59,999);let X=w(x),$=w(J),K=await O.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",X).where("check_in_time","<=",$).execute(),L=K.length,M=K.reduce((W,F)=>W+F.party_size,0),Z=L>0?M/L:0,Y=K.reduce((W,F)=>{return W[F.table_preference]=(W[F.table_preference]||0)+1,W},{}),H=K.reduce((W,F)=>{return W[F.party_size]=(W[F.party_size]||0)+1,W},{});return{totalTablesTurned:L,averagePartySize:Z,totalCustomersSeated:M,breakdownByTablePreference:Y,breakdownByPartySize:H}}async function z1(G,x){let J=w(G),X=w(x),$=await O.selectFrom("waitlist_restaurants").select(["status",(Y)=>Y.fn.count("id").as("count")]).where("check_in_time",">=",J).where("check_in_time","<=",X).groupBy("status").execute(),K=$.reduce((Y,{count:H})=>Y+H,0),L=$.find((Y)=>Y.status==="seated")?.count??0,M=K>0?Number(L)/K*100:0,Z=$.reduce((Y,{status:H,count:W})=>{return Y[H]={count:W,percentage:K>0?W/K*100:0},Y},{});return{totalEntries:K,seatedEntries:L,seatingRate:M,statusBreakdown:Z}}async function O1(G,x){let J=w(G),X=w(x),$=O.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",J).where("check_in_time","<=",X),K=await O.selectFrom("waitlist_restaurants").select((N)=>N.fn.count("id").as("count")).where("check_in_time",">=",J).where("check_in_time","<=",X).executeTakeFirst(),L=await $.execute(),M=L.length,Z=K?.count&&K.count>0?M/K.count*100:0,Y=L.reduce((N,z)=>N+(z.quoted_wait_time??0),0),H=M>0?Y/M:0,W=L.reduce((N,z)=>N+z.party_size,0),F=M>0?W/M:0,Q=L.reduce((N,z)=>{return N[z.table_preference]=(N[z.table_preference]||0)+1,N},{}),A=L.reduce((N,z)=>{return N[z.party_size]=(N[z.party_size]||0)+1,N},{});return{totalNoShows:M,noShowRate:Z,averageQuotedWaitTime:H,averagePartySize:F,breakdownByTablePreference:Q,breakdownByPartySize:A}}async function E1(){let G=await O.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),x=G.reduce(($,K)=>$+(K.quoted_wait_time||0),0),J=G.reduce(($,K)=>$+(K.actual_wait_time||0),0),X=G.length;return{averageQuoted:X>0?x/X:0,averageActual:X>0?J/X:0}}async function R1(){let G=Date.now()-86400000,x=await O.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",G).execute(),J=Array.from({length:24},(X,$)=>({hour:$,count:x.filter((K)=>{return K.seated_at===$}).length}));return{total:x.length,byHour:J}}async function U1(){return(await O.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((x,J)=>{let X=J.created_at;if(!x[X])x[X]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return x[X].total++,x[X][J.status]++,x},{})}var{randomUUIDv7:q1}=globalThis.Bun;import{db as T1}from"@stacksjs/database";import{formatDate as P1}from"@stacksjs/orm";async function S1(G){try{let x=G,J={name:G.name,email:G.email,phone:G.phone,party_size:x.party_size,check_in_time:typeof x.check_in_time==="number"?P1(x.check_in_time):x.check_in_time,table_preference:x.table_preference,status:G.status||"waiting",quoted_wait_time:G.quoted_wait_time,actual_wait_time:G.actual_wait_time,queue_position:G.queue_position,customer_id:G.customer_id,uuid:q1()},X={};for(let[L,M]of Object.entries(J))if(M!==void 0)X[L]=M;let $=await T1.insertInto("waitlist_restaurants").values(X).returningAll().executeTakeFirst();if(!$)throw Error("Failed to create restaurant waitlist entry");let K={...$};for(let L of Object.keys(K))if(K[L]===null)K[L]=void 0;return K}catch(x){if(x instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${x.message}`);throw x}}async function k1(G){if(!G.length)return 0;try{let x=G.map((X)=>{let $=X;return{name:X.name,email:X.email,phone:X.phone,party_size:$.party_size,check_in_time:typeof $.check_in_time==="number"?P1($.check_in_time):$.check_in_time,table_preference:$.table_preference,status:X.status||"waiting",quoted_wait_time:X.quoted_wait_time,actual_wait_time:X.actual_wait_time,queue_position:X.queue_position,customer_id:X.customer_id,uuid:q1()}}),J=await T1.insertInto("waitlist_restaurants").values(x).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows)}catch(x){if(x instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${x.message}`);throw x}}import{db as Nx}from"@stacksjs/database";import{formatDate as Qx}from"@stacksjs/orm";async function j1(G,x){try{if(!G)throw Error("Restaurant waitlist entry ID is required for update");let J=x,X=await Nx.updateTable("waitlist_restaurants").set({name:x.name,email:x.email,phone:x.phone,party_size:J.party_size,check_in_time:J.check_in_time?Math.floor(new Date(J.check_in_time).getTime()/1000):void 0,table_preference:J.table_preference,status:x.status,quoted_wait_time:x.quoted_wait_time,actual_wait_time:x.actual_wait_time,queue_position:x.queue_position,customer_id:x.customer_id,updated_at:Qx(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update restaurant waitlist entry");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${J.message}`);throw J}}async function w1(G,x){try{let J=await Nx.updateTable("waitlist_restaurants").set({status:x,updated_at:Qx(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update restaurant waitlist entry status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry status: ${J.message}`);throw J}}async function C1(G,x){try{let J=await Nx.updateTable("waitlist_restaurants").set({party_size:x,updated_at:Qx(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update party size");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update party size: ${J.message}`);throw J}}async function _1(G,x,J){try{let X=await Nx.updateTable("waitlist_restaurants").set({quoted_wait_time:x,actual_wait_time:J,updated_at:Qx(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update wait times");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update wait times: ${X.message}`);throw X}}async function I1(G,x){try{let J=await Nx.updateTable("waitlist_restaurants").set({queue_position:x,updated_at:Qx(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update queue position");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update queue position: ${J.message}`);throw J}}var W4={products:GG,restaurant:Gx},F4=W4;var N4={coupons:XG,customers:KG,devices:ZG,errors:FG,giftCards:VG,orders:EG,payments:RG,products:wG,receipts:IG,restaurant:Gx,shippings:cG,tax:oG,waitlists:dG},U0=N4;export{dG as waitlists,oG as tax,cG as shippings,Gx as restaurant,IG as receipts,wG as products,RG as payments,EG as orders,VG as giftCards,FG as errors,ZG as devices,U0 as default,KG as customers,XG as coupons,N4 as commerce};
|
|
38
|
+
</Relationships>`))},{name:"xl/workbook.xml",content:G},{name:"xl/worksheets/sheet1.xml",content:new Uint8Array(UG.from(X))}],Y=L.map((F)=>{let x=new Uint8Array(y9(F.content)),A=new Uint8Array(30+F.name.length),Q=new DataView(A.buffer);Q.setUint32(0,67324752,!0),Q.setUint32(4,8,!0),Q.setUint32(18,x.length,!0),Q.setUint32(22,F.content.length,!0),Q.setUint16(26,F.name.length,!0);let B=new TextEncoder;return A.set(B.encode(F.name),30),{header:A,compressedContent:x}}),Z=L.map((F,x)=>{let A=new Uint8Array(46+F.name.length),Q=new DataView(A.buffer);Q.setUint32(0,33639248,!0),Q.setUint16(4,20,!0),Q.setUint16(6,8,!0),Q.setUint32(8,8,!0),Q.setUint32(20,Y[x].compressedContent.length-30-F.name.length,!0),Q.setUint32(42,Y.slice(0,x).reduce((C,f)=>C+f.header.length+f.compressedContent.length,0),!0),Q.setUint16(28,F.name.length,!0);let B=new TextEncoder;return A.set(B.encode(F.name),46),A}),W=new Uint8Array(22),M=Y.reduce((F,{header:x,compressedContent:A})=>F+x.length+A.length,0)+Z.reduce((F,x)=>F+x.length,0)+W.length,N=new Uint8Array(M),H=0;for(let{header:F,compressedContent:x}of Y)N.set(F,H),H+=F.length,N.set(x,H),H+=x.length;for(let F of Z)N.set(F,H),H+=F.length;return N.set(W,H),N}import{db as eX}from"@stacksjs/database";async function g(J){return await eX.selectFrom("print_devices").where("id","=",J).selectAll().executeTakeFirst()}async function qG(){return await eX.selectFrom("print_devices").selectAll().execute()}async function PG(J="csv"){let G=await qG(),X=m9(G);return TG(X,{type:J})}function m9(J){let G=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],X=J.map(($)=>{return[$.id,$.name,$.macAddress,$.location,$.terminal,$.status,new Date($.lastPing).toLocaleString(),$.printCount]});return{headings:G,data:X}}async function G6(J="csv",G){let X=await PG(J),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;return X.download(G||$)}async function J6(J="csv",G){let X=await PG(J),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${J}`;X.store(G||$)}var{randomUUIDv7:X6}=globalThis.Bun;import{db as OJ}from"@stacksjs/database";async function $6(J){try{let G={...J,uuid:X6()},X=await OJ.insertInto("print_devices").values(G).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await OJ.selectFrom("print_devices").where("id","=",$).selectAll().executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to create print device: ${G.message}`);throw G}}async function K6(J){if(!J.length)return 0;let G=0;try{for(let X of J){let $={...X,uuid:X6()};await OJ.insertInto("print_devices").values($).execute(),G++}return G}catch(X){if(X instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${X.message}`);throw X}}import{db as RJ}from"@stacksjs/database";import{formatDate as UJ}from"@stacksjs/orm";async function L6(J,G){if(!await g(J))throw Error(`Print device with ID ${J} not found`);try{return await RJ.updateTable("print_devices").set({...G,updated_at:UJ(new Date)}).where("id","=",J).execute(),await g(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device: ${$.message}`);throw $}}async function Y6(J,G){if(!await g(J))throw Error(`Print device with ID ${J} not found`);try{return await RJ.updateTable("print_devices").set({status:G,updated_at:UJ(new Date)}).where("id","=",J).execute(),await g(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device status: ${$.message}`);throw $}}async function Z6(J,G){if(!await g(J))throw Error(`Print device with ID ${J} not found`);try{return await RJ.updateTable("print_devices").set({print_count:G,updated_at:UJ(new Date)}).where("id","=",J).execute(),await g(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print count: ${$.message}`);throw $}}var SJ={};V(SJ,{update:()=>V6,unresolveGroup:()=>O6,resolveGroup:()=>z6,ignoreGroup:()=>E6,fetchTimeline:()=>A6,fetchStats:()=>x6,fetchGrouped:()=>F6,fetchById:()=>H6,fetchByGroup:()=>Q6,fetchAll:()=>jG,destroyGroup:()=>N6,destroy:()=>M6,bulkUpdateStatus:()=>B6,bulkDestroy:()=>W6});import{db as qJ}from"@stacksjs/database";import{log as PJ}from"@stacksjs/logging";async function M6(J){try{return await qJ.deleteFrom("errors").where("id","=",J).execute(),!0}catch(G){return PJ.error("[commerce/errors] destroy failed",{id:J,error:G}),!1}}async function W6(J){try{return await qJ.deleteFrom("errors").where("id","in",J).execute(),!0}catch(G){return PJ.error("[commerce/errors] bulkDestroy failed",{count:J.length,error:G}),!1}}async function N6(J,G){try{return await qJ.deleteFrom("errors").where("type","=",J).where("message","=",G).execute(),!0}catch(X){return PJ.error("[commerce/errors] destroyGroup failed",{type:J,message:G,error:X}),!1}}import{db as SG}from"@stacksjs/database";async function H6(J){return await SG.selectFrom("errors").where("id","=",J).selectAll().executeTakeFirst()}async function jG(){return await SG.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function F6(){let J=await SG.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),G=new Map;for(let $ of J){let K=`${$.type}:${$.message}`;if(!G.has(K))G.set(K,{errors:[],firstSeen:new Date($.created_at),lastSeen:new Date($.created_at)});let L=G.get(K);L.errors.push($);let Y=new Date($.created_at);if(Y<L.firstSeen)L.firstSeen=Y;if(Y>L.lastSeen)L.lastSeen=Y}let X=[];for(let[$,K]of G){let L=K.errors[0],Y=K.errors.find((W)=>W.status!==null)?.status,Z="unresolved";if(Y===1)Z="resolved";else if(Y===2)Z="ignored";X.push({id:L.id,type:L.type,message:L.message,stack:L.stack,status:Z,count:K.errors.length,first_seen:K.firstSeen.toISOString(),last_seen:K.lastSeen.toISOString(),error_ids:K.errors.map((W)=>W.id)})}return X.sort(($,K)=>new Date(K.last_seen).getTime()-new Date($.last_seen).getTime()),X}async function Q6(J,G){return await SG.selectFrom("errors").where("type","=",J).where("message","=",G).selectAll().orderBy("created_at","desc").execute()}async function x6(){let J=await jG(),G=new Date,X=new Date(G.getTime()-86400000),$=new Date(G.getTime()-172800000),K=J.filter((Z)=>new Date(Z.created_at)>=X).length,L=J.filter((Z)=>{let W=new Date(Z.created_at);return W>=$&&W<X}).length,Y=L===0?K>0?100:0:Math.round((K-L)/L*100);return{total:J.length,unresolved:J.filter((Z)=>Z.status===null||Z.status===0).length,resolved:J.filter((Z)=>Z.status===1).length,ignored:J.filter((Z)=>Z.status===2).length,last_24h:K,trend:Y}}async function A6(){let J=await jG(),G=new Date,X=[];for(let $=23;$>=0;$--){let K=new Date(G.getTime()-$*60*60*1000);K.setMinutes(0,0,0);let L=new Date(K.getTime()+3600000),Y=J.filter((Z)=>{let W=new Date(Z.created_at);return W>=K&&W<L}).length;X.push({hour:K.toISOString(),count:Y})}return X}import{db as MG}from"@stacksjs/database";import{sql as WG}from"@stacksjs/database";import{log as NG}from"@stacksjs/logging";async function V6(J,G){try{return await MG.updateTable("errors").set({...G,updated_at:WG.raw("CURRENT_TIMESTAMP")}).where("id","=",J).execute(),!0}catch(X){return NG.error("[commerce/errors] update failed",{id:J,error:X}),!1}}async function B6(J,G){try{return await MG.updateTable("errors").set({status:G,updated_at:WG.raw("CURRENT_TIMESTAMP")}).where("id","in",J).execute(),!0}catch(X){return NG.error("[commerce/errors] bulkUpdateStatus failed",{count:J.length,status:G,error:X}),!1}}async function z6(J,G){try{return await MG.updateTable("errors").set({status:1,updated_at:WG.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",G).execute(),!0}catch(X){return NG.error("[commerce/errors] resolveGroup failed",{type:J,message:G,error:X}),!1}}async function E6(J,G){try{return await MG.updateTable("errors").set({status:2,updated_at:WG.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",G).execute(),!0}catch(X){return NG.error("[commerce/errors] ignoreGroup failed",{type:J,message:G,error:X}),!1}}async function O6(J,G){try{return await MG.updateTable("errors").set({status:0,updated_at:WG.raw("CURRENT_TIMESTAMP")}).where("type","=",J).where("message","=",G).execute(),!0}catch(X){return NG.error("[commerce/errors] unresolveGroup failed",{type:J,message:G,error:X}),!1}}var CJ={};V(CJ,{updateBalance:()=>y6,update:()=>h6,store:()=>f6,fetchTotalValue:()=>j6,fetchTotalCurrentBalance:()=>k6,fetchStats:()=>T6,fetchById:()=>h,fetchByCode:()=>kJ,fetchAll:()=>R6,fetchActive:()=>U6,destroy:()=>_6,compareActiveGiftCards:()=>P6,checkBalance:()=>q6,calculateGiftCardValues:()=>S6,bulkDestroy:()=>C6});import{db as _J}from"@stacksjs/database";import{formatDate as sL}from"@stacksjs/orm";import{db as k,sql as jJ}from"@stacksjs/database";import{formatDate as m,toTimestamp as e}from"@stacksjs/orm";import{db as b9}from"@stacksjs/database";async function p(J,G,X){let $=b9.selectFrom(J);if(X)$=X($);$=$.select((Y)=>Object.entries(G).map(([Z,W])=>{let M=W.column??"id",N=Y.fn[W.kind](M);if(W.filter){let H=W.filter;N=N.filterWhere(H.column,H.op,H.value)}return N.as(Z)}));let K=await $.executeTakeFirst(),L={};for(let Y of Object.keys(G)){let Z=K?.[Y];L[Y]=typeof Z==="number"?Z:Number(Z??0)||0}return L}async function R6(){return await k.selectFrom("gift_cards").selectAll().execute()}async function h(J){return await k.selectFrom("gift_cards").where("id","=",J).selectAll().executeTakeFirst()}async function kJ(J){return await k.selectFrom("gift_cards").where("code","=",J).selectAll().executeTakeFirst()}async function U6(){return await k.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function T6(){let{count:J}=await p("gift_cards",{count:{kind:"count"}}),G=e(new Date),X=await k.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where((N)=>N.or([N("expiry_date",">=",G),N("expiry_date","is",null)])).select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),$=await k.selectFrom("gift_cards").select(["status",(N)=>N.fn.count("id").as("count")]).groupBy("status").execute(),{count:K}=await p("gift_cards",{count:{kind:"count"}},(N)=>N.where((H)=>jJ`${H.ref("current_balance")} / ${H.ref("initial_balance")} < 0.25`)),{count:L}=await p("gift_cards",{count:{kind:"count"}},(N)=>N.where((H)=>jJ`${H.ref("current_balance")} / ${H.ref("initial_balance")} >= 0.25 AND ${H.ref("current_balance")} / ${H.ref("initial_balance")} <= 0.75`)),{count:Y}=await p("gift_cards",{count:{kind:"count"}},(N)=>N.where((H)=>jJ`${H.ref("current_balance")} / ${H.ref("initial_balance")} > 0.75`)),Z=new Date;Z.setDate(Z.getDate()+30);let W=await k.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",e(Z)).where("expiry_date",">=",G).selectAll().limit(5).execute(),M=await k.selectFrom("gift_cards").where("last_used_date","is not",null).selectAll().limit(5).execute();return{total:J,active:Number(X?.count||0),by_status:$.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:K,medium:L,high:Y},expiring_soon:W,recently_used:M}}async function q6(J){let G=await kJ(J);if(!G)return{valid:!1,message:"Gift card not found"};if(!G.isActive||G.status!=="ACTIVE")return{valid:!1,balance:G.currentBalance,currency:G.currency,message:`Gift card is ${G.status.toLowerCase()}`};if(G.expiryDate){if(new Date(G.expiryDate)<new Date)return{valid:!1,balance:G.currentBalance,currency:G.currency,message:"Gift card has expired"}}return{valid:!0,balance:G.currentBalance,currency:G.currency}}async function P6(J=30){let G=new Date,X=new Date(G);X.setDate(G.getDate()-J);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-J);let L=await k.selectFrom("gift_cards").select((H)=>H.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").where((H)=>H.or([H("expiry_date",">=",e(G)),H("expiry_date","is",null)])).where("created_at",">=",m(X)).where("created_at","<=",m(G)).executeTakeFirst(),Y=await k.selectFrom("gift_cards").select((H)=>H.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").where((H)=>H.or([H("expiry_date",">=",e(K)),H("expiry_date","is",null)])).where("created_at",">=",m(K)).where("created_at","<=",m($)).executeTakeFirst(),Z=Number(L?.count||0),W=Number(Y?.count||0),M=Z-W,N=W!==0?M/W*100:Z>0?100:0;return{current_period:Z,previous_period:W,difference:M,percentage_change:N,days_range:J}}async function S6(J=30){let G=new Date,X=new Date(G);X.setDate(G.getDate()-J);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-J);let L=await k.selectFrom("gift_cards").select((P)=>[P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").where((P)=>P.or([P("expiry_date",">=",e(G)),P("expiry_date","is",null)])).where("created_at",">=",m(X)).where("created_at","<=",m(G)).executeTakeFirst(),Y=await k.selectFrom("gift_cards").select((P)=>[P.fn.sum("initial_balance").as("total_initial"),P.fn.sum("current_balance").as("total_balance"),P.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").where((P)=>P.or([P("expiry_date",">=",e(K)),P("expiry_date","is",null)])).where("created_at",">=",m(K)).where("created_at","<=",m($)).executeTakeFirst(),Z=Number(L?.total_initial||0),W=Number(L?.total_balance||0),M=Number(L?.card_count||0),N=Number(Y?.total_initial||0),H=Number(Y?.total_balance||0),F=Number(Y?.card_count||0),x=Z>0?(Z-W)/Z*100:0,A=N>0?(N-H)/N*100:0,Q=M>0?Z/M:0,B=M>0?W/M:0,C=Z-N,f=W-H,l=M-F,t=N!==0?C/N*100:Z>0?100:0,R=H!==0?f/H*100:W>0?100:0,v=F!==0?l/F*100:M>0?100:0;return{current_period:{total_initial_value:Z,total_remaining_balance:W,utilization_rate:x,card_count:M,average_initial_value:Q,average_remaining_balance:B},previous_period:{total_initial_value:N,total_remaining_balance:H,utilization_rate:A,card_count:F},comparison:{initial_value:{difference:C,percentage:Math.abs(t),is_increase:C>=0},balance:{difference:f,percentage:Math.abs(R),is_increase:f>=0},card_count:{difference:l,percentage:Math.abs(v),is_increase:l>=0}},days_range:J}}async function j6(){let{total_value:J}=await p("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:J}}async function k6(){let{total_balance:J}=await p("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:J}}async function _6(J){if(!await h(J))throw Error(`Gift card with ID ${J} not found`);return!!await _J.deleteFrom("gift_cards").where("id","=",J).executeTakeFirst()}async function C6(J){if(!J.length)return 0;let G=await _J.deleteFrom("gift_cards").where("id","in",J).executeTakeFirst();return Number(G?.numDeletedRows)||0}var{randomUUIDv7:l9}=globalThis.Bun;import{db as w6}from"@stacksjs/database";import{HttpError as I6}from"@stacksjs/error-handling";import{isUniqueViolation as c9}from"@stacksjs/orm";async function f6(J){let G=J,X={...J,current_balance:G.current_balance??G.initial_balance,status:J.status||"ACTIVE",is_active:G.is_active??!0,uuid:l9()};try{let $=await w6.insertInto("gift_cards").values(X).executeTakeFirst(),K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);if(K)return await w6.selectFrom("gift_cards").where("id","=",K).selectAll().executeTakeFirst();return}catch($){if($ instanceof I6)throw $;if(c9($))throw new I6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to create gift card: ${$.message}`);throw $}}import{db as kG}from"@stacksjs/database";import{HttpError as v6}from"@stacksjs/error-handling";import{formatDate as g6,isUniqueViolation as u9}from"@stacksjs/orm";async function h6(J,G){if(!await h(J))throw Error(`Gift card with ID ${J} not found`);try{return await kG.updateTable("gift_cards").set({...G,updated_at:g6(new Date)}).where("id","=",J).execute(),await h(J)}catch($){if($ instanceof v6)throw $;if(u9($))throw new v6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to update gift card: ${$.message}`);throw $}}async function y6(J,G){let X=g6(new Date),$=await kG.updateTable("gift_cards").set({current_balance:kG.raw(`current_balance + ${G}`),last_used_date:X,status:kG.raw(`CASE WHEN current_balance + ${G} = 0 THEN 'USED' ELSE 'ACTIVE' END`),updated_at:X}).where("id","=",J).where("is_active","=",1).where("status","=","ACTIVE").where((Y)=>Y.cmpr(Y.raw(`current_balance + ${G}`),">=",0)).executeTakeFirst();if(Number($?.numUpdatedRows??$?.affectedRows??0)>0)return await h(J);let L=await h(J);if(!L)throw Error(`Gift card with ID ${J} not found`);if(!L.is_active||L.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var bJ={};V(bJ,{validateQuantityBounds:()=>mJ,validateCouponStacking:()=>W$,validateCartQuantities:()=>N$,updateStatus:()=>$$,updateDeliveryInfo:()=>K$,update:()=>X$,storeOrdersExport:()=>u6,store:()=>r6,softDelete:()=>p6,registerCommerceWebhookHandlers:()=>Y$,recomputeOrderTotals:()=>M$,placeOrder:()=>J$,handlePaymentIntentSucceeded:()=>yJ,handlePaymentIntentFailed:()=>DJ,handleChargeRefunded:()=>pJ,fetchStats:()=>o6,fetchDailyOrderTrends:()=>d6,fetchById:()=>y,fetchAll:()=>n6,exportOrders:()=>CG,emitOrderShipped:()=>wJ,emitOrderRefunded:()=>FG,emitOrderPaid:()=>u,emitOrderDelivered:()=>IJ,emitOrderCreated:()=>IG,emitOrderCancelled:()=>HG,emitForStatus:()=>fG,downloadOrders:()=>c6,destroy:()=>D6,compareOrdersByPeriod:()=>i6,cleanupAbandonedCarts:()=>H$,canTransition:()=>wG,calculateOrderMetrics:()=>s6,bulkSoftDelete:()=>b6,bulkDestroy:()=>m6});import{db as _G}from"@stacksjs/database";async function D6(J){try{let G=await _G.deleteFrom("orders").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete order: ${G.message}`);throw G}}async function p6(J){try{let G=await _G.updateTable("orders").set({status:"CANCELED"}).where("id","=",J).executeTakeFirst();return Number(G.numUpdatedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to soft delete order: ${G.message}`);throw G}}async function m6(J){if(!J.length)return 0;try{let G=await _G.deleteFrom("orders").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete orders: ${G.message}`);throw G}}async function b6(J){if(!J.length)return 0;try{let G=await _G.updateTable("orders").set({status:"CANCELED"}).where("id","in",J).executeTakeFirst();return Number(G.numUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to soft delete orders: ${G.message}`);throw G}}import{db as l6}from"@stacksjs/database";async function CG(J="csv"){let G=await n9(),X=o9(G);return TG(X,{type:J})}async function n9(){let J=await l6.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),G=J.map((L)=>L.id);if(G.length===0)return[];let $=(await l6.selectFrom("order_items").where("order_items.order_id","in",G).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((L,Y)=>{if(!Y.order_id)return L;if(!L[Y.order_id])L[Y.order_id]={totalItems:0,totalPrice:0};return L[Y.order_id].totalItems+=Y.quantity,L[Y.order_id].totalPrice+=Y.price*Y.quantity,L},{});return J.map((L)=>{let Y=$[L.id]||{totalItems:0,totalPrice:0};return{...L,totalItems:Y.totalItems,totalPrice:Y.totalPrice}})}function o9(J){let G=["Order ID","Customer","Date","Total","Status","Items"],X=J.map(($)=>{let K=$.order_items?.map((L)=>`${L.product?.name} (Qty: ${L.quantity}, Price: $${L.price})`).join(" | ")||"No Items";return[$.id,$.customer?.name||"N/A",$.created_at,$.total_amount,$.status,K]});return{headings:G,data:X}}async function c6(J="csv",G){let X=await CG(J),$=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;return X.download(G||$)}async function u6(J="csv",G){let X=await CG(J),$=`orders_export_${new Date().toISOString().split("T")[0]}.${J}`;X.store(G||$)}import{db as q}from"@stacksjs/database";async function n6(J){let G=q.selectFrom("orders").selectAll().orderBy("created_at","desc");if(J)G=G.limit(J);let X=await G.execute();return await Promise.all(X.map(async($)=>{let K=await q.selectFrom("order_items").where("order_id","=",$.id).selectAll().execute();return{...$,items:K}}))}async function y(J){return await q.selectFrom("orders").where("id","=",J).selectAll().executeTakeFirst()}async function o6(){let J=await q.selectFrom("orders").select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),G=await q.selectFrom("orders").select(["status",(Y)=>Y.fn.count("id").as("count")]).groupBy("status").execute(),X=await q.selectFrom("orders").select(["order_type",(Y)=>Y.fn.count("id").as("count")]).groupBy("order_type").execute(),$=await q.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),K=await Promise.all($.map(async(Y)=>{let Z=await q.selectFrom("order_items").where("order_id","=",Y.id).selectAll().execute();return{...Y,items:Z}})),L=await q.selectFrom("orders").select((Y)=>Y.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(J?.count||0),by_status:G,by_type:X,recent:K,revenue:Number(L?.total||0)}}async function i6(J=30){let G=new Date,X=new Date(G);X.setDate(G.getDate()-J);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-J);let L=await q.selectFrom("orders").select((H)=>H.fn.count("id").as("count")).where("created_at",">=",X.toISOString()).where("created_at","<=",G.toISOString()).executeTakeFirst(),Y=await q.selectFrom("orders").select((H)=>H.fn.count("id").as("count")).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),Z=Number(L?.count||0),W=Number(Y?.count||0),M=Z-W,N=W!==0?M/W*100:Z>0?100:0;return{current_period:Z,previous_period:W,difference:M,percentage_change:N,days_range:J}}async function s6(J=30){let G=new Date,X=new Date(G);X.setDate(G.getDate()-J);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-J);let L=await q.selectFrom("orders").select((R)=>[R.fn.count("id").as("total_orders"),R.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",X.toISOString()).where("created_at","<=",G.toISOString()).executeTakeFirst(),Y=await q.selectFrom("orders").select((R)=>[R.fn.count("id").as("total_orders"),R.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),Z=await q.selectFrom("orders").select(["status",(R)=>R.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",G.toISOString()).groupBy("status").execute(),W=await q.selectFrom("orders").select(["order_type",(R)=>R.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",G.toISOString()).groupBy("order_type").execute(),M=Number(L?.total_orders||0),N=Number(L?.total_revenue||0),H=M>0?N/M:0,F=Number(Y?.total_orders||0),x=Number(Y?.total_revenue||0),A=F>0?x/F:0,Q=M-F,B=N-x,C=H-A,f=F!==0?Q/F*100:M>0?100:0,l=x!==0?B/x*100:N>0?100:0,t=A!==0?C/A*100:H>0?100:0;return{current_period:{total_orders:M,total_revenue:N,average_order_value:H,orders_by_status:Z.map((R)=>({status:R.status,count:Number(R.count)})),orders_by_type:W.map((R)=>({order_type:R.order_type,count:Number(R.count)}))},previous_period:{total_orders:F,total_revenue:x,average_order_value:A},comparison:{orders:{difference:Q,percentage:Math.abs(f),is_increase:Q>=0},revenue:{difference:B,percentage:Math.abs(l),is_increase:B>=0},average_order_value:{difference:C,percentage:Math.abs(t),is_increase:C>=0}},days_range:J}}async function d6(J=30){let G=new Date,X=new Date(G);X.setDate(G.getDate()-J);let $=await q.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",X.toISOString()).where("created_at","<=",G.toISOString()).orderBy("created_at","asc").execute(),K=new Map;for(let L of $){let Y=(L.created_at||"").split("T")[0]||"unknown",Z=K.get(Y)||{order_count:0,revenue:0};Z.order_count++,Z.revenue+=Number(L.total_amount||0),K.set(Y,Z)}return Array.from(K.entries()).map(([L,Y])=>({date:L,order_count:Y.order_count,revenue:Y.revenue}))}var{randomUUIDv7:i9}=globalThis.Bun;import{db as a6}from"@stacksjs/database";import{formatDate as t6}from"@stacksjs/orm";async function r6(J){let G={...J,status:J.status||"PENDING",uuid:i9(),created_at:t6(new Date),updated_at:t6(new Date)};try{let X=await a6.insertInto("orders").values(G).executeTakeFirst(),$=Number(X?.insertId)||Number(X?.numInsertedOrUpdatedRows);if($)return await a6.selectFrom("orders").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof Error)throw Error(`Failed to create order: ${X.message}`);throw X}}var{randomUUIDv7:d9}=globalThis.Bun;import{db as vG}from"@stacksjs/database";import{formatDate as a9}from"@stacksjs/orm";import{sql as e6}from"@stacksjs/database";var s9={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","CANCELLED","REFUNDED"],SHIPPED:["DELIVERED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]};function wG(J,G){if(J===G)return!0;return s9[J]?.includes(G)??!1}async function GG(J,G){try{let X=await import("@stacksjs/events").catch(()=>null);if(!X)return;let $=X.dispatch;if(typeof $!=="function")return;$(J,G)}catch{}}async function IG(J){await GG("order:created",{order:J})}async function u(J,G){await GG("order:paid",{order:J,payment:G})}async function wJ(J){await GG("order:shipped",{order:J})}async function IJ(J){await GG("order:delivered",{order:J})}async function HG(J,G){await GG("order:cancelled",{order:J,reason:G})}async function FG(J,G){await GG("order:refunded",{order:J,refundAmount:G})}async function fG(J,G){switch(J){case"PROCESSING":return u(G);case"SHIPPED":return wJ(G);case"DELIVERED":return IJ(G);case"CANCELLED":return HG(G);case"REFUNDED":return FG(G);case"PENDING":default:}}var G$=!1;async function t9(J){try{let G=await vG.selectFrom("order_idempotency").where("idempotency_key","=",J).selectAll().executeTakeFirst();if(!G)return null;return await vG.selectFrom("orders").where("id","=",G.order_id).selectAll().executeTakeFirst()??null}catch(G){if(G?.message?.includes("no such table")||G?.message?.includes("doesn't exist")){if(!G$)G$=!0,console.warn("[commerce/orders] order_idempotency table missing \u2014 idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw G}}async function J$(J){if(J.idempotencyKey){let G=await t9(J.idempotencyKey);if(G)return{ok:!0,order:G}}try{let G=await vG.transaction().execute(async(X)=>{let $=a9(new Date),K={...J.order,status:J.order.status||"PENDING",uuid:d9(),created_at:$,updated_at:$},L=await X.insertInto("orders").values(K).executeTakeFirst(),Y=Number(L?.insertId)||Number(L?.numInsertedOrUpdatedRows);if(!Y)throw Object.assign(Error("order insert returned no id"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let Z;if(J.payment)try{let M=await X.insertInto("payments").values({...J.payment,order_id:Y,created_at:$,updated_at:$}).executeTakeFirst(),N=Number(M?.insertId)||Number(M?.numInsertedOrUpdatedRows);if(N)Z=await X.selectFrom("payments").where("id","=",N).selectAll().executeTakeFirst()}catch(M){if(M?.message?.includes("UNIQUE constraint")||M?.message?.includes("Duplicate entry"))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(M,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(J.inventory&&J.inventory.length>0)for(let M=0;M<J.inventory.length;M++){let{id:N,delta:H}=J.inventory[M];if(!Number.isFinite(H)||H===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});let F=await X.updateTable("products").set({inventory_count:e6`inventory_count + ${H}`,updated_at:$}).where("id","=",N).where(e6`inventory_count + ${H}`,">=",0).execute();if(!Number(F?.numUpdatedRows??F?.[0]?.numUpdatedRows??F?.numAffectedRows??0))throw Object.assign(Error(`inventory adjust failed for product ${N}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(J.idempotencyKey)try{await X.insertInto("order_idempotency").values({idempotency_key:J.idempotencyKey,order_id:Y,created_at:$}).execute()}catch(M){if(M?.message?.includes("UNIQUE constraint")||M?.message?.includes("Duplicate entry"))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!(M?.message?.includes("no such table")||M?.message?.includes("doesn't exist")))throw M}let W=await X.selectFrom("orders").where("id","=",Y).selectAll().executeTakeFirst();if(!W)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:W,payment:Z}});if(IG(G.order),G.payment)u(G.order,G.payment);return{ok:!0,order:G.order,payment:G.payment}}catch(G){if(G?.__placeFail)return{ok:!1,reason:G.reason,failedAt:G.failedAt,error:G};throw G}}import{db as fJ}from"@stacksjs/database";import{formatDate as vJ}from"@stacksjs/orm";async function X$(J,G){if(!await y(J))throw Error(`Order with ID ${J} not found`);try{return await fJ.updateTable("orders").set({...G,updated_at:vJ(new Date)}).where("id","=",J).execute(),await y(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to update order: ${$.message}`);throw $}}async function $$(J,G){let X=await y(J);if(!X)throw Error(`Order with ID ${J} not found`);let $=X.status??"PENDING";if(!wG($,G))throw Error(`[commerce/orders] illegal status transition ${$} \u2192 ${G}`);try{await fJ.updateTable("orders").set({status:G,updated_at:vJ(new Date)}).where("id","=",J).execute();let K=await y(J);if(K)fG(G,K);return K}catch(K){if(K instanceof Error)throw TypeError(`Failed to update order status: ${K.message}`);throw K}}async function K$(J,G,X){let $=await y(J);if(!$)throw Error(`Order with ID ${J} not found`);let K={updated_at:vJ(new Date)};if(G!==void 0)K.delivery_address=G;if(X!==void 0)K.estimated_delivery_time=X;if(Object.keys(K).length===1)return $;try{return await fJ.updateTable("orders").set(K).where("id","=",J).execute(),await y(J)}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery information: ${L.message}`);throw L}}import{db as JG}from"@stacksjs/database";import{formatDate as gG}from"@stacksjs/orm";async function gJ(J){let G=await JG.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!G)return null;return await JG.selectFrom("orders").where("id","=",G.order_id).selectAll().executeTakeFirst()??null}var L$=!1;async function hJ(J,G){try{return await G.insertInto("stripe_webhook_events").values({event_id:J,processed_at:gG(new Date)}).execute(),!0}catch(X){if(X?.message?.includes("UNIQUE constraint")||X?.message?.includes("Duplicate entry"))return!1;if(X?.message?.includes("no such table")||X?.message?.includes("doesn't exist")){if(!L$)L$=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw X}}async function yJ(J){let X=J.data.object?.id;if(!X)return;await JG.transaction().execute(async(K)=>{if(!await hJ(J.id,K))return;let Y=await K.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!Y)return;let Z=gG(new Date);await K.updateTable("payments").set({status:"succeeded",updated_at:Z}).where("id","=",Y.id).execute();let W=await K.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(W&&W.status==="PENDING")await K.updateTable("orders").set({status:"PROCESSING",updated_at:Z}).where("id","=",W.id).execute()});let $=await gJ(X);if($)await u($)}async function DJ(J){let G=J.data.object,X=G?.id;if(!X)return;let K=G?.last_payment_error?.message??"payment failed";await JG.transaction().execute(async(Y)=>{if(!await hJ(J.id,Y))return;let W=await Y.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!W)return;let M=gG(new Date);await Y.updateTable("payments").set({status:"failed",failure_reason:K,updated_at:M}).where("id","=",W.id).execute();let N=await Y.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await Y.updateTable("orders").set({status:"CANCELLED",updated_at:M}).where("id","=",N.id).execute()});let L=await gJ(X);if(L)await HG(L,K)}async function pJ(J){let G=J.data.object,X=G?.payment_intent;if(!X)return;let $=G?.amount_refunded??0;await JG.transaction().execute(async(L)=>{if(!await hJ(J.id,L))return;let Z=await L.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!Z)return;let W=gG(new Date);await L.updateTable("payments").set({status:"refunded",refund_amount:$,updated_at:W}).where("id","=",Z.id).execute();let M=await L.selectFrom("orders").where("id","=",Z.order_id).selectAll().executeTakeFirst();if(M&&M.status!=="REFUNDED")await L.updateTable("orders").set({status:"REFUNDED",updated_at:W}).where("id","=",M.id).execute()});let K=await gJ(X);if(K)await FG(K,$)}async function Y$(){let J=await import("@stacksjs/payments").catch(()=>null);if(!J)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:G,onCharge:X}=J;if(typeof G!=="function"||typeof X!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return G({succeeded:yJ,failed:DJ}),X({refunded:pJ}),()=>{}}import{db as Z$}from"@stacksjs/database";async function r9(J){if(J.length===0)return new Map;let G=await Z$.selectFrom("products").where("id","in",J).select(["id","price"]).execute(),X=new Map;for(let $ of G){let K=Number($.price);if(Number.isFinite(K))X.set($.id,Math.round(K))}return X}async function e9(J){try{let G=await Z$.selectFrom("tax_rates").where("id","=",J).select(["rate"]).executeTakeFirst(),X=Number(G?.rate??0);return Number.isFinite(X)?X:0}catch{return 0}}async function M$(J){let G=J.items.map((A)=>A.productId),X=await r9(G),$=J.taxRateId!=null?await e9(J.taxRateId):0,K=0,L=[];for(let A of J.items){let Q=A.unitPriceCents??X.get(A.productId)??0,B=Math.round(Q*A.quantity);K+=B,L.push({productId:A.productId,quantity:A.quantity,unitPriceCents:Q,lineCents:B})}let Y=Math.max(0,J.discountCents??0),Z=Math.max(0,K-Y),W=Math.round(Z*$),M=Math.max(0,J.shippingCents??0),N=K-Y+W+M,H=J.maxDriftCents??5,F=!1,x=0;if(J.clientTotalCents!=null)x=Math.abs(N-J.clientTotalCents),F=x>H;return{subtotalCents:K,discountCents:Y,taxCents:W,shippingCents:M,totalCents:N,resolvedItems:L,priceChanged:F,diffCents:x}}import{db as hG}from"@stacksjs/database";function W$(J,G={}){let X=J.length;if(X<=1)return{ok:!0,count:X};if(!G.allowMultiple)return{ok:!1,count:X,reason:"multiple-not-allowed"};let $=G.maxStacked??Number.POSITIVE_INFINITY;if(X>$)return{ok:!1,count:X,reason:"exceeds-max-stacked"};return{ok:!0,count:X}}async function mJ(J,G){if(!Number.isFinite(G)||G<=0)return{ok:!1,productId:J,quantity:G,reason:"non-positive"};let X;try{X=await hG.selectFrom("products").where("id","=",J).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:J,quantity:G}}if(!X)return{ok:!1,productId:J,quantity:G,reason:"product-missing"};let $=X.min_order_qty??null,K=X.max_order_qty??null;if($!=null&&G<$)return{ok:!1,productId:J,quantity:G,reason:"below-min",bound:$};if(K!=null&&G>K)return{ok:!1,productId:J,quantity:G,reason:"above-max",bound:K};return{ok:!0,productId:J,quantity:G}}async function N$(J){for(let X of J){let $=await mJ(X.productId,X.quantity);if(!$.ok)return $}let G=J[J.length-1]??{productId:0,quantity:0};return{ok:!0,productId:G.productId,quantity:G.quantity}}async function H$(J={}){let G=J.olderThanDays??30,X=J.limit??1000,K=new Date(Date.now()-G*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let L=await hG.deleteFrom("carts").where("updated_at","<",K).where("id","in",(Z)=>Z.selectFrom("carts").select("id").where("updated_at","<",K).limit(X)).execute();return{deleted:Number(L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??0),cutoffAt:K}}catch{try{let L=await hG.selectFrom("carts").where("updated_at","<",K).select(["id"]).limit(X).execute();if(L.length===0)return{deleted:0,cutoffAt:K};let Y=L.map((M)=>M.id),Z=await hG.deleteFrom("carts").where("id","in",Y).execute();return{deleted:Number(Z?.numDeletedRows??Z?.[0]?.numDeletedRows??Z?.affectedRows??L.length),cutoffAt:K}}catch{return{deleted:0,cutoffAt:K}}}}var lJ={};V(lJ,{update:()=>U$,store:()=>R$,fetchPaymentStatsByMethod:()=>B$,fetchPaymentStats:()=>V$,fetchMonthlyPaymentTrends:()=>z$,fetchById:()=>QG,fetchAll:()=>A$,destroy:()=>Q$,bulkDestroy:()=>x$});import{db as F$}from"@stacksjs/database";async function Q$(J){try{let G=await F$.deleteFrom("payments").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete payment: ${G.message}`);throw G}}async function x$(J){if(!J.length)return 0;try{let G=await F$.deleteFrom("payments").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete payments: ${G.message}`);throw G}}import{db as b}from"@stacksjs/database";import{formatDate as w}from"@stacksjs/orm";async function A$(){return await b.selectFrom("payments").selectAll().execute()}async function QG(J){return await b.selectFrom("payments").selectAll().where("id","=",J).executeTakeFirst()}async function V$(J=30){let G=new Date,X=new Date(G);X.setDate(G.getDate()-J);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-J);let L=await b.selectFrom("payments").select((v)=>[v.fn.count("id").as("transaction_count"),v.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(G)).where("status","=","completed").executeTakeFirst(),Y=await b.selectFrom("payments").select((v)=>[v.fn.count("id").as("transaction_count"),v.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(K)).where("created_at","<=",w($)).where("status","=","completed").executeTakeFirst(),Z=await b.selectFrom("payments").select((v)=>v.fn.count("id").as("count")).where("created_at",">=",w(X)).where("created_at","<=",w(G)).executeTakeFirst(),W=Number(L?.transaction_count||0),M=Number(L?.total_revenue||0),N=W>0?M/W:0,H=Number(Y?.transaction_count||0),F=Number(Y?.total_revenue||0),x=H>0?F/H:0,A=W-H,Q=M-F,B=N-x,C=H>0?A/H*100:W>0?100:0,f=F>0?Q/F*100:M>0?100:0,l=x>0?B/x*100:N>0?100:0,t=Number(Z?.count||0),R=t>0?W/t*100:0;return{total_transactions:W,total_revenue:M,average_transaction:N,successful_rate:R,comparison:{transactions:{difference:A,percentage:Math.abs(C),is_increase:A>=0},revenue:{difference:Q,percentage:Math.abs(f),is_increase:Q>=0},average:{difference:B,percentage:Math.abs(l),is_increase:B>=0}}}}async function B$(J=30){let G=new Date,X=new Date(G);X.setDate(G.getDate()-J);let $=await b.selectFrom("payments").select((Z)=>[Z.fn.count("id").as("total_count"),Z.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(G)).where("status","=","completed").executeTakeFirst(),K=Number($?.total_count||0),L=await b.selectFrom("payments").select(["method",(Z)=>Z.fn.count("id").as("count"),(Z)=>Z.fn.sum("amount").as("revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(G)).where("status","=","completed").groupBy("method").execute(),Y={};return L.forEach((Z)=>{let W=Number(Z.count||0),M=Number(Z.revenue||0),N=K>0?W/K*100:0;Y[Z.method]={count:W,revenue:M,percentage_of_total:N}}),Y}async function z$(){let J=new Date,G=new Date(J);G.setMonth(J.getMonth()-11),G.setDate(1);let X=await b.selectFrom("payments").selectAll().where("created_at",">=",w(G)).where("status","=","completed").execute(),$={};for(let L of X){let Y=L.created_at?new Date(L.created_at):new Date,Z=Y.getFullYear(),W=Y.getMonth()+1,M=`${Z}-${String(W).padStart(2,"0")}`;if(!$[M])$[M]={year:Z,month:W,transactions:0,revenue:0};$[M].transactions++,$[M].revenue+=Number(L.amount||0)}return Object.keys($).sort().map((L)=>{let Y=$[L],Z=Y.transactions,W=Y.revenue,M=Z>0?W/Z:0;return{month:new Date(Y.year,Y.month-1,1).toLocaleString("default",{month:"short"}),year:Y.year,transactions:Z,revenue:W,average:M}})}var{randomUUIDv7:GK}=globalThis.Bun;import{db as E$}from"@stacksjs/database";import{HttpError as O$}from"@stacksjs/error-handling";import{isUniqueViolation as JK}from"@stacksjs/orm";async function R$(J){let G={...J,status:J.status||"PENDING",currency:J.currency||"USD",uuid:GK()};try{let X=await E$.insertInto("payments").values(G).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if($)return await E$.selectFrom("payments").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof O$)throw X;if(JK(X))throw new O$(409,"A payment with this transaction ID already exists");if(X instanceof Error){if(X.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${X.message}`)}throw X}}import{db as XK}from"@stacksjs/database";import{formatDate as $K}from"@stacksjs/orm";async function U$(J,G){if(!await QG(J))throw Error(`Payment with ID ${J} not found`);try{return await XK.updateTable("payments").set({...G,updated_at:$K(new Date)}).where("id","=",J).execute(),await QG(J)}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry")&&$.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${$.message}`)}throw $}}var aJ={};V(aJ,{variants:()=>cG,units:()=>lG,reviews:()=>bG,manufacturers:()=>mG,items:()=>pG,default:()=>FK,categories:()=>DG});var DG={};V(DG,{updateParent:()=>b$,updateDisplayOrder:()=>p$,updateActiveStatus:()=>m$,update:()=>D$,store:()=>uJ,removeChildCategories:()=>f$,remove:()=>w$,findOrCreateByName:()=>y$,fetchStats:()=>k$,fetchRootCategories:()=>P$,fetchChildCategories:()=>S$,fetchCategoryTree:()=>C$,fetchByName:()=>T$,fetchById:()=>U,fetchByDisplayOrder:()=>j$,fetchAll:()=>cJ,fetchActive:()=>q$,deactivateChildCategories:()=>g$,deactivate:()=>v$,compareCategoryGrowth:()=>_$,bulkRemove:()=>I$});import{db as n}from"@stacksjs/database";import{db as S}from"@stacksjs/database";import{formatDate as xG}from"@stacksjs/orm";async function cJ(){return await S.selectFrom("categories").selectAll().execute()}async function U(J){return await S.selectFrom("categories").where("id","=",J).selectAll().executeTakeFirst()}async function T$(J){return await S.selectFrom("categories").where("name","=",J).selectAll().executeTakeFirst()}async function q$(){return await S.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function P$(){return await S.selectFrom("categories").where("parent_category_id","is",null).where("is_active","=",!0).selectAll().execute()}async function S$(J){return await S.selectFrom("categories").where("parent_category_id","=",J).where("is_active","=",!0).selectAll().execute()}async function j$(J=!0){let G=S.selectFrom("categories").where("is_active","=",!0).selectAll();if(J)return await G.orderBy("display_order","asc").execute();else return await G.orderBy("display_order","desc").execute()}async function k$(){let J=await S.selectFrom("categories").select((W)=>W.fn.count("id").as("count")).executeTakeFirst(),G=await S.selectFrom("categories").where("is_active","=",!0).select((W)=>W.fn.count("id").as("count")).executeTakeFirst(),X=await S.selectFrom("categories").where("parent_category_id","is",null).select((W)=>W.fn.count("id").as("count")).executeTakeFirst(),$=await S.selectFrom("categories").where("image_url","is not",null).select((W)=>W.fn.count("id").as("count")).executeTakeFirst(),K=new Date;K.setDate(K.getDate()-30);let L=xG(K),Y=await S.selectFrom("categories").where("created_at",">=",L).selectAll().limit(5).execute(),Z=await S.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)=>W.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(J?.count||0),active:Number(G?.count||0),root_categories:Number(X?.count||0),child_categories:Number(J?.count||0)-Number(X?.count||0),with_images:Number($?.count||0),recently_added:Y,top_parent_categories:Z.map((W)=>({id:String(W.parent_category_id||""),name:String(W.parent_name||""),child_count:Number(W.child_count)}))}}async function _$(J=30){let G=new Date,X=xG(G),$=new Date;$.setDate(G.getDate()-J);let K=xG($),L=new Date($);L.setDate(L.getDate()-1);let Y=xG(L),Z=new Date(L);Z.setDate(L.getDate()-J);let W=xG(Z),M=await S.selectFrom("categories").select((Q)=>Q.fn.count("id").as("count")).where("created_at",">=",K).where("created_at","<=",X).executeTakeFirst(),N=await S.selectFrom("categories").select((Q)=>Q.fn.count("id").as("count")).where("created_at",">=",W).where("created_at","<=",Y).executeTakeFirst(),H=Number(M?.count||0),F=Number(N?.count||0),x=H-F,A=F!==0?x/F*100:H>0?100:0;return{current_period:H,previous_period:F,difference:x,percentage_change:A,days_range:J}}async function C$(){let J=await cJ(),G=new Map;J.forEach((K)=>{G.set(K.id,{...K,children:[]})});let X=[];J.forEach((K)=>{let L=G.get(K.id);if(K.parent_category_id){let Y=G.get(K.parent_category_id);if(Y)Y.children.push(L)}else X.push(L)}),X.sort((K,L)=>K.display_order-L.display_order);let $=(K)=>{K.sort((L,Y)=>L.display_order-Y.display_order),K.forEach((L)=>{if(L.children.length>0)$(L.children)})};return $(X),X}async function w$(J){if(!await U(J))throw Error(`Category with ID ${J} not found`);return!!await n.deleteFrom("categories").where("id","=",J).executeTakeFirst()}async function I$(J){if(!J.length)return 0;let G=await n.deleteFrom("categories").where("id","in",J).executeTakeFirst();return Number(G?.numDeletedRows)||0}async function f$(J){let G=await n.deleteFrom("categories").where("parent_category_id","=",J).executeTakeFirst();return Number(G?.numDeletedRows)||0}async function v$(J){if(!await U(J))throw Error(`Category with ID ${J} not found`);return!!await n.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",J).executeTakeFirst()}async function g$(J){let G=await n.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",J).execute();return Number(G.length)||0}import{db as h$}from"@stacksjs/database";import{slug as KK}from"@stacksjs/strings";async function uJ(J){try{let G={...J,slug:J.name?.toLowerCase().replace(/\s+/g,"-")||"",categorizable_type:"product",display_order:0},X=await h$.insertInto("categories").values(G).executeTakeFirst();if(!X)throw Error("Failed to create category");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await U($);if(!K)throw Error("Failed to create category");return K}catch(G){if(G instanceof Error){if(G.message.includes("Duplicate entry")&&G.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to create category: ${G.message}`)}throw G}}async function y$(J){if(!J.name)throw Error("Name is required");let G=await h$.selectFrom("categories").selectAll().where("name","=",J.name).executeTakeFirst();if(G)return G;let X={name:J.name,slug:KK(J.name),is_active:J.is_active??!0,categorizable_type:J.categorizable_type??"default",display_order:0};return await uJ(X)}import{db as AG}from"@stacksjs/database";import{formatDate as yG}from"@stacksjs/orm";async function D$(J,G){await G.validate();let X=await U(J);if(!X)throw Error(`Category with ID ${J} not found`);let $={name:G.get("name"),description:G.get("description"),imageUrl:G.get("imageUrl"),isActive:G.get("isActive"),parentCategoryId:G.get("parentCategoryId"),displayOrder:G.get("displayOrder"),updated_at:yG(new Date)};if(Object.keys($).length===0)return X;try{return await AG.updateTable("categories").set($).where("id","=",J).execute(),await U(J)}catch(K){if(K instanceof Error){if(K.message.includes("Duplicate entry")&&K.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to update category: ${K.message}`)}throw K}}async function p$(J,G){if(!await U(J))throw Error(`Category with ID ${J} not found`);try{return await AG.updateTable("categories").set({display_order:G,updated_at:yG(new Date)}).where("id","=",J).execute(),await U(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category display order: ${$.message}`);throw $}}async function m$(J,G){if(!await U(J))throw Error(`Category with ID ${J} not found`);try{return await AG.updateTable("categories").set({is_active:G,updated_at:yG(new Date)}).where("id","=",J).execute(),await U(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category active status: ${$.message}`);throw $}}async function b$(J,G){if(!await U(J))throw Error(`Category with ID ${J} not found`);if(G){let $=Number(G);if($===J)throw Error("A category cannot be its own parent");if(!await U($))throw Error(`Parent category with ID ${G} not found`);if(await LK(J,G))throw Error("This operation would create a circular reference in the category hierarchy")}try{let $={updated_at:yG(new Date)};if(G===null)await AG.updateTable("categories").set({...$,parent_category_id:void 0}).where("id","=",J).execute();else await AG.updateTable("categories").set({...$,parent_category_id:G}).where("id","=",J).execute();return await U(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category parent: ${$.message}`);throw $}}async function LK(J,G){let X=Number(G),$=new Set;while(X){if($.has(X))return!0;if(X===J)return!0;$.add(X);let K=await U(X);if(!K||!K.parentCategoryId)return!1;X=Number(K.parentCategoryId)}return!1}var pG={};V(pG,{updateInventory:()=>e$,updateAvailability:()=>r$,update:()=>t$,store:()=>d$,fetchTopProducts:()=>o$,fetchById:()=>D,fetchAll:()=>n$,destroy:()=>c$,bulkStore:()=>a$,bulkDestroy:()=>u$});import{db as l$}from"@stacksjs/database";async function c$(J){try{let G=await l$.deleteFrom("products").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete product item: ${G.message}`);throw G}}async function u$(J){if(!J.length)return 0;try{let G=await l$.deleteFrom("products").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete product items: ${G.message}`);throw G}}import{db as o,sql as YK}from"@stacksjs/database";async function D(J){let G=await o.selectFrom("products").where("id","=",J).selectAll().executeTakeFirst();if(G){let X=null,$=null;if(G.manufacturer_id)X=await o.selectFrom("manufacturers").where("id","=",G.manufacturer_id).selectAll().executeTakeFirst();if(G.category_id)$=await o.selectFrom("categories").where("id","=",G.category_id).selectAll().executeTakeFirst();return{...G,manufacturer:X,category:$}}return}async function n$(){let J=await o.selectFrom("products").selectAll().execute(),G=J.map((M)=>M.manufacturer_id).filter((M)=>M!==null&&M!==void 0),X=J.map((M)=>M.category_id).filter((M)=>M!==null&&M!==void 0),$=o.selectFrom("manufacturers"),K=o.selectFrom("categories");if(G.length>0)$=$.where("id","in",G);if(X.length>0)K=K.where("id","in",X);let L=await $.selectAll().execute(),Y=await K.selectAll().execute(),Z=L.reduce((M,N)=>{return M[N.id]=N,M},{}),W=Y.reduce((M,N)=>{return M[N.id]=N,M},{});return J.map((M)=>({...M,manufacturer:M.manufacturer_id?Z[M.manufacturer_id]:null,category:M.category_id?W[M.category_id]:null}))}async function o$(J=5){try{return(await o.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",(X)=>X.fn.sum("order_items.quantity").as("units_sold"),YK`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(J).execute()).map((X)=>({id:Number(X.id),name:String(X.name??"Unnamed product"),units_sold:Number(X.units_sold??0),revenue:Number(X.revenue??0),inventory_count:Number(X.inventory_count??0)}))}catch(G){if(G instanceof Error)throw TypeError(`Failed to fetch top products: ${G.message}`);throw G}}var{randomUUIDv7:i$}=globalThis.Bun;import{db as s$}from"@stacksjs/database";async function d$(J){try{let G={...J,uuid:i$()},X=await s$.insertInto("products").values(G).executeTakeFirst();if(!X)throw Error("Failed to create product item");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await D($);if(!K)throw Error("Failed to create product item");return K}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product item: ${G.message}`);throw G}}async function a$(J){if(!J.length)return 0;let G=0;try{return await s$.transaction().execute(async(X)=>{for(let $ of J){let K={...$,uuid:i$()};await X.insertInto("products").values(K).execute(),G++}}),G}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product items in bulk: ${X.message}`);throw X}}import{db as nJ,sql as c0}from"@stacksjs/database";import{formatDate as oJ}from"@stacksjs/orm";async function t$(J,G){try{if(!J)throw Error("Product item ID is required for update");let X=await nJ.updateTable("products").set({...G,updated_at:oJ(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product item");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item: ${X.message}`);throw X}}async function r$(J,G){if(!await D(J))throw Error(`Product item with ID ${J} not found`);try{return await nJ.updateTable("products").set({is_available:G,updated_at:oJ(new Date)}).where("id","=",J).execute(),await D(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to update product item availability: ${$.message}`);throw $}}async function e$(J,G){let X=await D(J);if(!X)throw Error(`Product item with ID ${J} not found`);let $={updated_at:oJ(new Date)};if(G!==void 0)$.inventory_count=G;if(Object.keys($).length===1)return X;try{return await nJ.updateTable("products").set($).where("id","=",J).execute(),await D(J)}catch(K){if(K instanceof Error)throw TypeError(`Failed to update inventory information: ${K.message}`);throw K}}var mG={};V(mG,{updateFeaturedStatus:()=>V2,updateByUuid:()=>B2,update:()=>A2,store:()=>F2,fetchWithProductCount:()=>M2,fetchFeatured:()=>Y2,fetchByUuid:()=>L2,fetchById:()=>K2,fetchByCountry:()=>Z2,fetchAll:()=>$2,destroy:()=>J2,bulkStore:()=>Q2,bulkDestroy:()=>X2});import{db as G2}from"@stacksjs/database";async function J2(J){try{let G=await G2.deleteFrom("manufacturers").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete order: ${G.message}`);throw G}}async function X2(J){if(!J.length)return 0;try{let G=await G2.deleteFrom("manufacturers").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete orders: ${G.message}`);throw G}}import{db as i}from"@stacksjs/database";function $2(){return i.selectFrom("manufacturers").selectAll().execute()}async function K2(J){return await i.selectFrom("manufacturers").where("id","=",J).selectAll().executeTakeFirst()}async function L2(J){return await i.selectFrom("manufacturers").where("uuid","=",J).selectAll().executeTakeFirst()}async function Y2(J=10){return await i.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(J).execute()}async function Z2(J,G={}){let X=G.page||1,$=G.limit||2,K=await i.selectFrom("manufacturers").select((W)=>W.fn.count("id").as("total")).where("country","=",J).executeTakeFirst(),L=Number(K?.total||0),Y=await i.selectFrom("manufacturers").selectAll().where("country","=",J).limit($).offset((X-1)*$).execute(),Z=Math.ceil(L/$);return{data:Y,paging:{total_records:L,page:X,total_pages:Z},next_cursor:X<Z?X+1:null}}async function M2(J={}){let G=i.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(J.country)G=G.where("m.country","=",J.country);if(J.featured!==void 0)G=G.where("m.featured","=",J.featured);return G=G.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",(X)=>X.fn.count("p.id").as("product_count")]).groupBy("m.id"),G.execute()}var{randomUUIDv7:N2}=globalThis.Bun;import{db as H2}from"@stacksjs/database";import{HttpError as W2}from"@stacksjs/error-handling";import{isUniqueViolation as ZK}from"@stacksjs/orm";async function F2(J){try{let G={...J,uuid:N2(),featured:J.featured??!1},X=await H2.insertInto("manufacturers").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create manufacturer");return X}catch(G){if(G instanceof W2)throw G;if(ZK(G))throw new W2(409,"A manufacturer with this name already exists");if(G instanceof Error)throw Error(`Failed to create manufacturer: ${G.message}`);throw G}}async function Q2(J){if(!J.length)return 0;let G=0;try{for(let X of J){let $={...X,uuid:N2(),featured:X.featured??!1};await H2.insertInto("manufacturers").values($).execute(),G++}return G}catch(X){if(X instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${X.message}`);throw X}}import{db as iJ}from"@stacksjs/database";import{HttpError as x2}from"@stacksjs/error-handling";import{formatDate as sJ,isUniqueViolation as MK}from"@stacksjs/orm";async function A2(J,G){try{if(!J)throw Error("Manufacturer ID is required for update");let X=await iJ.updateTable("manufacturers").set({...G,updated_at:sJ(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error(`Manufacturer with ID ${J} not found`);return X}catch(X){if(X instanceof x2)throw X;if(MK(X))throw new x2(409,"A manufacturer with this name already exists");if(X instanceof Error)throw Error(`Failed to update manufacturer: ${X.message}`);throw X}}async function V2(J,G){try{let X=await iJ.updateTable("manufacturers").set({featured:G,updated_at:sJ(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update manufacturer featured status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${X.message}`);throw X}}async function B2(J,G){try{let X=await iJ.updateTable("manufacturers").set({...G,updated_at:sJ(new Date)}).where("uuid","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update manufacturer");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update manufacturer: ${X.message}`);throw X}}var bG={};V(bG,{updateVotes:()=>w2,update:()=>C2,store:()=>j2,fetchMostHelpfulByProductId:()=>S2,fetchByUserId:()=>q2,fetchByProductId:()=>T2,fetchById:()=>R2,fetchApprovedByProductId:()=>P2,fetchAll:()=>U2,destroy:()=>E2,bulkDestroy:()=>O2});import{db as z2}from"@stacksjs/database";async function E2(J){try{let G=await z2.deleteFrom("reviews").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete order: ${G.message}`);throw G}}async function O2(J){if(!J.length)return 0;try{let G=await z2.deleteFrom("reviews").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete orders: ${G.message}`);throw G}}import{db as XG}from"@stacksjs/database";async function R2(J){return await XG.selectFrom("reviews").where("id","=",J).selectAll().executeTakeFirst()}async function U2(){return await XG.selectFrom("reviews").selectAll().execute()}async function T2(J){return await XG.selectFrom("reviews").where("product_id","=",J).selectAll().execute()}async function q2(J){return await XG.selectFrom("reviews").where("customer_id","=",J).selectAll().execute()}async function P2(J){return await XG.selectFrom("reviews").where("product_id","=",J).where("is_approved","=",!0).selectAll().execute()}async function S2(J){return await XG.selectFrom("reviews").where("product_id","=",J).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:WK}=globalThis.Bun;import{db as NK}from"@stacksjs/database";async function j2(J){try{let G={...J,uuid:WK(),is_verified_purchase:J.is_verified_purchase??!1,is_approved:J.is_approved??!1,helpful_votes:J.helpful_votes??0,unhelpful_votes:J.unhelpful_votes??0,is_featured:J.is_featured??!1},X=await NK.insertInto("reviews").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create review");return X}catch(G){if(G instanceof Error){if(G.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${G.message}`)}throw G}}import{db as k2}from"@stacksjs/database";import{formatDate as _2}from"@stacksjs/orm";async function C2(J,G){try{if(!J)throw Error("Review ID is required for update");let X=await k2.updateTable("reviews").set({...G,updated_at:_2(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update review");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review: ${X.message}`);throw X}}async function w2(J,G,X=!0){try{let $=G==="helpful"?"helpful_votes":"unhelpful_votes",K=X?`COALESCE("${$}", 0) + 1`:`MAX(COALESCE("${$}", 0) - 1, 0)`,L=await k2.unsafe(`UPDATE "reviews" SET "${$}" = ${K}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[_2(new Date),J]).execute(),Y=Array.isArray(L)?L[0]:L;if(!Y)throw Error("Failed to update review votes");return Y}catch($){if($ instanceof Error)throw TypeError(`Failed to update review votes: ${$.message}`);throw $}}var lG={};V(lG,{updateDefaultStatus:()=>n2,update:()=>c2,store:()=>p2,getDefaultUnit:()=>l2,formatUnitOptions:()=>b2,fetchById:()=>h2,fetchAll:()=>y2,destroy:()=>f2,bulkUpdate:()=>u2,bulkStore:()=>m2,bulkDestroy:()=>v2});import{db as I2}from"@stacksjs/database";async function f2(J){try{let G=await I2.deleteFrom("product_units").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete product unit: ${G.message}`);throw G}}async function v2(J){if(!J.length)return 0;try{let G=await I2.deleteFrom("product_units").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete product units: ${G.message}`);throw G}}import{db as g2}from"@stacksjs/database";async function h2(J){return await g2.selectFrom("product_units").where("id","=",J).selectAll().executeTakeFirst()}async function y2(){return await g2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:D2}=globalThis.Bun;import{db as $G}from"@stacksjs/database";async function p2(J){try{let G={...J,uuid:D2()},X=await $G.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(G.is_default)await $G.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product unit: ${G.message}`);throw G}}async function m2(J){if(!J.length)return 0;let G=0;try{for(let X of J){let $={...X,uuid:D2()},K=await $G.insertInto("product_units").values($).returningAll().executeTakeFirst();if($.is_default&&K)await $G.updateTable("product_units").set({is_default:!1}).where("type","=",$.type).where("id","!=",K.id).execute();G++}return G}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product units in bulk: ${X.message}`);throw X}}function b2(J){try{let G=$G.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(J)G=G.where("type","=",J);return G=G.orderBy("name"),G.execute().then((X)=>X.map(($)=>({id:String($.id),name:$.name,abbreviation:$.abbreviation,is_default:$.is_default})))}catch(G){if(G instanceof Error)throw TypeError(`Failed to format unit options: ${G.message}`);throw G}}async function l2(J){try{return await $G.selectFrom("product_units").selectAll().where("type","=",J).where("is_default","=",!0).executeTakeFirst()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get default unit: ${G.message}`);throw G}}import{db as s}from"@stacksjs/database";import{formatDate as dJ}from"@stacksjs/orm";async function c2(J,G){try{if(!J)throw Error("Product unit ID is required for update");let X=await s.updateTable("product_units").set({...G,updated_at:dJ(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product unit");if(G.is_default===!0&&G.type)await s.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",J).execute();return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product unit: ${X.message}`);throw X}}async function u2(J){if(!J.length)return 0;let G=0;try{for(let X of J){let $=X;if(!$.id)continue;let K=$.data&&typeof $.data==="object"?$.data:{...$};delete K.id;let L=await s.updateTable("product_units").set({...K,updated_at:dJ(new Date)}).where("id","=",$.id).executeTakeFirst(),Y=K;if(Y.is_default===!0&&Y.type)await s.updateTable("product_units").set({is_default:!1}).where("type","=",Y.type).where("id","!=",$.id).execute();if(Number(L.numUpdatedRows)>0)G++}return G}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product units in bulk: ${X.message}`);throw X}}async function n2(J,G){try{let X=await s.selectFrom("product_units").select("type").where("id","=",J).executeTakeFirst();if(!X)return!1;let $=await s.updateTable("product_units").set({is_default:G,updated_at:dJ(new Date)}).where("id","=",J).executeTakeFirst();if(G&&X.type)await s.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",J).execute();return Number($.numUpdatedRows)>0}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product unit default status: ${X.message}`);throw X}}var cG={};V(cG,{update:()=>Y4,store:()=>G4,generateVariantCombinations:()=>$4,formatVariantOptions:()=>X4,fetchById:()=>a2,fetchAll:()=>t2,destroy:()=>i2,bulkUpdate:()=>Z4,bulkStore:()=>J4,bulkDestroy:()=>s2});import{db as o2}from"@stacksjs/database";async function i2(J){try{let G=await o2.deleteFrom("product_variants").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete product variant: ${G.message}`);throw G}}async function s2(J){if(!J.length)return 0;try{let G=await o2.deleteFrom("product_variants").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete product variants: ${G.message}`);throw G}}import{db as d2}from"@stacksjs/database";async function a2(J){return await d2.selectFrom("product_variants").where("id","=",J).selectAll().executeTakeFirst()}async function t2(){return await d2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:r2}=globalThis.Bun;import{db as e2}from"@stacksjs/database";async function G4(J){try{let G={...J,uuid:r2()},X=await e2.insertInto("product_variants").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product variant");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to create product variant: ${G.message}`);throw G}}async function J4(J){if(!J.length)return 0;let G=0;try{for(let X of J){let $={...X,uuid:r2()};await e2.insertInto("product_variants").values($).execute(),G++}return G}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${X.message}`);throw X}}function X4(J){if(!J||!J.length)return JSON.stringify([]);let G=J.map((X)=>X.trim()).filter(Boolean);return JSON.stringify(G)}function $4(J){let G=Object.keys(J);if(!G.length)return[];function X($,K){if($===G.length)return[K];let L=G[$],Y=J[L],Z=[];for(let W of Y){let M={...K,[L]:W};Z.push(...X($+1,M))}return Z}return X(0,{})}import{db as K4}from"@stacksjs/database";import{formatDate as L4}from"@stacksjs/orm";async function Y4(J,G){try{let X=await K4.updateTable("product_variants").set({...G,updated_at:L4(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product variant");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product variant: ${X.message}`);throw X}}async function Z4(J){if(!J.length)return 0;let G=0;try{for(let X of J){if(!X.id)continue;let $=await K4.updateTable("product_variants").set({...X,updated_at:L4(new Date)}).where("id","=",X.id).executeTakeFirst();if(Number($.numUpdatedRows)>0)G++}return G}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${X.message}`);throw X}}var HK={categories:DG,items:pG,manufacturers:mG,reviews:bG,units:lG,variants:cG},FK=HK;var eJ={};V(eJ,{updateStatus:()=>E4,updatePrintJob:()=>O4,update:()=>z4,store:()=>V4,fetchById:()=>F4,fetchAll:()=>Q4,destroy:()=>W4,bulkStore:()=>B4,bulkDestroy:()=>N4});import{db as M4}from"@stacksjs/database";async function W4(J){try{let G=await M4.deleteFrom("receipts").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete print log: ${G.message}`);throw G}}async function N4(J){if(!J.length)return 0;try{let G=await M4.deleteFrom("receipts").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete receipts: ${G.message}`);throw G}}import{db as H4}from"@stacksjs/database";async function F4(J){return await H4.selectFrom("receipts").where("id","=",J).selectAll().executeTakeFirst()}async function Q4(){return await H4.selectFrom("receipts").selectAll().execute()}var{randomUUIDv7:x4}=globalThis.Bun;import{db as A4}from"@stacksjs/database";async function V4(J){try{let G={...J,uuid:x4()},X=await A4.insertInto("receipts").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to create receipt: ${G.message}`);throw G}}async function B4(J){if(!J.length)return 0;try{let G=J.map(($)=>({...$,uuid:x4()})),X=await A4.insertInto("receipts").values(G).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${G.message}`);throw G}}import{db as tJ}from"@stacksjs/database";import{formatDate as rJ}from"@stacksjs/orm";async function z4(J,G){try{if(!J)throw Error("Receipt ID is required for update");let X=await tJ.updateTable("receipts").set({...G,updated_at:rJ(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update receipt");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt: ${X.message}`);throw X}}async function E4(J,G){try{let X=await tJ.updateTable("receipts").set({status:G,updated_at:rJ(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update receipt status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt status: ${X.message}`);throw X}}async function O4(J,G,X,$){try{let K={updated_at:rJ(new Date)};if(G!==void 0)K.size=G;if(X!==void 0)K.pages=X;if($!==void 0)K.duration=$;let L=await tJ.updateTable("receipts").set(K).where("id","=",J).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update receipt job information");return L}catch(K){if(K instanceof Error)throw TypeError(`Failed to update receipt job information: ${K.message}`);throw K}}var HX={};V(HX,{zones:()=>FJ,routes:()=>nG,rates:()=>MJ,methods:()=>XJ,licenses:()=>rG,drivers:()=>dG,digital:()=>sG,default:()=>AK});var nG={};V(nG,{updateStops:()=>I4,updateMetrics:()=>f4,updateLastActive:()=>C4,update:()=>w4,store:()=>_4,fetchById:()=>q4,fetchByDriver:()=>j4,fetchAll:()=>P4,fetchActive:()=>S4,destroy:()=>U4,bulkDestroy:()=>T4});import{db as R4}from"@stacksjs/database";async function U4(J){try{let G=await R4.deleteFrom("delivery_routes").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete delivery route: ${G.message}`);throw G}}async function T4(J){if(!J.length)return 0;try{let G=await R4.deleteFrom("delivery_routes").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete delivery routes: ${G.message}`);throw G}}import{db as uG}from"@stacksjs/database";async function q4(J){return await uG.selectFrom("delivery_routes").where("id","=",J).selectAll().executeTakeFirst()}async function P4(){return await uG.selectFrom("delivery_routes").selectAll().execute()}async function S4(){return await uG.selectFrom("delivery_routes").where("last_active","<=",new Date(Date.now()-86400000)).selectAll().execute()}async function j4(J){return await uG.selectFrom("delivery_routes").where("driver","=",J).selectAll().execute()}var{randomUUIDv7:QK}=globalThis.Bun;import{db as k4}from"@stacksjs/database";async function _4(J){try{let G={...J,uuid:QK()},X=await k4.insertInto("delivery_routes").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create delivery route");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to create delivery route: ${G.message}`);throw G}}async function C4(J){try{let G=await k4.updateTable("delivery_routes").set({last_active:new Date().toISOString(),updated_at:new Date().toISOString()}).where("id","=",J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update delivery route last active");return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery route last active: ${G.message}`);throw G}}import{db as GX}from"@stacksjs/database";import{formatDate as JX}from"@stacksjs/orm";async function w4(J,G){try{if(!J)throw Error("Delivery route ID is required for update");let X=await GX.updateTable("delivery_routes").set({...G,updated_at:JX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery route");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery route: ${X.message}`);throw X}}async function I4(J,G){try{let X=await GX.updateTable("delivery_routes").set({stops:G,updated_at:JX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery route stops");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery route stops: ${X.message}`);throw X}}async function f4(J,G,X){try{let $={updated_at:JX(new Date)};if(G!==void 0)$.delivery_time=G;if(X!==void 0)$.total_distance=X;let K=await GX.updateTable("delivery_routes").set($).where("id","=",J).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update delivery metrics");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery metrics: ${$.message}`);throw $}}var sG={};V(sG,{updateStatus:()=>n4,updateDeliverySettings:()=>o4,update:()=>u4,store:()=>l4,softDelete:()=>g4,fetchById:()=>iG,fetchAll:()=>p4,destroy:()=>v4,bulkStore:()=>c4,bulkSoftDelete:()=>y4,bulkDestroy:()=>h4});import{db as oG}from"@stacksjs/database";async function v4(J){try{let G=await oG.deleteFrom("digital_deliveries").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete digital delivery: ${G.message}`);throw G}}async function g4(J){try{let G=await oG.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Number(G.numUpdatedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${G.message}`);throw G}}async function h4(J){if(!J.length)return 0;try{let G=await oG.deleteFrom("digital_deliveries").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${G.message}`);throw G}}async function y4(J){if(!J.length)return 0;try{let G=await oG.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Number(G.numUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${G.message}`);throw G}}import{db as D4}from"@stacksjs/database";async function iG(J){return await D4.selectFrom("digital_deliveries").where("id","=",J).selectAll().executeTakeFirst()}async function p4(){return await D4.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:m4}=globalThis.Bun;import{db as b4}from"@stacksjs/database";async function l4(J){try{let G={...J,uuid:m4()},X=await b4.insertInto("digital_deliveries").values(G).executeTakeFirst();if(!X)throw Error("Failed to create digital delivery");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await iG($);if(!K)throw Error("Failed to create digital delivery");return K}catch(G){if(G instanceof Error)throw TypeError(`Failed to create digital delivery: ${G.message}`);throw G}}async function c4(J){if(!J.length)return 0;try{let G=J.map(($)=>({...$,uuid:m4()})),X=await b4.insertInto("digital_deliveries").values(G).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${G.message}`);throw G}}import{db as XX}from"@stacksjs/database";import{formatDate as $X}from"@stacksjs/orm";async function u4(J,G){try{if(!J)throw Error("Digital delivery ID is required for update");let X=await XX.updateTable("digital_deliveries").set({...G,updated_at:$X(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update digital delivery");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update digital delivery: ${X.message}`);throw X}}async function n4(J,G){try{let X=await XX.updateTable("digital_deliveries").set({status:G,updated_at:$X(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update digital delivery status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update digital delivery status: ${X.message}`);throw X}}async function o4(J,G,X,$,K){try{let L={updated_at:$X(new Date)};if(G!==void 0)L.download_limit=G;if(X!==void 0)L.expiry_days=X;if($!==void 0)L.requires_login=$;if(K!==void 0)L.automatic_delivery=K;let Y=await XX.updateTable("digital_deliveries").set(L).where("id","=",J).returningAll().executeTakeFirst();if(!Y)throw Error("Failed to update delivery settings");return Y}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery settings: ${L.message}`);throw L}}var dG={};V(dG,{updateStatus:()=>$7,updateContact:()=>K7,update:()=>X7,store:()=>G7,fetchById:()=>VG,fetchAll:()=>s4,destroy:()=>a4,bulkStore:()=>J7,bulkDestroy:()=>t4});import{db as d4}from"@stacksjs/database";import{db as i4}from"@stacksjs/database";async function VG(J){return await i4.selectFrom("drivers").where("id","=",J).selectAll().executeTakeFirst()}async function s4(){return await i4.selectFrom("drivers").selectAll().execute()}async function a4(J){let G=await VG(J);if(!G)throw Error(`Driver with ID ${J} not found`);try{return await d4.deleteFrom("drivers").where("id","=",J).execute(),G}catch(X){if(X instanceof Error)throw TypeError(`Failed to delete driver: ${X.message}`);throw X}}async function t4(J){if(!J.length)return 0;let G=0;try{return await d4.transaction().execute(async(X)=>{for(let $ of J)if(await VG($))await X.deleteFrom("drivers").where("id","=",$).execute(),G++}),G}catch(X){if(X instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${X.message}`);throw X}}var{randomUUIDv7:r4}=globalThis.Bun;import{db as e4}from"@stacksjs/database";async function G7(J){try{let G={...J,uuid:r4()},X=await e4.insertInto("drivers").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create driver");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to create driver: ${G.message}`);throw G}}async function J7(J){if(!J.length)return 0;try{let G=J.map(($)=>({...$,uuid:r4()})),X=await e4.insertInto("drivers").values(G).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${G.message}`);throw G}}import{db as KX}from"@stacksjs/database";import{formatDate as LX}from"@stacksjs/orm";async function X7(J,G){try{if(!J)throw Error("Driver ID is required for update");let X=await KX.updateTable("drivers").set({...G,updated_at:LX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update driver");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update driver: ${X.message}`);throw X}}async function $7(J,G){try{let X=await KX.updateTable("drivers").set({status:G,updated_at:LX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update driver status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update driver status: ${X.message}`);throw X}}async function K7(J,G){try{let X={updated_at:LX(new Date)};if(G!==void 0)X.phone=G;let $=await KX.updateTable("drivers").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update contact information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update contact information: ${X.message}`);throw X}}var rG={};V(rG,{updateStatus:()=>V7,updateExpiration:()=>B7,update:()=>A7,store:()=>Q7,softDelete:()=>Y7,fetchById:()=>tG,fetchAll:()=>N7,destroy:()=>L7,bulkStore:()=>x7,bulkSoftDelete:()=>M7,bulkDestroy:()=>Z7});import{db as aG}from"@stacksjs/database";async function L7(J){try{let G=await aG.deleteFrom("license_keys").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete license key: ${G.message}`);throw G}}async function Y7(J){try{let G=await aG.updateTable("license_keys").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Number(G.numUpdatedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to soft delete license key: ${G.message}`);throw G}}async function Z7(J){if(!J.length)return 0;try{let G=await aG.deleteFrom("license_keys").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete license keys: ${G.message}`);throw G}}async function M7(J){if(!J.length)return 0;try{let G=await aG.updateTable("license_keys").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Number(G.numUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to soft delete license keys: ${G.message}`);throw G}}import{db as W7}from"@stacksjs/database";async function tG(J){return await W7.selectFrom("license_keys").where("id","=",J).selectAll().executeTakeFirst()}async function N7(){return await W7.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:H7}=globalThis.Bun;import{db as F7}from"@stacksjs/database";async function Q7(J){try{let G={...J,uuid:H7()},X=await F7.insertInto("license_keys").values(G).executeTakeFirst();if(!X)throw Error("Failed to create license key");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await tG($);if(!K)throw Error("Failed to create license key");return K}catch(G){if(G instanceof Error)throw TypeError(`Failed to create license key: ${G.message}`);throw G}}async function x7(J){if(!J.length)return 0;try{let G=J.map(($)=>({...$,uuid:H7()})),X=await F7.insertInto("license_keys").values(G).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${G.message}`);throw G}}import{db as YX}from"@stacksjs/database";import{formatDate as ZX}from"@stacksjs/orm";async function A7(J,G){try{if(!J)throw Error("License key ID is required for update");let X=await YX.updateTable("license_keys").set({...G,updated_at:ZX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update license key");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update license key: ${X.message}`);throw X}}async function V7(J,G){try{let X=await YX.updateTable("license_keys").set({status:G,updated_at:ZX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update license key status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update license key status: ${X.message}`);throw X}}async function B7(J,G){try{let X={updated_at:ZX(new Date)};if(G!==void 0)X.expiry_date=G;let $=await YX.updateTable("license_keys").set(X).where("id","=",J).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update expiration information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update expiration information: ${X.message}`);throw X}}var XJ={};V(XJ,{updateStatus:()=>_7,updatePricing:()=>C7,update:()=>k7,store:()=>q7,softDelete:()=>E7,getActiveShippingMethods:()=>j7,formatShippingOptions:()=>S7,fetchById:()=>d,fetchAll:()=>U7,destroy:()=>z7,bulkStore:()=>P7,bulkSoftDelete:()=>R7,bulkDestroy:()=>O7});import{db as eG}from"@stacksjs/database";async function z7(J){try{let G=await eG.deleteFrom("shipping_methods").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete shipping method: ${G.message}`);throw G}}async function E7(J){try{let G=await eG.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Number(G.numUpdatedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${G.message}`);throw G}}async function O7(J){if(!J.length)return 0;try{let G=await eG.deleteFrom("shipping_methods").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete shipping methods: ${G.message}`);throw G}}async function R7(J){if(!J.length)return 0;try{let G=await eG.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Number(G.numUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${G.message}`);throw G}}import{db as GJ}from"@stacksjs/database";async function d(J){let G=await GJ.selectFrom("shipping_methods").where("id","=",J).selectAll().executeTakeFirst();if(G){let X=await GJ.selectFrom("shipping_zones").where("shipping_method_id","=",J).selectAll().execute();return{...G,shippingZones:X}}return}async function U7(){let J=await GJ.selectFrom("shipping_methods").selectAll().execute(),G=J.map((L)=>L.id),X=GJ.selectFrom("shipping_zones");if(G.length>0)X=X.where("shipping_method_id","in",G);let K=(await X.selectAll().execute()).reduce((L,Y)=>{let Z=Y.shipping_method_id;if(Z!==null&&Z!==void 0){if(!L[Z])L[Z]=[];L[Z].push(Y)}return L},{});return J.map((L)=>({...L,shipping_zones:K[L.id]||[]}))}var{randomUUIDv7:T7}=globalThis.Bun;import{db as JJ}from"@stacksjs/database";async function q7(J){try{let G=J,X={name:J.name,description:J.description,base_rate:G.base_rate,free_shipping:G.free_shipping,status:J.status,uuid:T7()},$=await JJ.insertInto("shipping_methods").values(X).executeTakeFirst();if(!$)throw Error("Failed to create shipping method");let K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);return await d(K)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create shipping method: ${G.message}`);throw G}}async function P7(J){if(!J.length)return 0;try{let G=J.map(($)=>({...$,uuid:T7()})),X=await JJ.insertInto("shipping_methods").values(G).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${G.message}`);throw G}}function S7(){try{return JJ.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping options: ${J.message}`);throw J}}async function j7(){try{return await JJ.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping methods: ${J.message}`);throw J}}import{db as MX}from"@stacksjs/database";import{formatDate as WX}from"@stacksjs/orm";async function k7(J,G){try{if(!J)throw Error("Shipping method ID is required for update");let X=await MX.updateTable("shipping_methods").set({...G,updated_at:WX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping method");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping method: ${X.message}`);throw X}}async function _7(J,G){try{let X=await MX.updateTable("shipping_methods").set({status:G,updated_at:WX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping method status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping method status: ${X.message}`);throw X}}async function C7(J,G,X){try{let $={updated_at:WX(new Date)};if(G!==void 0)$.base_rate=G;if(X!==void 0)$.free_shipping=X;let K=await MX.updateTable("shipping_methods").set($).where("id","=",J).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update pricing information");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update pricing information: ${$.message}`);throw $}}var MJ={};V(MJ,{validateZoneMatchesAddress:()=>p7,updateByZone:()=>r7,updateByMethod:()=>e7,update:()=>a7,store:()=>s7,resolveZoneForAddress:()=>LJ,getShippingRatesByMethod:()=>b7,getRatesByZone:()=>y7,getRateByWeightAndZone:()=>NX,getRateByWeightAndAddress:()=>D7,formatShippingRateOptions:()=>m7,fetchById:()=>KJ,fetchAll:()=>h7,destroyByZone:()=>f7,destroyByMethod:()=>v7,destroy:()=>w7,bulkUpdate:()=>t7,bulkStore:()=>d7,bulkDestroy:()=>I7});import{db as $J}from"@stacksjs/database";async function w7(J){try{let G=await $J.deleteFrom("shipping_rates").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete shipping rate: ${G.message}`);throw G}}async function I7(J){if(!J.length)return 0;try{let G=await $J.deleteFrom("shipping_rates").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete shipping rates: ${G.message}`);throw G}}async function f7(J){try{let G=await $J.deleteFrom("shipping_rates").where("zone","=",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${G.message}`);throw G}}async function v7(J){try{let G=await $J.deleteFrom("shipping_rates").where("method","=",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${G.message}`);throw G}}import{db as I}from"@stacksjs/database";async function KJ(J){let G=await I.selectFrom("shipping_rates").where("id","=",J).selectAll().executeTakeFirst();if(G){let X=null,$=null;if(G.shipping_zone_id)X=await I.selectFrom("shipping_zones").where("id","=",G.shipping_zone_id).selectAll().executeTakeFirst();if(G.shipping_method_id)$=await I.selectFrom("shipping_methods").where("id","=",G.shipping_method_id).selectAll().executeTakeFirst();return{...G,shipping_zone:X,shipping_method:$}}return}async function h7(){let J=await I.selectFrom("shipping_rates").selectAll().execute(),G=J.map((M)=>M.shipping_zone_id).filter((M)=>M!==null&&M!==void 0),X=J.map((M)=>M.shipping_method_id).filter((M)=>M!==null&&M!==void 0),$=I.selectFrom("shipping_zones"),K=I.selectFrom("shipping_methods");if(G.length>0)$=$.where("id","in",G);if(X.length>0)K=K.where("id","in",X);let L=await $.selectAll().execute(),Y=await K.selectAll().execute(),Z=L.reduce((M,N)=>{return M[N.id]=N,M},{}),W=Y.reduce((M,N)=>{return M[N.id]=N,M},{});return J.map((M)=>({...M,shipping_zone:M.shipping_zone_id?Z[M.shipping_zone_id]:[],shipping_method:M.shipping_method_id?W[M.shipping_method_id]:[]}))}async function y7(J){try{return await I.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).orderBy("weight_from").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${G.message}`);throw G}}async function NX(J,G){try{return await I.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",G).where("weight_from","<=",J).where("weight_to",">=",J).executeTakeFirst()}catch(X){if(X instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${X.message}`);throw X}}async function LJ(J){if(!J?.countryCode)return null;try{let G=await I.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J.countryCode}%`).where("status","=","active").execute();if(G.length===0)return null;let X=null;for(let $ of G){let K=1;if(J.region&&$.regions&&g7($.regions,J.region))K=2;if(J.postalCode&&$.postal_codes&&g7($.postal_codes,J.postalCode))K=3;if(!X||K>X.score)X={id:$.id,score:K}}return X?.id??null}catch{return null}}async function D7(J,G){let X=await LJ(G);if(X==null)return;return NX(J,X)}async function p7(J,G){return await LJ(G)===J}function g7(J,G){if(!J||!G)return!1;let X=G.trim().toUpperCase();for(let $ of J.split(/[,|;]/))if($.trim().toUpperCase()===X)return!0;return!1}async function m7(){try{return(await I.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((G)=>G.shipping_method_id!==null&&G.shipping_method_id!==void 0&&G.shipping_zone_id!==null&&G.shipping_zone_id!==void 0)}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping rate options: ${J.message}`);throw J}}async function b7(J){try{return await I.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",J).orderBy("weight_from").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${G.message}`);throw G}}var{randomUUIDv7:o7}=globalThis.Bun;import{db as i7}from"@stacksjs/database";import{db as BG}from"@stacksjs/database";async function l7(){return await BG.selectFrom("shipping_zones").selectAll().execute()}async function a(J){return await BG.selectFrom("shipping_zones").where("id","=",J).selectAll().executeTakeFirst()}function c7(){try{return BG.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to format shipping zone options: ${J.message}`);throw J}}async function u7(){try{return await BG.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get active shipping zones: ${J.message}`);throw J}}async function n7(J){try{return await BG.selectFrom("shipping_zones").selectAll().where("countries","like",`%${J}%`).where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${G.message}`);throw G}}async function s7(J){try{let G=await d(Number(J.shippingmethod_id)),X=await a(Number(J.shippingzone_id)),$={weightFrom:J.weightFrom,weightTo:J.weightTo,rate:J.rate,shippingmethod_id:G?.id,shippingzone_id:X?.id,uuid:o7()},K=await i7.insertInto("shipping_rates").values($).executeTakeFirst();if(!K)throw Error("Failed to create shipping rate");let L=Number(K.insertId)||Number(K.numInsertedOrUpdatedRows);return await KJ(L)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create shipping rate: ${G.message}`);throw G}}async function d7(J){if(!J.length)return 0;try{for(let $ of J){let K=await d(Number($.shippingmethod_id)),L=await a(Number($.shippingzone_id));if(!K)console.warn(`Shipping method with ID "${$.shippingmethod_id}" not found for bulk insert`);if(!L)console.warn(`Shipping zone with ID "${$.shippingzone_id}" not found for bulk insert`)}let G=J.map(($)=>({weightFrom:$.weightFrom,weightTo:$.weightTo,rate:$.rate,shippingmethod_id:$.shippingmethod_id,shippingzone_id:$.shippingzone_id,uuid:o7()})),X=await i7.insertInto("shipping_rates").values(G).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${G.message}`);throw G}}import{db as YJ}from"@stacksjs/database";import{formatDate as ZJ}from"@stacksjs/orm";async function a7(J,G){try{if(!J)throw Error("Shipping rate ID is required for update");let X=await YJ.updateTable("shipping_rates").set({...G,updated_at:ZJ(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping rate");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rate: ${X.message}`);throw X}}async function t7(J){if(!J.length)return 0;try{let G=0;for(let{id:X,data:$}of J){let K=await YJ.updateTable("shipping_rates").set({...$,updated_at:ZJ(new Date)}).where("id","=",X).executeTakeFirst();if(Number(K.numUpdatedRows)>0)G++}return G}catch(G){if(G instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${G.message}`);throw G}}async function r7(J,G){try{let X=await YJ.updateTable("shipping_rates").set({...G,updated_at:ZJ(new Date)}).where("zone_id","=",J).executeTakeFirst();return Number(X.numUpdatedRows)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${X.message}`);throw X}}async function e7(J,G){try{let X=await YJ.updateTable("shipping_rates").set({...G,updated_at:ZJ(new Date)}).where("method","=",J).executeTakeFirst();return Number(X.numUpdatedRows)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${X.message}`);throw X}}var FJ={};V(FJ,{updateStatus:()=>W1,updateRegionsAndPostalCodes:()=>H1,updateCountries:()=>N1,update:()=>M1,store:()=>Y1,softDelete:()=>J1,getZonesByCountry:()=>n7,getActiveShippingZones:()=>u7,formatZoneOptions:()=>c7,fetchById:()=>a,fetchAll:()=>l7,destroy:()=>G1,bulkStore:()=>Z1,bulkSoftDelete:()=>$1,bulkDestroy:()=>X1});import{db as WJ}from"@stacksjs/database";async function G1(J){try{let G=await WJ.deleteFrom("shipping_zones").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete shipping zone: ${G.message}`);throw G}}async function J1(J){try{let G=await WJ.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",J).executeTakeFirst();return Number(G.numUpdatedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${G.message}`);throw G}}async function X1(J){if(!J.length)return 0;try{let G=await WJ.deleteFrom("shipping_zones").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete shipping zones: ${G.message}`);throw G}}async function $1(J){if(!J.length)return 0;try{let G=await WJ.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",J).executeTakeFirst();return Number(G.numUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${G.message}`);throw G}}var{randomUUIDv7:K1}=globalThis.Bun;import{db as L1}from"@stacksjs/database";async function Y1(J){try{let G={...J,uuid:K1()},X=await L1.insertInto("shipping_zones").values(G).executeTakeFirst();if(!X)throw Error("Failed to create shipping zone");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await a($)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create shipping zone: ${G.message}`);throw G}}async function Z1(J){if(!J.length)return 0;try{let G=J.map(($)=>({...$,uuid:K1()})),X=await L1.insertInto("shipping_zones").values(G).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${G.message}`);throw G}}import{db as NJ}from"@stacksjs/database";import{formatDate as HJ}from"@stacksjs/orm";async function M1(J,G){try{if(!J)throw Error("Shipping zone ID is required for update");let X=await NJ.updateTable("shipping_zones").set({...G,updated_at:HJ(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone: ${X.message}`);throw X}}async function W1(J,G){try{let X=await NJ.updateTable("shipping_zones").set({status:G,updated_at:HJ(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone status: ${X.message}`);throw X}}async function N1(J,G){try{let X=await NJ.updateTable("shipping_zones").set({countries:G,updated_at:HJ(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone countries");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${X.message}`);throw X}}async function H1(J,G,X){try{let $={updated_at:HJ(new Date)};if(G!==void 0)$.regions=G;if(X!==void 0)$.postal_codes=X;let K=await NJ.updateTable("shipping_zones").set($).where("id","=",J).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update regions and postal codes");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${$.message}`);throw $}}var xK={digital:sG,drivers:dG,licenses:rG,methods:XJ,rates:MJ,routes:nG,zones:FJ},AK=xK;var xX={};V(xX,{updateStatus:()=>T1,updateRate:()=>q1,update:()=>U1,store:()=>O1,fetchById:()=>V1,fetchAll:()=>B1,destroy:()=>Q1,bulkStore:()=>R1,bulkDestroy:()=>x1});import{db as F1}from"@stacksjs/database";async function Q1(J){try{let G=await F1.deleteFrom("tax_rates").where("id","=",J).executeTakeFirst();return Number(G.numDeletedRows)>0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete tax rate: ${G.message}`);throw G}}async function x1(J){if(!J.length)return 0;try{let G=await F1.deleteFrom("tax_rates").where("id","in",J).executeTakeFirst();return Number(G.numDeletedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete tax rates: ${G.message}`);throw G}}import{db as A1}from"@stacksjs/database";async function V1(J){return await A1.selectFrom("tax_rates").where("id","=",J).selectAll().executeTakeFirst()}async function B1(){return await A1.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:z1}=globalThis.Bun;import{db as E1}from"@stacksjs/database";async function O1(J){try{let G={...J,uuid:z1()},X=await E1.insertInto("tax_rates").values(G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to create tax rate: ${G.message}`);throw G}}async function R1(J){if(!J.length)return 0;try{let G=J.map(($)=>({...$,uuid:z1()})),X=await E1.insertInto("tax_rates").values(G).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${G.message}`);throw G}}import{db as FX}from"@stacksjs/database";import{formatDate as QX}from"@stacksjs/orm";async function U1(J,G){try{if(!J)throw Error("Tax rate ID is required for update");let X=G,$=await FX.updateTable("tax_rates").set({name:G.name,rate:G.rate,type:G.type,country:G.country,region:G.region,status:G.status,is_default:X.is_default,updated_at:QX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update tax rate");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update tax rate: ${X.message}`);throw X}}async function T1(J,G){try{let X=await FX.updateTable("tax_rates").set({status:G,updated_at:QX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update tax rate status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update tax rate status: ${X.message}`);throw X}}async function q1(J,G){try{let X=await FX.updateTable("tax_rates").set({rate:G,updated_at:QX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update rate information");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update rate information: ${X.message}`);throw X}}var BX={};V(BX,{restaurant:()=>LG,products:()=>xJ,default:()=>BK});var xJ={};V(xJ,{updateStatus:()=>o1,updatePartySize:()=>i1,update:()=>n1,store:()=>c1,fetchWaiting:()=>h1,fetchPurchasedBetweenDates:()=>v1,fetchNotifiedBetweenDates:()=>f1,fetchCountByStatus:()=>y1,fetchCountBySource:()=>_1,fetchCountByQuantity:()=>w1,fetchCountByDateGrouped:()=>m1,fetchCountByDate:()=>C1,fetchCountByAllQuantities:()=>I1,fetchCountBetweenDates:()=>p1,fetchConversionRates:()=>D1,fetchCancelledBetweenDates:()=>g1,fetchById:()=>j1,fetchAll:()=>k1,destroy:()=>P1,bulkStore:()=>u1,bulkDestroy:()=>S1});import{db as QJ}from"@stacksjs/database";async function P1(J){try{let G=await QJ.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;return await QJ.deleteFrom("waitlist_products").where("id","=",J).execute(),G}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete waitlist product: ${G.message}`);throw G}}async function S1(J){if(!J.length)return 0;try{return(await QJ.deleteFrom("waitlist_products").where("id","in",J).execute()).length||0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${G.message}`);throw G}}import{db as T}from"@stacksjs/database";import{formatDate as O}from"@stacksjs/orm";async function j1(J){return await T.selectFrom("waitlist_products").where("id","=",J).selectAll().executeTakeFirst()}async function k1(){return await T.selectFrom("waitlist_products").selectAll().execute()}async function _1(J,G){let X=T.selectFrom("waitlist_products").select(["source",(K)=>K.fn.count("id").as("count")]).groupBy("source");if(J&&G){let K=O(J),L=O(G);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.execute()).reduce((K,{source:L,count:Y})=>{return K[L]=Y,K},{})}async function C1(J=new Date){let G=new Date(J);G.setHours(0,0,0,0);let X=new Date(J);X.setHours(23,59,59,999);let $=O(G),K=O(X);return(await T.selectFrom("waitlist_products").select((Y)=>Y.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function w1(J){return(await T.selectFrom("waitlist_products").select((X)=>X.fn.count("id").as("count")).where("quantity","=",J).executeTakeFirst())?.count??0}async function I1(J,G){let X=T.selectFrom("waitlist_products").select(["quantity",(K)=>K.fn.count("id").as("count")]).groupBy("quantity");if(J&&G){let K=O(J),L=O(G);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.execute()).reduce((K,{quantity:L,count:Y})=>{return K[L]=Y,K},{})}async function f1(J,G){let X=O(J),$=O(G);return await T.selectFrom("waitlist_products").selectAll().where("notified_at",">=",X).where("notified_at","<=",$).where("notified_at","is not",null).execute()}async function v1(J,G){let X=O(J),$=O(G);return await T.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",X).where("purchased_at","<=",$).where("purchased_at","is not",null).execute()}async function g1(J,G){let X=O(J),$=O(G);return await T.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",X).where("cancelled_at","<=",$).where("cancelled_at","is not",null).execute()}async function h1(){return await T.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function y1(J,G,X){let $=T.selectFrom("waitlist_products").select((L)=>L.fn.count("id").as("count")).where("status","=",J);if(G&&X){let L=O(G),Y=O(X);$=$.where("created_at",">=",L).where("created_at","<=",Y)}return(await $.executeTakeFirst())?.count??0}async function D1(J,G){let X=T.selectFrom("waitlist_products").select(["status",(W)=>W.fn.count("id").as("count")]).groupBy("status");if(J&&G){let W=O(J),M=O(G);X=X.where("created_at",">=",W).where("created_at","<=",M)}let $=await X.execute(),K=$.reduce((W,{count:M})=>W+M,0),L=$.find((W)=>W.status==="purchased")?.count??0,Y=K>0?L/K*100:0,Z=$.reduce((W,{status:M,count:N})=>{return W[M]={count:N,percentage:K>0?N/K*100:0},W},{});return{totalConversionRate:Y,statusBreakdown:Z}}async function p1(J,G){let X=O(J),$=O(G);return(await T.selectFrom("waitlist_products").select((L)=>L.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",$).executeTakeFirst())?.count??0}async function m1(J,G){let X=T.selectFrom("waitlist_products").select(["created_at"]);if(J&&G){let L=O(J),Y=O(G);X=X.where("created_at",">=",L).where("created_at","<=",Y)}let K=(await X.execute()).reduce((L,{created_at:Y})=>{let Z=(Y||"").split("T")[0]||"unknown";return L[Z]=(L[Z]||0)+1,L},{});return Object.entries(K).map(([L,Y])=>({date:L,count:Y})).sort((L,Y)=>L.date.localeCompare(Y.date))}var{randomUUIDv7:b1}=globalThis.Bun;import{db as l1}from"@stacksjs/database";import{formatDate as KG}from"@stacksjs/orm";async function c1(J){try{let G=J,X={name:J.name,email:J.email,phone:J.phone,quantity:J.quantity??G.party_size,notification_preference:G.notification_preference,source:J.source,notes:J.notes,product_id:J.product_id,customer_id:J.customer_id,uuid:b1(),status:J.status||"waiting"};if(J.notified_at!==void 0)X.notified_at=typeof J.notified_at==="number"?KG(J.notified_at):J.notified_at;if(J.purchased_at!==void 0)X.purchased_at=typeof J.purchased_at==="number"?KG(J.purchased_at):J.purchased_at;if(J.cancelled_at!==void 0)X.cancelled_at=typeof J.cancelled_at==="number"?KG(J.cancelled_at):J.cancelled_at;let $=await l1.insertInto("waitlist_products").values(X).returningAll().executeTakeFirst();if(!$)throw Error("Failed to create waitlist product");return $}catch(G){if(G instanceof Error)throw TypeError(`Failed to create waitlist product: ${G.message}`);throw G}}async function u1(J){if(!J.length)return 0;try{let G=J.map(($)=>{let K=$,L={name:$.name,email:$.email,phone:$.phone,quantity:$.quantity??K.party_size,notification_preference:K.notification_preference,source:$.source,notes:$.notes,product_id:$.product_id,customer_id:$.customer_id,uuid:b1(),status:$.status||"waiting"};if($.notified_at!==void 0)L.notified_at=typeof $.notified_at==="number"?KG($.notified_at):$.notified_at;if($.purchased_at!==void 0)L.purchased_at=typeof $.purchased_at==="number"?KG($.purchased_at):$.purchased_at;if($.cancelled_at!==void 0)L.cancelled_at=typeof $.cancelled_at==="number"?KG($.cancelled_at):$.cancelled_at;return L}),X=await l1.insertInto("waitlist_products").values(G).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${G.message}`);throw G}}import{db as AX}from"@stacksjs/database";import{formatDate as VX}from"@stacksjs/orm";async function n1(J,G){try{if(!J)throw Error("Waitlist product ID is required for update");let X=G,$=await AX.updateTable("waitlist_products").set({name:G.name,email:G.email,phone:G.phone,quantity:G.quantity??X.party_size,notification_preference:X.notification_preference,source:G.source,notes:G.notes,status:G.status,product_id:G.product_id,customer_id:G.customer_id,notified_at:X.notified_at,purchased_at:X.purchased_at,cancelled_at:X.cancelled_at,updated_at:VX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update waitlist product");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update waitlist product: ${X.message}`);throw X}}async function o1(J,G){try{let X=await AX.updateTable("waitlist_products").set({status:G,updated_at:VX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update waitlist product status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update waitlist product status: ${X.message}`);throw X}}async function i1(J,G){try{let X=await AX.updateTable("waitlist_products").set({quantity:G,updated_at:VX(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update party size");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update party size: ${X.message}`);throw X}}var LG={};V(LG,{updateWaitTimes:()=>T9,updateStatus:()=>R9,updateQueuePosition:()=>q9,updatePartySize:()=>U9,update:()=>O9,store:()=>z9,fetchWaitingWithQuotedTimes:()=>Z9,fetchWaitingWithPartySizes:()=>M9,fetchWaiting:()=>K9,fetchTimeSeriesStats:()=>x9,fetchTablesTurnedToday:()=>W9,fetchSeatingRate:()=>N9,fetchSeatedStats:()=>Q9,fetchSeatedBetweenDates:()=>$9,fetchNoShowStats:()=>H9,fetchCurrentWaitTimes:()=>F9,fetchCountByTablePreference:()=>r1,fetchCountByPartySize:()=>G9,fetchCountByDate:()=>e1,fetchCountByAllPartySizes:()=>J9,fetchConversionRates:()=>L9,fetchById:()=>a1,fetchBetweenDates:()=>X9,fetchAverageWaitTimes:()=>Y9,fetchAll:()=>t1,destroy:()=>s1,bulkStore:()=>E9,bulkDestroy:()=>d1});import{db as AJ}from"@stacksjs/database";async function s1(J){try{let G=await AJ.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst();if(!G)return;return await AJ.deleteFrom("waitlist_restaurants").where("id","=",J).execute(),G}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${G.message}`);throw G}}async function d1(J){if(!J.length)return 0;try{return(await AJ.deleteFrom("waitlist_restaurants").where("id","in",J).execute()).length||0}catch(G){if(G instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${G.message}`);throw G}}import{db as E}from"@stacksjs/database";import{formatDate as _}from"@stacksjs/orm";async function a1(J){return await E.selectFrom("waitlist_restaurants").where("id","=",J).selectAll().executeTakeFirst()}async function t1(){return await E.selectFrom("waitlist_restaurants").selectAll().execute()}async function r1(){return(await E.selectFrom("waitlist_restaurants").select(["table_preference",(G)=>G.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((G,{table_preference:X,count:$})=>{return G[X]=$,G},{})}async function e1(J=new Date){let G=new Date(J);G.setHours(0,0,0,0);let X=new Date(J);X.setHours(23,59,59,999);let $=_(G),K=_(X);return(await E.selectFrom("waitlist_restaurants").select((Y)=>Y.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function G9(J){return(await E.selectFrom("waitlist_restaurants").select((X)=>X.fn.count("id").as("count")).where("party_size","=",J).executeTakeFirst())?.count??0}async function J9(){return(await E.selectFrom("waitlist_restaurants").select(["party_size",(G)=>G.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((G,{party_size:X,count:$})=>{return G[X]=$,G},{})}async function X9(J,G){let X=_(J),$=_(G);return await E.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",X).where("created_at","<=",$).execute()}async function $9(J,G){let X=_(J),$=_(G);return await E.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",X).where("check_in_time","<=",$).where("status","=","seated").execute()}async function K9(){return await E.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function L9(){let J=await E.selectFrom("waitlist_restaurants").select(["status",(L)=>L.fn.count("id").as("count")]).groupBy("status").execute(),G=J.reduce((L,{count:Y})=>L+Y,0),X=J.find((L)=>L.status==="seated")?.count??0,$=G>0?Number(X)/G*100:0,K=J.reduce((L,{status:Y,count:Z})=>{return L[Y]={count:Z,percentage:G>0?Z/G*100:0},L},{});return{totalConversionRate:$,statusBreakdown:K}}async function Y9(){let J=await E.selectFrom("waitlist_restaurants").select([(G)=>G.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),(G)=>G.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:J?.avg_quoted_wait_time??0,averageActualWaitTime:J?.avg_actual_wait_time??0}}async function Z9(){let J=await E.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),G=J.reduce(($,K)=>$+(K.quoted_wait_time??0),0),X=J.length>0?G/J.length:0;return{entries:J,totalQuotedWaitTime:G,averageQuotedWaitTime:X}}async function M9(){let J=await E.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),G=J.reduce((K,L)=>K+L.party_size,0),X=J.length>0?G/J.length:0,$=J.reduce((K,L)=>{return K[L.party_size]=(K[L.party_size]||0)+1,K},{});return{entries:J,totalPartySize:G,averagePartySize:X,partySizeBreakdown:$}}async function W9(){let J=new Date,G=new Date(J);G.setHours(0,0,0,0);let X=new Date(J);X.setHours(23,59,59,999);let $=_(G),K=_(X),L=await E.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",$).where("check_in_time","<=",K).execute(),Y=L.length,Z=L.reduce((H,F)=>H+F.party_size,0),W=Y>0?Z/Y:0,M=L.reduce((H,F)=>{return H[F.table_preference]=(H[F.table_preference]||0)+1,H},{}),N=L.reduce((H,F)=>{return H[F.party_size]=(H[F.party_size]||0)+1,H},{});return{totalTablesTurned:Y,averagePartySize:W,totalCustomersSeated:Z,breakdownByTablePreference:M,breakdownByPartySize:N}}async function N9(J,G){let X=_(J),$=_(G),K=await E.selectFrom("waitlist_restaurants").select(["status",(M)=>M.fn.count("id").as("count")]).where("check_in_time",">=",X).where("check_in_time","<=",$).groupBy("status").execute(),L=K.reduce((M,{count:N})=>M+N,0),Y=K.find((M)=>M.status==="seated")?.count??0,Z=L>0?Number(Y)/L*100:0,W=K.reduce((M,{status:N,count:H})=>{return M[N]={count:H,percentage:L>0?H/L*100:0},M},{});return{totalEntries:L,seatedEntries:Y,seatingRate:Z,statusBreakdown:W}}async function H9(J,G){let X=_(J),$=_(G),K=E.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",X).where("check_in_time","<=",$),L=await E.selectFrom("waitlist_restaurants").select((Q)=>Q.fn.count("id").as("count")).where("check_in_time",">=",X).where("check_in_time","<=",$).executeTakeFirst(),Y=await K.execute(),Z=Y.length,W=L?.count&&L.count>0?Z/L.count*100:0,M=Y.reduce((Q,B)=>Q+(B.quoted_wait_time??0),0),N=Z>0?M/Z:0,H=Y.reduce((Q,B)=>Q+B.party_size,0),F=Z>0?H/Z:0,x=Y.reduce((Q,B)=>{return Q[B.table_preference]=(Q[B.table_preference]||0)+1,Q},{}),A=Y.reduce((Q,B)=>{return Q[B.party_size]=(Q[B.party_size]||0)+1,Q},{});return{totalNoShows:Z,noShowRate:W,averageQuotedWaitTime:N,averagePartySize:F,breakdownByTablePreference:x,breakdownByPartySize:A}}async function F9(){let J=await E.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),G=J.reduce((K,L)=>K+(L.quoted_wait_time||0),0),X=J.reduce((K,L)=>K+(L.actual_wait_time||0),0),$=J.length;return{averageQuoted:$>0?G/$:0,averageActual:$>0?X/$:0}}async function Q9(){let J=Date.now()-86400000,G=await E.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",J).execute(),X=Array.from({length:24},($,K)=>({hour:K,count:G.filter((L)=>{return L.seated_at===K}).length}));return{total:G.length,byHour:X}}async function x9(){return(await E.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((G,X)=>{let $=X.created_at;if(!G[$])G[$]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return G[$].total++,G[$][X.status]++,G},{})}var{randomUUIDv7:A9}=globalThis.Bun;import{db as V9}from"@stacksjs/database";import{formatDate as B9}from"@stacksjs/orm";async function z9(J){try{let G=J,X={name:J.name,email:J.email,phone:J.phone,party_size:G.party_size,check_in_time:typeof G.check_in_time==="number"?B9(G.check_in_time):G.check_in_time,table_preference:G.table_preference,status:J.status||"waiting",quoted_wait_time:J.quoted_wait_time,actual_wait_time:J.actual_wait_time,queue_position:J.queue_position,customer_id:J.customer_id,uuid:A9()},$={};for(let[Y,Z]of Object.entries(X))if(Z!==void 0)$[Y]=Z;let K=await V9.insertInto("waitlist_restaurants").values($).returningAll().executeTakeFirst();if(!K)throw Error("Failed to create restaurant waitlist entry");let L={...K};for(let Y of Object.keys(L))if(L[Y]===null)L[Y]=void 0;return L}catch(G){if(G instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${G.message}`);throw G}}async function E9(J){if(!J.length)return 0;try{let G=J.map(($)=>{let K=$;return{name:$.name,email:$.email,phone:$.phone,party_size:K.party_size,check_in_time:typeof K.check_in_time==="number"?B9(K.check_in_time):K.check_in_time,table_preference:K.table_preference,status:$.status||"waiting",quoted_wait_time:$.quoted_wait_time,actual_wait_time:$.actual_wait_time,queue_position:$.queue_position,customer_id:$.customer_id,uuid:A9()}}),X=await V9.insertInto("waitlist_restaurants").values(G).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(G){if(G instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${G.message}`);throw G}}import{db as zG}from"@stacksjs/database";import{formatDate as EG}from"@stacksjs/orm";async function O9(J,G){try{if(!J)throw Error("Restaurant waitlist entry ID is required for update");let X=G,$=await zG.updateTable("waitlist_restaurants").set({name:G.name,email:G.email,phone:G.phone,party_size:X.party_size,check_in_time:X.check_in_time?Math.floor(new Date(X.check_in_time).getTime()/1000):void 0,table_preference:X.table_preference,status:G.status,quoted_wait_time:G.quoted_wait_time,actual_wait_time:G.actual_wait_time,queue_position:G.queue_position,customer_id:G.customer_id,updated_at:EG(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update restaurant waitlist entry");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${X.message}`);throw X}}async function R9(J,G){try{let X=await zG.updateTable("waitlist_restaurants").set({status:G,updated_at:EG(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update restaurant waitlist entry status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry status: ${X.message}`);throw X}}async function U9(J,G){try{let X=await zG.updateTable("waitlist_restaurants").set({party_size:G,updated_at:EG(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update party size");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update party size: ${X.message}`);throw X}}async function T9(J,G,X){try{let $=await zG.updateTable("waitlist_restaurants").set({quoted_wait_time:G,actual_wait_time:X,updated_at:EG(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update wait times");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update wait times: ${$.message}`);throw $}}async function q9(J,G){try{let X=await zG.updateTable("waitlist_restaurants").set({queue_position:G,updated_at:EG(new Date)}).where("id","=",J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update queue position");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update queue position: ${X.message}`);throw X}}var VK={products:xJ,restaurant:LG},BK=VK;var zK={coupons:BJ,customers:EJ,devices:TJ,errors:SJ,giftCards:CJ,orders:bJ,payments:lJ,products:aJ,receipts:eJ,restaurant:LG,shippings:HX,tax:xX,waitlists:BX},MW=zK;export{BX as waitlists,xX as tax,HX as shippings,LG as restaurant,eJ as receipts,aJ as products,lJ as payments,bJ as orders,CJ as giftCards,SJ as errors,TJ as devices,MW as default,EJ as customers,BJ as coupons,zK as commerce};
|