@nextblock-cms/ecom 0.20.3 → 0.21.1

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 (446) hide show
  1. package/README.md +43 -0
  2. package/_virtual/_rolldown/runtime.cjs +1 -0
  3. package/index.cjs +1 -0
  4. package/index.es.js +38 -146
  5. package/lib/CurrencyProvider.cjs +1 -0
  6. package/lib/CurrencyProvider.d.ts +1 -1
  7. package/lib/CurrencyProvider.es.js +85 -95
  8. package/lib/PaymentReadinessProvider.cjs +1 -0
  9. package/lib/PaymentReadinessProvider.d.ts +1 -1
  10. package/lib/PaymentReadinessProvider.es.js +24 -27
  11. package/lib/cart-store.cjs +1 -0
  12. package/lib/cart-store.es.js +109 -121
  13. package/lib/components/AccountNavigationMenu.cjs +1 -0
  14. package/lib/components/AccountNavigationMenu.d.ts +1 -1
  15. package/lib/components/AccountNavigationMenu.es.js +36 -50
  16. package/lib/components/AddToCartButton.cjs +1 -0
  17. package/lib/components/AddToCartButton.d.ts +1 -1
  18. package/lib/components/AddToCartButton.es.js +94 -89
  19. package/lib/components/Cart.cjs +1 -0
  20. package/lib/components/Cart.d.ts +1 -1
  21. package/lib/components/Cart.es.js +261 -180
  22. package/lib/components/CartDrawer.cjs +1 -0
  23. package/lib/components/CartDrawer.d.ts +1 -1
  24. package/lib/components/CartDrawer.es.js +218 -148
  25. package/lib/components/CartIcon.cjs +1 -0
  26. package/lib/components/CartIcon.d.ts +1 -1
  27. package/lib/components/CartIcon.es.js +33 -35
  28. package/lib/components/Checkout.cjs +1 -0
  29. package/lib/components/Checkout.d.ts +1 -1
  30. package/lib/components/Checkout.es.js +1092 -1108
  31. package/lib/components/CouponForm.cjs +1 -0
  32. package/lib/components/CouponForm.d.ts +1 -1
  33. package/lib/components/CouponForm.es.js +136 -148
  34. package/lib/components/CurrencySwitcher.cjs +1 -0
  35. package/lib/components/CurrencySwitcher.d.ts +1 -1
  36. package/lib/components/CurrencySwitcher.es.js +22 -18
  37. package/lib/components/CustomerProfileForm.cjs +1 -0
  38. package/lib/components/CustomerProfileForm.es.js +454 -313
  39. package/lib/components/FeaturedProduct.cjs +1 -0
  40. package/lib/components/FeaturedProduct.d.ts +1 -1
  41. package/lib/components/FeaturedProduct.es.js +98 -83
  42. package/lib/components/FreemiusLicensePanel.cjs +1 -0
  43. package/lib/components/FreemiusLicensePanel.d.ts +1 -1
  44. package/lib/components/FreemiusLicensePanel.es.js +70 -65
  45. package/lib/components/InvoiceDocument.cjs +1 -0
  46. package/lib/components/InvoiceDocument.es.js +256 -192
  47. package/lib/components/InvoiceViewerShell.cjs +29 -0
  48. package/lib/components/InvoiceViewerShell.d.ts +1 -1
  49. package/lib/components/InvoiceViewerShell.es.js +75 -106
  50. package/lib/components/ProductCard.cjs +1 -0
  51. package/lib/components/ProductCard.d.ts +1 -1
  52. package/lib/components/ProductCard.es.js +186 -171
  53. package/lib/components/ProductDetailsLayout.cjs +1 -0
  54. package/lib/components/ProductDetailsLayout.es.js +405 -404
  55. package/lib/components/ProductGallery.cjs +1 -0
  56. package/lib/components/ProductGallery.d.ts +1 -1
  57. package/lib/components/ProductGallery.es.js +51 -54
  58. package/lib/components/ProductGrid.cjs +1 -0
  59. package/lib/components/ProductGrid.d.ts +1 -1
  60. package/lib/components/ProductGrid.es.js +23 -25
  61. package/lib/components/ShippingEstimator.cjs +1 -0
  62. package/lib/components/ShippingEstimator.d.ts +1 -1
  63. package/lib/components/ShippingEstimator.es.js +158 -153
  64. package/lib/components/ShortDescription.cjs +1 -0
  65. package/lib/components/ShortDescription.es.js +17 -17
  66. package/lib/components/SimpleTiptapRenderer.cjs +1 -0
  67. package/lib/components/SimpleTiptapRenderer.es.js +238 -211
  68. package/lib/components/SubscriptionSelector.cjs +1 -0
  69. package/lib/components/SubscriptionSelector.es.js +159 -154
  70. package/lib/countries.cjs +1 -0
  71. package/lib/countries.es.js +232 -75
  72. package/lib/coupon-server.cjs +1 -0
  73. package/lib/coupon-server.es.js +180 -224
  74. package/lib/coupons.cjs +1 -0
  75. package/lib/coupons.es.js +12 -14
  76. package/lib/currency-constants.cjs +1 -0
  77. package/lib/currency-constants.es.js +4 -4
  78. package/lib/currency-rest-client.cjs +1 -0
  79. package/lib/currency-rest-client.es.js +15 -22
  80. package/lib/currency-store.cjs +1 -0
  81. package/lib/currency-store.es.js +20 -27
  82. package/lib/currency-sync.cjs +1 -0
  83. package/lib/currency-sync.es.js +124 -170
  84. package/lib/currency.cjs +1 -0
  85. package/lib/currency.es.js +242 -310
  86. package/lib/customer-addresses.cjs +1 -0
  87. package/lib/customer-addresses.es.js +80 -109
  88. package/lib/customer-orders.cjs +1 -0
  89. package/lib/customer-orders.es.js +31 -43
  90. package/lib/customer.cjs +1 -0
  91. package/lib/customer.es.js +43 -52
  92. package/lib/export-helpers.cjs +1 -0
  93. package/lib/export-helpers.es.js +53 -52
  94. package/lib/factory.cjs +1 -0
  95. package/lib/factory.es.js +10 -7
  96. package/lib/freemius-coupons.cjs +1 -0
  97. package/lib/freemius-coupons.es.js +245 -262
  98. package/lib/freemius-license-claim.cjs +1 -0
  99. package/lib/freemius-license-claim.es.js +87 -71
  100. package/lib/freemius-license.cjs +1 -0
  101. package/lib/freemius-license.es.js +32 -39
  102. package/lib/freemius-order-sync.cjs +1 -0
  103. package/lib/freemius-order-sync.es.js +226 -290
  104. package/lib/freemius-trial-provision.cjs +1 -0
  105. package/lib/freemius-trial-provision.es.js +136 -130
  106. package/lib/inventory-settings.cjs +1 -0
  107. package/lib/inventory-settings.es.js +69 -77
  108. package/lib/invoice-server.cjs +33 -0
  109. package/lib/invoice-server.es.js +94 -141
  110. package/lib/invoice-ui.cjs +1 -0
  111. package/lib/invoice-ui.es.js +50 -66
  112. package/lib/invoice.cjs +1 -0
  113. package/lib/invoice.es.js +85 -94
  114. package/lib/order-inventory.cjs +61 -0
  115. package/lib/order-inventory.es.js +67 -79
  116. package/lib/order-tax-details.cjs +1 -0
  117. package/lib/order-tax-details.es.js +142 -153
  118. package/lib/pages/cms/coupons/CouponEditorForm.cjs +1 -0
  119. package/lib/pages/cms/coupons/CouponEditorForm.d.ts +1 -1
  120. package/lib/pages/cms/coupons/CouponEditorForm.es.js +227 -185
  121. package/lib/pages/cms/coupons/CouponsPage.cjs +5 -0
  122. package/lib/pages/cms/coupons/CouponsPage.d.ts +1 -1
  123. package/lib/pages/cms/coupons/CouponsPage.es.js +235 -166
  124. package/lib/pages/cms/coupons/CreateCouponDialog.cjs +1 -0
  125. package/lib/pages/cms/coupons/CreateCouponDialog.d.ts +1 -1
  126. package/lib/pages/cms/coupons/CreateCouponDialog.es.js +35 -34
  127. package/lib/pages/cms/coupons/EditCouponPage.cjs +1 -0
  128. package/lib/pages/cms/coupons/EditCouponPage.d.ts +1 -1
  129. package/lib/pages/cms/coupons/EditCouponPage.es.js +47 -47
  130. package/lib/pages/cms/coupons/ProductScopePicker.cjs +1 -0
  131. package/lib/pages/cms/coupons/ProductScopePicker.d.ts +1 -1
  132. package/lib/pages/cms/coupons/ProductScopePicker.es.js +128 -117
  133. package/lib/pages/cms/coupons/actions.cjs +1 -0
  134. package/lib/pages/cms/coupons/actions.es.js +112 -115
  135. package/lib/pages/cms/coupons/index.cjs +1 -0
  136. package/lib/pages/cms/coupons/index.es.js +3 -0
  137. package/lib/pages/cms/coupons/product-options.cjs +1 -0
  138. package/lib/pages/cms/coupons/product-options.es.js +21 -23
  139. package/lib/pages/cms/orders/ExportReportsDialog.cjs +1 -0
  140. package/lib/pages/cms/orders/ExportReportsDialog.es.js +135 -129
  141. package/lib/pages/cms/orders/MarkPaidButton.d.ts +1 -1
  142. package/lib/pages/cms/orders/OrderDetailPage.cjs +1 -0
  143. package/lib/pages/cms/orders/OrderDetailPage.d.ts +1 -1
  144. package/lib/pages/cms/orders/OrderDetailPage.es.js +186 -134
  145. package/lib/pages/cms/orders/OrderPrintButton.cjs +1 -0
  146. package/lib/pages/cms/orders/OrderPrintButton.d.ts +1 -1
  147. package/lib/pages/cms/orders/OrderPrintButton.es.js +15 -21
  148. package/lib/pages/cms/orders/OrderStatusForm.cjs +1 -0
  149. package/lib/pages/cms/orders/OrderStatusForm.d.ts +1 -1
  150. package/lib/pages/cms/orders/OrderStatusForm.es.js +85 -69
  151. package/lib/pages/cms/orders/OrdersPage.cjs +1 -0
  152. package/lib/pages/cms/orders/OrdersPage.d.ts +1 -1
  153. package/lib/pages/cms/orders/OrdersPage.es.js +170 -102
  154. package/lib/pages/cms/orders/actions.cjs +7 -0
  155. package/lib/pages/cms/orders/actions.es.js +53 -69
  156. package/lib/pages/cms/orders/export-actions.cjs +1 -0
  157. package/lib/pages/cms/orders/export-actions.es.js +23 -26
  158. package/lib/pages/cms/orders/index.cjs +1 -0
  159. package/lib/pages/cms/orders/index.es.js +6 -0
  160. package/lib/pages/cms/orders/server-actions.cjs +1 -0
  161. package/lib/pages/cms/orders/server-actions.es.js +60 -51
  162. package/lib/pages/cms/payments/PaymentsClient.cjs +1 -0
  163. package/lib/pages/cms/payments/PaymentsClient.d.ts +1 -1
  164. package/lib/pages/cms/payments/PaymentsClient.es.js +316 -346
  165. package/lib/pages/cms/payments/PaymentsPage.cjs +1 -0
  166. package/lib/pages/cms/payments/PaymentsPage.d.ts +1 -1
  167. package/lib/pages/cms/payments/PaymentsPage.es.js +29 -32
  168. package/lib/pages/cms/payments/actions.cjs +1 -0
  169. package/lib/pages/cms/payments/actions.es.js +38 -48
  170. package/lib/pages/cms/payments/index.cjs +1 -0
  171. package/lib/pages/cms/payments/index.es.js +3 -0
  172. package/lib/pages/cms/payments/queries.cjs +1 -0
  173. package/lib/pages/cms/payments/queries.es.js +38 -48
  174. package/lib/pages/cms/products/ProductsPage.cjs +1 -0
  175. package/lib/pages/cms/products/ProductsPage.d.ts +1 -1
  176. package/lib/pages/cms/products/ProductsPage.es.js +63 -66
  177. package/lib/pages/cms/products/[id]/edit/EditProductPage.cjs +1 -0
  178. package/lib/pages/cms/products/[id]/edit/EditProductPage.d.ts +1 -1
  179. package/lib/pages/cms/products/[id]/edit/EditProductPage.es.js +139 -0
  180. package/lib/pages/cms/products/actions.cjs +44 -0
  181. package/lib/pages/cms/products/actions.es.js +121 -162
  182. package/lib/pages/cms/products/attributes/AttributeManagementPage.cjs +1 -0
  183. package/lib/pages/cms/products/attributes/AttributeManagementPage.d.ts +1 -1
  184. package/lib/pages/cms/products/attributes/AttributeManagementPage.es.js +55 -47
  185. package/lib/pages/cms/products/attributes/components/AttributeManager.cjs +1 -0
  186. package/lib/pages/cms/products/attributes/components/AttributeManager.d.ts +1 -1
  187. package/lib/pages/cms/products/attributes/components/AttributeManager.es.js +285 -290
  188. package/lib/pages/cms/products/categories/CategoryManagementPage.cjs +1 -0
  189. package/lib/pages/cms/products/categories/CategoryManagementPage.d.ts +1 -1
  190. package/lib/pages/cms/products/categories/CategoryManagementPage.es.js +43 -35
  191. package/lib/pages/cms/products/categories/components/CategoryManager.cjs +1 -0
  192. package/lib/pages/cms/products/categories/components/CategoryManager.es.js +315 -262
  193. package/lib/pages/cms/products/components/CopyProductFromLanguage.cjs +1 -0
  194. package/lib/pages/cms/products/components/CopyProductFromLanguage.es.js +115 -113
  195. package/lib/pages/cms/products/components/CurrencyPriceFields.cjs +1 -0
  196. package/lib/pages/cms/products/components/CurrencyPriceFields.d.ts +1 -1
  197. package/lib/pages/cms/products/components/CurrencyPriceFields.es.js +136 -145
  198. package/lib/pages/cms/products/components/DeleteProductButton.cjs +1 -0
  199. package/lib/pages/cms/products/components/DeleteProductButton.d.ts +1 -1
  200. package/lib/pages/cms/products/components/DeleteProductButton.es.js +35 -47
  201. package/lib/pages/cms/products/components/FreemiusPricingDashboard.cjs +1 -0
  202. package/lib/pages/cms/products/components/FreemiusPricingDashboard.d.ts +1 -1
  203. package/lib/pages/cms/products/components/FreemiusPricingDashboard.es.js +106 -84
  204. package/lib/pages/cms/products/components/ProductCategorySelector.cjs +1 -0
  205. package/lib/pages/cms/products/components/ProductCategorySelector.es.js +156 -159
  206. package/lib/pages/cms/products/components/ProductForm.cjs +1 -0
  207. package/lib/pages/cms/products/components/ProductForm.es.js +872 -693
  208. package/lib/pages/cms/products/components/ProductMediaManager.cjs +1 -0
  209. package/lib/pages/cms/products/components/ProductMediaManager.es.js +106 -103
  210. package/lib/pages/cms/products/components/ProductsBulkTable.cjs +1 -0
  211. package/lib/pages/cms/products/components/ProductsBulkTable.d.ts +1 -1
  212. package/lib/pages/cms/products/components/ProductsBulkTable.es.js +303 -294
  213. package/lib/pages/cms/products/components/SaleScheduleFields.cjs +1 -0
  214. package/lib/pages/cms/products/components/SaleScheduleFields.d.ts +1 -1
  215. package/lib/pages/cms/products/components/SaleScheduleFields.es.js +111 -134
  216. package/lib/pages/cms/products/components/SyncFreemiusButton.cjs +1 -0
  217. package/lib/pages/cms/products/components/SyncFreemiusButton.d.ts +1 -1
  218. package/lib/pages/cms/products/components/SyncFreemiusButton.es.js +29 -35
  219. package/lib/pages/cms/products/components/SyncFreemiusPricingButton.cjs +5 -0
  220. package/lib/pages/cms/products/components/SyncFreemiusPricingButton.d.ts +1 -1
  221. package/lib/pages/cms/products/components/SyncFreemiusPricingButton.es.js +36 -48
  222. package/lib/pages/cms/products/components/SyncProductForm.d.ts +1 -1
  223. package/lib/pages/cms/products/components/VariationsEditor.cjs +1 -0
  224. package/lib/pages/cms/products/components/VariationsEditor.d.ts +1 -1
  225. package/lib/pages/cms/products/components/VariationsEditor.es.js +396 -405
  226. package/lib/pages/cms/products/index.cjs +1 -0
  227. package/lib/pages/cms/products/index.es.js +8 -0
  228. package/lib/pages/cms/products/inventory/InventoryPage.cjs +1 -0
  229. package/lib/pages/cms/products/inventory/InventoryPage.d.ts +1 -1
  230. package/lib/pages/cms/products/inventory/InventoryPage.es.js +21 -15
  231. package/lib/pages/cms/products/inventory/InventoryTableClient.cjs +2 -0
  232. package/lib/pages/cms/products/inventory/InventoryTableClient.d.ts +1 -1
  233. package/lib/pages/cms/products/inventory/InventoryTableClient.es.js +230 -209
  234. package/lib/pages/cms/products/inventory/actions.cjs +3 -0
  235. package/lib/pages/cms/products/inventory/actions.es.js +83 -91
  236. package/lib/pages/cms/products/new/NewProductPage.cjs +1 -0
  237. package/lib/pages/cms/products/new/NewProductPage.d.ts +1 -1
  238. package/lib/pages/cms/products/new/NewProductPage.es.js +58 -74
  239. package/lib/pages/cms/products/product-price-sync.cjs +1 -0
  240. package/lib/pages/cms/products/product-price-sync.es.js +74 -89
  241. package/lib/pages/cms/products/server-actions.cjs +1 -0
  242. package/lib/pages/cms/products/server-actions.es.js +250 -233
  243. package/lib/pages/cms/shipping/ShippingPage.cjs +5 -0
  244. package/lib/pages/cms/shipping/ShippingPage.es.js +287 -209
  245. package/lib/pages/cms/shipping/components/RateForm.cjs +1 -0
  246. package/lib/pages/cms/shipping/components/RateForm.d.ts +1 -1
  247. package/lib/pages/cms/shipping/components/RateForm.es.js +439 -436
  248. package/lib/pages/cms/shipping/components/ZoneForm.cjs +1 -0
  249. package/lib/pages/cms/shipping/components/ZoneForm.es.js +245 -224
  250. package/lib/pages/cms/shipping/index.cjs +1 -0
  251. package/lib/pages/cms/shipping/index.es.js +3 -0
  252. package/lib/pages/cms/shipping/server-actions.cjs +1 -0
  253. package/lib/pages/cms/shipping/server-actions.es.js +131 -149
  254. package/lib/pages/cms/taxes/TaxesPage.cjs +1 -0
  255. package/lib/pages/cms/taxes/TaxesPage.d.ts +1 -1
  256. package/lib/pages/cms/taxes/TaxesPage.es.js +211 -169
  257. package/lib/pages/cms/taxes/actions.cjs +1 -0
  258. package/lib/pages/cms/taxes/actions.es.js +41 -53
  259. package/lib/pages/cms/taxes/components/TaxRateForm.cjs +1 -0
  260. package/lib/pages/cms/taxes/components/TaxRateForm.d.ts +1 -1
  261. package/lib/pages/cms/taxes/components/TaxRateForm.es.js +112 -99
  262. package/lib/pages/cms/taxes/index.cjs +1 -0
  263. package/lib/pages/cms/taxes/index.es.js +3 -0
  264. package/lib/payment-config.cjs +1 -0
  265. package/lib/payment-config.es.js +110 -126
  266. package/lib/product-actions.cjs +238 -0
  267. package/lib/product-actions.es.js +289 -544
  268. package/lib/product-context.cjs +1 -0
  269. package/lib/product-context.es.js +13 -15
  270. package/lib/product-schema.cjs +1 -0
  271. package/lib/product-schema.es.js +99 -134
  272. package/lib/providers/freemius.cjs +1 -0
  273. package/lib/providers/freemius.es.js +446 -530
  274. package/lib/providers/stripe.cjs +1 -0
  275. package/lib/providers/stripe.es.js +417 -477
  276. package/lib/server-actions/coupon-actions.cjs +1 -0
  277. package/lib/server-actions/coupon-actions.es.js +22 -22
  278. package/lib/server-actions/customer-actions.cjs +1 -0
  279. package/lib/server-actions/customer-actions.es.js +26 -28
  280. package/lib/server-actions/product-actions.cjs +1 -0
  281. package/lib/server-actions/product-actions.es.js +9 -15
  282. package/lib/server-actions/shipping-actions.cjs +1 -0
  283. package/lib/server-actions/shipping-actions.es.js +27 -24
  284. package/lib/server-actions/tax-actions.cjs +1 -0
  285. package/lib/server-actions/tax-actions.es.js +33 -39
  286. package/lib/shared-inventory.cjs +15 -0
  287. package/lib/shared-inventory.es.js +111 -160
  288. package/lib/shipping/resolver.cjs +7 -0
  289. package/lib/shipping/resolver.es.js +44 -61
  290. package/lib/shipping-rate-currency.cjs +1 -0
  291. package/lib/shipping-rate-currency.es.js +52 -67
  292. package/lib/states.cjs +1 -0
  293. package/lib/states.es.js +333 -154
  294. package/lib/stripe/checkout.cjs +1 -0
  295. package/lib/stripe/checkout.es.js +125 -181
  296. package/lib/stripe/client.cjs +1 -0
  297. package/lib/stripe/client.es.js +14 -19
  298. package/lib/stripe/order-sync.cjs +1 -0
  299. package/lib/stripe/order-sync.es.js +106 -126
  300. package/lib/stripe/webhooks.cjs +1 -0
  301. package/lib/stripe/webhooks.es.js +37 -31
  302. package/lib/tax-calculation.cjs +1 -0
  303. package/lib/tax-calculation.es.js +84 -98
  304. package/lib/trials.cjs +1 -0
  305. package/lib/trials.es.js +24 -30
  306. package/lib/types.cjs +1 -0
  307. package/lib/types.es.js +21 -27
  308. package/lib/use-cart.cjs +1 -0
  309. package/lib/use-cart.es.js +38 -40
  310. package/lib/use-price-formatter.cjs +1 -0
  311. package/lib/use-price-formatter.es.js +10 -11
  312. package/lib/variation-utils.cjs +1 -0
  313. package/lib/variation-utils.es.js +199 -261
  314. package/lib/zod-config.cjs +1 -0
  315. package/lib/zod-config.es.js +5 -6
  316. package/package.json +22 -21
  317. package/server.cjs +1 -0
  318. package/server.es.js +56 -211
  319. package/index.cjs.js +0 -1
  320. package/lib/CurrencyProvider.cjs.js +0 -1
  321. package/lib/PaymentReadinessProvider.cjs.js +0 -1
  322. package/lib/cart-store.cjs.js +0 -1
  323. package/lib/components/AccountNavigationMenu.cjs.js +0 -1
  324. package/lib/components/AddToCartButton.cjs.js +0 -1
  325. package/lib/components/Cart.cjs.js +0 -1
  326. package/lib/components/CartDrawer.cjs.js +0 -1
  327. package/lib/components/CartIcon.cjs.js +0 -1
  328. package/lib/components/Checkout.cjs.js +0 -1
  329. package/lib/components/CouponForm.cjs.js +0 -1
  330. package/lib/components/CurrencySwitcher.cjs.js +0 -1
  331. package/lib/components/CustomerProfileForm.cjs.js +0 -1
  332. package/lib/components/FeaturedProduct.cjs.js +0 -1
  333. package/lib/components/FreemiusLicensePanel.cjs.js +0 -1
  334. package/lib/components/InvoiceDocument.cjs.js +0 -1
  335. package/lib/components/InvoiceViewerShell.cjs.js +0 -29
  336. package/lib/components/ProductCard.cjs.js +0 -1
  337. package/lib/components/ProductDetailsLayout.cjs.js +0 -1
  338. package/lib/components/ProductGallery.cjs.js +0 -1
  339. package/lib/components/ProductGrid.cjs.js +0 -1
  340. package/lib/components/ShippingEstimator.cjs.js +0 -1
  341. package/lib/components/ShortDescription.cjs.js +0 -1
  342. package/lib/components/SimpleTiptapRenderer.cjs.js +0 -1
  343. package/lib/components/SubscriptionSelector.cjs.js +0 -1
  344. package/lib/countries.cjs.js +0 -1
  345. package/lib/coupon-server.cjs.js +0 -1
  346. package/lib/coupons.cjs.js +0 -1
  347. package/lib/currency-constants.cjs.js +0 -1
  348. package/lib/currency-rest-client.cjs.js +0 -1
  349. package/lib/currency-store.cjs.js +0 -1
  350. package/lib/currency-sync.cjs.js +0 -1
  351. package/lib/currency.cjs.js +0 -1
  352. package/lib/customer-addresses.cjs.js +0 -1
  353. package/lib/customer-orders.cjs.js +0 -1
  354. package/lib/customer.cjs.js +0 -1
  355. package/lib/export-helpers.cjs.js +0 -1
  356. package/lib/factory.cjs.js +0 -1
  357. package/lib/freemius-coupons.cjs.js +0 -1
  358. package/lib/freemius-license-claim.cjs.js +0 -1
  359. package/lib/freemius-license.cjs.js +0 -1
  360. package/lib/freemius-order-sync.cjs.js +0 -1
  361. package/lib/freemius-trial-provision.cjs.js +0 -1
  362. package/lib/inventory-settings.cjs.js +0 -1
  363. package/lib/invoice-server.cjs.js +0 -33
  364. package/lib/invoice-ui.cjs.js +0 -1
  365. package/lib/invoice.cjs.js +0 -1
  366. package/lib/order-inventory.cjs.js +0 -61
  367. package/lib/order-tax-details.cjs.js +0 -1
  368. package/lib/pages/cms/coupons/CouponEditorForm.cjs.js +0 -1
  369. package/lib/pages/cms/coupons/CouponsPage.cjs.js +0 -5
  370. package/lib/pages/cms/coupons/CreateCouponDialog.cjs.js +0 -1
  371. package/lib/pages/cms/coupons/EditCouponPage.cjs.js +0 -1
  372. package/lib/pages/cms/coupons/ProductScopePicker.cjs.js +0 -1
  373. package/lib/pages/cms/coupons/actions.cjs.js +0 -1
  374. package/lib/pages/cms/coupons/product-options.cjs.js +0 -1
  375. package/lib/pages/cms/orders/ExportReportsDialog.cjs.js +0 -1
  376. package/lib/pages/cms/orders/OrderDetailPage.cjs.js +0 -1
  377. package/lib/pages/cms/orders/OrderPrintButton.cjs.js +0 -1
  378. package/lib/pages/cms/orders/OrderStatusForm.cjs.js +0 -1
  379. package/lib/pages/cms/orders/OrdersPage.cjs.js +0 -1
  380. package/lib/pages/cms/orders/actions.cjs.js +0 -7
  381. package/lib/pages/cms/orders/export-actions.cjs.js +0 -1
  382. package/lib/pages/cms/orders/server-actions.cjs.js +0 -1
  383. package/lib/pages/cms/payments/PaymentsClient.cjs.js +0 -1
  384. package/lib/pages/cms/payments/PaymentsPage.cjs.js +0 -1
  385. package/lib/pages/cms/payments/actions.cjs.js +0 -1
  386. package/lib/pages/cms/payments/queries.cjs.js +0 -1
  387. package/lib/pages/cms/products/ProductsPage.cjs.js +0 -1
  388. package/lib/pages/cms/products/_id_/edit/EditProductPage.cjs.js +0 -1
  389. package/lib/pages/cms/products/_id_/edit/EditProductPage.es.js +0 -156
  390. package/lib/pages/cms/products/actions.cjs.js +0 -44
  391. package/lib/pages/cms/products/attributes/AttributeManagementPage.cjs.js +0 -1
  392. package/lib/pages/cms/products/attributes/components/AttributeManager.cjs.js +0 -1
  393. package/lib/pages/cms/products/categories/CategoryManagementPage.cjs.js +0 -1
  394. package/lib/pages/cms/products/categories/components/CategoryManager.cjs.js +0 -1
  395. package/lib/pages/cms/products/components/CopyProductFromLanguage.cjs.js +0 -1
  396. package/lib/pages/cms/products/components/CurrencyPriceFields.cjs.js +0 -1
  397. package/lib/pages/cms/products/components/DeleteProductButton.cjs.js +0 -1
  398. package/lib/pages/cms/products/components/FreemiusPricingDashboard.cjs.js +0 -1
  399. package/lib/pages/cms/products/components/ProductCategorySelector.cjs.js +0 -1
  400. package/lib/pages/cms/products/components/ProductForm.cjs.js +0 -1
  401. package/lib/pages/cms/products/components/ProductMediaManager.cjs.js +0 -1
  402. package/lib/pages/cms/products/components/ProductsBulkTable.cjs.js +0 -1
  403. package/lib/pages/cms/products/components/SaleScheduleFields.cjs.js +0 -1
  404. package/lib/pages/cms/products/components/SyncFreemiusButton.cjs.js +0 -1
  405. package/lib/pages/cms/products/components/SyncFreemiusPricingButton.cjs.js +0 -5
  406. package/lib/pages/cms/products/components/VariationsEditor.cjs.js +0 -1
  407. package/lib/pages/cms/products/inventory/InventoryPage.cjs.js +0 -1
  408. package/lib/pages/cms/products/inventory/InventoryTableClient.cjs.js +0 -2
  409. package/lib/pages/cms/products/inventory/actions.cjs.js +0 -3
  410. package/lib/pages/cms/products/new/NewProductPage.cjs.js +0 -1
  411. package/lib/pages/cms/products/product-price-sync.cjs.js +0 -1
  412. package/lib/pages/cms/products/server-actions.cjs.js +0 -1
  413. package/lib/pages/cms/shipping/ShippingPage.cjs.js +0 -5
  414. package/lib/pages/cms/shipping/components/RateForm.cjs.js +0 -1
  415. package/lib/pages/cms/shipping/components/ZoneForm.cjs.js +0 -1
  416. package/lib/pages/cms/shipping/server-actions.cjs.js +0 -1
  417. package/lib/pages/cms/taxes/TaxesPage.cjs.js +0 -1
  418. package/lib/pages/cms/taxes/actions.cjs.js +0 -1
  419. package/lib/pages/cms/taxes/components/TaxRateForm.cjs.js +0 -1
  420. package/lib/payment-config.cjs.js +0 -1
  421. package/lib/product-actions.cjs.js +0 -238
  422. package/lib/product-context.cjs.js +0 -1
  423. package/lib/product-schema.cjs.js +0 -1
  424. package/lib/providers/freemius.cjs.js +0 -5
  425. package/lib/providers/stripe.cjs.js +0 -1
  426. package/lib/server-actions/coupon-actions.cjs.js +0 -1
  427. package/lib/server-actions/customer-actions.cjs.js +0 -1
  428. package/lib/server-actions/product-actions.cjs.js +0 -1
  429. package/lib/server-actions/shipping-actions.cjs.js +0 -1
  430. package/lib/server-actions/tax-actions.cjs.js +0 -1
  431. package/lib/shared-inventory.cjs.js +0 -15
  432. package/lib/shipping/resolver.cjs.js +0 -7
  433. package/lib/shipping-rate-currency.cjs.js +0 -1
  434. package/lib/states.cjs.js +0 -1
  435. package/lib/stripe/checkout.cjs.js +0 -1
  436. package/lib/stripe/client.cjs.js +0 -1
  437. package/lib/stripe/order-sync.cjs.js +0 -1
  438. package/lib/stripe/webhooks.cjs.js +0 -1
  439. package/lib/tax-calculation.cjs.js +0 -1
  440. package/lib/trials.cjs.js +0 -1
  441. package/lib/types.cjs.js +0 -1
  442. package/lib/use-cart.cjs.js +0 -1
  443. package/lib/use-price-formatter.cjs.js +0 -1
  444. package/lib/variation-utils.cjs.js +0 -1
  445. package/lib/zod-config.cjs.js +0 -1
  446. package/server.cjs.js +0 -1
