UNPKG

2.4 kBJavaScriptView Raw
1import ChannelContext from '@jetshop/core/components/ChannelContext';
2import { useContext } from 'react';
3import get from 'lodash.get';
4import { useIntl } from '@jetshop/intl';
5// #endregion Interfaces
6// #region
7export function usePrice({ currencyOverride, price, previousPrice, includeVat, formatter: defaultFormatter }) {
8 const context = useContext(ChannelContext);
9 const t = useIntl();
10 if (!context || !context.selectedChannel)
11 return null;
12 let formatter = defaultFormatter;
13 if (!formatter) {
14 formatter = t.number;
15 }
16 const { selectedChannel: { settings, currency } } = context;
17 /** Get the locale to be passed to the t.price formatter */
18 const currencyLocale = currencyOverride
19 ? { code: currencyOverride.code, culture: currencyOverride.culture }
20 : {
21 code: currency.name || undefined,
22 culture: currency.format ? currency.format.culture : undefined
23 };
24 /** Allow incVat to be overriden */
25 const incVat = typeof includeVat !== 'undefined'
26 ? includeVat
27 : get(settings, 'pricesIncVat', true);
28 /** Convert the pricing to {value: number} */
29 const pricing = {
30 price: selectPriceType(incVat, price),
31 previousPrice: previousPrice
32 ? selectPriceType(incVat, previousPrice)
33 : { value: 0, vat: 0 }
34 };
35 const formattedPricing = {
36 previousPrice: null,
37 price: null
38 };
39 for (const val in pricing) {
40 if (pricing.hasOwnProperty(val) && pricing[val]) {
41 formattedPricing[val] = formatter(pricing[val].value, currencyLocale.code, currencyLocale.culture);
42 }
43 }
44 return {
45 hasDiscount: pricing.previousPrice && pricing.previousPrice.value
46 ? pricing.price.value < pricing.previousPrice.value
47 : false,
48 includesVat: incVat,
49 currencyLocale,
50 pricing,
51 formattedPricing
52 };
53}
54// #endregion Container Component
55// #region Utilities
56/**
57 * Normalise the price to an object with keys `value` and `vat`
58 */
59export function selectPriceType(includeVat, priceObj) {
60 if (!priceObj)
61 return null;
62 const { vat, exVat, incVat } = priceObj;
63 if (includeVat) {
64 return { vat, value: incVat };
65 }
66 return {
67 vat,
68 value: exVat
69 };
70}
71// #endregion Utilities
72//# sourceMappingURL=usePrice.js.map
\No newline at end of file