@nextblock-cms/ecom 0.8.6 → 0.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs.js +1 -1
- package/index.es.js +136 -533
- package/lib/CurrencyProvider.cjs.js +1 -0
- package/lib/CurrencyProvider.es.js +99 -0
- package/lib/cart-store.cjs.js +1 -0
- package/{cart-store.es.js → lib/cart-store.es.js} +13 -13
- package/lib/components/AccountNavigationMenu.cjs.js +1 -0
- package/lib/components/AccountNavigationMenu.es.js +44 -0
- package/lib/components/AddToCartButton.cjs.js +1 -0
- package/{AddToCartButton-ffE0DhHu.js → lib/components/AddToCartButton.es.js} +14 -13
- package/lib/components/Cart.cjs.js +1 -0
- package/lib/components/Cart.es.js +148 -0
- package/lib/components/CartDrawer.cjs.js +1 -0
- package/{components → lib/components}/CartDrawer.es.js +15 -14
- package/{components → lib/components}/CartIcon.cjs.js +1 -1
- package/{components → lib/components}/CartIcon.es.js +1 -0
- package/lib/components/Checkout.cjs.js +1 -0
- package/{components → lib/components}/Checkout.es.js +330 -363
- package/lib/components/CouponForm.cjs.js +1 -0
- package/lib/components/CouponForm.es.js +136 -0
- package/lib/components/CurrencySwitcher.cjs.js +1 -0
- package/{components → lib/components}/CurrencySwitcher.es.js +5 -4
- package/lib/components/CustomerProfileForm.cjs.js +1 -0
- package/lib/components/CustomerProfileForm.es.js +355 -0
- package/lib/components/FeaturedProduct.cjs.js +1 -0
- package/{components → lib/components}/FeaturedProduct.es.js +9 -8
- package/lib/components/InvoiceDocument.cjs.js +1 -0
- package/lib/components/InvoiceDocument.es.js +196 -0
- package/lib/components/InvoiceViewerShell.cjs.js +29 -0
- package/lib/components/InvoiceViewerShell.es.js +100 -0
- package/lib/components/ProductCard.cjs.js +1 -0
- package/lib/components/ProductCard.es.js +119 -0
- package/lib/components/ProductDetailsLayout.cjs.js +1 -0
- package/lib/components/ProductDetailsLayout.es.js +361 -0
- package/lib/components/ProductGallery.cjs.js +1 -0
- package/lib/components/ProductGallery.es.js +41 -0
- package/lib/components/ProductGrid.cjs.js +1 -0
- package/lib/components/ProductGrid.es.js +19 -0
- package/lib/components/ShippingEstimator.cjs.js +1 -0
- package/lib/components/ShippingEstimator.es.js +125 -0
- package/lib/components/SubscriptionSelector.cjs.js +1 -0
- package/lib/components/SubscriptionSelector.es.js +140 -0
- package/lib/countries.cjs.js +1 -0
- package/lib/countries.es.js +77 -0
- package/lib/coupon-server.cjs.js +1 -0
- package/{coupon-server-DUKVtyYs.js → lib/coupon-server.es.js} +68 -82
- package/lib/coupons.cjs.js +1 -0
- package/lib/coupons.es.js +17 -0
- package/lib/currency-store.cjs.js +1 -0
- package/lib/currency-store.es.js +27 -0
- package/lib/currency-sync.cjs.js +1 -0
- package/lib/currency-sync.es.js +180 -0
- package/lib/customer-addresses.cjs.js +1 -0
- package/lib/customer-addresses.es.js +116 -0
- package/lib/customer-orders.cjs.js +1 -0
- package/lib/customer-orders.es.js +45 -0
- package/lib/customer.cjs.js +1 -0
- package/{customer-C3xccjUg.js → lib/customer.es.js} +15 -14
- package/lib/export-helpers.cjs.js +1 -0
- package/lib/export-helpers.es.js +56 -0
- package/lib/factory.cjs.js +1 -0
- package/lib/factory.es.js +8 -0
- package/lib/freemius-coupons.cjs.js +1 -0
- package/lib/freemius-coupons.es.js +272 -0
- package/lib/freemius-order-sync.cjs.js +1 -0
- package/lib/freemius-order-sync.es.js +284 -0
- package/lib/inventory-settings.cjs.js +1 -0
- package/lib/inventory-settings.es.js +86 -0
- package/lib/invoice-server.cjs.js +33 -0
- package/lib/invoice-server.es.js +141 -0
- package/lib/invoice-ui.cjs.js +1 -0
- package/lib/invoice-ui.es.js +71 -0
- package/lib/invoice.cjs.js +1 -0
- package/lib/invoice.es.js +102 -0
- package/lib/order-inventory.cjs.js +61 -0
- package/lib/order-inventory.es.js +128 -0
- package/lib/order-tax-details.cjs.js +1 -0
- package/lib/order-tax-details.es.js +164 -0
- package/lib/pages/cms/coupons/CouponEditorForm.cjs.js +1 -0
- package/lib/pages/cms/coupons/CouponEditorForm.es.js +189 -0
- package/lib/pages/cms/coupons/CouponsPage.cjs.js +5 -0
- package/lib/pages/cms/coupons/CouponsPage.es.js +171 -0
- package/lib/pages/cms/coupons/CreateCouponDialog.cjs.js +1 -0
- package/lib/pages/cms/coupons/CreateCouponDialog.es.js +35 -0
- package/lib/pages/cms/coupons/EditCouponPage.cjs.js +1 -0
- package/lib/pages/cms/coupons/EditCouponPage.es.js +48 -0
- package/lib/pages/cms/coupons/ProductScopePicker.cjs.js +1 -0
- package/lib/pages/cms/coupons/ProductScopePicker.es.js +120 -0
- package/lib/pages/cms/coupons/actions.cjs.js +1 -0
- package/lib/pages/cms/coupons/actions.es.js +128 -0
- package/lib/pages/cms/coupons/product-options.cjs.js +1 -0
- package/lib/pages/cms/coupons/product-options.es.js +27 -0
- package/lib/pages/cms/orders/ExportReportsDialog.cjs.js +1 -0
- package/lib/pages/cms/orders/ExportReportsDialog.es.js +130 -0
- package/lib/pages/cms/orders/OrderDetailPage.cjs.js +1 -0
- package/lib/pages/cms/orders/OrderDetailPage.es.js +137 -0
- package/lib/pages/cms/orders/OrderPrintButton.cjs.js +1 -0
- package/lib/pages/cms/orders/OrderPrintButton.es.js +22 -0
- package/lib/pages/cms/orders/OrderStatusForm.cjs.js +1 -0
- package/lib/pages/cms/orders/OrderStatusForm.es.js +71 -0
- package/lib/pages/cms/orders/OrdersPage.cjs.js +1 -0
- package/lib/pages/cms/orders/OrdersPage.es.js +104 -0
- package/lib/pages/cms/orders/actions.cjs.js +7 -0
- package/lib/pages/cms/orders/actions.es.js +71 -0
- package/lib/pages/cms/orders/export-actions.cjs.js +1 -0
- package/lib/pages/cms/orders/export-actions.es.js +27 -0
- package/lib/pages/cms/orders/server-actions.cjs.js +1 -0
- package/lib/pages/cms/orders/server-actions.es.js +55 -0
- package/lib/pages/cms/payments/PaymentsClient.cjs.js +1 -0
- package/lib/pages/cms/payments/PaymentsClient.es.js +188 -0
- package/lib/pages/cms/payments/PaymentsPage.cjs.js +1 -0
- package/lib/pages/cms/payments/PaymentsPage.es.js +29 -0
- package/lib/pages/cms/payments/actions.cjs.js +1 -0
- package/lib/pages/cms/payments/actions.es.js +23 -0
- package/lib/pages/cms/payments/queries.cjs.js +1 -0
- package/lib/pages/cms/payments/queries.es.js +30 -0
- package/lib/pages/cms/products/ProductsPage.cjs.js +1 -0
- package/lib/pages/cms/products/ProductsPage.es.js +46 -0
- package/lib/pages/cms/products/_id_/edit/EditProductPage.cjs.js +1 -0
- package/lib/pages/cms/products/_id_/edit/EditProductPage.es.js +156 -0
- package/lib/pages/cms/products/actions.cjs.js +44 -0
- package/lib/pages/cms/products/actions.es.js +175 -0
- package/lib/pages/cms/products/attributes/AttributeManagementPage.cjs.js +1 -0
- package/lib/pages/cms/products/attributes/AttributeManagementPage.es.js +48 -0
- package/lib/pages/cms/products/attributes/components/AttributeManager.cjs.js +1 -0
- package/lib/pages/cms/products/attributes/components/AttributeManager.es.js +291 -0
- package/lib/pages/cms/products/categories/CategoryManagementPage.cjs.js +1 -0
- package/lib/pages/cms/products/categories/CategoryManagementPage.es.js +36 -0
- package/lib/pages/cms/products/categories/components/CategoryManager.cjs.js +1 -0
- package/lib/pages/cms/products/categories/components/CategoryManager.es.js +263 -0
- package/lib/pages/cms/products/components/CopyProductFromLanguage.cjs.js +1 -0
- package/lib/pages/cms/products/components/CopyProductFromLanguage.es.js +114 -0
- package/lib/pages/cms/products/components/CurrencyPriceFields.cjs.js +1 -0
- package/lib/pages/cms/products/components/CurrencyPriceFields.es.js +107 -0
- package/lib/pages/cms/products/components/DeleteProductButton.cjs.js +1 -0
- package/lib/pages/cms/products/components/DeleteProductButton.es.js +48 -0
- package/lib/pages/cms/products/components/FreemiusPricingDashboard.cjs.js +1 -0
- package/lib/pages/cms/products/components/FreemiusPricingDashboard.es.js +86 -0
- package/lib/pages/cms/products/components/ProductCategorySelector.cjs.js +1 -0
- package/lib/pages/cms/products/components/ProductCategorySelector.es.js +160 -0
- package/lib/pages/cms/products/components/ProductForm.cjs.js +1 -0
- package/lib/pages/cms/products/components/ProductForm.es.js +702 -0
- package/lib/pages/cms/products/components/ProductMediaManager.cjs.js +1 -0
- package/lib/pages/cms/products/components/ProductMediaManager.es.js +104 -0
- package/lib/pages/cms/products/components/ProductsBulkTable.cjs.js +1 -0
- package/lib/pages/cms/products/components/ProductsBulkTable.es.js +228 -0
- package/lib/pages/cms/products/components/SaleScheduleFields.cjs.js +1 -0
- package/lib/pages/cms/products/components/SaleScheduleFields.es.js +137 -0
- package/lib/pages/cms/products/components/SyncFreemiusButton.cjs.js +1 -0
- package/lib/pages/cms/products/components/SyncFreemiusButton.es.js +36 -0
- package/lib/pages/cms/products/components/SyncFreemiusPricingButton.cjs.js +1 -0
- package/lib/pages/cms/products/components/SyncFreemiusPricingButton.es.js +40 -0
- package/lib/pages/cms/products/components/VariationsEditor.cjs.js +1 -0
- package/lib/pages/cms/products/components/VariationsEditor.es.js +408 -0
- package/lib/pages/cms/products/inventory/InventoryPage.cjs.js +1 -0
- package/lib/pages/cms/products/inventory/InventoryPage.es.js +16 -0
- package/lib/pages/cms/products/inventory/InventoryTableClient.cjs.js +2 -0
- package/lib/pages/cms/products/inventory/InventoryTableClient.es.js +214 -0
- package/lib/pages/cms/products/inventory/actions.cjs.js +3 -0
- package/lib/pages/cms/products/inventory/actions.es.js +95 -0
- package/lib/pages/cms/products/new/NewProductPage.cjs.js +1 -0
- package/lib/pages/cms/products/new/NewProductPage.es.js +76 -0
- package/lib/pages/cms/products/product-price-sync.cjs.js +1 -0
- package/lib/pages/cms/products/product-price-sync.es.js +98 -0
- package/lib/pages/cms/products/server-actions.cjs.js +1 -0
- package/lib/pages/cms/products/server-actions.es.js +193 -0
- package/lib/pages/cms/shipping/ShippingPage.cjs.js +5 -0
- package/lib/pages/cms/shipping/ShippingPage.es.js +211 -0
- package/lib/pages/cms/shipping/components/RateForm.cjs.js +1 -0
- package/lib/pages/cms/shipping/components/RateForm.es.js +441 -0
- package/lib/pages/cms/shipping/components/ZoneForm.cjs.js +1 -0
- package/lib/pages/cms/shipping/components/ZoneForm.es.js +228 -0
- package/lib/pages/cms/shipping/server-actions.cjs.js +1 -0
- package/lib/pages/cms/shipping/server-actions.es.js +159 -0
- package/lib/pages/cms/taxes/TaxesPage.cjs.js +1 -0
- package/lib/pages/cms/taxes/TaxesPage.es.js +172 -0
- package/lib/pages/cms/taxes/actions.cjs.js +1 -0
- package/lib/pages/cms/taxes/actions.es.js +57 -0
- package/lib/pages/cms/taxes/components/TaxRateForm.cjs.js +1 -0
- package/lib/pages/cms/taxes/components/TaxRateForm.es.js +100 -0
- package/lib/product-actions.cjs.js +237 -0
- package/lib/product-actions.es.js +524 -0
- package/lib/product-context.cjs.js +1 -0
- package/lib/product-context.es.js +16 -0
- package/lib/product-schema.cjs.js +1 -0
- package/lib/product-schema.es.js +134 -0
- package/lib/providers/freemius.cjs.js +5 -0
- package/lib/providers/freemius.es.js +538 -0
- package/lib/providers/stripe.cjs.js +1 -0
- package/lib/providers/stripe.es.js +473 -0
- package/lib/server-actions/coupon-actions.cjs.js +1 -0
- package/lib/server-actions/coupon-actions.es.js +23 -0
- package/lib/server-actions/customer-actions.cjs.js +1 -0
- package/lib/server-actions/customer-actions.es.js +30 -0
- package/lib/server-actions/product-actions.cjs.js +1 -0
- package/{server-actions → lib/server-actions}/product-actions.es.js +5 -4
- package/lib/server-actions/shipping-actions.cjs.js +1 -0
- package/{shipping-actions-BnHjlo2q.js → lib/server-actions/shipping-actions.es.js} +9 -7
- package/lib/server-actions/tax-actions.cjs.js +1 -0
- package/lib/server-actions/tax-actions.es.js +40 -0
- package/lib/shared-inventory.cjs.js +15 -0
- package/lib/shared-inventory.es.js +171 -0
- package/lib/shipping/resolver.cjs.js +7 -0
- package/lib/shipping/resolver.es.js +62 -0
- package/lib/shipping-rate-currency.cjs.js +1 -0
- package/lib/shipping-rate-currency.es.js +72 -0
- package/lib/states.cjs.js +1 -0
- package/{states-DlHJezQ1.js → lib/states.es.js} +27 -100
- package/lib/stripe/checkout.cjs.js +1 -0
- package/lib/stripe/checkout.es.js +182 -0
- package/lib/stripe/client.cjs.js +1 -0
- package/lib/stripe/client.es.js +7 -0
- package/lib/stripe/order-sync.cjs.js +1 -0
- package/lib/stripe/order-sync.es.js +130 -0
- package/lib/stripe/webhooks.cjs.js +1 -0
- package/lib/stripe/webhooks.es.js +30 -0
- package/lib/tax-calculation.cjs.js +1 -0
- package/lib/tax-calculation.es.js +101 -0
- package/lib/trials.cjs.js +1 -0
- package/{trials-RDcRAZKx.js → lib/trials.es.js} +9 -9
- package/{use-cart.es.js → lib/use-cart.es.js} +1 -0
- package/lib/zod-config.cjs.js +1 -0
- package/lib/zod-config.es.js +6 -0
- package/package.json +4 -4
- package/server.cjs.js +1 -110
- package/server.es.js +178 -6052
- package/AddToCartButton-DsSEH9yp.cjs +0 -1
- package/CouponForm-BI_5SBHQ.js +0 -152
- package/CouponForm-D_uu2bLP.cjs +0 -1
- package/CurrencyProvider-Cg-Q6ucj.cjs +0 -1
- package/CurrencyProvider-OzlRN96V.js +0 -120
- package/CurrencyProvider.cjs.js +0 -1
- package/CurrencyProvider.es.js +0 -10
- package/ProductDetailsLayout-BxJH_BxR.cjs +0 -1
- package/ProductDetailsLayout-Dg8dRTYp.js +0 -530
- package/ProductGrid-BdL7iglO.cjs +0 -1
- package/ProductGrid-D3AWM8sr.js +0 -130
- package/actions-AHmBrS5e.cjs +0 -48
- package/actions-j5fuSZX-.js +0 -820
- package/cart-store.cjs.js +0 -1
- package/components/Cart.cjs.js +0 -1
- package/components/Cart.es.js +0 -259
- package/components/CartDrawer.cjs.js +0 -1
- package/components/Checkout.cjs.js +0 -1
- package/components/CurrencySwitcher.cjs.js +0 -1
- package/components/FeaturedProduct.cjs.js +0 -1
- package/components/ProductDetailsLayout.cjs.js +0 -1
- package/components/ProductDetailsLayout.es.js +0 -19
- package/components/ProductGrid.cjs.js +0 -1
- package/components/ProductGrid.es.js +0 -6
- package/coupon-server-C9ySm3I5.cjs +0 -1
- package/customer-C-UPvrYN.cjs +0 -1
- package/invoice-ui-CAnJPu6n.cjs +0 -29
- package/invoice-ui-DtpbTJE1.js +0 -2886
- package/product-actions-CONBF8i6.cjs +0 -251
- package/product-actions-DjlIWCMH.js +0 -691
- package/resolver-Fz_FKsfX.cjs +0 -7
- package/resolver-cfrCaHpE.js +0 -128
- package/server-actions/product-actions.cjs.js +0 -1
- package/shipping-actions-D6zt20gg.cjs +0 -1
- package/states-CWYRxV4B.cjs +0 -1
- package/tax-calculation-Dab89aHd.js +0 -181
- package/tax-calculation-MkDKOEkL.cjs +0 -1
- package/trials-DvZaOtNy.cjs +0 -1
- /package/{components → lib/components}/SimpleTiptapRenderer.cjs.js +0 -0
- /package/{components → lib/components}/SimpleTiptapRenderer.es.js +0 -0
- /package/{currency-constants.cjs.js → lib/currency-constants.cjs.js} +0 -0
- /package/{currency-constants.es.js → lib/currency-constants.es.js} +0 -0
- /package/{currency-rest-client-uolJxUkL.cjs → lib/currency-rest-client.cjs.js} +0 -0
- /package/{currency-rest-client-CwoqdgAP.js → lib/currency-rest-client.es.js} +0 -0
- /package/{currency.cjs.js → lib/currency.cjs.js} +0 -0
- /package/{currency.es.js → lib/currency.es.js} +0 -0
- /package/{types.cjs.js → lib/types.cjs.js} +0 -0
- /package/{types.es.js → lib/types.es.js} +0 -0
- /package/{use-cart.cjs.js → lib/use-cart.cjs.js} +0 -0
- /package/{variation-utils.cjs.js → lib/variation-utils.cjs.js} +0 -0
- /package/{variation-utils.es.js → lib/variation-utils.es.js} +0 -0
package/server.cjs.js
CHANGED
|
@@ -1,110 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
SELECT inventory_deducted_at
|
|
3
|
-
FROM public.orders
|
|
4
|
-
WHERE id = ${t}
|
|
5
|
-
FOR UPDATE
|
|
6
|
-
`)[0];if(!c||c.inventory_deducted_at)return;const d=await i`
|
|
7
|
-
SELECT value
|
|
8
|
-
FROM public.site_settings
|
|
9
|
-
WHERE key = ${te.ECOMMERCE_INVENTORY_SETTINGS_KEY}
|
|
10
|
-
LIMIT 1
|
|
11
|
-
`;if(!te.normalizeEcommerceInventorySettings(d[0]?.value).trackQuantities){await i`
|
|
12
|
-
UPDATE public.orders
|
|
13
|
-
SET inventory_deducted_at = now()
|
|
14
|
-
WHERE id = ${t}
|
|
15
|
-
`;return}const u=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 p of u){if(p.variant_id){const b=(await i`
|
|
24
|
-
SELECT
|
|
25
|
-
sku,
|
|
26
|
-
stock_quantity
|
|
27
|
-
FROM public.product_variants
|
|
28
|
-
WHERE id = ${p.variant_id}
|
|
29
|
-
LIMIT 1
|
|
30
|
-
`)[0];if(!b?.sku)continue;await i`
|
|
31
|
-
INSERT INTO public.inventory_items (sku, quantity)
|
|
32
|
-
VALUES (${b.sku}, ${Math.max(0,b.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) - ${p.quantity}, 0),
|
|
38
|
-
updated_at = now()
|
|
39
|
-
WHERE sku = ${b.sku}
|
|
40
|
-
`;continue}if(p.product_id){const b=(await i`
|
|
41
|
-
SELECT
|
|
42
|
-
sku,
|
|
43
|
-
stock
|
|
44
|
-
FROM public.products
|
|
45
|
-
WHERE id = ${p.product_id}
|
|
46
|
-
LIMIT 1
|
|
47
|
-
`)[0];if(!b?.sku)continue;await i`
|
|
48
|
-
INSERT INTO public.inventory_items (sku, quantity)
|
|
49
|
-
VALUES (${b.sku}, ${Math.max(0,b.stock??0)})
|
|
50
|
-
ON CONFLICT (sku) DO NOTHING
|
|
51
|
-
`,await i`
|
|
52
|
-
UPDATE public.inventory_items
|
|
53
|
-
SET
|
|
54
|
-
quantity = GREATEST(COALESCE(quantity, 0) - ${p.quantity}, 0),
|
|
55
|
-
updated_at = now()
|
|
56
|
-
WHERE sku = ${b.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 Oe(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 vr(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 jr(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 De(t){return t??H.getServiceRoleSupabaseClient()}function Cr(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:jr(r),width:t.media?.width??null,height:t.media?.height??null}}async function wt(t){const r=De(t),[s,a]=await Promise.all([r.from("site_settings").select("value").eq("key",A.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:A.normalizeInvoiceSettings(s.data?.value??A.DEFAULT_INVOICE_SETTINGS),logo:Cr(a.data)}}async function Be(t){const r=De(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 Nt(t,r){const s=De(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 o=(a.order_items||[]).map(g=>g.product_id).filter(Boolean),c=(a.order_items||[]).map(g=>g.variant_id).filter(Boolean),[d,l]=await Promise.all([o.length?s.from("products").select("id, title, sku").in("id",o):Promise.resolve({data:[],error:null}),c.length?s.from("product_variants").select("id, sku").in("id",c):Promise.resolve({data:[],error:null})]),u=new Map((d.data||[]).map(g=>[g.id,g])),p=new Map((l.data||[]).map(g=>[g.id,g])),h=(a.order_items||[]).map(g=>{const w=g.product_id?u.get(g.product_id):null,S=g.variant_id?p.get(g.variant_id):null,R=w?.title||"Product",_=S?.sku?`SKU: ${S.sku}`:w?.sku?`SKU: ${w.sku}`:null;return{id:g.id,product_id:g.product_id??null,variant_id:g.variant_id??null,title:R,description:_,quantity:g.quantity,unit_amount:g.price_at_purchase,total_amount:g.price_at_purchase*g.quantity,sku:S?.sku??w?.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:h.reduce((g,w)=>g+w.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:me.normalizeOrderCustomerDetails(a.customer_details??{}),tax_details:A.normalizeOrderTaxDetails(a.tax_details),items:h}}async function Ge(t,r){const s=De(r),[a,i]=await Promise.all([Nt(t,s),wt(s)]);return{order:a,settings:i.settings,logo:i.logo}}const wr=["total_details.breakdown"],Nr=["data.taxes.rate"];function Sr(){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 Ae.createClient(t,r,{auth:{autoRefreshToken:!1,persistSession:!1}})}function it(t,r){return t?me.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 kr(t){const r=t??{};return me.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 St(t){const r=Sr();let s=t;try{s=await xe.checkout.sessions.retrieve(t.id,{expand:[...wr]})}catch(x){console.error("[Stripe Sync] Failed to rehydrate session tax details:",x)}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:o,error:c}=await i;if(c||!o)throw new Error(c?.message||"Order lookup failed");const d=kr(o.customer_details),l=A.normalizeOrderTaxDetails(o.tax_details),u=it(s.customer_details?.address,s.customer_details?.name??d.name),p=s,h=it(p.shipping_details?.address,p.shipping_details?.name??d.name),b=me.normalizeOrderCustomerDetails({email:s.customer_details?.email??d.email,name:s.customer_details?.name??d.name,phone:s.customer_details?.phone??d.phone,billing:d.billing??u,shipping:d.shipping??h}),g=o.status==="paid",w=await xe.checkout.sessions.listLineItems(s.id,{limit:100,expand:[...Nr]}),S=A.buildOrderTaxDetailsFromStripeSession({session:s,lineItems:w.data,subtotal:typeof o.subtotal=="number"?o.subtotal:l?.subtotal??0,shippingTotal:typeof o.shipping_total=="number"?o.shipping_total:l?.shipping_total??0,fallbackMode:l?.mode??"automatic",currency:(s.currency??o.currency??l?.currency??"USD").toUpperCase()}),R=S.tax_total>0||S.lines.length>0?S:l??S,_=R?.tax_total??(typeof o.tax_total=="number"?o.tax_total:0),N=(s.currency??o.currency??R?.currency??"USD").toUpperCase(),k={status:"paid",stripe_session_id:s.id,payment_intent_id:typeof s.payment_intent=="string"?s.payment_intent:null,provider:"stripe",customer_details:b,total:typeof s.amount_total=="number"?s.amount_total:o.total,currency:N,tax_total:_,tax_details:R},{error:F}=await r.from("orders").update(k).eq("id",o.id);if(F)throw new Error(F.message);if(o.user_id)try{await K.upsertDefaultUserAddresses({userId:o.user_id,billingAddress:b.billing,shippingAddress:b.shipping,client:r})}catch(x){console.error("[Stripe Sync] Failed to refresh saved customer addresses:",x)}const y=await Be({orderId:o.id,client:r});return await Oe(r,o.id),{orderId:o.id,alreadyPaid:g,customerDetails:b,order:{id:o.id,invoice_number:y.invoiceNumber,paid_at:y.paidAt,total:k.total,currency:N,subtotal:typeof o.subtotal=="number"?o.subtotal:R?.subtotal??0,shipping_total:typeof o.shipping_total=="number"?o.shipping_total:R?.shipping_total??0,tax_total:_,tax_details:R}}}const Er=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=xe.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 St(i)}catch(o){return console.error("[Stripe Webhook Error] Failed to sync completed session:",o),{received:!1,error:o.message||"Failed to sync Stripe session"}}break}default:console.log(`Unhandled event type ${a.type}`)}return{received:!0}};function We(t){return t??H.createClient()}async function kt(t){const{data:{user:r},error:s}=await t.auth.getUser();if(s||!r)throw new Error("Unauthorized");return r}async function Tr(t){const r=We(t),s=await kt(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 Et(t,r){const s=We(r),a=await kt(s),{data:i,error:o}=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(o)throw new Error(o.message);return i??null}async function Pr(t,r){const s=We(r),a=await Et(t,s);if(!a)return null;const i=a.invoice_number?await Ge(t,s):null;return{order:a,invoice:i}}const Ar="https://api.frankfurter.dev",Ir="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 Ve(t){if(!t.id)throw new Error(`Currency ${z.normalizeCurrencyCode(t.code)} is missing its ID.`);return t.id}function Rr(){return process.env.FX_API_BASE_URL?.trim().replace(/\/+$/,"")||Ar}function Fr(t){try{const r=new URL(t),s=r.pathname.replace(/\/+$/,"");return`${r.host}${s&&s!=="/"?s:""}`}catch{return t}}function Ur(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 Lr(t){return Array.isArray(t)&&t.every(Ur)}async function Tt(){const t=H.getServiceRoleSupabaseClient(),{data:r,error:s}=await t.from("currencies").select(Ir).order("code",{ascending:!0});if(s)throw new Error(s.message);return{supabase:t,currencies:r||[]}}async function Mr(t){const r=z.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 Tt();if(!i.find(p=>z.normalizeCurrencyCode(p.code)===r))throw new Error(`Currency ${r} was not found for rebasing.`);const c=new Date().toISOString(),d=[],l=i.map(p=>{const h=Ve(p),b=z.normalizeCurrencyCode(p.code),g=b===r?1:Number((p.exchange_rate/s).toFixed(10));return d.push(b),{...p,id:h,exchange_rate:g,auto_update_exchange_rate:b===r?!1:p.auto_update_exchange_rate,exchange_rate_source:b===r?"store-default":p.exchange_rate_source||"rebased-default",exchange_rate_updated_at:c,updated_at:c}}),{error:u}=await a.from("currencies").upsert(l,{onConflict:"id"});if(u)throw new Error(u.message);return{rebasedAt:c,newDefaultCurrencyCode:r,updatedCurrencies:d}}async function Or(){const{supabase:t,currencies:r}=await Tt();if(!r.length)throw new Error("No currencies are configured yet.");const s=r.map(N=>D.normalizeCurrencyRecord(N)),a=D.getDefaultCurrency(s),i=z.normalizeCurrencyCode(a.code),o=r.find(N=>z.normalizeCurrencyCode(N.code)===i);if(!o)throw new Error(`Default currency ${i} could not be found for syncing.`);const c=r.filter(N=>z.normalizeCurrencyCode(N.code)!==i&&N.auto_update_exchange_rate!==!1),d=Rr(),l=Fr(d),u=new Date().toISOString(),{error:p}=await t.from("currencies").upsert({...o,id:Ve(o),exchange_rate:1,auto_update_exchange_rate:!1,exchange_rate_source:"store-default",exchange_rate_updated_at:u,updated_at:u},{onConflict:"id"});if(p)throw new Error(p.message);if(!c.length)return{baseCurrencyCode:i,fetchedAt:u,provider:l,providerUrl:d,skippedCurrencies:[],updatedCurrencies:[]};const h=new URL(`${d}/v2/rates`);h.searchParams.set("base",i),h.searchParams.set("quotes",[...new Set(c.map(N=>z.normalizeCurrencyCode(N.code)))].join(","));const b=await fetch(h.toString(),{cache:"no-store",headers:{Accept:"application/json"}});if(!b.ok){const N=await b.text();throw new Error(`FX provider request failed (${b.status}): ${N||"Unexpected response body."}`)}const g=await b.json();if(!Lr(g))throw new Error("FX provider returned an unexpected response payload.");const w=new Map;for(const N of g)w.set(z.normalizeCurrencyCode(N.quote),N.rate);const S=[],R=[],_=[];for(const N of c){const k=z.normalizeCurrencyCode(N.code),F=w.get(k);if(!F||!Number.isFinite(F)||F<=0){R.push(k);continue}_.push({...N,id:Ve(N),exchange_rate:Number(F.toFixed(10)),exchange_rate_source:l,exchange_rate_updated_at:u,updated_at:u}),S.push(k)}if(_.length){const{error:N}=await t.from("currencies").upsert(_,{onConflict:"id"});if(N)throw new Error(N.message)}return{baseCurrencyCode:i,fetchedAt:u,provider:l,providerUrl:d,skippedCurrencies:R,updatedCurrencies:S}}async function Dr(t){const r=z.normalizeCurrencyCode(t),s=H.getServiceRoleSupabaseClient(),{error:a}=await s.rpc("clear_currency_price_overrides",{target_currency:r});if(a)throw new Error(a.message);return{currencyCode:r}}const Br=se.countries.map(t=>t.code),$r=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 ot(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 zr(t){const r=t?.trim().replace("_","-");if(!r)return;const s=[r,r.toLowerCase(),r.split("-")[0].toLowerCase()];for(const a of s)if($r.has(a))return a}function qr(t,r){return He.resolveTranslatedText(t.name,t.name_translations||null,r)}async function Kr(t){if(!t.email)return null;const r=ot(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:ot(t.billingAddress),metadata:t.userId?{userId:t.userId}:void 0,...r&&s?{shipping:{name:s,phone:t.phone||void 0,address:r}}:{}};try{const o=(await xe.customers.list({email:t.email,limit:1})).data[0];return o?(await xe.customers.update(o.id,a),o.id):(await xe.customers.create(a)).id}catch(i){return console.error("Failed to upsert Stripe customer for checkout prefill:",i),null}}class Pt{getProviderName(){return"Stripe"}async createCheckoutSession({items:r,customerEmail:s,customerPhone:a,userId:i,billingAddress:o,shippingAddress:c,shippingMethodId:d,currencyCode:l,locale:u,couponCode:p,couponContextItems:h}){const b=process.env.NEXT_PUBLIC_SUPABASE_URL,g=process.env.SUPABASE_SERVICE_ROLE_KEY;if(!b||!g)return console.error("Missing Supabase credentials for checkout (Service Key required)."),{error:"Internal Server Error",url:null};const w=Ae.createClient(b,g),S=process.env.NEXT_PUBLIC_URL||"http://localhost:4200",R=r.some(C=>!Ke.isDigitalItem(C));if(!r.length)return{error:"Cart is empty",url:null};const{data:_,error:N}=await w.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}),k=_??[];if(N||k.length===0)return console.error("Error fetching currencies for checkout:",N),{error:"Failed to resolve store currencies",url:null};const F=D.getDefaultCurrency(k),y=k.find(C=>C.code===(l||"").toUpperCase())??F,x=y.code.toLowerCase(),v=await te.getEcommerceInventorySettings(w),B=r.map(C=>C.product_id),$=r.map(C=>C.variant_id).filter(C=>!!C),{data:L,error:q}=await w.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",B);if(q||!L)return console.error("Error fetching products for validation:",q),{error:"Failed to validate product prices",url:null};const{data:ae,error:E}=$.length?await w.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",$):{data:[],error:null};if(E)return console.error("Error fetching variants for validation:",E),{error:"Failed to validate product variants",url:null};const W=new Map(L.map(C=>[C.id,C])),Q=new Map((ae||[]).map(C=>[C.id,C])),m=new Set,T=new Map;for(const C of r){const G=W.get(C.product_id);if(!G)continue;const ne=(C.variant_id?Q.get(C.variant_id):null)?.sku||G.sku;ne&&(m.add(ne),T.set(ne,(T.get(ne)??0)+C.quantity))}const{data:M,error:X}=m.size?await w.from("inventory_items").select("sku, quantity").in("sku",[...m]):{data:[],error:null};if(X)return console.error("Error fetching SKU inventory for validation:",X),{error:"Failed to validate SKU inventory",url:null};const oe=new Map((M||[]).map(C=>[C.sku,Math.max(0,C.quantity??0)])),j=[],O=[],I=[];let V=0,ie=0,ee=null;if(p){const C=await fe.getCouponQuote({client:w,code:p,items:h&&h.length>0?h:r,currencyCode:y.code});if(!C.success)return{error:C.error,errorKey:C.errorKey,errorStatus:400,url:null};ee=C.quote}const ue=fe.getQuoteLineDiscountMap(ee),Re=C=>{const G=C.unitAmount*C.quantity,ye=Math.max(0,G-C.lineDiscount);if(ye<=0)return;const ne=Math.floor(ye/C.quantity),ke=ye-ne*C.quantity,je=(Ee,Ce)=>{Ce<=0||Ee<=0||j.push({price_data:{currency:C.currency,product_data:{name:C.name,tax_code:te.getStripeTaxCodeForProduct(C.isTaxable),metadata:{productId:C.productId,variantId:C.variantId||""}},tax_behavior:"exclusive",unit_amount:Ee},quantity:Ce})};je(ne,C.quantity-ke),je(ne+1,ke)};for(const C of r){const G=W.get(C.product_id);if(!G)return console.warn(`Product ${C.product_id} not found in DB.`),{url:null,...te.createInventoryUnavailableError(C.title)};const ye=D.resolveEffectivePriceForCurrency({prices:D.normalizePriceMap(G.prices),salePrices:G.sale_prices||{},fallbackPrice:G.price,fallbackSalePrice:G.sale_price,saleStartAt:G.sale_start_at,saleEndAt:G.sale_end_at,scheduledPrice:G.scheduled_price,scheduledPrices:D.normalizePriceMap(G.scheduled_prices),scheduledPriceAt:G.scheduled_price_at,currencyCode:y.code,currencies:k});let ne=ye.sale_price??ye.price,ke=G.title,je=null;if(C.variant_id){const J=Q.get(C.variant_id);if(!J||J.product_id!==C.product_id)return{url:null,...te.createInventoryUnavailableError(C.title)};const Ue=T.get(J.sku)??C.quantity,st=oe.has(J.sku)?oe.get(J.sku)??0:Math.max(0,J.stock_quantity??0);if(v.trackQuantities&&Ue>st)return{url:null,...te.createInventoryInsufficientError(C.title,st)};const at=D.resolveEffectivePriceForCurrency({prices:D.normalizePriceMap(J.prices),salePrices:J.sale_prices||{},fallbackPrice:J.price,fallbackSalePrice:J.sale_price,saleStartAt:J.sale_start_at,saleEndAt:J.sale_end_at,scheduledPrice:J.scheduled_price,scheduledPrices:D.normalizePriceMap(J.scheduled_prices),scheduledPriceAt:J.scheduled_price_at,currencyCode:y.code,currencies:k});ne=at.sale_price??at.price,je=J.id,ke=C.variant_label?`${G.title} - ${C.variant_label}`:`${G.title} - ${J.sku}`}else{const J=T.get(G.sku)??C.quantity,Ue=oe.has(G.sku)?oe.get(G.sku)??0:Math.max(0,G.stock??0);if(v.trackQuantities&&J>Ue)return{url:null,...te.createInventoryInsufficientError(C.title,Ue)}}const Ee=G.is_taxable??!0;if(ne<0)return{error:"A product variation produced an invalid price.",url:null};const Ce=Math.min(ne*C.quantity,ue.get(fe.getCartLineCouponKey(C))??0);Re({name:ke,currency:x,productId:G.id,variantId:je,isTaxable:Ee,unitAmount:ne,quantity:C.quantity,lineDiscount:Ce}),V+=ne*C.quantity,ie+=Ce,I.push({product_id:G.id,quantity:C.quantity,price_at_purchase:ne,variant_id:je}),O.push({product_id:G.id,quantity:C.quantity,unit_amount:ne,discount_amount:Ce,is_taxable:Ee})}if(j.length===0&&ie>=V)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(j.length===0)return{error:"No valid items in cart",url:null};let ge=0,ze=null;if(d){const{data:C,error:G}=await w.from("shipping_zone_methods").select("id, name, name_translations, cost_amount, cost_currency").eq("id",d).single();if(G)return console.error("Failed to load shipping method:",G),{error:"Failed to load shipping method",url:null};ge=D.convertMinorUnitAmount({amount:C.cost_amount??0,fromCurrencyCode:C.cost_currency||F.code,toCurrencyCode:y.code,currencies:k}),ze=qr(C,u)}const Ze=R?c??o:o;let de;try{de=await te.calculateCheckoutTaxes(w,{items:O,destination:{country_code:Ze?.country_code,state:Ze?.state}})}catch(C){return console.error("Failed to calculate checkout taxes:",C),{error:"Failed to calculate taxes",url:null}}ge>0&&ze&&j.push({price_data:{currency:x,product_data:{name:ze,tax_code:de.enabled&&de.mode==="automatic"?te.STRIPE_TAX_CODE_SHIPPING:te.STRIPE_TAX_CODE_NONTAXABLE},tax_behavior:"exclusive",unit_amount:ge},quantity:1});const be=de.enabled&&de.mode==="manual"&&!de.isPendingExternalCalculation?de.amount:0;be>0&&j.push({price_data:{currency:x,product_data:{name:"Tax",tax_code:te.STRIPE_TAX_CODE_NONTAXABLE},tax_behavior:"exclusive",unit_amount:be},quantity:1});const cr=me.normalizeOrderCustomerDetails({email:s,phone:a,name:o?.recipient_name,billing:o,shipping:c}),Je=y.code,lr=A.buildOrderTaxDetailsFromCalculation({calculation:de,subtotal:V,shippingTotal:ge,total:Math.max(0,V-ie)+ge+be,currency:Je}),dr=Math.max(0,V-ie)+ge+be,{data:et,error:tt}=await w.from("orders").insert({status:"pending",total:dr,currency:Je,exchange_rate_at_purchase:y.exchange_rate,subtotal:V,shipping_total:ge,tax_total:be,tax_details:lr,coupon_id:ee?.couponId??null,coupon_code:ee?.code??null,discount_total:ie,discount_details:ee?{code:ee.code,discount_type:ee.discountType,discount_amount:ee.discountAmount,provider:"stripe",provider_discounts:ee.providerDiscounts,line_discounts:ee.lineDiscounts}:null,provider:"stripe",user_id:i,customer_details:cr}).select("id").single();if(tt||!et)return console.error("Failed to create pending order:",tt),{error:"Failed to initiate order",url:null};const ve=et.id,{error:rt}=await w.from("order_items").insert(I.map(C=>({order_id:ve,product_id:C.product_id,variant_id:C.variant_id??null,quantity:C.quantity,price_at_purchase:C.price_at_purchase})));if(rt)return console.error("Failed to insert order items:",rt),await w.from("orders").update({status:"failed"}).eq("id",ve),{error:"Failed to record order items",url:null};if(i)try{await K.upsertDefaultUserAddresses({userId:i,billingAddress:o,shippingAddress:c,client:w}),await K.fillMissingUserProfileCheckoutDetails({userId:i,fullName:o?.recipient_name??c?.recipient_name??null,phone:a,client:w})}catch(C){console.error("Failed to sync checkout profile defaults before checkout:",C)}ee&&await fe.recordCouponRedemption({client:w,quote:ee,orderId:ve,provider:"stripe",discountTotal:ie,userId:i,customerEmail:s,metadata:{currency:y.code,subtotal:V,shipping_total:ge,tax_total:be}});const Fe=await Kr({email:s,phone:a,userId:i,billingAddress:o,shippingAddress:c});try{const C=await xe.checkout.sessions.create({mode:"payment",success_url:`${S}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,cancel_url:`${S}/checkout`,locale:zr(u),line_items:j,automatic_tax:de.enabled&&de.mode==="automatic"?{enabled:!0}:void 0,billing_address_collection:"auto",customer:Fe||void 0,customer_email:Fe?void 0:s||void 0,customer_creation:Fe?void 0:"if_required",customer_update:Fe?{name:"auto",address:"auto",shipping:"auto"}:void 0,shipping_address_collection:R?{allowed_countries:Br}:void 0,metadata:{orderId:ve,taxMode:de.mode,currencyCode:y.code,couponCode:ee?.code||""}}),{error:G}=await w.from("orders").update({stripe_session_id:C.id}).eq("id",ve);return G&&console.error("Failed to save Stripe session ID on order:",G),{url:C.url}}catch(C){return console.error("Stripe session creation failed:",C),await w.from("orders").update({status:"failed"}).eq("id",ve),{error:C.message,url:null}}}}function Vr(t){return t==="freemius"?new K.FreemiusProvider:new Pt}function U(t){return t==null||t===""?null:String(t)}function he(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 Hr(t){if(t==null||t==="")return null;const r=Number(t);return Number.isFinite(r)?r:null}function Qe(...t){return t.some(r=>{const s=Hr(r);return s!==null&&s>0})}function Me(t){return t==="pending"||t==="trial"}function ct(t){return["license.cancelled","license.deleted","license.expired","subscription.cancelled","subscription.renewal.failed.last","trial.cancelled","trial.expired"].includes(t||"")}function Gr(t,r){return t==="license.extended"&&(r?.is_renewal===!0||r?.is_renewal===1||r?.is_renewal==="1"||r?.is_renewal==="true")}function Wr(t){const r=t.objects?.payment??t.data?.payment??t.data;return t.type==="payment.created"&&Qe(r?.gross,r?.total_gross,r?.amount,r?.initial_amount)}function At(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:he(s?.trial_ends_at)??he(s?.trialEndsAt)??he(r?.trial_ends)??he(r?.trialEnds)}}function It(t,r="pending"){const s=t?.purchase??null,a=t?.trial??null;return r==="paid"?"paid":a&&(a.canceled_at||a.canceledAt)&&Me(r)?"cancelled":a?"trial":s?(s.canceled_at||s.canceledAt)&&Me(r)?"cancelled":Qe(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 Xe(t){const{event:r,currentStatus:s,purchaseData:a}=t;return s==="paid"&&ct(r.type)?"paid":ct(r.type)?Me(s)?"cancelled":s:Wr(r)||Gr(r.type,r.data)||a&&Qe(a.initialAmount,a.initial_amount,a.gross,a.totalGross,a.total_gross)?"paid":a?.canceled===!0&&Me(s)?"cancelled":(a?.subscriptionId||a?.subscription_id||r.type==="subscription.created"||r.type==="license.created")&&s==="pending"?"trial":s}function Qr(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 Rt(){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 Ae.createClient(t,r,{auth:{autoRefreshToken:!1,persistSession:!1}})}async function Xr(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 Yr(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 Ft(t){const r=Qr(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 Be({orderId:t.order.id,client:t.client}),await Oe(t.client,t.order.id)),a}async function Zr(t){const r=t.client??Rt(),s=await Xr(r,t.orderId);if(s.provider!=="freemius")return{success:!1,error:"Only Freemius orders can be synced from Freemius checkout"};const a=At(t.checkoutResponse);let i=null;if(a.freemius_license_id)try{i=await Mt(a.freemius_product_id??s.freemius_product_id,a.freemius_license_id)}catch(p){console.error("[Freemius Checkout Sync] Failed to retrieve purchase data:",p)}const o={type:"checkout.purchaseCompleted",data:{license_id:a.freemius_license_id},objects:{}},c={...a,...Lt(o,i)},d=It(t.checkoutResponse,s.status),l=i?Xe({event:o,currentStatus:s.status,purchaseData:i}):d==="paid"?s.status:d,u=await Ft({client:r,order:s,nextStatus:l,metadata:c,eventType:"checkout.purchaseCompleted"});return{success:!0,orderId:s.id,status:u,metadata:c}}function Ut(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 Lt(t,r){const s=t.objects?.license,a=t.objects?.subscription,i=t.objects?.trial,o=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(o?.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)??Ut(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:he(i?.trial_ends_at)??he(i?.trial_ends)??he(s?.trial_ends)??he(r?.trialEndsAt)??he(r?.trial_ends_at)}}async function Mt(t,r){if(!t)return null;const s=K.resolveFreemiusCheckoutCredentials(t);return!s.apiKey||!s.secretKey||!s.publicKey?null:new hr.Freemius({productId:Number(t),apiKey:s.apiKey,secretKey:s.secretKey,publicKey:s.publicKey}).purchase.retrievePurchaseData(r)}async function Jr(t){const r=t.client??Rt(),s=Ut(t.event);if(!s)return{success:!0,ignored:!0,reason:"missing_license_id",type:t.event.type};const a=await Yr(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 Mt(a.freemius_product_id??t.event.objects?.license?.plugin_id,s)}catch(l){console.error("[Freemius Sync] Failed to retrieve purchase data:",l)}const o=Lt(t.event,i),c=Xe({event:t.event,currentStatus:a.status,purchaseData:i}),d=await Ft({client:r,order:a,nextStatus:c,metadata:o,eventType:t.event.type??null});return{success:!0,orderId:a.id,status:d,type:t.event.type}}function Ot(){const t=[K.readFreemiusEnvValue("FREEMIUS_SECRET_KEY"),K.readFreemiusEnvValue("FREEMIUS_ECOMMERCE_SANDBOX_SECRET_KEY"),...Object.values(K.parseFreemiusCheckoutCredentialsMap()??{}).map(r=>r.secretKey??null)];return Array.from(new Set(t.filter(r=>!!r)))}function es(t,r){return r?Ot().some(s=>{const a=nt.createHmac("sha256",s).update(t).digest("hex");try{return nt.timingSafeEqual(Buffer.from(a,"hex"),Buffer.from(r,"hex"))}catch{return!1}}):!1}async function $e(){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 Se(){const t=H.createClient(),{data:r,error:s}=await t.from("site_settings").select("value").eq("key","enabled_payment_providers").maybeSingle();return s||!r?{...Ke.DEFAULT_ENABLED_PAYMENT_PROVIDERS}:Ke.normalizeEnabledPaymentProviders(r.value)}async function ts(){const t=await Se();return t.stripe?"stripe":t.freemius?"freemius":"stripe"}const qe=20;async function Dt(t=1,r,s){const a=await H.createClient(),i=(t-1)*qe,o=i+qe-1;let c=a.from("orders").select(`
|
|
94
|
-
*,
|
|
95
|
-
order_items (*)
|
|
96
|
-
`,{count:"exact"}).order("created_at",{ascending:!1}).range(i,o);r&&r!=="all"&&(c=c.eq("status",r)),s&&(c=c.or(`id.eq.${s},user_id.eq.${s}`));const{data:d,error:l,count:u}=await c;if(l)throw console.error("Error fetching orders:",l),new Error("Failed to fetch orders");const p=d||[],h=Array.from(new Set(p.map(w=>w.user_id).filter(Boolean))),b=new Map;if(h.length>0){const{data:w,error:S}=await a.from("profiles").select("*").in("id",h);!S&&w&&w.forEach(R=>b.set(R.id,R))}return{data:p.map(w=>({...w,customer:w.user_id?b.get(w.user_id):null})),total:u||0,totalPages:u?Math.ceil(u/qe):0}}async function Bt(t){const r=await H.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 o=null;if(i.user_id){const{data:u}=await r.from("profiles").select("*").eq("id",i.user_id).single();o=u}const c=i.order_items.map(u=>u.product_id).filter(Boolean),d=new Map;if(c.length>0){const{data:u}=await r.from("products").select("id, title, slug, product_media(media(file_path))").in("id",c);u&&u.forEach(p=>{let h=null;p.product_media&&p.product_media.length>0&&p.product_media[0].media&&(h=p.product_media[0].media.file_path),d.set(p.id,{title:p.title,slug:p.slug,image_url:h})})}const l=i.order_items.map(u=>({...u,product:u.product_id?d.get(u.product_id):null}));return{...i,order_items:l,customer:o}}async function $t(t,r){const s=H.createClient();let a=s.from("orders").select("*, order_items(*)");if(t&&(a=a.gte("created_at",t)),r){const l=new Date(r);l.setHours(23,59,59,999),a=a.lte("created_at",l.toISOString())}const{data:i,error:o}=await a.order("created_at",{ascending:!0});if(o)throw console.error("Error fetching report data:",o),new Error(`Failed to fetch report data: ${o.message}`);if(!i||i.length===0)return[];const c=Array.from(new Set(i.map(l=>l.user_id).filter(Boolean))),d=new Map;if(c.length>0){const{data:l}=await s.from("profiles").select("id, full_name, email").in("id",c);l&&l.forEach(u=>d.set(u.id,u))}return i.map(l=>({...l,customer:l.user_id?d.get(l.user_id):null}))}function rs(t,r){const s=xr.unparse(t),a=new Blob([s],{type:"text/csv;charset=utf-8;"}),i=document.createElement("a");if(i.download!==void 0){const o=URL.createObjectURL(a);i.setAttribute("href",o),i.setAttribute("download",r),i.style.visibility="hidden",document.body.appendChild(i),i.click(),document.body.removeChild(i)}}function ss(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 as(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",o=r.tax_details?.lines?.[0]?.rate?.display_name||"N/A",c=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":`${c}% (${o})`,"Total Taxable Amount":(r.subtotal/100).toFixed(2),"Tax Collected":(r.tax_total/100).toFixed(2),Currency:r.currency.toUpperCase()}})}function ns(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 zt(){const[t,r]=f.useState(!1),[s,a]=f.useState(!1),[i,o]=f.useState(""),[c,d]=f.useState(""),[l,u]=f.useState("general_ledger"),p=async()=>{if(!i||!c){Z.toast.error("Please select both start and end dates");return}a(!0);try{Z.toast.info("Generating report...");const h=await $t(i,c);if(!h||h.length===0){Z.toast.error("No orders found for the selected date range"),a(!1);return}let b=[];const g=`report_${l}_${i}_to_${c}`;switch(l){case"general_ledger":b=ss(h);break;case"tax_liability":b=as(h);break;case"currency_summary":b=ns(h);break}rs(b,`${g}.csv`),Z.toast.success("Download complete!"),r(!1)}catch(h){console.error("Export error:",h),Z.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(P.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(P.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:h=>o(h.target.value),className:"pl-8"}),e.jsx(P.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:c,onChange:h=>d(h.target.value),className:"pl-8"}),e.jsx(P.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:l,onValueChange:h=>u(h),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:p,disabled:s,className:"w-full bg-blue-600 hover:bg-blue-700 text-white",children:s?e.jsxs(e.Fragment,{children:[e.jsx(P.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(P.Download,{className:"mr-2 h-4 w-4"}),"Download Report"]})})})]})]})}const lt=(t,r="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:r}).format(t/100);async function is({searchParams:t}){const r=await t,s=Number(r.page)||1,a=r.status||"all",{data:i,totalPages:o}=await Dt(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(zt,{}),e.jsx(re,{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(c=>e.jsx(re,{href:`/cms/orders?page=1&status=${c}`,className:`px-3 py-1 rounded-full text-sm font-medium capitalize ${a===c?"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:c},c))}),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(c=>{const d=c.customer_details,l=d?.name||d?.email||c.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:[c.id.slice(0,8),"..."]}),e.jsx("td",{className:"px-4 py-3 font-medium",children:l}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(os,{status:c.status})}),e.jsx("td",{className:"px-4 py-3 capitalize text-gray-600 dark:text-gray-400",children:c.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:lt(c.total,c.currency||"usd")}),c.discount_total?e.jsxs("span",{className:"text-[10px] text-emerald-600",children:[c.coupon_code," -",lt(c.discount_total,c.currency||"usd")]}):null]})}),e.jsx("td",{className:"px-4 py-3 text-right text-gray-500 whitespace-nowrap",children:new Date(c.created_at||"").toLocaleDateString()}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(re,{href:`/cms/orders/${c.id}`,className:"text-blue-600 hover:underline dark:text-blue-400",children:"View"})})]},c.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 ",o]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(re,{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(re,{href:`/cms/orders?page=${Math.min(o,s+1)}&status=${a}`,className:`px-3 py-1 border rounded text-sm ${s>=o?"pointer-events-none opacity-50":"hover:bg-gray-50 dark:hover:bg-slate-800"}`,children:"Next"})]})]})]})}function os({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 cs({disabled:t=!1}){return e.jsxs(n.Button,{type:"button",variant:"outline",onClick:()=>window.print(),disabled:t,children:[e.jsx(P.Printer,{className:"mr-2 h-4 w-4"}),"Print / Save as PDF"]})}const ls=["pending","trial","paid","shipped","cancelled","refunded"];async function ds(){const t=H.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 us(){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 Ae.createClient(r,t,{auth:{autoRefreshToken:!1,persistSession:!1}})}async function ms(t,r){const s=await ds();if("error"in s)return{success:!1,error:s.error};if(!ls.includes(r))return{success:!1,error:"Invalid order status"};let a;try{a=us()}catch(c){return{success:!1,error:c instanceof Error?c.message:"Server configuration error"}}const{data:i,error:o}=await a.from("orders").update({status:r}).eq("id",t).select();return o?(console.error("Order status update error:",o),{success:!1,error:o.message}):!i||i.length===0?{success:!1,error:"Order not found or update failed."}:(r==="paid"&&(await Be({orderId:t,client:a}),await Oe(a,t)),{success:!0})}const dt=[{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 ps({orderId:t,currentStatus:r}){const s=le.useRouter(),[a,i]=f.useState(dt.some(h=>h.value===r)?r:"pending"),[o,c]=f.useState(null),[d,l]=f.useTransition(),u=f.useMemo(()=>a!==r,[r,a]),p=()=>{u&&(c(null),l(async()=>{try{const h=await ms(t,a);if(!h.success){c(h.error||"Failed to update order status.");return}s.refresh()}catch(h){console.error(h),c("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:h=>{i(h),c(null)},children:[e.jsx(n.SelectTrigger,{children:e.jsx(n.SelectValue,{placeholder:"Select status"})}),e.jsx(n.SelectContent,{children:dt.map(h=>e.jsx(n.SelectItem,{value:h.value,children:h.label},h.value))})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(n.Button,{type:"button",onClick:p,disabled:d||!u,children:d?"Saving...":"Save"})})]}),o?e.jsx("p",{className:"mt-2 text-xs text-red-600 dark:text-red-400",children:o}):u?null:e.jsx("p",{className:"mt-2 text-xs text-slate-500",children:"Status is already up to date."})]})}const ut=(t,r="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:r}).format(t/100);async function hs({params:t}){const{id:r}=await t,[s,a]=await Promise.all([Bt(r),Ge(r).catch(()=>null)]);s||le.notFound();const i=a?.order.customer_details??s.customer_details,o=A.buildInvoiceDocumentLabels(c=>c);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(re,{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(xs,{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(ps,{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(_e,{label:"Provider",value:s.provider||"stripe",capitalize:!0}),e.jsx(_e,{label:"Currency",value:(s.currency||"usd").toUpperCase()}),e.jsx(_e,{label:"Created",value:new Date(s.created_at||"").toLocaleDateString()}),e.jsx(_e,{label:"Invoice #",value:a?.order.invoice_number||"Pending assignment"}),e.jsx(_e,{label:"Paid on",value:a?.order.paid_at?new Date(a.order.paid_at).toLocaleString():"Pending payment"}),e.jsx(_e,{label:"Total",value:typeof s.total=="number"?ut(s.total,s.currency||"usd"):"--"}),s.discount_total?e.jsx(_e,{label:"Discount",value:`${s.coupon_code?`${s.coupon_code} `:""}-${ut(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(cs,{disabled:!a})}),e.jsx(A.InvoiceViewerShell,{invoice:a,labels:o,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 _e({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 xs({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 qt({productName:t,isIcon:r=!1,className:s,redirectTo:a,deleteAction:i}){const[o,c]=f.useTransition(),d=le.useRouter(),l=async u=>{u.preventDefault(),u.stopPropagation(),window.confirm(`Are you sure you want to delete "${t}"? This action cannot be undone.`)&&c(async()=>{try{await i(),a?d.push(a):d.refresh()}catch(p){console.error("Failed to delete product:",p),alert("Failed to delete product. Please try again.")}})};return r?e.jsx(n.Button,{variant:"ghost",size:"icon",onClick:l,disabled:o,className:`text-red-500 hover:text-red-600 hover:bg-red-50 ${s}`,title:"Delete Product",children:e.jsx(P.Trash2,{className:"h-4 w-4"})}):e.jsx(n.Button,{variant:"destructive",onClick:l,disabled:o,className:s,type:"button",children:o?"Deleting...":"Delete Product"})}const mt=process.env.NEXT_PUBLIC_R2_BASE_URL||"";function gs(t){return t?t.startsWith("http")||!mt?t:`${mt.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`:null}function fs({products:t,languageLabels:r,defaultCurrencyCode:s,deleteProductAction:a,bulkDeleteProductsAction:i,bulkDraftProductsAction:o}){const c=le.useRouter(),[d,l]=f.useState(()=>new Set),[u,p]=f.useState(""),[h,b]=f.useState(null),[g,w]=f.useState(null),[S,R]=f.useTransition(),_=f.useMemo(()=>{const E=u.trim().toLowerCase();return E?t.filter(W=>{const Q=r[String(W.language_id)]||"";return[W.title,W.sku,W.slug,W.status,Q].filter(Boolean).join(" ").toLowerCase().includes(E)}):t},[r,t,u]),N=f.useMemo(()=>t.map(E=>E.id),[t]),k=f.useMemo(()=>_.map(E=>E.id),[_]),y=f.useMemo(()=>t.filter(E=>d.has(E.id)),[t,d]).length,x=y>1,v=k.filter(E=>d.has(E)).length,B=k.length>0&&k.every(E=>d.has(E)),$=v>0&&!B;f.useEffect(()=>{const E=new Set(N);l(W=>{const Q=new Set(Array.from(W).filter(m=>E.has(m)));return Q.size===W.size?W:Q})},[N]);const L=E=>{l(W=>{const Q=new Set(W);return E?k.forEach(m=>Q.add(m)):k.forEach(m=>Q.delete(m)),Q})},q=(E,W)=>{l(Q=>{const m=new Set(Q);return W?m.add(E):m.delete(E),m})},ae=(E,W,Q)=>{if(y===0){b("Select at least one product first.");return}window.confirm(W)&&(b(null),w(E),R(async()=>{try{const m=await Q(Array.from(d));if(!m.success){b(m.error||"Bulk action failed. Please try again."),w(null);return}l(new Set),c.refresh()}catch(m){console.error("Bulk product action failed:",m),b("Bulk action failed. Please try again.")}finally{w(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(P.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:u,onChange:E=>p(E.target.value),placeholder:"Search products...",className:"h-9 pl-9","aria-label":"Search products"})]}),y>0?e.jsxs("span",{className:"text-sm font-medium text-foreground",children:[y," selected"]}):null,h?e.jsx("span",{className:"text-sm text-destructive",children:h}):null]}),x?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(n.Button,{variant:"outline",size:"sm",disabled:S,onClick:()=>ae("Moving to draft...",`Move ${y} selected products to draft?`,o),children:[e.jsx(P.Archive,{className:"mr-2 h-4 w-4"}),g==="Moving to draft..."?g:"Set Draft"]}),e.jsxs(n.Button,{variant:"destructive",size:"sm",disabled:S,onClick:()=>ae("Deleting...",`Delete ${y} selected products? This action cannot be undone.`,i),children:[e.jsx(P.Trash2,{className:"mr-2 h-4 w-4"}),g==="Deleting..."?g:"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:B?!0:$?"indeterminate":!1,onCheckedChange:E=>L(E===!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:_.length>0?_.map(E=>{const W=gs(E.product_media?.[0]?.media?.file_path||E.product_media?.[0]?.media?.object_key);return e.jsxs(n.TableRow,{"data-state":d.has(E.id)?"selected":void 0,children:[e.jsx(n.TableCell,{children:e.jsx(n.Checkbox,{checked:d.has(E.id),onCheckedChange:Q=>q(E.id,Q===!0),"aria-label":`Select ${E.title}`})}),e.jsx(n.TableCell,{children:W?e.jsx(gr,{src:W,alt:E.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(re,{href:`/cms/products/${E.id}/edit`,className:"hover:underline",children:E.title})}),e.jsx(n.TableCell,{children:E.sku}),e.jsx(n.TableCell,{children:e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:E.sale_price?"font-semibold text-primary":"",children:typeof(E.sale_price??E.price)=="number"?z.formatPrice(E.sale_price??E.price??0,s):"N/A"}),E.sale_price?e.jsx("span",{className:"text-sm text-muted-foreground line-through",children:z.formatPrice(E.price??0,s)}):null]})}),e.jsx(n.TableCell,{children:e.jsx(n.Badge,{variant:"outline",children:r[String(E.language_id)]||"N/A"})}),e.jsx(n.TableCell,{children:E.stock}),e.jsx(n.TableCell,{children:e.jsx("span",{className:`px-2 py-1 rounded text-xs ${E.status==="active"?"bg-green-100 text-green-800":E.status==="archived"?"bg-gray-100 text-gray-800":"bg-yellow-100 text-yellow-800"}`,children:E.status})}),e.jsxs(n.TableCell,{className:"text-right flex justify-end gap-2 items-center",children:[E.slug?e.jsx(re,{href:`/product/${E.slug}`,target:"_blank",rel:"noopener noreferrer",children:e.jsx(n.Button,{variant:"outline",size:"sm",children:"View Product"})}):null,e.jsx(re,{href:`/cms/products/${E.id}/edit`,children:e.jsx(n.Button,{variant:"ghost",size:"sm",children:"Edit"})}),e.jsx(qt,{productName:E.title,isIcon:!0,deleteAction:()=>a(E.id)})]})]},E.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 ys({title:t="Sync Full Store"}){const[r,s]=f.useState(!1),a=async()=>{s(!0);try{const i=await K.triggerFreemiusSync();i.error?Z.toast.error(i.error):Z.toast.success(`Full store sync complete! Found ${i.data?.count||0} products.`)}catch(i){Z.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(P.RefreshCw,{className:`w-4 h-4 ${r?"animate-spin":""}`}),r?"Syncing...":t]})}async function _s({searchParams:t,languageFilterNode:r,transferControlsNode:s}){const a=H.getServiceRoleSupabaseClient(),[i,{data:o}]=await Promise.all([H.getActiveLanguagesServerSide(),a.from("currencies").select("code, is_default").eq("is_active",!0).order("is_default",{ascending:!1}).order("code",{ascending:!0})]),c=t?.lang?parseInt(t.lang,10):void 0,{data:d}=await K.getProducts({languageId:c}),l=Object.fromEntries(i.map(p=>[String(p.id),p.code.toUpperCase()])),u=o?.find(p=>p.is_default)?.code||o?.[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(ys,{title:"Sync Full Store"}),e.jsx(re,{href:"/cms/products/new",children:e.jsx(n.Button,{children:"New Product"})})]})]}),e.jsx(fs,{products:d||[],languageLabels:l,defaultCurrencyCode:u,deleteProductAction:A.deleteProductAction,bulkDeleteProductsAction:A.bulkDeleteProductsAction,bulkDraftProductsAction:A.bulkDraftProductsAction})]})}function bs(t){const r=[];let s=[],a="",i=!1;for(let o=0;o<t.length;o+=1){const c=t[o],d=t[o+1];if(c==='"'){i&&d==='"'?(a+='"',o+=1):i=!i;continue}if(c===","&&!i){s.push(a),a="";continue}if((c===`
|
|
100
|
-
`||c==="\r")&&!i){c==="\r"&&d===`
|
|
101
|
-
`&&(o+=1),(a.length>0||s.length>0)&&(s.push(a),r.push(s)),s=[],a="";continue}a+=c}return(a.length>0||s.length>0)&&(s.push(a),r.push(s)),r.filter(o=>o.some(c=>c.trim().length>0))}function vs(t){return t.sku}async function js(t){try{const r=Math.max(0,Math.trunc(t.stock));return await ce.setSharedInventoryQuantity({sku:t.sku,stock:r}),Y.revalidatePath("/cms/products"),Y.revalidatePath("/cms/products/inventory"),{success:!0,itemKey:vs(t),stock:r}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to update inventory."}}}async function Cs(t){try{const r=bs(t);if(r.length<2)return{success:!1,error:"The CSV file is empty."};const[s,...a]=r,i=s.map(p=>p.trim().toLowerCase()),o=i.indexOf("sku"),c=i.indexOf("stock");if(o===-1||c===-1)return{success:!1,error:"The CSV format is invalid. Please import a file exported from the Inventory page."};const d=H.getServiceRoleSupabaseClient();let l=0;for(const p of a){const h=(p[o]||"").trim(),b=Number.parseInt((p[c]||"").trim(),10);if(h){if(!Number.isFinite(b)||b<0)return{success:!1,error:`Invalid stock value for SKU "${h}".`};await ce.setSharedInventoryQuantity({sku:h,stock:b},d),l+=1}}const u=await ce.getInventoryItems(d);return Y.revalidatePath("/cms/products"),Y.revalidatePath("/cms/products/inventory"),{success:!0,updatedCount:l,items:u}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to import inventory CSV."}}}function ws(t){const r=String(t??"");return/[",\n]/.test(r)?`"${r.replace(/"/g,'""')}"`:r}function Ns(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=>ws(i)).join(",")).join(`
|
|
102
|
-
`)}function Ss(t){return t.usageType==="mixed"?"Shared SKU":t.usageType==="variant"?`Variant SKU ${t.sku}`:"Simple Product"}function ks(t){return t.usageType==="variant"?"secondary":"outline"}function Es({initialItems:t}){const[r,s]=f.useState(t),[a,i]=f.useState(()=>t.reduce((_,N)=>(_[N.key]=String(N.stock),_),{})),[o,c]=f.useState(""),[d,l]=f.useTransition(),[u,p]=f.useState(null),h=f.useRef(null),b=f.useMemo(()=>{const _=o.trim().toLowerCase();return _?r.filter(N=>N.sku.toLowerCase().includes(_)||N.productTitles.join(" ").toLowerCase().includes(_)||N.parentProductSkus.join(" ").toLowerCase().includes(_)||N.languages.join(" ").toLowerCase().includes(_)):r},[r,o]),g=()=>{const _=Ns(r),N=new Blob([_],{type:"text/csv;charset=utf-8;"}),k=URL.createObjectURL(N),F=document.createElement("a");F.href=k,F.download="inventory-export.csv",F.click(),URL.revokeObjectURL(k)},w=_=>{const N=a[_.key]??String(_.stock),k=Number.parseInt(N,10);if(!Number.isFinite(k)||k<0){Z.toast.error("Stock must be a non-negative whole number.");return}p(_.key),l(async()=>{const F=await js({sku:_.sku,stock:k});if(!F.success){Z.toast.error(F.error||"Failed to update inventory."),p(null);return}const y=typeof F.stock=="number"?F.stock:k;s(x=>x.map(v=>v.key===_.key?{...v,stock:y}:v)),i(x=>({...x,[_.key]:String(y)})),p(null),Z.toast.success(`Inventory updated for ${_.sku}.`)})},S=()=>{h.current?.click()},R=async _=>{const N=await _.text();p("import"),l(async()=>{const k=await Cs(N);if(!k.success){Z.toast.error(k.error||"Failed to import inventory CSV."),p(null);return}const F=k.items||[];s(F),i(F.reduce((y,x)=>(y[x.key]=String(x.stock),y),{})),p(null),Z.toast.success(`Imported ${k.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(P.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(n.Input,{value:o,onChange:_=>c(_.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:h,type:"file",accept:".csv,text/csv",className:"hidden",onChange:_=>{const N=_.target.files?.[0];N&&R(N),_.currentTarget.value=""}}),e.jsxs(n.Button,{type:"button",variant:"outline",onClick:S,disabled:d,children:[e.jsx(P.Upload,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(n.Button,{type:"button",variant:"outline",onClick:g,disabled:d,children:[e.jsx(P.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:b.length>0?b.map(_=>{const N=a[_.key]??String(_.stock),k=Number.parseInt(N,10),F=Number.isFinite(k)&&k!==_.stock,y=u===_.key;return e.jsxs(n.TableRow,{children:[e.jsx(n.TableCell,{className:"font-mono text-sm",children:_.sku}),e.jsx(n.TableCell,{children:e.jsx(n.Badge,{variant:ks(_),children:Ss(_)})}),e.jsx(n.TableCell,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:_.productTitles.join(", ")}),_.usageType!=="product"?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Parent SKU",_.parentProductSkus.length>1?"s":"",":"," ",e.jsx("span",{className:"font-mono",children:_.parentProductSkus.join(", ")})]}):null]})}),e.jsx(n.TableCell,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:_.languages.map(x=>e.jsx(n.Badge,{variant:"outline",children:x},`${_.key}:${x}`))})}),e.jsx(n.TableCell,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:_.statuses.map(x=>e.jsx(n.Badge,{variant:"outline",children:x},`${_.key}:${x}`))})}),e.jsx(n.TableCell,{children:e.jsx(n.Input,{type:"number",min:0,step:1,value:N,disabled:d,onChange:x=>i(v=>({...v,[_.key]:x.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||d,onClick:()=>i(x=>({...x,[_.key]:String(_.stock)})),children:[e.jsx(P.RotateCcw,{className:"mr-2 h-4 w-4"}),"Reset"]}),e.jsxs(n.Button,{type:"button",size:"sm",disabled:!F||d,onClick:()=>w(_),children:[e.jsx(P.Save,{className:"mr-2 h-4 w-4"}),y?"Saving...":"Save"]})]})})]},_.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 Ts(){const t=await ce.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(Es,{initialItems:t})]})}function Ps({attributes:t,languages:r,createAttributeAction:s,deleteAttributeAction:a,createTermAction:i,deleteTermAction:o,reorderTermsAction:c,updateTranslationsAction:d}){const l=le.useRouter(),[u,p]=f.useState(""),[h,b]=f.useState(null),[g,w]=f.useState(null),[S,R]=f.useState(null),[_,N]=f.useState(null),[k,F]=f.useState({}),[y,x]=f.useState(()=>t.reduce((m,T)=>(m[T.id]=T.name_translations||{},m),{})),[v,B]=f.useState(()=>t.reduce((m,T)=>{for(const M of T.terms)m[M.id]=M.value_translations||{};return m},{})),$=r.filter(m=>!m.is_default),L=async m=>{m.preventDefault();const T=await s({name:u});if(!T.success){alert(T.error||"Failed to create attribute.");return}p(""),l.refresh()},q=async(m,T)=>{m.preventDefault(),b(T);const M=await i({attributeId:T,value:k[T]||""});if(b(null),!M.success){alert(M.error||"Failed to create term.");return}F(X=>({...X,[T]:""})),l.refresh()},ae=async m=>{if(!window.confirm("Delete this attribute and all of its terms?"))return;const M=await a(m);if(!M.success){alert(M.error||"Failed to delete attribute.");return}l.refresh()},E=async m=>{w(m);const T=await o(m);if(w(null),!T.success){alert(T.error||"Failed to delete term.");return}l.refresh()},W=async(m,T,M)=>{const X=m.terms.findIndex(V=>V.id===T),oe=X+M;if(X===-1||oe<0||oe>=m.terms.length)return;const j=[...m.terms],[O]=j.splice(X,1);j.splice(oe,0,O),R(m.id);const I=await c({attributeId:m.id,orderedTermIds:j.map(V=>V.id)});if(R(null),!I.success){alert(I.error||"Failed to reorder terms.");return}l.refresh()},Q=async m=>{N(m.id);const T=await d({attributeId:m.id,nameTranslations:y[m.id]||{},termTranslations:m.terms.map(M=>({termId:M.id,valueTranslations:v[M.id]||{}}))});if(N(null),!T.success){alert(T.error||"Failed to save translations.");return}l.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:u,onChange:m=>p(m.target.value),placeholder:"Material, Size, Color..."})]}),e.jsxs(n.Button,{type:"submit",disabled:!u.trim(),children:[e.jsx(P.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(m=>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:m.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:m.slug})]}),e.jsx(n.Button,{type:"button",variant:"ghost",size:"icon",onClick:()=>ae(m.id),className:"text-muted-foreground hover:text-destructive",children:e.jsx(P.Trash2,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"mt-4 space-y-2",children:m.terms.map((T,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:T.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:()=>W(m,T.id,-1),disabled:M===0||S===m.id,children:e.jsx(P.ChevronUp,{className:"h-4 w-4"})}),e.jsx(n.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>W(m,T.id,1),disabled:M===m.terms.length-1||S===m.id,children:e.jsx(P.ChevronDown,{className:"h-4 w-4"})}),e.jsx(n.Button,{type:"button",variant:"ghost",size:"icon",onClick:()=>E(T.id),className:"h-8 w-8 text-muted-foreground hover:text-destructive",disabled:g===T.id,children:e.jsx(P.Trash2,{className:"h-4 w-4"})})]})]},T.id))}),e.jsxs("form",{onSubmit:T=>q(T,m.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-${m.id}`,children:"Add Term"}),e.jsx(n.Input,{id:`term-input-${m.id}`,value:k[m.id]||"",onChange:T=>F(M=>({...M,[m.id]:T.target.value})),placeholder:`Add a term for ${m.name}`})]}),e.jsxs(n.Button,{type:"submit",variant:"outline",disabled:!k[m.id]?.trim()||h===m.id,children:[e.jsx(P.Plus,{className:"mr-2 h-4 w-4"}),h===m.id?"Saving...":"Add Term"]})]}),$.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:()=>Q(m),disabled:_===m.id,children:_===m.id?"Saving...":"Save Translations"})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:$.map(T=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs(n.Label,{htmlFor:`attribute-translation-${m.id}-${T.code}`,children:["Attribute Name (",T.name,")"]}),e.jsx(n.Input,{id:`attribute-translation-${m.id}-${T.code}`,value:y[m.id]?.[T.code]||"",onChange:M=>x(X=>({...X,[m.id]:{...X[m.id]||{},[T.code]:M.target.value}})),placeholder:m.name})]},`${m.id}-${T.code}`))}),e.jsx("div",{className:"space-y-3",children:m.terms.map(T=>e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.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:$.map(M=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:`term-translation-${T.id}-${M.code}`,children:M.name}),e.jsx(n.Input,{id:`term-translation-${T.id}-${M.code}`,value:v[T.id]?.[M.code]||"",onChange:X=>B(oe=>({...oe,[T.id]:{...oe[T.id]||{},[M.code]:X.target.value}})),placeholder:T.value})]},`${T.id}-${M.code}`))})]},`translations-${T.id}`))})]})]},m.id))})]})}async function As(){const[t,r]=await Promise.all([K.getGlobalProductAttributes(),H.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(re,{href:"/cms/products",children:e.jsx(P.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(Ps,{attributes:s,createAttributeAction:A.createProductAttributeAction,deleteAttributeAction:A.deleteProductAttributeAction,createTermAction:A.createProductAttributeTermAction,deleteTermAction:A.deleteProductAttributeTermAction,reorderTermsAction:A.reorderProductAttributeTermsAction,updateTranslationsAction:A.updateProductAttributeTranslationsAction,languages:r})]})}async function Is({mediaPickerNode:t,availableLanguagesProp:r,translationGroupId:s,targetLanguageId:a,initialData:i}){const[o,c,d,l]=await Promise.all([Se(),$e(),K.getGlobalProductAttributes(),H.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(S=>S.data||[])]),u=(l||[]).map(S=>D.normalizeCurrencyRecord(S)),p=(d||[]).map(S=>({id:S.id,name:S.name,name_translations:S.name_translations||{},slug:S.slug,terms:(S.product_attribute_terms||[]).map(R=>({...R,value_translations:R.value_translations||{}}))})),h=r.find(S=>S.id===i?.language_id)?.code||r.find(S=>S.id===(a?parseInt(a,10):void 0))?.code||r.find(S=>S.is_default)?.code,{attributes:b,variants:g}=He.mapRawVariantRelations(i?.product_variants||[],h),w=i&&{...i,variation_attributes:i.variation_attributes||b.map(S=>({attribute_id:S.id,term_ids:S.terms.map(R=>R.id)})),variants:i.variants||g.map(S=>({...S,upc:S.upc??null,price:S.price/100,prices:Object.entries(S.prices||{}).reduce((R,[_,N])=>(R[_]=z.minorUnitAmountToMajor(N,_),R),{}),sale_price:typeof S.sale_price=="number"?S.sale_price/100:null,sale_prices:Object.entries(S.sale_prices||{}).reduce((R,[_,N])=>(R[_]=typeof N=="number"?z.minorUnitAmountToMajor(N,_):null,R),{}),main_media_id:S.main_media_id??null,main_image_url:S.image_url??null}))};return e.jsx("div",{className:"p-8",children:e.jsx(A.ProductForm,{mediaPickerNode:t,availableLanguagesProp:r,globalAttributesProp:p,currenciesProp:u,translationGroupId:s,targetLanguageId:a,initialData:w,enabledProviders:o,configStatus:c,createAction:A.createProductAction})})}function Rs({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(Fs,{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 Fs({pricing:t}){const[r,s]=f.useTransition(),a=(i,o)=>{const c=o===""?null:parseFloat(o);o!==""&&Number.isNaN(c)||s(async()=>{const{success:d,error:l}=await K.updateFreemiusOverride(t.id,{[i]:c});d?Z.toast.success("Pricing override saved"):Z.toast.error(l||"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 Us({params:t,mediaPickerNode:r,availableLanguagesProp:s,languageSwitcherNode:a,copyContentNode:i,translationCtaNode:o}){const{id:c}=await t,d=await K.getProduct(c);d||le.notFound();const l=d.product_type==="digital"||d.payment_provider==="freemius",[u,p,h,b,g]=await Promise.all([Se(),$e(),l&&d.freemius_product_id?K.getFreemiusPricingByProductId(d.id):Promise.resolve(null),K.getGlobalProductAttributes(),H.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(y=>y.data||[])]),w=(g||[]).map(y=>D.normalizeCurrencyRecord(y)),S=s.find(y=>y.id===d.language_id)?.code,{attributes:R,variants:_}=He.mapRawVariantRelations(d.product_variants||[],S),N=(b||[]).map(y=>({id:y.id,name:y.name,name_translations:y.name_translations||{},slug:y.slug,terms:(y.product_attribute_terms||[]).map(x=>({...x,value_translations:x.value_translations||{}}))})),k=qt,F=Rs;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(re,{href:"/cms/products",children:e.jsx(P.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:d.title,children:d.title})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[a,i,o,k?e.jsx(k,{productName:d.title,redirectTo:"/cms/products",className:"border-red-200 hover:bg-red-50 hover:text-red-700",deleteAction:A.deleteProductAction.bind(null,d.id)}):null,d.slug&&d.status==="active"&&e.jsx(n.Button,{variant:"outline",asChild:!0,children:e.jsxs(re,{href:`/product/${d.slug}`,target:"_blank",children:[e.jsx(P.ExternalLink,{className:"w-4 h-4 mr-2"}),"View"]})})]})]}),e.jsx(A.ProductForm,{initialData:{id:d.id,title:d.title,slug:d.slug,sku:d.sku,upc:d.upc??void 0,stock:d.stock||0,price:d.price||0,prices:Object.entries(d.prices||{}).reduce((y,[x,v])=>(y[x]=z.minorUnitAmountToMajor(v,x),y),{}),is_taxable:typeof d.is_taxable=="boolean"?d.is_taxable:!0,product_type:d.product_type,payment_provider:d.payment_provider,status:d.status,short_description:d.short_description??void 0,description_json:d.description_json,sale_price:typeof d.sale_price=="number"?d.sale_price:void 0,sale_prices:Object.entries(d.sale_prices||{}).reduce((y,[x,v])=>(y[x]=typeof v=="number"?z.minorUnitAmountToMajor(v,x):null,y),{}),freemius_plan_id:d.freemius_plan_id??void 0,freemius_product_id:d.freemius_product_id??void 0,trial_period_days:d.trial_period_days??0,trial_requires_payment_method:d.trial_requires_payment_method??!1,language_id:d.language_id,translation_group_id:d.translation_group_id,product_media:d.product_media,variation_attributes:R.map(y=>({attribute_id:y.id,term_ids:y.terms.map(x=>x.id)})),variants:_.map(y=>({...y,upc:y.upc??null,price:y.price/100,prices:Object.entries(y.prices||{}).reduce((x,[v,B])=>(x[v]=z.minorUnitAmountToMajor(B,v),x),{}),sale_price:typeof y.sale_price=="number"?y.sale_price/100:null,sale_prices:Object.entries(y.sale_prices||{}).reduce((x,[v,B])=>(x[v]=typeof B=="number"?z.minorUnitAmountToMajor(B,v):null,x),{}),main_media_id:y.main_media_id??null,main_image_url:y.image_url??null}))},isEdit:!0,mediaPickerNode:r,availableLanguagesProp:s,globalAttributesProp:N,currenciesProp:w,enabledProviders:u,configStatus:p,updateAction:A.updateProductAction.bind(null,d.id),freemiusDashboardNode:l&&d.freemius_product_id&&h&&F?e.jsx(F,{productId:d.id,freemiusProductId:d.freemius_product_id,plans:h}):void 0})]})}function Ls({productId:t,currentLanguageId:r,translationGroupId:s,allSiteLanguages:a}){const[i,o]=f.useState(!1),[c,d]=f.useState(null),[l,u]=f.useState([]),[p,h]=f.useState(!1),[b,g]=f.useState(null),[w,S]=f.useTransition(),R=le.useRouter();f.useEffect(()=>{i&&s&&(async()=>{h(!0);try{const y=(await K.getProductTranslations(s)).filter(x=>x.id!==t);u(y)}catch(F){console.error("Error fetching translations:",F)}finally{h(!1)}})()},[i,s,t]);const _=async()=>{if(!c){g({type:"error",text:"Please select a source version to copy from."});return}g(null),S(async()=>{const k=await K.copyProductFromLanguageAction(t,c);k.success?(g({type:"success",text:"Content copied successfully. The page will now refresh."}),setTimeout(()=>{o(!1),R.refresh()},1500)):g({type:"error",text:k.error||"Failed to copy content."})})},N=a.find(k=>k.id===r);return e.jsxs(n.Dialog,{open:i,onOpenChange:o,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:e.jsxs(n.Button,{variant:"outline",title:"Copy content from another language",children:[e.jsx(P.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 (",N?.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:k=>d(k),disabled:w||p,value:c||void 0,children:[e.jsx(n.SelectTrigger,{id:"sourceProduct",children:e.jsx(n.SelectValue,{placeholder:p?"Loading versions...":"Select a version..."})}),e.jsx(n.SelectContent,{children:l.length>0?l.map(k=>{const F=a.find(y=>y.id===k.language_id);return e.jsxs(n.SelectItem,{value:k.id,children:[k.title," (",F?.name||"Unknown Language",")"]},k.id)}):e.jsx(n.SelectItem,{value:"none",disabled:!0,children:"No other versions available"})})]})]}),b&&e.jsxs("div",{className:`p-3 rounded-md text-sm flex items-center gap-2 ${b.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:[b.type==="success"?e.jsx(P.CheckCircle2,{className:"h-5 w-5"}):e.jsx(P.AlertCircle,{className:"h-5 w-5"}),b.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:_,disabled:w||!c||c==="none",children:w?"Copying...":"Copy Content & Replace"})]})]})]})}function Ms({initialCategories:t=[],languages:r=[],createCategory:s,updateCategory:a,deleteCategory:i}){const o=le.useRouter(),[c,d]=f.useState(t),[l,u]=f.useState(!1),[p,h]=f.useState(null),[b,g]=f.useState(""),[w,S]=f.useState(""),[R,_]=f.useState(""),[N,k]=f.useState({}),[F,y]=f.useState({}),[x,v]=f.useState(!1),B=(r||[]).filter(m=>!m.is_default);f.useEffect(()=>{d(t)},[t]);const $=m=>m.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,""),L=m=>{const T=m.target.value;g(T),!x&&!p&&S($(T))},q=m=>{S($(m.target.value)),v(!0)},ae=m=>{h(m),g(m.name),S(m.slug),_(m.description||""),k(m.name_translations||{}),y(m.description_translations||{}),v(!0)},E=()=>{h(null),g(""),S(""),_(""),k({}),y({}),v(!1)},W=async m=>{if(m.preventDefault(),!b.trim()){Z.toast.error("Category name is required.");return}u(!0);const T=Z.toast.loading(p?"Updating category...":"Creating category...");try{const M={name:b.trim(),slug:w.trim()||void 0,description:R.trim()||void 0,nameTranslations:N,descriptionTranslations:F};let X;p?X=await a(p.id,M):X=await s(M),X.success?(Z.toast.success(p?"Category updated successfully!":"Category created successfully!",{id:T}),E(),o.refresh()):Z.toast.error(X.error||"Failed to save category.",{id:T})}catch(M){Z.toast.error(M.message||"An unexpected error occurred.",{id:T})}finally{u(!1)}},Q=async m=>{const T=`Are you sure you want to delete the category "${m.name}"? This will detach it from any assigned products.`;if(!window.confirm(T))return;u(!0);const M=Z.toast.loading("Deleting category...");try{const X=await i(m.id);X.success?(Z.toast.success("Category deleted successfully!",{id:M}),p?.id===m.id&&E(),o.refresh()):Z.toast.error(X.error||"Failed to delete category.",{id:M})}catch(X){Z.toast.error(X.message||"An unexpected error occurred.",{id:M})}finally{u(!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(P.FolderPlus,{className:"h-5 w-5 text-amber-500"}),e.jsx("h2",{className:"text-base font-bold tracking-tight",children:p?"Edit Category":"Add New Category"})]}),e.jsxs("form",{onSubmit:W,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:b,onChange:L,disabled:l,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"}),!x&&!p&&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:w,onChange:q,disabled:l,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:m=>_(m.target.value),disabled:l,className:"text-sm min-h-[90px] resize-none"})]}),B.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"}),B.map(m=>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:m.name}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(n.Label,{htmlFor:`name-${m.code}`,className:"text-[10px] uppercase font-bold text-muted-foreground tracking-wider leading-none",children:["Name (",m.code,")"]}),e.jsx(n.Input,{id:`name-${m.code}`,placeholder:`Translation for ${b||"Name"}`,value:N[m.code]||"",onChange:T=>k(M=>({...M,[m.code]:T.target.value})),disabled:l,className:"h-8 text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(n.Label,{htmlFor:`desc-${m.code}`,className:"text-[10px] uppercase font-bold text-muted-foreground tracking-wider leading-none",children:["Description (",m.code,")"]}),e.jsx(n.Textarea,{id:`desc-${m.code}`,placeholder:"Translation for Description",value:F[m.code]||"",onChange:T=>y(M=>({...M,[m.code]:T.target.value})),disabled:l,className:"text-sm min-h-[60px] resize-none"})]})]},m.code))]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx(n.Button,{type:"submit",disabled:l,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:l?e.jsxs(e.Fragment,{children:[e.jsx(P.Loader2,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}),"Saving..."]}):p?"Update Category":"Create Category"}),p&&e.jsx(n.Button,{type:"button",onClick:E,disabled:l,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(P.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."})]})]}),c.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(P.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:c.map(m=>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:m.name}),m.description&&e.jsx("div",{className:"text-[10px] text-muted-foreground mt-0.5 max-w-xs truncate leading-normal",title:m.description,children:m.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:["/",m.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:m.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:l,onClick:()=>ae(m),className:"h-7 w-7 opacity-85 hover:opacity-100 group-hover:border-amber-500/30 cursor-pointer",title:"Edit Category",children:e.jsx(P.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:l,onClick:()=>Q(m),className:"h-7 w-7 opacity-85 hover:opacity-100 group-hover:border-red-500/30 cursor-pointer",title:"Delete Category",children:e.jsx(P.Trash2,{className:"h-3.5 w-3.5 text-muted-foreground group-hover:text-red-500"})})]})})]},m.id))})]})})]})})]})}async function Os(){const[t,r]=await Promise.all([K.getCategoriesWithCount(),H.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(re,{href:"/cms/products",children:e.jsx(P.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(Ms,{initialCategories:t,createCategory:A.createCategoryAction,updateCategory:A.updateCategoryAction,deleteCategory:A.deleteCategoryAction,languages:r})]})}async function Kt(t){const r=await H.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 Y.revalidatePath("/cms/payments"),Y.revalidatePath("/cms/taxes"),Y.revalidatePath("/","layout"),{success:!0}}function Ds({initialEnabledProviders:t,configStatus:r,saveAction:s}){const[a,i]=f.useState(t),o=r?.stripe?.hasKeys,c=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(pt,{id:"stripe-enabled",label:"Stripe for Physical Products",description:"Use Stripe Checkout for physical merchandise and other shippable goods.",checked:a.stripe,disabled:!o,onCheckedChange:d=>i(l=>({...l,stripe:d})),ready:o,children:o?e.jsxs("div",{className:"mt-2 text-sm text-green-600 flex items-center gap-2",children:[e.jsx(P.CheckCircle2,{className:"w-4 h-4"}),e.jsx("span",{children:"Ready to process physical product checkout"})]}):e.jsx(ht,{provider:"Stripe",missingKeys:r.stripe.missing,docsUrl:"https://dashboard.stripe.com/apikeys",docsLabel:"Stripe Dashboard -> Developers -> API Keys"})}),e.jsx(pt,{id:"freemius-enabled",label:"Freemius for Digital Products",description:"Use Freemius for software licenses, SaaS plans, and other digital products.",checked:a.freemius,disabled:!c,onCheckedChange:d=>i(l=>({...l,freemius:d})),ready:c,children:c?e.jsxs("div",{className:"mt-2 text-sm text-green-600 flex items-center gap-2",children:[e.jsx(P.CheckCircle2,{className:"w-4 h-4"}),e.jsx("span",{children:"Ready to process digital product checkout"})]}):e.jsx(ht,{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(Bs,{})})]})]})]})}function Bs(){const{pending:t}=fr.useFormStatus();return e.jsx(n.Button,{type:"submit",disabled:t,children:t?"Saving...":"Save Changes"})}function pt({id:t,label:r,description:s,checked:a,disabled:i,ready:o,onCheckedChange:c,children:d}){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:l=>c(!!l),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}),!o&&e.jsx("p",{className:"text-xs text-amber-700",children:"This provider cannot be enabled until all required environment variables are present."}),d]})]})})}function ht({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(P.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 $s(){const[t,r]=await Promise.all([Se(),$e()]);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 Kt(i)}return e.jsx(Ds,{initialEnabledProviders:t,configStatus:r,saveAction:s})}function Vt(t){return Object.entries(t||{}).reduce((r,[s,a])=>{const i=s.trim().toLowerCase(),o=a.trim();return i&&o&&(r[i]=o),r},{})}async function Ht(t){const r=H.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"),o=await te.getEcommerceInventorySettings(r),{error:c}=await te.upsertEcommerceInventorySettings(r,{trackQuantities:i,enableTaxes:o.enableTaxes,taxCalculationMode:o.taxCalculationMode});if(c)throw new Error(c.message);Y.revalidatePath("/cms/shipping"),le.redirect("/cms/shipping?success=Inventory settings updated")}function Gt(t){const r=new Map;for(const s of t){const a=se.normalizeCountryCode(s.country_code);if(!a)continue;const i=se.normalizeSubdivisionCode(a,s.state_code)||null,o=`${a}:${i??"*"}`;r.set(o,{country_code:a,state_code:i})}return[...r.values()]}async function Wt(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 Qt(t,r,s){const a=H.getServiceRoleSupabaseClient(),i=Gt(s),{data:o,error:c}=await a.from("shipping_zones").insert({name:t,priority_order:r}).select().single();if(c||!o)return{error:c?.message||"Failed to create zone"};if(i.length>0){const d=i.map(u=>({zone_id:o.id,country_code:u.country_code,state_code:u.state_code??null})),{error:l}=await a.from("shipping_zone_locations").insert(d);if(l)return{error:l.message}}return Y.revalidatePath("/cms/shipping"),{success:!0}}async function Xt(t,r,s,a){const i=H.getServiceRoleSupabaseClient(),o=Gt(a),{error:c}=await i.from("shipping_zones").update({name:r,priority_order:s,updated_at:new Date().toISOString()}).eq("id",t);if(c)return{error:c.message||"Failed to update zone"};const{error:d}=await i.from("shipping_zone_locations").delete().eq("zone_id",t);if(d)return{error:"Failed to refresh locations"};if(o.length>0){const l=o.map(p=>({zone_id:t,country_code:p.country_code,state_code:p.state_code??null})),{error:u}=await i.from("shipping_zone_locations").insert(l);if(u)return{error:u.message}}return Y.revalidatePath("/cms/shipping"),{success:!0}}async function Yt(t){const r=H.getServiceRoleSupabaseClient(),{error:s}=await r.from("shipping_zones").delete().eq("id",t);return s?{error:s.message}:(Y.revalidatePath("/cms/shipping"),{success:!0})}async function Zt(t,r){const s=H.getServiceRoleSupabaseClient(),a=await Wt(s);if("error"in a)return{error:a.error};const i=Ne.sanitizeShippingRateAmountMaps({currencies:a.currencies.map(c=>D.normalizeCurrencyRecord(c)),mode:r.currencyPricingMode,sourceCurrencyCode:r.sourceCurrencyCode,costAmounts:r.costAmounts,minOrderAmounts:r.minOrderAmounts,fallbackCostAmount:r.cost,fallbackMinOrderAmount:r.minOrderAmount}),{error:o}=await s.from("shipping_zone_methods").insert({zone_id:t,name:r.name.trim(),name_translations:Vt(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 o?{error:o.message}:(Y.revalidatePath("/cms/shipping"),{success:!0})}async function Jt(t,r){const s=H.getServiceRoleSupabaseClient(),a=await Wt(s);if("error"in a)return{error:a.error};const i=Ne.sanitizeShippingRateAmountMaps({currencies:a.currencies.map(c=>D.normalizeCurrencyRecord(c)),mode:r.currencyPricingMode,sourceCurrencyCode:r.sourceCurrencyCode,costAmounts:r.costAmounts,minOrderAmounts:r.minOrderAmounts,fallbackCostAmount:r.cost,fallbackMinOrderAmount:r.minOrderAmount}),{error:o}=await s.from("shipping_zone_methods").update({name:r.name.trim(),name_translations:Vt(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 o?{error:o.message}:(Y.revalidatePath("/cms/shipping"),{success:!0})}async function er(t){const r=H.getServiceRoleSupabaseClient(),{error:s}=await r.from("shipping_zone_methods").delete().eq("id",t);return s?{error:s.message}:(Y.revalidatePath("/cms/shipping"),{success:!0})}function xt(t=[]){return[...new Set(t.map(r=>r.country_code))]}function gt(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 zs(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 ft({mode:t="create",initialData:r}){const[s,a]=f.useState(!1),i=t==="edit",[o,c]=f.useState(r?.name||""),[d,l]=f.useState(r?.priority_order||0),[u,p]=f.useState(xt(r?.locations)),[h,b]=f.useState(gt(r?.locations)),[g,w]=f.useState(""),[S,R]=f.useState(!1);f.useEffect(()=>{s&&(c(r?.name||""),l(r?.priority_order||0),p(xt(r?.locations)),b(gt(r?.locations)),w(""))},[r,s]);const _=f.useMemo(()=>{const x=g.trim().toLowerCase();return x?se.countries.filter(v=>v.name.toLowerCase().includes(x)||v.code.toLowerCase().includes(x)):se.countries},[g]),N=f.useMemo(()=>se.countries.filter(x=>u.includes(x.code)),[u]),k=x=>{p(v=>v.includes(x)?v.filter(B=>B!==x):[...v,x]),b(v=>{if(v[x]){const B={...v};return delete B[x],B}return v})},F=(x,v)=>{b(B=>{const $=new Set(B[x]||[]);return $.has(v)?$.delete(v):$.add(v),{...B,[x]:[...$]}})},y=async x=>{if(x.preventDefault(),!o||u.length===0)return;R(!0);const v=zs(u,h),B=i&&r?.id?await Xt(r.id,o,d,v):await Qt(o,d,v);R(!1),B.success?(a(!1),i||(c(""),l(0),p([]),b({}),w(""))):B.error&&alert(B.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(P.Edit2,{className:"h-4 w-4"})}):e.jsxs(n.Button,{className:"gap-2 shadow-sm",children:[e.jsx(P.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:y,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:o,onChange:x=>c(x.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:d,onChange:x=>l(Number(x.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 (",u.length,")"]}),e.jsxs("div",{className:"relative w-full max-w-xs",children:[e.jsx(P.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:g,onChange:x=>w(x.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:_.map(x=>{const v=u.includes(x.code);return e.jsxs("div",{className:`flex items-center space-x-2 rounded-md border p-2 transition-colors ${v?"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-${x.code}`,checked:v,onCheckedChange:()=>k(x.code)}),e.jsxs("label",{htmlFor:`country-${x.code}`,className:"flex-1 cursor-pointer text-xs py-1",children:[x.name," (",x.code,")"]})]},x.code)})})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(P.MapPin,{className:"h-4 w-4 text-slate-500"}),e.jsx(n.Label,{className:"text-sm font-semibold",children:"States / Provinces"})]}),N.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:N.map(x=>{const v=se.getStatesForCountry(x.code),B=h[x.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:[x.name," (",x.code,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.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:B.length>0?`${B.length} selected`:"Whole country"})]}),v.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:v.map($=>{const L=B.includes($.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:`${x.code}-${$.code}`,checked:L,onCheckedChange:()=>F(x.code,$.code)}),e.jsxs("label",{htmlFor:`${x.code}-${$.code}`,className:"flex-1 cursor-pointer text-xs py-1",children:[$.name," (",$.code,")"]})]},`${x.code}-${$.code}`)})}):null]})},x.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:S||!o||u.length===0,children:S?i?"Updating...":"Creating...":i?"Save Changes":"Create Zone"})]})]})})]})}function Pe(t,r){if(typeof t!="number")return"";const s=z.minorUnitAmountToMajor(t,r);return z.getCurrencyMinorUnitFactor(r)===1?s.toFixed(0):s.toFixed(2)}function qs(t){return t.reduce((r,s)=>(r[s.code]=z.getCurrencyMinorUnitFactor(s.code)===1?"0":"0.00",r),{})}function we(t,r){const s=String(t||"").trim();if(!s)return null;const a=Number(s);return!Number.isFinite(a)||a<0?null:z.majorUnitAmountToMinor(a,r)}function yt(t){return t.currencies.reduce((r,s)=>(r[s.code]=Pe(t.amounts[s.code],s.code),r),{})}function _t({zoneId:t,zoneName:r,languages:s,currencies:a=[],defaultCurrencyCode:i="USD",mode:o="create",initialData:c}){const[d,l]=f.useState(!1),u=o==="edit",p=f.useMemo(()=>s.find(j=>j.is_default)||s[0]||null,[s]),h=f.useMemo(()=>s.filter(j=>!j.is_default),[s]),b=z.normalizeCurrencyCode(i),g=f.useMemo(()=>{const j=D.normalizeCurrencyRecord({code:b,symbol:b,exchange_rate:1,is_default:!0,is_active:!0}),O=(a.length>0?a:[j]).map(I=>D.normalizeCurrencyRecord(I)).filter(I=>I.is_active!==!1).sort((I,V)=>I.is_default!==V.is_default?I.is_default?-1:1:I.code.localeCompare(V.code));return O.length>0?O:[j]},[a,b]),w=f.useMemo(()=>g.find(j=>j.is_default)||g[0],[g]),[S,R]=f.useState(c?.name||""),[_,N]=f.useState(c?.name_translations||{}),[k,F]=f.useState(c?.method_type||"flat_rate"),[y,x]=f.useState(Ne.normalizeShippingRateCurrencyMode(c?.currency_pricing_mode)),[v,B]=f.useState(z.normalizeCurrencyCode(c?.cost_currency||w?.code||b)),[$,L]=f.useState({}),[q,ae]=f.useState({}),[E,W]=f.useState(!1),Q=f.useMemo(()=>{if(y==="manual")return g.reduce((I,V)=>(I[V.code]=$[V.code]??"",I),{});const j=g.reduce((I,V)=>(I[V.code]=$[V.code]??(V.code===v,""),I),{}),O=we($[v],v);if(O===null)return j;for(const I of g){if(I.code===v){j[I.code]=$[I.code]??Pe(O,I.code);continue}j[I.code]=Pe(D.convertMinorUnitAmount({amount:O,fromCurrencyCode:v,toCurrencyCode:I.code,currencies:g}),I.code)}return j},[g,$,y,v]),m=f.useMemo(()=>{if(y==="manual")return g.reduce((I,V)=>(I[V.code]=q[V.code]??"",I),{});const j=g.reduce((I,V)=>(I[V.code]=q[V.code]??"",I),{}),O=we(q[v],v);if(O===null)return j;for(const I of g){if(I.code===v){j[I.code]=q[I.code]??Pe(O,I.code);continue}j[I.code]=Pe(D.convertMinorUnitAmount({amount:O,fromCurrencyCode:v,toCurrencyCode:I.code,currencies:g}),I.code)}return j},[g,q,y,v]);f.useEffect(()=>{w&&(g.some(j=>j.code===v)||B(w.code))},[g,w,v]),f.useEffect(()=>{if(!d||!w)return;const j=Ne.normalizeShippingRateCurrencyMode(c?.currency_pricing_mode),O=Ne.sanitizeShippingRateAmountMaps({currencies:g,mode:j,sourceCurrencyCode:c?.cost_currency||w.code,costAmounts:c?.cost_amounts||void 0,minOrderAmounts:c?.min_order_amounts||void 0,fallbackCostAmount:c?.cost_amount,fallbackMinOrderAmount:c?.min_order_amount});R(c?.name||""),N(c?.name_translations||{}),F(c?.method_type||"flat_rate"),x(j),B(O.sourceCurrencyCode),L(yt({amounts:O.costAmounts,currencies:g})),ae(yt({amounts:O.minOrderAmounts,currencies:g}))},[g,w,c,d]);const T=j=>{j!==y&&(j==="manual"&&(L(Q),ae(m)),x(j))},M=j=>{const O=z.normalizeCurrencyCode(j);L(I=>({...I,[O]:Q[O]??I[O]??""})),ae(I=>({...I,[O]:m[O]??I[O]??""})),B(O)},X=j=>{F(j),j==="free_shipping"&&L(qs(g))},oe=async j=>{j.preventDefault(),W(!0);const O={},I={};if(y==="manual")for(const ee of g){const ue=ee.code;if(k==="free_shipping")O[ue]=0;else{const Re=we($[ue],ue);if(Re===null){W(!1),alert(`Enter a valid shipping cost for ${ue}.`);return}O[ue]=Re}I[ue]=we(q[ue],ue)??0}else{const ee=k==="free_shipping"?0:we($[v],v);if(ee===null){W(!1),alert(`Enter a valid shipping cost for ${v}.`);return}O[v]=ee,I[v]=we(q[v],v)??0}const V={name:S,nameTranslations:_,type:k,currencyPricingMode:y,sourceCurrencyCode:v,costAmounts:O,minOrderAmounts:I},ie=u&&c?.id?await Jt(c.id,V):await Zt(t,V);W(!1),ie.success?l(!1):ie.error&&alert(ie.error)};return e.jsxs(n.Dialog,{open:d,onOpenChange:l,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:u?e.jsx(n.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-primary",children:e.jsx(P.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(P.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:oe,children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:u?"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",p?` (${p.name})`:""]}),e.jsx(n.Input,{id:"rate-name",value:S,onChange:j=>R(j.target.value),placeholder:"e.g. Standard, Express, Free Shipping",required:!0})]}),h.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(P.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:h.map(j=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:`rate-name-${j.code}`,children:j.name}),e.jsx(n.Input,{id:`rate-name-${j.code}`,value:_[j.code]||"",onChange:O=>N(I=>({...I,[j.code]:O.target.value})),placeholder:S||"Translated label"})]},j.code))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(n.Label,{htmlFor:"type",children:"Method Type"}),e.jsxs(n.Select,{value:k,onValueChange:X,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(P.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(P.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:y==="auto",onChange:j=>T(j.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."})]})]}),y==="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:v,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:g.map(j=>e.jsxs(n.SelectItem,{value:j.code,children:[j.code,j.is_default?" (Default)":""]},j.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:k==="free_shipping"?"Free-shipping methods keep cost at zero, but you can still control the threshold per currency.":y==="auto"?`Only ${v} 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:g.map(j=>{const O=y==="auto"&&j.code!==v,I=z.getCurrencyMinorUnitFactor(j.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:j.code}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Rate ",j.exchange_rate]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[j.is_default?e.jsx(n.Badge,{variant:"outline",children:"Default"}):null,y==="auto"&&j.code===v?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-${j.code}`,children:["Cost (",j.code,")"]}),e.jsxs("div",{className:"relative",children:[e.jsx(P.DollarSign,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-slate-400"}),e.jsx(n.Input,{id:`rate-cost-${j.code}`,type:"number",step:I,min:"0",value:Q[j.code]??"",onChange:V=>L(ie=>({...ie,[j.code]:V.target.value})),className:"pl-9 bg-slate-50/50 dark:bg-slate-900/50 disabled:opacity-70",disabled:k==="free_shipping"||O,required:k!=="free_shipping"&&y==="manual"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(n.Label,{htmlFor:`rate-threshold-${j.code}`,children:["Free-Shipping Threshold (",j.code,")"]}),e.jsxs("div",{className:"relative",children:[e.jsx(P.DollarSign,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-slate-400"}),e.jsx(n.Input,{id:`rate-threshold-${j.code}`,type:"number",step:I,min:"0",value:m[j.code]??"",onChange:V=>ae(ie=>({...ie,[j.code]:V.target.value})),className:"pl-9 bg-slate-50/50 dark:bg-slate-900/50 disabled:opacity-70",disabled:O,placeholder:z.getCurrencyMinorUnitFactor(j.code)===1?"0":"0.00"})]})]}),O?e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["This currency is synced automatically from ",v,"."]}):y==="manual"?e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Enter the exact amount shoppers should see in this currency."}):null]},j.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:()=>l(!1),disabled:E,children:"Cancel"}),e.jsx(n.Button,{type:"submit",disabled:E||!S.trim(),children:E?u?"Saving...":"Adding...":u?"Save Changes":"Add Rate"})]})]})})]})}async function Ks({searchParams:t}){const r=H.getServiceRoleSupabaseClient(),[{data:s},a,{data:i},{data:o}]=await Promise.all([r.from("shipping_zones").select(`
|
|
103
|
-
*,
|
|
104
|
-
shipping_zone_locations (*),
|
|
105
|
-
shipping_zone_methods (*)
|
|
106
|
-
`).order("priority_order",{ascending:!0}),te.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})]),c=o?.find(l=>l.is_default)?.code||o?.[0]?.code||"USD",d=(o||[]).map(l=>D.normalizeCurrencyRecord(l));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:Ht,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(P.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(ft,{})]}),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(P.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(l=>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(P.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:l.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: ",l.priority_order]})]}),e.jsxs(n.CardDescription,{className:"text-xs",children:[l.shipping_zone_locations?.length||0," regions covered"]})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(ft,{mode:"edit",initialData:{id:l.id,name:l.name,priority_order:l.priority_order,locations:l.shipping_zone_locations?.map(u=>({country_code:u.country_code,state_code:u.state_code}))||[]}}),e.jsx("form",{action:async()=>{"use server";await Yt(l.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(P.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(P.Globe,{className:"h-3 w-3"})," Target Regions"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.shipping_zone_locations?.length>0?l.shipping_zone_locations.map(u=>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:[u.country_code,u.state_code?e.jsxs("span",{className:"text-slate-400 ml-1",children:["(",se.resolveSubdivisionName(u.country_code,u.state_code),")"]}):""]},u.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(P.Truck,{className:"h-3 w-3"})," Shipping Methods"]}),e.jsx(_t,{zoneId:l.id,zoneName:l.name,languages:i||[],currencies:d,defaultCurrencyCode:c})]}),e.jsx("div",{className:"space-y-2",children:l.shipping_zone_methods?.length>0?l.shipping_zone_methods.map(u=>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:u.name}),e.jsx(n.Badge,{variant:"outline",className:"h-4 px-1 text-[9px]",children:u.currency_pricing_mode==="manual"?"Manual FX":"Auto FX"}),(u.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(P.Info,{className:"h-2 w-2 mr-0.5"}),z.formatPrice(u.min_order_amount,u.cost_currency?.toUpperCase()||c)]})}),e.jsxs(n.TooltipContent,{children:["Available for orders over ",z.formatPrice(u.min_order_amount,u.cost_currency?.toUpperCase()||c)]})]})]}),e.jsx("p",{className:"text-[10px] text-slate-500 uppercase tracking-tighter mix-blend-multiply dark:mix-blend-normal",children:u.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:u.method_type==="free_shipping"?"FREE":z.formatPrice(u.cost_amount,u.cost_currency?.toUpperCase()||c)}),e.jsxs("div",{className:"flex opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(_t,{zoneId:l.id,zoneName:l.name,languages:i||[],currencies:d,defaultCurrencyCode:c,mode:"edit",initialData:u}),e.jsx("form",{action:async()=>{"use server";await er(u.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(P.Trash2,{className:"h-3 w-3"})})})]})]})]},u.id)):e.jsx("p",{className:"text-xs text-slate-400 italic",children:"No methods defined for this zone."})})]})]})})]},l.id))})]})})}async function Ye(){const t=H.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 tr(t){const r=await Ye(),s=await te.getEcommerceInventorySettings(r),a=t.getAll("enableTaxes").includes("true"),i=t.get("taxCalculationMode")==="automatic"?"automatic":"manual",{error:o}=await te.upsertEcommerceInventorySettings(r,{trackQuantities:s.trackQuantities,enableTaxes:a,taxCalculationMode:i});if(o)throw new Error(o.message);Y.revalidatePath("/cms/shipping"),Y.revalidatePath("/cms/settings/taxes"),le.redirect("/cms/settings/taxes?success=Tax settings updated")}async function rr(t){const r=await Ye(),s=String(t.get("id")||"").trim(),a=se.normalizeCountryCode(String(t.get("country_code")||"").trim()),i=String(t.get("state_code")||"").trim(),o=String(t.get("tax_name")||"").trim(),c=Number(t.get("tax_rate"));if(!a)throw new Error("Country code is required.");if(!o)throw new Error("Tax name is required.");if(!Number.isFinite(c)||c<0||c>100)throw new Error("Tax rate must be between 0 and 100.");const d={country_code:a,state_code:se.normalizeSubdivisionCode(a,i)||null,tax_name:o,tax_rate:c},l=s?r.from("tax_rates").update(d).eq("id",s):r.from("tax_rates").insert(d),{error:u}=await l;if(u)throw new Error(u.message);Y.revalidatePath("/cms/settings/taxes")}async function sr(t){const r=await Ye(),{error:s}=await r.from("tax_rates").delete().eq("id",t);if(s)throw new Error(s.message);Y.revalidatePath("/cms/settings/taxes")}function bt({initialData:t,submitLabel:r="Save tax rate",compact:s=!1}){const a=se.normalizeCountryCode(t?.country_code)||"US",[i,o]=f.useState(a),[c,d]=f.useState(se.normalizeSubdivisionCode(a,t?.state_code)||t?.state_code||""),l=f.useMemo(()=>se.getStatesForCountry(i),[i]),u=se.countryUsesStructuredStates(i);return e.jsxs("form",{action:rr,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:p=>{const h=p.target.value,b=se.getStatesForCountry(h);o(h),d(b.some(g=>g.code===c)?c:"")},className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:se.countries.map(p=>e.jsx("option",{value:p.code,children:p.name},p.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"}),u?e.jsxs("select",{id:t?.id?`state-${t.id}`:"tax-rate-state",name:"state_code",value:c,onChange:p=>d(p.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"}),l.map(p=>e.jsx("option",{value:p.code,children:p.name},p.code))]}):e.jsx(n.Input,{id:t?.id?`state-${t.id}`:"tax-rate-state",name:"state_code",value:c,onChange:p=>d(p.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 Vs(t){return`${t.toFixed(4).replace(/\.?0+$/,"")}%`}function Hs(t){return t.state_code?`${t.country_code} - ${se.resolveSubdivisionName(t.country_code,t.state_code)}`:`${t.country_code} - Country-wide`}async function Gs({searchParams:t}){const r=H.createClient(),s=H.getServiceRoleSupabaseClient(),[a,i,o]=await Promise.all([te.getEcommerceInventorySettings(r),Se(),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")]),c=o.data||[],d=o.error,l=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(re,{href:"/cms/shipping",children:e.jsx(P.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:l?"default":"outline",className:"uppercase",children:["Stripe ",l?"Enabled":"Disabled"]}),e.jsx("div",{className:"rounded-full border bg-muted/30 p-3 text-muted-foreground",children:e.jsx(P.Settings2,{className:"h-5 w-5"})})]})]}),l?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:tr,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:[d?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,d?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(P.ShieldCheck,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"font-semibold",children:"Create a Tax Rate"})]}),e.jsx(bt,{})]}),e.jsx("div",{className:"space-y-4",children:c.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."})]}):c.map(u=>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:u.tax_name}),e.jsx(n.CardDescription,{children:Hs(u)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Badge,{variant:"outline",children:Vs(Number(u.tax_rate))}),e.jsx("form",{action:async()=>{"use server";await sr(u.id)},children:e.jsx(n.Button,{type:"submit",variant:"ghost",size:"icon","aria-label":"Delete tax rate",children:e.jsx(P.Trash2,{className:"h-4 w-4"})})})]})]})}),e.jsx(n.CardContent,{children:e.jsx(bt,{initialData:u,submitLabel:"Update tax rate",compact:!0})})]},u.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(re,{href:"/cms/payments",children:"Open Payment Settings"})})})]})]})}async function Ie(){const t=H.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 H.getServiceRoleSupabaseClient()}function pe(t){return(typeof t=="string"?t.trim():"")||null}function vt(t){const r=pe(t);if(!r)return null;const s=new Date(r);return Number.isNaN(s.getTime())?null:s.toISOString()}function Ws(t){const r=pe(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"?z.majorUnitAmountToMinor(s,t.currencyCode):Math.round(s)}function Qs(t,r){return t.getAll(r).some(s=>s==="true")}function ar(t){const r=fe.normalizeCouponCode(pe(t.get("code"))),s=pe(t.get("name")),a=pe(t.get("provider_scope"))||"all",i=pe(t.get("discount_type"))||"percent",o=z.normalizeCurrencyCode(pe(t.get("currency_code"))),c=Ws({value:t.get("discount_amount"),discountType:i,currencyCode:o}),d=pe(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"&&c>100)throw new Error("Percent discounts cannot exceed 100.");return{coupon:{code:r,name:s,internal_note:pe(t.get("internal_note")),provider_scope:a,discount_type:i,discount_amount:c,is_active:Qs(t,"is_active"),starts_at:vt(t.get("starts_at")),ends_at:vt(t.get("ends_at")),redemption_limit:d?Number.parseInt(d,10):null,freemius_sync_status:a==="stripe"?"not_required":"pending",freemius_sync_error:null},productIds:t.getAll("product_ids").map(l=>typeof l=="string"?l.trim():"").filter(Boolean)}}async function nr(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 Xs(t){const r=await Ie(),s=ar(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 nr({client:r,couponId:a.id,productIds:s.productIds}),await A.syncCouponToFreemius({couponId:a.id,client:r}),Y.revalidatePath("/cms/coupons"),le.redirect("/cms/coupons")}async function Ys(t,r){const s=await Ie(),a=ar(r),{error:i}=await s.from("coupons").update(a.coupon).eq("id",t);if(i)throw new Error(i.message);await nr({client:s,couponId:t,productIds:a.productIds}),a.coupon.provider_scope==="stripe"?await A.deleteCouponFromFreemius({couponId:t,client:s}):await A.syncCouponToFreemius({couponId:t,client:s}),Y.revalidatePath("/cms/coupons"),Y.revalidatePath(`/cms/coupons/${t}/edit`),le.redirect("/cms/coupons")}async function Zs(t,r){const s=await Ie(),{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 A.syncCouponToFreemius({couponId:t,client:s}),Y.revalidatePath("/cms/coupons")}async function Js(t){const r=await Ie();await A.syncCouponToFreemius({couponId:t,client:r}),Y.revalidatePath("/cms/coupons"),Y.revalidatePath(`/cms/coupons/${t}/edit`)}async function ea(t){const r=await Ie();await A.deleteCouponFromFreemius({couponId:t,client:r});const{error:s}=await r.from("coupons").delete().eq("id",t);if(s)throw new Error(s.message);Y.revalidatePath("/cms/coupons")}function ta(t){const r=t.sku?.trim();return r?r.toUpperCase():`PRODUCT:${t.id}`}function ra(t){const r=new Map;for(const s of t){const a=ta(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 sa({products:t,selectedProductIds:r=[]}){const s=f.useMemo(()=>new Set(r),[r]),[a,i]=f.useState(s),[o,c]=f.useState(""),d=f.useMemo(()=>ra(t),[t]),l=f.useMemo(()=>{const p=o.trim().toLowerCase();return p?d.filter(h=>[h.title,h.sku].some(b=>b.toLowerCase().includes(p))):d},[d,o]),u=p=>{i(new Set(t.filter(h=>h.payment_provider===p).map(h=>h.id)))};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Le.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>i(new Set(t.map(p=>p.id))),children:"Select All"}),e.jsx(Le.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>u("stripe"),children:"Stripe"}),e.jsx(Le.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>u("freemius"),children:"Freemius"})]}),e.jsxs("div",{className:"relative",children:[e.jsx(P.Search,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(yr.Input,{type:"search",value:o,onChange:p=>c(p.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:[l.map(p=>{const h=p.productIds.some(b=>a.has(b));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:h,onChange:b=>{const g=new Set(a);for(const w of p.productIds)b.target.checked?g.add(w):g.delete(w);i(g)},className:"mt-0.5 h-4 w-4 rounded border-slate-300 text-primary focus:ring-primary"}),h?p.productIds.map(b=>e.jsx("input",{type:"hidden",name:"product_ids",value:b},b)):null,e.jsx("span",{className:"flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-md border bg-muted",children:p.thumbnailUrl?e.jsx("img",{src:p.thumbnailUrl,alt:"",loading:"lazy",className:"h-full w-full object-cover"}):e.jsx(P.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:p.title}),e.jsx("span",{className:"block font-mono text-xs text-muted-foreground",children:p.sku})]})]},p.key)}),l.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 jt(t){if(!t)return"";const r=new Date(t);return Number.isNaN(r.getTime())?"":r.toISOString().slice(0,16)}function aa(t,r){const s=z.getCurrencyMinorUnitFactor(r)===1?0:2;return t.toFixed(s)}function na(t,r){return t?.discount_amount?t.discount_type==="fixed"?aa(z.minorUnitAmountToMajor(t.discount_amount,r),r):t.discount_amount:10}function ir({action:t,products:r,coupon:s,selectedProductIds:a=[],submitLabel:i,currencyCode:o="USD"}){return e.jsxs("form",{action:t,children:[e.jsx("input",{type:"hidden",name:"currency_code",value:o}),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:na(s,o),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:jt(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:jt(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(sa,{products:r,selectedProductIds:a})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(n.Button,{type:"submit",children:i})})]})]})]})}function ia({action:t,products:r,currencyCode:s}){const[a,i]=f.useState(!1);return e.jsxs(Te.Dialog,{open:a,onOpenChange:i,children:[e.jsx(Te.DialogTrigger,{asChild:!0,children:e.jsxs(Le.Button,{type:"button",className:"gap-2",children:[e.jsx(P.Plus,{className:"h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Te.DialogContent,{className:"max-h-[90vh] overflow-y-auto sm:max-w-[92vw] lg:max-w-5xl xl:max-w-6xl",children:[e.jsx(Te.DialogHeader,{children:e.jsx(Te.DialogTitle,{className:"sr-only",children:"Create Coupon"})}),e.jsx(ir,{action:t,products:r,submitLabel:"Create Coupon",currencyCode:s})]})]})}function oa(t){return Array.isArray(t)?t[0]??null:t??null}const Ct=process.env.NEXT_PUBLIC_R2_BASE_URL||"";function ca(t){return t?t.startsWith("http")||!Ct?t:`${Ct.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`:null}function la(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 ca(s)}function or(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:la(r),language:oa(r.language)}))}function da(t,r){return t.discount_type==="percent"?`${t.discount_amount}%`:z.formatPrice(t.discount_amount,r)}function ua(t,r){return r?t==="synced"||t==="not_required"?"default":"secondary":"outline"}function ma(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 pa(t,r){const s=ma(t,r);return s===0?"All eligible products":`${s} scoped SKU${s===1?"":"s"}`}async function ha({searchParams:t}){const r=H.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:o}]=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)]),c=o?.find(l=>l.is_default)?.code||o?.[0]?.code||"USD",d=new Map((i||[]).map(l=>[l.id,l.sku?.trim().toUpperCase()||l.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(ia,{action:Xs,products:or(i),currencyCode:c})]})]}),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(l=>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:l.code}),e.jsx(n.Badge,{variant:l.is_active?"default":"outline",children:l.is_active?"Active":"Inactive"})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l.name})]}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("span",{className:"capitalize",children:l.provider_scope}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:pa(l.coupon_products,d)})]}),e.jsx("td",{className:"px-4 py-3 font-medium",children:da(l,c)}),e.jsxs("td",{className:"px-4 py-3",children:[l.redemptions_count||0,l.redemption_limit?` / ${l.redemption_limit}`:""]}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx(n.Badge,{variant:ua(l.freemius_sync_status,l.is_active),children:l.freemius_sync_status}),l.freemius_sync_error?e.jsx("p",{className:"mt-1 max-w-[220px] text-xs text-destructive",children:l.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(re,{href:`/cms/coupons/${l.id}/edit`,children:"Edit"})}),e.jsx("form",{action:async()=>{"use server";await Zs(l.id,!l.is_active)},children:e.jsx(n.Button,{type:"submit",variant:"outline",size:"sm",children:l.is_active?"Disable":"Enable"})}),e.jsx("form",{action:async()=>{"use server";await Js(l.id)},children:e.jsx(n.Button,{type:"submit",variant:"ghost",size:"icon",title:"Resync Freemius","aria-label":`Resync Freemius coupon ${l.code}`,children:e.jsx(P.RefreshCw,{className:"h-4 w-4"})})}),e.jsx("form",{action:async()=>{"use server";await ea(l.id)},children:e.jsx(n.Button,{type:"submit",variant:"ghost",size:"icon",className:"text-destructive","aria-label":`Delete coupon ${l.code}`,children:e.jsx(P.Trash2,{className:"h-4 w-4"})})})]})})]},l.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 xa({params:t}){const{id:r}=await t,s=H.getServiceRoleSupabaseClient(),[{data:a},{data:i},{data:o},{data:c}]=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||le.notFound();const d=(o||[]).map(u=>u.product_id),l=c?.find(u=>u.is_default)?.code||c?.[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(re,{href:"/cms/coupons",children:"Back to coupons"})})]}),e.jsx(ir,{action:Ys.bind(null,r),products:or(i),coupon:a,selectedProductIds:d,submitLabel:"Save Coupon",currencyCode:l})]})}exports.CURRENCY_ROUNDING_MODES=D.CURRENCY_ROUNDING_MODES;exports.applyCurrencyRounding=D.applyCurrencyRounding;exports.convertMinorUnitAmount=D.convertMinorUnitAmount;exports.describeCurrencyRoundingRule=D.describeCurrencyRoundingRule;exports.getCurrencyLookup=D.getCurrencyLookup;exports.getDefaultCurrency=D.getDefaultCurrency;exports.getExchangeRateForCurrency=D.getExchangeRateForCurrency;exports.inferCurrencyCodeFromLocale=D.inferCurrencyCodeFromLocale;exports.isSaleWindowActive=D.isSaleWindowActive;exports.isScheduledPriceDue=D.isScheduledPriceDue;exports.normalizeCurrencyRecord=D.normalizeCurrencyRecord;exports.normalizeCurrencyRoundingMode=D.normalizeCurrencyRoundingMode;exports.normalizePriceMap=D.normalizePriceMap;exports.normalizeSalePriceMap=D.normalizeSalePriceMap;exports.resolveEffectivePriceForCurrency=D.resolveEffectivePriceForCurrency;exports.resolvePriceForCurrency=D.resolvePriceForCurrency;exports.resolvePriceRangeForCurrency=D.resolvePriceRangeForCurrency;exports.sortCurrencies=D.sortCurrencies;exports.addressesMatch=me.addressesMatch;exports.emptyCustomerAddress=me.emptyCustomerAddress;exports.isCustomerAddressComplete=me.isCustomerAddressComplete;exports.normalizeCustomerAddress=me.normalizeCustomerAddress;exports.normalizeOrderCustomerDetails=me.normalizeOrderCustomerDetails;exports.FreemiusProvider=K.FreemiusProvider;exports.fillMissingUserProfileCheckoutDetails=K.fillMissingUserProfileCheckoutDetails;exports.getCategoriesWithCount=K.getCategoriesWithCount;exports.getCategoryBySlug=K.getCategoryBySlug;exports.getCmsProduct=K.getProduct;exports.getCmsProducts=K.getProducts;exports.getDefaultUserAddresses=K.getDefaultUserAddresses;exports.getGlobalProductAttributes=K.getGlobalProductAttributes;exports.getProductCategories=K.getProductCategories;exports.getProductTranslations=K.getProductTranslations;exports.parseFreemiusCheckoutCredentialsMap=K.parseFreemiusCheckoutCredentialsMap;exports.readFreemiusEnvValue=K.readFreemiusEnvValue;exports.resolveFreemiusCheckoutCredentials=K.resolveFreemiusCheckoutCredentials;exports.syncFreemiusProductsToSupabase=K.syncFreemiusProductsToSupabase;exports.syncSingleFreemiusProduct=K.syncSingleFreemiusProduct;exports.upsertDefaultUserAddresses=K.upsertDefaultUserAddresses;exports.DEFAULT_INVOICE_SETTINGS=A.DEFAULT_INVOICE_SETTINGS;exports.INVOICE_SETTINGS_KEY=A.INVOICE_SETTINGS_KEY;exports.aggregateOrderTaxLines=A.aggregateOrderTaxLines;exports.buildOrderTaxDetailsFromCalculation=A.buildOrderTaxDetailsFromCalculation;exports.buildOrderTaxDetailsFromStripeSession=A.buildOrderTaxDetailsFromStripeSession;exports.createCategoryAction=A.createCategoryAction;exports.createProductAction=A.createProductAction;exports.deleteCategoryAction=A.deleteCategoryAction;exports.deleteCouponFromFreemius=A.deleteCouponFromFreemius;exports.deleteProductAction=A.deleteProductAction;exports.formatInvoiceCurrency=A.formatInvoiceCurrency;exports.formatInvoiceDate=A.formatInvoiceDate;exports.getInvoiceAddressLines=A.getInvoiceAddressLines;exports.getOrderTaxRateJurisdiction=A.getOrderTaxRateJurisdiction;exports.getOrderTaxRateLabel=A.getOrderTaxRateLabel;exports.getOrderTaxRatePercentage=A.getOrderTaxRatePercentage;exports.normalizeInvoiceSettings=A.normalizeInvoiceSettings;exports.normalizeOrderTaxDetails=A.normalizeOrderTaxDetails;exports.productSchema=A.productSchema;exports.serializeInvoiceSettings=A.serializeInvoiceSettings;exports.syncCouponToFreemius=A.syncCouponToFreemius;exports.syncProductCategoriesAction=A.syncProductCategoriesAction;exports.syncProductSaleCouponToFreemius=A.syncProductSaleCouponToFreemius;exports.updateCategoryAction=A.updateCategoryAction;exports.updateProductAction=A.updateProductAction;exports.getCouponQuote=fe.getCouponQuote;exports.getQuoteLineDiscountMap=fe.getQuoteLineDiscountMap;exports.recordCouponRedemption=fe.recordCouponRedemption;exports.CURRENCY_COOKIE_NAME=pr.CURRENCY_COOKIE_NAME;exports.copyProductFromLanguage=ce.copyProductFromLanguage;exports.createProduct=ce.createProduct;exports.deleteProduct=ce.deleteProduct;exports.fetchTranslatedProductsForCartInternal=ce.fetchTranslatedProductsForCartInternal;exports.getProduct=ce.getProduct;exports.getProductBySlug=ce.getProductBySlug;exports.getProducts=ce.getProducts;exports.syncCategoriesForTranslationGroup=ce.syncCategoriesForTranslationGroup;exports.updateProduct=ce.updateProduct;exports.AttributeManagementPage=As;exports.CategoryManagementPage=Os;exports.CopyProductFromLanguage=Ls;exports.CouponsPage=ha;exports.EditCouponPage=xa;exports.EditProductPage=Us;exports.ExportReportsDialog=zt;exports.InventoryPage=Ts;exports.NewProductPage=Is;exports.OrderDetailPage=hs;exports.OrdersPage=is;exports.PaymentsPage=$s;exports.ProductsPage=_s;exports.ShippingPage=Ks;exports.StripeProvider=Pt;exports.TaxesPage=Gs;exports.applyOrderInventoryDeduction=Oe;exports.assignInvoiceMetadata=Be;exports.clearAutoSyncedCurrencyPriceOverrides=Dr;exports.createCheckoutSession=_r;exports.createShippingRate=Zt;exports.createShippingZone=Qt;exports.deleteShippingRate=er;exports.deleteShippingZone=Yt;exports.deleteTaxRateAction=sr;exports.extractFreemiusCheckoutMetadata=At;exports.fetchOrderReportData=$t;exports.getCurrentCustomerOrder=Et;exports.getCurrentCustomerOrderInvoice=Pr;exports.getCurrentCustomerOrders=Tr;exports.getEnabledPaymentProviders=Se;exports.getFreemiusWebhookSecretCandidates=Ot;exports.getInvoiceBrandingData=wt;exports.getInvoiceOrder=Nt;exports.getInvoicePresentationData=Ge;exports.getOrderDetails=Bt;exports.getOrders=Dt;exports.getPaymentProvider=Vr;exports.getPaymentSettings=ts;exports.getStoreConfigStatus=$e;exports.handleStripeWebhook=Er;exports.rebaseStoreCurrencyExchangeRates=Mr;exports.resolveFreemiusStatusFromCheckoutResponse=It;exports.resolveFreemiusStatusFromWebhookEvent=Xe;exports.saveTaxRateAction=rr;exports.stripe=xe;exports.syncFreemiusCheckoutOrder=Zr;exports.syncFreemiusOrderFromWebhookEvent=Jr;exports.syncStoreCurrencyRates=Or;exports.syncStripeOrderFromSession=St;exports.updateInventoryTrackingAction=Ht;exports.updatePaymentSettings=Kt;exports.updateShippingRate=Jt;exports.updateShippingZone=Xt;exports.updateTaxSettingsAction=tr;exports.verifyFreemiusWebhookSignature=es;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("./lib/stripe/client.cjs.js"),F=require("./lib/stripe/checkout.cjs.js"),O=require("./lib/stripe/order-sync.cjs.js"),h=require("./lib/stripe/webhooks.cjs.js"),A=require("./lib/order-inventory.cjs.js"),t=require("./lib/order-tax-details.cjs.js"),o=require("./lib/invoice.cjs.js"),d=require("./lib/invoice-server.cjs.js"),g=require("./lib/customer-orders.cjs.js"),C=require("./lib/coupon-server.cjs.js"),l=require("./lib/freemius-coupons.cjs.js"),c=require("./lib/customer.cjs.js"),P=require("./lib/customer-addresses.cjs.js"),e=require("./lib/currency.cjs.js"),R=require("./lib/currency-constants.cjs.js"),p=require("./lib/currency-sync.cjs.js"),T=require("./lib/product-schema.cjs.js"),r=require("./lib/product-actions.cjs.js"),q=require("./lib/factory.cjs.js"),I=require("./lib/providers/stripe.cjs.js"),u=require("./lib/providers/freemius.cjs.js"),n=require("./lib/freemius-order-sync.cjs.js"),i=require("./lib/pages/cms/products/actions.cjs.js"),a=require("./lib/pages/cms/products/server-actions.cjs.js"),m=require("./lib/pages/cms/payments/queries.cjs.js"),D=require("./lib/pages/cms/orders/OrdersPage.cjs.js"),E=require("./lib/pages/cms/orders/OrderDetailPage.cjs.js"),b=require("./lib/pages/cms/orders/ExportReportsDialog.cjs.js"),x=require("./lib/pages/cms/orders/export-actions.cjs.js"),S=require("./lib/pages/cms/orders/actions.cjs.js"),f=require("./lib/pages/cms/products/ProductsPage.cjs.js"),M=require("./lib/pages/cms/products/inventory/InventoryPage.cjs.js"),k=require("./lib/pages/cms/products/attributes/AttributeManagementPage.cjs.js"),N=require("./lib/pages/cms/products/new/NewProductPage.cjs.js"),L=require("./lib/pages/cms/products/_id_/edit/EditProductPage.cjs.js"),z=require("./lib/pages/cms/products/components/CopyProductFromLanguage.cjs.js"),_=require("./lib/pages/cms/products/categories/CategoryManagementPage.cjs.js"),U=require("./lib/pages/cms/payments/PaymentsPage.cjs.js"),W=require("./lib/pages/cms/payments/actions.cjs.js"),G=require("./lib/pages/cms/shipping/ShippingPage.cjs.js"),s=require("./lib/pages/cms/shipping/server-actions.cjs.js"),w=require("./lib/pages/cms/taxes/TaxesPage.cjs.js"),y=require("./lib/pages/cms/taxes/actions.cjs.js"),B=require("./lib/pages/cms/coupons/CouponsPage.cjs.js"),V=require("./lib/pages/cms/coupons/EditCouponPage.cjs.js");exports.stripe=v.stripe;exports.createCheckoutSession=F.createCheckoutSession;exports.syncStripeOrderFromSession=O.syncStripeOrderFromSession;exports.handleStripeWebhook=h.handleStripeWebhook;exports.applyOrderInventoryDeduction=A.applyOrderInventoryDeduction;exports.aggregateOrderTaxLines=t.aggregateOrderTaxLines;exports.buildOrderTaxDetailsFromCalculation=t.buildOrderTaxDetailsFromCalculation;exports.buildOrderTaxDetailsFromStripeSession=t.buildOrderTaxDetailsFromStripeSession;exports.getOrderTaxRateJurisdiction=t.getOrderTaxRateJurisdiction;exports.getOrderTaxRateLabel=t.getOrderTaxRateLabel;exports.getOrderTaxRatePercentage=t.getOrderTaxRatePercentage;exports.normalizeOrderTaxDetails=t.normalizeOrderTaxDetails;exports.DEFAULT_INVOICE_SETTINGS=o.DEFAULT_INVOICE_SETTINGS;exports.INVOICE_SETTINGS_KEY=o.INVOICE_SETTINGS_KEY;exports.formatInvoiceCurrency=o.formatInvoiceCurrency;exports.formatInvoiceDate=o.formatInvoiceDate;exports.getInvoiceAddressLines=o.getInvoiceAddressLines;exports.normalizeInvoiceSettings=o.normalizeInvoiceSettings;exports.serializeInvoiceSettings=o.serializeInvoiceSettings;exports.assignInvoiceMetadata=d.assignInvoiceMetadata;exports.getInvoiceBrandingData=d.getInvoiceBrandingData;exports.getInvoiceOrder=d.getInvoiceOrder;exports.getInvoicePresentationData=d.getInvoicePresentationData;exports.getCurrentCustomerOrder=g.getCurrentCustomerOrder;exports.getCurrentCustomerOrderInvoice=g.getCurrentCustomerOrderInvoice;exports.getCurrentCustomerOrders=g.getCurrentCustomerOrders;exports.getCouponQuote=C.getCouponQuote;exports.getQuoteLineDiscountMap=C.getQuoteLineDiscountMap;exports.recordCouponRedemption=C.recordCouponRedemption;exports.deleteCouponFromFreemius=l.deleteCouponFromFreemius;exports.syncCouponToFreemius=l.syncCouponToFreemius;exports.syncProductSaleCouponToFreemius=l.syncProductSaleCouponToFreemius;exports.addressesMatch=c.addressesMatch;exports.emptyCustomerAddress=c.emptyCustomerAddress;exports.isCustomerAddressComplete=c.isCustomerAddressComplete;exports.normalizeCustomerAddress=c.normalizeCustomerAddress;exports.normalizeOrderCustomerDetails=c.normalizeOrderCustomerDetails;exports.fillMissingUserProfileCheckoutDetails=P.fillMissingUserProfileCheckoutDetails;exports.getDefaultUserAddresses=P.getDefaultUserAddresses;exports.upsertDefaultUserAddresses=P.upsertDefaultUserAddresses;exports.CURRENCY_ROUNDING_MODES=e.CURRENCY_ROUNDING_MODES;exports.applyCurrencyRounding=e.applyCurrencyRounding;exports.convertMinorUnitAmount=e.convertMinorUnitAmount;exports.describeCurrencyRoundingRule=e.describeCurrencyRoundingRule;exports.getCurrencyLookup=e.getCurrencyLookup;exports.getDefaultCurrency=e.getDefaultCurrency;exports.getExchangeRateForCurrency=e.getExchangeRateForCurrency;exports.inferCurrencyCodeFromLocale=e.inferCurrencyCodeFromLocale;exports.isSaleWindowActive=e.isSaleWindowActive;exports.isScheduledPriceDue=e.isScheduledPriceDue;exports.normalizeCurrencyRecord=e.normalizeCurrencyRecord;exports.normalizeCurrencyRoundingMode=e.normalizeCurrencyRoundingMode;exports.normalizePriceMap=e.normalizePriceMap;exports.normalizeSalePriceMap=e.normalizeSalePriceMap;exports.resolveEffectivePriceForCurrency=e.resolveEffectivePriceForCurrency;exports.resolvePriceForCurrency=e.resolvePriceForCurrency;exports.resolvePriceRangeForCurrency=e.resolvePriceRangeForCurrency;exports.sortCurrencies=e.sortCurrencies;exports.CURRENCY_COOKIE_NAME=R.CURRENCY_COOKIE_NAME;exports.clearAutoSyncedCurrencyPriceOverrides=p.clearAutoSyncedCurrencyPriceOverrides;exports.rebaseStoreCurrencyExchangeRates=p.rebaseStoreCurrencyExchangeRates;exports.syncStoreCurrencyRates=p.syncStoreCurrencyRates;exports.productSchema=T.productSchema;exports.copyProductFromLanguage=r.copyProductFromLanguage;exports.createProduct=r.createProduct;exports.deleteProduct=r.deleteProduct;exports.fetchTranslatedProductsForCartInternal=r.fetchTranslatedProductsForCartInternal;exports.getProduct=r.getProduct;exports.getProductBySlug=r.getProductBySlug;exports.getProducts=r.getProducts;exports.syncCategoriesForTranslationGroup=r.syncCategoriesForTranslationGroup;exports.updateProduct=r.updateProduct;exports.getPaymentProvider=q.getPaymentProvider;exports.StripeProvider=I.StripeProvider;exports.FreemiusProvider=u.FreemiusProvider;exports.parseFreemiusCheckoutCredentialsMap=u.parseFreemiusCheckoutCredentialsMap;exports.readFreemiusEnvValue=u.readFreemiusEnvValue;exports.resolveFreemiusCheckoutCredentials=u.resolveFreemiusCheckoutCredentials;exports.syncFreemiusProductsToSupabase=u.syncFreemiusProductsToSupabase;exports.syncSingleFreemiusProduct=u.syncSingleFreemiusProduct;exports.extractFreemiusCheckoutMetadata=n.extractFreemiusCheckoutMetadata;exports.getFreemiusWebhookSecretCandidates=n.getFreemiusWebhookSecretCandidates;exports.resolveFreemiusStatusFromCheckoutResponse=n.resolveFreemiusStatusFromCheckoutResponse;exports.resolveFreemiusStatusFromWebhookEvent=n.resolveFreemiusStatusFromWebhookEvent;exports.syncFreemiusCheckoutOrder=n.syncFreemiusCheckoutOrder;exports.syncFreemiusOrderFromWebhookEvent=n.syncFreemiusOrderFromWebhookEvent;exports.verifyFreemiusWebhookSignature=n.verifyFreemiusWebhookSignature;exports.getCategoriesWithCount=i.getCategoriesWithCount;exports.getCategoryBySlug=i.getCategoryBySlug;exports.getCmsProduct=i.getProduct;exports.getCmsProducts=i.getProducts;exports.getGlobalProductAttributes=i.getGlobalProductAttributes;exports.getProductCategories=i.getProductCategories;exports.getProductTranslations=i.getProductTranslations;exports.createCategoryAction=a.createCategoryAction;exports.createProductAction=a.createProductAction;exports.deleteCategoryAction=a.deleteCategoryAction;exports.deleteProductAction=a.deleteProductAction;exports.syncProductCategoriesAction=a.syncProductCategoriesAction;exports.updateCategoryAction=a.updateCategoryAction;exports.updateProductAction=a.updateProductAction;exports.getEnabledPaymentProviders=m.getEnabledPaymentProviders;exports.getPaymentSettings=m.getPaymentSettings;exports.getStoreConfigStatus=m.getStoreConfigStatus;exports.OrdersPage=D.OrdersPage;exports.OrderDetailPage=E.OrderDetailPage;exports.ExportReportsDialog=b.ExportReportsDialog;exports.fetchOrderReportData=x.fetchOrderReportData;exports.getOrderDetails=S.getOrderDetails;exports.getOrders=S.getOrders;exports.ProductsPage=f.ProductsPage;exports.InventoryPage=M.InventoryPage;exports.AttributeManagementPage=k.AttributeManagementPage;exports.NewProductPage=N.NewProductPage;exports.EditProductPage=L.EditProductPage;exports.CopyProductFromLanguage=z.CopyProductFromLanguage;exports.CategoryManagementPage=_.CategoryManagementPage;exports.PaymentsPage=U.PaymentsPage;exports.updatePaymentSettings=W.updatePaymentSettings;exports.ShippingPage=G.ShippingPage;exports.createShippingRate=s.createShippingRate;exports.createShippingZone=s.createShippingZone;exports.deleteShippingRate=s.deleteShippingRate;exports.deleteShippingZone=s.deleteShippingZone;exports.updateInventoryTrackingAction=s.updateInventoryTrackingAction;exports.updateShippingRate=s.updateShippingRate;exports.updateShippingZone=s.updateShippingZone;exports.TaxesPage=w.TaxesPage;exports.deleteTaxRateAction=y.deleteTaxRateAction;exports.saveTaxRateAction=y.saveTaxRateAction;exports.updateTaxSettingsAction=y.updateTaxSettingsAction;exports.CouponsPage=B.CouponsPage;exports.EditCouponPage=V.EditCouponPage;
|