@nextblock-cms/ecom 0.0.10 → 0.8.0

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 (147) hide show
  1. package/actions.d.ts +2 -0
  2. package/currency-rest-client-CwoqdgAP.js +23 -0
  3. package/currency-rest-client-uolJxUkL.cjs +1 -0
  4. package/index.cjs.js +1 -0
  5. package/index.d.ts +35 -0
  6. package/index.es.js +3226 -0
  7. package/invoice-ui-BJZfedDd.cjs +332 -0
  8. package/invoice-ui-GJ1ADAjn.js +5759 -0
  9. package/lib/CurrencyProvider.d.ts +18 -0
  10. package/lib/cart-store.d.ts +47 -0
  11. package/lib/components/AccountNavigationMenu.d.ts +14 -0
  12. package/lib/components/AddToCartButton.d.ts +8 -0
  13. package/lib/components/Cart.d.ts +1 -0
  14. package/lib/components/CartDrawer.d.ts +1 -0
  15. package/lib/components/CartIcon.d.ts +1 -0
  16. package/lib/components/Checkout.d.ts +6 -0
  17. package/lib/components/CouponForm.d.ts +8 -0
  18. package/lib/components/CurrencySwitcher.d.ts +1 -0
  19. package/lib/components/CustomerProfileForm.d.ts +21 -0
  20. package/lib/components/FeaturedProduct.d.ts +8 -0
  21. package/lib/components/InvoiceDocument.d.ts +32 -0
  22. package/lib/components/InvoiceViewerShell.d.ts +26 -0
  23. package/lib/components/ProductCard.d.ts +7 -0
  24. package/lib/components/ProductDetailsLayout.d.ts +7 -0
  25. package/lib/components/ProductGallery.d.ts +9 -0
  26. package/lib/components/ProductGrid.d.ts +8 -0
  27. package/lib/components/ShippingEstimator.d.ts +5 -0
  28. package/lib/components/SimpleTiptapRenderer.d.ts +7 -0
  29. package/lib/components/SubscriptionSelector.d.ts +7 -0
  30. package/lib/components/media/MediaImage.d.ts +12 -0
  31. package/lib/components/media/MediaPickerDialog.d.ts +16 -0
  32. package/lib/components/media/MediaUploadForm.d.ts +10 -0
  33. package/lib/components/media/UploadFolderContext.d.ts +10 -0
  34. package/lib/countries.d.ts +5 -0
  35. package/lib/coupon-server.d.ts +22 -0
  36. package/lib/coupon-server.test.d.ts +1 -0
  37. package/lib/coupons.d.ts +41 -0
  38. package/lib/currency-constants.d.ts +1 -0
  39. package/lib/currency-rest-client.d.ts +1 -0
  40. package/lib/currency-sale-schedule.test.d.ts +1 -0
  41. package/lib/currency-store.d.ts +20 -0
  42. package/lib/currency-sync.d.ts +19 -0
  43. package/lib/currency.d.ts +116 -0
  44. package/lib/customer-addresses.d.ts +19 -0
  45. package/lib/customer-orders.d.ts +23 -0
  46. package/lib/customer.d.ts +51 -0
  47. package/lib/export-helpers.d.ts +48 -0
  48. package/lib/factory.d.ts +2 -0
  49. package/lib/freemius-coupons.d.ts +58 -0
  50. package/lib/freemius-order-sync.d.ts +133 -0
  51. package/lib/freemius-order-sync.test.d.ts +1 -0
  52. package/lib/inventory-settings.d.ts +16 -0
  53. package/lib/invoice-server.d.ts +18 -0
  54. package/lib/invoice-ui.d.ts +29 -0
  55. package/lib/invoice.d.ts +75 -0
  56. package/lib/order-inventory.d.ts +7 -0
  57. package/lib/order-tax-details.d.ts +57 -0
  58. package/lib/pages/cms/coupons/CouponEditorForm.d.ts +23 -0
  59. package/lib/pages/cms/coupons/CouponsPage.d.ts +8 -0
  60. package/lib/pages/cms/coupons/CreateCouponDialog.d.ts +6 -0
  61. package/lib/pages/cms/coupons/EditCouponPage.d.ts +5 -0
  62. package/lib/pages/cms/coupons/ProductScopePicker.d.ts +16 -0
  63. package/lib/pages/cms/coupons/actions.d.ts +5 -0
  64. package/lib/pages/cms/coupons/index.d.ts +2 -0
  65. package/lib/pages/cms/coupons/product-options.d.ts +2 -0
  66. package/lib/pages/cms/orders/ExportReportsDialog.d.ts +2 -0
  67. package/lib/pages/cms/orders/MarkPaidButton.d.ts +3 -0
  68. package/lib/pages/cms/orders/OrderDetailPage.d.ts +5 -0
  69. package/lib/pages/cms/orders/OrderPrintButton.d.ts +3 -0
  70. package/lib/pages/cms/orders/OrderStatusForm.d.ts +4 -0
  71. package/lib/pages/cms/orders/OrdersPage.d.ts +6 -0
  72. package/lib/pages/cms/orders/actions.d.ts +7 -0
  73. package/lib/pages/cms/orders/export-actions.d.ts +2 -0
  74. package/lib/pages/cms/orders/index.d.ts +6 -0
  75. package/lib/pages/cms/orders/server-actions.d.ts +11 -0
  76. package/lib/pages/cms/orders/types.d.ts +60 -0
  77. package/lib/pages/cms/payments/PaymentsClient.d.ts +19 -0
  78. package/lib/pages/cms/payments/PaymentsPage.d.ts +1 -0
  79. package/lib/pages/cms/payments/actions.d.ts +4 -0
  80. package/lib/pages/cms/payments/index.d.ts +2 -0
  81. package/lib/pages/cms/payments/queries.d.ts +12 -0
  82. package/lib/pages/cms/products/ProductsPage.d.ts +7 -0
  83. package/lib/pages/cms/products/[id]/edit/EditProductPage.d.ts +12 -0
  84. package/lib/pages/cms/products/actions.d.ts +18201 -0
  85. package/lib/pages/cms/products/attributes/AttributeManagementPage.d.ts +1 -0
  86. package/lib/pages/cms/products/attributes/components/AttributeManager.d.ts +50 -0
  87. package/lib/pages/cms/products/categories/CategoryManagementPage.d.ts +1 -0
  88. package/lib/pages/cms/products/categories/components/CategoryManager.d.ts +47 -0
  89. package/lib/pages/cms/products/components/CopyProductFromLanguage.d.ts +9 -0
  90. package/lib/pages/cms/products/components/CurrencyPriceFields.d.ts +18 -0
  91. package/lib/pages/cms/products/components/DeleteProductButton.d.ts +9 -0
  92. package/lib/pages/cms/products/components/FreemiusPricingDashboard.d.ts +24 -0
  93. package/lib/pages/cms/products/components/ProductCategorySelector.d.ts +14 -0
  94. package/lib/pages/cms/products/components/ProductForm.d.ts +62 -0
  95. package/lib/pages/cms/products/components/ProductMediaManager.d.ts +17 -0
  96. package/lib/pages/cms/products/components/ProductsBulkTable.d.ts +32 -0
  97. package/lib/pages/cms/products/components/SaleScheduleFields.d.ts +16 -0
  98. package/lib/pages/cms/products/components/SyncFreemiusButton.d.ts +3 -0
  99. package/lib/pages/cms/products/components/SyncFreemiusPricingButton.d.ts +5 -0
  100. package/lib/pages/cms/products/components/SyncProductForm.d.ts +1 -0
  101. package/lib/pages/cms/products/components/VariationsEditor.d.ts +26 -0
  102. package/lib/pages/cms/products/index.d.ts +7 -0
  103. package/lib/pages/cms/products/inventory/InventoryPage.d.ts +1 -0
  104. package/lib/pages/cms/products/inventory/InventoryTableClient.d.ts +6 -0
  105. package/lib/pages/cms/products/inventory/actions.d.ts +38 -0
  106. package/lib/pages/cms/products/new/NewProductPage.d.ts +9 -0
  107. package/lib/pages/cms/products/product-price-sync.d.ts +43 -0
  108. package/lib/pages/cms/products/server-actions.d.ts +125 -0
  109. package/lib/pages/cms/shipping/ShippingPage.d.ts +6 -0
  110. package/lib/pages/cms/shipping/components/RateForm.d.ts +26 -0
  111. package/lib/pages/cms/shipping/components/ZoneForm.d.ts +13 -0
  112. package/lib/pages/cms/shipping/index.d.ts +2 -0
  113. package/lib/pages/cms/shipping/server-actions.d.ts +80 -0
  114. package/lib/pages/cms/taxes/TaxesPage.d.ts +5 -0
  115. package/lib/pages/cms/taxes/actions.d.ts +3 -0
  116. package/lib/pages/cms/taxes/components/TaxRateForm.d.ts +8 -0
  117. package/lib/pages/cms/taxes/index.d.ts +2 -0
  118. package/lib/product-actions.d.ts +18457 -0
  119. package/lib/product-context.d.ts +7 -0
  120. package/lib/product-schema.d.ts +73 -0
  121. package/lib/providers/freemius.d.ts +49 -0
  122. package/lib/providers/stripe.d.ts +13 -0
  123. package/lib/server-actions/coupon-actions.d.ts +17 -0
  124. package/lib/server-actions/customer-actions.d.ts +18 -0
  125. package/lib/server-actions/product-actions.d.ts +69 -0
  126. package/lib/server-actions/shipping-actions.d.ts +10 -0
  127. package/lib/server-actions/tax-actions.d.ts +7 -0
  128. package/lib/shared-inventory.d.ts +38 -0
  129. package/lib/shipping/resolver.d.ts +16 -0
  130. package/lib/shipping-rate-currency.d.ts +39 -0
  131. package/lib/states.d.ts +9 -0
  132. package/lib/stripe/checkout.d.ts +6 -0
  133. package/lib/stripe/client.d.ts +2 -0
  134. package/lib/stripe/order-sync.d.ts +18 -0
  135. package/lib/stripe/webhooks.d.ts +4 -0
  136. package/lib/tax-calculation.d.ts +23 -0
  137. package/lib/trials.d.ts +15 -0
  138. package/lib/types.d.ts +245 -0
  139. package/lib/use-cart.d.ts +11 -0
  140. package/lib/variation-utils.d.ts +72 -0
  141. package/lib/zod-config.d.ts +2 -0
  142. package/package.json +47 -2
  143. package/server.cjs.js +110 -0
  144. package/server.d.ts +31 -0
  145. package/server.es.js +6039 -0
  146. package/index.ts +0 -12
  147. package/tsconfig.lib.json +0 -10
