Ошибка при пустых значениях форма пустая, только divider и кнопка рендерятся. Сделать чтоб при пустых первоначальных значениях поставлялись нули
Ошибка в
initialValues={setting && setting.content ? setting : {content: [{
amountMin: '0',
amountMin: 0,
amountMax: 0,
dayFrom: 0,
dayTo: 0,
active: false
}],
modifiedAt: '',
modifiedBy: ''}}
Type 'SettingData<OnBaseRates[]> | { content: { amountMin: string; amountMax: string; dayFrom:
string; dayTo: string; active: false; }[]; modifiedAt: string; modifiedBy: string; }' is not
assignable to type 'Setting & { content: OnBaseRates []; } & (SettingData<OnBaseRates()> | { content:
{ amountMin: string; amountMax: string; dayFrom: string; dayTo: string; active: boolean; }[];
modifiedAt: string; modifiedBy: string; })'.
Type '{ content: { amountMin: string; amountMax: string; dayFrom: string; dayTo: string; active:
false; }[]; modifiedAt: string; modifiedBy: string; }' is not assignable to type 'Setting & {
content: OnBaseRates(); } & (SettingData<OnBaseRates []> | { content: { amountMin: string;
amountMax: string; dayFrom: string; dayTo: string; active: boolean; }(); modifiedAt: string;
modifiedBy: string; })'.
Type '{ content: { amountMin: string; amountMax: string; dayFrom: string; dayTo: string; active:
false; }[]; modifiedAt: string; modifiedBy: string; }' is not assignable to type 'Setting & {
content: OnBaseRates(); } & { content: { amountMin: string; amountMax: string; dayFrom: string;
dayTo: string; active: boolean; }(); modifiedAt: string; modifiedBy: string; }'.
Property 'name' is missing in type '{ content: { amountMin: string; amountMax: string;
dayFrom: string; dayTo: string; active: false; }(); modifiedAt: string; modifiedBy: string; }'
but required in type 'Setting'.ts(2322)
types.ts(14, 3): 'name' is declared here.
types.d.ts(147, 5): The expected type comes from property 'initialValues' which is declared here on
type 'IntrinsicAttributes & FormikConfig<SettingData<OnBaseRates []>> & { children: ({ values,
setFieldValue, handleSubmit, resetForm, errors, }: FormikProps<SettingData<OnBaseRates[]>>) =>
Element; 4 more ...; validate: (values: SettingData<...>) => FormErrorContent; }'
...
(property) initialValues: Setting & {
content: OnBaseRates (];
} & (SettingData<OnBaseRates[]> | {
content: {
amountMin: string;
amountMax: string;
dayFrom: string;
dayTo: string;
active: boolean;
}[];
modifiedAt: string;
modifiedBy: string;
})
src/pages/RatesPag/types.ts
export const SETTING_PAGE = {
LIMIT_FOR_BASE_RATE_BY_AMOUNT: {
name: DepositPageNames.BASE_RATES_LIMIT,
title: 'Лимиты по базовым ставкам',
route: `/gm-deposits/dictionaries/settings/base-rates-limit`,
},
....
export type SettingName =
| 'SPREAD'
| 'LIMIT'
'TERM'
| 'CURRENCY'
'LIMIT_FOR_CLOSED_EARLY'
| 'LIMIT_FOR_BASE_RATE_BY_AMOUNT'
export type Setting - {
modifiedAt: string
modifiedBy: string
name: SettingName
}
export type OnBaseRates = {
amountMin: string
amountMax: string
dayFrom: string
dayTo: string
active: boolean
}
export interface OnBaseRatesErrors {
amountMin?: string
amountMax?: string
dayFrom?: string
dayTo?: string
active?: string
}
export type FormErrors = FormikErrors<{ content?: OnBaseRates [] }>
export type FormErrorContent = {
content?: OnBaseRatesErrors[]
}
________________________________________________
src/pages/RatesPag/utils.ts
export const parseLimitFields = (limit: OnBaseRates) => {
return requiredFields.reduce((acc, key) => {
const value = limit[key]
const cleaned = String(value).replace(/[\s,]+/g,'')
acc[key] = cleaned ? Number(cleaned) : 0
return acc
}, {} as Record<keyof Omit<OnBaseRates, 'active'>, number>)
}
export const areLimitsValid = (limit: OnBaseRates): boolean => {
const { amountMin, amountMax, dayFrom, dayTo } = parseLimitFields(limit)
const isAmountValid =
!isNaN(amountMax) && !isNaN(amountMin) && amountMax > amountMin
const isDayValid = !isNaN(dayFrom) && !isNaN(dayTo) && dayTo > dayFrom
return isAmountValid && isDayValid
}
export const validateForm = (values: SettingData<OnBaseRates[]>) => {
const errors: FormErrorContent = {}
const contentErrors: OnBaseRates Errors[] = []
if (!values.content) return errors
values.content.forEach((limit, index) => {
const pars = parseLimitFields(limit)
const limitErrors: OnBaseRatesErrors = {}
const amountMin = pars.amountMin
const amountMax = pars.amountMax
const dayFrom = pars.dayFrom
const dayTo = pars.dayTo
if (!amountMin || amountMin <= 0) {
limitErrors.amountMin = 'Укажите минимальную сумму'
}
if (!amountMax || amountMax <= 0) {
limitErrors.amountMax = 'Укажите максимальную сумму'
} else if (amountMax <= amountMin) {
limitErrors.amountMax =
'Максимальная сумма не может быть меньше минимальной'
}
if (!dayFrom || dayFrom <= 0) {
limitErrors.dayFrom = 'Укажите минимальный срок'
}
if (!dayTo || dayTo <= 0) {
limitErrors.dayTo - 'Укажите максимальный срок'
} else if (dayTo <= dayFrom) {
limitErrors.dayTo - 'Максимальный срок не может быть меньше минимального'
}
if (object.keys(limitErrors).length > 0)
if (!errors.content) errors.content = []
contentErrors [index] = limitErrors
if (contentErrors.some((el) => el && Object.keys(el).length > 0)) {
errors.content = contentErrors
}
return errors
}
export const getFieldError = (
errors: FormErrors,
index: number,
field: keyof OnBaseRates Errors
): string | undefined => {
if (!errors.content || ! Array.isArray(errors.content)) {
return undefined
}
const itemErrors = errors.content[index]
if (typeof itemErrors === 'object' && itemErrors != null) {
return itemErrors [field]
}
return undefined
}
)}
________________________________________________
src/pages/RatesPag/LimitRadioGroup.tsx
export interface ConfirmationToggleProps {
index: number
limit: OnBaseRates
isEdit: boolean
setFieldValue: (field: string, value: TEMPORARY_ANY) => void
}
export const ConfirmationToggle = ({
index,
limit,
isEdit,
setFieldValue,
}: ConfirmationToggleProps) => (
<>
<StyledRow cols={1}>
<Typography
color="text-primary-text"
variant={TYPOGRAPHY_VARIANT.LEAD_2_MEDIUM}
style={{ paddingTop: '10px' }}
>
Автоматическое подтверждение (состояние)
</Typography>
</StyledRow>
<StyledRow cols={1}>
{!isEdit ? (
<Cell>
<Typography
variant={TYPOGRAPHY_VARIANT.BODY_1_MEDIUM}
color={`tag-humble-text--${limit.active ? 'green' : 'red'}`}
>
{limit.active ? 'Активно : ' : 'Неактивно'}
</Typography>
</Cell>
):(
<Cell>
<RadioGroup
orientation="vertical"
value={limit.active.toString()}
onChange={(value: string) =>
setFieldValue(`content[${index}].active`, value === 'true')
}
>
<RadioItem
value={'true'}
label={'Активно'}
disabled={!areLimitsValid(limit)}
/>
<RadioItem
value={'false'}
label={'Неактивно'}
disabled={!areLimitsValid(limit)}
/>
</RadioGroup>
</Cell>
)}
</StyledRow>
</>
)
________________________________________________
src/pages/RatesPag/LimitInputGroupProps.tsx
export interface LimitInputGroupProps {
title: string
fromField: 'amountMin' | 'dayFrom',
toField: 'amountMax' | 'dayTo',
index: number,
limit: OnBaseRates,
isEdit: boolean,
errors: FormErrors,
setFieldValue,: (field: string, value: TEMPORARY_ANY) => void
}
export const LimitInputGroup = ({
title,
fromField,
toField,
index,
limit,
isEdit,
errors,
setFieldValue,
}: LimitInputGroupProps) => {
const is decimal = fromField = 'amountMin' || toField = 'amountMax'
return (
<>
<StyledRow cols={1}>
<Typography
color="text-primary-text"
variant=(TYPOGRAPHY_VARIANT.LEAD_2_MEDIUM)
style={{ paddingTop: '10px' }}
>
{title}
</Typography>
</StyledRow>
<StyledRow cols={2}>
<Cell alignSelf="self-end">
<Typography
variant={TYPOGRAPHY_VARIANT.BODY_1}
color="form-text--default"
>
от
</Typography>
</Cell>
<Cell alignSelf="self-end">
{!isEdit ? (
<Cell>
<Typography
variant=[TYPOGRAPHY_VARIANT.BODY_1_MEDIUM}
color="text-primary-text"
>
{formatSumNumber(limit[fromField]}
</Typography>
</Cell>
):(
<Cell>
<Input
type="number"
placeholder="Введите значение"
include ThousandsSeperator
value={limit[fromField]}
onChange={(value) => {
setFieldValue(`content[${index}].${fromfield}`, value)
}}
hasError={!!getFieldError(errors, index, fromField)}
captionText={getFieldError(errors, index, fromField)}
/>
</Cell>
)}
</Cell>
</StyledRow>
<StyledRow cols={2}>
<Cell alignSelf="self-end">
<Typography
variant={TYPOGRAPHY_VARIANT.BODY_1}
color="form-text--default"
>
до
</Typography>
</Cell>
<Cell alignSelf="self-end">
{!isEdit ? (
<Cell>
<Typography
variant={TYPOGRAPHY_VARIANT.BODY_1_MEDIUM}
color="text-primary-text"
>
{formatSumNumber(limit[toField), isDecimal)}
</Typography>
</Cell>
):(
<Cell>
<Input
type="number"
placeholder="Введите значение"
include Thousands Separator
value={limit[toField]}
onChange={(value) => {
setFieldValue(`content[${index}].${toField}`, value)
}}
hasError={!!getFieldError(errors, index, toField)}
captionText={getFieldError(errors, index, toField)}
/>
</Cell>
)}
</Cell>
</StyledRow>
</>
)}
________________________________________________
src/pages/RatesPag/getFieldError.tsx
export const RatesPage: React.FC = () => {
const dispatch = useAppDispatch()
const [isEdit, setEdit] = useState(false)
const setting = useSelector((state: RootState) => state.setting.onBaseRates);
const [isLoading, setIsLoading] = useState<boolean>(true)
const page = useSelector((state: RootState) => state.page.depositPages[state.page.depositIndex]);
const getRatestLimits = async () => {
set is loading(true)
try {
dispatch(getBaseRatesLimits()).unwrap ()
} catch (error) {
console.error('ошибка при получении лимитов: ', error)
return null
} finally {
setIsLoading(false))
}
useEffect(() => {
setEdit(page?.title === 'Редактирование');
}, [page?.title]);
const handleClickSave = async (values: SettingData<OnBaseRates[]>) => {
const processValues = {
...values,
content: values.content.map((el) => {
const parseFields = parseLimitFields(el)
const allFieldValid = Object.values (parseFields).every(
(value) => !isNaN(value) && value > 0)
return {
...el,
amountMin: String(parseFields.amountMin),
amountMax: String(parseFields.amountMax),
dayFrom: String(parseFields.dayFrom),
dayTo: String(parseFields.dayTo),
active: allFieldValid ? el.active : false,
}
}),
}
try {
await dispatch(updateBaseRatesLimits(processValues.content)).unwrap()
setEdit(false)
} catch (error) {
console.error('Ошибка сохранения лимитов:', error)
}
dispatch(setBack())
}
useEffect(() => {
if (!setting?.content || !isEdit) getRatesLimits()
}, [isEdit])
const onEdit = () => {
setEdit(true)
dispatch(
addDepositPage({
name: DepositPageNames.BASE_RATES_LIMIT,
route: /gm-deposits/dictionaries/settings/base-rates-limits`,
title: `Редактирование`,
})
)
}
if (isLoading) {
return <Loader />;
}
if (!setting || ! setting.content) {
return (
<EmptyState
title="Нет данных"
actions={{
first: {
callback: getRatesLimits,
label: 'Повторить загрузку',
},
}}
/>
);
}
return (
<Box row justifyContent={'center'}>
<Box width={'960px'}>
<Card width='100%'}>
<Formik
key={setting?.modifiedAt}
enableReinitialize={true}
initialValues={setting && setting.content ? setting : {content: [{
amountMin: 0,
amountMax: 0,
dayFrom: 0,
dayTo: 0,
active: false
}],
modifiedAt: '',
modifiedBy: ''}}
onSubmit={handleClickSave}
validate={validateForm}
>
{({
values,
setFieldValue,
handleSubmit,
resetForm,
errors,
}: FormikProps<SettingData<OnBaseRates[]>>) => (
<>
<Box b={'8px'} гоw>
<Box mr={'8px'}>
<Typography
variant={TYPOGRAPHY_VARIANT.BODY_1_MEDIUM}
color="text-secondary-text"
{values.modifiedBy}
</Typography>
</Box>
{values.modifiedAt &&(
<TooltipWrapper text={values.modifiedAt}>
<Typography
variant={TYPOGRAPHY_VARIANT.BODY_1_MEDIUM}
color="text-tertiary-text»
>
{formatDistance(
parse(
values?.modifiedAt,
'dd.MM.yyyy HH:mm:ss',
new Date()
),
new Date(),
{ locale: ru, addSuffix: true }
)}
</Typography>
</TooltipWrapper>
)}
</Box>
<FieldArray
name="content"
render={() => (
<>
{values.content.map((limit, index) => (
<Box key={index} mb="4px">
<LimitInputGroup
title="Лимит по сумме депозита"
fromField="amountMin"
toField="amountMax"
index={index}
limit={limit}
isEdit={isEdit}
errors={errors}
setFieldValue={setFieldValue}
/>
<LimitInputGroup
title="Лимит по сроку в днях"
fromField="dayFrom"
toField="dayTo"
index={index}
limit={limit}
isEdit={isEdit}
errors={errors}
setFieldValue={setFieldValue}
/>
<ConfirmationToggle
limit={limit}
index={index}
isEdit={isEdit}
setFieldValue={setFieldValue}
/>
</Box>
))}
</>
)}
><FieldArray
<Divider />
<Box row justifyContent={'flex-end'}>
<Flex
gridGap="10px"
height={'48px'}
justifyContent={'flex-end'}
marginTop={'24px'}
>
{isEdit && (
<Button
width="240px"
type="button"
variation={BUTTON_VARIATION.SECONDARY}
onClick={() => {
resetForm()
setEdit(true)
dispatch(setBack())
}}
>
Отмена
</Button>
)}
<Button
width="240px"
type="button"
disabled= {Object.keys(errorr).length > 0}
onClick={() => {
if (!isEdit) {
onEdit()
} else {
handleSubmit()
}
}}
>
{isEdit ? 'Сохранить' : 'Редактировать'}
</Button>
</Flex>
</Box>
</>
)}
</Formik>
</Card>
</Box>
</Box>
)
}
________________________________________________
action.ts
export const getBaseRatesLimits = createAsyncThunk(
'settings/getBaseRatesLimits',
async () => {
const res = await Settings.getBaseRatesLimits()
if (res.success) return await res.response.json()
return {}
}
export const updateBaseRatesLimits = createAsyncThunk(
'settings/updateBaseRatesLimits',
async (ratesLimits: OnBaseRates[], thunkApi) => {
const res = await Settings.updateBaseRatesLimits(ratesLimits)
if (res.success) {
thunkApi.dispatch(getBaseRatesLimits)
thunkApi.dispatch(
setMessage({
message: 'Данные успешно изменены',
type: 'success',
})
)
thunkApi.dispatch(setBack())
} else {
const error = await res.error.text()
thunkApi.dispatch(
setMessage({
message: error || '',
type: 'error',
})
)
thunkApi.rejectWithValue(error)
}
return
}