@ubnt/store.core 9.20.0 → 9.21.0

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 (127) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/lib/assets/close.svg +1 -4
  3. package/lib/assets/close2.svg +3 -1
  4. package/lib/assets/close3.svg +3 -2
  5. package/lib/assets/minus4.svg +8 -8
  6. package/lib/assets/minus5.svg +8 -8
  7. package/lib/assets/plus5.svg +9 -9
  8. package/lib/assets/plus6.svg +9 -9
  9. package/lib/components/CustomImage/CustomImage.js +1 -1
  10. package/lib/components/CustomImage/CustomImage.mjs +1 -1
  11. package/lib/components/FeaturesSection_deprecated/FeaturesSection.js +1 -1
  12. package/lib/components/FeaturesSection_deprecated/FeaturesSection.mjs +1 -1
  13. package/lib/components/FeaturesSection_deprecated/assets/close.svg.js +1 -1
  14. package/lib/components/FeaturesSection_deprecated/assets/close.svg.mjs +2 -2
  15. package/lib/components/GridGallery/GridModal/GridModal.js +1 -1
  16. package/lib/components/GridGallery/GridModal/GridModal.mjs +1 -1
  17. package/lib/components/Header/CartModalV2/CartModal.js +1 -1
  18. package/lib/components/Header/CartModalV2/CartModal.mjs +1 -1
  19. package/lib/components/Header/Header.js +1 -1
  20. package/lib/components/Header/Header.mjs +1 -1
  21. package/lib/components/LandingPagePro/LandingPagePro.d.ts +3 -0
  22. package/lib/components/LandingPagePro/LandingPagePro.js +3 -3
  23. package/lib/components/LandingPagePro/LandingPagePro.js.map +1 -1
  24. package/lib/components/LandingPagePro/LandingPagePro.mjs +2 -2
  25. package/lib/components/LandingPagePro/LandingPagePro.mjs.map +1 -1
  26. package/lib/components/LandingPageSidebar/LandingPageSidebar.js +1 -1
  27. package/lib/components/LandingPageSidebar/LandingPageSidebar.mjs +1 -1
  28. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputSections/CounterSection.js +2 -2
  29. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputSections/CounterSection.mjs +2 -2
  30. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/minus.svg.js +1 -1
  31. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/minus.svg.mjs +2 -2
  32. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/plus.svg.js +1 -1
  33. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/plus.svg.mjs +2 -2
  34. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.js +2 -2
  35. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.mjs +2 -2
  36. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/assets/minus.svg.js +1 -1
  37. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/assets/minus.svg.mjs +2 -2
  38. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/assets/plus.svg.js +1 -1
  39. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/assets/plus.svg.mjs +2 -2
  40. package/lib/components/Search/Input/Input.js +1 -1
  41. package/lib/components/Search/Input/Input.mjs +1 -1
  42. package/lib/components/VideoPlayerNew/VideoPlayer.js +1 -1
  43. package/lib/components/VideoPlayerNew/VideoPlayer.mjs +1 -1
  44. package/lib/components/VideoPlayerNew/assets/close.svg.js +1 -1
  45. package/lib/components/VideoPlayerNew/assets/close.svg.mjs +2 -2
  46. package/lib/constants/icons/generic/close.svg.js +1 -1
  47. package/lib/constants/icons/generic/close.svg.mjs +2 -2
  48. package/lib/constants/icons/generic/index.js +1 -1
  49. package/lib/constants/icons/generic/index.mjs +1 -1
  50. package/lib/constants/icons/options/colors/black.svg.js +5 -5
  51. package/lib/constants/icons/options/colors/index.js +3 -3
  52. package/lib/constants/icons/options/styles/black.svg.js +5 -5
  53. package/lib/constants/icons/options/styles/index.js +3 -3
  54. package/lib/constants/optionIcons.js +6 -6
  55. package/lib/constants/optionIcons.mjs +4 -4
  56. package/lib/utils/money/allocators/fixedAmount.d.ts +26 -0
  57. package/lib/utils/money/allocators/fixedAmount.js +52 -0
  58. package/lib/utils/money/allocators/fixedAmount.js.map +1 -0
  59. package/lib/utils/money/allocators/fixedAmount.mjs +50 -0
  60. package/lib/utils/money/allocators/fixedAmount.mjs.map +1 -0
  61. package/lib/utils/money/allocators/index.d.ts +2 -0
  62. package/lib/utils/money/allocators/index.js +8 -0
  63. package/lib/utils/money/allocators/index.js.map +1 -0
  64. package/lib/utils/money/allocators/index.mjs +4 -0
  65. package/lib/utils/money/allocators/index.mjs.map +1 -0
  66. package/lib/utils/money/allocators/productAmount.d.ts +13 -0
  67. package/lib/utils/money/allocators/productAmount.js +98 -0
  68. package/lib/utils/money/allocators/productAmount.js.map +1 -0
  69. package/lib/utils/money/allocators/productAmount.mjs +96 -0
  70. package/lib/utils/money/allocators/productAmount.mjs.map +1 -0
  71. package/lib/utils/money/constants.d.ts +60 -22
  72. package/lib/utils/money/constants.js +71 -7
  73. package/lib/utils/money/constants.js.map +1 -1
  74. package/lib/utils/money/constants.mjs +68 -6
  75. package/lib/utils/money/constants.mjs.map +1 -1
  76. package/lib/utils/money/exchangeRate.d.ts +31 -0
  77. package/lib/utils/money/exchangeRate.js +27 -0
  78. package/lib/utils/money/exchangeRate.js.map +1 -0
  79. package/lib/utils/money/exchangeRate.mjs +23 -0
  80. package/lib/utils/money/exchangeRate.mjs.map +1 -0
  81. package/lib/utils/money/format.d.ts +10 -5
  82. package/lib/utils/money/format.js +22 -14
  83. package/lib/utils/money/format.js.map +1 -1
  84. package/lib/utils/money/format.mjs +23 -16
  85. package/lib/utils/money/format.mjs.map +1 -1
  86. package/lib/utils/money/index.d.ts +4 -1
  87. package/lib/utils/money/index.js +25 -8
  88. package/lib/utils/money/index.js.map +1 -1
  89. package/lib/utils/money/index.mjs +7 -4
  90. package/lib/utils/money/index.mjs.map +1 -1
  91. package/lib/utils/money/misc.d.ts +68 -28
  92. package/lib/utils/money/misc.js +35 -64
  93. package/lib/utils/money/misc.js.map +1 -1
  94. package/lib/utils/money/misc.mjs +32 -43
  95. package/lib/utils/money/misc.mjs.map +1 -1
  96. package/lib/utils/money/misc.private.d.ts +23 -0
  97. package/lib/utils/money/misc.private.js +46 -0
  98. package/lib/utils/money/misc.private.js.map +1 -0
  99. package/lib/utils/money/misc.private.mjs +21 -0
  100. package/lib/utils/money/misc.private.mjs.map +1 -0
  101. package/lib/utils/money/shipping.d.ts +5 -0
  102. package/lib/utils/money/shipping.js +8 -0
  103. package/lib/utils/money/shipping.js.map +1 -0
  104. package/lib/utils/money/shipping.mjs +6 -0
  105. package/lib/utils/money/shipping.mjs.map +1 -0
  106. package/lib/utils/money/tax.d.ts +38 -2
  107. package/lib/utils/money/tax.js +46 -10
  108. package/lib/utils/money/tax.js.map +1 -1
  109. package/lib/utils/money/tax.mjs +42 -11
  110. package/lib/utils/money/tax.mjs.map +1 -1
  111. package/lib/utils/money/tax.private.d.ts +17 -0
  112. package/lib/utils/money/tax.private.js +65 -0
  113. package/lib/utils/money/tax.private.js.map +1 -0
  114. package/lib/utils/money/tax.private.mjs +60 -0
  115. package/lib/utils/money/tax.private.mjs.map +1 -0
  116. package/lib/utils/money/types.d.ts +78 -3
  117. package/lib/utils/number.d.ts +1 -1
  118. package/lib/utils/number.js +1 -1
  119. package/lib/utils/number.js.map +1 -1
  120. package/lib/utils/number.mjs +1 -1
  121. package/lib/utils/number.mjs.map +1 -1
  122. package/package.json +1 -1
  123. package/lib/utils/validations.d.ts +0 -15
  124. package/lib/utils/validations.js +0 -23
  125. package/lib/utils/validations.js.map +0 -1
  126. package/lib/utils/validations.mjs +0 -21
  127. package/lib/utils/validations.mjs.map +0 -1
