1 | import ChannelContext from '@jetshop/core/components/ChannelContext';
|
2 | import { useContext } from 'react';
|
3 | import get from 'lodash.get';
|
4 | import { useIntl } from '@jetshop/intl';
|
5 |
|
6 |
|
7 | export 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 |
|
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 |
|
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 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 | export 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 |
|
72 |
|
\ | No newline at end of file |