@ubnt/store.core 10.0.0-pre-alpha.0 → 10.0.0-pre-alpha.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 (194) hide show
  1. package/lib/_virtual/_virtual_multi-entry.js +10 -12
  2. package/lib/_virtual/_virtual_multi-entry.js.map +1 -1
  3. package/lib/_virtual/_virtual_multi-entry.mjs +10 -12
  4. package/lib/_virtual/_virtual_multi-entry.mjs.map +1 -1
  5. package/lib/assets/clients.svg +9 -2
  6. package/lib/assets/clients2.svg +2 -9
  7. package/lib/assets/express7.jpg +0 -0
  8. package/lib/assets/express72.jpg +0 -0
  9. package/lib/assets/hdd.svg +2 -2
  10. package/lib/assets/hdd2.svg +2 -2
  11. package/lib/assets/icons/wizard/minus.svg.js +1 -1
  12. package/lib/assets/icons/wizard/minus.svg.mjs +2 -2
  13. package/lib/assets/keyFeatures/clients.svg.js +1 -1
  14. package/lib/assets/keyFeatures/clients.svg.mjs +2 -2
  15. package/lib/assets/keyFeatures/hdd.svg.js +1 -1
  16. package/lib/assets/keyFeatures/hdd.svg.mjs +2 -2
  17. package/lib/assets/keyFeatures/led.svg.js +1 -1
  18. package/lib/assets/keyFeatures/led.svg.mjs +2 -2
  19. package/lib/assets/keyFeatures/power.svg.js +1 -1
  20. package/lib/assets/keyFeatures/power.svg.mjs +2 -2
  21. package/lib/assets/keyFeatures/rack.svg.js +1 -1
  22. package/lib/assets/keyFeatures/rack.svg.mjs +2 -2
  23. package/lib/assets/keyFeatures/signal.svg.js +1 -1
  24. package/lib/assets/keyFeatures/signal.svg.mjs +2 -2
  25. package/lib/assets/keyFeatures/waterdrop.svg.js +1 -1
  26. package/lib/assets/keyFeatures/waterdrop.svg.mjs +2 -2
  27. package/lib/assets/led.svg +2 -9
  28. package/lib/assets/led2.svg +9 -2
  29. package/lib/assets/minus2.svg +13 -2
  30. package/lib/assets/minus3.svg +2 -13
  31. package/lib/assets/pause.svg +3 -3
  32. package/lib/assets/pause2.svg +3 -3
  33. package/lib/assets/power2.svg +3 -4
  34. package/lib/assets/power3.svg +4 -3
  35. package/lib/assets/rack2.svg +3 -3
  36. package/lib/assets/rack3.svg +3 -3
  37. package/lib/assets/signal.svg +2 -4
  38. package/lib/assets/signal2.svg +4 -2
  39. package/lib/assets/udmPro.jpg +0 -0
  40. package/lib/assets/udmPro2.jpg +0 -0
  41. package/lib/assets/udmProMax.jpg +0 -0
  42. package/lib/assets/udmProMax2.jpg +0 -0
  43. package/lib/assets/udmProSpecial.jpg +0 -0
  44. package/lib/assets/udmProSpecial2.jpg +0 -0
  45. package/lib/assets/udr2.jpg +0 -0
  46. package/lib/assets/udr3.jpg +0 -0
  47. package/lib/assets/udr7.jpg +0 -0
  48. package/lib/assets/udr72.jpg +0 -0
  49. package/lib/assets/waterdrop.svg +9 -2
  50. package/lib/assets/waterdrop2.svg +2 -9
  51. package/lib/components/MicrositeVideoSlideshow/MicrositeVideoSlideshow.js +1 -1
  52. package/lib/components/MicrositeVideoSlideshow/MicrositeVideoSlideshow.mjs +1 -1
  53. package/lib/components/MicrositeVideoSlideshow/assets/pause.svg.js +1 -1
  54. package/lib/components/MicrositeVideoSlideshow/assets/pause.svg.mjs +2 -2
  55. package/lib/components/ModelCompareV3/ModelComparePropertyValueGridItem.js +1 -1
  56. package/lib/components/ModelCompareV3/ModelComparePropertyValueGridItem.mjs +1 -1
  57. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/express7.jpg.js +5 -5
  58. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/express7.jpg.mjs +2 -2
  59. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmPro.jpg.js +5 -5
  60. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmPro.jpg.mjs +2 -2
  61. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProMax.jpg.js +5 -5
  62. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProMax.jpg.mjs +2 -2
  63. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProSpecial.jpg.js +5 -5
  64. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProSpecial.jpg.mjs +2 -2
  65. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udr.jpg.js +5 -5
  66. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udr.jpg.mjs +2 -2
  67. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udr7.jpg.js +5 -5
  68. package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udr7.jpg.mjs +2 -2
  69. package/lib/components/ModelCompareV3/assets/Consoles/express7.jpg.js +1 -1
  70. package/lib/components/ModelCompareV3/assets/Consoles/express7.jpg.mjs +2 -2
  71. package/lib/components/ModelCompareV3/assets/Consoles/udmPro.jpg.js +1 -1
  72. package/lib/components/ModelCompareV3/assets/Consoles/udmPro.jpg.mjs +2 -2
  73. package/lib/components/ModelCompareV3/assets/Consoles/udmProMax.jpg.js +1 -1
  74. package/lib/components/ModelCompareV3/assets/Consoles/udmProMax.jpg.mjs +2 -2
  75. package/lib/components/ModelCompareV3/assets/Consoles/udmProSpecial.jpg.js +1 -1
  76. package/lib/components/ModelCompareV3/assets/Consoles/udmProSpecial.jpg.mjs +2 -2
  77. package/lib/components/ModelCompareV3/assets/Consoles/udr.jpg.js +1 -1
  78. package/lib/components/ModelCompareV3/assets/Consoles/udr.jpg.mjs +2 -2
  79. package/lib/components/ModelCompareV3/assets/Consoles/udr7.jpg.js +1 -1
  80. package/lib/components/ModelCompareV3/assets/Consoles/udr7.jpg.mjs +2 -2
  81. package/lib/components/ModelCompareV3/assets/clients.svg.js +1 -1
  82. package/lib/components/ModelCompareV3/assets/clients.svg.mjs +2 -2
  83. package/lib/components/ModelCompareV3/assets/hdd.svg.js +1 -1
  84. package/lib/components/ModelCompareV3/assets/hdd.svg.mjs +2 -2
  85. package/lib/components/ModelCompareV3/assets/led.svg.js +1 -1
  86. package/lib/components/ModelCompareV3/assets/led.svg.mjs +2 -2
  87. package/lib/components/ModelCompareV3/assets/minus.svg.js +1 -1
  88. package/lib/components/ModelCompareV3/assets/minus.svg.mjs +2 -2
  89. package/lib/components/ModelCompareV3/assets/power.svg.js +1 -1
  90. package/lib/components/ModelCompareV3/assets/power.svg.mjs +2 -2
  91. package/lib/components/ModelCompareV3/assets/rack.svg.js +1 -1
  92. package/lib/components/ModelCompareV3/assets/rack.svg.mjs +2 -2
  93. package/lib/components/ModelCompareV3/assets/signal.svg.js +1 -1
  94. package/lib/components/ModelCompareV3/assets/signal.svg.mjs +2 -2
  95. package/lib/components/ModelCompareV3/assets/waterdrop.svg.js +1 -1
  96. package/lib/components/ModelCompareV3/assets/waterdrop.svg.mjs +2 -2
  97. package/lib/components/ModelCompareV3/data/CloudGateways.js +15 -15
  98. package/lib/components/ModelCompareV3/data/CloudGateways.mjs +10 -10
  99. package/lib/components/ModelCompareV3/data/products/express7.js +1 -1
  100. package/lib/components/ModelCompareV3/data/products/express7.mjs +1 -1
  101. package/lib/components/ModelCompareV3/data/products/udmPro.js +1 -1
  102. package/lib/components/ModelCompareV3/data/products/udmPro.mjs +1 -1
  103. package/lib/components/ModelCompareV3/data/products/udmProMax.js +1 -1
  104. package/lib/components/ModelCompareV3/data/products/udmProMax.mjs +1 -1
  105. package/lib/components/ModelCompareV3/data/products/udmProSpecial.js +1 -1
  106. package/lib/components/ModelCompareV3/data/products/udmProSpecial.mjs +1 -1
  107. package/lib/components/ModelCompareV3/data/products/udr.js +1 -1
  108. package/lib/components/ModelCompareV3/data/products/udr.mjs +1 -1
  109. package/lib/components/ModelCompareV3/data/products/udr7.js +1 -1
  110. package/lib/components/ModelCompareV3/data/products/udr7.mjs +1 -1
  111. package/lib/components/ModelCompareV3/data/properties/accessPowerMethod.js +1 -1
  112. package/lib/components/ModelCompareV3/data/properties/accessPowerMethod.mjs +1 -1
  113. package/lib/components/ModelCompareV3/data/properties/cellular.js +1 -1
  114. package/lib/components/ModelCompareV3/data/properties/cellular.mjs +1 -1
  115. package/lib/components/ModelCompareV3/data/properties/clientDevices.js +1 -1
  116. package/lib/components/ModelCompareV3/data/properties/clientDevices.mjs +1 -1
  117. package/lib/components/ModelCompareV3/data/properties/connectedDevices.js +1 -1
  118. package/lib/components/ModelCompareV3/data/properties/connectedDevices.mjs +1 -1
  119. package/lib/components/ModelCompareV3/data/properties/dataPlan.js +1 -1
  120. package/lib/components/ModelCompareV3/data/properties/dataPlan.mjs +1 -1
  121. package/lib/components/ModelCompareV3/data/properties/dcPowerOutput.js +1 -1
  122. package/lib/components/ModelCompareV3/data/properties/dcPowerOutput.mjs +1 -1
  123. package/lib/components/ModelCompareV3/data/properties/etherlighting.js +1 -1
  124. package/lib/components/ModelCompareV3/data/properties/etherlighting.mjs +1 -1
  125. package/lib/components/ModelCompareV3/data/properties/mounting.js +1 -1
  126. package/lib/components/ModelCompareV3/data/properties/mounting.mjs +1 -1
  127. package/lib/components/ModelCompareV3/data/properties/nvrHdd35Bay.js +1 -1
  128. package/lib/components/ModelCompareV3/data/properties/nvrHdd35Bay.mjs +1 -1
  129. package/lib/components/ModelCompareV3/data/properties/outdoorReady.js +1 -1
  130. package/lib/components/ModelCompareV3/data/properties/outdoorReady.mjs +1 -1
  131. package/lib/components/ModelCompareV3/data/properties/storage.js +1 -1
  132. package/lib/components/ModelCompareV3/data/properties/storage.mjs +1 -1
  133. package/lib/components/ModelCompareV3/data/properties/storageCapacity.js +1 -1
  134. package/lib/components/ModelCompareV3/data/properties/storageCapacity.mjs +1 -1
  135. package/lib/components/ModelCompareV3/data/properties/weatherproofing.js +1 -1
  136. package/lib/components/ModelCompareV3/data/properties/weatherproofing.mjs +1 -1
  137. package/lib/components/QuantityInput/QuantityInput.js +1 -1
  138. package/lib/components/QuantityInput/QuantityInput.mjs +1 -1
  139. package/lib/components/VideoPlayerNew/VideoPlayer.js +1 -1
  140. package/lib/components/VideoPlayerNew/VideoPlayer.mjs +1 -1
  141. package/lib/components/VideoPlayerNew/assets/pause.svg.js +1 -1
  142. package/lib/components/VideoPlayerNew/assets/pause.svg.mjs +2 -2
  143. package/lib/constants/shopify/keyFeatureIcons.js +7 -7
  144. package/lib/constants/shopify/keyFeatureIcons.mjs +7 -7
  145. package/lib/utils/index.d.ts +1 -2
  146. package/lib/utils/index.js +6 -8
  147. package/lib/utils/index.js.map +1 -1
  148. package/lib/utils/index.mjs +6 -8
  149. package/lib/utils/index.mjs.map +1 -1
  150. package/lib/utils/money/allocators/fixedAmount.js +44 -0
  151. package/lib/utils/money/allocators/fixedAmount.js.map +1 -0
  152. package/lib/utils/money/allocators/fixedAmount.mjs +42 -0
  153. package/lib/utils/money/allocators/fixedAmount.mjs.map +1 -0
  154. package/lib/utils/money/allocators/productAmount.js +75 -0
  155. package/lib/utils/money/allocators/productAmount.js.map +1 -0
  156. package/lib/utils/money/allocators/productAmount.mjs +73 -0
  157. package/lib/utils/money/allocators/productAmount.mjs.map +1 -0
  158. package/lib/utils/money/exchangeRate.js +27 -0
  159. package/lib/utils/money/exchangeRate.js.map +1 -0
  160. package/lib/utils/money/exchangeRate.mjs +23 -0
  161. package/lib/utils/money/exchangeRate.mjs.map +1 -0
  162. package/lib/utils/money/format.js +101 -0
  163. package/lib/utils/money/format.js.map +1 -0
  164. package/lib/utils/money/format.mjs +96 -0
  165. package/lib/utils/money/format.mjs.map +1 -0
  166. package/lib/utils/money/index.js +56 -0
  167. package/lib/utils/money/index.js.map +1 -0
  168. package/lib/utils/money/index.mjs +11 -0
  169. package/lib/utils/money/index.mjs.map +1 -0
  170. package/lib/utils/money/shipping.js +8 -0
  171. package/lib/utils/money/shipping.js.map +1 -0
  172. package/lib/utils/money/shipping.mjs +6 -0
  173. package/lib/utils/money/shipping.mjs.map +1 -0
  174. package/lib/utils/money/tax.js +59 -0
  175. package/lib/utils/money/tax.js.map +1 -0
  176. package/lib/utils/money/tax.mjs +51 -0
  177. package/lib/utils/money/tax.mjs.map +1 -0
  178. package/lib/utils/money/tax.private.js +56 -0
  179. package/lib/utils/money/tax.private.js.map +1 -0
  180. package/lib/utils/money/tax.private.mjs +52 -0
  181. package/lib/utils/money/tax.private.mjs.map +1 -0
  182. package/lib/utils/money/types.js +3 -0
  183. package/lib/utils/money/types.js.map +1 -0
  184. package/lib/utils/money/types.mjs +2 -0
  185. package/lib/utils/money/types.mjs.map +1 -0
  186. package/package.json +1 -1
  187. package/lib/utils/variant.d.ts +0 -8
  188. package/lib/utils/variant.test.d.ts +0 -1
  189. package/lib/utils/wattage.d.ts +0 -11
  190. package/lib/utils/wattage.js +0 -20
  191. package/lib/utils/wattage.js.map +0 -1
  192. package/lib/utils/wattage.mjs +0 -18
  193. package/lib/utils/wattage.mjs.map +0 -1
  194. package/lib/utils/wattage.test.d.ts +0 -1
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+
3
+ var currencies = require('@dinero.js/currencies');
4
+ var dinero_js = require('dinero.js');
5
+ var errors = require('../errors.js');
6
+ var constants = require('./constants.js');
7
+ var misc = require('./misc.js');
8
+ "use strict";
9
+ const getLocalizedCurrency = currencyCode => {
10
+ return currencyCode ? constants.localizedCurrencyLookup.get(currencyCode) : void 0;
11
+ };
12
+ const currencyFormatterCache = /* @__PURE__ */new Map();
13
+ const getCurrencyFormatter = (locale, currencyCode) => {
14
+ const cacheKey = `${locale}_${currencyCode}`;
15
+ let formatter = currencyFormatterCache.get(cacheKey);
16
+ if (formatter) {
17
+ return formatter;
18
+ }
19
+ formatter = new Intl.NumberFormat(locale, {
20
+ style: "currency",
21
+ currency: currencyCode,
22
+ /**
23
+ * Explicitly define default behavior - just in case some runtime overrides it
24
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign
25
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay
26
+ */
27
+ currencySign: "standard",
28
+ currencyDisplay: "symbol"
29
+ });
30
+ currencyFormatterCache.set(cacheKey, formatter);
31
+ return formatter;
32
+ };
33
+ function formatPriceRaw(dinero, locale, options) {
34
+ return dinero_js.toFormat(dinero, ({
35
+ amount,
36
+ currency
37
+ }) => {
38
+ if (options?.asNegativeAmount) {
39
+ amount = amount === 0 ? 0 : -Math.abs(amount);
40
+ }
41
+ const formatter = getCurrencyFormatter(locale, currency.code);
42
+ const formatted = formatter.format(amount);
43
+ return options?.removeFractions || options?.removeTrailingZeros ? (
44
+ /**
45
+ * Regex to handle complex removing trailing zeros from currency
46
+ * - Dynamically create regex based on currency as their exponent changes
47
+ * - Also handles some currencies (e.g. EUR) having trailing currency symbol
48
+ *
49
+ * TODO: improve how we detect "decimal separator" for formatted currency, at least right now we have tests for it and doesn't seem like an issue
50
+ */
51
+ formatted.replace(
52
+ // For some reason `\.` need to be double-escaped `\\` when creating the regex from template string
53
+ new RegExp(`(\\.|,)${
54
+ // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding
55
+ options?.removeFractions ? "\\d" : 0}{0,${currency.exponent}}(\\s\\D)?$`),
56
+ // In the replaced using "last capture group" (if-exists) so we restore the trailing currency sign
57
+ "$2")) : formatted;
58
+ });
59
+ }
60
+ const formatPrice = (money, options) => {
61
+ const localizedCurrency = getLocalizedCurrency(money.currency);
62
+ errors.assert(!!localizedCurrency, `Currency ${money.currency} not supported`);
63
+ return formatPriceRaw(misc.getDinero(money.amount, money.currency), localizedCurrency.locale, options);
64
+ };
65
+ const prettifyTotal = total => {
66
+ const totalJson = total.toJSON();
67
+ switch (totalJson.currency.code) {
68
+ // @see: https://ubiquiti.atlassian.net/browse/NEP-3846
69
+ case currencies.EUR.code:
70
+ case currencies.GBP.code:
71
+ case currencies.CAD.code:
72
+ {
73
+ const totalAsFloat = dinero_js.toUnit(total);
74
+ if (totalAsFloat < 10) {
75
+ return misc.roundDinero(total, constants.Round.PrettifyDecimalCents);
76
+ } else if (totalAsFloat < 20) {
77
+ return misc.roundDinero(total, constants.Round.PrettifyHalfUnitCents);
78
+ } else if (totalAsFloat < 50) {
79
+ return misc.roundDinero(total, constants.Round.Prettify);
80
+ } else {
81
+ return misc.roundDinero(total, constants.Round.PrettifyFull059);
82
+ }
83
+ }
84
+ default:
85
+ {
86
+ if (!dinero_js.hasSubUnits(total)) {
87
+ return total;
88
+ }
89
+ const minValueInclusiveToRoundDownFrom = constants.prettifyPriceLookup.get(totalJson.currency.code);
90
+ if (minValueInclusiveToRoundDownFrom == null || dinero_js.toUnit(total) < minValueInclusiveToRoundDownFrom) {
91
+ return total;
92
+ }
93
+ return misc.roundDinero(total, constants.Round.Prettify);
94
+ }
95
+ }
96
+ };
97
+ exports.formatPrice = formatPrice;
98
+ exports.formatPriceRaw = formatPriceRaw;
99
+ exports.getLocalizedCurrency = getLocalizedCurrency;
100
+ exports.prettifyTotal = prettifyTotal;
101
+ //# sourceMappingURL=format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.js","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n /**\n * Given amount will be treated as negative and formatted accordingly.\n * In our system we don't have stored negative amounts, but this is useful for displaying discount/refunded amounts\n * @default false\n * @example\n * \"420,66 €\" => \"-420,66 €\"\n */\n asNegativeAmount?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n /**\n * Optionally invert the amount to display it as negative\n * Doing math.abs as if we receive already negative amount, we want to keep it as negative. Also special case for 0\n * where we always want to display it as positive\n */\n if (options?.asNegativeAmount) {\n amount = amount === 0 ? 0 : -Math.abs(amount);\n }\n\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n // eslint-disable-next-line sonarjs/deprecation\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","asNegativeAmount","Math","abs","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,SAAA,CAAAA,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,CAAA,CAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,SAAA,GAAY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AAApD,GAAA,CAC3DqC,UAAU3B,QAAS,CAAAY,IACrB,CAAA;QAGA,IACE6B,gCAAoC,IAAA,IAAA,IACpCR,SAAO,CAAAA,MAAA,CAAAP,KAAK,IAAIe,gCAChB,EAAA;UACO,OAAAf,KAAA;QAAA;QAGF,OAAAQ,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMG,QAAQ,CAAA;MAAA;EAC1C;AAEJ,CAAA;;;;"}
@@ -0,0 +1,96 @@
1
+ import { CAD, GBP, EUR } from '@dinero.js/currencies';
2
+ import { toFormat, hasSubUnits, toUnit } from 'dinero.js';
3
+ import { assert } from '../errors.mjs';
4
+ import { localizedCurrencyLookup, prettifyPriceLookup, Round } from './constants.mjs';
5
+ import { getDinero, roundDinero } from './misc.mjs';
6
+ "use strict";
7
+ const getLocalizedCurrency = currencyCode => {
8
+ return currencyCode ? localizedCurrencyLookup.get(currencyCode) : void 0;
9
+ };
10
+ const currencyFormatterCache = /* @__PURE__ */new Map();
11
+ const getCurrencyFormatter = (locale, currencyCode) => {
12
+ const cacheKey = `${locale}_${currencyCode}`;
13
+ let formatter = currencyFormatterCache.get(cacheKey);
14
+ if (formatter) {
15
+ return formatter;
16
+ }
17
+ formatter = new Intl.NumberFormat(locale, {
18
+ style: "currency",
19
+ currency: currencyCode,
20
+ /**
21
+ * Explicitly define default behavior - just in case some runtime overrides it
22
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign
23
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay
24
+ */
25
+ currencySign: "standard",
26
+ currencyDisplay: "symbol"
27
+ });
28
+ currencyFormatterCache.set(cacheKey, formatter);
29
+ return formatter;
30
+ };
31
+ function formatPriceRaw(dinero, locale, options) {
32
+ return toFormat(dinero, ({
33
+ amount,
34
+ currency
35
+ }) => {
36
+ if (options?.asNegativeAmount) {
37
+ amount = amount === 0 ? 0 : -Math.abs(amount);
38
+ }
39
+ const formatter = getCurrencyFormatter(locale, currency.code);
40
+ const formatted = formatter.format(amount);
41
+ return options?.removeFractions || options?.removeTrailingZeros ? (
42
+ /**
43
+ * Regex to handle complex removing trailing zeros from currency
44
+ * - Dynamically create regex based on currency as their exponent changes
45
+ * - Also handles some currencies (e.g. EUR) having trailing currency symbol
46
+ *
47
+ * TODO: improve how we detect "decimal separator" for formatted currency, at least right now we have tests for it and doesn't seem like an issue
48
+ */
49
+ formatted.replace(
50
+ // For some reason `\.` need to be double-escaped `\\` when creating the regex from template string
51
+ new RegExp(`(\\.|,)${
52
+ // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding
53
+ options?.removeFractions ? "\\d" : 0}{0,${currency.exponent}}(\\s\\D)?$`),
54
+ // In the replaced using "last capture group" (if-exists) so we restore the trailing currency sign
55
+ "$2")) : formatted;
56
+ });
57
+ }
58
+ const formatPrice = (money, options) => {
59
+ const localizedCurrency = getLocalizedCurrency(money.currency);
60
+ assert(!!localizedCurrency, `Currency ${money.currency} not supported`);
61
+ return formatPriceRaw(getDinero(money.amount, money.currency), localizedCurrency.locale, options);
62
+ };
63
+ const prettifyTotal = total => {
64
+ const totalJson = total.toJSON();
65
+ switch (totalJson.currency.code) {
66
+ // @see: https://ubiquiti.atlassian.net/browse/NEP-3846
67
+ case EUR.code:
68
+ case GBP.code:
69
+ case CAD.code:
70
+ {
71
+ const totalAsFloat = toUnit(total);
72
+ if (totalAsFloat < 10) {
73
+ return roundDinero(total, Round.PrettifyDecimalCents);
74
+ } else if (totalAsFloat < 20) {
75
+ return roundDinero(total, Round.PrettifyHalfUnitCents);
76
+ } else if (totalAsFloat < 50) {
77
+ return roundDinero(total, Round.Prettify);
78
+ } else {
79
+ return roundDinero(total, Round.PrettifyFull059);
80
+ }
81
+ }
82
+ default:
83
+ {
84
+ if (!hasSubUnits(total)) {
85
+ return total;
86
+ }
87
+ const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(totalJson.currency.code);
88
+ if (minValueInclusiveToRoundDownFrom == null || toUnit(total) < minValueInclusiveToRoundDownFrom) {
89
+ return total;
90
+ }
91
+ return roundDinero(total, Round.Prettify);
92
+ }
93
+ }
94
+ };
95
+ export { formatPrice, formatPriceRaw, getLocalizedCurrency, prettifyTotal };
96
+ //# sourceMappingURL=format.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.mjs","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n /**\n * Given amount will be treated as negative and formatted accordingly.\n * In our system we don't have stored negative amounts, but this is useful for displaying discount/refunded amounts\n * @default false\n * @example\n * \"420,66 €\" => \"-420,66 €\"\n */\n asNegativeAmount?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n /**\n * Optionally invert the amount to display it as negative\n * Doing math.abs as if we receive already negative amount, we want to keep it as negative. Also special case for 0\n * where we always want to display it as positive\n */\n if (options?.asNegativeAmount) {\n amount = amount === 0 ? 0 : -Math.abs(amount);\n }\n\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n // eslint-disable-next-line sonarjs/deprecation\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","asNegativeAmount","Math","abs","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,CAAA,CAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,SAAA,GAAYL,sBAAuB,CAAAD,GAAA,CAAIK,QAAQ,CAAA;EACnD,IAAIC,SAAW,EAAA;IACN,OAAAA,SAAA;EAAA;EAGGA,SAAA,GAAA,IAAIC,IAAK,CAAAC,YAAA,CAAaJ,MAAQ,EAAA;IACxCK,KAAO,EAAA,UAAA;IACPC,QAAU,EAAAZ,YAAA;IAAA;AAAA;AAAA;AAAA;AAAA;IAMVa,YAAc,EAAA,UAAA;IACdC,eAAiB,EAAA;EAA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AA;EAC5C,MAAAC,SAAA,GAAYD,MAAME,MAAO,CAAA,CAAA;EAEvB,QAAAD,SAAA,CAAU3B,SAASY,IAAM;IAAA;IAE/B,KAAKiB,GAAI,CAAAjB,IAAA;IACT,KAAKkB,GAAI,CAAAlB,IAAA;IACT,KAAKmB,IAAInB,IAAM;MAAA;QACP,MAAAoB,YAAA,GAAeC,OAAOP,KAAK,CAAA;QAEjC,IAAIM,eAAe,EAAI,EAAA;UACd,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMC,oBAAoB,CAAA;QAAA,CACtD,MAAA,IAAWJ,eAAe,EAAI,EAAA;UACrB,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAME,qBAAqB,CAAA;QAAA,CACvD,MAAA,IAAWL,eAAe,EAAI,EAAA;UACrB,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMG,QAAQ,CAAA;QAAA,CACnC,MAAA;UACE,OAAAJ,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMI,eAAe,CAAA;QAAA;MACjD;IAEF;MAAS;QAEH,IAAA,CAACC,WAAY,CAAAd,KAAK,CAAG,EAAA;UAChB,OAAAA,KAAA;QAAA;QAGT,MAAMe,mCAAmCC,mBAAoB,CAAApD,GAAA,CAC3DqC,UAAU3B,QAAS,CAAAY,IACrB,CAAA;QAGA,IACE6B,gCAAoC,IAAA,IAAA,IACpCR,MAAO,CAAAP,KAAK,IAAIe,gCAChB,EAAA;UACO,OAAAf,KAAA;QAAA;QAGF,OAAAQ,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMG,QAAQ,CAAA;MAAA;EAC1C;AAEJ,CAAA;"}
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+
3
+ var fixedAmount = require('./allocators/fixedAmount.js');
4
+ var productAmount = require('./allocators/productAmount.js');
5
+ var constants = require('./constants.js');
6
+ var exchangeRate = require('./exchangeRate.js');
7
+ var format = require('./format.js');
8
+ var misc = require('./misc.js');
9
+ var shipping = require('./shipping.js');
10
+ var tax = require('./tax.js');
11
+ require('./types.js');
12
+ "use strict";
13
+ exports.FixedAmountAllocator = fixedAmount.FixedAmountAllocator;
14
+ exports.ProductAmountAllocator = productAmount.ProductAmountAllocator;
15
+ exports.EXCHANGE_RATE_DINERO_CURRENCY = constants.EXCHANGE_RATE_DINERO_CURRENCY;
16
+ exports.Round = constants.Round;
17
+ exports.TAX_RATE_DINERO_CURRENCY = constants.TAX_RATE_DINERO_CURRENCY;
18
+ exports.localizedCurrencyLookup = constants.localizedCurrencyLookup;
19
+ exports.prettifyPriceLookup = constants.prettifyPriceLookup;
20
+ exports.roundToNearestDecimalCent = constants.roundToNearestDecimalCent;
21
+ exports.roundToNearestFull059 = constants.roundToNearestFull059;
22
+ exports.roundToNearestHalfUnitCent = constants.roundToNearestHalfUnitCent;
23
+ exports.smallestSubunitLookup = constants.smallestSubunitLookup;
24
+ exports.storesWithPerItemTaxRate = constants.storesWithPerItemTaxRate;
25
+ exports.invertExchangeRate = exchangeRate.invertExchangeRate;
26
+ exports.toFixedExchangeRate = exchangeRate.toFixedExchangeRate;
27
+ exports.toSnapshotExchangeRate = exchangeRate.toSnapshotExchangeRate;
28
+ exports.formatPrice = format.formatPrice;
29
+ exports.formatPriceRaw = format.formatPriceRaw;
30
+ exports.getLocalizedCurrency = format.getLocalizedCurrency;
31
+ exports.prettifyTotal = format.prettifyTotal;
32
+ exports.addMany = misc.addMany;
33
+ exports.amount = misc.amount;
34
+ exports.centsToCurrencyUnit = misc.centsToCurrencyUnit;
35
+ exports.currency = misc.currency;
36
+ exports.dineroToCurrencyUnit = misc.dineroToCurrencyUnit;
37
+ exports.getDinero = misc.getDinero;
38
+ exports.getDineroCurrency = misc.getDineroCurrency;
39
+ exports.money = misc.money;
40
+ exports.multiplyByFullPercent = misc.multiplyByFullPercent;
41
+ exports.parseCurrencyCode = misc.parseCurrencyCode;
42
+ exports.parseFloatToDinero = misc.parseFloatToDinero;
43
+ exports.parseFloatToDineroRaw = misc.parseFloatToDineroRaw;
44
+ exports.roundDinero = misc.roundDinero;
45
+ exports.stringAmountToDinero = misc.stringAmountToDinero;
46
+ exports.subtractMany = misc.subtractMany;
47
+ exports.toSmallestSubunit = misc.toSmallestSubunit;
48
+ exports.roundShippingPrice = shipping.roundShippingPrice;
49
+ exports.calculateLineItemTax = tax.calculateLineItemTax;
50
+ exports.calculateTotalTaxRate = tax.calculateTotalTaxRate;
51
+ exports.convertDecimalTaxRateToPercentage = tax.convertDecimalTaxRateToPercentage;
52
+ exports.decimalTaxRateToDinero = tax.decimalTaxRateToDinero;
53
+ exports.formatDecimalTaxRate = tax.formatDecimalTaxRate;
54
+ exports.removeTaxAmount = tax.removeTaxAmount;
55
+ exports.stringTaxRateToFloat = tax.stringTaxRateToFloat;
56
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,11 @@
1
+ export { FixedAmountAllocator } from './allocators/fixedAmount.mjs';
2
+ export { ProductAmountAllocator } from './allocators/productAmount.mjs';
3
+ export { EXCHANGE_RATE_DINERO_CURRENCY, Round, TAX_RATE_DINERO_CURRENCY, localizedCurrencyLookup, prettifyPriceLookup, roundToNearestDecimalCent, roundToNearestFull059, roundToNearestHalfUnitCent, smallestSubunitLookup, storesWithPerItemTaxRate } from './constants.mjs';
4
+ export { invertExchangeRate, toFixedExchangeRate, toSnapshotExchangeRate } from './exchangeRate.mjs';
5
+ export { formatPrice, formatPriceRaw, getLocalizedCurrency, prettifyTotal } from './format.mjs';
6
+ export { addMany, amount, centsToCurrencyUnit, currency, dineroToCurrencyUnit, getDinero, getDineroCurrency, money, multiplyByFullPercent, parseCurrencyCode, parseFloatToDinero, parseFloatToDineroRaw, roundDinero, stringAmountToDinero, subtractMany, toSmallestSubunit } from './misc.mjs';
7
+ export { roundShippingPrice } from './shipping.mjs';
8
+ export { calculateLineItemTax, calculateTotalTaxRate, convertDecimalTaxRateToPercentage, decimalTaxRateToDinero, formatDecimalTaxRate, removeTaxAmount, stringTaxRateToFloat } from './tax.mjs';
9
+ import './types.mjs';
10
+ "use strict";
11
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;"}
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+
3
+ var constants = require('./constants.js');
4
+ var misc = require('./misc.js');
5
+ "use strict";
6
+ const roundShippingPrice = price => misc.roundDinero(price, constants.Round.Shipping);
7
+ exports.roundShippingPrice = roundShippingPrice;
8
+ //# sourceMappingURL=shipping.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shipping.js","sources":["../../../src/utils/money/shipping.ts"],"sourcesContent":["import { Round } from \"./constants\";\nimport { roundDinero } from \"./misc\";\nimport type { Dino } from \"./types\";\n\n/**\n * Rounding for shipping price used only after applying\n */\nexport const roundShippingPrice = (price: Dino) =>\n roundDinero(price, Round.Shipping);\n"],"names":["roundShippingPrice","price","roundDinero","Round","Shipping"],"mappings":";;;;;AAOO,MAAMA,qBAAsBC,KAAA,IACjCC,IAAY,CAAAA,WAAA,CAAAD,KAAA,EAAOE,gBAAMC,QAAQ,CAAA;"}
@@ -0,0 +1,6 @@
1
+ import { Round } from './constants.mjs';
2
+ import { roundDinero } from './misc.mjs';
3
+ "use strict";
4
+ const roundShippingPrice = price => roundDinero(price, Round.Shipping);
5
+ export { roundShippingPrice };
6
+ //# sourceMappingURL=shipping.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shipping.mjs","sources":["../../../src/utils/money/shipping.ts"],"sourcesContent":["import { Round } from \"./constants\";\nimport { roundDinero } from \"./misc\";\nimport type { Dino } from \"./types\";\n\n/**\n * Rounding for shipping price used only after applying\n */\nexport const roundShippingPrice = (price: Dino) =>\n roundDinero(price, Round.Shipping);\n"],"names":["roundShippingPrice","price","roundDinero","Round","Shipping"],"mappings":";;;AAOO,MAAMA,qBAAsBC,KAAA,IACjCC,WAAY,CAAAD,KAAA,EAAOE,MAAMC,QAAQ,CAAA;"}
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ var dinero_js = require('dinero.js');
4
+ var errors = require('../errors.js');
5
+ var number = require('../number.js');
6
+ var constants = require('./constants.js');
7
+ var tax_private = require('./tax.private.js');
8
+ "use strict";
9
+ const calculateLineItemTax = ({
10
+ itemSummary,
11
+ taxRate,
12
+ storeId
13
+ }) => {
14
+ return constants.storesWithPerItemTaxRate.has(storeId) ? tax_private.calculatePerQtyLineItemTax(itemSummary, taxRate) : tax_private.calculateWholeQtyLineItemTax(itemSummary, taxRate);
15
+ };
16
+ const removeTaxAmount = (baseAmountWithTaxObj, taxRate) => {
17
+ const snapshot = dinero_js.toSnapshot(baseAmountWithTaxObj);
18
+ const taxAmount = constants.Round.Financial(snapshot.amount - snapshot.amount / (1 + taxRate));
19
+ return dinero_js.dinero({
20
+ ...snapshot,
21
+ amount: snapshot.amount - taxAmount
22
+ });
23
+ };
24
+ const convertDecimalTaxRateToPercentage = taxRate => {
25
+ const dineroObj = decimalTaxRateToDinero(taxRate);
26
+ const t = dinero_js.multiply(dineroObj, 100);
27
+ return dinero_js.toUnit(t, {
28
+ digits: constants.TAX_RATE_DINERO_CURRENCY.exponent,
29
+ round: dinero_js.halfEven
30
+ });
31
+ };
32
+ const decimalTaxRateToDinero = taxRate => {
33
+ const parsedNumber = typeof taxRate === "number" ? taxRate : Number.parseFloat(taxRate);
34
+ number.isFloat(parsedNumber);
35
+ const parsedNumberInt = Number.parseInt((parsedNumber * Math.pow(constants.TAX_RATE_DINERO_CURRENCY.base, constants.TAX_RATE_DINERO_CURRENCY.exponent)).toFixed(0));
36
+ return dinero_js.dinero({
37
+ amount: parsedNumberInt,
38
+ currency: constants.TAX_RATE_DINERO_CURRENCY
39
+ });
40
+ };
41
+ const formatDecimalTaxRate = taxRate => {
42
+ return `${convertDecimalTaxRateToPercentage(taxRate)}%`;
43
+ };
44
+ const stringTaxRateToFloat = rate => number.toFixedRate(+rate, constants.TAX_RATE_DINERO_CURRENCY.exponent, true);
45
+ const calculateTotalTaxRate = rates => {
46
+ const rateSum = rates.reduce((sum, rate) => sum + rate, 0);
47
+ const result = number.toFixedRate(rateSum, constants.TAX_RATE_DINERO_CURRENCY.exponent, true);
48
+ errors.assert(result >= 0, "Tax rate must be positive");
49
+ errors.assert(result < 1, "Tax rate must be less than 1");
50
+ return result;
51
+ };
52
+ exports.calculateLineItemTax = calculateLineItemTax;
53
+ exports.calculateTotalTaxRate = calculateTotalTaxRate;
54
+ exports.convertDecimalTaxRateToPercentage = convertDecimalTaxRateToPercentage;
55
+ exports.decimalTaxRateToDinero = decimalTaxRateToDinero;
56
+ exports.formatDecimalTaxRate = formatDecimalTaxRate;
57
+ exports.removeTaxAmount = removeTaxAmount;
58
+ exports.stringTaxRateToFloat = stringTaxRateToFloat;
59
+ //# sourceMappingURL=tax.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tax.js","sources":["../../../src/utils/money/tax.ts"],"sourcesContent":["import {\n dinero,\n // FIXME: move usage to rounding\n halfEven,\n multiply,\n toSnapshot,\n toUnit,\n} from \"dinero.js\";\n\nimport type { StoreId } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, toFixedRate } from \"../number\";\nimport {\n Round,\n storesWithPerItemTaxRate,\n TAX_RATE_DINERO_CURRENCY,\n} from \"./constants\";\nimport {\n calculatePerQtyLineItemTax,\n calculateWholeQtyLineItemTax,\n} from \"./tax.private\";\nimport type { Dino, LineItemSummary, TaxRate } from \"./types\";\n\n/**\n * Function to calculate the tax amount for a given line item depending on the store's tax rate calculation strategy\n */\nexport const calculateLineItemTax = ({\n itemSummary,\n taxRate,\n storeId,\n}: {\n itemSummary: LineItemSummary;\n taxRate: TaxRate;\n storeId: StoreId;\n}) => {\n return storesWithPerItemTaxRate.has(storeId)\n ? calculatePerQtyLineItemTax(itemSummary, taxRate)\n : calculateWholeQtyLineItemTax(itemSummary, taxRate);\n};\n\nexport const removeTaxAmount = (\n baseAmountWithTaxObj: Dino,\n taxRate: TaxRate,\n) => {\n const snapshot = toSnapshot(baseAmountWithTaxObj);\n\n // Calculate the tax amount and apply rounding on it so that behavior for reverse process is consistent\n const taxAmount = Round.Financial(\n snapshot.amount - snapshot.amount / (1 + taxRate),\n );\n\n return dinero({\n ...snapshot,\n amount: snapshot.amount - taxAmount,\n });\n};\n\n/**\n * Will return a percentage tax rate from a decimal tax rate (usually returned by DB)\n *\n * Use for math-related calculations ONLY! Use `formatDecimalTaxRate` for display purposes e.g. invoices.\n *\n * @example convertDecimalTaxRateToPercentage(\"0.01\") // 1\n * @example convertDecimalTaxRateToPercentage(\"0.1023\") // 10.23\n * @example convertDecimalTaxRateToPercentage(\"0.12345678\") // 12.345678\n */\nexport const convertDecimalTaxRateToPercentage = (\n taxRate: string | number,\n): number => {\n const dineroObj = decimalTaxRateToDinero(taxRate);\n const t = multiply(dineroObj, 100);\n return toUnit(t, {\n digits: TAX_RATE_DINERO_CURRENCY.exponent,\n round: halfEven,\n });\n};\n\nexport const decimalTaxRateToDinero = (taxRate: string | number): Dino => {\n const parsedNumber =\n typeof taxRate === \"number\" ? taxRate : Number.parseFloat(taxRate);\n isFloat(parsedNumber);\n\n const parsedNumberInt = Number.parseInt(\n (\n parsedNumber *\n Math.pow(TAX_RATE_DINERO_CURRENCY.base, TAX_RATE_DINERO_CURRENCY.exponent)\n ).toFixed(0),\n );\n return dinero({\n amount: parsedNumberInt,\n currency: TAX_RATE_DINERO_CURRENCY,\n });\n};\n\n/**\n * Will return a percentage string from a decimal tax rate (usually returned by DB).\n *\n * Use for display purposes e.g. invoices.\n *\n * @example formatDecimalTaxRate(\"0.01\") // \"1%\"\n * @example formatDecimalTaxRate(\"0.1023\") // \"10.23%\"\n * @example formatDecimalTaxRate(\"0.12345678\") // \"12.345678%\"\n */\nexport const formatDecimalTaxRate = <TaxRateFloat extends string | number>(\n taxRate: TaxRateFloat,\n): `${number}%` => {\n return `${convertDecimalTaxRateToPercentage(taxRate)}%`;\n};\n\nexport const stringTaxRateToFloat = (rate: string): number =>\n toFixedRate(+rate, TAX_RATE_DINERO_CURRENCY.exponent, true);\n\n/**\n * Calculate total Tax(LV: \"PVN\") for country, which consists of multiple tax entries\n * Returning fixed to ${TAX_RATE_DINERO_CURRENCY.exponent} 4 decimal places, to for example 0.2100 represent 21.00%\n */\nexport const calculateTotalTaxRate = (rates: number[]): number => {\n const rateSum = rates.reduce((sum, rate) => sum + rate, 0);\n const result = toFixedRate(rateSum, TAX_RATE_DINERO_CURRENCY.exponent, true);\n assert(result >= 0, \"Tax rate must be positive\");\n assert(result < 1, \"Tax rate must be less than 1\");\n return result;\n};\n"],"names":["calculateLineItemTax","itemSummary","taxRate","storeId","storesWithPerItemTaxRate","has","calculatePerQtyLineItemTax","calculateWholeQtyLineItemTax","removeTaxAmount","baseAmountWithTaxObj","snapshot","toSnapshot","taxAmount","Round","Financial","amount","dinero","convertDecimalTaxRateToPercentage","dineroObj","decimalTaxRateToDinero","t","multiply","toUnit","digits","TAX_RATE_DINERO_CURRENCY","exponent","round","halfEven","parsedNumber","Number","parseFloat","isFloat","parsedNumberInt","parseInt","Math","pow","base","toFixed","currency","formatDecimalTaxRate","stringTaxRateToFloat","rate","toFixedRate","calculateTotalTaxRate","rates","rateSum","reduce","sum","result","assert"],"mappings":";;;;;;;;AA0BO,MAAMA,uBAAuBA,CAAC;EACnCC,WAAA;EACAC,OAAA;EACAC;AACF,CAIM,KAAA;EACG,OAAAC,kCAAA,CAAyBC,GAAI,CAAAF,OAAO,CACvC,GAAAG,WAAA,CAAAA,0BAAA,CAA2BL,aAAaC,OAAO,CAAA,GAC/CK,WAAAA,CAAAA,4BAA6B,CAAAN,WAAA,EAAaC,OAAO,CAAA;AACvD,CAAA;AAEa,MAAAM,eAAA,GAAkB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,CAAAf,OAAO,CAAC,GAAA;AACtD,CAAA;AAEa,MAAAsC,oBAAA,GAAwBC,IACnC,IAAAC,MAAA,CAAAA,WAAA,CAAY,CAACD,IAAM,EAAAjB,SAAAA,CAAAA,wBAAA,CAAyBC,UAAU,IAAI,CAAA;AAM/C,MAAAkB,qBAAA,GAAyBC,KAA4B,IAAA;EAC1D,MAAAC,OAAA,GAAUD,MAAME,MAAO,CAAA,CAACC,KAAKN,IAAS,KAAAM,GAAA,GAAMN,MAAM,CAAC,CAAA;EACzD,MAAMO,MAAS,GAAAN,MAAAA,CAAAA,WAAA,CAAYG,OAAS,EAAArB,SAAAA,CAAAA,wBAAA,CAAyBC,UAAU,IAAI,CAAA;EACpEwB,aAAA,CAAAD,MAAA,IAAU,GAAG,2BAA2B,CAAA;EACxCC,aAAA,CAAAD,MAAA,GAAS,GAAG,8BAA8B,CAAA;EAC1C,OAAAA,MAAA;AACT,CAAA;;;;;;;"}
@@ -0,0 +1,51 @@
1
+ import { toSnapshot, dinero, multiply, toUnit, halfEven } from 'dinero.js';
2
+ import { assert } from '../errors.mjs';
3
+ import { isFloat, toFixedRate } from '../number.mjs';
4
+ import { storesWithPerItemTaxRate, Round, TAX_RATE_DINERO_CURRENCY } from './constants.mjs';
5
+ import { calculatePerQtyLineItemTax, calculateWholeQtyLineItemTax } from './tax.private.mjs';
6
+ "use strict";
7
+ const calculateLineItemTax = ({
8
+ itemSummary,
9
+ taxRate,
10
+ storeId
11
+ }) => {
12
+ return storesWithPerItemTaxRate.has(storeId) ? calculatePerQtyLineItemTax(itemSummary, taxRate) : calculateWholeQtyLineItemTax(itemSummary, taxRate);
13
+ };
14
+ const removeTaxAmount = (baseAmountWithTaxObj, taxRate) => {
15
+ const snapshot = toSnapshot(baseAmountWithTaxObj);
16
+ const taxAmount = Round.Financial(snapshot.amount - snapshot.amount / (1 + taxRate));
17
+ return dinero({
18
+ ...snapshot,
19
+ amount: snapshot.amount - taxAmount
20
+ });
21
+ };
22
+ const convertDecimalTaxRateToPercentage = taxRate => {
23
+ const dineroObj = decimalTaxRateToDinero(taxRate);
24
+ const t = multiply(dineroObj, 100);
25
+ return toUnit(t, {
26
+ digits: TAX_RATE_DINERO_CURRENCY.exponent,
27
+ round: halfEven
28
+ });
29
+ };
30
+ const decimalTaxRateToDinero = taxRate => {
31
+ const parsedNumber = typeof taxRate === "number" ? taxRate : Number.parseFloat(taxRate);
32
+ isFloat(parsedNumber);
33
+ const parsedNumberInt = Number.parseInt((parsedNumber * Math.pow(TAX_RATE_DINERO_CURRENCY.base, TAX_RATE_DINERO_CURRENCY.exponent)).toFixed(0));
34
+ return dinero({
35
+ amount: parsedNumberInt,
36
+ currency: TAX_RATE_DINERO_CURRENCY
37
+ });
38
+ };
39
+ const formatDecimalTaxRate = taxRate => {
40
+ return `${convertDecimalTaxRateToPercentage(taxRate)}%`;
41
+ };
42
+ const stringTaxRateToFloat = rate => toFixedRate(+rate, TAX_RATE_DINERO_CURRENCY.exponent, true);
43
+ const calculateTotalTaxRate = rates => {
44
+ const rateSum = rates.reduce((sum, rate) => sum + rate, 0);
45
+ const result = toFixedRate(rateSum, TAX_RATE_DINERO_CURRENCY.exponent, true);
46
+ assert(result >= 0, "Tax rate must be positive");
47
+ assert(result < 1, "Tax rate must be less than 1");
48
+ return result;
49
+ };
50
+ export { calculateLineItemTax, calculateTotalTaxRate, convertDecimalTaxRateToPercentage, decimalTaxRateToDinero, formatDecimalTaxRate, removeTaxAmount, stringTaxRateToFloat };
51
+ //# sourceMappingURL=tax.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tax.mjs","sources":["../../../src/utils/money/tax.ts"],"sourcesContent":["import {\n dinero,\n // FIXME: move usage to rounding\n halfEven,\n multiply,\n toSnapshot,\n toUnit,\n} from \"dinero.js\";\n\nimport type { StoreId } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, toFixedRate } from \"../number\";\nimport {\n Round,\n storesWithPerItemTaxRate,\n TAX_RATE_DINERO_CURRENCY,\n} from \"./constants\";\nimport {\n calculatePerQtyLineItemTax,\n calculateWholeQtyLineItemTax,\n} from \"./tax.private\";\nimport type { Dino, LineItemSummary, TaxRate } from \"./types\";\n\n/**\n * Function to calculate the tax amount for a given line item depending on the store's tax rate calculation strategy\n */\nexport const calculateLineItemTax = ({\n itemSummary,\n taxRate,\n storeId,\n}: {\n itemSummary: LineItemSummary;\n taxRate: TaxRate;\n storeId: StoreId;\n}) => {\n return storesWithPerItemTaxRate.has(storeId)\n ? calculatePerQtyLineItemTax(itemSummary, taxRate)\n : calculateWholeQtyLineItemTax(itemSummary, taxRate);\n};\n\nexport const removeTaxAmount = (\n baseAmountWithTaxObj: Dino,\n taxRate: TaxRate,\n) => {\n const snapshot = toSnapshot(baseAmountWithTaxObj);\n\n // Calculate the tax amount and apply rounding on it so that behavior for reverse process is consistent\n const taxAmount = Round.Financial(\n snapshot.amount - snapshot.amount / (1 + taxRate),\n );\n\n return dinero({\n ...snapshot,\n amount: snapshot.amount - taxAmount,\n });\n};\n\n/**\n * Will return a percentage tax rate from a decimal tax rate (usually returned by DB)\n *\n * Use for math-related calculations ONLY! Use `formatDecimalTaxRate` for display purposes e.g. invoices.\n *\n * @example convertDecimalTaxRateToPercentage(\"0.01\") // 1\n * @example convertDecimalTaxRateToPercentage(\"0.1023\") // 10.23\n * @example convertDecimalTaxRateToPercentage(\"0.12345678\") // 12.345678\n */\nexport const convertDecimalTaxRateToPercentage = (\n taxRate: string | number,\n): number => {\n const dineroObj = decimalTaxRateToDinero(taxRate);\n const t = multiply(dineroObj, 100);\n return toUnit(t, {\n digits: TAX_RATE_DINERO_CURRENCY.exponent,\n round: halfEven,\n });\n};\n\nexport const decimalTaxRateToDinero = (taxRate: string | number): Dino => {\n const parsedNumber =\n typeof taxRate === \"number\" ? taxRate : Number.parseFloat(taxRate);\n isFloat(parsedNumber);\n\n const parsedNumberInt = Number.parseInt(\n (\n parsedNumber *\n Math.pow(TAX_RATE_DINERO_CURRENCY.base, TAX_RATE_DINERO_CURRENCY.exponent)\n ).toFixed(0),\n );\n return dinero({\n amount: parsedNumberInt,\n currency: TAX_RATE_DINERO_CURRENCY,\n });\n};\n\n/**\n * Will return a percentage string from a decimal tax rate (usually returned by DB).\n *\n * Use for display purposes e.g. invoices.\n *\n * @example formatDecimalTaxRate(\"0.01\") // \"1%\"\n * @example formatDecimalTaxRate(\"0.1023\") // \"10.23%\"\n * @example formatDecimalTaxRate(\"0.12345678\") // \"12.345678%\"\n */\nexport const formatDecimalTaxRate = <TaxRateFloat extends string | number>(\n taxRate: TaxRateFloat,\n): `${number}%` => {\n return `${convertDecimalTaxRateToPercentage(taxRate)}%`;\n};\n\nexport const stringTaxRateToFloat = (rate: string): number =>\n toFixedRate(+rate, TAX_RATE_DINERO_CURRENCY.exponent, true);\n\n/**\n * Calculate total Tax(LV: \"PVN\") for country, which consists of multiple tax entries\n * Returning fixed to ${TAX_RATE_DINERO_CURRENCY.exponent} 4 decimal places, to for example 0.2100 represent 21.00%\n */\nexport const calculateTotalTaxRate = (rates: number[]): number => {\n const rateSum = rates.reduce((sum, rate) => sum + rate, 0);\n const result = toFixedRate(rateSum, TAX_RATE_DINERO_CURRENCY.exponent, true);\n assert(result >= 0, \"Tax rate must be positive\");\n assert(result < 1, \"Tax rate must be less than 1\");\n return result;\n};\n"],"names":["calculateLineItemTax","itemSummary","taxRate","storeId","storesWithPerItemTaxRate","has","calculatePerQtyLineItemTax","calculateWholeQtyLineItemTax","removeTaxAmount","baseAmountWithTaxObj","snapshot","toSnapshot","taxAmount","Round","Financial","amount","dinero","convertDecimalTaxRateToPercentage","dineroObj","decimalTaxRateToDinero","t","multiply","toUnit","digits","TAX_RATE_DINERO_CURRENCY","exponent","round","halfEven","parsedNumber","Number","parseFloat","isFloat","parsedNumberInt","parseInt","Math","pow","base","toFixed","currency","formatDecimalTaxRate","stringTaxRateToFloat","rate","toFixedRate","calculateTotalTaxRate","rates","rateSum","reduce","sum","result","assert"],"mappings":";;;;;;AA0BO,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D,MAAQ,EAAAiB,eAAA;IACRM,QAAU,EAAAd;EAAA,CACX,CAAA;AACH,CAAA;AAWa,MAAAe,oBAAA,GACXrC,OACiB,IAAA;EACV,OAAA,GAAGe,iCAAkC,CAAAf,OAAO,CAAC,GAAA;AACtD,CAAA;AAEa,MAAAsC,oBAAA,GAAwBC,IACnC,IAAAC,WAAA,CAAY,CAACD,IAAM,EAAAjB,wBAAA,CAAyBC,UAAU,IAAI,CAAA;AAM/C,MAAAkB,qBAAA,GAAyBC,KAA4B,IAAA;EAC1D,MAAAC,OAAA,GAAUD,MAAME,MAAO,CAAA,CAACC,KAAKN,IAAS,KAAAM,GAAA,GAAMN,MAAM,CAAC,CAAA;EACzD,MAAMO,MAAS,GAAAN,WAAA,CAAYG,OAAS,EAAArB,wBAAA,CAAyBC,UAAU,IAAI,CAAA;EACpEwB,MAAA,CAAAD,MAAA,IAAU,GAAG,2BAA2B,CAAA;EACxCC,MAAA,CAAAD,MAAA,GAAS,GAAG,8BAA8B,CAAA;EAC1C,OAAAA,MAAA;AACT,CAAA;"}
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+
3
+ var dinero_js = require('dinero.js');
4
+ var fixedAmount = require('./allocators/fixedAmount.js');
5
+ var constants = require('./constants.js');
6
+ var misc = require('./misc.js');
7
+ "use strict";
8
+ const allocatePerItemTaxableAmount = itemSummary => {
9
+ if (itemSummary.quantity === 1) {
10
+ return [itemSummary];
11
+ }
12
+ const preDiscountAmount = dinero_js.add(misc.getDinero(itemSummary.taxableAmount, itemSummary.currency), misc.getDinero(itemSummary.discountAmount, itemSummary.currency));
13
+ const allocator = new fixedAmount.FixedAmountAllocator({
14
+ initialAllocateAmount: itemSummary.discountAmount,
15
+ initialTotalAmount: misc.amount(preDiscountAmount),
16
+ currency: itemSummary.currency
17
+ });
18
+ return Array.from({
19
+ length: itemSummary.quantity
20
+ }, () => {
21
+ const discountAllocatedAmount = allocator.allocate(itemSummary.itemPrice, itemSummary.currency);
22
+ const taxableAmount = dinero_js.subtract(misc.getDinero(itemSummary.itemPrice, itemSummary.currency), discountAllocatedAmount);
23
+ return {
24
+ itemPrice: itemSummary.itemPrice,
25
+ taxableAmount: misc.amount(taxableAmount),
26
+ discountAmount: misc.amount(discountAllocatedAmount),
27
+ currency: itemSummary.currency,
28
+ quantity: 1
29
+ };
30
+ });
31
+ };
32
+ const calculateWholeQtyLineItemTax = (itemSummary, taxRate) => {
33
+ if (taxRate === 0) {
34
+ return misc.getDinero(0, itemSummary.currency);
35
+ }
36
+ return dinero_js.dinero({
37
+ amount: constants.Round.Financial(itemSummary.taxableAmount * taxRate),
38
+ currency: misc.getDineroCurrency(itemSummary.currency)
39
+ });
40
+ };
41
+ const calculatePerQtyLineItemTax = (itemSummary, taxRate) => {
42
+ if (taxRate === 0) {
43
+ return misc.getDinero(0, itemSummary.currency);
44
+ }
45
+ const singleItemSummaries = allocatePerItemTaxableAmount(itemSummary);
46
+ let totalTaxAmount = misc.getDinero(0, itemSummary.currency);
47
+ singleItemSummaries.forEach(itemSummary2 => {
48
+ const taxAmount = calculateWholeQtyLineItemTax(itemSummary2, taxRate);
49
+ totalTaxAmount = dinero_js.add(totalTaxAmount, taxAmount);
50
+ });
51
+ return totalTaxAmount;
52
+ };
53
+ exports.allocatePerItemTaxableAmount = allocatePerItemTaxableAmount;
54
+ exports.calculatePerQtyLineItemTax = calculatePerQtyLineItemTax;
55
+ exports.calculateWholeQtyLineItemTax = calculateWholeQtyLineItemTax;
56
+ //# sourceMappingURL=tax.private.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tax.private.js","sources":["../../../src/utils/money/tax.private.ts"],"sourcesContent":["// #############################################################################\n// Internal helper functions not for consumption outside of store.core!\n// Wrote as separate files so that they can be easily unit tested without exposing them\n// #############################################################################\nimport { add, dinero, subtract } from \"dinero.js\";\n\nimport { FixedAmountAllocator } from \"./allocators/fixedAmount\";\nimport { Round } from \"./constants\";\nimport { amount, getDinero, getDineroCurrency } from \"./misc\";\nimport type {\n Dino,\n LineItemSummary,\n SingleLineItemSummary,\n TaxRate,\n} from \"./types\";\n\n/**\n * Reverse engineer the taxable amount from \"whole item\" taxable amount into \"per item\" taxable amount for custom tax\n * rate calculations\n */\nexport const allocatePerItemTaxableAmount = (\n itemSummary: LineItemSummary,\n): SingleLineItemSummary[] => {\n /**\n * If the item quantity is 1, we can just return the item summary as is\n */\n if (itemSummary.quantity === 1) {\n return [itemSummary as SingleLineItemSummary];\n }\n\n // Reverse engineer price before discount\n const preDiscountAmount = add(\n getDinero(itemSummary.taxableAmount, itemSummary.currency),\n getDinero(itemSummary.discountAmount, itemSummary.currency),\n );\n\n const allocator = new FixedAmountAllocator({\n initialAllocateAmount: itemSummary.discountAmount,\n initialTotalAmount: amount(preDiscountAmount),\n currency: itemSummary.currency,\n });\n\n // Iterate over the amount of qty to reverse engineer the discount price\n return Array.from({ length: itemSummary.quantity }, () => {\n const discountAllocatedAmount = allocator.allocate(\n itemSummary.itemPrice,\n itemSummary.currency,\n );\n\n const taxableAmount = subtract(\n getDinero(itemSummary.itemPrice, itemSummary.currency),\n discountAllocatedAmount,\n );\n\n return {\n itemPrice: itemSummary.itemPrice,\n taxableAmount: amount(taxableAmount),\n discountAmount: amount(discountAllocatedAmount),\n currency: itemSummary.currency,\n quantity: 1,\n } as SingleLineItemSummary;\n });\n};\n\nexport const calculateWholeQtyLineItemTax = (\n itemSummary: LineItemSummary,\n taxRate: TaxRate,\n): Dino => {\n // Nothing to calculate\n if (taxRate === 0) {\n return getDinero(0, itemSummary.currency);\n }\n\n /**\n * Historically we calculate the tax by using dinero allocation, but we did not have control over how we round things.\n * So instead as we are already working with currency in cents we can multiply and round it ourselves.\n */\n return dinero({\n amount: Round.Financial(itemSummary.taxableAmount * taxRate),\n currency: getDineroCurrency(itemSummary.currency),\n });\n};\n\nexport const calculatePerQtyLineItemTax = (\n itemSummary: LineItemSummary,\n taxRate: TaxRate,\n): Dino => {\n // Nothing to calculate\n if (taxRate === 0) {\n return getDinero(0, itemSummary.currency);\n }\n\n // Split the item summary into per individual item qty summaries\n const singleItemSummaries = allocatePerItemTaxableAmount(itemSummary);\n\n // Calculate individual item qty tax and sum them up\n let totalTaxAmount = getDinero(0, itemSummary.currency);\n\n singleItemSummaries.forEach((itemSummary) => {\n // Probably a bit confusing at first, but calling the whole qty tax calculation function here as we can safely use\n // it as item summary is always a single item summary here\n const taxAmount = calculateWholeQtyLineItemTax(itemSummary, taxRate);\n totalTaxAmount = add(totalTaxAmount, taxAmount);\n });\n\n return totalTaxAmount;\n};\n"],"names":["allocatePerItemTaxableAmount","itemSummary","quantity","preDiscountAmount","add","getDinero","taxableAmount","currency","discountAmount","allocator","FixedAmountAllocator","initialAllocateAmount","initialTotalAmount","amount","Array","from","length","discountAllocatedAmount","allocate","itemPrice","subtract","calculateWholeQtyLineItemTax","taxRate","dinero","Round","Financial","getDineroCurrency","calculatePerQtyLineItemTax","singleItemSummaries","totalTaxAmount","forEach","taxAmount"],"mappings":";;;;;;;AAoBa,MAAAA,4BAAA,GACXC,WAC4B,IAAA;EAIxB,IAAAA,WAAA,CAAYC,aAAa,CAAG,EAAA;IAC9B,OAAO,CAACD,WAAoC,CAAA;EAAA;EAI9C,MAAME,iBAAoB,GAAAC,SAAA,CAAAA,GAAA,CACxBC,IAAAA,CAAAA,SAAU,CAAAJ,WAAA,CAAYK,aAAe,EAAAL,WAAA,CAAYM,QAAQ,CAAA,EACzDF,IAAAA,CAAAA,SAAU,CAAAJ,WAAA,CAAYO,cAAgB,EAAAP,WAAA,CAAYM,QAAQ,CAC5D,CAAA;EAEM,MAAAE,SAAA,GAAY,IAAIC,gCAAqB,CAAA;IACzCC,uBAAuBV,WAAY,CAAAO,cAAA;IACnCI,kBAAA,EAAoBC,YAAOV,iBAAiB,CAAA;IAC5CI,UAAUN,WAAY,CAAAM;EAAA,CACvB,CAAA;EAGD,OAAOO,MAAMC,IAAK,CAAA;IAAEC,QAAQf,WAAY,CAAAC;EAAA,GAAY,MAAM;IACxD,MAAM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AAA;IAGrC,MAAA8B,SAAA,GAAYV,4BAA6BpB,CAAAA,YAAAA,EAAaqB,OAAO,CAAA;IAClDO,cAAA,GAAAzB,SAAAA,CAAAA,GAAA,CAAIyB,gBAAgBE,SAAS,CAAA;EAAA,CAC/C,CAAA;EAEM,OAAAF,cAAA;AACT,CAAA;;;"}
@@ -0,0 +1,52 @@
1
+ import { add, subtract, dinero } from 'dinero.js';
2
+ import { FixedAmountAllocator } from './allocators/fixedAmount.mjs';
3
+ import { Round } from './constants.mjs';
4
+ import { getDinero, amount, getDineroCurrency } from './misc.mjs';
5
+ "use strict";
6
+ const allocatePerItemTaxableAmount = itemSummary => {
7
+ if (itemSummary.quantity === 1) {
8
+ return [itemSummary];
9
+ }
10
+ const preDiscountAmount = add(getDinero(itemSummary.taxableAmount, itemSummary.currency), getDinero(itemSummary.discountAmount, itemSummary.currency));
11
+ const allocator = new FixedAmountAllocator({
12
+ initialAllocateAmount: itemSummary.discountAmount,
13
+ initialTotalAmount: amount(preDiscountAmount),
14
+ currency: itemSummary.currency
15
+ });
16
+ return Array.from({
17
+ length: itemSummary.quantity
18
+ }, () => {
19
+ const discountAllocatedAmount = allocator.allocate(itemSummary.itemPrice, itemSummary.currency);
20
+ const taxableAmount = subtract(getDinero(itemSummary.itemPrice, itemSummary.currency), discountAllocatedAmount);
21
+ return {
22
+ itemPrice: itemSummary.itemPrice,
23
+ taxableAmount: amount(taxableAmount),
24
+ discountAmount: amount(discountAllocatedAmount),
25
+ currency: itemSummary.currency,
26
+ quantity: 1
27
+ };
28
+ });
29
+ };
30
+ const calculateWholeQtyLineItemTax = (itemSummary, taxRate) => {
31
+ if (taxRate === 0) {
32
+ return getDinero(0, itemSummary.currency);
33
+ }
34
+ return dinero({
35
+ amount: Round.Financial(itemSummary.taxableAmount * taxRate),
36
+ currency: getDineroCurrency(itemSummary.currency)
37
+ });
38
+ };
39
+ const calculatePerQtyLineItemTax = (itemSummary, taxRate) => {
40
+ if (taxRate === 0) {
41
+ return getDinero(0, itemSummary.currency);
42
+ }
43
+ const singleItemSummaries = allocatePerItemTaxableAmount(itemSummary);
44
+ let totalTaxAmount = getDinero(0, itemSummary.currency);
45
+ singleItemSummaries.forEach(itemSummary2 => {
46
+ const taxAmount = calculateWholeQtyLineItemTax(itemSummary2, taxRate);
47
+ totalTaxAmount = add(totalTaxAmount, taxAmount);
48
+ });
49
+ return totalTaxAmount;
50
+ };
51
+ export { allocatePerItemTaxableAmount, calculatePerQtyLineItemTax, calculateWholeQtyLineItemTax };
52
+ //# sourceMappingURL=tax.private.mjs.map