@stacksjs/commerce 0.70.57 → 0.70.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -37
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,38 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
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
|
-
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
|
6
|
-
<sheets>
|
|
7
|
-
<sheet name="Sheet1" sheetId="1" r:id="rId1"/>
|
|
8
|
-
</sheets>
|
|
9
|
-
</workbook>`)),X=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
10
|
-
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
|
11
|
-
<sheetData>
|
|
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
|
-
<v>${typeof A==="string"?A.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"):A}</v>
|
|
17
|
-
</c>`).join("")}
|
|
18
|
-
</row>`).join("")}
|
|
19
|
-
</sheetData>
|
|
20
|
-
</worksheet>`,$=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
21
|
-
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
|
22
|
-
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
|
23
|
-
<Default Extension="xml" ContentType="application/xml"/>
|
|
24
|
-
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
|
|
25
|
-
<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
|
|
26
|
-
</Types>`,K=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
27
|
-
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
|
28
|
-
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
|
|
29
|
-
</Relationships>`,L=[{name:"[Content_Types].xml",content:new Uint8Array(UG.from(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
30
|
-
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
|
31
|
-
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
|
32
|
-
<Default Extension="xml" ContentType="application/xml"/>
|
|
33
|
-
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
|
|
34
|
-
<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
|
|
35
|
-
</Types>`))},{name:"_rels/.rels",content:new Uint8Array(UG.from(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
36
|
-
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
|
37
|
-
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
|
|
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};
|
|
2
|
+
var R9=Object.defineProperty;var U9=(G)=>G;function T9(G,J){this[G]=U9.bind(null,J)}var Q=(G,J)=>{for(var X in J)R9(G,X,{get:J[X],enumerable:!0,configurable:!0,set:T9.bind(J,X)})};var QX=import.meta.require;var FG={};Q(FG,{update:()=>gX,store:()=>fX,redeem:()=>yX,getActiveCouponsMoMChange:()=>CX,fetchTopRedeemedCoupons:()=>jX,fetchStats:()=>TX,fetchRedemptionTrend:()=>kX,fetchRedemptionStats:()=>PX,fetchCouponCountsByType:()=>qX,fetchCouponCounts:()=>SX,fetchConversionRate:()=>wX,fetchById:()=>l,fetchByCode:()=>RX,fetchAll:()=>OX,fetchActive:()=>UX,deleteExpiredCoupons:()=>AX,deleteCoupons:()=>BX,deleteCoupon:()=>VX});import{db as LJ}from"@stacksjs/database";import{formatDate as S9}from"@stacksjs/orm";async function VX(G){return!!await LJ.deleteFrom("coupons").where("id","=",G).executeTakeFirst()}async function BX(G){if(!G.length)return 0;return(await LJ.deleteFrom("coupons").where("id","in",G).execute()).length||0}async function AX(){let G=S9(new Date),J=await LJ.deleteFrom("coupons").where("end_date","<",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}import{db as V}from"@stacksjs/database";import{extractDate as zX,formatDate as EX}from"@stacksjs/orm";function EJ(G){let J={...G};if(J.endDate)J.endDate=zX(new Date(J.endDate));if(J.startDate)J.startDate=zX(new Date(J.startDate));if(J.isActive!==void 0)J.isActive=Boolean(J.isActive);return J}async function OX(){return(await V.selectFrom("coupons").selectAll().execute()).map(EJ)}async function l(G){let J=await V.selectFrom("coupons").where("id","=",G).selectAll().executeTakeFirst();if(J)return EJ(J);return}async function RX(G){let J=await V.selectFrom("coupons").where("code","=",G).selectAll().executeTakeFirst();if(J)return EJ(J);return}async function UX(){let G=EX(new Date);return(await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).selectAll().execute()).map(EJ)}async function TX(){let G=await V.selectFrom("coupons").select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),J=EX(new Date),X=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),$=await V.selectFrom("coupons").select(["discount_type",(Y)=>Y.fn.count("id").as("count")]).groupBy("discount_type").execute(),K=await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),L=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",J).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(G?.count||0),active:Number(X?.count||0),by_type:$,most_used:K,upcoming:L}}async function SX(){let G=new Date,J=new Date(G);J.setDate(G.getDate()-7);let X=new Date(G);X.setMonth(G.getMonth()-1);let $=new Date(G);$.setFullYear(G.getFullYear()-1);let K=await zJ(null,null,G),L=await zJ(J,null,G),Y=await zJ(X,null,G),W=await zJ($,null,G);return{week:L,month:Y,year:W,all_time:K}}async function zJ(G,J,X){let $=V.selectFrom("coupons");if(G)$=$.where("created_at",">=",G.toISOString());if(J)$=$.where("created_at","<=",J.toISOString());let K=await $.select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),L=V.selectFrom("coupons");if(G)L=L.where("created_at",">=",G.toISOString());if(J)L=L.where("created_at","<=",J.toISOString());L=L.where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",X);let Y=await L.select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),W=Number(K?.count||0),M=Number(Y?.count||0),Z=W-M;return{total:W,active:M,inactive:Z}}async function qX(){let G=new Date,J=await V.selectFrom("coupons").select("discount_type").distinct().execute(),X={};for(let{discount_type:$}of J){let K=await V.selectFrom("coupons").where("discount_type","=",$).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),L=await V.selectFrom("coupons").where("discount_type","=",$).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),Y=Number(K?.count||0),W=Number(L?.count||0);X[$]={total:Y,active:W,inactive:Y-W}}return X}async function PX(){let G=await V.selectFrom("coupons").select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),J=new Date,X=new Date(J);X.setDate(J.getDate()-7);let $=new Date(J);$.setMonth(J.getMonth()-1);let K=new Date(J);K.setFullYear(J.getFullYear()-1);let L=await V.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await V.selectFrom("coupons").where("updated_at",">=",$.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await V.selectFrom("coupons").where("updated_at",">=",K.toISOString()).select((N)=>N.fn.sum("usage_count").as("total")).executeTakeFirst(),M=await V.selectFrom("coupons").select(["discount_type",(N)=>N.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),Z={};return M.forEach((N)=>{Z[N.discount_type]=Number(N.total||0)}),{total:Number(G?.total||0),week:Number(L?.total||0),month:Number(Y?.total||0),year:Number(W?.total||0),by_type:Z}}async function jX(G=5){return await V.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(G).execute()}async function kX(G=30){let J=new Date().toISOString(),X=new Date;X.setDate(X.getDate()-G);let $=await V.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",X.toISOString()).where("updated_at","<=",J).where("usage_count",">",0).orderBy("updated_at","desc").execute(),K={};return $.forEach((L)=>{let Y=L.updated_at?new Date(L.updated_at).toISOString().split("T")[0]:"unknown-date";if(!K[Y])K[Y]=0;K[Y]+=L?.usage_count||0}),Object.entries(K).map(([L,Y])=>({date:L,count:Y}))}async function wX(){let G=new Date,J=await V.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),X=await V.selectFrom("coupons").where("usage_count",">",0).select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),$=Number(J?.count||0),K=Number(X?.count||0);return{rate:$>0?K/$*100:0,total_active:$,total_redeemed:K}}async function CX(){let G=new Date,J=new Date(G.getFullYear(),G.getMonth(),1),X=new Date(G.getFullYear(),G.getMonth()-1,1),$=new Date(G.getFullYear(),G.getMonth(),0),K=await V.selectFrom("coupons").select((N)=>N.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",J).executeTakeFirst(),L=await V.selectFrom("coupons").select((N)=>N.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",X).executeTakeFirst(),Y=Number(K?.count||0),W=Number(L?.count||0),M=Y-W,Z=W!==0?M/W*100:Y>0?100:0;return{current_month:Y,previous_month:W,difference:M,percentage_change:Z}}import{db as _X}from"@stacksjs/database";import{HttpError as IX}from"@stacksjs/error-handling";import{isUniqueViolation as q9}from"@stacksjs/orm";async function fX(G){try{let J=await _X.insertInto("coupons").values(G).executeTakeFirst(),X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows);if(X)return await _X.selectFrom("coupons").where("id","=",X).selectAll().executeTakeFirst();return}catch(J){if(J instanceof IX)throw J;if(q9(J))throw new IX(409,"A coupon with this code already exists");if(J instanceof Error)throw Error(`Failed to create coupon: ${J.message}`);throw J}}import{db as HG}from"@stacksjs/database";import{HttpError as vX}from"@stacksjs/error-handling";import{formatDate as hX,isUniqueViolation as P9}from"@stacksjs/orm";async function gX(G,J){if(!await l(G))throw Error(`Coupon with ID ${G} not found`);try{await HG.updateTable("coupons").set({...J,updated_at:hX(new Date)}).where("id","=",G).execute();let $=await l(G);if($){let K=$;K.is_active=Boolean(K.is_active)}return $}catch($){if($ instanceof vX)throw $;if(P9($))throw new vX(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to update coupon: ${$.message}`);throw $}}async function yX(G){let J=hX(new Date),X=await HG.updateTable("coupons").set({usage_count:HG.raw("COALESCE(usage_count, 0) + 1"),updated_at:J}).where("id","=",G).where((W)=>W.or([W("max_uses","is",null),W.cmpr("usage_count","<",W.ref("max_uses"))])).where("is_active","=",1).where((W)=>W.or([W("start_date","is",null),W.cmpr("start_date","<=",J)])).where((W)=>W.or([W("end_date","is",null),W.cmpr("end_date",">=",J)])).executeTakeFirst();if(Number(X?.numUpdatedRows??X?.affectedRows??0)>0){let W=await l(G);if(W){let M=W;return M.is_active=Boolean(M.is_active),{ok:!0,coupon:W}}return{ok:!1,reason:"not-found"}}let K=await l(G);if(!K)return{ok:!1,reason:"not-found"};if(!K.is_active)return{ok:!1,reason:"inactive"};let L=!K.start_date||K.start_date<=J,Y=!K.end_date||K.end_date>=J;if(!L||!Y)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var VG={};Q(VG,{update:()=>nX,store:()=>cX,fetchById:()=>t,fetchAll:()=>pX,destroy:()=>mX,bulkDestroy:()=>bX});import{db as QG}from"@stacksjs/database";import{db as DX}from"@stacksjs/database";async function t(G){return await DX.selectFrom("customers").where("id","=",G).selectAll().executeTakeFirst()}async function pX(){return await DX.selectFrom("customers").selectAll().execute()}async function mX(G){try{if(!await t(G))throw Error(`Customer with ID ${G} not found`);return(await QG.deleteFrom("customers").where("id","=",G).executeTakeFirst()).numDeletedRows>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customer: ${J.message}`);throw J}}async function bX(G){if(!G.length)return 0;try{let J=await QG.deleteFrom("customers").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${J.message}`);throw J}}import{db as j9}from"@stacksjs/database";import{HttpError as lX}from"@stacksjs/error-handling";import{isUniqueViolation as k9}from"@stacksjs/orm";async function cX(G){try{let J={...G,avatar:G.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},X=await j9.insertInto("customers").values(J).executeTakeFirst();if(!X)throw Error("Failed to create customer");let $=X.insertId||Number(X.numInsertedOrUpdatedRows);return await t(Number($))}catch(J){if(J instanceof lX)throw J;if(k9(J))throw new lX(409,"A customer with this email already exists");if(J instanceof Error)throw Error(`Failed to create customer: ${J.message}`);throw J}}import{db as w9}from"@stacksjs/database";import{HttpError as uX}from"@stacksjs/error-handling";import{formatDate as C9,isUniqueViolation as _9}from"@stacksjs/orm";async function nX(G,J){try{if(!G)throw Error("Customer ID is required for update");let X=await w9.updateTable("customers").set({...J,updated_at:C9(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update customer");return X}catch(X){if(X instanceof uX)throw X;if(_9(X))throw new uX(409,"A customer with this email already exists");if(X instanceof Error)throw Error(`Failed to update customer: ${X.message}`);throw X}}var EG={};Q(EG,{updateStatus:()=>X6,updatePrintCount:()=>$6,update:()=>G6,storePrintDevicesExport:()=>tX,store:()=>eX,fetchById:()=>f,fetchAll:()=>OJ,exportPrintDevices:()=>RJ,downloadPrintDevices:()=>aX,destroy:()=>iX,bulkStore:()=>J6,bulkDestroy:()=>sX});import{db as oX}from"@stacksjs/database";async function iX(G){try{let J=await oX.deleteFrom("print_devices").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print device: ${J.message}`);throw J}}async function sX(G){if(!G.length)return 0;try{let J=await oX.deleteFrom("print_devices").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print devices: ${J.message}`);throw J}}import{createSpreadsheet as I9}from"ts-spreadsheets";import{db as dX}from"@stacksjs/database";async function f(G){return await dX.selectFrom("print_devices").where("id","=",G).selectAll().executeTakeFirst()}async function OJ(){return await dX.selectFrom("print_devices").selectAll().execute()}async function RJ(G="csv"){let J=await OJ(),X=f9(J);return I9(X,{type:G})}function f9(G){let J=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],X=G.map(($)=>{return[$.id,$.name,$.macAddress,$.location,$.terminal,$.status,new Date($.lastPing).toLocaleString(),$.printCount]});return{headings:J,data:X}}async function aX(G="csv",J){let X=await RJ(G),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;return X.download(J||$)}async function tX(G="csv",J){let X=await RJ(G),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;X.store(J||$)}var{randomUUIDv7:rX}=globalThis.Bun;import{db as BG}from"@stacksjs/database";async function eX(G){try{let J={...G,uuid:rX()},X=await BG.insertInto("print_devices").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await BG.selectFrom("print_devices").where("id","=",$).selectAll().executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print device: ${J.message}`);throw J}}async function J6(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:rX()};await BG.insertInto("print_devices").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${X.message}`);throw X}}import{db as AG}from"@stacksjs/database";import{formatDate as zG}from"@stacksjs/orm";async function G6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await AG.updateTable("print_devices").set({...J,updated_at:zG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device: ${$.message}`);throw $}}async function X6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await AG.updateTable("print_devices").set({status:J,updated_at:zG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device status: ${$.message}`);throw $}}async function $6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await AG.updateTable("print_devices").set({print_count:J,updated_at:zG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print count: ${$.message}`);throw $}}var UG={};Q(UG,{update:()=>H6,unresolveGroup:()=>B6,resolveGroup:()=>Q6,ignoreGroup:()=>V6,fetchTimeline:()=>x6,fetchStats:()=>N6,fetchGrouped:()=>Z6,fetchById:()=>W6,fetchByGroup:()=>M6,fetchAll:()=>TJ,destroyGroup:()=>Y6,destroy:()=>K6,bulkUpdateStatus:()=>F6,bulkDestroy:()=>L6});import{db as OG}from"@stacksjs/database";import{log as RG}from"@stacksjs/logging";async function K6(G){try{return await OG.deleteFrom("errors").where("id","=",G).execute(),!0}catch(J){return RG.error("[commerce/errors] destroy failed",{id:G,error:J}),!1}}async function L6(G){try{return await OG.deleteFrom("errors").where("id","in",G).execute(),!0}catch(J){return RG.error("[commerce/errors] bulkDestroy failed",{count:G.length,error:J}),!1}}async function Y6(G,J){try{return await OG.deleteFrom("errors").where("type","=",G).where("message","=",J).execute(),!0}catch(X){return RG.error("[commerce/errors] destroyGroup failed",{type:G,message:J,error:X}),!1}}import{db as UJ}from"@stacksjs/database";async function W6(G){return await UJ.selectFrom("errors").where("id","=",G).selectAll().executeTakeFirst()}async function TJ(){return await UJ.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function Z6(){let G=await UJ.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),J=new Map;for(let $ of G){let K=`${$.type}:${$.message}`;if(!J.has(K))J.set(K,{errors:[],firstSeen:new Date($.created_at),lastSeen:new Date($.created_at)});let L=J.get(K);L.errors.push($);let Y=new Date($.created_at);if(Y<L.firstSeen)L.firstSeen=Y;if(Y>L.lastSeen)L.lastSeen=Y}let X=[];for(let[$,K]of J){let L=K.errors[0],Y=K.errors.find((M)=>M.status!==null)?.status,W="unresolved";if(Y===1)W="resolved";else if(Y===2)W="ignored";X.push({id:L.id,type:L.type,message:L.message,stack:L.stack,status:W,count:K.errors.length,first_seen:K.firstSeen.toISOString(),last_seen:K.lastSeen.toISOString(),error_ids:K.errors.map((M)=>M.id)})}return X.sort(($,K)=>new Date(K.last_seen).getTime()-new Date($.last_seen).getTime()),X}async function M6(G,J){return await UJ.selectFrom("errors").where("type","=",G).where("message","=",J).selectAll().orderBy("created_at","desc").execute()}async function N6(){let G=await TJ(),J=new Date,X=new Date(J.getTime()-86400000),$=new Date(J.getTime()-172800000),K=G.filter((W)=>new Date(W.created_at)>=X).length,L=G.filter((W)=>{let M=new Date(W.created_at);return M>=$&&M<X}).length,Y=L===0?K>0?100:0:Math.round((K-L)/L*100);return{total:G.length,unresolved:G.filter((W)=>W.status===null||W.status===0).length,resolved:G.filter((W)=>W.status===1).length,ignored:G.filter((W)=>W.status===2).length,last_24h:K,trend:Y}}async function x6(){let G=await TJ(),J=new Date,X=[];for(let $=23;$>=0;$--){let K=new Date(J.getTime()-$*60*60*1000);K.setMinutes(0,0,0);let L=new Date(K.getTime()+3600000),Y=G.filter((W)=>{let M=new Date(W.created_at);return M>=K&&M<L}).length;X.push({hour:K.toISOString(),count:Y})}return X}import{db as YJ}from"@stacksjs/database";import{sql as WJ}from"@stacksjs/database";import{log as ZJ}from"@stacksjs/logging";async function H6(G,J){try{return await YJ.updateTable("errors").set({...J,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("id","=",G).execute(),!0}catch(X){return ZJ.error("[commerce/errors] update failed",{id:G,error:X}),!1}}async function F6(G,J){try{return await YJ.updateTable("errors").set({status:J,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("id","in",G).execute(),!0}catch(X){return ZJ.error("[commerce/errors] bulkUpdateStatus failed",{count:G.length,status:J,error:X}),!1}}async function Q6(G,J){try{return await YJ.updateTable("errors").set({status:1,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return ZJ.error("[commerce/errors] resolveGroup failed",{type:G,message:J,error:X}),!1}}async function V6(G,J){try{return await YJ.updateTable("errors").set({status:2,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return ZJ.error("[commerce/errors] ignoreGroup failed",{type:G,message:J,error:X}),!1}}async function B6(G,J){try{return await YJ.updateTable("errors").set({status:0,updated_at:WJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return ZJ.error("[commerce/errors] unresolveGroup failed",{type:G,message:J,error:X}),!1}}var PG={};Q(PG,{updateBalance:()=>f6,update:()=>I6,store:()=>w6,fetchTotalValue:()=>T6,fetchTotalCurrentBalance:()=>S6,fetchStats:()=>E6,fetchById:()=>v,fetchByCode:()=>SG,fetchAll:()=>A6,fetchActive:()=>z6,destroy:()=>q6,compareActiveGiftCards:()=>R6,checkBalance:()=>O6,calculateGiftCardValues:()=>U6,bulkDestroy:()=>P6});import{db as qG}from"@stacksjs/database";import{formatDate as gL}from"@stacksjs/orm";import{db as j,sql as TG}from"@stacksjs/database";import{formatDate as D,toTimestamp as r}from"@stacksjs/orm";import{db as v9}from"@stacksjs/database";async function y(G,J,X){let $=v9.selectFrom(G);if(X)$=X($);$=$.select((Y)=>Object.entries(J).map(([W,M])=>{let Z=M.column??"id",N=Y.fn[M.kind](Z);if(M.filter){let x=M.filter;N=N.filterWhere(x.column,x.op,x.value)}return N.as(W)}));let K=await $.executeTakeFirst(),L={};for(let Y of Object.keys(J)){let W=K?.[Y];L[Y]=typeof W==="number"?W:Number(W??0)||0}return L}async function A6(){return await j.selectFrom("gift_cards").selectAll().execute()}async function v(G){return await j.selectFrom("gift_cards").where("id","=",G).selectAll().executeTakeFirst()}async function SG(G){return await j.selectFrom("gift_cards").where("code","=",G).selectAll().executeTakeFirst()}async function z6(){return await j.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function E6(){let{count:G}=await y("gift_cards",{count:{kind:"count"}}),J=r(new Date),X=await j.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where((N)=>N.or([N("expiry_date",">=",J),N("expiry_date","is",null)])).select((N)=>N.fn.count("id").as("count")).executeTakeFirst(),$=await j.selectFrom("gift_cards").select(["status",(N)=>N.fn.count("id").as("count")]).groupBy("status").execute(),{count:K}=await y("gift_cards",{count:{kind:"count"}},(N)=>N.where((x)=>TG`${x.ref("current_balance")} / ${x.ref("initial_balance")} < 0.25`)),{count:L}=await y("gift_cards",{count:{kind:"count"}},(N)=>N.where((x)=>TG`${x.ref("current_balance")} / ${x.ref("initial_balance")} >= 0.25 AND ${x.ref("current_balance")} / ${x.ref("initial_balance")} <= 0.75`)),{count:Y}=await y("gift_cards",{count:{kind:"count"}},(N)=>N.where((x)=>TG`${x.ref("current_balance")} / ${x.ref("initial_balance")} > 0.75`)),W=new Date;W.setDate(W.getDate()+30);let M=await j.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",r(W)).where("expiry_date",">=",J).selectAll().limit(5).execute(),Z=await j.selectFrom("gift_cards").where("last_used_date","is not",null).selectAll().limit(5).execute();return{total:G,active:Number(X?.count||0),by_status:$.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:K,medium:L,high:Y},expiring_soon:M,recently_used:Z}}async function O6(G){let J=await SG(G);if(!J)return{valid:!1,message:"Gift card not found"};if(!J.isActive||J.status!=="ACTIVE")return{valid:!1,balance:J.currentBalance,currency:J.currency,message:`Gift card is ${J.status.toLowerCase()}`};if(J.expiryDate){if(new Date(J.expiryDate)<new Date)return{valid:!1,balance:J.currentBalance,currency:J.currency,message:"Gift card has expired"}}return{valid:!0,balance:J.currentBalance,currency:J.currency}}async function R6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await j.selectFrom("gift_cards").select((x)=>x.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").where((x)=>x.or([x("expiry_date",">=",r(J)),x("expiry_date","is",null)])).where("created_at",">=",D(X)).where("created_at","<=",D(J)).executeTakeFirst(),Y=await j.selectFrom("gift_cards").select((x)=>x.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").where((x)=>x.or([x("expiry_date",">=",r(K)),x("expiry_date","is",null)])).where("created_at",">=",D(K)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(L?.count||0),M=Number(Y?.count||0),Z=W-M,N=M!==0?Z/M*100:W>0?100:0;return{current_period:W,previous_period:M,difference:Z,percentage_change:N,days_range:G}}async function U6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await j.selectFrom("gift_cards").select((q)=>[q.fn.sum("initial_balance").as("total_initial"),q.fn.sum("current_balance").as("total_balance"),q.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").where((q)=>q.or([q("expiry_date",">=",r(J)),q("expiry_date","is",null)])).where("created_at",">=",D(X)).where("created_at","<=",D(J)).executeTakeFirst(),Y=await j.selectFrom("gift_cards").select((q)=>[q.fn.sum("initial_balance").as("total_initial"),q.fn.sum("current_balance").as("total_balance"),q.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").where((q)=>q.or([q("expiry_date",">=",r(K)),q("expiry_date","is",null)])).where("created_at",">=",D(K)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(L?.total_initial||0),M=Number(L?.total_balance||0),Z=Number(L?.card_count||0),N=Number(Y?.total_initial||0),x=Number(Y?.total_balance||0),H=Number(Y?.card_count||0),E=W>0?(W-M)/W*100:0,B=N>0?(N-x)/N*100:0,F=Z>0?W/Z:0,A=Z>0?M/Z:0,_=W-N,m=M-x,b=Z-H,a=N!==0?_/N*100:W>0?100:0,R=x!==0?m/x*100:M>0?100:0,I=H!==0?b/H*100:Z>0?100:0;return{current_period:{total_initial_value:W,total_remaining_balance:M,utilization_rate:E,card_count:Z,average_initial_value:F,average_remaining_balance:A},previous_period:{total_initial_value:N,total_remaining_balance:x,utilization_rate:B,card_count:H},comparison:{initial_value:{difference:_,percentage:Math.abs(a),is_increase:_>=0},balance:{difference:m,percentage:Math.abs(R),is_increase:m>=0},card_count:{difference:b,percentage:Math.abs(I),is_increase:b>=0}},days_range:G}}async function T6(){let{total_value:G}=await y("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:G}}async function S6(){let{total_balance:G}=await y("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:G}}async function q6(G){if(!await v(G))throw Error(`Gift card with ID ${G} not found`);return!!await qG.deleteFrom("gift_cards").where("id","=",G).executeTakeFirst()}async function P6(G){if(!G.length)return 0;let J=await qG.deleteFrom("gift_cards").where("id","in",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}var{randomUUIDv7:h9}=globalThis.Bun;import{db as j6}from"@stacksjs/database";import{HttpError as k6}from"@stacksjs/error-handling";import{isUniqueViolation as g9}from"@stacksjs/orm";async function w6(G){let J=G,X={...G,current_balance:J.current_balance??J.initial_balance,status:G.status||"ACTIVE",is_active:J.is_active??!0,uuid:h9()};try{let $=await j6.insertInto("gift_cards").values(X).executeTakeFirst(),K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);if(K)return await j6.selectFrom("gift_cards").where("id","=",K).selectAll().executeTakeFirst();return}catch($){if($ instanceof k6)throw $;if(g9($))throw new k6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to create gift card: ${$.message}`);throw $}}import{db as SJ}from"@stacksjs/database";import{HttpError as C6}from"@stacksjs/error-handling";import{formatDate as _6,isUniqueViolation as y9}from"@stacksjs/orm";async function I6(G,J){if(!await v(G))throw Error(`Gift card with ID ${G} not found`);try{return await SJ.updateTable("gift_cards").set({...J,updated_at:_6(new Date)}).where("id","=",G).execute(),await v(G)}catch($){if($ instanceof C6)throw $;if(y9($))throw new C6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to update gift card: ${$.message}`);throw $}}async function f6(G,J){let X=_6(new Date),$=await SJ.updateTable("gift_cards").set({current_balance:SJ.raw(`current_balance + ${J}`),last_used_date:X,status:SJ.raw(`CASE WHEN current_balance + ${J} = 0 THEN 'USED' ELSE 'ACTIVE' END`),updated_at:X}).where("id","=",G).where("is_active","=",1).where("status","=","ACTIVE").where((Y)=>Y.cmpr(Y.raw(`current_balance + ${J}`),">=",0)).executeTakeFirst();if(Number($?.numUpdatedRows??$?.affectedRows??0)>0)return await v(G);let L=await v(G);if(!L)throw Error(`Gift card with ID ${G} not found`);if(!L.is_active||L.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var yG={};Q(yG,{validateQuantityBounds:()=>gG,validateCouponStacking:()=>L$,validateCartQuantities:()=>Y$,updateStatus:()=>e6,updateDeliveryInfo:()=>J$,update:()=>r6,storeOrdersExport:()=>m6,store:()=>s6,softDelete:()=>h6,registerCommerceWebhookHandlers:()=>X$,recomputeOrderTotals:()=>K$,placeOrder:()=>t6,handlePaymentIntentSucceeded:()=>fG,handlePaymentIntentFailed:()=>vG,handleChargeRefunded:()=>hG,fetchStats:()=>l6,fetchDailyOrderTrends:()=>n6,fetchById:()=>h,fetchAll:()=>b6,exportOrders:()=>PJ,emitOrderShipped:()=>jG,emitOrderRefunded:()=>NJ,emitOrderPaid:()=>c,emitOrderDelivered:()=>kG,emitOrderCreated:()=>kJ,emitOrderCancelled:()=>MJ,emitForStatus:()=>wJ,downloadOrders:()=>p6,destroy:()=>v6,compareOrdersByPeriod:()=>c6,cleanupAbandonedCarts:()=>W$,canTransition:()=>jJ,calculateOrderMetrics:()=>u6,bulkSoftDelete:()=>y6,bulkDestroy:()=>g6});import{db as qJ}from"@stacksjs/database";async function v6(G){try{let J=await qJ.deleteFrom("orders").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function h6(G){try{let J=await qJ.updateTable("orders").set({status:"CANCELED"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete order: ${J.message}`);throw J}}async function g6(G){if(!G.length)return 0;try{let J=await qJ.deleteFrom("orders").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}async function y6(G){if(!G.length)return 0;try{let J=await qJ.updateTable("orders").set({status:"CANCELED"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete orders: ${J.message}`);throw J}}import{db as D6}from"@stacksjs/database";import{createSpreadsheet as D9}from"ts-spreadsheets";async function PJ(G="csv"){let J=await p9(),X=m9(J);return D9(X,{type:G})}async function p9(){let G=await D6.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),J=G.map((L)=>L.id);if(J.length===0)return[];let $=(await D6.selectFrom("order_items").where("order_items.order_id","in",J).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((L,Y)=>{if(!Y.order_id)return L;if(!L[Y.order_id])L[Y.order_id]={totalItems:0,totalPrice:0};return L[Y.order_id].totalItems+=Y.quantity,L[Y.order_id].totalPrice+=Y.price*Y.quantity,L},{});return G.map((L)=>{let Y=$[L.id]||{totalItems:0,totalPrice:0};return{...L,totalItems:Y.totalItems,totalPrice:Y.totalPrice}})}function m9(G){let J=["Order ID","Customer","Date","Total","Status","Items"],X=G.map(($)=>{let K=$.order_items?.map((L)=>`${L.product?.name} (Qty: ${L.quantity}, Price: $${L.price})`).join(" | ")||"No Items";return[$.id,$.customer?.name||"N/A",$.created_at,$.total_amount,$.status,K]});return{headings:J,data:X}}async function p6(G="csv",J){let X=await PJ(G),$=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;return X.download(J||$)}async function m6(G="csv",J){let X=await PJ(G),$=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;X.store(J||$)}import{db as S}from"@stacksjs/database";async function b6(G){let J=S.selectFrom("orders").selectAll().orderBy("created_at","desc");if(G)J=J.limit(G);let X=await J.execute();return await Promise.all(X.map(async($)=>{let K=await S.selectFrom("order_items").where("order_id","=",$.id).selectAll().execute();return{...$,items:K}}))}async function h(G){return await S.selectFrom("orders").where("id","=",G).selectAll().executeTakeFirst()}async function l6(){let G=await S.selectFrom("orders").select((Y)=>Y.fn.count("id").as("count")).executeTakeFirst(),J=await S.selectFrom("orders").select(["status",(Y)=>Y.fn.count("id").as("count")]).groupBy("status").execute(),X=await S.selectFrom("orders").select(["order_type",(Y)=>Y.fn.count("id").as("count")]).groupBy("order_type").execute(),$=await S.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),K=await Promise.all($.map(async(Y)=>{let W=await S.selectFrom("order_items").where("order_id","=",Y.id).selectAll().execute();return{...Y,items:W}})),L=await S.selectFrom("orders").select((Y)=>Y.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(G?.count||0),by_status:J,by_type:X,recent:K,revenue:Number(L?.total||0)}}async function c6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await S.selectFrom("orders").select((x)=>x.fn.count("id").as("count")).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),Y=await S.selectFrom("orders").select((x)=>x.fn.count("id").as("count")).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=Number(L?.count||0),M=Number(Y?.count||0),Z=W-M,N=M!==0?Z/M*100:W>0?100:0;return{current_period:W,previous_period:M,difference:Z,percentage_change:N,days_range:G}}async function u6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await S.selectFrom("orders").select((R)=>[R.fn.count("id").as("total_orders"),R.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),Y=await S.selectFrom("orders").select((R)=>[R.fn.count("id").as("total_orders"),R.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=await S.selectFrom("orders").select(["status",(R)=>R.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).groupBy("status").execute(),M=await S.selectFrom("orders").select(["order_type",(R)=>R.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).groupBy("order_type").execute(),Z=Number(L?.total_orders||0),N=Number(L?.total_revenue||0),x=Z>0?N/Z:0,H=Number(Y?.total_orders||0),E=Number(Y?.total_revenue||0),B=H>0?E/H:0,F=Z-H,A=N-E,_=x-B,m=H!==0?F/H*100:Z>0?100:0,b=E!==0?A/E*100:N>0?100:0,a=B!==0?_/B*100:x>0?100:0;return{current_period:{total_orders:Z,total_revenue:N,average_order_value:x,orders_by_status:W.map((R)=>({status:R.status,count:Number(R.count)})),orders_by_type:M.map((R)=>({order_type:R.order_type,count:Number(R.count)}))},previous_period:{total_orders:H,total_revenue:E,average_order_value:B},comparison:{orders:{difference:F,percentage:Math.abs(m),is_increase:F>=0},revenue:{difference:A,percentage:Math.abs(b),is_increase:A>=0},average_order_value:{difference:_,percentage:Math.abs(a),is_increase:_>=0}},days_range:G}}async function n6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await S.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).orderBy("created_at","asc").execute(),K=new Map;for(let L of $){let Y=(L.created_at||"").split("T")[0]||"unknown",W=K.get(Y)||{order_count:0,revenue:0};W.order_count++,W.revenue+=Number(L.total_amount||0),K.set(Y,W)}return Array.from(K.entries()).map(([L,Y])=>({date:L,order_count:Y.order_count,revenue:Y.revenue}))}var{randomUUIDv7:b9}=globalThis.Bun;import{db as o6}from"@stacksjs/database";import{formatDate as i6}from"@stacksjs/orm";async function s6(G){let J={...G,status:G.status||"PENDING",uuid:b9(),created_at:i6(new Date),updated_at:i6(new Date)};try{let X=await o6.insertInto("orders").values(J).executeTakeFirst(),$=Number(X?.insertId)||Number(X?.numInsertedOrUpdatedRows);if($)return await o6.selectFrom("orders").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof Error)throw Error(`Failed to create order: ${X.message}`);throw X}}var{randomUUIDv7:c9}=globalThis.Bun;import{db as CJ}from"@stacksjs/database";import{formatDate as u9}from"@stacksjs/orm";import{sql as d6}from"@stacksjs/database";var l9={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","CANCELLED","REFUNDED"],SHIPPED:["DELIVERED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]};function jJ(G,J){if(G===J)return!0;return l9[G]?.includes(J)??!1}async function e(G,J){try{let X=await import("@stacksjs/events").catch(()=>null);if(!X)return;let $=X.dispatch;if(typeof $!=="function")return;$(G,J)}catch{}}async function kJ(G){await e("order:created",{order:G})}async function c(G,J){await e("order:paid",{order:G,payment:J})}async function jG(G){await e("order:shipped",{order:G})}async function kG(G){await e("order:delivered",{order:G})}async function MJ(G,J){await e("order:cancelled",{order:G,reason:J})}async function NJ(G,J){await e("order:refunded",{order:G,refundAmount:J})}async function wJ(G,J){switch(G){case"PROCESSING":return c(J);case"SHIPPED":return jG(J);case"DELIVERED":return kG(J);case"CANCELLED":return MJ(J);case"REFUNDED":return NJ(J);case"PENDING":default:}}var a6=!1;async function n9(G){try{let J=await CJ.selectFrom("order_idempotency").where("idempotency_key","=",G).selectAll().executeTakeFirst();if(!J)return null;return await CJ.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}catch(J){if(J?.message?.includes("no such table")||J?.message?.includes("doesn't exist")){if(!a6)a6=!0,console.warn("[commerce/orders] order_idempotency table missing \u2014 idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw J}}async function t6(G){if(G.idempotencyKey){let J=await n9(G.idempotencyKey);if(J)return{ok:!0,order:J}}try{let J=await CJ.transaction().execute(async(X)=>{let $=u9(new Date),K={...G.order,status:G.order.status||"PENDING",uuid:c9(),created_at:$,updated_at:$},L=await X.insertInto("orders").values(K).executeTakeFirst(),Y=Number(L?.insertId)||Number(L?.numInsertedOrUpdatedRows);if(!Y)throw Object.assign(Error("order insert returned no id"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let W;if(G.payment)try{let Z=await X.insertInto("payments").values({...G.payment,order_id:Y,created_at:$,updated_at:$}).executeTakeFirst(),N=Number(Z?.insertId)||Number(Z?.numInsertedOrUpdatedRows);if(N)W=await X.selectFrom("payments").where("id","=",N).selectAll().executeTakeFirst()}catch(Z){if(Z?.message?.includes("UNIQUE constraint")||Z?.message?.includes("Duplicate entry"))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(Z,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(G.inventory&&G.inventory.length>0)for(let Z=0;Z<G.inventory.length;Z++){let{id:N,delta:x}=G.inventory[Z];if(!Number.isFinite(x)||x===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});let H=await X.updateTable("products").set({inventory_count:d6`inventory_count + ${x}`,updated_at:$}).where("id","=",N).where(d6`inventory_count + ${x}`,">=",0).execute();if(!Number(H?.numUpdatedRows??H?.[0]?.numUpdatedRows??H?.numAffectedRows??0))throw Object.assign(Error(`inventory adjust failed for product ${N}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(G.idempotencyKey)try{await X.insertInto("order_idempotency").values({idempotency_key:G.idempotencyKey,order_id:Y,created_at:$}).execute()}catch(Z){if(Z?.message?.includes("UNIQUE constraint")||Z?.message?.includes("Duplicate entry"))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!(Z?.message?.includes("no such table")||Z?.message?.includes("doesn't exist")))throw Z}let M=await X.selectFrom("orders").where("id","=",Y).selectAll().executeTakeFirst();if(!M)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:M,payment:W}});if(kJ(J.order),J.payment)c(J.order,J.payment);return{ok:!0,order:J.order,payment:J.payment}}catch(J){if(J?.__placeFail)return{ok:!1,reason:J.reason,failedAt:J.failedAt,error:J};throw J}}import{db as wG}from"@stacksjs/database";import{formatDate as CG}from"@stacksjs/orm";async function r6(G,J){if(!await h(G))throw Error(`Order with ID ${G} not found`);try{return await wG.updateTable("orders").set({...J,updated_at:CG(new Date)}).where("id","=",G).execute(),await h(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update order: ${$.message}`);throw $}}async function e6(G,J){let X=await h(G);if(!X)throw Error(`Order with ID ${G} not found`);let $=X.status??"PENDING";if(!jJ($,J))throw Error(`[commerce/orders] illegal status transition ${$} \u2192 ${J}`);try{await wG.updateTable("orders").set({status:J,updated_at:CG(new Date)}).where("id","=",G).execute();let K=await h(G);if(K)wJ(J,K);return K}catch(K){if(K instanceof Error)throw TypeError(`Failed to update order status: ${K.message}`);throw K}}async function J$(G,J,X){let $=await h(G);if(!$)throw Error(`Order with ID ${G} not found`);let K={updated_at:CG(new Date)};if(J!==void 0)K.delivery_address=J;if(X!==void 0)K.estimated_delivery_time=X;if(Object.keys(K).length===1)return $;try{return await wG.updateTable("orders").set(K).where("id","=",G).execute(),await h(G)}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery information: ${L.message}`);throw L}}import{db as JJ}from"@stacksjs/database";import{formatDate as _J}from"@stacksjs/orm";async function _G(G){let J=await JJ.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!J)return null;return await JJ.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}var G$=!1;async function IG(G,J){try{return await J.insertInto("stripe_webhook_events").values({event_id:G,processed_at:_J(new Date)}).execute(),!0}catch(X){if(X?.message?.includes("UNIQUE constraint")||X?.message?.includes("Duplicate entry"))return!1;if(X?.message?.includes("no such table")||X?.message?.includes("doesn't exist")){if(!G$)G$=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw X}}async function fG(G){let X=G.data.object?.id;if(!X)return;await JJ.transaction().execute(async(K)=>{if(!await IG(G.id,K))return;let Y=await K.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!Y)return;let W=_J(new Date);await K.updateTable("payments").set({status:"succeeded",updated_at:W}).where("id","=",Y.id).execute();let M=await K.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(M&&M.status==="PENDING")await K.updateTable("orders").set({status:"PROCESSING",updated_at:W}).where("id","=",M.id).execute()});let $=await _G(X);if($)await c($)}async function vG(G){let J=G.data.object,X=J?.id;if(!X)return;let K=J?.last_payment_error?.message??"payment failed";await JJ.transaction().execute(async(Y)=>{if(!await IG(G.id,Y))return;let M=await Y.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!M)return;let Z=_J(new Date);await Y.updateTable("payments").set({status:"failed",failure_reason:K,updated_at:Z}).where("id","=",M.id).execute();let N=await Y.selectFrom("orders").where("id","=",M.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await Y.updateTable("orders").set({status:"CANCELLED",updated_at:Z}).where("id","=",N.id).execute()});let L=await _G(X);if(L)await MJ(L,K)}async function hG(G){let J=G.data.object,X=J?.payment_intent;if(!X)return;let $=J?.amount_refunded??0;await JJ.transaction().execute(async(L)=>{if(!await IG(G.id,L))return;let W=await L.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!W)return;let M=_J(new Date);await L.updateTable("payments").set({status:"refunded",refund_amount:$,updated_at:M}).where("id","=",W.id).execute();let Z=await L.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(Z&&Z.status!=="REFUNDED")await L.updateTable("orders").set({status:"REFUNDED",updated_at:M}).where("id","=",Z.id).execute()});let K=await _G(X);if(K)await NJ(K,$)}async function X$(){let G=await import("@stacksjs/payments").catch(()=>null);if(!G)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:J,onCharge:X}=G;if(typeof J!=="function"||typeof X!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return J({succeeded:fG,failed:vG}),X({refunded:hG}),()=>{}}import{db as $$}from"@stacksjs/database";async function o9(G){if(G.length===0)return new Map;let J=await $$.selectFrom("products").where("id","in",G).select(["id","price"]).execute(),X=new Map;for(let $ of J){let K=Number($.price);if(Number.isFinite(K))X.set($.id,Math.round(K))}return X}async function i9(G){try{let J=await $$.selectFrom("tax_rates").where("id","=",G).select(["rate"]).executeTakeFirst(),X=Number(J?.rate??0);return Number.isFinite(X)?X:0}catch{return 0}}async function K$(G){let J=G.items.map((B)=>B.productId),X=await o9(J),$=G.taxRateId!=null?await i9(G.taxRateId):0,K=0,L=[];for(let B of G.items){let F=B.unitPriceCents??X.get(B.productId)??0,A=Math.round(F*B.quantity);K+=A,L.push({productId:B.productId,quantity:B.quantity,unitPriceCents:F,lineCents:A})}let Y=Math.max(0,G.discountCents??0),W=Math.max(0,K-Y),M=Math.round(W*$),Z=Math.max(0,G.shippingCents??0),N=K-Y+M+Z,x=G.maxDriftCents??5,H=!1,E=0;if(G.clientTotalCents!=null)E=Math.abs(N-G.clientTotalCents),H=E>x;return{subtotalCents:K,discountCents:Y,taxCents:M,shippingCents:Z,totalCents:N,resolvedItems:L,priceChanged:H,diffCents:E}}import{db as IJ}from"@stacksjs/database";function L$(G,J={}){let X=G.length;if(X<=1)return{ok:!0,count:X};if(!J.allowMultiple)return{ok:!1,count:X,reason:"multiple-not-allowed"};let $=J.maxStacked??Number.POSITIVE_INFINITY;if(X>$)return{ok:!1,count:X,reason:"exceeds-max-stacked"};return{ok:!0,count:X}}async function gG(G,J){if(!Number.isFinite(J)||J<=0)return{ok:!1,productId:G,quantity:J,reason:"non-positive"};let X;try{X=await IJ.selectFrom("products").where("id","=",G).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:G,quantity:J}}if(!X)return{ok:!1,productId:G,quantity:J,reason:"product-missing"};let $=X.min_order_qty??null,K=X.max_order_qty??null;if($!=null&&J<$)return{ok:!1,productId:G,quantity:J,reason:"below-min",bound:$};if(K!=null&&J>K)return{ok:!1,productId:G,quantity:J,reason:"above-max",bound:K};return{ok:!0,productId:G,quantity:J}}async function Y$(G){for(let X of G){let $=await gG(X.productId,X.quantity);if(!$.ok)return $}let J=G[G.length-1]??{productId:0,quantity:0};return{ok:!0,productId:J.productId,quantity:J.quantity}}async function W$(G={}){let J=G.olderThanDays??30,X=G.limit??1000,K=new Date(Date.now()-J*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let L=await IJ.deleteFrom("carts").where("updated_at","<",K).where("id","in",(W)=>W.selectFrom("carts").select("id").where("updated_at","<",K).limit(X)).execute();return{deleted:Number(L?.numDeletedRows??L?.[0]?.numDeletedRows??L?.affectedRows??0),cutoffAt:K}}catch{try{let L=await IJ.selectFrom("carts").where("updated_at","<",K).select(["id"]).limit(X).execute();if(L.length===0)return{deleted:0,cutoffAt:K};let Y=L.map((Z)=>Z.id),W=await IJ.deleteFrom("carts").where("id","in",Y).execute();return{deleted:Number(W?.numDeletedRows??W?.[0]?.numDeletedRows??W?.affectedRows??L.length),cutoffAt:K}}catch{return{deleted:0,cutoffAt:K}}}}var DG={};Q(DG,{update:()=>z$,store:()=>A$,fetchPaymentStatsByMethod:()=>F$,fetchPaymentStats:()=>H$,fetchMonthlyPaymentTrends:()=>Q$,fetchById:()=>xJ,fetchAll:()=>x$,destroy:()=>M$,bulkDestroy:()=>N$});import{db as Z$}from"@stacksjs/database";async function M$(G){try{let J=await Z$.deleteFrom("payments").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payment: ${J.message}`);throw J}}async function N$(G){if(!G.length)return 0;try{let J=await Z$.deleteFrom("payments").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payments: ${J.message}`);throw J}}import{db as p}from"@stacksjs/database";import{formatDate as w}from"@stacksjs/orm";async function x$(){return await p.selectFrom("payments").selectAll().execute()}async function xJ(G){return await p.selectFrom("payments").selectAll().where("id","=",G).executeTakeFirst()}async function H$(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await p.selectFrom("payments").select((I)=>[I.fn.count("id").as("transaction_count"),I.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").executeTakeFirst(),Y=await p.selectFrom("payments").select((I)=>[I.fn.count("id").as("transaction_count"),I.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(K)).where("created_at","<=",w($)).where("status","=","completed").executeTakeFirst(),W=await p.selectFrom("payments").select((I)=>I.fn.count("id").as("count")).where("created_at",">=",w(X)).where("created_at","<=",w(J)).executeTakeFirst(),M=Number(L?.transaction_count||0),Z=Number(L?.total_revenue||0),N=M>0?Z/M:0,x=Number(Y?.transaction_count||0),H=Number(Y?.total_revenue||0),E=x>0?H/x:0,B=M-x,F=Z-H,A=N-E,_=x>0?B/x*100:M>0?100:0,m=H>0?F/H*100:Z>0?100:0,b=E>0?A/E*100:N>0?100:0,a=Number(W?.count||0),R=a>0?M/a*100:0;return{total_transactions:M,total_revenue:Z,average_transaction:N,successful_rate:R,comparison:{transactions:{difference:B,percentage:Math.abs(_),is_increase:B>=0},revenue:{difference:F,percentage:Math.abs(m),is_increase:F>=0},average:{difference:A,percentage:Math.abs(b),is_increase:A>=0}}}}async function F$(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await p.selectFrom("payments").select((W)=>[W.fn.count("id").as("total_count"),W.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").executeTakeFirst(),K=Number($?.total_count||0),L=await p.selectFrom("payments").select(["method",(W)=>W.fn.count("id").as("count"),(W)=>W.fn.sum("amount").as("revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").groupBy("method").execute(),Y={};return L.forEach((W)=>{let M=Number(W.count||0),Z=Number(W.revenue||0),N=K>0?M/K*100:0;Y[W.method]={count:M,revenue:Z,percentage_of_total:N}}),Y}async function Q$(){let G=new Date,J=new Date(G);J.setMonth(G.getMonth()-11),J.setDate(1);let X=await p.selectFrom("payments").selectAll().where("created_at",">=",w(J)).where("status","=","completed").execute(),$={};for(let L of X){let Y=L.created_at?new Date(L.created_at):new Date,W=Y.getFullYear(),M=Y.getMonth()+1,Z=`${W}-${String(M).padStart(2,"0")}`;if(!$[Z])$[Z]={year:W,month:M,transactions:0,revenue:0};$[Z].transactions++,$[Z].revenue+=Number(L.amount||0)}return Object.keys($).sort().map((L)=>{let Y=$[L],W=Y.transactions,M=Y.revenue,Z=W>0?M/W:0;return{month:new Date(Y.year,Y.month-1,1).toLocaleString("default",{month:"short"}),year:Y.year,transactions:W,revenue:M,average:Z}})}var{randomUUIDv7:s9}=globalThis.Bun;import{db as V$}from"@stacksjs/database";import{HttpError as B$}from"@stacksjs/error-handling";import{isUniqueViolation as d9}from"@stacksjs/orm";async function A$(G){let J={...G,status:G.status||"PENDING",currency:G.currency||"USD",uuid:s9()};try{let X=await V$.insertInto("payments").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if($)return await V$.selectFrom("payments").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof B$)throw X;if(d9(X))throw new B$(409,"A payment with this transaction ID already exists");if(X instanceof Error){if(X.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${X.message}`)}throw X}}import{db as a9}from"@stacksjs/database";import{formatDate as t9}from"@stacksjs/orm";async function z$(G,J){if(!await xJ(G))throw Error(`Payment with ID ${G} not found`);try{return await a9.updateTable("payments").set({...J,updated_at:t9(new Date)}).where("id","=",G).execute(),await xJ(G)}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry")&&$.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${$.message}`)}throw $}}var oG={};Q(oG,{variants:()=>pJ,units:()=>DJ,reviews:()=>yJ,manufacturers:()=>gJ,items:()=>hJ,default:()=>YK,categories:()=>vJ});var vJ={};Q(vJ,{updateParent:()=>y$,updateDisplayOrder:()=>h$,updateActiveStatus:()=>g$,update:()=>v$,store:()=>mG,removeChildCategories:()=>w$,remove:()=>j$,findOrCreateByName:()=>f$,fetchStats:()=>S$,fetchRootCategories:()=>R$,fetchChildCategories:()=>U$,fetchCategoryTree:()=>P$,fetchByName:()=>E$,fetchById:()=>U,fetchByDisplayOrder:()=>T$,fetchAll:()=>pG,fetchActive:()=>O$,deactivateChildCategories:()=>_$,deactivate:()=>C$,compareCategoryGrowth:()=>q$,bulkRemove:()=>k$});import{db as u}from"@stacksjs/database";import{db as P}from"@stacksjs/database";import{formatDate as HJ}from"@stacksjs/orm";async function pG(){return await P.selectFrom("categories").selectAll().execute()}async function U(G){return await P.selectFrom("categories").where("id","=",G).selectAll().executeTakeFirst()}async function E$(G){return await P.selectFrom("categories").where("name","=",G).selectAll().executeTakeFirst()}async function O$(){return await P.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function R$(){return await P.selectFrom("categories").where("parent_category_id","is",null).where("is_active","=",!0).selectAll().execute()}async function U$(G){return await P.selectFrom("categories").where("parent_category_id","=",G).where("is_active","=",!0).selectAll().execute()}async function T$(G=!0){let J=P.selectFrom("categories").where("is_active","=",!0).selectAll();if(G)return await J.orderBy("display_order","asc").execute();else return await J.orderBy("display_order","desc").execute()}async function S$(){let G=await P.selectFrom("categories").select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),J=await P.selectFrom("categories").where("is_active","=",!0).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),X=await P.selectFrom("categories").where("parent_category_id","is",null).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),$=await P.selectFrom("categories").where("image_url","is not",null).select((M)=>M.fn.count("id").as("count")).executeTakeFirst(),K=new Date;K.setDate(K.getDate()-30);let L=HJ(K),Y=await P.selectFrom("categories").where("created_at",">=",L).selectAll().limit(5).execute(),W=await P.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").where("c.parent_category_id","is not",null).select(["c.parent_category_id","parent.name as parent_name",(M)=>M.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(G?.count||0),active:Number(J?.count||0),root_categories:Number(X?.count||0),child_categories:Number(G?.count||0)-Number(X?.count||0),with_images:Number($?.count||0),recently_added:Y,top_parent_categories:W.map((M)=>({id:String(M.parent_category_id||""),name:String(M.parent_name||""),child_count:Number(M.child_count)}))}}async function q$(G=30){let J=new Date,X=HJ(J),$=new Date;$.setDate(J.getDate()-G);let K=HJ($),L=new Date($);L.setDate(L.getDate()-1);let Y=HJ(L),W=new Date(L);W.setDate(L.getDate()-G);let M=HJ(W),Z=await P.selectFrom("categories").select((F)=>F.fn.count("id").as("count")).where("created_at",">=",K).where("created_at","<=",X).executeTakeFirst(),N=await P.selectFrom("categories").select((F)=>F.fn.count("id").as("count")).where("created_at",">=",M).where("created_at","<=",Y).executeTakeFirst(),x=Number(Z?.count||0),H=Number(N?.count||0),E=x-H,B=H!==0?E/H*100:x>0?100:0;return{current_period:x,previous_period:H,difference:E,percentage_change:B,days_range:G}}async function P$(){let G=await pG(),J=new Map;G.forEach((K)=>{J.set(K.id,{...K,children:[]})});let X=[];G.forEach((K)=>{let L=J.get(K.id);if(K.parent_category_id){let Y=J.get(K.parent_category_id);if(Y)Y.children.push(L)}else X.push(L)}),X.sort((K,L)=>K.display_order-L.display_order);let $=(K)=>{K.sort((L,Y)=>L.display_order-Y.display_order),K.forEach((L)=>{if(L.children.length>0)$(L.children)})};return $(X),X}async function j$(G){if(!await U(G))throw Error(`Category with ID ${G} not found`);return!!await u.deleteFrom("categories").where("id","=",G).executeTakeFirst()}async function k$(G){if(!G.length)return 0;let J=await u.deleteFrom("categories").where("id","in",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}async function w$(G){let J=await u.deleteFrom("categories").where("parent_category_id","=",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}async function C$(G){if(!await U(G))throw Error(`Category with ID ${G} not found`);return!!await u.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",G).executeTakeFirst()}async function _$(G){let J=await u.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",G).execute();return Number(J.length)||0}import{db as I$}from"@stacksjs/database";import{slug as r9}from"@stacksjs/strings";async function mG(G){try{let J={...G,slug:G.name?.toLowerCase().replace(/\s+/g,"-")||"",categorizable_type:"product",display_order:0},X=await I$.insertInto("categories").values(J).executeTakeFirst();if(!X)throw Error("Failed to create category");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await U($);if(!K)throw Error("Failed to create category");return K}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry")&&J.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to create category: ${J.message}`)}throw J}}async function f$(G){if(!G.name)throw Error("Name is required");let J=await I$.selectFrom("categories").selectAll().where("name","=",G.name).executeTakeFirst();if(J)return J;let X={name:G.name,slug:r9(G.name),is_active:G.is_active??!0,categorizable_type:G.categorizable_type??"default",display_order:0};return await mG(X)}import{db as FJ}from"@stacksjs/database";import{formatDate as fJ}from"@stacksjs/orm";async function v$(G,J){await J.validate();let X=await U(G);if(!X)throw Error(`Category with ID ${G} not found`);let $={name:J.get("name"),description:J.get("description"),imageUrl:J.get("imageUrl"),isActive:J.get("isActive"),parentCategoryId:J.get("parentCategoryId"),displayOrder:J.get("displayOrder"),updated_at:fJ(new Date)};if(Object.keys($).length===0)return X;try{return await FJ.updateTable("categories").set($).where("id","=",G).execute(),await U(G)}catch(K){if(K instanceof Error){if(K.message.includes("Duplicate entry")&&K.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to update category: ${K.message}`)}throw K}}async function h$(G,J){if(!await U(G))throw Error(`Category with ID ${G} not found`);try{return await FJ.updateTable("categories").set({display_order:J,updated_at:fJ(new Date)}).where("id","=",G).execute(),await U(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category display order: ${$.message}`);throw $}}async function g$(G,J){if(!await U(G))throw Error(`Category with ID ${G} not found`);try{return await FJ.updateTable("categories").set({is_active:J,updated_at:fJ(new Date)}).where("id","=",G).execute(),await U(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category active status: ${$.message}`);throw $}}async function y$(G,J){if(!await U(G))throw Error(`Category with ID ${G} not found`);if(J){let $=Number(J);if($===G)throw Error("A category cannot be its own parent");if(!await U($))throw Error(`Parent category with ID ${J} not found`);if(await e9(G,J))throw Error("This operation would create a circular reference in the category hierarchy")}try{let $={updated_at:fJ(new Date)};if(J===null)await FJ.updateTable("categories").set({...$,parent_category_id:void 0}).where("id","=",G).execute();else await FJ.updateTable("categories").set({...$,parent_category_id:J}).where("id","=",G).execute();return await U(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category parent: ${$.message}`);throw $}}async function e9(G,J){let X=Number(J),$=new Set;while(X){if($.has(X))return!0;if(X===G)return!0;$.add(X);let K=await U(X);if(!K||!K.parentCategoryId)return!1;X=Number(K.parentCategoryId)}return!1}var hJ={};Q(hJ,{updateInventory:()=>d$,updateAvailability:()=>s$,update:()=>i$,store:()=>n$,fetchTopProducts:()=>l$,fetchById:()=>g,fetchAll:()=>b$,destroy:()=>p$,bulkStore:()=>o$,bulkDestroy:()=>m$});import{db as D$}from"@stacksjs/database";async function p$(G){try{let J=await D$.deleteFrom("products").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product item: ${J.message}`);throw J}}async function m$(G){if(!G.length)return 0;try{let J=await D$.deleteFrom("products").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product items: ${J.message}`);throw J}}import{db as n,sql as JK}from"@stacksjs/database";async function g(G){let J=await n.selectFrom("products").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=null,$=null;if(J.manufacturer_id)X=await n.selectFrom("manufacturers").where("id","=",J.manufacturer_id).selectAll().executeTakeFirst();if(J.category_id)$=await n.selectFrom("categories").where("id","=",J.category_id).selectAll().executeTakeFirst();return{...J,manufacturer:X,category:$}}return}async function b$(){let G=await n.selectFrom("products").selectAll().execute(),J=G.map((Z)=>Z.manufacturer_id).filter((Z)=>Z!==null&&Z!==void 0),X=G.map((Z)=>Z.category_id).filter((Z)=>Z!==null&&Z!==void 0),$=n.selectFrom("manufacturers"),K=n.selectFrom("categories");if(J.length>0)$=$.where("id","in",J);if(X.length>0)K=K.where("id","in",X);let L=await $.selectAll().execute(),Y=await K.selectAll().execute(),W=L.reduce((Z,N)=>{return Z[N.id]=N,Z},{}),M=Y.reduce((Z,N)=>{return Z[N.id]=N,Z},{});return G.map((Z)=>({...Z,manufacturer:Z.manufacturer_id?W[Z.manufacturer_id]:null,category:Z.category_id?M[Z.category_id]:null}))}async function l$(G=5){try{return(await n.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",(X)=>X.fn.sum("order_items.quantity").as("units_sold"),JK`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(G).execute()).map((X)=>({id:Number(X.id),name:String(X.name??"Unnamed product"),units_sold:Number(X.units_sold??0),revenue:Number(X.revenue??0),inventory_count:Number(X.inventory_count??0)}))}catch(J){if(J instanceof Error)throw TypeError(`Failed to fetch top products: ${J.message}`);throw J}}var{randomUUIDv7:c$}=globalThis.Bun;import{db as u$}from"@stacksjs/database";async function n$(G){try{let J={...G,uuid:c$()},X=await u$.insertInto("products").values(J).executeTakeFirst();if(!X)throw Error("Failed to create product item");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await g($);if(!K)throw Error("Failed to create product item");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product item: ${J.message}`);throw J}}async function o$(G){if(!G.length)return 0;let J=0;try{return await u$.transaction().execute(async(X)=>{for(let $ of G){let K={...$,uuid:c$()};await X.insertInto("products").values(K).execute(),J++}}),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product items in bulk: ${X.message}`);throw X}}import{db as bG,sql as _0}from"@stacksjs/database";import{formatDate as lG}from"@stacksjs/orm";async function i$(G,J){try{if(!G)throw Error("Product item ID is required for update");let X=await bG.updateTable("products").set({...J,updated_at:lG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product item");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item: ${X.message}`);throw X}}async function s$(G,J){if(!await g(G))throw Error(`Product item with ID ${G} not found`);try{return await bG.updateTable("products").set({is_available:J,updated_at:lG(new Date)}).where("id","=",G).execute(),await g(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update product item availability: ${$.message}`);throw $}}async function d$(G,J){let X=await g(G);if(!X)throw Error(`Product item with ID ${G} not found`);let $={updated_at:lG(new Date)};if(J!==void 0)$.inventory_count=J;if(Object.keys($).length===1)return X;try{return await bG.updateTable("products").set($).where("id","=",G).execute(),await g(G)}catch(K){if(K instanceof Error)throw TypeError(`Failed to update inventory information: ${K.message}`);throw K}}var gJ={};Q(gJ,{updateFeaturedStatus:()=>H2,updateByUuid:()=>F2,update:()=>x2,store:()=>Z2,fetchWithProductCount:()=>K2,fetchFeatured:()=>X2,fetchByUuid:()=>G2,fetchById:()=>J2,fetchByCountry:()=>$2,fetchAll:()=>e$,destroy:()=>t$,bulkStore:()=>M2,bulkDestroy:()=>r$});import{db as a$}from"@stacksjs/database";async function t$(G){try{let J=await a$.deleteFrom("manufacturers").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function r$(G){if(!G.length)return 0;try{let J=await a$.deleteFrom("manufacturers").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}import{db as o}from"@stacksjs/database";function e$(){return o.selectFrom("manufacturers").selectAll().execute()}async function J2(G){return await o.selectFrom("manufacturers").where("id","=",G).selectAll().executeTakeFirst()}async function G2(G){return await o.selectFrom("manufacturers").where("uuid","=",G).selectAll().executeTakeFirst()}async function X2(G=10){return await o.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(G).execute()}async function $2(G,J={}){let X=J.page||1,$=J.limit||2,K=await o.selectFrom("manufacturers").select((M)=>M.fn.count("id").as("total")).where("country","=",G).executeTakeFirst(),L=Number(K?.total||0),Y=await o.selectFrom("manufacturers").selectAll().where("country","=",G).limit($).offset((X-1)*$).execute(),W=Math.ceil(L/$);return{data:Y,paging:{total_records:L,page:X,total_pages:W},next_cursor:X<W?X+1:null}}async function K2(G={}){let J=o.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(G.country)J=J.where("m.country","=",G.country);if(G.featured!==void 0)J=J.where("m.featured","=",G.featured);return J=J.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",(X)=>X.fn.count("p.id").as("product_count")]).groupBy("m.id"),J.execute()}var{randomUUIDv7:Y2}=globalThis.Bun;import{db as W2}from"@stacksjs/database";import{HttpError as L2}from"@stacksjs/error-handling";import{isUniqueViolation as GK}from"@stacksjs/orm";async function Z2(G){try{let J={...G,uuid:Y2(),featured:G.featured??!1},X=await W2.insertInto("manufacturers").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create manufacturer");return X}catch(J){if(J instanceof L2)throw J;if(GK(J))throw new L2(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to create manufacturer: ${J.message}`);throw J}}async function M2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:Y2(),featured:X.featured??!1};await W2.insertInto("manufacturers").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${X.message}`);throw X}}import{db as cG}from"@stacksjs/database";import{HttpError as N2}from"@stacksjs/error-handling";import{formatDate as uG,isUniqueViolation as XK}from"@stacksjs/orm";async function x2(G,J){try{if(!G)throw Error("Manufacturer ID is required for update");let X=await cG.updateTable("manufacturers").set({...J,updated_at:uG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error(`Manufacturer with ID ${G} not found`);return X}catch(X){if(X instanceof N2)throw X;if(XK(X))throw new N2(409,"A manufacturer with this name already exists");if(X instanceof Error)throw Error(`Failed to update manufacturer: ${X.message}`);throw X}}async function H2(G,J){try{let X=await cG.updateTable("manufacturers").set({featured:J,updated_at:uG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update manufacturer featured status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${X.message}`);throw X}}async function F2(G,J){try{let X=await cG.updateTable("manufacturers").set({...J,updated_at:uG(new Date)}).where("uuid","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update manufacturer");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update manufacturer: ${X.message}`);throw X}}var yJ={};Q(yJ,{updateVotes:()=>j2,update:()=>P2,store:()=>T2,fetchMostHelpfulByProductId:()=>U2,fetchByUserId:()=>O2,fetchByProductId:()=>E2,fetchById:()=>A2,fetchApprovedByProductId:()=>R2,fetchAll:()=>z2,destroy:()=>V2,bulkDestroy:()=>B2});import{db as Q2}from"@stacksjs/database";async function V2(G){try{let J=await Q2.deleteFrom("reviews").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function B2(G){if(!G.length)return 0;try{let J=await Q2.deleteFrom("reviews").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}import{db as GJ}from"@stacksjs/database";async function A2(G){return await GJ.selectFrom("reviews").where("id","=",G).selectAll().executeTakeFirst()}async function z2(){return await GJ.selectFrom("reviews").selectAll().execute()}async function E2(G){return await GJ.selectFrom("reviews").where("product_id","=",G).selectAll().execute()}async function O2(G){return await GJ.selectFrom("reviews").where("customer_id","=",G).selectAll().execute()}async function R2(G){return await GJ.selectFrom("reviews").where("product_id","=",G).where("is_approved","=",!0).selectAll().execute()}async function U2(G){return await GJ.selectFrom("reviews").where("product_id","=",G).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:$K}=globalThis.Bun;import{db as KK}from"@stacksjs/database";async function T2(G){try{let J={...G,uuid:$K(),is_verified_purchase:G.is_verified_purchase??!1,is_approved:G.is_approved??!1,helpful_votes:G.helpful_votes??0,unhelpful_votes:G.unhelpful_votes??0,is_featured:G.is_featured??!1},X=await KK.insertInto("reviews").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create review");return X}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${J.message}`)}throw J}}import{db as S2}from"@stacksjs/database";import{formatDate as q2}from"@stacksjs/orm";async function P2(G,J){try{if(!G)throw Error("Review ID is required for update");let X=await S2.updateTable("reviews").set({...J,updated_at:q2(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update review");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review: ${X.message}`);throw X}}async function j2(G,J,X=!0){try{let $=J==="helpful"?"helpful_votes":"unhelpful_votes",K=X?`COALESCE("${$}", 0) + 1`:`MAX(COALESCE("${$}", 0) - 1, 0)`,L=await S2.unsafe(`UPDATE "reviews" SET "${$}" = ${K}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[q2(new Date),G]).execute(),Y=Array.isArray(L)?L[0]:L;if(!Y)throw Error("Failed to update review votes");return Y}catch($){if($ instanceof Error)throw TypeError(`Failed to update review votes: ${$.message}`);throw $}}var DJ={};Q(DJ,{updateDefaultStatus:()=>b2,update:()=>p2,store:()=>h2,getDefaultUnit:()=>D2,formatUnitOptions:()=>y2,fetchById:()=>I2,fetchAll:()=>f2,destroy:()=>w2,bulkUpdate:()=>m2,bulkStore:()=>g2,bulkDestroy:()=>C2});import{db as k2}from"@stacksjs/database";async function w2(G){try{let J=await k2.deleteFrom("product_units").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product unit: ${J.message}`);throw J}}async function C2(G){if(!G.length)return 0;try{let J=await k2.deleteFrom("product_units").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product units: ${J.message}`);throw J}}import{db as _2}from"@stacksjs/database";async function I2(G){return await _2.selectFrom("product_units").where("id","=",G).selectAll().executeTakeFirst()}async function f2(){return await _2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:v2}=globalThis.Bun;import{db as XJ}from"@stacksjs/database";async function h2(G){try{let J={...G,uuid:v2()},X=await XJ.insertInto("product_units").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(J.is_default)await XJ.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",X.id).execute();return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product unit: ${J.message}`);throw J}}async function g2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:v2()},K=await XJ.insertInto("product_units").values($).returningAll().executeTakeFirst();if($.is_default&&K)await XJ.updateTable("product_units").set({is_default:!1}).where("type","=",$.type).where("id","!=",K.id).execute();J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product units in bulk: ${X.message}`);throw X}}function y2(G){try{let J=XJ.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(G)J=J.where("type","=",G);return J=J.orderBy("name"),J.execute().then((X)=>X.map(($)=>({id:String($.id),name:$.name,abbreviation:$.abbreviation,is_default:$.is_default})))}catch(J){if(J instanceof Error)throw TypeError(`Failed to format unit options: ${J.message}`);throw J}}async function D2(G){try{return await XJ.selectFrom("product_units").selectAll().where("type","=",G).where("is_default","=",!0).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get default unit: ${J.message}`);throw J}}import{db as i}from"@stacksjs/database";import{formatDate as nG}from"@stacksjs/orm";async function p2(G,J){try{if(!G)throw Error("Product unit ID is required for update");let X=await i.updateTable("product_units").set({...J,updated_at:nG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product unit");if(J.is_default===!0&&J.type)await i.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",G).execute();return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product unit: ${X.message}`);throw X}}async function m2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $=X;if(!$.id)continue;let K=$.data&&typeof $.data==="object"?$.data:{...$};delete K.id;let L=await i.updateTable("product_units").set({...K,updated_at:nG(new Date)}).where("id","=",$.id).executeTakeFirst(),Y=K;if(Y.is_default===!0&&Y.type)await i.updateTable("product_units").set({is_default:!1}).where("type","=",Y.type).where("id","!=",$.id).execute();if(Number(L.numUpdatedRows)>0)J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product units in bulk: ${X.message}`);throw X}}async function b2(G,J){try{let X=await i.selectFrom("product_units").select("type").where("id","=",G).executeTakeFirst();if(!X)return!1;let $=await i.updateTable("product_units").set({is_default:J,updated_at:nG(new Date)}).where("id","=",G).executeTakeFirst();if(J&&X.type)await i.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",G).execute();return Number($.numUpdatedRows)>0}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product unit default status: ${X.message}`);throw X}}var pJ={};Q(pJ,{update:()=>X4,store:()=>a2,generateVariantCombinations:()=>e2,formatVariantOptions:()=>r2,fetchById:()=>o2,fetchAll:()=>i2,destroy:()=>c2,bulkUpdate:()=>$4,bulkStore:()=>t2,bulkDestroy:()=>u2});import{db as l2}from"@stacksjs/database";async function c2(G){try{let J=await l2.deleteFrom("product_variants").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variant: ${J.message}`);throw J}}async function u2(G){if(!G.length)return 0;try{let J=await l2.deleteFrom("product_variants").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variants: ${J.message}`);throw J}}import{db as n2}from"@stacksjs/database";async function o2(G){return await n2.selectFrom("product_variants").where("id","=",G).selectAll().executeTakeFirst()}async function i2(){return await n2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:s2}=globalThis.Bun;import{db as d2}from"@stacksjs/database";async function a2(G){try{let J={...G,uuid:s2()},X=await d2.insertInto("product_variants").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product variant");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variant: ${J.message}`);throw J}}async function t2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:s2()};await d2.insertInto("product_variants").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${X.message}`);throw X}}function r2(G){if(!G||!G.length)return JSON.stringify([]);let J=G.map((X)=>X.trim()).filter(Boolean);return JSON.stringify(J)}function e2(G){let J=Object.keys(G);if(!J.length)return[];function X($,K){if($===J.length)return[K];let L=J[$],Y=G[L],W=[];for(let M of Y){let Z={...K,[L]:M};W.push(...X($+1,Z))}return W}return X(0,{})}import{db as J4}from"@stacksjs/database";import{formatDate as G4}from"@stacksjs/orm";async function X4(G,J){try{let X=await J4.updateTable("product_variants").set({...J,updated_at:G4(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product variant");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product variant: ${X.message}`);throw X}}async function $4(G){if(!G.length)return 0;let J=0;try{for(let X of G){if(!X.id)continue;let $=await J4.updateTable("product_variants").set({...X,updated_at:G4(new Date)}).where("id","=",X.id).executeTakeFirst();if(Number($.numUpdatedRows)>0)J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${X.message}`);throw X}}var LK={categories:vJ,items:hJ,manufacturers:gJ,reviews:yJ,units:DJ,variants:pJ},YK=LK;var dG={};Q(dG,{updateStatus:()=>V4,updatePrintJob:()=>B4,update:()=>Q4,store:()=>H4,fetchById:()=>Z4,fetchAll:()=>M4,destroy:()=>L4,bulkStore:()=>F4,bulkDestroy:()=>Y4});import{db as K4}from"@stacksjs/database";async function L4(G){try{let J=await K4.deleteFrom("receipts").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print log: ${J.message}`);throw J}}async function Y4(G){if(!G.length)return 0;try{let J=await K4.deleteFrom("receipts").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete receipts: ${J.message}`);throw J}}import{db as W4}from"@stacksjs/database";async function Z4(G){return await W4.selectFrom("receipts").where("id","=",G).selectAll().executeTakeFirst()}async function M4(){return await W4.selectFrom("receipts").selectAll().execute()}var{randomUUIDv7:N4}=globalThis.Bun;import{db as x4}from"@stacksjs/database";async function H4(G){try{let J={...G,uuid:N4()},X=await x4.insertInto("receipts").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipt: ${J.message}`);throw J}}async function F4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:N4()})),X=await x4.insertInto("receipts").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${J.message}`);throw J}}import{db as iG}from"@stacksjs/database";import{formatDate as sG}from"@stacksjs/orm";async function Q4(G,J){try{if(!G)throw Error("Receipt ID is required for update");let X=await iG.updateTable("receipts").set({...J,updated_at:sG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update receipt");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt: ${X.message}`);throw X}}async function V4(G,J){try{let X=await iG.updateTable("receipts").set({status:J,updated_at:sG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update receipt status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt status: ${X.message}`);throw X}}async function B4(G,J,X,$){try{let K={updated_at:sG(new Date)};if(J!==void 0)K.size=J;if(X!==void 0)K.pages=X;if($!==void 0)K.duration=$;let L=await iG.updateTable("receipts").set(K).where("id","=",G).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update receipt job information");return L}catch(K){if(K instanceof Error)throw TypeError(`Failed to update receipt job information: ${K.message}`);throw K}}var WX={};Q(WX,{zones:()=>ZG,routes:()=>bJ,rates:()=>KG,methods:()=>rJ,licenses:()=>sJ,drivers:()=>nJ,digital:()=>uJ,default:()=>MK});var bJ={};Q(bJ,{updateStops:()=>k4,updateMetrics:()=>w4,updateLastActive:()=>P4,update:()=>j4,store:()=>q4,fetchById:()=>O4,fetchByDriver:()=>T4,fetchAll:()=>R4,fetchActive:()=>U4,destroy:()=>z4,bulkDestroy:()=>E4});import{db as A4}from"@stacksjs/database";async function z4(G){try{let J=await A4.deleteFrom("delivery_routes").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery route: ${J.message}`);throw J}}async function E4(G){if(!G.length)return 0;try{let J=await A4.deleteFrom("delivery_routes").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery routes: ${J.message}`);throw J}}import{db as mJ}from"@stacksjs/database";async function O4(G){return await mJ.selectFrom("delivery_routes").where("id","=",G).selectAll().executeTakeFirst()}async function R4(){return await mJ.selectFrom("delivery_routes").selectAll().execute()}async function U4(){return await mJ.selectFrom("delivery_routes").where("last_active","<=",new Date(Date.now()-86400000)).selectAll().execute()}async function T4(G){return await mJ.selectFrom("delivery_routes").where("driver","=",G).selectAll().execute()}var{randomUUIDv7:WK}=globalThis.Bun;import{db as S4}from"@stacksjs/database";async function q4(G){try{let J={...G,uuid:WK()},X=await S4.insertInto("delivery_routes").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create delivery route");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create delivery route: ${J.message}`);throw J}}async function P4(G){try{let J=await S4.updateTable("delivery_routes").set({last_active:new Date().toISOString(),updated_at:new Date().toISOString()}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update delivery route last active");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route last active: ${J.message}`);throw J}}import{db as aG}from"@stacksjs/database";import{formatDate as tG}from"@stacksjs/orm";async function j4(G,J){try{if(!G)throw Error("Delivery route ID is required for update");let X=await aG.updateTable("delivery_routes").set({...J,updated_at:tG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery route");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery route: ${X.message}`);throw X}}async function k4(G,J){try{let X=await aG.updateTable("delivery_routes").set({stops:J,updated_at:tG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery route stops");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery route stops: ${X.message}`);throw X}}async function w4(G,J,X){try{let $={updated_at:tG(new Date)};if(J!==void 0)$.delivery_time=J;if(X!==void 0)$.total_distance=X;let K=await aG.updateTable("delivery_routes").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update delivery metrics");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery metrics: ${$.message}`);throw $}}var uJ={};Q(uJ,{updateStatus:()=>b4,updateDeliverySettings:()=>l4,update:()=>m4,store:()=>D4,softDelete:()=>_4,fetchById:()=>cJ,fetchAll:()=>h4,destroy:()=>C4,bulkStore:()=>p4,bulkSoftDelete:()=>f4,bulkDestroy:()=>I4});import{db as lJ}from"@stacksjs/database";async function C4(G){try{let J=await lJ.deleteFrom("digital_deliveries").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital delivery: ${J.message}`);throw J}}async function _4(G){try{let J=await lJ.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${J.message}`);throw J}}async function I4(G){if(!G.length)return 0;try{let J=await lJ.deleteFrom("digital_deliveries").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${J.message}`);throw J}}async function f4(G){if(!G.length)return 0;try{let J=await lJ.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${J.message}`);throw J}}import{db as v4}from"@stacksjs/database";async function cJ(G){return await v4.selectFrom("digital_deliveries").where("id","=",G).selectAll().executeTakeFirst()}async function h4(){return await v4.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:g4}=globalThis.Bun;import{db as y4}from"@stacksjs/database";async function D4(G){try{let J={...G,uuid:g4()},X=await y4.insertInto("digital_deliveries").values(J).executeTakeFirst();if(!X)throw Error("Failed to create digital delivery");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await cJ($);if(!K)throw Error("Failed to create digital delivery");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital delivery: ${J.message}`);throw J}}async function p4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:g4()})),X=await y4.insertInto("digital_deliveries").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${J.message}`);throw J}}import{db as rG}from"@stacksjs/database";import{formatDate as eG}from"@stacksjs/orm";async function m4(G,J){try{if(!G)throw Error("Digital delivery ID is required for update");let X=await rG.updateTable("digital_deliveries").set({...J,updated_at:eG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update digital delivery");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update digital delivery: ${X.message}`);throw X}}async function b4(G,J){try{let X=await rG.updateTable("digital_deliveries").set({status:J,updated_at:eG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update digital delivery status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update digital delivery status: ${X.message}`);throw X}}async function l4(G,J,X,$,K){try{let L={updated_at:eG(new Date)};if(J!==void 0)L.download_limit=J;if(X!==void 0)L.expiry_days=X;if($!==void 0)L.requires_login=$;if(K!==void 0)L.automatic_delivery=K;let Y=await rG.updateTable("digital_deliveries").set(L).where("id","=",G).returningAll().executeTakeFirst();if(!Y)throw Error("Failed to update delivery settings");return Y}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery settings: ${L.message}`);throw L}}var nJ={};Q(nJ,{updateStatus:()=>e4,updateContact:()=>J7,update:()=>r4,store:()=>a4,fetchById:()=>QJ,fetchAll:()=>u4,destroy:()=>o4,bulkStore:()=>t4,bulkDestroy:()=>i4});import{db as n4}from"@stacksjs/database";import{db as c4}from"@stacksjs/database";async function QJ(G){return await c4.selectFrom("drivers").where("id","=",G).selectAll().executeTakeFirst()}async function u4(){return await c4.selectFrom("drivers").selectAll().execute()}async function o4(G){let J=await QJ(G);if(!J)throw Error(`Driver with ID ${G} not found`);try{return await n4.deleteFrom("drivers").where("id","=",G).execute(),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to delete driver: ${X.message}`);throw X}}async function i4(G){if(!G.length)return 0;let J=0;try{return await n4.transaction().execute(async(X)=>{for(let $ of G)if(await QJ($))await X.deleteFrom("drivers").where("id","=",$).execute(),J++}),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${X.message}`);throw X}}var{randomUUIDv7:s4}=globalThis.Bun;import{db as d4}from"@stacksjs/database";async function a4(G){try{let J={...G,uuid:s4()},X=await d4.insertInto("drivers").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create driver");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create driver: ${J.message}`);throw J}}async function t4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:s4()})),X=await d4.insertInto("drivers").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${J.message}`);throw J}}import{db as JX}from"@stacksjs/database";import{formatDate as GX}from"@stacksjs/orm";async function r4(G,J){try{if(!G)throw Error("Driver ID is required for update");let X=await JX.updateTable("drivers").set({...J,updated_at:GX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update driver");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update driver: ${X.message}`);throw X}}async function e4(G,J){try{let X=await JX.updateTable("drivers").set({status:J,updated_at:GX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update driver status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update driver status: ${X.message}`);throw X}}async function J7(G,J){try{let X={updated_at:GX(new Date)};if(J!==void 0)X.phone=J;let $=await JX.updateTable("drivers").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update contact information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update contact information: ${X.message}`);throw X}}var sJ={};Q(sJ,{updateStatus:()=>H7,updateExpiration:()=>F7,update:()=>x7,store:()=>M7,softDelete:()=>X7,fetchById:()=>iJ,fetchAll:()=>Y7,destroy:()=>G7,bulkStore:()=>N7,bulkSoftDelete:()=>K7,bulkDestroy:()=>$7});import{db as oJ}from"@stacksjs/database";async function G7(G){try{let J=await oJ.deleteFrom("license_keys").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license key: ${J.message}`);throw J}}async function X7(G){try{let J=await oJ.updateTable("license_keys").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license key: ${J.message}`);throw J}}async function $7(G){if(!G.length)return 0;try{let J=await oJ.deleteFrom("license_keys").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license keys: ${J.message}`);throw J}}async function K7(G){if(!G.length)return 0;try{let J=await oJ.updateTable("license_keys").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license keys: ${J.message}`);throw J}}import{db as L7}from"@stacksjs/database";async function iJ(G){return await L7.selectFrom("license_keys").where("id","=",G).selectAll().executeTakeFirst()}async function Y7(){return await L7.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:W7}=globalThis.Bun;import{db as Z7}from"@stacksjs/database";async function M7(G){try{let J={...G,uuid:W7()},X=await Z7.insertInto("license_keys").values(J).executeTakeFirst();if(!X)throw Error("Failed to create license key");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await iJ($);if(!K)throw Error("Failed to create license key");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create license key: ${J.message}`);throw J}}async function N7(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:W7()})),X=await Z7.insertInto("license_keys").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${J.message}`);throw J}}import{db as XX}from"@stacksjs/database";import{formatDate as $X}from"@stacksjs/orm";async function x7(G,J){try{if(!G)throw Error("License key ID is required for update");let X=await XX.updateTable("license_keys").set({...J,updated_at:$X(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update license key");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update license key: ${X.message}`);throw X}}async function H7(G,J){try{let X=await XX.updateTable("license_keys").set({status:J,updated_at:$X(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update license key status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update license key status: ${X.message}`);throw X}}async function F7(G,J){try{let X={updated_at:$X(new Date)};if(J!==void 0)X.expiry_date=J;let $=await XX.updateTable("license_keys").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update expiration information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update expiration information: ${X.message}`);throw X}}var rJ={};Q(rJ,{updateStatus:()=>q7,updatePricing:()=>P7,update:()=>S7,store:()=>O7,softDelete:()=>V7,getActiveShippingMethods:()=>T7,formatShippingOptions:()=>U7,fetchById:()=>s,fetchAll:()=>z7,destroy:()=>Q7,bulkStore:()=>R7,bulkSoftDelete:()=>A7,bulkDestroy:()=>B7});import{db as dJ}from"@stacksjs/database";async function Q7(G){try{let J=await dJ.deleteFrom("shipping_methods").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping method: ${J.message}`);throw J}}async function V7(G){try{let J=await dJ.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${J.message}`);throw J}}async function B7(G){if(!G.length)return 0;try{let J=await dJ.deleteFrom("shipping_methods").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping methods: ${J.message}`);throw J}}async function A7(G){if(!G.length)return 0;try{let J=await dJ.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${J.message}`);throw J}}import{db as aJ}from"@stacksjs/database";async function s(G){let J=await aJ.selectFrom("shipping_methods").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=await aJ.selectFrom("shipping_zones").where("shipping_method_id","=",G).selectAll().execute();return{...J,shippingZones:X}}return}async function z7(){let G=await aJ.selectFrom("shipping_methods").selectAll().execute(),J=G.map((L)=>L.id),X=aJ.selectFrom("shipping_zones");if(J.length>0)X=X.where("shipping_method_id","in",J);let K=(await X.selectAll().execute()).reduce((L,Y)=>{let W=Y.shipping_method_id;if(W!==null&&W!==void 0){if(!L[W])L[W]=[];L[W].push(Y)}return L},{});return G.map((L)=>({...L,shipping_zones:K[L.id]||[]}))}var{randomUUIDv7:E7}=globalThis.Bun;import{db as tJ}from"@stacksjs/database";async function O7(G){try{let J=G,X={name:G.name,description:G.description,base_rate:J.base_rate,free_shipping:J.free_shipping,status:G.status,uuid:E7()},$=await tJ.insertInto("shipping_methods").values(X).executeTakeFirst();if(!$)throw Error("Failed to create shipping method");let K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);return await s(K)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping method: ${J.message}`);throw J}}async function R7(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:E7()})),X=await tJ.insertInto("shipping_methods").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${J.message}`);throw J}}function U7(){try{return tJ.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping options: ${G.message}`);throw G}}async function T7(){try{return await tJ.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get active shipping methods: ${G.message}`);throw G}}import{db as KX}from"@stacksjs/database";import{formatDate as LX}from"@stacksjs/orm";async function S7(G,J){try{if(!G)throw Error("Shipping method ID is required for update");let X=await KX.updateTable("shipping_methods").set({...J,updated_at:LX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping method");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping method: ${X.message}`);throw X}}async function q7(G,J){try{let X=await KX.updateTable("shipping_methods").set({status:J,updated_at:LX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping method status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping method status: ${X.message}`);throw X}}async function P7(G,J,X){try{let $={updated_at:LX(new Date)};if(J!==void 0)$.base_rate=J;if(X!==void 0)$.free_shipping=X;let K=await KX.updateTable("shipping_methods").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update pricing information");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update pricing information: ${$.message}`);throw $}}var KG={};Q(KG,{validateZoneMatchesAddress:()=>h7,updateByZone:()=>s7,updateByMethod:()=>d7,update:()=>o7,store:()=>u7,resolveZoneForAddress:()=>GG,getShippingRatesByMethod:()=>y7,getRatesByZone:()=>f7,getRateByWeightAndZone:()=>YX,getRateByWeightAndAddress:()=>v7,formatShippingRateOptions:()=>g7,fetchById:()=>JG,fetchAll:()=>I7,destroyByZone:()=>w7,destroyByMethod:()=>C7,destroy:()=>j7,bulkUpdate:()=>i7,bulkStore:()=>n7,bulkDestroy:()=>k7});import{db as eJ}from"@stacksjs/database";async function j7(G){try{let J=await eJ.deleteFrom("shipping_rates").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rate: ${J.message}`);throw J}}async function k7(G){if(!G.length)return 0;try{let J=await eJ.deleteFrom("shipping_rates").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates: ${J.message}`);throw J}}async function w7(G){try{let J=await eJ.deleteFrom("shipping_rates").where("zone","=",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${J.message}`);throw J}}async function C7(G){try{let J=await eJ.deleteFrom("shipping_rates").where("method","=",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${J.message}`);throw J}}import{db as C}from"@stacksjs/database";async function JG(G){let J=await C.selectFrom("shipping_rates").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=null,$=null;if(J.shipping_zone_id)X=await C.selectFrom("shipping_zones").where("id","=",J.shipping_zone_id).selectAll().executeTakeFirst();if(J.shipping_method_id)$=await C.selectFrom("shipping_methods").where("id","=",J.shipping_method_id).selectAll().executeTakeFirst();return{...J,shipping_zone:X,shipping_method:$}}return}async function I7(){let G=await C.selectFrom("shipping_rates").selectAll().execute(),J=G.map((Z)=>Z.shipping_zone_id).filter((Z)=>Z!==null&&Z!==void 0),X=G.map((Z)=>Z.shipping_method_id).filter((Z)=>Z!==null&&Z!==void 0),$=C.selectFrom("shipping_zones"),K=C.selectFrom("shipping_methods");if(J.length>0)$=$.where("id","in",J);if(X.length>0)K=K.where("id","in",X);let L=await $.selectAll().execute(),Y=await K.selectAll().execute(),W=L.reduce((Z,N)=>{return Z[N.id]=N,Z},{}),M=Y.reduce((Z,N)=>{return Z[N.id]=N,Z},{});return G.map((Z)=>({...Z,shipping_zone:Z.shipping_zone_id?W[Z.shipping_zone_id]:[],shipping_method:Z.shipping_method_id?M[Z.shipping_method_id]:[]}))}async function f7(G){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",G).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${J.message}`);throw J}}async function YX(G,J){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).where("weight_from","<=",G).where("weight_to",">=",G).executeTakeFirst()}catch(X){if(X instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${X.message}`);throw X}}async function GG(G){if(!G?.countryCode)return null;try{let J=await C.selectFrom("shipping_zones").selectAll().where("countries","like",`%${G.countryCode}%`).where("status","=","active").execute();if(J.length===0)return null;let X=null;for(let $ of J){let K=1;if(G.region&&$.regions&&_7($.regions,G.region))K=2;if(G.postalCode&&$.postal_codes&&_7($.postal_codes,G.postalCode))K=3;if(!X||K>X.score)X={id:$.id,score:K}}return X?.id??null}catch{return null}}async function v7(G,J){let X=await GG(J);if(X==null)return;return YX(G,X)}async function h7(G,J){return await GG(J)===G}function _7(G,J){if(!G||!J)return!1;let X=J.trim().toUpperCase();for(let $ of G.split(/[,|;]/))if($.trim().toUpperCase()===X)return!0;return!1}async function g7(){try{return(await C.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((J)=>J.shipping_method_id!==null&&J.shipping_method_id!==void 0&&J.shipping_zone_id!==null&&J.shipping_zone_id!==void 0)}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping rate options: ${G.message}`);throw G}}async function y7(G){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",G).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${J.message}`);throw J}}var{randomUUIDv7:l7}=globalThis.Bun;import{db as c7}from"@stacksjs/database";import{db as VJ}from"@stacksjs/database";async function D7(){return await VJ.selectFrom("shipping_zones").selectAll().execute()}async function d(G){return await VJ.selectFrom("shipping_zones").where("id","=",G).selectAll().executeTakeFirst()}function p7(){try{return VJ.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping zone options: ${G.message}`);throw G}}async function m7(){try{return await VJ.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get active shipping zones: ${G.message}`);throw G}}async function b7(G){try{return await VJ.selectFrom("shipping_zones").selectAll().where("countries","like",`%${G}%`).where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${J.message}`);throw J}}async function u7(G){try{let J=await s(Number(G.shippingmethod_id)),X=await d(Number(G.shippingzone_id)),$={weightFrom:G.weightFrom,weightTo:G.weightTo,rate:G.rate,shippingmethod_id:J?.id,shippingzone_id:X?.id,uuid:l7()},K=await c7.insertInto("shipping_rates").values($).executeTakeFirst();if(!K)throw Error("Failed to create shipping rate");let L=Number(K.insertId)||Number(K.numInsertedOrUpdatedRows);return await JG(L)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping rate: ${J.message}`);throw J}}async function n7(G){if(!G.length)return 0;try{for(let $ of G){let K=await s(Number($.shippingmethod_id)),L=await d(Number($.shippingzone_id));if(!K)console.warn(`Shipping method with ID "${$.shippingmethod_id}" not found for bulk insert`);if(!L)console.warn(`Shipping zone with ID "${$.shippingzone_id}" not found for bulk insert`)}let J=G.map(($)=>({weightFrom:$.weightFrom,weightTo:$.weightTo,rate:$.rate,shippingmethod_id:$.shippingmethod_id,shippingzone_id:$.shippingzone_id,uuid:l7()})),X=await c7.insertInto("shipping_rates").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${J.message}`);throw J}}import{db as XG}from"@stacksjs/database";import{formatDate as $G}from"@stacksjs/orm";async function o7(G,J){try{if(!G)throw Error("Shipping rate ID is required for update");let X=await XG.updateTable("shipping_rates").set({...J,updated_at:$G(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping rate");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rate: ${X.message}`);throw X}}async function i7(G){if(!G.length)return 0;try{let J=0;for(let{id:X,data:$}of G){let K=await XG.updateTable("shipping_rates").set({...$,updated_at:$G(new Date)}).where("id","=",X).executeTakeFirst();if(Number(K.numUpdatedRows)>0)J++}return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${J.message}`);throw J}}async function s7(G,J){try{let X=await XG.updateTable("shipping_rates").set({...J,updated_at:$G(new Date)}).where("zone_id","=",G).executeTakeFirst();return Number(X.numUpdatedRows)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${X.message}`);throw X}}async function d7(G,J){try{let X=await XG.updateTable("shipping_rates").set({...J,updated_at:$G(new Date)}).where("method","=",G).executeTakeFirst();return Number(X.numUpdatedRows)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${X.message}`);throw X}}var ZG={};Q(ZG,{updateStatus:()=>L1,updateRegionsAndPostalCodes:()=>W1,updateCountries:()=>Y1,update:()=>K1,store:()=>X1,softDelete:()=>t7,getZonesByCountry:()=>b7,getActiveShippingZones:()=>m7,formatZoneOptions:()=>p7,fetchById:()=>d,fetchAll:()=>D7,destroy:()=>a7,bulkStore:()=>$1,bulkSoftDelete:()=>e7,bulkDestroy:()=>r7});import{db as LG}from"@stacksjs/database";async function a7(G){try{let J=await LG.deleteFrom("shipping_zones").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zone: ${J.message}`);throw J}}async function t7(G){try{let J=await LG.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${J.message}`);throw J}}async function r7(G){if(!G.length)return 0;try{let J=await LG.deleteFrom("shipping_zones").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zones: ${J.message}`);throw J}}async function e7(G){if(!G.length)return 0;try{let J=await LG.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${J.message}`);throw J}}var{randomUUIDv7:J1}=globalThis.Bun;import{db as G1}from"@stacksjs/database";async function X1(G){try{let J={...G,uuid:J1()},X=await G1.insertInto("shipping_zones").values(J).executeTakeFirst();if(!X)throw Error("Failed to create shipping zone");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await d($)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zone: ${J.message}`);throw J}}async function $1(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:J1()})),X=await G1.insertInto("shipping_zones").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${J.message}`);throw J}}import{db as YG}from"@stacksjs/database";import{formatDate as WG}from"@stacksjs/orm";async function K1(G,J){try{if(!G)throw Error("Shipping zone ID is required for update");let X=await YG.updateTable("shipping_zones").set({...J,updated_at:WG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone: ${X.message}`);throw X}}async function L1(G,J){try{let X=await YG.updateTable("shipping_zones").set({status:J,updated_at:WG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone status: ${X.message}`);throw X}}async function Y1(G,J){try{let X=await YG.updateTable("shipping_zones").set({countries:J,updated_at:WG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone countries");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${X.message}`);throw X}}async function W1(G,J,X){try{let $={updated_at:WG(new Date)};if(J!==void 0)$.regions=J;if(X!==void 0)$.postal_codes=X;let K=await YG.updateTable("shipping_zones").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update regions and postal codes");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${$.message}`);throw $}}var ZK={digital:uJ,drivers:nJ,licenses:sJ,methods:rJ,rates:KG,routes:bJ,zones:ZG},MK=ZK;var NX={};Q(NX,{updateStatus:()=>E1,updateRate:()=>O1,update:()=>z1,store:()=>B1,fetchById:()=>H1,fetchAll:()=>F1,destroy:()=>M1,bulkStore:()=>A1,bulkDestroy:()=>N1});import{db as Z1}from"@stacksjs/database";async function M1(G){try{let J=await Z1.deleteFrom("tax_rates").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rate: ${J.message}`);throw J}}async function N1(G){if(!G.length)return 0;try{let J=await Z1.deleteFrom("tax_rates").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rates: ${J.message}`);throw J}}import{db as x1}from"@stacksjs/database";async function H1(G){return await x1.selectFrom("tax_rates").where("id","=",G).selectAll().executeTakeFirst()}async function F1(){return await x1.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:Q1}=globalThis.Bun;import{db as V1}from"@stacksjs/database";async function B1(G){try{let J={...G,uuid:Q1()},X=await V1.insertInto("tax_rates").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rate: ${J.message}`);throw J}}async function A1(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:Q1()})),X=await V1.insertInto("tax_rates").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${J.message}`);throw J}}import{db as ZX}from"@stacksjs/database";import{formatDate as MX}from"@stacksjs/orm";async function z1(G,J){try{if(!G)throw Error("Tax rate ID is required for update");let X=J,$=await ZX.updateTable("tax_rates").set({name:J.name,rate:J.rate,type:J.type,country:J.country,region:J.region,status:J.status,is_default:X.is_default,updated_at:MX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update tax rate");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update tax rate: ${X.message}`);throw X}}async function E1(G,J){try{let X=await ZX.updateTable("tax_rates").set({status:J,updated_at:MX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update tax rate status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update tax rate status: ${X.message}`);throw X}}async function O1(G,J){try{let X=await ZX.updateTable("tax_rates").set({rate:J,updated_at:MX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update rate information");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update rate information: ${X.message}`);throw X}}var FX={};Q(FX,{restaurant:()=>KJ,products:()=>NG,default:()=>xK});var NG={};Q(NG,{updateStatus:()=>l1,updatePartySize:()=>c1,update:()=>b1,store:()=>p1,fetchWaiting:()=>I1,fetchPurchasedBetweenDates:()=>C1,fetchNotifiedBetweenDates:()=>w1,fetchCountByStatus:()=>f1,fetchCountBySource:()=>q1,fetchCountByQuantity:()=>j1,fetchCountByDateGrouped:()=>g1,fetchCountByDate:()=>P1,fetchCountByAllQuantities:()=>k1,fetchCountBetweenDates:()=>h1,fetchConversionRates:()=>v1,fetchCancelledBetweenDates:()=>_1,fetchById:()=>T1,fetchAll:()=>S1,destroy:()=>R1,bulkStore:()=>m1,bulkDestroy:()=>U1});import{db as MG}from"@stacksjs/database";async function R1(G){try{let J=await MG.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst();if(!J)return;return await MG.deleteFrom("waitlist_products").where("id","=",G).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist product: ${J.message}`);throw J}}async function U1(G){if(!G.length)return 0;try{return(await MG.deleteFrom("waitlist_products").where("id","in",G).execute()).length||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${J.message}`);throw J}}import{db as T}from"@stacksjs/database";import{formatDate as O}from"@stacksjs/orm";async function T1(G){return await T.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst()}async function S1(){return await T.selectFrom("waitlist_products").selectAll().execute()}async function q1(G,J){let X=T.selectFrom("waitlist_products").select(["source",(K)=>K.fn.count("id").as("count")]).groupBy("source");if(G&&J){let K=O(G),L=O(J);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.execute()).reduce((K,{source:L,count:Y})=>{return K[L]=Y,K},{})}async function P1(G=new Date){let J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=O(J),K=O(X);return(await T.selectFrom("waitlist_products").select((Y)=>Y.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function j1(G){return(await T.selectFrom("waitlist_products").select((X)=>X.fn.count("id").as("count")).where("quantity","=",G).executeTakeFirst())?.count??0}async function k1(G,J){let X=T.selectFrom("waitlist_products").select(["quantity",(K)=>K.fn.count("id").as("count")]).groupBy("quantity");if(G&&J){let K=O(G),L=O(J);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.execute()).reduce((K,{quantity:L,count:Y})=>{return K[L]=Y,K},{})}async function w1(G,J){let X=O(G),$=O(J);return await T.selectFrom("waitlist_products").selectAll().where("notified_at",">=",X).where("notified_at","<=",$).where("notified_at","is not",null).execute()}async function C1(G,J){let X=O(G),$=O(J);return await T.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",X).where("purchased_at","<=",$).where("purchased_at","is not",null).execute()}async function _1(G,J){let X=O(G),$=O(J);return await T.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",X).where("cancelled_at","<=",$).where("cancelled_at","is not",null).execute()}async function I1(){return await T.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function f1(G,J,X){let $=T.selectFrom("waitlist_products").select((L)=>L.fn.count("id").as("count")).where("status","=",G);if(J&&X){let L=O(J),Y=O(X);$=$.where("created_at",">=",L).where("created_at","<=",Y)}return(await $.executeTakeFirst())?.count??0}async function v1(G,J){let X=T.selectFrom("waitlist_products").select(["status",(M)=>M.fn.count("id").as("count")]).groupBy("status");if(G&&J){let M=O(G),Z=O(J);X=X.where("created_at",">=",M).where("created_at","<=",Z)}let $=await X.execute(),K=$.reduce((M,{count:Z})=>M+Z,0),L=$.find((M)=>M.status==="purchased")?.count??0,Y=K>0?L/K*100:0,W=$.reduce((M,{status:Z,count:N})=>{return M[Z]={count:N,percentage:K>0?N/K*100:0},M},{});return{totalConversionRate:Y,statusBreakdown:W}}async function h1(G,J){let X=O(G),$=O(J);return(await T.selectFrom("waitlist_products").select((L)=>L.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",$).executeTakeFirst())?.count??0}async function g1(G,J){let X=T.selectFrom("waitlist_products").select(["created_at"]);if(G&&J){let L=O(G),Y=O(J);X=X.where("created_at",">=",L).where("created_at","<=",Y)}let K=(await X.execute()).reduce((L,{created_at:Y})=>{let W=(Y||"").split("T")[0]||"unknown";return L[W]=(L[W]||0)+1,L},{});return Object.entries(K).map(([L,Y])=>({date:L,count:Y})).sort((L,Y)=>L.date.localeCompare(Y.date))}var{randomUUIDv7:y1}=globalThis.Bun;import{db as D1}from"@stacksjs/database";import{formatDate as $J}from"@stacksjs/orm";async function p1(G){try{let J=G,X={name:G.name,email:G.email,phone:G.phone,quantity:G.quantity??J.party_size,notification_preference:J.notification_preference,source:G.source,notes:G.notes,product_id:G.product_id,customer_id:G.customer_id,uuid:y1(),status:G.status||"waiting"};if(G.notified_at!==void 0)X.notified_at=typeof G.notified_at==="number"?$J(G.notified_at):G.notified_at;if(G.purchased_at!==void 0)X.purchased_at=typeof G.purchased_at==="number"?$J(G.purchased_at):G.purchased_at;if(G.cancelled_at!==void 0)X.cancelled_at=typeof G.cancelled_at==="number"?$J(G.cancelled_at):G.cancelled_at;let $=await D1.insertInto("waitlist_products").values(X).returningAll().executeTakeFirst();if(!$)throw Error("Failed to create waitlist product");return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist product: ${J.message}`);throw J}}async function m1(G){if(!G.length)return 0;try{let J=G.map(($)=>{let K=$,L={name:$.name,email:$.email,phone:$.phone,quantity:$.quantity??K.party_size,notification_preference:K.notification_preference,source:$.source,notes:$.notes,product_id:$.product_id,customer_id:$.customer_id,uuid:y1(),status:$.status||"waiting"};if($.notified_at!==void 0)L.notified_at=typeof $.notified_at==="number"?$J($.notified_at):$.notified_at;if($.purchased_at!==void 0)L.purchased_at=typeof $.purchased_at==="number"?$J($.purchased_at):$.purchased_at;if($.cancelled_at!==void 0)L.cancelled_at=typeof $.cancelled_at==="number"?$J($.cancelled_at):$.cancelled_at;return L}),X=await D1.insertInto("waitlist_products").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${J.message}`);throw J}}import{db as xX}from"@stacksjs/database";import{formatDate as HX}from"@stacksjs/orm";async function b1(G,J){try{if(!G)throw Error("Waitlist product ID is required for update");let X=J,$=await xX.updateTable("waitlist_products").set({name:J.name,email:J.email,phone:J.phone,quantity:J.quantity??X.party_size,notification_preference:X.notification_preference,source:J.source,notes:J.notes,status:J.status,product_id:J.product_id,customer_id:J.customer_id,notified_at:X.notified_at,purchased_at:X.purchased_at,cancelled_at:X.cancelled_at,updated_at:HX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update waitlist product");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update waitlist product: ${X.message}`);throw X}}async function l1(G,J){try{let X=await xX.updateTable("waitlist_products").set({status:J,updated_at:HX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update waitlist product status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update waitlist product status: ${X.message}`);throw X}}async function c1(G,J){try{let X=await xX.updateTable("waitlist_products").set({quantity:J,updated_at:HX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update party size");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update party size: ${X.message}`);throw X}}var KJ={};Q(KJ,{updateWaitTimes:()=>E9,updateStatus:()=>A9,updateQueuePosition:()=>O9,updatePartySize:()=>z9,update:()=>B9,store:()=>Q9,fetchWaitingWithQuotedTimes:()=>$9,fetchWaitingWithPartySizes:()=>K9,fetchWaiting:()=>J9,fetchTimeSeriesStats:()=>N9,fetchTablesTurnedToday:()=>L9,fetchSeatingRate:()=>Y9,fetchSeatedStats:()=>M9,fetchSeatedBetweenDates:()=>e1,fetchNoShowStats:()=>W9,fetchCurrentWaitTimes:()=>Z9,fetchCountByTablePreference:()=>s1,fetchCountByPartySize:()=>a1,fetchCountByDate:()=>d1,fetchCountByAllPartySizes:()=>t1,fetchConversionRates:()=>G9,fetchById:()=>o1,fetchBetweenDates:()=>r1,fetchAverageWaitTimes:()=>X9,fetchAll:()=>i1,destroy:()=>u1,bulkStore:()=>V9,bulkDestroy:()=>n1});import{db as xG}from"@stacksjs/database";async function u1(G){try{let J=await xG.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst();if(!J)return;return await xG.deleteFrom("waitlist_restaurants").where("id","=",G).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${J.message}`);throw J}}async function n1(G){if(!G.length)return 0;try{return(await xG.deleteFrom("waitlist_restaurants").where("id","in",G).execute()).length||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as z}from"@stacksjs/database";import{formatDate as k}from"@stacksjs/orm";async function o1(G){return await z.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst()}async function i1(){return await z.selectFrom("waitlist_restaurants").selectAll().execute()}async function s1(){return(await z.selectFrom("waitlist_restaurants").select(["table_preference",(J)=>J.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((J,{table_preference:X,count:$})=>{return J[X]=$,J},{})}async function d1(G=new Date){let J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=k(J),K=k(X);return(await z.selectFrom("waitlist_restaurants").select((Y)=>Y.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function a1(G){return(await z.selectFrom("waitlist_restaurants").select((X)=>X.fn.count("id").as("count")).where("party_size","=",G).executeTakeFirst())?.count??0}async function t1(){return(await z.selectFrom("waitlist_restaurants").select(["party_size",(J)=>J.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((J,{party_size:X,count:$})=>{return J[X]=$,J},{})}async function r1(G,J){let X=k(G),$=k(J);return await z.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",X).where("created_at","<=",$).execute()}async function e1(G,J){let X=k(G),$=k(J);return await z.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",X).where("check_in_time","<=",$).where("status","=","seated").execute()}async function J9(){return await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function G9(){let G=await z.selectFrom("waitlist_restaurants").select(["status",(L)=>L.fn.count("id").as("count")]).groupBy("status").execute(),J=G.reduce((L,{count:Y})=>L+Y,0),X=G.find((L)=>L.status==="seated")?.count??0,$=J>0?Number(X)/J*100:0,K=G.reduce((L,{status:Y,count:W})=>{return L[Y]={count:W,percentage:J>0?W/J*100:0},L},{});return{totalConversionRate:$,statusBreakdown:K}}async function X9(){let G=await z.selectFrom("waitlist_restaurants").select([(J)=>J.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),(J)=>J.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:G?.avg_quoted_wait_time??0,averageActualWaitTime:G?.avg_actual_wait_time??0}}async function $9(){let G=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=G.reduce(($,K)=>$+(K.quoted_wait_time??0),0),X=G.length>0?J/G.length:0;return{entries:G,totalQuotedWaitTime:J,averageQuotedWaitTime:X}}async function K9(){let G=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=G.reduce((K,L)=>K+L.party_size,0),X=G.length>0?J/G.length:0,$=G.reduce((K,L)=>{return K[L.party_size]=(K[L.party_size]||0)+1,K},{});return{entries:G,totalPartySize:J,averagePartySize:X,partySizeBreakdown:$}}async function L9(){let G=new Date,J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=k(J),K=k(X),L=await z.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",$).where("check_in_time","<=",K).execute(),Y=L.length,W=L.reduce((x,H)=>x+H.party_size,0),M=Y>0?W/Y:0,Z=L.reduce((x,H)=>{return x[H.table_preference]=(x[H.table_preference]||0)+1,x},{}),N=L.reduce((x,H)=>{return x[H.party_size]=(x[H.party_size]||0)+1,x},{});return{totalTablesTurned:Y,averagePartySize:M,totalCustomersSeated:W,breakdownByTablePreference:Z,breakdownByPartySize:N}}async function Y9(G,J){let X=k(G),$=k(J),K=await z.selectFrom("waitlist_restaurants").select(["status",(Z)=>Z.fn.count("id").as("count")]).where("check_in_time",">=",X).where("check_in_time","<=",$).groupBy("status").execute(),L=K.reduce((Z,{count:N})=>Z+N,0),Y=K.find((Z)=>Z.status==="seated")?.count??0,W=L>0?Number(Y)/L*100:0,M=K.reduce((Z,{status:N,count:x})=>{return Z[N]={count:x,percentage:L>0?x/L*100:0},Z},{});return{totalEntries:L,seatedEntries:Y,seatingRate:W,statusBreakdown:M}}async function W9(G,J){let X=k(G),$=k(J),K=z.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",X).where("check_in_time","<=",$),L=await z.selectFrom("waitlist_restaurants").select((F)=>F.fn.count("id").as("count")).where("check_in_time",">=",X).where("check_in_time","<=",$).executeTakeFirst(),Y=await K.execute(),W=Y.length,M=L?.count&&L.count>0?W/L.count*100:0,Z=Y.reduce((F,A)=>F+(A.quoted_wait_time??0),0),N=W>0?Z/W:0,x=Y.reduce((F,A)=>F+A.party_size,0),H=W>0?x/W:0,E=Y.reduce((F,A)=>{return F[A.table_preference]=(F[A.table_preference]||0)+1,F},{}),B=Y.reduce((F,A)=>{return F[A.party_size]=(F[A.party_size]||0)+1,F},{});return{totalNoShows:W,noShowRate:M,averageQuotedWaitTime:N,averagePartySize:H,breakdownByTablePreference:E,breakdownByPartySize:B}}async function Z9(){let G=await z.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),J=G.reduce((K,L)=>K+(L.quoted_wait_time||0),0),X=G.reduce((K,L)=>K+(L.actual_wait_time||0),0),$=G.length;return{averageQuoted:$>0?J/$:0,averageActual:$>0?X/$:0}}async function M9(){let G=Date.now()-86400000,J=await z.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",G).execute(),X=Array.from({length:24},($,K)=>({hour:K,count:J.filter((L)=>{return L.seated_at===K}).length}));return{total:J.length,byHour:X}}async function N9(){return(await z.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((J,X)=>{let $=X.created_at;if(!J[$])J[$]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return J[$].total++,J[$][X.status]++,J},{})}var{randomUUIDv7:x9}=globalThis.Bun;import{db as H9}from"@stacksjs/database";import{formatDate as F9}from"@stacksjs/orm";async function Q9(G){try{let J=G,X={name:G.name,email:G.email,phone:G.phone,party_size:J.party_size,check_in_time:typeof J.check_in_time==="number"?F9(J.check_in_time):J.check_in_time,table_preference:J.table_preference,status:G.status||"waiting",quoted_wait_time:G.quoted_wait_time,actual_wait_time:G.actual_wait_time,queue_position:G.queue_position,customer_id:G.customer_id,uuid:x9()},$={};for(let[Y,W]of Object.entries(X))if(W!==void 0)$[Y]=W;let K=await H9.insertInto("waitlist_restaurants").values($).returningAll().executeTakeFirst();if(!K)throw Error("Failed to create restaurant waitlist entry");let L={...K};for(let Y of Object.keys(L))if(L[Y]===null)L[Y]=void 0;return L}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${J.message}`);throw J}}async function V9(G){if(!G.length)return 0;try{let J=G.map(($)=>{let K=$;return{name:$.name,email:$.email,phone:$.phone,party_size:K.party_size,check_in_time:typeof K.check_in_time==="number"?F9(K.check_in_time):K.check_in_time,table_preference:K.table_preference,status:$.status||"waiting",quoted_wait_time:$.quoted_wait_time,actual_wait_time:$.actual_wait_time,queue_position:$.queue_position,customer_id:$.customer_id,uuid:x9()}}),X=await H9.insertInto("waitlist_restaurants").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as BJ}from"@stacksjs/database";import{formatDate as AJ}from"@stacksjs/orm";async function B9(G,J){try{if(!G)throw Error("Restaurant waitlist entry ID is required for update");let X=J,$=await BJ.updateTable("waitlist_restaurants").set({name:J.name,email:J.email,phone:J.phone,party_size:X.party_size,check_in_time:X.check_in_time?Math.floor(new Date(X.check_in_time).getTime()/1000):void 0,table_preference:X.table_preference,status:J.status,quoted_wait_time:J.quoted_wait_time,actual_wait_time:J.actual_wait_time,queue_position:J.queue_position,customer_id:J.customer_id,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update restaurant waitlist entry");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${X.message}`);throw X}}async function A9(G,J){try{let X=await BJ.updateTable("waitlist_restaurants").set({status:J,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update restaurant waitlist entry status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry status: ${X.message}`);throw X}}async function z9(G,J){try{let X=await BJ.updateTable("waitlist_restaurants").set({party_size:J,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update party size");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update party size: ${X.message}`);throw X}}async function E9(G,J,X){try{let $=await BJ.updateTable("waitlist_restaurants").set({quoted_wait_time:J,actual_wait_time:X,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update wait times");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update wait times: ${$.message}`);throw $}}async function O9(G,J){try{let X=await BJ.updateTable("waitlist_restaurants").set({queue_position:J,updated_at:AJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update queue position");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update queue position: ${X.message}`);throw X}}var NK={products:NG,restaurant:KJ},xK=NK;var HK={coupons:FG,customers:VG,devices:EG,errors:UG,giftCards:PG,orders:yG,payments:DG,products:oG,receipts:dG,restaurant:KJ,shippings:WX,tax:NX,waitlists:FX},aZ=HK;export{FX as waitlists,NX as tax,WX as shippings,KJ as restaurant,dG as receipts,oG as products,DG as payments,yG as orders,PG as giftCards,UG as errors,EG as devices,aZ as default,VG as customers,FG as coupons,HK as commerce};
|