@@ -1,33 +1,50 @@
1
1
  'use strict';
2
2
 
3
+ require('./allocators/index.js');
3
4
  var constants = require('./constants.js');
5
+ var exchangeRate = require('./exchangeRate.js');
4
6
  var format = require('./format.js');
5
7
  var misc = require('./misc.js');
6
- require('./types.js');
8
+ var shipping = require('./shipping.js');
7
9
  var tax = require('./tax.js');
10
+ require('./types.js');
8
11
  "use strict";
9
- exports.currencyObjLookup = constants.currencyObjLookup;
10
- exports.financialRound = constants.financialRound;
11
- exports.maximumPriceFilterLookup = constants.maximumPriceFilterLookup;
12
+ exports.EXCHANGE_RATE_DINERO_CURRENCY = constants.EXCHANGE_RATE_DINERO_CURRENCY;
13
+ exports.Round = constants.Round;
14
+ exports.TAX_RATE_DINERO_CURRENCY = constants.TAX_RATE_DINERO_CURRENCY;
15
+ exports.localizedCurrencyLookup = constants.localizedCurrencyLookup;
12
16
  exports.prettifyPriceLookup = constants.prettifyPriceLookup;
13
17
  exports.smallestSubunitLookup = constants.smallestSubunitLookup;
18
+ exports.storesWithPerItemTaxRate = constants.storesWithPerItemTaxRate;
19
+ exports.invertExchangeRate = exchangeRate.invertExchangeRate;
20
+ exports.toFixedExchangeRate = exchangeRate.toFixedExchangeRate;
21
+ exports.toSnapshotExchangeRate = exchangeRate.toSnapshotExchangeRate;
14
22
  exports.formatPrice = format.formatPrice;
15
23
  exports.formatPriceRaw = format.formatPriceRaw;
16
- exports.getCurrencyObj = format.getCurrencyObj;
24
+ exports.getLocalizedCurrency = format.getLocalizedCurrency;
25
+ exports.prettifyTotal = format.prettifyTotal;
17
26
  exports.addMany = misc.addMany;
