@stacksjs/commerce 0.75.36 → 0.75.38

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 (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +12 -12
package/dist/index.js CHANGED
@@ -25,4 +25,4 @@ var Lm=Object.defineProperty;var jm=(t)=>t;function zm(t,e){this[t]=jm.bind(null
25
25
  updated_at = ${o(3)}
26
26
  WHERE id = ${o(4)}
27
27
  AND status IN ('completed', 'succeeded', 'partiallyRefunded')
28
- AND COALESCE(refund_amount, 0) + ${o(5)} <= amount`,[e,e,n,t,e]);if(Lp(a)>0){let l=await ye(t);if(l)return l;throw Error(`Payment with ID ${t} disappeared during refund`)}let s=await ye(t);if(!s)throw Error(`Payment with ID ${t} not found`);let i=String(s.status||"");if(!Gp.has(i))throw Error(`Payment status ${i||"unknown"} cannot be refunded`);let u=s,c=Number(s.amount||0)-Number(u.refundAmount??u.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${c} minor units`)}var jo={};g(jo,{categories:()=>Nt,default:()=>sf,items:()=>Jt,manufacturers:()=>Bt,reviews:()=>Ot,units:()=>Wt,variants:()=>Lt});var Nt={};g(Nt,{bulkRemove:()=>Ti,compareCategoryGrowth:()=>vi,deactivate:()=>Si,deactivateChildCategories:()=>Ci,fetchActive:()=>bi,fetchAll:()=>Bo,fetchByDisplayOrder:()=>xi,fetchById:()=>S,fetchByName:()=>gi,fetchCategoryTree:()=>Pi,fetchChildCategories:()=>Ri,fetchRootCategories:()=>_i,fetchStats:()=>Di,findOrCreateByName:()=>Mi,remove:()=>ki,removeChildCategories:()=>Ei,store:()=>Oo,update:()=>Ii,updateActiveStatus:()=>Ji,updateDisplayOrder:()=>Ni,updateParent:()=>Bi});import{db as Ke,matchedRows as qp}from"@stacksjs/database/runtime";import{formatDate as Fi}from"@stacksjs/orm";import{db as P}from"@stacksjs/database/runtime";import{formatDate as He}from"@stacksjs/orm";async function Bo(){return await P.selectFrom("categories").selectAll().execute()}async function S(t){return await P.selectFrom("categories").where("id","=",t).selectAll().executeTakeFirst()}async function gi(t){return await P.selectFrom("categories").where("name","=",t).selectAll().executeTakeFirst()}async function bi(){return await P.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function _i(){return await P.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function Ri(t){return await P.selectFrom("categories").where("parent_category_id","=",t).where("is_active","=",!0).selectAll().execute()}async function xi(t=!0){let e=P.selectFrom("categories").where("is_active","=",!0).selectAll();if(t)return await e.orderBy("display_order","asc").execute();else return await e.orderBy("display_order","desc").execute()}async function Di(){let t=await P.selectFrom("categories").select(P.fn.count("id").as("count")).executeTakeFirst(),e=await P.selectFrom("categories").where("is_active","=",!0).select(P.fn.count("id").as("count")).executeTakeFirst(),r=await P.selectFrom("categories").whereNull("parent_category_id").select(P.fn.count("id").as("count")).executeTakeFirst(),o=await P.selectFrom("categories").whereNotNull("image_url").select(P.fn.count("id").as("count")).executeTakeFirst(),n=new Date;n.setDate(n.getDate()-30);let a=He(n),s=await P.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await P.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",P.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(t?.count||0),active:Number(e?.count||0),root_categories:Number(r?.count||0),child_categories:Number(t?.count||0)-Number(r?.count||0),with_images:Number(o?.count||0),recently_added:s,top_parent_categories:i.map((u)=>({id:String(u.parent_category_id||""),name:String(u.parent_name||""),child_count:Number(u.child_count)}))}}async function vi(t=30){let e=new Date,r=He(e),o=new Date;o.setDate(e.getDate()-t);let n=He(o),a=new Date(o);a.setDate(a.getDate()-1);let s=He(a),i=new Date(a);i.setDate(a.getDate()-t);let u=He(i),c=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",r).executeTakeFirst(),l=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),m=Number(c?.count||0),f=Number(l?.count||0),h=m-f,b=f!==0?h/f*100:m>0?100:0;return{current_period:m,previous_period:f,difference:h,percentage_change:b,days_range:t}}async function Pi(){let t=await Bo(),e=new Map;t.forEach((n)=>{e.set(n.id,{...n,children:[]})});let r=[];t.forEach((n)=>{let a=e.get(n.id);if(n.parent_category_id){let s=e.get(n.parent_category_id);if(s)s.children.push(a)}else r.push(a)}),r.sort((n,a)=>n.display_order-a.display_order);let o=(n)=>{n.sort((a,s)=>a.display_order-s.display_order),n.forEach((a)=>{if(a.children.length>0)o(a.children)})};return o(r),r}async function ki(t){let e=await Ke.deleteFrom("categories").where("id","=",t).executeTakeFirst();return p(e)>0}async function Ti(t){if(!t.length)return 0;let e=await Ke.deleteFrom("categories").where("id","in",t).executeTakeFirst();return p(e)}async function Ei(t){let e=await Ke.deleteFrom("categories").where("parent_category_id","=",t).executeTakeFirst();return p(e)}async function Si(t){if(!await S(t))throw Error(`Category with ID ${t} not found`);let r=await Ke.updateTable("categories").set({is_active:!1,updated_at:Fi(new Date)}).where("id","=",t).returning("id").executeTakeFirst();return Boolean(r)}async function Ci(t){return(await qp(Ke.updateTable("categories").set({is_active:!1,updated_at:Fi(new Date)}).where("parent_category_id","=",t))).length}var{randomUUIDv7:Vp}=globalThis.Bun;import{db as Ai}from"@stacksjs/database/runtime";import{HttpError as Mt}from"@stacksjs/error-handling";import{isUniqueViolation as Zp}from"@stacksjs/orm";import{slug as Hp}from"@stacksjs/strings";async function Oo(t){try{let e=t.parent_category_id?Number(t.parent_category_id):void 0;if(e!==void 0&&(!Number.isSafeInteger(e)||e<=0))throw new Mt(422,"Parent category ID must be a positive integer");if(e&&!await S(e))throw new Mt(422,`Parent category with ID ${t.parent_category_id} not found`);let r={...t,uuid:Vp(),is_active:t.is_active??!0,parent_category_id:t.parent_category_id||null},o=await Ai.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create category");return o}catch(e){if(e instanceof Mt)throw e;if(Zp(e))throw new Mt(409,"A category with this name or slug already exists");if(e instanceof Error)throw Error(`Failed to create category: ${e.message}`);throw e}}async function Mi(t){if(!t.name)throw Error("Name is required");let e=await Ai.selectFrom("categories").selectAll().where("name","=",t.name).executeTakeFirst();if(e)return e;let r={name:t.name,slug:Hp(t.name),is_active:t.is_active??!0,display_order:0};return await Oo(r)}import{db as Qe}from"@stacksjs/database/runtime";import{HttpError as ke}from"@stacksjs/error-handling";import{formatDate as It,isUniqueViolation as Kp}from"@stacksjs/orm";async function Ii(t,e){if(!await S(t))return;if(Object.hasOwn(e,"parent_category_id")){let o=e.parent_category_id?Number(e.parent_category_id):void 0;if(o!==void 0&&(!Number.isSafeInteger(o)||o<=0))throw new ke(422,"Parent category ID must be a positive integer");if(o===t)throw new ke(422,"A category cannot be its own parent");if(o&&!await S(o))throw new ke(422,`Parent category with ID ${e.parent_category_id} not found`);if(o&&await Oi(t,String(o)))throw new ke(422,"This operation would create a circular category hierarchy")}try{let o=Object.hasOwn(e,"parent_category_id")?{parent_category_id:e.parent_category_id||null}:{},n=await Qe.updateTable("categories").set({...e,...o,updated_at:It(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return n}catch(o){if(o instanceof ke)throw o;if(Kp(o))throw new ke(409,"A category with this name or slug already exists");if(o instanceof Error)throw Error(`Failed to update category: ${o.message}`);throw o}}async function Ni(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);try{return await Qe.updateTable("categories").set({display_order:e,updated_at:It(new Date)}).where("id","=",t).execute(),await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category display order: ${o.message}`);throw o}}async function Ji(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);try{return await Qe.updateTable("categories").set({is_active:e,updated_at:It(new Date)}).where("id","=",t).execute(),await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category active status: ${o.message}`);throw o}}async function Bi(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);if(e){let o=Number(e);if(o===t)throw Error("A category cannot be its own parent");if(!await S(o))throw Error(`Parent category with ID ${e} not found`);if(await Oi(t,e))throw Error("This operation would create a circular reference in the category hierarchy")}try{let o={updated_at:It(new Date)};if(e===null)await Qe.updateTable("categories").set({...o,parent_category_id:null}).where("id","=",t).execute();else await Qe.updateTable("categories").set({...o,parent_category_id:e}).where("id","=",t).execute();return await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category parent: ${o.message}`);throw o}}async function Oi(t,e){let r=Number(e),o=new Set;while(r){if(o.has(r))return!0;if(r===t)return!0;o.add(r);let n=await S(r),a=n?.parent_category_id;if(!n||!a)return!1;r=Number(a)}return!1}var Jt={};g(Jt,{bulkDestroy:()=>Wi,bulkStore:()=>Zi,destroy:()=>$i,fetchAll:()=>Li,fetchById:()=>ee,fetchTopProducts:()=>zi,store:()=>Vi,update:()=>Hi,updateAvailability:()=>Ki,updateInventory:()=>Qi});import{db as Ui}from"@stacksjs/database/runtime";async function $i(t){try{let e=await Ui.deleteFrom("products").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product item: ${e.message}`);throw e}}async function Wi(t){if(!t.length)return 0;try{let e=await Ui.deleteFrom("products").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product items: ${e.message}`);throw e}}import{db as X,sql as Qp}from"@stacksjs/database/runtime";async function ee(t){let e=await X.selectFrom("products").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.manufacturer_id)r=await X.selectFrom("manufacturers").where("id","=",e.manufacturer_id).selectAll().executeTakeFirst();if(e.category_id)o=await X.selectFrom("categories").where("id","=",e.category_id).selectAll().executeTakeFirst();return{...e,manufacturer:r,category:o}}return}async function Li(){let t=await X.selectFrom("products").selectAll().execute(),e=t.map((c)=>c.manufacturer_id).filter((c)=>c!==null&&c!==void 0),r=t.map((c)=>c.category_id).filter((c)=>c!==null&&c!==void 0),o=X.selectFrom("manufacturers"),n=X.selectFrom("categories");if(e.length>0)o=o.where("id","in",e);if(r.length>0)n=n.where("id","in",r);let a=await o.selectAll().execute(),s=await n.selectAll().execute(),i=a.reduce((c,l)=>(c[l.id]=l,c),{}),u=s.reduce((c,l)=>(c[l.id]=l,c),{});return t.map((c)=>({...c,manufacturer:c.manufacturer_id?i[c.manufacturer_id]:null,category:c.category_id?u[c.category_id]:null}))}async function ji(t){try{let e=await X.selectFrom("products").selectAll().where("uuid","=",t).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get product by UUID: ${e.message}`);throw e}}async function zi(t=5){try{return(await X.selectFrom("order_items").innerJoin("products","products.id","=","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",X.fn.sum("order_items.quantity").as("units_sold"),Qp`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(t).execute()).map((r)=>({id:Number(r.id),name:String(r.name??"Unnamed product"),units_sold:Number(r.units_sold??0),revenue:Number(r.revenue??0),inventory_count:Number(r.inventory_count??0)}))}catch(e){if(e instanceof Error)throw TypeError(`Failed to fetch top products: ${e.message}`);throw e}}var{randomUUIDv7:Gi}=globalThis.Bun;import{db as qi}from"@stacksjs/database/runtime";async function Vi(t){try{let e={...t,uuid:Gi()},r=await qi.insertInto("products").values(e).executeTakeFirst();if(!r)throw Error("Failed to create product item");let o=H(r),n=o!==void 0?await ee(o):await ji(e.uuid);if(!n)throw Error("Failed to create product item");return n}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product item: ${e.message}`);throw e}}async function Zi(t){if(!t.length)return 0;let e=0;try{return await qi.transaction(async(r)=>{for(let o of t){let n={...o,uuid:Gi()};await r.insertInto("products").values(n).execute(),e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product items in bulk: ${r.message}`);throw r}}import{db as Uo,matchedRows as y_}from"@stacksjs/database/runtime";import{formatDate as $o}from"@stacksjs/orm";async function Hi(t,e){try{if(!t)throw Error("Product item ID is required for update");let r=await Uo.updateTable("products").set({...e,updated_at:$o(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function Ki(t,e){if(!await ee(t))throw Error(`Product item with ID ${t} not found`);try{return await Uo.updateTable("products").set({is_available:e,updated_at:$o(new Date)}).where("id","=",t).execute(),await ee(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update product item availability: ${o.message}`);throw o}}async function Qi(t,e){let r=await ee(t);if(!r)throw Error(`Product item with ID ${t} not found`);let o={updated_at:$o(new Date)};if(e!==void 0)o.inventory_count=e;if(Object.keys(o).length===1)return r;try{return await Uo.updateTable("products").set(o).where("id","=",t).execute(),await ee(t)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update inventory information: ${n.message}`);throw n}}var Bt={};g(Bt,{bulkDestroy:()=>eu,bulkStore:()=>lu,destroy:()=>Xi,fetchAll:()=>tu,fetchByCountry:()=>au,fetchById:()=>ru,fetchByUuid:()=>ou,fetchFeatured:()=>nu,fetchWithProductCount:()=>su,store:()=>du,update:()=>pu,updateByUuid:()=>wu,updateFeaturedStatus:()=>fu});import{db as Yi}from"@stacksjs/database/runtime";async function Xi(t){try{let e=await Yi.deleteFrom("manufacturers").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete order: ${e.message}`);throw e}}async function eu(t){if(!t.length)return 0;try{let e=await Yi.deleteFrom("manufacturers").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete orders: ${e.message}`);throw e}}import{db as te}from"@stacksjs/database/runtime";async function tu(){return w(await te.selectFrom("manufacturers").selectAll().execute())}async function ru(t){let e=await te.selectFrom("manufacturers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ou(t){let e=await te.selectFrom("manufacturers").where("uuid","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function nu(t=10){let e=await te.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(t).execute();return w(e)}async function au(t,e={}){let r=e.page||1,o=e.limit||2,n=await te.selectFrom("manufacturers").select(te.fn.count("id").as("total")).where("country","=",t).executeTakeFirst(),a=Number(n?.total||0),s=await te.selectFrom("manufacturers").selectAll().where("country","=",t).limit(o).offset((r-1)*o).execute(),i=Math.ceil(a/o);return{data:w(s),paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function su(t={}){let e=te.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(t.country)e=e.where("m.country","=",t.country);if(t.featured!==void 0)e=e.where("m.featured","=",t.featured);return e=e.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",te.fn.count("p.id").as("product_count")]).groupBy("m.id"),e.execute()}var{randomUUIDv7:uu}=globalThis.Bun;import{db as cu}from"@stacksjs/database/runtime";import{HttpError as iu}from"@stacksjs/error-handling";import{isUniqueViolation as Yp}from"@stacksjs/orm";async function du(t){try{let e={...t,uuid:uu(),featured:t.featured??!1},r=await cu.insertInto("manufacturers").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return d(r)}catch(e){if(e instanceof iu)throw e;if(Yp(e))throw new iu(409,"A manufacturer with this name already exists");if(e instanceof Error)throw Error(`Failed to create manufacturer: ${e.message}`);throw e}}async function lu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:uu(),featured:r.featured??!1};await cu.insertInto("manufacturers").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${r.message}`);throw r}}import{db as Wo}from"@stacksjs/database/runtime";import{HttpError as mu}from"@stacksjs/error-handling";import{formatDate as Lo,isUniqueViolation as Xp}from"@stacksjs/orm";async function pu(t,e){try{if(!t)throw Error("Manufacturer ID is required for update");let r=await Wo.updateTable("manufacturers").set({...e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof mu)throw r;if(Xp(r))throw new mu(409,"A manufacturer with this name already exists");if(r instanceof Error)throw Error(`Failed to update manufacturer: ${r.message}`);throw r}}async function fu(t,e){try{let r=await Wo.updateTable("manufacturers").set({featured:e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function wu(t,e){try{let r=await Wo.updateTable("manufacturers").set({...e,updated_at:Lo(new Date)}).where("uuid","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var Ot={};g(Ot,{bulkDestroy:()=>gu,destroy:()=>hu,fetchAll:()=>_u,fetchApprovedByProductId:()=>Du,fetchById:()=>bu,fetchByProductId:()=>Ru,fetchByUserId:()=>xu,fetchMostHelpfulByProductId:()=>vu,fetchStats:()=>Tu,fetchStatsByProductIds:()=>Eu,store:()=>Su,update:()=>Mu,updateVotes:()=>Iu});import{db as yu}from"@stacksjs/database/runtime";async function hu(t){try{let e=await yu.deleteFrom("reviews").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete review: ${e.message}`);throw e}}async function gu(t){if(!t.length)return 0;try{let e=await yu.deleteFrom("reviews").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete reviews: ${e.message}`);throw e}}import{db as Te}from"@stacksjs/database/runtime";async function bu(t){return d(await Te.selectFrom("reviews").where("id","=",t).selectAll().executeTakeFirst(),!0)}async function _u(){return w(await Te.selectFrom("reviews").selectAll().execute())}async function Ru(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).selectAll().execute())}async function xu(t){return w(await Te.selectFrom("reviews").where("customer_id","=",t).selectAll().execute())}async function Du(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).where("is_approved","=",!0).selectAll().execute())}async function vu(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).orderBy("helpful_votes","desc").selectAll().execute())}import{db as Pu}from"@stacksjs/database/runtime";function Fu(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function ku(t){let e=Fu();e.total=t.length;let r=0;for(let o of t){if(o.rating===null||o.rating===void 0){e.commentsOnly++;continue}let n=Number(o.rating);if(Number.isNaN(n)){e.commentsOnly++;continue}e.rated++,r+=n;let a=Math.min(5,Math.max(1,Math.round(n)));e.distribution[a]++}if(e.rated>0)e.average=Math.round(r/e.rated*10)/10;return e}async function Tu(t){let e=await Pu.selectFrom("reviews").select(["rating"]).where("product_id","=",t).where("is_approved","=",!0).execute();return ku(e)}async function Eu(t){let e=new Map;for(let n of t)e.set(n,Fu());if(t.length===0)return e;let r=await Pu.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",t).where("is_approved","=",!0).execute(),o=new Map;for(let n of r){let a=o.get(n.product_id);if(a)a.push({rating:n.rating});else o.set(n.product_id,[{rating:n.rating}])}for(let[n,a]of o)e.set(n,ku(a));return e}var{randomUUIDv7:ef}=globalThis.Bun;import{db as tf}from"@stacksjs/database/runtime";function rf(t){let e=t.rating!==void 0&&t.rating!==null,r=typeof t.content==="string"&&t.content.trim().length>0,o=typeof t.title==="string"&&t.title.trim().length>0;return!e&&!r&&!o}async function Su(t){try{if(rf(t))throw Error("A review needs a rating or something written: both were empty");let e={...t,uuid:ef(),rating:t.rating??null,is_verified_purchase:t.is_verified_purchase??!1,is_approved:t.is_approved??!1,helpful_votes:t.helpful_votes??0,unhelpful_votes:t.unhelpful_votes??0,is_featured:t.is_featured??!1},r=await tf.insertInto("reviews").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return d(r)}catch(e){if(e instanceof Error){if(e.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${e.message}`)}throw e}}import{db as Cu}from"@stacksjs/database/runtime";import{formatDate as Au}from"@stacksjs/orm";async function Mu(t,e){try{if(!t)throw Error("Review ID is required for update");let r=await Cu.updateTable("reviews").set({...e,updated_at:Au(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function Iu(t,e,r=!0){try{let o=e==="helpful"?"helpful_votes":"unhelpful_votes",n=r?`COALESCE("${o}", 0) + 1`:`MAX(COALESCE("${o}", 0) - 1, 0)`,a=await Cu.unsafe(`UPDATE "reviews" SET "${o}" = ${n}, "updated_at" = ? WHERE "id" = ? RETURNING *`,[Au(new Date),t]).execute(),s=Array.isArray(a)?a[0]:a;if(!s)throw Error("Failed to update review votes");return d(s)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update review votes: ${o.message}`);throw o}}var Wt={};g(Wt,{bulkDestroy:()=>Bu,bulkStore:()=>ju,bulkUpdate:()=>Vu,destroy:()=>Ju,fetchAll:()=>$u,fetchById:()=>Uu,formatUnitOptions:()=>zu,getDefaultUnit:()=>Gu,store:()=>Lu,update:()=>qu,updateDefaultStatus:()=>Zu});import{db as Nu}from"@stacksjs/database/runtime";async function Ju(t){try{let e=await Nu.deleteFrom("product_units").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product unit: ${e.message}`);throw e}}async function Bu(t){if(!t.length)return 0;try{let e=await Nu.deleteFrom("product_units").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product units: ${e.message}`);throw e}}import{db as Ou}from"@stacksjs/database/runtime";async function Uu(t){let e=await Ou.selectFrom("product_units").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function $u(){return w(await Ou.selectFrom("product_units").selectAll().execute())}var{randomUUIDv7:Wu}=globalThis.Bun;import{db as Ye}from"@stacksjs/database/runtime";async function Lu(t){try{return await Ye.transaction(async(e)=>{let r={...t,uuid:Wu()},o=await e.insertInto("product_units").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create product unit");if(r.is_default&&r.type)await e.updateTable("product_units").set({is_default:!1}).where("type","=",r.type).where("id","!=",o.id).execute();return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product unit: ${e.message}`);throw e}}async function ju(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:Wu()},n=await Ye.insertInto("product_units").values(o).returningAll().executeTakeFirst();if(o.is_default&&o.type&&n)await Ye.updateTable("product_units").set({is_default:!1}).where("type","=",o.type).where("id","!=",n.id).execute();e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product units in bulk: ${r.message}`);throw r}}function zu(t){try{let e=Ye.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(t)e=e.where("type","=",t);return e=e.orderBy("name"),e.execute().then((r)=>r.map((o)=>({id:String(o.id),name:o.name,abbreviation:o.abbreviation,is_default:o.is_default})))}catch(e){if(e instanceof Error)throw TypeError(`Failed to format unit options: ${e.message}`);throw e}}async function Gu(t){try{let e=await Ye.selectFrom("product_units").selectAll().where("type","=",t).where("is_default","=",!0).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get default unit: ${e.message}`);throw e}}import{db as Ut,matchedRows as of}from"@stacksjs/database/runtime";import{formatDate as $t}from"@stacksjs/orm";async function qu(t,e){try{if(!t)throw Error("Product unit ID is required for update");return await Ut.transaction(async(r)=>{let o=await r.selectFrom("product_units").select(["type","is_default"]).where("id","=",t).executeTakeFirst();if(!o)return;let n=e.type??o.type;if((e.is_default??Boolean(o.is_default))&&n)await r.updateTable("product_units").set({is_default:!1,updated_at:$t(new Date)}).where("type","=",n).where("id","!=",t).execute();let s=await r.updateTable("product_units").set({...e,updated_at:$t(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function Vu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o=r;if(!o.id)continue;let n=o.data&&typeof o.data==="object"?o.data:{...o};delete n.id;let a=await of(Ut.updateTable("product_units").set({...n,updated_at:$t(new Date)}).where("id","=",o.id)),s=n;if(s.is_default===!0&&s.type)await Ut.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",o.id).execute();if(a.length>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product units in bulk: ${r.message}`);throw r}}async function Zu(t,e){try{return await Ut.transaction(async(r)=>{let o=await r.selectFrom("product_units").select("type").where("id","=",t).executeTakeFirst();if(!o)return!1;let n=$t(new Date);if(e&&o.type)await r.updateTable("product_units").set({is_default:!1,updated_at:n}).where("type","=",o.type).where("id","!=",t).execute();return await r.updateTable("product_units").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit default status: ${r.message}`);throw r}}var Lt={};g(Lt,{bulkDestroy:()=>Qu,bulkStore:()=>nc,bulkUpdate:()=>dc,destroy:()=>Ku,fetchAll:()=>ec,fetchById:()=>Xu,formatVariantOptions:()=>ac,generateVariantCombinations:()=>sc,store:()=>oc,update:()=>cc});import{db as Hu}from"@stacksjs/database/runtime";async function Ku(t){try{let e=await Hu.deleteFrom("product_variants").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variant: ${e.message}`);throw e}}async function Qu(t){if(!t.length)return 0;try{let e=await Hu.deleteFrom("product_variants").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variants: ${e.message}`);throw e}}import{db as Yu}from"@stacksjs/database/runtime";async function Xu(t){let e=await Yu.selectFrom("product_variants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ec(){return w(await Yu.selectFrom("product_variants").selectAll().execute())}var{randomUUIDv7:tc}=globalThis.Bun;import{db as rc}from"@stacksjs/database/runtime";async function oc(t){try{let e={...t,uuid:tc()},r=await rc.insertInto("product_variants").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return d(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product variant: ${e.message}`);throw e}}async function nc(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:tc()};await rc.insertInto("product_variants").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${r.message}`);throw r}}function ac(t){if(!t||!t.length)return JSON.stringify([]);let e=t.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(e)}function sc(t){let e=Object.keys(t);if(!e.length)return[];function r(o,n){if(o===e.length)return[n];let a=e[o],s=t[a]??[],i=[];for(let u of s){let c={...n,[a]:u};i.push(...r(o+1,c))}return i}return r(0,{})}import{db as ic,matchedRows as nf}from"@stacksjs/database/runtime";import{formatDate as uc}from"@stacksjs/orm";async function cc(t,e){try{let r=await ic.updateTable("product_variants").set({...e,updated_at:uc(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function dc(t){if(!t.length)return 0;let e=0;try{for(let r of t){if(!r.id)continue;if((await nf(ic.updateTable("product_variants").set({...r,updated_at:uc(new Date)}).where("id","=",r.id))).length>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var af={categories:Nt,items:Jt,manufacturers:Bt,reviews:Ot,units:Wt,variants:Lt},sf=af;var Ho={};g(Ho,{bulkDestroy:()=>pc,bulkStore:()=>xc,destroy:()=>mc,fetchAll:()=>fc,fetchById:()=>Ee,fetchPageStats:()=>hc,fetchPrintJobStats:()=>wc,fetchPrintTimeStats:()=>gc,fetchPrintsPerHour:()=>bc,fetchSuccessRate:()=>yc,store:()=>Rc,update:()=>Dc,updatePrintJob:()=>Pc,updateStatus:()=>vc});import{db as lc}from"@stacksjs/database/runtime";async function mc(t){try{let e=await lc.deleteFrom("receipts").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print log: ${e.message}`);throw e}}async function pc(t){if(!t.length)return 0;try{let e=await lc.deleteFrom("receipts").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete receipts: ${e.message}`);throw e}}import{db as zo}from"@stacksjs/database/runtime";import{formatDate as uf}from"@stacksjs/orm";function j(t){return uf(t)}function cf(t){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t==="number"){let o=new Date(t<=2147483647?t*1000:t);return Number.isNaN(o.getTime())?null:o}let e=String(t||"").trim();if(!e)return null;if(/^\d{10}$/.test(e)){let o=new Date(Number(e)*1000);return Number.isNaN(o.getTime())?null:o}let r=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(r.getTime())?null:r}async function Ee(t){let e=await zo.selectFrom("receipts").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function fc(){return w(await zo.selectFrom("receipts").selectAll().execute())}async function wc(t,e){let r=j(t),o=j(e),n=await J("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"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{total:n.total,success:n.success,failed:n.failed,warning:n.warning,averageSize:Math.round(n.averageSize),averagePages:Math.round(n.averagePages),averageDuration:Math.round(n.averageDuration)}}async function yc(t,e){let r=j(t),o=j(e),n=await J("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"}}},(s)=>s.where("timestamp",">=",r).where("timestamp","<=",o));return{successRate:n.total>0?Math.round(n.success/n.total*100):0,total:n.total,success:n.success,failed:n.failed,warning:n.warning}}async function hc(t,e){let r=j(t),o=j(e),n=await J("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{totalPages:n.totalPages,averagePagesPerReceipt:Math.round(n.averagePagesPerReceipt),totalReceipts:n.totalReceipts}}async function gc(t,e){let r=j(t),o=j(e),n=await J("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{averageDuration:Math.round(n.averageDuration),minDuration:n.minDuration,maxDuration:n.maxDuration,totalJobs:n.totalJobs}}async function bc(t,e){let r=typeof t==="number"?t:t.getTime(),o=typeof e==="number"?e:e.getTime(),n=j(t),a=j(e),s=await zo.selectFrom("receipts").where("timestamp",">=",n).where("timestamp","<=",a).selectAll().execute(),i=s.length,u=Math.ceil((o-r)/3600000),c=u>0?Math.round(i/u):0,l=Array.from({length:24},(m,f)=>({hour:f,count:0}));return s.forEach((m)=>{let f=cf(m.timestamp);if(!f)return;l[f.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:l}}var{randomUUIDv7:_c}=globalThis.Bun;import{db as qo}from"@stacksjs/database/runtime";import{formatDate as Go}from"@stacksjs/orm";function Xe(t){try{if(typeof t==="number")return Go(t<=2147483647?t*1000:t);if(typeof t==="string"&&/^\d{10}$/.test(t))return Go(Number(t)*1000);return Go(t)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function Rc(t){try{let e=_c(),r={...t,timestamp:Xe(t.timestamp),uuid:e};await qo.insertInto("receipts").values(r).executeTakeFirst();let o=await qo.selectFrom("receipts").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create receipt");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipt: ${e.message}`);throw e}}async function xc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...o,timestamp:Xe(o.timestamp),uuid:_c()})),r=await qo.insertInto("receipts").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${e.message}`);throw e}}import{db as Vo}from"@stacksjs/database/runtime";import{formatDate as Zo}from"@stacksjs/orm";async function Dc(t,e){try{if(!t)throw Error("Receipt ID is required for update");let r={...e,...e.timestamp===void 0?{}:{timestamp:Xe(e.timestamp)},updated_at:Zo(new Date)};await Vo.updateTable("receipts").set(r).where("id","=",t).execute();let o=await Ee(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function vc(t,e){try{await Vo.updateTable("receipts").set({status:e,updated_at:Zo(new Date)}).where("id","=",t).execute();let r=await Ee(t);if(!r)throw Error("Failed to update receipt status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function Pc(t,e,r,o){try{let n={updated_at:Zo(new Date)};if(e!==void 0)n.size=e;if(r!==void 0)n.pages=r;if(o!==void 0)n.duration=o;await Vo.updateTable("receipts").set(n).where("id","=",t).execute();let a=await Ee(t);if(!a)throw Error("Failed to update receipt job information");return d(a)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update receipt job information: ${n.message}`);throw n}}var Rn={};g(Rn,{couriers:()=>Yt,default:()=>Mf,digital:()=>Kt,geocoding:()=>rr,licenses:()=>ar,methods:()=>cr,rates:()=>fr,routes:()=>Zt,tracking:()=>xr,zones:()=>Fr});var Zt={};g(Zt,{DeliveryRouteInputError:()=>N,bulkDestroy:()=>Tc,destroy:()=>kc,fetchActive:()=>Sc,fetchAll:()=>Ec,fetchByCourier:()=>Cc,fetchById:()=>zt,store:()=>Ac,update:()=>Ic,updateLastActive:()=>Mc,updateMetrics:()=>Jc,updateStops:()=>Nc,validateDeliveryRouteWrite:()=>Se});import{db as Fc}from"@stacksjs/database/runtime";async function kc(t){try{let e=await Fc.deleteFrom("delivery_routes").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery route: ${e.message}`);throw e}}async function Tc(t){if(!t.length)return 0;try{let e=await Fc.deleteFrom("delivery_routes").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery routes: ${e.message}`);throw e}}import{db as jt}from"@stacksjs/database/runtime";async function zt(t){return await jt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst()}async function Ec(){return await jt.selectFrom("delivery_routes").selectAll().execute()}async function Sc(){return await jt.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function Cc(t){return await jt.selectFrom("delivery_routes").where("courier","=",t).selectAll().execute()}var{randomUUIDv7:mf}=globalThis.Bun;import{db as Ko}from"@stacksjs/database/runtime";function he(t,e){let r={};for(let[o,n]of Object.entries(e))for(let a of n){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)continue;r[o]=t[a];break}return r}function et(t){return he(t,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function re(t){return he(t,{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 tt(t){return he(t,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function rt(t){return he(t,{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 ot(t){return he(t,{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 nt(t){return he(t,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function Gt(t){return he(t,{courier:["courier"],courier_id:["courier_id","courierId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as df}from"@stacksjs/database/runtime";class N extends TypeError{constructor(t){super(t);this.name="DeliveryRouteInputError"}}function qt(t,e,r){return Number(t[r]??e?.[r])}function lf(t,e){let r=t.last_active??e?.last_active;if(r===void 0||r===null)return Date.now();if(r instanceof Date)return r.getTime();if(typeof r==="number")return r;if(typeof r==="string"&&/^\d{10,13}$/.test(r))return Number(r);return Number.NaN}async function Se(t,e){let r=qt(t,e,"courier_id"),o=qt(t,e,"stops"),n=qt(t,e,"delivery_time"),a=qt(t,e,"total_distance"),s=lf(t,e);if(!Number.isSafeInteger(r)||r<1)throw new N("Courier must be a positive integer.");if(!Number.isSafeInteger(o)||o<0)throw new N("Stops must be a non-negative integer.");if(!Number.isSafeInteger(n)||n<0)throw new N("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(a)||a<0)throw new N("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(s)||s<0)throw new N("Last active must be a valid Unix timestamp.");let i=await df.selectFrom("couriers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new N(`Courier ${r} was not found.`);return{...t,courier_id:Number(i.id),courier:i.name,vehicle:i.vehicle_number,last_active:s}}async function Ac(t){try{let e=mf(),r=Gt(t),n={...await Se(r),uuid:e};await Ko.insertInto("delivery_routes").values(n).executeTakeFirst();let a=await Ko.selectFrom("delivery_routes").where("uuid","=",e).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(e){if(e instanceof N)throw e;if(e instanceof Error)throw TypeError(`Failed to create delivery route: ${e.message}`);throw e}}async function Mc(t){try{await Ko.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",t).execute();let e=await zt(t);if(!e)throw Error("Failed to update delivery route last active");return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update delivery route last active: ${e.message}`);throw e}}import{db as Vt}from"@stacksjs/database/runtime";import{formatDate as Qo}from"@stacksjs/orm";async function Ic(t,e){try{if(!t)throw Error("Delivery route ID is required for update");let r=await Vt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=Gt(e),n=await Se(o,r),a=await Vt.updateTable("delivery_routes").set({...n,updated_at:Qo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof N)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function Nc(t,e){try{let r=await Vt.updateTable("delivery_routes").set({stops:e,updated_at:Qo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update delivery route stops");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update delivery route stops: ${r.message}`);throw r}}async function Jc(t,e,r){try{let o={updated_at:Qo(new Date)};if(e!==void 0)o.delivery_time=e;if(r!==void 0)o.total_distance=r;let n=await Vt.updateTable("delivery_routes").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update delivery metrics");return n}catch(o){if(o instanceof Error)throw TypeError(`Failed to update delivery metrics: ${o.message}`);throw o}}var Kt={};g(Kt,{bulkDestroy:()=>$c,bulkSoftDelete:()=>Wc,bulkStore:()=>Vc,destroy:()=>Oc,fetchAll:()=>zc,fetchById:()=>jc,softDelete:()=>Uc,store:()=>qc,update:()=>Zc,updateDeliverySettings:()=>Kc,updateStatus:()=>Hc});import{db as Ht,matchedRows as Bc}from"@stacksjs/database/runtime";async function Oc(t){try{let e=await Ht.deleteFrom("digital_deliveries").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital delivery: ${e.message}`);throw e}}async function Uc(t){try{return(await Bc(Ht.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${e.message}`);throw e}}async function $c(t){if(!t.length)return 0;try{let e=await Ht.deleteFrom("digital_deliveries").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${e.message}`);throw e}}async function Wc(t){if(!t.length)return 0;try{return(await Bc(Ht.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${e.message}`);throw e}}import{db as Lc}from"@stacksjs/database/runtime";async function jc(t){let e=await Lc.selectFrom("digital_deliveries").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function zc(){return w(await Lc.selectFrom("digital_deliveries").selectAll().execute())}var{randomUUIDv7:Gc}=globalThis.Bun;import{db as Yo}from"@stacksjs/database/runtime";async function qc(t){try{let e=Gc(),r={...rt(t),uuid:e};await Yo.insertInto("digital_deliveries").values(r).executeTakeFirst();let o=await Yo.selectFrom("digital_deliveries").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created digital delivery");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital delivery: ${e.message}`);throw e}}async function Vc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...rt(o),uuid:Gc()})),r=await Yo.insertInto("digital_deliveries").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${e.message}`);throw e}}import{db as Xo}from"@stacksjs/database/runtime";import{formatDate as en}from"@stacksjs/orm";async function Zc(t,e){try{if(!t)throw Error("Digital delivery ID is required for update");let r=await Xo.updateTable("digital_deliveries").set({...rt(e),updated_at:en(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function Hc(t,e){try{let r=await Xo.updateTable("digital_deliveries").set({status:e,updated_at:en(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function Kc(t,e,r,o,n){try{let a={updated_at:en(new Date)};if(e!==void 0)a.download_limit=e;if(r!==void 0)a.expiry_days=r;if(o!==void 0)a.requires_login=o;if(n!==void 0)a.automatic_delivery=n;let s=await Xo.updateTable("digital_deliveries").set(a).where("id","=",t).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return d(s)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var Yt={};g(Yt,{bulkDestroy:()=>td,bulkStore:()=>nd,destroy:()=>ed,fetchAll:()=>Yc,fetchById:()=>Qt,store:()=>od,update:()=>ad,updateContact:()=>id,updateStatus:()=>sd});import{db as Xc}from"@stacksjs/database/runtime";import{db as Qc}from"@stacksjs/database/runtime";async function Qt(t){let e=await Qc.selectFrom("couriers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Yc(){return w(await Qc.selectFrom("couriers").selectAll().execute())}async function ed(t){try{let e=await Xc.deleteFrom("couriers").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete courier: ${e.message}`);throw e}}async function td(t){if(!t.length)return 0;let e=0;try{return await Xc.transaction(async(r)=>{for(let o of t)if(await Qt(o))await r.deleteFrom("couriers").where("id","=",o).execute(),e++}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to delete couriers in bulk: ${r.message}`);throw r}}var{randomUUIDv7:rd}=globalThis.Bun;import{db as tn}from"@stacksjs/database/runtime";async function od(t){try{let e=rd(),r={...nt(t),uuid:e};await tn.insertInto("couriers").values(r).executeTakeFirst();let o=await tn.selectFrom("couriers").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created courier");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create courier: ${e.message}`);throw e}}async function nd(t){if(!t.length)return 0;try{let e=t.map((o)=>({...nt(o),uuid:rd()})),r=await tn.insertInto("couriers").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create couriers in bulk: ${e.message}`);throw e}}import{db as rn}from"@stacksjs/database/runtime";import{formatDate as on}from"@stacksjs/orm";async function ad(t,e){try{if(!t)throw Error("Courier ID is required for update");let r=await rn.updateTable("couriers").set({...nt(e),updated_at:on(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier: ${r.message}`);throw r}}async function sd(t,e){try{let r=await rn.updateTable("couriers").set({status:e,updated_at:on(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update courier status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier status: ${r.message}`);throw r}}async function id(t,e){try{let r={updated_at:on(new Date)};if(e!==void 0)r.phone=e;let o=await rn.updateTable("couriers").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update contact information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var rr={};g(rr,{PRECISION_RANK:()=>st,checkCoverage:()=>gf,formatQuery:()=>Ce,geocode:()=>hf,geocodingDriver:()=>pd,nominatimDriver:()=>tr,setGeocodingDriver:()=>yf});var ge=(t)=>t*Math.PI/180;function ce(t,e){let r=ge(e.latitude-t.latitude),o=ge(e.longitude-t.longitude),n=ge(t.latitude),a=ge(e.latitude),s=Math.sin(r/2)**2+Math.sin(o/2)**2*Math.cos(n)*Math.cos(a);return 12742017.6*Math.asin(Math.sqrt(s))}function Xt(t,e){let r=ge(t.latitude),o=ge(e.latitude),n=ge(e.longitude-t.longitude),a=Math.sin(n)*Math.cos(o),s=Math.cos(r)*Math.sin(o)-Math.sin(r)*Math.cos(o)*Math.cos(n);return(Math.atan2(a,s)*180/Math.PI+360)%360}function er(t,e,r={}){let o=r.detourFactor??1.35,n=r.minimumSeconds??30;if(!Number.isFinite(e)||e<=0.5)return null;let a=t*o/e;return Math.max(n,Math.round(a))}function ud(t,e,r){return ce(t,e)<=r}function at(t){return typeof t?.latitude==="number"&&typeof t?.longitude==="number"&&Number.isFinite(t.latitude)&&Number.isFinite(t.longitude)}var st={unknown:0,locality:1,postal:2,street:3,rooftop:4};function Ce(t){return[t.street,t.city,t.region,t.postalCode,t.country].map((e)=>String(e??"").trim()).filter(Boolean).join(", ")}var pf="https://nominatim.openstreetmap.org/search",cd=1000,dd=0,ld=Promise.resolve();async function ff(t){let e=ld.then(async()=>{let r=Date.now()-dd;if(r<cd)await Bun.sleep(cd-r);return dd=Date.now(),t()});return ld=e.then(()=>{return},()=>{return}),e}function wf(t){let e=t.address??{},r=String(t.addresstype??""),o=String(t.type??""),n=String(t.category??t.class??"");if(e.house_number||o==="house"||o==="building"||r==="building")return"rooftop";if(e.road||n==="highway"||r==="road")return"street";if(r==="postcode"||e.postcode&&!e.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(r))return"locality";return"unknown"}function tr(t={}){let e=t.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,r=t.endpoint??pf;return{name:"nominatim",async geocode(o){let n=Ce(o);if(!n)return null;let a=new URL(r);if(a.searchParams.set("q",n),a.searchParams.set("format","jsonv2"),a.searchParams.set("limit","1"),a.searchParams.set("addressdetails","1"),o.country)a.searchParams.set("countrycodes",o.country.toLowerCase());let s=await ff(()=>fetch(a,{headers:{"user-agent":e,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!s.ok)throw Error(`Nominatim responded ${s.status}`);let u=(await s.json())?.[0];if(!u)return null;let c=Number(u.lat),l=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(l))return null;let m=wf(u);return{latitude:c,longitude:l,formatted:String(u.display_name??n),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[m],precision:m,provider:"nominatim"}}}}var md=null;function yf(t){md=t}function pd(){return md??tr()}async function hf(t,e={}){let r=e.driver??pd(),o=e.minimumPrecision??"street",n=`geocode:${r.name}:${Ce(t).toLowerCase()}`,a=await bf(n);if(a!==void 0)return a;let s=await r.geocode(t),i=s&&st[s.precision]>=st[o]?s:null;return await _f(n,i,i?e.cacheSeconds??2592000:600),i}function gf(t,e,r){if(e.length===0)return null;let o=e[0],n=ce(t,o);for(let a of e.slice(1)){let s=ce(t,a);if(s<n)n=s,o=a}return{covered:n<=r,distanceMeters:Math.round(n),nearest:o}}async function bf(t){try{let r=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!r)return;let o=await r.get(t);if(o===null||o===void 0)return;return o==="null"?null:JSON.parse(String(o))}catch{return}}async function _f(t,e,r){try{let n=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!n)return;await n.set(t,e===null?"null":JSON.stringify(e),r)}catch{}}var ar={};g(ar,{LicenseKeyInputError:()=>T,bulkDestroy:()=>hd,bulkSoftDelete:()=>gd,bulkStore:()=>Fd,destroy:()=>wd,fetchAll:()=>Rd,fetchById:()=>_d,softDelete:()=>yd,store:()=>Pd,update:()=>kd,updateExpiration:()=>Ed,updateStatus:()=>Td,validateLicenseKeyWrite:()=>be});import{db as or,matchedRows as fd}from"@stacksjs/database/runtime";async function wd(t){try{let e=await or.deleteFrom("license_keys").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license key: ${e.message}`);throw e}}async function yd(t){try{return(await fd(or.updateTable("license_keys").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license key: ${e.message}`);throw e}}async function hd(t){if(!t.length)return 0;try{let e=await or.deleteFrom("license_keys").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license keys: ${e.message}`);throw e}}async function gd(t){if(!t.length)return 0;try{return(await fd(or.updateTable("license_keys").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license keys: ${e.message}`);throw e}}import{db as bd}from"@stacksjs/database/runtime";async function _d(t){let e=await bd.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Rd(){return w(await bd.selectFrom("license_keys").selectAll().execute())}var{randomUUIDv7:vd}=globalThis.Bun;import{db as sn}from"@stacksjs/database/runtime";import{db as nn}from"@stacksjs/database/runtime";var xd=["Standard License","Premium License","Enterprise License"],Dd=["active","inactive","unassigned"];class T extends TypeError{constructor(t){super(t);this.name="LicenseKeyInputError"}}function it(t,e,r){return t[r]!==void 0?t[r]:e?.[r]}function an(t,e,r,o){let n=it(t,e,r);if(n===void 0||n===null||n==="")return null;let a=Number(n);if(!Number.isSafeInteger(a)||a<1)throw new T(`${o} must be a positive integer or null.`);return a}function Rf(t){if(typeof t==="number")return t>2147483647?Math.floor(t/1000):t;if(typeof t==="string"&&/^\d{10,13}$/.test(t))return t.length===13?Math.floor(Number(t)/1000):Number(t);if(typeof t==="string"){let e=/^\d{4}-\d{2}-\d{2} \d/.test(t)?`${t.replace(" ","T")}Z`:t;return Math.floor(new Date(e).getTime()/1000)}return Number.NaN}async function be(t,e){let r=String(it(t,e,"key")||"").trim().toUpperCase(),o=String(it(t,e,"template")||""),n=String(it(t,e,"status")||""),a=Rf(it(t,e,"expiry_date")),s=an(t,e,"customer_id","Customer"),i=an(t,e,"product_id","Product"),u=an(t,e,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new T("License key must use five groups of four uppercase letters or numbers.");if(!xd.includes(o))throw new T(`Template must be one of: ${xd.join(", ")}.`);if(!Dd.includes(n))throw new T(`Status must be one of: ${Dd.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new T("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,l,m]=await Promise.all([s?nn.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?nn.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?nn.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new T(`Customer ${s} was not found.`);if(i&&!l)throw new T(`Product ${i} was not found.`);if(u&&!m)throw new T(`Order ${u} was not found.`);if(s&&m?.customer_id&&Number(m.customer_id)!==s)throw new T(`Order ${u} belongs to Customer ${m.customer_id}, not Customer ${s}.`);return{...t,key:r,template:o,expiry_date:a,status:n,customer_id:s,product_id:i,order_id:u}}async function Pd(t){try{let e=vd(),r=ot(t),o={...await be(r),uuid:e};await sn.insertInto("license_keys").values(o).executeTakeFirst();let n=await sn.selectFrom("license_keys").where("uuid","=",e).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created license key");return d(n)}catch(e){if(e instanceof T)throw e;if(e instanceof Error){if(e.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${e.message}`)}throw e}}async function Fd(t){if(!t.length)return 0;try{let e=await Promise.all(t.map(async(o)=>({...await be(ot(o)),uuid:vd()}))),r=await sn.insertInto("license_keys").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof T)throw e;if(e instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${e.message}`);throw e}}import{db as nr}from"@stacksjs/database/runtime";import{formatDate as un}from"@stacksjs/orm";async function kd(t,e){try{if(!t)throw Error("License key ID is required for update");let r=await nr.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=ot(e),n=await be(o,r),a=await nr.updateTable("license_keys").set({...n,updated_at:un(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return d(a)}catch(r){if(r instanceof T)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function Td(t,e){try{let r=await nr.updateTable("license_keys").set({status:e,updated_at:un(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function Ed(t,e){try{let r={updated_at:un(new Date)};if(e!==void 0)r.expiry_date=e;let o=await nr.updateTable("license_keys").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update expiration information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var cr={};g(cr,{bulkDestroy:()=>Md,bulkSoftDelete:()=>Id,bulkStore:()=>Od,destroy:()=>Cd,fetchAll:()=>Nd,fetchById:()=>ur,formatShippingOptions:()=>Ud,getActiveShippingMethods:()=>$d,softDelete:()=>Ad,store:()=>Bd,update:()=>Wd,updatePricing:()=>jd,updateStatus:()=>Ld});import{db as sr,matchedRows as Sd}from"@stacksjs/database/runtime";async function Cd(t){try{let e=await sr.deleteFrom("shipping_methods").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping method: ${e.message}`);throw e}}async function Ad(t){try{return(await Sd(sr.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${e.message}`);throw e}}async function Md(t){if(!t.length)return 0;try{let e=await sr.deleteFrom("shipping_methods").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping methods: ${e.message}`);throw e}}async function Id(t){if(!t.length)return 0;try{return(await Sd(sr.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${e.message}`);throw e}}import{db as ir}from"@stacksjs/database/runtime";async function ur(t){let e=await ir.selectFrom("shipping_methods").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=await ir.selectFrom("shipping_zones").where("shipping_method_id","=",t).selectAll().execute();return{...e,shippingZones:r}}return}async function Nd(){let t=await ir.selectFrom("shipping_methods").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((a)=>a.id))],n=(await ir.selectFrom("shipping_zones").where("shipping_method_id","in",e).selectAll().execute()).reduce((a,s)=>{let i=s.shipping_method_id;if(i!==null&&i!==void 0){if(!a[i])a[i]=[];a[i].push(s)}return a},{});return t.map((a)=>({...a,shipping_zones:n[a.id]||[]}))}var{randomUUIDv7:Jd}=globalThis.Bun;import{db as ut}from"@stacksjs/database/runtime";async function Bd(t){try{let e=Jd(),r={...et(t),uuid:e};await ut.insertInto("shipping_methods").values(r).executeTakeFirst();let o=await ut.selectFrom("shipping_methods").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping method");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping method: ${e.message}`);throw e}}async function Od(t){if(!t.length)return 0;try{let e=t.map((o)=>({...et(o),uuid:Jd()})),r=await ut.insertInto("shipping_methods").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${e.message}`);throw e}}function Ud(){try{return ut.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping options: ${t.message}`);throw t}}async function $d(){try{let t=await ut.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping methods: ${t.message}`);throw t}}import{db as cn}from"@stacksjs/database/runtime";import{formatDate as dn}from"@stacksjs/orm";async function Wd(t,e){try{if(!t)throw Error("Shipping method ID is required for update");let r=await cn.updateTable("shipping_methods").set({...et(e),updated_at:dn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function Ld(t,e){try{let r=await cn.updateTable("shipping_methods").set({status:e,updated_at:dn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function jd(t,e,r){try{let o={updated_at:dn(new Date)};if(e!==void 0)o.base_rate=e;if(r!==void 0)o.free_shipping=r;let n=await cn.updateTable("shipping_methods").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update pricing information");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update pricing information: ${o.message}`);throw o}}var fr={};g(fr,{ShippingRateInputError:()=>A,bulkDestroy:()=>Gd,bulkStore:()=>ul,bulkUpdate:()=>dl,destroy:()=>zd,destroyByMethod:()=>Vd,destroyByZone:()=>qd,fetchAll:()=>Kd,fetchById:()=>Hd,formatShippingRateOptions:()=>el,getRateByWeightAndAddress:()=>Yd,getRateByWeightAndZone:()=>ln,getRatesByZone:()=>Qd,getShippingRatesByMethod:()=>tl,resolveZoneForAddress:()=>lr,store:()=>il,update:()=>cl,updateByMethod:()=>ml,updateByZone:()=>ll,validateShippingRateWrite:()=>_e,validateZoneMatchesAddress:()=>Xd});import{db as dr}from"@stacksjs/database/runtime";async function zd(t){try{let e=await dr.deleteFrom("shipping_rates").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rate: ${e.message}`);throw e}}async function Gd(t){if(!t.length)return 0;try{let e=await dr.deleteFrom("shipping_rates").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates: ${e.message}`);throw e}}async function qd(t){try{let e=await dr.deleteFrom("shipping_rates").where("shipping_zone_id","=",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${e.message}`);throw e}}async function Vd(t){try{let e=await dr.deleteFrom("shipping_rates").where("shipping_method_id","=",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${e.message}`);throw e}}import{db as W}from"@stacksjs/database/runtime";async function Hd(t){let e=await W.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.shipping_zone_id)r=await W.selectFrom("shipping_zones").where("id","=",e.shipping_zone_id).selectAll().executeTakeFirst();if(e.shipping_method_id)o=await W.selectFrom("shipping_methods").where("id","=",e.shipping_method_id).selectAll().executeTakeFirst();return{...e,shipping_zone:r,shipping_method:o}}return}async function Kd(){let t=await W.selectFrom("shipping_rates").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((i)=>i.shipping_zone_id).filter((i)=>i!==null&&i!==void 0))],r=[...new Set(t.map((i)=>i.shipping_method_id).filter((i)=>i!==null&&i!==void 0))],[o,n]=await Promise.all([e.length?W.selectFrom("shipping_zones").where("id","in",e).selectAll().execute():[],r.length?W.selectFrom("shipping_methods").where("id","in",r).selectAll().execute():[]]),a=o.reduce((i,u)=>(i[u.id]=u,i),{}),s=n.reduce((i,u)=>(i[u.id]=u,i),{});return t.map((i)=>({...i,shipping_zone:i.shipping_zone_id?a[i.shipping_zone_id]:[],shipping_method:i.shipping_method_id?s[i.shipping_method_id]:[]}))}async function Qd(t){try{let e=await W.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${e.message}`);throw e}}async function ln(t,e){try{let r=await W.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).where("weight_from","<=",t).where("weight_to",">=",t).executeTakeFirst();return d(r,!0)}catch(r){if(r instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${r.message}`);throw r}}async function lr(t){if(!t?.countryCode)return null;try{let e=await W.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t.countryCode}%`).where("status","=","active").execute();if(e.length===0)return null;let r=null;for(let o of e){let n=1;if(t.region&&o.regions&&Zd(o.regions,t.region))n=2;if(t.postalCode&&o.postal_codes&&Zd(o.postal_codes,t.postalCode))n=3;if(!r||n>r.score)r={id:o.id,score:n}}return r?.id??null}catch{return null}}async function Yd(t,e){let r=await lr(e);if(r==null)return;return ln(t,r)}async function Xd(t,e){return await lr(e)===t}function Zd(t,e){if(!t||!e)return!1;let r=e.trim().toUpperCase();for(let o of t.split(/[,|;]/))if(o.trim().toUpperCase()===r)return!0;return!1}async function el(){try{return(await W.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((e)=>e.shipping_method_id!==null&&e.shipping_method_id!==void 0&&e.shipping_zone_id!==null&&e.shipping_zone_id!==void 0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping rate options: ${t.message}`);throw t}}async function tl(t){try{let e=await W.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${e.message}`);throw e}}var{randomUUIDv7:sl}=globalThis.Bun;import{db as mn}from"@stacksjs/database/runtime";import{db as ct}from"@stacksjs/database/runtime";async function rl(){return w(await ct.selectFrom("shipping_zones").selectAll().execute())}async function mr(t){let e=await ct.selectFrom("shipping_zones").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}function ol(){try{return ct.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping zone options: ${t.message}`);throw t}}async function nl(){try{let t=await ct.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping zones: ${t.message}`);throw t}}async function al(t){try{let e=await ct.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t}%`).where("status","=","active").orderBy("name").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${e.message}`);throw e}}class A extends TypeError{constructor(t){super(t);this.name="ShippingRateInputError"}}function dt(t,e,r){return Number(t[r]??e?.[r])}async function _e(t,e){let r=dt(t,e,"shipping_method_id"),o=dt(t,e,"shipping_zone_id"),n=dt(t,e,"weight_from"),a=dt(t,e,"weight_to"),s=dt(t,e,"rate");if(!Number.isSafeInteger(r)||r<1)throw new A("Shipping method must be a positive integer.");if(!Number.isSafeInteger(o)||o<1)throw new A("Shipping zone must be a positive integer.");if(!Number.isFinite(n)||n<0)throw new A("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<n)throw new A("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new A("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([ur(r),mr(o)]);if(!i)throw new A(`Shipping method ${r} was not found.`);if(!u)throw new A(`Shipping zone ${o} was not found.`);if(Number(u.shipping_method_id)!==r)throw new A(`Shipping zone ${o} is not assigned to shipping method ${r}.`)}async function il(t){try{let e=re(t),r=Number(e.shipping_method_id),o=Number(e.shipping_zone_id);await _e(e);let n=sl(),a={...e,shipping_method_id:r,shipping_zone_id:o,uuid:n};await mn.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await mn.selectFrom("shipping_rates").where("uuid","=",n).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return d(s)}catch(e){if(e instanceof A)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rate: ${e.message}`);throw e}}async function ul(t){if(!t.length)return 0;try{for(let o of t){let n=re(o);await _e(n)}let e=t.map((o)=>({...re(o),uuid:sl()})),r=await mn.insertInto("shipping_rates").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof A)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${e.message}`);throw e}}import{db as lt,matchedRows as pn}from"@stacksjs/database/runtime";import{formatDate as pr}from"@stacksjs/orm";async function cl(t,e){try{if(!t)throw Error("Shipping rate ID is required for update");let r=await lt.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=re(e);await _e(o,r);let n=await lt.updateTable("shipping_rates").set({...o,updated_at:pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return d(n)}catch(r){if(r instanceof A)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function dl(t){if(!t.length)return 0;try{let e=0;for(let{id:r,data:o}of t)if((await pn(lt.updateTable("shipping_rates").set({...re(o),updated_at:pr(new Date)}).where("id","=",r))).length>0)e++;return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${e.message}`);throw e}}async function ll(t,e){try{return(await pn(lt.updateTable("shipping_rates").set({...re(e),updated_at:pr(new Date)}).where("shipping_zone_id","=",t))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function ml(t,e){try{return(await pn(lt.updateTable("shipping_rates").set({...re(e),updated_at:pr(new Date)}).where("shipping_method_id","=",t))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var xr={};g(xr,{ARRIVAL_RADIUS_METERS:()=>yn,NEARBY_RADIUS_METERS:()=>wn,assignStop:()=>fl,bearingInDegrees:()=>Xt,broadcastToChannel:()=>oe,completeStop:()=>yl,distanceInMeters:()=>ce,emitDeliveryArrived:()=>br,emitDeliveryAssigned:()=>yr,emitDeliveryCompleted:()=>_r,emitDeliveryFailed:()=>Rr,emitDeliveryNearby:()=>gr,emitDeliveryPosition:()=>wr,emitDeliveryStarted:()=>hr,estimateSecondsRemaining:()=>er,failStop:()=>hl,hasCoordinates:()=>at,isWithin:()=>ud,orderTrackingChannel:()=>de,recordCourierPing:()=>pl,routeTrackingChannel:()=>fn,startRoute:()=>gl,startStop:()=>wl});function de(t){return`order.${t}`}function fn(t){return`delivery-route.${t}`}async function Ae(t,e){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let o=r.dispatch;if(typeof o!=="function")return;o(t,e)}catch{}}async function oe(t,e,r){try{let o=await import("@stacksjs/realtime").catch(()=>null);if(!o)return;let n=o.channel;if(typeof n!=="function")return;await n(t).broadcast(e,r,"private")}catch{}}async function wr(t,e,r){await Promise.all([...t.map((o)=>oe(de(o),"delivery:position",r)),e==null?Promise.resolve():oe(fn(e),"delivery:position",r)])}async function yr(t){if(await Ae("delivery:assigned",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:assigned",{stop:t})}async function hr(t){if(await Ae("delivery:started",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:started",{stop:t})}async function gr(t,e,r){if(await Ae("delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r}),t.order_id!=null)await oe(de(t.order_id),"delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r})}async function br(t){if(await Ae("delivery:arrived",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:arrived",{stop:t})}async function _r(t){if(await Ae("delivery:completed",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:completed",{stop:t})}async function Rr(t,e){await Ae("delivery:failed",{stop:t,reason:e})}var{randomUUIDv7:xf}=globalThis.Bun;import{db as ne}from"@stacksjs/database/runtime";var wn=400,yn=60,Df=250;async function pl(t){let e=t.recordedAt??new Date().toISOString(),r=typeof t.accuracy!=="number"||t.accuracy<=Df,o=await ne.selectFrom("couriers").where("id","=",t.courierId).select(["id","latitude","longitude"]).executeTakeFirst();if(!o)throw Error(`Unknown courier: ${t.courierId}`);let n=at(o)?{latitude:o.latitude,longitude:o.longitude}:null,a=typeof t.heading==="number"?t.heading:n?Xt(n,t):null,s=await vf(t.courierId),i=s?await Pf(s.id):null,u=null,c=null,l=!1,m=!1,f=i&&at({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&f)u=Math.round(ce(t,f)),c=er(u,t.speed??0),m=u<=yn&&i.arrived_at==null,l=!m&&u<=wn&&i.status==="en_route"&&i.notified_nearby_at==null;let h=await Ff({courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e});if(r)await ne.updateTable("couriers").set({latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??0,last_ping_at:e}).where("id","=",t.courierId).execute();if(i&&(u!=null||c!=null))await ne.updateTable("delivery_stops").set({eta_at:c==null?i.eta_at:new Date(Date.now()+c*1000).toISOString()}).where("id","=",i.id).execute();if(r)await wr(i?.order_id==null?[]:[i.order_id],s?.id??null,{courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e,distanceToStopMeters:u,etaSeconds:c});if(l&&i)await ne.updateTable("delivery_stops").set({notified_nearby_at:e}).where("id","=",i.id).execute(),await gr(i,u,c);if(m&&i)await ne.updateTable("delivery_stops").set({status:"arrived",arrived_at:e}).where("id","=",i.id).execute(),await br({...i,status:"arrived",arrived_at:e});return{pingId:h,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:l,crossedArrival:m}}async function vf(t){return await ne.selectFrom("delivery_routes").where("courier_id","=",t).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function Pf(t){let e=await ne.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return e.find((r)=>r.status==="en_route")??e.find((r)=>r.status==="arrived")??e[0]??null}async function Ff(t){let e=xf();return await ne.insertInto("courier_pings").values({uuid:e,courier_id:t.courierId,delivery_route_id:t.routeId,latitude:t.latitude,longitude:t.longitude,heading:t.heading,speed:t.speed??0,accuracy:t.accuracy,recorded_at:t.recordedAt}).executeTakeFirst(),(await ne.selectFrom("courier_pings").where("uuid","=",e).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:kf}=globalThis.Bun;import{db as M}from"@stacksjs/database/runtime";function hn(t){return t.type==="pickup"}async function fl(t){let e=kf(),r=t.sequence??await Ef(t.deliveryRouteId);await M.insertInto("delivery_stops").values({uuid:e,delivery_route_id:t.deliveryRouteId,order_id:t.orderId??null,sequence:r,status:"pending",address:t.address,latitude:t.latitude??null,longitude:t.longitude??null,recipient_name:t.recipientName??null,recipient_phone:t.recipientPhone??null,eta_at:t.etaAt??null,type:t.type??"dropoff"}).executeTakeFirst();let o=await Cf(e);if(o)await yr(o);return o??{}}async function wl(t){await M.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",t).execute();let e=await bn(t);if(!e)return null;if(e.order_id!=null&&!hn(e))await gn(e.order_id,"OUT_FOR_DELIVERY");return await hr(e),e}async function yl(t,e){let r=new Date().toISOString();await M.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await Sf(t)?{}:{arrived_at:r},...e?{notes:e}:{}}).where("id","=",t).execute();let o=await bn(t);if(!o)return null;if(o.order_id!=null)await gn(o.order_id,hn(o)?"OUT_FOR_DELIVERY":"DELIVERED");return await _r(o),await bl(o.delivery_route_id),o}async function hl(t,e){await M.updateTable("delivery_stops").set({status:"failed",notes:e}).where("id","=",t).execute();let r=await bn(t);if(!r)return null;if(r.order_id!=null&&!hn(r))await gn(r.order_id,"SHIPPED");return await Rr(r,e),await bl(r.delivery_route_id),r}async function gl(t){await M.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",t).execute()}async function bl(t){if(t==null)return;if(await M.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await M.selectFrom("delivery_routes").where("id","=",t).select(["courier_id"]).executeTakeFirst();if(await M.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",t).execute(),r?.courier_id!=null)await M.updateTable("couriers").set({status:"active"}).where("id","=",r.courier_id).execute()}async function gn(t,e){let r=await M.selectFrom("orders").where("id","=",t).select(["id","status"]).executeTakeFirst();if(!r)return;let o=await Promise.resolve().then(() => (Fe(),{}));let s=Tf(r.status,e,ve);if(s.length===0){let{log:i}=await import("@stacksjs/logging").catch(()=>({log:null}));i?.warn(`[delivery] refused to move order ${t} from ${r.status} to ${e}: no legal transition`);return}for(let i of s)await M.updateTable("orders").set({status:i}).where("id","=",t).execute(),await Pe(i,{...r,status:i})}function Tf(t,e,r){if(t===e)return[];if(r(t,e))return[e];for(let o of["PROCESSING","SHIPPED"]){if(o===t||o===e)continue;if(r(t,o)&&r(o,e))return[o,e]}return[]}async function Ef(t){return(await M.selectFrom("delivery_stops").where("delivery_route_id","=",t).select(["sequence"]).execute()).reduce((r,o)=>Math.max(r,o.sequence??0),0)+1}async function Sf(t){return(await M.selectFrom("delivery_stops").where("id","=",t).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function bn(t){return await M.selectFrom("delivery_stops").where("id","=",t).selectAll().executeTakeFirst()??null}async function Cf(t){return await M.selectFrom("delivery_stops").where("uuid","=",t).selectAll().executeTakeFirst()??null}var Fr={};g(Fr,{bulkDestroy:()=>Dl,bulkSoftDelete:()=>vl,bulkStore:()=>kl,destroy:()=>Rl,fetchAll:()=>rl,fetchById:()=>mr,formatZoneOptions:()=>ol,getActiveShippingZones:()=>nl,getZonesByCountry:()=>al,softDelete:()=>xl,store:()=>Fl,update:()=>Tl,updateCountries:()=>Sl,updateRegionsAndPostalCodes:()=>Cl,updateStatus:()=>El});import{db as Dr,matchedRows as _l}from"@stacksjs/database/runtime";async function Rl(t){try{let e=await Dr.deleteFrom("shipping_zones").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zone: ${e.message}`);throw e}}async function xl(t){try{return(await _l(Dr.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${e.message}`);throw e}}async function Dl(t){if(!t.length)return 0;try{let e=await Dr.deleteFrom("shipping_zones").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zones: ${e.message}`);throw e}}async function vl(t){if(!t.length)return 0;try{return(await _l(Dr.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${e.message}`);throw e}}var{randomUUIDv7:Pl}=globalThis.Bun;import{db as _n}from"@stacksjs/database/runtime";async function Fl(t){try{let e=Pl(),r={...tt(t),uuid:e};await _n.insertInto("shipping_zones").values(r).executeTakeFirst();let o=await _n.selectFrom("shipping_zones").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping zone");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zone: ${e.message}`);throw e}}async function kl(t){if(!t.length)return 0;try{let e=t.map((o)=>({...tt(o),uuid:Pl()})),r=await _n.insertInto("shipping_zones").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${e.message}`);throw e}}import{db as vr}from"@stacksjs/database/runtime";import{formatDate as Pr}from"@stacksjs/orm";async function Tl(t,e){try{if(!t)throw Error("Shipping zone ID is required for update");let r=await vr.updateTable("shipping_zones").set({...tt(e),updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function El(t,e){try{let r=await vr.updateTable("shipping_zones").set({status:e,updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function Sl(t,e){try{let r=await vr.updateTable("shipping_zones").set({countries:e,updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function Cl(t,e,r){try{let o={updated_at:Pr(new Date)};if(e!==void 0)o.regions=e;if(r!==void 0)o.postal_codes=r;let n=await vr.updateTable("shipping_zones").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update regions and postal codes");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${o.message}`);throw o}}var Af={digital:Kt,couriers:Yt,geocoding:rr,licenses:ar,methods:cr,rates:fr,routes:Zt,tracking:xr,zones:Fr},Mf=Af;var vn={};g(vn,{activeTaxRates:()=>xn,breakdownFor:()=>Dn,bulkDestroy:()=>Nl,bulkStore:()=>Ll,destroy:()=>Il,fetchAll:()=>Ol,fetchById:()=>Bl,store:()=>Wl,taxFor:()=>Al,update:()=>jl,updateDefaultStatus:()=>ql,updateRate:()=>Gl,updateStatus:()=>zl});import{db as If}from"@stacksjs/database/runtime";function Nf(t){let e=Number(t);return Number.isFinite(e)?e/100:0}async function xn(t={}){let e=If.selectFrom("tax_rates").where("status","=","active").selectAll();if(t.country)e=e.where("country","=",t.country);let r=await e.execute();if(!t.codes?.length)return r;let o=new Set(t.codes);return r.filter((n)=>o.has(String(n.code??"")))}function Dn(t,e,r={}){let o=Math.max(0,Math.round(t)),n=[],a=0,s=0;for(let i of e){let u=Nf(i.rate),c=Math.round(o*u),l=Boolean(r.exempt&&i.exemptible);if(l)s+=c;else a+=c;n.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:l?0:c,exempted:l})}return{taxable:o,components:n,tax:a,exempted:s}}async function Al(t,e={}){return Dn(t,await xn(e),e)}import{db as Ml}from"@stacksjs/database/runtime";async function Il(t){try{let e=await Ml.deleteFrom("tax_rates").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rate: ${e.message}`);throw e}}async function Nl(t){if(!t.length)return 0;try{let e=await Ml.deleteFrom("tax_rates").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rates: ${e.message}`);throw e}}import{db as Jl}from"@stacksjs/database/runtime";async function Bl(t){let e=await Jl.selectFrom("tax_rates").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Ol(){return w(await Jl.selectFrom("tax_rates").selectAll().execute())}var{randomUUIDv7:Ul}=globalThis.Bun;import{db as $l}from"@stacksjs/database/runtime";async function Wl(t){try{return await $l.transaction(async(e)=>{let r={...t,uuid:Ul()};if(r.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();let o=await e.insertInto("tax_rates").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create tax rate");return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rate: ${e.message}`);throw e}}async function Ll(t){if(!t.length)return 0;try{return await $l.transaction(async(e)=>{let r=0;for(let o of t){let n={...o,uuid:Ul()};if(n.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();if(await e.insertInto("tax_rates").values(n).executeTakeFirst())r++}return r})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${e.message}`);throw e}}import{db as kr}from"@stacksjs/database/runtime";import{formatDate as Tr}from"@stacksjs/orm";async function jl(t,e){try{if(!t)throw Error("Tax rate ID is required for update");return await kr.transaction(async(r)=>{let o=await r.selectFrom("tax_rates").select("is_default").where("id","=",t).executeTakeFirst();if(!o)return;let n=e.is_default??Boolean(o.is_default),a=Tr(new Date);if(n)await r.updateTable("tax_rates").set({is_default:!1,updated_at:a}).where("id","!=",t).execute();let s=await r.updateTable("tax_rates").set({...e,updated_at:a}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function zl(t,e){try{let r=await kr.updateTable("tax_rates").set({status:e,updated_at:Tr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function Gl(t,e){try{let r=await kr.updateTable("tax_rates").set({rate:e,updated_at:Tr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function ql(t,e){try{return await kr.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",t).executeTakeFirst())return!1;let n=Tr(new Date);if(e)await r.updateTable("tax_rates").set({is_default:!1,updated_at:n}).where("id","!=",t).execute();return await r.updateTable("tax_rates").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate default status: ${r.message}`);throw r}}var Sn={};g(Sn,{default:()=>Gf,products:()=>Sr,restaurant:()=>Ie});var Sr={};g(Sr,{bulkDestroy:()=>Zl,bulkStore:()=>lm,destroy:()=>Vl,fetchAll:()=>Hl,fetchById:()=>mt,fetchCancelledBetweenDates:()=>rm,fetchConversionRates:()=>am,fetchCountBetweenDates:()=>sm,fetchCountByAllQuantities:()=>Xl,fetchCountByDate:()=>Ql,fetchCountByDateGrouped:()=>im,fetchCountByQuantity:()=>Yl,fetchCountBySource:()=>Kl,fetchCountByStatus:()=>nm,fetchNotifiedBetweenDates:()=>em,fetchPurchasedBetweenDates:()=>tm,fetchWaiting:()=>om,store:()=>dm,update:()=>Er,updatePartySize:()=>pm,updateStatus:()=>mm});import{db as Pn}from"@stacksjs/database/runtime";async function Vl(t){try{let e=await Pn.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await Pn.deleteFrom("waitlist_products").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist product: ${e.message}`);throw e}}async function Zl(t){if(!t.length)return 0;try{let e=await Pn.deleteFrom("waitlist_products").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${e.message}`);throw e}}import{db as F}from"@stacksjs/database/runtime";import{formatDate as k}from"@stacksjs/orm";async function mt(t){let e=await F.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Hl(){return w(await F.selectFrom("waitlist_products").selectAll().execute())}async function Kl(t,e){let r=F.selectFrom("waitlist_products").select(["source",F.fn.count("id").as("count")]).groupBy("source");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{source:a,count:s})=>(n[a]=s,n),{})}async function Ql(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=k(e),n=k(r);return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function Yl(t){return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("quantity","=",t).executeTakeFirst())?.count??0}async function Xl(t,e){let r=F.selectFrom("waitlist_products").select(["quantity",F.fn.count("id").as("count")]).groupBy("quantity");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{quantity:a,count:s})=>(n[a]=s,n),{})}async function em(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",o).whereNotNull("notified_at").execute();return w(n)}async function tm(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",o).whereNotNull("purchased_at").execute();return w(n)}async function rm(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",o).whereNotNull("cancelled_at").execute();return w(n)}async function om(){let t=await F.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute();return w(t)}async function nm(t,e,r){let o=F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("status","=",t);if(e&&r){let a=k(e),s=k(r);o=o.where("created_at",">=",a).where("created_at","<=",s)}return(await o.executeTakeFirst())?.count??0}async function am(t,e){let r=F.selectFrom("waitlist_products").select(["status",F.fn.count("id").as("count")]).groupBy("status");if(t&&e){let u=k(t),c=k(e);r=r.where("created_at",">=",u).where("created_at","<=",c)}let o=await r.execute(),n=o.reduce((u,{count:c})=>u+c,0),a=Number(o.find((u)=>u.status==="purchased")?.count??0),s=n>0?a/n*100:0,i=o.reduce((u,{status:c,count:l})=>(u[c]={count:l,percentage:n>0?l/n*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function sm(t,e){let r=k(t),o=k(e);return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",o).executeTakeFirst())?.count??0}async function im(t,e){let r=F.selectFrom("waitlist_products").select(["created_at"]);if(t&&e){let a=k(t),s=k(e);r=r.where("created_at",">=",a).where("created_at","<=",s)}let n=(await r.execute()).reduce((a,{created_at:s})=>{let i=(s||"").split("T")[0]||"unknown";return a[i]=(a[i]||0)+1,a},{});return Object.entries(n).map(([a,s])=>({date:a,count:s})).sort((a,s)=>a.date.localeCompare(s.date))}var{randomUUIDv7:cm}=globalThis.Bun;import{db as Fn}from"@stacksjs/database/runtime";import{formatDate as um}from"@stacksjs/orm";var Jf={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Bf(t){return typeof t==="number"||t instanceof Date?um(t):t}function pt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));if(r.quantity===void 0&&r.party_size!==void 0)r.quantity=r.party_size;delete r.party_size;for(let n of["notified_at","purchased_at","cancelled_at"])if(r[n]!==void 0)r[n]=Bf(r[n]);let o=Jf[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=um(new Date);return r}async function dm(t){try{let e=cm(),r={...pt(t),uuid:e,status:t.status||"waiting"};await Fn.insertInto("waitlist_products").values(r).executeTakeFirst();let o=await Fn.selectFrom("waitlist_products").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create waitlist product");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist product: ${e.message}`);throw e}}async function lm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...pt(o),status:o.status||"waiting",uuid:cm()})),r=await Fn.insertInto("waitlist_products").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${e.message}`);throw e}}import{db as Of}from"@stacksjs/database/runtime";import{formatDate as Uf}from"@stacksjs/orm";async function Er(t,e){try{if(!t)throw Error("Waitlist product ID is required for update");let r=await mt(t);if(!r)return;await Of.updateTable("waitlist_products").set({...pt(e,r),updated_at:Uf(new Date)}).where("id","=",t).execute();let o=await mt(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function mm(t,e){return await Er(t,{status:e})}async function pm(t,e){return await Er(t,{quantity:e})}var Ie={};g(Ie,{bulkDestroy:()=>wm,bulkStore:()=>Jm,destroy:()=>fm,fetchAll:()=>ym,fetchAverageWaitTimes:()=>Pm,fetchBetweenDates:()=>Rm,fetchById:()=>ft,fetchConversionRates:()=>vm,fetchCountByAllPartySizes:()=>_m,fetchCountByDate:()=>gm,fetchCountByPartySize:()=>bm,fetchCountByTablePreference:()=>hm,fetchCurrentWaitTimes:()=>Cm,fetchNoShowStats:()=>Sm,fetchSeatedBetweenDates:()=>xm,fetchSeatedStats:()=>Am,fetchSeatingRate:()=>Em,fetchTablesTurnedToday:()=>Tm,fetchTimeSeriesStats:()=>Mm,fetchWaiting:()=>Dm,fetchWaitingWithPartySizes:()=>km,fetchWaitingWithQuotedTimes:()=>Fm,store:()=>Nm,update:()=>Me,updatePartySize:()=>Om,updateQueuePosition:()=>$m,updateStatus:()=>Bm,updateWaitTimes:()=>Um});import{db as kn}from"@stacksjs/database/runtime";async function fm(t){try{let e=await kn.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await kn.deleteFrom("waitlist_restaurants").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${e.message}`);throw e}}async function wm(t){if(!t.length)return 0;try{let e=await kn.deleteFrom("waitlist_restaurants").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as R}from"@stacksjs/database/runtime";import{formatDate as B}from"@stacksjs/orm";async function ft(t){let e=await R.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ym(){return w(await R.selectFrom("waitlist_restaurants").selectAll().execute())}async function hm(){return(await R.selectFrom("waitlist_restaurants").select(["table_preference",R.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((e,{table_preference:r,count:o})=>(e[r]=o,e),{})}async function gm(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r);return(await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function bm(t){return(await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("party_size","=",t).executeTakeFirst())?.count??0}async function _m(){return(await R.selectFrom("waitlist_restaurants").select(["party_size",R.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((e,{party_size:r,count:o})=>(e[r]=o,e),{})}async function Rm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",o).execute();return w(n)}async function xm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",o).where("status","=","seated").execute();return w(n)}async function Dm(){let t=await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute();return w(t)}async function vm(){let t=await R.selectFrom("waitlist_restaurants").select(["status",R.fn.count("id").as("count")]).groupBy("status").execute(),e=t.reduce((a,{count:s})=>a+s,0),r=t.find((a)=>a.status==="seated")?.count??0,o=e>0?Number(r)/e*100:0,n=t.reduce((a,{status:s,count:i})=>(a[s]={count:i,percentage:e>0?i/e*100:0},a),{});return{totalConversionRate:o,statusBreakdown:n}}async function Pm(){let t=await R.selectFrom("waitlist_restaurants").select([R.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),R.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:t?.avg_quoted_wait_time??0,averageActualWaitTime:t?.avg_actual_wait_time??0}}async function Fm(){let t=w(await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((o,n)=>o+(n.quoted_wait_time??0),0),r=t.length>0?e/t.length:0;return{entries:t,totalQuotedWaitTime:e,averageQuotedWaitTime:r}}async function km(){let t=w(await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((n,a)=>n+a.party_size,0),r=t.length>0?e/t.length:0,o=t.reduce((n,a)=>(n[a.party_size]=(n[a.party_size]||0)+1,n),{});return{entries:t,totalPartySize:e,averagePartySize:r,partySizeBreakdown:o}}async function Tm(){let t=new Date,e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r),a=await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",o).where("check_in_time","<=",n).execute(),s=a.length,i=a.reduce((m,f)=>m+f.party_size,0),u=s>0?i/s:0,c=a.reduce((m,f)=>(m[f.table_preference]=(m[f.table_preference]||0)+1,m),{}),l=a.reduce((m,f)=>(m[f.party_size]=(m[f.party_size]||0)+1,m),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:l}}async function Em(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").select(["status",R.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",o).groupBy("status").execute(),a=n.reduce((c,{count:l})=>c+l,0),s=n.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=n.reduce((c,{status:l,count:m})=>(c[l]={count:m,percentage:a>0?m/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function Sm(t,e){let r=B(t),o=B(e),n=R.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",o),a=await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("check_in_time",">=",r).where("check_in_time","<=",o).executeTakeFirst(),s=await n.execute(),i=s.length,u=a?.count&&a.count>0?i/a.count*100:0,c=s.reduce((_,D)=>_+(D.quoted_wait_time??0),0),l=i>0?c/i:0,m=s.reduce((_,D)=>_+D.party_size,0),f=i>0?m/i:0,h=s.reduce((_,D)=>(_[D.table_preference]=(_[D.table_preference]||0)+1,_),{}),b=s.reduce((_,D)=>(_[D.party_size]=(_[D.party_size]||0)+1,_),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:l,averagePartySize:f,breakdownByTablePreference:h,breakdownByPartySize:b}}async function Cm(){let t=await R.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),e=t.reduce((n,a)=>n+(a.quoted_wait_time||0),0),r=t.reduce((n,a)=>n+(a.actual_wait_time||0),0),o=t.length;return{averageQuoted:o>0?e/o:0,averageActual:o>0?r/o:0}}async function Am(){let t=Date.now()-86400000,e=await R.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",t).execute(),r=Array.from({length:24},(o,n)=>({hour:n,count:e.filter((a)=>a.seated_at===n).length}));return{total:e.length,byHour:r}}async function Mm(){return(await R.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((e,r)=>{let o=r.created_at;if(!e[o])e[o]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return e[o].total++,e[o][r.status]++,e},{})}var{randomUUIDv7:Im}=globalThis.Bun;import{db as En}from"@stacksjs/database/runtime";import{formatDate as Tn}from"@stacksjs/orm";var $f={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function Wf(t){if(typeof t==="number")return Tn(t<=2147483647?t*1000:t);if(t instanceof Date)return Tn(t);return t}function wt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));for(let n of["check_in_time","seated_at","no_show_at","cancelled_at"])if(r[n]!==void 0)r[n]=Wf(r[n]);let o=$f[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=Tn(new Date);return r}async function Nm(t){try{let e=Im(),r={...wt(t),status:t.status||"waiting",uuid:e};await En.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let o=await En.selectFrom("waitlist_restaurants").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create restaurant waitlist entry");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${e.message}`);throw e}}async function Jm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...wt(o),status:o.status||"waiting",uuid:Im()})),r=await En.insertInto("waitlist_restaurants").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as Lf}from"@stacksjs/database/runtime";import{formatDate as jf}from"@stacksjs/orm";async function Me(t,e){try{if(!t)throw Error("Restaurant waitlist entry ID is required for update");let r=await ft(t);if(!r)return;await Lf.updateTable("waitlist_restaurants").set({...wt(e,r),updated_at:jf(new Date)}).where("id","=",t).execute();let o=await ft(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function Bm(t,e){return await Me(t,{status:e})}async function Om(t,e){return await Me(t,{party_size:e})}async function Um(t,e,r){return await Me(t,{quoted_wait_time:e,...r===void 0?{}:{actual_wait_time:r}})}async function $m(t,e){return await Me(t,{queue_position:e})}var zf={products:Sr,restaurant:Ie},Gf=zf;var qf={auctions:no,carts:ao,coupons:io,customers:co,devices:wo,errors:go,giftCards:Ro,orders:No,payments:Jo,products:jo,receipts:Ho,restaurant:Ie,shippings:Rn,tax:vn,waitlists:Sn},ck=qf;export{no as auctions,ao as carts,qf as commerce,io as coupons,co as customers,ck as default,wo as devices,go as errors,Ro as giftCards,No as orders,Jo as payments,jo as products,Ho as receipts,Ie as restaurant,Rn as shippings,vn as tax,Sn as waitlists};
28
+ AND COALESCE(refund_amount, 0) + ${o(5)} <= amount`,[e,e,n,t,e]);if(Lp(a)>0){let l=await ye(t);if(l)return l;throw Error(`Payment with ID ${t} disappeared during refund`)}let s=await ye(t);if(!s)throw Error(`Payment with ID ${t} not found`);let i=String(s.status||"");if(!Gp.has(i))throw Error(`Payment status ${i||"unknown"} cannot be refunded`);let u=s,c=Number(s.amount||0)-Number(u.refundAmount??u.refund_amount??0);throw Error(`Refund amount exceeds the remaining ${c} minor units`)}var jo={};g(jo,{categories:()=>Nt,default:()=>cf,items:()=>Jt,manufacturers:()=>Bt,reviews:()=>Ot,units:()=>Wt,variants:()=>Lt});var Nt={};g(Nt,{bulkRemove:()=>Ti,compareCategoryGrowth:()=>vi,deactivate:()=>Si,deactivateChildCategories:()=>Ci,fetchActive:()=>bi,fetchAll:()=>Bo,fetchByDisplayOrder:()=>xi,fetchById:()=>S,fetchByName:()=>gi,fetchCategoryTree:()=>Pi,fetchChildCategories:()=>Ri,fetchRootCategories:()=>_i,fetchStats:()=>Di,findOrCreateByName:()=>Mi,remove:()=>ki,removeChildCategories:()=>Ei,store:()=>Oo,update:()=>Ii,updateActiveStatus:()=>Ji,updateDisplayOrder:()=>Ni,updateParent:()=>Bi});import{db as Ke,matchedRows as qp}from"@stacksjs/database/runtime";import{formatDate as Fi}from"@stacksjs/orm";import{db as P}from"@stacksjs/database/runtime";import{formatDate as He}from"@stacksjs/orm";async function Bo(){return await P.selectFrom("categories").selectAll().execute()}async function S(t){return await P.selectFrom("categories").where("id","=",t).selectAll().executeTakeFirst()}async function gi(t){return await P.selectFrom("categories").where("name","=",t).selectAll().executeTakeFirst()}async function bi(){return await P.selectFrom("categories").where("is_active","=",!0).selectAll().execute()}async function _i(){return await P.selectFrom("categories").whereNull("parent_category_id").where("is_active","=",!0).selectAll().execute()}async function Ri(t){return await P.selectFrom("categories").where("parent_category_id","=",t).where("is_active","=",!0).selectAll().execute()}async function xi(t=!0){let e=P.selectFrom("categories").where("is_active","=",!0).selectAll();if(t)return await e.orderBy("display_order","asc").execute();else return await e.orderBy("display_order","desc").execute()}async function Di(){let t=await P.selectFrom("categories").select(P.fn.count("id").as("count")).executeTakeFirst(),e=await P.selectFrom("categories").where("is_active","=",!0).select(P.fn.count("id").as("count")).executeTakeFirst(),r=await P.selectFrom("categories").whereNull("parent_category_id").select(P.fn.count("id").as("count")).executeTakeFirst(),o=await P.selectFrom("categories").whereNotNull("image_url").select(P.fn.count("id").as("count")).executeTakeFirst(),n=new Date;n.setDate(n.getDate()-30);let a=He(n),s=await P.selectFrom("categories").where("created_at",">=",a).selectAll().limit(5).execute(),i=await P.selectFrom("categories as c").leftJoin("categories as parent","c.parent_category_id","=","parent.id").whereNotNull("c.parent_category_id").select(["c.parent_category_id","parent.name as parent_name",P.fn.count("c.id").as("child_count")]).groupBy(["c.parent_category_id","parent.name"]).orderBy("child_count","desc").limit(5).execute();return{total:Number(t?.count||0),active:Number(e?.count||0),root_categories:Number(r?.count||0),child_categories:Number(t?.count||0)-Number(r?.count||0),with_images:Number(o?.count||0),recently_added:s,top_parent_categories:i.map((u)=>({id:String(u.parent_category_id||""),name:String(u.parent_name||""),child_count:Number(u.child_count)}))}}async function vi(t=30){let e=new Date,r=He(e),o=new Date;o.setDate(e.getDate()-t);let n=He(o),a=new Date(o);a.setDate(a.getDate()-1);let s=He(a),i=new Date(a);i.setDate(a.getDate()-t);let u=He(i),c=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",n).where("created_at","<=",r).executeTakeFirst(),l=await P.selectFrom("categories").select(P.fn.count("id").as("count")).where("created_at",">=",u).where("created_at","<=",s).executeTakeFirst(),m=Number(c?.count||0),f=Number(l?.count||0),h=m-f,b=f!==0?h/f*100:m>0?100:0;return{current_period:m,previous_period:f,difference:h,percentage_change:b,days_range:t}}async function Pi(){let t=await Bo(),e=new Map;t.forEach((n)=>{e.set(n.id,{...n,children:[]})});let r=[];t.forEach((n)=>{let a=e.get(n.id);if(n.parent_category_id){let s=e.get(n.parent_category_id);if(s)s.children.push(a)}else r.push(a)}),r.sort((n,a)=>n.display_order-a.display_order);let o=(n)=>{n.sort((a,s)=>a.display_order-s.display_order),n.forEach((a)=>{if(a.children.length>0)o(a.children)})};return o(r),r}async function ki(t){let e=await Ke.deleteFrom("categories").where("id","=",t).executeTakeFirst();return p(e)>0}async function Ti(t){if(!t.length)return 0;let e=await Ke.deleteFrom("categories").where("id","in",t).executeTakeFirst();return p(e)}async function Ei(t){let e=await Ke.deleteFrom("categories").where("parent_category_id","=",t).executeTakeFirst();return p(e)}async function Si(t){if(!await S(t))throw Error(`Category with ID ${t} not found`);let r=await Ke.updateTable("categories").set({is_active:!1,updated_at:Fi(new Date)}).where("id","=",t).returning("id").executeTakeFirst();return Boolean(r)}async function Ci(t){return(await qp(Ke.updateTable("categories").set({is_active:!1,updated_at:Fi(new Date)}).where("parent_category_id","=",t))).length}var{randomUUIDv7:Vp}=globalThis.Bun;import{db as Ai}from"@stacksjs/database/runtime";import{HttpError as Mt}from"@stacksjs/error-handling";import{isUniqueViolation as Zp}from"@stacksjs/orm";import{slug as Hp}from"@stacksjs/strings";async function Oo(t){try{let e=t.parent_category_id?Number(t.parent_category_id):void 0;if(e!==void 0&&(!Number.isSafeInteger(e)||e<=0))throw new Mt(422,"Parent category ID must be a positive integer");if(e&&!await S(e))throw new Mt(422,`Parent category with ID ${t.parent_category_id} not found`);let r={...t,uuid:Vp(),is_active:t.is_active??!0,parent_category_id:t.parent_category_id||null},o=await Ai.insertInto("categories").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create category");return o}catch(e){if(e instanceof Mt)throw e;if(Zp(e))throw new Mt(409,"A category with this name or slug already exists");if(e instanceof Error)throw Error(`Failed to create category: ${e.message}`);throw e}}async function Mi(t){if(!t.name)throw Error("Name is required");let e=await Ai.selectFrom("categories").selectAll().where("name","=",t.name).executeTakeFirst();if(e)return e;let r={name:t.name,slug:Hp(t.name),is_active:t.is_active??!0,display_order:0};return await Oo(r)}import{db as Qe}from"@stacksjs/database/runtime";import{HttpError as ke}from"@stacksjs/error-handling";import{formatDate as It,isUniqueViolation as Kp}from"@stacksjs/orm";async function Ii(t,e){if(!await S(t))return;if(Object.hasOwn(e,"parent_category_id")){let o=e.parent_category_id?Number(e.parent_category_id):void 0;if(o!==void 0&&(!Number.isSafeInteger(o)||o<=0))throw new ke(422,"Parent category ID must be a positive integer");if(o===t)throw new ke(422,"A category cannot be its own parent");if(o&&!await S(o))throw new ke(422,`Parent category with ID ${e.parent_category_id} not found`);if(o&&await Oi(t,String(o)))throw new ke(422,"This operation would create a circular category hierarchy")}try{let o=Object.hasOwn(e,"parent_category_id")?{parent_category_id:e.parent_category_id||null}:{},n=await Qe.updateTable("categories").set({...e,...o,updated_at:It(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return n}catch(o){if(o instanceof ke)throw o;if(Kp(o))throw new ke(409,"A category with this name or slug already exists");if(o instanceof Error)throw Error(`Failed to update category: ${o.message}`);throw o}}async function Ni(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);try{return await Qe.updateTable("categories").set({display_order:e,updated_at:It(new Date)}).where("id","=",t).execute(),await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category display order: ${o.message}`);throw o}}async function Ji(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);try{return await Qe.updateTable("categories").set({is_active:e,updated_at:It(new Date)}).where("id","=",t).execute(),await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category active status: ${o.message}`);throw o}}async function Bi(t,e){if(!await S(t))throw Error(`Category with ID ${t} not found`);if(e){let o=Number(e);if(o===t)throw Error("A category cannot be its own parent");if(!await S(o))throw Error(`Parent category with ID ${e} not found`);if(await Oi(t,e))throw Error("This operation would create a circular reference in the category hierarchy")}try{let o={updated_at:It(new Date)};if(e===null)await Qe.updateTable("categories").set({...o,parent_category_id:null}).where("id","=",t).execute();else await Qe.updateTable("categories").set({...o,parent_category_id:e}).where("id","=",t).execute();return await S(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update category parent: ${o.message}`);throw o}}async function Oi(t,e){let r=Number(e),o=new Set;while(r){if(o.has(r))return!0;if(r===t)return!0;o.add(r);let n=await S(r),a=n?.parent_category_id;if(!n||!a)return!1;r=Number(a)}return!1}var Jt={};g(Jt,{bulkDestroy:()=>Wi,bulkStore:()=>Zi,destroy:()=>$i,fetchAll:()=>Li,fetchById:()=>ee,fetchTopProducts:()=>zi,store:()=>Vi,update:()=>Hi,updateAvailability:()=>Ki,updateInventory:()=>Qi});import{db as Ui}from"@stacksjs/database/runtime";async function $i(t){try{let e=await Ui.deleteFrom("products").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product item: ${e.message}`);throw e}}async function Wi(t){if(!t.length)return 0;try{let e=await Ui.deleteFrom("products").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product items: ${e.message}`);throw e}}import{db as X,sql as Qp}from"@stacksjs/database/runtime";async function ee(t){let e=await X.selectFrom("products").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.manufacturer_id)r=await X.selectFrom("manufacturers").where("id","=",e.manufacturer_id).selectAll().executeTakeFirst();if(e.category_id)o=await X.selectFrom("categories").where("id","=",e.category_id).selectAll().executeTakeFirst();return{...e,manufacturer:r,category:o}}return}async function Li(){let t=await X.selectFrom("products").selectAll().execute(),e=t.map((c)=>c.manufacturer_id).filter((c)=>c!==null&&c!==void 0),r=t.map((c)=>c.category_id).filter((c)=>c!==null&&c!==void 0),o=X.selectFrom("manufacturers"),n=X.selectFrom("categories");if(e.length>0)o=o.where("id","in",e);if(r.length>0)n=n.where("id","in",r);let a=await o.selectAll().execute(),s=await n.selectAll().execute(),i=a.reduce((c,l)=>(c[l.id]=l,c),{}),u=s.reduce((c,l)=>(c[l.id]=l,c),{});return t.map((c)=>({...c,manufacturer:c.manufacturer_id?i[c.manufacturer_id]:null,category:c.category_id?u[c.category_id]:null}))}async function ji(t){try{let e=await X.selectFrom("products").selectAll().where("uuid","=",t).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get product by UUID: ${e.message}`);throw e}}async function zi(t=5){try{return(await X.selectFrom("order_items").innerJoin("products","products.id","=","order_items.product_id").select(["products.id as id","products.name as name","products.inventory_count as inventory_count",X.fn.sum("order_items.quantity").as("units_sold"),Qp`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(t).execute()).map((r)=>({id:Number(r.id),name:String(r.name??"Unnamed product"),units_sold:Number(r.units_sold??0),revenue:Number(r.revenue??0),inventory_count:Number(r.inventory_count??0)}))}catch(e){if(e instanceof Error)throw TypeError(`Failed to fetch top products: ${e.message}`);throw e}}var{randomUUIDv7:Gi}=globalThis.Bun;import{db as qi}from"@stacksjs/database/runtime";async function Vi(t){try{let e={...t,uuid:Gi()},r=await qi.insertInto("products").values(e).executeTakeFirst();if(!r)throw Error("Failed to create product item");let o=H(r),n=o!==void 0?await ee(o):await ji(e.uuid);if(!n)throw Error("Failed to create product item");return n}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product item: ${e.message}`);throw e}}async function Zi(t){if(!t.length)return 0;let e=0;try{return await qi.transaction(async(r)=>{for(let o of t){let n={...o,uuid:Gi()};await r.insertInto("products").values(n).execute(),e++}}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product items in bulk: ${r.message}`);throw r}}import{db as Uo,matchedRows as g_}from"@stacksjs/database/runtime";import{formatDate as $o}from"@stacksjs/orm";async function Hi(t,e){try{if(!t)throw Error("Product item ID is required for update");let r=await Uo.updateTable("products").set({...e,updated_at:$o(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product item: ${r.message}`);throw r}}async function Ki(t,e){if(!await ee(t))throw Error(`Product item with ID ${t} not found`);try{return await Uo.updateTable("products").set({is_available:e,updated_at:$o(new Date)}).where("id","=",t).execute(),await ee(t)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update product item availability: ${o.message}`);throw o}}async function Qi(t,e){let r=await ee(t);if(!r)throw Error(`Product item with ID ${t} not found`);let o={updated_at:$o(new Date)};if(e!==void 0)o.inventory_count=e;if(Object.keys(o).length===1)return r;try{return await Uo.updateTable("products").set(o).where("id","=",t).execute(),await ee(t)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update inventory information: ${n.message}`);throw n}}var Bt={};g(Bt,{bulkDestroy:()=>eu,bulkStore:()=>lu,destroy:()=>Xi,fetchAll:()=>tu,fetchByCountry:()=>au,fetchById:()=>ru,fetchByUuid:()=>ou,fetchFeatured:()=>nu,fetchWithProductCount:()=>su,store:()=>du,update:()=>pu,updateByUuid:()=>wu,updateFeaturedStatus:()=>fu});import{db as Yi}from"@stacksjs/database/runtime";async function Xi(t){try{let e=await Yi.deleteFrom("manufacturers").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete order: ${e.message}`);throw e}}async function eu(t){if(!t.length)return 0;try{let e=await Yi.deleteFrom("manufacturers").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete orders: ${e.message}`);throw e}}import{db as te}from"@stacksjs/database/runtime";async function tu(){return w(await te.selectFrom("manufacturers").selectAll().execute())}async function ru(t){let e=await te.selectFrom("manufacturers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ou(t){let e=await te.selectFrom("manufacturers").where("uuid","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function nu(t=10){let e=await te.selectFrom("manufacturers").where("featured","=",!0).selectAll().orderBy("manufacturer","asc").limit(t).execute();return w(e)}async function au(t,e={}){let r=e.page||1,o=e.limit||2,n=await te.selectFrom("manufacturers").select(te.fn.count("id").as("total")).where("country","=",t).executeTakeFirst(),a=Number(n?.total||0),s=await te.selectFrom("manufacturers").selectAll().where("country","=",t).limit(o).offset((r-1)*o).execute(),i=Math.ceil(a/o);return{data:w(s),paging:{total_records:a,page:r,total_pages:i},next_cursor:r<i?r+1:null}}async function su(t={}){let e=te.selectFrom("manufacturers as m").leftJoin("products as p","p.manufacturer_id","=","m.id");if(t.country)e=e.where("m.country","=",t.country);if(t.featured!==void 0)e=e.where("m.featured","=",t.featured);return e=e.select(["m.id","m.uuid","m.manufacturer","m.description","m.country","m.featured","m.created_at","m.updated_at",te.fn.count("p.id").as("product_count")]).groupBy("m.id"),e.execute()}var{randomUUIDv7:uu}=globalThis.Bun;import{db as cu}from"@stacksjs/database/runtime";import{HttpError as iu}from"@stacksjs/error-handling";import{isUniqueViolation as Yp}from"@stacksjs/orm";async function du(t){try{let e={...t,uuid:uu(),featured:t.featured??!1},r=await cu.insertInto("manufacturers").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create manufacturer");return d(r)}catch(e){if(e instanceof iu)throw e;if(Yp(e))throw new iu(409,"A manufacturer with this name already exists");if(e instanceof Error)throw Error(`Failed to create manufacturer: ${e.message}`);throw e}}async function lu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:uu(),featured:r.featured??!1};await cu.insertInto("manufacturers").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create manufacturers in bulk: ${r.message}`);throw r}}import{db as Wo}from"@stacksjs/database/runtime";import{HttpError as mu}from"@stacksjs/error-handling";import{formatDate as Lo,isUniqueViolation as Xp}from"@stacksjs/orm";async function pu(t,e){try{if(!t)throw Error("Manufacturer ID is required for update");let r=await Wo.updateTable("manufacturers").set({...e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof mu)throw r;if(Xp(r))throw new mu(409,"A manufacturer with this name already exists");if(r instanceof Error)throw Error(`Failed to update manufacturer: ${r.message}`);throw r}}async function fu(t,e){try{let r=await Wo.updateTable("manufacturers").set({featured:e,updated_at:Lo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer featured status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer featured status: ${r.message}`);throw r}}async function wu(t,e){try{let r=await Wo.updateTable("manufacturers").set({...e,updated_at:Lo(new Date)}).where("uuid","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update manufacturer");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update manufacturer: ${r.message}`);throw r}}var Ot={};g(Ot,{bulkDestroy:()=>gu,destroy:()=>hu,fetchAll:()=>_u,fetchApprovedByProductId:()=>Du,fetchById:()=>bu,fetchByProductId:()=>Ru,fetchByUserId:()=>xu,fetchMostHelpfulByProductId:()=>vu,fetchStats:()=>Tu,fetchStatsByProductIds:()=>Eu,store:()=>Su,update:()=>Mu,updateVotes:()=>Iu});import{db as yu}from"@stacksjs/database/runtime";async function hu(t){try{let e=await yu.deleteFrom("reviews").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete review: ${e.message}`);throw e}}async function gu(t){if(!t.length)return 0;try{let e=await yu.deleteFrom("reviews").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete reviews: ${e.message}`);throw e}}import{db as Te}from"@stacksjs/database/runtime";async function bu(t){return d(await Te.selectFrom("reviews").where("id","=",t).selectAll().executeTakeFirst(),!0)}async function _u(){return w(await Te.selectFrom("reviews").selectAll().execute())}async function Ru(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).selectAll().execute())}async function xu(t){return w(await Te.selectFrom("reviews").where("customer_id","=",t).selectAll().execute())}async function Du(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).where("is_approved","=",!0).selectAll().execute())}async function vu(t){return w(await Te.selectFrom("reviews").where("product_id","=",t).orderBy("helpful_votes","desc").selectAll().execute())}import{db as Pu}from"@stacksjs/database/runtime";function Fu(){return{total:0,rated:0,commentsOnly:0,average:0,distribution:{1:0,2:0,3:0,4:0,5:0}}}function ku(t){let e=Fu();e.total=t.length;let r=0;for(let o of t){if(o.rating===null||o.rating===void 0){e.commentsOnly++;continue}let n=Number(o.rating);if(Number.isNaN(n)){e.commentsOnly++;continue}e.rated++,r+=n;let a=Math.min(5,Math.max(1,Math.round(n)));e.distribution[a]++}if(e.rated>0)e.average=Math.round(r/e.rated*10)/10;return e}async function Tu(t){let e=await Pu.selectFrom("reviews").select(["rating"]).where("product_id","=",t).where("is_approved","=",!0).execute();return ku(e)}async function Eu(t){let e=new Map;for(let n of t)e.set(n,Fu());if(t.length===0)return e;let r=await Pu.selectFrom("reviews").select(["product_id","rating"]).where("product_id","in",t).where("is_approved","=",!0).execute(),o=new Map;for(let n of r){let a=o.get(n.product_id);if(a)a.push({rating:n.rating});else o.set(n.product_id,[{rating:n.rating}])}for(let[n,a]of o)e.set(n,ku(a));return e}var{randomUUIDv7:ef}=globalThis.Bun;import{db as tf}from"@stacksjs/database/runtime";function rf(t){let e=t.rating!==void 0&&t.rating!==null,r=typeof t.content==="string"&&t.content.trim().length>0,o=typeof t.title==="string"&&t.title.trim().length>0;return!e&&!r&&!o}async function Su(t){try{if(rf(t))throw Error("A review needs a rating or something written: both were empty");let e={...t,uuid:ef(),rating:t.rating??null,is_verified_purchase:t.is_verified_purchase??!1,is_approved:t.is_approved??!1,helpful_votes:t.helpful_votes??0,unhelpful_votes:t.unhelpful_votes??0,is_featured:t.is_featured??!1},r=await tf.insertInto("reviews").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create review");return d(r)}catch(e){if(e instanceof Error){if(e.message.includes("Duplicate entry"))throw Error("A review with this code already exists");throw Error(`Failed to create review: ${e.message}`)}throw e}}import{db as Cu,sqlHelpers as of}from"@stacksjs/database/runtime";import{env as nf}from"@stacksjs/env";import{formatDate as Au}from"@stacksjs/orm";async function Mu(t,e){try{if(!t)throw Error("Review ID is required for update");let r=await Cu.updateTable("reviews").set({...e,updated_at:Au(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update review: ${r.message}`);throw r}}async function Iu(t,e,r=!0){try{let o=e==="helpful"?"helpful_votes":"unhelpful_votes",n=r?`COALESCE("${o}", 0) + 1`:`MAX(COALESCE("${o}", 0) - 1, 0)`,{param:a}=of(nf.DB_CONNECTION||"sqlite"),s=await Cu.unsafe(`UPDATE "reviews" SET "${o}" = ${n}, "updated_at" = ${a(1)} WHERE "id" = ${a(2)} RETURNING *`,[Au(new Date),t]).execute(),i=Array.isArray(s)?s[0]:s;if(!i)throw Error("Failed to update review votes");return d(i)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update review votes: ${o.message}`);throw o}}var Wt={};g(Wt,{bulkDestroy:()=>Bu,bulkStore:()=>ju,bulkUpdate:()=>Vu,destroy:()=>Ju,fetchAll:()=>$u,fetchById:()=>Uu,formatUnitOptions:()=>zu,getDefaultUnit:()=>Gu,store:()=>Lu,update:()=>qu,updateDefaultStatus:()=>Zu});import{db as Nu}from"@stacksjs/database/runtime";async function Ju(t){try{let e=await Nu.deleteFrom("product_units").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product unit: ${e.message}`);throw e}}async function Bu(t){if(!t.length)return 0;try{let e=await Nu.deleteFrom("product_units").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product units: ${e.message}`);throw e}}import{db as Ou}from"@stacksjs/database/runtime";async function Uu(t){let e=await Ou.selectFrom("product_units").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function $u(){return w(await Ou.selectFrom("product_units").selectAll().execute())}var{randomUUIDv7:Wu}=globalThis.Bun;import{db as Ye}from"@stacksjs/database/runtime";async function Lu(t){try{return await Ye.transaction(async(e)=>{let r={...t,uuid:Wu()},o=await e.insertInto("product_units").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create product unit");if(r.is_default&&r.type)await e.updateTable("product_units").set({is_default:!1}).where("type","=",r.type).where("id","!=",o.id).execute();return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product unit: ${e.message}`);throw e}}async function ju(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:Wu()},n=await Ye.insertInto("product_units").values(o).returningAll().executeTakeFirst();if(o.is_default&&o.type&&n)await Ye.updateTable("product_units").set({is_default:!1}).where("type","=",o.type).where("id","!=",n.id).execute();e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product units in bulk: ${r.message}`);throw r}}function zu(t){try{let e=Ye.selectFrom("product_units").select(["id","name","abbreviation","is_default"]);if(t)e=e.where("type","=",t);return e=e.orderBy("name"),e.execute().then((r)=>r.map((o)=>({id:String(o.id),name:o.name,abbreviation:o.abbreviation,is_default:o.is_default})))}catch(e){if(e instanceof Error)throw TypeError(`Failed to format unit options: ${e.message}`);throw e}}async function Gu(t){try{let e=await Ye.selectFrom("product_units").selectAll().where("type","=",t).where("is_default","=",!0).executeTakeFirst();return d(e,!0)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get default unit: ${e.message}`);throw e}}import{db as Ut,matchedRows as af}from"@stacksjs/database/runtime";import{formatDate as $t}from"@stacksjs/orm";async function qu(t,e){try{if(!t)throw Error("Product unit ID is required for update");return await Ut.transaction(async(r)=>{let o=await r.selectFrom("product_units").select(["type","is_default"]).where("id","=",t).executeTakeFirst();if(!o)return;let n=e.type??o.type;if((e.is_default??Boolean(o.is_default))&&n)await r.updateTable("product_units").set({is_default:!1,updated_at:$t(new Date)}).where("type","=",n).where("id","!=",t).execute();let s=await r.updateTable("product_units").set({...e,updated_at:$t(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit: ${r.message}`);throw r}}async function Vu(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o=r;if(!o.id)continue;let n=o.data&&typeof o.data==="object"?o.data:{...o};delete n.id;let a=await af(Ut.updateTable("product_units").set({...n,updated_at:$t(new Date)}).where("id","=",o.id)),s=n;if(s.is_default===!0&&s.type)await Ut.updateTable("product_units").set({is_default:!1}).where("type","=",s.type).where("id","!=",o.id).execute();if(a.length>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product units in bulk: ${r.message}`);throw r}}async function Zu(t,e){try{return await Ut.transaction(async(r)=>{let o=await r.selectFrom("product_units").select("type").where("id","=",t).executeTakeFirst();if(!o)return!1;let n=$t(new Date);if(e&&o.type)await r.updateTable("product_units").set({is_default:!1,updated_at:n}).where("type","=",o.type).where("id","!=",t).execute();return await r.updateTable("product_units").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product unit default status: ${r.message}`);throw r}}var Lt={};g(Lt,{bulkDestroy:()=>Qu,bulkStore:()=>nc,bulkUpdate:()=>dc,destroy:()=>Ku,fetchAll:()=>ec,fetchById:()=>Xu,formatVariantOptions:()=>ac,generateVariantCombinations:()=>sc,store:()=>oc,update:()=>cc});import{db as Hu}from"@stacksjs/database/runtime";async function Ku(t){try{let e=await Hu.deleteFrom("product_variants").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variant: ${e.message}`);throw e}}async function Qu(t){if(!t.length)return 0;try{let e=await Hu.deleteFrom("product_variants").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete product variants: ${e.message}`);throw e}}import{db as Yu}from"@stacksjs/database/runtime";async function Xu(t){let e=await Yu.selectFrom("product_variants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ec(){return w(await Yu.selectFrom("product_variants").selectAll().execute())}var{randomUUIDv7:tc}=globalThis.Bun;import{db as rc}from"@stacksjs/database/runtime";async function oc(t){try{let e={...t,uuid:tc()},r=await rc.insertInto("product_variants").values(e).returningAll().executeTakeFirst();if(!r)throw Error("Failed to create product variant");return d(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create product variant: ${e.message}`);throw e}}async function nc(t){if(!t.length)return 0;let e=0;try{for(let r of t){let o={...r,uuid:tc()};await rc.insertInto("product_variants").values(o).execute(),e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to create product variants in bulk: ${r.message}`);throw r}}function ac(t){if(!t||!t.length)return JSON.stringify([]);let e=t.map((r)=>r.trim()).filter(Boolean);return JSON.stringify(e)}function sc(t){let e=Object.keys(t);if(!e.length)return[];function r(o,n){if(o===e.length)return[n];let a=e[o],s=t[a]??[],i=[];for(let u of s){let c={...n,[a]:u};i.push(...r(o+1,c))}return i}return r(0,{})}import{db as ic,matchedRows as sf}from"@stacksjs/database/runtime";import{formatDate as uc}from"@stacksjs/orm";async function cc(t,e){try{let r=await ic.updateTable("product_variants").set({...e,updated_at:uc(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variant: ${r.message}`);throw r}}async function dc(t){if(!t.length)return 0;let e=0;try{for(let r of t){if(!r.id)continue;if((await sf(ic.updateTable("product_variants").set({...r,updated_at:uc(new Date)}).where("id","=",r.id))).length>0)e++}return e}catch(r){if(r instanceof Error)throw TypeError(`Failed to update product variants in bulk: ${r.message}`);throw r}}var uf={categories:Nt,items:Jt,manufacturers:Bt,reviews:Ot,units:Wt,variants:Lt},cf=uf;var Ho={};g(Ho,{bulkDestroy:()=>pc,bulkStore:()=>xc,destroy:()=>mc,fetchAll:()=>fc,fetchById:()=>Ee,fetchPageStats:()=>hc,fetchPrintJobStats:()=>wc,fetchPrintTimeStats:()=>gc,fetchPrintsPerHour:()=>bc,fetchSuccessRate:()=>yc,store:()=>Rc,update:()=>Dc,updatePrintJob:()=>Pc,updateStatus:()=>vc});import{db as lc}from"@stacksjs/database/runtime";async function mc(t){try{let e=await lc.deleteFrom("receipts").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete print log: ${e.message}`);throw e}}async function pc(t){if(!t.length)return 0;try{let e=await lc.deleteFrom("receipts").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete receipts: ${e.message}`);throw e}}import{db as zo}from"@stacksjs/database/runtime";import{formatDate as df}from"@stacksjs/orm";function j(t){return df(t)}function lf(t){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t==="number"){let o=new Date(t<=2147483647?t*1000:t);return Number.isNaN(o.getTime())?null:o}let e=String(t||"").trim();if(!e)return null;if(/^\d{10}$/.test(e)){let o=new Date(Number(e)*1000);return Number.isNaN(o.getTime())?null:o}let r=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(r.getTime())?null:r}async function Ee(t){let e=await zo.selectFrom("receipts").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function fc(){return w(await zo.selectFrom("receipts").selectAll().execute())}async function wc(t,e){let r=j(t),o=j(e),n=await J("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"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{total:n.total,success:n.success,failed:n.failed,warning:n.warning,averageSize:Math.round(n.averageSize),averagePages:Math.round(n.averagePages),averageDuration:Math.round(n.averageDuration)}}async function yc(t,e){let r=j(t),o=j(e),n=await J("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"}}},(s)=>s.where("timestamp",">=",r).where("timestamp","<=",o));return{successRate:n.total>0?Math.round(n.success/n.total*100):0,total:n.total,success:n.success,failed:n.failed,warning:n.warning}}async function hc(t,e){let r=j(t),o=j(e),n=await J("receipts",{totalReceipts:{kind:"count"},totalPages:{kind:"sum",column:"pages"},averagePagesPerReceipt:{kind:"avg",column:"pages"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{totalPages:n.totalPages,averagePagesPerReceipt:Math.round(n.averagePagesPerReceipt),totalReceipts:n.totalReceipts}}async function gc(t,e){let r=j(t),o=j(e),n=await J("receipts",{totalJobs:{kind:"count"},averageDuration:{kind:"avg",column:"duration"},minDuration:{kind:"min",column:"duration"},maxDuration:{kind:"max",column:"duration"}},(a)=>a.where("timestamp",">=",r).where("timestamp","<=",o));return{averageDuration:Math.round(n.averageDuration),minDuration:n.minDuration,maxDuration:n.maxDuration,totalJobs:n.totalJobs}}async function bc(t,e){let r=typeof t==="number"?t:t.getTime(),o=typeof e==="number"?e:e.getTime(),n=j(t),a=j(e),s=await zo.selectFrom("receipts").where("timestamp",">=",n).where("timestamp","<=",a).selectAll().execute(),i=s.length,u=Math.ceil((o-r)/3600000),c=u>0?Math.round(i/u):0,l=Array.from({length:24},(m,f)=>({hour:f,count:0}));return s.forEach((m)=>{let f=lf(m.timestamp);if(!f)return;l[f.getHours()].count++}),{totalPrints:i,totalHours:u,printsPerHour:c,hourlyBreakdown:l}}var{randomUUIDv7:_c}=globalThis.Bun;import{db as qo}from"@stacksjs/database/runtime";import{formatDate as Go}from"@stacksjs/orm";function Xe(t){try{if(typeof t==="number")return Go(t<=2147483647?t*1000:t);if(typeof t==="string"&&/^\d{10}$/.test(t))return Go(Number(t)*1000);return Go(t)}catch{throw TypeError("Receipt timestamp must be a valid date")}}async function Rc(t){try{let e=_c(),r={...t,timestamp:Xe(t.timestamp),uuid:e};await qo.insertInto("receipts").values(r).executeTakeFirst();let o=await qo.selectFrom("receipts").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create receipt");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipt: ${e.message}`);throw e}}async function xc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...o,timestamp:Xe(o.timestamp),uuid:_c()})),r=await qo.insertInto("receipts").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create receipts in bulk: ${e.message}`);throw e}}import{db as Vo}from"@stacksjs/database/runtime";import{formatDate as Zo}from"@stacksjs/orm";async function Dc(t,e){try{if(!t)throw Error("Receipt ID is required for update");let r={...e,...e.timestamp===void 0?{}:{timestamp:Xe(e.timestamp)},updated_at:Zo(new Date)};await Vo.updateTable("receipts").set(r).where("id","=",t).execute();let o=await Ee(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt: ${r.message}`);throw r}}async function vc(t,e){try{await Vo.updateTable("receipts").set({status:e,updated_at:Zo(new Date)}).where("id","=",t).execute();let r=await Ee(t);if(!r)throw Error("Failed to update receipt status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update receipt status: ${r.message}`);throw r}}async function Pc(t,e,r,o){try{let n={updated_at:Zo(new Date)};if(e!==void 0)n.size=e;if(r!==void 0)n.pages=r;if(o!==void 0)n.duration=o;await Vo.updateTable("receipts").set(n).where("id","=",t).execute();let a=await Ee(t);if(!a)throw Error("Failed to update receipt job information");return d(a)}catch(n){if(n instanceof Error)throw TypeError(`Failed to update receipt job information: ${n.message}`);throw n}}var Rn={};g(Rn,{couriers:()=>Yt,default:()=>Nf,digital:()=>Kt,geocoding:()=>rr,licenses:()=>ar,methods:()=>cr,rates:()=>fr,routes:()=>Zt,tracking:()=>xr,zones:()=>Fr});var Zt={};g(Zt,{DeliveryRouteInputError:()=>N,bulkDestroy:()=>Tc,destroy:()=>kc,fetchActive:()=>Sc,fetchAll:()=>Ec,fetchByCourier:()=>Cc,fetchById:()=>zt,store:()=>Ac,update:()=>Ic,updateLastActive:()=>Mc,updateMetrics:()=>Jc,updateStops:()=>Nc,validateDeliveryRouteWrite:()=>Se});import{db as Fc}from"@stacksjs/database/runtime";async function kc(t){try{let e=await Fc.deleteFrom("delivery_routes").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery route: ${e.message}`);throw e}}async function Tc(t){if(!t.length)return 0;try{let e=await Fc.deleteFrom("delivery_routes").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete delivery routes: ${e.message}`);throw e}}import{db as jt}from"@stacksjs/database/runtime";async function zt(t){return await jt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst()}async function Ec(){return await jt.selectFrom("delivery_routes").selectAll().execute()}async function Sc(){return await jt.selectFrom("delivery_routes").where("last_active",">=",Date.now()-86400000).selectAll().execute()}async function Cc(t){return await jt.selectFrom("delivery_routes").where("courier","=",t).selectAll().execute()}var{randomUUIDv7:ff}=globalThis.Bun;import{db as Ko}from"@stacksjs/database/runtime";function he(t,e){let r={};for(let[o,n]of Object.entries(e))for(let a of n){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)continue;r[o]=t[a];break}return r}function et(t){return he(t,{name:["name"],description:["description"],base_rate:["base_rate","baseRate"],free_shipping:["free_shipping","freeShipping"],status:["status"]})}function re(t){return he(t,{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 tt(t){return he(t,{name:["name"],countries:["countries"],regions:["regions"],postal_codes:["postal_codes","postalCodes"],status:["status"],shipping_method_id:["shipping_method_id","shippingMethodId","shippingmethod_id"]})}function rt(t){return he(t,{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 ot(t){return he(t,{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 nt(t){return he(t,{name:["name"],phone:["phone"],vehicle_number:["vehicle_number","vehicleNumber"],license:["license"],status:["status"],user_id:["user_id","userId"]})}function Gt(t){return he(t,{courier:["courier"],courier_id:["courier_id","courierId"],vehicle:["vehicle"],stops:["stops"],delivery_time:["delivery_time","deliveryTime"],total_distance:["total_distance","totalDistance"],last_active:["last_active","lastActive"]})}import{db as mf}from"@stacksjs/database/runtime";class N extends TypeError{constructor(t){super(t);this.name="DeliveryRouteInputError"}}function qt(t,e,r){return Number(t[r]??e?.[r])}function pf(t,e){let r=t.last_active??e?.last_active;if(r===void 0||r===null)return Date.now();if(r instanceof Date)return r.getTime();if(typeof r==="number")return r;if(typeof r==="string"&&/^\d{10,13}$/.test(r))return Number(r);return Number.NaN}async function Se(t,e){let r=qt(t,e,"courier_id"),o=qt(t,e,"stops"),n=qt(t,e,"delivery_time"),a=qt(t,e,"total_distance"),s=pf(t,e);if(!Number.isSafeInteger(r)||r<1)throw new N("Courier must be a positive integer.");if(!Number.isSafeInteger(o)||o<0)throw new N("Stops must be a non-negative integer.");if(!Number.isSafeInteger(n)||n<0)throw new N("Delivery time must be a non-negative integer.");if(!Number.isSafeInteger(a)||a<0)throw new N("Total distance must be a non-negative integer.");if(!Number.isSafeInteger(s)||s<0)throw new N("Last active must be a valid Unix timestamp.");let i=await mf.selectFrom("couriers").where("id","=",r).select(["id","name","vehicle_number"]).executeTakeFirst();if(!i)throw new N(`Courier ${r} was not found.`);return{...t,courier_id:Number(i.id),courier:i.name,vehicle:i.vehicle_number,last_active:s}}async function Ac(t){try{let e=ff(),r=Gt(t),n={...await Se(r),uuid:e};await Ko.insertInto("delivery_routes").values(n).executeTakeFirst();let a=await Ko.selectFrom("delivery_routes").where("uuid","=",e).selectAll().executeTakeFirst();if(!a)throw Error("Failed to create delivery route");return a}catch(e){if(e instanceof N)throw e;if(e instanceof Error)throw TypeError(`Failed to create delivery route: ${e.message}`);throw e}}async function Mc(t){try{await Ko.updateTable("delivery_routes").set({last_active:Date.now(),updated_at:new Date().toISOString()}).where("id","=",t).execute();let e=await zt(t);if(!e)throw Error("Failed to update delivery route last active");return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update delivery route last active: ${e.message}`);throw e}}import{db as Vt}from"@stacksjs/database/runtime";import{formatDate as Qo}from"@stacksjs/orm";async function Ic(t,e){try{if(!t)throw Error("Delivery route ID is required for update");let r=await Vt.selectFrom("delivery_routes").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=Gt(e),n=await Se(o,r),a=await Vt.updateTable("delivery_routes").set({...n,updated_at:Qo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return a}catch(r){if(r instanceof N)throw r;if(r instanceof Error)throw TypeError(`Failed to update delivery route: ${r.message}`);throw r}}async function Nc(t,e){try{let r=await Vt.updateTable("delivery_routes").set({stops:e,updated_at:Qo(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update delivery route stops");return r}catch(r){if(r instanceof Error)throw TypeError(`Failed to update delivery route stops: ${r.message}`);throw r}}async function Jc(t,e,r){try{let o={updated_at:Qo(new Date)};if(e!==void 0)o.delivery_time=e;if(r!==void 0)o.total_distance=r;let n=await Vt.updateTable("delivery_routes").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update delivery metrics");return n}catch(o){if(o instanceof Error)throw TypeError(`Failed to update delivery metrics: ${o.message}`);throw o}}var Kt={};g(Kt,{bulkDestroy:()=>$c,bulkSoftDelete:()=>Wc,bulkStore:()=>Vc,destroy:()=>Oc,fetchAll:()=>zc,fetchById:()=>jc,softDelete:()=>Uc,store:()=>qc,update:()=>Zc,updateDeliverySettings:()=>Kc,updateStatus:()=>Hc});import{db as Ht,matchedRows as Bc}from"@stacksjs/database/runtime";async function Oc(t){try{let e=await Ht.deleteFrom("digital_deliveries").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital delivery: ${e.message}`);throw e}}async function Uc(t){try{return(await Bc(Ht.updateTable("digital_deliveries").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital delivery: ${e.message}`);throw e}}async function $c(t){if(!t.length)return 0;try{let e=await Ht.deleteFrom("digital_deliveries").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete digital deliveries: ${e.message}`);throw e}}async function Wc(t){if(!t.length)return 0;try{return(await Bc(Ht.updateTable("digital_deliveries").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete digital deliveries: ${e.message}`);throw e}}import{db as Lc}from"@stacksjs/database/runtime";async function jc(t){let e=await Lc.selectFrom("digital_deliveries").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function zc(){return w(await Lc.selectFrom("digital_deliveries").selectAll().execute())}var{randomUUIDv7:Gc}=globalThis.Bun;import{db as Yo}from"@stacksjs/database/runtime";async function qc(t){try{let e=Gc(),r={...rt(t),uuid:e};await Yo.insertInto("digital_deliveries").values(r).executeTakeFirst();let o=await Yo.selectFrom("digital_deliveries").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created digital delivery");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital delivery: ${e.message}`);throw e}}async function Vc(t){if(!t.length)return 0;try{let e=t.map((o)=>({...rt(o),uuid:Gc()})),r=await Yo.insertInto("digital_deliveries").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create digital deliveries in bulk: ${e.message}`);throw e}}import{db as Xo}from"@stacksjs/database/runtime";import{formatDate as en}from"@stacksjs/orm";async function Zc(t,e){try{if(!t)throw Error("Digital delivery ID is required for update");let r=await Xo.updateTable("digital_deliveries").set({...rt(e),updated_at:en(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery: ${r.message}`);throw r}}async function Hc(t,e){try{let r=await Xo.updateTable("digital_deliveries").set({status:e,updated_at:en(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update digital delivery status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update digital delivery status: ${r.message}`);throw r}}async function Kc(t,e,r,o,n){try{let a={updated_at:en(new Date)};if(e!==void 0)a.download_limit=e;if(r!==void 0)a.expiry_days=r;if(o!==void 0)a.requires_login=o;if(n!==void 0)a.automatic_delivery=n;let s=await Xo.updateTable("digital_deliveries").set(a).where("id","=",t).returningAll().executeTakeFirst();if(!s)throw Error("Failed to update delivery settings");return d(s)}catch(a){if(a instanceof Error)throw TypeError(`Failed to update delivery settings: ${a.message}`);throw a}}var Yt={};g(Yt,{bulkDestroy:()=>td,bulkStore:()=>nd,destroy:()=>ed,fetchAll:()=>Yc,fetchById:()=>Qt,store:()=>od,update:()=>ad,updateContact:()=>id,updateStatus:()=>sd});import{db as Xc}from"@stacksjs/database/runtime";import{db as Qc}from"@stacksjs/database/runtime";async function Qt(t){let e=await Qc.selectFrom("couriers").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Yc(){return w(await Qc.selectFrom("couriers").selectAll().execute())}async function ed(t){try{let e=await Xc.deleteFrom("couriers").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete courier: ${e.message}`);throw e}}async function td(t){if(!t.length)return 0;let e=0;try{return await Xc.transaction(async(r)=>{for(let o of t)if(await Qt(o))await r.deleteFrom("couriers").where("id","=",o).execute(),e++}),e}catch(r){if(r instanceof Error)throw TypeError(`Failed to delete couriers in bulk: ${r.message}`);throw r}}var{randomUUIDv7:rd}=globalThis.Bun;import{db as tn}from"@stacksjs/database/runtime";async function od(t){try{let e=rd(),r={...nt(t),uuid:e};await tn.insertInto("couriers").values(r).executeTakeFirst();let o=await tn.selectFrom("couriers").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created courier");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create courier: ${e.message}`);throw e}}async function nd(t){if(!t.length)return 0;try{let e=t.map((o)=>({...nt(o),uuid:rd()})),r=await tn.insertInto("couriers").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create couriers in bulk: ${e.message}`);throw e}}import{db as rn}from"@stacksjs/database/runtime";import{formatDate as on}from"@stacksjs/orm";async function ad(t,e){try{if(!t)throw Error("Courier ID is required for update");let r=await rn.updateTable("couriers").set({...nt(e),updated_at:on(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier: ${r.message}`);throw r}}async function sd(t,e){try{let r=await rn.updateTable("couriers").set({status:e,updated_at:on(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update courier status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update courier status: ${r.message}`);throw r}}async function id(t,e){try{let r={updated_at:on(new Date)};if(e!==void 0)r.phone=e;let o=await rn.updateTable("couriers").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update contact information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update contact information: ${r.message}`);throw r}}var rr={};g(rr,{PRECISION_RANK:()=>st,checkCoverage:()=>_f,formatQuery:()=>Ce,geocode:()=>bf,geocodingDriver:()=>pd,nominatimDriver:()=>tr,setGeocodingDriver:()=>gf});var ge=(t)=>t*Math.PI/180;function ce(t,e){let r=ge(e.latitude-t.latitude),o=ge(e.longitude-t.longitude),n=ge(t.latitude),a=ge(e.latitude),s=Math.sin(r/2)**2+Math.sin(o/2)**2*Math.cos(n)*Math.cos(a);return 12742017.6*Math.asin(Math.sqrt(s))}function Xt(t,e){let r=ge(t.latitude),o=ge(e.latitude),n=ge(e.longitude-t.longitude),a=Math.sin(n)*Math.cos(o),s=Math.cos(r)*Math.sin(o)-Math.sin(r)*Math.cos(o)*Math.cos(n);return(Math.atan2(a,s)*180/Math.PI+360)%360}function er(t,e,r={}){let o=r.detourFactor??1.35,n=r.minimumSeconds??30;if(!Number.isFinite(e)||e<=0.5)return null;let a=t*o/e;return Math.max(n,Math.round(a))}function ud(t,e,r){return ce(t,e)<=r}function at(t){return typeof t?.latitude==="number"&&typeof t?.longitude==="number"&&Number.isFinite(t.latitude)&&Number.isFinite(t.longitude)}var st={unknown:0,locality:1,postal:2,street:3,rooftop:4};function Ce(t){return[t.street,t.city,t.region,t.postalCode,t.country].map((e)=>String(e??"").trim()).filter(Boolean).join(", ")}var wf="https://nominatim.openstreetmap.org/search",cd=1000,dd=0,ld=Promise.resolve();async function yf(t){let e=ld.then(async()=>{let r=Date.now()-dd;if(r<cd)await Bun.sleep(cd-r);return dd=Date.now(),t()});return ld=e.then(()=>{return},()=>{return}),e}function hf(t){let e=t.address??{},r=String(t.addresstype??""),o=String(t.type??""),n=String(t.category??t.class??"");if(e.house_number||o==="house"||o==="building"||r==="building")return"rooftop";if(e.road||n==="highway"||r==="road")return"street";if(r==="postcode"||e.postcode&&!e.road)return"postal";if(["city","town","village","suburb","neighbourhood"].includes(r))return"locality";return"unknown"}function tr(t={}){let e=t.userAgent??`${process.env.APP_NAME??"Stacks"} (${process.env.APP_URL??"stacks-app"})`,r=t.endpoint??wf;return{name:"nominatim",async geocode(o){let n=Ce(o);if(!n)return null;let a=new URL(r);if(a.searchParams.set("q",n),a.searchParams.set("format","jsonv2"),a.searchParams.set("limit","1"),a.searchParams.set("addressdetails","1"),o.country)a.searchParams.set("countrycodes",o.country.toLowerCase());let s=await yf(()=>fetch(a,{headers:{"user-agent":e,accept:"application/json"},signal:AbortSignal.timeout(8000)}));if(!s.ok)throw Error(`Nominatim responded ${s.status}`);let u=(await s.json())?.[0];if(!u)return null;let c=Number(u.lat),l=Number(u.lon);if(!Number.isFinite(c)||!Number.isFinite(l))return null;let m=hf(u);return{latitude:c,longitude:l,formatted:String(u.display_name??n),confidence:{rooftop:1,street:0.8,postal:0.5,locality:0.3,unknown:0.1}[m],precision:m,provider:"nominatim"}}}}var md=null;function gf(t){md=t}function pd(){return md??tr()}async function bf(t,e={}){let r=e.driver??pd(),o=e.minimumPrecision??"street",n=`geocode:${r.name}:${Ce(t).toLowerCase()}`,a=await Rf(n);if(a!==void 0)return a;let s=await r.geocode(t),i=s&&st[s.precision]>=st[o]?s:null;return await xf(n,i,i?e.cacheSeconds??2592000:600),i}function _f(t,e,r){if(e.length===0)return null;let o=e[0],n=ce(t,o);for(let a of e.slice(1)){let s=ce(t,a);if(s<n)n=s,o=a}return{covered:n<=r,distanceMeters:Math.round(n),nearest:o}}async function Rf(t){try{let r=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!r)return;let o=await r.get(t);if(o===null||o===void 0)return;return o==="null"?null:JSON.parse(String(o))}catch{return}}async function xf(t,e,r){try{let n=(await import("@stacksjs/cache").catch(()=>null))?.cache;if(!n)return;await n.set(t,e===null?"null":JSON.stringify(e),r)}catch{}}var ar={};g(ar,{LicenseKeyInputError:()=>T,bulkDestroy:()=>hd,bulkSoftDelete:()=>gd,bulkStore:()=>Fd,destroy:()=>wd,fetchAll:()=>Rd,fetchById:()=>_d,softDelete:()=>yd,store:()=>Pd,update:()=>kd,updateExpiration:()=>Ed,updateStatus:()=>Td,validateLicenseKeyWrite:()=>be});import{db as or,matchedRows as fd}from"@stacksjs/database/runtime";async function wd(t){try{let e=await or.deleteFrom("license_keys").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license key: ${e.message}`);throw e}}async function yd(t){try{return(await fd(or.updateTable("license_keys").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license key: ${e.message}`);throw e}}async function hd(t){if(!t.length)return 0;try{let e=await or.deleteFrom("license_keys").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete license keys: ${e.message}`);throw e}}async function gd(t){if(!t.length)return 0;try{return(await fd(or.updateTable("license_keys").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete license keys: ${e.message}`);throw e}}import{db as bd}from"@stacksjs/database/runtime";async function _d(t){let e=await bd.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Rd(){return w(await bd.selectFrom("license_keys").selectAll().execute())}var{randomUUIDv7:vd}=globalThis.Bun;import{db as sn}from"@stacksjs/database/runtime";import{db as nn}from"@stacksjs/database/runtime";var xd=["Standard License","Premium License","Enterprise License"],Dd=["active","inactive","unassigned"];class T extends TypeError{constructor(t){super(t);this.name="LicenseKeyInputError"}}function it(t,e,r){return t[r]!==void 0?t[r]:e?.[r]}function an(t,e,r,o){let n=it(t,e,r);if(n===void 0||n===null||n==="")return null;let a=Number(n);if(!Number.isSafeInteger(a)||a<1)throw new T(`${o} must be a positive integer or null.`);return a}function Df(t){if(typeof t==="number")return t>2147483647?Math.floor(t/1000):t;if(typeof t==="string"&&/^\d{10,13}$/.test(t))return t.length===13?Math.floor(Number(t)/1000):Number(t);if(typeof t==="string"){let e=/^\d{4}-\d{2}-\d{2} \d/.test(t)?`${t.replace(" ","T")}Z`:t;return Math.floor(new Date(e).getTime()/1000)}return Number.NaN}async function be(t,e){let r=String(it(t,e,"key")||"").trim().toUpperCase(),o=String(it(t,e,"template")||""),n=String(it(t,e,"status")||""),a=Df(it(t,e,"expiry_date")),s=an(t,e,"customer_id","Customer"),i=an(t,e,"product_id","Product"),u=an(t,e,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(r))throw new T("License key must use five groups of four uppercase letters or numbers.");if(!xd.includes(o))throw new T(`Template must be one of: ${xd.join(", ")}.`);if(!Dd.includes(n))throw new T(`Status must be one of: ${Dd.join(", ")}.`);if(!Number.isSafeInteger(a)||a<0||a>2147483647)throw new T("Expiry date must be a Unix timestamp between 1970 and 2038.");let[c,l,m]=await Promise.all([s?nn.selectFrom("customers").where("id","=",s).select("id").executeTakeFirst():null,i?nn.selectFrom("products").where("id","=",i).select("id").executeTakeFirst():null,u?nn.selectFrom("orders").where("id","=",u).select(["id","customer_id"]).executeTakeFirst():null]);if(s&&!c)throw new T(`Customer ${s} was not found.`);if(i&&!l)throw new T(`Product ${i} was not found.`);if(u&&!m)throw new T(`Order ${u} was not found.`);if(s&&m?.customer_id&&Number(m.customer_id)!==s)throw new T(`Order ${u} belongs to Customer ${m.customer_id}, not Customer ${s}.`);return{...t,key:r,template:o,expiry_date:a,status:n,customer_id:s,product_id:i,order_id:u}}async function Pd(t){try{let e=vd(),r=ot(t),o={...await be(r),uuid:e};await sn.insertInto("license_keys").values(o).executeTakeFirst();let n=await sn.selectFrom("license_keys").where("uuid","=",e).selectAll().executeTakeFirst();if(!n)throw Error("Failed to resolve created license key");return d(n)}catch(e){if(e instanceof T)throw e;if(e instanceof Error){if(e.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to create license key: ${e.message}`)}throw e}}async function Fd(t){if(!t.length)return 0;try{let e=await Promise.all(t.map(async(o)=>({...await be(ot(o)),uuid:vd()}))),r=await sn.insertInto("license_keys").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof T)throw e;if(e instanceof Error)throw TypeError(`Failed to create license keys in bulk: ${e.message}`);throw e}}import{db as nr}from"@stacksjs/database/runtime";import{formatDate as un}from"@stacksjs/orm";async function kd(t,e){try{if(!t)throw Error("License key ID is required for update");let r=await nr.selectFrom("license_keys").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=ot(e),n=await be(o,r),a=await nr.updateTable("license_keys").set({...n,updated_at:un(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!a)return;return d(a)}catch(r){if(r instanceof T)throw r;if(r instanceof Error){if(r.message.includes("UNIQUE constraint failed: license_keys.key"))throw new T("A license key with this value already exists.");throw TypeError(`Failed to update license key: ${r.message}`)}throw r}}async function Td(t,e){try{let r=await nr.updateTable("license_keys").set({status:e,updated_at:un(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update license key status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update license key status: ${r.message}`);throw r}}async function Ed(t,e){try{let r={updated_at:un(new Date)};if(e!==void 0)r.expiry_date=e;let o=await nr.updateTable("license_keys").set(r).where("id","=",t).returningAll().executeTakeFirst();if(!o)throw Error("Failed to update expiration information");return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update expiration information: ${r.message}`);throw r}}var cr={};g(cr,{bulkDestroy:()=>Md,bulkSoftDelete:()=>Id,bulkStore:()=>Od,destroy:()=>Cd,fetchAll:()=>Nd,fetchById:()=>ur,formatShippingOptions:()=>Ud,getActiveShippingMethods:()=>$d,softDelete:()=>Ad,store:()=>Bd,update:()=>Wd,updatePricing:()=>jd,updateStatus:()=>Ld});import{db as sr,matchedRows as Sd}from"@stacksjs/database/runtime";async function Cd(t){try{let e=await sr.deleteFrom("shipping_methods").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping method: ${e.message}`);throw e}}async function Ad(t){try{return(await Sd(sr.updateTable("shipping_methods").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping method: ${e.message}`);throw e}}async function Md(t){if(!t.length)return 0;try{let e=await sr.deleteFrom("shipping_methods").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping methods: ${e.message}`);throw e}}async function Id(t){if(!t.length)return 0;try{return(await Sd(sr.updateTable("shipping_methods").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping methods: ${e.message}`);throw e}}import{db as ir}from"@stacksjs/database/runtime";async function ur(t){let e=await ir.selectFrom("shipping_methods").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=await ir.selectFrom("shipping_zones").where("shipping_method_id","=",t).selectAll().execute();return{...e,shippingZones:r}}return}async function Nd(){let t=await ir.selectFrom("shipping_methods").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((a)=>a.id))],n=(await ir.selectFrom("shipping_zones").where("shipping_method_id","in",e).selectAll().execute()).reduce((a,s)=>{let i=s.shipping_method_id;if(i!==null&&i!==void 0){if(!a[i])a[i]=[];a[i].push(s)}return a},{});return t.map((a)=>({...a,shipping_zones:n[a.id]||[]}))}var{randomUUIDv7:Jd}=globalThis.Bun;import{db as ut}from"@stacksjs/database/runtime";async function Bd(t){try{let e=Jd(),r={...et(t),uuid:e};await ut.insertInto("shipping_methods").values(r).executeTakeFirst();let o=await ut.selectFrom("shipping_methods").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping method");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping method: ${e.message}`);throw e}}async function Od(t){if(!t.length)return 0;try{let e=t.map((o)=>({...et(o),uuid:Jd()})),r=await ut.insertInto("shipping_methods").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping methods in bulk: ${e.message}`);throw e}}function Ud(){try{return ut.selectFrom("shipping_methods").select(["id","name","status","base_rate"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping options: ${t.message}`);throw t}}async function $d(){try{let t=await ut.selectFrom("shipping_methods").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping methods: ${t.message}`);throw t}}import{db as cn}from"@stacksjs/database/runtime";import{formatDate as dn}from"@stacksjs/orm";async function Wd(t,e){try{if(!t)throw Error("Shipping method ID is required for update");let r=await cn.updateTable("shipping_methods").set({...et(e),updated_at:dn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method: ${r.message}`);throw r}}async function Ld(t,e){try{let r=await cn.updateTable("shipping_methods").set({status:e,updated_at:dn(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping method status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping method status: ${r.message}`);throw r}}async function jd(t,e,r){try{let o={updated_at:dn(new Date)};if(e!==void 0)o.base_rate=e;if(r!==void 0)o.free_shipping=r;let n=await cn.updateTable("shipping_methods").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update pricing information");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update pricing information: ${o.message}`);throw o}}var fr={};g(fr,{ShippingRateInputError:()=>A,bulkDestroy:()=>Gd,bulkStore:()=>ul,bulkUpdate:()=>dl,destroy:()=>zd,destroyByMethod:()=>Vd,destroyByZone:()=>qd,fetchAll:()=>Kd,fetchById:()=>Hd,formatShippingRateOptions:()=>el,getRateByWeightAndAddress:()=>Yd,getRateByWeightAndZone:()=>ln,getRatesByZone:()=>Qd,getShippingRatesByMethod:()=>tl,resolveZoneForAddress:()=>lr,store:()=>il,update:()=>cl,updateByMethod:()=>ml,updateByZone:()=>ll,validateShippingRateWrite:()=>_e,validateZoneMatchesAddress:()=>Xd});import{db as dr}from"@stacksjs/database/runtime";async function zd(t){try{let e=await dr.deleteFrom("shipping_rates").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rate: ${e.message}`);throw e}}async function Gd(t){if(!t.length)return 0;try{let e=await dr.deleteFrom("shipping_rates").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates: ${e.message}`);throw e}}async function qd(t){try{let e=await dr.deleteFrom("shipping_rates").where("shipping_zone_id","=",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by zone: ${e.message}`);throw e}}async function Vd(t){try{let e=await dr.deleteFrom("shipping_rates").where("shipping_method_id","=",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping rates by method: ${e.message}`);throw e}}import{db as W}from"@stacksjs/database/runtime";async function Hd(t){let e=await W.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(e){let r=null,o=null;if(e.shipping_zone_id)r=await W.selectFrom("shipping_zones").where("id","=",e.shipping_zone_id).selectAll().executeTakeFirst();if(e.shipping_method_id)o=await W.selectFrom("shipping_methods").where("id","=",e.shipping_method_id).selectAll().executeTakeFirst();return{...e,shipping_zone:r,shipping_method:o}}return}async function Kd(){let t=await W.selectFrom("shipping_rates").selectAll().execute();if(t.length===0)return[];let e=[...new Set(t.map((i)=>i.shipping_zone_id).filter((i)=>i!==null&&i!==void 0))],r=[...new Set(t.map((i)=>i.shipping_method_id).filter((i)=>i!==null&&i!==void 0))],[o,n]=await Promise.all([e.length?W.selectFrom("shipping_zones").where("id","in",e).selectAll().execute():[],r.length?W.selectFrom("shipping_methods").where("id","in",r).selectAll().execute():[]]),a=o.reduce((i,u)=>(i[u.id]=u,i),{}),s=n.reduce((i,u)=>(i[u.id]=u,i),{});return t.map((i)=>({...i,shipping_zone:i.shipping_zone_id?a[i.shipping_zone_id]:[],shipping_method:i.shipping_method_id?s[i.shipping_method_id]:[]}))}async function Qd(t){try{let e=await W.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by zone: ${e.message}`);throw e}}async function ln(t,e){try{let r=await W.selectFrom("shipping_rates").selectAll().where("shipping_zone_id","=",e).where("weight_from","<=",t).where("weight_to",">=",t).executeTakeFirst();return d(r,!0)}catch(r){if(r instanceof Error)throw TypeError(`Failed to get shipping rate by weight and zone: ${r.message}`);throw r}}async function lr(t){if(!t?.countryCode)return null;try{let e=await W.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t.countryCode}%`).where("status","=","active").execute();if(e.length===0)return null;let r=null;for(let o of e){let n=1;if(t.region&&o.regions&&Zd(o.regions,t.region))n=2;if(t.postalCode&&o.postal_codes&&Zd(o.postal_codes,t.postalCode))n=3;if(!r||n>r.score)r={id:o.id,score:n}}return r?.id??null}catch{return null}}async function Yd(t,e){let r=await lr(e);if(r==null)return;return ln(t,r)}async function Xd(t,e){return await lr(e)===t}function Zd(t,e){if(!t||!e)return!1;let r=e.trim().toUpperCase();for(let o of t.split(/[,|;]/))if(o.trim().toUpperCase()===r)return!0;return!1}async function el(){try{return(await W.selectFrom("shipping_rates").select(["id","shipping_method_id","shipping_zone_id","rate"]).orderBy("shipping_method_id").execute()).filter((e)=>e.shipping_method_id!==null&&e.shipping_method_id!==void 0&&e.shipping_zone_id!==null&&e.shipping_zone_id!==void 0)}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping rate options: ${t.message}`);throw t}}async function tl(t){try{let e=await W.selectFrom("shipping_rates").selectAll().where("shipping_method_id","=",t).orderBy("weight_from").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping rates by method: ${e.message}`);throw e}}var{randomUUIDv7:sl}=globalThis.Bun;import{db as mn}from"@stacksjs/database/runtime";import{db as ct}from"@stacksjs/database/runtime";async function rl(){return w(await ct.selectFrom("shipping_zones").selectAll().execute())}async function mr(t){let e=await ct.selectFrom("shipping_zones").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}function ol(){try{return ct.selectFrom("shipping_zones").select(["id","name","status","countries"]).orderBy("name").execute()}catch(t){if(t instanceof Error)throw TypeError(`Failed to format shipping zone options: ${t.message}`);throw t}}async function nl(){try{let t=await ct.selectFrom("shipping_zones").selectAll().where("status","=","active").orderBy("name").execute();return w(t)}catch(t){if(t instanceof Error)throw TypeError(`Failed to get active shipping zones: ${t.message}`);throw t}}async function al(t){try{let e=await ct.selectFrom("shipping_zones").selectAll().where("countries","like",`%${t}%`).where("status","=","active").orderBy("name").execute();return w(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to get shipping zones by country: ${e.message}`);throw e}}class A extends TypeError{constructor(t){super(t);this.name="ShippingRateInputError"}}function dt(t,e,r){return Number(t[r]??e?.[r])}async function _e(t,e){let r=dt(t,e,"shipping_method_id"),o=dt(t,e,"shipping_zone_id"),n=dt(t,e,"weight_from"),a=dt(t,e,"weight_to"),s=dt(t,e,"rate");if(!Number.isSafeInteger(r)||r<1)throw new A("Shipping method must be a positive integer.");if(!Number.isSafeInteger(o)||o<1)throw new A("Shipping zone must be a positive integer.");if(!Number.isFinite(n)||n<0)throw new A("Weight from must be a non-negative number.");if(!Number.isFinite(a)||a<n)throw new A("Weight to must be greater than or equal to weight from.");if(!Number.isSafeInteger(s)||s<0)throw new A("Rate must be a non-negative integer in minor currency units.");let[i,u]=await Promise.all([ur(r),mr(o)]);if(!i)throw new A(`Shipping method ${r} was not found.`);if(!u)throw new A(`Shipping zone ${o} was not found.`);if(Number(u.shipping_method_id)!==r)throw new A(`Shipping zone ${o} is not assigned to shipping method ${r}.`)}async function il(t){try{let e=re(t),r=Number(e.shipping_method_id),o=Number(e.shipping_zone_id);await _e(e);let n=sl(),a={...e,shipping_method_id:r,shipping_zone_id:o,uuid:n};await mn.insertInto("shipping_rates").values(a).executeTakeFirst();let s=await mn.selectFrom("shipping_rates").where("uuid","=",n).selectAll().executeTakeFirst();if(!s)throw Error("Failed to resolve created shipping rate");return d(s)}catch(e){if(e instanceof A)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rate: ${e.message}`);throw e}}async function ul(t){if(!t.length)return 0;try{for(let o of t){let n=re(o);await _e(n)}let e=t.map((o)=>({...re(o),uuid:sl()})),r=await mn.insertInto("shipping_rates").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof A)throw e;if(e instanceof Error)throw TypeError(`Failed to create shipping rates in bulk: ${e.message}`);throw e}}import{db as lt,matchedRows as pn}from"@stacksjs/database/runtime";import{formatDate as pr}from"@stacksjs/orm";async function cl(t,e){try{if(!t)throw Error("Shipping rate ID is required for update");let r=await lt.selectFrom("shipping_rates").where("id","=",t).selectAll().executeTakeFirst();if(!r)return;let o=re(e);await _e(o,r);let n=await lt.updateTable("shipping_rates").set({...o,updated_at:pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!n)return;return d(n)}catch(r){if(r instanceof A)throw r;if(r instanceof Error)throw TypeError(`Failed to update shipping rate: ${r.message}`);throw r}}async function dl(t){if(!t.length)return 0;try{let e=0;for(let{id:r,data:o}of t)if((await pn(lt.updateTable("shipping_rates").set({...re(o),updated_at:pr(new Date)}).where("id","=",r))).length>0)e++;return e}catch(e){if(e instanceof Error)throw TypeError(`Failed to update shipping rates in bulk: ${e.message}`);throw e}}async function ll(t,e){try{return(await pn(lt.updateTable("shipping_rates").set({...re(e),updated_at:pr(new Date)}).where("shipping_zone_id","=",t))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by zone: ${r.message}`);throw r}}async function ml(t,e){try{return(await pn(lt.updateTable("shipping_rates").set({...re(e),updated_at:pr(new Date)}).where("shipping_method_id","=",t))).length}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping rates by method: ${r.message}`);throw r}}var xr={};g(xr,{ARRIVAL_RADIUS_METERS:()=>yn,NEARBY_RADIUS_METERS:()=>wn,assignStop:()=>fl,bearingInDegrees:()=>Xt,broadcastToChannel:()=>oe,completeStop:()=>yl,distanceInMeters:()=>ce,emitDeliveryArrived:()=>br,emitDeliveryAssigned:()=>yr,emitDeliveryCompleted:()=>_r,emitDeliveryFailed:()=>Rr,emitDeliveryNearby:()=>gr,emitDeliveryPosition:()=>wr,emitDeliveryStarted:()=>hr,estimateSecondsRemaining:()=>er,failStop:()=>hl,hasCoordinates:()=>at,isWithin:()=>ud,orderTrackingChannel:()=>de,recordCourierPing:()=>pl,routeTrackingChannel:()=>fn,startRoute:()=>gl,startStop:()=>wl});function de(t){return`order.${t}`}function fn(t){return`delivery-route.${t}`}async function Ae(t,e){try{let r=await import("@stacksjs/events").catch(()=>null);if(!r)return;let o=r.dispatch;if(typeof o!=="function")return;o(t,e)}catch{}}async function oe(t,e,r){try{let o=await import("@stacksjs/realtime").catch(()=>null);if(!o)return;let n=o.channel;if(typeof n!=="function")return;await n(t).broadcast(e,r,"private")}catch{}}async function wr(t,e,r){await Promise.all([...t.map((o)=>oe(de(o),"delivery:position",r)),e==null?Promise.resolve():oe(fn(e),"delivery:position",r)])}async function yr(t){if(await Ae("delivery:assigned",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:assigned",{stop:t})}async function hr(t){if(await Ae("delivery:started",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:started",{stop:t})}async function gr(t,e,r){if(await Ae("delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r}),t.order_id!=null)await oe(de(t.order_id),"delivery:nearby",{stop:t,distanceMeters:e,etaSeconds:r})}async function br(t){if(await Ae("delivery:arrived",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:arrived",{stop:t})}async function _r(t){if(await Ae("delivery:completed",{stop:t}),t.order_id!=null)await oe(de(t.order_id),"delivery:completed",{stop:t})}async function Rr(t,e){await Ae("delivery:failed",{stop:t,reason:e})}var{randomUUIDv7:vf}=globalThis.Bun;import{db as ne}from"@stacksjs/database/runtime";var wn=400,yn=60,Pf=250;async function pl(t){let e=t.recordedAt??new Date().toISOString(),r=typeof t.accuracy!=="number"||t.accuracy<=Pf,o=await ne.selectFrom("couriers").where("id","=",t.courierId).select(["id","latitude","longitude"]).executeTakeFirst();if(!o)throw Error(`Unknown courier: ${t.courierId}`);let n=at(o)?{latitude:o.latitude,longitude:o.longitude}:null,a=typeof t.heading==="number"?t.heading:n?Xt(n,t):null,s=await Ff(t.courierId),i=s?await kf(s.id):null,u=null,c=null,l=!1,m=!1,f=i&&at({latitude:i.latitude??void 0,longitude:i.longitude??void 0})?{latitude:i.latitude,longitude:i.longitude}:null;if(r&&i&&f)u=Math.round(ce(t,f)),c=er(u,t.speed??0),m=u<=yn&&i.arrived_at==null,l=!m&&u<=wn&&i.status==="en_route"&&i.notified_nearby_at==null;let h=await Tf({courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e});if(r)await ne.updateTable("couriers").set({latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??0,last_ping_at:e}).where("id","=",t.courierId).execute();if(i&&(u!=null||c!=null))await ne.updateTable("delivery_stops").set({eta_at:c==null?i.eta_at:new Date(Date.now()+c*1000).toISOString()}).where("id","=",i.id).execute();if(r)await wr(i?.order_id==null?[]:[i.order_id],s?.id??null,{courierId:t.courierId,routeId:s?.id??null,latitude:t.latitude,longitude:t.longitude,heading:a,speed:t.speed??null,accuracy:t.accuracy??null,recordedAt:e,distanceToStopMeters:u,etaSeconds:c});if(l&&i)await ne.updateTable("delivery_stops").set({notified_nearby_at:e}).where("id","=",i.id).execute(),await gr(i,u,c);if(m&&i)await ne.updateTable("delivery_stops").set({status:"arrived",arrived_at:e}).where("id","=",i.id).execute(),await br({...i,status:"arrived",arrived_at:e});return{pingId:h,routeId:s?.id??null,stopId:i?.id??null,distanceToStopMeters:u,etaSeconds:c,crossedNearby:l,crossedArrival:m}}async function Ff(t){return await ne.selectFrom("delivery_routes").where("courier_id","=",t).where("status","=","active").select(["id"]).orderBy("id","desc").executeTakeFirst()??null}async function kf(t){let e=await ne.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["en_route","pending","arrived"]).select(["id","order_id","status","latitude","longitude","eta_at","arrived_at","notified_nearby_at"]).orderBy("sequence","asc").execute();return e.find((r)=>r.status==="en_route")??e.find((r)=>r.status==="arrived")??e[0]??null}async function Tf(t){let e=vf();return await ne.insertInto("courier_pings").values({uuid:e,courier_id:t.courierId,delivery_route_id:t.routeId,latitude:t.latitude,longitude:t.longitude,heading:t.heading,speed:t.speed??0,accuracy:t.accuracy,recorded_at:t.recordedAt}).executeTakeFirst(),(await ne.selectFrom("courier_pings").where("uuid","=",e).select(["id"]).executeTakeFirst())?.id??null}var{randomUUIDv7:Ef}=globalThis.Bun;import{db as M}from"@stacksjs/database/runtime";function hn(t){return t.type==="pickup"}async function fl(t){let e=Ef(),r=t.sequence??await Cf(t.deliveryRouteId);await M.insertInto("delivery_stops").values({uuid:e,delivery_route_id:t.deliveryRouteId,order_id:t.orderId??null,sequence:r,status:"pending",address:t.address,latitude:t.latitude??null,longitude:t.longitude??null,recipient_name:t.recipientName??null,recipient_phone:t.recipientPhone??null,eta_at:t.etaAt??null,type:t.type??"dropoff"}).executeTakeFirst();let o=await Mf(e);if(o)await yr(o);return o??{}}async function wl(t){await M.updateTable("delivery_stops").set({status:"en_route"}).where("id","=",t).execute();let e=await bn(t);if(!e)return null;if(e.order_id!=null&&!hn(e))await gn(e.order_id,"OUT_FOR_DELIVERY");return await hr(e),e}async function yl(t,e){let r=new Date().toISOString();await M.updateTable("delivery_stops").set({status:"completed",completed_at:r,...await Af(t)?{}:{arrived_at:r},...e?{notes:e}:{}}).where("id","=",t).execute();let o=await bn(t);if(!o)return null;if(o.order_id!=null)await gn(o.order_id,hn(o)?"OUT_FOR_DELIVERY":"DELIVERED");return await _r(o),await bl(o.delivery_route_id),o}async function hl(t,e){await M.updateTable("delivery_stops").set({status:"failed",notes:e}).where("id","=",t).execute();let r=await bn(t);if(!r)return null;if(r.order_id!=null&&!hn(r))await gn(r.order_id,"SHIPPED");return await Rr(r,e),await bl(r.delivery_route_id),r}async function gl(t){await M.updateTable("delivery_routes").set({status:"active",started_at:new Date().toISOString()}).where("id","=",t).execute()}async function bl(t){if(t==null)return;if(await M.selectFrom("delivery_stops").where("delivery_route_id","=",t).where("status","in",["pending","en_route","arrived"]).select(["id"]).executeTakeFirst())return;let r=await M.selectFrom("delivery_routes").where("id","=",t).select(["courier_id"]).executeTakeFirst();if(await M.updateTable("delivery_routes").set({status:"completed",completed_at:new Date().toISOString()}).where("id","=",t).execute(),r?.courier_id!=null)await M.updateTable("couriers").set({status:"active"}).where("id","=",r.courier_id).execute()}async function gn(t,e){let r=await M.selectFrom("orders").where("id","=",t).select(["id","status"]).executeTakeFirst();if(!r)return;let o=await Promise.resolve().then(() => (Fe(),{}));let s=Sf(r.status,e,ve);if(s.length===0){let{log:i}=await import("@stacksjs/logging").catch(()=>({log:null}));i?.warn(`[delivery] refused to move order ${t} from ${r.status} to ${e}: no legal transition`);return}for(let i of s)await M.updateTable("orders").set({status:i}).where("id","=",t).execute(),await Pe(i,{...r,status:i})}function Sf(t,e,r){if(t===e)return[];if(r(t,e))return[e];for(let o of["PROCESSING","SHIPPED"]){if(o===t||o===e)continue;if(r(t,o)&&r(o,e))return[o,e]}return[]}async function Cf(t){return(await M.selectFrom("delivery_stops").where("delivery_route_id","=",t).select(["sequence"]).execute()).reduce((r,o)=>Math.max(r,o.sequence??0),0)+1}async function Af(t){return(await M.selectFrom("delivery_stops").where("id","=",t).select(["arrived_at"]).executeTakeFirst())?.arrived_at!=null}async function bn(t){return await M.selectFrom("delivery_stops").where("id","=",t).selectAll().executeTakeFirst()??null}async function Mf(t){return await M.selectFrom("delivery_stops").where("uuid","=",t).selectAll().executeTakeFirst()??null}var Fr={};g(Fr,{bulkDestroy:()=>Dl,bulkSoftDelete:()=>vl,bulkStore:()=>kl,destroy:()=>Rl,fetchAll:()=>rl,fetchById:()=>mr,formatZoneOptions:()=>ol,getActiveShippingZones:()=>nl,getZonesByCountry:()=>al,softDelete:()=>xl,store:()=>Fl,update:()=>Tl,updateCountries:()=>Sl,updateRegionsAndPostalCodes:()=>Cl,updateStatus:()=>El});import{db as Dr,matchedRows as _l}from"@stacksjs/database/runtime";async function Rl(t){try{let e=await Dr.deleteFrom("shipping_zones").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zone: ${e.message}`);throw e}}async function xl(t){try{return(await _l(Dr.updateTable("shipping_zones").set({status:"inactive"}).where("id","=",t))).length>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zone: ${e.message}`);throw e}}async function Dl(t){if(!t.length)return 0;try{let e=await Dr.deleteFrom("shipping_zones").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete shipping zones: ${e.message}`);throw e}}async function vl(t){if(!t.length)return 0;try{return(await _l(Dr.updateTable("shipping_zones").set({status:"inactive"}).where("id","in",t))).length}catch(e){if(e instanceof Error)throw TypeError(`Failed to soft delete shipping zones: ${e.message}`);throw e}}var{randomUUIDv7:Pl}=globalThis.Bun;import{db as _n}from"@stacksjs/database/runtime";async function Fl(t){try{let e=Pl(),r={...tt(t),uuid:e};await _n.insertInto("shipping_zones").values(r).executeTakeFirst();let o=await _n.selectFrom("shipping_zones").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to resolve created shipping zone");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zone: ${e.message}`);throw e}}async function kl(t){if(!t.length)return 0;try{let e=t.map((o)=>({...tt(o),uuid:Pl()})),r=await _n.insertInto("shipping_zones").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create shipping zones in bulk: ${e.message}`);throw e}}import{db as vr}from"@stacksjs/database/runtime";import{formatDate as Pr}from"@stacksjs/orm";async function Tl(t,e){try{if(!t)throw Error("Shipping zone ID is required for update");let r=await vr.updateTable("shipping_zones").set({...tt(e),updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)return;return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone: ${r.message}`);throw r}}async function El(t,e){try{let r=await vr.updateTable("shipping_zones").set({status:e,updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone status: ${r.message}`);throw r}}async function Sl(t,e){try{let r=await vr.updateTable("shipping_zones").set({countries:e,updated_at:Pr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update shipping zone countries");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update shipping zone countries: ${r.message}`);throw r}}async function Cl(t,e,r){try{let o={updated_at:Pr(new Date)};if(e!==void 0)o.regions=e;if(r!==void 0)o.postal_codes=r;let n=await vr.updateTable("shipping_zones").set(o).where("id","=",t).returningAll().executeTakeFirst();if(!n)throw Error("Failed to update regions and postal codes");return d(n)}catch(o){if(o instanceof Error)throw TypeError(`Failed to update regions and postal codes: ${o.message}`);throw o}}var If={digital:Kt,couriers:Yt,geocoding:rr,licenses:ar,methods:cr,rates:fr,routes:Zt,tracking:xr,zones:Fr},Nf=If;var vn={};g(vn,{activeTaxRates:()=>xn,breakdownFor:()=>Dn,bulkDestroy:()=>Nl,bulkStore:()=>Ll,destroy:()=>Il,fetchAll:()=>Ol,fetchById:()=>Bl,store:()=>Wl,taxFor:()=>Al,update:()=>jl,updateDefaultStatus:()=>ql,updateRate:()=>Gl,updateStatus:()=>zl});import{db as Jf}from"@stacksjs/database/runtime";function Bf(t){let e=Number(t);return Number.isFinite(e)?e/100:0}async function xn(t={}){let e=Jf.selectFrom("tax_rates").where("status","=","active").selectAll();if(t.country)e=e.where("country","=",t.country);let r=await e.execute();if(!t.codes?.length)return r;let o=new Set(t.codes);return r.filter((n)=>o.has(String(n.code??"")))}function Dn(t,e,r={}){let o=Math.max(0,Math.round(t)),n=[],a=0,s=0;for(let i of e){let u=Bf(i.rate),c=Math.round(o*u),l=Boolean(r.exempt&&i.exemptible);if(l)s+=c;else a+=c;n.push({id:Number(i.id),code:String(i.code??""),name:String(i.name??""),rate:u,amount:l?0:c,exempted:l})}return{taxable:o,components:n,tax:a,exempted:s}}async function Al(t,e={}){return Dn(t,await xn(e),e)}import{db as Ml}from"@stacksjs/database/runtime";async function Il(t){try{let e=await Ml.deleteFrom("tax_rates").where("id","=",t).executeTakeFirst();return p(e)>0}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rate: ${e.message}`);throw e}}async function Nl(t){if(!t.length)return 0;try{let e=await Ml.deleteFrom("tax_rates").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete tax rates: ${e.message}`);throw e}}import{db as Jl}from"@stacksjs/database/runtime";async function Bl(t){let e=await Jl.selectFrom("tax_rates").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Ol(){return w(await Jl.selectFrom("tax_rates").selectAll().execute())}var{randomUUIDv7:Ul}=globalThis.Bun;import{db as $l}from"@stacksjs/database/runtime";async function Wl(t){try{return await $l.transaction(async(e)=>{let r={...t,uuid:Ul()};if(r.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();let o=await e.insertInto("tax_rates").values(r).returningAll().executeTakeFirst();if(!o)throw Error("Failed to create tax rate");return d(o)})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rate: ${e.message}`);throw e}}async function Ll(t){if(!t.length)return 0;try{return await $l.transaction(async(e)=>{let r=0;for(let o of t){let n={...o,uuid:Ul()};if(n.is_default)await e.updateTable("tax_rates").set({is_default:!1}).execute();if(await e.insertInto("tax_rates").values(n).executeTakeFirst())r++}return r})}catch(e){if(e instanceof Error)throw TypeError(`Failed to create tax rates in bulk: ${e.message}`);throw e}}import{db as kr}from"@stacksjs/database/runtime";import{formatDate as Tr}from"@stacksjs/orm";async function jl(t,e){try{if(!t)throw Error("Tax rate ID is required for update");return await kr.transaction(async(r)=>{let o=await r.selectFrom("tax_rates").select("is_default").where("id","=",t).executeTakeFirst();if(!o)return;let n=e.is_default??Boolean(o.is_default),a=Tr(new Date);if(n)await r.updateTable("tax_rates").set({is_default:!1,updated_at:a}).where("id","!=",t).execute();let s=await r.updateTable("tax_rates").set({...e,updated_at:a}).where("id","=",t).returningAll().executeTakeFirst();if(!s)return;return d(s)})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate: ${r.message}`);throw r}}async function zl(t,e){try{let r=await kr.updateTable("tax_rates").set({status:e,updated_at:Tr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update tax rate status");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate status: ${r.message}`);throw r}}async function Gl(t,e){try{let r=await kr.updateTable("tax_rates").set({rate:e,updated_at:Tr(new Date)}).where("id","=",t).returningAll().executeTakeFirst();if(!r)throw Error("Failed to update rate information");return d(r)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update rate information: ${r.message}`);throw r}}async function ql(t,e){try{return await kr.transaction(async(r)=>{if(!await r.selectFrom("tax_rates").select("id").where("id","=",t).executeTakeFirst())return!1;let n=Tr(new Date);if(e)await r.updateTable("tax_rates").set({is_default:!1,updated_at:n}).where("id","!=",t).execute();return await r.updateTable("tax_rates").set({is_default:e,updated_at:n}).where("id","=",t).execute(),!0})}catch(r){if(r instanceof Error)throw TypeError(`Failed to update tax rate default status: ${r.message}`);throw r}}var Sn={};g(Sn,{default:()=>Vf,products:()=>Sr,restaurant:()=>Ie});var Sr={};g(Sr,{bulkDestroy:()=>Zl,bulkStore:()=>lm,destroy:()=>Vl,fetchAll:()=>Hl,fetchById:()=>mt,fetchCancelledBetweenDates:()=>rm,fetchConversionRates:()=>am,fetchCountBetweenDates:()=>sm,fetchCountByAllQuantities:()=>Xl,fetchCountByDate:()=>Ql,fetchCountByDateGrouped:()=>im,fetchCountByQuantity:()=>Yl,fetchCountBySource:()=>Kl,fetchCountByStatus:()=>nm,fetchNotifiedBetweenDates:()=>em,fetchPurchasedBetweenDates:()=>tm,fetchWaiting:()=>om,store:()=>dm,update:()=>Er,updatePartySize:()=>pm,updateStatus:()=>mm});import{db as Pn}from"@stacksjs/database/runtime";async function Vl(t){try{let e=await Pn.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await Pn.deleteFrom("waitlist_products").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist product: ${e.message}`);throw e}}async function Zl(t){if(!t.length)return 0;try{let e=await Pn.deleteFrom("waitlist_products").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete waitlist products in bulk: ${e.message}`);throw e}}import{db as F}from"@stacksjs/database/runtime";import{formatDate as k}from"@stacksjs/orm";async function mt(t){let e=await F.selectFrom("waitlist_products").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function Hl(){return w(await F.selectFrom("waitlist_products").selectAll().execute())}async function Kl(t,e){let r=F.selectFrom("waitlist_products").select(["source",F.fn.count("id").as("count")]).groupBy("source");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{source:a,count:s})=>(n[a]=s,n),{})}async function Ql(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=k(e),n=k(r);return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function Yl(t){return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("quantity","=",t).executeTakeFirst())?.count??0}async function Xl(t,e){let r=F.selectFrom("waitlist_products").select(["quantity",F.fn.count("id").as("count")]).groupBy("quantity");if(t&&e){let n=k(t),a=k(e);r=r.where("created_at",">=",n).where("created_at","<=",a)}return(await r.execute()).reduce((n,{quantity:a,count:s})=>(n[a]=s,n),{})}async function em(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("notified_at",">=",r).where("notified_at","<=",o).whereNotNull("notified_at").execute();return w(n)}async function tm(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("purchased_at",">=",r).where("purchased_at","<=",o).whereNotNull("purchased_at").execute();return w(n)}async function rm(t,e){let r=k(t),o=k(e),n=await F.selectFrom("waitlist_products").selectAll().where("cancelled_at",">=",r).where("cancelled_at","<=",o).whereNotNull("cancelled_at").execute();return w(n)}async function om(){let t=await F.selectFrom("waitlist_products").selectAll().where("status","=","waiting").execute();return w(t)}async function nm(t,e,r){let o=F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("status","=",t);if(e&&r){let a=k(e),s=k(r);o=o.where("created_at",">=",a).where("created_at","<=",s)}return(await o.executeTakeFirst())?.count??0}async function am(t,e){let r=F.selectFrom("waitlist_products").select(["status",F.fn.count("id").as("count")]).groupBy("status");if(t&&e){let u=k(t),c=k(e);r=r.where("created_at",">=",u).where("created_at","<=",c)}let o=await r.execute(),n=o.reduce((u,{count:c})=>u+c,0),a=Number(o.find((u)=>u.status==="purchased")?.count??0),s=n>0?a/n*100:0,i=o.reduce((u,{status:c,count:l})=>(u[c]={count:l,percentage:n>0?l/n*100:0},u),{});return{totalConversionRate:s,statusBreakdown:i}}async function sm(t,e){let r=k(t),o=k(e);return(await F.selectFrom("waitlist_products").select(F.fn.count("id").as("count")).where("created_at",">=",r).where("created_at","<=",o).executeTakeFirst())?.count??0}async function im(t,e){let r=F.selectFrom("waitlist_products").select(["created_at"]);if(t&&e){let a=k(t),s=k(e);r=r.where("created_at",">=",a).where("created_at","<=",s)}let n=(await r.execute()).reduce((a,{created_at:s})=>{let i=(s||"").split("T")[0]||"unknown";return a[i]=(a[i]||0)+1,a},{});return Object.entries(n).map(([a,s])=>({date:a,count:s})).sort((a,s)=>a.date.localeCompare(s.date))}var{randomUUIDv7:cm}=globalThis.Bun;import{db as Fn}from"@stacksjs/database/runtime";import{formatDate as um}from"@stacksjs/orm";var Of={notified:"notified_at",purchased:"purchased_at",cancelled:"cancelled_at"};function Uf(t){return typeof t==="number"||t instanceof Date?um(t):t}function pt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));if(r.quantity===void 0&&r.party_size!==void 0)r.quantity=r.party_size;delete r.party_size;for(let n of["notified_at","purchased_at","cancelled_at"])if(r[n]!==void 0)r[n]=Uf(r[n]);let o=Of[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=um(new Date);return r}async function dm(t){try{let e=cm(),r={...pt(t),uuid:e,status:t.status||"waiting"};await Fn.insertInto("waitlist_products").values(r).executeTakeFirst();let o=await Fn.selectFrom("waitlist_products").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create waitlist product");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist product: ${e.message}`);throw e}}async function lm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...pt(o),status:o.status||"waiting",uuid:cm()})),r=await Fn.insertInto("waitlist_products").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create waitlist products in bulk: ${e.message}`);throw e}}import{db as $f}from"@stacksjs/database/runtime";import{formatDate as Wf}from"@stacksjs/orm";async function Er(t,e){try{if(!t)throw Error("Waitlist product ID is required for update");let r=await mt(t);if(!r)return;await $f.updateTable("waitlist_products").set({...pt(e,r),updated_at:Wf(new Date)}).where("id","=",t).execute();let o=await mt(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update waitlist product: ${r.message}`);throw r}}async function mm(t,e){return await Er(t,{status:e})}async function pm(t,e){return await Er(t,{quantity:e})}var Ie={};g(Ie,{bulkDestroy:()=>wm,bulkStore:()=>Jm,destroy:()=>fm,fetchAll:()=>ym,fetchAverageWaitTimes:()=>Pm,fetchBetweenDates:()=>Rm,fetchById:()=>ft,fetchConversionRates:()=>vm,fetchCountByAllPartySizes:()=>_m,fetchCountByDate:()=>gm,fetchCountByPartySize:()=>bm,fetchCountByTablePreference:()=>hm,fetchCurrentWaitTimes:()=>Cm,fetchNoShowStats:()=>Sm,fetchSeatedBetweenDates:()=>xm,fetchSeatedStats:()=>Am,fetchSeatingRate:()=>Em,fetchTablesTurnedToday:()=>Tm,fetchTimeSeriesStats:()=>Mm,fetchWaiting:()=>Dm,fetchWaitingWithPartySizes:()=>km,fetchWaitingWithQuotedTimes:()=>Fm,store:()=>Nm,update:()=>Me,updatePartySize:()=>Om,updateQueuePosition:()=>$m,updateStatus:()=>Bm,updateWaitTimes:()=>Um});import{db as kn}from"@stacksjs/database/runtime";async function fm(t){try{let e=await kn.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();if(!e)return;return await kn.deleteFrom("waitlist_restaurants").where("id","=",t).execute(),d(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entry: ${e.message}`);throw e}}async function wm(t){if(!t.length)return 0;try{let e=await kn.deleteFrom("waitlist_restaurants").where("id","in",t).executeTakeFirst();return p(e)}catch(e){if(e instanceof Error)throw TypeError(`Failed to delete restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as R}from"@stacksjs/database/runtime";import{formatDate as B}from"@stacksjs/orm";async function ft(t){let e=await R.selectFrom("waitlist_restaurants").where("id","=",t).selectAll().executeTakeFirst();return d(e,!0)}async function ym(){return w(await R.selectFrom("waitlist_restaurants").selectAll().execute())}async function hm(){return(await R.selectFrom("waitlist_restaurants").select(["table_preference",R.fn.count("id").as("count")]).groupBy("table_preference").execute()).reduce((e,{table_preference:r,count:o})=>(e[r]=o,e),{})}async function gm(t=new Date){let e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r);return(await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("created_at",">=",o).where("created_at","<=",n).executeTakeFirst())?.count??0}async function bm(t){return(await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("party_size","=",t).executeTakeFirst())?.count??0}async function _m(){return(await R.selectFrom("waitlist_restaurants").select(["party_size",R.fn.count("id").as("count")]).groupBy("party_size").execute()).reduce((e,{party_size:r,count:o})=>(e[r]=o,e),{})}async function Rm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").selectAll().where("created_at",">=",r).where("created_at","<=",o).execute();return w(n)}async function xm(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").selectAll().where("check_in_time",">=",r).where("check_in_time","<=",o).where("status","=","seated").execute();return w(n)}async function Dm(){let t=await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute();return w(t)}async function vm(){let t=await R.selectFrom("waitlist_restaurants").select(["status",R.fn.count("id").as("count")]).groupBy("status").execute(),e=t.reduce((a,{count:s})=>a+s,0),r=t.find((a)=>a.status==="seated")?.count??0,o=e>0?Number(r)/e*100:0,n=t.reduce((a,{status:s,count:i})=>(a[s]={count:i,percentage:e>0?i/e*100:0},a),{});return{totalConversionRate:o,statusBreakdown:n}}async function Pm(){let t=await R.selectFrom("waitlist_restaurants").select([R.fn.avg("quoted_wait_time").as("avg_quoted_wait_time"),R.fn.avg("actual_wait_time").as("avg_actual_wait_time")]).executeTakeFirst();return{averageQuotedWaitTime:t?.avg_quoted_wait_time??0,averageActualWaitTime:t?.avg_actual_wait_time??0}}async function Fm(){let t=w(await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((o,n)=>o+(n.quoted_wait_time??0),0),r=t.length>0?e/t.length:0;return{entries:t,totalQuotedWaitTime:e,averageQuotedWaitTime:r}}async function km(){let t=w(await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","waiting").execute()),e=t.reduce((n,a)=>n+a.party_size,0),r=t.length>0?e/t.length:0,o=t.reduce((n,a)=>(n[a.party_size]=(n[a.party_size]||0)+1,n),{});return{entries:t,totalPartySize:e,averagePartySize:r,partySizeBreakdown:o}}async function Tm(){let t=new Date,e=new Date(t);e.setHours(0,0,0,0);let r=new Date(t);r.setHours(23,59,59,999);let o=B(e),n=B(r),a=await R.selectFrom("waitlist_restaurants").selectAll().where("status","=","seated").where("check_in_time",">=",o).where("check_in_time","<=",n).execute(),s=a.length,i=a.reduce((m,f)=>m+f.party_size,0),u=s>0?i/s:0,c=a.reduce((m,f)=>(m[f.table_preference]=(m[f.table_preference]||0)+1,m),{}),l=a.reduce((m,f)=>(m[f.party_size]=(m[f.party_size]||0)+1,m),{});return{totalTablesTurned:s,averagePartySize:u,totalCustomersSeated:i,breakdownByTablePreference:c,breakdownByPartySize:l}}async function Em(t,e){let r=B(t),o=B(e),n=await R.selectFrom("waitlist_restaurants").select(["status",R.fn.count("id").as("count")]).where("check_in_time",">=",r).where("check_in_time","<=",o).groupBy("status").execute(),a=n.reduce((c,{count:l})=>c+l,0),s=n.find((c)=>c.status==="seated")?.count??0,i=a>0?Number(s)/a*100:0,u=n.reduce((c,{status:l,count:m})=>(c[l]={count:m,percentage:a>0?m/a*100:0},c),{});return{totalEntries:a,seatedEntries:s,seatingRate:i,statusBreakdown:u}}async function Sm(t,e){let r=B(t),o=B(e),n=R.selectFrom("waitlist_restaurants").selectAll().where("status","=","no_show").where("check_in_time",">=",r).where("check_in_time","<=",o),a=await R.selectFrom("waitlist_restaurants").select(R.fn.count("id").as("count")).where("check_in_time",">=",r).where("check_in_time","<=",o).executeTakeFirst(),s=await n.execute(),i=s.length,u=a?.count&&a.count>0?i/a.count*100:0,c=s.reduce((_,D)=>_+(D.quoted_wait_time??0),0),l=i>0?c/i:0,m=s.reduce((_,D)=>_+D.party_size,0),f=i>0?m/i:0,h=s.reduce((_,D)=>(_[D.table_preference]=(_[D.table_preference]||0)+1,_),{}),b=s.reduce((_,D)=>(_[D.party_size]=(_[D.party_size]||0)+1,_),{});return{totalNoShows:i,noShowRate:u,averageQuotedWaitTime:l,averagePartySize:f,breakdownByTablePreference:h,breakdownByPartySize:b}}async function Cm(){let t=await R.selectFrom("waitlist_restaurants").select(["quoted_wait_time","actual_wait_time"]).where("status","=","waiting").execute(),e=t.reduce((n,a)=>n+(a.quoted_wait_time||0),0),r=t.reduce((n,a)=>n+(a.actual_wait_time||0),0),o=t.length;return{averageQuoted:o>0?e/o:0,averageActual:o>0?r/o:0}}async function Am(){let t=Date.now()-86400000,e=await R.selectFrom("waitlist_restaurants").select(["seated_at"]).where("status","=","seated").where("seated_at",">=",t).execute(),r=Array.from({length:24},(o,n)=>({hour:n,count:e.filter((a)=>a.seated_at===n).length}));return{total:e.length,byHour:r}}async function Mm(){return(await R.selectFrom("waitlist_restaurants").select(["created_at","status"]).execute()).reduce((e,r)=>{let o=r.created_at;if(!e[o])e[o]={total:0,waiting:0,seated:0,cancelled:0,no_show:0};return e[o].total++,e[o][r.status]++,e},{})}var{randomUUIDv7:Im}=globalThis.Bun;import{db as En}from"@stacksjs/database/runtime";import{formatDate as Tn}from"@stacksjs/orm";var Lf={seated:"seated_at",no_show:"no_show_at",cancelled:"cancelled_at"};function jf(t){if(typeof t==="number")return Tn(t<=2147483647?t*1000:t);if(t instanceof Date)return Tn(t);return t}function wt(t,e={}){let r=Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0));for(let n of["check_in_time","seated_at","no_show_at","cancelled_at"])if(r[n]!==void 0)r[n]=jf(r[n]);let o=Lf[r.status];if(o&&r[o]===void 0&&!e[o])r[o]=Tn(new Date);return r}async function Nm(t){try{let e=Im(),r={...wt(t),status:t.status||"waiting",uuid:e};await En.insertInto("waitlist_restaurants").values(r).executeTakeFirst();let o=await En.selectFrom("waitlist_restaurants").where("uuid","=",e).selectAll().executeTakeFirst();if(!o)throw Error("Failed to create restaurant waitlist entry");return d(o)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entry: ${e.message}`);throw e}}async function Jm(t){if(!t.length)return 0;try{let e=t.map((o)=>({...wt(o),status:o.status||"waiting",uuid:Im()})),r=await En.insertInto("waitlist_restaurants").values(e).executeTakeFirst();return p(r)}catch(e){if(e instanceof Error)throw TypeError(`Failed to create restaurant waitlist entries in bulk: ${e.message}`);throw e}}import{db as zf}from"@stacksjs/database/runtime";import{formatDate as Gf}from"@stacksjs/orm";async function Me(t,e){try{if(!t)throw Error("Restaurant waitlist entry ID is required for update");let r=await ft(t);if(!r)return;await zf.updateTable("waitlist_restaurants").set({...wt(e,r),updated_at:Gf(new Date)}).where("id","=",t).execute();let o=await ft(t);if(!o)return;return d(o)}catch(r){if(r instanceof Error)throw TypeError(`Failed to update restaurant waitlist entry: ${r.message}`);throw r}}async function Bm(t,e){return await Me(t,{status:e})}async function Om(t,e){return await Me(t,{party_size:e})}async function Um(t,e,r){return await Me(t,{quoted_wait_time:e,...r===void 0?{}:{actual_wait_time:r}})}async function $m(t,e){return await Me(t,{queue_position:e})}var qf={products:Sr,restaurant:Ie},Vf=qf;var Zf={auctions:no,carts:ao,coupons:io,customers:co,devices:wo,errors:go,giftCards:Ro,orders:No,payments:Jo,products:jo,receipts:Ho,restaurant:Ie,shippings:Rn,tax:vn,waitlists:Sn},mk=Zf;export{no as auctions,ao as carts,Zf as commerce,io as coupons,co as customers,mk as default,wo as devices,go as errors,Ro as giftCards,No as orders,Jo as payments,jo as products,Ho as receipts,Ie as restaurant,Rn as shippings,vn as tax,Sn as waitlists};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/commerce",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.36",
5
+ "version": "0.75.38",
6
6
  "description": "Stacks commerce utilities.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,17 +58,17 @@
58
58
  "prepublishOnly": "bun run build"
59
59
  },
60
60
  "dependencies": {
61
- "@stacksjs/cache": "0.75.36",
62
- "@stacksjs/config": "0.75.36",
63
- "@stacksjs/database": "0.75.36",
64
- "@stacksjs/env": "0.75.36",
65
- "@stacksjs/error-handling": "0.75.36",
66
- "@stacksjs/events": "0.75.36",
67
- "@stacksjs/logging": "0.75.36",
68
- "@stacksjs/orm": "0.75.36",
69
- "@stacksjs/payments": "0.75.36",
70
- "@stacksjs/realtime": "0.75.36",
71
- "@stacksjs/strings": "0.75.36",
61
+ "@stacksjs/cache": "0.75.38",
62
+ "@stacksjs/config": "0.75.38",
63
+ "@stacksjs/database": "0.75.38",
64
+ "@stacksjs/env": "0.75.38",
65
+ "@stacksjs/error-handling": "0.75.38",
66
+ "@stacksjs/events": "0.75.38",
67
+ "@stacksjs/logging": "0.75.38",
68
+ "@stacksjs/orm": "0.75.38",
69
+ "@stacksjs/payments": "0.75.38",
70
+ "@stacksjs/realtime": "0.75.38",
71
+ "@stacksjs/strings": "0.75.38",
72
72
  "ts-spreadsheets": "^0.2.0"
73
73
  },
74
74
  "devDependencies": {