package/server.cjs.js ADDED
@@ -0,0 +1,110 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const tr=require("stripe"),Ce=require("@supabase/supabase-js"),K=require("@nextblock-cms/db/server"),o=require("./invoice-ui-BJZfedDd.cjs");require("D:/Websites/nextblock-sandbox/node_modules/server-only/index.js");const rr=require("D:/Websites/nextblock-sandbox/node_modules/postgres/src/index.js"),$=require("@nextblock-cms/utils"),Qe=require("crypto"),sr=require("D:/Websites/nextblock-sandbox/node_modules/@freemius/sdk/dist/index.mjs"),e=require("react/jsx-runtime"),J=require("next/link"),y=require("react"),n=require("@nextblock-cms/ui"),A=require("D:/Websites/nextblock-sandbox/node_modules/lucide-react/dist/esm/lucide-react.js"),X=require("D:/Websites/nextblock-sandbox/node_modules/sonner/dist/index.mjs"),ar=require("D:/Websites/nextblock-sandbox/node_modules/papaparse/papaparse.min.js"),ae=require("next/navigation"),nr=require("next/image"),Q=require("next/cache"),ir=require("react-dom"),Ee=require("@nextblock-cms/ui/button"),ve=require("@nextblock-cms/ui/dialog"),or=require("@nextblock-cms/ui/input"),le=new tr(process.env.STRIPE_SECRET_KEY||"sk_test_dummy",{typescript:!0}),cr=async(t,r,s,a)=>{const i=process.env.NEXT_PUBLIC_SUPABASE_URL,c=process.env.SUPABASE_SERVICE_ROLE_KEY;if(!i||!c)return console.error("Missing Supabase credentials for checkout (Service Key required)."),{error:"Internal Server Error",url:null};const l=Ce.createClient(i,c),u=process.env.NEXT_PUBLIC_URL||"http://localhost:4200";if(!t.length)return{error:"Cart is empty",url:null};const{data:d}=await l.from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("code",{ascending:!0}),m=d??[],h=o.getDefaultCurrency(m),x=m.find(L=>L.code===(a||"").toUpperCase())??h;if(!await K.verifyPackageOnline("ecommerce"))return{error:"E-Commerce Package not active. Please purchase a license to accept payments.",url:null};const f=t.map(L=>L.product_id),{data:N,error:k}=await l.from("products").select("id, title, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at").in("id",f);if(k||!N)return console.error("Error fetching products for validation:",k),{error:"Failed to validate product prices",url:null};const R=new Map(N.map(L=>[L.id,L])),b=[];let S=0;const E=[];for(const L of t){const z=R.get(L.product_id);if(!z){console.warn(`Product ${L.product_id} not found in DB, skipping.`);continue}const ee=o.resolveEffectivePriceForCurrency({prices:z.prices||{},salePrices:z.sale_prices||{},fallbackPrice:z.price,fallbackSalePrice:z.sale_price,saleStartAt:z.sale_start_at,saleEndAt:z.sale_end_at,scheduledPrice:z.scheduled_price,scheduledPrices:z.scheduled_prices||{},scheduledPriceAt:z.scheduled_price_at,currencyCode:x.code,currencies:m}),T=ee.sale_price??ee.price;T<=0&&console.warn(`[Checkout Session Warning] Product ${z.title} has zero or negative price!`),b.push({price_data:{currency:x.code.toLowerCase(),product_data:{name:z.title,images:[],metadata:{productId:z.id}},unit_amount:T},quantity:L.quantity}),S+=T*L.quantity,E.push({product_id:z.id,quantity:L.quantity,price_at_purchase:T})}if(b.length===0)return{error:"No valid items in cart",url:null};const{data:F,error:_}=await l.from("orders").insert({total:S,user_id:r,currency:x.code,exchange_rate_at_purchase:x.exchange_rate}).select("id").single();if(_||!F)return console.error("Failed to create pending order:",_),console.error("Order Data attempted:",{status:"pending",total:S}),{error:`Failed to initiate order: ${_?.message||"Unknown error"}`,url:null};const g=E.map(L=>({order_id:F.id,product_id:L.product_id,quantity:L.quantity,price_at_purchase:L.price_at_purchase})),{error:j}=await l.from("order_items").insert(g);j&&console.error("Failed to insert order items:",j);let D=[],B=s;if(!B&&r){const{data:L}=await l.from("user_addresses").select("country_code, state_code, postal_code").eq("user_id",r).eq("address_type","shipping").limit(1).single();L&&(B={country:L.country_code,state:L.state_code,postal_code:L.postal_code})}B&&(D=(await o.resolveShippingOptions(S,B,null,x.code)).map(z=>({shipping_rate_data:{type:"fixed_amount",fixed_amount:{amount:z.amount,currency:z.currency.toLowerCase()},display_name:z.name}})));try{const L=await le.checkout.sessions.create({mode:"payment",success_url:`${u}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,cancel_url:`${u}/`,line_items:b,billing_address_collection:"required",shipping_address_collection:{allowed_countries:["US","CA","GB","AU","NZ","IE","FR","DE","IT","ES","MX","BR","AR","CL","CO","PE","ZA","NG","KE","IN","JP","KR","CN","SG","MY","PH","TH","VN","ID","AE","SA","EG","MA","DZ","TN","PT","NL","BE","CH","AT","SE","NO","DK","FI","PL","CZ","HU","RO","BG","GR","TR","IL","CY","MT"]},shipping_options:D.length>0?D:void 0,metadata:{orderId:F.id}});return await l.from("orders").update({stripe_session_id:L.id}).eq("id",F.id),{url:L.url}}catch(L){return console.error("Stripe session creation failed:",L),{error:L.message,url:null}}};function lr(){return process.env.POSTGRES_URL||process.env.DATABASE_URL||null}async function dr(t){const r=lr();if(!r)throw new Error("Missing POSTGRES_URL or DATABASE_URL for inventory fallback");const s=rr(r,{ssl:"require",onnotice:()=>{}});try{await s.begin(async a=>{const i=a,l=(await i`
2
+ SELECT inventory_deducted_at
3
+ FROM public.orders
4
+ WHERE id = ${t}
5
+ FOR UPDATE
6
+ `)[0];if(!l||l.inventory_deducted_at)return;const u=await i`
7
+ SELECT value
8
+ FROM public.site_settings
9
+ WHERE key = ${o.ECOMMERCE_INVENTORY_SETTINGS_KEY}
10
+ LIMIT 1
11
+ `;if(!o.normalizeEcommerceInventorySettings(u[0]?.value).trackQuantities){await i`
12
+ UPDATE public.orders
13
+ SET inventory_deducted_at = now()
14
+ WHERE id = ${t}
15
+ `;return}const m=await i`
16
+ SELECT
17
+ product_id,
18
+ variant_id,
19
+ SUM(quantity)::integer AS quantity
20
+ FROM public.order_items
21
+ WHERE order_id = ${t}
22
+ GROUP BY product_id, variant_id
23
+ `;for(const h of m){if(h.variant_id){const v=(await i`
24
+ SELECT
25
+ sku,
26
+ stock_quantity
27
+ FROM public.product_variants
28
+ WHERE id = ${h.variant_id}
29
+ LIMIT 1
30
+ `)[0];if(!v?.sku)continue;await i`
31
+ INSERT INTO public.inventory_items (sku, quantity)
32
+ VALUES (${v.sku}, ${Math.max(0,v.stock_quantity??0)})
33
+ ON CONFLICT (sku) DO NOTHING
34
+ `,await i`
35
+ UPDATE public.inventory_items
36
+ SET
37
+ quantity = GREATEST(COALESCE(quantity, 0) - ${h.quantity}, 0),
38
+ updated_at = now()
39
+ WHERE sku = ${v.sku}
40
+ `;continue}if(h.product_id){const v=(await i`
41
+ SELECT
42
+ sku,
43
+ stock
44
+ FROM public.products
45
+ WHERE id = ${h.product_id}
46
+ LIMIT 1
47
+ `)[0];if(!v?.sku)continue;await i`
48
+ INSERT INTO public.inventory_items (sku, quantity)
49
+ VALUES (${v.sku}, ${Math.max(0,v.stock??0)})
50
+ ON CONFLICT (sku) DO NOTHING
51
+ `,await i`
52
+ UPDATE public.inventory_items
53
+ SET
54
+ quantity = GREATEST(COALESCE(quantity, 0) - ${h.quantity}, 0),
55
+ updated_at = now()
56
+ WHERE sku = ${v.sku}
57
+ `}}await i`
58
+ UPDATE public.orders
59
+ SET inventory_deducted_at = now()
60
+ WHERE id = ${t}
61
+ `})}finally{await s.end()}}async function Pe(t,r){const{error:s}=await t.rpc("apply_order_inventory_deduction",{p_order_id:r});if(!s)return{method:"rpc"};console.error(`[Inventory] RPC deduction failed for order ${r}:`,s);try{return await dr(r),{method:"sql-fallback"}}catch(a){const i=a instanceof Error?a.message:String(a);throw new Error(`Failed to reconcile inventory for order ${r}. RPC error: ${s.message}. Fallback error: ${i}`)}}function ur(t){return t?t.startsWith("http")||t.startsWith("/")?t:process.env.NEXT_PUBLIC_R2_BASE_URL?`${process.env.NEXT_PUBLIC_R2_BASE_URL}/${t}`:process.env.NEXT_PUBLIC_SUPABASE_URL?`${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/media/${t}`:t:null}function Ae(t){return t??K.getServiceRoleSupabaseClient()}function mr(t){if(!t)return null;const r=t.media?.object_key??t.media?.file_path??null;return{id:t.id,name:t.name??null,url:ur(r),width:t.media?.width??null,height:t.media?.height??null}}async function ht(t){const r=Ae(t),[s,a]=await Promise.all([r.from("site_settings").select("value").eq("key",o.INVOICE_SETTINGS_KEY).maybeSingle(),r.from("logos").select(`
62
+ id,
63
+ name,
64
+ media:media_id (
65
+ object_key,
66
+ file_path,
67
+ width,
68
+ height
69
+ )
70
+ `).order("created_at",{ascending:!1}).limit(1).maybeSingle()]);return{settings:o.normalizeInvoiceSettings(s.data?.value??o.DEFAULT_INVOICE_SETTINGS),logo:mr(a.data)}}async function Ie(t){const r=Ae(t.client),{data:s,error:a}=await r.rpc("assign_order_invoice_metadata",{p_order_id:t.orderId,p_paid_at:t.paidAt??null}).single();if(a)throw new Error(a.message);return{invoiceNumber:s?.invoice_number??null,paidAt:s?.paid_at??null}}async function xt(t,r){const s=Ae(r),{data:a,error:i}=await s.from("orders").select(`
71
+ id,
72
+ invoice_number,
73
+ paid_at,
74
+ created_at,
75
+ currency,
76
+ status,
77
+ provider,
78
+ subtotal,
79
+ shipping_total,
80
+ discount_total,
81
+ coupon_code,
82
+ tax_total,
83
+ total,
84
+ customer_details,
85
+ tax_details,
86
+ order_items (
87
+ id,
88
+ product_id,
89
+ variant_id,
90
+ quantity,
91
+ price_at_purchase
92
+ )
93
+ `).eq("id",t).single();if(i||!a)throw new Error(i?.message||"Order not found");const c=(a.order_items||[]).map(f=>f.product_id).filter(Boolean),l=(a.order_items||[]).map(f=>f.variant_id).filter(Boolean),[u,d]=await Promise.all([c.length?s.from("products").select("id, title, sku").in("id",c):Promise.resolve({data:[],error:null}),l.length?s.from("product_variants").select("id, sku").in("id",l):Promise.resolve({data:[],error:null})]),m=new Map((u.data||[]).map(f=>[f.id,f])),h=new Map((d.data||[]).map(f=>[f.id,f])),x=(a.order_items||[]).map(f=>{const N=f.product_id?m.get(f.product_id):null,k=f.variant_id?h.get(f.variant_id):null,R=N?.title||"Product",b=k?.sku?`SKU: ${k.sku}`:N?.sku?`SKU: ${N.sku}`:null;return{id:f.id,product_id:f.product_id??null,variant_id:f.variant_id??null,title:R,description:b,quantity:f.quantity,unit_amount:f.price_at_purchase,total_amount:f.price_at_purchase*f.quantity,sku:k?.sku??N?.sku??null}});return{id:a.id,invoice_number:a.invoice_number??null,paid_at:a.paid_at??null,created_at:a.created_at??null,currency:a.currency||"usd",status:a.status,provider:a.provider??null,subtotal:typeof a.subtotal=="number"?a.subtotal:x.reduce((f,N)=>f+N.total_amount,0),shipping_total:typeof a.shipping_total=="number"?a.shipping_total:0,discount_total:typeof a.discount_total=="number"?a.discount_total:0,coupon_code:a.coupon_code??null,tax_total:typeof a.tax_total=="number"?a.tax_total:0,total:a.total,customer_details:o.normalizeOrderCustomerDetails(a.customer_details??{}),tax_details:o.normalizeOrderTaxDetails(a.tax_details),items:x}}async function Me(t,r){const s=Ae(r),[a,i]=await Promise.all([xt(t,s),ht(s)]);return{order:a,settings:i.settings,logo:i.logo}}const pr=["total_details.breakdown"],hr=["data.taxes.rate"];function xr(){const t=process.env.NEXT_PUBLIC_SUPABASE_URL,r=process.env.SUPABASE_SERVICE_ROLE_KEY;if(!t||!r)throw new Error("Missing Supabase Service Role environment variables");return Ce.createClient(t,r,{auth:{autoRefreshToken:!1,persistSession:!1}})}function Xe(t,r){return t?o.normalizeCustomerAddress({recipient_name:r,line1:t.line1??null,line2:t.line2??null,city:t.city??null,state:t.state??null,postal_code:t.postal_code??null,country_code:t.country??null}):null}function gr(t){const r=t??{};return o.normalizeOrderCustomerDetails({email:typeof r.email=="string"?r.email:null,name:typeof r.name=="string"?r.name:null,phone:typeof r.phone=="string"?r.phone:null,billing:r.billing??null,shipping:r.shipping??null})}async function gt(t){const r=xr();let s=t;try{s=await le.checkout.sessions.retrieve(t.id,{expand:[...pr]})}catch(g){console.error("[Stripe Sync] Failed to rehydrate session tax details:",g)}const a=s.metadata?.orderId;let i=r.from("orders").select("id, user_id, status, total, currency, subtotal, shipping_total, tax_total, tax_details, customer_details").eq("stripe_session_id",t.id).maybeSingle();a&&(i=r.from("orders").select("id, user_id, status, total, currency, subtotal, shipping_total, tax_total, tax_details, customer_details").eq("id",a).maybeSingle());const{data:c,error:l}=await i;if(l||!c)throw new Error(l?.message||"Order lookup failed");const u=gr(c.customer_details),d=o.normalizeOrderTaxDetails(c.tax_details),m=Xe(s.customer_details?.address,s.customer_details?.name??u.name),h=s,x=Xe(h.shipping_details?.address,h.shipping_details?.name??u.name),v=o.normalizeOrderCustomerDetails({email:s.customer_details?.email??u.email,name:s.customer_details?.name??u.name,phone:s.customer_details?.phone??u.phone,billing:u.billing??m,shipping:u.shipping??x}),f=c.status==="paid",N=await le.checkout.sessions.listLineItems(s.id,{limit:100,expand:[...hr]}),k=o.buildOrderTaxDetailsFromStripeSession({session:s,lineItems:N.data,subtotal:typeof c.subtotal=="number"?c.subtotal:d?.subtotal??0,shippingTotal:typeof c.shipping_total=="number"?c.shipping_total:d?.shipping_total??0,fallbackMode:d?.mode??"automatic",currency:(s.currency??c.currency??d?.currency??"USD").toUpperCase()}),R=k.tax_total>0||k.lines.length>0?k:d??k,b=R?.tax_total??(typeof c.tax_total=="number"?c.tax_total:0),S=(s.currency??c.currency??R?.currency??"USD").toUpperCase(),E={status:"paid",stripe_session_id:s.id,payment_intent_id:typeof s.payment_intent=="string"?s.payment_intent:null,provider:"stripe",customer_details:v,total:typeof s.amount_total=="number"?s.amount_total:c.total,currency:S,tax_total:b,tax_details:R},{error:F}=await r.from("orders").update(E).eq("id",c.id);if(F)throw new Error(F.message);if(c.user_id)try{await o.upsertDefaultUserAddresses({userId:c.user_id,billingAddress:v.billing,shippingAddress:v.shipping,client:r})}catch(g){console.error("[Stripe Sync] Failed to refresh saved customer addresses:",g)}const _=await Ie({orderId:c.id,client:r});return await Pe(r,c.id),{orderId:c.id,alreadyPaid:f,customerDetails:v,order:{id:c.id,invoice_number:_.invoiceNumber,paid_at:_.paidAt,total:E.total,currency:S,subtotal:typeof c.subtotal=="number"?c.subtotal:R?.subtotal??0,shipping_total:typeof c.shipping_total=="number"?c.shipping_total:R?.shipping_total??0,tax_total:b,tax_details:R}}}const fr=async(t,r)=>{const s=process.env.STRIPE_WEBHOOK_SECRET;if(!s)return console.error("Missing STRIPE_WEBHOOK_SECRET"),{received:!1,error:"Server configuration error"};let a;try{a=le.webhooks.constructEvent(r,t,s)}catch(i){return console.error(`Webhook signature verification failed: ${i.message}`),{received:!1,error:`Webhook Error: ${i.message}`}}switch(a.type){case"checkout.session.completed":{const i=a.data.object;try{await gt(i)}catch(c){return console.error("[Stripe Webhook Error] Failed to sync completed session:",c),{received:!1,error:c.message||"Failed to sync Stripe session"}}break}default:console.log(`Unhandled event type ${a.type}`)}return{received:!0}};function Oe(t){return t??K.createClient()}async function ft(t){const{data:{user:r},error:s}=await t.auth.getUser();if(s||!r)throw new Error("Unauthorized");return r}async function yr(t){const r=Oe(t),s=await ft(r),{data:a,error:i}=await r.from("orders").select("id, invoice_number, paid_at, created_at, currency, status, provider, subtotal, shipping_total, tax_total, total").eq("user_id",s.id).order("created_at",{ascending:!1});if(i)throw new Error(i.message);return a??[]}async function yt(t,r){const s=Oe(r),a=await ft(s),{data:i,error:c}=await s.from("orders").select("id, invoice_number, paid_at, created_at, currency, status, provider, subtotal, shipping_total, tax_total, total").eq("id",t).eq("user_id",a.id).maybeSingle();if(c)throw new Error(c.message);return i??null}async function _r(t,r){const s=Oe(r),a=await yt(t,s);if(!a)return null;const i=a.invoice_number?await Me(t,s):null;return{order:a,invoice:i}}const br="https://api.frankfurter.dev",vr="id, code, symbol, exchange_rate, is_default, is_active, auto_update_exchange_rate, auto_sync_product_prices, exchange_rate_source, exchange_rate_updated_at, updated_at, rounding_mode, rounding_increment, rounding_charm_amount";function Le(t){if(!t.id)throw new Error(`Currency ${$.normalizeCurrencyCode(t.code)} is missing its ID.`);return t.id}function jr(){return process.env.FX_API_BASE_URL?.trim().replace(/\/+$/,"")||br}function Cr(t){try{const r=new URL(t),s=r.pathname.replace(/\/+$/,"");return`${r.host}${s&&s!=="/"?s:""}`}catch{return t}}function wr(t){if(!t||typeof t!="object")return!1;const r=t;return typeof r.base=="string"&&typeof r.date=="string"&&typeof r.quote=="string"&&typeof r.rate=="number"&&Number.isFinite(r.rate)&&r.rate>0}function Nr(t){return Array.isArray(t)&&t.every(wr)}async function _t(){const t=K.getServiceRoleSupabaseClient(),{data:r,error:s}=await t.from("currencies").select(vr).order("code",{ascending:!0});if(s)throw new Error(s.message);return{supabase:t,currencies:r||[]}}async function Sr(t){const r=$.normalizeCurrencyCode(t.newDefaultCurrencyCode),s=Number(t.previousBaseRate);if(!Number.isFinite(s)||s<=0)throw new Error("Cannot rebase exchange rates without a valid previous base rate.");const{supabase:a,currencies:i}=await _t();if(!i.find(h=>$.normalizeCurrencyCode(h.code)===r))throw new Error(`Currency ${r} was not found for rebasing.`);const l=new Date().toISOString(),u=[],d=i.map(h=>{const x=Le(h),v=$.normalizeCurrencyCode(h.code),f=v===r?1:Number((h.exchange_rate/s).toFixed(10));return u.push(v),{...h,id:x,exchange_rate:f,auto_update_exchange_rate:v===r?!1:h.auto_update_exchange_rate,exchange_rate_source:v===r?"store-default":h.exchange_rate_source||"rebased-default",exchange_rate_updated_at:l,updated_at:l}}),{error:m}=await a.from("currencies").upsert(d,{onConflict:"id"});if(m)throw new Error(m.message);return{rebasedAt:l,newDefaultCurrencyCode:r,updatedCurrencies:u}}async function kr(){const{supabase:t,currencies:r}=await _t();if(!r.length)throw new Error("No currencies are configured yet.");const s=r.map(S=>o.normalizeCurrencyRecord(S)),a=o.getDefaultCurrency(s),i=$.normalizeCurrencyCode(a.code),c=r.find(S=>$.normalizeCurrencyCode(S.code)===i);if(!c)throw new Error(`Default currency ${i} could not be found for syncing.`);const l=r.filter(S=>$.normalizeCurrencyCode(S.code)!==i&&S.auto_update_exchange_rate!==!1),u=jr(),d=Cr(u),m=new Date().toISOString(),{error:h}=await t.from("currencies").upsert({...c,id:Le(c),exchange_rate:1,auto_update_exchange_rate:!1,exchange_rate_source:"store-default",exchange_rate_updated_at:m,updated_at:m},{onConflict:"id"});if(h)throw new Error(h.message);if(!l.length)return{baseCurrencyCode:i,fetchedAt:m,provider:d,providerUrl:u,skippedCurrencies:[],updatedCurrencies:[]};const x=new URL(`${u}/v2/rates`);x.searchParams.set("base",i),x.searchParams.set("quotes",[...new Set(l.map(S=>$.normalizeCurrencyCode(S.code)))].join(","));const v=await fetch(x.toString(),{cache:"no-store",headers:{Accept:"application/json"}});if(!v.ok){const S=await v.text();throw new Error(`FX provider request failed (${v.status}): ${S||"Unexpected response body."}`)}const f=await v.json();if(!Nr(f))throw new Error("FX provider returned an unexpected response payload.");const N=new Map;for(const S of f)N.set($.normalizeCurrencyCode(S.quote),S.rate);const k=[],R=[],b=[];for(const S of l){const E=$.normalizeCurrencyCode(S.code),F=N.get(E);if(!F||!Number.isFinite(F)||F<=0){R.push(E);continue}b.push({...S,id:Le(S),exchange_rate:Number(F.toFixed(10)),exchange_rate_source:d,exchange_rate_updated_at:m,updated_at:m}),k.push(E)}if(b.length){const{error:S}=await t.from("currencies").upsert(b,{onConflict:"id"});if(S)throw new Error(S.message)}return{baseCurrencyCode:i,fetchedAt:m,provider:d,providerUrl:u,skippedCurrencies:R,updatedCurrencies:k}}async function Er(t){const r=$.normalizeCurrencyCode(t),s=K.getServiceRoleSupabaseClient(),{error:a}=await s.rpc("clear_currency_price_overrides",{target_currency:r});if(a)throw new Error(a.message);return{currencyCode:r}}const Tr=o.countries.map(t=>t.code),Pr=new Set(["bg","cs","da","de","el","en","en-GB","es","es-419","et","fi","fil","fr","hr","hu","id","it","ja","ko","lt","lv","ms","mt","nb","nl","pl","pt","pt-BR","ro","ru","sk","sl","sv","th","tr","vi","zh","zh-HK","zh-TW"]);function Ye(t){if(t)return{line1:t.line1||void 0,line2:t.line2||void 0,city:t.city||void 0,state:t.state||void 0,postal_code:t.postal_code||void 0,country:t.country_code||void 0}}function Ar(t){const r=t?.trim().replace("_","-");if(!r)return;const s=[r,r.toLowerCase(),r.split("-")[0].toLowerCase()];for(const a of s)if(Pr.has(a))return a}function Ir(t,r){return o.resolveTranslatedText(t.name,t.name_translations||null,r)}async function Rr(t){if(!t.email)return null;const r=Ye(t.shippingAddress),s=t.shippingAddress?.recipient_name||t.billingAddress?.recipient_name||void 0,a={email:t.email,name:t.billingAddress?.recipient_name||t.shippingAddress?.recipient_name||void 0,phone:t.phone||void 0,address:Ye(t.billingAddress),metadata:t.userId?{userId:t.userId}:void 0,...r&&s?{shipping:{name:s,phone:t.phone||void 0,address:r}}:{}};try{const c=(await le.customers.list({email:t.email,limit:1})).data[0];return c?(await le.customers.update(c.id,a),c.id):(await le.customers.create(a)).id}catch(i){return console.error("Failed to upsert Stripe customer for checkout prefill:",i),null}}class bt{getProviderName(){return"Stripe"}async createCheckoutSession({items:r,customerEmail:s,customerPhone:a,userId:i,billingAddress:c,shippingAddress:l,shippingMethodId:u,currencyCode:d,locale:m,couponCode:h,couponContextItems:x}){const v=process.env.NEXT_PUBLIC_SUPABASE_URL,f=process.env.SUPABASE_SERVICE_ROLE_KEY;if(!v||!f)return console.error("Missing Supabase credentials for checkout (Service Key required)."),{error:"Internal Server Error",url:null};const N=Ce.createClient(v,f),k=process.env.NEXT_PUBLIC_URL||"http://localhost:4200",R=r.some(w=>!o.isDigitalItem(w));if(!r.length)return{error:"Cart is empty",url:null};const{data:b,error:S}=await N.from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("code",{ascending:!0}),E=b??[];if(S||E.length===0)return console.error("Error fetching currencies for checkout:",S),{error:"Failed to resolve store currencies",url:null};const F=o.getDefaultCurrency(E),_=E.find(w=>w.code===(d||"").toUpperCase())??F,g=_.code.toLowerCase(),j=await o.getEcommerceInventorySettings(N),D=r.map(w=>w.product_id),B=r.map(w=>w.variant_id).filter(w=>!!w),{data:L,error:z}=await N.from("products").select("id, title, sku, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, stock, is_taxable").in("id",D);if(z||!L)return console.error("Error fetching products for validation:",z),{error:"Failed to validate product prices",url:null};const{data:ee,error:T}=B.length?await N.from("product_variants").select("id, product_id, sku, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, stock_quantity").in("id",B):{data:[],error:null};if(T)return console.error("Error fetching variants for validation:",T),{error:"Failed to validate product variants",url:null};const H=new Map(L.map(w=>[w.id,w])),G=new Map((ee||[]).map(w=>[w.id,w])),p=new Set,P=new Map;for(const w of r){const V=H.get(w.product_id);if(!V)continue;const te=(w.variant_id?G.get(w.variant_id):null)?.sku||V.sku;te&&(p.add(te),P.set(te,(P.get(te)??0)+w.quantity))}const{data:M,error:W}=p.size?await N.from("inventory_items").select("sku, quantity").in("sku",[...p]):{data:[],error:null};if(W)return console.error("Error fetching SKU inventory for validation:",W),{error:"Failed to validate SKU inventory",url:null};const se=new Map((M||[]).map(w=>[w.sku,Math.max(0,w.quantity??0)])),C=[],O=[],I=[];let q=0,re=0,Z=null;if(h){const w=await o.getCouponQuote({client:N,code:h,items:x&&x.length>0?x:r,currencyCode:_.code});if(!w.success)return{error:w.error,errorKey:w.errorKey,errorStatus:400,url:null};Z=w.quote}const ie=o.getQuoteLineDiscountMap(Z),Ne=w=>{const V=w.unitAmount*w.quantity,ue=Math.max(0,V-w.lineDiscount);if(ue<=0)return;const te=Math.floor(ue/w.quantity),_e=ue-te*w.quantity,xe=(be,ge)=>{ge<=0||be<=0||C.push({price_data:{currency:w.currency,product_data:{name:w.name,tax_code:o.getStripeTaxCodeForProduct(w.isTaxable),metadata:{productId:w.productId,variantId:w.variantId||""}},tax_behavior:"exclusive",unit_amount:be},quantity:ge})};xe(te,w.quantity-_e),xe(te+1,_e)};for(const w of r){const V=H.get(w.product_id);if(!V)return console.warn(`Product ${w.product_id} not found in DB.`),{url:null,...o.createInventoryUnavailableError(w.title)};const ue=o.resolveEffectivePriceForCurrency({prices:o.normalizePriceMap(V.prices),salePrices:V.sale_prices||{},fallbackPrice:V.price,fallbackSalePrice:V.sale_price,saleStartAt:V.sale_start_at,saleEndAt:V.sale_end_at,scheduledPrice:V.scheduled_price,scheduledPrices:o.normalizePriceMap(V.scheduled_prices),scheduledPriceAt:V.scheduled_price_at,currencyCode:_.code,currencies:E});let te=ue.sale_price??ue.price,_e=V.title,xe=null;if(w.variant_id){const Y=G.get(w.variant_id);if(!Y||Y.product_id!==w.product_id)return{url:null,...o.createInventoryUnavailableError(w.title)};const ke=P.get(Y.sku)??w.quantity,Ge=se.has(Y.sku)?se.get(Y.sku)??0:Math.max(0,Y.stock_quantity??0);if(j.trackQuantities&&ke>Ge)return{url:null,...o.createInventoryInsufficientError(w.title,Ge)};const We=o.resolveEffectivePriceForCurrency({prices:o.normalizePriceMap(Y.prices),salePrices:Y.sale_prices||{},fallbackPrice:Y.price,fallbackSalePrice:Y.sale_price,saleStartAt:Y.sale_start_at,saleEndAt:Y.sale_end_at,scheduledPrice:Y.scheduled_price,scheduledPrices:o.normalizePriceMap(Y.scheduled_prices),scheduledPriceAt:Y.scheduled_price_at,currencyCode:_.code,currencies:E});te=We.sale_price??We.price,xe=Y.id,_e=w.variant_label?`${V.title} - ${w.variant_label}`:`${V.title} - ${Y.sku}`}else{const Y=P.get(V.sku)??w.quantity,ke=se.has(V.sku)?se.get(V.sku)??0:Math.max(0,V.stock??0);if(j.trackQuantities&&Y>ke)return{url:null,...o.createInventoryInsufficientError(w.title,ke)}}const be=V.is_taxable??!0;if(te<0)return{error:"A product variation produced an invalid price.",url:null};const ge=Math.min(te*w.quantity,ie.get(o.getCartLineCouponKey(w))??0);Ne({name:_e,currency:g,productId:V.id,variantId:xe,isTaxable:be,unitAmount:te,quantity:w.quantity,lineDiscount:ge}),q+=te*w.quantity,re+=ge,I.push({product_id:V.id,quantity:w.quantity,price_at_purchase:te,variant_id:xe}),O.push({product_id:V.id,quantity:w.quantity,unit_amount:te,discount_amount:ge,is_taxable:be})}if(C.length===0&&re>=q)return{error:"This coupon would reduce the Stripe order to zero. Use a smaller discount for Stripe checkout.",errorKey:"ecommerce.coupon_zero_total_not_supported",errorStatus:400,url:null};if(C.length===0)return{error:"No valid items in cart",url:null};let de=0,Fe=null;if(u){const{data:w,error:V}=await N.from("shipping_zone_methods").select("id, name, name_translations, cost_amount, cost_currency").eq("id",u).single();if(V)return console.error("Failed to load shipping method:",V),{error:"Failed to load shipping method",url:null};de=o.convertMinorUnitAmount({amount:w.cost_amount??0,fromCurrencyCode:w.cost_currency||F.code,toCurrencyCode:_.code,currencies:E}),Fe=Ir(w,m)}const ze=R?l??c:c;let ne;try{ne=await o.calculateCheckoutTaxes(N,{items:O,destination:{country_code:ze?.country_code,state:ze?.state}})}catch(w){return console.error("Failed to calculate checkout taxes:",w),{error:"Failed to calculate taxes",url:null}}de>0&&Fe&&C.push({price_data:{currency:g,product_data:{name:Fe,tax_code:ne.enabled&&ne.mode==="automatic"?o.STRIPE_TAX_CODE_SHIPPING:o.STRIPE_TAX_CODE_NONTAXABLE},tax_behavior:"exclusive",unit_amount:de},quantity:1});const pe=ne.enabled&&ne.mode==="manual"&&!ne.isPendingExternalCalculation?ne.amount:0;pe>0&&C.push({price_data:{currency:g,product_data:{name:"Tax",tax_code:o.STRIPE_TAX_CODE_NONTAXABLE},tax_behavior:"exclusive",unit_amount:pe},quantity:1});const Zt=o.normalizeOrderCustomerDetails({email:s,phone:a,name:c?.recipient_name,billing:c,shipping:l}),qe=_.code,Jt=o.buildOrderTaxDetailsFromCalculation({calculation:ne,subtotal:q,shippingTotal:de,total:Math.max(0,q-re)+de+pe,currency:qe}),er=Math.max(0,q-re)+de+pe,{data:Ke,error:Ve}=await N.from("orders").insert({status:"pending",total:er,currency:qe,exchange_rate_at_purchase:_.exchange_rate,subtotal:q,shipping_total:de,tax_total:pe,tax_details:Jt,coupon_id:Z?.couponId??null,coupon_code:Z?.code??null,discount_total:re,discount_details:Z?{code:Z.code,discount_type:Z.discountType,discount_amount:Z.discountAmount,provider:"stripe",provider_discounts:Z.providerDiscounts,line_discounts:Z.lineDiscounts}:null,provider:"stripe",user_id:i,customer_details:Zt}).select("id").single();if(Ve||!Ke)return console.error("Failed to create pending order:",Ve),{error:"Failed to initiate order",url:null};const he=Ke.id,{error:He}=await N.from("order_items").insert(I.map(w=>({order_id:he,product_id:w.product_id,variant_id:w.variant_id??null,quantity:w.quantity,price_at_purchase:w.price_at_purchase})));if(He)return console.error("Failed to insert order items:",He),await N.from("orders").update({status:"failed"}).eq("id",he),{error:"Failed to record order items",url:null};if(i)try{await o.upsertDefaultUserAddresses({userId:i,billingAddress:c,shippingAddress:l,client:N}),await o.fillMissingUserProfileCheckoutDetails({userId:i,fullName:c?.recipient_name??l?.recipient_name??null,phone:a,client:N})}catch(w){console.error("Failed to sync checkout profile defaults before checkout:",w)}Z&&await o.recordCouponRedemption({client:N,quote:Z,orderId:he,provider:"stripe",discountTotal:re,userId:i,customerEmail:s,metadata:{currency:_.code,subtotal:q,shipping_total:de,tax_total:pe}});const Se=await Rr({email:s,phone:a,userId:i,billingAddress:c,shippingAddress:l});try{const w=await le.checkout.sessions.create({mode:"payment",success_url:`${k}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,cancel_url:`${k}/checkout`,locale:Ar(m),line_items:C,automatic_tax:ne.enabled&&ne.mode==="automatic"?{enabled:!0}:void 0,billing_address_collection:"auto",customer:Se||void 0,customer_email:Se?void 0:s||void 0,customer_creation:Se?void 0:"if_required",customer_update:Se?{name:"auto",address:"auto",shipping:"auto"}:void 0,shipping_address_collection:R?{allowed_countries:Tr}:void 0,metadata:{orderId:he,taxMode:ne.mode,currencyCode:_.code,couponCode:Z?.code||""}}),{error:V}=await N.from("orders").update({stripe_session_id:w.id}).eq("id",he);return V&&console.error("Failed to save Stripe session ID on order:",V),{url:w.url}}catch(w){return console.error("Stripe session creation failed:",w),await N.from("orders").update({status:"failed"}).eq("id",he),{error:w.message,url:null}}}}function Fr(t){return t==="freemius"?new o.FreemiusProvider:new bt}function U(t){return t==null||t===""?null:String(t)}function ce(t){const r=U(t);if(!r)return null;const s=r.includes("T")?r:r.replace(" ","T")+"Z",a=new Date(s);return Number.isNaN(a.getTime())?r:a.toISOString()}function Ur(t){if(t==null||t==="")return null;const r=Number(t);return Number.isFinite(r)?r:null}function De(...t){return t.some(r=>{const s=Ur(r);return s!==null&&s>0})}function Te(t){return t==="pending"||t==="trial"}function Ze(t){return["license.cancelled","license.deleted","license.expired","subscription.cancelled","subscription.renewal.failed.last","trial.cancelled","trial.expired"].includes(t||"")}function Lr(t,r){return t==="license.extended"&&(r?.is_renewal===!0||r?.is_renewal===1||r?.is_renewal==="1"||r?.is_renewal==="true")}function Mr(t){const r=t.objects?.payment??t.data?.payment??t.data;return t.type==="payment.created"&&De(r?.gross,r?.total_gross,r?.amount,r?.initial_amount)}function vt(t){const r=t?.purchase??null,s=t?.trial??null;return{freemius_product_id:U(r?.plugin_id)??U(r?.product_id)??U(r?.productId)??U(s?.plugin_id)??U(s?.product_id)??U(s?.productId),freemius_plan_id:U(r?.plan_id)??U(r?.planId),freemius_license_id:U(r?.license_id)??U(r?.licenseId)??U(s?.license_id)??U(s?.licenseId),freemius_subscription_id:U(r?.subscription_id)??U(r?.subscriptionId)??U(s?.subscription_id)??U(s?.subscriptionId),freemius_trial_id:U(s?.id),freemius_user_id:U(r?.user_id)??U(r?.userId)??U(s?.user_id)??U(s?.userId)??U(t?.user?.id),freemius_trial_ends_at:ce(s?.trial_ends_at)??ce(s?.trialEndsAt)??ce(r?.trial_ends)??ce(r?.trialEnds)}}function jt(t,r="pending"){const s=t?.purchase??null,a=t?.trial??null;return r==="paid"?"paid":a&&(a.canceled_at||a.canceledAt)&&Te(r)?"cancelled":a?"trial":s?(s.canceled_at||s.canceledAt)&&Te(r)?"cancelled":De(s.initial_amount,s.initialAmount,s.gross,s.total_gross,s.totalGross)?"paid":s.trial_ends||s.trialEnds||s.subscription_id||s.subscriptionId?"trial":r:r}function Be(t){const{event:r,currentStatus:s,purchaseData:a}=t;return s==="paid"&&Ze(r.type)?"paid":Ze(r.type)?Te(s)?"cancelled":s:Mr(r)||Lr(r.type,r.data)||a&&De(a.initialAmount,a.initial_amount,a.gross,a.totalGross,a.total_gross)?"paid":a?.canceled===!0&&Te(s)?"cancelled":(a?.subscriptionId||a?.subscription_id||r.type==="subscription.created"||r.type==="license.created")&&s==="pending"?"trial":s}function Or(t,r){const s={freemius_last_event_type:r,freemius_last_synced_at:new Date().toISOString()};for(const[a,i]of Object.entries(t))i!=null&&i!==""&&(s[a]=i);return s}function Ct(){const t=process.env.NEXT_PUBLIC_SUPABASE_URL,r=process.env.SUPABASE_SERVICE_ROLE_KEY;if(!t||!r)throw new Error("Missing Supabase Service Role environment variables");return Ce.createClient(t,r,{auth:{autoRefreshToken:!1,persistSession:!1}})}async function Dr(t,r){const{data:s,error:a}=await t.from("orders").select("id, status, provider, freemius_product_id, freemius_plan_id, freemius_license_id, freemius_subscription_id, freemius_trial_id, freemius_user_id, freemius_trial_ends_at").eq("id",r).single();if(a||!s)throw new Error(a?.message||"Order not found");return s}async function Br(t,r){const{data:s,error:a}=await t.from("orders").select("id, status, provider, freemius_product_id, freemius_plan_id, freemius_license_id, freemius_subscription_id, freemius_trial_id, freemius_user_id, freemius_trial_ends_at").eq("freemius_license_id",r).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(a)throw new Error(a.message);return s??null}async function wt(t){const r=Or(t.metadata,t.eventType),s=t.order.status,a=s==="paid"&&t.nextStatus!=="paid"?"paid":t.nextStatus;a!==s&&(r.status=a);const{error:i}=await t.client.from("orders").update(r).eq("id",t.order.id);if(i)throw new Error(i.message);return a==="paid"&&s!=="paid"&&(await Ie({orderId:t.order.id,client:t.client}),await Pe(t.client,t.order.id)),a}async function $r(t){const r=t.client??Ct(),s=await Dr(r,t.orderId);if(s.provider!=="freemius")return{success:!1,error:"Only Freemius orders can be synced from Freemius checkout"};const a=vt(t.checkoutResponse);let i=null;if(a.freemius_license_id)try{i=await kt(a.freemius_product_id??s.freemius_product_id,a.freemius_license_id)}catch(h){console.error("[Freemius Checkout Sync] Failed to retrieve purchase data:",h)}const c={type:"checkout.purchaseCompleted",data:{license_id:a.freemius_license_id},objects:{}},l={...a,...St(c,i)},u=jt(t.checkoutResponse,s.status),d=i?Be({event:c,currentStatus:s.status,purchaseData:i}):u==="paid"?s.status:u,m=await wt({client:r,order:s,nextStatus:d,metadata:l,eventType:"checkout.purchaseCompleted"});return{success:!0,orderId:s.id,status:m,metadata:l}}function Nt(t){return U(t.data?.license_id)??U(t.objects?.license?.id)??U(t.objects?.subscription?.license_id)??U(t.objects?.payment?.license_id)??U(t.data?.payment?.license_id)}function St(t,r){const s=t.objects?.license,a=t.objects?.subscription,i=t.objects?.trial,c=t.objects?.payment??t.data?.payment;return{freemius_product_id:U(r?.productId)??U(r?.product_id)??U(s?.plugin_id)??U(a?.plugin_id)??U(c?.plugin_id),freemius_plan_id:U(r?.planId)??U(r?.plan_id)??U(s?.plan_id),freemius_license_id:U(r?.licenseId)??U(r?.license_id)??Nt(t),freemius_subscription_id:U(r?.subscriptionId)??U(r?.subscription_id)??U(a?.id)??U(t.data?.subscription_id),freemius_trial_id:U(i?.id)??U(t.data?.trial_id),freemius_user_id:U(r?.userId)??U(r?.user_id)??U(t.objects?.user?.id),freemius_trial_ends_at:ce(i?.trial_ends_at)??ce(i?.trial_ends)??ce(s?.trial_ends)??ce(r?.trialEndsAt)??ce(r?.trial_ends_at)}}async function kt(t,r){if(!t)return null;const s=o.resolveFreemiusCheckoutCredentials(t);return!s.apiKey||!s.secretKey||!s.publicKey?null:new sr.Freemius({productId:Number(t),apiKey:s.apiKey,secretKey:s.secretKey,publicKey:s.publicKey}).purchase.retrievePurchaseData(r)}async function zr(t){const r=t.client??Ct(),s=Nt(t.event);if(!s)return{success:!0,ignored:!0,reason:"missing_license_id",type:t.event.type};const a=await Br(r,s);if(!a)return{success:!0,ignored:!0,reason:"unknown_license_id",licenseId:s,type:t.event.type};let i=null;try{i=await kt(a.freemius_product_id??t.event.objects?.license?.plugin_id,s)}catch(d){console.error("[Freemius Sync] Failed to retrieve purchase data:",d)}const c=St(t.event,i),l=Be({event:t.event,currentStatus:a.status,purchaseData:i}),u=await wt({client:r,order:a,nextStatus:l,metadata:c,eventType:t.event.type??null});return{success:!0,orderId:a.id,status:u,type:t.event.type}}function Et(){const t=[o.readFreemiusEnvValue("FREEMIUS_SECRET_KEY"),o.readFreemiusEnvValue("FREEMIUS_ECOMMERCE_SANDBOX_SECRET_KEY"),...Object.values(o.parseFreemiusCheckoutCredentialsMap()??{}).map(r=>r.secretKey??null)];return Array.from(new Set(t.filter(r=>!!r)))}function qr(t,r){return r?Et().some(s=>{const a=Qe.createHmac("sha256",s).update(t).digest("hex");try{return Qe.timingSafeEqual(Buffer.from(a,"hex"),Buffer.from(r,"hex"))}catch{return!1}}):!1}async function Re(){const t=[];process.env.STRIPE_SECRET_KEY||t.push("STRIPE_SECRET_KEY"),process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY||t.push("NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY"),process.env.STRIPE_WEBHOOK_SECRET||t.push("STRIPE_WEBHOOK_SECRET");const r=[];return process.env.FREEMIUS_PUBLIC_KEY||r.push("FREEMIUS_PUBLIC_KEY"),process.env.FREEMIUS_SECRET_KEY||r.push("FREEMIUS_SECRET_KEY"),{stripe:{hasKeys:t.length===0,missing:t},freemius:{hasKeys:r.length===0,missing:r}}}async function ye(){const t=K.createClient(),{data:r,error:s}=await t.from("site_settings").select("value").eq("key","enabled_payment_providers").maybeSingle();return s||!r?{...o.DEFAULT_ENABLED_PAYMENT_PROVIDERS}:o.normalizeEnabledPaymentProviders(r.value)}async function Kr(){const t=await ye();return t.stripe?"stripe":t.freemius?"freemius":"stripe"}const Ue=20;async function Tt(t=1,r,s){const a=await K.createClient(),i=(t-1)*Ue,c=i+Ue-1;let l=a.from("orders").select(`
94
+ *,
95
+ order_items (*)
96
+ `,{count:"exact"}).order("created_at",{ascending:!1}).range(i,c);r&&r!=="all"&&(l=l.eq("status",r)),s&&(l=l.or(`id.eq.${s},user_id.eq.${s}`));const{data:u,error:d,count:m}=await l;if(d)throw console.error("Error fetching orders:",d),new Error("Failed to fetch orders");const h=u||[],x=Array.from(new Set(h.map(N=>N.user_id).filter(Boolean))),v=new Map;if(x.length>0){const{data:N,error:k}=await a.from("profiles").select("*").in("id",x);!k&&N&&N.forEach(R=>v.set(R.id,R))}return{data:h.map(N=>({...N,customer:N.user_id?v.get(N.user_id):null})),total:m||0,totalPages:m?Math.ceil(m/Ue):0}}async function Pt(t){const r=await K.createClient(),{data:s,error:a}=await r.from("orders").select(`
97
+ *,
98
+ order_items (*)
99
+ `).eq("id",t).single();if(a||!s)return console.error(`Error fetching order ${t}:`,a),null;const i=s;let c=null;if(i.user_id){const{data:m}=await r.from("profiles").select("*").eq("id",i.user_id).single();c=m}const l=i.order_items.map(m=>m.product_id).filter(Boolean),u=new Map;if(l.length>0){const{data:m}=await r.from("products").select("id, title, slug, product_media(media(file_path))").in("id",l);m&&m.forEach(h=>{let x=null;h.product_media&&h.product_media.length>0&&h.product_media[0].media&&(x=h.product_media[0].media.file_path),u.set(h.id,{title:h.title,slug:h.slug,image_url:x})})}const d=i.order_items.map(m=>({...m,product:m.product_id?u.get(m.product_id):null}));return{...i,order_items:d,customer:c}}async function At(t,r){const s=K.createClient();let a=s.from("orders").select("*, order_items(*)");if(t&&(a=a.gte("created_at",t)),r){const d=new Date(r);d.setHours(23,59,59,999),a=a.lte("created_at",d.toISOString())}const{data:i,error:c}=await a.order("created_at",{ascending:!0});if(c)throw console.error("Error fetching report data:",c),new Error(`Failed to fetch report data: ${c.message}`);if(!i||i.length===0)return[];const l=Array.from(new Set(i.map(d=>d.user_id).filter(Boolean))),u=new Map;if(l.length>0){const{data:d}=await s.from("profiles").select("id, full_name, email").in("id",l);d&&d.forEach(m=>u.set(m.id,m))}return i.map(d=>({...d,customer:d.user_id?u.get(d.user_id):null}))}function Vr(t,r){const s=ar.unparse(t),a=new Blob([s],{type:"text/csv;charset=utf-8;"}),i=document.createElement("a");if(i.download!==void 0){const c=URL.createObjectURL(a);i.setAttribute("href",c),i.setAttribute("download",r),i.style.visibility="hidden",document.body.appendChild(i),i.click(),document.body.removeChild(i)}}function Hr(t){return t.map(r=>({"Order ID":r.id,Date:new Date(r.created_at).toLocaleDateString(),"Customer Name":r.customer?.full_name||r.customer_details?.name||"Guest","Customer Email":r.customer?.email||r.customer_details?.email||"N/A",Subtotal:(r.subtotal/100).toFixed(2),"Tax Amount":(r.tax_total/100).toFixed(2),"Shipping Amount":(r.shipping_total/100).toFixed(2),Total:(r.total/100).toFixed(2),Currency:r.currency.toUpperCase(),"Payment Status":r.status,"Fulfillment Status":r.status==="shipped"?"Shipped":r.status==="paid"?"Paid":r.status==="trial"?"Trial":"Pending","Payment Gateway":r.provider==="freemius"?"Freemius":"Stripe"}))}function Gr(t){return t.filter(r=>r.status==="paid").map(r=>{const s=r.customer_details?.shipping||r.customer_details?.billing,a=s?.country_code||"N/A",i=s?.state||"N/A",c=r.tax_details?.lines?.[0]?.rate?.display_name||"N/A",l=r.tax_details?.lines?.[0]?.rate?.percentage||0;return{Date:r.paid_at?new Date(r.paid_at).toLocaleDateString():new Date(r.created_at).toLocaleDateString(),"Order ID":r.id,Destination:`${i}, ${a}`,"Tax Rate Applied":`${l}% (${c})`,"Total Taxable Amount":(r.subtotal/100).toFixed(2),"Tax Collected":(r.tax_total/100).toFixed(2),Currency:r.currency.toUpperCase()}})}function Wr(t){const r={};return t.filter(s=>s.status==="paid").forEach(s=>{const a=s.currency.toUpperCase();r[a]||(r[a]={volume:0,subtotal:0,tax:0}),r[a].volume+=s.total,r[a].subtotal+=s.subtotal,r[a].tax+=s.tax_total}),Object.entries(r).map(([s,a])=>({Currency:s,"Total Transaction Volume":(a.volume/100).toFixed(2),"Total Subtotal":(a.subtotal/100).toFixed(2),"Total Tax Collected":(a.tax/100).toFixed(2)}))}function It(){const[t,r]=y.useState(!1),[s,a]=y.useState(!1),[i,c]=y.useState(""),[l,u]=y.useState(""),[d,m]=y.useState("general_ledger"),h=async()=>{if(!i||!l){X.toast.error("Please select both start and end dates");return}a(!0);try{X.toast.info("Generating report...");const x=await At(i,l);if(!x||x.length===0){X.toast.error("No orders found for the selected date range"),a(!1);return}let v=[];const f=`report_${d}_${i}_to_${l}`;switch(d){case"general_ledger":v=Hr(x);break;case"tax_liability":v=Gr(x);break;case"currency_summary":v=Wr(x);break}Vr(v,`${f}.csv`),X.toast.success("Download complete!"),r(!1)}catch(x){console.error("Export error:",x),X.toast.error("Failed to generate report")}finally{a(!1)}};return e.jsxs(n.Dialog,{open:t,onOpenChange:r,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:e.jsxs(n.Button,{variant:"outline",className:"flex items-center gap-2",children:[e.jsx(A.Download,{className:"h-4 w-4"}),"Export Reports"]})}),e.jsxs(n.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(n.DialogHeader,{children:[e.jsxs(n.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(A.FileDown,{className:"h-5 w-5 text-blue-600"}),"Accounting Reports"]}),e.jsx(n.DialogDescription,{children:"Generate and download accountant-friendly order reports."})]}),e.jsxs("div",{className:"grid gap-6 py-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(n.Label,{htmlFor:"start-date",className:"text-xs font-semibold uppercase text-gray-500 tracking-wider",children:"Start Date"}),e.jsxs("div",{className:"relative",children:[e.jsx(n.Input,{id:"start-date",type:"date",value:i,onChange:x=>c(x.target.value),className:"pl-8"}),e.jsx(A.Calendar,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-400"})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(n.Label,{htmlFor:"end-date",className:"text-xs font-semibold uppercase text-gray-500 tracking-wider",children:"End Date"}),e.jsxs("div",{className:"relative",children:[e.jsx(n.Input,{id:"end-date",type:"date",value:l,onChange:x=>u(x.target.value),className:"pl-8"}),e.jsx(A.Calendar,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-400"})]})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(n.Label,{htmlFor:"report-type",className:"text-xs font-semibold uppercase text-gray-500 tracking-wider",children:"Report Type"}),e.jsxs(n.Select,{value:d,onValueChange:x=>m(x),children:[e.jsx(n.SelectTrigger,{id:"report-type",className:"w-full",children:e.jsx(n.SelectValue,{placeholder:"Select report type"})}),e.jsxs(n.SelectContent,{children:[e.jsx(n.SelectItem,{value:"general_ledger",children:"General Sales Ledger"}),e.jsx(n.SelectItem,{value:"tax_liability",children:"Tax Liability Summary"}),e.jsx(n.SelectItem,{value:"currency_summary",children:"Multi-Currency Revenue Summary"})]})]})]})]}),e.jsx(n.DialogFooter,{children:e.jsx(n.Button,{onClick:h,disabled:s,className:"w-full bg-blue-600 hover:bg-blue-700 text-white",children:s?e.jsxs(e.Fragment,{children:[e.jsx(A.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(A.Download,{className:"mr-2 h-4 w-4"}),"Download Report"]})})})]})]})}const Je=(t,r="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:r}).format(t/100);async function Qr({searchParams:t}){const r=await t,s=Number(r.page)||1,a=r.status||"all",{data:i,totalPages:c}=await Tt(s,a);return e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Orders"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{}),e.jsx(J,{href:`/cms/orders?page=${s}&status=${a}`,className:"px-3 py-2 text-sm font-medium border rounded hover:bg-gray-50 dark:hover:bg-slate-800",children:"Refresh"})]})]}),e.jsx("div",{className:"flex gap-2 border-b pb-4",children:["all","paid","trial","pending","failed"].map(l=>e.jsx(J,{href:`/cms/orders?page=1&status=${l}`,className:`px-3 py-1 rounded-full text-sm font-medium capitalize ${a===l?"bg-black text-white dark:bg-white dark:text-black":"bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-slate-800 dark:text-gray-300 dark:hover:bg-slate-700"}`,children:l},l))}),e.jsx("div",{className:"border rounded-lg overflow-hidden dark:border-slate-800",children:e.jsxs("table",{className:"w-full text-sm text-left align-middle",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-500 font-medium border-b dark:bg-slate-900 dark:text-slate-400 dark:border-slate-800",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"ID"}),e.jsx("th",{className:"px-4 py-3",children:"Customer"}),e.jsx("th",{className:"px-4 py-3",children:"Status"}),e.jsx("th",{className:"px-4 py-3",children:"Provider"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"Amount"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"Date"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y dark:divide-slate-800",children:i.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-8 text-center text-gray-500",children:"No orders found."})}):i.map(l=>{const u=l.customer_details,d=u?.name||u?.email||l.customer?.full_name||"Guest Customer";return e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-slate-800/50",children:[e.jsxs("td",{className:"px-4 py-3 font-mono text-gray-500",children:[l.id.slice(0,8),"..."]}),e.jsx("td",{className:"px-4 py-3 font-medium",children:d}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(Xr,{status:l.status})}),e.jsx("td",{className:"px-4 py-3 capitalize text-gray-600 dark:text-gray-400",children:l.provider==="freemius"?"Freemius":"Stripe"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"flex flex-col items-end",children:[e.jsx("span",{children:Je(l.total,l.currency||"usd")}),l.discount_total?e.jsxs("span",{className:"text-[10px] text-emerald-600",children:[l.coupon_code," -",Je(l.discount_total,l.currency||"usd")]}):null]})}),e.jsx("td",{className:"px-4 py-3 text-right text-gray-500 whitespace-nowrap",children:new Date(l.created_at||"").toLocaleDateString()}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(J,{href:`/cms/orders/${l.id}`,className:"text-blue-600 hover:underline dark:text-blue-400",children:"View"})})]},l.id)})})]})}),e.jsxs("div",{className:"flex justify-between items-center pt-4",children:[e.jsxs("div",{className:"text-sm text-gray-500",children:["Page ",s," of ",c]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(J,{href:`/cms/orders?page=${Math.max(1,s-1)}&status=${a}`,className:`px-3 py-1 border rounded text-sm ${s<=1?"pointer-events-none opacity-50":"hover:bg-gray-50 dark:hover:bg-slate-800"}`,children:"Previous"}),e.jsx(J,{href:`/cms/orders?page=${Math.min(c,s+1)}&status=${a}`,className:`px-3 py-1 border rounded text-sm ${s>=c?"pointer-events-none opacity-50":"hover:bg-gray-50 dark:hover:bg-slate-800"}`,children:"Next"})]})]})]})}function Xr({status:t}){let r="bg-gray-100 text-gray-700 dark:bg-slate-800 dark:text-gray-300";return t==="paid"&&(r="bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"),t==="trial"&&(r="bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300"),t==="pending"&&(r="bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"),t==="failed"&&(r="bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"),e.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium capitalize ${r}`,children:t})}function Yr({disabled:t=!1}){return e.jsxs(n.Button,{type:"button",variant:"outline",onClick:()=>window.print(),disabled:t,children:[e.jsx(A.Printer,{className:"mr-2 h-4 w-4"}),"Print / Save as PDF"]})}const Zr=["pending","trial","paid","shipped","cancelled","refunded"];async function Jr(){const t=K.createClient(),{data:{user:r},error:s}=await t.auth.getUser();if(s||!r)return{error:"Unauthorized"};const{data:a,error:i}=await t.from("profiles").select("role").eq("id",r.id).single();return i||!a||!["ADMIN","WRITER"].includes(a.role)?{error:"Forbidden"}:{supabase:t,user:r}}function es(){const t=process.env.SUPABASE_SERVICE_ROLE_KEY,r=process.env.NEXT_PUBLIC_SUPABASE_URL;if(!t||!r)throw new Error("Server configuration error");return Ce.createClient(r,t,{auth:{autoRefreshToken:!1,persistSession:!1}})}async function ts(t,r){const s=await Jr();if("error"in s)return{success:!1,error:s.error};if(!Zr.includes(r))return{success:!1,error:"Invalid order status"};let a;try{a=es()}catch(l){return{success:!1,error:l instanceof Error?l.message:"Server configuration error"}}const{data:i,error:c}=await a.from("orders").update({status:r}).eq("id",t).select();return c?(console.error("Order status update error:",c),{success:!1,error:c.message}):!i||i.length===0?{success:!1,error:"Order not found or update failed."}:(r==="paid"&&(await Ie({orderId:t,client:a}),await Pe(a,t)),{success:!0})}const et=[{value:"pending",label:"Pending"},{value:"trial",label:"Trial"},{value:"paid",label:"Paid"},{value:"shipped",label:"Shipped"},{value:"cancelled",label:"Cancelled"},{value:"refunded",label:"Refunded"}];function rs({orderId:t,currentStatus:r}){const s=ae.useRouter(),[a,i]=y.useState(et.some(x=>x.value===r)?r:"pending"),[c,l]=y.useState(null),[u,d]=y.useTransition(),m=y.useMemo(()=>a!==r,[r,a]),h=()=>{m&&(l(null),d(async()=>{try{const x=await ts(t,a);if(!x.success){l(x.error||"Failed to update order status.");return}s.refresh()}catch(x){console.error(x),l("Unexpected error while saving the order status.")}}))};return e.jsxs("div",{className:"rounded-lg border bg-white p-4 dark:border-slate-800 dark:bg-slate-900",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end",children:[e.jsxs("div",{className:"min-w-[220px] flex-1 space-y-2",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500",children:"Order Status"}),e.jsxs(n.Select,{value:a,onValueChange:x=>{i(x),l(null)},children:[e.jsx(n.SelectTrigger,{children:e.jsx(n.SelectValue,{placeholder:"Select status"})}),e.jsx(n.SelectContent,{children:et.map(x=>e.jsx(n.SelectItem,{value:x.value,children:x.label},x.value))})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(n.Button,{type:"button",onClick:h,disabled:u||!m,children:u?"Saving...":"Save"})})]}),c?e.jsx("p",{className:"mt-2 text-xs text-red-600 dark:text-red-400",children:c}):m?null:e.jsx("p",{className:"mt-2 text-xs text-slate-500",children:"Status is already up to date."})]})}const tt=(t,r="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:r}).format(t/100);async function ss({params:t}){const{id:r}=await t,[s,a]=await Promise.all([Pt(r),Me(r).catch(()=>null)]);s||ae.notFound();const i=a?.order.customer_details??s.customer_details,c=o.buildInvoiceDocumentLabels(l=>l);return e.jsxs("div",{className:"mx-auto w-full max-w-6xl px-4 py-10 md:px-6",children:[e.jsxs("div",{className:"flex flex-col gap-4 border-b pb-6 md:flex-row md:items-start md:justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(J,{href:"/cms/orders",className:"hover:underline",children:"Orders"}),e.jsx("span",{children:"/"}),e.jsx("span",{className:"font-mono",children:s.id})]}),e.jsxs("h1",{className:"flex flex-wrap items-center gap-3 text-3xl font-bold tracking-tight",children:["Order",e.jsx(as,{status:s.status,size:"lg"})]}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Review the finalized invoice, customer details, and payment metadata in one place."})]}),e.jsx("div",{className:"w-full max-w-md",children:e.jsx(rs,{orderId:r,currentStatus:s.status})})]}),e.jsxs("div",{className:"mt-6 grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border bg-white p-4 dark:border-slate-800 dark:bg-slate-900",children:[e.jsx("h3",{className:"mb-3 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500",children:"Customer"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[i?.name?e.jsx("p",{className:"font-semibold text-gray-900 dark:text-white",children:i.name}):null,i?.email?e.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:i.email}):null,i?.phone?e.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:i.phone}):null,!i?.name&&!i?.email&&!i?.phone?e.jsx("p",{className:"italic text-gray-400",children:"No contact info captured."}):null,s.user_id?e.jsxs("p",{className:"pt-1 font-mono text-[10px] uppercase tracking-wider text-gray-400",children:["User ID: ",s.user_id.slice(0,13),"..."]}):null]})]}),e.jsxs("div",{className:"rounded-lg border bg-white p-4 dark:border-slate-800 dark:bg-slate-900",children:[e.jsx("h3",{className:"mb-3 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500",children:"Payment Details"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx(me,{label:"Provider",value:s.provider||"stripe",capitalize:!0}),e.jsx(me,{label:"Currency",value:(s.currency||"usd").toUpperCase()}),e.jsx(me,{label:"Created",value:new Date(s.created_at||"").toLocaleDateString()}),e.jsx(me,{label:"Invoice #",value:a?.order.invoice_number||"Pending assignment"}),e.jsx(me,{label:"Paid on",value:a?.order.paid_at?new Date(a.order.paid_at).toLocaleString():"Pending payment"}),e.jsx(me,{label:"Total",value:typeof s.total=="number"?tt(s.total,s.currency||"usd"):"--"}),s.discount_total?e.jsx(me,{label:"Discount",value:`${s.coupon_code?`${s.coupon_code} `:""}-${tt(s.discount_total,s.currency||"usd")}`}):null,s.stripe_session_id?e.jsxs("div",{className:"mt-3 border-t pt-3 dark:border-slate-800",children:[e.jsx("p",{className:"mb-1 text-xs text-gray-500",children:"Session ID"}),e.jsx("p",{className:"break-all rounded bg-gray-50 p-1 font-mono text-xs dark:bg-slate-800",children:s.stripe_session_id})]}):null]})]})]}),e.jsx("div",{className:"mt-6 flex justify-end print:hidden",children:e.jsx(Yr,{disabled:!a})}),e.jsx(o.InvoiceViewerShell,{invoice:a,labels:c,locale:"en-US",title:a?.order.invoice_number||"Order invoice",description:"Open the printable invoice below and update the order status whenever you need to.",printLabel:"Print / Save as PDF",action:{href:"/cms/orders",label:"Back to orders",variant:"outline"},emptyMessage:"The printable invoice will appear here after the order payment metadata is synced.",className:"max-w-none px-0 py-6 md:px-0",showHeader:!1})]})}function me({label:t,value:r,capitalize:s=!1}){return e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-gray-500",children:t}),e.jsx("span",{className:s?"capitalize font-medium":"font-medium",children:r})]})}function as({status:t,size:r="md"}){let s="bg-gray-100 text-gray-700 dark:bg-slate-800 dark:text-gray-300";t==="paid"&&(s="bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"),t==="trial"&&(s="bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300"),t==="pending"&&(s="bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"),t==="shipped"&&(s="bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"),t==="cancelled"&&(s="bg-slate-200 text-slate-700 dark:bg-slate-800 dark:text-slate-300"),t==="refunded"&&(s="bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300"),t==="failed"&&(s="bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400");const a=r==="lg"?"px-3 py-1 text-sm":"px-2 py-0.5 text-xs";return e.jsx("span",{className:`${a} rounded-full font-medium capitalize ${s}`,children:t})}function Rt({productName:t,isIcon:r=!1,className:s,redirectTo:a,deleteAction:i}){const[c,l]=y.useTransition(),u=ae.useRouter(),d=async m=>{m.preventDefault(),m.stopPropagation(),window.confirm(`Are you sure you want to delete "${t}"? This action cannot be undone.`)&&l(async()=>{try{await i(),a?u.push(a):u.refresh()}catch(h){console.error("Failed to delete product:",h),alert("Failed to delete product. Please try again.")}})};return r?e.jsx(n.Button,{variant:"ghost",size:"icon",onClick:d,disabled:c,className:`text-red-500 hover:text-red-600 hover:bg-red-50 ${s}`,title:"Delete Product",children:e.jsx(A.Trash2,{className:"h-4 w-4"})}):e.jsx(n.Button,{variant:"destructive",onClick:d,disabled:c,className:s,type:"button",children:c?"Deleting...":"Delete Product"})}const rt=process.env.NEXT_PUBLIC_R2_BASE_URL||"";function ns(t){return t?t.startsWith("http")||!rt?t:`${rt.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`:null}function is({products:t,languageLabels:r,defaultCurrencyCode:s,deleteProductAction:a,bulkDeleteProductsAction:i,bulkDraftProductsAction:c}){const l=ae.useRouter(),[u,d]=y.useState(()=>new Set),[m,h]=y.useState(""),[x,v]=y.useState(null),[f,N]=y.useState(null),[k,R]=y.useTransition(),b=y.useMemo(()=>{const T=m.trim().toLowerCase();return T?t.filter(H=>{const G=r[String(H.language_id)]||"";return[H.title,H.sku,H.slug,H.status,G].filter(Boolean).join(" ").toLowerCase().includes(T)}):t},[r,t,m]),S=y.useMemo(()=>t.map(T=>T.id),[t]),E=y.useMemo(()=>b.map(T=>T.id),[b]),_=y.useMemo(()=>t.filter(T=>u.has(T.id)),[t,u]).length,g=_>1,j=E.filter(T=>u.has(T)).length,D=E.length>0&&E.every(T=>u.has(T)),B=j>0&&!D;y.useEffect(()=>{const T=new Set(S);d(H=>{const G=new Set(Array.from(H).filter(p=>T.has(p)));return G.size===H.size?H:G})},[S]);const L=T=>{d(H=>{const G=new Set(H);return T?E.forEach(p=>G.add(p)):E.forEach(p=>G.delete(p)),G})},z=(T,H)=>{d(G=>{const p=new Set(G);return H?p.add(T):p.delete(T),p})},ee=(T,H,G)=>{if(_===0){v("Select at least one product first.");return}window.confirm(H)&&(v(null),N(T),R(async()=>{try{const p=await G(Array.from(u));if(!p.success){v(p.error||"Bulk action failed. Please try again."),N(null);return}d(new Set),l.refresh()}catch(p){console.error("Bulk product action failed:",p),v("Bulk action failed. Please try again.")}finally{N(null)}}))};return e.jsxs("div",{className:"rounded-lg border overflow-hidden dark:border-slate-700",children:[e.jsxs("div",{className:"flex min-h-14 flex-wrap items-center justify-between gap-3 border-b bg-muted/20 px-4 py-3",children:[e.jsxs("div",{className:"flex min-w-[260px] flex-1 flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsx(A.Search,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(n.Input,{value:m,onChange:T=>h(T.target.value),placeholder:"Search products...",className:"h-9 pl-9","aria-label":"Search products"})]}),_>0?e.jsxs("span",{className:"text-sm font-medium text-foreground",children:[_," selected"]}):null,x?e.jsx("span",{className:"text-sm text-destructive",children:x}):null]}),g?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(n.Button,{variant:"outline",size:"sm",disabled:k,onClick:()=>ee("Moving to draft...",`Move ${_} selected products to draft?`,c),children:[e.jsx(A.Archive,{className:"mr-2 h-4 w-4"}),f==="Moving to draft..."?f:"Set Draft"]}),e.jsxs(n.Button,{variant:"destructive",size:"sm",disabled:k,onClick:()=>ee("Deleting...",`Delete ${_} selected products? This action cannot be undone.`,i),children:[e.jsx(A.Trash2,{className:"mr-2 h-4 w-4"}),f==="Deleting..."?f:"Delete"]})]}):null]}),e.jsxs(n.Table,{children:[e.jsx(n.TableHeader,{children:e.jsxs(n.TableRow,{children:[e.jsx(n.TableHead,{className:"w-12",children:e.jsx(n.Checkbox,{checked:D?!0:B?"indeterminate":!1,onCheckedChange:T=>L(T===!0),"aria-label":"Select all products on this page"})}),e.jsx(n.TableHead,{children:"Image"}),e.jsx(n.TableHead,{children:"Title"}),e.jsx(n.TableHead,{children:"SKU"}),e.jsx(n.TableHead,{children:"Price"}),e.jsx(n.TableHead,{children:"Language"}),e.jsx(n.TableHead,{children:"Stock"}),e.jsx(n.TableHead,{children:"Status"}),e.jsx(n.TableHead,{className:"text-right",children:"Actions"})]})}),e.jsx(n.TableBody,{children:b.length>0?b.map(T=>{const H=ns(T.product_media?.[0]?.media?.file_path||T.product_media?.[0]?.media?.object_key);return e.jsxs(n.TableRow,{"data-state":u.has(T.id)?"selected":void 0,children:[e.jsx(n.TableCell,{children:e.jsx(n.Checkbox,{checked:u.has(T.id),onCheckedChange:G=>z(T.id,G===!0),"aria-label":`Select ${T.title}`})}),e.jsx(n.TableCell,{children:H?e.jsx(nr,{src:H,alt:T.title,width:40,height:40,className:"w-10 h-10 object-cover rounded"}):e.jsx("div",{className:"w-10 h-10 bg-gray-200 rounded flex items-center justify-center text-xs text-gray-500",children:"No Img"})}),e.jsx(n.TableCell,{className:"font-medium",children:e.jsx(J,{href:`/cms/products/${T.id}/edit`,className:"hover:underline",children:T.title})}),e.jsx(n.TableCell,{children:T.sku}),e.jsx(n.TableCell,{children:e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:T.sale_price?"font-semibold text-primary":"",children:typeof(T.sale_price??T.price)=="number"?$.formatPrice(T.sale_price??T.price??0,s):"N/A"}),T.sale_price?e.jsx("span",{className:"text-sm text-muted-foreground line-through",children:$.formatPrice(T.price??0,s)}):null]})}),e.jsx(n.TableCell,{children:e.jsx(n.Badge,{variant:"outline",children:r[String(T.language_id)]||"N/A"})}),e.jsx(n.TableCell,{children:T.stock}),e.jsx(n.TableCell,{children:e.jsx("span",{className:`px-2 py-1 rounded text-xs ${T.status==="active"?"bg-green-100 text-green-800":T.status==="archived"?"bg-gray-100 text-gray-800":"bg-yellow-100 text-yellow-800"}`,children:T.status})}),e.jsxs(n.TableCell,{className:"text-right flex justify-end gap-2 items-center",children:[T.slug?e.jsx(J,{href:`/product/${T.slug}`,target:"_blank",rel:"noopener noreferrer",children:e.jsx(n.Button,{variant:"outline",size:"sm",children:"View Product"})}):null,e.jsx(J,{href:`/cms/products/${T.id}/edit`,children:e.jsx(n.Button,{variant:"ghost",size:"sm",children:"Edit"})}),e.jsx(Rt,{productName:T.title,isIcon:!0,deleteAction:()=>a(T.id)})]})]},T.id)}):e.jsx(n.TableRow,{children:e.jsx(n.TableCell,{colSpan:9,className:"text-center py-10",children:t.length===0?"No products found.":"No products match your search."})})})]})]})}function os({title:t="Sync Full Store"}){const[r,s]=y.useState(!1),a=async()=>{s(!0);try{const i=await o.triggerFreemiusSync();i.error?X.toast.error(i.error):X.toast.success(`Full store sync complete! Found ${i.data?.count||0} products.`)}catch(i){X.toast.error(i.message||"An unexpected error occurred during sync")}finally{s(!1)}};return e.jsxs(n.Button,{variant:"secondary",onClick:a,disabled:r,className:"gap-2",children:[e.jsx(A.RefreshCw,{className:`w-4 h-4 ${r?"animate-spin":""}`}),r?"Syncing...":t]})}async function cs({searchParams:t,languageFilterNode:r,transferControlsNode:s}){const a=K.getServiceRoleSupabaseClient(),[i,{data:c}]=await Promise.all([K.getActiveLanguagesServerSide(),a.from("currencies").select("code, is_default").eq("is_active",!0).order("is_default",{ascending:!1}).order("code",{ascending:!0})]),l=t?.lang?parseInt(t.lang,10):void 0,{data:u}=await o.getProducts({languageId:l}),d=Object.fromEntries(i.map(h=>[String(h.id),h.code.toUpperCase()])),m=c?.find(h=>h.is_default)?.code||c?.[0]?.code||"USD";return e.jsxs("div",{className:"p-8 space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h1",{className:"text-3xl font-bold",children:"Products"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx("div",{className:"h-10 w-[1px] bg-slate-200 dark:bg-slate-800 mx-2 hidden sm:block"}),s,r,e.jsx(os,{title:"Sync Full Store"}),e.jsx(J,{href:"/cms/products/new",children:e.jsx(n.Button,{children:"New Product"})})]})]}),e.jsx(is,{products:u||[],languageLabels:d,defaultCurrencyCode:m,deleteProductAction:o.deleteProductAction,bulkDeleteProductsAction:o.bulkDeleteProductsAction,bulkDraftProductsAction:o.bulkDraftProductsAction})]})}function ls(t){const r=[];let s=[],a="",i=!1;for(let c=0;c<t.length;c+=1){const l=t[c],u=t[c+1];if(l==='"'){i&&u==='"'?(a+='"',c+=1):i=!i;continue}if(l===","&&!i){s.push(a),a="";continue}if((l===`
100
+ `||l==="\r")&&!i){l==="\r"&&u===`
101
+ `&&(c+=1),(a.length>0||s.length>0)&&(s.push(a),r.push(s)),s=[],a="";continue}a+=l}return(a.length>0||s.length>0)&&(s.push(a),r.push(s)),r.filter(c=>c.some(l=>l.trim().length>0))}function ds(t){return t.sku}async function us(t){try{const r=Math.max(0,Math.trunc(t.stock));return await o.setSharedInventoryQuantity({sku:t.sku,stock:r}),Q.revalidatePath("/cms/products"),Q.revalidatePath("/cms/products/inventory"),{success:!0,itemKey:ds(t),stock:r}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to update inventory."}}}async function ms(t){try{const r=ls(t);if(r.length<2)return{success:!1,error:"The CSV file is empty."};const[s,...a]=r,i=s.map(h=>h.trim().toLowerCase()),c=i.indexOf("sku"),l=i.indexOf("stock");if(c===-1||l===-1)return{success:!1,error:"The CSV format is invalid. Please import a file exported from the Inventory page."};const u=K.getServiceRoleSupabaseClient();let d=0;for(const h of a){const x=(h[c]||"").trim(),v=Number.parseInt((h[l]||"").trim(),10);if(x){if(!Number.isFinite(v)||v<0)return{success:!1,error:`Invalid stock value for SKU "${x}".`};await o.setSharedInventoryQuantity({sku:x,stock:v},u),d+=1}}const m=await o.getInventoryItems(u);return Q.revalidatePath("/cms/products"),Q.revalidatePath("/cms/products/inventory"),{success:!0,updatedCount:d,items:m}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to import inventory CSV."}}}function ps(t){const r=String(t??"");return/[",\n]/.test(r)?`"${r.replace(/"/g,'""')}"`:r}function hs(t){const r=["sku","stock","usage_type","product_titles","languages","statuses","parent_product_skus"],s=t.map(a=>[a.sku,a.stock,a.usageType,a.productTitles.join("|"),a.languages.join("|"),a.statuses.join("|"),a.parentProductSkus.join("|")]);return[r,...s].map(a=>a.map(i=>ps(i)).join(",")).join(`
102
+ `)}function xs(t){return t.usageType==="mixed"?"Shared SKU":t.usageType==="variant"?`Variant SKU ${t.sku}`:"Simple Product"}function gs(t){return t.usageType==="variant"?"secondary":"outline"}function fs({initialItems:t}){const[r,s]=y.useState(t),[a,i]=y.useState(()=>t.reduce((b,S)=>(b[S.key]=String(S.stock),b),{})),[c,l]=y.useState(""),[u,d]=y.useTransition(),[m,h]=y.useState(null),x=y.useRef(null),v=y.useMemo(()=>{const b=c.trim().toLowerCase();return b?r.filter(S=>S.sku.toLowerCase().includes(b)||S.productTitles.join(" ").toLowerCase().includes(b)||S.parentProductSkus.join(" ").toLowerCase().includes(b)||S.languages.join(" ").toLowerCase().includes(b)):r},[r,c]),f=()=>{const b=hs(r),S=new Blob([b],{type:"text/csv;charset=utf-8;"}),E=URL.createObjectURL(S),F=document.createElement("a");F.href=E,F.download="inventory-export.csv",F.click(),URL.revokeObjectURL(E)},N=b=>{const S=a[b.key]??String(b.stock),E=Number.parseInt(S,10);if(!Number.isFinite(E)||E<0){X.toast.error("Stock must be a non-negative whole number.");return}h(b.key),d(async()=>{const F=await us({sku:b.sku,stock:E});if(!F.success){X.toast.error(F.error||"Failed to update inventory."),h(null);return}const _=typeof F.stock=="number"?F.stock:E;s(g=>g.map(j=>j.key===b.key?{...j,stock:_}:j)),i(g=>({...g,[b.key]:String(_)})),h(null),X.toast.success(`Inventory updated for ${b.sku}.`)})},k=()=>{x.current?.click()},R=async b=>{const S=await b.text();h("import"),d(async()=>{const E=await ms(S);if(!E.success){X.toast.error(E.error||"Failed to import inventory CSV."),h(null);return}const F=E.items||[];s(F),i(F.reduce((_,g)=>(_[g.key]=String(g.stock),_),{})),h(null),X.toast.success(`Imported ${E.updatedCount||0} inventory updates.`)})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border bg-card p-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("div",{className:"relative w-full lg:max-w-md",children:[e.jsx(A.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(n.Input,{value:c,onChange:b=>l(b.target.value),placeholder:"Search by SKU, product title, parent SKU, or language...",className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{ref:x,type:"file",accept:".csv,text/csv",className:"hidden",onChange:b=>{const S=b.target.files?.[0];S&&R(S),b.currentTarget.value=""}}),e.jsxs(n.Button,{type:"button",variant:"outline",onClick:k,disabled:u,children:[e.jsx(A.Upload,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(n.Button,{type:"button",variant:"outline",onClick:f,disabled:u,children:[e.jsx(A.Download,{className:"mr-2 h-4 w-4"}),"Export CSV"]})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Inventory is keyed by sellable SKU. Any product or variant using the same SKU shares the same quantity, and CSV imports can update those shared SKU quantities in bulk."})]}),e.jsx("div",{className:"rounded-xl border bg-card",children:e.jsxs(n.Table,{children:[e.jsx(n.TableHeader,{children:e.jsxs(n.TableRow,{children:[e.jsx(n.TableHead,{children:"SKU"}),e.jsx(n.TableHead,{children:"Usage"}),e.jsx(n.TableHead,{children:"Linked Products"}),e.jsx(n.TableHead,{children:"Languages"}),e.jsx(n.TableHead,{children:"Status"}),e.jsx(n.TableHead,{className:"w-[160px]",children:"Quantity"}),e.jsx(n.TableHead,{className:"text-right",children:"Actions"})]})}),e.jsx(n.TableBody,{children:v.length>0?v.map(b=>{const S=a[b.key]??String(b.stock),E=Number.parseInt(S,10),F=Number.isFinite(E)&&E!==b.stock,_=m===b.key;return e.jsxs(n.TableRow,{children:[e.jsx(n.TableCell,{className:"font-mono text-sm",children:b.sku}),e.jsx(n.TableCell,{children:e.jsx(n.Badge,{variant:gs(b),children:xs(b)})}),e.jsx(n.TableCell,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:b.productTitles.join(", ")}),b.usageType!=="product"?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Parent SKU",b.parentProductSkus.length>1?"s":"",":"," ",e.jsx("span",{className:"font-mono",children:b.parentProductSkus.join(", ")})]}):null]})}),e.jsx(n.TableCell,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:b.languages.map(g=>e.jsx(n.Badge,{variant:"outline",children:g},`${b.key}:${g}`))})}),e.jsx(n.TableCell,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:b.statuses.map(g=>e.jsx(n.Badge,{variant:"outline",children:g},`${b.key}:${g}`))})}),e.jsx(n.TableCell,{children:e.jsx(n.Input,{type:"number",min:0,step:1,value:S,disabled:u,onChange:g=>i(j=>({...j,[b.key]:g.target.value})),className:"w-28"})}),e.jsx(n.TableCell,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs(n.Button,{type:"button",size:"sm",variant:"ghost",disabled:!F||u,onClick:()=>i(g=>({...g,[b.key]:String(b.stock)})),children:[e.jsx(A.RotateCcw,{className:"mr-2 h-4 w-4"}),"Reset"]}),e.jsxs(n.Button,{type:"button",size:"sm",disabled:!F||u,onClick:()=>N(b),children:[e.jsx(A.Save,{className:"mr-2 h-4 w-4"}),_?"Saving...":"Save"]})]})})]},b.key)}):e.jsx(n.TableRow,{children:e.jsx(n.TableCell,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No inventory rows matched your search."})})})]})})]})}async function ys(){const t=await o.getInventoryItems();return e.jsxs("div",{className:"p-8 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-3xl font-bold",children:"Inventory"}),e.jsx("p",{className:"max-w-3xl text-sm text-muted-foreground",children:"Manage source-of-truth stock for every sellable SKU in one place. Matching SKUs share the same quantity across products, translations, and variants, and you can update those shared quantities inline or in bulk through CSV import and export."})]}),e.jsx(fs,{initialItems:t})]})}function _s({attributes:t,languages:r,createAttributeAction:s,deleteAttributeAction:a,createTermAction:i,deleteTermAction:c,reorderTermsAction:l,updateTranslationsAction:u}){const d=ae.useRouter(),[m,h]=y.useState(""),[x,v]=y.useState(null),[f,N]=y.useState(null),[k,R]=y.useState(null),[b,S]=y.useState(null),[E,F]=y.useState({}),[_,g]=y.useState(()=>t.reduce((p,P)=>(p[P.id]=P.name_translations||{},p),{})),[j,D]=y.useState(()=>t.reduce((p,P)=>{for(const M of P.terms)p[M.id]=M.value_translations||{};return p},{})),B=r.filter(p=>!p.is_default),L=async p=>{p.preventDefault();const P=await s({name:m});if(!P.success){alert(P.error||"Failed to create attribute.");return}h(""),d.refresh()},z=async(p,P)=>{p.preventDefault(),v(P);const M=await i({attributeId:P,value:E[P]||""});if(v(null),!M.success){alert(M.error||"Failed to create term.");return}F(W=>({...W,[P]:""})),d.refresh()},ee=async p=>{if(!window.confirm("Delete this attribute and all of its terms?"))return;const M=await a(p);if(!M.success){alert(M.error||"Failed to delete attribute.");return}d.refresh()},T=async p=>{N(p);const P=await c(p);if(N(null),!P.success){alert(P.error||"Failed to delete term.");return}d.refresh()},H=async(p,P,M)=>{const W=p.terms.findIndex(q=>q.id===P),se=W+M;if(W===-1||se<0||se>=p.terms.length)return;const C=[...p.terms],[O]=C.splice(W,1);C.splice(se,0,O),R(p.id);const I=await l({attributeId:p.id,orderedTermIds:C.map(q=>q.id)});if(R(null),!I.success){alert(I.error||"Failed to reorder terms.");return}d.refresh()},G=async p=>{S(p.id);const P=await u({attributeId:p.id,nameTranslations:_[p.id]||{},termTranslations:p.terms.map(M=>({termId:M.id,valueTranslations:j[M.id]||{}}))});if(S(null),!P.success){alert(P.error||"Failed to save translations.");return}d.refresh()};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("form",{onSubmit:L,className:"rounded-lg border bg-card p-6 shadow-sm",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-[220px] space-y-2",children:[e.jsx(n.Label,{htmlFor:"attribute-name",children:"New Attribute"}),e.jsx(n.Input,{id:"attribute-name",value:m,onChange:p=>h(p.target.value),placeholder:"Material, Size, Color..."})]}),e.jsxs(n.Button,{type:"submit",disabled:!m.trim(),children:[e.jsx(A.Plus,{className:"mr-2 h-4 w-4"}),"Create Attribute"]})]})}),t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:"No global attributes have been created yet."}):e.jsx("div",{className:"grid gap-6",children:t.map(p=>e.jsxs("div",{className:"rounded-lg border bg-card p-6 shadow-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:p.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:p.slug})]}),e.jsx(n.Button,{type:"button",variant:"ghost",size:"icon",onClick:()=>ee(p.id),className:"text-muted-foreground hover:text-destructive",children:e.jsx(A.Trash2,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"mt-4 space-y-2",children:p.terms.map((P,M)=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"secondary",className:"py-1.5",children:P.value}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Position ",M+1]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(n.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>H(p,P.id,-1),disabled:M===0||k===p.id,children:e.jsx(A.ChevronUp,{className:"h-4 w-4"})}),e.jsx(n.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>H(p,P.id,1),disabled:M===p.terms.length-1||k===p.id,children:e.jsx(A.ChevronDown,{className:"h-4 w-4"})}),e.jsx(n.Button,{type:"button",variant:"ghost",size:"icon",onClick:()=>T(P.id),className:"h-8 w-8 text-muted-foreground hover:text-destructive",disabled:f===P.id,children:e.jsx(A.Trash2,{className:"h-4 w-4"})})]})]},P.id))}),e.jsxs("form",{onSubmit:P=>z(P,p.id),className:"mt-6 flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-[220px] space-y-2",children:[e.jsx(n.Label,{htmlFor:`term-input-${p.id}`,children:"Add Term"}),e.jsx(n.Input,{id:`term-input-${p.id}`,value:E[p.id]||"",onChange:P=>F(M=>({...M,[p.id]:P.target.value})),placeholder:`Add a term for ${p.name}`})]}),e.jsxs(n.Button,{type:"submit",variant:"outline",disabled:!E[p.id]?.trim()||x===p.id,children:[e.jsx(A.Plus,{className:"mr-2 h-4 w-4"}),x===p.id?"Saving...":"Add Term"]})]}),B.length>0&&e.jsxs("div",{className:"mt-6 border-t pt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Translations"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Translate the attribute label and each term for every active site language."})]}),e.jsx(n.Button,{type:"button",variant:"outline",onClick:()=>G(p),disabled:b===p.id,children:b===p.id?"Saving...":"Save Translations"})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:B.map(P=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs(n.Label,{htmlFor:`attribute-translation-${p.id}-${P.code}`,children:["Attribute Name (",P.name,")"]}),e.jsx(n.Input,{id:`attribute-translation-${p.id}-${P.code}`,value:_[p.id]?.[P.code]||"",onChange:M=>g(W=>({...W,[p.id]:{...W[p.id]||{},[P.code]:M.target.value}})),placeholder:p.name})]},`${p.id}-${P.code}`))}),e.jsx("div",{className:"space-y-3",children:p.terms.map(P=>e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:P.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Translate this term for each language."})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:B.map(M=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:`term-translation-${P.id}-${M.code}`,children:M.name}),e.jsx(n.Input,{id:`term-translation-${P.id}-${M.code}`,value:j[P.id]?.[M.code]||"",onChange:W=>D(se=>({...se,[P.id]:{...se[P.id]||{},[M.code]:W.target.value}})),placeholder:P.value})]},`${P.id}-${M.code}`))})]},`translations-${P.id}`))})]})]},p.id))})]})}async function bs(){const[t,r]=await Promise.all([o.getGlobalProductAttributes(),K.getActiveLanguagesServerSide()]),s=(t||[]).map(a=>({id:a.id,name:a.name,name_translations:a.name_translations||{},slug:a.slug,terms:(a.product_attribute_terms||[]).map(i=>({...i,value_translations:i.value_translations||{}}))}));return e.jsxs("div",{className:"space-y-8 w-full max-w-[1200px] mx-auto px-6 py-8",children:[e.jsx("div",{className:"flex flex-wrap items-center justify-between gap-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(n.Button,{variant:"outline",size:"icon",asChild:!0,children:e.jsx(J,{href:"/cms/products",children:e.jsx(A.ArrowLeft,{className:"h-4 w-4"})})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Global Attribute Management"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Define reusable attributes and terms for variation-based physical products."})]})]})}),e.jsx(_s,{attributes:s,createAttributeAction:o.createProductAttributeAction,deleteAttributeAction:o.deleteProductAttributeAction,createTermAction:o.createProductAttributeTermAction,deleteTermAction:o.deleteProductAttributeTermAction,reorderTermsAction:o.reorderProductAttributeTermsAction,updateTranslationsAction:o.updateProductAttributeTranslationsAction,languages:r})]})}async function vs({mediaPickerNode:t,availableLanguagesProp:r,translationGroupId:s,targetLanguageId:a,initialData:i}){const[c,l,u,d]=await Promise.all([ye(),Re(),o.getGlobalProductAttributes(),K.getServiceRoleSupabaseClient().from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("code",{ascending:!0}).then(k=>k.data||[])]),m=(d||[]).map(k=>o.normalizeCurrencyRecord(k)),h=(u||[]).map(k=>({id:k.id,name:k.name,name_translations:k.name_translations||{},slug:k.slug,terms:(k.product_attribute_terms||[]).map(R=>({...R,value_translations:R.value_translations||{}}))})),x=r.find(k=>k.id===i?.language_id)?.code||r.find(k=>k.id===(a?parseInt(a,10):void 0))?.code||r.find(k=>k.is_default)?.code,{attributes:v,variants:f}=o.mapRawVariantRelations(i?.product_variants||[],x),N=i&&{...i,variation_attributes:i.variation_attributes||v.map(k=>({attribute_id:k.id,term_ids:k.terms.map(R=>R.id)})),variants:i.variants||f.map(k=>({...k,upc:k.upc??null,price:k.price/100,prices:Object.entries(k.prices||{}).reduce((R,[b,S])=>(R[b]=$.minorUnitAmountToMajor(S,b),R),{}),sale_price:typeof k.sale_price=="number"?k.sale_price/100:null,sale_prices:Object.entries(k.sale_prices||{}).reduce((R,[b,S])=>(R[b]=typeof S=="number"?$.minorUnitAmountToMajor(S,b):null,R),{}),main_media_id:k.main_media_id??null,main_image_url:k.image_url??null}))};return e.jsx("div",{className:"p-8",children:e.jsx(o.ProductForm,{mediaPickerNode:t,availableLanguagesProp:r,globalAttributesProp:h,currenciesProp:m,translationGroupId:s,targetLanguageId:a,initialData:N,enabledProviders:c,configStatus:l,createAction:o.createProductAction})})}function js({plans:t}){return e.jsx("div",{className:"w-full",children:t&&t.length>0?e.jsx("div",{className:"space-y-8",children:t.map(r=>e.jsxs("div",{className:"w-full",children:[t.length>1&&e.jsx("h3",{className:"font-semibold text-lg text-slate-700 dark:text-slate-300 border-b pb-2 mb-4 mt-6",children:r.title||r.name}),e.jsx("div",{className:`${t.length>1?"rounded-lg border":"rounded-b-lg border-x border-b"} overflow-x-auto dark:border-slate-700 bg-card`,children:e.jsxs(n.Table,{children:[e.jsx(n.TableHeader,{children:e.jsxs(n.TableRow,{children:[e.jsx(n.TableHead,{children:"Licenses"}),e.jsx(n.TableHead,{children:"API Monthly"}),e.jsx(n.TableHead,{children:"Override Monthly"}),e.jsx(n.TableHead,{children:"API Annual"}),e.jsx(n.TableHead,{children:"Override Annual"}),e.jsx(n.TableHead,{children:"API Lifetime"}),e.jsx(n.TableHead,{children:"Override Lifetime"})]})}),e.jsx(n.TableBody,{children:r.freemius_pricing&&r.freemius_pricing.length>0?r.freemius_pricing.map(s=>e.jsx(Cs,{pricing:s},s.id)):e.jsx(n.TableRow,{children:e.jsx(n.TableCell,{colSpan:7,className:"text-center text-slate-500 py-4",children:"No pricing configurations found for this plan."})})})]})})]},r.id))}):e.jsxs("div",{className:"text-center py-10 bg-slate-50 dark:bg-slate-800/50 rounded border border-dashed border-slate-300 dark:border-slate-700",children:[e.jsx("p",{className:"text-slate-500",children:"No Freemius plans synchronized yet."}),e.jsx("p",{className:"text-xs mt-2 text-slate-400",children:"Click the full synchronization button to import from Freemius."})]})})}function Cs({pricing:t}){const[r,s]=y.useTransition(),a=(i,c)=>{const l=c===""?null:parseFloat(c);c!==""&&Number.isNaN(l)||s(async()=>{const{success:u,error:d}=await o.updateFreemiusOverride(t.id,{[i]:l});u?X.toast.success("Pricing override saved"):X.toast.error(d||"Failed to update pricing")})};return e.jsxs(n.TableRow,{children:[e.jsx(n.TableCell,{className:"font-medium",children:t.license_quota||"Unlimited"}),e.jsx(n.TableCell,{className:"text-slate-500",children:t.api_monthly_price?`$${t.api_monthly_price}`:"-"}),e.jsx(n.TableCell,{children:e.jsx(n.Input,{type:"number",step:"0.01",placeholder:"Override...",defaultValue:t.override_monthly_price||"",onBlur:i=>{i.target.value!==(t.override_monthly_price?.toString()||"")&&a("override_monthly_price",i.target.value)},className:"w-24 h-8",disabled:r})}),e.jsx(n.TableCell,{className:"text-slate-500",children:t.api_annual_price?`$${t.api_annual_price}`:"-"}),e.jsx(n.TableCell,{children:e.jsx(n.Input,{type:"number",step:"0.01",placeholder:"Override...",defaultValue:t.override_annual_price||"",onBlur:i=>{i.target.value!==(t.override_annual_price?.toString()||"")&&a("override_annual_price",i.target.value)},className:"w-24 h-8",disabled:r})}),e.jsx(n.TableCell,{className:"text-slate-500",children:t.api_lifetime_price?`$${t.api_lifetime_price}`:"-"}),e.jsx(n.TableCell,{children:e.jsx(n.Input,{type:"number",step:"0.01",placeholder:"Override...",defaultValue:t.override_lifetime_price||"",onBlur:i=>{i.target.value!==(t.override_lifetime_price?.toString()||"")&&a("override_lifetime_price",i.target.value)},className:"w-24 h-8",disabled:r})})]})}async function ws({params:t,mediaPickerNode:r,availableLanguagesProp:s,languageSwitcherNode:a,copyContentNode:i,translationCtaNode:c}){const{id:l}=await t,u=await o.getProduct(l);u||ae.notFound();const d=u.product_type==="digital"||u.payment_provider==="freemius",[m,h,x,v,f]=await Promise.all([ye(),Re(),d&&u.freemius_product_id?o.getFreemiusPricingByProductId(u.id):Promise.resolve(null),o.getGlobalProductAttributes(),K.getServiceRoleSupabaseClient().from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("code",{ascending:!0}).then(_=>_.data||[])]),N=(f||[]).map(_=>o.normalizeCurrencyRecord(_)),k=s.find(_=>_.id===u.language_id)?.code,{attributes:R,variants:b}=o.mapRawVariantRelations(u.product_variants||[],k),S=(v||[]).map(_=>({id:_.id,name:_.name,name_translations:_.name_translations||{},slug:_.slug,terms:(_.product_attribute_terms||[]).map(g=>({...g,value_translations:g.value_translations||{}}))})),E=Rt,F=js;return e.jsxs("div",{className:"space-y-8 w-full max-w-[1400px] mx-auto px-6 py-8",children:[e.jsxs("div",{className:"flex justify-between items-center flex-wrap gap-4 w-full",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(n.Button,{variant:"outline",size:"icon","aria-label":"Back to products",asChild:!0,children:e.jsx(J,{href:"/cms/products",children:e.jsx(A.ArrowLeft,{className:"h-4 w-4"})})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Edit Product"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate max-w-md",title:u.title,children:u.title})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[a,i,c,E?e.jsx(E,{productName:u.title,redirectTo:"/cms/products",className:"border-red-200 hover:bg-red-50 hover:text-red-700",deleteAction:o.deleteProductAction.bind(null,u.id)}):null,u.slug&&u.status==="active"&&e.jsx(n.Button,{variant:"outline",asChild:!0,children:e.jsxs(J,{href:`/product/${u.slug}`,target:"_blank",children:[e.jsx(A.ExternalLink,{className:"w-4 h-4 mr-2"}),"View"]})})]})]}),e.jsx(o.ProductForm,{initialData:{id:u.id,title:u.title,slug:u.slug,sku:u.sku,upc:u.upc??void 0,stock:u.stock||0,price:u.price||0,prices:Object.entries(u.prices||{}).reduce((_,[g,j])=>(_[g]=$.minorUnitAmountToMajor(j,g),_),{}),is_taxable:typeof u.is_taxable=="boolean"?u.is_taxable:!0,product_type:u.product_type,payment_provider:u.payment_provider,status:u.status,short_description:u.short_description??void 0,description_json:u.description_json,sale_price:typeof u.sale_price=="number"?u.sale_price:void 0,sale_prices:Object.entries(u.sale_prices||{}).reduce((_,[g,j])=>(_[g]=typeof j=="number"?$.minorUnitAmountToMajor(j,g):null,_),{}),freemius_plan_id:u.freemius_plan_id??void 0,freemius_product_id:u.freemius_product_id??void 0,trial_period_days:u.trial_period_days??0,trial_requires_payment_method:u.trial_requires_payment_method??!1,language_id:u.language_id,translation_group_id:u.translation_group_id,product_media:u.product_media,variation_attributes:R.map(_=>({attribute_id:_.id,term_ids:_.terms.map(g=>g.id)})),variants:b.map(_=>({..._,upc:_.upc??null,price:_.price/100,prices:Object.entries(_.prices||{}).reduce((g,[j,D])=>(g[j]=$.minorUnitAmountToMajor(D,j),g),{}),sale_price:typeof _.sale_price=="number"?_.sale_price/100:null,sale_prices:Object.entries(_.sale_prices||{}).reduce((g,[j,D])=>(g[j]=typeof D=="number"?$.minorUnitAmountToMajor(D,j):null,g),{}),main_media_id:_.main_media_id??null,main_image_url:_.image_url??null}))},isEdit:!0,mediaPickerNode:r,availableLanguagesProp:s,globalAttributesProp:S,currenciesProp:N,enabledProviders:m,configStatus:h,updateAction:o.updateProductAction.bind(null,u.id),freemiusDashboardNode:d&&u.freemius_product_id&&x&&F?e.jsx(F,{productId:u.id,freemiusProductId:u.freemius_product_id,plans:x}):void 0})]})}function Ns({productId:t,currentLanguageId:r,translationGroupId:s,allSiteLanguages:a}){const[i,c]=y.useState(!1),[l,u]=y.useState(null),[d,m]=y.useState([]),[h,x]=y.useState(!1),[v,f]=y.useState(null),[N,k]=y.useTransition(),R=ae.useRouter();y.useEffect(()=>{i&&s&&(async()=>{x(!0);try{const _=(await o.getProductTranslations(s)).filter(g=>g.id!==t);m(_)}catch(F){console.error("Error fetching translations:",F)}finally{x(!1)}})()},[i,s,t]);const b=async()=>{if(!l){f({type:"error",text:"Please select a source version to copy from."});return}f(null),k(async()=>{const E=await o.copyProductFromLanguageAction(t,l);E.success?(f({type:"success",text:"Content copied successfully. The page will now refresh."}),setTimeout(()=>{c(!1),R.refresh()},1500)):f({type:"error",text:E.error||"Failed to copy content."})})},S=a.find(E=>E.id===r);return e.jsxs(n.Dialog,{open:i,onOpenChange:c,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:e.jsxs(n.Button,{variant:"outline",title:"Copy content from another language",children:[e.jsx(A.Copy,{className:"h-4 w-4 mr-2"}),"Copy Content..."]})}),e.jsxs(n.DialogContent,{children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Copy Content from Another Language"}),e.jsxs(n.DialogDescription,{children:["Select a source version to copy from. This will replace the title, description, and media of the current product (",S?.name,"). This action cannot be undone."]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"sourceProduct",children:"Select Source Version"}),e.jsxs(n.Select,{onValueChange:E=>u(E),disabled:N||h,value:l||void 0,children:[e.jsx(n.SelectTrigger,{id:"sourceProduct",children:e.jsx(n.SelectValue,{placeholder:h?"Loading versions...":"Select a version..."})}),e.jsx(n.SelectContent,{children:d.length>0?d.map(E=>{const F=a.find(_=>_.id===E.language_id);return e.jsxs(n.SelectItem,{value:E.id,children:[E.title," (",F?.name||"Unknown Language",")"]},E.id)}):e.jsx(n.SelectItem,{value:"none",disabled:!0,children:"No other versions available"})})]})]}),v&&e.jsxs("div",{className:`p-3 rounded-md text-sm flex items-center gap-2 ${v.type==="success"?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"}`,children:[v.type==="success"?e.jsx(A.CheckCircle2,{className:"h-5 w-5"}):e.jsx(A.AlertCircle,{className:"h-5 w-5"}),v.text]})]}),e.jsxs(n.DialogFooter,{children:[e.jsx(n.DialogClose,{asChild:!0,children:e.jsx(n.Button,{variant:"outline",children:"Cancel"})}),e.jsx(n.Button,{onClick:b,disabled:N||!l||l==="none",children:N?"Copying...":"Copy Content & Replace"})]})]})]})}function Ss({initialCategories:t=[],languages:r=[],createCategory:s,updateCategory:a,deleteCategory:i}){const c=ae.useRouter(),[l,u]=y.useState(t),[d,m]=y.useState(!1),[h,x]=y.useState(null),[v,f]=y.useState(""),[N,k]=y.useState(""),[R,b]=y.useState(""),[S,E]=y.useState({}),[F,_]=y.useState({}),[g,j]=y.useState(!1),D=(r||[]).filter(p=>!p.is_default);y.useEffect(()=>{u(t)},[t]);const B=p=>p.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,""),L=p=>{const P=p.target.value;f(P),!g&&!h&&k(B(P))},z=p=>{k(B(p.target.value)),j(!0)},ee=p=>{x(p),f(p.name),k(p.slug),b(p.description||""),E(p.name_translations||{}),_(p.description_translations||{}),j(!0)},T=()=>{x(null),f(""),k(""),b(""),E({}),_({}),j(!1)},H=async p=>{if(p.preventDefault(),!v.trim()){X.toast.error("Category name is required.");return}m(!0);const P=X.toast.loading(h?"Updating category...":"Creating category...");try{const M={name:v.trim(),slug:N.trim()||void 0,description:R.trim()||void 0,nameTranslations:S,descriptionTranslations:F};let W;h?W=await a(h.id,M):W=await s(M),W.success?(X.toast.success(h?"Category updated successfully!":"Category created successfully!",{id:P}),T(),c.refresh()):X.toast.error(W.error||"Failed to save category.",{id:P})}catch(M){X.toast.error(M.message||"An unexpected error occurred.",{id:P})}finally{m(!1)}},G=async p=>{const P=`Are you sure you want to delete the category "${p.name}"? This will detach it from any assigned products.`;if(!window.confirm(P))return;m(!0);const M=X.toast.loading("Deleting category...");try{const W=await i(p.id);W.success?(X.toast.success("Category deleted successfully!",{id:M}),h?.id===p.id&&T(),c.refresh()):X.toast.error(W.error||"Failed to delete category.",{id:M})}catch(W){X.toast.error(W.message||"An unexpected error occurred.",{id:M})}finally{m(!1)}};return e.jsxs("div",{className:"grid gap-6 md:grid-cols-12 items-start",children:[e.jsx("div",{className:"md:col-span-4 space-y-4",children:e.jsxs(n.Card,{className:"p-5 shadow-lg border-t-4 border-t-amber-500 bg-card/65 backdrop-blur-md transition-all duration-300",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(A.FolderPlus,{className:"h-5 w-5 text-amber-500"}),e.jsx("h2",{className:"text-base font-bold tracking-tight",children:h?"Edit Category":"Add New Category"})]}),e.jsxs("form",{onSubmit:H,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(n.Label,{htmlFor:"name",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Name"}),e.jsx(n.Input,{id:"name",placeholder:"e.g. T-Shirts",value:v,onChange:L,disabled:d,className:"h-8 text-sm",required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(n.Label,{htmlFor:"slug",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none flex items-center justify-between w-full",children:[e.jsx("span",{children:"Slug"}),!g&&!h&&e.jsx("span",{className:"text-[10px] text-amber-600 dark:text-amber-400 capitalize",children:"Auto-generating"})]}),e.jsx(n.Input,{id:"slug",placeholder:"e.g. t-shirts",value:N,onChange:z,disabled:d,className:"h-8 text-sm font-mono"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(n.Label,{htmlFor:"description",className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Description"}),e.jsx(n.Textarea,{id:"description",placeholder:"Optional description of the category...",value:R,onChange:p=>b(p.target.value),disabled:d,className:"text-sm min-h-[90px] resize-none"})]}),D.length>0&&e.jsxs("div",{className:"border-t border-border/50 pt-4 mt-4 space-y-4",children:[e.jsx("h3",{className:"text-xs uppercase font-bold text-muted-foreground tracking-wider",children:"Translations"}),D.map(p=>e.jsxs("div",{className:"space-y-3 p-3 rounded-md bg-muted/30 border border-border/30",children:[e.jsx("span",{className:"text-[11px] font-bold text-amber-600 dark:text-amber-400 uppercase tracking-wider",children:p.name}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(n.Label,{htmlFor:`name-${p.code}`,className:"text-[10px] uppercase font-bold text-muted-foreground tracking-wider leading-none",children:["Name (",p.code,")"]}),e.jsx(n.Input,{id:`name-${p.code}`,placeholder:`Translation for ${v||"Name"}`,value:S[p.code]||"",onChange:P=>E(M=>({...M,[p.code]:P.target.value})),disabled:d,className:"h-8 text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(n.Label,{htmlFor:`desc-${p.code}`,className:"text-[10px] uppercase font-bold text-muted-foreground tracking-wider leading-none",children:["Description (",p.code,")"]}),e.jsx(n.Textarea,{id:`desc-${p.code}`,placeholder:"Translation for Description",value:F[p.code]||"",onChange:P=>_(M=>({...M,[p.code]:P.target.value})),disabled:d,className:"text-sm min-h-[60px] resize-none"})]})]},p.code))]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx(n.Button,{type:"submit",disabled:d,size:"sm",className:"flex-1 bg-amber-600 hover:bg-amber-500 text-white font-medium shadow-md shadow-amber-600/10 h-8 text-xs cursor-pointer",children:d?e.jsxs(e.Fragment,{children:[e.jsx(A.Loader2,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}),"Saving..."]}):h?"Update Category":"Create Category"}),h&&e.jsx(n.Button,{type:"button",onClick:T,disabled:d,variant:"outline",size:"sm",className:"h-8 text-xs border-dashed cursor-pointer",children:"Cancel"})]})]})]})}),e.jsx("div",{className:"md:col-span-8",children:e.jsxs(n.Card,{className:"p-4 shadow-lg bg-card/65 backdrop-blur-md border border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 pb-2 border-b border-border/50",children:[e.jsx(A.FolderKanban,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-bold tracking-tight",children:"Active Categories"}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-none mt-0.5",children:"Categories are shared globally across languages."})]})]}),l.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center border-2 border-dashed border-border/60 rounded-lg bg-muted/20 animate-in fade-in duration-300",children:[e.jsx(A.HelpCircle,{className:"h-10 w-10 text-muted-foreground/50 mb-3"}),e.jsx("h3",{className:"text-sm font-bold text-muted-foreground",children:"No Categories Found"}),e.jsx("p",{className:"text-xs text-muted-foreground/80 max-w-sm mt-1",children:"Add your first category using the form on the left to start organizing your catalog products."})]}):e.jsx("div",{className:"overflow-x-auto border rounded-lg bg-background/50",children:e.jsxs("table",{className:"w-full text-left border-collapse text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/40 font-bold uppercase tracking-wider text-muted-foreground/85 select-none",children:[e.jsx("th",{className:"p-3 pl-4",children:"Name"}),e.jsx("th",{className:"p-3",children:"Slug"}),e.jsx("th",{className:"p-3 text-center",children:"Products"}),e.jsx("th",{className:"p-3 pr-4 text-right",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-border/60",children:l.map(p=>e.jsxs("tr",{className:"hover:bg-muted/10 transition-colors group",children:[e.jsxs("td",{className:"p-3 pl-4",children:[e.jsx("div",{className:"font-semibold text-slate-800 dark:text-slate-100",children:p.name}),p.description&&e.jsx("div",{className:"text-[10px] text-muted-foreground mt-0.5 max-w-xs truncate leading-normal",title:p.description,children:p.description})]}),e.jsx("td",{className:"p-3",children:e.jsxs("code",{className:"px-1.5 py-0.5 rounded bg-muted/65 font-mono text-[10px]",children:["/",p.slug]})}),e.jsx("td",{className:"p-3 text-center",children:e.jsx("span",{className:"inline-flex items-center justify-center px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-500/10 text-amber-800 dark:text-amber-300 border border-amber-500/15",children:p.productCount})}),e.jsx("td",{className:"p-3 pr-4 text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[e.jsx(n.Button,{variant:"outline",size:"icon",disabled:d,onClick:()=>ee(p),className:"h-7 w-7 opacity-85 hover:opacity-100 group-hover:border-amber-500/30 cursor-pointer",title:"Edit Category",children:e.jsx(A.Edit2,{className:"h-3.5 w-3.5 text-muted-foreground group-hover:text-amber-600 dark:group-hover:text-amber-400"})}),e.jsx(n.Button,{variant:"outline",size:"icon",disabled:d,onClick:()=>G(p),className:"h-7 w-7 opacity-85 hover:opacity-100 group-hover:border-red-500/30 cursor-pointer",title:"Delete Category",children:e.jsx(A.Trash2,{className:"h-3.5 w-3.5 text-muted-foreground group-hover:text-red-500"})})]})})]},p.id))})]})})]})})]})}async function ks(){const[t,r]=await Promise.all([o.getCategoriesWithCount(),K.getActiveLanguagesServerSide()]);return e.jsxs("div",{className:"space-y-8 w-full max-w-[1200px] mx-auto px-6 py-8",children:[e.jsx("div",{className:"flex flex-wrap items-center justify-between gap-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(n.Button,{variant:"outline",size:"icon",asChild:!0,children:e.jsx(J,{href:"/cms/products",children:e.jsx(A.ArrowLeft,{className:"h-4 w-4"})})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Category Management"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create and manage product categories for organizing your e-commerce catalog."})]})]})}),e.jsx(Ss,{initialCategories:t,createCategory:o.createCategoryAction,updateCategory:o.updateCategoryAction,deleteCategory:o.deleteCategoryAction,languages:r})]})}async function Ft(t){const r=await K.createClient(),{data:{user:s}}=await r.auth.getUser();if(!s)throw new Error("Unauthorized");const{data:a}=await r.from("profiles").select("role").eq("id",s.id).single();if(!a||a.role!=="ADMIN")throw new Error("Forbidden");const{error:i}=await r.from("site_settings").upsert({key:"enabled_payment_providers",value:t});if(i)throw console.error("Error updating payment providers:",i),new Error("Failed to update settings");return Q.revalidatePath("/cms/payments"),Q.revalidatePath("/cms/taxes"),Q.revalidatePath("/","layout"),{success:!0}}function Es({initialEnabledProviders:t,configStatus:r,saveAction:s}){const[a,i]=y.useState(t),c=r?.stripe?.hasKeys,l=r?.freemius?.hasKeys;return e.jsxs("form",{action:s,className:"space-y-6 max-w-3xl p-8",children:[e.jsx("input",{type:"hidden",name:"stripe_enabled",value:a.stripe?"true":"false"}),e.jsx("input",{type:"hidden",name:"freemius_enabled",value:a.freemius?"true":"false"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Payment Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Enable the payment providers your store needs. Physical products use Stripe and digital products use Freemius."})]}),e.jsxs(n.Card,{children:[e.jsxs(n.CardHeader,{children:[e.jsx(n.CardTitle,{children:"Payment Providers"}),e.jsx(n.CardDescription,{children:"You can run both providers at the same time. Each product picks its provider from its product type."})]}),e.jsxs(n.CardContent,{className:"space-y-6",children:[e.jsx(st,{id:"stripe-enabled",label:"Stripe for Physical Products",description:"Use Stripe Checkout for physical merchandise and other shippable goods.",checked:a.stripe,disabled:!c,onCheckedChange:u=>i(d=>({...d,stripe:u})),ready:c,children:c?e.jsxs("div",{className:"mt-2 text-sm text-green-600 flex items-center gap-2",children:[e.jsx(A.CheckCircle2,{className:"w-4 h-4"}),e.jsx("span",{children:"Ready to process physical product checkout"})]}):e.jsx(at,{provider:"Stripe",missingKeys:r.stripe.missing,docsUrl:"https://dashboard.stripe.com/apikeys",docsLabel:"Stripe Dashboard -> Developers -> API Keys"})}),e.jsx(st,{id:"freemius-enabled",label:"Freemius for Digital Products",description:"Use Freemius for software licenses, SaaS plans, and other digital products.",checked:a.freemius,disabled:!l,onCheckedChange:u=>i(d=>({...d,freemius:u})),ready:l,children:l?e.jsxs("div",{className:"mt-2 text-sm text-green-600 flex items-center gap-2",children:[e.jsx(A.CheckCircle2,{className:"w-4 h-4"}),e.jsx("span",{children:"Ready to process digital product checkout"})]}):e.jsx(at,{provider:"Freemius",missingKeys:r.freemius.missing,docsUrl:"https://dashboard.freemius.com/",docsLabel:"Freemius Dashboard -> Developers -> Credentials"})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(Ts,{})})]})]})]})}function Ts(){const{pending:t}=ir.useFormStatus();return e.jsx(n.Button,{type:"submit",disabled:t,children:t?"Saving...":"Save Changes"})}function st({id:t,label:r,description:s,checked:a,disabled:i,ready:c,onCheckedChange:l,children:u}){return e.jsx("div",{className:"rounded-md border p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(n.Checkbox,{id:t,checked:a,disabled:i,onCheckedChange:d=>l(!!d),className:"mt-1"}),e.jsxs("div",{className:"grid gap-1.5 leading-none w-full",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx(n.Label,{htmlFor:t,className:"font-semibold text-base cursor-pointer",children:r}),e.jsx("span",{className:`text-xs font-medium ${a?"text-foreground":"text-muted-foreground"}`,children:a?"Enabled":"Disabled"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s}),!c&&e.jsx("p",{className:"text-xs text-amber-700",children:"This provider cannot be enabled until all required environment variables are present."}),u]})]})})}function at({provider:t,missingKeys:r,docsUrl:s,docsLabel:a}){return e.jsxs("div",{className:"mt-3 text-sm p-4 rounded-md border border-destructive/20 bg-destructive/5 text-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2 font-semibold text-destructive mb-2",children:[e.jsx(A.AlertCircle,{className:"w-4 h-4"}),e.jsx("span",{children:"Configuration Required"})]}),e.jsxs("p",{className:"mb-2",children:["The ",t," integration is missing the following environment variables:"]}),e.jsx("ul",{className:"list-disc list-inside bg-white/50 dark:bg-black/20 p-2 rounded mb-3 font-mono text-xs",children:r.map(i=>e.jsx("li",{children:i},i))}),e.jsx("p",{className:"mb-2",children:e.jsx("strong",{children:"How to fix:"})}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 ml-1 mb-3",children:[e.jsxs("li",{children:["Go to"," ",e.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"underline font-medium hover:text-destructive/80",children:a}),"."]}),e.jsx("li",{children:"Copy your API keys."}),e.jsxs("li",{children:["Open your ",e.jsx("code",{children:".env"})," (or variables settings in Vercel/Railway)."]}),e.jsx("li",{children:"Add the keys listed above."}),e.jsx("li",{children:"Restart your development server."})]})]})}async function Ps(){const[t,r]=await Promise.all([ye(),Re()]);async function s(a){"use server";const i={stripe:a.get("stripe_enabled")==="true"&&r.stripe.hasKeys,freemius:a.get("freemius_enabled")==="true"&&r.freemius.hasKeys};await Ft(i)}return e.jsx(Es,{initialEnabledProviders:t,configStatus:r,saveAction:s})}function Ut(t){return Object.entries(t||{}).reduce((r,[s,a])=>{const i=s.trim().toLowerCase(),c=a.trim();return i&&c&&(r[i]=c),r},{})}async function Lt(t){const r=K.createClient(),{data:{user:s}}=await r.auth.getUser();if(!s)throw new Error("Unauthorized");const{data:a}=await r.from("profiles").select("role").eq("id",s.id).single();if(!a||a.role!=="ADMIN")throw new Error("Forbidden");const i=t.getAll("trackQuantities").includes("true"),c=await o.getEcommerceInventorySettings(r),{error:l}=await o.upsertEcommerceInventorySettings(r,{trackQuantities:i,enableTaxes:c.enableTaxes,taxCalculationMode:c.taxCalculationMode});if(l)throw new Error(l.message);Q.revalidatePath("/cms/shipping"),ae.redirect("/cms/shipping?success=Inventory settings updated")}function Mt(t){const r=new Map;for(const s of t){const a=o.normalizeCountryCode(s.country_code);if(!a)continue;const i=o.normalizeSubdivisionCode(a,s.state_code)||null,c=`${a}:${i??"*"}`;r.set(c,{country_code:a,state_code:i})}return[...r.values()]}async function Ot(t){const{data:r,error:s}=await t.from("currencies").select("code, is_default").eq("is_active",!0).order("is_default",{ascending:!1}).order("code",{ascending:!0});return s?{error:s.message}:{currencies:r||[]}}async function Dt(t,r,s){const a=K.getServiceRoleSupabaseClient(),i=Mt(s),{data:c,error:l}=await a.from("shipping_zones").insert({name:t,priority_order:r}).select().single();if(l||!c)return{error:l?.message||"Failed to create zone"};if(i.length>0){const u=i.map(m=>({zone_id:c.id,country_code:m.country_code,state_code:m.state_code??null})),{error:d}=await a.from("shipping_zone_locations").insert(u);if(d)return{error:d.message}}return Q.revalidatePath("/cms/shipping"),{success:!0}}async function Bt(t,r,s,a){const i=K.getServiceRoleSupabaseClient(),c=Mt(a),{error:l}=await i.from("shipping_zones").update({name:r,priority_order:s,updated_at:new Date().toISOString()}).eq("id",t);if(l)return{error:l.message||"Failed to update zone"};const{error:u}=await i.from("shipping_zone_locations").delete().eq("zone_id",t);if(u)return{error:"Failed to refresh locations"};if(c.length>0){const d=c.map(h=>({zone_id:t,country_code:h.country_code,state_code:h.state_code??null})),{error:m}=await i.from("shipping_zone_locations").insert(d);if(m)return{error:m.message}}return Q.revalidatePath("/cms/shipping"),{success:!0}}async function $t(t){const r=K.getServiceRoleSupabaseClient(),{error:s}=await r.from("shipping_zones").delete().eq("id",t);return s?{error:s.message}:(Q.revalidatePath("/cms/shipping"),{success:!0})}async function zt(t,r){const s=K.getServiceRoleSupabaseClient(),a=await Ot(s);if("error"in a)return{error:a.error};const i=o.sanitizeShippingRateAmountMaps({currencies:a.currencies.map(l=>o.normalizeCurrencyRecord(l)),mode:r.currencyPricingMode,sourceCurrencyCode:r.sourceCurrencyCode,costAmounts:r.costAmounts,minOrderAmounts:r.minOrderAmounts,fallbackCostAmount:r.cost,fallbackMinOrderAmount:r.minOrderAmount}),{error:c}=await s.from("shipping_zone_methods").insert({zone_id:t,name:r.name.trim(),name_translations:Ut(r.nameTranslations),method_type:r.type,currency_pricing_mode:i.mode,cost_amount:i.costAmounts[i.sourceCurrencyCode],cost_amounts:i.costAmounts,cost_currency:i.sourceCurrencyCode,min_order_amount:i.minOrderAmounts[i.sourceCurrencyCode],min_order_amounts:i.minOrderAmounts});return c?{error:c.message}:(Q.revalidatePath("/cms/shipping"),{success:!0})}async function qt(t,r){const s=K.getServiceRoleSupabaseClient(),a=await Ot(s);if("error"in a)return{error:a.error};const i=o.sanitizeShippingRateAmountMaps({currencies:a.currencies.map(l=>o.normalizeCurrencyRecord(l)),mode:r.currencyPricingMode,sourceCurrencyCode:r.sourceCurrencyCode,costAmounts:r.costAmounts,minOrderAmounts:r.minOrderAmounts,fallbackCostAmount:r.cost,fallbackMinOrderAmount:r.minOrderAmount}),{error:c}=await s.from("shipping_zone_methods").update({name:r.name.trim(),name_translations:Ut(r.nameTranslations),method_type:r.type,currency_pricing_mode:i.mode,cost_amount:i.costAmounts[i.sourceCurrencyCode],cost_amounts:i.costAmounts,cost_currency:i.sourceCurrencyCode,min_order_amount:i.minOrderAmounts[i.sourceCurrencyCode],min_order_amounts:i.minOrderAmounts,updated_at:new Date().toISOString()}).eq("id",t);return c?{error:c.message}:(Q.revalidatePath("/cms/shipping"),{success:!0})}async function Kt(t){const r=K.getServiceRoleSupabaseClient(),{error:s}=await r.from("shipping_zone_methods").delete().eq("id",t);return s?{error:s.message}:(Q.revalidatePath("/cms/shipping"),{success:!0})}function nt(t=[]){return[...new Set(t.map(r=>r.country_code))]}function it(t=[]){return t.reduce((r,s)=>{if(!s.state_code)return r;const a=new Set(r[s.country_code]||[]);return a.add(s.state_code),r[s.country_code]=[...a],r},{})}function As(t,r){return t.flatMap(s=>{const a=r[s]||[];return a.length===0?[{country_code:s,state_code:null}]:a.map(i=>({country_code:s,state_code:i}))})}function ot({mode:t="create",initialData:r}){const[s,a]=y.useState(!1),i=t==="edit",[c,l]=y.useState(r?.name||""),[u,d]=y.useState(r?.priority_order||0),[m,h]=y.useState(nt(r?.locations)),[x,v]=y.useState(it(r?.locations)),[f,N]=y.useState(""),[k,R]=y.useState(!1);y.useEffect(()=>{s&&(l(r?.name||""),d(r?.priority_order||0),h(nt(r?.locations)),v(it(r?.locations)),N(""))},[r,s]);const b=y.useMemo(()=>{const g=f.trim().toLowerCase();return g?o.countries.filter(j=>j.name.toLowerCase().includes(g)||j.code.toLowerCase().includes(g)):o.countries},[f]),S=y.useMemo(()=>o.countries.filter(g=>m.includes(g.code)),[m]),E=g=>{h(j=>j.includes(g)?j.filter(D=>D!==g):[...j,g]),v(j=>{if(j[g]){const D={...j};return delete D[g],D}return j})},F=(g,j)=>{v(D=>{const B=new Set(D[g]||[]);return B.has(j)?B.delete(j):B.add(j),{...D,[g]:[...B]}})},_=async g=>{if(g.preventDefault(),!c||m.length===0)return;R(!0);const j=As(m,x),D=i&&r?.id?await Bt(r.id,c,u,j):await Dt(c,u,j);R(!1),D.success?(a(!1),i||(l(""),d(0),h([]),v({}),N(""))):D.error&&alert(D.error)};return e.jsxs(n.Dialog,{open:s,onOpenChange:a,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:i?e.jsx(n.Button,{variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-primary",children:e.jsx(A.Edit2,{className:"h-4 w-4"})}):e.jsxs(n.Button,{className:"gap-2 shadow-sm",children:[e.jsx(A.Plus,{className:"h-4 w-4"}),"New Zone"]})}),e.jsx(n.DialogContent,{className:"max-w-4xl max-h-[90vh] flex flex-col overflow-hidden",children:e.jsxs("form",{onSubmit:_,className:"flex h-full flex-col overflow-hidden",children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:i?"Edit Shipping Zone":"Create Shipping Zone"}),e.jsx(n.DialogDescription,{children:"Select countries first, then optionally limit a zone to specific states or provinces. Leaving state selections empty keeps the whole country in the zone."})]}),e.jsxs("div",{className:"grid gap-6 overflow-y-auto py-6 pr-2",children:[e.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[e.jsx(n.Label,{htmlFor:"name",className:"text-right",children:"Zone Name"}),e.jsx(n.Input,{id:"name",value:c,onChange:g=>l(g.target.value),placeholder:"e.g. North America, Canada East, US West",className:"col-span-3",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[e.jsx(n.Label,{htmlFor:"priority",className:"text-right",children:"Priority Order"}),e.jsx(n.Input,{id:"priority",type:"number",value:u,onChange:g=>d(Number(g.target.value)),className:"col-span-3"})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1.2fr_1fr]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-end justify-between gap-3",children:[e.jsxs(n.Label,{className:"text-sm font-semibold",children:["Countries (",m.length,")"]}),e.jsxs("div",{className:"relative w-full max-w-xs",children:[e.jsx(A.Search,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-slate-400"}),e.jsx(n.Input,{placeholder:"Search countries...",className:"pl-9 h-9",value:f,onChange:g=>N(g.target.value)})]})]}),e.jsx(n.Card,{className:"border-slate-200 bg-slate-50/30 p-4 dark:border-slate-800 dark:bg-slate-900/30",children:e.jsx("div",{className:"grid max-h-[360px] grid-cols-1 gap-3 overflow-y-auto pr-1 sm:grid-cols-2",children:b.map(g=>{const j=m.includes(g.code);return e.jsxs("div",{className:`flex items-center space-x-2 rounded-md border p-2 transition-colors ${j?"border-primary/30 bg-primary/5 text-primary":"border-transparent hover:bg-slate-100 dark:hover:bg-slate-800/60"}`,children:[e.jsx(n.Checkbox,{id:`country-${g.code}`,checked:j,onCheckedChange:()=>E(g.code)}),e.jsxs("label",{htmlFor:`country-${g.code}`,className:"flex-1 cursor-pointer text-xs py-1",children:[g.name," (",g.code,")"]})]},g.code)})})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A.MapPin,{className:"h-4 w-4 text-slate-500"}),e.jsx(n.Label,{className:"text-sm font-semibold",children:"States / Provinces"})]}),S.length===0?e.jsx(n.Card,{className:"border-dashed p-4 text-sm text-muted-foreground",children:"Select one or more countries to optionally narrow the zone to specific states or provinces."}):e.jsx("div",{className:"space-y-4",children:S.map(g=>{const j=o.getStatesForCountry(g.code),D=x[g.code]||[];return e.jsx(n.Card,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[g.name," (",g.code,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j.length>0?"Leave all unchecked to apply this zone to the whole country.":"This country uses a country-level zone in the current UI."})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:D.length>0?`${D.length} selected`:"Whole country"})]}),j.length>0?e.jsx("div",{className:"grid max-h-[220px] grid-cols-1 gap-2 overflow-y-auto pr-1 sm:grid-cols-2",children:j.map(B=>{const L=D.includes(B.code);return e.jsxs("div",{className:`flex items-center space-x-2 rounded-md border p-2 transition-colors ${L?"border-primary/30 bg-primary/5 text-primary":"border-transparent hover:bg-slate-50 dark:hover:bg-slate-800/60"}`,children:[e.jsx(n.Checkbox,{id:`${g.code}-${B.code}`,checked:L,onCheckedChange:()=>F(g.code,B.code)}),e.jsxs("label",{htmlFor:`${g.code}-${B.code}`,className:"flex-1 cursor-pointer text-xs py-1",children:[B.name," (",B.code,")"]})]},`${g.code}-${B.code}`)})}):null]})},g.code)})})]})]})]}),e.jsxs(n.DialogFooter,{className:"mt-auto border-t pt-4",children:[e.jsx(n.Button,{type:"button",variant:"ghost",onClick:()=>a(!1),children:"Cancel"}),e.jsx(n.Button,{type:"submit",disabled:k||!c||m.length===0,children:k?i?"Updating...":"Creating...":i?"Save Changes":"Create Zone"})]})]})})]})}function je(t,r){if(typeof t!="number")return"";const s=$.minorUnitAmountToMajor(t,r);return $.getCurrencyMinorUnitFactor(r)===1?s.toFixed(0):s.toFixed(2)}function Is(t){return t.reduce((r,s)=>(r[s.code]=$.getCurrencyMinorUnitFactor(s.code)===1?"0":"0.00",r),{})}function fe(t,r){const s=String(t||"").trim();if(!s)return null;const a=Number(s);return!Number.isFinite(a)||a<0?null:$.majorUnitAmountToMinor(a,r)}function ct(t){return t.currencies.reduce((r,s)=>(r[s.code]=je(t.amounts[s.code],s.code),r),{})}function lt({zoneId:t,zoneName:r,languages:s,currencies:a=[],defaultCurrencyCode:i="USD",mode:c="create",initialData:l}){const[u,d]=y.useState(!1),m=c==="edit",h=y.useMemo(()=>s.find(C=>C.is_default)||s[0]||null,[s]),x=y.useMemo(()=>s.filter(C=>!C.is_default),[s]),v=$.normalizeCurrencyCode(i),f=y.useMemo(()=>{const C=o.normalizeCurrencyRecord({code:v,symbol:v,exchange_rate:1,is_default:!0,is_active:!0}),O=(a.length>0?a:[C]).map(I=>o.normalizeCurrencyRecord(I)).filter(I=>I.is_active!==!1).sort((I,q)=>I.is_default!==q.is_default?I.is_default?-1:1:I.code.localeCompare(q.code));return O.length>0?O:[C]},[a,v]),N=y.useMemo(()=>f.find(C=>C.is_default)||f[0],[f]),[k,R]=y.useState(l?.name||""),[b,S]=y.useState(l?.name_translations||{}),[E,F]=y.useState(l?.method_type||"flat_rate"),[_,g]=y.useState(o.normalizeShippingRateCurrencyMode(l?.currency_pricing_mode)),[j,D]=y.useState($.normalizeCurrencyCode(l?.cost_currency||N?.code||v)),[B,L]=y.useState({}),[z,ee]=y.useState({}),[T,H]=y.useState(!1),G=y.useMemo(()=>{if(_==="manual")return f.reduce((I,q)=>(I[q.code]=B[q.code]??"",I),{});const C=f.reduce((I,q)=>(I[q.code]=B[q.code]??(q.code===j,""),I),{}),O=fe(B[j],j);if(O===null)return C;for(const I of f){if(I.code===j){C[I.code]=B[I.code]??je(O,I.code);continue}C[I.code]=je(o.convertMinorUnitAmount({amount:O,fromCurrencyCode:j,toCurrencyCode:I.code,currencies:f}),I.code)}return C},[f,B,_,j]),p=y.useMemo(()=>{if(_==="manual")return f.reduce((I,q)=>(I[q.code]=z[q.code]??"",I),{});const C=f.reduce((I,q)=>(I[q.code]=z[q.code]??"",I),{}),O=fe(z[j],j);if(O===null)return C;for(const I of f){if(I.code===j){C[I.code]=z[I.code]??je(O,I.code);continue}C[I.code]=je(o.convertMinorUnitAmount({amount:O,fromCurrencyCode:j,toCurrencyCode:I.code,currencies:f}),I.code)}return C},[f,z,_,j]);y.useEffect(()=>{N&&(f.some(C=>C.code===j)||D(N.code))},[f,N,j]),y.useEffect(()=>{if(!u||!N)return;const C=o.normalizeShippingRateCurrencyMode(l?.currency_pricing_mode),O=o.sanitizeShippingRateAmountMaps({currencies:f,mode:C,sourceCurrencyCode:l?.cost_currency||N.code,costAmounts:l?.cost_amounts||void 0,minOrderAmounts:l?.min_order_amounts||void 0,fallbackCostAmount:l?.cost_amount,fallbackMinOrderAmount:l?.min_order_amount});R(l?.name||""),S(l?.name_translations||{}),F(l?.method_type||"flat_rate"),g(C),D(O.sourceCurrencyCode),L(ct({amounts:O.costAmounts,currencies:f})),ee(ct({amounts:O.minOrderAmounts,currencies:f}))},[f,N,l,u]);const P=C=>{C!==_&&(C==="manual"&&(L(G),ee(p)),g(C))},M=C=>{const O=$.normalizeCurrencyCode(C);L(I=>({...I,[O]:G[O]??I[O]??""})),ee(I=>({...I,[O]:p[O]??I[O]??""})),D(O)},W=C=>{F(C),C==="free_shipping"&&L(Is(f))},se=async C=>{C.preventDefault(),H(!0);const O={},I={};if(_==="manual")for(const Z of f){const ie=Z.code;if(E==="free_shipping")O[ie]=0;else{const Ne=fe(B[ie],ie);if(Ne===null){H(!1),alert(`Enter a valid shipping cost for ${ie}.`);return}O[ie]=Ne}I[ie]=fe(z[ie],ie)??0}else{const Z=E==="free_shipping"?0:fe(B[j],j);if(Z===null){H(!1),alert(`Enter a valid shipping cost for ${j}.`);return}O[j]=Z,I[j]=fe(z[j],j)??0}const q={name:k,nameTranslations:b,type:E,currencyPricingMode:_,sourceCurrencyCode:j,costAmounts:O,minOrderAmounts:I},re=m&&l?.id?await qt(l.id,q):await zt(t,q);H(!1),re.success?d(!1):re.error&&alert(re.error)};return e.jsxs(n.Dialog,{open:u,onOpenChange:d,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:m?e.jsx(n.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-primary",children:e.jsx(A.Edit2,{className:"h-3 w-3"})}):e.jsxs(n.Button,{variant:"outline",size:"sm",className:"h-8 gap-1.5 border-dashed hover:border-solid shadow-sm",children:[e.jsx(A.Plus,{className:"h-3.5 w-3.5"}),"Add Rate"]})}),e.jsx(n.DialogContent,{className:"max-h-[85vh] max-w-4xl overflow-y-auto",children:e.jsxs("form",{onSubmit:se,children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:m?"Edit Shipping Rate":"Add Shipping Rate"}),e.jsxs(n.DialogDescription,{children:["Configure shipping costs and localized labels for matching orders in ",e.jsx("strong",{children:r}),"."]})]}),e.jsxs("div",{className:"grid gap-5 py-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(n.Label,{htmlFor:"rate-name",children:["Rate Name",h?` (${h.name})`:""]}),e.jsx(n.Input,{id:"rate-name",value:k,onChange:C=>R(C.target.value),placeholder:"e.g. Standard, Express, Free Shipping",required:!0})]}),x.length>0&&e.jsxs("div",{className:"space-y-4 rounded-xl border bg-slate-50/70 p-4 dark:bg-slate-900/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A.Languages,{className:"h-4 w-4 text-slate-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Translations"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add translated shipping rate labels for the active storefront languages."})]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:x.map(C=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:`rate-name-${C.code}`,children:C.name}),e.jsx(n.Input,{id:`rate-name-${C.code}`,value:b[C.code]||"",onChange:O=>S(I=>({...I,[C.code]:O.target.value})),placeholder:k||"Translated label"})]},C.code))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"type",children:"Method Type"}),e.jsxs(n.Select,{value:E,onValueChange:W,children:[e.jsx(n.SelectTrigger,{id:"type",className:"bg-slate-50/50 dark:bg-slate-900/50",children:e.jsx(n.SelectValue,{placeholder:"Select type"})}),e.jsxs(n.SelectContent,{children:[e.jsx(n.SelectItem,{value:"flat_rate",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-1 min-w-5 h-5 rounded bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600",children:e.jsx(A.DollarSign,{className:"h-3 w-3"})}),e.jsx("span",{children:"Flat Rate"})]})}),e.jsx(n.SelectItem,{value:"free_shipping",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-1 min-w-5 h-5 rounded bg-amber-100 dark:bg-amber-900/30 text-amber-600",children:e.jsx(A.Gift,{className:"h-3 w-3"})}),e.jsx("span",{children:"Free Shipping"})]})})]})]})]}),e.jsxs("div",{className:"space-y-3 rounded-xl border bg-slate-50/70 p-4 dark:bg-slate-900/40",children:[e.jsxs("label",{className:"flex items-start gap-3",children:[e.jsx("input",{type:"checkbox",checked:_==="auto",onChange:C=>P(C.target.checked?"auto":"manual"),className:"mt-1 h-4 w-4 rounded border-slate-300 text-primary focus:ring-primary"}),e.jsxs("span",{className:"space-y-1",children:[e.jsx("span",{className:"block text-sm font-medium text-slate-900 dark:text-slate-100",children:"Auto-sync all currency rates from one source amount"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Turn this off to set exact shipping costs and free-shipping thresholds for every active currency manually."})]})]}),_==="auto"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"rate-currency",children:"Sync From Currency"}),e.jsxs(n.Select,{value:j,onValueChange:M,children:[e.jsx(n.SelectTrigger,{id:"rate-currency",className:"bg-background",children:e.jsx(n.SelectValue,{placeholder:"Select currency"})}),e.jsx(n.SelectContent,{children:f.map(C=>e.jsxs(n.SelectItem,{value:C.code,children:[C.code,C.is_default?" (Default)":""]},C.code))})]}),e.jsx("p",{className:"text-[10px] text-slate-500",children:"Enter the source amount once and the other currencies will be derived automatically using the current FX rates."})]}):e.jsx("p",{className:"text-[10px] text-slate-500",children:"Manual mode stores exact values per currency. This is the best choice when shipping should not follow exchange-rate math directly."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Currency Rates"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:E==="free_shipping"?"Free-shipping methods keep cost at zero, but you can still control the threshold per currency.":_==="auto"?`Only ${j} is editable. The rest are derived automatically.`:"Set the exact shopper-facing shipping price for each active currency."})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:f.map(C=>{const O=_==="auto"&&C.code!==j,I=$.getCurrencyMinorUnitFactor(C.code)===1?"1":"0.01";return e.jsxs("div",{className:"space-y-4 rounded-xl border bg-card/70 p-4 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.code}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Rate ",C.exchange_rate]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[C.is_default?e.jsx(n.Badge,{variant:"outline",children:"Default"}):null,_==="auto"&&C.code===j?e.jsx(n.Badge,{children:"Source"}):null,O?e.jsx(n.Badge,{variant:"outline",children:"Derived"}):null]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(n.Label,{htmlFor:`rate-cost-${C.code}`,children:["Cost (",C.code,")"]}),e.jsxs("div",{className:"relative",children:[e.jsx(A.DollarSign,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-slate-400"}),e.jsx(n.Input,{id:`rate-cost-${C.code}`,type:"number",step:I,min:"0",value:G[C.code]??"",onChange:q=>L(re=>({...re,[C.code]:q.target.value})),className:"pl-9 bg-slate-50/50 dark:bg-slate-900/50 disabled:opacity-70",disabled:E==="free_shipping"||O,required:E!=="free_shipping"&&_==="manual"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(n.Label,{htmlFor:`rate-threshold-${C.code}`,children:["Free-Shipping Threshold (",C.code,")"]}),e.jsxs("div",{className:"relative",children:[e.jsx(A.DollarSign,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-slate-400"}),e.jsx(n.Input,{id:`rate-threshold-${C.code}`,type:"number",step:I,min:"0",value:p[C.code]??"",onChange:q=>ee(re=>({...re,[C.code]:q.target.value})),className:"pl-9 bg-slate-50/50 dark:bg-slate-900/50 disabled:opacity-70",disabled:O,placeholder:$.getCurrencyMinorUnitFactor(C.code)===1?"0":"0.00"})]})]}),O?e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["This currency is synced automatically from ",j,"."]}):_==="manual"?e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Enter the exact amount shoppers should see in this currency."}):null]},C.code)})})]})]}),e.jsxs(n.DialogFooter,{className:"bg-slate-50 dark:bg-slate-900/50 -mx-6 -mb-6 p-4 border-t dark:border-slate-800",children:[e.jsx(n.Button,{type:"button",variant:"ghost",onClick:()=>d(!1),disabled:T,children:"Cancel"}),e.jsx(n.Button,{type:"submit",disabled:T||!k.trim(),children:T?m?"Saving...":"Adding...":m?"Save Changes":"Add Rate"})]})]})})]})}async function Rs({searchParams:t}){const r=K.getServiceRoleSupabaseClient(),[{data:s},a,{data:i},{data:c}]=await Promise.all([r.from("shipping_zones").select(`
103
+ *,
104
+ shipping_zone_locations (*),
105
+ shipping_zone_methods (*)
106
+ `).order("priority_order",{ascending:!0}),o.getEcommerceInventorySettings(r),r.from("languages").select("code, name, is_default").eq("is_active",!0).order("name",{ascending:!0}),r.from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("is_default",{ascending:!1}).order("code",{ascending:!0})]),l=c?.find(d=>d.is_default)?.code||c?.[0]?.code||"USD",u=(c||[]).map(d=>o.normalizeCurrencyRecord(d));return e.jsx(n.TooltipProvider,{children:e.jsxs("div",{className:"space-y-6",children:[t?.success?e.jsx("div",{className:"rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700",children:t.success}):null,e.jsx(n.Card,{className:"overflow-hidden border-slate-200 dark:border-slate-800 shadow-sm",children:e.jsx(n.CardContent,{className:"p-4 sm:p-5",children:e.jsxs("form",{action:Lt,className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg text-primary shadow-inner shrink-0",children:e.jsx(A.Boxes,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(n.CardTitle,{className:"text-base font-semibold leading-none",children:"Inventory Tracking"}),e.jsx(n.CardDescription,{className:"mt-1 text-sm",children:"Control whether checkout enforces stock counts and paid orders deduct inventory."})]})]}),e.jsx("div",{className:"flex justify-end lg:justify-start shrink-0",children:e.jsx(n.Button,{type:"submit",size:"sm",className:"w-full sm:w-auto",children:"Save Inventory Settings"})})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-4 py-3",children:[e.jsx("input",{type:"hidden",name:"trackQuantities",value:"false"}),e.jsxs("label",{htmlFor:"track-quantities",className:"flex cursor-pointer items-start gap-3",children:[e.jsx("input",{id:"track-quantities",name:"trackQuantities",type:"checkbox",value:"true",defaultChecked:a.trackQuantities,className:"mt-0.5 h-4 w-4 rounded border-slate-300 text-primary focus:ring-primary"}),e.jsxs("span",{className:"space-y-0.5",children:[e.jsx("span",{className:"block text-sm font-medium text-slate-900 dark:text-slate-100",children:"Track product quantities"}),e.jsx("span",{className:"block text-sm text-muted-foreground",children:"Prevent overselling by checking stock during checkout and decrementing quantities after payment is confirmed."})]})]})]})]})})}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight text-slate-900 dark:text-slate-100",children:"Shipping Zones"}),e.jsx("p",{className:"text-slate-500 dark:text-slate-400 text-sm",children:"Manage geographical delivery areas and their associated shipping rates."})]}),e.jsx(ot,{})]}),e.jsx("div",{className:"grid gap-6",children:!s||s.length===0?e.jsx(n.Card,{className:"bg-slate-50/50 dark:bg-slate-900/10 border-dashed",children:e.jsxs(n.CardContent,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(A.Truck,{className:"h-12 w-12 text-slate-300 dark:text-slate-700 mb-4"}),e.jsx("p",{className:"text-slate-600 dark:text-slate-400 font-medium",children:"No shipping zones defined yet."}),e.jsx("p",{className:"text-xs text-slate-500 mb-6 text-center max-w-xs",children:"Create a zone to start defining shipping rates for specific regions (e.g., North America, Europe)."})]})}):s.map(d=>e.jsxs(n.Card,{className:"overflow-hidden border-slate-200 dark:border-slate-800 shadow-sm hover:shadow-md transition-shadow",children:[e.jsx(n.CardHeader,{className:"bg-slate-50/50 dark:bg-slate-900/50 border-b dark:border-slate-800 py-4",children:e.jsxs("div",{className:"flex justify-between items-start md:items-center",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg text-primary shadow-inner",children:e.jsx(A.Globe,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.CardTitle,{className:"text-lg font-bold",children:d.name}),e.jsxs(n.Badge,{variant:"outline",className:"text-[10px] uppercase font-bold py-0 h-4 border-slate-200 bg-white/50 dark:bg-black/20",children:["Prio: ",d.priority_order]})]}),e.jsxs(n.CardDescription,{className:"text-xs",children:[d.shipping_zone_locations?.length||0," regions covered"]})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(ot,{mode:"edit",initialData:{id:d.id,name:d.name,priority_order:d.priority_order,locations:d.shipping_zone_locations?.map(m=>({country_code:m.country_code,state_code:m.state_code}))||[]}}),e.jsx("form",{action:async()=>{"use server";await $t(d.id)},children:e.jsx(n.Button,{type:"submit",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20",children:e.jsx(A.Trash2,{className:"h-4 w-4"})})})]})]})}),e.jsx(n.CardContent,{className:"p-0",children:e.jsxs("div",{className:"grid md:grid-cols-2 divide-y md:divide-y-0 md:divide-x divide-slate-100 dark:divide-slate-800",children:[e.jsxs("div",{className:"p-6",children:[e.jsxs("h4",{className:"text-[10px] font-bold uppercase tracking-widest text-slate-500 mb-4 flex items-center gap-1.5",children:[e.jsx(A.Globe,{className:"h-3 w-3"})," Target Regions"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:d.shipping_zone_locations?.length>0?d.shipping_zone_locations.map(m=>e.jsxs(n.Badge,{variant:"secondary",className:"bg-slate-100 dark:bg-slate-800/80 text-slate-700 dark:text-slate-300 hover:bg-slate-200 border-none px-2 py-0.5 text-[11px] font-medium",children:[m.country_code,m.state_code?e.jsxs("span",{className:"text-slate-400 ml-1",children:["(",o.resolveSubdivisionName(m.country_code,m.state_code),")"]}):""]},m.id)):e.jsx("p",{className:"text-sm text-slate-400 italic",children:"No specific locations assigned."})})]}),e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("h4",{className:"text-[10px] font-bold uppercase tracking-widest text-slate-500 flex items-center gap-1.5",children:[e.jsx(A.Truck,{className:"h-3 w-3"})," Shipping Methods"]}),e.jsx(lt,{zoneId:d.id,zoneName:d.name,languages:i||[],currencies:u,defaultCurrencyCode:l})]}),e.jsx("div",{className:"space-y-2",children:d.shipping_zone_methods?.length>0?d.shipping_zone_methods.map(m=>e.jsxs("div",{className:"flex justify-between items-center group p-2 hover:bg-slate-50/80 dark:hover:bg-slate-800/30 rounded-lg transition-all border border-transparent hover:border-slate-100 dark:hover:border-slate-800",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-900 dark:text-slate-100 truncate",children:m.name}),e.jsx(n.Badge,{variant:"outline",className:"h-4 px-1 text-[9px]",children:m.currency_pricing_mode==="manual"?"Manual FX":"Auto FX"}),(m.min_order_amount||0)>0&&e.jsxs(n.Tooltip,{children:[e.jsx(n.TooltipTrigger,{asChild:!0,children:e.jsxs(n.Badge,{variant:"outline",className:"h-4 px-1 text-[9px] bg-emerald-50 text-emerald-700 dark:bg-emerald-900/20 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/50",children:[e.jsx(A.Info,{className:"h-2 w-2 mr-0.5"}),$.formatPrice(m.min_order_amount,m.cost_currency?.toUpperCase()||l)]})}),e.jsxs(n.TooltipContent,{children:["Available for orders over ",$.formatPrice(m.min_order_amount,m.cost_currency?.toUpperCase()||l)]})]})]}),e.jsx("p",{className:"text-[10px] text-slate-500 uppercase tracking-tighter mix-blend-multiply dark:mix-blend-normal",children:m.method_type.replace("_"," ")})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("p",{className:"text-sm font-black text-primary px-2",children:m.method_type==="free_shipping"?"FREE":$.formatPrice(m.cost_amount,m.cost_currency?.toUpperCase()||l)}),e.jsxs("div",{className:"flex opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(lt,{zoneId:d.id,zoneName:d.name,languages:i||[],currencies:u,defaultCurrencyCode:l,mode:"edit",initialData:m}),e.jsx("form",{action:async()=>{"use server";await Kt(m.id)},children:e.jsx(n.Button,{type:"submit",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-red-500",children:e.jsx(A.Trash2,{className:"h-3 w-3"})})})]})]})]},m.id)):e.jsx("p",{className:"text-xs text-slate-400 italic",children:"No methods defined for this zone."})})]})]})})]},d.id))})]})})}async function $e(){const t=K.createClient(),{data:{user:r}}=await t.auth.getUser();if(!r)throw new Error("Unauthorized");const{data:s}=await t.from("profiles").select("role").eq("id",r.id).single();if(!s||s.role!=="ADMIN")throw new Error("Forbidden");return t}async function Vt(t){const r=await $e(),s=await o.getEcommerceInventorySettings(r),a=t.getAll("enableTaxes").includes("true"),i=t.get("taxCalculationMode")==="automatic"?"automatic":"manual",{error:c}=await o.upsertEcommerceInventorySettings(r,{trackQuantities:s.trackQuantities,enableTaxes:a,taxCalculationMode:i});if(c)throw new Error(c.message);Q.revalidatePath("/cms/shipping"),Q.revalidatePath("/cms/settings/taxes"),ae.redirect("/cms/settings/taxes?success=Tax settings updated")}async function Ht(t){const r=await $e(),s=String(t.get("id")||"").trim(),a=o.normalizeCountryCode(String(t.get("country_code")||"").trim()),i=String(t.get("state_code")||"").trim(),c=String(t.get("tax_name")||"").trim(),l=Number(t.get("tax_rate"));if(!a)throw new Error("Country code is required.");if(!c)throw new Error("Tax name is required.");if(!Number.isFinite(l)||l<0||l>100)throw new Error("Tax rate must be between 0 and 100.");const u={country_code:a,state_code:o.normalizeSubdivisionCode(a,i)||null,tax_name:c,tax_rate:l},d=s?r.from("tax_rates").update(u).eq("id",s):r.from("tax_rates").insert(u),{error:m}=await d;if(m)throw new Error(m.message);Q.revalidatePath("/cms/settings/taxes")}async function Gt(t){const r=await $e(),{error:s}=await r.from("tax_rates").delete().eq("id",t);if(s)throw new Error(s.message);Q.revalidatePath("/cms/settings/taxes")}function dt({initialData:t,submitLabel:r="Save tax rate",compact:s=!1}){const a=o.normalizeCountryCode(t?.country_code)||"US",[i,c]=y.useState(a),[l,u]=y.useState(o.normalizeSubdivisionCode(a,t?.state_code)||t?.state_code||""),d=y.useMemo(()=>o.getStatesForCountry(i),[i]),m=o.countryUsesStructuredStates(i);return e.jsxs("form",{action:Ht,className:"space-y-4",children:[t?.id?e.jsx("input",{type:"hidden",name:"id",value:t.id}):null,e.jsxs("div",{className:s?"grid gap-4 md:grid-cols-4":"grid gap-4 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:t?.id?`country-${t.id}`:"tax-rate-country",children:"Country"}),e.jsx("select",{id:t?.id?`country-${t.id}`:"tax-rate-country",name:"country_code",value:i,onChange:h=>{const x=h.target.value,v=o.getStatesForCountry(x);c(x),u(v.some(f=>f.code===l)?l:"")},className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:o.countries.map(h=>e.jsx("option",{value:h.code,children:h.name},h.code))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:t?.id?`state-${t.id}`:"tax-rate-state",children:"State / Province"}),m?e.jsxs("select",{id:t?.id?`state-${t.id}`:"tax-rate-state",name:"state_code",value:l,onChange:h=>u(h.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:[e.jsx("option",{value:"",children:"Country-wide / federal"}),d.map(h=>e.jsx("option",{value:h.code,children:h.name},h.code))]}):e.jsx(n.Input,{id:t?.id?`state-${t.id}`:"tax-rate-state",name:"state_code",value:l,onChange:h=>u(h.target.value),placeholder:"Optional"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:t?.id?`name-${t.id}`:"tax-rate-name",children:"Tax name"}),e.jsx(n.Input,{id:t?.id?`name-${t.id}`:"tax-rate-name",name:"tax_name",defaultValue:t?.tax_name||"",placeholder:"GST, PST, State Sales Tax",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:t?.id?`rate-${t.id}`:"tax-rate-rate",children:"Rate (%)"}),e.jsx(n.Input,{id:t?.id?`rate-${t.id}`:"tax-rate-rate",name:"tax_rate",type:"number",min:"0",max:"100",step:"0.0001",defaultValue:typeof t?.tax_rate=="number"?t.tax_rate.toString():"",placeholder:"5.0000",required:!0})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(n.Button,{type:"submit",size:s?"sm":"default",children:r})})]})}function Fs(t){return`${t.toFixed(4).replace(/\.?0+$/,"")}%`}function Us(t){return t.state_code?`${t.country_code} - ${o.resolveSubdivisionName(t.country_code,t.state_code)}`:`${t.country_code} - Country-wide`}async function Ls({searchParams:t}){const r=K.createClient(),s=K.getServiceRoleSupabaseClient(),[a,i,c]=await Promise.all([o.getEcommerceInventorySettings(r),ye(),s.from("tax_rates").select("id, country_code, state_code, tax_name, tax_rate, created_at, updated_at").order("country_code").order("state_code").order("tax_name")]),l=c.data||[],u=c.error,d=i.stripe;return e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 px-6 py-8",children:[t?.success?e.jsx("div",{className:"rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700",children:t.success}):null,e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(n.Button,{asChild:!0,variant:"outline",size:"icon","aria-label":"Back to shipping",children:e.jsx(J,{href:"/cms/shipping",children:e.jsx(A.ArrowLeft,{className:"h-4 w-4"})})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Tax Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure Stripe tax behavior globally and maintain manual country or state/province tax rates for physical goods."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(n.Badge,{variant:d?"default":"outline",className:"uppercase",children:["Stripe ",d?"Enabled":"Disabled"]}),e.jsx("div",{className:"rounded-full border bg-muted/30 p-3 text-muted-foreground",children:e.jsx(A.Settings2,{className:"h-5 w-5"})})]})]}),d?e.jsxs(e.Fragment,{children:[e.jsxs(n.Card,{children:[e.jsxs(n.CardHeader,{children:[e.jsx(n.CardTitle,{children:"Global Tax Controls"}),e.jsx(n.CardDescription,{children:"Manual mode uses the tax rates below. Automatic mode uses Stripe Tax during Stripe Checkout instead of a free third-party tax API."})]}),e.jsx(n.CardContent,{children:e.jsxs("form",{action:Vt,className:"space-y-6",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-4",children:[e.jsx("input",{type:"hidden",name:"enableTaxes",value:"false"}),e.jsxs("label",{htmlFor:"enable-taxes",className:"flex cursor-pointer items-start gap-3",children:[e.jsx("input",{id:"enable-taxes",name:"enableTaxes",type:"checkbox",value:"true",defaultChecked:a.enableTaxes,className:"mt-1 h-4 w-4 rounded border-slate-300 text-primary focus:ring-primary"}),e.jsxs("span",{className:"space-y-1",children:[e.jsx("span",{className:"block font-medium",children:"Enable taxes"}),e.jsx("span",{className:"block text-sm text-muted-foreground",children:"When disabled, tax totals resolve to zero even if product or jurisdiction records exist."})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-[minmax(0,1fr)_auto] md:items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"tax-calculation-mode",className:"text-sm font-medium text-foreground",children:"Tax calculation mode"}),e.jsxs("select",{id:"tax-calculation-mode",name:"taxCalculationMode",defaultValue:a.taxCalculationMode,className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:[e.jsx("option",{value:"manual",children:"Manual tax rates"}),e.jsx("option",{value:"automatic",children:"Automatic via Stripe Tax"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatic mode depends on your Stripe Tax setup. Manual rates stay saved and can be used again if you switch back later."})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(n.Button,{type:"submit",children:"Save Tax Settings"})})]})]})})]}),e.jsxs(n.Card,{children:[e.jsx(n.CardHeader,{children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(n.CardTitle,{children:"Manual Tax Rates"}),e.jsx(n.CardDescription,{children:"Add combined taxes as separate rows. For example, create both GST and PST for the same province if they should stack."})]}),e.jsx(n.Badge,{variant:a.taxCalculationMode==="manual"?"default":"outline",children:a.taxCalculationMode==="manual"?"Active Mode":"Stored for Manual Mode"})]})}),e.jsxs(n.CardContent,{className:"space-y-6",children:[u?e.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:"Tax rates couldn't be loaded yet. This usually means the new tax migration hasn't been applied to the current database."}):null,u?null:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center gap-2",children:[e.jsx(A.ShieldCheck,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"font-semibold",children:"Create a Tax Rate"})]}),e.jsx(dt,{})]}),e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed bg-muted/10 px-4 py-8 text-center",children:[e.jsx("p",{className:"font-medium",children:"No manual tax rates yet"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Add country-wide or state/province-specific rows to start calculating manual taxes."})]}):l.map(m=>e.jsxs(n.Card,{className:"border-muted",children:[e.jsx(n.CardHeader,{className:"pb-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(n.CardTitle,{className:"text-base",children:m.tax_name}),e.jsx(n.CardDescription,{children:Us(m)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"outline",children:Fs(Number(m.tax_rate))}),e.jsx("form",{action:async()=>{"use server";await Gt(m.id)},children:e.jsx(n.Button,{type:"submit",variant:"ghost",size:"icon","aria-label":"Delete tax rate",children:e.jsx(A.Trash2,{className:"h-4 w-4"})})})]})]})}),e.jsx(n.CardContent,{children:e.jsx(dt,{initialData:m,submitLabel:"Update tax rate",compact:!0})})]},m.id))})]})]})]})]}):e.jsxs(n.Card,{className:"border-dashed",children:[e.jsxs(n.CardHeader,{children:[e.jsx(n.CardTitle,{children:"Enable Stripe to configure physical-product taxes"}),e.jsx(n.CardDescription,{children:"Stripe tax settings apply whenever Stripe is enabled for physical products. Freemius still handles taxes on its own digital checkout flow."})]}),e.jsx(n.CardContent,{children:e.jsx(n.Button,{asChild:!0,variant:"outline",children:e.jsx(J,{href:"/cms/payments",children:"Open Payment Settings"})})})]})]})}async function we(){const t=K.createClient(),{data:{user:r}}=await t.auth.getUser();if(!r)throw new Error("Unauthorized");const{data:s}=await t.from("profiles").select("role").eq("id",r.id).single();if(s?.role!=="ADMIN")throw new Error("Forbidden");return K.getServiceRoleSupabaseClient()}function oe(t){return(typeof t=="string"?t.trim():"")||null}function ut(t){const r=oe(t);if(!r)return null;const s=new Date(r);return Number.isNaN(s.getTime())?null:s.toISOString()}function Ms(t){const r=oe(t.value),s=r?Number.parseFloat(r):Number.NaN;if(!Number.isFinite(s)||s<=0)throw new Error("Discount amount must be greater than zero.");return t.discountType==="fixed"?$.majorUnitAmountToMinor(s,t.currencyCode):Math.round(s)}function Os(t,r){return t.getAll(r).some(s=>s==="true")}function Wt(t){const r=o.normalizeCouponCode(oe(t.get("code"))),s=oe(t.get("name")),a=oe(t.get("provider_scope"))||"all",i=oe(t.get("discount_type"))||"percent",c=$.normalizeCurrencyCode(oe(t.get("currency_code"))),l=Ms({value:t.get("discount_amount"),discountType:i,currencyCode:c}),u=oe(t.get("redemption_limit"));if(!r)throw new Error("Coupon code is required.");if(!s)throw new Error("Coupon name is required.");if(i==="percent"&&l>100)throw new Error("Percent discounts cannot exceed 100.");return{coupon:{code:r,name:s,internal_note:oe(t.get("internal_note")),provider_scope:a,discount_type:i,discount_amount:l,is_active:Os(t,"is_active"),starts_at:ut(t.get("starts_at")),ends_at:ut(t.get("ends_at")),redemption_limit:u?Number.parseInt(u,10):null,freemius_sync_status:a==="stripe"?"not_required":"pending",freemius_sync_error:null},productIds:t.getAll("product_ids").map(d=>typeof d=="string"?d.trim():"").filter(Boolean)}}async function Qt(t){if(await t.client.from("coupon_products").delete().eq("coupon_id",t.couponId),t.productIds.length===0)return;const{error:r}=await t.client.from("coupon_products").insert(t.productIds.map(s=>({coupon_id:t.couponId,product_id:s})));if(r)throw new Error(r.message)}async function Ds(t){const r=await we(),s=Wt(t),{data:a,error:i}=await r.from("coupons").insert(s.coupon).select("id").single();if(i||!a)throw new Error(i?.message||"Failed to create coupon.");await Qt({client:r,couponId:a.id,productIds:s.productIds}),await o.syncCouponToFreemius({couponId:a.id,client:r}),Q.revalidatePath("/cms/coupons"),ae.redirect("/cms/coupons")}async function Bs(t,r){const s=await we(),a=Wt(r),{error:i}=await s.from("coupons").update(a.coupon).eq("id",t);if(i)throw new Error(i.message);await Qt({client:s,couponId:t,productIds:a.productIds}),a.coupon.provider_scope==="stripe"?await o.deleteCouponFromFreemius({couponId:t,client:s}):await o.syncCouponToFreemius({couponId:t,client:s}),Q.revalidatePath("/cms/coupons"),Q.revalidatePath(`/cms/coupons/${t}/edit`),ae.redirect("/cms/coupons")}async function $s(t,r){const s=await we(),{error:a}=await s.from("coupons").update({is_active:r,freemius_sync_status:"pending",updated_at:new Date().toISOString()}).eq("id",t);if(a)throw new Error(a.message);await o.syncCouponToFreemius({couponId:t,client:s}),Q.revalidatePath("/cms/coupons")}async function zs(t){const r=await we();await o.syncCouponToFreemius({couponId:t,client:r}),Q.revalidatePath("/cms/coupons"),Q.revalidatePath(`/cms/coupons/${t}/edit`)}async function qs(t){const r=await we();await o.deleteCouponFromFreemius({couponId:t,client:r});const{error:s}=await r.from("coupons").delete().eq("id",t);if(s)throw new Error(s.message);Q.revalidatePath("/cms/coupons")}function Ks(t){const r=t.sku?.trim();return r?r.toUpperCase():`PRODUCT:${t.id}`}function Vs(t){const r=new Map;for(const s of t){const a=Ks(s),i=r.get(a);if(i){i.productIds.push(s.id);continue}r.set(a,{key:a,title:s.title,sku:s.sku?.trim()||"No SKU",thumbnailUrl:s.thumbnailUrl??null,productIds:[s.id]})}return[...r.values()]}function Hs({products:t,selectedProductIds:r=[]}){const s=y.useMemo(()=>new Set(r),[r]),[a,i]=y.useState(s),[c,l]=y.useState(""),u=y.useMemo(()=>Vs(t),[t]),d=y.useMemo(()=>{const h=c.trim().toLowerCase();return h?u.filter(x=>[x.title,x.sku].some(v=>v.toLowerCase().includes(h))):u},[u,c]),m=h=>{i(new Set(t.filter(x=>x.payment_provider===h).map(x=>x.id)))};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ee.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>i(new Set(t.map(h=>h.id))),children:"Select All"}),e.jsx(Ee.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>m("stripe"),children:"Stripe"}),e.jsx(Ee.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>m("freemius"),children:"Freemius"})]}),e.jsxs("div",{className:"relative",children:[e.jsx(A.Search,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(or.Input,{type:"search",value:c,onChange:h=>l(h.target.value),placeholder:"Search products by title or SKU",className:"pl-9"})]}),e.jsxs("div",{className:"grid max-h-[420px] gap-2 overflow-y-auto rounded-lg border p-3 md:grid-cols-2",children:[d.map(h=>{const x=h.productIds.some(v=>a.has(v));return e.jsxs("label",{className:"flex cursor-pointer items-center gap-3 rounded-md px-2 py-2 hover:bg-muted/40",children:[e.jsx("input",{type:"checkbox",checked:x,onChange:v=>{const f=new Set(a);for(const N of h.productIds)v.target.checked?f.add(N):f.delete(N);i(f)},className:"mt-0.5 h-4 w-4 rounded border-slate-300 text-primary focus:ring-primary"}),x?h.productIds.map(v=>e.jsx("input",{type:"hidden",name:"product_ids",value:v},v)):null,e.jsx("span",{className:"flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-md border bg-muted",children:h.thumbnailUrl?e.jsx("img",{src:h.thumbnailUrl,alt:"",loading:"lazy",className:"h-full w-full object-cover"}):e.jsx(A.ImageIcon,{className:"h-5 w-5 text-muted-foreground","aria-hidden":"true"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block whitespace-normal break-words text-sm font-medium",children:h.title}),e.jsx("span",{className:"block font-mono text-xs text-muted-foreground",children:h.sku})]})]},h.key)}),d.length===0?e.jsx("div",{className:"px-2 py-8 text-center text-sm text-muted-foreground md:col-span-2",children:"No matching products."}):null]})]})}function mt(t){if(!t)return"";const r=new Date(t);return Number.isNaN(r.getTime())?"":r.toISOString().slice(0,16)}function Gs(t,r){const s=$.getCurrencyMinorUnitFactor(r)===1?0:2;return t.toFixed(s)}function Ws(t,r){return t?.discount_amount?t.discount_type==="fixed"?Gs($.minorUnitAmountToMajor(t.discount_amount,r),r):t.discount_amount:10}function Xt({action:t,products:r,coupon:s,selectedProductIds:a=[],submitLabel:i,currencyCode:c="USD"}){return e.jsxs("form",{action:t,children:[e.jsx("input",{type:"hidden",name:"currency_code",value:c}),e.jsxs(n.Card,{children:[e.jsx(n.CardHeader,{children:e.jsx(n.CardTitle,{children:s?.id?"Edit Coupon":"Create Coupon"})}),e.jsxs(n.CardContent,{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"coupon-code",children:"Code"}),e.jsx(n.Input,{id:"coupon-code",name:"code",defaultValue:s?.code||"",className:"uppercase",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"coupon-name",children:"Name"}),e.jsx(n.Input,{id:"coupon-name",name:"name",defaultValue:s?.name||"",required:!0})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"provider-scope",children:"Provider scope"}),e.jsxs("select",{id:"provider-scope",name:"provider_scope",defaultValue:s?.provider_scope||"all",className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:[e.jsx("option",{value:"all",children:"Stripe + Freemius"}),e.jsx("option",{value:"stripe",children:"Stripe only"}),e.jsx("option",{value:"freemius",children:"Freemius only"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"discount-type",children:"Discount type"}),e.jsxs("select",{id:"discount-type",name:"discount_type",defaultValue:s?.discount_type||"percent",className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:[e.jsx("option",{value:"percent",children:"Percent"}),e.jsx("option",{value:"fixed",children:"Fixed amount"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"discount-amount",children:"Amount"}),e.jsx(n.Input,{id:"discount-amount",name:"discount_amount",type:"number",min:"0.01",step:"0.01",defaultValue:Ws(s,c),required:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Percent coupons use 1-100. Fixed coupons use regular amounts, for example $10.00."})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"starts-at",children:"Starts at"}),e.jsx(n.Input,{id:"starts-at",name:"starts_at",type:"datetime-local",defaultValue:mt(s?.starts_at)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"ends-at",children:"Ends at"}),e.jsx(n.Input,{id:"ends-at",name:"ends_at",type:"datetime-local",defaultValue:mt(s?.ends_at)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"redemption-limit",children:"Redemption limit"}),e.jsx(n.Input,{id:"redemption-limit",name:"redemption_limit",type:"number",min:"1",defaultValue:s?.redemption_limit||""})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"internal-note",children:"Internal note"}),e.jsx(n.Textarea,{id:"internal-note",name:"internal_note",defaultValue:s?.internal_note||"",rows:3})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-4",children:[e.jsx("input",{type:"hidden",name:"is_active",value:"false"}),e.jsxs("label",{htmlFor:"coupon-active",className:"flex cursor-pointer items-start gap-3",children:[e.jsx("input",{id:"coupon-active",name:"is_active",type:"checkbox",value:"true",defaultChecked:s?.is_active??!0,className:"mt-0.5 h-4 w-4 rounded border-slate-300 text-primary focus:ring-primary"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-medium",children:"Active"}),e.jsx("span",{className:"block text-sm text-muted-foreground",children:"Active coupons can be applied by shoppers during cart and checkout."})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Product scope"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Leave every product unchecked to apply this coupon to all products in the selected provider scope."})]}),e.jsx(Hs,{products:r,selectedProductIds:a})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(n.Button,{type:"submit",children:i})})]})]})]})}function Qs({action:t,products:r,currencyCode:s}){const[a,i]=y.useState(!1);return e.jsxs(ve.Dialog,{open:a,onOpenChange:i,children:[e.jsx(ve.DialogTrigger,{asChild:!0,children:e.jsxs(Ee.Button,{type:"button",className:"gap-2",children:[e.jsx(A.Plus,{className:"h-4 w-4"}),"Create Coupon"]})}),e.jsxs(ve.DialogContent,{className:"max-h-[90vh] overflow-y-auto sm:max-w-[92vw] lg:max-w-5xl xl:max-w-6xl",children:[e.jsx(ve.DialogHeader,{children:e.jsx(ve.DialogTitle,{className:"sr-only",children:"Create Coupon"})}),e.jsx(Xt,{action:t,products:r,submitLabel:"Create Coupon",currencyCode:s})]})]})}function Xs(t){return Array.isArray(t)?t[0]??null:t??null}const pt=process.env.NEXT_PUBLIC_R2_BASE_URL||"";function Ys(t){return t?t.startsWith("http")||!pt?t:`${pt.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`:null}function Zs(t){const r=Array.isArray(t.product_media)?[...t.product_media].sort((a,i)=>(a.sort_order??0)-(i.sort_order??0)):[],s=r[0]?.media?.file_path||r[0]?.media?.object_key||null;return Ys(s)}function Yt(t){return(t||[]).map(r=>({id:r.id,title:r.title,sku:r.sku??null,payment_provider:r.payment_provider||"stripe",freemius_product_id:r.freemius_product_id??null,thumbnailUrl:Zs(r),language:Xs(r.language)}))}function Js(t,r){return t.discount_type==="percent"?`${t.discount_amount}%`:$.formatPrice(t.discount_amount,r)}function ea(t,r){return r?t==="synced"||t==="not_required"?"default":"secondary":"outline"}function ta(t,r){const s=new Set;for(const a of t||[]){const i=a.product_id;i&&s.add(r.get(i)||i)}return s.size}function ra(t,r){const s=ta(t,r);return s===0?"All eligible products":`${s} scoped SKU${s===1?"":"s"}`}async function sa({searchParams:t}){const r=K.getServiceRoleSupabaseClient();let s=r.from("coupons").select(`
107
+ *,
108
+ coupon_products(product_id),
109
+ coupon_freemius_mappings(sync_status, sync_error)
110
+ `).order("created_at",{ascending:!1});t?.q&&(s=s.or(`code.ilike.%${t.q}%,name.ilike.%${t.q}%`)),t?.status==="active"?s=s.eq("is_active",!0):t?.status==="inactive"&&(s=s.eq("is_active",!1));const[{data:a},{data:i},{data:c}]=await Promise.all([s,r.from("products").select("id, title, sku, payment_provider, freemius_product_id, language:languages(code, name), product_media(sort_order, media(file_path, object_key))").order("title",{ascending:!0}),r.from("currencies").select("code, is_default").eq("is_active",!0)]),l=c?.find(d=>d.is_default)?.code||c?.[0]?.code||"USD",u=new Map((i||[]).map(d=>[d.id,d.sku?.trim().toUpperCase()||d.id]));return e.jsxs("div",{className:"mx-auto w-full max-w-7xl space-y-6 px-6 py-8",children:[e.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-end md:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Coupons"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create provider-aware discounts for Stripe checkout and Freemius licenses."})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs("form",{className:"flex gap-2",action:"/cms/coupons",children:[e.jsx("input",{name:"q",placeholder:"Search coupons",defaultValue:t?.q||"",className:"h-10 rounded-md border border-input bg-background px-3 py-2 text-sm"}),e.jsxs("select",{name:"status",defaultValue:t?.status||"all",className:"h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",children:[e.jsx("option",{value:"all",children:"All"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Inactive"})]}),e.jsx(n.Button,{type:"submit",variant:"outline",children:"Filter"})]}),e.jsx(Qs,{action:Ds,products:Yt(i),currencyCode:l})]})]}),e.jsxs(n.Card,{children:[e.jsxs(n.CardHeader,{children:[e.jsx(n.CardTitle,{children:"All Coupons"}),e.jsx(n.CardDescription,{children:"Freemius sync runs when a coupon is created, updated, toggled, or manually resynced."})]}),e.jsx(n.CardContent,{children:e.jsx("div",{className:"overflow-hidden rounded-lg border",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"border-b bg-muted/40 text-xs uppercase text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"Code"}),e.jsx("th",{className:"px-4 py-3",children:"Scope"}),e.jsx("th",{className:"px-4 py-3",children:"Discount"}),e.jsx("th",{className:"px-4 py-3",children:"Usage"}),e.jsx("th",{className:"px-4 py-3",children:"Sync"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y",children:a?.length?a.map(d=>e.jsxs("tr",{className:"align-top",children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:d.code}),e.jsx(n.Badge,{variant:d.is_active?"default":"outline",children:d.is_active?"Active":"Inactive"})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:d.name})]}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("span",{className:"capitalize",children:d.provider_scope}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:ra(d.coupon_products,u)})]}),e.jsx("td",{className:"px-4 py-3 font-medium",children:Js(d,l)}),e.jsxs("td",{className:"px-4 py-3",children:[d.redemptions_count||0,d.redemption_limit?` / ${d.redemption_limit}`:""]}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx(n.Badge,{variant:ea(d.freemius_sync_status,d.is_active),children:d.freemius_sync_status}),d.freemius_sync_error?e.jsx("p",{className:"mt-1 max-w-[220px] text-xs text-destructive",children:d.freemius_sync_error}):null]}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(n.Button,{asChild:!0,variant:"outline",size:"sm",children:e.jsx(J,{href:`/cms/coupons/${d.id}/edit`,children:"Edit"})}),e.jsx("form",{action:async()=>{"use server";await $s(d.id,!d.is_active)},children:e.jsx(n.Button,{type:"submit",variant:"outline",size:"sm",children:d.is_active?"Disable":"Enable"})}),e.jsx("form",{action:async()=>{"use server";await zs(d.id)},children:e.jsx(n.Button,{type:"submit",variant:"ghost",size:"icon",title:"Resync Freemius","aria-label":`Resync Freemius coupon ${d.code}`,children:e.jsx(A.RefreshCw,{className:"h-4 w-4"})})}),e.jsx("form",{action:async()=>{"use server";await qs(d.id)},children:e.jsx(n.Button,{type:"submit",variant:"ghost",size:"icon",className:"text-destructive","aria-label":`Delete coupon ${d.code}`,children:e.jsx(A.Trash2,{className:"h-4 w-4"})})})]})})]},d.id)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-10 text-center text-muted-foreground",children:"No coupons yet."})})})]})})})]})]})}async function aa({params:t}){const{id:r}=await t,s=K.getServiceRoleSupabaseClient(),[{data:a},{data:i},{data:c},{data:l}]=await Promise.all([s.from("coupons").select("*").eq("id",r).single(),s.from("products").select("id, title, sku, payment_provider, freemius_product_id, language:languages(code, name), product_media(sort_order, media(file_path, object_key))").order("title",{ascending:!0}),s.from("coupon_products").select("product_id").eq("coupon_id",r),s.from("currencies").select("code, is_default").eq("is_active",!0)]);a||ae.notFound();const u=(c||[]).map(m=>m.product_id),d=l?.find(m=>m.is_default)?.code||l?.[0]?.code||"USD";return e.jsxs("div",{className:"mx-auto w-full max-w-5xl space-y-6 px-6 py-8",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Edit Coupon"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Changes are resynced to Freemius after saving."})]}),e.jsx(n.Button,{asChild:!0,variant:"outline",children:e.jsx(J,{href:"/cms/coupons",children:"Back to coupons"})})]}),e.jsx(Xt,{action:Bs.bind(null,r),products:Yt(i),coupon:a,selectedProductIds:u,submitLabel:"Save Coupon",currencyCode:d})]})}exports.CURRENCY_COOKIE_NAME=o.CURRENCY_COOKIE_NAME;exports.CURRENCY_ROUNDING_MODES=o.CURRENCY_ROUNDING_MODES;exports.DEFAULT_INVOICE_SETTINGS=o.DEFAULT_INVOICE_SETTINGS;exports.FreemiusProvider=o.FreemiusProvider;exports.INVOICE_SETTINGS_KEY=o.INVOICE_SETTINGS_KEY;exports.addressesMatch=o.addressesMatch;exports.aggregateOrderTaxLines=o.aggregateOrderTaxLines;exports.applyCurrencyRounding=o.applyCurrencyRounding;exports.buildOrderTaxDetailsFromCalculation=o.buildOrderTaxDetailsFromCalculation;exports.buildOrderTaxDetailsFromStripeSession=o.buildOrderTaxDetailsFromStripeSession;exports.convertMinorUnitAmount=o.convertMinorUnitAmount;exports.copyProductFromLanguage=o.copyProductFromLanguage;exports.createCategoryAction=o.createCategoryAction;exports.createProduct=o.createProduct;exports.createProductAction=o.createProductAction;exports.deleteCategoryAction=o.deleteCategoryAction;exports.deleteCouponFromFreemius=o.deleteCouponFromFreemius;exports.deleteProduct=o.deleteProduct;exports.deleteProductAction=o.deleteProductAction;exports.describeCurrencyRoundingRule=o.describeCurrencyRoundingRule;exports.emptyCustomerAddress=o.emptyCustomerAddress;exports.fetchTranslatedProductsForCartInternal=o.fetchTranslatedProductsForCartInternal;exports.fillMissingUserProfileCheckoutDetails=o.fillMissingUserProfileCheckoutDetails;exports.formatInvoiceCurrency=o.formatInvoiceCurrency;exports.formatInvoiceDate=o.formatInvoiceDate;exports.getCategoriesWithCount=o.getCategoriesWithCount;exports.getCategoryBySlug=o.getCategoryBySlug;exports.getCmsProduct=o.getProduct;exports.getCmsProducts=o.getProducts;exports.getCouponQuote=o.getCouponQuote;exports.getCurrencyLookup=o.getCurrencyLookup;exports.getDefaultCurrency=o.getDefaultCurrency;exports.getDefaultUserAddresses=o.getDefaultUserAddresses;exports.getExchangeRateForCurrency=o.getExchangeRateForCurrency;exports.getGlobalProductAttributes=o.getGlobalProductAttributes;exports.getInvoiceAddressLines=o.getInvoiceAddressLines;exports.getOrderTaxRateJurisdiction=o.getOrderTaxRateJurisdiction;exports.getOrderTaxRateLabel=o.getOrderTaxRateLabel;exports.getOrderTaxRatePercentage=o.getOrderTaxRatePercentage;exports.getProduct=o.getProduct$1;exports.getProductBySlug=o.getProductBySlug;exports.getProductCategories=o.getProductCategories;exports.getProductTranslations=o.getProductTranslations;exports.getProducts=o.getProducts$1;exports.getQuoteLineDiscountMap=o.getQuoteLineDiscountMap;exports.inferCurrencyCodeFromLocale=o.inferCurrencyCodeFromLocale;exports.isCustomerAddressComplete=o.isCustomerAddressComplete;exports.isSaleWindowActive=o.isSaleWindowActive;exports.isScheduledPriceDue=o.isScheduledPriceDue;exports.normalizeCurrencyRecord=o.normalizeCurrencyRecord;exports.normalizeCurrencyRoundingMode=o.normalizeCurrencyRoundingMode;exports.normalizeCustomerAddress=o.normalizeCustomerAddress;exports.normalizeInvoiceSettings=o.normalizeInvoiceSettings;exports.normalizeOrderCustomerDetails=o.normalizeOrderCustomerDetails;exports.normalizeOrderTaxDetails=o.normalizeOrderTaxDetails;exports.normalizePriceMap=o.normalizePriceMap;exports.normalizeSalePriceMap=o.normalizeSalePriceMap;exports.parseFreemiusCheckoutCredentialsMap=o.parseFreemiusCheckoutCredentialsMap;exports.productSchema=o.productSchema;exports.readFreemiusEnvValue=o.readFreemiusEnvValue;exports.recordCouponRedemption=o.recordCouponRedemption;exports.resolveEffectivePriceForCurrency=o.resolveEffectivePriceForCurrency;exports.resolveFreemiusCheckoutCredentials=o.resolveFreemiusCheckoutCredentials;exports.resolvePriceForCurrency=o.resolvePriceForCurrency;exports.resolvePriceRangeForCurrency=o.resolvePriceRangeForCurrency;exports.serializeInvoiceSettings=o.serializeInvoiceSettings;exports.sortCurrencies=o.sortCurrencies;exports.syncCategoriesForTranslationGroup=o.syncCategoriesForTranslationGroup;exports.syncCouponToFreemius=o.syncCouponToFreemius;exports.syncFreemiusProductsToSupabase=o.syncFreemiusProductsToSupabase;exports.syncProductCategoriesAction=o.syncProductCategoriesAction;exports.syncProductSaleCouponToFreemius=o.syncProductSaleCouponToFreemius;exports.syncSingleFreemiusProduct=o.syncSingleFreemiusProduct;exports.updateCategoryAction=o.updateCategoryAction;exports.updateProduct=o.updateProduct;exports.updateProductAction=o.updateProductAction;exports.upsertDefaultUserAddresses=o.upsertDefaultUserAddresses;exports.AttributeManagementPage=bs;exports.CategoryManagementPage=ks;exports.CopyProductFromLanguage=Ns;exports.CouponsPage=sa;exports.EditCouponPage=aa;exports.EditProductPage=ws;exports.ExportReportsDialog=It;exports.InventoryPage=ys;exports.NewProductPage=vs;exports.OrderDetailPage=ss;exports.OrdersPage=Qr;exports.PaymentsPage=Ps;exports.ProductsPage=cs;exports.ShippingPage=Rs;exports.StripeProvider=bt;exports.TaxesPage=Ls;exports.applyOrderInventoryDeduction=Pe;exports.assignInvoiceMetadata=Ie;exports.clearAutoSyncedCurrencyPriceOverrides=Er;exports.createCheckoutSession=cr;exports.createShippingRate=zt;exports.createShippingZone=Dt;exports.deleteShippingRate=Kt;exports.deleteShippingZone=$t;exports.deleteTaxRateAction=Gt;exports.extractFreemiusCheckoutMetadata=vt;exports.fetchOrderReportData=At;exports.getCurrentCustomerOrder=yt;exports.getCurrentCustomerOrderInvoice=_r;exports.getCurrentCustomerOrders=yr;exports.getEnabledPaymentProviders=ye;exports.getFreemiusWebhookSecretCandidates=Et;exports.getInvoiceBrandingData=ht;exports.getInvoiceOrder=xt;exports.getInvoicePresentationData=Me;exports.getOrderDetails=Pt;exports.getOrders=Tt;exports.getPaymentProvider=Fr;exports.getPaymentSettings=Kr;exports.getStoreConfigStatus=Re;exports.handleStripeWebhook=fr;exports.rebaseStoreCurrencyExchangeRates=Sr;exports.resolveFreemiusStatusFromCheckoutResponse=jt;exports.resolveFreemiusStatusFromWebhookEvent=Be;exports.saveTaxRateAction=Ht;exports.stripe=le;exports.syncFreemiusCheckoutOrder=$r;exports.syncFreemiusOrderFromWebhookEvent=zr;exports.syncStoreCurrencyRates=kr;exports.syncStripeOrderFromSession=gt;exports.updateInventoryTrackingAction=Lt;exports.updatePaymentSettings=Ft;exports.updateShippingRate=qt;exports.updateShippingZone=Bt;exports.updateTaxSettingsAction=Vt;exports.verifyFreemiusWebhookSignature=qr;
package/server.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ export * from './lib/stripe/client';
2
+ export * from './lib/stripe/checkout';
3
+ export * from './lib/stripe/order-sync';
4
+ export * from './lib/stripe/webhooks';
5
+ export * from './lib/order-inventory';
6
+ export * from './lib/order-tax-details';
7
+ export * from './lib/invoice';
8
+ export * from './lib/invoice-server';
9
+ export * from './lib/customer-orders';
10
+ export * from './lib/coupon-server';
11
+ export * from './lib/freemius-coupons';
12
+ export * from './lib/customer';
13
+ export * from './lib/customer-addresses';
14
+ export * from './lib/currency';
15
+ export * from './lib/currency-constants';
16
+ export * from './lib/currency-sync';
17
+ export { productSchema } from './lib/product-schema';
18
+ export * from './lib/product-actions';
19
+ export * from './lib/factory';
20
+ export * from './lib/providers/stripe';
21
+ export * from './lib/providers/freemius';
22
+ export * from './lib/freemius-order-sync';
23
+ export { getProduct as getCmsProduct, getProducts as getCmsProducts, getGlobalProductAttributes, getProductTranslations, getCategoriesWithCount, getProductCategories, getCategoryBySlug, } from './lib/pages/cms/products/actions';
24
+ export { createProductAction, updateProductAction, deleteProductAction, createCategoryAction, updateCategoryAction, deleteCategoryAction, syncProductCategoriesAction, } from './lib/pages/cms/products/server-actions';
25
+ export { getEnabledPaymentProviders, getPaymentSettings, getStoreConfigStatus, } from './lib/pages/cms/payments/queries';
26
+ export * from './lib/pages/cms/orders';
27
+ export * from './lib/pages/cms/products';
28
+ export * from './lib/pages/cms/payments';
29
+ export * from './lib/pages/cms/shipping';
30
+ export * from './lib/pages/cms/taxes';
31
+ export * from './lib/pages/cms/coupons';