18
27
  exports.amount = misc.amount;
19
- exports.centsToMajorUnits = misc.centsToMajorUnits;
28
+ exports.centsToCurrencyUnit = misc.centsToCurrencyUnit;
20
29
  exports.currency = misc.currency;
30
+ exports.dineroToCurrencyUnit = misc.dineroToCurrencyUnit;
21
31
  exports.getDinero = misc.getDinero;
22
32
  exports.getDineroCurrency = misc.getDineroCurrency;
23
33
  exports.money = misc.money;
24
34
  exports.multiplyByFullPercent = misc.multiplyByFullPercent;
25
35
  exports.parseCurrencyCode = misc.parseCurrencyCode;
26
36
  exports.parseFloatToDinero = misc.parseFloatToDinero;
27
- exports.prettifyTotal = misc.prettifyTotal;
37
+ exports.parseFloatToDineroRaw = misc.parseFloatToDineroRaw;
38
+ exports.roundDinero = misc.roundDinero;
28
39
  exports.stringAmountToDinero = misc.stringAmountToDinero;
29
40
  exports.subtractMany = misc.subtractMany;
30
41
  exports.toSmallestSubunit = misc.toSmallestSubunit;
31
- exports.allocateTaxAmount = tax.allocateTaxAmount;
42
+ exports.roundShippingPrice = shipping.roundShippingPrice;
43
+ exports.calculateLineItemTax = tax.calculateLineItemTax;
44
+ exports.calculateTotalTaxRate = tax.calculateTotalTaxRate;
45
+ exports.convertDecimalTaxRateToPercentage = tax.convertDecimalTaxRateToPercentage;
46
+ exports.decimalTaxRateToDinero = tax.decimalTaxRateToDinero;
47
+ exports.formatDecimalTaxRate = tax.formatDecimalTaxRate;
32
48
  exports.removeTaxAmount = tax.removeTaxAmount;
49
+ exports.stringTaxRateToFloat = tax.stringTaxRateToFloat;
33
50
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -1,7 +1,10 @@
1
- export { currencyObjLookup, financialRound, maximumPriceFilterLookup, prettifyPriceLookup, smallestSubunitLookup } from './constants.mjs';
2
- export { formatPrice, formatPriceRaw, getCurrencyObj } from './format.mjs';
3
- export { addMany, amount, centsToMajorUnits, currency, getDinero, getDineroCurrency, money, multiplyByFullPercent, parseCurrencyCode, parseFloatToDinero, prettifyTotal, stringAmountToDinero, subtractMany, toSmallestSubunit } from './misc.mjs';
1
+ import './allocators/index.mjs';
2
+ export { EXCHANGE_RATE_DINERO_CURRENCY, Round, TAX_RATE_DINERO_CURRENCY, localizedCurrencyLookup, prettifyPriceLookup, smallestSubunitLookup, storesWithPerItemTaxRate } from './constants.mjs';
3
+ export { invertExchangeRate, toFixedExchangeRate, toSnapshotExchangeRate } from './exchangeRate.mjs';
4
+ export { formatPrice, formatPriceRaw, getLocalizedCurrency, prettifyTotal } from './format.mjs';
5
+ export { addMany, amount, centsToCurrencyUnit, currency, dineroToCurrencyUnit, getDinero, getDineroCurrency, money, multiplyByFullPercent, parseCurrencyCode, parseFloatToDinero, parseFloatToDineroRaw, roundDinero, stringAmountToDinero, subtractMany, toSmallestSubunit } from './misc.mjs';
6
+ export { roundShippingPrice } from './shipping.mjs';
7
+ export { calculateLineItemTax, calculateTotalTaxRate, convertDecimalTaxRateToPercentage, decimalTaxRateToDinero, formatDecimalTaxRate, removeTaxAmount, stringTaxRateToFloat } from './tax.mjs';
4
8
  import './types.mjs';
5
- export { allocateTaxAmount, removeTaxAmount } from './tax.mjs';
6
9
  "use strict";
7
10
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"}
@@ -1,53 +1,72 @@
1
- import type { Dinero, Currency as DineroCurrency } from "dinero.js";
2
1
  import { Currency } from "../../types";
3
- export interface Money {
4
- amount: number;
5
- currency: Currency;
6
- }
7
- /**
8
- * Prettify numbers depending on the currency using rounding down.
9
- * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !
10
- */
11
- export declare const prettifyTotal: (total: Dinero<number>) => Dinero<number>;
2
+ import type { Cents, Dino, DinoCurrency, Money, RoundingFn } from "./types";
12
3
  /**
13
4
  * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.
14
5
  * This util rounds down any unused subunits to closest subunit resolution.
15
6
  *
16
7
  * ! Not to be confused with prettifyTotal
17
8
  */
18
- export declare const toSmallestSubunit: (total: Dinero<number>) => Dinero<number>;
9
+ export declare const toSmallestSubunit: (total: Dino) => Dino;
19
10
  /**
20
11
  * Find Dinero.js currency instance from our Currency enum.
21
12
  * @throws Throws an error if currency is not found!
13
+ *
22
14
  * @example
23
15
  * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance
24
16
  * getDineroCurrency("invalid"); // => throws AssertionError
25
17
  */
