@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,180 @@
1
+ import "server-only";
2
+ import { getServiceRoleSupabaseClient as E } from "@nextblock-cms/db/server";
3
+ import { normalizeCurrencyCode as a } from "@nextblock-cms/utils";
4
+ import { normalizeCurrencyRecord as S, getDefaultCurrency as v } from "./currency.es.js";
5
+ const F = "https://api.frankfurter.dev", A = "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";
6
+ function C(r) {
7
+ if (!r.id)
8
+ throw new Error(`Currency ${a(r.code)} is missing its ID.`);
9
+ return r.id;
10
+ }
11
+ function $() {
12
+ return process.env.FX_API_BASE_URL?.trim().replace(/\/+$/, "") || F;
13
+ }
14
+ function D(r) {
15
+ try {
16
+ const e = new URL(r), n = e.pathname.replace(/\/+$/, "");
17
+ return `${e.host}${n && n !== "/" ? n : ""}`;
18
+ } catch {
19
+ return r;
20
+ }
21
+ }
22
+ function N(r) {
23
+ if (!r || typeof r != "object")
24
+ return !1;
25
+ const e = r;
26
+ return typeof e.base == "string" && typeof e.date == "string" && typeof e.quote == "string" && typeof e.rate == "number" && Number.isFinite(e.rate) && e.rate > 0;
27
+ }
28
+ function U(r) {
29
+ return Array.isArray(r) && r.every(N);
30
+ }
31
+ async function R() {
32
+ const r = E(), { data: e, error: n } = await r.from("currencies").select(A).order("code", { ascending: !0 });
33
+ if (n)
34
+ throw new Error(n.message);
35
+ return {
36
+ supabase: r,
37
+ currencies: e || []
38
+ };
39
+ }
40
+ async function L(r) {
41
+ const e = a(r.newDefaultCurrencyCode), n = Number(r.previousBaseRate);
42
+ if (!Number.isFinite(n) || n <= 0)
43
+ throw new Error("Cannot rebase exchange rates without a valid previous base rate.");
44
+ const { supabase: f, currencies: c } = await R();
45
+ if (!c.find(
46
+ (o) => a(o.code) === e
47
+ ))
48
+ throw new Error(`Currency ${e} was not found for rebasing.`);
49
+ const i = (/* @__PURE__ */ new Date()).toISOString(), d = [], p = c.map((o) => {
50
+ const _ = C(o), u = a(o.code), g = u === e ? 1 : Number((o.exchange_rate / n).toFixed(10));
51
+ return d.push(u), {
52
+ ...o,
53
+ id: _,
54
+ exchange_rate: g,
55
+ auto_update_exchange_rate: u === e ? !1 : o.auto_update_exchange_rate,
56
+ exchange_rate_source: u === e ? "store-default" : o.exchange_rate_source || "rebased-default",
57
+ exchange_rate_updated_at: i,
58
+ updated_at: i
59
+ };
60
+ }), { error: s } = await f.from("currencies").upsert(p, {
61
+ onConflict: "id"
62
+ });
63
+ if (s)
64
+ throw new Error(s.message);
65
+ return {
66
+ rebasedAt: i,
67
+ newDefaultCurrencyCode: e,
68
+ updatedCurrencies: d
69
+ };
70
+ }
71
+ async function q() {
72
+ const { supabase: r, currencies: e } = await R();
73
+ if (!e.length)
74
+ throw new Error("No currencies are configured yet.");
75
+ const n = e.map(
76
+ (t) => S(t)
77
+ ), f = v(n), c = a(f.code), h = e.find(
78
+ (t) => a(t.code) === c
79
+ );
80
+ if (!h)
81
+ throw new Error(`Default currency ${c} could not be found for syncing.`);
82
+ const i = e.filter(
83
+ (t) => a(t.code) !== c && t.auto_update_exchange_rate !== !1
84
+ ), d = $(), p = D(d), s = (/* @__PURE__ */ new Date()).toISOString(), { error: o } = await r.from("currencies").upsert(
85
+ {
86
+ ...h,
87
+ id: C(h),
88
+ exchange_rate: 1,
89
+ auto_update_exchange_rate: !1,
90
+ exchange_rate_source: "store-default",
91
+ exchange_rate_updated_at: s,
92
+ updated_at: s
93
+ },
94
+ {
95
+ onConflict: "id"
96
+ }
97
+ );
98
+ if (o)
99
+ throw new Error(o.message);
100
+ if (!i.length)
101
+ return {
102
+ baseCurrencyCode: c,
103
+ fetchedAt: s,
104
+ provider: p,
105
+ providerUrl: d,
106
+ skippedCurrencies: [],
107
+ updatedCurrencies: []
108
+ };
109
+ const _ = new URL(`${d}/v2/rates`);
110
+ _.searchParams.set("base", c), _.searchParams.set(
111
+ "quotes",
112
+ [...new Set(i.map((t) => a(t.code)))].join(
113
+ ","
114
+ )
115
+ );
116
+ const u = await fetch(_.toString(), {
117
+ cache: "no-store",
118
+ headers: {
119
+ Accept: "application/json"
120
+ }
121
+ });
122
+ if (!u.ok) {
123
+ const t = await u.text();
124
+ throw new Error(
125
+ `FX provider request failed (${u.status}): ${t || "Unexpected response body."}`
126
+ );
127
+ }
128
+ const g = await u.json();
129
+ if (!U(g))
130
+ throw new Error("FX provider returned an unexpected response payload.");
131
+ const m = /* @__PURE__ */ new Map();
132
+ for (const t of g)
133
+ m.set(a(t.quote), t.rate);
134
+ const x = [], b = [], y = [];
135
+ for (const t of i) {
136
+ const l = a(t.code), w = m.get(l);
137
+ if (!w || !Number.isFinite(w) || w <= 0) {
138
+ b.push(l);
139
+ continue;
140
+ }
141
+ y.push({
142
+ ...t,
143
+ id: C(t),
144
+ exchange_rate: Number(w.toFixed(10)),
145
+ exchange_rate_source: p,
146
+ exchange_rate_updated_at: s,
147
+ updated_at: s
148
+ }), x.push(l);
149
+ }
150
+ if (y.length) {
151
+ const { error: t } = await r.from("currencies").upsert(y, {
152
+ onConflict: "id"
153
+ });
154
+ if (t)
155
+ throw new Error(t.message);
156
+ }
157
+ return {
158
+ baseCurrencyCode: c,
159
+ fetchedAt: s,
160
+ provider: p,
161
+ providerUrl: d,
162
+ skippedCurrencies: b,
163
+ updatedCurrencies: x
164
+ };
165
+ }
166
+ async function z(r) {
167
+ const e = a(r), n = E(), { error: f } = await n.rpc("clear_currency_price_overrides", {
168
+ target_currency: e
169
+ });
170
+ if (f)
171
+ throw new Error(f.message);
172
+ return {
173
+ currencyCode: e
174
+ };
175
+ }
176
+ export {
177
+ z as clearAutoSyncedCurrencyPriceOverrides,
178
+ L as rebaseStoreCurrencyExchangeRates,
179
+ q as syncStoreCurrencyRates
180
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("@nextblock-cms/db/server"),w=require("./customer.cjs.js");function a(e){const s=e?.trim();return s||null}function p(e){return e?w.normalizeCustomerAddress({company_name:e.company_name,recipient_name:e.recipient_name,line1:e.line1,line2:e.line2,city:e.city,state:e.state,postal_code:e.postal_code,country_code:e.country_code}):null}function _(e,s){return e?.find(t=>t.address_type===s&&t.is_default)??e?.find(t=>t.address_type===s)??null}async function g(e,s,t,o){const r=w.normalizeCustomerAddress(o),{data:i,error:l}=await e.from("user_addresses").select("*").eq("user_id",s).eq("address_type",t).order("is_default",{ascending:!1}).order("updated_at",{ascending:!1});if(l)throw new Error(l.message);const d=i?.[0]??null,c=(i??[]).slice(1).map(n=>n.id);if(!r){if(i?.length){const n=i.map(h=>h.id),{error:m}=await e.from("user_addresses").delete().in("id",n);if(m)throw new Error(m.message)}return}const f={user_id:s,address_type:t,is_default:!0,company_name:r.company_name??null,recipient_name:r.recipient_name??null,line1:r.line1??null,line2:r.line2??null,city:r.city??null,state:r.state??null,postal_code:r.postal_code??null,country_code:r.country_code??null,updated_at:new Date().toISOString()};if(d){const{error:n}=await e.from("user_addresses").update(f).eq("id",d.id);if(n)throw new Error(n.message)}else{const{error:n}=await e.from("user_addresses").insert(f);if(n)throw new Error(n.message)}if(c.length){const{error:n}=await e.from("user_addresses").delete().in("id",c);if(n)throw new Error(n.message)}}async function y(e,s){const t=s??u.createClient(),{data:o,error:r}=await t.from("user_addresses").select("*").eq("user_id",e).in("address_type",["billing","shipping"]).order("is_default",{ascending:!1}).order("updated_at",{ascending:!1});if(r)throw new Error(r.message);const i=p(_(o??[],"billing")),l=p(_(o??[],"shipping"));return{billingAddress:i,shippingAddress:l}}async function A(e){const s=e.client??u.createClient();await g(s,e.userId,"billing",e.billingAddress??null),await g(s,e.userId,"shipping",e.shippingAddress??null)}async function E(e){const s=e.client??u.createClient(),t=a(e.fullName),o=a(e.phone);if(!t&&!o)return;const{data:r,error:i}=await s.from("profiles").select("full_name, phone").eq("id",e.userId).maybeSingle();if(i)throw new Error(i.message);if(!r)return;const l=a(r.full_name)||t,d=a(r.phone)||o;if(a(r.full_name)===l&&a(r.phone)===d)return;const{error:c}=await s.from("profiles").update({full_name:l,phone:d,updated_at:new Date().toISOString()}).eq("id",e.userId);if(c)throw new Error(c.message)}exports.fillMissingUserProfileCheckoutDetails=E;exports.getDefaultUserAddresses=y;exports.upsertDefaultUserAddresses=A;
@@ -0,0 +1,116 @@
1
+ import { createClient as u } from "@nextblock-cms/db/server";
2
+ import { normalizeCustomerAddress as w } from "./customer.es.js";
3
+ function l(e) {
4
+ const n = e?.trim();
5
+ return n || null;
6
+ }
7
+ function p(e) {
8
+ return e ? w({
9
+ company_name: e.company_name,
10
+ recipient_name: e.recipient_name,
11
+ line1: e.line1,
12
+ line2: e.line2,
13
+ city: e.city,
14
+ state: e.state,
15
+ postal_code: e.postal_code,
16
+ country_code: e.country_code
17
+ }) : null;
18
+ }
19
+ function _(e, n) {
20
+ return e?.find(
21
+ (t) => t.address_type === n && t.is_default
22
+ ) ?? e?.find((t) => t.address_type === n) ?? null;
23
+ }
24
+ async function g(e, n, t, i) {
25
+ const r = w(i), { data: o, error: a } = await e.from("user_addresses").select("*").eq("user_id", n).eq("address_type", t).order("is_default", { ascending: !1 }).order("updated_at", { ascending: !1 });
26
+ if (a)
27
+ throw new Error(a.message);
28
+ const d = o?.[0] ?? null, c = (o ?? []).slice(1).map((s) => s.id);
29
+ if (!r) {
30
+ if (o?.length) {
31
+ const s = o.map((h) => h.id), { error: m } = await e.from("user_addresses").delete().in("id", s);
32
+ if (m)
33
+ throw new Error(m.message);
34
+ }
35
+ return;
36
+ }
37
+ const f = {
38
+ user_id: n,
39
+ address_type: t,
40
+ is_default: !0,
41
+ company_name: r.company_name ?? null,
42
+ recipient_name: r.recipient_name ?? null,
43
+ line1: r.line1 ?? null,
44
+ line2: r.line2 ?? null,
45
+ city: r.city ?? null,
46
+ state: r.state ?? null,
47
+ postal_code: r.postal_code ?? null,
48
+ country_code: r.country_code ?? null,
49
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
50
+ };
51
+ if (d) {
52
+ const { error: s } = await e.from("user_addresses").update(f).eq("id", d.id);
53
+ if (s)
54
+ throw new Error(s.message);
55
+ } else {
56
+ const { error: s } = await e.from("user_addresses").insert(f);
57
+ if (s)
58
+ throw new Error(s.message);
59
+ }
60
+ if (c.length) {
61
+ const { error: s } = await e.from("user_addresses").delete().in("id", c);
62
+ if (s)
63
+ throw new Error(s.message);
64
+ }
65
+ }
66
+ async function A(e, n) {
67
+ const t = n ?? u(), { data: i, error: r } = await t.from("user_addresses").select("*").eq("user_id", e).in("address_type", ["billing", "shipping"]).order("is_default", { ascending: !1 }).order("updated_at", { ascending: !1 });
68
+ if (r)
69
+ throw new Error(r.message);
70
+ const o = p(_(i ?? [], "billing")), a = p(
71
+ _(i ?? [], "shipping")
72
+ );
73
+ return {
74
+ billingAddress: o,
75
+ shippingAddress: a
76
+ };
77
+ }
78
+ async function D(e) {
79
+ const n = e.client ?? u();
80
+ await g(
81
+ n,
82
+ e.userId,
83
+ "billing",
84
+ e.billingAddress ?? null
85
+ ), await g(
86
+ n,
87
+ e.userId,
88
+ "shipping",
89
+ e.shippingAddress ?? null
90
+ );
91
+ }
92
+ async function q(e) {
93
+ const n = e.client ?? u(), t = l(e.fullName), i = l(e.phone);
94
+ if (!t && !i)
95
+ return;
96
+ const { data: r, error: o } = await n.from("profiles").select("full_name, phone").eq("id", e.userId).maybeSingle();
97
+ if (o)
98
+ throw new Error(o.message);
99
+ if (!r)
100
+ return;
101
+ const a = l(r.full_name) || t, d = l(r.phone) || i;
102
+ if (l(r.full_name) === a && l(r.phone) === d)
103
+ return;
104
+ const { error: c } = await n.from("profiles").update({
105
+ full_name: a,
106
+ phone: d,
107
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
108
+ }).eq("id", e.userId);
109
+ if (c)
110
+ throw new Error(c.message);
111
+ }
112
+ export {
113
+ q as fillMissingUserProfileCheckoutDetails,
114
+ A as getDefaultUserAddresses,
115
+ D as upsertDefaultUserAddresses
116
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@nextblock-cms/db/server"),d=require("./invoice-server.cjs.js");function o(e){return e??c.createClient()}async function i(e){const{data:{user:r},error:t}=await e.auth.getUser();if(t||!r)throw new Error("Unauthorized");return r}async function l(e){const r=o(e),t=await i(r),{data:n,error:a}=await r.from("orders").select("id, invoice_number, paid_at, created_at, currency, status, provider, subtotal, shipping_total, tax_total, total").eq("user_id",t.id).order("created_at",{ascending:!1});if(a)throw new Error(a.message);return n??[]}async function u(e,r){const t=o(r),n=await i(t),{data:a,error:s}=await t.from("orders").select("id, invoice_number, paid_at, created_at, currency, status, provider, subtotal, shipping_total, tax_total, total").eq("id",e).eq("user_id",n.id).maybeSingle();if(s)throw new Error(s.message);return a??null}async function g(e,r){const t=o(r),n=await u(e,t);if(!n)return null;const a=n.invoice_number?await d.getInvoicePresentationData(e,t):null;return{order:n,invoice:a}}exports.getCurrentCustomerOrder=u;exports.getCurrentCustomerOrderInvoice=g;exports.getCurrentCustomerOrders=l;
@@ -0,0 +1,45 @@
1
+ import { createClient as u } from "@nextblock-cms/db/server";
2
+ import { getInvoicePresentationData as c } from "./invoice-server.es.js";
3
+ function o(t) {
4
+ return t ?? u();
5
+ }
6
+ async function s(t) {
7
+ const {
8
+ data: { user: e },
9
+ error: r
10
+ } = await t.auth.getUser();
11
+ if (r || !e)
12
+ throw new Error("Unauthorized");
13
+ return e;
14
+ }
15
+ async function p(t) {
16
+ const e = o(t), r = await s(e), { data: a, error: n } = await e.from("orders").select(
17
+ "id, invoice_number, paid_at, created_at, currency, status, provider, subtotal, shipping_total, tax_total, total"
18
+ ).eq("user_id", r.id).order("created_at", { ascending: !1 });
19
+ if (n)
20
+ throw new Error(n.message);
21
+ return a ?? [];
22
+ }
23
+ async function d(t, e) {
24
+ const r = o(e), a = await s(r), { data: n, error: i } = await r.from("orders").select(
25
+ "id, invoice_number, paid_at, created_at, currency, status, provider, subtotal, shipping_total, tax_total, total"
26
+ ).eq("id", t).eq("user_id", a.id).maybeSingle();
27
+ if (i)
28
+ throw new Error(i.message);
29
+ return n ?? null;
30
+ }
31
+ async function f(t, e) {
32
+ const r = o(e), a = await d(t, r);
33
+ if (!a)
34
+ return null;
35
+ const n = a.invoice_number ? await c(t, r) : null;
36
+ return {
37
+ order: a,
38
+ invoice: n
39
+ };
40
+ }
41
+ export {
42
+ d as getCurrentCustomerOrder,
43
+ f as getCurrentCustomerOrderInvoice,
44
+ p as getCurrentCustomerOrders
45
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./countries.cjs.js"),c=require("./states.cjs.js"),m=()=>({company_name:"",recipient_name:"",line1:"",line2:"",city:"",state:"",postal_code:"",country_code:"CA"});function t(e){const n=e?.trim();return n||null}function o(e){if(!e)return null;const n={company_name:t(e.company_name),recipient_name:t(e.recipient_name),line1:t(e.line1),line2:t(e.line2),city:t(e.city),postal_code:t(e.postal_code),country_code:a.normalizeCountryCode(e.country_code)};return n.state=c.normalizeSubdivisionCode(n.country_code,t(e.state)),Object.values(n).some(Boolean)?n:null}function u(e){const n=o(e);return n?!!(n.recipient_name&&n.line1&&n.city&&n.postal_code&&n.country_code&&(!c.countryUsesStructuredStates(n.country_code)||n.state)):!1}function d(e){const n=o(e.billing),r=o(e.shipping),i=t(e.email)?.toLowerCase()??null,s=t(e.phone),l=t(e.name)??n?.recipient_name??r?.recipient_name??null;return{email:i,name:l,phone:s,billing:n,shipping:r}}function y(e,n){const r=o(e),i=o(n);return JSON.stringify(r)===JSON.stringify(i)}exports.addressesMatch=y;exports.emptyCustomerAddress=m;exports.isCustomerAddressComplete=u;exports.normalizeCustomerAddress=o;exports.normalizeOrderCustomerDetails=d;
@@ -1,4 +1,5 @@
1
- import { a as l, n as s, b as m } from "./states-DlHJezQ1.js";
1
+ import { normalizeCountryCode as a } from "./countries.es.js";
2
+ import { countryUsesStructuredStates as m, normalizeSubdivisionCode as s } from "./states.es.js";
2
3
  const y = () => ({
3
4
  company_name: "",
4
5
  recipient_name: "",
@@ -23,35 +24,35 @@ function i(n) {
23
24
  line2: o(n.line2),
24
25
  city: o(n.city),
25
26
  postal_code: o(n.postal_code),
26
- country_code: s(n.country_code)
27
+ country_code: a(n.country_code)
27
28
  };
28
- return e.state = m(
29
+ return e.state = s(
29
30
  e.country_code,
30
31
  o(n.state)
31
32
  ), Object.values(e).some(Boolean) ? e : null;
32
33
  }
33
- function p(n) {
34
+ function _(n) {
34
35
  const e = i(n);
35
- return e ? !!(e.recipient_name && e.line1 && e.city && e.postal_code && e.country_code && (!l(e.country_code) || e.state)) : !1;
36
+ return e ? !!(e.recipient_name && e.line1 && e.city && e.postal_code && e.country_code && (!m(e.country_code) || e.state)) : !1;
36
37
  }
37
- function _(n) {
38
- const e = i(n.billing), t = i(n.shipping), c = o(n.email)?.toLowerCase() ?? null, r = o(n.phone), a = o(n.name) ?? e?.recipient_name ?? t?.recipient_name ?? null;
38
+ function d(n) {
39
+ const e = i(n.billing), t = i(n.shipping), c = o(n.email)?.toLowerCase() ?? null, r = o(n.phone), l = o(n.name) ?? e?.recipient_name ?? t?.recipient_name ?? null;
39
40
  return {
40
41
  email: c,
41
- name: a,
42
+ name: l,
42
43
  phone: r,
43
44
  billing: e,
44
45
  shipping: t
45
46
  };
46
47
  }
47
- function d(n, e) {
48
+ function f(n, e) {
48
49
  const t = i(n), c = i(e);
49
50
  return JSON.stringify(t) === JSON.stringify(c);
50
51
  }
51
52
  export {
52
- d as a,
53
- _ as b,
54
- y as e,
55
- p as i,
56
- i as n
53
+ f as addressesMatch,
54
+ y as emptyCustomerAddress,
55
+ _ as isCustomerAddressComplete,
56
+ i as normalizeCustomerAddress,
57
+ d as normalizeOrderCustomerDetails
57
58
  };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("papaparse");function o(n,t){const e=u.unparse(n),a=new Blob([e],{type:"text/csv;charset=utf-8;"}),i=document.createElement("a");if(i.download!==void 0){const l=URL.createObjectURL(a);i.setAttribute("href",l),i.setAttribute("download",t),i.style.visibility="hidden",document.body.appendChild(i),i.click(),document.body.removeChild(i)}}function c(n){return n.map(t=>({"Order ID":t.id,Date:new Date(t.created_at).toLocaleDateString(),"Customer Name":t.customer?.full_name||t.customer_details?.name||"Guest","Customer Email":t.customer?.email||t.customer_details?.email||"N/A",Subtotal:(t.subtotal/100).toFixed(2),"Tax Amount":(t.tax_total/100).toFixed(2),"Shipping Amount":(t.shipping_total/100).toFixed(2),Total:(t.total/100).toFixed(2),Currency:t.currency.toUpperCase(),"Payment Status":t.status,"Fulfillment Status":t.status==="shipped"?"Shipped":t.status==="paid"?"Paid":t.status==="trial"?"Trial":"Pending","Payment Gateway":t.provider==="freemius"?"Freemius":"Stripe"}))}function m(n){return n.filter(t=>t.status==="paid").map(t=>{const e=t.customer_details?.shipping||t.customer_details?.billing,a=e?.country_code||"N/A",i=e?.state||"N/A",l=t.tax_details?.lines?.[0]?.rate?.display_name||"N/A",s=t.tax_details?.lines?.[0]?.rate?.percentage||0;return{Date:t.paid_at?new Date(t.paid_at).toLocaleDateString():new Date(t.created_at).toLocaleDateString(),"Order ID":t.id,Destination:`${i}, ${a}`,"Tax Rate Applied":`${s}% (${l})`,"Total Taxable Amount":(t.subtotal/100).toFixed(2),"Tax Collected":(t.tax_total/100).toFixed(2),Currency:t.currency.toUpperCase()}})}function p(n){const t={};return n.filter(e=>e.status==="paid").forEach(e=>{const a=e.currency.toUpperCase();t[a]||(t[a]={volume:0,subtotal:0,tax:0}),t[a].volume+=e.total,t[a].subtotal+=e.subtotal,t[a].tax+=e.tax_total}),Object.entries(t).map(([e,a])=>({Currency:e,"Total Transaction Volume":(a.volume/100).toFixed(2),"Total Subtotal":(a.subtotal/100).toFixed(2),"Total Tax Collected":(a.tax/100).toFixed(2)}))}exports.generateCSV=o;exports.mapGeneralSalesLedger=c;exports.mapMultiCurrencyRevenue=p;exports.mapTaxLiabilitySummary=m;
@@ -0,0 +1,56 @@
1
+ import u from "papaparse";
2
+ function c(n, t) {
3
+ const a = u.unparse(n), e = new Blob([a], { type: "text/csv;charset=utf-8;" }), i = document.createElement("a");
4
+ if (i.download !== void 0) {
5
+ const s = URL.createObjectURL(e);
6
+ i.setAttribute("href", s), i.setAttribute("download", t), i.style.visibility = "hidden", document.body.appendChild(i), i.click(), document.body.removeChild(i);
7
+ }
8
+ }
9
+ function m(n) {
10
+ return n.map((t) => ({
11
+ "Order ID": t.id,
12
+ Date: new Date(t.created_at).toLocaleDateString(),
13
+ "Customer Name": t.customer?.full_name || t.customer_details?.name || "Guest",
14
+ "Customer Email": t.customer?.email || t.customer_details?.email || "N/A",
15
+ Subtotal: (t.subtotal / 100).toFixed(2),
16
+ "Tax Amount": (t.tax_total / 100).toFixed(2),
17
+ "Shipping Amount": (t.shipping_total / 100).toFixed(2),
18
+ Total: (t.total / 100).toFixed(2),
19
+ Currency: t.currency.toUpperCase(),
20
+ "Payment Status": t.status,
21
+ "Fulfillment Status": t.status === "shipped" ? "Shipped" : t.status === "paid" ? "Paid" : t.status === "trial" ? "Trial" : "Pending",
22
+ "Payment Gateway": t.provider === "freemius" ? "Freemius" : "Stripe"
23
+ }));
24
+ }
25
+ function p(n) {
26
+ return n.filter((t) => t.status === "paid").map((t) => {
27
+ const a = t.customer_details?.shipping || t.customer_details?.billing, e = a?.country_code || "N/A", i = a?.state || "N/A", s = t.tax_details?.lines?.[0]?.rate?.display_name || "N/A", l = t.tax_details?.lines?.[0]?.rate?.percentage || 0;
28
+ return {
29
+ Date: t.paid_at ? new Date(t.paid_at).toLocaleDateString() : new Date(t.created_at).toLocaleDateString(),
30
+ "Order ID": t.id,
31
+ Destination: `${i}, ${e}`,
32
+ "Tax Rate Applied": `${l}% (${s})`,
33
+ "Total Taxable Amount": (t.subtotal / 100).toFixed(2),
34
+ "Tax Collected": (t.tax_total / 100).toFixed(2),
35
+ Currency: t.currency.toUpperCase()
36
+ };
37
+ });
38
+ }
39
+ function x(n) {
40
+ const t = {};
41
+ return n.filter((a) => a.status === "paid").forEach((a) => {
42
+ const e = a.currency.toUpperCase();
43
+ t[e] || (t[e] = { volume: 0, subtotal: 0, tax: 0 }), t[e].volume += a.total, t[e].subtotal += a.subtotal, t[e].tax += a.tax_total;
44
+ }), Object.entries(t).map(([a, e]) => ({
45
+ Currency: a,
46
+ "Total Transaction Volume": (e.volume / 100).toFixed(2),
47
+ "Total Subtotal": (e.subtotal / 100).toFixed(2),
48
+ "Total Tax Collected": (e.tax / 100).toFixed(2)
49
+ }));
50
+ }
51
+ export {
52
+ c as generateCSV,
53
+ m as mapGeneralSalesLedger,
54
+ x as mapMultiCurrencyRevenue,
55
+ p as mapTaxLiabilitySummary
56
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./providers/stripe.cjs.js"),t=require("./providers/freemius.cjs.js");function i(e){return e==="freemius"?new t.FreemiusProvider:new r.StripeProvider}exports.getPaymentProvider=i;
@@ -0,0 +1,8 @@
1
+ import { StripeProvider as r } from "./providers/stripe.es.js";
2
+ import { FreemiusProvider as t } from "./providers/freemius.es.js";
3
+ function m(e) {
4
+ return e === "freemius" ? new t() : new r();
5
+ }
6
+ export {
7
+ m as getPaymentProvider
8
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("@nextblock-cms/utils"),f=require("./providers/freemius.cjs.js");function y(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}function h(e){return e==="percent"?"percentage":"dollar"}function C(e){return f.resolveFreemiusCheckoutCredentials(e).apiKey||f.readFreemiusEnvValue("FREEMIUS_API_KEY")}async function l(e){const t=C(e.productId);if(!t)throw new Error(`Missing Freemius API bearer token for product ${e.productId}. Set FREEMIUS_API_KEY or FREEMIUS_CHECKOUT_PRODUCTS_JSON[${e.productId}].apiKey.`);const s=e.couponId?`/${e.couponId}`:"",o=await fetch(`https://api.freemius.com/v1/products/${e.productId}/coupons${s}.json`,{method:e.method,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",Accept:"application/json"},body:e.method==="DELETE"?void 0:JSON.stringify(e.body||{})}),n=await o.text(),r=n?JSON.parse(n):null;if(!o.ok)throw new Error(r?.message||r?.error?.message||`Freemius coupon request failed with ${o.status}`);return r}function g(e,t){return{code:e.code,discount:e.discount_type==="fixed"?w.minorUnitAmountToMajor(e.discount_amount,"USD"):e.discount_amount,discount_type:h(e.discount_type),plans:t.planIds.length>0?t.planIds.join(","):null,licenses:null,billing_cycles:null,start_date:y(e.starts_at),end_date:y(e.ends_at),redemptions_limit:e.redemption_limit??null,has_renewals_discount:!1,has_addons_discount:!1,is_one_per_user:!1,is_active:e.is_active,user_type:"all"}}async function E(e,t){if(t.provider_scope==="stripe")return[];const{data:s,error:o}=await e.from("coupon_products").select("product_id").eq("coupon_id",t.id);if(o)throw new Error(o.message);const n=(s||[]).map(c=>c.product_id);let r=e.from("products").select("id, freemius_product_id, freemius_plan_id").eq("payment_provider","freemius").not("freemius_product_id","is",null);n.length>0&&(r=r.in("id",n));const{data:u,error:i}=await r;if(i)throw new Error(i.message);const d=new Map;for(const c of u||[]){const a=String(c.freemius_product_id||"").trim();if(!a)continue;const p=d.get(a)??{freemiusProductId:a,productId:c.id,planIds:[]};n.length>0&&c.freemius_plan_id&&p.planIds.push(String(c.freemius_plan_id)),d.set(a,p)}return[...d.values()].map(c=>({...c,planIds:[...new Set(c.planIds)]}))}async function P(e,t){const{data:s}=await e.from("coupon_freemius_mappings").select("sync_status, sync_error").eq("coupon_id",t),o=s||[];if(o.length===0){await e.from("coupons").update({freemius_sync_status:"not_required",freemius_sync_error:null}).eq("id",t);return}const n=o.find(r=>r.sync_status==="failed");await e.from("coupons").update({freemius_sync_status:n?"failed":"synced",freemius_sync_error:n?.sync_error??null}).eq("id",t)}async function q(e){const{data:t,error:s}=await e.client.from("coupons").select("id, code, name, internal_note, provider_scope, discount_type, discount_amount, is_active, starts_at, ends_at, redemption_limit").eq("id",e.couponId).single();if(s||!t)return{success:!1,error:s?.message||"Coupon not found"};const o=t,n=await E(e.client,o);await e.client.from("coupons").update({freemius_sync_status:n.length>0?"pending":"not_required",freemius_sync_error:null}).eq("id",o.id);for(const r of n){const{data:u}=await e.client.from("coupon_freemius_mappings").select("id, freemius_coupon_id").eq("coupon_id",o.id).eq("freemius_product_id",r.freemiusProductId).maybeSingle(),i=g(o,r);try{const d=await l({productId:r.freemiusProductId,method:u?.freemius_coupon_id?"PUT":"POST",couponId:u?.freemius_coupon_id??null,body:i}),c=d?.coupon??d;await e.client.from("coupon_freemius_mappings").upsert({id:u?.id,coupon_id:o.id,product_id:r.productId,freemius_product_id:r.freemiusProductId,freemius_coupon_id:c?.id?String(c.id):u?.freemius_coupon_id??null,freemius_coupon_code:o.code,sync_status:"synced",sync_error:null,remote_payload:d,last_synced_at:new Date().toISOString()},{onConflict:"coupon_id,freemius_product_id"})}catch(d){await e.client.from("coupon_freemius_mappings").upsert({id:u?.id,coupon_id:o.id,product_id:r.productId,freemius_product_id:r.freemiusProductId,freemius_coupon_id:u?.freemius_coupon_id??null,freemius_coupon_code:o.code,sync_status:"failed",sync_error:d.message||"Freemius sync failed",last_synced_at:new Date().toISOString()},{onConflict:"coupon_id,freemius_product_id"})}}return await P(e.client,o.id),{success:!0,targetCount:n.length}}function F(e){const t=(e.sku||"").toUpperCase().replace(/[^A-Z0-9]/g,"");return t?`SALE${t}`.slice(0,32):`SALE${e.productId.replace(/[^A-Za-z0-9]/g,"").toUpperCase()}`.slice(0,32)}function v(e,t){if(typeof e!="number"||e<=0||typeof t!="number"||t<0||t>=e)return null;const s=Math.round((1-t/e)*100);return s<=0||s>100?null:s}async function T(e){const{data:t,error:s}=await e.client.from("products").select("id, sku, price, sale_price, sale_start_at, sale_end_at, payment_provider, freemius_product_id, freemius_plan_id").eq("id",e.productId).maybeSingle();if(s||!t)return{success:!1,error:s?.message||"Product not found"};const o=t,n=String(o.freemius_product_id||"").trim();if(o.payment_provider!=="freemius"||!n)return{success:!0,skipped:!0,reason:"not_a_freemius_product"};const r=v(o.price,o.sale_price),u=r!==null,{data:i}=await e.client.from("product_freemius_sale_coupons").select("id, freemius_coupon_id, freemius_coupon_code, discount_percent, is_active").eq("product_id",o.id).maybeSingle();if(!u&&!i?.freemius_coupon_id)return i?.id&&await e.client.from("product_freemius_sale_coupons").update({is_active:!1,updated_at:new Date().toISOString()}).eq("id",i.id),{success:!0,active:!1};const d=i?.freemius_coupon_code||F({sku:o.sku,productId:o.id}),c=o.freemius_plan_id?[String(o.freemius_plan_id)]:[],a=r??i?.discount_percent??1,p={id:o.id,code:d,name:`Scheduled sale ${o.sku||o.id}`,discount_type:"percent",discount_amount:a,is_active:u,starts_at:o.sale_start_at,ends_at:o.sale_end_at,redemption_limit:null},S={productId:o.id,planIds:c},I=g(p,S);try{const _=await l({productId:n,method:i?.freemius_coupon_id?"PUT":"POST",couponId:i?.freemius_coupon_id??null,body:I}),m=_?.coupon??_;return await e.client.from("product_freemius_sale_coupons").upsert({id:i?.id,product_id:o.id,freemius_product_id:n,freemius_plan_id:o.freemius_plan_id?String(o.freemius_plan_id):null,freemius_coupon_id:m?.id?String(m.id):i?.freemius_coupon_id??null,freemius_coupon_code:d,discount_percent:r,starts_at:o.sale_start_at,ends_at:o.sale_end_at,is_active:u,sync_status:"synced",sync_error:null,remote_payload:_,last_synced_at:new Date().toISOString()},{onConflict:"product_id"}),{success:!0,active:u,code:d}}catch(_){return await e.client.from("product_freemius_sale_coupons").upsert({id:i?.id,product_id:o.id,freemius_product_id:n,freemius_plan_id:o.freemius_plan_id?String(o.freemius_plan_id):null,freemius_coupon_id:i?.freemius_coupon_id??null,freemius_coupon_code:d,discount_percent:r,starts_at:o.sale_start_at,ends_at:o.sale_end_at,is_active:u,sync_status:"failed",sync_error:_.message||"Freemius sale coupon sync failed",last_synced_at:new Date().toISOString()},{onConflict:"product_id"}),{success:!1,error:_.message||"Freemius sale coupon sync failed"}}}async function b(e){const{data:t}=await e.client.from("coupon_freemius_mappings").select("id, freemius_product_id, freemius_coupon_id").eq("coupon_id",e.couponId).not("freemius_coupon_id","is",null);for(const s of t||[])try{await l({productId:s.freemius_product_id,couponId:s.freemius_coupon_id,method:"DELETE"}),await e.client.from("coupon_freemius_mappings").update({sync_status:"deleted",sync_error:null,updated_at:new Date().toISOString()}).eq("id",s.id)}catch(o){await e.client.from("coupon_freemius_mappings").update({sync_status:"failed",sync_error:o.message||"Freemius delete failed",updated_at:new Date().toISOString()}).eq("id",s.id)}}exports.deleteCouponFromFreemius=b;exports.syncCouponToFreemius=q;exports.syncProductSaleCouponToFreemius=T;