@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.
Files changed (277) hide show
  1. package/index.cjs.js +1 -1
  2. package/index.es.js +136 -533
  3. package/lib/CurrencyProvider.cjs.js +1 -0
  4. package/lib/CurrencyProvider.es.js +99 -0
  5. package/lib/cart-store.cjs.js +1 -0
  6. package/{cart-store.es.js → lib/cart-store.es.js} +13 -13
  7. package/lib/components/AccountNavigationMenu.cjs.js +1 -0
  8. package/lib/components/AccountNavigationMenu.es.js +44 -0
  9. package/lib/components/AddToCartButton.cjs.js +1 -0
  10. package/{AddToCartButton-ffE0DhHu.js → lib/components/AddToCartButton.es.js} +14 -13
  11. package/lib/components/Cart.cjs.js +1 -0
  12. package/lib/components/Cart.es.js +148 -0
  13. package/lib/components/CartDrawer.cjs.js +1 -0
  14. package/{components → lib/components}/CartDrawer.es.js +15 -14
  15. package/{components → lib/components}/CartIcon.cjs.js +1 -1
  16. package/{components → lib/components}/CartIcon.es.js +1 -0
  17. package/lib/components/Checkout.cjs.js +1 -0
  18. package/{components → lib/components}/Checkout.es.js +330 -363
  19. package/lib/components/CouponForm.cjs.js +1 -0
  20. package/lib/components/CouponForm.es.js +136 -0
  21. package/lib/components/CurrencySwitcher.cjs.js +1 -0
  22. package/{components → lib/components}/CurrencySwitcher.es.js +5 -4
  23. package/lib/components/CustomerProfileForm.cjs.js +1 -0
  24. package/lib/components/CustomerProfileForm.es.js +355 -0
  25. package/lib/components/FeaturedProduct.cjs.js +1 -0
  26. package/{components → lib/components}/FeaturedProduct.es.js +9 -8
  27. package/lib/components/InvoiceDocument.cjs.js +1 -0
  28. package/lib/components/InvoiceDocument.es.js +196 -0
  29. package/lib/components/InvoiceViewerShell.cjs.js +29 -0
  30. package/lib/components/InvoiceViewerShell.es.js +100 -0
  31. package/lib/components/ProductCard.cjs.js +1 -0
  32. package/lib/components/ProductCard.es.js +119 -0
  33. package/lib/components/ProductDetailsLayout.cjs.js +1 -0
  34. package/lib/components/ProductDetailsLayout.es.js +361 -0
  35. package/lib/components/ProductGallery.cjs.js +1 -0
  36. package/lib/components/ProductGallery.es.js +41 -0
  37. package/lib/components/ProductGrid.cjs.js +1 -0
  38. package/lib/components/ProductGrid.es.js +19 -0
  39. package/lib/components/ShippingEstimator.cjs.js +1 -0
  40. package/lib/components/ShippingEstimator.es.js +125 -0
  41. package/lib/components/SubscriptionSelector.cjs.js +1 -0
  42. package/lib/components/SubscriptionSelector.es.js +140 -0
  43. package/lib/countries.cjs.js +1 -0
  44. package/lib/countries.es.js +77 -0
  45. package/lib/coupon-server.cjs.js +1 -0
  46. package/{coupon-server-DUKVtyYs.js → lib/coupon-server.es.js} +68 -82
  47. package/lib/coupons.cjs.js +1 -0
  48. package/lib/coupons.es.js +17 -0
  49. package/lib/currency-store.cjs.js +1 -0
  50. package/lib/currency-store.es.js +27 -0
  51. package/lib/currency-sync.cjs.js +1 -0
  52. package/lib/currency-sync.es.js +180 -0
  53. package/lib/customer-addresses.cjs.js +1 -0
  54. package/lib/customer-addresses.es.js +116 -0
  55. package/lib/customer-orders.cjs.js +1 -0
  56. package/lib/customer-orders.es.js +45 -0
  57. package/lib/customer.cjs.js +1 -0
  58. package/{customer-C3xccjUg.js → lib/customer.es.js} +15 -14
  59. package/lib/export-helpers.cjs.js +1 -0
  60. package/lib/export-helpers.es.js +56 -0
  61. package/lib/factory.cjs.js +1 -0
  62. package/lib/factory.es.js +8 -0
  63. package/lib/freemius-coupons.cjs.js +1 -0
  64. package/lib/freemius-coupons.es.js +272 -0
  65. package/lib/freemius-order-sync.cjs.js +1 -0
  66. package/lib/freemius-order-sync.es.js +284 -0
  67. package/lib/inventory-settings.cjs.js +1 -0
  68. package/lib/inventory-settings.es.js +86 -0
  69. package/lib/invoice-server.cjs.js +33 -0
  70. package/lib/invoice-server.es.js +141 -0
  71. package/lib/invoice-ui.cjs.js +1 -0
  72. package/lib/invoice-ui.es.js +71 -0
  73. package/lib/invoice.cjs.js +1 -0
  74. package/lib/invoice.es.js +102 -0
  75. package/lib/order-inventory.cjs.js +61 -0
  76. package/lib/order-inventory.es.js +128 -0
  77. package/lib/order-tax-details.cjs.js +1 -0
  78. package/lib/order-tax-details.es.js +164 -0
  79. package/lib/pages/cms/coupons/CouponEditorForm.cjs.js +1 -0
  80. package/lib/pages/cms/coupons/CouponEditorForm.es.js +189 -0
  81. package/lib/pages/cms/coupons/CouponsPage.cjs.js +5 -0
  82. package/lib/pages/cms/coupons/CouponsPage.es.js +171 -0
  83. package/lib/pages/cms/coupons/CreateCouponDialog.cjs.js +1 -0
  84. package/lib/pages/cms/coupons/CreateCouponDialog.es.js +35 -0
  85. package/lib/pages/cms/coupons/EditCouponPage.cjs.js +1 -0
  86. package/lib/pages/cms/coupons/EditCouponPage.es.js +48 -0
  87. package/lib/pages/cms/coupons/ProductScopePicker.cjs.js +1 -0
  88. package/lib/pages/cms/coupons/ProductScopePicker.es.js +120 -0
  89. package/lib/pages/cms/coupons/actions.cjs.js +1 -0
  90. package/lib/pages/cms/coupons/actions.es.js +128 -0
  91. package/lib/pages/cms/coupons/product-options.cjs.js +1 -0
  92. package/lib/pages/cms/coupons/product-options.es.js +27 -0
  93. package/lib/pages/cms/orders/ExportReportsDialog.cjs.js +1 -0
  94. package/lib/pages/cms/orders/ExportReportsDialog.es.js +130 -0
  95. package/lib/pages/cms/orders/OrderDetailPage.cjs.js +1 -0
  96. package/lib/pages/cms/orders/OrderDetailPage.es.js +137 -0
  97. package/lib/pages/cms/orders/OrderPrintButton.cjs.js +1 -0
  98. package/lib/pages/cms/orders/OrderPrintButton.es.js +22 -0
  99. package/lib/pages/cms/orders/OrderStatusForm.cjs.js +1 -0
  100. package/lib/pages/cms/orders/OrderStatusForm.es.js +71 -0
  101. package/lib/pages/cms/orders/OrdersPage.cjs.js +1 -0
  102. package/lib/pages/cms/orders/OrdersPage.es.js +104 -0
  103. package/lib/pages/cms/orders/actions.cjs.js +7 -0
  104. package/lib/pages/cms/orders/actions.es.js +71 -0
  105. package/lib/pages/cms/orders/export-actions.cjs.js +1 -0
  106. package/lib/pages/cms/orders/export-actions.es.js +27 -0
  107. package/lib/pages/cms/orders/server-actions.cjs.js +1 -0
  108. package/lib/pages/cms/orders/server-actions.es.js +55 -0
  109. package/lib/pages/cms/payments/PaymentsClient.cjs.js +1 -0
  110. package/lib/pages/cms/payments/PaymentsClient.es.js +188 -0
  111. package/lib/pages/cms/payments/PaymentsPage.cjs.js +1 -0
  112. package/lib/pages/cms/payments/PaymentsPage.es.js +29 -0
  113. package/lib/pages/cms/payments/actions.cjs.js +1 -0
  114. package/lib/pages/cms/payments/actions.es.js +23 -0
  115. package/lib/pages/cms/payments/queries.cjs.js +1 -0
  116. package/lib/pages/cms/payments/queries.es.js +30 -0
  117. package/lib/pages/cms/products/ProductsPage.cjs.js +1 -0
  118. package/lib/pages/cms/products/ProductsPage.es.js +46 -0
  119. package/lib/pages/cms/products/_id_/edit/EditProductPage.cjs.js +1 -0
  120. package/lib/pages/cms/products/_id_/edit/EditProductPage.es.js +156 -0
  121. package/lib/pages/cms/products/actions.cjs.js +44 -0
  122. package/lib/pages/cms/products/actions.es.js +175 -0
  123. package/lib/pages/cms/products/attributes/AttributeManagementPage.cjs.js +1 -0
  124. package/lib/pages/cms/products/attributes/AttributeManagementPage.es.js +48 -0
  125. package/lib/pages/cms/products/attributes/components/AttributeManager.cjs.js +1 -0
  126. package/lib/pages/cms/products/attributes/components/AttributeManager.es.js +291 -0
  127. package/lib/pages/cms/products/categories/CategoryManagementPage.cjs.js +1 -0
  128. package/lib/pages/cms/products/categories/CategoryManagementPage.es.js +36 -0
  129. package/lib/pages/cms/products/categories/components/CategoryManager.cjs.js +1 -0
  130. package/lib/pages/cms/products/categories/components/CategoryManager.es.js +263 -0
  131. package/lib/pages/cms/products/components/CopyProductFromLanguage.cjs.js +1 -0
  132. package/lib/pages/cms/products/components/CopyProductFromLanguage.es.js +114 -0
  133. package/lib/pages/cms/products/components/CurrencyPriceFields.cjs.js +1 -0
  134. package/lib/pages/cms/products/components/CurrencyPriceFields.es.js +107 -0
  135. package/lib/pages/cms/products/components/DeleteProductButton.cjs.js +1 -0
  136. package/lib/pages/cms/products/components/DeleteProductButton.es.js +48 -0
  137. package/lib/pages/cms/products/components/FreemiusPricingDashboard.cjs.js +1 -0
  138. package/lib/pages/cms/products/components/FreemiusPricingDashboard.es.js +86 -0
  139. package/lib/pages/cms/products/components/ProductCategorySelector.cjs.js +1 -0
  140. package/lib/pages/cms/products/components/ProductCategorySelector.es.js +160 -0
  141. package/lib/pages/cms/products/components/ProductForm.cjs.js +1 -0
  142. package/lib/pages/cms/products/components/ProductForm.es.js +702 -0
  143. package/lib/pages/cms/products/components/ProductMediaManager.cjs.js +1 -0
  144. package/lib/pages/cms/products/components/ProductMediaManager.es.js +104 -0
  145. package/lib/pages/cms/products/components/ProductsBulkTable.cjs.js +1 -0
  146. package/lib/pages/cms/products/components/ProductsBulkTable.es.js +228 -0
  147. package/lib/pages/cms/products/components/SaleScheduleFields.cjs.js +1 -0
  148. package/lib/pages/cms/products/components/SaleScheduleFields.es.js +137 -0
  149. package/lib/pages/cms/products/components/SyncFreemiusButton.cjs.js +1 -0
  150. package/lib/pages/cms/products/components/SyncFreemiusButton.es.js +36 -0
  151. package/lib/pages/cms/products/components/SyncFreemiusPricingButton.cjs.js +1 -0
  152. package/lib/pages/cms/products/components/SyncFreemiusPricingButton.es.js +40 -0
  153. package/lib/pages/cms/products/components/VariationsEditor.cjs.js +1 -0
  154. package/lib/pages/cms/products/components/VariationsEditor.es.js +408 -0
  155. package/lib/pages/cms/products/inventory/InventoryPage.cjs.js +1 -0
  156. package/lib/pages/cms/products/inventory/InventoryPage.es.js +16 -0
  157. package/lib/pages/cms/products/inventory/InventoryTableClient.cjs.js +2 -0
  158. package/lib/pages/cms/products/inventory/InventoryTableClient.es.js +214 -0
  159. package/lib/pages/cms/products/inventory/actions.cjs.js +3 -0
  160. package/lib/pages/cms/products/inventory/actions.es.js +95 -0
  161. package/lib/pages/cms/products/new/NewProductPage.cjs.js +1 -0
  162. package/lib/pages/cms/products/new/NewProductPage.es.js +76 -0
  163. package/lib/pages/cms/products/product-price-sync.cjs.js +1 -0
  164. package/lib/pages/cms/products/product-price-sync.es.js +98 -0
  165. package/lib/pages/cms/products/server-actions.cjs.js +1 -0
  166. package/lib/pages/cms/products/server-actions.es.js +193 -0
  167. package/lib/pages/cms/shipping/ShippingPage.cjs.js +5 -0
  168. package/lib/pages/cms/shipping/ShippingPage.es.js +211 -0
  169. package/lib/pages/cms/shipping/components/RateForm.cjs.js +1 -0
  170. package/lib/pages/cms/shipping/components/RateForm.es.js +441 -0
  171. package/lib/pages/cms/shipping/components/ZoneForm.cjs.js +1 -0
  172. package/lib/pages/cms/shipping/components/ZoneForm.es.js +228 -0
  173. package/lib/pages/cms/shipping/server-actions.cjs.js +1 -0
  174. package/lib/pages/cms/shipping/server-actions.es.js +159 -0
  175. package/lib/pages/cms/taxes/TaxesPage.cjs.js +1 -0
  176. package/lib/pages/cms/taxes/TaxesPage.es.js +172 -0
  177. package/lib/pages/cms/taxes/actions.cjs.js +1 -0
  178. package/lib/pages/cms/taxes/actions.es.js +57 -0
  179. package/lib/pages/cms/taxes/components/TaxRateForm.cjs.js +1 -0
  180. package/lib/pages/cms/taxes/components/TaxRateForm.es.js +100 -0
  181. package/lib/product-actions.cjs.js +237 -0
  182. package/lib/product-actions.es.js +524 -0
  183. package/lib/product-context.cjs.js +1 -0
  184. package/lib/product-context.es.js +16 -0
  185. package/lib/product-schema.cjs.js +1 -0
  186. package/lib/product-schema.es.js +134 -0
  187. package/lib/providers/freemius.cjs.js +5 -0
  188. package/lib/providers/freemius.es.js +538 -0
  189. package/lib/providers/stripe.cjs.js +1 -0
  190. package/lib/providers/stripe.es.js +473 -0
  191. package/lib/server-actions/coupon-actions.cjs.js +1 -0
  192. package/lib/server-actions/coupon-actions.es.js +23 -0
  193. package/lib/server-actions/customer-actions.cjs.js +1 -0
  194. package/lib/server-actions/customer-actions.es.js +30 -0
  195. package/lib/server-actions/product-actions.cjs.js +1 -0
  196. package/{server-actions → lib/server-actions}/product-actions.es.js +5 -4
  197. package/lib/server-actions/shipping-actions.cjs.js +1 -0
  198. package/{shipping-actions-BnHjlo2q.js → lib/server-actions/shipping-actions.es.js} +9 -7
  199. package/lib/server-actions/tax-actions.cjs.js +1 -0
  200. package/lib/server-actions/tax-actions.es.js +40 -0
  201. package/lib/shared-inventory.cjs.js +15 -0
  202. package/lib/shared-inventory.es.js +171 -0
  203. package/lib/shipping/resolver.cjs.js +7 -0
  204. package/lib/shipping/resolver.es.js +62 -0
  205. package/lib/shipping-rate-currency.cjs.js +1 -0
  206. package/lib/shipping-rate-currency.es.js +72 -0
  207. package/lib/states.cjs.js +1 -0
  208. package/{states-DlHJezQ1.js → lib/states.es.js} +27 -100
  209. package/lib/stripe/checkout.cjs.js +1 -0
  210. package/lib/stripe/checkout.es.js +182 -0
  211. package/lib/stripe/client.cjs.js +1 -0
  212. package/lib/stripe/client.es.js +7 -0
  213. package/lib/stripe/order-sync.cjs.js +1 -0
  214. package/lib/stripe/order-sync.es.js +130 -0
  215. package/lib/stripe/webhooks.cjs.js +1 -0
  216. package/lib/stripe/webhooks.es.js +30 -0
  217. package/lib/tax-calculation.cjs.js +1 -0
  218. package/lib/tax-calculation.es.js +101 -0
  219. package/lib/trials.cjs.js +1 -0
  220. package/{trials-RDcRAZKx.js → lib/trials.es.js} +9 -9
  221. package/{use-cart.es.js → lib/use-cart.es.js} +1 -0
  222. package/lib/zod-config.cjs.js +1 -0
  223. package/lib/zod-config.es.js +6 -0
  224. package/package.json +4 -4
  225. package/server.cjs.js +1 -110
  226. package/server.es.js +178 -6052
  227. package/AddToCartButton-DsSEH9yp.cjs +0 -1
  228. package/CouponForm-BI_5SBHQ.js +0 -152
  229. package/CouponForm-D_uu2bLP.cjs +0 -1
  230. package/CurrencyProvider-Cg-Q6ucj.cjs +0 -1
  231. package/CurrencyProvider-OzlRN96V.js +0 -120
  232. package/CurrencyProvider.cjs.js +0 -1
  233. package/CurrencyProvider.es.js +0 -10
  234. package/ProductDetailsLayout-BxJH_BxR.cjs +0 -1
  235. package/ProductDetailsLayout-Dg8dRTYp.js +0 -530
  236. package/ProductGrid-BdL7iglO.cjs +0 -1
  237. package/ProductGrid-D3AWM8sr.js +0 -130
  238. package/actions-AHmBrS5e.cjs +0 -48
  239. package/actions-j5fuSZX-.js +0 -820
  240. package/cart-store.cjs.js +0 -1
  241. package/components/Cart.cjs.js +0 -1
  242. package/components/Cart.es.js +0 -259
  243. package/components/CartDrawer.cjs.js +0 -1
  244. package/components/Checkout.cjs.js +0 -1
  245. package/components/CurrencySwitcher.cjs.js +0 -1
  246. package/components/FeaturedProduct.cjs.js +0 -1
  247. package/components/ProductDetailsLayout.cjs.js +0 -1
  248. package/components/ProductDetailsLayout.es.js +0 -19
  249. package/components/ProductGrid.cjs.js +0 -1
  250. package/components/ProductGrid.es.js +0 -6
  251. package/coupon-server-C9ySm3I5.cjs +0 -1
  252. package/customer-C-UPvrYN.cjs +0 -1
  253. package/invoice-ui-CAnJPu6n.cjs +0 -29
  254. package/invoice-ui-DtpbTJE1.js +0 -2886
  255. package/product-actions-CONBF8i6.cjs +0 -251
  256. package/product-actions-DjlIWCMH.js +0 -691
  257. package/resolver-Fz_FKsfX.cjs +0 -7
  258. package/resolver-cfrCaHpE.js +0 -128
  259. package/server-actions/product-actions.cjs.js +0 -1
  260. package/shipping-actions-D6zt20gg.cjs +0 -1
  261. package/states-CWYRxV4B.cjs +0 -1
  262. package/tax-calculation-Dab89aHd.js +0 -181
  263. package/tax-calculation-MkDKOEkL.cjs +0 -1
  264. package/trials-DvZaOtNy.cjs +0 -1
  265. /package/{components → lib/components}/SimpleTiptapRenderer.cjs.js +0 -0
  266. /package/{components → lib/components}/SimpleTiptapRenderer.es.js +0 -0
  267. /package/{currency-constants.cjs.js → lib/currency-constants.cjs.js} +0 -0
  268. /package/{currency-constants.es.js → lib/currency-constants.es.js} +0 -0
  269. /package/{currency-rest-client-uolJxUkL.cjs → lib/currency-rest-client.cjs.js} +0 -0
  270. /package/{currency-rest-client-CwoqdgAP.js → lib/currency-rest-client.es.js} +0 -0
  271. /package/{currency.cjs.js → lib/currency.cjs.js} +0 -0
  272. /package/{currency.es.js → lib/currency.es.js} +0 -0
  273. /package/{types.cjs.js → lib/types.cjs.js} +0 -0
  274. /package/{types.es.js → lib/types.es.js} +0 -0
  275. /package/{use-cart.cjs.js → lib/use-cart.cjs.js} +0 -0
  276. /package/{variation-utils.cjs.js → lib/variation-utils.cjs.js} +0 -0
  277. /package/{variation-utils.es.js → lib/variation-utils.es.js} +0 -0
