2023-03-16 15:35:44 +03:00

57 lines
1.7 KiB
TypeScript

import { createValidationSchema } from '../validation';
import type { Elements } from '@/Components/Calculation/config/map/values';
import type { ProcessContext } from '@/process/types';
import ValidationHelper from '@/stores/validation/helper';
import { comparer, reaction, toJS } from 'mobx';
import { uid } from 'radash';
const key = uid(7);
export default function reactions(context: ProcessContext) {
const { $calculation, $tables } = context.store;
const validationSchema = createValidationSchema();
const helper = new ValidationHelper();
reaction(
() => {
const payments = toJS($tables.payments.values);
const values = $calculation.$values.getValues([
'graphType',
'highSeasonStart',
'leasingPeriod',
'seasonType',
'insNSIB',
'lastPaymentRub',
]);
return {
payments: { values: payments },
...values,
};
},
async (values) => {
helper.removeErrors();
const validationResult = await validationSchema.safeParseAsync(values);
if (!validationResult.success) {
validationResult.error.errors.forEach(({ path, message }) => {
(path as Array<Elements & 'payments'>).forEach((elementName) => {
if (elementName === 'payments') {
const removeError = $tables.payments.setError({ key, message });
if (removeError) helper.add(removeError);
} else {
const removeError = $calculation.element(elementName).setError({ key, message });
if (removeError) helper.add(removeError);
}
});
});
}
},
{
delay: 100,
equals: comparer.structural,
}
);
}