Skip to content

Commit

Permalink
fix(core-components-money-input): type for currency according comments
Browse files Browse the repository at this point in the history
  • Loading branch information
stepancar committed Jun 17, 2020
1 parent 4625eee commit 078069d
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 25 deletions.
12 changes: 8 additions & 4 deletions packages/money-input/src/Component.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import React, { useState } from 'react';
import { render, fireEvent, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import { MoneyInput } from './index';
import { MoneyInput, CurrencyCodes } from './index';

const THINSP = String.fromCharCode(8201);

Expand Down Expand Up @@ -178,13 +178,17 @@ describe('MoneyInput', () => {

it('should render new amount from props (looped value)', async () => {
const dataTestId = 'test-id';
let setAmountManually: (value: number, currency: string, minority: number) => void;
let setAmountManually: (value: number, currency: CurrencyCodes, minority: number) => void;
const HOCWithAmountInState = () => {
const [value, setValue] = useState<number | null>(200);
const [currency, setCurrency] = useState('RUR');
const [currency, setCurrency] = useState<CurrencyCodes>('RUR');
const [minority, setMinority] = useState(100);

setAmountManually = (value: number | null, currency: string, minority: number) => {
setAmountManually = (
value: number | null,
currency: CurrencyCodes,
minority: number,
) => {
setValue(value);
setCurrency(currency);
setMinority(minority);
Expand Down
11 changes: 9 additions & 2 deletions packages/money-input/src/Component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,17 @@ import React, { useState, useEffect } from 'react';
import { Input, InputProps } from '@alfalab/core-components-input';
import { FormControl } from '@alfalab/core-components-form-control';

import { CURRENCY_CODES, THINSP } from './utils/currencyCodes';
import { CURRENCY_CODES, CurrencyCodes, THINSP } from './utils/currencyCodes';
import { getFormatedValue, getAmountValueFromStr, formatAmount } from './utils';
import styles from './index.module.css';

/**
* Тип явно описывающий набор поддерживаемых валют
* Если вам на проекте приходится что-то кастовать - дайте знать
* TODO: тип должен стать общим для банка
*/
export { CurrencyCodes } from './utils/currencyCodes';

export type MoneyInputProps = Omit<InputProps, 'value' | 'onChange' | 'type'> & {
/**
* Денежное значение в минорных единицах
Expand All @@ -17,7 +24,7 @@ export type MoneyInputProps = Omit<InputProps, 'value' | 'onChange' | 'type'> &
/**
* Валюта
*/
currency?: string;
currency?: CurrencyCodes;

/**
* Минорные единицы
Expand Down
8 changes: 4 additions & 4 deletions packages/money-input/src/click-money-input.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React from 'react';

import { MoneyInputProps, MoneyInput } from './Component';
import { MoneyInputProps, MoneyInput, CurrencyCodes } from './Component';

type AmountType = {
/** Сумма в минорных единицах */
value: number;
value: number | null;
/** Валюта */
currency: string;
/** Минорные единицы */
Expand Down Expand Up @@ -33,7 +33,7 @@ export const ClickMoneyInput: React.FC<ClickMoneyInputProps> = ({
}) => {
function handleChange(
e: React.ChangeEvent<HTMLInputElement>,
payload: { value: number; valueString: string },
payload: { value: number | null; valueString: string },
) {
const { value: newValue, valueString } = payload;
if (onChange) {
Expand All @@ -52,7 +52,7 @@ export const ClickMoneyInput: React.FC<ClickMoneyInputProps> = ({
<MoneyInput
{...restProps}
value={value}
currency={currency}
currency={currency as CurrencyCodes}
minority={minorUnits}
onChange={handleChange}
/>
Expand Down
8 changes: 3 additions & 5 deletions packages/money-input/src/utils/currencyCodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@ export const AMOUNT_MAJOR_PART_SIZE = 3;
export const AMOUNT_SPLIT_CODE_FROM = 4;
export const NEGATIVE_AMOUNT_SYMBOL = '−';

export type CurrencyType = {
[key: string]: string;
};

export const CURRENCY_CODES: CurrencyType = {
export const CURRENCY_CODES = {
ALL: '\u004c\u0065\u006b',
AFN: '\u060b',
ARS: '\u0024',
Expand Down Expand Up @@ -125,3 +121,5 @@ export const CURRENCY_CODES: CurrencyType = {
YER: '\ufdfc',
ZWD: '\u005a\u0024',
};

export type CurrencyCodes = keyof typeof CURRENCY_CODES;
7 changes: 4 additions & 3 deletions packages/money-input/src/utils/formatAmount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
NEGATIVE_AMOUNT_SYMBOL,
AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR,
AMOUNT_SPLIT_CODE_FROM,
CurrencyCodes,
} from './currencyCodes';

/**
Expand All @@ -15,8 +16,8 @@ import {
* @param {Number} [partSize=3] Размер частей суммы
* @param {String} [splitter=THINSP] Символ, разбивающий части суммы
* @param {String} [splitFrom=5] Длина суммы, начиная с которой необходимо осуществлять разбивку. По-умолчанию длина
* равняется пяти по требованию гайдлайнов: https://design.alfabank.ru/patterns/amount. Пример: 2900 не разбивается,
* 29 000 разбивается.
* равняется пяти по требованию гайдлайнов: https://design.alfabank.ru/patterns/amount. Пример: 2900 - не разбивается,
* 29 000 - разбивается.
* @returns {String}
*/

Expand Down Expand Up @@ -58,7 +59,7 @@ export const splitAmount = (
type AmountType = {
value: number | null;
currency: {
code: string;
code: CurrencyCodes;
minority: number;
};
};
Expand Down
5 changes: 3 additions & 2 deletions packages/money-input/src/utils/getCurrencySymbol.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { CURRENCY_CODES } from './currencyCodes';
import { CURRENCY_CODES, CurrencyCodes } from './currencyCodes';

/**
* Возвращает знак валюты по ISO коду.
*
* @param currencyCode Код валюты.
*/
export const getCurrencySymbol = (currencyCode: string): string => CURRENCY_CODES[currencyCode];
export const getCurrencySymbol = (currencyCode: CurrencyCodes): string =>
CURRENCY_CODES[currencyCode];
4 changes: 2 additions & 2 deletions packages/money-input/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { formatAmount } from './formatAmount';
import { CurrencyCodes } from './currencyCodes';

export * from './formatAmount';
export * from './getCurrencySymbol';

/**
* Форматирует введенное значение
* @param enteredValue Значение введенное в инпут
* @param currency валюта
* @param minority количество минорных единиц
*/
export function getFormatedValue(enteredValue: string, currency: string, minority: number) {
export function getFormatedValue(enteredValue: string, currency: CurrencyCodes, minority: number) {
const [head, tail] = enteredValue.split(',');
const { majorPart } = formatAmount({
value: Number(head) * minority,
Expand Down
4 changes: 1 addition & 3 deletions packages/utils/getCurrencySymbol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import { CURRENCY_CODES } from '../configs/currencyCodes';
/**
* Возвращает знак валюты по ISO коду.
*
* @param {String} currencyCode Код валюты.
* @returns {String}
* @param currencyCode Код валюты.
*/

export const getCurrencySymbol = (currencyCode: string): string =>
CURRENCY_CODES[currencyCode] ?? currencyCode;

0 comments on commit 078069d

Please sign in to comment.