@@ -0,0 +1,171 @@
1
+ import "server-only";
2
+ import { getServiceRoleSupabaseClient as w } from "@nextblock-cms/db/server";
3
+ function f(a) {
4
+ return a ?? w();
5
+ }
6
+ function S(a) {
7
+ return a ? (Array.isArray(a) ? a : [a]).map((r) => r?.code?.toUpperCase().trim()).filter((r) => !!r) : [];
8
+ }
9
+ function g(a) {
10
+ return [...new Set(a)].sort((n, r) => n.localeCompare(r));
11
+ }
12
+ function M(a, n) {
13
+ return !a || a === n ? n : "mixed";
14
+ }
15
+ async function l(a, n) {
16
+ const r = Array.from(
17
+ n.reduce((u, s) => {
18
+ const t = s.sku.trim();
19
+ return t && u.set(t, {
20
+ sku: t,
21
+ quantity: Math.max(0, Math.trunc(s.quantity))
22
+ }), u;
23
+ }, /* @__PURE__ */ new Map()).values()
24
+ );
25
+ if (r.length === 0)
26
+ return;
27
+ const { error: o } = await a.from("inventory_items").upsert(r, { onConflict: "sku" });
28
+ if (o)
29
+ throw new Error(o.message);
30
+ }
31
+ async function k(a, n) {
32
+ const r = g(
33
+ n.map((s) => s.trim()).filter(Boolean)
34
+ );
35
+ if (r.length === 0)
36
+ return /* @__PURE__ */ new Map();
37
+ const { data: o, error: u } = await a.from("inventory_items").select("sku, quantity").in("sku", r);
38
+ if (u)
39
+ throw new Error(u.message);
40
+ return new Map(
41
+ (o || []).map((s) => [
42
+ s.sku,
43
+ Math.max(0, s.quantity ?? 0)
44
+ ])
45
+ );
46
+ }
47
+ async function m(a) {
48
+ const { data: n, error: r } = await a.from("products").select(
49
+ `
50
+ id,
51
+ title,
52
+ sku,
53
+ stock,
54
+ status,
55
+ languages (
56
+ code
57
+ ),
58
+ product_variants (
59
+ id,
60
+ sku,
61
+ stock_quantity
62
+ )
63
+ `
64
+ ).order("title", { ascending: !0 });
65
+ if (r)
66
+ throw new Error(r.message);
67
+ const o = /* @__PURE__ */ new Map(), u = (s, t, e, c, d) => {
68
+ const p = s.trim();
69
+ if (!p)
70
+ return;
71
+ const y = S(c.languages), i = o.get(p);
72
+ if (i) {
73
+ i.usageType = M(i.usageType, t), i.stockFallback = Math.min(i.stockFallback, e), i.productTitles.add(c.title), i.parentProductSkus.add(c.sku), i.languages = /* @__PURE__ */ new Set([...i.languages, ...y]), i.statuses.add(c.status), i.productIds.add(c.id), d && i.variantIds.add(d);
74
+ return;
75
+ }
76
+ o.set(p, {
77
+ sku: p,
78
+ stockFallback: e,
79
+ usageType: t,
80
+ productTitles: /* @__PURE__ */ new Set([c.title]),
81
+ parentProductSkus: /* @__PURE__ */ new Set([c.sku]),
82
+ languages: new Set(y),
83
+ statuses: /* @__PURE__ */ new Set([c.status]),
84
+ productIds: /* @__PURE__ */ new Set([c.id]),
85
+ variantIds: d ? /* @__PURE__ */ new Set([d]) : /* @__PURE__ */ new Set()
86
+ });
87
+ };
88
+ for (const s of n || []) {
89
+ const t = s.product_variants || [];
90
+ if (t.length > 0) {
91
+ for (const e of t)
92
+ u(
93
+ e.sku,
94
+ "variant",
95
+ Math.max(0, e.stock_quantity ?? 0),
96
+ s,
97
+ e.id
98
+ );
99
+ continue;
100
+ }
101
+ u(
102
+ s.sku,
103
+ "product",
104
+ Math.max(0, s.stock ?? 0),
105
+ s
106
+ );
107
+ }
108
+ return o;
109
+ }
110
+ async function I(a) {
111
+ const n = f(a), r = await m(n), o = [...r.keys()];
112
+ if (o.length === 0)
113
+ return [];
114
+ let u = await k(n, o);
115
+ const s = o.filter((t) => !u.has(t)).flatMap((t) => {
116
+ const e = r.get(t);
117
+ return e ? [
118
+ {
119
+ sku: t,
120
+ quantity: e.stockFallback
121
+ }
122
+ ] : [];
123
+ });
124
+ return s.length > 0 && (await l(n, s), u = await k(n, o)), o.flatMap((t) => {
125
+ const e = r.get(t);
126
+ return e ? {
127
+ key: t,
128
+ sku: t,
129
+ stock: u.get(t) ?? e.stockFallback,
130
+ usageType: e.usageType,
131
+ productTitles: g(e.productTitles),
132
+ parentProductSkus: g(e.parentProductSkus),
133
+ languages: g(e.languages),
134
+ statuses: g(e.statuses),
135
+ productIds: g(e.productIds),
136
+ variantIds: g(e.variantIds)
137
+ } : [];
138
+ }).sort((t, e) => t.sku.localeCompare(e.sku) || t.usageType.localeCompare(e.usageType) || t.productTitles.join(", ").localeCompare(e.productTitles.join(", ")));
139
+ }
140
+ async function q(a, n) {
141
+ const r = f(n), o = a.sku.trim(), u = Math.max(0, Math.trunc(a.stock));
142
+ if (!o)
143
+ throw new Error("SKU is required to update inventory.");
144
+ await l(r, [{ sku: o, quantity: u }]);
145
+ const t = (await m(r)).get(o), e = (t?.productIds.size ?? 0) + (t?.variantIds.size ?? 0);
146
+ return { stock: u, affectedCount: e };
147
+ }
148
+ async function T(a, n, r) {
149
+ const o = f(r);
150
+ if (n.variants && n.variants.length > 0) {
151
+ const u = Array.from(
152
+ n.variants.reduce((s, t) => (s.set(
153
+ t.sku.trim(),
154
+ Math.max(0, Math.trunc(t.stock_quantity))
155
+ ), s), /* @__PURE__ */ new Map()).entries()
156
+ ).map(([s, t]) => ({ sku: s, quantity: t }));
157
+ await l(o, u);
158
+ return;
159
+ }
160
+ await l(o, [
161
+ {
162
+ sku: n.sku,
163
+ quantity: Math.max(0, Math.trunc(n.stock))
164
+ }
165
+ ]);
166
+ }
167
+ export {
168
+ I as getInventoryItems,
169
+ q as setSharedInventoryQuantity,
170
+ T as syncSharedInventoryForSavedProduct
171
+ };
@@ -0,0 +1,7 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@nextblock-cms/db/server"),v=require("../currency.cjs.js"),d=require("../shipping-rate-currency.cjs.js"),C=require("../variation-utils.cjs.js");async function z(l,t,p,m){const c=h.getSsgSupabaseClient(),{data:y}=await c.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}),s=y??[],a=v.getDefaultCurrency(s),i=m||a.code,{data:o,error:g}=await c.from("shipping_zone_locations").select(`
2
+ zone_id,
3
+ country_code,
4
+ state_code,
5
+ postal_code,
6
+ shipping_zones!inner(priority_order)
7
+ `).eq("country_code",t.country).order("shipping_zones(priority_order)",{ascending:!0});if(g||!o||o.length===0)return[];let n=null;if(t.state){const e=o.find(r=>r.state_code===t.state);e&&(n=e.zone_id)}if(!n){const e=o.find(r=>!r.state_code&&!r.postal_code);e&&(n=e.zone_id)}n||(n=o[0].zone_id);const{data:u,error:f}=await c.from("shipping_zone_methods").select("id, zone_id, method_type, cost_amount, cost_amounts, cost_currency, currency_pricing_mode, min_order_amount, min_order_amounts, name, name_translations").eq("zone_id",n);if(f||!u)return[];const _=u.filter(e=>{const r=d.resolveShippingRateAmountForCurrency({amountMap:e.min_order_amounts||{},fallbackAmount:e.min_order_amount||0,sourceCurrencyCode:e.cost_currency||a.code,mode:e.currency_pricing_mode,currencyCode:i,currencies:s});return l>=r}).map(e=>({id:e.id,name:C.resolveTranslatedText(e.name,e.name_translations||null,p),amount:d.resolveShippingRateAmountForCurrency({amountMap:e.cost_amounts||{},fallbackAmount:e.cost_amount||0,sourceCurrencyCode:e.cost_currency||a.code,mode:e.currency_pricing_mode,currencyCode:i,currencies:s}),currency:i,type:e.method_type})).sort((e,r)=>e.amount-r.amount)[0];return _?[_]:[]}exports.resolveShippingOptions=z;
@@ -0,0 +1,62 @@
1
+ import { getSsgSupabaseClient as h } from "@nextblock-cms/db/server";
2
+ import { getDefaultCurrency as C } from "../currency.es.js";
3
+ import { resolveShippingRateAmountForCurrency as d } from "../shipping-rate-currency.es.js";
4
+ import { resolveTranslatedText as v } from "../variation-utils.es.js";
5
+ async function w(m, n, p, l) {
6
+ const c = h(), { data: y } = await c.from("currencies").select(
7
+ "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"
8
+ ).eq("is_active", !0).order("code", { ascending: !0 }), a = y ?? [], s = C(a), i = l || s.code, { data: t, error: f } = await c.from("shipping_zone_locations").select(`
9
+ zone_id,
10
+ country_code,
11
+ state_code,
12
+ postal_code,
13
+ shipping_zones!inner(priority_order)
14
+ `).eq("country_code", n.country).order("shipping_zones(priority_order)", { ascending: !0 });
15
+ if (f || !t || t.length === 0)
16
+ return [];
17
+ let r = null;
18
+ if (n.state) {
19
+ const e = t.find((o) => o.state_code === n.state);
20
+ e && (r = e.zone_id);
21
+ }
22
+ if (!r) {
23
+ const e = t.find((o) => !o.state_code && !o.postal_code);
24
+ e && (r = e.zone_id);
25
+ }
26
+ r || (r = t[0].zone_id);
27
+ const { data: u, error: g } = await c.from("shipping_zone_methods").select("id, zone_id, method_type, cost_amount, cost_amounts, cost_currency, currency_pricing_mode, min_order_amount, min_order_amounts, name, name_translations").eq("zone_id", r);
28
+ if (g || !u)
29
+ return [];
30
+ const _ = u.filter((e) => {
31
+ const o = d({
32
+ amountMap: e.min_order_amounts || {},
33
+ fallbackAmount: e.min_order_amount || 0,
34
+ sourceCurrencyCode: e.cost_currency || s.code,
35
+ mode: e.currency_pricing_mode,
36
+ currencyCode: i,
37
+ currencies: a
38
+ });
39
+ return m >= o;
40
+ }).map((e) => ({
41
+ id: e.id,
42
+ name: v(
43
+ e.name,
44
+ e.name_translations || null,
45
+ p
46
+ ),
47
+ amount: d({
48
+ amountMap: e.cost_amounts || {},
49
+ fallbackAmount: e.cost_amount || 0,
50
+ sourceCurrencyCode: e.cost_currency || s.code,
51
+ mode: e.currency_pricing_mode,
52
+ currencyCode: i,
53
+ currencies: a
54
+ }),
55
+ currency: i,
56
+ type: e.method_type
57
+ })).sort((e, o) => e.amount - o.amount)[0];
58
+ return _ ? [_] : [];
59
+ }
60
+ export {
61
+ w as resolveShippingOptions
62
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@nextblock-cms/utils"),c=require("./currency.cjs.js"),a=["auto","manual"];function l(e){if(typeof e=="string"){const r=e.trim().toLowerCase();if(a.includes(r))return r}return"auto"}function m(e,r=0){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.round(e):r}function y(e){const r=d.normalizeCurrencyCode(e.sourceCurrencyCode),o=c.normalizePriceMap(e.amountMap);if(o[r]!==void 0)return r;const t=Object.keys(o)[0];return t?d.normalizeCurrencyCode(t):c.getDefaultCurrency(e.currencies).code}function A(e){const r=l(e.mode),o=c.normalizePriceMap(e.costAmounts),t=c.normalizePriceMap(e.minOrderAmounts),n=y({amountMap:Object.keys(o).length>0?o:t,sourceCurrencyCode:e.sourceCurrencyCode,currencies:e.currencies}),u=o[n]??m(e.fallbackCostAmount),i=t[n]??m(e.fallbackMinOrderAmount);if(r==="auto")return{mode:r,sourceCurrencyCode:n,costAmounts:{[n]:u},minOrderAmounts:{[n]:i}};const s=Object.keys(o).length>0?{...o}:{[n]:u},C=Object.keys(t).length>0?{...t}:{[n]:i};return s[n]===void 0&&(s[n]=u),C[n]===void 0&&(C[n]=i),{mode:r,sourceCurrencyCode:n,costAmounts:s,minOrderAmounts:C}}function f(e){const r=l(e.mode),o=c.normalizePriceMap(e.amountMap),t=d.normalizeCurrencyCode(e.currencyCode);if(r==="manual"&&o[t]!==void 0)return o[t];const n=y({amountMap:o,sourceCurrencyCode:e.sourceCurrencyCode,currencies:e.currencies}),u=o[n]??m(e.fallbackAmount);return t===n?u:c.convertMinorUnitAmount({amount:u,fromCurrencyCode:n,toCurrencyCode:t,currencies:e.currencies})}exports.SHIPPING_RATE_CURRENCY_MODES=a;exports.normalizeShippingRateCurrencyMode=l;exports.resolveShippingRateAmountForCurrency=f;exports.sanitizeShippingRateAmountMaps=A;
@@ -0,0 +1,72 @@
1
+ import { normalizeCurrencyCode as m } from "@nextblock-cms/utils";
2
+ import { normalizePriceMap as c, convertMinorUnitAmount as l, getDefaultCurrency as A } from "./currency.es.js";
3
+ const M = ["auto", "manual"];
4
+ function f(n) {
5
+ if (typeof n == "string") {
6
+ const o = n.trim().toLowerCase();
7
+ if (M.includes(
8
+ o
9
+ ))
10
+ return o;
11
+ }
12
+ return "auto";
13
+ }
14
+ function C(n, o = 0) {
15
+ return typeof n == "number" && Number.isFinite(n) && n >= 0 ? Math.round(n) : o;
16
+ }
17
+ function y(n) {
18
+ const o = m(
19
+ n.sourceCurrencyCode
20
+ ), r = c(n.amountMap);
21
+ if (r[o] !== void 0)
22
+ return o;
23
+ const t = Object.keys(r)[0];
24
+ return t ? m(t) : A(n.currencies).code;
25
+ }
26
+ function O(n) {
27
+ const o = f(n.mode), r = c(n.costAmounts), t = c(n.minOrderAmounts), e = y({
28
+ amountMap: Object.keys(r).length > 0 ? r : t,
29
+ sourceCurrencyCode: n.sourceCurrencyCode,
30
+ currencies: n.currencies
31
+ }), u = r[e] ?? C(n.fallbackCostAmount), i = t[e] ?? C(n.fallbackMinOrderAmount);
32
+ if (o === "auto")
33
+ return {
34
+ mode: o,
35
+ sourceCurrencyCode: e,
36
+ costAmounts: {
37
+ [e]: u
38
+ },
39
+ minOrderAmounts: {
40
+ [e]: i
41
+ }
42
+ };
43
+ const s = Object.keys(r).length > 0 ? { ...r } : { [e]: u }, d = Object.keys(t).length > 0 ? { ...t } : { [e]: i };
44
+ return s[e] === void 0 && (s[e] = u), d[e] === void 0 && (d[e] = i), {
45
+ mode: o,
46
+ sourceCurrencyCode: e,
47
+ costAmounts: s,
48
+ minOrderAmounts: d
49
+ };
50
+ }
51
+ function g(n) {
52
+ const o = f(n.mode), r = c(n.amountMap), t = m(n.currencyCode);
53
+ if (o === "manual" && r[t] !== void 0)
54
+ return r[t];
55
+ const e = y({
56
+ amountMap: r,
57
+ sourceCurrencyCode: n.sourceCurrencyCode,
58
+ currencies: n.currencies
59
+ }), u = r[e] ?? C(n.fallbackAmount);
60
+ return t === e ? u : l({
61
+ amount: u,
62
+ fromCurrencyCode: e,
63
+ toCurrencyCode: t,
64
+ currencies: n.currencies
65
+ });
66
+ }
67
+ export {
68
+ M as SHIPPING_RATE_CURRENCY_MODES,
69
+ f as normalizeShippingRateCurrencyMode,
70
+ g as resolveShippingRateAmountForCurrency,
71
+ O as sanitizeShippingRateAmountMaps
72
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./countries.cjs.js"),S=[{code:"AL",name:"Alabama"},{code:"AK",name:"Alaska"},{code:"AZ",name:"Arizona"},{code:"AR",name:"Arkansas"},{code:"CA",name:"California"},{code:"CO",name:"Colorado"},{code:"CT",name:"Connecticut"},{code:"DE",name:"Delaware"},{code:"DC",name:"District of Columbia"},{code:"FL",name:"Florida"},{code:"GA",name:"Georgia"},{code:"HI",name:"Hawaii"},{code:"ID",name:"Idaho"},{code:"IL",name:"Illinois"},{code:"IN",name:"Indiana"},{code:"IA",name:"Iowa"},{code:"KS",name:"Kansas"},{code:"KY",name:"Kentucky"},{code:"LA",name:"Louisiana"},{code:"ME",name:"Maine"},{code:"MD",name:"Maryland"},{code:"MA",name:"Massachusetts"},{code:"MI",name:"Michigan"},{code:"MN",name:"Minnesota"},{code:"MS",name:"Mississippi"},{code:"MO",name:"Missouri"},{code:"MT",name:"Montana"},{code:"NE",name:"Nebraska"},{code:"NV",name:"Nevada"},{code:"NH",name:"New Hampshire"},{code:"NJ",name:"New Jersey"},{code:"NM",name:"New Mexico"},{code:"NY",name:"New York"},{code:"NC",name:"North Carolina"},{code:"ND",name:"North Dakota"},{code:"OH",name:"Ohio"},{code:"OK",name:"Oklahoma"},{code:"OR",name:"Oregon"},{code:"PA",name:"Pennsylvania"},{code:"RI",name:"Rhode Island"},{code:"SC",name:"South Carolina"},{code:"SD",name:"South Dakota"},{code:"TN",name:"Tennessee"},{code:"TX",name:"Texas"},{code:"UT",name:"Utah"},{code:"VT",name:"Vermont"},{code:"VA",name:"Virginia"},{code:"WA",name:"Washington"},{code:"WV",name:"West Virginia"},{code:"WI",name:"Wisconsin"},{code:"WY",name:"Wyoming"}],l=[{code:"AB",name:"Alberta"},{code:"BC",name:"British Columbia"},{code:"MB",name:"Manitoba"},{code:"NB",name:"New Brunswick"},{code:"NL",name:"Newfoundland and Labrador"},{code:"NS",name:"Nova Scotia"},{code:"NT",name:"Northwest Territories"},{code:"NU",name:"Nunavut"},{code:"ON",name:"Ontario"},{code:"PE",name:"Prince Edward Island"},{code:"QC",name:"Quebec"},{code:"SK",name:"Saskatchewan"},{code:"YT",name:"Yukon"}],t={US:S,CA:l},N={US:{CALIFORNIA:"CA",NEWYORK:"NY","NEW YORK":"NY",DISTRICTOFCOLUMBIA:"DC","DISTRICT OF COLUMBIA":"DC"},CA:{QUEBEC:"QC",ONTARIO:"ON","BRITISH COLUMBIA":"BC",BRITISHCOLUMBIA:"BC","NEWFOUNDLAND AND LABRADOR":"NL",NEWFOUNDLANDANDLABRADOR:"NL","NORTHWEST TERRITORIES":"NT",NORTHWESTTERRITORIES:"NT","PRINCE EDWARD ISLAND":"PE",PRINCEEDWARDISLAND:"PE"}};function u(e){const a=r.normalizeCountryCode(e);return a?t[a]??[]:[]}function I(e){return u(e).length>0}function C(e,a){const o=r.normalizeCountryCode(e),n=a?.trim();if(!o||!n)return n||null;const d=t[o];if(!d?.length)return n.toUpperCase();const c=n.toUpperCase(),m=d.find(i=>i.code===c);if(m)return m.code;const s=d.find(i=>i.name.toUpperCase()===c);if(s)return s.code;const A=c.replace(/\s+/g,"");return N[o]?.[c]??N[o]?.[A]??c}function T(e,a){const o=r.normalizeCountryCode(e),n=C(e,a);return!o||!n?a??null:t[o]?.find(c=>c.code===n)?.name??n}exports.STATES_BY_COUNTRY=t;exports.countryUsesStructuredStates=I;exports.getStatesForCountry=u;exports.normalizeSubdivisionCode=C;exports.resolveSubdivisionName=T;
@@ -1,76 +1,4 @@
1
- const N = [
2
- { code: "US", name: "United States" },
3
- { code: "CA", name: "Canada" },
4
- { code: "GB", name: "United Kingdom" },
5
- { code: "AU", name: "Australia" },
6
- { code: "NZ", name: "New Zealand" },
7
- { code: "IE", name: "Ireland" },
8
- { code: "FR", name: "France" },
9
- { code: "DE", name: "Germany" },
10
- { code: "IT", name: "Italy" },
11
- { code: "ES", name: "Spain" },
12
- { code: "MX", name: "Mexico" },
13
- { code: "BR", name: "Brazil" },
14
- { code: "AR", name: "Argentina" },
15
- { code: "CL", name: "Chile" },
16
- { code: "CO", name: "Colombia" },
17
- { code: "PE", name: "Peru" },
18
- { code: "ZA", name: "South Africa" },
19
- { code: "NG", name: "Nigeria" },
20
- { code: "KE", name: "Kenya" },
21
- { code: "IN", name: "India" },
22
- { code: "JP", name: "Japan" },
23
- { code: "KR", name: "South Korea" },
24
- { code: "CN", name: "China" },
25
- { code: "SG", name: "Singapore" },
26
- { code: "MY", name: "Malaysia" },
27
- { code: "PH", name: "Philippines" },
28
- { code: "TH", name: "Thailand" },
29
- { code: "VN", name: "Vietnam" },
30
- { code: "ID", name: "Indonesia" },
31
- { code: "AE", name: "United Arab Emirates" },
32
- { code: "SA", name: "Saudi Arabia" },
33
- { code: "EG", name: "Egypt" },
34
- { code: "MA", name: "Morocco" },
35
- { code: "DZ", name: "Algeria" },
36
- { code: "TN", name: "Tunisia" },
37
- { code: "PT", name: "Portugal" },
38
- { code: "NL", name: "Netherlands" },
39
- { code: "BE", name: "Belgium" },
40
- { code: "CH", name: "Switzerland" },
41
- { code: "AT", name: "Austria" },
42
- { code: "SE", name: "Sweden" },
43
- { code: "NO", name: "Norway" },
44
- { code: "DK", name: "Denmark" },
45
- { code: "FI", name: "Finland" },
46
- { code: "PL", name: "Poland" },
47
- { code: "CZ", name: "Czech Republic" },
48
- { code: "HU", name: "Hungary" },
49
- { code: "RO", name: "Romania" },
50
- { code: "BG", name: "Bulgaria" },
51
- { code: "GR", name: "Greece" },
52
- { code: "TR", name: "Turkey" },
53
- { code: "IL", name: "Israel" },
54
- { code: "CY", name: "Cyprus" },
55
- { code: "MT", name: "Malta" }
56
- ], l = {
57
- USA: "US",
58
- "UNITED STATES OF AMERICA": "US",
59
- UK: "GB",
60
- "GREAT BRITAIN": "GB"
61
- };
62
- function t(n) {
63
- const o = n?.trim();
64
- if (!o)
65
- return null;
66
- const e = o.toUpperCase(), a = l[e];
67
- if (a)
68
- return a;
69
- const d = N.find((m) => m.code === e);
70
- return d ? d.code : N.find(
71
- (m) => m.name.toUpperCase() === e
72
- )?.code ?? null;
73
- }
1
+ import { normalizeCountryCode as t } from "./countries.es.js";
74
2
  const C = [
75
3
  { code: "AL", name: "Alabama" },
76
4
  { code: "AK", name: "Alaska" },
@@ -123,7 +51,7 @@ const C = [
123
51
  { code: "WV", name: "West Virginia" },
124
52
  { code: "WI", name: "Wisconsin" },
125
53
  { code: "WY", name: "Wyoming" }
126
- ], I = [
54
+ ], u = [
127
55
  { code: "AB", name: "Alberta" },
128
56
  { code: "BC", name: "British Columbia" },
129
57
  { code: "MB", name: "Manitoba" },
@@ -137,10 +65,10 @@ const C = [
137
65
  { code: "QC", name: "Quebec" },
138
66
  { code: "SK", name: "Saskatchewan" },
139
67
  { code: "YT", name: "Yukon" }
140
- ], r = {
68
+ ], i = {
141
69
  US: C,
142
- CA: I
143
- }, u = {
70
+ CA: u
71
+ }, N = {
144
72
  US: {
145
73
  CALIFORNIA: "CA",
146
74
  NEWYORK: "NY",
@@ -161,40 +89,39 @@ const C = [
161
89
  PRINCEEDWARDISLAND: "PE"
162
90
  }
163
91
  };
164
- function S(n) {
165
- const o = t(n);
166
- return o ? r[o] ?? [] : [];
92
+ function I(e) {
93
+ const n = t(e);
94
+ return n ? i[n] ?? [] : [];
167
95
  }
168
- function E(n) {
169
- return S(n).length > 0;
96
+ function T(e) {
97
+ return I(e).length > 0;
170
98
  }
171
- function T(n, o) {
172
- const e = t(n), a = o?.trim();
173
- if (!e || !a)
99
+ function l(e, n) {
100
+ const o = t(e), a = n?.trim();
101
+ if (!o || !a)
174
102
  return a || null;
175
- const d = r[e];
103
+ const d = i[o];
176
104
  if (!d?.length)
177
105
  return a.toUpperCase();
178
- const c = a.toUpperCase(), m = d.find((i) => i.code === c);
179
- if (m)
180
- return m.code;
181
- const s = d.find((i) => i.name.toUpperCase() === c);
106
+ const c = a.toUpperCase(), r = d.find((m) => m.code === c);
107
+ if (r)
108
+ return r.code;
109
+ const s = d.find((m) => m.name.toUpperCase() === c);
182
110
  if (s)
183
111
  return s.code;
184
112
  const A = c.replace(/\s+/g, "");
185
- return u[e]?.[c] ?? u[e]?.[A] ?? c;
113
+ return N[o]?.[c] ?? N[o]?.[A] ?? c;
186
114
  }
187
- function M(n, o) {
188
- const e = t(n), a = T(n, o);
189
- return !e || !a ? o ?? null : r[e]?.find(
115
+ function R(e, n) {
116
+ const o = t(e), a = l(e, n);
117
+ return !o || !a ? n ?? null : i[o]?.find(
190
118
  (c) => c.code === a
191
119
  )?.name ?? a;
192
120
  }
193
121
  export {
194
- E as a,
195
- T as b,
196
- N as c,
197
- S as g,
198
- t as n,
199
- M as r
122
+ i as STATES_BY_COUNTRY,
123
+ T as countryUsesStructuredStates,
124
+ I as getStatesForCountry,
125
+ l as normalizeSubdivisionCode,
126
+ R as resolveSubdivisionName
200
127
  };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("./client.cjs.js"),N=require("@supabase/supabase-js"),R=require("@nextblock-cms/db/server"),L=require("../shipping/resolver.cjs.js"),S=require("../currency.cjs.js"),T=async(n,d,P,A)=>{const m=process.env.NEXT_PUBLIC_SUPABASE_URL,h=process.env.SUPABASE_SERVICE_ROLE_KEY;if(!m||!h)return console.error("Missing Supabase credentials for checkout (Service Key required)."),{error:"Internal Server Error",url:null};const t=N.createClient(m,h),f=process.env.NEXT_PUBLIC_URL||"http://localhost:4200";if(!n.length)return{error:"Cart is empty",url:null};const{data:q}=await t.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}),u=q??[],w=S.getDefaultCurrency(u),c=u.find(e=>e.code===(A||"").toUpperCase())??w;if(!await R.verifyPackageOnline("ecommerce"))return{error:"E-Commerce Package not active. Please purchase a license to accept payments.",url:null};const I=n.map(e=>e.product_id),{data:g,error:y}=await t.from("products").select("id, title, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at").in("id",I);if(y||!g)return console.error("Error fetching products for validation:",y),{error:"Failed to validate product prices",url:null};const U=new Map(g.map(e=>[e.id,e])),l=[];let s=0;const E=[];for(const e of n){const r=U.get(e.product_id);if(!r){console.warn(`Product ${e.product_id} not found in DB, skipping.`);continue}const C=S.resolveEffectivePriceForCurrency({prices:r.prices||{},salePrices:r.sale_prices||{},fallbackPrice:r.price,fallbackSalePrice:r.sale_price,saleStartAt:r.sale_start_at,saleEndAt:r.sale_end_at,scheduledPrice:r.scheduled_price,scheduledPrices:r.scheduled_prices||{},scheduledPriceAt:r.scheduled_price_at,currencyCode:c.code,currencies:u}),a=C.sale_price??C.price;a<=0&&console.warn(`[Checkout Session Warning] Product ${r.title} has zero or negative price!`),l.push({price_data:{currency:c.code.toLowerCase(),product_data:{name:r.title,images:[],metadata:{productId:r.id}},unit_amount:a},quantity:e.quantity}),s+=a*e.quantity,E.push({product_id:r.id,quantity:e.quantity,price_at_purchase:a})}if(l.length===0)return{error:"No valid items in cart",url:null};const{data:o,error:p}=await t.from("orders").insert({total:s,user_id:d,currency:c.code,exchange_rate_at_purchase:c.exchange_rate}).select("id").single();if(p||!o)return console.error("Failed to create pending order:",p),console.error("Order Data attempted:",{status:"pending",total:s}),{error:`Failed to initiate order: ${p?.message||"Unknown error"}`,url:null};const b=E.map(e=>({order_id:o.id,product_id:e.product_id,quantity:e.quantity,price_at_purchase:e.price_at_purchase})),{error:v}=await t.from("order_items").insert(b);v&&console.error("Failed to insert order items:",v);let _=[],i=P;if(!i&&d){const{data:e}=await t.from("user_addresses").select("country_code, state_code, postal_code").eq("user_id",d).eq("address_type","shipping").limit(1).single();e&&(i={country:e.country_code,state:e.state_code,postal_code:e.postal_code})}i&&(_=(await L.resolveShippingOptions(s,i,null,c.code)).map(r=>({shipping_rate_data:{type:"fixed_amount",fixed_amount:{amount:r.amount,currency:r.currency.toLowerCase()},display_name:r.name}})));try{const e=await k.stripe.checkout.sessions.create({mode:"payment",success_url:`${f}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,cancel_url:`${f}/`,line_items:l,billing_address_collection:"required",shipping_address_collection:{allowed_countries:["US","CA","GB","AU","NZ","IE","FR","DE","IT","ES","MX","BR","AR","CL","CO","PE","ZA","NG","KE","IN","JP","KR","CN","SG","MY","PH","TH","VN","ID","AE","SA","EG","MA","DZ","TN","PT","NL","BE","CH","AT","SE","NO","DK","FI","PL","CZ","HU","RO","BG","GR","TR","IL","CY","MT"]},shipping_options:_.length>0?_:void 0,metadata:{orderId:o.id}});return await t.from("orders").update({stripe_session_id:e.id}).eq("id",o.id),{url:e.url}}catch(e){return console.error("Stripe session creation failed:",e),{error:e.message,url:null}}};exports.createCheckoutSession=T;