import types from '@/Components/Calculation/config/elements-types'; import type * as Values from '@/Components/Calculation/config/map/values'; import type * as Insurance from '@/Components/Calculation/Form/Insurance/InsuranceTable/types'; import type { ProcessContext } from '@/process/types'; import ValidationHelper from '@/stores/validation/helper'; import { disposableReaction } from '@/utils/mobx'; import { reaction } from 'mobx'; import { shake, uid } from 'radash'; import type { BaseOption } from 'ui/elements/types'; function hasInvalidValueOrOptions(value: unknown, options: Array>) { if (value === null) { return false; } return (value && !options?.length) || !options.some((x) => x.value === value); } export default function reactions({ store }: ProcessContext) { const { $calculation, $tables, $process } = store; /** * Проверяем, что выбранное значение элемента есть в списке */ const key = uid(7); const message = 'Выбранное значение отсутствует в списке'; function validateOptionsElement(elementName: Values.Elements) { const type = types[elementName]; if (type().typeName !== 'Options') { return; } const element = $calculation.element(elementName); const validationHelper = new ValidationHelper(); reaction( () => { const options = element.getOptions(); const value = element.getValue(); return { options, value, }; }, ({ value, options }) => { if (hasInvalidValueOrOptions(value, options)) { const removeError = element.setError({ key, message, silent: true, }); if (removeError) validationHelper.add(removeError); } else { validationHelper.removeErrors(); } }, { delay: 100, } ); disposableReaction( () => $process.has('LoadKP'), () => element.getOptions(), (options) => { const value = element.getValue(); if (hasInvalidValueOrOptions(value, options)) { element.resetValue(); } }, { delay: 100, } ); } const optionsTypes = shake(types, (type) => type().typeName !== 'Options'); (Object.keys(optionsTypes) as Values.Elements[]).forEach((elementName) => validateOptionsElement(elementName) ); function validateInsuranceCompany(rowKey: Insurance.Keys) { const row = $tables.insurance.row(rowKey); const validationHelper = new ValidationHelper(); reaction( () => { const options = row.getOptions('insuranceCompany'); const value = row.getValue('insuranceCompany'); return { options, value, }; }, ({ value, options }) => { if (hasInvalidValueOrOptions(value, options)) { const removeError = $tables.insurance.setError({ key, message, silent: true, }); validationHelper.add(removeError); } else { validationHelper.removeErrors(); } }, { delay: 100, } ); disposableReaction( () => $process.has('LoadKP'), () => row.getOptions('insuranceCompany'), (options) => { const value = row.getValue('insuranceCompany'); if (hasInvalidValueOrOptions(value, options)) { row.resetValue('insuranceCompany'); } }, { delay: 100, } ); } validateInsuranceCompany('kasko'); validateInsuranceCompany('osago'); validateInsuranceCompany('fingap'); }