@@ -1,5 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),u=require("react"),l=require("next/navigation"),d=require("@nextblock-cms/ui"),f=require("lucide-react"),r=require("sonner"),g=require("../actions.cjs.js");function y({productId:t,hasOpenDraft:c=!1}){const o=l.useRouter(),[n,i]=u.useState(!1),a=async()=>{if(!t){r.toast.error("Product ID is missing");return}if(!(c&&!window.confirm(`You have unpublished draft changes for this product.
2
-
3
- Syncing updates the live pricing now, but publishing your draft afterward will overwrite it with the draft’s older values. Publish or discard your draft first to keep the synced prices.
4
-
5
- Sync anyway?`))){i(!0);try{const e=await g.triggerSingleProductSync(t);e.error?r.toast.error(e.error):(r.toast.success("Pricing sync complete!"),o.refresh())}catch(e){r.toast.error(e.message||"An unexpected error occurred during sync")}finally{i(!1)}}};return s.jsxs(d.Button,{variant:"outline",onClick:a,disabled:n,className:"gap-2",children:[s.jsx(f.RefreshCw,{className:`w-4 h-4 ${n?"animate-spin":""}`}),n?"Syncing...":"Sync Plans & Pricing from Freemius"]})}exports.SyncFreemiusPricingButton=y;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),R=require("next/link"),f=require("react"),p=require("@nextblock-cms/ui"),g=require("../../../../variation-utils.cjs.js"),Q=require("./CurrencyPriceFields.cjs.js"),W=require("./SaleScheduleFields.cjs.js"),y=require("../../../../currency.cjs.js"),j=require("../product-price-sync.cjs.js"),k=require("@nextblock-cms/utils"),E=process.env.NEXT_PUBLIC_R2_BASE_URL||"",D=process.env.NEXT_PUBLIC_SUPABASE_URL||"",H=c=>c.startsWith("http")?c:E?`${E.replace(/\/+$/,"")}/${c.replace(/^\/+/,"")}`:D?`${D.replace(/\/+$/,"")}/storage/v1/object/public/media/${c.replace(/^\/+/,"")}`:c;function L(c,a="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:a}).format(c)}function J(c){return Object.entries(c).filter(([,a])=>a.length>0).map(([a,b])=>({attribute_id:a,term_ids:b}))}function Y({globalAttributes:c,currentLanguageCode:a,baseSku:b,basePrice:$,basePrices:w,baseSalePrice:T,baseSalePrices:B,currencies:o,availableVariantImages:N=[],initialVariationAttributes:C,initialVariants:V,onChange:q}){const[_,z]=f.useState(()=>C&&C.length>0?C.reduce((e,r)=>(e[r.attribute_id]=r.term_ids,e),{}):g.extractSelectedTermsByAttribute(V||[])),[h,x]=f.useState(j.sanitizeVariantDraftsForStoreManagedCurrencies(V||[],o)),S=f.useMemo(()=>c.map(e=>({attribute_id:e.id,attribute_name:g.resolveAttributeName(e,a),terms:e.terms.filter(r=>(_[e.id]||[]).includes(r.id)).map(r=>({...r,value:g.resolveTermValue(r,a)}))})).filter(e=>e.terms.length>0),[a,c,_]);f.useEffect(()=>{if(S.length===0){x([]);return}x(e=>j.sanitizeVariantDraftsForStoreManagedCurrencies(g.generateVariantDrafts({baseSku:b,basePrice:$,basePrices:y.normalizePriceMap(w),baseSalePrice:T,baseSalePrices:y.normalizeSalePriceMap(B),selectedAttributes:S,previousVariants:e}),o))},[$,w,T,B,b,o,S]),f.useEffect(()=>{q({variationAttributes:J(_),variants:h})},[q,_,h]);const I=h.reduce((e,r)=>e+(r.stock_quantity||0),0),P=o.find(e=>e.is_default)??o[0],U=f.useMemo(()=>j.getStoreManagedPriceCurrencyCodes(o),[o]),K=(e,r)=>{z(t=>{const n=new Set(t[e]||[]);return n.has(r)?n.delete(r):n.add(r),{...t,[e]:[...n]}})},M=(e,r,t)=>{x(n=>n.map(i=>{if(i.combination_key!==e)return i;if(r==="sku")return{...i,sku:t};if(r==="upc")return{...i,upc:t};if(r==="sale_price"&&t==="")return{...i,sale_price:null};if(r==="prices"||r==="sale_prices")return i;const d=t===""?0:Number(t);return{...i,[r]:Number.isFinite(d)?d:0}}))},O=(e,r,t)=>{x(n=>n.map(i=>i.combination_key===e?{...i,[r]:t}:i))},F=(e,r,t,n)=>{const i=o.find(d=>d.is_default)??o[0];x(d=>d.map(m=>{if(m.combination_key!==e)return m;const u={...t==="prices"?m.prices:m.sale_prices,[r]:n};return{...m,[t]:u,...r===i?.code?t==="prices"?{price:n??0}:{sale_price:n}:{}}}))},X=e=>{const r=o.find(n=>n.is_default)??o[0],t=new Set(U);r&&x(n=>n.map(i=>{if(i.combination_key!==e)return i;const d=o.reduce((u,l)=>{if(l.code!==r.code&&t.has(l.code))return u;const A=y.convertMinorUnitAmount({amount:k.majorUnitAmountToMinor(i.price,r.code),fromCurrencyCode:r.code,toCurrencyCode:l.code,currencies:o,applyRounding:!0});return u[l.code]=k.minorUnitAmountToMajor(A,l.code),u},{}),m=o.reduce((u,l)=>{if(l.code!==r.code&&t.has(l.code))return u;if(typeof i.sale_price!="number")return u[l.code]=null,u;const A=y.convertMinorUnitAmount({amount:k.majorUnitAmountToMinor(i.sale_price,r.code),fromCurrencyCode:r.code,toCurrencyCode:l.code,currencies:o,applyRounding:!0});return u[l.code]=k.minorUnitAmountToMajor(A,l.code),u},{});return{...i,prices:d,sale_prices:m}}))},G=(e,r)=>{const t=N.find(d=>d.media_id===r);if(!t)return;const n=t.file_path,i=H(n);x(d=>d.map(m=>m.combination_key===e?{...m,main_media_id:t.media_id,main_image_url:i}:m))},v=e=>{x(r=>r.map(t=>t.combination_key===e?{...t,main_media_id:null,main_image_url:null}:t))};return c.length===0?s.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:["No global attributes have been created yet. Create them first in"," ",s.jsx(R,{href:"/cms/products/attributes",className:"font-medium text-primary underline-offset-4 hover:underline",children:"Attribute Management"}),"."]}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xs uppercase font-bold text-muted-foreground tracking-wider leading-none",children:"Attributes"}),s.jsxs(p.Badge,{variant:"outline",className:"text-[10px] px-1.5 h-4",children:[h.length," variants"]}),s.jsxs(p.Badge,{variant:"secondary",className:"text-[10px] px-1.5 h-4",children:["Stock: ",I]})]}),s.jsx(p.Button,{asChild:!0,variant:"outline",size:"sm",className:"h-7 text-xs px-3",children:s.jsx(R,{href:"/cms/products/attributes",children:"Manage"})})]}),s.jsx("div",{className:"grid gap-2 lg:grid-cols-2",children:c.map(e=>{const r=_[e.id]||[];return s.jsxs("div",{className:"flex items-center gap-3 rounded border p-2.5",children:[s.jsxs("div",{className:"shrink-0 w-[100px]",children:[s.jsx("span",{className:"text-sm font-bold block leading-tight",children:g.resolveAttributeName(e,a)}),s.jsxs("span",{className:"text-[10px] text-muted-foreground leading-none",children:[r.length," selected"]})]}),s.jsx("div",{className:"flex flex-wrap gap-1.5 flex-1",children:e.terms.map(t=>{const n=r.includes(t.id);return s.jsx("button",{type:"button",onClick:()=>K(e.id,t.id),className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${n?"border-primary bg-primary/10 text-primary":"border-border bg-background text-foreground hover:border-primary/40"}`,children:g.resolveTermValue(t,a)},t.id)})})]},e.id)})})]}),h.length===0?s.jsx("div",{className:"rounded border border-dashed p-3 text-xs text-muted-foreground text-center",children:"Select terms above to generate variations."}):s.jsx("div",{className:"space-y-2",children:h.map(e=>{const r=j.resolveEditorCurrencyPriceMaps({currencies:o,prices:e.prices||{},salePrices:e.sale_prices||{},fallbackPrice:e.price,fallbackSalePrice:e.sale_price});return s.jsxs("div",{className:"rounded border p-3 space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-bold",children:e.label}),s.jsx("span",{className:"text-xs text-muted-foreground",children:e.selected_options.map(t=>`${t.attribute_name}: ${t.term_value}`).join(" · ")})]}),s.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[s.jsxs("span",{children:["Reg: ",L(e.price,P?.code||"USD")]}),s.jsxs("span",{children:["Sale:"," ",e.sale_price!==null&&e.sale_price!==void 0?L(e.sale_price,P?.code||"USD"):"—"]})]})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(p.Label,{htmlFor:`variant-sku-${e.combination_key}`,className:"text-xs uppercase font-bold text-muted-foreground tracking-wider shrink-0",children:"SKU"}),s.jsx(p.Input,{id:`variant-sku-${e.combination_key}`,value:e.sku,onChange:t=>M(e.combination_key,"sku",t.target.value),placeholder:"SKU",className:"h-8 text-sm font-mono"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(p.Label,{htmlFor:`variant-upc-${e.combination_key}`,className:"text-xs uppercase font-bold text-muted-foreground tracking-wider shrink-0",children:"UPC"}),s.jsx(p.Input,{id:`variant-upc-${e.combination_key}`,value:e.upc??"",onChange:t=>M(e.combination_key,"upc",t.target.value),placeholder:"—",className:"h-8 text-sm font-mono"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(p.Label,{htmlFor:`variant-stock-${e.combination_key}`,className:"text-xs uppercase font-bold text-muted-foreground tracking-wider shrink-0",children:"Qty"}),s.jsx(p.Input,{id:`variant-stock-${e.combination_key}`,type:"number",min:"0",value:e.stock_quantity,onChange:t=>M(e.combination_key,"stock_quantity",t.target.value),className:"h-8 text-sm font-mono w-20"})]})]}),s.jsx(Q.CurrencyPriceFields,{idPrefix:`variant-${e.combination_key}`,currencies:o,prices:r.prices,salePrices:r.salePrices,managedCurrencyCodes:U,onPriceChange:(t,n)=>F(e.combination_key,t,"prices",n),onSalePriceChange:(t,n)=>F(e.combination_key,t,"sale_prices",n),onAutoFill:()=>X(e.combination_key),helperText:U.length>0?`Store-managed currencies derive from ${P?.code||"the base currency"}.`:void 0,trailing:s.jsx(W.SaleScheduleFields,{idPrefix:`variant-${e.combination_key}`,startAt:e.sale_start_at,endAt:e.sale_end_at,onChange:(t,n)=>O(e.combination_key,t,n),bare:!0})}),s.jsxs("div",{className:"flex items-center gap-3 pt-1.5 border-t border-muted/30",children:[e.main_image_url&&s.jsx("div",{className:"h-9 w-9 overflow-hidden rounded border bg-background shrink-0",children:s.jsx("img",{src:e.main_image_url,alt:`${e.label} image`,className:"h-full w-full object-cover"})}),s.jsx("span",{className:"text-xs uppercase font-bold text-muted-foreground tracking-wider shrink-0",children:"Image"}),N.length>0?s.jsxs("select",{className:"flex h-8 rounded-md border border-input bg-background px-2 py-1 text-sm min-w-[180px]",value:e.main_media_id??"",onChange:t=>{if(!t.target.value){v(e.combination_key);return}G(e.combination_key,t.target.value)},children:[s.jsx("option",{value:"",children:"Use parent image"}),N.map((t,n)=>s.jsx("option",{value:t.media_id,children:t.alt?.trim()||`Gallery image ${n+1}`},t.media_id))]}):s.jsx("span",{className:"text-xs text-muted-foreground",children:"Add gallery images first."}),e.main_media_id&&s.jsx(p.Button,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2 text-muted-foreground hover:text-destructive",onClick:()=>v(e.combination_key),children:"Remove"})]})]},e.combination_key)})})]})}exports.VariationsEditor=Y;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),n=require("../../../../shared-inventory.cjs.js"),s=require("./InventoryTableClient.cjs.js");async function a(){const t=await n.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(s.InventoryTableClient,{initialItems:t})]})}exports.InventoryPage=a;
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),d=require("react"),t=require("@nextblock-cms/ui"),y=require("lucide-react"),j=require("sonner"),S=require("./actions.cjs.js");function R(o){const i=String(o??"");return/[",\n]/.test(i)?`"${i.replace(/"/g,'""')}"`:i}function K(o){const i=["sku","stock","usage_type","product_titles","languages","statuses","parent_product_skus"],b=o.map(c=>[c.sku,c.stock,c.usageType,c.productTitles.join("|"),c.languages.join("|"),c.statuses.join("|"),c.parentProductSkus.join("|")]);return[i,...b].map(c=>c.map(p=>R(p)).join(",")).join(`
2
- `)}function B(o){return o.usageType==="mixed"?"Shared SKU":o.usageType==="variant"?`Variant SKU ${o.sku}`:"Simple Product"}function L(o){return o.usageType==="variant"?"secondary":"outline"}function P({initialItems:o}){const[i,b]=d.useState(o),[c,p]=d.useState(()=>o.reduce((s,n)=>(s[n.key]=String(n.stock),s),{})),[k,T]=d.useState(""),[h,f]=d.useTransition(),[w,x]=d.useState(null),v=d.useRef(null),m=d.useMemo(()=>{const s=k.trim().toLowerCase();return s?i.filter(n=>n.sku.toLowerCase().includes(s)||n.productTitles.join(" ").toLowerCase().includes(s)||n.parentProductSkus.join(" ").toLowerCase().includes(s)||n.languages.join(" ").toLowerCase().includes(s)):i},[i,k]),C=()=>{const s=K(i),n=new Blob([s],{type:"text/csv;charset=utf-8;"}),r=URL.createObjectURL(n),l=document.createElement("a");l.href=r,l.download="inventory-export.csv",l.click(),URL.revokeObjectURL(r)},N=s=>{const n=c[s.key]??String(s.stock),r=Number.parseInt(n,10);if(!Number.isFinite(r)||r<0){j.toast.error("Stock must be a non-negative whole number.");return}x(s.key),f(async()=>{const l=await S.updateInventoryQuantityAction({sku:s.sku,stock:r});if(!l.success){j.toast.error(l.error||"Failed to update inventory."),x(null);return}const u=typeof l.stock=="number"?l.stock:r;b(a=>a.map(g=>g.key===s.key?{...g,stock:u}:g)),p(a=>({...a,[s.key]:String(u)})),x(null),j.toast.success(`Inventory updated for ${s.sku}.`)})},I=()=>{v.current?.click()},U=async s=>{const n=await s.text();x("import"),f(async()=>{const r=await S.importInventoryCsvAction(n);if(!r.success){j.toast.error(r.error||"Failed to import inventory CSV."),x(null);return}const l=r.items||[];b(l),p(l.reduce((u,a)=>(u[a.key]=String(a.stock),u),{})),x(null),j.toast.success(`Imported ${r.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(y.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{value:k,onChange:s=>T(s.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:v,type:"file",accept:".csv,text/csv",className:"hidden",onChange:s=>{const n=s.target.files?.[0];n&&U(n),s.currentTarget.value=""}}),e.jsxs(t.Button,{type:"button",variant:"outline",onClick:I,disabled:h,children:[e.jsx(y.Upload,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(t.Button,{type:"button",variant:"outline",onClick:C,disabled:h,children:[e.jsx(y.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(t.Table,{children:[e.jsx(t.TableHeader,{children:e.jsxs(t.TableRow,{children:[e.jsx(t.TableHead,{children:"SKU"}),e.jsx(t.TableHead,{children:"Usage"}),e.jsx(t.TableHead,{children:"Linked Products"}),e.jsx(t.TableHead,{children:"Languages"}),e.jsx(t.TableHead,{children:"Status"}),e.jsx(t.TableHead,{className:"w-[160px]",children:"Quantity"}),e.jsx(t.TableHead,{className:"text-right",children:"Actions"})]})}),e.jsx(t.TableBody,{children:m.length>0?m.map(s=>{const n=c[s.key]??String(s.stock),r=Number.parseInt(n,10),l=Number.isFinite(r)&&r!==s.stock,u=w===s.key;return e.jsxs(t.TableRow,{children:[e.jsx(t.TableCell,{className:"font-mono text-sm",children:s.sku}),e.jsx(t.TableCell,{children:e.jsx(t.Badge,{variant:L(s),children:B(s)})}),e.jsx(t.TableCell,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:s.productTitles.join(", ")}),s.usageType!=="product"?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Parent SKU",s.parentProductSkus.length>1?"s":"",":"," ",e.jsx("span",{className:"font-mono",children:s.parentProductSkus.join(", ")})]}):null]})}),e.jsx(t.TableCell,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:s.languages.map(a=>e.jsx(t.Badge,{variant:"outline",children:a},`${s.key}:${a}`))})}),e.jsx(t.TableCell,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:s.statuses.map(a=>e.jsx(t.Badge,{variant:"outline",children:a},`${s.key}:${a}`))})}),e.jsx(t.TableCell,{children:e.jsx(t.Input,{type:"number",min:0,step:1,value:n,disabled:h,onChange:a=>p(g=>({...g,[s.key]:a.target.value})),className:"w-28"})}),e.jsx(t.TableCell,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs(t.Button,{type:"button",size:"sm",variant:"ghost",disabled:!l||h,onClick:()=>p(a=>({...a,[s.key]:String(s.stock)})),children:[e.jsx(y.RotateCcw,{className:"mr-2 h-4 w-4"}),"Reset"]}),e.jsxs(t.Button,{type:"button",size:"sm",disabled:!l||h,onClick:()=>N(s),children:[e.jsx(y.Save,{className:"mr-2 h-4 w-4"}),u?"Saving...":"Save"]})]})})]},s.key)}):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No inventory rows matched your search."})})})]})})]})}exports.InventoryTableClient=P;
@@ -1,3 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("next/cache"),m=require("@nextblock-cms/db/server"),d=require("../../../../shared-inventory.cjs.js");function p(t){const e=[];let o=[],r="",a=!1;for(let n=0;n<t.length;n+=1){const s=t[n],c=t[n+1];if(s==='"'){a&&c==='"'?(r+='"',n+=1):a=!a;continue}if(s===","&&!a){o.push(r),r="";continue}if((s===`
2
- `||s==="\r")&&!a){s==="\r"&&c===`
3
- `&&(n+=1),(r.length>0||o.length>0)&&(o.push(r),e.push(o)),o=[],r="";continue}r+=s}return(r.length>0||o.length>0)&&(o.push(r),e.push(o)),e.filter(n=>n.some(s=>s.trim().length>0))}function v(t){return t.sku}async function I(t){try{const e=Math.max(0,Math.trunc(t.stock));return await d.setSharedInventoryQuantity({sku:t.sku,stock:e}),u.revalidatePath("/cms/products"),u.revalidatePath("/cms/products/inventory"),{success:!0,itemKey:v(t),stock:e}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to update inventory."}}}async function g(t){try{const e=p(t);if(e.length<2)return{success:!1,error:"The CSV file is empty."};const[o,...r]=e,a=o.map(i=>i.trim().toLowerCase()),n=a.indexOf("sku"),s=a.indexOf("stock");if(n===-1||s===-1)return{success:!1,error:"The CSV format is invalid. Please import a file exported from the Inventory page."};const c=m.getServiceRoleSupabaseClient();let h=0;for(const i of r){const l=(i[n]||"").trim(),f=Number.parseInt((i[s]||"").trim(),10);if(l){if(!Number.isFinite(f)||f<0)return{success:!1,error:`Invalid stock value for SKU "${l}".`};await d.setSharedInventoryQuantity({sku:l,stock:f},c),h+=1}}const y=await d.getInventoryItems(c);return u.revalidatePath("/cms/products"),u.revalidatePath("/cms/products/inventory"),{success:!0,updatedCount:h,items:y}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to import inventory CSV."}}}exports.importInventoryCsvAction=g;exports.updateInventoryQuantityAction=I;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),v=require("../components/ProductForm.cjs.js"),y=require("../actions.cjs.js"),h=require("../../../../variation-utils.cjs.js"),x=require("../server-actions.cjs.js"),u=require("../../payments/queries.cjs.js"),R=require("@nextblock-cms/db/server"),a=require("@nextblock-cms/utils"),S=require("../../../../currency.cjs.js");async function w({mediaPickerNode:d,availableLanguagesProp:s,translationGroupId:l,targetLanguageId:o,initialData:t}){const[_,m,p,b]=await Promise.all([u.getEnabledPaymentProviders(),u.getStoreConfigStatus(),y.getGlobalProductAttributes(),R.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(e=>e.data||[])]),g=(b||[]).map(e=>S.normalizeCurrencyRecord(e)),f=(p||[]).map(e=>({id:e.id,name:e.name,name_translations:e.name_translations||{},slug:e.slug,terms:(e.product_attribute_terms||[]).map(r=>({...r,value_translations:r.value_translations||{}}))})),P=s.find(e=>e.id===t?.language_id)?.code||s.find(e=>e.id===(o?parseInt(o,10):void 0))?.code||s.find(e=>e.is_default)?.code,{attributes:q,variants:A}=h.mapRawVariantRelations(t?.product_variants||[],P),j=t&&{...t,variation_attributes:t.variation_attributes||q.map(e=>({attribute_id:e.id,term_ids:e.terms.map(r=>r.id)})),variants:t.variants||A.map(e=>({...e,upc:e.upc??null,price:e.price/100,prices:Object.entries(e.prices||{}).reduce((r,[i,n])=>(r[i]=a.minorUnitAmountToMajor(n,i),r),{}),sale_price:typeof e.sale_price=="number"?e.sale_price/100:null,sale_prices:Object.entries(e.sale_prices||{}).reduce((r,[i,n])=>(r[i]=typeof n=="number"?a.minorUnitAmountToMajor(n,i):null,r),{}),main_media_id:e.main_media_id??null,main_image_url:e.image_url??null}))};return c.jsx("div",{className:"p-8",children:c.jsx(v.ProductForm,{mediaPickerNode:d,availableLanguagesProp:s,globalAttributesProp:f,currenciesProp:g,translationGroupId:l,targetLanguageId:o,initialData:j,enabledProviders:_,configStatus:m,createAction:x.createProductAction})})}exports.NewProductPage=w;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@nextblock-cms/utils"),l=require("../../../currency.cjs.js");function p(r){return Object.entries(r||{}).reduce((e,[o,n])=>(typeof n=="number"&&Number.isFinite(n)&&n>=0?e[a.normalizeCurrencyCode(o)]=n:n===null&&(e[a.normalizeCurrencyCode(o)]=null),e),{})}function C(r){const e=l.normalizeCurrencyRecord(r);return e.is_default!==!0&&e.auto_sync_product_prices===!0}function z(r){return r.map(e=>l.normalizeCurrencyRecord(e)).filter(e=>C(e)).map(e=>e.code)}function f(r,e){const o=new Set(z(e)),n=p(r);return Object.entries(n).reduce((t,[i,u])=>(o.has(i)||(t[i]=u),t),{})}function g(r){const{baseAmount:e,defaultCurrencyCode:o,targetCurrencyCode:n,currencies:t}=r;if(typeof e!="number"||!Number.isFinite(e)||e<0)return null;const i=l.convertMinorUnitAmount({amount:a.majorUnitAmountToMinor(e,o),fromCurrencyCode:o,toCurrencyCode:n,currencies:t,applyRounding:!0});return a.minorUnitAmountToMajor(i,n)}function F(r){const{currencies:e,fallbackPrice:o,fallbackSalePrice:n}=r,t=p(r.prices),i=p(r.salePrices),u=e.find(s=>s.is_default)??e[0];if(!u)return{prices:t,salePrices:i};const d=a.normalizeCurrencyCode(u.code),m=t[d]??(typeof o=="number"?o:null),b=i[d]??(typeof n=="number"?n:null),S=e.reduce((s,y)=>{const c=l.normalizeCurrencyRecord(y);return C(c)?(s[c.code]=g({baseAmount:m,defaultCurrencyCode:d,targetCurrencyCode:c.code,currencies:e}),s):(s[c.code]=t[c.code]??(c.code===d?m:void 0),s)},{}),_=e.reduce((s,y)=>{const c=l.normalizeCurrencyRecord(y);return C(c)?(s[c.code]=g({baseAmount:b,defaultCurrencyCode:d,targetCurrencyCode:c.code,currencies:e}),s):(s[c.code]=i[c.code]??(c.code===d?b:void 0),s)},{});return{prices:S,salePrices:_}}function P(r,e){const o=e.find(u=>u.is_default)??e[0],n=o?a.normalizeCurrencyCode(o.code):"USD",t=f(r.prices,e),i=f(r.sale_prices,e);return{...r,price:typeof t[n]=="number"?t[n]:r.price,prices:t,sale_price:typeof i[n]=="number"?i[n]:r.sale_price??null,sale_prices:i}}function M(r,e){return r?.map(o=>P(o,e))||[]}function A(r,e){const o=e.find(u=>u.is_default)??e[0],n=o?a.normalizeCurrencyCode(o.code):"USD",t=f(r.prices,e),i=f(r.sale_prices,e);return{...r,price:typeof t[n]=="number"?t[n]:r.price,prices:t,sale_price:typeof i[n]=="number"?i[n]:r.sale_price??null,sale_prices:i,variants:M(r.variants,e)}}exports.getStoreManagedPriceCurrencyCodes=z;exports.isCurrencyStoreManagedPrice=C;exports.resolveEditorCurrencyPriceMaps=F;exports.sanitizeProductFormValuesForStoreManagedCurrencies=A;exports.sanitizeVariantDraftForStoreManagedCurrencies=P;exports.sanitizeVariantDraftsForStoreManagedCurrencies=M;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@nextblock-cms/db/server"),l=require("../../../product-actions.cjs.js"),h=require("../../../freemius-coupons.cjs.js"),g=require("../../../currency.cjs.js"),_=require("./product-price-sync.cjs.js"),a=require("next/cache"),v=require("next/navigation");function u(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}async function w(e){const t=i.createClient(),{data:r}=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}),s=_.sanitizeProductFormValuesForStoreManagedCurrencies(e,(r||[]).map(o=>g.normalizeCurrencyRecord(o))),c=await l.createProduct(t,s);if(s.payment_provider==="freemius"&&c?.id)try{await h.syncProductSaleCouponToFreemius({productId:c.id,client:i.getServiceRoleSupabaseClient()})}catch(o){console.error("Failed to sync Freemius sale coupon on create:",o)}a.revalidatePath("/cms/products"),v.redirect("/cms/products")}async function y(e,t,r,s){const c={author_id:r,meta:s,updated_at:new Date().toISOString()},o=async()=>{const{error:f}=await e.from("product_drafts").update(c).eq("product_id",t);if(f)throw new Error(`Failed to save product draft: ${f.message}`)},{data:n,error:m}=await e.from("product_drafts").select("id").eq("product_id",t).maybeSingle();if(m)throw new Error(`Failed to read product draft: ${m.message}`);if(n){await o();return}const{data:P,error:p}=await e.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order, created_at, updated_at").eq("product_id",t).order("order",{ascending:!0});if(p)throw new Error(`Failed to read product blocks: ${p.message}`);const{error:d}=await e.from("product_drafts").insert({...c,blocks:P??[],product_id:t});if(d){if(d.code==="23505"){await o();return}throw new Error(`Failed to save product draft: ${d.message}`)}}async function A(e,t){const r=i.createClient(),{data:{user:s}}=await r.auth.getUser();if(!s)throw new Error("User not authenticated.");const{data:c}=await 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("code",{ascending:!0}),o=_.sanitizeProductFormValuesForStoreManagedCurrencies(t,(c||[]).map(n=>g.normalizeCurrencyRecord(n)));return await y(r,e,s.id,o),{success:!0}}async function S(e){const t=i.createClient();await l.deleteProduct(t,e),a.revalidatePath("/cms/products")}function b(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean)))}async function C(e){const t=b(e);if(t.length===0)return{success:!1,error:"Select at least one product."};const r=i.createClient(),{error:s}=await r.from("products").delete().in("id",t);return s?{success:!1,error:s.message}:(a.revalidatePath("/cms/products"),{success:!0,count:t.length})}async function q(e){const t=b(e);if(t.length===0)return{success:!1,error:"Select at least one product."};const r=i.createClient(),{error:s}=await r.from("products").update({status:"draft",updated_at:new Date().toISOString()}).in("id",t);return s?{success:!1,error:s.message}:(a.revalidatePath("/cms/products"),{success:!0,count:t.length})}async function T(e){const t=String(e||"").trim();if(!t)return{error:"Missing product id."};const r=i.createClient(),{data:{user:s}}=await r.auth.getUser();if(!s)return{error:"You must be signed in to publish a product."};const{data:c,error:o}=await r.from("products").update({status:"active",updated_at:new Date().toISOString()}).eq("id",t).select("slug").single();return o||!c?{error:o?.message||"Could not publish the product."}:(a.revalidatePath("/cms/products"),a.revalidatePath(`/cms/products/${t}/edit`),c.slug&&a.revalidatePath(`/product/${c.slug}`),{})}async function D(e){const t=i.getServiceRoleSupabaseClient(),r=e.name.trim(),s=u(e.slug?.trim()||e.name);if(!r||!s)return{success:!1,error:"Attribute name is required."};const{error:c}=await t.from("product_attributes").insert({name:r,slug:s});return c?{success:!1,error:c.message}:(a.revalidatePath("/cms/products/attributes"),a.revalidatePath("/cms/products/new"),a.revalidatePath("/cms/products"),{success:!0})}async function x(e){const t=i.getServiceRoleSupabaseClient(),{error:r}=await t.from("product_attributes").delete().eq("id",e);return r?{success:!1,error:r.message}:(a.revalidatePath("/cms/products/attributes"),a.revalidatePath("/cms/products/new"),a.revalidatePath("/cms/products"),{success:!0})}async function R(e){const t=i.getServiceRoleSupabaseClient(),r=e.value.trim(),s=u(e.slug?.trim()||e.value);if(!r||!s)return{success:!1,error:"Term value is required."};const{data:c}=await t.from("product_attribute_terms").select("sort_order").eq("attribute_id",e.attributeId).order("sort_order",{ascending:!1}).limit(1),o=typeof c?.[0]?.sort_order=="number"?c[0].sort_order+1:0,{error:n}=await t.from("product_attribute_terms").insert({attribute_id:e.attributeId,value:r,slug:s,sort_order:o});return n?{success:!1,error:n.message}:(a.revalidatePath("/cms/products/attributes"),a.revalidatePath("/cms/products/new"),a.revalidatePath("/cms/products"),{success:!0})}async function F(e){const t=i.getServiceRoleSupabaseClient();for(const[r,s]of e.orderedTermIds.entries()){const{error:c}=await t.from("product_attribute_terms").update({sort_order:r,updated_at:new Date().toISOString()}).eq("id",s).eq("attribute_id",e.attributeId);if(c)return{success:!1,error:c.message}}return a.revalidatePath("/cms/products/attributes"),a.revalidatePath("/cms/products/new"),a.revalidatePath("/cms/products"),{success:!0}}async function I(e){const t=i.getServiceRoleSupabaseClient(),{error:r}=await t.from("product_attributes").update({name_translations:e.nameTranslations,updated_at:new Date().toISOString()}).eq("id",e.attributeId);if(r)return{success:!1,error:r.message};for(const s of e.termTranslations){const{error:c}=await t.from("product_attribute_terms").update({value_translations:s.valueTranslations,updated_at:new Date().toISOString()}).eq("id",s.termId).eq("attribute_id",e.attributeId);if(c)return{success:!1,error:c.message}}return a.revalidatePath("/cms/products/attributes"),a.revalidatePath("/cms/products/new"),a.revalidatePath("/cms/products"),{success:!0}}async function E(e){const t=i.getServiceRoleSupabaseClient(),{error:r}=await t.from("product_attribute_terms").delete().eq("id",e);return r?{success:!1,error:r.message}:(a.revalidatePath("/cms/products/attributes"),a.revalidatePath("/cms/products/new"),a.revalidatePath("/cms/products"),{success:!0})}async function k(e){const t=i.getServiceRoleSupabaseClient(),r=e.name.trim(),s=u(e.slug?.trim()||e.name);if(!r||!s)return{success:!1,error:"Category name is required."};const{data:c,error:o}=await t.from("categories").insert({name:r,slug:s,description:e.description?.trim()||null,name_translations:e.nameTranslations||{},description_translations:e.descriptionTranslations||{}}).select().single();return o?{success:!1,error:o.message}:(a.revalidatePath("/cms/products/categories"),a.revalidatePath("/cms/products/new"),a.revalidatePath("/cms/products"),{success:!0,category:c})}async function z(e,t){const r=i.getServiceRoleSupabaseClient(),s=t.name.trim(),c=u(t.slug?.trim()||t.name);if(!s||!c)return{success:!1,error:"Category name is required."};const{error:o}=await r.from("categories").update({name:s,slug:c,description:t.description?.trim()||null,name_translations:t.nameTranslations||{},description_translations:t.descriptionTranslations||{}}).eq("id",e);return o?{success:!1,error:o.message}:(a.revalidatePath("/cms/products/categories"),a.revalidatePath("/cms/products/new"),a.revalidatePath("/cms/products"),{success:!0})}async function O(e){const t=i.getServiceRoleSupabaseClient(),{error:r}=await t.from("categories").delete().eq("id",e);return r?{success:!1,error:r.message}:(a.revalidatePath("/cms/products/categories"),a.revalidatePath("/cms/products/new"),a.revalidatePath("/cms/products"),{success:!0})}async function $(e,t){const r=i.getServiceRoleSupabaseClient();try{return await l.syncCategoriesForTranslationGroup(r,e,t),a.revalidatePath("/cms/products"),a.revalidatePath(`/cms/products/${e}/edit`),{success:!0}}catch(s){return{success:!1,error:s.message}}}exports.bulkDeleteProductsAction=C;exports.bulkDraftProductsAction=q;exports.createCategoryAction=k;exports.createProductAction=w;exports.createProductAttributeAction=D;exports.createProductAttributeTermAction=R;exports.deleteCategoryAction=O;exports.deleteProductAction=S;exports.deleteProductAttributeAction=x;exports.deleteProductAttributeTermAction=E;exports.publishProductAction=T;exports.reorderProductAttributeTermsAction=F;exports.syncProductCategoriesAction=$;exports.updateCategoryAction=z;exports.updateProductAction=A;exports.updateProductAttributeTranslationsAction=I;
@@ -1,5 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),j=require("@nextblock-cms/db/server"),a=require("@nextblock-cms/ui"),r=require("lucide-react"),h=require("./components/ZoneForm.cjs.js"),u=require("./components/RateForm.cjs.js"),l=require("./server-actions.cjs.js"),f=require("../../../currency.cjs.js"),v=require("../../../inventory-settings.cjs.js"),b=require("../../../states.cjs.js"),o=require("@nextblock-cms/utils");async function N({searchParams:m}){const n=j.getServiceRoleSupabaseClient(),[{data:c},g,{data:x},{data:d}]=await Promise.all([n.from("shipping_zones").select(`
2
- *,
3
- shipping_zone_locations (*),
4
- shipping_zone_methods (*)
5
- `).order("priority_order",{ascending:!0}),v.getEcommerceInventorySettings(n),n.from("languages").select("code, name, is_default").eq("is_active",!0).order("name",{ascending:!0}),n.from("currencies").select("code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount").eq("is_active",!0).order("is_default",{ascending:!1}).order("code",{ascending:!0})]),i=d?.find(t=>t.is_default)?.code||d?.[0]?.code||"USD",p=(d||[]).map(t=>f.normalizeCurrencyRecord(t));return e.jsx(a.TooltipProvider,{children:e.jsxs("div",{className:"space-y-6",children:[m?.success?e.jsx("div",{className:"rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700",children:m.success}):null,e.jsx(a.Card,{className:"overflow-hidden border-slate-200 dark:border-slate-800 shadow-sm",children:e.jsx(a.CardContent,{className:"p-4 sm:p-5",children:e.jsxs("form",{action:l.updateInventoryTrackingAction,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(r.Boxes,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(a.CardTitle,{className:"text-base font-semibold leading-none",children:"Inventory Tracking"}),e.jsx(a.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(a.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:g.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(h.ZoneForm,{})]}),e.jsx("div",{className:"grid gap-6",children:!c||c.length===0?e.jsx(a.Card,{className:"bg-slate-50/50 dark:bg-slate-900/10 border-dashed",children:e.jsxs(a.CardContent,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(r.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)."})]})}):c.map(t=>e.jsxs(a.Card,{className:"overflow-hidden border-slate-200 dark:border-slate-800 shadow-sm hover:shadow-md transition-shadow",children:[e.jsx(a.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(r.Globe,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.CardTitle,{className:"text-lg font-bold",children:t.name}),e.jsxs(a.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: ",t.priority_order]})]}),e.jsxs(a.CardDescription,{className:"text-xs",children:[t.shipping_zone_locations?.length||0," regions covered"]})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(h.ZoneForm,{mode:"edit",initialData:{id:t.id,name:t.name,priority_order:t.priority_order,locations:t.shipping_zone_locations?.map(s=>({country_code:s.country_code,state_code:s.state_code}))||[]}}),e.jsx("form",{action:async()=>{"use server";await l.deleteShippingZone(t.id)},children:e.jsx(a.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(r.Trash2,{className:"h-4 w-4"})})})]})]})}),e.jsx(a.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(r.Globe,{className:"h-3 w-3"})," Target Regions"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.shipping_zone_locations?.length>0?t.shipping_zone_locations.map(s=>e.jsxs(a.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:[s.country_code,s.state_code?e.jsxs("span",{className:"text-slate-400 ml-1",children:["(",b.resolveSubdivisionName(s.country_code,s.state_code),")"]}):""]},s.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(r.Truck,{className:"h-3 w-3"})," Shipping Methods"]}),e.jsx(u.RateForm,{zoneId:t.id,zoneName:t.name,languages:x||[],currencies:p,defaultCurrencyCode:i})]}),e.jsx("div",{className:"space-y-2",children:t.shipping_zone_methods?.length>0?t.shipping_zone_methods.map(s=>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:s.name}),e.jsx(a.Badge,{variant:"outline",className:"h-4 px-1 text-[9px]",children:s.currency_pricing_mode==="manual"?"Manual FX":"Auto FX"}),(s.min_order_amount||0)>0&&e.jsxs(a.Tooltip,{children:[e.jsx(a.TooltipTrigger,{asChild:!0,children:e.jsxs(a.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(r.Info,{className:"h-2 w-2 mr-0.5"}),o.formatPrice(s.min_order_amount,s.cost_currency?.toUpperCase()||i)]})}),e.jsxs(a.TooltipContent,{children:["Available for orders over ",o.formatPrice(s.min_order_amount,s.cost_currency?.toUpperCase()||i)]})]})]}),e.jsx("p",{className:"text-[10px] text-slate-500 uppercase tracking-tighter mix-blend-multiply dark:mix-blend-normal",children:s.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:s.method_type==="free_shipping"?"FREE":o.formatPrice(s.cost_amount,s.cost_currency?.toUpperCase()||i)}),e.jsxs("div",{className:"flex opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(u.RateForm,{zoneId:t.id,zoneName:t.name,languages:x||[],currencies:p,defaultCurrencyCode:i,mode:"edit",initialData:s}),e.jsx("form",{action:async()=>{"use server";await l.deleteShippingRate(s.id)},children:e.jsx(a.Button,{type:"submit",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-red-500",children:e.jsx(r.Trash2,{className:"h-3 w-3"})})})]})]})]},s.id)):e.jsx("p",{className:"text-xs text-slate-400 italic",children:"No methods defined for this zone."})})]})]})})]},t.id))})]})})}exports.ShippingPage=N;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),i=require("react"),r=require("@nextblock-cms/ui"),C=require("lucide-react"),Z=require("../server-actions.cjs.js"),p=require("@nextblock-cms/utils"),T=require("../../../../currency.cjs.js"),$=require("../../../../shipping-rate-currency.cjs.js");function A(h,m){if(typeof h!="number")return"";const d=p.minorUnitAmountToMajor(h,m);return p.getCurrencyMinorUnitFactor(m)===1?d.toFixed(0):d.toFixed(2)}function te(h){return h.reduce((m,d)=>(m[d.code]=p.getCurrencyMinorUnitFactor(d.code)===1?"0":"0.00",m),{})}function N(h,m){const d=String(h||"").trim();if(!d)return null;const g=Number(d);return!Number.isFinite(g)||g<0?null:p.majorUnitAmountToMinor(g,m)}function J(h){return h.currencies.reduce((m,d)=>(m[d.code]=A(h.amounts[d.code],d.code),m),{})}function re({zoneId:h,zoneName:m,languages:d,currencies:g=[],defaultCurrencyCode:K="USD",mode:Q="create",initialData:l}){const[z,I]=i.useState(!1),S=Q==="edit",U=i.useMemo(()=>d.find(s=>s.is_default)||d[0]||null,[d]),B=i.useMemo(()=>d.filter(s=>!s.is_default),[d]),M=p.normalizeCurrencyCode(K),a=i.useMemo(()=>{const s=T.normalizeCurrencyRecord({code:M,symbol:M,exchange_rate:1,is_default:!0,is_active:!0}),n=(g.length>0?g:[s]).map(t=>T.normalizeCurrencyRecord(t)).filter(t=>t.is_active!==!1).sort((t,c)=>t.is_default!==c.is_default?t.is_default?-1:1:t.code.localeCompare(c.code));return n.length>0?n:[s]},[g,M]),f=i.useMemo(()=>a.find(s=>s.is_default)||a[0],[a]),[F,P]=i.useState(l?.name||""),[V,D]=i.useState(l?.name_translations||{}),[j,G]=i.useState(l?.method_type||"flat_rate"),[u,H]=i.useState($.normalizeShippingRateCurrencyMode(l?.currency_pricing_mode)),[o,O]=i.useState(p.normalizeCurrencyCode(l?.cost_currency||f?.code||M)),[b,_]=i.useState({}),[v,w]=i.useState({}),[E,k]=i.useState(!1),L=i.useMemo(()=>{if(u==="manual")return a.reduce((t,c)=>(t[c.code]=b[c.code]??"",t),{});const s=a.reduce((t,c)=>(t[c.code]=b[c.code]??(c.code===o,""),t),{}),n=N(b[o],o);if(n===null)return s;for(const t of a){if(t.code===o){s[t.code]=b[t.code]??A(n,t.code);continue}s[t.code]=A(T.convertMinorUnitAmount({amount:n,fromCurrencyCode:o,toCurrencyCode:t.code,currencies:a}),t.code)}return s},[a,b,u,o]),q=i.useMemo(()=>{if(u==="manual")return a.reduce((t,c)=>(t[c.code]=v[c.code]??"",t),{});const s=a.reduce((t,c)=>(t[c.code]=v[c.code]??"",t),{}),n=N(v[o],o);if(n===null)return s;for(const t of a){if(t.code===o){s[t.code]=v[t.code]??A(n,t.code);continue}s[t.code]=A(T.convertMinorUnitAmount({amount:n,fromCurrencyCode:o,toCurrencyCode:t.code,currencies:a}),t.code)}return s},[a,v,u,o]);i.useEffect(()=>{f&&(a.some(s=>s.code===o)||O(f.code))},[a,f,o]),i.useEffect(()=>{if(!z||!f)return;const s=$.normalizeShippingRateCurrencyMode(l?.currency_pricing_mode),n=$.sanitizeShippingRateAmountMaps({currencies:a,mode:s,sourceCurrencyCode:l?.cost_currency||f.code,costAmounts:l?.cost_amounts||void 0,minOrderAmounts:l?.min_order_amounts||void 0,fallbackCostAmount:l?.cost_amount,fallbackMinOrderAmount:l?.min_order_amount});P(l?.name||""),D(l?.name_translations||{}),G(l?.method_type||"flat_rate"),H(s),O(n.sourceCurrencyCode),_(J({amounts:n.costAmounts,currencies:a})),w(J({amounts:n.minOrderAmounts,currencies:a}))},[a,f,l,z]);const W=s=>{s!==u&&(s==="manual"&&(_(L),w(q)),H(s))},Y=s=>{const n=p.normalizeCurrencyCode(s);_(t=>({...t,[n]:L[n]??t[n]??""})),w(t=>({...t,[n]:q[n]??t[n]??""})),O(n)},ee=s=>{G(s),s==="free_shipping"&&_(te(a))},se=async s=>{s.preventDefault(),k(!0);const n={},t={};if(u==="manual")for(const R of a){const x=R.code;if(j==="free_shipping")n[x]=0;else{const X=N(b[x],x);if(X===null){k(!1),alert(`Enter a valid shipping cost for ${x}.`);return}n[x]=X}t[x]=N(v[x],x)??0}else{const R=j==="free_shipping"?0:N(b[o],o);if(R===null){k(!1),alert(`Enter a valid shipping cost for ${o}.`);return}n[o]=R,t[o]=N(v[o],o)??0}const c={name:F,nameTranslations:V,type:j,currencyPricingMode:u,sourceCurrencyCode:o,costAmounts:n,minOrderAmounts:t},y=S&&l?.id?await Z.updateShippingRate(l.id,c):await Z.createShippingRate(h,c);k(!1),y.success?I(!1):y.error&&alert(y.error)};return e.jsxs(r.Dialog,{open:z,onOpenChange:I,children:[e.jsx(r.DialogTrigger,{asChild:!0,children:S?e.jsx(r.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-primary",children:e.jsx(C.Edit2,{className:"h-3 w-3"})}):e.jsxs(r.Button,{variant:"outline",size:"sm",className:"h-8 gap-1.5 border-dashed hover:border-solid shadow-sm",children:[e.jsx(C.Plus,{className:"h-3.5 w-3.5"}),"Add Rate"]})}),e.jsx(r.DialogContent,{className:"max-h-[85vh] max-w-4xl overflow-y-auto",children:e.jsxs("form",{onSubmit:se,children:[e.jsxs(r.DialogHeader,{children:[e.jsx(r.DialogTitle,{children:S?"Edit Shipping Rate":"Add Shipping Rate"}),e.jsxs(r.DialogDescription,{children:["Configure shipping costs and localized labels for matching orders in ",e.jsx("strong",{children:m}),"."]})]}),e.jsxs("div",{className:"grid gap-5 py-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(r.Label,{htmlFor:"rate-name",children:["Rate Name",U?` (${U.name})`:""]}),e.jsx(r.Input,{id:"rate-name",value:F,onChange:s=>P(s.target.value),placeholder:"e.g. Standard, Express, Free Shipping",required:!0})]}),B.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(C.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:B.map(s=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(r.Label,{htmlFor:`rate-name-${s.code}`,children:s.name}),e.jsx(r.Input,{id:`rate-name-${s.code}`,value:V[s.code]||"",onChange:n=>D(t=>({...t,[s.code]:n.target.value})),placeholder:F||"Translated label"})]},s.code))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(r.Label,{htmlFor:"type",children:"Method Type"}),e.jsxs(r.Select,{value:j,onValueChange:ee,children:[e.jsx(r.SelectTrigger,{id:"type",className:"bg-slate-50/50 dark:bg-slate-900/50",children:e.jsx(r.SelectValue,{placeholder:"Select type"})}),e.jsxs(r.SelectContent,{children:[e.jsx(r.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(C.DollarSign,{className:"h-3 w-3"})}),e.jsx("span",{children:"Flat Rate"})]})}),e.jsx(r.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(C.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:u==="auto",onChange:s=>W(s.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."})]})]}),u==="auto"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(r.Label,{htmlFor:"rate-currency",children:"Sync From Currency"}),e.jsxs(r.Select,{value:o,onValueChange:Y,children:[e.jsx(r.SelectTrigger,{id:"rate-currency",className:"bg-background",children:e.jsx(r.SelectValue,{placeholder:"Select currency"})}),e.jsx(r.SelectContent,{children:a.map(s=>e.jsxs(r.SelectItem,{value:s.code,children:[s.code,s.is_default?" (Default)":""]},s.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:j==="free_shipping"?"Free-shipping methods keep cost at zero, but you can still control the threshold per currency.":u==="auto"?`Only ${o} 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:a.map(s=>{const n=u==="auto"&&s.code!==o,t=p.getCurrencyMinorUnitFactor(s.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:s.code}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Rate ",s.exchange_rate]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.is_default?e.jsx(r.Badge,{variant:"outline",children:"Default"}):null,u==="auto"&&s.code===o?e.jsx(r.Badge,{children:"Source"}):null,n?e.jsx(r.Badge,{variant:"outline",children:"Derived"}):null]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(r.Label,{htmlFor:`rate-cost-${s.code}`,children:["Cost (",s.code,")"]}),e.jsxs("div",{className:"relative",children:[e.jsx(C.DollarSign,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-slate-400"}),e.jsx(r.Input,{id:`rate-cost-${s.code}`,type:"number",step:t,min:"0",value:L[s.code]??"",onChange:c=>_(y=>({...y,[s.code]:c.target.value})),className:"pl-9 bg-slate-50/50 dark:bg-slate-900/50 disabled:opacity-70",disabled:j==="free_shipping"||n,required:j!=="free_shipping"&&u==="manual"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(r.Label,{htmlFor:`rate-threshold-${s.code}`,children:["Free-Shipping Threshold (",s.code,")"]}),e.jsxs("div",{className:"relative",children:[e.jsx(C.DollarSign,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-slate-400"}),e.jsx(r.Input,{id:`rate-threshold-${s.code}`,type:"number",step:t,min:"0",value:q[s.code]??"",onChange:c=>w(y=>({...y,[s.code]:c.target.value})),className:"pl-9 bg-slate-50/50 dark:bg-slate-900/50 disabled:opacity-70",disabled:n,placeholder:p.getCurrencyMinorUnitFactor(s.code)===1?"0":"0.00"})]})]}),n?e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["This currency is synced automatically from ",o,"."]}):u==="manual"?e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Enter the exact amount shoppers should see in this currency."}):null]},s.code)})})]})]}),e.jsxs(r.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(r.Button,{type:"button",variant:"ghost",onClick:()=>I(!1),disabled:E,children:"Cancel"}),e.jsx(r.Button,{type:"submit",disabled:E||!F.trim(),children:E?S?"Saving...":"Adding...":S?"Save Changes":"Add Rate"})]})]})})]})}exports.RateForm=re;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),c=require("react"),r=require("@nextblock-cms/ui"),p=require("lucide-react"),S=require("../../../../countries.cjs.js"),B=require("../../../../states.cjs.js"),_=require("../server-actions.cjs.js");function $(h=[]){return[...new Set(h.map(o=>o.country_code))]}function q(h=[]){return h.reduce((o,a)=>{if(!a.state_code)return o;const i=new Set(o[a.country_code]||[]);return i.add(a.state_code),o[a.country_code]=[...i],o},{})}function E(h,o){return h.flatMap(a=>{const i=o[a]||[];return i.length===0?[{country_code:a,state_code:null}]:i.map(d=>({country_code:a,state_code:d}))})}function I({mode:h="create",initialData:o}){const[a,i]=c.useState(!1),d=h==="edit",[u,g]=c.useState(o?.name||""),[f,j]=c.useState(o?.priority_order||0),[m,v]=c.useState($(o?.locations)),[y,x]=c.useState(q(o?.locations)),[N,b]=c.useState(""),[w,C]=c.useState(!1);c.useEffect(()=>{a&&(g(o?.name||""),j(o?.priority_order||0),v($(o?.locations)),x(q(o?.locations)),b(""))},[o,a]);const Z=c.useMemo(()=>{const s=N.trim().toLowerCase();return s?S.countries.filter(t=>t.name.toLowerCase().includes(s)||t.code.toLowerCase().includes(s)):S.countries},[N]),k=c.useMemo(()=>S.countries.filter(s=>m.includes(s.code)),[m]),F=s=>{v(t=>t.includes(s)?t.filter(n=>n!==s):[...t,s]),x(t=>{if(t[s]){const n={...t};return delete n[s],n}return t})},P=(s,t)=>{x(n=>{const l=new Set(n[s]||[]);return l.has(t)?l.delete(t):l.add(t),{...n,[s]:[...l]}})},z=async s=>{if(s.preventDefault(),!u||m.length===0)return;C(!0);const t=E(m,y),n=d&&o?.id?await _.updateShippingZone(o.id,u,f,t):await _.createShippingZone(u,f,t);C(!1),n.success?(i(!1),d||(g(""),j(0),v([]),x({}),b(""))):n.error&&alert(n.error)};return e.jsxs(r.Dialog,{open:a,onOpenChange:i,children:[e.jsx(r.DialogTrigger,{asChild:!0,children:d?e.jsx(r.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(r.Button,{className:"gap-2 shadow-sm",children:[e.jsx(p.Plus,{className:"h-4 w-4"}),"New Zone"]})}),e.jsx(r.DialogContent,{className:"max-w-4xl max-h-[90vh] flex flex-col overflow-hidden",children:e.jsxs("form",{onSubmit:z,className:"flex h-full flex-col overflow-hidden",children:[e.jsxs(r.DialogHeader,{children:[e.jsx(r.DialogTitle,{children:d?"Edit Shipping Zone":"Create Shipping Zone"}),e.jsx(r.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(r.Label,{htmlFor:"name",className:"text-right",children:"Zone Name"}),e.jsx(r.Input,{id:"name",value:u,onChange:s=>g(s.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(r.Label,{htmlFor:"priority",className:"text-right",children:"Priority Order"}),e.jsx(r.Input,{id:"priority",type:"number",value:f,onChange:s=>j(Number(s.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(r.Label,{className:"text-sm font-semibold",children:["Countries (",m.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(r.Input,{placeholder:"Search countries...",className:"pl-9 h-9",value:N,onChange:s=>b(s.target.value)})]})]}),e.jsx(r.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:Z.map(s=>{const t=m.includes(s.code);return e.jsxs("div",{className:`flex items-center space-x-2 rounded-md border p-2 transition-colors ${t?"border-primary/30 bg-primary/5 text-primary":"border-transparent hover:bg-slate-100 dark:hover:bg-slate-800/60"}`,children:[e.jsx(r.Checkbox,{id:`country-${s.code}`,checked:t,onCheckedChange:()=>F(s.code)}),e.jsxs("label",{htmlFor:`country-${s.code}`,className:"flex-1 cursor-pointer text-xs py-1",children:[s.name," (",s.code,")"]})]},s.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(r.Label,{className:"text-sm font-semibold",children:"States / Provinces"})]}),k.length===0?e.jsx(r.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:k.map(s=>{const t=B.getStatesForCountry(s.code),n=y[s.code]||[];return e.jsx(r.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:[s.name," (",s.code,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.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:n.length>0?`${n.length} selected`:"Whole country"})]}),t.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:t.map(l=>{const L=n.includes(l.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(r.Checkbox,{id:`${s.code}-${l.code}`,checked:L,onCheckedChange:()=>P(s.code,l.code)}),e.jsxs("label",{htmlFor:`${s.code}-${l.code}`,className:"flex-1 cursor-pointer text-xs py-1",children:[l.name," (",l.code,")"]})]},`${s.code}-${l.code}`)})}):null]})},s.code)})})]})]})]}),e.jsxs(r.DialogFooter,{className:"mt-auto border-t pt-4",children:[e.jsx(r.Button,{type:"button",variant:"ghost",onClick:()=>i(!1),children:"Cancel"}),e.jsx(r.Button,{type:"submit",disabled:w||!u||m.length===0,children:w?d?"Updating...":"Creating...":d?"Save Changes":"Create Zone"})]})]})})]})}exports.ZoneForm=I;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@nextblock-cms/db/server"),a=require("next/cache"),C=require("next/navigation"),S=require("../../../countries.cjs.js"),g=require("../../../currency.cjs.js"),l=require("../../../inventory-settings.cjs.js"),_=require("../../../shipping-rate-currency.cjs.js"),z=require("../../../states.cjs.js");function h(o){return Object.entries(o||{}).reduce((e,[n,t])=>{const r=n.trim().toLowerCase(),s=t.trim();return r&&s&&(e[r]=s),e},{})}async function A(o){const e=c.createClient(),{data:{user:n}}=await e.auth.getUser();if(!n)throw new Error("Unauthorized");const{data:t}=await e.from("profiles").select("role").eq("id",n.id).single();if(!t||t.role!=="ADMIN")throw new Error("Forbidden");const r=o.getAll("trackQuantities").includes("true"),s=await l.getEcommerceInventorySettings(e),{error:i}=await l.upsertEcommerceInventorySettings(e,{trackQuantities:r,enableTaxes:s.enableTaxes,taxCalculationMode:s.taxCalculationMode});if(i)throw new Error(i.message);a.revalidatePath("/cms/shipping"),C.redirect("/cms/shipping?success=Inventory settings updated")}function f(o){const e=new Map;for(const n of o){const t=S.normalizeCountryCode(n.country_code);if(!t)continue;const r=z.normalizeSubdivisionCode(t,n.state_code)||null,s=`${t}:${r??"*"}`;e.set(s,{country_code:t,state_code:r})}return[...e.values()]}async function y(o){const{data:e,error:n}=await o.from("currencies").select("code, is_default").eq("is_active",!0).order("is_default",{ascending:!1}).order("code",{ascending:!0});return n?{error:n.message}:{currencies:e||[]}}async function v(o,e,n){const t=c.getServiceRoleSupabaseClient(),r=f(n),{data:s,error:i}=await t.from("shipping_zones").insert({name:o,priority_order:e}).select().single();if(i||!s)return{error:i?.message||"Failed to create zone"};if(r.length>0){const m=r.map(u=>({zone_id:s.id,country_code:u.country_code,state_code:u.state_code??null})),{error:d}=await t.from("shipping_zone_locations").insert(m);if(d)return{error:d.message}}return a.revalidatePath("/cms/shipping"),{success:!0}}async function w(o,e,n,t){const r=c.getServiceRoleSupabaseClient(),s=f(t),{error:i}=await r.from("shipping_zones").update({name:e,priority_order:n,updated_at:new Date().toISOString()}).eq("id",o);if(i)return{error:i.message||"Failed to update zone"};const{error:m}=await r.from("shipping_zone_locations").delete().eq("zone_id",o);if(m)return{error:"Failed to refresh locations"};if(s.length>0){const d=s.map(p=>({zone_id:o,country_code:p.country_code,state_code:p.state_code??null})),{error:u}=await r.from("shipping_zone_locations").insert(d);if(u)return{error:u.message}}return a.revalidatePath("/cms/shipping"),{success:!0}}async function b(o){const e=c.getServiceRoleSupabaseClient(),{error:n}=await e.from("shipping_zones").delete().eq("id",o);return n?{error:n.message}:(a.revalidatePath("/cms/shipping"),{success:!0})}async function R(o,e){const n=c.getServiceRoleSupabaseClient(),t=await y(n);if("error"in t)return{error:t.error};const r=_.sanitizeShippingRateAmountMaps({currencies:t.currencies.map(i=>g.normalizeCurrencyRecord(i)),mode:e.currencyPricingMode,sourceCurrencyCode:e.sourceCurrencyCode,costAmounts:e.costAmounts,minOrderAmounts:e.minOrderAmounts,fallbackCostAmount:e.cost,fallbackMinOrderAmount:e.minOrderAmount}),{error:s}=await n.from("shipping_zone_methods").insert({zone_id:o,name:e.name.trim(),name_translations:h(e.nameTranslations),method_type:e.type,currency_pricing_mode:r.mode,cost_amount:r.costAmounts[r.sourceCurrencyCode],cost_amounts:r.costAmounts,cost_currency:r.sourceCurrencyCode,min_order_amount:r.minOrderAmounts[r.sourceCurrencyCode],min_order_amounts:r.minOrderAmounts});return s?{error:s.message}:(a.revalidatePath("/cms/shipping"),{success:!0})}async function O(o,e){const n=c.getServiceRoleSupabaseClient(),t=await y(n);if("error"in t)return{error:t.error};const r=_.sanitizeShippingRateAmountMaps({currencies:t.currencies.map(i=>g.normalizeCurrencyRecord(i)),mode:e.currencyPricingMode,sourceCurrencyCode:e.sourceCurrencyCode,costAmounts:e.costAmounts,minOrderAmounts:e.minOrderAmounts,fallbackCostAmount:e.cost,fallbackMinOrderAmount:e.minOrderAmount}),{error:s}=await n.from("shipping_zone_methods").update({name:e.name.trim(),name_translations:h(e.nameTranslations),method_type:e.type,currency_pricing_mode:r.mode,cost_amount:r.costAmounts[r.sourceCurrencyCode],cost_amounts:r.costAmounts,cost_currency:r.sourceCurrencyCode,min_order_amount:r.minOrderAmounts[r.sourceCurrencyCode],min_order_amounts:r.minOrderAmounts,updated_at:new Date().toISOString()}).eq("id",o);return s?{error:s.message}:(a.revalidatePath("/cms/shipping"),{success:!0})}async function q(o){const e=c.getServiceRoleSupabaseClient(),{error:n}=await e.from("shipping_zone_methods").delete().eq("id",o);return n?{error:n.message}:(a.revalidatePath("/cms/shipping"),{success:!0})}exports.createShippingRate=R;exports.createShippingZone=v;exports.deleteShippingRate=q;exports.deleteShippingZone=b;exports.updateInventoryTrackingAction=A;exports.updateShippingRate=O;exports.updateShippingZone=w;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),o=require("@nextblock-cms/db/server"),a=require("@nextblock-cms/ui"),n=require("lucide-react"),x=require("next/link"),b=require("../../../inventory-settings.cjs.js"),g=require("../../../states.cjs.js"),f=require("../payments/queries.cjs.js"),u=require("./actions.cjs.js"),m=require("./components/TaxRateForm.cjs.js");function y(s){return`${s.toFixed(4).replace(/\.?0+$/,"")}%`}function v(s){return s.state_code?`${s.country_code} - ${g.resolveSubdivisionName(s.country_code,s.state_code)}`:`${s.country_code} - Country-wide`}async function N({searchParams:s}){const h=o.createClient(),p=o.getServiceRoleSupabaseClient(),[r,j,d]=await Promise.all([b.getEcommerceInventorySettings(h),f.getEnabledPaymentProviders(),p.from("tax_rates").select("id, country_code, state_code, tax_name, tax_rate, created_at, updated_at").order("country_code").order("state_code").order("tax_name")]),l=d.data||[],c=d.error,i=j.stripe;return e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 px-6 py-8",children:[s?.success?e.jsx("div",{className:"rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700",children:s.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(a.Button,{asChild:!0,variant:"outline",size:"icon","aria-label":"Back to shipping",children:e.jsx(x,{href:"/cms/shipping",children:e.jsx(n.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(a.Badge,{variant:i?"default":"outline",className:"uppercase",children:["Stripe ",i?"Enabled":"Disabled"]}),e.jsx("div",{className:"rounded-full border bg-muted/30 p-3 text-muted-foreground",children:e.jsx(n.Settings2,{className:"h-5 w-5"})})]})]}),i?e.jsxs(e.Fragment,{children:[e.jsxs(a.Card,{children:[e.jsxs(a.CardHeader,{children:[e.jsx(a.CardTitle,{children:"Global Tax Controls"}),e.jsx(a.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(a.CardContent,{children:e.jsxs("form",{action:u.updateTaxSettingsAction,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:r.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:r.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(a.Button,{type:"submit",children:"Save Tax Settings"})})]})]})})]}),e.jsxs(a.Card,{children:[e.jsx(a.CardHeader,{children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(a.CardTitle,{children:"Manual Tax Rates"}),e.jsx(a.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(a.Badge,{variant:r.taxCalculationMode==="manual"?"default":"outline",children:r.taxCalculationMode==="manual"?"Active Mode":"Stored for Manual Mode"})]})}),e.jsxs(a.CardContent,{className:"space-y-6",children:[c?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,c?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(n.ShieldCheck,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"font-semibold",children:"Create a Tax Rate"})]}),e.jsx(m.TaxRateForm,{})]}),e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed bg-muted/10 px-4 py-8 text-center",children:[e.jsx("p",{className:"font-medium",children:"No manual tax rates yet"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Add country-wide or state/province-specific rows to start calculating manual taxes."})]}):l.map(t=>e.jsxs(a.Card,{className:"border-muted",children:[e.jsx(a.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(a.CardTitle,{className:"text-base",children:t.tax_name}),e.jsx(a.CardDescription,{children:v(t)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.Badge,{variant:"outline",children:y(Number(t.tax_rate))}),e.jsx("form",{action:async()=>{"use server";await u.deleteTaxRateAction(t.id)},children:e.jsx(a.Button,{type:"submit",variant:"ghost",size:"icon","aria-label":"Delete tax rate",children:e.jsx(n.Trash2,{className:"h-4 w-4"})})})]})]})}),e.jsx(a.CardContent,{children:e.jsx(m.TaxRateForm,{initialData:t,submitLabel:"Update tax rate",compact:!0})})]},t.id))})]})]})]})]}):e.jsxs(a.Card,{className:"border-dashed",children:[e.jsxs(a.CardHeader,{children:[e.jsx(a.CardTitle,{children:"Enable Stripe to configure physical-product taxes"}),e.jsx(a.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(a.CardContent,{children:e.jsx(a.Button,{asChild:!0,variant:"outline",children:e.jsx(x,{href:"/cms/payments",children:"Open Payment Settings"})})})]})]})}exports.TaxesPage=N;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("@nextblock-cms/db/server"),i=require("next/cache"),w=require("next/navigation"),x=require("../../../countries.cjs.js"),g=require("../../../inventory-settings.cjs.js"),h=require("../../../states.cjs.js");async function c(){const t=m.createClient(),{data:{user:e}}=await t.auth.getUser();if(!e)throw new Error("Unauthorized");const{data:a}=await t.from("profiles").select("role").eq("id",e.id).single();if(!a||a.role!=="ADMIN")throw new Error("Forbidden");return t}async function y(t){const e=await c(),a=await g.getEcommerceInventorySettings(e),r=t.getAll("enableTaxes").includes("true"),o=t.get("taxCalculationMode")==="automatic"?"automatic":"manual",{error:n}=await g.upsertEcommerceInventorySettings(e,{trackQuantities:a.trackQuantities,enableTaxes:r,taxCalculationMode:o});if(n)throw new Error(n.message);i.revalidatePath("/cms/shipping"),i.revalidatePath("/cms/settings/taxes"),w.redirect("/cms/settings/taxes?success=Tax settings updated")}async function p(t){const e=await c(),a=String(t.get("id")||"").trim(),r=x.normalizeCountryCode(String(t.get("country_code")||"").trim()),o=String(t.get("state_code")||"").trim(),n=String(t.get("tax_name")||"").trim(),s=Number(t.get("tax_rate"));if(!r)throw new Error("Country code is required.");if(!n)throw new Error("Tax name is required.");if(!Number.isFinite(s)||s<0||s>100)throw new Error("Tax rate must be between 0 and 100.");const u={country_code:r,state_code:h.normalizeSubdivisionCode(r,o)||null,tax_name:n,tax_rate:s},l=a?e.from("tax_rates").update(u).eq("id",a):e.from("tax_rates").insert(u),{error:d}=await l;if(d)throw new Error(d.message);i.revalidatePath("/cms/settings/taxes")}async function b(t){const e=await c(),{error:a}=await e.from("tax_rates").delete().eq("id",t);if(a)throw new Error(a.message);i.revalidatePath("/cms/settings/taxes")}exports.deleteTaxRateAction=b;exports.saveTaxRateAction=p;exports.updateTaxSettingsAction=y;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),s=require("@nextblock-cms/ui"),u=require("react"),m=require("../../../../countries.cjs.js"),c=require("../../../../states.cjs.js"),S=require("../actions.cjs.js");function C({initialData:e,submitLabel:p="Save tax rate",compact:a=!1}){const l=m.normalizeCountryCode(e?.country_code)||"US",[d,h]=u.useState(l),[o,n]=u.useState(c.normalizeSubdivisionCode(l,e?.state_code)||e?.state_code||""),y=u.useMemo(()=>c.getStatesForCountry(d),[d]),j=c.countryUsesStructuredStates(d);return t.jsxs("form",{action:S.saveTaxRateAction,className:"space-y-4",children:[e?.id?t.jsx("input",{type:"hidden",name:"id",value:e.id}):null,t.jsxs("div",{className:a?"grid gap-4 md:grid-cols-4":"grid gap-4 md:grid-cols-2 xl:grid-cols-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(s.Label,{htmlFor:e?.id?`country-${e.id}`:"tax-rate-country",children:"Country"}),t.jsx("select",{id:e?.id?`country-${e.id}`:"tax-rate-country",name:"country_code",value:d,onChange:r=>{const x=r.target.value,g=c.getStatesForCountry(x);h(x),n(g.some(v=>v.code===o)?o:"")},className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:m.countries.map(r=>t.jsx("option",{value:r.code,children:r.name},r.code))})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(s.Label,{htmlFor:e?.id?`state-${e.id}`:"tax-rate-state",children:"State / Province"}),j?t.jsxs("select",{id:e?.id?`state-${e.id}`:"tax-rate-state",name:"state_code",value:o,onChange:r=>n(r.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:[t.jsx("option",{value:"",children:"Country-wide / federal"}),y.map(r=>t.jsx("option",{value:r.code,children:r.name},r.code))]}):t.jsx(s.Input,{id:e?.id?`state-${e.id}`:"tax-rate-state",name:"state_code",value:o,onChange:r=>n(r.target.value),placeholder:"Optional"})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(s.Label,{htmlFor:e?.id?`name-${e.id}`:"tax-rate-name",children:"Tax name"}),t.jsx(s.Input,{id:e?.id?`name-${e.id}`:"tax-rate-name",name:"tax_name",defaultValue:e?.tax_name||"",placeholder:"GST, PST, State Sales Tax",required:!0})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(s.Label,{htmlFor:e?.id?`rate-${e.id}`:"tax-rate-rate",children:"Rate (%)"}),t.jsx(s.Input,{id:e?.id?`rate-${e.id}`:"tax-rate-rate",name:"tax_rate",type:"number",min:"0",max:"100",step:"0.0001",defaultValue:typeof e?.tax_rate=="number"?e.tax_rate.toString():"",placeholder:"5.0000",required:!0})]})]}),t.jsx("div",{className:"flex justify-end",children:t.jsx(s.Button,{type:"submit",size:a?"sm":"default",children:p})})]})}exports.TaxRateForm=C;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("@nextblock-cms/db/server"),E="payment_secret",f="payment_public",K=6e4;let u=null;function a(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}async function S(e=!1){const r=Date.now();if(!e&&u&&r-u.at<K)return{secret:u.secret,public:u.public};let i={},t={};try{const n=s.getServiceRoleSupabaseClient(),[{data:o},{data:c}]=await Promise.all([n.from("site_settings").select("value").eq("key",E).maybeSingle(),n.from("site_settings").select("value").eq("key",f).maybeSingle()]);i=a(o?.value),t=a(c?.value)}catch{}return u={at:r,secret:i,public:t},{secret:i,public:t}}function d(){u=null}function l(e,r){return s.tryDecryptWithEnvKey(e[r])}async function h(){const{secret:e}=await S();return s.resolveConfigValue(l(e,"stripeSecretKey"),"STRIPE_SECRET_KEY")}async function _(){const{secret:e}=await S();return s.resolveConfigValue(l(e,"stripeWebhookSecret"),"STRIPE_WEBHOOK_SECRET")}async function v(){const{public:e}=await S(),r=a(e.stripe).publishableKey;return s.resolveConfigValue(typeof r=="string"?r:null,"NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY")}async function C(){try{const{secret:e,public:r}=await S(),i=a(r.freemius),t=(n,o)=>{o&&o.trim()&&(process.env[n]=o.trim())};t("FREEMIUS_SECRET_KEY",l(e,"freemiusSecretKey")),t("FREEMIUS_API_KEY",l(e,"freemiusApiKey")),t("FREEMIUS_ECOMMERCE_SANDBOX_SECRET_KEY",l(e,"freemiusSandboxSecretKey")),t("FREEMIUS_PUBLIC_KEY",typeof i.publicKey=="string"?i.publicKey:null),t("FREEMIUS_PRODUCT_ID",typeof i.productId=="string"?i.productId:null),t("FREEMIUS_DEVELOPER_ID",typeof i.developerId=="string"?i.developerId:null)}catch(e){console.warn("[payment-config] Could not hydrate Freemius credentials from the database:",e)}}async function P(){const{secret:e,public:r}=await S(),i=a(r.freemius),t=a(r.stripe),n=[];s.resolveConfigValue(l(e,"stripeSecretKey"),"STRIPE_SECRET_KEY")||n.push("Secret key"),s.resolveConfigValue(typeof t.publishableKey=="string"?t.publishableKey:null,"NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY")||n.push("Publishable key"),s.resolveConfigValue(l(e,"stripeWebhookSecret"),"STRIPE_WEBHOOK_SECRET")||n.push("Webhook secret");const o=[];return s.resolveConfigValue(typeof i.publicKey=="string"?i.publicKey:null,"FREEMIUS_PUBLIC_KEY")||o.push("Public key"),s.resolveConfigValue(l(e,"freemiusSecretKey"),"FREEMIUS_SECRET_KEY")||o.push("Secret key"),{stripe:{hasKeys:n.length===0,missing:n},freemius:{hasKeys:o.length===0,missing:o}}}async function I(){const e=s.createClient(),[{data:r},{data:i}]=await Promise.all([e.from("site_settings").select("value").eq("key",E).maybeSingle(),e.from("site_settings").select("value").eq("key",f).maybeSingle()]),t=a(r?.value),n=a(i?.value),o=a(n.stripe),c=a(n.freemius),p=y=>typeof y=="string"?y:"";return{stripe:{publishableKey:p(o.publishableKey),hasSecretKey:s.getSecretEnvelopeStatus(t.stripeSecretKey).hasStoredValue,hasWebhookSecret:s.getSecretEnvelopeStatus(t.stripeWebhookSecret).hasStoredValue},freemius:{developerId:p(c.developerId),publicKey:p(c.publicKey),productId:p(c.productId),hasSecretKey:s.getSecretEnvelopeStatus(t.freemiusSecretKey).hasStoredValue,hasApiKey:s.getSecretEnvelopeStatus(t.freemiusApiKey).hasStoredValue},envFallbackActive:!!(!t.stripeSecretKey&&process.env.STRIPE_SECRET_KEY)}}async function R(e){const r=s.createClient(),i={stripe:{publishableKey:e.stripe.publishableKey.trim()},freemius:{developerId:e.freemius.developerId.trim(),publicKey:e.freemius.publicKey.trim(),productId:e.freemius.productId.trim(),sandboxEnabled:!1}},{error:t}=await r.from("site_settings").upsert({key:f,value:i});if(t)throw console.error("Error saving payment_public settings:",t.message),new Error("Failed to save payment settings.");const n=[["stripeSecretKey",e.stripe.secretKey],["stripeWebhookSecret",e.stripe.webhookSecret],["freemiusSecretKey",e.freemius.secretKey],["freemiusApiKey",e.freemius.apiKey]];if(n.some(([,c])=>c&&c.trim())){if(s.isSandboxEnvironment())throw new Error("The sandbox cannot store live payment credentials.");const{data:c}=await r.from("site_settings").select("value").eq("key",E).maybeSingle(),y={...a(c?.value)};for(const[g,b]of n)b&&b.trim()&&(y[g]=s.encryptWithEnvKey(b.trim()));const{error:m}=await r.from("site_settings").upsert({key:E,value:y});if(m)throw console.error("Error saving payment_secret settings:",m.message),new Error("Failed to save payment credentials.")}d()}exports.clearPaymentConfigCache=d;exports.getPaymentConfigStatus=P;exports.getPaymentCredentialsView=I;exports.hydrateFreemiusEnvFromDb=C;exports.resolveStripePublishableKey=v;exports.resolveStripeSecretKey=h;exports.resolveStripeWebhookSecret=_;exports.savePaymentCredentials=R;
@@ -1,238 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("@nextblock-cms/utils/server"),P=require("./shared-inventory.cjs.js"),M=require("@nextblock-cms/utils/utils"),C=require("@nextblock-cms/utils"),w=e=>Math.round(e*100);function q(e){return Object.entries(e||{}).reduce((t,[r,i])=>(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(t[M.normalizeCurrencyCode(r)]=w(i)),t),{})}function E(e){return(e||[]).map(t=>({id:t.id,sku:t.sku,upc:t.upc??null,price:w(t.price),sale_price:typeof t.sale_price=="number"&&!isNaN(t.sale_price)?w(t.sale_price):null,prices:q(t.prices),sale_prices:q(t.sale_prices),sale_start_at:t.sale_start_at??null,sale_end_at:t.sale_end_at??null,stock_quantity:t.stock_quantity,main_media_id:t.main_media_id??null,attribute_term_ids:t.attribute_term_ids}))}function S(e,t){const i=e.product_type==="digital"&&e.payment_provider==="freemius"?Math.max(0,Number(e.trial_period_days??0)):0;return{id:t,product_type:e.product_type,payment_provider:e.payment_provider,title:e.title,slug:e.slug,sku:e.sku,upc:e.upc??null,stock:e.stock,status:e.status,short_description:e.short_description??null,description_json:e.description_json??null,metadata:{},price:w(e.price),sale_price:typeof e.sale_price=="number"&&!isNaN(e.sale_price)?w(e.sale_price):null,prices:q(e.prices),sale_prices:q(e.sale_prices),sale_start_at:e.sale_start_at??null,sale_end_at:e.sale_end_at??null,freemius_plan_id:e.freemius_plan_id??null,freemius_product_id:e.freemius_product_id??null,trial_period_days:i,trial_requires_payment_method:i>0?e.trial_requires_payment_method??!1:!1,is_taxable:e.is_taxable,language_id:e.language_id,translation_group_id:e.translation_group_id||void 0,variants:E(e.variants)}}async function j(e,t,r){const i=o=>{const a=typeof o=="string"?o.trim():"";return a||null},{error:s}=await e.from("products").update({meta_title:i(r.meta_title),meta_description:i(r.meta_description),custom_canonical:i(r.custom_canonical),updated_at:new Date().toISOString()}).eq("id",t);if(s)throw s}async function x(e,t,r){const{error:i}=await e.from("products").update({is_taxable:r,updated_at:new Date().toISOString()}).eq("id",t);if(i)throw i}async function F(e,t,r){const i=new Date().toISOString(),{data:s}=await e.from("products").select("sku, sale_price, sale_prices").eq("id",t).maybeSingle(),o=s?.sku??r.sku,{data:a}=await e.from("products").select("id").eq("sku",o),c=(a??[]).map(n=>n.id);c.length===0&&c.push(t);const{error:_}=await e.from("products").update({sale_price:s?.sale_price??null,sale_prices:s?.sale_prices??null,sale_start_at:r.sale_start_at??null,sale_end_at:r.sale_end_at??null,updated_at:i}).in("id",c);if(_)throw _;const l=r.variants??[];if(l.length===0)return;const{data:p}=await e.from("product_variants").select("sku, sale_price, sale_prices").eq("product_id",t),f=new Map((p??[]).map(n=>[n.sku,n]));for(const n of l){const u=f.get(n.sku);if(!u)continue;const{error:d}=await e.from("product_variants").update({sale_price:u.sale_price??null,sale_prices:u.sale_prices??null,sale_start_at:n.sale_start_at??null,sale_end_at:n.sale_end_at??null,updated_at:i}).eq("sku",n.sku).in("product_id",c);if(d)throw d}}async function A(e,{page:t=1,limit:r=10,offset:i,search:s="",languageId:o,categoryId:a,categoryIds:c,productIds:_,translationGroupIds:l,status:p="active"}={}){const f=r>0,n=typeof i=="number"?Math.max(0,i):(t-1)*r,u=n+r-1;let d=e.from("products").select("id, title, meta_title, meta_description, average_rating, total_reviews, sku, upc, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, is_taxable, product_type, payment_provider, short_description, stock, status, slug, language_id, translation_group_id, freemius_product_id, freemius_plan_id, trial_period_days, trial_requires_payment_method, product_media(media(file_path, object_key)), product_variants(id, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at), freemius_plans(id, name, title, freemius_pricing(id, license_quota, api_monthly_price, api_annual_price, api_lifetime_price, override_monthly_price, override_annual_price, override_lifetime_price, is_active)), product_categories(category:categories(id, name, slug, description, name_translations, description_translations))",{count:"exact"}).order("created_at",{ascending:!1});if(f&&(d=d.range(n,u)),p!=="all"&&(d=d.eq("status",p)),o&&(d=d.eq("language_id",o)),_){if(_.length===0)return{data:[],error:null,count:0};d=d.in("id",_)}if(l){if(l.length===0)return{data:[],error:null,count:0};d=d.in("translation_group_id",l)}const g=c?.length?c:a?[a]:[];if(g.length>0){const{data:y,error:m}=await e.from("product_categories").select("product_id").in("category_id",g);if(m)return{data:[],error:m,count:0};const h=Array.from(new Set((y||[]).map(v=>v.product_id).filter(Boolean)));if(h.length===0)return{data:[],error:null,count:0};d=d.in("id",h)}return s&&(d=d.or(`title.ilike.%${s}%,sku.ilike.%${s}%`)),d}async function T(e,t){return e.from("products").select(`
2
- *,
3
- languages (
4
- code
5
- ),
6
- product_media (
7
- media_id,
8
- sort_order,
9
- media (
10
- id,
11
- file_path,
12
- object_key,
13
- file_name,
14
- blur_data_url,
15
- width,
16
- height
17
- )
18
- ),
19
- product_variants (
20
- id,
21
- sku,
22
- upc,
23
- main_media_id,
24
- price,
25
- prices,
26
- sale_price,
27
- sale_prices,
28
- sale_start_at,
29
- sale_end_at,
30
- scheduled_price,
31
- scheduled_prices,
32
- scheduled_price_at,
33
- stock_quantity,
34
- media:main_media_id (
35
- id,
36
- file_path,
37
- object_key,
38
- description
39
- ),
40
- variant_attribute_mapping (
41
- attribute_term_id,
42
- product_attribute_terms (
43
- id,
44
- attribute_id,
45
- value,
46
- slug,
47
- sort_order,
48
- value_translations,
49
- product_attributes (
50
- id,
51
- name,
52
- slug,
53
- name_translations
54
- )
55
- )
56
- )
57
- ),
58
- freemius_plans (
59
- id,
60
- name,
61
- title,
62
- freemius_pricing (
63
- id,
64
- license_quota,
65
- api_monthly_price,
66
- api_annual_price,
67
- api_lifetime_price,
68
- override_monthly_price,
69
- override_annual_price,
70
- override_lifetime_price,
71
- is_active
72
- )
73
- ),
74
- product_categories (
75
- category:categories (
76
- id,
77
- name,
78
- slug,
79
- description,
80
- name_translations,
81
- description_translations
82
- )
83
- )
84
- `).eq("id",t).single()}async function R(e,t,r){const{data:i,error:s}=await e.from("products").select(`
85
- *,
86
- languages (
87
- id,
88
- code,
89
- is_default
90
- ),
91
- product_media (
92
- media_id,
93
- sort_order,
94
- media (
95
- id,
96
- file_path,
97
- object_key,
98
- file_name,
99
- blur_data_url,
100
- width,
101
- height,
102
- variants
103
- )
104
- ),
105
- product_variants (
106
- id,
107
- sku,
108
- upc,
109
- main_media_id,
110
- price,
111
- prices,
112
- sale_price,
113
- sale_prices,
114
- sale_start_at,
115
- sale_end_at,
116
- scheduled_price,
117
- scheduled_prices,
118
- scheduled_price_at,
119
- stock_quantity,
120
- media:main_media_id (
121
- id,
122
- file_path,
123
- object_key,
124
- description
125
- ),
126
- variant_attribute_mapping (
127
- attribute_term_id,
128
- product_attribute_terms (
129
- id,
130
- attribute_id,
131
- value,
132
- slug,
133
- sort_order,
134
- value_translations,
135
- product_attributes (
136
- id,
137
- name,
138
- slug,
139
- name_translations
140
- )
141
- )
142
- )
143
- ),
144
- freemius_plans (
145
- id,
146
- name,
147
- title,
148
- freemius_pricing (
149
- id,
150
- license_quota,
151
- api_monthly_price,
152
- api_annual_price,
153
- api_lifetime_price,
154
- override_monthly_price,
155
- override_annual_price,
156
- override_lifetime_price,
157
- is_active
158
- )
159
- ),
160
- product_categories (
161
- category:categories (
162
- id,
163
- name,
164
- slug,
165
- description,
166
- name_translations,
167
- description_translations
168
- )
169
- )
170
- `).eq("slug",t);if(s)return{data:null,error:s};if(!i||i.length===0)return{data:null,error:{message:"Product not found",code:"PGRST116"}};let o=null;return r&&(o=i.find(a=>(Array.isArray(a.languages)?a.languages[0]:a.languages)?.code===r)),o||(o=i.find(a=>(Array.isArray(a.languages)?a.languages[0]:a.languages)?.is_default)),o||(o=i.find(a=>(Array.isArray(a.languages)?a.languages[0]:a.languages)?.code==="en")),o||(o=i[0]),{data:o,error:null}}async function $(e,t){const{data:r,error:i}=await e.rpc("upsert_product_with_variants",{product_payload:S(t)});if(i||!r)throw i||new Error("Failed to create product");if(t.product_media&&t.product_media.length>0){const o=t.product_media.map((a,c)=>({product_id:r,media_id:a.media_id,sort_order:c}));await e.from("product_media").insert(o)}else t.media_id&&await e.from("product_media").insert({product_id:r,media_id:t.media_id,sort_order:0});await x(e,r,t.is_taxable),await j(e,r,t),await F(e,r,t),await P.syncSharedInventoryForSavedProduct(r,t),t.category_ids!==void 0&&await k(e,r,t.category_ids);const{data:s}=await e.from("products").select("*").eq("id",r).single();return s}async function D(e,t,r){const{data:i}=await e.from("product_media").select("media_id").eq("product_id",t),s=i?.map(n=>n.media_id)||[],{data:o,error:a}=await e.rpc("upsert_product_with_variants",{product_payload:S(r,t)});if(a||!o)throw a||new Error("Failed to update product");if(r.product_media){if(await e.from("product_media").delete().eq("product_id",t),r.product_media.length>0){const n=r.product_media.map((u,d)=>({product_id:t,media_id:u.media_id,sort_order:d}));await e.from("product_media").insert(n)}}else r.media_id&&(await e.from("product_media").delete().eq("product_id",t),await e.from("product_media").insert({product_id:t,media_id:r.media_id,sort_order:0}));await x(e,o,r.is_taxable),await j(e,o,r),await F(e,o,r);const c=r.product_media?r.product_media.map(n=>n.media_id):r.media_id?[r.media_id]:[],_=r.explicitly_removed_media_ids||[],l=s.filter(n=>!c.includes(n)),p=Array.from(new Set([...l,..._]));if(p.length>0)for(const n of p){const{count:u}=await e.from("product_media").select("*",{count:"exact",head:!0}).eq("media_id",n);if(u&&u>0)continue;const{count:d}=await e.from("posts").select("*",{count:"exact",head:!0}).eq("feature_image_id",n);if(d&&d>0)continue;const{count:g}=await e.from("logos").select("*",{count:"exact",head:!0}).eq("media_id",n);if(g&&g>0)continue;const{count:y}=await e.from("product_variants").select("*",{count:"exact",head:!0}).eq("main_media_id",n);if(y&&y>0)continue;const{data:m}=await e.from("media").select("object_key, variants").eq("id",n).single();if(m){const h=[m.object_key];m.variants&&Array.isArray(m.variants)&&m.variants.forEach(v=>{v.objectKey&&h.push(v.objectKey)}),await b.deleteMediaFiles(h),await e.from("media").delete().eq("id",n)}}await P.syncSharedInventoryForSavedProduct(o,r),r.category_ids!==void 0&&await k(e,t,r.category_ids);const{data:f}=await e.from("products").select("*").eq("id",o).single();return f}async function N(e,t){const{error:r}=await e.from("products").delete().eq("id",t);if(r)throw r;return!0}async function O(e,t,r){const{data:i,error:s}=await e.from("products").select("*").eq("id",r).single();if(s||!i)throw new Error(s?.message||"Source product not found");const{data:o,error:a}=await e.from("products").select("language_id").eq("id",t).single();if(a||!o)throw new Error(a?.message||"Target product not found");const{error:c}=await e.from("products").update({title:i.title,short_description:i.short_description,description_json:i.description_json}).eq("id",t);if(c)throw c;const{data:_,error:l}=await e.from("blocks").select("*").eq("product_id",r).order("order",{ascending:!0});if(l)throw l;if(await e.from("blocks").delete().eq("product_id",t),_&&_.length>0){const f=_.map(u=>{const{id:d,created_at:g,updated_at:y,...m}=u;return{...m,product_id:t,language_id:o.language_id}}),{error:n}=await e.from("blocks").insert(f);if(n)throw n}await e.from("product_drafts").delete().eq("product_id",t),await e.from("product_media").delete().eq("product_id",t);const{data:p}=await e.from("product_media").select("media_id, sort_order").eq("product_id",r);if(p&&p.length>0){const f=p.map(n=>({product_id:t,media_id:n.media_id,sort_order:n.sort_order}));await e.from("product_media").insert(f)}return{success:!0}}async function B(e,t,r,i=[],s=[]){const{data:o}=await e.from("languages").select("id").eq("code",r).single();if(!o)return{data:[],error:"Language not found"};const a=[];t.length>0&&a.push(`translation_group_id.in.(${t.join(",")})`),i.length>0&&a.push(`sku.in.(${i.map(l=>`"${l}"`).join(",")})`),s.length>0&&a.push(`id.in.(${s.join(",")})`);let c=e.from("products").select(`
171
- id,
172
- title,
173
- sku,
174
- price,
175
- prices,
176
- sale_price,
177
- sale_prices,
178
- sale_start_at,
179
- sale_end_at,
180
- scheduled_price,
181
- scheduled_prices,
182
- scheduled_price_at,
183
- stock,
184
- slug,
185
- language_id,
186
- product_type,
187
- payment_provider,
188
- freemius_product_id,
189
- freemius_plan_id,
190
- trial_period_days,
191
- trial_requires_payment_method,
192
- is_taxable,
193
- product_media (
194
- media (
195
- file_path,
196
- object_key
197
- )
198
- ),
199
- product_variants (
200
- id,
201
- sku,
202
- upc,
203
- main_media_id,
204
- price,
205
- prices,
206
- sale_price,
207
- sale_prices,
208
- sale_start_at,
209
- sale_end_at,
210
- scheduled_price,
211
- scheduled_prices,
212
- scheduled_price_at,
213
- stock_quantity,
214
- media:main_media_id (
215
- file_path,
216
- object_key,
217
- description
218
- ),
219
- variant_attribute_mapping (
220
- attribute_term_id,
221
- product_attribute_terms (
222
- id,
223
- attribute_id,
224
- value,
225
- slug,
226
- sort_order,
227
- value_translations,
228
- product_attributes (
229
- id,
230
- name,
231
- slug,
232
- name_translations
233
- )
234
- )
235
- )
236
- ),
237
- translation_group_id
238
- `).eq("language_id",o.id).eq("status","active").or(C.buildPublishedAtOrFilter());return a.length>0&&(c=c.or(a.join(","))),await c.order("id")}async function k(e,t,r){const{data:i}=await e.from("products").select("translation_group_id").eq("id",t).single();if(!i||!i.translation_group_id){if(await e.from("product_categories").delete().eq("product_id",t),r.length>0){const a=r.map(c=>({product_id:t,category_id:c}));await e.from("product_categories").insert(a)}return}const{data:s}=await e.from("products").select("id").eq("translation_group_id",i.translation_group_id),o=s&&s.length>0?s.map(a=>a.id):[t];if(await e.from("product_categories").delete().in("product_id",o),r.length>0){const a=[];for(const c of o)for(const _ of r)a.push({product_id:c,category_id:_});await e.from("product_categories").insert(a)}}exports.copyProductFromLanguage=O;exports.createProduct=$;exports.deleteProduct=N;exports.fetchTranslatedProductsForCartInternal=B;exports.getProduct=T;exports.getProductBySlug=R;exports.getProducts=A;exports.syncCategoriesForTranslationGroup=k;exports.updateProduct=D;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),e=require("react"),r=e.createContext(void 0),c=({product:t,children:o})=>u.jsx(r.Provider,{value:{product:t},children:o}),n=()=>{const t=e.useContext(r);if(!t)throw new Error("useProduct must be used within a ProductProvider. Ensure the component is wrapped in a ProductProvider.");return t.product};exports.ProductProvider=c;exports.useProduct=n;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./zod-config.cjs.js");const e=require("zod"),u=e.z.enum(["physical","digital"]).or(e.z.literal("")).refine(r=>r!=="",{message:"Product type is required"}).transform(r=>r),s=e.z.record(e.z.string().regex(/^[A-Z]{3}$/,"Currency code must be ISO 4217"),e.z.coerce.number().min(0,"Prices must be non-negative")),l=e.z.record(e.z.string().regex(/^[A-Z]{3}$/,"Currency code must be ISO 4217"),e.z.coerce.number().min(0,"Sale prices must be non-negative").nullable()),n=e.z.string().trim().refine(r=>r===""||!Number.isNaN(Date.parse(r)),{message:"Must be a valid date and time"}).transform(r=>r===""?null:r).nullable().optional();function o(r,a){if(!r||!a)return!0;const t=Date.parse(r),i=Date.parse(a);return Number.isNaN(t)||Number.isNaN(i)?!0:t<i}const c=e.z.object({attribute_id:e.z.string().uuid(),attribute_name:e.z.string(),term_id:e.z.string().uuid(),term_value:e.z.string(),term_slug:e.z.string().optional()}),m=e.z.object({id:e.z.string().uuid().optional(),combination_key:e.z.string().min(1),sku:e.z.string().min(1,"Variant SKU is required"),upc:e.z.string().optional().nullable(),price:e.z.coerce.number().min(0,"Variant price must be non-negative"),prices:s.default({}),sale_price:e.z.coerce.number().min(0,"Variant sale price must be non-negative").optional().nullable(),sale_prices:l.default({}),sale_start_at:n,sale_end_at:n,stock_quantity:e.z.coerce.number().int().min(0,"Variant stock must be a non-negative integer"),main_media_id:e.z.string().uuid().optional().nullable(),main_image_url:e.z.string().optional().nullable(),attribute_term_ids:e.z.array(e.z.string().uuid()).min(1),selected_options:e.z.array(c).min(1),label:e.z.string().min(1)}).refine(r=>r.sale_price===null||r.sale_price===void 0||r.sale_price<=r.price,{message:"Variant sale price cannot exceed the regular price",path:["sale_price"]}).refine(r=>Object.entries(r.sale_prices||{}).every(([a,t])=>{if(t==null)return!0;const i=r.prices?.[a];return typeof i=="number"?t<=i:!0}),{message:"Variant sale prices cannot exceed regular prices",path:["sale_prices"]}).refine(r=>o(r.sale_start_at,r.sale_end_at),{message:"Sale end must be after the sale start",path:["sale_end_at"]}),p=e.z.object({attribute_id:e.z.string().uuid(),term_ids:e.z.array(e.z.string().uuid())}),d=e.z.object({product_type:u,payment_provider:e.z.enum(["stripe","freemius"]),title:e.z.string().min(1,"Title is required"),slug:e.z.string().min(1,"Slug is required").regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Slug must be lowercase alphanumeric with hyphens"),sku:e.z.string().min(1,"SKU is required"),upc:e.z.string().optional().nullable(),price:e.z.coerce.number().min(0,"Price must be non-negative"),prices:s.default({}),sale_price:e.z.coerce.number().min(0,"Sale price must be non-negative").optional().nullable(),sale_prices:l.default({}),sale_start_at:n,sale_end_at:n,stock:e.z.coerce.number().int().min(0,"Stock must be a non-negative integer"),meta_title:e.z.string().optional().nullable(),meta_description:e.z.string().optional().nullable(),custom_canonical:e.z.string().optional().nullable(),short_description:e.z.string().optional(),description_json:e.z.any().optional(),freemius_plan_id:e.z.string().optional(),freemius_product_id:e.z.string().optional(),trial_period_days:e.z.coerce.number().int().min(0,"Trial period must be zero or greater").default(0),trial_requires_payment_method:e.z.boolean().default(!1),media_id:e.z.string().optional(),product_media:e.z.array(e.z.object({media_id:e.z.string()})).optional(),category_ids:e.z.array(e.z.string().uuid()).optional(),is_taxable:e.z.boolean(),status:e.z.enum(["draft","active","archived"]),language_id:e.z.coerce.number().int().min(1,"Language is required"),translation_group_id:e.z.string().uuid().optional().or(e.z.literal("")).transform(r=>r===""?void 0:r),explicitly_removed_media_ids:e.z.array(e.z.string()).optional(),variation_attributes:e.z.array(p).optional(),variants:e.z.array(m).optional()}).refine(r=>r.sale_price===null||r.sale_price===void 0||r.sale_price<=r.price,{message:"Sale price cannot exceed the regular price",path:["sale_price"]}).refine(r=>Object.entries(r.sale_prices||{}).every(([a,t])=>{if(t==null)return!0;const i=r.prices?.[a];return typeof i=="number"?t<=i:!0}),{message:"Sale prices cannot exceed regular prices",path:["sale_prices"]}).refine(r=>o(r.sale_start_at,r.sale_end_at),{message:"Sale end must be after the sale start",path:["sale_end_at"]});exports.productSchema=d;
@@ -1,5 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("@supabase/supabase-js"),Z=require("crypto"),oe=require("@freemius/sdk"),ce=require("../payment-config.cjs.js"),ae=require("../customer.cjs.js"),Q=require("../coupon-server.cjs.js"),G=require("../customer-addresses.cjs.js"),j=require("../currency.cjs.js");function i(e){const r=process.env[e];if(!r)return null;const t=r.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).trim():t}function ue(e){const r=e?.trim();if(!r)return{firstName:null,lastName:null};const[t,...s]=r.split(/\s+/);return{firstName:t||null,lastName:s.length>0?s.join(" "):null}}function ee(e){if(e==null||e==="")return 0;const r=Number(e);return!Number.isFinite(r)||r<=0?0:Math.round(r)}function le(e){return e===!0||e===1||e==="1"||e==="true"}function de(e,r){const t=e?.[r];return Array.isArray(t)?t:t&&typeof t=="object"?[t]:[]}function H(e,r){for(const t of r){const s=de(e,t);if(s.length>0)return s}return Array.isArray(e)?e:[]}function k(e){if(e==null||e==="")return null;const r=Number(e);return Number.isFinite(r)?r:null}function pe(e){return e===null?0:e>5e3?(console.warn(`[Freemius Sync] Suspiciously high price detected: ${e}. Assuming it is already in cents.`),Math.round(e)):Math.round(e*100)}function _e(e){const r=Number(e);return!Number.isFinite(r)||r<1?1:Math.round(r)}function re(){const e=i("FREEMIUS_CHECKOUT_PRODUCTS_JSON");if(!e)return null;try{const r=JSON.parse(e);return r&&typeof r=="object"?r:null}catch(r){return console.error("[Freemius Checkout] Failed to parse FREEMIUS_CHECKOUT_PRODUCTS_JSON:",r),null}}function te(e){const r=re(),t=String(e),s=r?.[t],c=i("FREEMIUS_PRODUCT_ID"),d=i("FREEMIUS_ECOMMERCE_SANDBOX_PUBLIC_KEY"),f=i("FREEMIUS_ECOMMERCE_SANDBOX_SECRET_KEY");return s?.publicKey?{publicKey:s.publicKey,secretKey:s.secretKey??null,apiKey:s.apiKey??null,source:"product-map"}:process.env.FREEMIUS_SANDBOX_ENABLED==="true"&&c&&c===t&&d?{publicKey:d,secretKey:f,apiKey:i("FREEMIUS_API_KEY"),source:"single-product-sandbox-env"}:c&&c===t&&i("FREEMIUS_PUBLIC_KEY")?{publicKey:i("FREEMIUS_PUBLIC_KEY"),secretKey:i("FREEMIUS_SECRET_KEY"),apiKey:i("FREEMIUS_API_KEY"),source:"single-product-env"}:{publicKey:i("FREEMIUS_PUBLIC_KEY"),secretKey:i("FREEMIUS_SECRET_KEY"),apiKey:i("FREEMIUS_API_KEY"),source:"legacy-env"}}async function me(e){if(!e.apiKey)throw new Error("Missing Freemius API key for SDK sandbox generation.");return new oe.Freemius({productId:Number(e.productId),apiKey:e.apiKey,secretKey:e.secretKey,publicKey:e.publicKey}).checkout.getSandboxParams()}class fe{getProviderName(){return"Freemius"}async createCheckoutSession({items:r,customerEmail:t,customerPhone:s,userId:c,billingAddress:d,shippingAddress:f,currencyCode:m,couponCode:b,couponContextItems:E}){const a=process.env.NEXT_PUBLIC_SUPABASE_URL||process.env.SUPABASE_URL,u=process.env.SUPABASE_SERVICE_ROLE_KEY||process.env.SUPABASE_SECRET_KEY;if(!a||!u)return{error:"Missing Supabase credentials for checkout (Service Key required).",url:null};const p=V.createClient(a,u);if(!r||r.length===0)return{error:"Cart is empty",url:null};if(r.length!==1)return{error:"Freemius items must be checked out one at a time.",url:null};const{data:g,error:K}=await p.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}),$=g??[];if(K||$.length===0)return{error:"Failed to resolve store currencies",url:null};const X=j.getDefaultCurrency($),w=$.find(l=>l.code===(m||"").toUpperCase())??X,y=r[0],{data:o,error:M}=await p.from("products").select("id, title, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, freemius_plan_id, freemius_product_id, trial_period_days, trial_requires_payment_method").eq("id",y.product_id).single();if(M||!o)return{error:"Product not found",url:null};const R=o.freemius_plan_id,P=o.freemius_product_id;if(!R||!P)return{error:"Product is not configured for Freemius checkout (missing Plan ID or Product ID)",url:null};const D=j.resolveEffectivePriceForCurrency({prices:o.prices||{},salePrices:o.sale_prices||{},fallbackPrice:o.price,fallbackSalePrice:o.sale_price,saleStartAt:o.sale_start_at,saleEndAt:o.sale_end_at,scheduledPrice:o.scheduled_price,scheduledPrices:o.scheduled_prices||{},scheduledPriceAt:o.scheduled_price_at,currencyCode:w.code,currencies:$}),q=D.sale_price??D.price,N=j.isSaleWindowActive({saleStartAt:o.sale_start_at,saleEndAt:o.sale_end_at}),S=q*y.quantity;let n=null,_=0;if(b){const l=await Q.getCouponQuote({client:p,code:b,items:E&&E.length>0?E:r,currencyCode:w.code});if(!l.success)return{error:l.error,errorKey:l.errorKey,errorStatus:400,url:null};n=l.quote,_=Math.min(S,n.lineDiscounts.filter(v=>v.product_id===o.id).reduce((v,L)=>v+L.discount,0))}const F=ee(o.trial_period_days),U=F>0?y.trial_preference?y.trial_preference:o.trial_requires_payment_method?"paid":"free":null,O="pending",h=ue(d?.recipient_name??null),{data:Y,error:J}=await p.from("orders").insert({status:O,total:Math.max(0,S-_),currency:w.code,exchange_rate_at_purchase:w.exchange_rate,subtotal:S,discount_total:_,coupon_id:n?.couponId??null,coupon_code:n?.code??null,discount_details:n?{code:n.code,discount_type:n.discountType,discount_amount:n.discountAmount,provider:"freemius",provider_discounts:n.providerDiscounts,line_discounts:n.lineDiscounts,final_amount_owned_by:"freemius"}:null,provider:"freemius",freemius_product_id:String(P),freemius_plan_id:String(R),user_id:c||null,customer_details:ae.normalizeOrderCustomerDetails({email:t,phone:s,name:d?.recipient_name,billing:d,shipping:f})}).select("id").single();if(J||!Y)return console.error("Failed to create pending order:",J),{error:"Failed to initiate order",url:null};const{error:W}=await p.from("order_items").insert([{order_id:Y.id,product_id:o.id,quantity:y.quantity,price_at_purchase:q}]);if(W&&console.error("Failed to insert order items:",W),c)try{await G.upsertDefaultUserAddresses({userId:c,billingAddress:d,shippingAddress:f,client:p}),await G.fillMissingUserProfileCheckoutDetails({userId:c,fullName:d?.recipient_name??f?.recipient_name??null,phone:s,client:p})}catch(l){console.error("Failed to sync checkout profile defaults before checkout:",l)}n&&await Q.recordCouponRedemption({client:p,quote:n,orderId:Y.id,provider:"freemius",discountTotal:_,userId:c,customerEmail:t,metadata:{currency:w.code,subtotal:S,final_amount_owned_by:"freemius"}}),await ce.hydrateFreemiusEnvFromDb();const B=process.env.FREEMIUS_SANDBOX_ENABLED==="true",A=te(P),I=A.publicKey,x=A.secretKey,z=A.apiKey;if(!I||B&&!x)return console.error("Freemius checkout blocked: missing credentials (PUBLIC_KEY or SECRET_KEY) in CMS → Payments or environment."),{error:"This store is not able to take payments right now. Please contact the seller to complete your purchase.",errorKey:"ecommerce.checkout_payments_unavailable",errorStatus:503,url:null};if(B&&A.source==="legacy-env"){const l=i("FREEMIUS_PRODUCT_ID"),v=!!i("FREEMIUS_ECOMMERCE_SANDBOX_PUBLIC_KEY"),L=!!i("FREEMIUS_ECOMMERCE_SANDBOX_SECRET_KEY");console.warn(`[Freemius Checkout] Sandbox is enabled for product ${P}, but no product-scoped checkout credentials were selected. Falling back to legacy FREEMIUS_PUBLIC_KEY/FREEMIUS_SECRET_KEY may open live checkout instead of sandbox.`,{configuredProductId:l,productIdsMatch:l===String(P),hasSandboxOverridePublicKey:v,hasSandboxOverrideSecretKey:L,hasCheckoutProductsJson:!!i("FREEMIUS_CHECKOUT_PRODUCTS_JSON")})}let T=!1;if(B&&x&&I)try{T=await me({productId:P,publicKey:I,secretKey:x,apiKey:z})}catch(l){console.warn("Freemius Checkout - SDK sandbox generation failed. Falling back to manual token generation.",l,{credentialSource:A.source,hasApiKey:!!z});const v=Math.floor(Date.now()/1e3).toString(),L=`${v}${P}${x}${I}checkout`,ie=Z.createHash("md5").update(L).digest("hex");T={ctx:v,token:ie}}const C=new URL(`https://checkout.freemius.com/app/${P}/plan/${R}/`);if(B&&x&&I?(C.searchParams.append("sandbox",T.token),C.searchParams.append("s_ctx_ts",T.ctx)):B&&C.searchParams.append("sandbox","true"),t&&C.searchParams.append("user_email",t),h.firstName&&C.searchParams.append("user_firstname",h.firstName),h.lastName&&C.searchParams.append("user_lastname",h.lastName),C.searchParams.append("currency",w.code.toLowerCase()),y.billing_cycle&&C.searchParams.append("billing_cycle",y.billing_cycle),U&&C.searchParams.append("trial",U),n)C.searchParams.append("coupon",n.code);else if(N){const{data:l}=await p.from("product_freemius_sale_coupons").select("freemius_coupon_code, is_active, starts_at, ends_at, sync_status").eq("product_id",o.id).maybeSingle();l?.is_active&&l.sync_status==="synced"&&l.freemius_coupon_code&&j.isSaleWindowActive({saleStartAt:l.starts_at,saleEndAt:l.ends_at})&&C.searchParams.append("coupon",l.freemius_coupon_code)}return{url:C.toString(),customProps:{provider:"freemius",plugin_id:P,plan_id:R,public_key:I,user_email:t,user_firstname:h.firstName,user_lastname:h.lastName,credential_source:A.source,sandbox:T,billing_cycle:y.billing_cycle,trial:U,trial_period_days:F,trial_requires_payment_method:o.trial_requires_payment_method,initial_order_status:O,coupon:n?.code??null,order_id:Y.id}}}}async function ne(e,r,t,s){const d=new Date().toUTCString().replace("GMT","+0000"),f=`GET
2
-
3
-
4
- ${d}
5
- ${e}`,m=Z.createHmac("sha256",s).update(f).digest("hex"),b=Buffer.from(m).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),E=`FS ${r}:${t}:${b}`,a=await fetch(`https://api.freemius.com${e}`,{headers:{Authorization:E,Date:d,Accept:"application/json"}});if(!a.ok){const u=await a.text();throw console.error(`[Freemius API] [ERROR] ${e} returned ${a.status}: ${u}`),new Error(`Freemius API failed on ${e}: ${a.status} - ${u}`)}return a.json()}async function Ee(){const e=i("FREEMIUS_DEVELOPER_ID"),r=i("FREEMIUS_PUBLIC_KEY"),t=i("FREEMIUS_SECRET_KEY"),s=process.env.NEXT_PUBLIC_SUPABASE_URL||process.env.SUPABASE_URL,c=process.env.SUPABASE_SERVICE_ROLE_KEY||process.env.SUPABASE_SECRET_KEY;if(!e||!r||!t||!s||!c)throw new Error("Missing necessary environment variables for Freemius Sync.");const d=V.createClient(s,c,{auth:{autoRefreshToken:!1,persistSession:!1}}),f=m=>ne(m,e,r,t);try{console.log(`[Freemius Sync] Fetching all plugins for developer ${e}...`);const m=await f(`/v1/developers/${e}/plugins.json`),b=H(m,["plugins","plugin"]);console.log(`[Freemius Sync] Found ${b.length} plugins. Syncing plans...`);let E=0;const{data:a}=await d.from("languages").select("id").eq("code","en").single(),u=a?.id;if(!u)throw new Error("English language not found in database. Cannot sync products.");for(const p of b){const g=p.id?.toString();if(!g){console.warn("[Freemius Sync] Skipping plugin without an id:",p);continue}const K=await se(d,e,g,p.title||p.name||`Freemius Product ${g}`,f,u);E+=K}return{success:!0,count:E}}catch(m){throw console.error("[Freemius Sync] Global Error:",m),m}}async function ge(e){const r=i("FREEMIUS_DEVELOPER_ID"),t=i("FREEMIUS_PUBLIC_KEY"),s=i("FREEMIUS_SECRET_KEY"),c=process.env.NEXT_PUBLIC_SUPABASE_URL||process.env.SUPABASE_URL,d=process.env.SUPABASE_SERVICE_ROLE_KEY||process.env.SUPABASE_SECRET_KEY;if(!r||!t||!s||!c||!d)throw new Error("Missing environment variables for Freemius Sync.");const f=V.createClient(c,d),m=g=>ne(g,r,t,s),{data:b}=await f.from("languages").select("id").eq("code","en").single(),E=b?.id;if(!E)throw new Error("English language not found in database. Cannot sync products.");const a=await m(`/v1/developers/${r}/plugins/${e}.json`),u=a.plugin??a;return{success:!0,count:await se(f,r,e,u.title||u.name||`Freemius Product ${e}`,m,E)}}async function se(e,r,t,s,c,d){console.log(`[Freemius Sync] Fetching plans for plugin: ${s} (${t})...`);let f=0;try{const m=`/v1/developers/${r}/plugins/${t}/plans.json`,b=await c(m),E=H(b,["plans","plan"]);console.log(`[Freemius Sync] Received ${E.length} plans for plugin ${t}.`);for(const a of E){const u=a.id?.toString();if(!u){console.warn("[Freemius Sync] Skipping plan without an id:",a);continue}const p=a.name||a.title||u,g=a.title||p;console.log(`[Freemius Sync] Processing plan: ${g} (${u})...`);let K=a;if(K.trial_period===void 0||K.is_require_subscription===void 0)try{const n=`/v1/developers/${r}/plugins/${t}/plans/${u}.json`,_=await c(n),F=_.plan??_;K={...K,...F}}catch(n){console.warn(`[Freemius Sync] Could not fetch trial details for plan ${u}:`,n instanceof Error?n.message:n)}const $=ee(K.trial_period),X=$>0&&le(K.is_require_subscription);let w=0,y=[];try{const n=`/v1/developers/${r}/plugins/${t}/plans/${u}/pricing.json`,_=await c(n);if(y=H(_,["pricing","prices","pricings"]),y.length>0){const F=y[0],U=k(F.annual_price)??k(F.monthly_price)??k(F.lifetime_price);w=pe(U)}console.log(`[Freemius Sync] Plan: ${g} -> Resolved Price (cents): ${w}`)}catch(n){console.warn(`[Freemius Sync] Could not fetch pricing for plan ${u}:`,n instanceof Error?n.message:n)}const o=`${s}-${g}`.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,""),M={title:`${s} - ${g}`,slug:o,short_description:a.description||"",price:w,product_type:"digital",payment_provider:"freemius",freemius_plan_id:u,freemius_product_id:t,trial_period_days:$,trial_requires_payment_method:X,status:"active",stock:999,sku:`FM-${t}-${u}`,language_id:d},{data:R,error:P}=await e.from("products").upsert(M,{onConflict:"language_id, sku"}).select();if(P||!R||R.length===0){console.error(`[Freemius Sync] Error upserting product ${M.sku}:`,P);continue}const D=R[0].id,{data:q,error:N}=await e.from("freemius_plans").select("id").eq("product_id",D).eq("name",p).maybeSingle();N&&console.warn(`[Freemius Sync] Could not check existing local plan for ${M.sku}:`,N.message||N);let S="";if(q){S=q.id;const{error:n}=await e.from("freemius_plans").update({title:g,updated_at:new Date().toISOString()}).eq("id",S);n&&console.warn(`[Freemius Sync] Could not update local plan ${S}:`,n.message||n)}else{const{data:n,error:_}=await e.from("freemius_plans").insert({product_id:D,name:p,title:g}).select("id").single();_&&console.warn(`[Freemius Sync] Could not insert local plan for ${M.sku}:`,_.message||_),n&&(S=n.id)}if(S&&y.length>0)for(const n of y){const _=_e(n.licenses??n.license_quota??n.quota),{data:F,error:U}=await e.from("freemius_pricing").select("id").eq("plan_id",S).eq("license_quota",_).maybeSingle();U&&console.warn(`[Freemius Sync] Could not check pricing for plan ${S}, quota ${_}:`,U.message||U);const O={api_monthly_price:k(n.monthly_price),api_annual_price:k(n.annual_price),api_lifetime_price:k(n.lifetime_price),updated_at:new Date().toISOString()};if(F){const{error:h}=await e.from("freemius_pricing").update(O).eq("id",F.id);h&&console.warn(`[Freemius Sync] Could not update pricing ${F.id}:`,h.message||h)}else{const{error:h}=await e.from("freemius_pricing").insert({plan_id:S,license_quota:_,...O});h&&console.warn(`[Freemius Sync] Could not insert pricing for plan ${S}, quota ${_}:`,h.message||h)}}console.log(`[Freemius Sync] Successfully fully synced product ${M.sku}.`),f++}}catch(m){console.error(`[Freemius Sync] Failed sync for plugin ${t}:`,m.message)}return f}exports.FreemiusProvider=fe;exports.parseFreemiusCheckoutCredentialsMap=re;exports.readFreemiusEnvValue=i;exports.resolveFreemiusCheckoutCredentials=te;exports.syncFreemiusProductsToSupabase=Ee;exports.syncSingleFreemiusProduct=ge;