87 lines
2.5 KiB
TypeScript

import types from 'Components/Calculation/config/elements-types';
import type * as Values from 'Components/Calculation/config/map/values';
import { reaction } from 'mobx';
import type { ReactionsContext } from 'process/types';
import type { BaseOption } from 'ui/elements/types';
function hasInvalidValue(value: unknown, options: BaseOption<unknown>[]) {
if (value === null) {
return false;
}
return (value && !options?.length) || !options.some((x) => x.value === value);
}
export default function validationReactions({ store }: ReactionsContext) {
const { $calculation, $tables } = store;
reaction(
() => {
const hasElementsErrors = Object.values($calculation.$validation).some(
(validation) => validation.hasErrors
);
const hasPaymentsErrors = $tables.payments.validation.hasErrors;
const hasInsuranceErrors = $tables.insurance.validation.hasErrors;
const hasFingapErrors = $tables.fingap.validation.hasErrors;
return hasElementsErrors || hasPaymentsErrors || hasInsuranceErrors || hasFingapErrors;
},
(hasErrors) => {
if (hasErrors) {
$calculation.$status.setStatus('btnCalculate', 'Disabled');
$calculation.$status.setStatus('btnCreateKP', 'Disabled');
} else {
$calculation.$status.setStatus('btnCalculate', 'Default');
$calculation.$status.setStatus('btnCreateKP', 'Default');
}
},
{
fireImmediately: true,
}
);
/**
* Проверяем, что выбранное значение элемента есть в списке
*/
(Object.keys(types) as Values.Elements[]).forEach((elementName) => {
const type = types[elementName];
if (type().typeName !== 'Options') {
return;
}
const element = $calculation.element(elementName);
reaction(
() => {
const options = element.getOptions();
const value = element.getValue();
return {
value,
options,
};
},
({ value, options }) => {
element.validate({
invalid: hasInvalidValue(value, options),
message: 'Выбранное значение отсутствует в списке',
silent: true,
});
},
{
delay: 100,
}
);
reaction(
() => element.getOptions(),
(options) => {
const value = element.getValue();
if (hasInvalidValue(value, options)) {
element.resetValue();
}
}
);
});
}