26
- export declare const getDineroCurrency: (currency: Currency) => DineroCurrency<number>;
18
+ export declare const getDineroCurrency: (currency: Currency) => DinoCurrency;
27
19
  /**
28
- * Convert Dinero currency to local currency type
20
+ * Convert Dinero currency (case-insensitive) to local currency type
21
+ * @throws Throws an error if currency is not found!
22
+ *
23
+ * @example
24
+ * parseCurrencyCode('usd') // Currency.Usd
25
+ * parseCurrencyCode('JPY') // Currency.Jpy
26
+ * parseCurrencyCode('invalid') // throws AssertionError
29
27
  */
30
28
  export declare const parseCurrencyCode: (code: string) => Currency;
31
29
  /**
32
- * Get major units amount for cents amount and currency
30
+ * Utility to quickly convert cents to a to currency float amount number
31
+ *
32
+ * @example
33
+ * centsToCurrencyUnit(100, "USD") // 1
34
+ * centsToCurrencyUnit(1, "USD") // 0.01
35
+ * centsToCurrencyUnit(420, "USD") // 4.2
36
+ * centsToCurrencyUnit(420, "JPY") // 420
37
+ * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input
38
+ */
39
+ export declare const centsToCurrencyUnit: (centsAmount: Cents, currency: Currency) => number;
40
+ /**
41
+ * Utility to quickly convert dinero instance to a to currency amount number
33
42
  *
34
- * Can look into the approach of dinero core toUnits if we need a more robust approach
35
- * https://github.com/dinerojs/dinero.js/blob/main/packages/core/src/api/toUnits.ts
36
- * Though, based on experimentation, it's a basic division in the end regardless
43
+ * @example
44
+ * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1
45
+ * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01
46
+ * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2
37
47
  */
38
- export declare const centsToMajorUnits: (amount: number, currency: Currency) => number;
48
+ export declare const dineroToCurrencyUnit: (dineroObj: Dino) => number;
39
49
  /**
40
- * Parse arbitrary float amount in a given currency to a dinero object
50
+ * Parse arbitrary float amount in a given currency to a dinero object.
51
+ * Wrapper around `parseFloatToDineroRaw` for easier usage.
41
52
  *
42
53
  * Doesn't work on string float amounts!
43
54
  * @example
44
55
  * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance
45
56
  */
46
- export declare const parseFloatToDinero: (floatAmount: number, currency: Currency) => Dinero<number>;
57
+ export declare const parseFloatToDinero: (floatAmount: number, currency: Currency) => import("dinero.js").Dinero<number>;
58
+ /**
59
+ * Parse arbitrary float amount in a given dinero like currency object to a dinero object.
60
+ * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)
61
+ */
62
+ export declare const parseFloatToDineroRaw: (floatAmount: number, dineroCurrency: DinoCurrency) => import("dinero.js").Dinero<number>;
47
63
  /**
48
64
  * Shorthand for dinero constructor
65
+ *
66
+ * @example
67
+ * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)
49
68
  */
50
- export declare const getDinero: (amount: number, currency: Currency) => Dinero<number>;
69
+ export declare const getDinero: (amount: Cents, currency: Currency) => Dino;
51
70
  /**
52
71
  * Shorthand to get amount from dinero instance
53
72
  *
@@ -58,8 +77,11 @@ export declare const getDinero: (amount: number, currency: Currency) => Dinero<n
58
77
  *
59
78
  * We should call something like: transformScale(d, currency.exponent)
60
79
  * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale
80
+ *
81
+ * @example
82
+ * amount(getDinero(100, Currency.Usd)); // 100
61
83
  */
62
- export declare const amount: (dinero: Dinero<number>) => number;
84
+ export declare const amount: (dinero: Dino) => Cents;
63
85
  /**
64
86
  * Method to multiply dinero amount by full percent.
65
87
  * It also transforms scale back to currency exponent.
@@ -68,24 +90,42 @@ export declare const amount: (dinero: Dinero<number>) => number;
68
90
  * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because
69
91
  * of dinero version we do not control rounding
70
92
  */
71
- export declare const multiplyByFullPercent: (dinero: Dinero<number>, percentIncrease: number) => Dinero<number>;
93
+ export declare const multiplyByFullPercent: (dinero: Dino, percentIncrease: number) => Dino;
72
94
  /**
73
95
  * Shorthand to get currency from dinero instance
96
+ *
97
+ * @example
98
+ * currency(getDinero(100, Currency.Usd)); // Currency.Usd
74
99
  */
75
- export declare const currency: (dinero: Dinero<number>) => Currency;
100
+ export declare const currency: (dinero: Dino) => Currency;
76
101
  /**
77
102
  * Shorthand to get our GraphQL Money type from dinero instance
103
+ *
104
+ * @example
105
+ * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }
78
106
  */
79
- export declare const money: (dinero: Dinero<number>) => Money;
107
+ export declare const money: (dinero: Dino) => Money;
80
108
  /**
81
109
  * Helper to quickly add multiple dinero instances with same currency
110
+ *
111
+ * @example
112
+ * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)
82
113
  */
83
- export declare const addMany: (addends: Array<Dinero<number>>, defaultCurrency: Currency) => Dinero<number>;
114
+ export declare const addMany: (addends: Array<Dino>, defaultCurrency: Currency) => Dino;
84
115
  /**
85
116
  * Helper to quickly subtract multiple dinero instances with same currency
86
117
  */
