mirror of
https://github.com/kingomarnajjar/flex-template-web.git
synced 2026-07-28 20:53:24 +10:00
Merge pull request #364 from sharetribe/clean-up-money-handling
Clean up money handling
This commit is contained in:
commit
bb2b229f81
23 changed files with 111 additions and 131 deletions
|
|
@ -7,7 +7,7 @@ import { FormattedMessage, FormattedHTMLMessage, intlShape, injectIntl } from 'r
|
|||
import Decimal from 'decimal.js';
|
||||
import classNames from 'classnames';
|
||||
import config from '../../config';
|
||||
import { convertMoneyToNumber } from '../../util/currency';
|
||||
import { convertMoneyToNumber, formatMoney } from '../../util/currency';
|
||||
import * as propTypes from '../../util/propTypes';
|
||||
|
||||
import css from './BookingBreakdown.css';
|
||||
|
|
@ -68,16 +68,15 @@ export const BookingBreakdownComponent = props => {
|
|||
);
|
||||
|
||||
const currencyConfig = config.currencyConfig;
|
||||
const subUnitDivisor = currencyConfig.subUnitDivisor;
|
||||
|
||||
const unitPriceAsNumber = convertMoneyToNumber(nightPurchase.unitPrice, subUnitDivisor);
|
||||
const formattedUnitPrice = intl.formatNumber(unitPriceAsNumber, currencyConfig);
|
||||
const formattedUnitPrice = formatMoney(intl, nightPurchase.unitPrice);
|
||||
|
||||
// If commission is passed it will be shown as a fee already reduces from the total price
|
||||
let subTotalInfo = null;
|
||||
let commissionInfo = null;
|
||||
|
||||
if (userRole === 'provider') {
|
||||
// TODO: Calculate subtotal from provider total and the commission
|
||||
const unitPriceAsNumber = convertMoneyToNumber(nightPurchase.unitPrice);
|
||||
const subTotal = new Decimal(nightCount).times(unitPriceAsNumber).toNumber();
|
||||
const formattedSubTotal = intl.formatNumber(subTotal, currencyConfig);
|
||||
|
||||
|
|
@ -91,10 +90,7 @@ export const BookingBreakdownComponent = props => {
|
|||
);
|
||||
|
||||
const commission = providerCommission.lineTotal;
|
||||
const commissionAsNumber = commission ? convertMoneyToNumber(commission, subUnitDivisor) : 0;
|
||||
const formattedCommission = commission
|
||||
? intl.formatNumber(new Decimal(commissionAsNumber).toNumber(), currencyConfig)
|
||||
: null;
|
||||
const formattedCommission = commission ? formatMoney(intl, commission) : null;
|
||||
|
||||
commissionInfo = (
|
||||
<div className={css.lineItem}>
|
||||
|
|
@ -111,13 +107,8 @@ export const BookingBreakdownComponent = props => {
|
|||
: <FormattedMessage id="BookingBreakdown.providerTotal" />;
|
||||
const totalLabel = totalLabelMessage || defaultTotalLabel;
|
||||
|
||||
const totalPriceAsNumber = convertMoneyToNumber(
|
||||
userRole === 'customer' ? payinTotal : payoutTotal,
|
||||
subUnitDivisor
|
||||
);
|
||||
const formattedTotalPrice = totalPriceAsNumber
|
||||
? intl.formatNumber(totalPriceAsNumber, currencyConfig)
|
||||
: null;
|
||||
const totalPrice = userRole === 'customer' ? payinTotal : payoutTotal;
|
||||
const formattedTotalPrice = formatMoney(intl, totalPrice);
|
||||
|
||||
return (
|
||||
<div className={classes}>
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { ValidationError } from '../../components';
|
|||
import { types } from '../../util/sdkLoader';
|
||||
import {
|
||||
isSafeNumber,
|
||||
unitDivisor,
|
||||
convertUnitToSubUnit,
|
||||
convertMoneyToNumber,
|
||||
ensureDotSeparator,
|
||||
|
|
@ -36,7 +37,7 @@ const getPrice = (unformattedValue, currencyConfig) => {
|
|||
return isEmptyString
|
||||
? null
|
||||
: new types.Money(
|
||||
convertUnitToSubUnit(unformattedValue, currencyConfig.subUnitDivisor),
|
||||
convertUnitToSubUnit(unformattedValue, unitDivisor(currencyConfig.currency)),
|
||||
currencyConfig.currency
|
||||
);
|
||||
} catch (e) {
|
||||
|
|
@ -49,7 +50,7 @@ class CurrencyInputComponent extends Component {
|
|||
super(props);
|
||||
const { currencyConfig, defaultValue, input, intl } = props;
|
||||
const initialValue = input.value instanceof types.Money
|
||||
? convertMoneyToNumber(input.value, currencyConfig.subUnitDivisor)
|
||||
? convertMoneyToNumber(input.value)
|
||||
: defaultValue;
|
||||
const hasInitialValue = typeof initialValue === 'number' && !isNaN(initialValue);
|
||||
|
||||
|
|
@ -64,7 +65,7 @@ class CurrencyInputComponent extends Component {
|
|||
const unformattedValue = hasInitialValue
|
||||
? truncateToSubUnitPrecision(
|
||||
ensureSeparator(initialValue.toString(), usesComma),
|
||||
currencyConfig.subUnitDivisor,
|
||||
unitDivisor(currencyConfig.currency),
|
||||
usesComma
|
||||
)
|
||||
: '';
|
||||
|
|
@ -152,7 +153,7 @@ class CurrencyInputComponent extends Component {
|
|||
// truncate decimals to subunit precision: 10000.999 => 10000.99
|
||||
const truncatedValueString = truncateToSubUnitPrecision(
|
||||
valueOrZero,
|
||||
currencyConfig.subUnitDivisor,
|
||||
unitDivisor(currencyConfig.currency),
|
||||
this.state.usesComma
|
||||
);
|
||||
const unformattedValue = !isEmptyString ? truncatedValueString : '';
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import { EditListingPhotosForm, PayoutDetailsForm } from '../../containers';
|
|||
import { ensureListing } from '../../util/data';
|
||||
import { Modal } from '../../components';
|
||||
import * as propTypes from '../../util/propTypes';
|
||||
import config from '../../config';
|
||||
|
||||
import css from './EditListingPhotosPanel.css';
|
||||
|
||||
|
|
@ -93,7 +92,6 @@ class EditListingPhotosPanel extends Component {
|
|||
const classes = classNames(rootClass, className, {
|
||||
[css.payoutModalOpen]: this.state.showPayoutDetails,
|
||||
});
|
||||
const currency = config.currencyConfig.currency;
|
||||
const currentListing = ensureListing(listing);
|
||||
const { title } = currentListing.attributes;
|
||||
const listingTitle = title || '';
|
||||
|
|
@ -139,7 +137,6 @@ class EditListingPhotosPanel extends Component {
|
|||
</div>
|
||||
<PayoutDetailsForm
|
||||
className={css.payoutDetails}
|
||||
currency={currency}
|
||||
disabled={fetchInProgress}
|
||||
onSubmit={this.handlePayoutSubmit}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
/* eslint-disable no-console */
|
||||
import React from 'react';
|
||||
import ListingCard from './ListingCard';
|
||||
import { createUser, createListing, currencyConfig, fakeIntl } from '../../util/test-data';
|
||||
import { createUser, createListing, fakeIntl } from '../../util/test-data';
|
||||
|
||||
const author = createUser('user1');
|
||||
const listing = { ...createListing('listing1'), author };
|
||||
|
|
@ -15,7 +15,6 @@ const ListingCardWrapper = props => (
|
|||
export const ListingCardWrapped = {
|
||||
component: ListingCardWrapper,
|
||||
props: {
|
||||
currencyConfig,
|
||||
intl: fakeIntl,
|
||||
listing,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -3,16 +3,16 @@ import { FormattedMessage, intlShape, injectIntl } from 'react-intl';
|
|||
import classNames from 'classnames';
|
||||
import { NamedLink, ResponsiveImage } from '../../components';
|
||||
import * as propTypes from '../../util/propTypes';
|
||||
import { convertMoneyToNumber } from '../../util/currency';
|
||||
import { formatMoney } from '../../util/currency';
|
||||
import { ensureListing, ensureUser } from '../../util/data';
|
||||
import { createSlug } from '../../util/urlHelpers';
|
||||
import config from '../../config';
|
||||
|
||||
import css from './ListingCard.css';
|
||||
|
||||
const priceData = (price, currencyConfig, intl) => {
|
||||
if (price && price.currency === currencyConfig.currency) {
|
||||
const priceAsNumber = convertMoneyToNumber(price, currencyConfig.subUnitDivisor);
|
||||
const formattedPrice = intl.formatNumber(priceAsNumber, currencyConfig);
|
||||
const priceData = (price, intl) => {
|
||||
if (price && price.currency === config.currency) {
|
||||
const formattedPrice = formatMoney(intl, price);
|
||||
return { formattedPrice, priceTitle: formattedPrice };
|
||||
} else if (price) {
|
||||
return {
|
||||
|
|
@ -30,7 +30,7 @@ const priceData = (price, currencyConfig, intl) => {
|
|||
};
|
||||
|
||||
export const ListingCardComponent = props => {
|
||||
const { className, rootClassName, currencyConfig, intl, listing } = props;
|
||||
const { className, rootClassName, intl, listing } = props;
|
||||
const classes = classNames(rootClassName || css.root, className);
|
||||
const currentListing = ensureListing(listing);
|
||||
const id = currentListing.id.uuid;
|
||||
|
|
@ -43,7 +43,7 @@ export const ListingCardComponent = props => {
|
|||
: null;
|
||||
|
||||
// TODO: Currently, API can return currencies that are not supported by starter app.
|
||||
const { formattedPrice, priceTitle } = priceData(price, currencyConfig, intl);
|
||||
const { formattedPrice, priceTitle } = priceData(price, intl);
|
||||
|
||||
return (
|
||||
<NamedLink className={classes} name="ListingPage" params={{ id, slug }}>
|
||||
|
|
@ -96,7 +96,6 @@ const { string } = PropTypes;
|
|||
ListingCardComponent.propTypes = {
|
||||
className: string,
|
||||
rootClassName: string,
|
||||
currencyConfig: propTypes.currencyConfig.isRequired,
|
||||
intl: intlShape.isRequired,
|
||||
listing: propTypes.listing.isRequired,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -7,9 +7,7 @@ describe('ListingCard', () => {
|
|||
it('matches snapshot', () => {
|
||||
const author = createUser('user1');
|
||||
const listing = { ...createListing('listing1'), author };
|
||||
const tree = renderShallow(
|
||||
<ListingCardComponent listing={listing} intl={fakeIntl} currencyConfig={currencyConfig} />
|
||||
);
|
||||
const tree = renderShallow(<ListingCardComponent listing={listing} intl={fakeIntl} />);
|
||||
expect(tree).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -33,8 +33,8 @@ const ListingCard = props => {
|
|||
const { className, clickHandler, flattenedRoutes, history, intl, isInCarousel, listing } = props;
|
||||
|
||||
const { title, price } = listing.attributes;
|
||||
const formattedPrice = price && price.currency === config.currencyConfig.currency
|
||||
? formatMoney(intl, config.currencyConfig, price)
|
||||
const formattedPrice = price && price.currency === config.currency
|
||||
? formatMoney(intl, price)
|
||||
: price.currency;
|
||||
const firstImage = listing.images && listing.images.length > 0 ? listing.images[0] : null;
|
||||
const urlToListing = createURL(flattenedRoutes, history, listing);
|
||||
|
|
|
|||
|
|
@ -30,8 +30,8 @@ class SearchMapPriceLabel extends Component {
|
|||
const { geolocation, price } = currentListing.attributes;
|
||||
|
||||
// Create formatted price if currency is known or alternatively show just the unknown currency.
|
||||
const formattedPrice = price && price.currency === config.currencyConfig.currency
|
||||
? formatMoney(intl, config.currencyConfig, price)
|
||||
const formattedPrice = price && price.currency === config.currency
|
||||
? formatMoney(intl, price)
|
||||
: price.currency;
|
||||
|
||||
// Explicit type change to object literal for Google OverlayViews (geolocation is SDK type)
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { ListingCard, PaginationLinks } from '../../components';
|
|||
import css from './SearchResultsPanel.css';
|
||||
|
||||
const SearchResultsPanel = props => {
|
||||
const { className, rootClassName, currencyConfig, listings, pagination, search } = props;
|
||||
const { className, rootClassName, listings, pagination, search } = props;
|
||||
const classes = classNames(rootClassName || css.root, className);
|
||||
|
||||
const paginationLinks = pagination && pagination.totalPages > 1
|
||||
|
|
@ -20,14 +20,7 @@ const SearchResultsPanel = props => {
|
|||
return (
|
||||
<div className={classes}>
|
||||
<div className={css.listingCards}>
|
||||
{listings.map(l => (
|
||||
<ListingCard
|
||||
className={css.listingCard}
|
||||
key={l.id.uuid}
|
||||
listing={l}
|
||||
currencyConfig={currencyConfig}
|
||||
/>
|
||||
))}
|
||||
{listings.map(l => <ListingCard className={css.listingCard} key={l.id.uuid} listing={l} />)}
|
||||
{props.children}
|
||||
</div>
|
||||
{paginationLinks}
|
||||
|
|
@ -49,7 +42,6 @@ const { array, node, object, string } = PropTypes;
|
|||
SearchResultsPanel.propTypes = {
|
||||
children: node,
|
||||
className: string,
|
||||
currencyConfig: propTypes.currencyConfig.isRequired,
|
||||
listings: array,
|
||||
pagination: propTypes.pagination,
|
||||
rootClassName: string,
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import SearchResultsPanel from './SearchResultsPanel';
|
|||
describe('SearchResultsPanel', () => {
|
||||
it('matches snapshot', () => {
|
||||
const props = {
|
||||
currencyConfig,
|
||||
intl: fakeIntl,
|
||||
};
|
||||
const tree = renderShallow(<SearchResultsPanel {...props} />);
|
||||
|
|
|
|||
|
|
@ -9,17 +9,19 @@ const sdkClientId = process.env.REACT_APP_SHARETRIBE_SDK_CLIENT_ID ||
|
|||
'08ec69f6-d37e-414d-83eb-324e94afddf0';
|
||||
const sdkBaseUrl = process.env.REACT_APP_SHARETRIBE_SDK_BASE_URL || 'http://localhost:8088';
|
||||
|
||||
// Currency configuration contains subUnitsDivisor and formatting for React-Intl
|
||||
// SubUnitDivisor is used to convert Money.amount to presentational value
|
||||
// E.g. 1099¢ / subUnitDivisor = $10.99
|
||||
const currency = process.env.REACT_APP_SHARETRIBE_MARKETPLACE_CURRENCY || 'USD';
|
||||
|
||||
// Currency formatting options.
|
||||
// See: https://github.com/yahoo/react-intl/wiki/API#formatnumber
|
||||
//
|
||||
// TODO: Remove this and hide formating within the util/currency module
|
||||
const currencyConfig = {
|
||||
style: 'currency',
|
||||
currency: process.env.REACT_APP_SHARETRIBE_MARKETPLACE_CURRENCY || 'USD',
|
||||
currency,
|
||||
currencyDisplay: 'symbol',
|
||||
useGrouping: true,
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
subUnitDivisor: 100,
|
||||
};
|
||||
|
||||
const stripePublishableKey = process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY ||
|
||||
|
|
@ -118,6 +120,7 @@ const config = {
|
|||
env,
|
||||
dev,
|
||||
sdk: { clientId: sdkClientId, baseUrl: sdkBaseUrl },
|
||||
currency,
|
||||
currencyConfig,
|
||||
stripe: { publishableKey: stripePublishableKey, supportedCountries: stripeSupportedCountries },
|
||||
};
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import Decimal from 'decimal.js';
|
|||
import { types } from '../../util/sdkLoader';
|
||||
import { required, bookingDatesRequired } from '../../util/validators';
|
||||
import { nightsBetween } from '../../util/dates';
|
||||
import { convertMoneyToNumber, convertUnitToSubUnit } from '../../util/currency';
|
||||
import { unitDivisor, convertMoneyToNumber, convertUnitToSubUnit } from '../../util/currency';
|
||||
import config from '../../config';
|
||||
import { PrimaryButton, BookingBreakdown, DateRangeInputField } from '../../components';
|
||||
|
||||
|
|
@ -19,11 +19,10 @@ import css from './BookingDatesForm.css';
|
|||
// price. This should be removed when the API supports dry-runs and we
|
||||
// can take the total price from the transaction itself.
|
||||
const estimatedTotalPrice = (unitPrice, nightCount) => {
|
||||
const { subUnitDivisor } = config.currencyConfig;
|
||||
const numericPrice = convertMoneyToNumber(unitPrice, subUnitDivisor);
|
||||
const numericPrice = convertMoneyToNumber(unitPrice);
|
||||
const numericTotalPrice = new Decimal(numericPrice).times(nightCount).toNumber();
|
||||
return new types.Money(
|
||||
convertUnitToSubUnit(numericTotalPrice, subUnitDivisor),
|
||||
convertUnitToSubUnit(numericTotalPrice, unitDivisor(unitPrice.currency)),
|
||||
unitPrice.currency
|
||||
);
|
||||
};
|
||||
|
|
@ -73,7 +72,6 @@ export const BookingDatesFormComponent = props => {
|
|||
|
||||
const { startDate, endDate } = bookingDates;
|
||||
const classes = classNames(rootClassName || css.root, className);
|
||||
const { currency: marketplaceCurrency } = config.currencyConfig;
|
||||
|
||||
if (!unitPrice) {
|
||||
return (
|
||||
|
|
@ -84,7 +82,7 @@ export const BookingDatesFormComponent = props => {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
if (unitPrice.currency !== marketplaceCurrency) {
|
||||
if (unitPrice.currency !== config.currency) {
|
||||
return (
|
||||
<div className={classes}>
|
||||
<p className={css.error}>
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import * as propTypes from '../../util/propTypes';
|
|||
import { ensureListing, ensureUser } from '../../util/data';
|
||||
import { withFlattenedRoutes } from '../../util/contextHelpers';
|
||||
import { nightsBetween } from '../../util/dates';
|
||||
import { convertMoneyToNumber, convertUnitToSubUnit } from '../../util/currency';
|
||||
import { unitDivisor, convertMoneyToNumber, convertUnitToSubUnit } from '../../util/currency';
|
||||
import {
|
||||
AvatarMedium,
|
||||
BookingBreakdown,
|
||||
|
|
@ -34,12 +34,11 @@ const STORAGE_KEY = 'CheckoutPage';
|
|||
// price. This should be removed when the API supports dry-runs and we
|
||||
// can take the total price from the transaction itself.
|
||||
const estimatedTotalPrice = (startDate, endDate, unitPrice) => {
|
||||
const { subUnitDivisor } = config.currencyConfig;
|
||||
const numericPrice = convertMoneyToNumber(unitPrice, subUnitDivisor);
|
||||
const numericPrice = convertMoneyToNumber(unitPrice);
|
||||
const nightCount = nightsBetween(startDate, endDate);
|
||||
const numericTotalPrice = new Decimal(numericPrice).times(nightCount).toNumber();
|
||||
return new types.Money(
|
||||
convertUnitToSubUnit(numericTotalPrice, subUnitDivisor),
|
||||
convertUnitToSubUnit(numericTotalPrice, unitDivisor(unitPrice.currency)),
|
||||
unitPrice.currency
|
||||
);
|
||||
};
|
||||
|
|
@ -146,13 +145,12 @@ export class CheckoutPageComponent extends Component {
|
|||
|
||||
// Estimate total price. NOTE: this will change when we can do a
|
||||
// dry-run to the API and get a proper breakdown of the price.
|
||||
const { currency: marketplaceCurrency } = config.currencyConfig;
|
||||
const unitPrice = currentListing.attributes.price;
|
||||
|
||||
if (!unitPrice) {
|
||||
throw new Error('Listing has no price');
|
||||
}
|
||||
if (unitPrice.currency !== marketplaceCurrency) {
|
||||
if (unitPrice.currency !== config.currency) {
|
||||
throw new Error(
|
||||
`Listing currency different from marketplace currency: ${unitPrice.currency}`
|
||||
);
|
||||
|
|
|
|||
|
|
@ -14,7 +14,6 @@ import {
|
|||
TabNav,
|
||||
Topbar,
|
||||
} from '../../components';
|
||||
import config from '../../config';
|
||||
import * as propTypes from '../../util/propTypes';
|
||||
import { formatMoney } from '../../util/currency';
|
||||
import { getMarketplaceEntities } from '../../ducks/marketplaceData.duck';
|
||||
|
|
@ -102,7 +101,7 @@ export const InboxItem = props => {
|
|||
const bookingStart = formatDate(intl, booking.attributes.start);
|
||||
const bookingEnd = formatDate(intl, booking.attributes.end);
|
||||
const bookingPrice = isOrder ? tx.attributes.payinTotal : tx.attributes.payoutTotal;
|
||||
const price = formatMoney(intl, config.currencyConfig, bookingPrice);
|
||||
const price = formatMoney(intl, bookingPrice);
|
||||
|
||||
return (
|
||||
<NamedLink
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import config from '../../config';
|
|||
import * as propTypes from '../../util/propTypes';
|
||||
import { types } from '../../util/sdkLoader';
|
||||
import { createSlug } from '../../util/urlHelpers';
|
||||
import { convertMoneyToNumber } from '../../util/currency';
|
||||
import { formatMoney } from '../../util/currency';
|
||||
import { createResourceLocatorString, findRouteByRouteName } from '../../util/routes';
|
||||
import { ensureListing, ensureUser } from '../../util/data';
|
||||
import {
|
||||
|
|
@ -35,10 +35,9 @@ const MODAL_BREAKPOINT = 1023;
|
|||
|
||||
const { UUID } = types;
|
||||
|
||||
const priceData = (price, currencyConfig, intl) => {
|
||||
if (price && price.currency === currencyConfig.currency) {
|
||||
const priceAsNumber = convertMoneyToNumber(price, currencyConfig.subUnitDivisor);
|
||||
const formattedPrice = intl.formatNumber(priceAsNumber, currencyConfig);
|
||||
const priceData = (price, intl) => {
|
||||
if (price && price.currency === config.currency) {
|
||||
const formattedPrice = formatMoney(intl, price);
|
||||
return { formattedPrice, priceTitle: formattedPrice };
|
||||
} else if (price) {
|
||||
return {
|
||||
|
|
@ -105,7 +104,6 @@ export class ListingPageComponent extends Component {
|
|||
scrollingDisabled,
|
||||
showListingError,
|
||||
} = this.props;
|
||||
const currencyConfig = config.currencyConfig;
|
||||
const currentListing = ensureListing(getListing(new UUID(params.id)));
|
||||
const {
|
||||
address = '',
|
||||
|
|
@ -146,7 +144,7 @@ export class ListingPageComponent extends Component {
|
|||
}
|
||||
|
||||
const bookBtnMessage = intl.formatMessage({ id: 'ListingPage.ctaButtonMessage' });
|
||||
const { formattedPrice, priceTitle } = priceData(price, currencyConfig, intl);
|
||||
const { formattedPrice, priceTitle } = priceData(price, intl);
|
||||
const map = geolocation
|
||||
? <div className={css.locationContainer}>
|
||||
<h3 className={css.locationTitle}>
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import PayoutDetailsForm from './PayoutDetailsForm';
|
|||
export const USD = {
|
||||
component: PayoutDetailsForm,
|
||||
props: {
|
||||
currency: 'USD',
|
||||
onSubmit: values => {
|
||||
console.log('submit payout details:', values);
|
||||
},
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ const PayoutDetailsFormComponent = props => {
|
|||
const {
|
||||
className,
|
||||
country,
|
||||
currency,
|
||||
form,
|
||||
disabled,
|
||||
handleSubmit,
|
||||
|
|
@ -155,7 +154,7 @@ const PayoutDetailsFormComponent = props => {
|
|||
routingNumberId={`${form}.bankAccountToken.routingNumber`}
|
||||
accountNumberId={`${form}.bankAccountToken.accountNumber`}
|
||||
country={country}
|
||||
currency={currency}
|
||||
currency={config.currency}
|
||||
validate={bankAccountRequired}
|
||||
/>
|
||||
</div>
|
||||
|
|
@ -239,7 +238,6 @@ PayoutDetailsFormComponent.propTypes = {
|
|||
...formPropTypes,
|
||||
className: string,
|
||||
disabled: bool,
|
||||
currency: string.isRequired,
|
||||
|
||||
// from mapStateToProps
|
||||
country: string,
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import { compose } from 'redux';
|
|||
import { withRouter } from 'react-router-dom';
|
||||
import { debounce, isEqual, unionWith } from 'lodash';
|
||||
import classNames from 'classnames';
|
||||
import config from '../../config';
|
||||
import { withFlattenedRoutes } from '../../util/contextHelpers';
|
||||
import { googleLatLngToSDKLatLng, googleBoundsToSDKBounds } from '../../util/googleMaps';
|
||||
import { createResourceLocatorString } from '../../util/routes';
|
||||
|
|
@ -264,7 +263,6 @@ export class SearchPageComponent extends Component {
|
|||
>
|
||||
<SearchResultsPanel
|
||||
className={css.searchListingsPanel}
|
||||
currencyConfig={config.currencyConfig}
|
||||
listings={listings}
|
||||
pagination={listingsAreLoaded ? pagination : null}
|
||||
search={searchParamsForPagination}
|
||||
|
|
|
|||
|
|
@ -39,17 +39,6 @@ exports[`SearchPageComponent matches snapshot 1`] = `
|
|||
className="">
|
||||
<SearchResultsPanel
|
||||
className={null}
|
||||
currencyConfig={
|
||||
Object {
|
||||
"currency": "USD",
|
||||
"currencyDisplay": "symbol",
|
||||
"maximumFractionDigits": 2,
|
||||
"minimumFractionDigits": 2,
|
||||
"style": "currency",
|
||||
"subUnitDivisor": 100,
|
||||
"useGrouping": true,
|
||||
}
|
||||
}
|
||||
listings={Array []}
|
||||
pagination={
|
||||
Object {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { trimEnd } from 'lodash';
|
||||
import { has, trimEnd } from 'lodash';
|
||||
import Decimal from 'decimal.js';
|
||||
import { types } from './sdkLoader';
|
||||
import config from '../config';
|
||||
import { subUnitDivisors } from './currencyConfig';
|
||||
|
||||
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
|
||||
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER
|
||||
|
|
@ -15,6 +17,14 @@ export const isSafeNumber = decimalValue => {
|
|||
return decimalValue.gte(MIN_SAFE_INTEGER) && decimalValue.lte(MAX_SAFE_INTEGER);
|
||||
};
|
||||
|
||||
// Get the minor unit divisor for the given currency
|
||||
export const unitDivisor = currency => {
|
||||
if (!has(subUnitDivisors, currency)) {
|
||||
throw new Error(`No minor unit divisor defined for currency: ${currency}`);
|
||||
}
|
||||
return subUnitDivisors[currency];
|
||||
};
|
||||
|
||||
////////// Currency manipulation in string format //////////
|
||||
|
||||
/**
|
||||
|
|
@ -190,16 +200,16 @@ const isGoogleMathLong = value => {
|
|||
*
|
||||
* @param {Money} value
|
||||
*
|
||||
* @param {Decimal|Number|String} subUnitDivisor - should be something that can be converted to
|
||||
* Decimal. (This is a ratio between currency's main unit and sub units.)
|
||||
*
|
||||
* @return {Number} converted value
|
||||
*/
|
||||
export const convertMoneyToNumber = (value, subUnitDivisor) => {
|
||||
export const convertMoneyToNumber = value => {
|
||||
if (!(value instanceof types.Money)) {
|
||||
throw new Error('Value must be a Money type');
|
||||
}
|
||||
const subUnitDivisorAsDecimal = convertDivisorToDecimal(subUnitDivisor);
|
||||
if (value.currency !== config.currency) {
|
||||
throw new Error('Given currency different from marketplace currency');
|
||||
}
|
||||
const subUnitDivisorAsDecimal = convertDivisorToDecimal(unitDivisor(value.currency));
|
||||
let amount;
|
||||
|
||||
if (isGoogleMathLong(value.amount)) {
|
||||
|
|
@ -228,18 +238,28 @@ export const convertMoneyToNumber = (value, subUnitDivisor) => {
|
|||
* Format the given money to a string
|
||||
*
|
||||
* @param {Object} intl
|
||||
* @param {Object} currencyConfig
|
||||
* @param {Money} value
|
||||
*
|
||||
* @return {String} formatted money value
|
||||
*/
|
||||
export const formatMoney = (intl, currencyConfig, value) => {
|
||||
export const formatMoney = (intl, value) => {
|
||||
if (!(value instanceof types.Money)) {
|
||||
throw new Error('Value must be a Money type');
|
||||
}
|
||||
if (value.currency !== currencyConfig.currency) {
|
||||
if (value.currency !== config.currency) {
|
||||
throw new Error('Given currency different from marketplace currency');
|
||||
}
|
||||
const valueAsNumber = convertMoneyToNumber(value, currencyConfig.subUnitDivisor);
|
||||
return intl.formatNumber(valueAsNumber, currencyConfig);
|
||||
const valueAsNumber = convertMoneyToNumber(value);
|
||||
|
||||
// See: https://github.com/yahoo/react-intl/wiki/API#formatnumber
|
||||
const numberFormatOptions = {
|
||||
style: 'currency',
|
||||
currency: value.currency,
|
||||
currencyDisplay: 'symbol',
|
||||
useGrouping: true,
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
};
|
||||
|
||||
return intl.formatNumber(valueAsNumber, numberFormatOptions);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -211,31 +211,22 @@ describe('currency utils', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('convertMoneyToNumber(value, subUnitDivisor)', () => {
|
||||
const subUnitDivisor = 100;
|
||||
describe('convertMoneyToNumber(value)', () => {
|
||||
const Money = types.Money;
|
||||
|
||||
it('Money as value', () => {
|
||||
expect(convertMoneyToNumber(new Money(10, 'USD'), subUnitDivisor)).toBeCloseTo(0.1);
|
||||
expect(convertMoneyToNumber(new Money(1000, 'USD'), subUnitDivisor)).toBeCloseTo(10);
|
||||
expect(convertMoneyToNumber(new Money(9900, 'USD'), subUnitDivisor)).toBeCloseTo(99);
|
||||
expect(convertMoneyToNumber(new Money(10099, 'USD'), subUnitDivisor)).toBeCloseTo(100.99);
|
||||
expect(convertMoneyToNumber(new Money(10, 'USD'))).toBeCloseTo(0.1);
|
||||
expect(convertMoneyToNumber(new Money(1000, 'USD'))).toBeCloseTo(10);
|
||||
expect(convertMoneyToNumber(new Money(9900, 'USD'))).toBeCloseTo(99);
|
||||
expect(convertMoneyToNumber(new Money(10099, 'USD'))).toBeCloseTo(100.99);
|
||||
});
|
||||
|
||||
it('Wrong type of a parameter', () => {
|
||||
expect(() => convertMoneyToNumber(10, subUnitDivisor)).toThrowError(
|
||||
'Value must be a Money type'
|
||||
);
|
||||
expect(() => convertMoneyToNumber('10', subUnitDivisor)).toThrowError(
|
||||
'Value must be a Money type'
|
||||
);
|
||||
expect(() => convertMoneyToNumber(true, subUnitDivisor)).toThrowError(
|
||||
'Value must be a Money type'
|
||||
);
|
||||
expect(() => convertMoneyToNumber({}, subUnitDivisor)).toThrowError(
|
||||
'Value must be a Money type'
|
||||
);
|
||||
expect(() => convertMoneyToNumber(new Money('asdf', 'USD'), subUnitDivisor)).toThrowError(
|
||||
expect(() => convertMoneyToNumber(10)).toThrowError('Value must be a Money type');
|
||||
expect(() => convertMoneyToNumber('10')).toThrowError('Value must be a Money type');
|
||||
expect(() => convertMoneyToNumber(true)).toThrowError('Value must be a Money type');
|
||||
expect(() => convertMoneyToNumber({})).toThrowError('Value must be a Money type');
|
||||
expect(() => convertMoneyToNumber(new Money('asdf', 'USD'))).toThrowError(
|
||||
'[DecimalError] Invalid argument'
|
||||
);
|
||||
});
|
||||
|
|
@ -244,17 +235,13 @@ describe('currency utils', () => {
|
|||
describe('formatMoney', () => {
|
||||
it('complains about incorrect value type', () => {
|
||||
const intl = null;
|
||||
const currencyConfig = {};
|
||||
const value = null;
|
||||
expect(() => formatMoney(intl, currencyConfig, value)).toThrowError(
|
||||
'Value must be a Money type'
|
||||
);
|
||||
expect(() => formatMoney(intl, value)).toThrowError('Value must be a Money type');
|
||||
});
|
||||
it('complains about mismatching currencies', () => {
|
||||
const intl = null;
|
||||
const currencyConfig = { currency: 'USD' };
|
||||
const value = new types.Money(100, 'EUR');
|
||||
expect(() => formatMoney(intl, currencyConfig, value)).toThrowError(
|
||||
expect(() => formatMoney(intl, value)).toThrowError(
|
||||
'Given currency different from marketplace currency'
|
||||
);
|
||||
});
|
||||
|
|
|
|||
18
src/util/currencyConfig.js
Normal file
18
src/util/currencyConfig.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// See: https://en.wikipedia.org/wiki/ISO_4217
|
||||
// See: https://stripe.com/docs/currencies
|
||||
export const subUnitDivisors = {
|
||||
EUR: 100,
|
||||
USD: 100,
|
||||
GBP: 100,
|
||||
AUD: 100,
|
||||
CAD: 100,
|
||||
DKK: 100,
|
||||
JPY: 100,
|
||||
SGD: 100,
|
||||
SEK: 100,
|
||||
CHF: 100,
|
||||
INR: 100,
|
||||
MXN: 100,
|
||||
CNY: 100,
|
||||
NOK: 100,
|
||||
};
|
||||
|
|
@ -40,7 +40,6 @@ export const currencyConfig = shape({
|
|||
useGrouping: bool,
|
||||
minimumFractionDigits: number,
|
||||
maximumFractionDigits: number,
|
||||
subUnitDivisor: number,
|
||||
});
|
||||
|
||||
// Configuration for a single route
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue