@stacksjs/commerce 0.70.229 → 0.70.230

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.
Files changed (51) hide show
  1. package/dist/customers/update.d.ts +1 -1
  2. package/dist/devices/index.d.ts +7 -0
  3. package/dist/index.js +14 -3
  4. package/dist/orders/index.d.ts +4 -4
  5. package/dist/orders/place-order.d.ts +10 -1
  6. package/dist/payments/index.d.ts +1 -1
  7. package/dist/payments/update.d.ts +8 -0
  8. package/dist/products/categories/index.d.ts +1 -0
  9. package/dist/products/categories/store.d.ts +2 -2
  10. package/dist/products/categories/types.d.ts +10 -0
  11. package/dist/products/categories/update.d.ts +3 -2
  12. package/dist/products/items/update.d.ts +1 -1
  13. package/dist/products/manufacturers/update.d.ts +1 -1
  14. package/dist/products/reviews/destroy.d.ts +6 -6
  15. package/dist/products/reviews/update.d.ts +1 -1
  16. package/dist/products/units/index.d.ts +1 -0
  17. package/dist/products/units/store.d.ts +3 -3
  18. package/dist/products/units/types.d.ts +9 -0
  19. package/dist/products/units/update.d.ts +2 -1
  20. package/dist/products/variants/update.d.ts +1 -1
  21. package/dist/receipts/index.d.ts +5 -0
  22. package/dist/receipts/timestamp.d.ts +1 -0
  23. package/dist/receipts/update.d.ts +1 -1
  24. package/dist/shippings/delivery-routes/index.d.ts +4 -0
  25. package/dist/shippings/delivery-routes/store.d.ts +6 -1
  26. package/dist/shippings/delivery-routes/update.d.ts +1 -1
  27. package/dist/shippings/delivery-routes/validate-write.d.ts +5 -0
  28. package/dist/shippings/digital-deliveries/update.d.ts +1 -1
  29. package/dist/shippings/drivers/destroy.d.ts +2 -4
  30. package/dist/shippings/drivers/update.d.ts +1 -1
  31. package/dist/shippings/license-keys/index.d.ts +4 -0
  32. package/dist/shippings/license-keys/update.d.ts +1 -1
  33. package/dist/shippings/license-keys/validate-write.d.ts +5 -0
  34. package/dist/shippings/shipping-methods/update.d.ts +1 -1
  35. package/dist/shippings/shipping-rates/destroy.d.ts +2 -2
  36. package/dist/shippings/shipping-rates/index.d.ts +4 -0
  37. package/dist/shippings/shipping-rates/update.d.ts +2 -2
  38. package/dist/shippings/shipping-rates/validate-write.d.ts +5 -0
  39. package/dist/shippings/shipping-zones/update.d.ts +1 -1
  40. package/dist/shippings/write-data.d.ts +9 -0
  41. package/dist/tax/index.d.ts +2 -0
  42. package/dist/tax/store.d.ts +3 -3
  43. package/dist/tax/types.d.ts +10 -0
  44. package/dist/tax/update.d.ts +10 -2
  45. package/dist/utils/inventory-adjustment.d.ts +13 -0
  46. package/dist/utils/mutation-count.d.ts +1 -0
  47. package/dist/waitlists/products/update.d.ts +3 -3
  48. package/dist/waitlists/products/write-data.d.ts +1 -0
  49. package/dist/waitlists/restaurant/update.d.ts +5 -5
  50. package/dist/waitlists/restaurant/write-data.d.ts +1 -0
  51. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- var R9=Object.defineProperty;var U9=(G)=>G;function T9(G,J){this[G]=U9.bind(null,J)}var B=(G,J)=>{for(var X in J)R9(G,X,{get:J[X],enumerable:!0,configurable:!0,set:T9.bind(J,X)})};var NX=import.meta.require;var NG={};B(NG,{update:()=>fX,store:()=>wX,redeem:()=>vX,getActiveCouponsMoMChange:()=>qX,fetchTopRedeemedCoupons:()=>TX,fetchStats:()=>EX,fetchRedemptionTrend:()=>SX,fetchRedemptionStats:()=>UX,fetchCouponCountsByType:()=>RX,fetchCouponCounts:()=>OX,fetchConversionRate:()=>PX,fetchById:()=>l,fetchByCode:()=>AX,fetchAll:()=>BX,fetchActive:()=>zX,deleteExpiredCoupons:()=>FX,deleteCoupons:()=>HX,deleteCoupon:()=>xX});import{db as KJ}from"@stacksjs/database";import{formatDate as S9}from"@stacksjs/orm";async function xX(G){return!!await KJ.deleteFrom("coupons").where("id","=",G).executeTakeFirst()}async function HX(G){if(!G.length)return 0;return(await KJ.deleteFrom("coupons").where("id","in",G).execute()).length||0}async function FX(){let G=S9(new Date),J=await KJ.deleteFrom("coupons").where("end_date","<",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}import{db as H}from"@stacksjs/database";import{extractDate as QX,formatDate as VX}from"@stacksjs/orm";import{camelCase as P9}from"@stacksjs/strings";function zJ(G){let J=Object.fromEntries(Object.entries(G).map(([X,$])=>[P9(X),$]));if(J.endDate)J.endDate=QX(new Date(J.endDate));if(J.startDate)J.startDate=QX(new Date(J.startDate));if(J.isActive!==void 0)J.isActive=Boolean(J.isActive);return J}async function BX(){return(await H.selectFrom("coupons").selectAll().execute()).map(zJ)}async function l(G){let J=await H.selectFrom("coupons").where("id","=",G).selectAll().executeTakeFirst();if(J)return zJ(J);return}async function AX(G){let J=await H.selectFrom("coupons").where("code","=",G).selectAll().executeTakeFirst();if(J)return zJ(J);return}async function zX(){let G=VX(new Date);return(await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).selectAll().execute()).map(zJ)}async function EX(){let G=await H.selectFrom("coupons").select(H.fn.count("id").as("count")).executeTakeFirst(),J=VX(new Date),X=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J).select(H.fn.count("id").as("count")).executeTakeFirst(),$=await H.selectFrom("coupons").select(["discount_type",H.fn.count("id").as("count")]).groupBy("discount_type").execute(),K=await H.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),L=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",J).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(G?.count||0),active:Number(X?.count||0),by_type:$,most_used:K,upcoming:L}}async function OX(){let G=new Date,J=new Date(G);J.setDate(G.getDate()-7);let X=new Date(G);X.setMonth(G.getMonth()-1);let $=new Date(G);$.setFullYear(G.getFullYear()-1);let K=await AJ(null,null,G),L=await AJ(J,null,G),Y=await AJ(X,null,G),W=await AJ($,null,G);return{week:L,month:Y,year:W,all_time:K}}async function AJ(G,J,X){let $=H.selectFrom("coupons");if(G)$=$.where("created_at",">=",G.toISOString());if(J)$=$.where("created_at","<=",J.toISOString());let K=await $.select(H.fn.count("id").as("count")).executeTakeFirst(),L=H.selectFrom("coupons");if(G)L=L.where("created_at",">=",G.toISOString());if(J)L=L.where("created_at","<=",J.toISOString());L=L.where("is_active","=",!0).where("start_date","<=",X).where("end_date",">=",X);let Y=await L.select(H.fn.count("id").as("count")).executeTakeFirst(),W=Number(K?.count||0),M=Number(Y?.count||0),Z=W-M;return{total:W,active:M,inactive:Z}}async function RX(){let G=new Date,J=await H.selectFrom("coupons").select("discount_type").distinct().execute(),X={};for(let{discount_type:$}of J){let K=await H.selectFrom("coupons").where("discount_type","=",$).select(H.fn.count("id").as("count")).executeTakeFirst(),L=await H.selectFrom("coupons").where("discount_type","=",$).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select(H.fn.count("id").as("count")).executeTakeFirst(),Y=Number(K?.count||0),W=Number(L?.count||0);X[$]={total:Y,active:W,inactive:Y-W}}return X}async function UX(){let G=await H.selectFrom("coupons").select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),J=new Date,X=new Date(J);X.setDate(J.getDate()-7);let $=new Date(J);$.setMonth(J.getMonth()-1);let K=new Date(J);K.setFullYear(J.getFullYear()-1);let L=await H.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await H.selectFrom("coupons").where("updated_at",">=",$.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await H.selectFrom("coupons").where("updated_at",">=",K.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),M=await H.selectFrom("coupons").select(["discount_type",H.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),Z={};return M.forEach((N)=>{Z[N.discount_type]=Number(N.total||0)}),{total:Number(G?.total||0),week:Number(L?.total||0),month:Number(Y?.total||0),year:Number(W?.total||0),by_type:Z}}async function TX(G=5){return await H.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(G).execute()}async function SX(G=30){let J=new Date().toISOString(),X=new Date;X.setDate(X.getDate()-G);let $=await H.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",X.toISOString()).where("updated_at","<=",J).where("usage_count",">",0).orderBy("updated_at","desc").execute(),K={};return $.forEach((L)=>{let Y=L.updated_at?new Date(L.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!K[Y])K[Y]=0;K[Y]+=L?.usage_count||0}),Object.entries(K).map(([L,Y])=>({date:L,count:Y}))}async function PX(){let G=new Date,J=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",G).select(H.fn.count("id").as("count")).executeTakeFirst(),X=await H.selectFrom("coupons").where("usage_count",">",0).select(H.fn.count("id").as("count")).executeTakeFirst(),$=Number(J?.count||0),K=Number(X?.count||0);return{rate:$>0?K/$*100:0,total_active:$,total_redeemed:K}}async function qX(){let G=new Date,J=new Date(G.getFullYear(),G.getMonth(),1),X=new Date(G.getFullYear(),G.getMonth()-1,1),$=new Date(G.getFullYear(),G.getMonth(),0),K=await H.selectFrom("coupons").select(H.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",J).executeTakeFirst(),L=await H.selectFrom("coupons").select(H.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",X).executeTakeFirst(),Y=Number(K?.count||0),W=Number(L?.count||0),M=Y-W,Z=W!==0?M/W*100:Y>0?100:0;return{current_month:Y,previous_month:W,difference:M,percentage_change:Z}}import{db as jX}from"@stacksjs/database";import{HttpError as kX}from"@stacksjs/error-handling";import{isUniqueViolation as q9}from"@stacksjs/orm";async function wX(G){try{let J=await jX.insertInto("coupons").values(G).executeTakeFirst(),X=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows);if(X)return await jX.selectFrom("coupons").where("id","=",X).selectAll().executeTakeFirst();return}catch(J){if(J instanceof kX)throw J;if(q9(J))throw new kX(409,"A coupon with this code already exists");if(J instanceof Error)throw Error(`Failed to create coupon: ${J.message}`);throw J}}import{db as _X}from"@stacksjs/database";import{HttpError as CX}from"@stacksjs/error-handling";import{formatDate as IX,isUniqueViolation as j9}from"@stacksjs/orm";async function fX(G,J){if(!await l(G))throw Error(`Coupon with ID ${G} not found`);try{return await _X.updateTable("coupons").set({...J,updated_at:IX(new Date)}).where("id","=",G).execute(),await l(G)}catch($){if($ instanceof CX)throw $;if(j9($))throw new CX(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to update coupon: ${$.message}`);throw $}}async function vX(G){let J=IX(new Date),X=await _X.unsafe(`UPDATE coupons
2
+ var x3=Object.defineProperty;var H3=(N)=>N;function V3(N,$){this[N]=H3.bind(null,$)}var B=(N,$)=>{for(var J in $)x3(N,J,{get:$[J],enumerable:!0,configurable:!0,set:V3.bind($,J)})};var o1=import.meta.require;var p$={};B(p$,{update:()=>z4,store:()=>Q4,redeem:()=>B4,getActiveCouponsMoMChange:()=>M4,fetchTopRedeemedCoupons:()=>W4,fetchStats:()=>J4,fetchRedemptionTrend:()=>Y4,fetchRedemptionStats:()=>L4,fetchCouponCountsByType:()=>X4,fetchCouponCounts:()=>G4,fetchConversionRate:()=>Z4,fetchById:()=>d,fetchByCode:()=>$4,fetchAll:()=>r1,fetchActive:()=>N4,deleteExpiredCoupons:()=>a1,deleteCoupons:()=>d1,deleteCoupon:()=>s1});import{db as v0}from"@stacksjs/database";import{formatDate as z3}from"@stacksjs/orm";function F(N){if(typeof N==="number")return Number.isFinite(N)?N:0;if(typeof N==="bigint")return Number(N);if(!N||typeof N!=="object")return 0;let $=N;for(let J of["changes","affectedRows","count","numAffectedRows","numDeletedRows","numInsertedOrUpdatedRows","numUpdatedRows"])if($[J]!==void 0&&$[J]!==null)return F($[J]);if(Array.isArray(N))return N.reduce((J,G)=>J+F(G),0);return 0}async function s1(N){let $=await v0.deleteFrom("coupons").where("id","=",N).executeTakeFirst();return F($)>0}async function d1(N){if(!N.length)return 0;return(await v0.deleteFrom("coupons").where("id","in",N).execute()).length||0}async function a1(){let N=z3(new Date),$=await v0.deleteFrom("coupons").where("end_date","<",N).executeTakeFirst();return F($)}import{db as H}from"@stacksjs/database";import{extractDate as e1,formatDate as t1}from"@stacksjs/orm";import{camelCase as B3}from"@stacksjs/strings";function D0(N){let $=Object.fromEntries(Object.entries(N).map(([J,G])=>[B3(J),G]));if($.endDate)$.endDate=e1(new Date($.endDate));if($.startDate)$.startDate=e1(new Date($.startDate));if($.isActive!==void 0)$.isActive=Boolean($.isActive);return $}async function r1(){return(await H.selectFrom("coupons").selectAll().execute()).map(D0)}async function d(N){let $=await H.selectFrom("coupons").where("id","=",N).selectAll().executeTakeFirst();if($)return D0($);return}async function $4(N){let $=await H.selectFrom("coupons").where("code","=",N).selectAll().executeTakeFirst();if($)return D0($);return}async function N4(){let N=t1(new Date);return(await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",N).selectAll().execute()).map(D0)}async function J4(){let N=await H.selectFrom("coupons").select(H.fn.count("id").as("count")).executeTakeFirst(),$=t1(new Date),J=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",$).where("end_date",">=",$).select(H.fn.count("id").as("count")).executeTakeFirst(),G=await H.selectFrom("coupons").select(["discount_type",H.fn.count("id").as("count")]).groupBy("discount_type").execute(),X=await H.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count"]).orderBy("usage_count","desc").limit(5).execute(),L=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date",">",$).select(["id","code","discount_type","discount_value","start_date","end_date"]).orderBy("start_date","asc").limit(5).execute();return{total:Number(N?.count||0),active:Number(J?.count||0),by_type:G,most_used:X,upcoming:L}}async function G4(){let N=new Date,$=new Date(N);$.setDate(N.getDate()-7);let J=new Date(N);J.setMonth(N.getMonth()-1);let G=new Date(N);G.setFullYear(N.getFullYear()-1);let X=await y0(null,null,N),L=await y0($,null,N),W=await y0(J,null,N),Y=await y0(G,null,N);return{week:L,month:W,year:Y,all_time:X}}async function y0(N,$,J){let G=H.selectFrom("coupons");if(N)G=G.where("created_at",">=",N.toISOString());if($)G=G.where("created_at","<=",$.toISOString());let X=await G.select(H.fn.count("id").as("count")).executeTakeFirst(),L=H.selectFrom("coupons");if(N)L=L.where("created_at",">=",N.toISOString());if($)L=L.where("created_at","<=",$.toISOString());L=L.where("is_active","=",!0).where("start_date","<=",J).where("end_date",">=",J);let W=await L.select(H.fn.count("id").as("count")).executeTakeFirst(),Y=Number(X?.count||0),Z=Number(W?.count||0),M=Y-Z;return{total:Y,active:Z,inactive:M}}async function X4(){let N=new Date,$=await H.selectFrom("coupons").select("discount_type").distinct().execute(),J={};for(let{discount_type:G}of $){let X=await H.selectFrom("coupons").where("discount_type","=",G).select(H.fn.count("id").as("count")).executeTakeFirst(),L=await H.selectFrom("coupons").where("discount_type","=",G).where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",N).select(H.fn.count("id").as("count")).executeTakeFirst(),W=Number(X?.count||0),Y=Number(L?.count||0);J[G]={total:W,active:Y,inactive:W-Y}}return J}async function L4(){let N=await H.selectFrom("coupons").select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),$=new Date,J=new Date($);J.setDate($.getDate()-7);let G=new Date($);G.setMonth($.getMonth()-1);let X=new Date($);X.setFullYear($.getFullYear()-1);let L=await H.selectFrom("coupons").where("updated_at",">=",J.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),W=await H.selectFrom("coupons").where("updated_at",">=",G.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),Y=await H.selectFrom("coupons").where("updated_at",">=",X.toISOString()).select(H.fn.sum("usage_count").as("total")).executeTakeFirst(),Z=await H.selectFrom("coupons").select(["discount_type",H.fn.sum("usage_count").as("total")]).groupBy("discount_type").execute(),M={};return Z.forEach((K)=>{M[K.discount_type]=Number(K.total||0)}),{total:Number(N?.total||0),week:Number(L?.total||0),month:Number(W?.total||0),year:Number(Y?.total||0),by_type:M}}async function W4(N=5){return await H.selectFrom("coupons").select(["id","code","discount_type","discount_value","usage_count","start_date","end_date"]).where("usage_count",">",0).orderBy("usage_count","desc").limit(N).execute()}async function Y4(N=30){let $=new Date().toISOString(),J=new Date;J.setDate(J.getDate()-N);let G=await H.selectFrom("coupons").select(["id","code","updated_at","usage_count"]).where("updated_at",">=",J.toISOString()).where("updated_at","<=",$).where("usage_count",">",0).orderBy("updated_at","desc").execute(),X={};return G.forEach((L)=>{let W=L.updated_at?new Date(L.updated_at).toISOString().split("T")[0]??"unknown-date":"unknown-date";if(!X[W])X[W]=0;X[W]+=L?.usage_count||0}),Object.entries(X).map(([L,W])=>({date:L,count:W}))}async function Z4(){let N=new Date,$=await H.selectFrom("coupons").where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",N).select(H.fn.count("id").as("count")).executeTakeFirst(),J=await H.selectFrom("coupons").where("usage_count",">",0).select(H.fn.count("id").as("count")).executeTakeFirst(),G=Number($?.count||0),X=Number(J?.count||0);return{rate:G>0?X/G*100:0,total_active:G,total_redeemed:X}}async function M4(){let N=new Date,$=new Date(N.getFullYear(),N.getMonth(),1),J=new Date(N.getFullYear(),N.getMonth()-1,1),G=new Date(N.getFullYear(),N.getMonth(),0),X=await H.selectFrom("coupons").select(H.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",N).where("end_date",">=",$).executeTakeFirst(),L=await H.selectFrom("coupons").select(H.fn.count("id").as("count")).where("is_active","=",!0).where("start_date","<=",G).where("end_date",">=",J).executeTakeFirst(),W=Number(X?.count||0),Y=Number(L?.count||0),Z=W-Y,M=Y!==0?Z/Y*100:W>0?100:0;return{current_month:W,previous_month:Y,difference:Z,percentage_change:M}}var{randomUUIDv7:A3}=globalThis.Bun;import{db as F4}from"@stacksjs/database";import{HttpError as K4}from"@stacksjs/error-handling";import{isUniqueViolation as R3}from"@stacksjs/orm";async function Q4(N){try{let $=A3();return await F4.insertInto("coupons").values({...N,uuid:$}).executeTakeFirst(),await F4.selectFrom("coupons").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof K4)throw $;if(R3($))throw new K4(409,"A coupon with this code already exists");if($ instanceof Error)throw Error(`Failed to create coupon: ${$.message}`);throw $}}import{db as H4}from"@stacksjs/database";import{HttpError as x4}from"@stacksjs/error-handling";import{formatDate as V4,isUniqueViolation as _3}from"@stacksjs/orm";async function z4(N,$){if(!await d(N))return;try{return await H4.updateTable("coupons").set({...$,updated_at:V4(new Date)}).where("id","=",N).execute(),await d(N)}catch(G){if(G instanceof x4)throw G;if(_3(G))throw new x4(409,"A coupon with this code already exists");if(G instanceof Error)throw Error(`Failed to update coupon: ${G.message}`);throw G}}async function B4(N){let $=V4(new Date),J=await H4.unsafe(`UPDATE coupons
3
3
  SET usage_count = COALESCE(usage_count, 0) + 1, updated_at = ?
4
4
  WHERE id = ?
5
5
  AND (max_uses IS NULL OR usage_count < max_uses)
6
6
  AND is_active = 1
7
7
  AND (start_date IS NULL OR start_date <= ?)
8
- AND (end_date IS NULL OR end_date >= ?)`,[J,G,J,J]),$=typeof X?.execute==="function"?await X.execute():X;if(Number($?.changes??$?.numUpdatedRows??$?.affectedRows??0)>0){let M=await l(G);if(M)return{ok:!0,coupon:M};return{ok:!1,reason:"not-found"}}let L=await l(G);if(!L)return{ok:!1,reason:"not-found"};if(!L.isActive)return{ok:!1,reason:"inactive"};let Y=!L.startDate||L.startDate<=J,W=!L.endDate||L.endDate>=J;if(!Y||!W)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var HG={};B(HG,{update:()=>lX,store:()=>bX,fetchById:()=>a,fetchAll:()=>gX,destroy:()=>yX,bulkDestroy:()=>DX});import{db as xG}from"@stacksjs/database";import{db as hX}from"@stacksjs/database";async function a(G){return await hX.selectFrom("customers").where("id","=",G).selectAll().executeTakeFirst()}async function gX(){return await hX.selectFrom("customers").selectAll().execute()}async function yX(G){try{if(!await a(G))throw Error(`Customer with ID ${G} not found`);return(await xG.deleteFrom("customers").where("id","=",G).executeTakeFirst()).numDeletedRows>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customer: ${J.message}`);throw J}}async function DX(G){if(!G.length)return 0;try{let J=await xG.deleteFrom("customers").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${J.message}`);throw J}}import{db as k9}from"@stacksjs/database";import{HttpError as pX}from"@stacksjs/error-handling";import{isUniqueViolation as w9}from"@stacksjs/orm";async function bX(G){try{let J={...G,avatar:G.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},X=await k9.insertInto("customers").values(J).executeTakeFirst();if(!X)throw Error("Failed to create customer");let $=X.insertId||Number(X.numInsertedOrUpdatedRows);return await a(Number($))}catch(J){if(J instanceof pX)throw J;if(w9(J))throw new pX(409,"A customer with this email already exists");if(J instanceof Error)throw Error(`Failed to create customer: ${J.message}`);throw J}}import{db as C9}from"@stacksjs/database";import{HttpError as mX}from"@stacksjs/error-handling";import{formatDate as _9,isUniqueViolation as I9}from"@stacksjs/orm";async function lX(G,J){try{if(!G)throw Error("Customer ID is required for update");let X=await C9.updateTable("customers").set({...J,updated_at:_9(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update customer");return X}catch(X){if(X instanceof mX)throw X;if(I9(X))throw new mX(409,"A customer with this email already exists");if(X instanceof Error)throw Error(`Failed to update customer: ${X.message}`);throw X}}var BG={};B(BG,{updateStatus:()=>eX,updatePrintCount:()=>J6,update:()=>rX,storePrintDevicesExport:()=>sX,store:()=>aX,fetchById:()=>f,fetchAll:()=>EJ,exportPrintDevices:()=>OJ,downloadPrintDevices:()=>iX,destroy:()=>uX,bulkStore:()=>tX,bulkDestroy:()=>nX});import{db as cX}from"@stacksjs/database";async function uX(G){try{let J=await cX.deleteFrom("print_devices").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print device: ${J.message}`);throw J}}async function nX(G){if(!G.length)return 0;try{let J=await cX.deleteFrom("print_devices").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print devices: ${J.message}`);throw J}}import{createSpreadsheet as f9}from"ts-spreadsheets";import{db as oX}from"@stacksjs/database";async function f(G){return await oX.selectFrom("print_devices").where("id","=",G).selectAll().executeTakeFirst()}async function EJ(){return await oX.selectFrom("print_devices").selectAll().execute()}async function OJ(G="csv"){let J=await EJ(),X=v9(J);return f9(X,{type:G})}function v9(G){let J=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],X=G.map(($)=>{return[$.id,$.name,$.macAddress,$.location,$.terminal,$.status,new Date($.lastPing).toLocaleString(),$.printCount]});return{headings:J,data:X}}async function iX(G="csv",J){let X=await OJ(G),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;return X.download(J||$)}async function sX(G="csv",J){let X=await OJ(G),$=`print_devices_export_${new Date().toISOString().split("T")[0]}.${G}`;X.store(J||$)}var{randomUUIDv7:dX}=globalThis.Bun;import{db as FG}from"@stacksjs/database";async function aX(G){try{let J={...G,uuid:dX()},X=await FG.insertInto("print_devices").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await FG.selectFrom("print_devices").where("id","=",$).selectAll().executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print device: ${J.message}`);throw J}}async function tX(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:dX()};await FG.insertInto("print_devices").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${X.message}`);throw X}}import{db as QG}from"@stacksjs/database";import{formatDate as VG}from"@stacksjs/orm";async function rX(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await QG.updateTable("print_devices").set({...J,updated_at:VG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device: ${$.message}`);throw $}}async function eX(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await QG.updateTable("print_devices").set({status:J,updated_at:VG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print device status: ${$.message}`);throw $}}async function J6(G,J){if(!await f(G))throw Error(`Print device with ID ${G} not found`);try{return await QG.updateTable("print_devices").set({print_count:J,updated_at:VG(new Date)}).where("id","=",G).execute(),await f(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update print count: ${$.message}`);throw $}}var EG={};B(EG,{update:()=>M6,unresolveGroup:()=>F6,resolveGroup:()=>x6,ignoreGroup:()=>H6,fetchTimeline:()=>Z6,fetchStats:()=>W6,fetchGrouped:()=>L6,fetchById:()=>K6,fetchByGroup:()=>Y6,fetchAll:()=>UJ,destroyGroup:()=>$6,destroy:()=>G6,bulkUpdateStatus:()=>N6,bulkDestroy:()=>X6});import{db as AG}from"@stacksjs/database";import{log as zG}from"@stacksjs/logging";async function G6(G){try{return await AG.deleteFrom("errors").where("id","=",G).execute(),!0}catch(J){return zG.error("[commerce/errors] destroy failed",{id:G,error:J}),!1}}async function X6(G){try{return await AG.deleteFrom("errors").where("id","in",G).execute(),!0}catch(J){return zG.error("[commerce/errors] bulkDestroy failed",{count:G.length,error:J}),!1}}async function $6(G,J){try{return await AG.deleteFrom("errors").where("type","=",G).where("message","=",J).execute(),!0}catch(X){return zG.error("[commerce/errors] destroyGroup failed",{type:G,message:J,error:X}),!1}}import{db as RJ}from"@stacksjs/database";async function K6(G){return await RJ.selectFrom("errors").where("id","=",G).selectAll().executeTakeFirst()}async function UJ(){return await RJ.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function L6(){let G=await RJ.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),J=new Map;for(let $ of G){let K=`${$.type}:${$.message}`;if(!J.has(K))J.set(K,{errors:[],firstSeen:new Date($.created_at),lastSeen:new Date($.created_at)});let L=J.get(K);L.errors.push($);let Y=new Date($.created_at);if(Y<L.firstSeen)L.firstSeen=Y;if(Y>L.lastSeen)L.lastSeen=Y}let X=[];for(let[$,K]of J){let L=K.errors[0];if(!L)continue;let Y=K.errors.find((M)=>M.status!==null)?.status,W="unresolved";if(Y===1)W="resolved";else if(Y===2)W="ignored";X.push({id:L.id,type:L.type,message:L.message,stack:L.stack,status:W,count:K.errors.length,first_seen:K.firstSeen.toISOString(),last_seen:K.lastSeen.toISOString(),error_ids:K.errors.map((M)=>M.id)})}return X.sort(($,K)=>new Date(K.last_seen).getTime()-new Date($.last_seen).getTime()),X}async function Y6(G,J){return await RJ.selectFrom("errors").where("type","=",G).where("message","=",J).selectAll().orderBy("created_at","desc").execute()}async function W6(){let G=await UJ(),J=new Date,X=new Date(J.getTime()-86400000),$=new Date(J.getTime()-172800000),K=G.filter((W)=>new Date(W.created_at)>=X).length,L=G.filter((W)=>{let M=new Date(W.created_at);return M>=$&&M<X}).length,Y=L===0?K>0?100:0:Math.round((K-L)/L*100);return{total:G.length,unresolved:G.filter((W)=>W.status===null||W.status===0).length,resolved:G.filter((W)=>W.status===1).length,ignored:G.filter((W)=>W.status===2).length,last_24h:K,trend:Y}}async function Z6(){let G=await UJ(),J=new Date,X=[];for(let $=23;$>=0;$--){let K=new Date(J.getTime()-$*60*60*1000);K.setMinutes(0,0,0);let L=new Date(K.getTime()+3600000),Y=G.filter((W)=>{let M=new Date(W.created_at);return M>=K&&M<L}).length;X.push({hour:K.toISOString(),count:Y})}return X}import{db as LJ}from"@stacksjs/database";import{sql as YJ}from"@stacksjs/database";import{log as WJ}from"@stacksjs/logging";async function M6(G,J){try{return await LJ.updateTable("errors").set({...J,updated_at:YJ.raw("CURRENT_TIMESTAMP")}).where("id","=",G).execute(),!0}catch(X){return WJ.error("[commerce/errors] update failed",{id:G,error:X}),!1}}async function N6(G,J){try{return await LJ.updateTable("errors").set({status:J,updated_at:YJ.raw("CURRENT_TIMESTAMP")}).where("id","in",G).execute(),!0}catch(X){return WJ.error("[commerce/errors] bulkUpdateStatus failed",{count:G.length,status:J,error:X}),!1}}async function x6(G,J){try{return await LJ.updateTable("errors").set({status:1,updated_at:YJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return WJ.error("[commerce/errors] resolveGroup failed",{type:G,message:J,error:X}),!1}}async function H6(G,J){try{return await LJ.updateTable("errors").set({status:2,updated_at:YJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return WJ.error("[commerce/errors] ignoreGroup failed",{type:G,message:J,error:X}),!1}}async function F6(G,J){try{return await LJ.updateTable("errors").set({status:0,updated_at:YJ.raw("CURRENT_TIMESTAMP")}).where("type","=",G).where("message","=",J).execute(),!0}catch(X){return WJ.error("[commerce/errors] unresolveGroup failed",{type:G,message:J,error:X}),!1}}var UG={};B(UG,{updateBalance:()=>_6,update:()=>C6,store:()=>q6,fetchTotalValue:()=>O6,fetchTotalCurrentBalance:()=>R6,fetchStats:()=>B6,fetchById:()=>v,fetchByCode:()=>OG,fetchAll:()=>Q6,fetchActive:()=>V6,destroy:()=>U6,compareActiveGiftCards:()=>z6,checkBalance:()=>A6,calculateGiftCardValues:()=>E6,bulkDestroy:()=>T6});import{db as RG}from"@stacksjs/database";import{formatDate as bL}from"@stacksjs/orm";import{db as R,sql as j}from"@stacksjs/database";import{formatDate as D,toTimestamp as t}from"@stacksjs/orm";import{aggregateFunctions as h9,db as g9}from"@stacksjs/database";async function c(G,J,X){let $=g9.selectFrom(G);if(X)$=X($);$=$.select(Object.entries(J).map(([Y,W])=>{let M=W.column??"id",Z=h9[W.kind](M);if(W.filter)Z=Z.filterWhere(W.filter.column,W.filter.op,W.filter.value);return Z.as(Y)}));let K=await $.executeTakeFirst(),L={};for(let Y of Object.keys(J)){let W=K?.[Y];L[Y]=typeof W==="number"?W:Number(W??0)||0}return L}async function Q6(){return await R.selectFrom("gift_cards").selectAll().execute()}async function v(G){return await R.selectFrom("gift_cards").where("id","=",G).selectAll().executeTakeFirst()}async function OG(G){return await R.selectFrom("gift_cards").where("code","=",G).selectAll().executeTakeFirst()}async function V6(){return await R.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function B6(){let{count:G}=await c("gift_cards",{count:{kind:"count"}}),J=t(new Date),X=await R.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(J)} OR expiry_date IS NULL)`).select(R.fn.count("id").as("count")).executeTakeFirst(),$=await R.selectFrom("gift_cards").select(["status",R.fn.count("id").as("count")]).groupBy("status").execute(),{count:K}=await c("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(j`current_balance / initial_balance < 0.25`)),{count:L}=await c("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(j`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:Y}=await c("gift_cards",{count:{kind:"count"}},(N)=>N.whereRaw(j`current_balance / initial_balance > 0.75`)),W=new Date;W.setDate(W.getDate()+30);let M=await R.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",t(W)).where("expiry_date",">=",J).selectAll().limit(5).execute(),Z=await R.selectFrom("gift_cards").where("last_used_date","is not",null).selectAll().limit(5).execute();return{total:G,active:Number(X?.count||0),by_status:$.map((N)=>({status:N.status,count:Number(N.count)})),by_balance:{low:K,medium:L,high:Y},expiring_soon:M,recently_used:Z}}async function A6(G){let J=await OG(G);if(!J)return{valid:!1,message:"Gift card not found"};if(!J.isActive||J.status!=="ACTIVE")return{valid:!1,balance:J.currentBalance,currency:J.currency,message:`Gift card is ${J.status.toLowerCase()}`};if(J.expiryDate){if(new Date(J.expiryDate)<new Date)return{valid:!1,balance:J.currentBalance,currency:J.currency,message:"Gift card has expired"}}return{valid:!0,balance:J.currentBalance,currency:J.currency}}async function z6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await R.selectFrom("gift_cards").select(R.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(t(J))} OR expiry_date IS NULL)`).where("created_at",">=",D(X)).where("created_at","<=",D(J)).executeTakeFirst(),Y=await R.selectFrom("gift_cards").select(R.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(t(K))} OR expiry_date IS NULL)`).where("created_at",">=",D(K)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(L?.count||0),M=Number(Y?.count||0),Z=W-M,N=M!==0?Z/M*100:W>0?100:0;return{current_period:W,previous_period:M,difference:Z,percentage_change:N,days_range:G}}async function E6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await R.selectFrom("gift_cards").select([R.fn.sum("initial_balance").as("total_initial"),R.fn.sum("current_balance").as("total_balance"),R.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(t(J))} OR expiry_date IS NULL)`).where("created_at",">=",D(X)).where("created_at","<=",D(J)).executeTakeFirst(),Y=await R.selectFrom("gift_cards").select([R.fn.sum("initial_balance").as("total_initial"),R.fn.sum("current_balance").as("total_balance"),R.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(t(K))} OR expiry_date IS NULL)`).where("created_at",">=",D(K)).where("created_at","<=",D($)).executeTakeFirst(),W=Number(L?.total_initial||0),M=Number(L?.total_balance||0),Z=Number(L?.card_count||0),N=Number(Y?.total_initial||0),x=Number(Y?.total_balance||0),F=Number(Y?.card_count||0),T=W>0?(W-M)/W*100:0,E=N>0?(N-x)/N*100:0,z=Z>0?W/Z:0,O=Z>0?M/Z:0,_=W-N,b=M-x,m=Z-F,d=N!==0?_/N*100:W>0?100:0,I=x!==0?b/x*100:M>0?100:0,O9=F!==0?m/F*100:Z>0?100:0;return{current_period:{total_initial_value:W,total_remaining_balance:M,utilization_rate:T,card_count:Z,average_initial_value:z,average_remaining_balance:O},previous_period:{total_initial_value:N,total_remaining_balance:x,utilization_rate:E,card_count:F},comparison:{initial_value:{difference:_,percentage:Math.abs(d),is_increase:_>=0},balance:{difference:b,percentage:Math.abs(I),is_increase:b>=0},card_count:{difference:m,percentage:Math.abs(O9),is_increase:m>=0}},days_range:G}}async function O6(){let{total_value:G}=await c("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:G}}async function R6(){let{total_balance:G}=await c("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:G}}async function U6(G){if(!await v(G))throw Error(`Gift card with ID ${G} not found`);return!!await RG.deleteFrom("gift_cards").where("id","=",G).executeTakeFirst()}async function T6(G){if(!G.length)return 0;let J=await RG.deleteFrom("gift_cards").where("id","in",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}var{randomUUIDv7:y9}=globalThis.Bun;import{db as S6}from"@stacksjs/database";import{HttpError as P6}from"@stacksjs/error-handling";import{isUniqueViolation as D9}from"@stacksjs/orm";async function q6(G){let J=G,X={...G,current_balance:J.current_balance??J.initial_balance,status:G.status||"ACTIVE",is_active:J.is_active??!0,uuid:y9()};try{let $=await S6.insertInto("gift_cards").values(X).executeTakeFirst(),K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);if(K)return await S6.selectFrom("gift_cards").where("id","=",K).selectAll().executeTakeFirst();return}catch($){if($ instanceof P6)throw $;if(D9($))throw new P6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to create gift card: ${$.message}`);throw $}}import{db as k6}from"@stacksjs/database";import{HttpError as j6}from"@stacksjs/error-handling";import{formatDate as w6,isUniqueViolation as p9}from"@stacksjs/orm";async function C6(G,J){if(!await v(G))throw Error(`Gift card with ID ${G} not found`);try{return await k6.updateTable("gift_cards").set({...J,updated_at:w6(new Date)}).where("id","=",G).execute(),await v(G)}catch($){if($ instanceof j6)throw $;if(p9($))throw new j6(409,"A gift card with this code already exists");if($ instanceof Error)throw Error(`Failed to update gift card: ${$.message}`);throw $}}async function _6(G,J){if(!Number.isFinite(J))throw Error(`Gift card balance adjustment must be a finite number, got ${J}`);let X=w6(new Date),$=await k6.unsafe(`UPDATE gift_cards
8
+ AND (end_date IS NULL OR end_date >= ?)`,[$,N,$,$]),G=typeof J?.execute==="function"?await J.execute():J;if(Number(G?.changes??G?.numUpdatedRows??G?.affectedRows??0)>0){let Z=await d(N);if(Z)return{ok:!0,coupon:Z};return{ok:!1,reason:"not-found"}}let L=await d(N);if(!L)return{ok:!1,reason:"not-found"};if(!L.isActive)return{ok:!1,reason:"inactive"};let W=!L.startDate||L.startDate<=$,Y=!L.endDate||L.endDate>=$;if(!W||!Y)return{ok:!1,reason:"expired"};return{ok:!1,reason:"limit-reached"}}var b$={};B(b$,{update:()=>E4,store:()=>w4,fetchById:()=>p0,fetchAll:()=>S4,destroy:()=>R4,bulkDestroy:()=>_4});import{db as A4}from"@stacksjs/database";async function R4(N){try{let $=await A4.deleteFrom("customers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customer: ${$.message}`);throw $}}async function _4(N){if(!N.length)return 0;try{let $=await A4.deleteFrom("customers").where("id","in",N).executeTakeFirst();return F($)||0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete customers in bulk: ${$.message}`);throw $}}import{db as O4}from"@stacksjs/database";async function p0(N){return await O4.selectFrom("customers").where("id","=",N).selectAll().executeTakeFirst()}async function S4(){return await O4.selectFrom("customers").selectAll().execute()}import{db as O3}from"@stacksjs/database";import{HttpError as T4}from"@stacksjs/error-handling";import{isUniqueViolation as S3}from"@stacksjs/orm";async function w4(N){try{let $={...N,avatar:N.avatar??"https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&fit=crop&q=60"},J=await O3.insertInto("customers").values($).executeTakeFirst();if(!J)throw Error("Failed to create customer");let G=J.insertId||Number(J.numInsertedOrUpdatedRows);return await p0(Number(G))}catch($){if($ instanceof T4)throw $;if(S3($))throw new T4(409,"A customer with this email already exists");if($ instanceof Error)throw Error(`Failed to create customer: ${$.message}`);throw $}}import{db as T3}from"@stacksjs/database";import{HttpError as U4}from"@stacksjs/error-handling";import{formatDate as w3,isUniqueViolation as U3}from"@stacksjs/orm";async function E4(N,$){try{if(!N)throw Error("Customer ID is required for update");let J=await T3.updateTable("customers").set({...$,updated_at:w3(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof U4)throw J;if(U3(J))throw new U4(409,"A customer with this email already exists");if(J instanceof Error)throw Error(`Failed to update customer: ${J.message}`);throw J}}var u$={};B(u$,{updateStatus:()=>c4,updatePrintCount:()=>n4,update:()=>l4,storePrintDevicesExport:()=>D4,store:()=>b4,getPrinterStatusCounts:()=>v4,fetchErrorsByDeviceId:()=>h4,fetchById:()=>b,fetchAll:()=>b0,exportPrintDevices:()=>m0,downloadPrintDevices:()=>y4,destroy:()=>q4,countTotalPrints:()=>j4,countPrintsByDeviceId:()=>C4,countAll:()=>k4,calculatePrinterHealth:()=>g4,calculateErrorRate:()=>I4,bulkStore:()=>m4,bulkDestroy:()=>f4});import{db as P4}from"@stacksjs/database";async function q4(N){try{let $=await P4.deleteFrom("print_devices").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print device: ${$.message}`);throw $}}async function f4(N){if(!N.length)return 0;try{let $=await P4.deleteFrom("print_devices").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print devices: ${$.message}`);throw $}}import{createSpreadsheet as E3}from"ts-spreadsheets";import{db as P}from"@stacksjs/database";async function b(N){return await P.selectFrom("print_devices").where("id","=",N).selectAll().executeTakeFirst()}async function b0(){return await P.selectFrom("print_devices").selectAll().execute()}async function k4(){let N=await P.selectFrom("print_devices").select(P.fn.count("id").as("count")).executeTakeFirst();return Number(N?.count||0)}async function j4(){let N=await P.selectFrom("print_devices").select(P.fn.sum("print_count").as("total")).executeTakeFirst();return Number(N?.total||0)}async function C4(N){return(await P.selectFrom("print_devices").select("print_count").where("id","=",N).executeTakeFirst())?.print_count??0}async function I4(){let N=await P.selectFrom("receipts").select([P.fn.count("id").as("total"),P.fn.count("id").filterWhere("status","=","failed").as("failed_count")]).executeTakeFirst();if(!N?.total||N.total===0)return 0;return Number((N.failed_count??0)/N.total*100)}async function h4(N){return await P.selectFrom("receipts").where("print_device_id","=",N).where("status","=","failed").selectAll().execute()}async function g4(){let N=await P.selectFrom("print_devices").select([P.fn.count("id").as("total"),P.fn.count("id").filterWhere("status","=","online").as("online_count")]).executeTakeFirst();if(!N?.total||N.total===0)return 0;return Number((N.online_count??0)/N.total*100)}async function v4(){return(await P.selectFrom("print_devices").select(["status",P.fn.count("id").as("count")]).groupBy("status").execute()).reduce(($,J)=>{return $[J.status]=Number(J.count||0),$},{})}function m$(N,$,J=$){return N?.[$]??N?.[J]}function P3(N){let $=String(N||""),J=/^\d+$/.test($)?Number($):N;return new Date(J)}async function m0(N="csv"){let $=await b0(),J=q3($);return E3(J,{type:N})}function q3(N){let $=["Device ID","Name","MAC Address","Location","Terminal","Status","Last Ping","Print Count"],J=N.map((G)=>{return[G.id,G.name,m$(G,"macAddress","mac_address"),G.location,G.terminal,G.status,P3(m$(G,"lastPing","last_ping")).toLocaleString(),m$(G,"printCount","print_count")]});return{headings:$,data:J}}async function y4(N="csv",$){let J=await m0(N),G=`print_devices_export_${new Date().toISOString().split("T")[0]}.${N}`;return J.download($||G)}async function D4(N="csv",$){let J=await m0(N),G=`print_devices_export_${new Date().toISOString().split("T")[0]}.${N}`;J.store($||G)}var{randomUUIDv7:p4}=globalThis.Bun;import{db as l$}from"@stacksjs/database";async function b4(N){try{let $=p4(),J={last_ping:0,print_count:0,...N,uuid:$};return await l$.insertInto("print_devices").values(J).executeTakeFirst(),await l$.selectFrom("print_devices").where("uuid","=",$).selectAll().executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to create print device: ${$.message}`);throw $}}async function m4(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={last_ping:0,print_count:0,...J,uuid:p4()};await l$.insertInto("print_devices").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create print devices in bulk: ${J.message}`);throw J}}import{db as c$}from"@stacksjs/database";import{formatDate as n$}from"@stacksjs/orm";async function l4(N,$){if(!await b(N))return;try{return await c$.updateTable("print_devices").set({...$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print device: ${G.message}`);throw G}}async function c4(N,$){if(!await b(N))throw Error(`Print device with ID ${N} not found`);try{return await c$.updateTable("print_devices").set({status:$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print device status: ${G.message}`);throw G}}async function n4(N,$){if(!await b(N))throw Error(`Print device with ID ${N} not found`);try{return await c$.updateTable("print_devices").set({print_count:$,updated_at:n$(new Date)}).where("id","=",N).execute(),await b(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update print count: ${G.message}`);throw G}}var s$={};B(s$,{update:()=>r4,unresolveGroup:()=>GN,resolveGroup:()=>NN,ignoreGroup:()=>JN,fetchTimeline:()=>t4,fetchStats:()=>e4,fetchGrouped:()=>d4,fetchById:()=>s4,fetchByGroup:()=>a4,fetchAll:()=>c0,destroyGroup:()=>o4,destroy:()=>u4,bulkUpdateStatus:()=>$N,bulkDestroy:()=>i4});import{db as i$}from"@stacksjs/database";import{log as o$}from"@stacksjs/logging";async function u4(N){try{return await i$.deleteFrom("errors").where("id","=",N).execute(),!0}catch($){return o$.error("[commerce/errors] destroy failed",{id:N,error:$}),!1}}async function i4(N){try{return await i$.deleteFrom("errors").where("id","in",N).execute(),!0}catch($){return o$.error("[commerce/errors] bulkDestroy failed",{count:N.length,error:$}),!1}}async function o4(N,$){try{return await i$.deleteFrom("errors").where("type","=",N).where("message","=",$).execute(),!0}catch(J){return o$.error("[commerce/errors] destroyGroup failed",{type:N,message:$,error:J}),!1}}import{db as l0}from"@stacksjs/database";async function s4(N){return await l0.selectFrom("errors").where("id","=",N).selectAll().executeTakeFirst()}async function c0(){return await l0.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}async function d4(){let N=await l0.selectFrom("errors").selectAll().orderBy("created_at","desc").execute(),$=new Map;for(let G of N){let X=`${G.type}:${G.message}`;if(!$.has(X))$.set(X,{errors:[],firstSeen:new Date(G.created_at),lastSeen:new Date(G.created_at)});let L=$.get(X);L.errors.push(G);let W=new Date(G.created_at);if(W<L.firstSeen)L.firstSeen=W;if(W>L.lastSeen)L.lastSeen=W}let J=[];for(let[G,X]of $){let L=X.errors[0];if(!L)continue;let W=X.errors.find((Z)=>Z.status!==null)?.status,Y="unresolved";if(W===1)Y="resolved";else if(W===2)Y="ignored";J.push({id:L.id,type:L.type,message:L.message,stack:L.stack,status:Y,count:X.errors.length,first_seen:X.firstSeen.toISOString(),last_seen:X.lastSeen.toISOString(),error_ids:X.errors.map((Z)=>Z.id)})}return J.sort((G,X)=>new Date(X.last_seen).getTime()-new Date(G.last_seen).getTime()),J}async function a4(N,$){return await l0.selectFrom("errors").where("type","=",N).where("message","=",$).selectAll().orderBy("created_at","desc").execute()}async function e4(){let N=await c0(),$=new Date,J=new Date($.getTime()-86400000),G=new Date($.getTime()-172800000),X=N.filter((Y)=>new Date(Y.created_at)>=J).length,L=N.filter((Y)=>{let Z=new Date(Y.created_at);return Z>=G&&Z<J}).length,W=L===0?X>0?100:0:Math.round((X-L)/L*100);return{total:N.length,unresolved:N.filter((Y)=>Y.status===null||Y.status===0).length,resolved:N.filter((Y)=>Y.status===1).length,ignored:N.filter((Y)=>Y.status===2).length,last_24h:X,trend:W}}async function t4(){let N=await c0(),$=new Date,J=[];for(let G=23;G>=0;G--){let X=new Date($.getTime()-G*60*60*1000);X.setMinutes(0,0,0);let L=new Date(X.getTime()+3600000),W=N.filter((Y)=>{let Z=new Date(Y.created_at);return Z>=X&&Z<L}).length;J.push({hour:X.toISOString(),count:W})}return J}import{db as x0}from"@stacksjs/database";import{sql as H0}from"@stacksjs/database";import{log as V0}from"@stacksjs/logging";async function r4(N,$){try{return await x0.updateTable("errors").set({...$,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("id","=",N).execute(),!0}catch(J){return V0.error("[commerce/errors] update failed",{id:N,error:J}),!1}}async function $N(N,$){try{return await x0.updateTable("errors").set({status:$,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("id","in",N).execute(),!0}catch(J){return V0.error("[commerce/errors] bulkUpdateStatus failed",{count:N.length,status:$,error:J}),!1}}async function NN(N,$){try{return await x0.updateTable("errors").set({status:1,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] resolveGroup failed",{type:N,message:$,error:J}),!1}}async function JN(N,$){try{return await x0.updateTable("errors").set({status:2,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] ignoreGroup failed",{type:N,message:$,error:J}),!1}}async function GN(N,$){try{return await x0.updateTable("errors").set({status:0,updated_at:H0.raw("CURRENT_TIMESTAMP")}).where("type","=",N).where("message","=",$).execute(),!0}catch(J){return V0.error("[commerce/errors] unresolveGroup failed",{type:N,message:$,error:J}),!1}}var a$={};B(a$,{updateBalance:()=>SN,update:()=>ON,store:()=>BN,fetchTotalValue:()=>FN,fetchTotalCurrentBalance:()=>KN,fetchStats:()=>WN,fetchById:()=>a,fetchByCode:()=>d$,fetchAll:()=>XN,fetchActive:()=>LN,destroy:()=>xN,compareActiveGiftCards:()=>ZN,checkBalance:()=>YN,calculateGiftCardValues:()=>MN,bulkDestroy:()=>HN});import{db as QN}from"@stacksjs/database";import{formatDate as NL}from"@stacksjs/orm";import{db as T,sql as j}from"@stacksjs/database";import{formatDate as u,toTimestamp as G0}from"@stacksjs/orm";import{aggregateFunctions as f3,db as k3}from"@stacksjs/database";async function I(N,$,J){let G=k3.selectFrom(N);if(J)G=J(G);G=G.select(Object.entries($).map(([W,Y])=>{let Z=Y.column??"id",M=f3[Y.kind](Z);if(Y.filter)M=M.filterWhere(Y.filter.column,Y.filter.op,Y.filter.value);return M.as(W)}));let X=await G.executeTakeFirst(),L={};for(let W of Object.keys($)){let Y=X?.[W];L[W]=typeof Y==="number"?Y:Number(Y??0)||0}return L}async function XN(){return await T.selectFrom("gift_cards").selectAll().execute()}async function a(N){return await T.selectFrom("gift_cards").where("id","=",N).selectAll().executeTakeFirst()}async function d$(N){return await T.selectFrom("gift_cards").where("code","=",N).selectAll().executeTakeFirst()}async function LN(){return await T.selectFrom("gift_cards").where("is_active","=",!0).selectAll().execute()}async function WN(){let{count:N}=await I("gift_cards",{count:{kind:"count"}}),$=G0(new Date),J=await T.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal($)} OR expiry_date IS NULL)`).select(T.fn.count("id").as("count")).executeTakeFirst(),G=await T.selectFrom("gift_cards").select(["status",T.fn.count("id").as("count")]).groupBy("status").execute(),{count:X}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance < 0.25`)),{count:L}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`)),{count:W}=await I("gift_cards",{count:{kind:"count"}},(K)=>K.whereRaw(j`current_balance / initial_balance > 0.75`)),Y=new Date;Y.setDate(Y.getDate()+30);let Z=await T.selectFrom("gift_cards").where("is_active","=",!0).where("status","=","ACTIVE").where("expiry_date","<=",G0(Y)).where("expiry_date",">=",$).selectAll().limit(5).execute(),M=await T.selectFrom("gift_cards").where("last_used_date","is not",null).selectAll().limit(5).execute();return{total:N,active:Number(J?.count||0),by_status:G.map((K)=>({status:K.status,count:Number(K.count)})),by_balance:{low:X,medium:L,high:W},expiring_soon:Z,recently_used:M}}async function YN(N){let $=await d$(N);if(!$)return{valid:!1,message:"Gift card not found"};if(!$.isActive||$.status!=="ACTIVE")return{valid:!1,balance:$.currentBalance,currency:$.currency,message:`Gift card is ${$.status.toLowerCase()}`};if($.expiryDate){if(new Date($.expiryDate)<new Date)return{valid:!1,balance:$.currentBalance,currency:$.currency,message:"Gift card has expired"}}return{valid:!0,balance:$.currentBalance,currency:$.currency}}async function ZN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await T.selectFrom("gift_cards").select(T.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0($))} OR expiry_date IS NULL)`).where("created_at",">=",u(J)).where("created_at","<=",u($)).executeTakeFirst(),W=await T.selectFrom("gift_cards").select(T.fn.count("id").as("count")).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0(X))} OR expiry_date IS NULL)`).where("created_at",">=",u(X)).where("created_at","<=",u(G)).executeTakeFirst(),Y=Number(L?.count||0),Z=Number(W?.count||0),M=Y-Z,K=Z!==0?M/Z*100:Y>0?100:0;return{current_period:Y,previous_period:Z,difference:M,percentage_change:K,days_range:N}}async function MN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await T.selectFrom("gift_cards").select([T.fn.sum("initial_balance").as("total_initial"),T.fn.sum("current_balance").as("total_balance"),T.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0($))} OR expiry_date IS NULL)`).where("created_at",">=",u(J)).where("created_at","<=",u($)).executeTakeFirst(),W=await T.selectFrom("gift_cards").select([T.fn.sum("initial_balance").as("total_initial"),T.fn.sum("current_balance").as("total_balance"),T.fn.count("id").as("card_count")]).where("is_active","=",!0).where("status","=","ACTIVE").whereRaw(j`(expiry_date >= ${j.literal(G0(X))} OR expiry_date IS NULL)`).where("created_at",">=",u(X)).where("created_at","<=",u(G)).executeTakeFirst(),Y=Number(L?.total_initial||0),Z=Number(L?.total_balance||0),M=Number(L?.card_count||0),K=Number(W?.total_initial||0),Q=Number(W?.total_balance||0),x=Number(W?.card_count||0),R=Y>0?(Y-Z)/Y*100:0,O=K>0?(K-Q)/K*100:0,_=M>0?Y/M:0,S=M>0?Z/M:0,D=Y-K,o=Z-Q,s=M-x,J0=K!==0?D/K*100:Y>0?100:0,p=Q!==0?o/Q*100:Z>0?100:0,Q3=x!==0?s/x*100:M>0?100:0;return{current_period:{total_initial_value:Y,total_remaining_balance:Z,utilization_rate:R,card_count:M,average_initial_value:_,average_remaining_balance:S},previous_period:{total_initial_value:K,total_remaining_balance:Q,utilization_rate:O,card_count:x},comparison:{initial_value:{difference:D,percentage:Math.abs(J0),is_increase:D>=0},balance:{difference:o,percentage:Math.abs(p),is_increase:o>=0},card_count:{difference:s,percentage:Math.abs(Q3),is_increase:s>=0}},days_range:N}}async function FN(){let{total_value:N}=await I("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value:N}}async function KN(){let{total_balance:N}=await I("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance:N}}async function xN(N){let $=await QN.deleteFrom("gift_cards").where("id","=",N).executeTakeFirst();return F($)>0}async function HN(N){if(!N.length)return 0;let $=await QN.deleteFrom("gift_cards").where("id","in",N).executeTakeFirst();return F($)}var{randomUUIDv7:j3}=globalThis.Bun;import{db as VN}from"@stacksjs/database";import{HttpError as zN}from"@stacksjs/error-handling";import{isUniqueViolation as C3}from"@stacksjs/orm";async function BN(N){let $=N,J={...N,current_balance:$.current_balance??$.initial_balance,status:N.status||"ACTIVE",is_active:$.is_active??!0,uuid:j3()};try{let G=await VN.insertInto("gift_cards").values(J).executeTakeFirst(),X=Number(G.insertId)||Number(G.numInsertedOrUpdatedRows);if(X)return await VN.selectFrom("gift_cards").where("id","=",X).selectAll().executeTakeFirst();return}catch(G){if(G instanceof zN)throw G;if(C3(G))throw new zN(409,"A gift card with this code already exists");if(G instanceof Error)throw Error(`Failed to create gift card: ${G.message}`);throw G}}import{db as RN}from"@stacksjs/database";import{HttpError as AN}from"@stacksjs/error-handling";import{formatDate as _N,isUniqueViolation as I3}from"@stacksjs/orm";async function ON(N,$){if(!await a(N))return;try{return await RN.updateTable("gift_cards").set({...$,updated_at:_N(new Date)}).where("id","=",N).execute(),await a(N)}catch(G){if(G instanceof AN)throw G;if(I3(G))throw new AN(409,"A gift card with this code already exists");if(G instanceof Error)throw Error(`Failed to update gift card: ${G.message}`);throw G}}async function SN(N,$){if(!Number.isFinite($))throw Error(`Gift card balance adjustment must be a finite number, got ${$}`);let J=_N(new Date),G=await RN.unsafe(`UPDATE gift_cards
9
9
  SET current_balance = current_balance + ?,
10
10
  last_used_date = ?,
11
11
  status = CASE WHEN current_balance + ? = 0 THEN 'USED' ELSE 'ACTIVE' END,
@@ -13,4 +13,15 @@ var R9=Object.defineProperty;var U9=(G)=>G;function T9(G,J){this[G]=U9.bind(null
13
13
  WHERE id = ?
14
14
  AND is_active = 1
15
15
  AND status = 'ACTIVE'
16
- AND current_balance + ? >= 0`,[J,X,J,X,G,J]),K=typeof $?.execute==="function"?await $.execute():$;if(Number(K?.changes??K?.numUpdatedRows??K?.affectedRows??0)>0)return await v(G);let Y=await v(G);if(!Y)throw Error(`Gift card with ID ${G} not found`);if(!Y.is_active||Y.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var fG={};B(fG,{validateQuantityBounds:()=>IG,validateCouponStacking:()=>K$,validateCartQuantities:()=>L$,updateStatus:()=>r6,updateDeliveryInfo:()=>e6,update:()=>t6,storeOrdersExport:()=>D6,store:()=>o6,softDelete:()=>f6,registerCommerceWebhookHandlers:()=>G$,recomputeOrderTotals:()=>$$,placeOrder:()=>a6,handlePaymentIntentSucceeded:()=>wG,handlePaymentIntentFailed:()=>CG,handleChargeRefunded:()=>_G,fetchStats:()=>b6,fetchDailyOrderTrends:()=>c6,fetchById:()=>h,fetchAll:()=>p6,exportOrders:()=>SJ,emitOrderShipped:()=>TG,emitOrderRefunded:()=>MJ,emitOrderPaid:()=>u,emitOrderDelivered:()=>SG,emitOrderCreated:()=>qJ,emitOrderCancelled:()=>ZJ,emitForStatus:()=>jJ,downloadOrders:()=>y6,destroy:()=>I6,compareOrdersByPeriod:()=>m6,cleanupAbandonedCarts:()=>Y$,canTransition:()=>PJ,calculateOrderMetrics:()=>l6,bulkSoftDelete:()=>h6,bulkDestroy:()=>v6});import{db as TJ}from"@stacksjs/database";async function I6(G){try{let J=await TJ.deleteFrom("orders").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function f6(G){try{let J=await TJ.updateTable("orders").set({status:"CANCELED"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete order: ${J.message}`);throw J}}async function v6(G){if(!G.length)return 0;try{let J=await TJ.deleteFrom("orders").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}async function h6(G){if(!G.length)return 0;try{let J=await TJ.updateTable("orders").set({status:"CANCELED"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete orders: ${J.message}`);throw J}}import{db as g6}from"@stacksjs/database";import{createSpreadsheet as b9}from"ts-spreadsheets";async function SJ(G="csv"){let J=await m9(),X=l9(J);return b9(X,{type:G})}async function m9(){let G=await g6.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),J=G.map((L)=>L.id);if(J.length===0)return[];let $=(await g6.selectFrom("order_items").where("order_items.order_id","in",J).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((L,Y)=>{if(!Y.order_id)return L;if(!L[Y.order_id])L[Y.order_id]={totalItems:0,totalPrice:0};return L[Y.order_id].totalItems+=Y.quantity,L[Y.order_id].totalPrice+=Y.price*Y.quantity,L},{});return G.map((L)=>{let Y=$[L.id]||{totalItems:0,totalPrice:0};return{...L,totalItems:Y.totalItems,totalPrice:Y.totalPrice}})}function l9(G){let J=["Order ID","Customer","Date","Total","Status","Items"],X=G.map(($)=>{let K=$.order_items?.map((L)=>`${L.product?.name} (Qty: ${L.quantity}, Price: $${L.price})`).join(" | ")||"No Items";return[$.id,$.customer?.name||"N/A",$.created_at,$.total_amount,$.status,K]});return{headings:J,data:X}}async function y6(G="csv",J){let X=await SJ(G),$=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;return X.download(J||$)}async function D6(G="csv",J){let X=await SJ(G),$=`orders_export_${new Date().toISOString().split("T")[0]}.${G}`;X.store(J||$)}import{db as V}from"@stacksjs/database";async function p6(G){let J=V.selectFrom("orders").selectAll().orderBy("created_at","desc");if(G)J=J.limit(G);let X=await J.execute();return await Promise.all(X.map(async($)=>{let K=await V.selectFrom("order_items").where("order_id","=",$.id).selectAll().execute();return{...$,items:K}}))}async function h(G){return await V.selectFrom("orders").where("id","=",G).selectAll().executeTakeFirst()}async function b6(){let G=await V.selectFrom("orders").select(V.fn.count("id").as("count")).executeTakeFirst(),J=await V.selectFrom("orders").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),X=await V.selectFrom("orders").select(["order_type",V.fn.count("id").as("count")]).groupBy("order_type").execute(),$=await V.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),K=await Promise.all($.map(async(Y)=>{let W=await V.selectFrom("order_items").where("order_id","=",Y.id).selectAll().execute();return{...Y,items:W}})),L=await V.selectFrom("orders").select(V.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(G?.count||0),by_status:J,by_type:X,recent:K,revenue:Number(L?.total||0)}}async function m6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await V.selectFrom("orders").select(V.fn.count("id").as("count")).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),Y=await V.selectFrom("orders").select(V.fn.count("id").as("count")).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=Number(L?.count||0),M=Number(Y?.count||0),Z=W-M,N=M!==0?Z/M*100:W>0?100:0;return{current_period:W,previous_period:M,difference:Z,percentage_change:N,days_range:G}}async function l6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await V.selectFrom("orders").select([V.fn.count("id").as("total_orders"),V.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).executeTakeFirst(),Y=await V.selectFrom("orders").select([V.fn.count("id").as("total_orders"),V.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",K.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=await V.selectFrom("orders").select(["status",V.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).groupBy("status").execute(),M=await V.selectFrom("orders").select(["order_type",V.fn.count("id").as("count")]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).groupBy("order_type").execute(),Z=Number(L?.total_orders||0),N=Number(L?.total_revenue||0),x=Z>0?N/Z:0,F=Number(Y?.total_orders||0),T=Number(Y?.total_revenue||0),E=F>0?T/F:0,z=Z-F,O=N-T,_=x-E,b=F!==0?z/F*100:Z>0?100:0,m=T!==0?O/T*100:N>0?100:0,d=E!==0?_/E*100:x>0?100:0;return{current_period:{total_orders:Z,total_revenue:N,average_order_value:x,orders_by_status:W.map((I)=>({status:I.status,count:Number(I.count)})),orders_by_type:M.map((I)=>({order_type:I.order_type,count:Number(I.count)}))},previous_period:{total_orders:F,total_revenue:T,average_order_value:E},comparison:{orders:{difference:z,percentage:Math.abs(b),is_increase:z>=0},revenue:{difference:O,percentage:Math.abs(m),is_increase:O>=0},average_order_value:{difference:_,percentage:Math.abs(d),is_increase:_>=0}},days_range:G}}async function c6(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await V.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",X.toISOString()).where("created_at","<=",J.toISOString()).orderBy("created_at","asc").execute(),K=new Map;for(let L of $){let Y=(L.created_at||"").split("T")[0]||"unknown",W=K.get(Y)||{order_count:0,revenue:0};W.order_count++,W.revenue+=Number(L.total_amount||0),K.set(Y,W)}return Array.from(K.entries()).map(([L,Y])=>({date:L,order_count:Y.order_count,revenue:Y.revenue}))}var{randomUUIDv7:c9}=globalThis.Bun;import{db as u6}from"@stacksjs/database";import{formatDate as n6}from"@stacksjs/orm";async function o6(G){let J={...G,status:G.status||"PENDING",uuid:c9(),created_at:n6(new Date),updated_at:n6(new Date)};try{let X=await u6.insertInto("orders").values(J).executeTakeFirst(),$=Number(X?.insertId)||Number(X?.numInsertedOrUpdatedRows);if($)return await u6.selectFrom("orders").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof Error)throw Error(`Failed to create order: ${X.message}`);throw X}}var{randomUUIDv7:n9}=globalThis.Bun;import{db as kJ}from"@stacksjs/database";import{formatDate as o9}from"@stacksjs/orm";import{sql as i6}from"@stacksjs/database";var u9={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","CANCELLED","REFUNDED"],SHIPPED:["DELIVERED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]};function PJ(G,J){if(G===J)return!0;return u9[G]?.includes(J)??!1}async function r(G,J){try{let X=await import("@stacksjs/events").catch(()=>null);if(!X)return;let $=X.dispatch;if(typeof $!=="function")return;$(G,J)}catch{}}async function qJ(G){await r("order:created",{order:G})}async function u(G,J){await r("order:paid",{order:G,payment:J})}async function TG(G){await r("order:shipped",{order:G})}async function SG(G){await r("order:delivered",{order:G})}async function ZJ(G,J){await r("order:cancelled",{order:G,reason:J})}async function MJ(G,J){await r("order:refunded",{order:G,refundAmount:J})}async function jJ(G,J){switch(G){case"PROCESSING":return u(J);case"SHIPPED":return TG(J);case"DELIVERED":return SG(J);case"CANCELLED":return ZJ(J);case"REFUNDED":return MJ(J);case"PENDING":default:}}var s6=!1;function d6(G){let J=G,X=J?.message??"";return J?.code==="42P01"||X.includes("no such table")||X.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(X)}async function i9(G){try{let J=await kJ.selectFrom("order_idempotency").where("idempotency_key","=",G).selectAll().executeTakeFirst();if(!J)return null;return await kJ.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}catch(J){if(d6(J)){if(!s6)s6=!0,console.warn("[commerce/orders] order_idempotency table missing \u2014 idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw J}}async function a6(G){if(G.idempotencyKey){let J=await i9(G.idempotencyKey);if(J)return{ok:!0,order:J}}try{let J=await kJ.transaction(async(X)=>{let $=o9(new Date),K={...G.order,status:G.order.status||"PENDING",uuid:n9(),created_at:$,updated_at:$},L=await X.insertInto("orders").values(K).executeTakeFirst(),Y=Number(L?.insertId)||Number(L?.numInsertedOrUpdatedRows);if(!Y)throw Object.assign(Error("order insert returned no id"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let W;if(G.payment)try{let Z=await X.insertInto("payments").values({...G.payment,order_id:Y,created_at:$,updated_at:$}).executeTakeFirst(),N=Number(Z?.insertId)||Number(Z?.numInsertedOrUpdatedRows);if(N)W=await X.selectFrom("payments").where("id","=",N).selectAll().executeTakeFirst()}catch(Z){if(Z?.message?.includes("UNIQUE constraint")||Z?.message?.includes("Duplicate entry"))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(Z,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(G.inventory&&G.inventory.length>0)for(let Z=0;Z<G.inventory.length;Z++){let{id:N,delta:x}=G.inventory[Z];if(!Number.isFinite(x)||x===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});let F=await X.updateTable("products").set({inventory_count:i6`inventory_count + ${x}`,updated_at:$}).where("id","=",N).where(i6`inventory_count + ${x}`,">=",0).execute();if(!Number(F?.numUpdatedRows??F?.[0]?.numUpdatedRows??F?.numAffectedRows??0))throw Object.assign(Error(`inventory adjust failed for product ${N}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(G.idempotencyKey)try{await X.insertInto("order_idempotency").values({idempotency_key:G.idempotencyKey,order_id:Y,created_at:$}).execute()}catch(Z){if(Z?.message?.includes("UNIQUE constraint")||Z?.message?.includes("Duplicate entry"))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!d6(Z))throw Z}let M=await X.selectFrom("orders").where("id","=",Y).selectAll().executeTakeFirst();if(!M)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:M,payment:W}});if(qJ(J.order),J.payment)u(J.order,J.payment);return{ok:!0,order:J.order,payment:J.payment}}catch(J){if(J?.__placeFail)return{ok:!1,reason:J.reason,failedAt:J.failedAt,error:J};throw J}}import{db as PG}from"@stacksjs/database";import{formatDate as qG}from"@stacksjs/orm";async function t6(G,J){if(!await h(G))throw Error(`Order with ID ${G} not found`);try{return await PG.updateTable("orders").set({...J,updated_at:qG(new Date)}).where("id","=",G).execute(),await h(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update order: ${$.message}`);throw $}}async function r6(G,J){let X=await h(G);if(!X)throw Error(`Order with ID ${G} not found`);let $=X.status??"PENDING";if(!PJ($,J))throw Error(`[commerce/orders] illegal status transition ${$} \u2192 ${J}`);try{await PG.updateTable("orders").set({status:J,updated_at:qG(new Date)}).where("id","=",G).execute();let K=await h(G);if(K)jJ(J,K);return K}catch(K){if(K instanceof Error)throw TypeError(`Failed to update order status: ${K.message}`);throw K}}async function e6(G,J,X){let $=await h(G);if(!$)throw Error(`Order with ID ${G} not found`);let K={updated_at:qG(new Date)};if(J!==void 0)K.delivery_address=J;if(X!==void 0)K.estimated_delivery_time=X;if(Object.keys(K).length===1)return $;try{return await PG.updateTable("orders").set(K).where("id","=",G).execute(),await h(G)}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery information: ${L.message}`);throw L}}import{db as e}from"@stacksjs/database";import{formatDate as wJ}from"@stacksjs/orm";async function jG(G){let J=await e.selectFrom("payments").where("transaction_id","=",G).selectAll().executeTakeFirst();if(!J)return null;return await e.selectFrom("orders").where("id","=",J.order_id).selectAll().executeTakeFirst()??null}var J$=!1;function s9(G){let J=G,X=J?.message??"";return J?.code==="42P01"||X.includes("no such table")||X.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(X)}async function kG(G,J){try{return await J.insertInto("stripe_webhook_events").values({event_id:G,processed_at:wJ(new Date)}).execute(),!0}catch(X){if(X?.message?.includes("UNIQUE constraint")||X?.message?.includes("Duplicate entry"))return!1;if(s9(X)){if(!J$)J$=!0,console.warn("[commerce/webhook] stripe_webhook_events table missing \u2014 Stripe retries may be processed multiple times. Run migrations to enable dedup.");return!0}throw X}}async function wG(G){let X=G.data.object?.id;if(!X)return;await e.transaction(async(K)=>{if(!await kG(G.id,K))return;let Y=await K.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!Y)return;let W=wJ(new Date);await K.updateTable("payments").set({status:"succeeded",updated_at:W}).where("id","=",Y.id).execute();let M=await K.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(M&&M.status==="PENDING")await K.updateTable("orders").set({status:"PROCESSING",updated_at:W}).where("id","=",M.id).execute()});let $=await jG(X);if($)await u($)}async function CG(G){let J=G.data.object,X=J?.id;if(!X)return;let K=J?.last_payment_error?.message??"payment failed";await e.transaction(async(Y)=>{if(!await kG(G.id,Y))return;let M=await Y.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!M)return;let Z=wJ(new Date);await Y.updateTable("payments").set({status:"failed",failure_reason:K,updated_at:Z}).where("id","=",M.id).execute();let N=await Y.selectFrom("orders").where("id","=",M.order_id).selectAll().executeTakeFirst();if(N&&N.status==="PENDING")await Y.updateTable("orders").set({status:"CANCELLED",updated_at:Z}).where("id","=",N.id).execute()});let L=await jG(X);if(L)await ZJ(L,K)}async function _G(G){let J=G.data.object,X=J?.payment_intent;if(!X)return;let $=J?.amount_refunded??0;await e.transaction(async(L)=>{if(!await kG(G.id,L))return;let W=await L.selectFrom("payments").where("transaction_id","=",X).selectAll().executeTakeFirst();if(!W)return;let M=wJ(new Date);await L.updateTable("payments").set({status:"refunded",refund_amount:$,updated_at:M}).where("id","=",W.id).execute();let Z=await L.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(Z&&Z.status!=="REFUNDED")await L.updateTable("orders").set({status:"REFUNDED",updated_at:M}).where("id","=",Z.id).execute()});let K=await jG(X);if(K)await MJ(K,$)}async function G$(){let G=await import("@stacksjs/payments").catch(()=>null);if(!G)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:J,onCharge:X}=G;if(typeof J!=="function"||typeof X!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return J({succeeded:wG,failed:CG}),X({refunded:_G}),()=>{}}import{db as X$}from"@stacksjs/database";async function d9(G){if(G.length===0)return new Map;let J=await X$.selectFrom("products").where("id","in",G).select(["id","price"]).execute(),X=new Map;for(let $ of J){let K=Number($.price);if(Number.isFinite(K))X.set($.id,Math.round(K))}return X}async function a9(G){try{let J=await X$.selectFrom("tax_rates").where("id","=",G).select(["rate"]).executeTakeFirst(),X=Number(J?.rate??0);return Number.isFinite(X)?X:0}catch{return 0}}async function $$(G){let J=G.items.map((E)=>E.productId),X=await d9(J),$=G.taxRateId!=null?await a9(G.taxRateId):0,K=0,L=[];for(let E of G.items){let z=E.unitPriceCents??X.get(E.productId)??0,O=Math.round(z*E.quantity);K+=O,L.push({productId:E.productId,quantity:E.quantity,unitPriceCents:z,lineCents:O})}let Y=Math.max(0,G.discountCents??0),W=Math.max(0,K-Y),M=Math.round(W*$),Z=Math.max(0,G.shippingCents??0),N=K-Y+M+Z,x=G.maxDriftCents??5,F=!1,T=0;if(G.clientTotalCents!=null)T=Math.abs(N-G.clientTotalCents),F=T>x;return{subtotalCents:K,discountCents:Y,taxCents:M,shippingCents:Z,totalCents:N,resolvedItems:L,priceChanged:F,diffCents:T}}import{db as CJ}from"@stacksjs/database";function K$(G,J={}){let X=G.length;if(X<=1)return{ok:!0,count:X};if(!J.allowMultiple)return{ok:!1,count:X,reason:"multiple-not-allowed"};let $=J.maxStacked??Number.POSITIVE_INFINITY;if(X>$)return{ok:!1,count:X,reason:"exceeds-max-stacked"};return{ok:!0,count:X}}async function IG(G,J){if(!Number.isFinite(J)||J<=0)return{ok:!1,productId:G,quantity:J,reason:"non-positive"};let X;try{X=await CJ.selectFrom("products").where("id","=",G).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:G,quantity:J}}if(!X)return{ok:!1,productId:G,quantity:J,reason:"product-missing"};let $=X.min_order_qty??null,K=X.max_order_qty??null;if($!=null&&J<$)return{ok:!1,productId:G,quantity:J,reason:"below-min",bound:$};if(K!=null&&J>K)return{ok:!1,productId:G,quantity:J,reason:"above-max",bound:K};return{ok:!0,productId:G,quantity:J}}async function L$(G){for(let X of G){let $=await IG(X.productId,X.quantity);if(!$.ok)return $}let J=G[G.length-1]??{productId:0,quantity:0};return{ok:!0,productId:J.productId,quantity:J.quantity}}async function Y$(G={}){let J=G.olderThanDays??30,X=G.limit??1000,K=new Date(Date.now()-J*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let L=await CJ.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[K,K,X]),Y=typeof L?.execute==="function"?await L.execute():L;return{deleted:Number(Y?.changes??Y?.numDeletedRows??Y?.[0]?.numDeletedRows??Y?.affectedRows??0),cutoffAt:K}}catch{try{let L=await CJ.selectFrom("carts").where("updated_at","<",K).select(["id"]).limit(X).execute();if(L.length===0)return{deleted:0,cutoffAt:K};let Y=L.map((Z)=>Z.id),W=await CJ.deleteFrom("carts").where("id","in",Y).execute();return{deleted:Number(W?.numDeletedRows??W?.[0]?.numDeletedRows??W?.affectedRows??L.length),cutoffAt:K}}catch{return{deleted:0,cutoffAt:K}}}}var vG={};B(vG,{update:()=>A$,store:()=>B$,fetchPaymentStatsByMethod:()=>H$,fetchPaymentStats:()=>x$,fetchMonthlyPaymentTrends:()=>F$,fetchById:()=>NJ,fetchAll:()=>N$,destroy:()=>Z$,bulkDestroy:()=>M$});import{db as W$}from"@stacksjs/database";async function Z$(G){try{let J=await W$.deleteFrom("payments").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payment: ${J.message}`);throw J}}async function M$(G){if(!G.length)return 0;try{let J=await W$.deleteFrom("payments").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete payments: ${J.message}`);throw J}}import{db as q}from"@stacksjs/database";import{formatDate as w}from"@stacksjs/orm";async function N$(){return await q.selectFrom("payments").selectAll().execute()}async function NJ(G){return await q.selectFrom("payments").selectAll().where("id","=",G).executeTakeFirst()}async function x$(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=new Date(X);$.setDate($.getDate()-1);let K=new Date($);K.setDate($.getDate()-G);let L=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").executeTakeFirst(),Y=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(K)).where("created_at","<=",w($)).where("status","=","completed").executeTakeFirst(),W=await q.selectFrom("payments").select(q.fn.count("id").as("count")).where("created_at",">=",w(X)).where("created_at","<=",w(J)).executeTakeFirst(),M=Number(L?.transaction_count||0),Z=Number(L?.total_revenue||0),N=M>0?Z/M:0,x=Number(Y?.transaction_count||0),F=Number(Y?.total_revenue||0),T=x>0?F/x:0,E=M-x,z=Z-F,O=N-T,_=x>0?E/x*100:M>0?100:0,b=F>0?z/F*100:Z>0?100:0,m=T>0?O/T*100:N>0?100:0,d=Number(W?.count||0),I=d>0?M/d*100:0;return{total_transactions:M,total_revenue:Z,average_transaction:N,successful_rate:I,comparison:{transactions:{difference:E,percentage:Math.abs(_),is_increase:E>=0},revenue:{difference:z,percentage:Math.abs(b),is_increase:z>=0},average:{difference:O,percentage:Math.abs(m),is_increase:O>=0}}}}async function H$(G=30){let J=new Date,X=new Date(J);X.setDate(J.getDate()-G);let $=await q.selectFrom("payments").select([q.fn.count("id").as("total_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").executeTakeFirst(),K=Number($?.total_count||0),L=await q.selectFrom("payments").select(["method",q.fn.count("id").as("count"),q.fn.sum("amount").as("revenue")]).where("created_at",">=",w(X)).where("created_at","<=",w(J)).where("status","=","completed").groupBy("method").execute(),Y={};return L.forEach((W)=>{let M=Number(W.count||0),Z=Number(W.revenue||0),N=K>0?M/K*100:0;Y[W.method]={count:M,revenue:Z,percentage_of_total:N}}),Y}async function F$(){let G=new Date,J=new Date(G);J.setMonth(G.getMonth()-11),J.setDate(1);let X=await q.selectFrom("payments").selectAll().where("created_at",">=",w(J)).where("status","=","completed").execute(),$={};for(let L of X){let Y=L.created_at?new Date(L.created_at):new Date,W=Y.getFullYear(),M=Y.getMonth()+1,Z=`${W}-${String(M).padStart(2,"0")}`;if(!$[Z])$[Z]={year:W,month:M,transactions:0,revenue:0};$[Z].transactions++,$[Z].revenue+=Number(L.amount||0)}return Object.keys($).sort().map((L)=>{let Y=$[L],W=Y.transactions,M=Y.revenue,Z=W>0?M/W:0;return{month:new Date(Y.year,Y.month-1,1).toLocaleString("default",{month:"short"}),year:Y.year,transactions:W,revenue:M,average:Z}})}var{randomUUIDv7:t9}=globalThis.Bun;import{db as Q$}from"@stacksjs/database";import{HttpError as V$}from"@stacksjs/error-handling";import{isUniqueViolation as r9}from"@stacksjs/orm";async function B$(G){let J={...G,status:G.status||"PENDING",currency:G.currency||"USD",uuid:t9()};try{let X=await Q$.insertInto("payments").values(J).executeTakeFirst(),$=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);if($)return await Q$.selectFrom("payments").where("id","=",$).selectAll().executeTakeFirst();return}catch(X){if(X instanceof V$)throw X;if(r9(X))throw new V$(409,"A payment with this transaction ID already exists");if(X instanceof Error){if(X.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${X.message}`)}throw X}}import{db as e9}from"@stacksjs/database";import{formatDate as JK}from"@stacksjs/orm";async function A$(G,J){if(!await NJ(G))throw Error(`Payment with ID ${G} not found`);try{return await e9.updateTable("payments").set({...J,updated_at:JK(new Date)}).where("id","=",G).execute(),await NJ(G)}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry")&&$.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${$.message}`)}throw $}}var lG={};B(lG,{variants:()=>yJ,units:()=>gJ,reviews:()=>hJ,manufacturers:()=>vJ,items:()=>fJ,default:()=>MK,categories:()=>IJ});var IJ={};B(IJ,{updateParent:()=>g$,updateDisplayOrder:()=>v$,updateActiveStatus:()=>h$,update:()=>f$,store:()=>gG,removeChildCategories:()=>k$,remove:()=>q$,findOrCreateByName:()=>I$,fetchStats:()=>T$,fetchRootCategories:()=>O$,fetchChildCategories:()=>R$,fetchCategoryTree:()=>P$,fetchByName:()=>z$,fetchById:()=>P,fetchByDisplayOrder:()=>U$,fetchAll:()=>hG,fetchActive:()=>E$,deactivateChildCategories:()=>C$,deactivate:()=>w$,compareCategoryGrowth:()=>S$,bulkRemove:()=>j$});import{db as n}from"@stacksjs/database";import{db as U}from"@stacksjs/database";import{formatDate as xJ}from"@stacksjs/orm";async function hG(){return await U.selectFrom("categories").selectAll().execute()}async function P(G){return await U.selectFrom("categories").where("id","=",G).selectAll().executeTakeFirst()}async function z$(G){return await U.selectFrom("categories").where("name","=",G).selectAll().executeTakeFirst()}async function E$(){return await U.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function O$(){return await U.selectFrom("categories").where("parent_category_id","is",null).where("is_active","=",!0).selectAll().execute()}async function R$(G){return await U.selectFrom("categories").where("parent_category_id","=",G).where("is_active","=",!0).selectAll().execute()}async function U$(G=!0){let J=U.selectFrom("categories").where("is_active","=",!0).selectAll();if(G)return await J.orderBy("display_order","asc").execute();else return await J.orderBy("display_order","desc").execute()}async function T$(){let G=await U.selectFrom("categories").select(U.fn.count("id").as("count")).executeTakeFirst(),J=await U.selectFrom("categories").where("is_active","=",!0).select(U.fn.count("id").as("count")).executeTakeFirst(),X=await U.selectFrom("categories").where("parent_category_id","is",null).select(U.fn.count("id").as("count")).executeTakeFirst(),$=await U.selectFrom("categories").where("image_url","is not",null).select(U.fn.count("id").as("count")).executeTakeFirst(),K=new Date;K.setDate(K.getDate()-30);let L=xJ(K),Y=await U.selectFrom("categories").where("created_at",">=",L).selectAll().limit(5).execute(),W=await U.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").where("c.parent_category_id","is not",null).select(["c.parent_category_id","parent.name as parent_name",U.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(G?.count||0),active:Number(J?.count||0),root_categories:Number(X?.count||0),child_categories:Number(G?.count||0)-Number(X?.count||0),with_images:Number($?.count||0),recently_added:Y,top_parent_categories:W.map((M)=>({id:String(M.parent_category_id||""),name:String(M.parent_name||""),child_count:Number(M.child_count)}))}}async function S$(G=30){let J=new Date,X=xJ(J),$=new Date;$.setDate(J.getDate()-G);let K=xJ($),L=new Date($);L.setDate(L.getDate()-1);let Y=xJ(L),W=new Date(L);W.setDate(L.getDate()-G);let M=xJ(W),Z=await U.selectFrom("categories").select(U.fn.count("id").as("count")).where("created_at",">=",K).where("created_at","<=",X).executeTakeFirst(),N=await U.selectFrom("categories").select(U.fn.count("id").as("count")).where("created_at",">=",M).where("created_at","<=",Y).executeTakeFirst(),x=Number(Z?.count||0),F=Number(N?.count||0),T=x-F,E=F!==0?T/F*100:x>0?100:0;return{current_period:x,previous_period:F,difference:T,percentage_change:E,days_range:G}}async function P$(){let G=await hG(),J=new Map;G.forEach((K)=>{J.set(K.id,{...K,children:[]})});let X=[];G.forEach((K)=>{let L=J.get(K.id);if(K.parent_category_id){let Y=J.get(K.parent_category_id);if(Y)Y.children.push(L)}else X.push(L)}),X.sort((K,L)=>K.display_order-L.display_order);let $=(K)=>{K.sort((L,Y)=>L.display_order-Y.display_order),K.forEach((L)=>{if(L.children.length>0)$(L.children)})};return $(X),X}async function q$(G){if(!await P(G))throw Error(`Category with ID ${G} not found`);return!!await n.deleteFrom("categories").where("id","=",G).executeTakeFirst()}async function j$(G){if(!G.length)return 0;let J=await n.deleteFrom("categories").where("id","in",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}async function k$(G){let J=await n.deleteFrom("categories").where("parent_category_id","=",G).executeTakeFirst();return Number(J?.numDeletedRows)||0}async function w$(G){if(!await P(G))throw Error(`Category with ID ${G} not found`);return!!await n.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",G).executeTakeFirst()}async function C$(G){let J=await n.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",G).execute();return Number(J.length)||0}import{db as _$}from"@stacksjs/database";import{slug as GK}from"@stacksjs/strings";async function gG(G){try{let J={...G,slug:G.name?.toLowerCase().replace(/\s+/g,"-")||"",categorizable_type:"product",display_order:0},X=await _$.insertInto("categories").values(J).executeTakeFirst();if(!X)throw Error("Failed to create category");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await P($);if(!K)throw Error("Failed to create category");return K}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry")&&J.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to create category: ${J.message}`)}throw J}}async function I$(G){if(!G.name)throw Error("Name is required");let J=await _$.selectFrom("categories").selectAll().where("name","=",G.name).executeTakeFirst();if(J)return J;let X={name:G.name,slug:GK(G.name),is_active:G.is_active??!0,categorizable_type:G.categorizable_type??"default",display_order:0};return await gG(X)}import{db as HJ}from"@stacksjs/database";import{formatDate as _J}from"@stacksjs/orm";async function f$(G,J){await J.validate();let X=await P(G);if(!X)throw Error(`Category with ID ${G} not found`);let $={name:J.get("name"),description:J.get("description"),imageUrl:J.get("imageUrl"),isActive:J.get("isActive"),parentCategoryId:J.get("parentCategoryId"),displayOrder:J.get("displayOrder"),updated_at:_J(new Date)};if(Object.keys($).length===0)return X;try{return await HJ.updateTable("categories").set($).where("id","=",G).execute(),await P(G)}catch(K){if(K instanceof Error){if(K.message.includes("Duplicate entry")&&K.message.includes("name"))throw Error("A category with this name already exists");throw Error(`Failed to update category: ${K.message}`)}throw K}}async function v$(G,J){if(!await P(G))throw Error(`Category with ID ${G} not found`);try{return await HJ.updateTable("categories").set({display_order:J,updated_at:_J(new Date)}).where("id","=",G).execute(),await P(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category display order: ${$.message}`);throw $}}async function h$(G,J){if(!await P(G))throw Error(`Category with ID ${G} not found`);try{return await HJ.updateTable("categories").set({is_active:J,updated_at:_J(new Date)}).where("id","=",G).execute(),await P(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category active status: ${$.message}`);throw $}}async function g$(G,J){if(!await P(G))throw Error(`Category with ID ${G} not found`);if(J){let $=Number(J);if($===G)throw Error("A category cannot be its own parent");if(!await P($))throw Error(`Parent category with ID ${J} not found`);if(await XK(G,J))throw Error("This operation would create a circular reference in the category hierarchy")}try{let $={updated_at:_J(new Date)};if(J===null)await HJ.updateTable("categories").set({...$,parent_category_id:void 0}).where("id","=",G).execute();else await HJ.updateTable("categories").set({...$,parent_category_id:J}).where("id","=",G).execute();return await P(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update category parent: ${$.message}`);throw $}}async function XK(G,J){let X=Number(J),$=new Set;while(X){if($.has(X))return!0;if(X===G)return!0;$.add(X);let K=await P(X);if(!K||!K.parentCategoryId)return!1;X=Number(K.parentCategoryId)}return!1}var fJ={};B(fJ,{updateInventory:()=>s$,updateAvailability:()=>i$,update:()=>o$,store:()=>u$,fetchTopProducts:()=>m$,fetchById:()=>g,fetchAll:()=>b$,destroy:()=>D$,bulkStore:()=>n$,bulkDestroy:()=>p$});import{db as y$}from"@stacksjs/database";async function D$(G){try{let J=await y$.deleteFrom("products").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product item: ${J.message}`);throw J}}async function p$(G){if(!G.length)return 0;try{let J=await y$.deleteFrom("products").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product items: ${J.message}`);throw J}}import{db as p,sql as $K}from"@stacksjs/database";async function g(G){let J=await p.selectFrom("products").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=null,$=null;if(J.manufacturer_id)X=await p.selectFrom("manufacturers").where("id","=",J.manufacturer_id).selectAll().executeTakeFirst();if(J.category_id)$=await p.selectFrom("categories").where("id","=",J.category_id).selectAll().executeTakeFirst();return{...J,manufacturer:X,category:$}}return}async function b$(){let G=await p.selectFrom("products").selectAll().execute(),J=G.map((Z)=>Z.manufacturer_id).filter((Z)=>Z!==null&&Z!==void 0),X=G.map((Z)=>Z.category_id).filter((Z)=>Z!==null&&Z!==void 0),$=p.selectFrom("manufacturers"),K=p.selectFrom("categories");if(J.length>0)$=$.where("id","in",J);if(X.length>0)K=K.where("id","in",X);let L=await $.selectAll().execute(),Y=await K.selectAll().execute(),W=L.reduce((Z,N)=>{return Z[N.id]=N,Z},{}),M=Y.reduce((Z,N)=>{return Z[N.id]=N,Z},{});return G.map((Z)=>({...Z,manufacturer:Z.manufacturer_id?W[Z.manufacturer_id]:null,category:Z.category_id?M[Z.category_id]:null}))}async function m$(G=5){try{return(await p.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",p.fn.sum("order_items.quantity").as("units_sold"),$K`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(G).execute()).map((X)=>({id:Number(X.id),name:String(X.name??"Unnamed product"),units_sold:Number(X.units_sold??0),revenue:Number(X.revenue??0),inventory_count:Number(X.inventory_count??0)}))}catch(J){if(J instanceof Error)throw TypeError(`Failed to fetch top products: ${J.message}`);throw J}}var{randomUUIDv7:l$}=globalThis.Bun;import{db as c$}from"@stacksjs/database";async function u$(G){try{let J={...G,uuid:l$()},X=await c$.insertInto("products").values(J).executeTakeFirst();if(!X)throw Error("Failed to create product item");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await g($);if(!K)throw Error("Failed to create product item");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product item: ${J.message}`);throw J}}async function n$(G){if(!G.length)return 0;let J=0;try{return await c$.transaction().execute(async(X)=>{for(let $ of G){let K={...$,uuid:l$()};await X.insertInto("products").values(K).execute(),J++}}),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product items in bulk: ${X.message}`);throw X}}import{db as yG,sql as h0}from"@stacksjs/database";import{formatDate as DG}from"@stacksjs/orm";async function o$(G,J){try{if(!G)throw Error("Product item ID is required for update");let X=await yG.updateTable("products").set({...J,updated_at:DG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product item");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product item: ${X.message}`);throw X}}async function i$(G,J){if(!await g(G))throw Error(`Product item with ID ${G} not found`);try{return await yG.updateTable("products").set({is_available:J,updated_at:DG(new Date)}).where("id","=",G).execute(),await g(G)}catch($){if($ instanceof Error)throw TypeError(`Failed to update product item availability: ${$.message}`);throw $}}async function s$(G,J){let X=await g(G);if(!X)throw Error(`Product item with ID ${G} not found`);let $={updated_at:DG(new Date)};if(J!==void 0)$.inventory_count=J;if(Object.keys($).length===1)return X;try{return await yG.updateTable("products").set($).where("id","=",G).execute(),await g(G)}catch(K){if(K instanceof Error)throw TypeError(`Failed to update inventory information: ${K.message}`);throw K}}var vJ={};B(vJ,{updateFeaturedStatus:()=>x2,updateByUuid:()=>H2,update:()=>N2,store:()=>W2,fetchWithProductCount:()=>$2,fetchFeatured:()=>G2,fetchByUuid:()=>J2,fetchById:()=>e$,fetchByCountry:()=>X2,fetchAll:()=>r$,destroy:()=>a$,bulkStore:()=>Z2,bulkDestroy:()=>t$});import{db as d$}from"@stacksjs/database";async function a$(G){try{let J=await d$.deleteFrom("manufacturers").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function t$(G){if(!G.length)return 0;try{let J=await d$.deleteFrom("manufacturers").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}import{db as y}from"@stacksjs/database";function r$(){return y.selectFrom("manufacturers").selectAll().execute()}async function e$(G){return await y.selectFrom("manufacturers").where("id","=",G).selectAll().executeTakeFirst()}async function J2(G){return await y.selectFrom("manufacturers").where("uuid","=",G).selectAll().executeTakeFirst()}async function G2(G=10){return await y.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(G).execute()}async function X2(G,J={}){let X=J.page||1,$=J.limit||2,K=await y.selectFrom("manufacturers").select(y.fn.count("id").as("total")).where("country","=",G).executeTakeFirst(),L=Number(K?.total||0),Y=await y.selectFrom("manufacturers").selectAll().where("country","=",G).limit($).offset((X-1)*$).execute(),W=Math.ceil(L/$);return{data:Y,paging:{total_records:L,page:X,total_pages:W},next_cursor:X<W?X+1:null}}async function $2(G={}){let J=y.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(G.country)J=J.where("m.country","=",G.country);if(G.featured!==void 0)J=J.where("m.featured","=",G.featured);return J=J.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",y.fn.count("p.id").as("product_count")]).groupBy("m.id"),J.execute()}var{randomUUIDv7:L2}=globalThis.Bun;import{db as Y2}from"@stacksjs/database";import{HttpError as K2}from"@stacksjs/error-handling";import{isUniqueViolation as KK}from"@stacksjs/orm";async function W2(G){try{let J={...G,uuid:L2(),featured:G.featured??!1},X=await Y2.insertInto("manufacturers").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create manufacturer");return X}catch(J){if(J instanceof K2)throw J;if(KK(J))throw new K2(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to create manufacturer: ${J.message}`);throw J}}async function Z2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:L2(),featured:X.featured??!1};await Y2.insertInto("manufacturers").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${X.message}`);throw X}}import{db as pG}from"@stacksjs/database";import{HttpError as M2}from"@stacksjs/error-handling";import{formatDate as bG,isUniqueViolation as LK}from"@stacksjs/orm";async function N2(G,J){try{if(!G)throw Error("Manufacturer ID is required for update");let X=await pG.updateTable("manufacturers").set({...J,updated_at:bG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error(`Manufacturer with ID ${G} not found`);return X}catch(X){if(X instanceof M2)throw X;if(LK(X))throw new M2(409,"A manufacturer with this name already exists");if(X instanceof Error)throw Error(`Failed to update manufacturer: ${X.message}`);throw X}}async function x2(G,J){try{let X=await pG.updateTable("manufacturers").set({featured:J,updated_at:bG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update manufacturer featured status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${X.message}`);throw X}}async function H2(G,J){try{let X=await pG.updateTable("manufacturers").set({...J,updated_at:bG(new Date)}).where("uuid","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update manufacturer");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update manufacturer: ${X.message}`);throw X}}var hJ={};B(hJ,{updateVotes:()=>q2,update:()=>P2,store:()=>U2,fetchMostHelpfulByProductId:()=>R2,fetchByUserId:()=>E2,fetchByProductId:()=>z2,fetchById:()=>B2,fetchApprovedByProductId:()=>O2,fetchAll:()=>A2,destroy:()=>Q2,bulkDestroy:()=>V2});import{db as F2}from"@stacksjs/database";async function Q2(G){try{let J=await F2.deleteFrom("reviews").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete order: ${J.message}`);throw J}}async function V2(G){if(!G.length)return 0;try{let J=await F2.deleteFrom("reviews").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete orders: ${J.message}`);throw J}}import{db as JJ}from"@stacksjs/database";async function B2(G){return await JJ.selectFrom("reviews").where("id","=",G).selectAll().executeTakeFirst()}async function A2(){return await JJ.selectFrom("reviews").selectAll().execute()}async function z2(G){return await JJ.selectFrom("reviews").where("product_id","=",G).selectAll().execute()}async function E2(G){return await JJ.selectFrom("reviews").where("customer_id","=",G).selectAll().execute()}async function O2(G){return await JJ.selectFrom("reviews").where("product_id","=",G).where("is_approved","=",!0).selectAll().execute()}async function R2(G){return await JJ.selectFrom("reviews").where("product_id","=",G).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:YK}=globalThis.Bun;import{db as WK}from"@stacksjs/database";async function U2(G){try{let J={...G,uuid:YK(),is_verified_purchase:G.is_verified_purchase??!1,is_approved:G.is_approved??!1,helpful_votes:G.helpful_votes??0,unhelpful_votes:G.unhelpful_votes??0,is_featured:G.is_featured??!1},X=await WK.insertInto("reviews").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create review");return X}catch(J){if(J instanceof Error){if(J.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${J.message}`)}throw J}}import{db as T2}from"@stacksjs/database";import{formatDate as S2}from"@stacksjs/orm";async function P2(G,J){try{if(!G)throw Error("Review ID is required for update");let X=await T2.updateTable("reviews").set({...J,updated_at:S2(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update review");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update review: ${X.message}`);throw X}}async function q2(G,J,X=!0){try{let $=J==="helpful"?"helpful_votes":"unhelpful_votes",K=X?`COALESCE("${$}", 0) + 1`:`MAX(COALESCE("${$}", 0) - 1, 0)`,L=await T2.unsafe(`UPDATE "reviews" SET "${$}" = ${K}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[S2(new Date),G]).execute(),Y=Array.isArray(L)?L[0]:L;if(!Y)throw Error("Failed to update review votes");return Y}catch($){if($ instanceof Error)throw TypeError(`Failed to update review votes: ${$.message}`);throw $}}var gJ={};B(gJ,{updateDefaultStatus:()=>b2,update:()=>D2,store:()=>v2,getDefaultUnit:()=>y2,formatUnitOptions:()=>g2,fetchById:()=>_2,fetchAll:()=>I2,destroy:()=>k2,bulkUpdate:()=>p2,bulkStore:()=>h2,bulkDestroy:()=>w2});import{db as j2}from"@stacksjs/database";async function k2(G){try{let J=await j2.deleteFrom("product_units").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product unit: ${J.message}`);throw J}}async function w2(G){if(!G.length)return 0;try{let J=await j2.deleteFrom("product_units").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product units: ${J.message}`);throw J}}import{db as C2}from"@stacksjs/database";async function _2(G){return await C2.selectFrom("product_units").where("id","=",G).selectAll().executeTakeFirst()}async function I2(){return await C2.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:f2}=globalThis.Bun;import{db as GJ}from"@stacksjs/database";async function v2(G){try{let J={...G,uuid:f2()},X=await GJ.insertInto("product_units").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product unit");if(J.is_default)await GJ.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",X.id).execute();return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product unit: ${J.message}`);throw J}}async function h2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:f2()},K=await GJ.insertInto("product_units").values($).returningAll().executeTakeFirst();if($.is_default&&K)await GJ.updateTable("product_units").set({is_default:!1}).where("type","=",$.type).where("id","!=",K.id).execute();J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product units in bulk: ${X.message}`);throw X}}function g2(G){try{let J=GJ.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(G)J=J.where("type","=",G);return J=J.orderBy("name"),J.execute().then((X)=>X.map(($)=>({id:String($.id),name:$.name,abbreviation:$.abbreviation,is_default:$.is_default})))}catch(J){if(J instanceof Error)throw TypeError(`Failed to format unit options: ${J.message}`);throw J}}async function y2(G){try{return await GJ.selectFrom("product_units").selectAll().where("type","=",G).where("is_default","=",!0).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get default unit: ${J.message}`);throw J}}import{db as o}from"@stacksjs/database";import{formatDate as mG}from"@stacksjs/orm";async function D2(G,J){try{if(!G)throw Error("Product unit ID is required for update");let X=await o.updateTable("product_units").set({...J,updated_at:mG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product unit");if(J.is_default===!0&&J.type)await o.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",G).execute();return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product unit: ${X.message}`);throw X}}async function p2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $=X;if(!$.id)continue;let K=$.data&&typeof $.data==="object"?$.data:{...$};delete K.id;let L=await o.updateTable("product_units").set({...K,updated_at:mG(new Date)}).where("id","=",$.id).executeTakeFirst(),Y=K;if(Y.is_default===!0&&Y.type)await o.updateTable("product_units").set({is_default:!1}).where("type","=",Y.type).where("id","!=",$.id).execute();if(Number(L.numUpdatedRows)>0)J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product units in bulk: ${X.message}`);throw X}}async function b2(G,J){try{let X=await o.selectFrom("product_units").select("type").where("id","=",G).executeTakeFirst();if(!X)return!1;let $=await o.updateTable("product_units").set({is_default:J,updated_at:mG(new Date)}).where("id","=",G).executeTakeFirst();if(J&&X.type)await o.updateTable("product_units").set({is_default:!1}).where("type","=",X.type).where("id","!=",G).execute();return Number($.numUpdatedRows)>0}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product unit default status: ${X.message}`);throw X}}var yJ={};B(yJ,{update:()=>G4,store:()=>d2,generateVariantCombinations:()=>r2,formatVariantOptions:()=>t2,fetchById:()=>n2,fetchAll:()=>o2,destroy:()=>l2,bulkUpdate:()=>X4,bulkStore:()=>a2,bulkDestroy:()=>c2});import{db as m2}from"@stacksjs/database";async function l2(G){try{let J=await m2.deleteFrom("product_variants").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variant: ${J.message}`);throw J}}async function c2(G){if(!G.length)return 0;try{let J=await m2.deleteFrom("product_variants").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete product variants: ${J.message}`);throw J}}import{db as u2}from"@stacksjs/database";async function n2(G){return await u2.selectFrom("product_variants").where("id","=",G).selectAll().executeTakeFirst()}async function o2(){return await u2.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:i2}=globalThis.Bun;import{db as s2}from"@stacksjs/database";async function d2(G){try{let J={...G,uuid:i2()},X=await s2.insertInto("product_variants").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create product variant");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variant: ${J.message}`);throw J}}async function a2(G){if(!G.length)return 0;let J=0;try{for(let X of G){let $={...X,uuid:i2()};await s2.insertInto("product_variants").values($).execute(),J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${X.message}`);throw X}}function t2(G){if(!G||!G.length)return JSON.stringify([]);let J=G.map((X)=>X.trim()).filter(Boolean);return JSON.stringify(J)}function r2(G){let J=Object.keys(G);if(!J.length)return[];function X($,K){if($===J.length)return[K];let L=J[$],Y=G[L]??[],W=[];for(let M of Y){let Z={...K,[L]:M};W.push(...X($+1,Z))}return W}return X(0,{})}import{db as e2}from"@stacksjs/database";import{formatDate as J4}from"@stacksjs/orm";async function G4(G,J){try{let X=await e2.updateTable("product_variants").set({...J,updated_at:J4(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update product variant");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product variant: ${X.message}`);throw X}}async function X4(G){if(!G.length)return 0;let J=0;try{for(let X of G){if(!X.id)continue;let $=await e2.updateTable("product_variants").set({...X,updated_at:J4(new Date)}).where("id","=",X.id).executeTakeFirst();if(Number($.numUpdatedRows)>0)J++}return J}catch(X){if(X instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${X.message}`);throw X}}var ZK={categories:IJ,items:fJ,manufacturers:vJ,reviews:hJ,units:gJ,variants:yJ},MK=ZK;var nG={};B(nG,{updateStatus:()=>Q4,updatePrintJob:()=>V4,update:()=>F4,store:()=>x4,fetchById:()=>W4,fetchAll:()=>Z4,destroy:()=>K4,bulkStore:()=>H4,bulkDestroy:()=>L4});import{db as $4}from"@stacksjs/database";async function K4(G){try{let J=await $4.deleteFrom("receipts").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete print log: ${J.message}`);throw J}}async function L4(G){if(!G.length)return 0;try{let J=await $4.deleteFrom("receipts").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete receipts: ${J.message}`);throw J}}import{db as Y4}from"@stacksjs/database";async function W4(G){return await Y4.selectFrom("receipts").where("id","=",G).selectAll().executeTakeFirst()}async function Z4(){return await Y4.selectFrom("receipts").selectAll().execute()}var{randomUUIDv7:M4}=globalThis.Bun;import{db as N4}from"@stacksjs/database";async function x4(G){try{let J={...G,uuid:M4()},X=await N4.insertInto("receipts").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create receipt");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipt: ${J.message}`);throw J}}async function H4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:M4()})),X=await N4.insertInto("receipts").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${J.message}`);throw J}}import{db as cG}from"@stacksjs/database";import{formatDate as uG}from"@stacksjs/orm";async function F4(G,J){try{if(!G)throw Error("Receipt ID is required for update");let X=await cG.updateTable("receipts").set({...J,updated_at:uG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update receipt");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt: ${X.message}`);throw X}}async function Q4(G,J){try{let X=await cG.updateTable("receipts").set({status:J,updated_at:uG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update receipt status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt status: ${X.message}`);throw X}}async function V4(G,J,X,$){try{let K={updated_at:uG(new Date)};if(J!==void 0)K.size=J;if(X!==void 0)K.pages=X;if($!==void 0)K.duration=$;let L=await cG.updateTable("receipts").set(K).where("id","=",G).returningAll().executeTakeFirst();if(!L)throw Error("Failed to update receipt job information");return L}catch(K){if(K instanceof Error)throw TypeError(`Failed to update receipt job information: ${K.message}`);throw K}}var $X={};B($X,{zones:()=>YG,routes:()=>pJ,rates:()=>XG,methods:()=>aJ,licenses:()=>oJ,drivers:()=>cJ,digital:()=>lJ,default:()=>HK});var pJ={};B(pJ,{updateStops:()=>j4,updateMetrics:()=>k4,updateLastActive:()=>P4,update:()=>q4,store:()=>S4,fetchById:()=>E4,fetchByDriver:()=>U4,fetchAll:()=>O4,fetchActive:()=>R4,destroy:()=>A4,bulkDestroy:()=>z4});import{db as B4}from"@stacksjs/database";async function A4(G){try{let J=await B4.deleteFrom("delivery_routes").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery route: ${J.message}`);throw J}}async function z4(G){if(!G.length)return 0;try{let J=await B4.deleteFrom("delivery_routes").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete delivery routes: ${J.message}`);throw J}}import{db as DJ}from"@stacksjs/database";async function E4(G){return await DJ.selectFrom("delivery_routes").where("id","=",G).selectAll().executeTakeFirst()}async function O4(){return await DJ.selectFrom("delivery_routes").selectAll().execute()}async function R4(){return await DJ.selectFrom("delivery_routes").where("last_active","<=",new Date(Date.now()-86400000)).selectAll().execute()}async function U4(G){return await DJ.selectFrom("delivery_routes").where("driver","=",G).selectAll().execute()}var{randomUUIDv7:NK}=globalThis.Bun;import{db as T4}from"@stacksjs/database";async function S4(G){try{let J={...G,uuid:NK()},X=await T4.insertInto("delivery_routes").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create delivery route");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create delivery route: ${J.message}`);throw J}}async function P4(G){try{let J=await T4.updateTable("delivery_routes").set({last_active:new Date().toISOString(),updated_at:new Date().toISOString()}).where("id","=",G).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update delivery route last active");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route last active: ${J.message}`);throw J}}import{db as oG}from"@stacksjs/database";import{formatDate as iG}from"@stacksjs/orm";async function q4(G,J){try{if(!G)throw Error("Delivery route ID is required for update");let X=await oG.updateTable("delivery_routes").set({...J,updated_at:iG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery route");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery route: ${X.message}`);throw X}}async function j4(G,J){try{let X=await oG.updateTable("delivery_routes").set({stops:J,updated_at:iG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery route stops");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update delivery route stops: ${X.message}`);throw X}}async function k4(G,J,X){try{let $={updated_at:iG(new Date)};if(J!==void 0)$.delivery_time=J;if(X!==void 0)$.total_distance=X;let K=await oG.updateTable("delivery_routes").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update delivery metrics");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery metrics: ${$.message}`);throw $}}var lJ={};B(lJ,{updateStatus:()=>b4,updateDeliverySettings:()=>m4,update:()=>p4,store:()=>y4,softDelete:()=>C4,fetchById:()=>mJ,fetchAll:()=>v4,destroy:()=>w4,bulkStore:()=>D4,bulkSoftDelete:()=>I4,bulkDestroy:()=>_4});import{db as bJ}from"@stacksjs/database";async function w4(G){try{let J=await bJ.deleteFrom("digital_deliveries").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital delivery: ${J.message}`);throw J}}async function C4(G){try{let J=await bJ.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${J.message}`);throw J}}async function _4(G){if(!G.length)return 0;try{let J=await bJ.deleteFrom("digital_deliveries").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${J.message}`);throw J}}async function I4(G){if(!G.length)return 0;try{let J=await bJ.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${J.message}`);throw J}}import{db as f4}from"@stacksjs/database";async function mJ(G){return await f4.selectFrom("digital_deliveries").where("id","=",G).selectAll().executeTakeFirst()}async function v4(){return await f4.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:h4}=globalThis.Bun;import{db as g4}from"@stacksjs/database";async function y4(G){try{let J={...G,uuid:h4()},X=await g4.insertInto("digital_deliveries").values(J).executeTakeFirst();if(!X)throw Error("Failed to create digital delivery");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await mJ($);if(!K)throw Error("Failed to create digital delivery");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital delivery: ${J.message}`);throw J}}async function D4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:h4()})),X=await g4.insertInto("digital_deliveries").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${J.message}`);throw J}}import{db as sG}from"@stacksjs/database";import{formatDate as dG}from"@stacksjs/orm";async function p4(G,J){try{if(!G)throw Error("Digital delivery ID is required for update");let X=await sG.updateTable("digital_deliveries").set({...J,updated_at:dG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update digital delivery");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update digital delivery: ${X.message}`);throw X}}async function b4(G,J){try{let X=await sG.updateTable("digital_deliveries").set({status:J,updated_at:dG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update digital delivery status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update digital delivery status: ${X.message}`);throw X}}async function m4(G,J,X,$,K){try{let L={updated_at:dG(new Date)};if(J!==void 0)L.download_limit=J;if(X!==void 0)L.expiry_days=X;if($!==void 0)L.requires_login=$;if(K!==void 0)L.automatic_delivery=K;let Y=await sG.updateTable("digital_deliveries").set(L).where("id","=",G).returningAll().executeTakeFirst();if(!Y)throw Error("Failed to update delivery settings");return Y}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery settings: ${L.message}`);throw L}}var cJ={};B(cJ,{updateStatus:()=>r4,updateContact:()=>e4,update:()=>t4,store:()=>d4,fetchById:()=>FJ,fetchAll:()=>c4,destroy:()=>n4,bulkStore:()=>a4,bulkDestroy:()=>o4});import{db as u4}from"@stacksjs/database";import{db as l4}from"@stacksjs/database";async function FJ(G){return await l4.selectFrom("drivers").where("id","=",G).selectAll().executeTakeFirst()}async function c4(){return await l4.selectFrom("drivers").selectAll().execute()}async function n4(G){let J=await FJ(G);if(!J)throw Error(`Driver with ID ${G} not found`);try{return await u4.deleteFrom("drivers").where("id","=",G).execute(),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to delete driver: ${X.message}`);throw X}}async function o4(G){if(!G.length)return 0;let J=0;try{return await u4.transaction().execute(async(X)=>{for(let $ of G)if(await FJ($))await X.deleteFrom("drivers").where("id","=",$).execute(),J++}),J}catch(X){if(X instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${X.message}`);throw X}}var{randomUUIDv7:i4}=globalThis.Bun;import{db as s4}from"@stacksjs/database";async function d4(G){try{let J={...G,uuid:i4()},X=await s4.insertInto("drivers").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create driver");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create driver: ${J.message}`);throw J}}async function a4(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:i4()})),X=await s4.insertInto("drivers").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${J.message}`);throw J}}import{db as aG}from"@stacksjs/database";import{formatDate as tG}from"@stacksjs/orm";async function t4(G,J){try{if(!G)throw Error("Driver ID is required for update");let X=await aG.updateTable("drivers").set({...J,updated_at:tG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update driver");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update driver: ${X.message}`);throw X}}async function r4(G,J){try{let X=await aG.updateTable("drivers").set({status:J,updated_at:tG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update driver status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update driver status: ${X.message}`);throw X}}async function e4(G,J){try{let X={updated_at:tG(new Date)};if(J!==void 0)X.phone=J;let $=await aG.updateTable("drivers").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update contact information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update contact information: ${X.message}`);throw X}}var oJ={};B(oJ,{updateStatus:()=>x7,updateExpiration:()=>H7,update:()=>N7,store:()=>Z7,softDelete:()=>G7,fetchById:()=>nJ,fetchAll:()=>L7,destroy:()=>J7,bulkStore:()=>M7,bulkSoftDelete:()=>$7,bulkDestroy:()=>X7});import{db as uJ}from"@stacksjs/database";async function J7(G){try{let J=await uJ.deleteFrom("license_keys").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license key: ${J.message}`);throw J}}async function G7(G){try{let J=await uJ.updateTable("license_keys").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license key: ${J.message}`);throw J}}async function X7(G){if(!G.length)return 0;try{let J=await uJ.deleteFrom("license_keys").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete license keys: ${J.message}`);throw J}}async function $7(G){if(!G.length)return 0;try{let J=await uJ.updateTable("license_keys").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete license keys: ${J.message}`);throw J}}import{db as K7}from"@stacksjs/database";async function nJ(G){return await K7.selectFrom("license_keys").where("id","=",G).selectAll().executeTakeFirst()}async function L7(){return await K7.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:Y7}=globalThis.Bun;import{db as W7}from"@stacksjs/database";async function Z7(G){try{let J={...G,uuid:Y7()},X=await W7.insertInto("license_keys").values(J).executeTakeFirst();if(!X)throw Error("Failed to create license key");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows),K=await nJ($);if(!K)throw Error("Failed to create license key");return K}catch(J){if(J instanceof Error)throw TypeError(`Failed to create license key: ${J.message}`);throw J}}async function M7(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:Y7()})),X=await W7.insertInto("license_keys").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${J.message}`);throw J}}import{db as rG}from"@stacksjs/database";import{formatDate as eG}from"@stacksjs/orm";async function N7(G,J){try{if(!G)throw Error("License key ID is required for update");let X=await rG.updateTable("license_keys").set({...J,updated_at:eG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update license key");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update license key: ${X.message}`);throw X}}async function x7(G,J){try{let X=await rG.updateTable("license_keys").set({status:J,updated_at:eG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update license key status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update license key status: ${X.message}`);throw X}}async function H7(G,J){try{let X={updated_at:eG(new Date)};if(J!==void 0)X.expiry_date=J;let $=await rG.updateTable("license_keys").set(X).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update expiration information");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update expiration information: ${X.message}`);throw X}}var aJ={};B(aJ,{updateStatus:()=>S7,updatePricing:()=>P7,update:()=>T7,store:()=>E7,softDelete:()=>Q7,getActiveShippingMethods:()=>U7,formatShippingOptions:()=>R7,fetchById:()=>i,fetchAll:()=>A7,destroy:()=>F7,bulkStore:()=>O7,bulkSoftDelete:()=>B7,bulkDestroy:()=>V7});import{db as iJ}from"@stacksjs/database";async function F7(G){try{let J=await iJ.deleteFrom("shipping_methods").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping method: ${J.message}`);throw J}}async function Q7(G){try{let J=await iJ.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${J.message}`);throw J}}async function V7(G){if(!G.length)return 0;try{let J=await iJ.deleteFrom("shipping_methods").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping methods: ${J.message}`);throw J}}async function B7(G){if(!G.length)return 0;try{let J=await iJ.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${J.message}`);throw J}}import{db as sJ}from"@stacksjs/database";async function i(G){let J=await sJ.selectFrom("shipping_methods").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=await sJ.selectFrom("shipping_zones").where("shipping_method_id","=",G).selectAll().execute();return{...J,shippingZones:X}}return}async function A7(){let G=await sJ.selectFrom("shipping_methods").selectAll().execute(),J=G.map((L)=>L.id),X=sJ.selectFrom("shipping_zones");if(J.length>0)X=X.where("shipping_method_id","in",J);let K=(await X.selectAll().execute()).reduce((L,Y)=>{let W=Y.shipping_method_id;if(W!==null&&W!==void 0){if(!L[W])L[W]=[];L[W].push(Y)}return L},{});return G.map((L)=>({...L,shipping_zones:K[L.id]||[]}))}var{randomUUIDv7:z7}=globalThis.Bun;import{db as dJ}from"@stacksjs/database";async function E7(G){try{let J=G,X={name:G.name,description:G.description,base_rate:J.base_rate,free_shipping:J.free_shipping,status:G.status,uuid:z7()},$=await dJ.insertInto("shipping_methods").values(X).executeTakeFirst();if(!$)throw Error("Failed to create shipping method");let K=Number($.insertId)||Number($.numInsertedOrUpdatedRows);return await i(K)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping method: ${J.message}`);throw J}}async function O7(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:z7()})),X=await dJ.insertInto("shipping_methods").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${J.message}`);throw J}}function R7(){try{return dJ.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping options: ${G.message}`);throw G}}async function U7(){try{return await dJ.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get active shipping methods: ${G.message}`);throw G}}import{db as JX}from"@stacksjs/database";import{formatDate as GX}from"@stacksjs/orm";async function T7(G,J){try{if(!G)throw Error("Shipping method ID is required for update");let X=await JX.updateTable("shipping_methods").set({...J,updated_at:GX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping method");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping method: ${X.message}`);throw X}}async function S7(G,J){try{let X=await JX.updateTable("shipping_methods").set({status:J,updated_at:GX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping method status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping method status: ${X.message}`);throw X}}async function P7(G,J,X){try{let $={updated_at:GX(new Date)};if(J!==void 0)$.base_rate=J;if(X!==void 0)$.free_shipping=X;let K=await JX.updateTable("shipping_methods").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update pricing information");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update pricing information: ${$.message}`);throw $}}var XG={};B(XG,{validateZoneMatchesAddress:()=>v7,updateByZone:()=>i7,updateByMethod:()=>s7,update:()=>n7,store:()=>c7,resolveZoneForAddress:()=>eJ,getShippingRatesByMethod:()=>g7,getRatesByZone:()=>I7,getRateByWeightAndZone:()=>XX,getRateByWeightAndAddress:()=>f7,formatShippingRateOptions:()=>h7,fetchById:()=>rJ,fetchAll:()=>_7,destroyByZone:()=>k7,destroyByMethod:()=>w7,destroy:()=>q7,bulkUpdate:()=>o7,bulkStore:()=>u7,bulkDestroy:()=>j7});import{db as tJ}from"@stacksjs/database";async function q7(G){try{let J=await tJ.deleteFrom("shipping_rates").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rate: ${J.message}`);throw J}}async function j7(G){if(!G.length)return 0;try{let J=await tJ.deleteFrom("shipping_rates").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates: ${J.message}`);throw J}}async function k7(G){try{let J=await tJ.deleteFrom("shipping_rates").where("zone","=",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${J.message}`);throw J}}async function w7(G){try{let J=await tJ.deleteFrom("shipping_rates").where("method","=",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${J.message}`);throw J}}import{db as C}from"@stacksjs/database";async function rJ(G){let J=await C.selectFrom("shipping_rates").where("id","=",G).selectAll().executeTakeFirst();if(J){let X=null,$=null;if(J.shipping_zone_id)X=await C.selectFrom("shipping_zones").where("id","=",J.shipping_zone_id).selectAll().executeTakeFirst();if(J.shipping_method_id)$=await C.selectFrom("shipping_methods").where("id","=",J.shipping_method_id).selectAll().executeTakeFirst();return{...J,shipping_zone:X,shipping_method:$}}return}async function _7(){let G=await C.selectFrom("shipping_rates").selectAll().execute(),J=G.map((Z)=>Z.shipping_zone_id).filter((Z)=>Z!==null&&Z!==void 0),X=G.map((Z)=>Z.shipping_method_id).filter((Z)=>Z!==null&&Z!==void 0),$=C.selectFrom("shipping_zones"),K=C.selectFrom("shipping_methods");if(J.length>0)$=$.where("id","in",J);if(X.length>0)K=K.where("id","in",X);let L=await $.selectAll().execute(),Y=await K.selectAll().execute(),W=L.reduce((Z,N)=>{return Z[N.id]=N,Z},{}),M=Y.reduce((Z,N)=>{return Z[N.id]=N,Z},{});return G.map((Z)=>({...Z,shipping_zone:Z.shipping_zone_id?W[Z.shipping_zone_id]:[],shipping_method:Z.shipping_method_id?M[Z.shipping_method_id]:[]}))}async function I7(G){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",G).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${J.message}`);throw J}}async function XX(G,J){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",J).where("weight_from","<=",G).where("weight_to",">=",G).executeTakeFirst()}catch(X){if(X instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${X.message}`);throw X}}async function eJ(G){if(!G?.countryCode)return null;try{let J=await C.selectFrom("shipping_zones").selectAll().where("countries","like",`%${G.countryCode}%`).where("status","=","active").execute();if(J.length===0)return null;let X=null;for(let $ of J){let K=1;if(G.region&&$.regions&&C7($.regions,G.region))K=2;if(G.postalCode&&$.postal_codes&&C7($.postal_codes,G.postalCode))K=3;if(!X||K>X.score)X={id:$.id,score:K}}return X?.id??null}catch{return null}}async function f7(G,J){let X=await eJ(J);if(X==null)return;return XX(G,X)}async function v7(G,J){return await eJ(J)===G}function C7(G,J){if(!G||!J)return!1;let X=J.trim().toUpperCase();for(let $ of G.split(/[,|;]/))if($.trim().toUpperCase()===X)return!0;return!1}async function h7(){try{return(await C.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((J)=>J.shipping_method_id!==null&&J.shipping_method_id!==void 0&&J.shipping_zone_id!==null&&J.shipping_zone_id!==void 0)}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping rate options: ${G.message}`);throw G}}async function g7(G){try{return await C.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",G).orderBy("weight_from").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${J.message}`);throw J}}var{randomUUIDv7:m7}=globalThis.Bun;import{db as l7}from"@stacksjs/database";import{db as QJ}from"@stacksjs/database";async function y7(){return await QJ.selectFrom("shipping_zones").selectAll().execute()}async function s(G){return await QJ.selectFrom("shipping_zones").where("id","=",G).selectAll().executeTakeFirst()}function D7(){try{return QJ.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to format shipping zone options: ${G.message}`);throw G}}async function p7(){try{return await QJ.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(G){if(G instanceof Error)throw TypeError(`Failed to get active shipping zones: ${G.message}`);throw G}}async function b7(G){try{return await QJ.selectFrom("shipping_zones").selectAll().where("countries","like",`%${G}%`).where("status","=","active").orderBy("name").execute()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${J.message}`);throw J}}async function c7(G){try{let J=await i(Number(G.shippingmethod_id)),X=await s(Number(G.shippingzone_id)),$={weightFrom:G.weightFrom,weightTo:G.weightTo,rate:G.rate,shippingmethod_id:J?.id,shippingzone_id:X?.id,uuid:m7()},K=await l7.insertInto("shipping_rates").values($).executeTakeFirst();if(!K)throw Error("Failed to create shipping rate");let L=Number(K.insertId)||Number(K.numInsertedOrUpdatedRows);return await rJ(L)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping rate: ${J.message}`);throw J}}async function u7(G){if(!G.length)return 0;try{for(let $ of G){let K=await i(Number($.shippingmethod_id)),L=await s(Number($.shippingzone_id));if(!K)console.warn(`Shipping method with ID "${$.shippingmethod_id}" not found for bulk insert`);if(!L)console.warn(`Shipping zone with ID "${$.shippingzone_id}" not found for bulk insert`)}let J=G.map(($)=>({weightFrom:$.weightFrom,weightTo:$.weightTo,rate:$.rate,shippingmethod_id:$.shippingmethod_id,shippingzone_id:$.shippingzone_id,uuid:m7()})),X=await l7.insertInto("shipping_rates").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${J.message}`);throw J}}import{db as JG}from"@stacksjs/database";import{formatDate as GG}from"@stacksjs/orm";async function n7(G,J){try{if(!G)throw Error("Shipping rate ID is required for update");let X=await JG.updateTable("shipping_rates").set({...J,updated_at:GG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping rate");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rate: ${X.message}`);throw X}}async function o7(G){if(!G.length)return 0;try{let J=0;for(let{id:X,data:$}of G){let K=await JG.updateTable("shipping_rates").set({...$,updated_at:GG(new Date)}).where("id","=",X).executeTakeFirst();if(Number(K.numUpdatedRows)>0)J++}return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${J.message}`);throw J}}async function i7(G,J){try{let X=await JG.updateTable("shipping_rates").set({...J,updated_at:GG(new Date)}).where("zone_id","=",G).executeTakeFirst();return Number(X.numUpdatedRows)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${X.message}`);throw X}}async function s7(G,J){try{let X=await JG.updateTable("shipping_rates").set({...J,updated_at:GG(new Date)}).where("method","=",G).executeTakeFirst();return Number(X.numUpdatedRows)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${X.message}`);throw X}}var YG={};B(YG,{updateStatus:()=>K1,updateRegionsAndPostalCodes:()=>Y1,updateCountries:()=>L1,update:()=>$1,store:()=>G1,softDelete:()=>a7,getZonesByCountry:()=>b7,getActiveShippingZones:()=>p7,formatZoneOptions:()=>D7,fetchById:()=>s,fetchAll:()=>y7,destroy:()=>d7,bulkStore:()=>X1,bulkSoftDelete:()=>r7,bulkDestroy:()=>t7});import{db as $G}from"@stacksjs/database";async function d7(G){try{let J=await $G.deleteFrom("shipping_zones").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zone: ${J.message}`);throw J}}async function a7(G){try{let J=await $G.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",G).executeTakeFirst();return Number(J.numUpdatedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${J.message}`);throw J}}async function t7(G){if(!G.length)return 0;try{let J=await $G.deleteFrom("shipping_zones").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete shipping zones: ${J.message}`);throw J}}async function r7(G){if(!G.length)return 0;try{let J=await $G.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",G).executeTakeFirst();return Number(J.numUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${J.message}`);throw J}}var{randomUUIDv7:e7}=globalThis.Bun;import{db as J1}from"@stacksjs/database";async function G1(G){try{let J={...G,uuid:e7()},X=await J1.insertInto("shipping_zones").values(J).executeTakeFirst();if(!X)throw Error("Failed to create shipping zone");let $=Number(X.insertId)||Number(X.numInsertedOrUpdatedRows);return await s($)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zone: ${J.message}`);throw J}}async function X1(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:e7()})),X=await J1.insertInto("shipping_zones").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${J.message}`);throw J}}import{db as KG}from"@stacksjs/database";import{formatDate as LG}from"@stacksjs/orm";async function $1(G,J){try{if(!G)throw Error("Shipping zone ID is required for update");let X=await KG.updateTable("shipping_zones").set({...J,updated_at:LG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone: ${X.message}`);throw X}}async function K1(G,J){try{let X=await KG.updateTable("shipping_zones").set({status:J,updated_at:LG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone status: ${X.message}`);throw X}}async function L1(G,J){try{let X=await KG.updateTable("shipping_zones").set({countries:J,updated_at:LG(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update shipping zone countries");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${X.message}`);throw X}}async function Y1(G,J,X){try{let $={updated_at:LG(new Date)};if(J!==void 0)$.regions=J;if(X!==void 0)$.postal_codes=X;let K=await KG.updateTable("shipping_zones").set($).where("id","=",G).returningAll().executeTakeFirst();if(!K)throw Error("Failed to update regions and postal codes");return K}catch($){if($ instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${$.message}`);throw $}}var xK={digital:lJ,drivers:cJ,licenses:oJ,methods:aJ,rates:XG,routes:pJ,zones:YG},HK=xK;var YX={};B(YX,{updateStatus:()=>z1,updateRate:()=>E1,update:()=>A1,store:()=>V1,fetchById:()=>x1,fetchAll:()=>H1,destroy:()=>Z1,bulkStore:()=>B1,bulkDestroy:()=>M1});import{db as W1}from"@stacksjs/database";async function Z1(G){try{let J=await W1.deleteFrom("tax_rates").where("id","=",G).executeTakeFirst();return Number(J.numDeletedRows)>0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rate: ${J.message}`);throw J}}async function M1(G){if(!G.length)return 0;try{let J=await W1.deleteFrom("tax_rates").where("id","in",G).executeTakeFirst();return Number(J.numDeletedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete tax rates: ${J.message}`);throw J}}import{db as N1}from"@stacksjs/database";async function x1(G){return await N1.selectFrom("tax_rates").where("id","=",G).selectAll().executeTakeFirst()}async function H1(){return await N1.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:F1}=globalThis.Bun;import{db as Q1}from"@stacksjs/database";async function V1(G){try{let J={...G,uuid:F1()},X=await Q1.insertInto("tax_rates").values(J).returningAll().executeTakeFirst();if(!X)throw Error("Failed to create tax rate");return X}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rate: ${J.message}`);throw J}}async function B1(G){if(!G.length)return 0;try{let J=G.map(($)=>({...$,uuid:F1()})),X=await Q1.insertInto("tax_rates").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${J.message}`);throw J}}import{db as KX}from"@stacksjs/database";import{formatDate as LX}from"@stacksjs/orm";async function A1(G,J){try{if(!G)throw Error("Tax rate ID is required for update");let X=J,$=await KX.updateTable("tax_rates").set({name:J.name,rate:J.rate,type:J.type,country:J.country,region:J.region,status:J.status,is_default:X.is_default,updated_at:LX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update tax rate");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update tax rate: ${X.message}`);throw X}}async function z1(G,J){try{let X=await KX.updateTable("tax_rates").set({status:J,updated_at:LX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update tax rate status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update tax rate status: ${X.message}`);throw X}}async function E1(G,J){try{let X=await KX.updateTable("tax_rates").set({rate:J,updated_at:LX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update rate information");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update rate information: ${X.message}`);throw X}}var MX={};B(MX,{restaurant:()=>$J,products:()=>ZG,default:()=>QK});var ZG={};B(ZG,{updateStatus:()=>m1,updatePartySize:()=>l1,update:()=>b1,store:()=>D1,fetchWaiting:()=>_1,fetchPurchasedBetweenDates:()=>w1,fetchNotifiedBetweenDates:()=>k1,fetchCountByStatus:()=>I1,fetchCountBySource:()=>S1,fetchCountByQuantity:()=>q1,fetchCountByDateGrouped:()=>h1,fetchCountByDate:()=>P1,fetchCountByAllQuantities:()=>j1,fetchCountBetweenDates:()=>v1,fetchConversionRates:()=>f1,fetchCancelledBetweenDates:()=>C1,fetchById:()=>U1,fetchAll:()=>T1,destroy:()=>O1,bulkStore:()=>p1,bulkDestroy:()=>R1});import{db as WG}from"@stacksjs/database";async function O1(G){try{let J=await WG.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst();if(!J)return;return await WG.deleteFrom("waitlist_products").where("id","=",G).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist product: ${J.message}`);throw J}}async function R1(G){if(!G.length)return 0;try{return(await WG.deleteFrom("waitlist_products").where("id","in",G).execute()).length||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${J.message}`);throw J}}import{db as A}from"@stacksjs/database";import{formatDate as S}from"@stacksjs/orm";async function U1(G){return await A.selectFrom("waitlist_products").where("id","=",G).selectAll().executeTakeFirst()}async function T1(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function S1(G,J){let X=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(G&&J){let K=S(G),L=S(J);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.execute()).reduce((K,{source:L,count:Y})=>{return K[L]=Y,K},{})}async function P1(G=new Date){let J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=S(J),K=S(X);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function q1(G){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",G).executeTakeFirst())?.count??0}async function j1(G,J){let X=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(G&&J){let K=S(G),L=S(J);X=X.where("created_at",">=",K).where("created_at","<=",L)}return(await X.execute()).reduce((K,{quantity:L,count:Y})=>{return K[L]=Y,K},{})}async function k1(G,J){let X=S(G),$=S(J);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",X).where("notified_at","<=",$).where("notified_at","is not",null).execute()}async function w1(G,J){let X=S(G),$=S(J);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",X).where("purchased_at","<=",$).where("purchased_at","is not",null).execute()}async function C1(G,J){let X=S(G),$=S(J);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",X).where("cancelled_at","<=",$).where("cancelled_at","is not",null).execute()}async function _1(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function I1(G,J,X){let $=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",G);if(J&&X){let L=S(J),Y=S(X);$=$.where("created_at",">=",L).where("created_at","<=",Y)}return(await $.executeTakeFirst())?.count??0}async function f1(G,J){let X=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(G&&J){let M=S(G),Z=S(J);X=X.where("created_at",">=",M).where("created_at","<=",Z)}let $=await X.execute(),K=$.reduce((M,{count:Z})=>M+Z,0),L=$.find((M)=>M.status==="purchased")?.count??0,Y=K>0?L/K*100:0,W=$.reduce((M,{status:Z,count:N})=>{return M[Z]={count:N,percentage:K>0?N/K*100:0},M},{});return{totalConversionRate:Y,statusBreakdown:W}}async function v1(G,J){let X=S(G),$=S(J);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",$).executeTakeFirst())?.count??0}async function h1(G,J){let X=A.selectFrom("waitlist_products").select(["created_at"]);if(G&&J){let L=S(G),Y=S(J);X=X.where("created_at",">=",L).where("created_at","<=",Y)}let K=(await X.execute()).reduce((L,{created_at:Y})=>{let W=(Y||"").split("T")[0]||"unknown";return L[W]=(L[W]||0)+1,L},{});return Object.entries(K).map(([L,Y])=>({date:L,count:Y})).sort((L,Y)=>L.date.localeCompare(Y.date))}var{randomUUIDv7:g1}=globalThis.Bun;import{db as y1}from"@stacksjs/database";import{formatDate as XJ}from"@stacksjs/orm";async function D1(G){try{let J=G,X={name:G.name,email:G.email,phone:G.phone,quantity:G.quantity??J.party_size,notification_preference:J.notification_preference,source:G.source,notes:G.notes,product_id:G.product_id,customer_id:G.customer_id,uuid:g1(),status:G.status||"waiting"};if(G.notified_at!==void 0)X.notified_at=typeof G.notified_at==="number"?XJ(G.notified_at):G.notified_at;if(G.purchased_at!==void 0)X.purchased_at=typeof G.purchased_at==="number"?XJ(G.purchased_at):G.purchased_at;if(G.cancelled_at!==void 0)X.cancelled_at=typeof G.cancelled_at==="number"?XJ(G.cancelled_at):G.cancelled_at;let $=await y1.insertInto("waitlist_products").values(X).returningAll().executeTakeFirst();if(!$)throw Error("Failed to create waitlist product");return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist product: ${J.message}`);throw J}}async function p1(G){if(!G.length)return 0;try{let J=G.map(($)=>{let K=$,L={name:$.name,email:$.email,phone:$.phone,quantity:$.quantity??K.party_size,notification_preference:K.notification_preference,source:$.source,notes:$.notes,product_id:$.product_id,customer_id:$.customer_id,uuid:g1(),status:$.status||"waiting"};if($.notified_at!==void 0)L.notified_at=typeof $.notified_at==="number"?XJ($.notified_at):$.notified_at;if($.purchased_at!==void 0)L.purchased_at=typeof $.purchased_at==="number"?XJ($.purchased_at):$.purchased_at;if($.cancelled_at!==void 0)L.cancelled_at=typeof $.cancelled_at==="number"?XJ($.cancelled_at):$.cancelled_at;return L}),X=await y1.insertInto("waitlist_products").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${J.message}`);throw J}}import{db as WX}from"@stacksjs/database";import{formatDate as ZX}from"@stacksjs/orm";async function b1(G,J){try{if(!G)throw Error("Waitlist product ID is required for update");let X=J,$=await WX.updateTable("waitlist_products").set({name:J.name,email:J.email,phone:J.phone,quantity:J.quantity??X.party_size,notification_preference:X.notification_preference,source:J.source,notes:J.notes,status:J.status,product_id:J.product_id,customer_id:J.customer_id,notified_at:X.notified_at,purchased_at:X.purchased_at,cancelled_at:X.cancelled_at,updated_at:ZX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update waitlist product");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update waitlist product: ${X.message}`);throw X}}async function m1(G,J){try{let X=await WX.updateTable("waitlist_products").set({status:J,updated_at:ZX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update waitlist product status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update waitlist product status: ${X.message}`);throw X}}async function l1(G,J){try{let X=await WX.updateTable("waitlist_products").set({quantity:J,updated_at:ZX(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update party size");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update party size: ${X.message}`);throw X}}var $J={};B($J,{updateWaitTimes:()=>z9,updateStatus:()=>B9,updateQueuePosition:()=>E9,updatePartySize:()=>A9,update:()=>V9,store:()=>F9,fetchWaitingWithQuotedTimes:()=>X9,fetchWaitingWithPartySizes:()=>$9,fetchWaiting:()=>e1,fetchTimeSeriesStats:()=>M9,fetchTablesTurnedToday:()=>K9,fetchSeatingRate:()=>L9,fetchSeatedStats:()=>Z9,fetchSeatedBetweenDates:()=>r1,fetchNoShowStats:()=>Y9,fetchCurrentWaitTimes:()=>W9,fetchCountByTablePreference:()=>i1,fetchCountByPartySize:()=>d1,fetchCountByDate:()=>s1,fetchCountByAllPartySizes:()=>a1,fetchConversionRates:()=>J9,fetchById:()=>n1,fetchBetweenDates:()=>t1,fetchAverageWaitTimes:()=>G9,fetchAll:()=>o1,destroy:()=>c1,bulkStore:()=>Q9,bulkDestroy:()=>u1});import{db as MG}from"@stacksjs/database";async function c1(G){try{let J=await MG.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst();if(!J)return;return await MG.deleteFrom("waitlist_restaurants").where("id","=",G).execute(),J}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${J.message}`);throw J}}async function u1(G){if(!G.length)return 0;try{return(await MG.deleteFrom("waitlist_restaurants").where("id","in",G).execute()).length||0}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as Q}from"@stacksjs/database";import{formatDate as k}from"@stacksjs/orm";async function n1(G){return await Q.selectFrom("waitlist_restaurants").where("id","=",G).selectAll().executeTakeFirst()}async function o1(){return await Q.selectFrom("waitlist_restaurants").selectAll().execute()}async function i1(){return(await Q.selectFrom("waitlist_restaurants").select(["table_preference",Q.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((J,{table_preference:X,count:$})=>{return J[X]=$,J},{})}async function s1(G=new Date){let J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=k(J),K=k(X);return(await Q.selectFrom("waitlist_restaurants").select(Q.fn.count("id").as("count")).where("created_at",">=",$).where("created_at","<=",K).executeTakeFirst())?.count??0}async function d1(G){return(await Q.selectFrom("waitlist_restaurants").select(Q.fn.count("id").as("count")).where("party_size","=",G).executeTakeFirst())?.count??0}async function a1(){return(await Q.selectFrom("waitlist_restaurants").select(["party_size",Q.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((J,{party_size:X,count:$})=>{return J[X]=$,J},{})}async function t1(G,J){let X=k(G),$=k(J);return await Q.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",X).where("created_at","<=",$).execute()}async function r1(G,J){let X=k(G),$=k(J);return await Q.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",X).where("check_in_time","<=",$).where("status","=","seated").execute()}async function e1(){return await Q.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function J9(){let G=await Q.selectFrom("waitlist_restaurants").select(["status",Q.fn.count("id").as("count")]).groupBy("status").execute(),J=G.reduce((L,{count:Y})=>L+Y,0),X=G.find((L)=>L.status==="seated")?.count??0,$=J>0?Number(X)/J*100:0,K=G.reduce((L,{status:Y,count:W})=>{return L[Y]={count:W,percentage:J>0?W/J*100:0},L},{});return{totalConversionRate:$,statusBreakdown:K}}async function G9(){let G=await Q.selectFrom("waitlist_restaurants").select([Q.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),Q.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:G?.avg_quoted_wait_time??0,averageActualWaitTime:G?.avg_actual_wait_time??0}}async function X9(){let G=await Q.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=G.reduce(($,K)=>$+(K.quoted_wait_time??0),0),X=G.length>0?J/G.length:0;return{entries:G,totalQuotedWaitTime:J,averageQuotedWaitTime:X}}async function $9(){let G=await Q.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),J=G.reduce((K,L)=>K+L.party_size,0),X=G.length>0?J/G.length:0,$=G.reduce((K,L)=>{return K[L.party_size]=(K[L.party_size]||0)+1,K},{});return{entries:G,totalPartySize:J,averagePartySize:X,partySizeBreakdown:$}}async function K9(){let G=new Date,J=new Date(G);J.setHours(0,0,0,0);let X=new Date(G);X.setHours(23,59,59,999);let $=k(J),K=k(X),L=await Q.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",$).where("check_in_time","<=",K).execute(),Y=L.length,W=L.reduce((x,F)=>x+F.party_size,0),M=Y>0?W/Y:0,Z=L.reduce((x,F)=>{return x[F.table_preference]=(x[F.table_preference]||0)+1,x},{}),N=L.reduce((x,F)=>{return x[F.party_size]=(x[F.party_size]||0)+1,x},{});return{totalTablesTurned:Y,averagePartySize:M,totalCustomersSeated:W,breakdownByTablePreference:Z,breakdownByPartySize:N}}async function L9(G,J){let X=k(G),$=k(J),K=await Q.selectFrom("waitlist_restaurants").select(["status",Q.fn.count("id").as("count")]).where("check_in_time",">=",X).where("check_in_time","<=",$).groupBy("status").execute(),L=K.reduce((Z,{count:N})=>Z+N,0),Y=K.find((Z)=>Z.status==="seated")?.count??0,W=L>0?Number(Y)/L*100:0,M=K.reduce((Z,{status:N,count:x})=>{return Z[N]={count:x,percentage:L>0?x/L*100:0},Z},{});return{totalEntries:L,seatedEntries:Y,seatingRate:W,statusBreakdown:M}}async function Y9(G,J){let X=k(G),$=k(J),K=Q.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",X).where("check_in_time","<=",$),L=await Q.selectFrom("waitlist_restaurants").select(Q.fn.count("id").as("count")).where("check_in_time",">=",X).where("check_in_time","<=",$).executeTakeFirst(),Y=await K.execute(),W=Y.length,M=L?.count&&L.count>0?W/L.count*100:0,Z=Y.reduce((z,O)=>z+(O.quoted_wait_time??0),0),N=W>0?Z/W:0,x=Y.reduce((z,O)=>z+O.party_size,0),F=W>0?x/W:0,T=Y.reduce((z,O)=>{return z[O.table_preference]=(z[O.table_preference]||0)+1,z},{}),E=Y.reduce((z,O)=>{return z[O.party_size]=(z[O.party_size]||0)+1,z},{});return{totalNoShows:W,noShowRate:M,averageQuotedWaitTime:N,averagePartySize:F,breakdownByTablePreference:T,breakdownByPartySize:E}}async function W9(){let G=await Q.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),J=G.reduce((K,L)=>K+(L.quoted_wait_time||0),0),X=G.reduce((K,L)=>K+(L.actual_wait_time||0),0),$=G.length;return{averageQuoted:$>0?J/$:0,averageActual:$>0?X/$:0}}async function Z9(){let G=Date.now()-86400000,J=await Q.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",G).execute(),X=Array.from({length:24},($,K)=>({hour:K,count:J.filter((L)=>{return L.seated_at===K}).length}));return{total:J.length,byHour:X}}async function M9(){return(await Q.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((J,X)=>{let $=X.created_at;if(!J[$])J[$]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return J[$].total++,J[$][X.status]++,J},{})}var{randomUUIDv7:N9}=globalThis.Bun;import{db as x9}from"@stacksjs/database";import{formatDate as H9}from"@stacksjs/orm";async function F9(G){try{let J=G,X={name:G.name,email:G.email,phone:G.phone,party_size:J.party_size,check_in_time:typeof J.check_in_time==="number"?H9(J.check_in_time):J.check_in_time,table_preference:J.table_preference,status:G.status||"waiting",quoted_wait_time:G.quoted_wait_time,actual_wait_time:G.actual_wait_time,queue_position:G.queue_position,customer_id:G.customer_id,uuid:N9()},$={};for(let[Y,W]of Object.entries(X))if(W!==void 0)$[Y]=W;let K=await x9.insertInto("waitlist_restaurants").values($).returningAll().executeTakeFirst();if(!K)throw Error("Failed to create restaurant waitlist entry");let L={...K};for(let Y of Object.keys(L))if(L[Y]===null)L[Y]=void 0;return L}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${J.message}`);throw J}}async function Q9(G){if(!G.length)return 0;try{let J=G.map(($)=>{let K=$;return{name:$.name,email:$.email,phone:$.phone,party_size:K.party_size,check_in_time:typeof K.check_in_time==="number"?H9(K.check_in_time):K.check_in_time,table_preference:K.table_preference,status:$.status||"waiting",quoted_wait_time:$.quoted_wait_time,actual_wait_time:$.actual_wait_time,queue_position:$.queue_position,customer_id:$.customer_id,uuid:N9()}}),X=await x9.insertInto("waitlist_restaurants").values(J).executeTakeFirst();return Number(X.numInsertedOrUpdatedRows)}catch(J){if(J instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${J.message}`);throw J}}import{db as VJ}from"@stacksjs/database";import{formatDate as BJ}from"@stacksjs/orm";async function V9(G,J){try{if(!G)throw Error("Restaurant waitlist entry ID is required for update");let X=J,$=await VJ.updateTable("waitlist_restaurants").set({name:J.name,email:J.email,phone:J.phone,party_size:X.party_size,check_in_time:X.check_in_time?Math.floor(new Date(X.check_in_time).getTime()/1000):void 0,table_preference:X.table_preference,status:J.status,quoted_wait_time:J.quoted_wait_time,actual_wait_time:J.actual_wait_time,queue_position:J.queue_position,customer_id:J.customer_id,updated_at:BJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update restaurant waitlist entry");return $}catch(X){if(X instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${X.message}`);throw X}}async function B9(G,J){try{let X=await VJ.updateTable("waitlist_restaurants").set({status:J,updated_at:BJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update restaurant waitlist entry status");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry status: ${X.message}`);throw X}}async function A9(G,J){try{let X=await VJ.updateTable("waitlist_restaurants").set({party_size:J,updated_at:BJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update party size");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update party size: ${X.message}`);throw X}}async function z9(G,J,X){try{let $=await VJ.updateTable("waitlist_restaurants").set({quoted_wait_time:J,actual_wait_time:X,updated_at:BJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!$)throw Error("Failed to update wait times");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update wait times: ${$.message}`);throw $}}async function E9(G,J){try{let X=await VJ.updateTable("waitlist_restaurants").set({queue_position:J,updated_at:BJ(new Date)}).where("id","=",G).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update queue position");return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update queue position: ${X.message}`);throw X}}var FK={products:ZG,restaurant:$J},QK=FK;var VK={coupons:NG,customers:HG,devices:BG,errors:EG,giftCards:UG,orders:fG,payments:vG,products:lG,receipts:nG,restaurant:$J,shippings:$X,tax:YX,waitlists:MX},eZ=VK;export{MX as waitlists,YX as tax,$X as shippings,$J as restaurant,nG as receipts,lG as products,vG as payments,fG as orders,UG as giftCards,EG as errors,BG as devices,eZ as default,HG as customers,NG as coupons,VK as commerce};
16
+ AND current_balance + ? >= 0`,[$,J,$,J,N,$]),X=typeof G?.execute==="function"?await G.execute():G;if(Number(X?.changes??X?.numUpdatedRows??X?.affectedRows??0)>0)return await a(N);let W=await a(N);if(!W)throw Error(`Gift card with ID ${N} not found`);if(!W.is_active||W.status!=="ACTIVE")throw Error("Gift card is not active");throw Error("Insufficient gift card balance")}var Y1={};B(Y1,{validateQuantityBounds:()=>W1,validateCouponStacking:()=>eN,validateCartQuantities:()=>tN,updateStatus:()=>uN,updateDeliveryInfo:()=>iN,update:()=>nN,storeOrdersExport:()=>fN,store:()=>yN,softDelete:()=>wN,registerCommerceWebhookHandlers:()=>sN,recomputeOrderTotals:()=>aN,placeOrder:()=>cN,handlePaymentIntentSucceeded:()=>G1,handlePaymentIntentFailed:()=>X1,handleChargeRefunded:()=>L1,findOrderByIdempotencyKey:()=>a0,fetchStats:()=>jN,fetchDailyOrderTrends:()=>hN,fetchById:()=>m,fetchAll:()=>kN,exportOrders:()=>u0,emitOrderShipped:()=>e$,emitOrderRefunded:()=>B0,emitOrderPaid:()=>e,emitOrderDelivered:()=>t$,emitOrderCreated:()=>o0,emitOrderCancelled:()=>z0,emitForStatus:()=>s0,downloadOrders:()=>qN,destroy:()=>TN,compareOrdersByPeriod:()=>CN,cleanupAbandonedCarts:()=>rN,canTransition:()=>i0,calculateOrderMetrics:()=>IN,bulkSoftDelete:()=>EN,bulkDestroy:()=>UN});import{db as n0}from"@stacksjs/database";async function TN(N){try{let $=await n0.deleteFrom("orders").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function wN(N){try{let $=await n0.updateTable("orders").set({status:"CANCELED"}).where("id","=",N).executeTakeFirst();return Number($.numUpdatedRows)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete order: ${$.message}`);throw $}}async function UN(N){if(!N.length)return 0;try{let $=await n0.deleteFrom("orders").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}async function EN(N){if(!N.length)return 0;try{let $=await n0.updateTable("orders").set({status:"CANCELED"}).where("id","in",N).executeTakeFirst();return Number($.numUpdatedRows)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete orders: ${$.message}`);throw $}}import{db as PN}from"@stacksjs/database";import{createSpreadsheet as h3}from"ts-spreadsheets";async function u0(N="csv"){let $=await g3(),J=v3($);return h3(J,{type:N})}async function g3(){let N=await PN.selectFrom("orders").leftJoin("customers","customers.id","=","orders.customer_id").selectAll().select(["customers.name as customer_name","customers.email as customer_email"]).execute(),$=N.map((L)=>L.id);if($.length===0)return[];let G=(await PN.selectFrom("order_items").where("order_items.order_id","in",$).select(["order_items.order_id","order_items.quantity","order_items.price"]).execute()).reduce((L,W)=>{if(!W.order_id)return L;if(!L[W.order_id])L[W.order_id]={totalItems:0,totalPrice:0};return L[W.order_id].totalItems+=W.quantity,L[W.order_id].totalPrice+=W.price*W.quantity,L},{});return N.map((L)=>{let W=G[L.id]||{totalItems:0,totalPrice:0};return{...L,totalItems:W.totalItems,totalPrice:W.totalPrice}})}function v3(N){let $=["Order ID","Customer","Date","Total","Status","Items"],J=N.map((G)=>{let X=G.order_items?.map((L)=>`${L.product?.name} (Qty: ${L.quantity}, Price: $${L.price})`).join(" | ")||"No Items";return[G.id,G.customer?.name||"N/A",G.created_at,G.total_amount,G.status,X]});return{headings:$,data:J}}async function qN(N="csv",$){let J=await u0(N),G=`orders_export_${new Date().toISOString().split("T")[0]}.${N}`;return J.download($||G)}async function fN(N="csv",$){let J=await u0(N),G=`orders_export_${new Date().toISOString().split("T")[0]}.${N}`;J.store($||G)}import{db as z}from"@stacksjs/database";async function kN(N){let $=z.selectFrom("orders").selectAll().orderBy("created_at","desc");if(N)$=$.limit(N);let J=await $.execute();return await Promise.all(J.map(async(G)=>{let X=await z.selectFrom("order_items").where("order_id","=",G.id).selectAll().execute();return{...G,items:X}}))}async function m(N){return await z.selectFrom("orders").where("id","=",N).selectAll().executeTakeFirst()}async function jN(){let N=await z.selectFrom("orders").select(z.fn.count("id").as("count")).executeTakeFirst(),$=await z.selectFrom("orders").select(["status",z.fn.count("id").as("count")]).groupBy("status").execute(),J=await z.selectFrom("orders").select(["order_type",z.fn.count("id").as("count")]).groupBy("order_type").execute(),G=await z.selectFrom("orders").selectAll().orderBy("created_at","desc").limit(5).execute(),X=await Promise.all(G.map(async(W)=>{let Y=await z.selectFrom("order_items").where("order_id","=",W.id).selectAll().execute();return{...W,items:Y}})),L=await z.selectFrom("orders").select(z.fn.sum("total_amount").as("total")).executeTakeFirst();return{total:Number(N?.count||0),by_status:$,by_type:J,recent:X,revenue:Number(L?.total||0)}}async function CN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await z.selectFrom("orders").select(z.fn.count("id").as("count")).where("created_at",">=",J.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=await z.selectFrom("orders").select(z.fn.count("id").as("count")).where("created_at",">=",X.toISOString()).where("created_at","<=",G.toISOString()).executeTakeFirst(),Y=Number(L?.count||0),Z=Number(W?.count||0),M=Y-Z,K=Z!==0?M/Z*100:Y>0?100:0;return{current_period:Y,previous_period:Z,difference:M,percentage_change:K,days_range:N}}async function IN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await z.selectFrom("orders").select([z.fn.count("id").as("total_orders"),z.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",J.toISOString()).where("created_at","<=",$.toISOString()).executeTakeFirst(),W=await z.selectFrom("orders").select([z.fn.count("id").as("total_orders"),z.fn.sum("total_amount").as("total_revenue")]).where("created_at",">=",X.toISOString()).where("created_at","<=",G.toISOString()).executeTakeFirst(),Y=await z.selectFrom("orders").select(["status",z.fn.count("id").as("count")]).where("created_at",">=",J.toISOString()).where("created_at","<=",$.toISOString()).groupBy("status").execute(),Z=await z.selectFrom("orders").select(["order_type",z.fn.count("id").as("count")]).where("created_at",">=",J.toISOString()).where("created_at","<=",$.toISOString()).groupBy("order_type").execute(),M=Number(L?.total_orders||0),K=Number(L?.total_revenue||0),Q=M>0?K/M:0,x=Number(W?.total_orders||0),R=Number(W?.total_revenue||0),O=x>0?R/x:0,_=M-x,S=K-R,D=Q-O,o=x!==0?_/x*100:M>0?100:0,s=R!==0?S/R*100:K>0?100:0,J0=O!==0?D/O*100:Q>0?100:0;return{current_period:{total_orders:M,total_revenue:K,average_order_value:Q,orders_by_status:Y.map((p)=>({status:p.status,count:Number(p.count)})),orders_by_type:Z.map((p)=>({order_type:p.order_type,count:Number(p.count)}))},previous_period:{total_orders:x,total_revenue:R,average_order_value:O},comparison:{orders:{difference:_,percentage:Math.abs(o),is_increase:_>=0},revenue:{difference:S,percentage:Math.abs(s),is_increase:S>=0},average_order_value:{difference:D,percentage:Math.abs(J0),is_increase:D>=0}},days_range:N}}async function hN(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=await z.selectFrom("orders").select(["created_at","total_amount"]).where("created_at",">=",J.toISOString()).where("created_at","<=",$.toISOString()).orderBy("created_at","asc").execute(),X=new Map;for(let L of G){let W=(L.created_at||"").split("T")[0]||"unknown",Y=X.get(W)||{order_count:0,revenue:0};Y.order_count++,Y.revenue+=Number(L.total_amount||0),X.set(W,Y)}return Array.from(X.entries()).map(([L,W])=>({date:L,order_count:W.order_count,revenue:W.revenue}))}var{randomUUIDv7:y3}=globalThis.Bun;import{db as gN}from"@stacksjs/database";import{formatDate as vN}from"@stacksjs/orm";async function yN(N){let $={...N,status:N.status||"PENDING",uuid:y3(),created_at:vN(new Date),updated_at:vN(new Date)};try{let J=await gN.insertInto("orders").values($).executeTakeFirst(),G=Number(J?.insertId)||Number(J?.numInsertedOrUpdatedRows);if(G)return await gN.selectFrom("orders").where("id","=",G).selectAll().executeTakeFirst();return}catch(J){if(J instanceof Error)throw Error(`Failed to create order: ${J.message}`);throw J}}var{randomUUIDv7:pN}=globalThis.Bun;import{db as d0}from"@stacksjs/database";import{formatDate as l3,isUniqueViolation as bN}from"@stacksjs/orm";var D3={PENDING:["PROCESSING","CANCELLED"],PROCESSING:["SHIPPED","CANCELLED","REFUNDED"],SHIPPED:["DELIVERED","REFUNDED"],DELIVERED:["REFUNDED"],CANCELLED:["PROCESSING"],REFUNDED:[]};function i0(N,$){if(N===$)return!0;return D3[N]?.includes($)??!1}async function X0(N,$){try{let J=await import("@stacksjs/events").catch(()=>null);if(!J)return;let G=J.dispatch;if(typeof G!=="function")return;G(N,$)}catch{}}async function o0(N){await X0("order:created",{order:N})}async function e(N,$){await X0("order:paid",{order:N,payment:$})}async function e$(N){await X0("order:shipped",{order:N})}async function t$(N){await X0("order:delivered",{order:N})}async function z0(N,$){await X0("order:cancelled",{order:N,reason:$})}async function B0(N,$){await X0("order:refunded",{order:N,refundAmount:$})}async function s0(N,$){switch(N){case"PROCESSING":return e($);case"SHIPPED":return e$($);case"DELIVERED":return t$($);case"CANCELLED":return z0($);case"REFUNDED":return B0($);case"PENDING":default:}}import{sqlHelpers as p3}from"@stacksjs/database";import{env as b3}from"@stacksjs/env";function m3(N,$,J,G){let X=p3(N).param;return{query:`UPDATE products
17
+ SET inventory_count = inventory_count + ${X(1)},
18
+ updated_at = ${X(2)}
19
+ WHERE id = ${X(3)}
20
+ AND inventory_count + ${X(4)} >= 0`,parameters:[J,G,$,J]}}async function DN(N,$,J,G){let X=m3(b3.DB_CONNECTION||"sqlite",$,J,G),L=await N.unsafe(X.query,X.parameters),W=typeof L?.execute==="function"?await L.execute():L;return F(W)}var mN=!1;function lN(N){let $=N,J=$?.message??"";return $?.code==="42P01"||J.includes("no such table")||J.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(J)}async function a0(N){try{let $=await d0.selectFrom("order_idempotency").where("idempotency_key","=",N).selectAll().executeTakeFirst();if(!$)return null;return await d0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}catch($){if(lN($)){if(!mN)mN=!0,console.warn("[commerce/orders] order_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.");return null}throw $}}async function cN(N){if(N.idempotencyKey){let $=await a0(N.idempotencyKey);if($)return{ok:!0,order:$}}try{let $=await d0.transaction(async(J)=>{let G=l3(new Date),X=pN(),L={...N.order,status:N.order.status||"PENDING",uuid:X,created_at:G,updated_at:G};await J.insertInto("orders").values(L).executeTakeFirst();let W=await J.selectFrom("orders").where("uuid","=",X).selectAll().executeTakeFirst(),Y=Number(W?.id);if(!Number.isSafeInteger(Y)||Y<=0)throw Object.assign(Error("order insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"order",reason:"unknown"});let Z;if(N.items&&N.items.length>0){let Q=N.items.map((x)=>{if(!Number.isInteger(x.productId)||x.productId<=0)throw Object.assign(Error("order item product id must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isInteger(x.quantity)||x.quantity<=0)throw Object.assign(Error("order item quantity must be a positive integer"),{__placeFail:!0,failedAt:"items",reason:"unknown"});if(!Number.isFinite(x.price)||x.price<0)throw Object.assign(Error("order item price must be a non-negative finite number"),{__placeFail:!0,failedAt:"items",reason:"unknown"});return{order_id:Y,product_id:x.productId,quantity:x.quantity,price:x.price,special_instructions:x.specialInstructions||null,created_at:G,updated_at:G}});await J.insertInto("order_items").values(Q).execute(),Z=await J.selectFrom("order_items").where("order_id","=",Y).selectAll().execute()}let M;if(N.payment)try{let Q=pN();if(await J.insertInto("payments").values({...N.payment,order_id:Y,uuid:Q,created_at:G,updated_at:G}).executeTakeFirst(),M=await J.selectFrom("payments").where("uuid","=",Q).selectAll().executeTakeFirst(),!M)throw Object.assign(Error("payment insert could not be resolved by uuid"),{__placeFail:!0,failedAt:"payment",reason:"unknown"})}catch(Q){if(bN(Q))throw Object.assign(Error("duplicate payment transaction_id"),{__placeFail:!0,failedAt:"payment",reason:"duplicate-payment"});throw Object.assign(Q,{__placeFail:!0,failedAt:"payment",reason:"unknown"})}if(N.inventory&&N.inventory.length>0)for(let Q=0;Q<N.inventory.length;Q++){let{id:x,delta:R}=N.inventory[Q];if(!Number.isFinite(R)||R===0)throw Object.assign(Error("inventory delta must be a non-zero finite number"),{__placeFail:!0,failedAt:"inventory",reason:"unknown"});if(!await DN(J,x,R,G))throw Object.assign(Error(`inventory adjust failed for product ${x}`),{__placeFail:!0,failedAt:"inventory",reason:"out-of-stock"})}if(N.idempotencyKey)try{await J.insertInto("order_idempotency").values({idempotency_key:N.idempotencyKey,order_id:Y,created_at:G}).execute()}catch(Q){if(bN(Q))throw Object.assign(Error("idempotency-key collision"),{__placeFail:!0,failedAt:"idempotency",reason:"duplicate-idempotency-key"});if(!lN(Q))throw Q}let K=await J.selectFrom("orders").where("id","=",Y).selectAll().executeTakeFirst();if(!K)throw Object.assign(Error("order disappeared mid-transaction"),{__placeFail:!0,failedAt:"order",reason:"unknown"});return{order:K,items:Z,payment:M}});if(o0($.order),$.payment)e($.order,$.payment);return{ok:!0,order:$.order,items:$.items,payment:$.payment}}catch($){if($?.__placeFail){if($.reason==="duplicate-idempotency-key"&&N.idempotencyKey){let J=await a0(N.idempotencyKey);if(J)return{ok:!0,order:J}}return{ok:!1,reason:$.reason,failedAt:$.failedAt,error:$}}throw $}}import{db as r$}from"@stacksjs/database";import{formatDate as $1}from"@stacksjs/orm";async function nN(N,$){if(!await m(N))return;try{return await r$.updateTable("orders").set({...$,updated_at:$1(new Date)}).where("id","=",N).execute(),await m(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update order: ${G.message}`);throw G}}async function uN(N,$){let J=await m(N);if(!J)throw Error(`Order with ID ${N} not found`);let G=J.status??"PENDING";if(!i0(G,$))throw Error(`[commerce/orders] illegal status transition ${G} \u2192 ${$}`);try{await r$.updateTable("orders").set({status:$,updated_at:$1(new Date)}).where("id","=",N).execute();let X=await m(N);if(X)s0($,X);return X}catch(X){if(X instanceof Error)throw TypeError(`Failed to update order status: ${X.message}`);throw X}}async function iN(N,$,J){let G=await m(N);if(!G)throw Error(`Order with ID ${N} not found`);let X={updated_at:$1(new Date)};if($!==void 0)X.delivery_address=$;if(J!==void 0)X.estimated_delivery_time=J;if(Object.keys(X).length===1)return G;try{return await r$.updateTable("orders").set(X).where("id","=",N).execute(),await m(N)}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery information: ${L.message}`);throw L}}import{db as L0}from"@stacksjs/database";import{formatDate as e0}from"@stacksjs/orm";async function N1(N){let $=await L0.selectFrom("payments").where("transaction_id","=",N).selectAll().executeTakeFirst();if(!$)return null;return await L0.selectFrom("orders").where("id","=",$.order_id).selectAll().executeTakeFirst()??null}var oN=!1;function c3(N){let $=N,J=$?.message??"";return $?.code==="42P01"||J.includes("no such table")||J.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(J)}async function J1(N,$){try{return await $.insertInto("stripe_webhook_events").values({event_id:N,processed_at:e0(new Date)}).execute(),!0}catch(J){if(J?.message?.includes("UNIQUE constraint")||J?.message?.includes("Duplicate entry"))return!1;if(c3(J)){if(!oN)oN=!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 J}}async function G1(N){let J=N.data.object?.id;if(!J)return;await L0.transaction(async(X)=>{if(!await J1(N.id,X))return;let W=await X.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!W)return;let Y=e0(new Date);await X.updateTable("payments").set({status:"succeeded",updated_at:Y}).where("id","=",W.id).execute();let Z=await X.selectFrom("orders").where("id","=",W.order_id).selectAll().executeTakeFirst();if(Z&&Z.status==="PENDING")await X.updateTable("orders").set({status:"PROCESSING",updated_at:Y}).where("id","=",Z.id).execute()});let G=await N1(J);if(G)await e(G)}async function X1(N){let $=N.data.object,J=$?.id;if(!J)return;let X=$?.last_payment_error?.message??"payment failed";await L0.transaction(async(W)=>{if(!await J1(N.id,W))return;let Z=await W.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!Z)return;let M=e0(new Date);await W.updateTable("payments").set({status:"failed",failure_reason:X,updated_at:M}).where("id","=",Z.id).execute();let K=await W.selectFrom("orders").where("id","=",Z.order_id).selectAll().executeTakeFirst();if(K&&K.status==="PENDING")await W.updateTable("orders").set({status:"CANCELLED",updated_at:M}).where("id","=",K.id).execute()});let L=await N1(J);if(L)await z0(L,X)}async function L1(N){let $=N.data.object,J=$?.payment_intent;if(!J)return;let G=$?.amount_refunded??0;await L0.transaction(async(L)=>{if(!await J1(N.id,L))return;let Y=await L.selectFrom("payments").where("transaction_id","=",J).selectAll().executeTakeFirst();if(!Y)return;let Z=e0(new Date);await L.updateTable("payments").set({status:"refunded",refund_amount:G,updated_at:Z}).where("id","=",Y.id).execute();let M=await L.selectFrom("orders").where("id","=",Y.order_id).selectAll().executeTakeFirst();if(M&&M.status!=="REFUNDED")await L.updateTable("orders").set({status:"REFUNDED",updated_at:Z}).where("id","=",M.id).execute()});let X=await N1(J);if(X)await B0(X,G)}async function sN(){let N=await import("@stacksjs/payments").catch(()=>null);if(!N)return console.warn("[commerce/webhook] @stacksjs/payments not installed \u2014 Stripe webhook handlers NOT registered"),()=>{};let{onPaymentIntent:$,onCharge:J}=N;if(typeof $!=="function"||typeof J!=="function")return console.warn("[commerce/webhook] @stacksjs/payments shape changed \u2014 handlers NOT registered"),()=>{};return $({succeeded:G1,failed:X1}),J({refunded:L1}),()=>{}}import{db as dN}from"@stacksjs/database";async function n3(N){if(N.length===0)return new Map;let $=await dN.selectFrom("products").where("id","in",N).select(["id","price"]).execute(),J=new Map;for(let G of $){let X=Number(G.price);if(Number.isFinite(X))J.set(G.id,Math.round(X))}return J}async function u3(N){try{let $=await dN.selectFrom("tax_rates").where("id","=",N).select(["rate"]).executeTakeFirst(),J=Number($?.rate??0);return Number.isFinite(J)?J:0}catch{return 0}}async function aN(N){let $=N.items.map((O)=>O.productId),J=await n3($),G=N.taxRateId!=null?await u3(N.taxRateId):0,X=0,L=[];for(let O of N.items){let _=O.unitPriceCents??J.get(O.productId)??0,S=Math.round(_*O.quantity);X+=S,L.push({productId:O.productId,quantity:O.quantity,unitPriceCents:_,lineCents:S})}let W=Math.max(0,N.discountCents??0),Y=Math.max(0,X-W),Z=Math.round(Y*G),M=Math.max(0,N.shippingCents??0),K=X-W+Z+M,Q=N.maxDriftCents??5,x=!1,R=0;if(N.clientTotalCents!=null)R=Math.abs(K-N.clientTotalCents),x=R>Q;return{subtotalCents:X,discountCents:W,taxCents:Z,shippingCents:M,totalCents:K,resolvedItems:L,priceChanged:x,diffCents:R}}import{db as t0}from"@stacksjs/database";function eN(N,$={}){let J=N.length;if(J<=1)return{ok:!0,count:J};if(!$.allowMultiple)return{ok:!1,count:J,reason:"multiple-not-allowed"};let G=$.maxStacked??Number.POSITIVE_INFINITY;if(J>G)return{ok:!1,count:J,reason:"exceeds-max-stacked"};return{ok:!0,count:J}}async function W1(N,$){if(!Number.isFinite($)||$<=0)return{ok:!1,productId:N,quantity:$,reason:"non-positive"};let J;try{J=await t0.selectFrom("products").where("id","=",N).select(["min_order_qty","max_order_qty"]).executeTakeFirst()}catch{return{ok:!0,productId:N,quantity:$}}if(!J)return{ok:!1,productId:N,quantity:$,reason:"product-missing"};let G=J.min_order_qty??null,X=J.max_order_qty??null;if(G!=null&&$<G)return{ok:!1,productId:N,quantity:$,reason:"below-min",bound:G};if(X!=null&&$>X)return{ok:!1,productId:N,quantity:$,reason:"above-max",bound:X};return{ok:!0,productId:N,quantity:$}}async function tN(N){for(let J of N){let G=await W1(J.productId,J.quantity);if(!G.ok)return G}let $=N[N.length-1]??{productId:0,quantity:0};return{ok:!0,productId:$.productId,quantity:$.quantity}}async function rN(N={}){let $=N.olderThanDays??30,J=N.limit??1000,X=new Date(Date.now()-$*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");try{let L=await t0.unsafe("DELETE FROM carts WHERE updated_at < ? AND id IN (SELECT id FROM carts WHERE updated_at < ? LIMIT ?)",[X,X,J]),W=typeof L?.execute==="function"?await L.execute():L;return{deleted:Number(W?.changes??W?.numDeletedRows??W?.[0]?.numDeletedRows??W?.affectedRows??0),cutoffAt:X}}catch{try{let L=await t0.selectFrom("carts").where("updated_at","<",X).select(["id"]).limit(J).execute();if(L.length===0)return{deleted:0,cutoffAt:X};let W=L.map((M)=>M.id),Y=await t0.deleteFrom("carts").where("id","in",W).execute();return{deleted:Number(Y?.numDeletedRows??Y?.[0]?.numDeletedRows??Y?.affectedRows??L.length),cutoffAt:X}}catch{return{deleted:0,cutoffAt:X}}}}var Z1={};B(Z1,{update:()=>Q2,store:()=>M2,recordRefund:()=>x2,fetchPaymentStatsByMethod:()=>L2,fetchPaymentStats:()=>X2,fetchMonthlyPaymentTrends:()=>W2,fetchById:()=>t,fetchAll:()=>G2,destroy:()=>N2,bulkDestroy:()=>J2});import{db as $2}from"@stacksjs/database";async function N2(N){try{let $=await $2.deleteFrom("payments").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payment: ${$.message}`);throw $}}async function J2(N){if(!N.length)return 0;try{let $=await $2.deleteFrom("payments").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete payments: ${$.message}`);throw $}}import{db as q}from"@stacksjs/database";import{formatDate as g}from"@stacksjs/orm";async function G2(){return await q.selectFrom("payments").selectAll().execute()}async function t(N){return await q.selectFrom("payments").selectAll().where("id","=",N).executeTakeFirst()}async function X2(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=new Date(J);G.setDate(G.getDate()-1);let X=new Date(G);X.setDate(G.getDate()-N);let L=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",g(J)).where("created_at","<=",g($)).where("status","=","completed").executeTakeFirst(),W=await q.selectFrom("payments").select([q.fn.count("id").as("transaction_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",g(X)).where("created_at","<=",g(G)).where("status","=","completed").executeTakeFirst(),Y=await q.selectFrom("payments").select(q.fn.count("id").as("count")).where("created_at",">=",g(J)).where("created_at","<=",g($)).executeTakeFirst(),Z=Number(L?.transaction_count||0),M=Number(L?.total_revenue||0),K=Z>0?M/Z:0,Q=Number(W?.transaction_count||0),x=Number(W?.total_revenue||0),R=Q>0?x/Q:0,O=Z-Q,_=M-x,S=K-R,D=Q>0?O/Q*100:Z>0?100:0,o=x>0?_/x*100:M>0?100:0,s=R>0?S/R*100:K>0?100:0,J0=Number(Y?.count||0),p=J0>0?Z/J0*100:0;return{total_transactions:Z,total_revenue:M,average_transaction:K,successful_rate:p,comparison:{transactions:{difference:O,percentage:Math.abs(D),is_increase:O>=0},revenue:{difference:_,percentage:Math.abs(o),is_increase:_>=0},average:{difference:S,percentage:Math.abs(s),is_increase:S>=0}}}}async function L2(N=30){let $=new Date,J=new Date($);J.setDate($.getDate()-N);let G=await q.selectFrom("payments").select([q.fn.count("id").as("total_count"),q.fn.sum("amount").as("total_revenue")]).where("created_at",">=",g(J)).where("created_at","<=",g($)).where("status","=","completed").executeTakeFirst(),X=Number(G?.total_count||0),L=await q.selectFrom("payments").select(["method",q.fn.count("id").as("count"),q.fn.sum("amount").as("revenue")]).where("created_at",">=",g(J)).where("created_at","<=",g($)).where("status","=","completed").groupBy("method").execute(),W={};return L.forEach((Y)=>{let Z=Number(Y.count||0),M=Number(Y.revenue||0),K=X>0?Z/X*100:0;W[Y.method]={count:Z,revenue:M,percentage_of_total:K}}),W}async function W2(){let N=new Date,$=new Date(N);$.setMonth(N.getMonth()-11),$.setDate(1);let J=await q.selectFrom("payments").selectAll().where("created_at",">=",g($)).where("status","=","completed").execute(),G={};for(let L of J){let W=L.created_at?new Date(L.created_at):new Date,Y=W.getFullYear(),Z=W.getMonth()+1,M=`${Y}-${String(Z).padStart(2,"0")}`;if(!G[M])G[M]={year:Y,month:Z,transactions:0,revenue:0};G[M].transactions++,G[M].revenue+=Number(L.amount||0)}return Object.keys(G).sort().map((L)=>{let W=G[L],Y=W.transactions,Z=W.revenue,M=Y>0?Z/Y:0;return{month:new Date(W.year,W.month-1,1).toLocaleString("default",{month:"short"}),year:W.year,transactions:Y,revenue:Z,average:M}})}var{randomUUIDv7:i3}=globalThis.Bun;import{db as Y2}from"@stacksjs/database";import{HttpError as Z2}from"@stacksjs/error-handling";import{isUniqueViolation as o3}from"@stacksjs/orm";async function M2(N){let $=i3(),J={...N,status:N.status||"pending",currency:N.currency||"USD",uuid:$};try{return await Y2.insertInto("payments").values(J).executeTakeFirst(),await Y2.selectFrom("payments").where("uuid","=",$).selectAll().executeTakeFirst()}catch(G){if(G instanceof Z2)throw G;if(o3(G))throw new Z2(409,"A payment with this transaction ID already exists");if(G instanceof Error){if(G.message.includes("Insufficient funds"))throw Error("Insufficient funds for this payment");throw Error(`Failed to create payment: ${G.message}`)}throw G}}import{db as F2,sqlHelpers as s3}from"@stacksjs/database";import{env as d3}from"@stacksjs/env";import{formatDate as K2}from"@stacksjs/orm";async function Q2(N,$){if(!await t(N))return;try{return await F2.updateTable("payments").set({...$,updated_at:K2(new Date)}).where("id","=",N).execute(),await t(N)}catch(G){if(G instanceof Error){if(G.message.includes("Duplicate entry")&&G.message.includes("transaction_id"))throw Error("A payment with this transaction ID already exists");throw Error(`Failed to update payment: ${G.message}`)}throw G}}var a3=new Set(["completed","succeeded","partiallyRefunded"]);async function x2(N,$){if(!Number.isSafeInteger(N)||N<=0)throw TypeError("Payment ID must be a positive integer");if(!Number.isSafeInteger($)||$<=0)throw TypeError("Refund amount must be a positive integer in minor units");let G=s3(d3.DB_CONNECTION||"sqlite").param,X=K2(new Date),L=await F2.unsafe(`UPDATE payments
21
+ SET refund_amount = COALESCE(refund_amount, 0) + ${G(1)},
22
+ status = CASE WHEN COALESCE(refund_amount, 0) + ${G(2)} = amount
23
+ THEN 'refunded' ELSE 'partiallyRefunded' END,
24
+ updated_at = ${G(3)}
25
+ WHERE id = ${G(4)}
26
+ AND status IN ('completed', 'succeeded', 'partiallyRefunded')
27
+ AND COALESCE(refund_amount, 0) + ${G(5)} <= amount`,[$,$,X,N,$]),W=typeof L?.execute==="function"?await L.execute():L;if(Number(W?.numUpdatedRows??W?.[0]?.numUpdatedRows??W?.numAffectedRows??W?.affectedRows??W?.[0]?.affectedRows??W?.changes??0)>0){let x=await t(N);if(x)return x;throw Error(`Payment with ID ${N} disappeared during refund`)}let Z=await t(N);if(!Z)throw Error(`Payment with ID ${N} not found`);let M=String(Z.status||"");if(!a3.has(M))throw Error(`Payment status ${M||"unknown"} cannot be refunded`);let K=Z,Q=Number(Z.amount||0)-Number(K.refundAmount??K.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${Q} minor units`)}var V1={};B(V1,{variants:()=>Z$,units:()=>Y$,reviews:()=>X$,manufacturers:()=>G$,items:()=>J$,default:()=>YX,categories:()=>N$});var N$={};B(N$,{updateParent:()=>C2,updateDisplayOrder:()=>k2,updateActiveStatus:()=>j2,update:()=>f2,store:()=>F1,removeChildCategories:()=>w2,remove:()=>S2,findOrCreateByName:()=>q2,fetchStats:()=>R2,fetchRootCategories:()=>z2,fetchChildCategories:()=>B2,fetchCategoryTree:()=>O2,fetchByName:()=>H2,fetchById:()=>f,fetchByDisplayOrder:()=>A2,fetchAll:()=>M1,fetchActive:()=>V2,deactivateChildCategories:()=>E2,deactivate:()=>U2,compareCategoryGrowth:()=>_2,bulkRemove:()=>T2});import{db as W0}from"@stacksjs/database";import{db as w}from"@stacksjs/database";import{formatDate as A0}from"@stacksjs/orm";async function M1(){return await w.selectFrom("categories").selectAll().execute()}async function f(N){return await w.selectFrom("categories").where("id","=",N).selectAll().executeTakeFirst()}async function H2(N){return await w.selectFrom("categories").where("name","=",N).selectAll().executeTakeFirst()}async function V2(){return await w.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function z2(){return await w.selectFrom("categories").where("parent_category_id","is",null).where("is_active","=",!0).selectAll().execute()}async function B2(N){return await w.selectFrom("categories").where("parent_category_id","=",N).where("is_active","=",!0).selectAll().execute()}async function A2(N=!0){let $=w.selectFrom("categories").where("is_active","=",!0).selectAll();if(N)return await $.orderBy("display_order","asc").execute();else return await $.orderBy("display_order","desc").execute()}async function R2(){let N=await w.selectFrom("categories").select(w.fn.count("id").as("count")).executeTakeFirst(),$=await w.selectFrom("categories").where("is_active","=",!0).select(w.fn.count("id").as("count")).executeTakeFirst(),J=await w.selectFrom("categories").where("parent_category_id","is",null).select(w.fn.count("id").as("count")).executeTakeFirst(),G=await w.selectFrom("categories").where("image_url","is not",null).select(w.fn.count("id").as("count")).executeTakeFirst(),X=new Date;X.setDate(X.getDate()-30);let L=A0(X),W=await w.selectFrom("categories").where("created_at",">=",L).selectAll().limit(5).execute(),Y=await w.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").where("c.parent_category_id","is not",null).select(["c.parent_category_id","parent.name as parent_name",w.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(N?.count||0),active:Number($?.count||0),root_categories:Number(J?.count||0),child_categories:Number(N?.count||0)-Number(J?.count||0),with_images:Number(G?.count||0),recently_added:W,top_parent_categories:Y.map((Z)=>({id:String(Z.parent_category_id||""),name:String(Z.parent_name||""),child_count:Number(Z.child_count)}))}}async function _2(N=30){let $=new Date,J=A0($),G=new Date;G.setDate($.getDate()-N);let X=A0(G),L=new Date(G);L.setDate(L.getDate()-1);let W=A0(L),Y=new Date(L);Y.setDate(L.getDate()-N);let Z=A0(Y),M=await w.selectFrom("categories").select(w.fn.count("id").as("count")).where("created_at",">=",X).where("created_at","<=",J).executeTakeFirst(),K=await w.selectFrom("categories").select(w.fn.count("id").as("count")).where("created_at",">=",Z).where("created_at","<=",W).executeTakeFirst(),Q=Number(M?.count||0),x=Number(K?.count||0),R=Q-x,O=x!==0?R/x*100:Q>0?100:0;return{current_period:Q,previous_period:x,difference:R,percentage_change:O,days_range:N}}async function O2(){let N=await M1(),$=new Map;N.forEach((X)=>{$.set(X.id,{...X,children:[]})});let J=[];N.forEach((X)=>{let L=$.get(X.id);if(X.parent_category_id){let W=$.get(X.parent_category_id);if(W)W.children.push(L)}else J.push(L)}),J.sort((X,L)=>X.display_order-L.display_order);let G=(X)=>{X.sort((L,W)=>L.display_order-W.display_order),X.forEach((L)=>{if(L.children.length>0)G(L.children)})};return G(J),J}async function S2(N){let $=await W0.deleteFrom("categories").where("id","=",N).executeTakeFirst();return F($)>0}async function T2(N){if(!N.length)return 0;let $=await W0.deleteFrom("categories").where("id","in",N).executeTakeFirst();return F($)}async function w2(N){let $=await W0.deleteFrom("categories").where("parent_category_id","=",N).executeTakeFirst();return F($)}async function U2(N){if(!await f(N))throw Error(`Category with ID ${N} not found`);return!!await W0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("id","=",N).executeTakeFirst()}async function E2(N){let $=await W0.updateTable("categories").set({is_active:!1,updated_at:new Date().toISOString()}).where("parent_category_id","=",N).execute();return Number($.length)||0}var{randomUUIDv7:e3}=globalThis.Bun;import{db as P2}from"@stacksjs/database";import{HttpError as r0}from"@stacksjs/error-handling";import{isUniqueViolation as t3}from"@stacksjs/orm";import{slug as r3}from"@stacksjs/strings";async function F1(N){try{let $=N.parent_category_id?Number(N.parent_category_id):void 0;if($!==void 0&&(!Number.isSafeInteger($)||$<=0))throw new r0(422,"Parent category ID must be a positive integer");if($&&!await f($))throw new r0(422,`Parent category with ID ${N.parent_category_id} not found`);let J={...N,uuid:e3(),is_active:N.is_active??!0,parent_category_id:N.parent_category_id||null},G=await P2.insertInto("categories").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create category");return G}catch($){if($ instanceof r0)throw $;if(t3($))throw new r0(409,"A category with this name or slug already exists");if($ instanceof Error)throw Error(`Failed to create category: ${$.message}`);throw $}}async function q2(N){if(!N.name)throw Error("Name is required");let $=await P2.selectFrom("categories").selectAll().where("name","=",N.name).executeTakeFirst();if($)return $;let J={name:N.name,slug:r3(N.name),is_active:N.is_active??!0,display_order:0};return await F1(J)}import{db as R0}from"@stacksjs/database";import{HttpError as Y0}from"@stacksjs/error-handling";import{formatDate as $$,isUniqueViolation as $X}from"@stacksjs/orm";async function f2(N,$){if(!await f(N))return;if(Object.hasOwn($,"parent_category_id")){let G=$.parent_category_id?Number($.parent_category_id):void 0;if(G!==void 0&&(!Number.isSafeInteger(G)||G<=0))throw new Y0(422,"Parent category ID must be a positive integer");if(G===N)throw new Y0(422,"A category cannot be its own parent");if(G&&!await f(G))throw new Y0(422,`Parent category with ID ${$.parent_category_id} not found`);if(G&&await I2(N,String(G)))throw new Y0(422,"This operation would create a circular category hierarchy")}try{let G=Object.hasOwn($,"parent_category_id")?{parent_category_id:$.parent_category_id||null}:{},X=await R0.updateTable("categories").set({...$,...G,updated_at:$$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!X)return;return X}catch(G){if(G instanceof Y0)throw G;if($X(G))throw new Y0(409,"A category with this name or slug already exists");if(G instanceof Error)throw Error(`Failed to update category: ${G.message}`);throw G}}async function k2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);try{return await R0.updateTable("categories").set({display_order:$,updated_at:$$(new Date)}).where("id","=",N).execute(),await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category display order: ${G.message}`);throw G}}async function j2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);try{return await R0.updateTable("categories").set({is_active:$,updated_at:$$(new Date)}).where("id","=",N).execute(),await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category active status: ${G.message}`);throw G}}async function C2(N,$){if(!await f(N))throw Error(`Category with ID ${N} not found`);if($){let G=Number($);if(G===N)throw Error("A category cannot be its own parent");if(!await f(G))throw Error(`Parent category with ID ${$} not found`);if(await I2(N,$))throw Error("This operation would create a circular reference in the category hierarchy")}try{let G={updated_at:$$(new Date)};if($===null)await R0.updateTable("categories").set({...G,parent_category_id:null}).where("id","=",N).execute();else await R0.updateTable("categories").set({...G,parent_category_id:$}).where("id","=",N).execute();return await f(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update category parent: ${G.message}`);throw G}}async function I2(N,$){let J=Number($),G=new Set;while(J){if(G.has(J))return!0;if(J===N)return!0;G.add(J);let X=await f(J),L=X?.parent_category_id??X?.parentCategoryId;if(!X||!L)return!1;J=Number(L)}return!1}var J$={};B(J$,{updateInventory:()=>u2,updateAvailability:()=>n2,update:()=>c2,store:()=>m2,fetchTopProducts:()=>D2,fetchById:()=>l,fetchAll:()=>y2,destroy:()=>g2,bulkStore:()=>l2,bulkDestroy:()=>v2});import{db as h2}from"@stacksjs/database";async function g2(N){try{let $=await h2.deleteFrom("products").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product item: ${$.message}`);throw $}}async function v2(N){if(!N.length)return 0;try{let $=await h2.deleteFrom("products").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product items: ${$.message}`);throw $}}import{db as i,sql as NX}from"@stacksjs/database";async function l(N){let $=await i.selectFrom("products").where("id","=",N).selectAll().executeTakeFirst();if($){let J=null,G=null;if($.manufacturer_id)J=await i.selectFrom("manufacturers").where("id","=",$.manufacturer_id).selectAll().executeTakeFirst();if($.category_id)G=await i.selectFrom("categories").where("id","=",$.category_id).selectAll().executeTakeFirst();return{...$,manufacturer:J,category:G}}return}async function y2(){let N=await i.selectFrom("products").selectAll().execute(),$=N.map((M)=>M.manufacturer_id).filter((M)=>M!==null&&M!==void 0),J=N.map((M)=>M.category_id).filter((M)=>M!==null&&M!==void 0),G=i.selectFrom("manufacturers"),X=i.selectFrom("categories");if($.length>0)G=G.where("id","in",$);if(J.length>0)X=X.where("id","in",J);let L=await G.selectAll().execute(),W=await X.selectAll().execute(),Y=L.reduce((M,K)=>{return M[K.id]=K,M},{}),Z=W.reduce((M,K)=>{return M[K.id]=K,M},{});return N.map((M)=>({...M,manufacturer:M.manufacturer_id?Y[M.manufacturer_id]:null,category:M.category_id?Z[M.category_id]:null}))}async function D2(N=5){try{return(await i.selectFrom("order_items").innerJoin("products","products.id","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",i.fn.sum("order_items.quantity").as("units_sold"),NX`SUM(COALESCE(order_items.price, products.price) * order_items.quantity)`.as("revenue")]).groupBy(["products.id","products.name","products.inventory_count"]).orderBy("units_sold","desc").limit(N).execute()).map((J)=>({id:Number(J.id),name:String(J.name??"Unnamed product"),units_sold:Number(J.units_sold??0),revenue:Number(J.revenue??0),inventory_count:Number(J.inventory_count??0)}))}catch($){if($ instanceof Error)throw TypeError(`Failed to fetch top products: ${$.message}`);throw $}}var{randomUUIDv7:p2}=globalThis.Bun;import{db as b2}from"@stacksjs/database";async function m2(N){try{let $={...N,uuid:p2()},J=await b2.insertInto("products").values($).executeTakeFirst();if(!J)throw Error("Failed to create product item");let G=Number(J.insertId)||Number(J.numInsertedOrUpdatedRows),X=await l(G);if(!X)throw Error("Failed to create product item");return X}catch($){if($ instanceof Error)throw TypeError(`Failed to create product item: ${$.message}`);throw $}}async function l2(N){if(!N.length)return 0;let $=0;try{return await b2.transaction().execute(async(J)=>{for(let G of N){let X={...G,uuid:p2()};await J.insertInto("products").values(X).execute(),$++}}),$}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product items in bulk: ${J.message}`);throw J}}import{db as K1}from"@stacksjs/database";import{formatDate as Q1}from"@stacksjs/orm";async function c2(N,$){try{if(!N)throw Error("Product item ID is required for update");let J=await K1.updateTable("products").set({...$,updated_at:Q1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product item: ${J.message}`);throw J}}async function n2(N,$){if(!await l(N))throw Error(`Product item with ID ${N} not found`);try{return await K1.updateTable("products").set({is_available:$,updated_at:Q1(new Date)}).where("id","=",N).execute(),await l(N)}catch(G){if(G instanceof Error)throw TypeError(`Failed to update product item availability: ${G.message}`);throw G}}async function u2(N,$){let J=await l(N);if(!J)throw Error(`Product item with ID ${N} not found`);let G={updated_at:Q1(new Date)};if($!==void 0)G.inventory_count=$;if(Object.keys(G).length===1)return J;try{return await K1.updateTable("products").set(G).where("id","=",N).execute(),await l(N)}catch(X){if(X instanceof Error)throw TypeError(`Failed to update inventory information: ${X.message}`);throw X}}var G$={};B(G$,{updateFeaturedStatus:()=>Z7,updateByUuid:()=>M7,update:()=>Y7,store:()=>X7,fetchWithProductCount:()=>$7,fetchFeatured:()=>t2,fetchByUuid:()=>e2,fetchById:()=>a2,fetchByCountry:()=>r2,fetchAll:()=>d2,destroy:()=>o2,bulkStore:()=>L7,bulkDestroy:()=>s2});import{db as i2}from"@stacksjs/database";async function o2(N){try{let $=await i2.deleteFrom("manufacturers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete order: ${$.message}`);throw $}}async function s2(N){if(!N.length)return 0;try{let $=await i2.deleteFrom("manufacturers").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete orders: ${$.message}`);throw $}}import{db as c}from"@stacksjs/database";function d2(){return c.selectFrom("manufacturers").selectAll().execute()}async function a2(N){return await c.selectFrom("manufacturers").where("id","=",N).selectAll().executeTakeFirst()}async function e2(N){return await c.selectFrom("manufacturers").where("uuid","=",N).selectAll().executeTakeFirst()}async function t2(N=10){return await c.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(N).execute()}async function r2(N,$={}){let J=$.page||1,G=$.limit||2,X=await c.selectFrom("manufacturers").select(c.fn.count("id").as("total")).where("country","=",N).executeTakeFirst(),L=Number(X?.total||0),W=await c.selectFrom("manufacturers").selectAll().where("country","=",N).limit(G).offset((J-1)*G).execute(),Y=Math.ceil(L/G);return{data:W,paging:{total_records:L,page:J,total_pages:Y},next_cursor:J<Y?J+1:null}}async function $7(N={}){let $=c.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(N.country)$=$.where("m.country","=",N.country);if(N.featured!==void 0)$=$.where("m.featured","=",N.featured);return $=$.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",c.fn.count("p.id").as("product_count")]).groupBy("m.id"),$.execute()}var{randomUUIDv7:J7}=globalThis.Bun;import{db as G7}from"@stacksjs/database";import{HttpError as N7}from"@stacksjs/error-handling";import{isUniqueViolation as JX}from"@stacksjs/orm";async function X7(N){try{let $={...N,uuid:J7(),featured:N.featured??!1},J=await G7.insertInto("manufacturers").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create manufacturer");return J}catch($){if($ instanceof N7)throw $;if(JX($))throw new N7(409,"A manufacturer with this name already exists");if($ instanceof Error)throw Error(`Failed to create manufacturer: ${$.message}`);throw $}}async function L7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:J7(),featured:J.featured??!1};await G7.insertInto("manufacturers").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${J.message}`);throw J}}import{db as x1}from"@stacksjs/database";import{HttpError as W7}from"@stacksjs/error-handling";import{formatDate as H1,isUniqueViolation as GX}from"@stacksjs/orm";async function Y7(N,$){try{if(!N)throw Error("Manufacturer ID is required for update");let J=await x1.updateTable("manufacturers").set({...$,updated_at:H1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof W7)throw J;if(GX(J))throw new W7(409,"A manufacturer with this name already exists");if(J instanceof Error)throw Error(`Failed to update manufacturer: ${J.message}`);throw J}}async function Z7(N,$){try{let J=await x1.updateTable("manufacturers").set({featured:$,updated_at:H1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update manufacturer featured status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${J.message}`);throw J}}async function M7(N,$){try{let J=await x1.updateTable("manufacturers").set({...$,updated_at:H1(new Date)}).where("uuid","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update manufacturer");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update manufacturer: ${J.message}`);throw J}}var X$={};B(X$,{updateVotes:()=>T7,update:()=>S7,store:()=>R7,fetchMostHelpfulByProductId:()=>A7,fetchByUserId:()=>z7,fetchByProductId:()=>V7,fetchById:()=>x7,fetchApprovedByProductId:()=>B7,fetchAll:()=>H7,destroy:()=>K7,bulkDestroy:()=>Q7});import{db as F7}from"@stacksjs/database";async function K7(N){try{let $=await F7.deleteFrom("reviews").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete review: ${$.message}`);throw $}}async function Q7(N){if(!N.length)return 0;try{let $=await F7.deleteFrom("reviews").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete reviews: ${$.message}`);throw $}}import{db as Z0}from"@stacksjs/database";async function x7(N){return await Z0.selectFrom("reviews").where("id","=",N).selectAll().executeTakeFirst()}async function H7(){return await Z0.selectFrom("reviews").selectAll().execute()}async function V7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).selectAll().execute()}async function z7(N){return await Z0.selectFrom("reviews").where("customer_id","=",N).selectAll().execute()}async function B7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).where("is_approved","=",!0).selectAll().execute()}async function A7(N){return await Z0.selectFrom("reviews").where("product_id","=",N).orderBy("helpful_votes","desc").selectAll().execute()}var{randomUUIDv7:XX}=globalThis.Bun;import{db as LX}from"@stacksjs/database";async function R7(N){try{let $={...N,uuid:XX(),is_verified_purchase:N.is_verified_purchase??!1,is_approved:N.is_approved??!1,helpful_votes:N.helpful_votes??0,unhelpful_votes:N.unhelpful_votes??0,is_featured:N.is_featured??!1},J=await LX.insertInto("reviews").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create review");return J}catch($){if($ instanceof Error){if($.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${$.message}`)}throw $}}import{db as _7}from"@stacksjs/database";import{formatDate as O7}from"@stacksjs/orm";async function S7(N,$){try{if(!N)throw Error("Review ID is required for update");let J=await _7.updateTable("reviews").set({...$,updated_at:O7(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update review: ${J.message}`);throw J}}async function T7(N,$,J=!0){try{let G=$==="helpful"?"helpful_votes":"unhelpful_votes",X=J?`COALESCE("${G}", 0) + 1`:`MAX(COALESCE("${G}", 0) - 1, 0)`,L=await _7.unsafe(`UPDATE "reviews" SET "${G}" = ${X}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[O7(new Date),N]).execute(),W=Array.isArray(L)?L[0]:L;if(!W)throw Error("Failed to update review votes");return W}catch(G){if(G instanceof Error)throw TypeError(`Failed to update review votes: ${G.message}`);throw G}}var Y$={};B(Y$,{updateDefaultStatus:()=>y7,update:()=>g7,store:()=>j7,getDefaultUnit:()=>h7,formatUnitOptions:()=>I7,fetchById:()=>q7,fetchAll:()=>f7,destroy:()=>U7,bulkUpdate:()=>v7,bulkStore:()=>C7,bulkDestroy:()=>E7});import{db as w7}from"@stacksjs/database";async function U7(N){try{let $=await w7.deleteFrom("product_units").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product unit: ${$.message}`);throw $}}async function E7(N){if(!N.length)return 0;try{let $=await w7.deleteFrom("product_units").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product units: ${$.message}`);throw $}}import{db as P7}from"@stacksjs/database";async function q7(N){return await P7.selectFrom("product_units").where("id","=",N).selectAll().executeTakeFirst()}async function f7(){return await P7.selectFrom("product_units").selectAll().execute()}var{randomUUIDv7:k7}=globalThis.Bun;import{db as _0}from"@stacksjs/database";async function j7(N){try{return await _0.transaction(async($)=>{let J={...N,uuid:k7()},G=await $.insertInto("product_units").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create product unit");if(J.is_default&&J.type)await $.updateTable("product_units").set({is_default:!1}).where("type","=",J.type).where("id","!=",G.id).execute();return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create product unit: ${$.message}`);throw $}}async function C7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:k7()},X=await _0.insertInto("product_units").values(G).returningAll().executeTakeFirst();if(G.is_default&&G.type&&X)await _0.updateTable("product_units").set({is_default:!1}).where("type","=",G.type).where("id","!=",X.id).execute();$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product units in bulk: ${J.message}`);throw J}}function I7(N){try{let $=_0.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(N)$=$.where("type","=",N);return $=$.orderBy("name"),$.execute().then((J)=>J.map((G)=>({id:String(G.id),name:G.name,abbreviation:G.abbreviation,is_default:G.is_default})))}catch($){if($ instanceof Error)throw TypeError(`Failed to format unit options: ${$.message}`);throw $}}async function h7(N){try{return await _0.selectFrom("product_units").selectAll().where("type","=",N).where("is_default","=",!0).executeTakeFirst()}catch($){if($ instanceof Error)throw TypeError(`Failed to get default unit: ${$.message}`);throw $}}import{db as L$}from"@stacksjs/database";import{formatDate as W$}from"@stacksjs/orm";async function g7(N,$){try{if(!N)throw Error("Product unit ID is required for update");return await L$.transaction(async(J)=>{let G=await J.selectFrom("product_units").select(["type","is_default"]).where("id","=",N).executeTakeFirst();if(!G)return;let X=$.type??G.type;if(($.is_default??Boolean(G.is_default))&&X)await J.updateTable("product_units").set({is_default:!1,updated_at:W$(new Date)}).where("type","=",X).where("id","!=",N).execute();let W=await J.updateTable("product_units").set({...$,updated_at:W$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!W)return;return W})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product unit: ${J.message}`);throw J}}async function v7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G=J;if(!G.id)continue;let X=G.data&&typeof G.data==="object"?G.data:{...G};delete X.id;let L=await L$.updateTable("product_units").set({...X,updated_at:W$(new Date)}).where("id","=",G.id).executeTakeFirst(),W=X;if(W.is_default===!0&&W.type)await L$.updateTable("product_units").set({is_default:!1}).where("type","=",W.type).where("id","!=",G.id).execute();if(Number(L.numUpdatedRows)>0)$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product units in bulk: ${J.message}`);throw J}}async function y7(N,$){try{return await L$.transaction(async(J)=>{let G=await J.selectFrom("product_units").select("type").where("id","=",N).executeTakeFirst();if(!G)return!1;let X=W$(new Date);if($&&G.type)await J.updateTable("product_units").set({is_default:!1,updated_at:X}).where("type","=",G.type).where("id","!=",N).execute();return await J.updateTable("product_units").set({is_default:$,updated_at:X}).where("id","=",N).execute(),!0})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product unit default status: ${J.message}`);throw J}}var Z$={};B(Z$,{update:()=>t7,store:()=>i7,generateVariantCombinations:()=>d7,formatVariantOptions:()=>s7,fetchById:()=>l7,fetchAll:()=>c7,destroy:()=>p7,bulkUpdate:()=>r7,bulkStore:()=>o7,bulkDestroy:()=>b7});import{db as D7}from"@stacksjs/database";async function p7(N){try{let $=await D7.deleteFrom("product_variants").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variant: ${$.message}`);throw $}}async function b7(N){if(!N.length)return 0;try{let $=await D7.deleteFrom("product_variants").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete product variants: ${$.message}`);throw $}}import{db as m7}from"@stacksjs/database";async function l7(N){return await m7.selectFrom("product_variants").where("id","=",N).selectAll().executeTakeFirst()}async function c7(){return await m7.selectFrom("product_variants").selectAll().execute()}var{randomUUIDv7:n7}=globalThis.Bun;import{db as u7}from"@stacksjs/database";async function i7(N){try{let $={...N,uuid:n7()},J=await u7.insertInto("product_variants").values($).returningAll().executeTakeFirst();if(!J)throw Error("Failed to create product variant");return J}catch($){if($ instanceof Error)throw TypeError(`Failed to create product variant: ${$.message}`);throw $}}async function o7(N){if(!N.length)return 0;let $=0;try{for(let J of N){let G={...J,uuid:n7()};await u7.insertInto("product_variants").values(G).execute(),$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${J.message}`);throw J}}function s7(N){if(!N||!N.length)return JSON.stringify([]);let $=N.map((J)=>J.trim()).filter(Boolean);return JSON.stringify($)}function d7(N){let $=Object.keys(N);if(!$.length)return[];function J(G,X){if(G===$.length)return[X];let L=$[G],W=N[L]??[],Y=[];for(let Z of W){let M={...X,[L]:Z};Y.push(...J(G+1,M))}return Y}return J(0,{})}import{db as a7}from"@stacksjs/database";import{formatDate as e7}from"@stacksjs/orm";async function t7(N,$){try{let J=await a7.updateTable("product_variants").set({...$,updated_at:e7(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product variant: ${J.message}`);throw J}}async function r7(N){if(!N.length)return 0;let $=0;try{for(let J of N){if(!J.id)continue;let G=await a7.updateTable("product_variants").set({...J,updated_at:e7(new Date)}).where("id","=",J.id).executeTakeFirst();if(Number(G.numUpdatedRows)>0)$++}return $}catch(J){if(J instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${J.message}`);throw J}}var WX={categories:N$,items:J$,manufacturers:G$,reviews:X$,units:Y$,variants:Z$},YX=WX;var O1={};B(O1,{updateStatus:()=>xJ,updatePrintJob:()=>HJ,update:()=>QJ,store:()=>FJ,fetchSuccessRate:()=>LJ,fetchPrintsPerHour:()=>ZJ,fetchPrintTimeStats:()=>YJ,fetchPrintJobStats:()=>XJ,fetchPageStats:()=>WJ,fetchById:()=>M0,fetchAll:()=>GJ,destroy:()=>NJ,bulkStore:()=>KJ,bulkDestroy:()=>JJ});import{db as $J}from"@stacksjs/database";async function NJ(N){try{let $=await $J.deleteFrom("receipts").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete print log: ${$.message}`);throw $}}async function JJ(N){if(!N.length)return 0;try{let $=await $J.deleteFrom("receipts").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete receipts: ${$.message}`);throw $}}import{db as z1}from"@stacksjs/database";import{formatDate as ZX}from"@stacksjs/orm";function y(N){return ZX(N)}function MX(N){if(N instanceof Date)return Number.isNaN(N.getTime())?null:N;if(typeof N==="number"){let G=new Date(N<=2147483647?N*1000:N);return Number.isNaN(G.getTime())?null:G}let $=String(N||"").trim();if(!$)return null;if(/^\d{10}$/.test($)){let G=new Date(Number($)*1000);return Number.isNaN(G.getTime())?null:G}let J=new Date($.includes("T")?$:`${$.replace(" ","T")}Z`);return Number.isNaN(J.getTime())?null:J}async function M0(N){return await z1.selectFrom("receipts").where("id","=",N).selectAll().executeTakeFirst()}async function GJ(){return await z1.selectFrom("receipts").selectAll().execute()}async function XJ(N,$){let J=y(N),G=y($),X=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}},averageSize:{kind:"avg",column:"size"},averagePages:{kind:"avg",column:"pages"},averageDuration:{kind:"avg",column:"duration"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{total:X.total,success:X.success,failed:X.failed,warning:X.warning,averageSize:Math.round(X.averageSize),averagePages:Math.round(X.averagePages),averageDuration:Math.round(X.averageDuration)}}async function LJ(N,$){let J=y(N),G=y($),X=await I("receipts",{total:{kind:"count"},success:{kind:"count",filter:{column:"status",op:"=",value:"success"}},failed:{kind:"count",filter:{column:"status",op:"=",value:"failed"}},warning:{kind:"count",filter:{column:"status",op:"=",value:"warning"}}},(W)=>W.where("timestamp",">=",J).where("timestamp","<=",G));return{successRate:X.total>0?Math.round(X.success/X.total*100):0,total:X.total,success:X.success,failed:X.failed,warning:X.warning}}async function WJ(N,$){let J=y(N),G=y($),X=await I("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{totalPages:X.totalPages,averagePagesPerReceipt:Math.round(X.averagePagesPerReceipt),totalReceipts:X.totalReceipts}}async function YJ(N,$){let J=y(N),G=y($),X=await I("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(L)=>L.where("timestamp",">=",J).where("timestamp","<=",G));return{averageDuration:Math.round(X.averageDuration),minDuration:X.minDuration,maxDuration:X.maxDuration,totalJobs:X.totalJobs}}async function ZJ(N,$){let J=typeof N==="number"?N:N.getTime(),G=typeof $==="number"?$:$.getTime(),X=y(N),L=y($),W=await z1.selectFrom("receipts").where("timestamp",">=",X).where("timestamp","<=",L).selectAll().execute(),Y=W.length,Z=Math.ceil((G-J)/3600000),M=Z>0?Math.round(Y/Z):0,K=Array.from({length:24},(Q,x)=>({hour:x,count:0}));return W.forEach((Q)=>{let x=MX(Q.timestamp);if(!x)return;K[x.getHours()].count++}),{totalPrints:Y,totalHours:Z,printsPerHour:M,hourlyBreakdown:K}}var{randomUUIDv7:MJ}=globalThis.Bun;import{db as A1}from"@stacksjs/database";import{formatDate as B1}from"@stacksjs/orm";function O0(N){try{if(typeof N==="number")return B1(N<=2147483647?N*1000:N);if(typeof N==="string"&&/^\d{10}$/.test(N))return B1(Number(N)*1000);return B1(N)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function FJ(N){try{let $=MJ(),J={...N,timestamp:O0(N.timestamp),uuid:$};await A1.insertInto("receipts").values(J).executeTakeFirst();let G=await A1.selectFrom("receipts").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create receipt");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipt: ${$.message}`);throw $}}async function KJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...G,timestamp:O0(G.timestamp),uuid:MJ()})),J=await A1.insertInto("receipts").values($).executeTakeFirst();return Number(J.numInsertedOrUpdatedRows??J.numAffectedRows??J.affectedRows??J.changes??0)}catch($){if($ instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${$.message}`);throw $}}import{db as R1}from"@stacksjs/database";import{formatDate as _1}from"@stacksjs/orm";async function QJ(N,$){try{if(!N)throw Error("Receipt ID is required for update");let J={...$,...$.timestamp===void 0?{}:{timestamp:O0($.timestamp)},updated_at:_1(new Date)};await R1.updateTable("receipts").set(J).where("id","=",N).execute();let G=await M0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update receipt: ${J.message}`);throw J}}async function xJ(N,$){try{await R1.updateTable("receipts").set({status:$,updated_at:_1(new Date)}).where("id","=",N).execute();let J=await M0(N);if(!J)throw Error("Failed to update receipt status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update receipt status: ${J.message}`);throw J}}async function HJ(N,$,J,G){try{let X={updated_at:_1(new Date)};if($!==void 0)X.size=$;if(J!==void 0)X.pages=J;if(G!==void 0)X.duration=G;await R1.updateTable("receipts").set(X).where("id","=",N).execute();let L=await M0(N);if(!L)throw Error("Failed to update receipt job information");return L}catch(X){if(X instanceof Error)throw TypeError(`Failed to update receipt job information: ${X.message}`);throw X}}var p1={};B(p1,{zones:()=>h$,routes:()=>H$,rates:()=>k$,methods:()=>U$,licenses:()=>O$,drivers:()=>A$,digital:()=>z$,default:()=>VX});var H$={};B(H$,{validateDeliveryRouteWrite:()=>F0,updateStops:()=>wJ,updateMetrics:()=>UJ,updateLastActive:()=>SJ,update:()=>TJ,store:()=>OJ,fetchById:()=>F$,fetchByDriver:()=>_J,fetchAll:()=>AJ,fetchActive:()=>RJ,destroy:()=>zJ,bulkDestroy:()=>BJ,DeliveryRouteInputError:()=>C});import{db as VJ}from"@stacksjs/database";async function zJ(N){try{let $=await VJ.deleteFrom("delivery_routes").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery route: ${$.message}`);throw $}}async function BJ(N){if(!N.length)return 0;try{let $=await VJ.deleteFrom("delivery_routes").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete delivery routes: ${$.message}`);throw $}}import{db as M$}from"@stacksjs/database";async function F$(N){return await M$.selectFrom("delivery_routes").where("id","=",N).selectAll().executeTakeFirst()}async function AJ(){return await M$.selectFrom("delivery_routes").selectAll().execute()}async function RJ(){return await M$.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function _J(N){return await M$.selectFrom("delivery_routes").where("driver","=",N).selectAll().execute()}var{randomUUIDv7:QX}=globalThis.Bun;import{db as S1}from"@stacksjs/database";function r(N,$){let J={};for(let[G,X]of Object.entries($))for(let L of X){if(!Object.prototype.hasOwnProperty.call(N,L)||N[L]===void 0)continue;J[G]=N[L];break}return J}function S0(N){return r(N,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function n(N){return r(N,{weight_from:["weight_from","weightFrom"],weight_to:["weight_to","weightTo"],rate:["rate"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"],shipping_zone_id:["shipping_zone_id","shippingZoneId","shippingzone_id"]})}function T0(N){return r(N,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function w0(N){return r(N,{name:["name"],description:["description"],download_limit:["download_limit","downloadLimit"],expiry_days:["expiry_days","expiryDays"],requires_login:["requires_login","requiresLogin"],automatic_delivery:["automatic_delivery","automaticDelivery"],status:["status"]})}function U0(N){return r(N,{key:["key"],template:["template"],expiry_date:["expiry_date","expiryDate"],status:["status"],customer_id:["customer_id","customerId"],product_id:["product_id","productId"],order_id:["order_id","orderId"]})}function E0(N){return r(N,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function K$(N){return r(N,{driver:["driver"],driver_id:["driver_id","driverId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as FX}from"@stacksjs/database";class C extends TypeError{constructor(N){super(N);this.name="DeliveryRouteInputError"}}function Q$(N,$,J){return Number(N[J]??$?.[J])}function KX(N,$){let J=N.last_active??$?.last_active;if(J instanceof Date)return J.getTime();if(typeof J==="number")return J;if(typeof J==="string"&&/^\d{10,13}$/.test(J))return Number(J);return Number.NaN}async function F0(N,$){let J=Q$(N,$,"driver_id"),G=Q$(N,$,"stops"),X=Q$(N,$,"delivery_time"),L=Q$(N,$,"total_distance"),W=KX(N,$);if(!Number.isSafeInteger(J)||J<1)throw new C("Driver must be a positive integer.");if(!Number.isSafeInteger(G)||G<0)throw new C("Stops must be a non-negative integer.");if(!Number.isSafeInteger(X)||X<0)throw new C("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(L)||L<0)throw new C("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(W)||W<0)throw new C("Last active must be a valid Unix timestamp.");let Y=await FX.selectFrom("drivers").where("id","=",J).select(["id","name","vehicle_number"]).executeTakeFirst();if(!Y)throw new C(`Driver ${J} was not found.`);return{...N,driver_id:Number(Y.id),driver:Y.name,vehicle:Y.vehicle_number}}async function OJ(N){try{let $=QX(),J=K$(N),X={...await F0(J),uuid:$};await S1.insertInto("delivery_routes").values(X).executeTakeFirst();let L=await S1.selectFrom("delivery_routes").where("uuid","=",$).selectAll().executeTakeFirst();if(!L)throw Error("Failed to create delivery route");return L}catch($){if($ instanceof C)throw $;if($ instanceof Error)throw TypeError(`Failed to create delivery route: ${$.message}`);throw $}}async function SJ(N){try{await S1.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",N).execute();let $=await F$(N);if(!$)throw Error("Failed to update delivery route last active");return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update delivery route last active: ${$.message}`);throw $}}import{db as x$}from"@stacksjs/database";import{formatDate as T1}from"@stacksjs/orm";async function TJ(N,$){try{if(!N)throw Error("Delivery route ID is required for update");let J=await x$.selectFrom("delivery_routes").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=K$($),X=await F0(G,J),L=await x$.updateTable("delivery_routes").set({...X,updated_at:T1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!L)return;return L}catch(J){if(J instanceof C)throw J;if(J instanceof Error)throw TypeError(`Failed to update delivery route: ${J.message}`);throw J}}async function wJ(N,$){try{let J=await x$.updateTable("delivery_routes").set({stops:$,updated_at:T1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update delivery route stops");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update delivery route stops: ${J.message}`);throw J}}async function UJ(N,$,J){try{let G={updated_at:T1(new Date)};if($!==void 0)G.delivery_time=$;if(J!==void 0)G.total_distance=J;let X=await x$.updateTable("delivery_routes").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update delivery metrics");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update delivery metrics: ${G.message}`);throw G}}var z$={};B(z$,{updateStatus:()=>yJ,updateDeliverySettings:()=>DJ,update:()=>vJ,store:()=>hJ,softDelete:()=>PJ,fetchById:()=>jJ,fetchAll:()=>CJ,destroy:()=>EJ,bulkStore:()=>gJ,bulkSoftDelete:()=>fJ,bulkDestroy:()=>qJ});import{db as V$}from"@stacksjs/database";async function EJ(N){try{let $=await V$.deleteFrom("digital_deliveries").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital delivery: ${$.message}`);throw $}}async function PJ(N){try{let $=await V$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${$.message}`);throw $}}async function qJ(N){if(!N.length)return 0;try{let $=await V$.deleteFrom("digital_deliveries").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${$.message}`);throw $}}async function fJ(N){if(!N.length)return 0;try{let $=await V$.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${$.message}`);throw $}}import{db as kJ}from"@stacksjs/database";async function jJ(N){return await kJ.selectFrom("digital_deliveries").where("id","=",N).selectAll().executeTakeFirst()}async function CJ(){return await kJ.selectFrom("digital_deliveries").selectAll().execute()}var{randomUUIDv7:IJ}=globalThis.Bun;import{db as w1}from"@stacksjs/database";async function hJ(N){try{let $=IJ(),J={...w0(N),uuid:$};await w1.insertInto("digital_deliveries").values(J).executeTakeFirst();let G=await w1.selectFrom("digital_deliveries").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created digital delivery");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital delivery: ${$.message}`);throw $}}async function gJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...w0(G),uuid:IJ()})),J=await w1.insertInto("digital_deliveries").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${$.message}`);throw $}}import{db as U1}from"@stacksjs/database";import{formatDate as E1}from"@stacksjs/orm";async function vJ(N,$){try{if(!N)throw Error("Digital delivery ID is required for update");let J=await U1.updateTable("digital_deliveries").set({...w0($),updated_at:E1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update digital delivery: ${J.message}`);throw J}}async function yJ(N,$){try{let J=await U1.updateTable("digital_deliveries").set({status:$,updated_at:E1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update digital delivery status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update digital delivery status: ${J.message}`);throw J}}async function DJ(N,$,J,G,X){try{let L={updated_at:E1(new Date)};if($!==void 0)L.download_limit=$;if(J!==void 0)L.expiry_days=J;if(G!==void 0)L.requires_login=G;if(X!==void 0)L.automatic_delivery=X;let W=await U1.updateTable("digital_deliveries").set(L).where("id","=",N).returningAll().executeTakeFirst();if(!W)throw Error("Failed to update delivery settings");return W}catch(L){if(L instanceof Error)throw TypeError(`Failed to update delivery settings: ${L.message}`);throw L}}var A$={};B(A$,{updateStatus:()=>sJ,updateContact:()=>dJ,update:()=>oJ,store:()=>uJ,fetchById:()=>B$,fetchAll:()=>bJ,destroy:()=>lJ,bulkStore:()=>iJ,bulkDestroy:()=>cJ});import{db as mJ}from"@stacksjs/database";import{db as pJ}from"@stacksjs/database";async function B$(N){return await pJ.selectFrom("drivers").where("id","=",N).selectAll().executeTakeFirst()}async function bJ(){return await pJ.selectFrom("drivers").selectAll().execute()}async function lJ(N){try{let $=await mJ.deleteFrom("drivers").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete driver: ${$.message}`);throw $}}async function cJ(N){if(!N.length)return 0;let $=0;try{return await mJ.transaction().execute(async(J)=>{for(let G of N)if(await B$(G))await J.deleteFrom("drivers").where("id","=",G).execute(),$++}),$}catch(J){if(J instanceof Error)throw TypeError(`Failed to delete drivers in bulk: ${J.message}`);throw J}}var{randomUUIDv7:nJ}=globalThis.Bun;import{db as P1}from"@stacksjs/database";async function uJ(N){try{let $=nJ(),J={...E0(N),uuid:$};await P1.insertInto("drivers").values(J).executeTakeFirst();let G=await P1.selectFrom("drivers").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created driver");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create driver: ${$.message}`);throw $}}async function iJ(N){if(!N.length)return 0;try{let $=N.map((G)=>({...E0(G),uuid:nJ()})),J=await P1.insertInto("drivers").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create drivers in bulk: ${$.message}`);throw $}}import{db as q1}from"@stacksjs/database";import{formatDate as f1}from"@stacksjs/orm";async function oJ(N,$){try{if(!N)throw Error("Driver ID is required for update");let J=await q1.updateTable("drivers").set({...E0($),updated_at:f1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update driver: ${J.message}`);throw J}}async function sJ(N,$){try{let J=await q1.updateTable("drivers").set({status:$,updated_at:f1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update driver status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update driver status: ${J.message}`);throw J}}async function dJ(N,$){try{let J={updated_at:f1(new Date)};if($!==void 0)J.phone=$;let G=await q1.updateTable("drivers").set(J).where("id","=",N).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update contact information");return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update contact information: ${J.message}`);throw J}}var O$={};B(O$,{validateLicenseKeyWrite:()=>$0,updateStatus:()=>M6,updateExpiration:()=>F6,update:()=>Z6,store:()=>W6,softDelete:()=>eJ,fetchById:()=>N6,fetchAll:()=>J6,destroy:()=>aJ,bulkStore:()=>Y6,bulkSoftDelete:()=>rJ,bulkDestroy:()=>tJ,LicenseKeyInputError:()=>E});import{db as R$}from"@stacksjs/database";async function aJ(N){try{let $=await R$.deleteFrom("license_keys").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license key: ${$.message}`);throw $}}async function eJ(N){try{let $=await R$.updateTable("license_keys").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license key: ${$.message}`);throw $}}async function tJ(N){if(!N.length)return 0;try{let $=await R$.deleteFrom("license_keys").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete license keys: ${$.message}`);throw $}}async function rJ(N){if(!N.length)return 0;try{let $=await R$.updateTable("license_keys").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete license keys: ${$.message}`);throw $}}import{db as $6}from"@stacksjs/database";async function N6(N){return await $6.selectFrom("license_keys").where("id","=",N).selectAll().executeTakeFirst()}async function J6(){return await $6.selectFrom("license_keys").selectAll().execute()}var{randomUUIDv7:L6}=globalThis.Bun;import{db as C1}from"@stacksjs/database";import{db as k1}from"@stacksjs/database";var G6=["Standard License","Premium License","Enterprise License"],X6=["active","inactive","unassigned"];class E extends TypeError{constructor(N){super(N);this.name="LicenseKeyInputError"}}function P0(N,$,J){return N[J]!==void 0?N[J]:$?.[J]}function j1(N,$,J,G){let X=P0(N,$,J);if(X===void 0||X===null||X==="")return null;let L=Number(X);if(!Number.isSafeInteger(L)||L<1)throw new E(`${G} must be a positive integer or null.`);return L}function xX(N){if(typeof N==="number")return N>2147483647?Math.floor(N/1000):N;if(typeof N==="string"&&/^\d{10,13}$/.test(N))return N.length===13?Math.floor(Number(N)/1000):Number(N);if(typeof N==="string"){let $=/^\d{4}-\d{2}-\d{2} \d/.test(N)?`${N.replace(" ","T")}Z`:N;return Math.floor(new Date($).getTime()/1000)}return Number.NaN}async function $0(N,$){let J=String(P0(N,$,"key")||"").trim().toUpperCase(),G=String(P0(N,$,"template")||""),X=String(P0(N,$,"status")||""),L=xX(P0(N,$,"expiry_date")),W=j1(N,$,"customer_id","Customer"),Y=j1(N,$,"product_id","Product"),Z=j1(N,$,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(J))throw new E("License key must use five groups of four uppercase letters or numbers.");if(!G6.includes(G))throw new E(`Template must be one of: ${G6.join(", ")}.`);if(!X6.includes(X))throw new E(`Status must be one of: ${X6.join(", ")}.`);if(!Number.isSafeInteger(L)||L<0||L>2147483647)throw new E("Expiry date must be a Unix timestamp between 1970 and 2038.");let[M,K,Q]=await Promise.all([W?k1.selectFrom("customers").where("id","=",W).select("id").executeTakeFirst():null,Y?k1.selectFrom("products").where("id","=",Y).select("id").executeTakeFirst():null,Z?k1.selectFrom("orders").where("id","=",Z).select(["id","customer_id"]).executeTakeFirst():null]);if(W&&!M)throw new E(`Customer ${W} was not found.`);if(Y&&!K)throw new E(`Product ${Y} was not found.`);if(Z&&!Q)throw new E(`Order ${Z} was not found.`);if(W&&Q?.customer_id&&Number(Q.customer_id)!==W)throw new E(`Order ${Z} belongs to Customer ${Q.customer_id}, not Customer ${W}.`);return{...N,key:J,template:G,expiry_date:L,status:X,customer_id:W,product_id:Y,order_id:Z}}async function W6(N){try{let $=L6(),J=U0(N),G={...await $0(J),uuid:$};await C1.insertInto("license_keys").values(G).executeTakeFirst();let X=await C1.selectFrom("license_keys").where("uuid","=",$).selectAll().executeTakeFirst();if(!X)throw Error("Failed to resolve created license key");return X}catch($){if($ instanceof E)throw $;if($ instanceof Error){if($.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${$.message}`)}throw $}}async function Y6(N){if(!N.length)return 0;try{let $=await Promise.all(N.map(async(G)=>({...await $0(U0(G)),uuid:L6()}))),J=await C1.insertInto("license_keys").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof E)throw $;if($ instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${$.message}`);throw $}}import{db as _$}from"@stacksjs/database";import{formatDate as I1}from"@stacksjs/orm";async function Z6(N,$){try{if(!N)throw Error("License key ID is required for update");let J=await _$.selectFrom("license_keys").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=U0($),X=await $0(G,J),L=await _$.updateTable("license_keys").set({...X,updated_at:I1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!L)return;return L}catch(J){if(J instanceof E)throw J;if(J instanceof Error){if(J.message.includes("UNIQUE constraint failed: license_keys.key"))throw new E("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${J.message}`)}throw J}}async function M6(N,$){try{let J=await _$.updateTable("license_keys").set({status:$,updated_at:I1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update license key status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update license key status: ${J.message}`);throw J}}async function F6(N,$){try{let J={updated_at:I1(new Date)};if($!==void 0)J.expiry_date=$;let G=await _$.updateTable("license_keys").set(J).where("id","=",N).returningAll().executeTakeFirst();if(!G)throw Error("Failed to update expiration information");return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update expiration information: ${J.message}`);throw J}}var U$={};B(U$,{updateStatus:()=>S6,updatePricing:()=>T6,update:()=>O6,store:()=>B6,softDelete:()=>Q6,getActiveShippingMethods:()=>_6,formatShippingOptions:()=>R6,fetchById:()=>w$,fetchAll:()=>V6,destroy:()=>K6,bulkStore:()=>A6,bulkSoftDelete:()=>H6,bulkDestroy:()=>x6});import{db as S$}from"@stacksjs/database";async function K6(N){try{let $=await S$.deleteFrom("shipping_methods").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping method: ${$.message}`);throw $}}async function Q6(N){try{let $=await S$.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${$.message}`);throw $}}async function x6(N){if(!N.length)return 0;try{let $=await S$.deleteFrom("shipping_methods").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping methods: ${$.message}`);throw $}}async function H6(N){if(!N.length)return 0;try{let $=await S$.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${$.message}`);throw $}}import{db as T$}from"@stacksjs/database";async function w$(N){let $=await T$.selectFrom("shipping_methods").where("id","=",N).selectAll().executeTakeFirst();if($){let J=await T$.selectFrom("shipping_zones").where("shipping_method_id","=",N).selectAll().execute();return{...$,shippingZones:J}}return}async function V6(){let N=await T$.selectFrom("shipping_methods").selectAll().execute();if(N.length===0)return[];let $=[...new Set(N.map((L)=>L.id))],X=(await T$.selectFrom("shipping_zones").where("shipping_method_id","in",$).selectAll().execute()).reduce((L,W)=>{let Y=W.shipping_method_id;if(Y!==null&&Y!==void 0){if(!L[Y])L[Y]=[];L[Y].push(W)}return L},{});return N.map((L)=>({...L,shipping_zones:X[L.id]||[]}))}var{randomUUIDv7:z6}=globalThis.Bun;import{db as q0}from"@stacksjs/database";async function B6(N){try{let $=z6(),J={...S0(N),uuid:$};await q0.insertInto("shipping_methods").values(J).executeTakeFirst();let G=await q0.selectFrom("shipping_methods").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created shipping method");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping method: ${$.message}`);throw $}}async function A6(N){if(!N.length)return 0;try{let $=N.map((G)=>({...S0(G),uuid:z6()})),J=await q0.insertInto("shipping_methods").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${$.message}`);throw $}}function R6(){try{return q0.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping options: ${N.message}`);throw N}}async function _6(){try{return await q0.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to get active shipping methods: ${N.message}`);throw N}}import{db as h1}from"@stacksjs/database";import{formatDate as g1}from"@stacksjs/orm";async function O6(N,$){try{if(!N)throw Error("Shipping method ID is required for update");let J=await h1.updateTable("shipping_methods").set({...S0($),updated_at:g1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping method: ${J.message}`);throw J}}async function S6(N,$){try{let J=await h1.updateTable("shipping_methods").set({status:$,updated_at:g1(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping method status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping method status: ${J.message}`);throw J}}async function T6(N,$,J){try{let G={updated_at:g1(new Date)};if($!==void 0)G.base_rate=$;if(J!==void 0)G.free_shipping=J;let X=await h1.updateTable("shipping_methods").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update pricing information");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update pricing information: ${G.message}`);throw G}}var k$={};B(k$,{validateZoneMatchesAddress:()=>I6,validateShippingRateWrite:()=>N0,updateByZone:()=>u6,updateByMethod:()=>i6,update:()=>c6,store:()=>m6,resolveZoneForAddress:()=>P$,getShippingRatesByMethod:()=>g6,getRatesByZone:()=>j6,getRateByWeightAndZone:()=>v1,getRateByWeightAndAddress:()=>C6,formatShippingRateOptions:()=>h6,fetchById:()=>f6,fetchAll:()=>k6,destroyByZone:()=>E6,destroyByMethod:()=>P6,destroy:()=>w6,bulkUpdate:()=>n6,bulkStore:()=>l6,bulkDestroy:()=>U6,ShippingRateInputError:()=>k});import{db as E$}from"@stacksjs/database";async function w6(N){try{let $=await E$.deleteFrom("shipping_rates").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rate: ${$.message}`);throw $}}async function U6(N){if(!N.length)return 0;try{let $=await E$.deleteFrom("shipping_rates").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates: ${$.message}`);throw $}}async function E6(N){try{let $=await E$.deleteFrom("shipping_rates").where("shipping_zone_id","=",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${$.message}`);throw $}}async function P6(N){try{let $=await E$.deleteFrom("shipping_rates").where("shipping_method_id","=",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${$.message}`);throw $}}import{db as v}from"@stacksjs/database";async function f6(N){let $=await v.selectFrom("shipping_rates").where("id","=",N).selectAll().executeTakeFirst();if($){let J=null,G=null;if($.shipping_zone_id)J=await v.selectFrom("shipping_zones").where("id","=",$.shipping_zone_id).selectAll().executeTakeFirst();if($.shipping_method_id)G=await v.selectFrom("shipping_methods").where("id","=",$.shipping_method_id).selectAll().executeTakeFirst();return{...$,shipping_zone:J,shipping_method:G}}return}async function k6(){let N=await v.selectFrom("shipping_rates").selectAll().execute();if(N.length===0)return[];let $=[...new Set(N.map((Y)=>Y.shipping_zone_id).filter((Y)=>Y!==null&&Y!==void 0))],J=[...new Set(N.map((Y)=>Y.shipping_method_id).filter((Y)=>Y!==null&&Y!==void 0))],[G,X]=await Promise.all([$.length?v.selectFrom("shipping_zones").where("id","in",$).selectAll().execute():[],J.length?v.selectFrom("shipping_methods").where("id","in",J).selectAll().execute():[]]),L=G.reduce((Y,Z)=>{return Y[Z.id]=Z,Y},{}),W=X.reduce((Y,Z)=>{return Y[Z.id]=Z,Y},{});return N.map((Y)=>({...Y,shipping_zone:Y.shipping_zone_id?L[Y.shipping_zone_id]:[],shipping_method:Y.shipping_method_id?W[Y.shipping_method_id]:[]}))}async function j6(N){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",N).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${$.message}`);throw $}}async function v1(N,$){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",$).where("weight_from","<=",N).where("weight_to",">=",N).executeTakeFirst()}catch(J){if(J instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${J.message}`);throw J}}async function P$(N){if(!N?.countryCode)return null;try{let $=await v.selectFrom("shipping_zones").selectAll().where("countries","like",`%${N.countryCode}%`).where("status","=","active").execute();if($.length===0)return null;let J=null;for(let G of $){let X=1;if(N.region&&G.regions&&q6(G.regions,N.region))X=2;if(N.postalCode&&G.postal_codes&&q6(G.postal_codes,N.postalCode))X=3;if(!J||X>J.score)J={id:G.id,score:X}}return J?.id??null}catch{return null}}async function C6(N,$){let J=await P$($);if(J==null)return;return v1(N,J)}async function I6(N,$){return await P$($)===N}function q6(N,$){if(!N||!$)return!1;let J=$.trim().toUpperCase();for(let G of N.split(/[,|;]/))if(G.trim().toUpperCase()===J)return!0;return!1}async function h6(){try{return(await v.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter(($)=>$.shipping_method_id!==null&&$.shipping_method_id!==void 0&&$.shipping_zone_id!==null&&$.shipping_zone_id!==void 0)}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping rate options: ${N.message}`);throw N}}async function g6(N){try{return await v.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",N).orderBy("weight_from").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${$.message}`);throw $}}var{randomUUIDv7:b6}=globalThis.Bun;import{db as y1}from"@stacksjs/database";import{db as f0}from"@stacksjs/database";async function v6(){return await f0.selectFrom("shipping_zones").selectAll().execute()}async function q$(N){return await f0.selectFrom("shipping_zones").where("id","=",N).selectAll().executeTakeFirst()}function y6(){try{return f0.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to format shipping zone options: ${N.message}`);throw N}}async function D6(){try{return await f0.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute()}catch(N){if(N instanceof Error)throw TypeError(`Failed to get active shipping zones: ${N.message}`);throw N}}async function p6(N){try{return await f0.selectFrom("shipping_zones").selectAll().where("countries","like",`%${N}%`).where("status","=","active").orderBy("name").execute()}catch($){if($ instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${$.message}`);throw $}}class k extends TypeError{constructor(N){super(N);this.name="ShippingRateInputError"}}function k0(N,$,J){return Number(N[J]??$?.[J])}async function N0(N,$){let J=k0(N,$,"shipping_method_id"),G=k0(N,$,"shipping_zone_id"),X=k0(N,$,"weight_from"),L=k0(N,$,"weight_to"),W=k0(N,$,"rate");if(!Number.isSafeInteger(J)||J<1)throw new k("Shipping method must be a positive integer.");if(!Number.isSafeInteger(G)||G<1)throw new k("Shipping zone must be a positive integer.");if(!Number.isFinite(X)||X<0)throw new k("Weight from must be a non-negative number.");if(!Number.isFinite(L)||L<X)throw new k("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(W)||W<0)throw new k("Rate must be a non-negative integer in minor currency units.");let[Y,Z]=await Promise.all([w$(J),q$(G)]);if(!Y)throw new k(`Shipping method ${J} was not found.`);if(!Z)throw new k(`Shipping zone ${G} was not found.`);if(Number(Z.shipping_method_id)!==J)throw new k(`Shipping zone ${G} is not assigned to shipping method ${J}.`)}async function m6(N){try{let $=n(N),J=Number($.shipping_method_id),G=Number($.shipping_zone_id);await N0($);let X=b6(),L={...$,shipping_method_id:J,shipping_zone_id:G,uuid:X};await y1.insertInto("shipping_rates").values(L).executeTakeFirst();let W=await y1.selectFrom("shipping_rates").where("uuid","=",X).selectAll().executeTakeFirst();if(!W)throw Error("Failed to resolve created shipping rate");return W}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rate: ${$.message}`);throw $}}async function l6(N){if(!N.length)return 0;try{for(let G of N){let X=n(G);await N0(X)}let $=N.map((G)=>({...n(G),uuid:b6()})),J=await y1.insertInto("shipping_rates").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof k)throw $;if($ instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${$.message}`);throw $}}import{db as j0}from"@stacksjs/database";import{formatDate as f$}from"@stacksjs/orm";async function c6(N,$){try{if(!N)throw Error("Shipping rate ID is required for update");let J=await j0.selectFrom("shipping_rates").where("id","=",N).selectAll().executeTakeFirst();if(!J)return;let G=n($);await N0(G,J);let X=await j0.updateTable("shipping_rates").set({...G,updated_at:f$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!X)return;return X}catch(J){if(J instanceof k)throw J;if(J instanceof Error)throw TypeError(`Failed to update shipping rate: ${J.message}`);throw J}}async function n6(N){if(!N.length)return 0;try{let $=0;for(let{id:J,data:G}of N){let X=await j0.updateTable("shipping_rates").set({...n(G),updated_at:f$(new Date)}).where("id","=",J).executeTakeFirst();if(F(X)>0)$++}return $}catch($){if($ instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${$.message}`);throw $}}async function u6(N,$){try{let J=await j0.updateTable("shipping_rates").set({...n($),updated_at:f$(new Date)}).where("shipping_zone_id","=",N).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${J.message}`);throw J}}async function i6(N,$){try{let J=await j0.updateTable("shipping_rates").set({...n($),updated_at:f$(new Date)}).where("shipping_method_id","=",N).executeTakeFirst();return F(J)}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${J.message}`);throw J}}var h$={};B(h$,{updateStatus:()=>NG,updateRegionsAndPostalCodes:()=>GG,updateCountries:()=>JG,update:()=>$G,store:()=>t6,softDelete:()=>s6,getZonesByCountry:()=>p6,getActiveShippingZones:()=>D6,formatZoneOptions:()=>y6,fetchById:()=>q$,fetchAll:()=>v6,destroy:()=>o6,bulkStore:()=>r6,bulkSoftDelete:()=>a6,bulkDestroy:()=>d6});import{db as j$}from"@stacksjs/database";async function o6(N){try{let $=await j$.deleteFrom("shipping_zones").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zone: ${$.message}`);throw $}}async function s6(N){try{let $=await j$.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${$.message}`);throw $}}async function d6(N){if(!N.length)return 0;try{let $=await j$.deleteFrom("shipping_zones").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete shipping zones: ${$.message}`);throw $}}async function a6(N){if(!N.length)return 0;try{let $=await j$.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${$.message}`);throw $}}var{randomUUIDv7:e6}=globalThis.Bun;import{db as D1}from"@stacksjs/database";async function t6(N){try{let $=e6(),J={...T0(N),uuid:$};await D1.insertInto("shipping_zones").values(J).executeTakeFirst();let G=await D1.selectFrom("shipping_zones").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to resolve created shipping zone");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zone: ${$.message}`);throw $}}async function r6(N){if(!N.length)return 0;try{let $=N.map((G)=>({...T0(G),uuid:e6()})),J=await D1.insertInto("shipping_zones").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${$.message}`);throw $}}import{db as C$}from"@stacksjs/database";import{formatDate as I$}from"@stacksjs/orm";async function $G(N,$){try{if(!N)throw Error("Shipping zone ID is required for update");let J=await C$.updateTable("shipping_zones").set({...T0($),updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)return;return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone: ${J.message}`);throw J}}async function NG(N,$){try{let J=await C$.updateTable("shipping_zones").set({status:$,updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping zone status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone status: ${J.message}`);throw J}}async function JG(N,$){try{let J=await C$.updateTable("shipping_zones").set({countries:$,updated_at:I$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update shipping zone countries");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${J.message}`);throw J}}async function GG(N,$,J){try{let G={updated_at:I$(new Date)};if($!==void 0)G.regions=$;if(J!==void 0)G.postal_codes=J;let X=await C$.updateTable("shipping_zones").set(G).where("id","=",N).returningAll().executeTakeFirst();if(!X)throw Error("Failed to update regions and postal codes");return X}catch(G){if(G instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${G.message}`);throw G}}var HX={digital:z$,drivers:A$,licenses:O$,methods:U$,rates:k$,routes:H$,zones:h$},VX=HX;var b1={};B(b1,{updateStatus:()=>VG,updateRate:()=>zG,updateDefaultStatus:()=>BG,update:()=>HG,store:()=>QG,fetchById:()=>ZG,fetchAll:()=>MG,destroy:()=>LG,bulkStore:()=>xG,bulkDestroy:()=>WG});import{db as XG}from"@stacksjs/database";async function LG(N){try{let $=await XG.deleteFrom("tax_rates").where("id","=",N).executeTakeFirst();return F($)>0}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rate: ${$.message}`);throw $}}async function WG(N){if(!N.length)return 0;try{let $=await XG.deleteFrom("tax_rates").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete tax rates: ${$.message}`);throw $}}import{db as YG}from"@stacksjs/database";async function ZG(N){return await YG.selectFrom("tax_rates").where("id","=",N).selectAll().executeTakeFirst()}async function MG(){return await YG.selectFrom("tax_rates").selectAll().execute()}var{randomUUIDv7:FG}=globalThis.Bun;import{db as KG}from"@stacksjs/database";async function QG(N){try{return await KG.transaction(async($)=>{let J={...N,uuid:FG()};if(J.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();let G=await $.insertInto("tax_rates").values(J).returningAll().executeTakeFirst();if(!G)throw Error("Failed to create tax rate");return G})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rate: ${$.message}`);throw $}}async function xG(N){if(!N.length)return 0;try{return await KG.transaction(async($)=>{let J=0;for(let G of N){let X={...G,uuid:FG()};if(X.is_default)await $.updateTable("tax_rates").set({is_default:!1}).execute();if(await $.insertInto("tax_rates").values(X).executeTakeFirst())J++}return J})}catch($){if($ instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${$.message}`);throw $}}import{db as g$}from"@stacksjs/database";import{formatDate as v$}from"@stacksjs/orm";async function HG(N,$){try{if(!N)throw Error("Tax rate ID is required for update");return await g$.transaction(async(J)=>{let G=await J.selectFrom("tax_rates").select("is_default").where("id","=",N).executeTakeFirst();if(!G)return;let X=$.is_default??Boolean(G.is_default),L=v$(new Date);if(X)await J.updateTable("tax_rates").set({is_default:!1,updated_at:L}).where("id","!=",N).execute();let W=await J.updateTable("tax_rates").set({...$,updated_at:L}).where("id","=",N).returningAll().executeTakeFirst();if(!W)return;return W})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate: ${J.message}`);throw J}}async function VG(N,$){try{let J=await g$.updateTable("tax_rates").set({status:$,updated_at:v$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update tax rate status");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate status: ${J.message}`);throw J}}async function zG(N,$){try{let J=await g$.updateTable("tax_rates").set({rate:$,updated_at:v$(new Date)}).where("id","=",N).returningAll().executeTakeFirst();if(!J)throw Error("Failed to update rate information");return J}catch(J){if(J instanceof Error)throw TypeError(`Failed to update rate information: ${J.message}`);throw J}}async function BG(N,$){try{return await g$.transaction(async(J)=>{if(!await J.selectFrom("tax_rates").select("id").where("id","=",N).executeTakeFirst())return!1;let X=v$(new Date);if($)await J.updateTable("tax_rates").set({is_default:!1,updated_at:X}).where("id","!=",N).execute();return await J.updateTable("tax_rates").set({is_default:$,updated_at:X}).where("id","=",N).execute(),!0})}catch(J){if(J instanceof Error)throw TypeError(`Failed to update tax rate default status: ${J.message}`);throw J}}var i1={};B(i1,{restaurant:()=>Q0,products:()=>D$,default:()=>UX});var D$={};B(D$,{updateStatus:()=>yG,updatePartySize:()=>DG,update:()=>y$,store:()=>gG,fetchWaiting:()=>qG,fetchPurchasedBetweenDates:()=>EG,fetchNotifiedBetweenDates:()=>UG,fetchCountByStatus:()=>fG,fetchCountBySource:()=>OG,fetchCountByQuantity:()=>TG,fetchCountByDateGrouped:()=>CG,fetchCountByDate:()=>SG,fetchCountByAllQuantities:()=>wG,fetchCountBetweenDates:()=>jG,fetchConversionRates:()=>kG,fetchCancelledBetweenDates:()=>PG,fetchById:()=>C0,fetchAll:()=>_G,destroy:()=>AG,bulkStore:()=>vG,bulkDestroy:()=>RG});import{db as m1}from"@stacksjs/database";async function AG(N){try{let $=await m1.selectFrom("waitlist_products").where("id","=",N).selectAll().executeTakeFirst();if(!$)return;return await m1.deleteFrom("waitlist_products").where("id","=",N).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist product: ${$.message}`);throw $}}async function RG(N){if(!N.length)return 0;try{let $=await m1.deleteFrom("waitlist_products").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${$.message}`);throw $}}import{db as A}from"@stacksjs/database";import{formatDate as U}from"@stacksjs/orm";async function C0(N){return await A.selectFrom("waitlist_products").where("id","=",N).selectAll().executeTakeFirst()}async function _G(){return await A.selectFrom("waitlist_products").selectAll().execute()}async function OG(N,$){let J=A.selectFrom("waitlist_products").select(["source",A.fn.count("id").as("count")]).groupBy("source");if(N&&$){let X=U(N),L=U($);J=J.where("created_at",">=",X).where("created_at","<=",L)}return(await J.execute()).reduce((X,{source:L,count:W})=>{return X[L]=W,X},{})}async function SG(N=new Date){let $=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=U($),X=U(J);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function TG(N){return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("quantity","=",N).executeTakeFirst())?.count??0}async function wG(N,$){let J=A.selectFrom("waitlist_products").select(["quantity",A.fn.count("id").as("count")]).groupBy("quantity");if(N&&$){let X=U(N),L=U($);J=J.where("created_at",">=",X).where("created_at","<=",L)}return(await J.execute()).reduce((X,{quantity:L,count:W})=>{return X[L]=W,X},{})}async function UG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("notified_at",">=",J).where("notified_at","<=",G).where("notified_at","is not",null).execute()}async function EG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",J).where("purchased_at","<=",G).where("purchased_at","is not",null).execute()}async function PG(N,$){let J=U(N),G=U($);return await A.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",J).where("cancelled_at","<=",G).where("cancelled_at","is not",null).execute()}async function qG(){return await A.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute()}async function fG(N,$,J){let G=A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("status","=",N);if($&&J){let L=U($),W=U(J);G=G.where("created_at",">=",L).where("created_at","<=",W)}return(await G.executeTakeFirst())?.count??0}async function kG(N,$){let J=A.selectFrom("waitlist_products").select(["status",A.fn.count("id").as("count")]).groupBy("status");if(N&&$){let Z=U(N),M=U($);J=J.where("created_at",">=",Z).where("created_at","<=",M)}let G=await J.execute(),X=G.reduce((Z,{count:M})=>Z+M,0),L=G.find((Z)=>Z.status==="purchased")?.count??0,W=X>0?L/X*100:0,Y=G.reduce((Z,{status:M,count:K})=>{return Z[M]={count:K,percentage:X>0?K/X*100:0},Z},{});return{totalConversionRate:W,statusBreakdown:Y}}async function jG(N,$){let J=U(N),G=U($);return(await A.selectFrom("waitlist_products").select(A.fn.count("id").as("count")).where("created_at",">=",J).where("created_at","<=",G).executeTakeFirst())?.count??0}async function CG(N,$){let J=A.selectFrom("waitlist_products").select(["created_at"]);if(N&&$){let L=U(N),W=U($);J=J.where("created_at",">=",L).where("created_at","<=",W)}let X=(await J.execute()).reduce((L,{created_at:W})=>{let Y=(W||"").split("T")[0]||"unknown";return L[Y]=(L[Y]||0)+1,L},{});return Object.entries(X).map(([L,W])=>({date:L,count:W})).sort((L,W)=>L.date.localeCompare(W.date))}var{randomUUIDv7:hG}=globalThis.Bun;import{db as l1}from"@stacksjs/database";import{formatDate as IG}from"@stacksjs/orm";var zX={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function BX(N){return typeof N==="number"||N instanceof Date?IG(N):N}function I0(N,$={}){let J=Object.fromEntries(Object.entries(N).filter(([,X])=>X!==void 0));if(J.quantity===void 0&&J.party_size!==void 0)J.quantity=J.party_size;delete J.party_size;for(let X of["notified_at","purchased_at","cancelled_at"])if(J[X]!==void 0)J[X]=BX(J[X]);let G=zX[J.status];if(G&&J[G]===void 0&&!$[G])J[G]=IG(new Date);return J}async function gG(N){try{let $=hG(),J={...I0(N),uuid:$,status:N.status||"waiting"};await l1.insertInto("waitlist_products").values(J).executeTakeFirst();let G=await l1.selectFrom("waitlist_products").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create waitlist product");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist product: ${$.message}`);throw $}}async function vG(N){if(!N.length)return 0;try{let $=N.map((G)=>({...I0(G),status:G.status||"waiting",uuid:hG()})),J=await l1.insertInto("waitlist_products").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${$.message}`);throw $}}import{db as AX}from"@stacksjs/database";import{formatDate as RX}from"@stacksjs/orm";async function y$(N,$){try{if(!N)throw Error("Waitlist product ID is required for update");let J=await C0(N);if(!J)return;await AX.updateTable("waitlist_products").set({...I0($,J),updated_at:RX(new Date)}).where("id","=",N).execute();let G=await C0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update waitlist product: ${J.message}`);throw J}}async function yG(N,$){return await y$(N,{status:$})}async function DG(N,$){return await y$(N,{quantity:$})}var Q0={};B(Q0,{updateWaitTimes:()=>F3,updateStatus:()=>Z3,updateQueuePosition:()=>K3,updatePartySize:()=>M3,update:()=>K0,store:()=>W3,fetchWaitingWithQuotedTimes:()=>eG,fetchWaitingWithPartySizes:()=>tG,fetchWaiting:()=>sG,fetchTimeSeriesStats:()=>X3,fetchTablesTurnedToday:()=>rG,fetchSeatingRate:()=>$3,fetchSeatedStats:()=>G3,fetchSeatedBetweenDates:()=>oG,fetchNoShowStats:()=>N3,fetchCurrentWaitTimes:()=>J3,fetchCountByTablePreference:()=>lG,fetchCountByPartySize:()=>nG,fetchCountByDate:()=>cG,fetchCountByAllPartySizes:()=>uG,fetchConversionRates:()=>dG,fetchById:()=>h0,fetchBetweenDates:()=>iG,fetchAverageWaitTimes:()=>aG,fetchAll:()=>mG,destroy:()=>pG,bulkStore:()=>Y3,bulkDestroy:()=>bG});import{db as c1}from"@stacksjs/database";async function pG(N){try{let $=await c1.selectFrom("waitlist_restaurants").where("id","=",N).selectAll().executeTakeFirst();if(!$)return;return await c1.deleteFrom("waitlist_restaurants").where("id","=",N).execute(),$}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${$.message}`);throw $}}async function bG(N){if(!N.length)return 0;try{let $=await c1.deleteFrom("waitlist_restaurants").where("id","in",N).executeTakeFirst();return F($)}catch($){if($ instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as V}from"@stacksjs/database";import{formatDate as h}from"@stacksjs/orm";async function h0(N){return await V.selectFrom("waitlist_restaurants").where("id","=",N).selectAll().executeTakeFirst()}async function mG(){return await V.selectFrom("waitlist_restaurants").selectAll().execute()}async function lG(){return(await V.selectFrom("waitlist_restaurants").select(["table_preference",V.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce(($,{table_preference:J,count:G})=>{return $[J]=G,$},{})}async function cG(N=new Date){let $=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=h($),X=h(J);return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("created_at",">=",G).where("created_at","<=",X).executeTakeFirst())?.count??0}async function nG(N){return(await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("party_size","=",N).executeTakeFirst())?.count??0}async function uG(){return(await V.selectFrom("waitlist_restaurants").select(["party_size",V.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce(($,{party_size:J,count:G})=>{return $[J]=G,$},{})}async function iG(N,$){let J=h(N),G=h($);return await V.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",J).where("created_at","<=",G).execute()}async function oG(N,$){let J=h(N),G=h($);return await V.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",J).where("check_in_time","<=",G).where("status","=","seated").execute()}async function sG(){return await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()}async function dG(){let N=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).groupBy("status").execute(),$=N.reduce((L,{count:W})=>L+W,0),J=N.find((L)=>L.status==="seated")?.count??0,G=$>0?Number(J)/$*100:0,X=N.reduce((L,{status:W,count:Y})=>{return L[W]={count:Y,percentage:$>0?Y/$*100:0},L},{});return{totalConversionRate:G,statusBreakdown:X}}async function aG(){let N=await V.selectFrom("waitlist_restaurants").select([V.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),V.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:N?.avg_quoted_wait_time??0,averageActualWaitTime:N?.avg_actual_wait_time??0}}async function eG(){let N=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=N.reduce((G,X)=>G+(X.quoted_wait_time??0),0),J=N.length>0?$/N.length:0;return{entries:N,totalQuotedWaitTime:$,averageQuotedWaitTime:J}}async function tG(){let N=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute(),$=N.reduce((X,L)=>X+L.party_size,0),J=N.length>0?$/N.length:0,G=N.reduce((X,L)=>{return X[L.party_size]=(X[L.party_size]||0)+1,X},{});return{entries:N,totalPartySize:$,averagePartySize:J,partySizeBreakdown:G}}async function rG(){let N=new Date,$=new Date(N);$.setHours(0,0,0,0);let J=new Date(N);J.setHours(23,59,59,999);let G=h($),X=h(J),L=await V.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",G).where("check_in_time","<=",X).execute(),W=L.length,Y=L.reduce((Q,x)=>Q+x.party_size,0),Z=W>0?Y/W:0,M=L.reduce((Q,x)=>{return Q[x.table_preference]=(Q[x.table_preference]||0)+1,Q},{}),K=L.reduce((Q,x)=>{return Q[x.party_size]=(Q[x.party_size]||0)+1,Q},{});return{totalTablesTurned:W,averagePartySize:Z,totalCustomersSeated:Y,breakdownByTablePreference:M,breakdownByPartySize:K}}async function $3(N,$){let J=h(N),G=h($),X=await V.selectFrom("waitlist_restaurants").select(["status",V.fn.count("id").as("count")]).where("check_in_time",">=",J).where("check_in_time","<=",G).groupBy("status").execute(),L=X.reduce((M,{count:K})=>M+K,0),W=X.find((M)=>M.status==="seated")?.count??0,Y=L>0?Number(W)/L*100:0,Z=X.reduce((M,{status:K,count:Q})=>{return M[K]={count:Q,percentage:L>0?Q/L*100:0},M},{});return{totalEntries:L,seatedEntries:W,seatingRate:Y,statusBreakdown:Z}}async function N3(N,$){let J=h(N),G=h($),X=V.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",J).where("check_in_time","<=",G),L=await V.selectFrom("waitlist_restaurants").select(V.fn.count("id").as("count")).where("check_in_time",">=",J).where("check_in_time","<=",G).executeTakeFirst(),W=await X.execute(),Y=W.length,Z=L?.count&&L.count>0?Y/L.count*100:0,M=W.reduce((_,S)=>_+(S.quoted_wait_time??0),0),K=Y>0?M/Y:0,Q=W.reduce((_,S)=>_+S.party_size,0),x=Y>0?Q/Y:0,R=W.reduce((_,S)=>{return _[S.table_preference]=(_[S.table_preference]||0)+1,_},{}),O=W.reduce((_,S)=>{return _[S.party_size]=(_[S.party_size]||0)+1,_},{});return{totalNoShows:Y,noShowRate:Z,averageQuotedWaitTime:K,averagePartySize:x,breakdownByTablePreference:R,breakdownByPartySize:O}}async function J3(){let N=await V.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),$=N.reduce((X,L)=>X+(L.quoted_wait_time||0),0),J=N.reduce((X,L)=>X+(L.actual_wait_time||0),0),G=N.length;return{averageQuoted:G>0?$/G:0,averageActual:G>0?J/G:0}}async function G3(){let N=Date.now()-86400000,$=await V.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",N).execute(),J=Array.from({length:24},(G,X)=>({hour:X,count:$.filter((L)=>{return L.seated_at===X}).length}));return{total:$.length,byHour:J}}async function X3(){return(await V.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce(($,J)=>{let G=J.created_at;if(!$[G])$[G]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return $[G].total++,$[G][J.status]++,$},{})}var{randomUUIDv7:L3}=globalThis.Bun;import{db as u1}from"@stacksjs/database";import{formatDate as n1}from"@stacksjs/orm";var _X={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function OX(N){if(typeof N==="number")return n1(N<=2147483647?N*1000:N);if(N instanceof Date)return n1(N);return N}function g0(N,$={}){let J=Object.fromEntries(Object.entries(N).filter(([,X])=>X!==void 0));for(let X of["check_in_time","seated_at","no_show_at","cancelled_at"])if(J[X]!==void 0)J[X]=OX(J[X]);let G=_X[J.status];if(G&&J[G]===void 0&&!$[G])J[G]=n1(new Date);return J}async function W3(N){try{let $=L3(),J={...g0(N),status:N.status||"waiting",uuid:$};await u1.insertInto("waitlist_restaurants").values(J).executeTakeFirst();let G=await u1.selectFrom("waitlist_restaurants").where("uuid","=",$).selectAll().executeTakeFirst();if(!G)throw Error("Failed to create restaurant waitlist entry");return G}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${$.message}`);throw $}}async function Y3(N){if(!N.length)return 0;try{let $=N.map((G)=>({...g0(G),status:G.status||"waiting",uuid:L3()})),J=await u1.insertInto("waitlist_restaurants").values($).executeTakeFirst();return F(J)}catch($){if($ instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${$.message}`);throw $}}import{db as SX}from"@stacksjs/database";import{formatDate as TX}from"@stacksjs/orm";async function K0(N,$){try{if(!N)throw Error("Restaurant waitlist entry ID is required for update");let J=await h0(N);if(!J)return;await SX.updateTable("waitlist_restaurants").set({...g0($,J),updated_at:TX(new Date)}).where("id","=",N).execute();let G=await h0(N);if(!G)return;return G}catch(J){if(J instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${J.message}`);throw J}}async function Z3(N,$){return await K0(N,{status:$})}async function M3(N,$){return await K0(N,{party_size:$})}async function F3(N,$,J){return await K0(N,{quoted_wait_time:$,...J===void 0?{}:{actual_wait_time:J}})}async function K3(N,$){return await K0(N,{queue_position:$})}var wX={products:D$,restaurant:Q0},UX=wX;var EX={coupons:p$,customers:b$,devices:u$,errors:s$,giftCards:a$,orders:Y1,payments:Z1,products:V1,receipts:O1,restaurant:Q0,shippings:p1,tax:b1,waitlists:i1},vK=EX;export{i1 as waitlists,b1 as tax,p1 as shippings,Q0 as restaurant,O1 as receipts,V1 as products,Z1 as payments,Y1 as orders,a$ as giftCards,s$ as errors,u$ as devices,vK as default,b$ as customers,p$ as coupons,EX as commerce};