87
- export declare const subtractMany: (subtractions: Array<Dinero<number>>, defaultCurrency: Currency) => Dinero<number>;
118
+ export declare const subtractMany: (subtractions: Array<Dino>, defaultCurrency: Currency) => Dino;
88
119
  /**
89
120
  * Helper to quickly get dinero object from string
90
121
  */
91
- export declare const stringAmountToDinero: (price: string, currency: Currency) => Dinero<number>;
122
+ export declare const stringAmountToDinero: (price: string, currency: Currency) => import("dinero.js").Dinero<number>;
123
+ /**
124
+ * Helper to quickly round dinero object to closest integer by a given rounding function
125
+ * FIXME: add tests
126
+ *
127
+ * @example
128
+ * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)
129
+ * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)
130
+ */
131
+ export declare const roundDinero: (dinero: Dino, roundingFn: RoundingFn) => Dino;
@@ -1,56 +1,14 @@
1
1
  'use strict';
2
2
 
3
- var currencies = require('@dinero.js/currencies');
4
3
  var dinero_js = require('dinero.js');
5
4
  require('../../types/index.js');
6
5
  var errors = require('../errors.js');
7
6
  var number = require('../number.js');
8
7
  var string = require('../string.js');
9
- var validations = require('../validations.js');
10
8
  var constants = require('./constants.js');
9
+ var misc_private = require('./misc.private.js');
11
10
  var generated = require('../../types/generated.js');
12
- function _interopNamespace(e) {
13
- if (e && e.__esModule) return e;
14
- var n = Object.create(null);
15
- if (e) {
16
- Object.keys(e).forEach(function (k) {
17
- if (k !== 'default') {
18
- var d = Object.getOwnPropertyDescriptor(e, k);
19
- Object.defineProperty(n, k, d.get ? d : {
20
- enumerable: true,
21
- get: function () {
22
- return e[k];
23
- }
24
- });
25
- }
26
- });
27
- }
28
- n["default"] = e;
29
- return Object.freeze(n);
30
- }
31
- var currencies__namespace = /*#__PURE__*/_interopNamespace(currencies);
32
11
  "use strict";
33
- const currencyLookup = new Set(Object.keys(generated.Currency).map(el => el.toString()));
34
- const currenciesMap = new Map(Object.values(currencies__namespace).map(currency2 => [currency2.code, currency2]));
35
- const floatToInt = (floatAmount, base, exponent) => constants.financialRound(floatAmount * Math.pow(base, exponent));
36
- const prettifyTotal = total => {
37
- if (!dinero_js.hasSubUnits(total)) {
38
- return total;
39
- }
40
- const totalJson = total.toJSON();
41
- const minValueInclusiveToRoundDownFrom = constants.prettifyPriceLookup.get(totalJson.currency.code);
42
- if (minValueInclusiveToRoundDownFrom == null || dinero_js.toUnit(total) < minValueInclusiveToRoundDownFrom) {
43
- return total;
44
- }
45
- const roundedUnitPrice = dinero_js.toUnit(total, {
46
- digits: 0,
47
- round: dinero_js.down
48
- });
49
- return dinero_js.dinero({
50
- amount: roundedUnitPrice * Math.pow(totalJson.currency.base, totalJson.currency.exponent),
51
- currency: totalJson.currency
52
- });
53
- };
54
12
  const toSmallestSubunit = total => {
55
13
  if (!dinero_js.hasSubUnits(total)) {
56
14
  return total;
@@ -60,49 +18,47 @@ const toSmallestSubunit = total => {
60
18
  if (roundToDigits == null || roundingMode == null) {
61
19
  return total;
62
20
  }
63
- const roundedUnitPrice = dinero_js.toUnit(total, {
64
- digits: roundToDigits,
65
- round: roundingMode
66
- });
67
- return dinero_js.dinero({
68
- amount: roundedUnitPrice * Math.pow(totalJson.currency.base, totalJson.currency.exponent),
69
- currency: totalJson.currency
70
- });
21
+ return roundDinero(total, roundingMode);
71
22
  };
72
23
  const getDineroCurrency = currency2 => {
73
- const dineroCurrency = currenciesMap.get(currency2);
24
+ const dineroCurrency = misc_private.dineroCurrenciesLookup.get(currency2);
74
25
  errors.assert(!!dineroCurrency, `Unsupported currency: "${currency2}"`);
75
26
  return dineroCurrency;
76
27
  };
77
28
  const parseCurrencyCode = code => {
78
29
  const normalizedCode = string.capitalize(code.toLowerCase());
79
- errors.assert(currencyLookup.has(normalizedCode), `Invalid currency code: ${normalizedCode}`);
30
+ errors.assert(misc_private.currencyLookup.has(normalizedCode), `Invalid currency code: ${normalizedCode}`);
80
31
  return generated.Currency[normalizedCode];
81
32
  };
82
- const centsToMajorUnits = (amount2, currency2) => {
33
+ const centsToCurrencyUnit = (centsAmount, currency2) => {
83
34
  const dineroCurrency = getDineroCurrency(currency2);
84
- const price = dinero_js.dinero({
85
- amount: amount2,
35
+ const dineroObj = dinero_js.dinero({
36
+ amount: centsAmount,
86
37
  currency: dineroCurrency
87
38
  });
88
- const divider = Math.pow(10, dineroCurrency.exponent);
89
- return dinero_js.toSnapshot(price).amount / divider;
39
+ return dineroToCurrencyUnit(dineroObj);
40
+ };
41
+ const dineroToCurrencyUnit = dineroObj => {
42
+ return dinero_js.toUnit(dineroObj);
90
43
  };
91
44
  const parseFloatToDinero = (floatAmount, currency2) => {
92
- number.isFloat(floatAmount, "Amount");
93
45
  const dineroCurrency = getDineroCurrency(currency2);
46
+ return parseFloatToDineroRaw(floatAmount, dineroCurrency);
47
+ };
48
+ const parseFloatToDineroRaw = (floatAmount, dineroCurrency) => {
49
+ number.isFloat(floatAmount, "Amount");
94
50
  const scaleOfGivenAmount = String(floatAmount).split(".")[1]?.length ?? dineroCurrency.exponent;
95
51
  if (scaleOfGivenAmount == null || scaleOfGivenAmount > dineroCurrency.exponent) {
96
52
  throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);
97
53
  }
98
- const rateInt = floatToInt(floatAmount, dineroCurrency.base, dineroCurrency.exponent);
54
+ const rateInt = misc_private.floatToInt(floatAmount, dineroCurrency.base, dineroCurrency.exponent);
99
55
  return dinero_js.dinero({
100
56
  amount: rateInt,
101
57
  currency: dineroCurrency
102
58
  });
103
59
  };
104
60
  const getDinero = (amount2, currency2) => {
105
- validations.isInt(amount2, "Amount");
61
+ number.isInt(amount2, "Amount");
106
62
  return dinero_js.dinero({
107
63
  amount: amount2,
108
64
  currency: getDineroCurrency(currency2)
@@ -134,18 +90,33 @@ const money = dinero2 => {
134
90
  };
135
91
  const addMany = (addends, defaultCurrency) => [...addends, getDinero(0, defaultCurrency)].reduce(dinero_js.add);
136
92
  const subtractMany = (subtractions, defaultCurrency) => [...subtractions, getDinero(0, defaultCurrency)].reduce(dinero_js.subtract);
137
- const stringAmountToDinero = (price, currency2) => parseFloatToDinero(parseFloat(price), currency2);
93
+ const stringAmountToDinero = (price, currency2) =>
94
+ // FIXME: parseFloat seems dangerous O_O
95
+ parseFloatToDinero(parseFloat(price), currency2);
96
+ const roundDinero = (dinero2, roundingFn) => {
97
+ const roundedUnitPrice = dinero_js.toUnit(dinero2, {
98
+ digits: 0,
99
+ round: roundingFn
100
+ });
101
+ const snapshot = dinero_js.toSnapshot(dinero2);
102
+ return dinero2.create({
103
+ amount: roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,
104
+ currency: snapshot.currency
105
+ });
106
+ };
138
107
  exports.addMany = addMany;
139
108
  exports.amount = amount;
140
- exports.centsToMajorUnits = centsToMajorUnits;
109
+ exports.centsToCurrencyUnit = centsToCurrencyUnit;
141
110
  exports.currency = currency;
111
+ exports.dineroToCurrencyUnit = dineroToCurrencyUnit;
142
112
  exports.getDinero = getDinero;
143
113
  exports.getDineroCurrency = getDineroCurrency;
144
114
  exports.money = money;
145
115
  exports.multiplyByFullPercent = multiplyByFullPercent;
146
116
  exports.parseCurrencyCode = parseCurrencyCode;
147
117
  exports.parseFloatToDinero = parseFloatToDinero;
148
- exports.prettifyTotal = prettifyTotal;
118
+ exports.parseFloatToDineroRaw = parseFloatToDineroRaw;
119
+ exports.roundDinero = roundDinero;
149
120
  exports.stringAmountToDinero = stringAmountToDinero;
150
121
  exports.subtractMany = subtractMany;
151
122
  exports.toSmallestSubunit = toSmallestSubunit;
@@ -1 +1 @@
1
- {"version":3,"file":"misc.js","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import * as currencies from \"@dinero.js/currencies\";\nimport type { Dinero, Currency as DineroCurrency } from \"dinero.js\";\nimport {\n add,\n dinero,\n down,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { isInt } from \"../validations\";\nimport {\n financialRound,\n prettifyPriceLookup,\n smallestSubunitLookup,\n} from \"./constants\";\n\nexport interface Money {\n amount: number;\n currency: Currency;\n}\n\n// #############################################################################\n// Private helpers\n// #############################################################################\nconst currencyLookup = new Set(\n Object.keys(Currency).map((el) => el.toString()),\n);\n\n/**\n * Creating a map of currencies for way faster lookup then doing a array.find()\n * @see https://stackoverflow.com/a/65604244/1378261\n */\nconst currenciesMap = new Map(\n Object.values(currencies).map((currency) => [currency.code, currency]),\n);\n\n/**\n * Private util to convert a float value into a int. Also applies financial rounding to the value if needed.\n * Inspired by https://v2.dinerojs.com/docs/faq/how-can-i-create-dinero-objects-from-floats\n * @private Just for using within this file, please consider using other methods to solve your issue\n * @example\n * floatToInt(69.10, 10, 2); // 6910\n * floatToInt(42, 10, 2); // 4200\n * floatToInt(0.22, 10, 6); // 220000\n */\nconst floatToInt = (\n floatAmount: number,\n base: number,\n exponent: number,\n): number => financialRound(floatAmount * Math.pow(base, exponent));\n\n// #############################################################################\n// Public functions\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: Dinero<number>): Dinero<number> => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\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 const roundedUnitPrice = toUnit(total, { digits: 0, round: down });\n // Multiplying by 100 to get the cents\n return dinero({\n amount:\n roundedUnitPrice *\n Math.pow(totalJson.currency.base, totalJson.currency.exponent),\n currency: totalJson.currency,\n });\n};\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dinero<number>): Dinero<number> => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n const roundedUnitPrice = toUnit(total, {\n digits: roundToDigits,\n round: roundingMode,\n });\n return dinero({\n amount:\n roundedUnitPrice *\n Math.pow(totalJson.currency.base, totalJson.currency.exponent),\n currency: totalJson.currency,\n });\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (\n currency: Currency,\n): DineroCurrency<number> => {\n const dineroCurrency = currenciesMap.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency to local currency type\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Get major units amount for cents amount and currency\n *\n * Can look into the approach of dinero core toUnits if we need a more robust approach\n * https://github.com/dinerojs/dinero.js/blob/main/packages/core/src/api/toUnits.ts\n * Though, based on experimentation, it's a basic division in the end regardless\n */\nexport const centsToMajorUnits = (\n amount: number,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const price = dinero({ amount, currency: dineroCurrency });\n const divider = Math.pow(10, dineroCurrency.exponent);\n\n return toSnapshot(price).amount / divider;\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n isFloat(floatAmount, \"Amount\");\n\n const dineroCurrency = getDineroCurrency(currency);\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n */\nexport const getDinero = (\n amount: number,\n currency: Currency,\n): Dinero<number> => {\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n */\nexport const amount = (dinero: Dinero<number>): number => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dinero<number>,\n percentIncrease: number,\n): Dinero<number> => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n */\nexport const currency = (dinero: Dinero<number>): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n */\nexport const money = (dinero: Dinero<number>): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n */\nexport const addMany = (\n addends: Array<Dinero<number>>,\n defaultCurrency: Currency,\n) => [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dinero<number>>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n parseFloatToDinero(parseFloat(price), currency);\n"],"names":["currencyLookup","Set","Object","keys","Currency","map","el","toString","currenciesMap","Map","values","currencies","currency","code","floatToInt","floatAmount","base","exponent","financialRound","Math","pow","prettifyTotal","total","hasSubUnits","totalJson","toJSON","minValueInclusiveToRoundDownFrom","prettifyPriceLookup","get","toUnit","roundedUnitPrice","digits","round","down","dinero","amount","toSmallestSubunit","roundToDigits","roundingMode","smallestSubunitLookup","getDineroCurrency","dineroCurrency","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","has","centsToMajorUnits","price","divider","toSnapshot","parseFloatToDinero","isFloat","scaleOfGivenAmount","String","split","length","Error","rateInt","getDinero","isInt","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","parseFloat"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAMA,iBAAiB,IAAIC,GAAA,CACzBC,MAAA,CAAOC,KAAKC,SAAAA,CAAAA,QAAQ,CAAA,CAAEC,IAAKC,EAAA,IAAO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AQ,CAAA;AAKxD,MAAAC,oBAAA,GAAuBA,CAAC5B,KAAerC,EAAAA,SAAAA,KAClDwC,mBAAmB0B,UAAW,CAAA7B,KAAK,GAAGrC,SAAQ,CAAA;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"misc.js","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n amount:\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create"],"mappings":";;;;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,SAAAA,CAAAA,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,SAAA,CAAAA,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,aAAA,IAAiB,IAAQ,IAAAC,YAAA,IAAgB,IAAM,EAAA;IAC1C,OAAAL,KAAA;EACT;EAEO,OAAAU,WAAA,CAAYV,OAAOK,YAAY,CAAA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Q0B,SAAS3D,QAAS,CAAA6B,QAAA;IACjE7B,UAAU2D,QAAS,CAAA3D;EAAA,CACpB,CAAA;AACH,CAAA;;;;;;;;;;;;;;;;"}
@@ -1,34 +1,12 @@
1
- import * as currencies from '@dinero.js/currencies';
2
- import { hasSubUnits, toUnit, down, dinero, toSnapshot, multiply, transformScale, add, subtract } from 'dinero.js';
1
+ import { hasSubUnits, dinero, toUnit, toSnapshot, multiply, transformScale, add, subtract } from 'dinero.js';
3
2
  import '../../types/index.mjs';
4
3
  import { assert } from '../errors.mjs';
5
- import { isFloat } from '../number.mjs';
4
+ import { isFloat, isInt } from '../number.mjs';
6
5
  import { capitalize } from '../string.mjs';
7
- import { isInt } from '../validations.mjs';
8
- import { financialRound, prettifyPriceLookup, smallestSubunitLookup } from './constants.mjs';
6
+ import { smallestSubunitLookup } from './constants.mjs';
7
+ import { dineroCurrenciesLookup, currencyLookup, floatToInt } from './misc.private.mjs';
9
8
  import { Currency } from '../../types/generated.mjs';
10
9
  "use strict";
11
- const currencyLookup = new Set(Object.keys(Currency).map(el => el.toString()));
12
- const currenciesMap = new Map(Object.values(currencies).map(currency2 => [currency2.code, currency2]));
13
- const floatToInt = (floatAmount, base, exponent) => financialRound(floatAmount * Math.pow(base, exponent));
14
- const prettifyTotal = total => {
15
- if (!hasSubUnits(total)) {
16
- return total;
17
- }
18
- const totalJson = total.toJSON();
19
- const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(totalJson.currency.code);
20
- if (minValueInclusiveToRoundDownFrom == null || toUnit(total) < minValueInclusiveToRoundDownFrom) {
21
- return total;
22
- }
23
- const roundedUnitPrice = toUnit(total, {
24
- digits: 0,
25
- round: down
26
- });
27
- return dinero({
28
- amount: roundedUnitPrice * Math.pow(totalJson.currency.base, totalJson.currency.exponent),
29
- currency: totalJson.currency
30
- });
31
- };
32
10
  const toSmallestSubunit = total => {
33
11
  if (!hasSubUnits(total)) {
34
12
  return total;
@@ -38,17 +16,10 @@ const toSmallestSubunit = total => {
38
16
  if (roundToDigits == null || roundingMode == null) {
39
17
  return total;
40
18
  }
41
- const roundedUnitPrice = toUnit(total, {
42
- digits: roundToDigits,
43
- round: roundingMode
44
- });
45
- return dinero({
46
- amount: roundedUnitPrice * Math.pow(totalJson.currency.base, totalJson.currency.exponent),
47
- currency: totalJson.currency
48
- });
19
+ return roundDinero(total, roundingMode);
49
20
  };
50
21
  const getDineroCurrency = currency2 => {
51
- const dineroCurrency = currenciesMap.get(currency2);
22
+ const dineroCurrency = dineroCurrenciesLookup.get(currency2);
52
23
  assert(!!dineroCurrency, `Unsupported currency: "${currency2}"`);
53
24
  return dineroCurrency;
54
25
  };
@@ -57,18 +28,23 @@ const parseCurrencyCode = code => {
57
28
  assert(currencyLookup.has(normalizedCode), `Invalid currency code: ${normalizedCode}`);
58
29
  return Currency[normalizedCode];
59
30
  };
60
- const centsToMajorUnits = (amount2, currency2) => {
31
+ const centsToCurrencyUnit = (centsAmount, currency2) => {
61
32
  const dineroCurrency = getDineroCurrency(currency2);
62
- const price = dinero({
63
- amount: amount2,
33
+ const dineroObj = dinero({
34
+ amount: centsAmount,
64
35
  currency: dineroCurrency
65
36
  });
66
- const divider = Math.pow(10, dineroCurrency.exponent);
67
- return toSnapshot(price).amount / divider;
37
+ return dineroToCurrencyUnit(dineroObj);
38
+ };
39
+ const dineroToCurrencyUnit = dineroObj => {
40
+ return toUnit(dineroObj);
68
41
  };
69
42
  const parseFloatToDinero = (floatAmount, currency2) => {
70
- isFloat(floatAmount, "Amount");
71
43
  const dineroCurrency = getDineroCurrency(currency2);
44
+ return parseFloatToDineroRaw(floatAmount, dineroCurrency);
45
+ };
46
+ const parseFloatToDineroRaw = (floatAmount, dineroCurrency) => {
47
+ isFloat(floatAmount, "Amount");
72
48
  const scaleOfGivenAmount = String(floatAmount).split(".")[1]?.length ?? dineroCurrency.exponent;
73
49
  if (scaleOfGivenAmount == null || scaleOfGivenAmount > dineroCurrency.exponent) {
74
50
  throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);
@@ -112,6 +88,19 @@ const money = dinero2 => {
112
88
  };
113
89
  const addMany = (addends, defaultCurrency) => [...addends, getDinero(0, defaultCurrency)].reduce(add);
114
90
  const subtractMany = (subtractions, defaultCurrency) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);
115
- const stringAmountToDinero = (price, currency2) => parseFloatToDinero(parseFloat(price), currency2);
116
- export { addMany, amount, centsToMajorUnits, currency, getDinero, getDineroCurrency, money, multiplyByFullPercent, parseCurrencyCode, parseFloatToDinero, prettifyTotal, stringAmountToDinero, subtractMany, toSmallestSubunit };
91
+ const stringAmountToDinero = (price, currency2) =>
92
+ // FIXME: parseFloat seems dangerous O_O
93
+ parseFloatToDinero(parseFloat(price), currency2);
94
+ const roundDinero = (dinero2, roundingFn) => {
95
+ const roundedUnitPrice = toUnit(dinero2, {
96
+ digits: 0,
97
+ round: roundingFn
98
+ });
99
+ const snapshot = toSnapshot(dinero2);
100
+ return dinero2.create({
101
+ amount: roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,
102
+ currency: snapshot.currency
103
+ });
104
+ };
105
+ export { addMany, amount, centsToCurrencyUnit, currency, dineroToCurrencyUnit, getDinero, getDineroCurrency, money, multiplyByFullPercent, parseCurrencyCode, parseFloatToDinero, parseFloatToDineroRaw, roundDinero, stringAmountToDinero, subtractMany, toSmallestSubunit };
117
106
  //# sourceMappingURL=misc.mjs.map