/* eslint-disable object-curly-newline */ import titles from 'Components/Calculation/config/elements-titles'; import type { Elements } from 'Components/Calculation/config/map/values'; import notification from 'Elements/notification'; import { makeAutoObservable, observable } from 'mobx'; import type RootStore from 'stores/root'; import type { ElementsErrors, Error } from './types'; export default class ValidationStore { root: RootStore; elementsErrors: Partial = {}; constructor(rootStore: RootStore) { makeAutoObservable(this); this.root = rootStore; } get hasErrors() { return (Object.keys(this.elementsErrors) as Elements[]).some( (elementName) => this.elementsErrors[elementName]?.length ); } getValidation(elementName: Elements) { return { isValid: !this.elementsErrors[elementName]?.length, errors: this.elementsErrors[elementName]?.map((x) => x.text), }; } addError = (elementName: Elements, error: Error) => { if (!this.elementsErrors[elementName]) this.elementsErrors[elementName] = observable([]); const errorIndex = this.elementsErrors[elementName]?.findIndex((x) => x.name === error.name); const hasError = errorIndex !== undefined && errorIndex !== -1; if (!hasError) { this.elementsErrors[elementName]?.push(error); } else { this.elementsErrors[elementName]?.splice(errorIndex, 1, error); } notification.error({ key: error.name, message: `${titles[elementName]}`, description: error.text, }); return () => this.#removeError(elementName, error.name); }; #removeError = (elementName: Elements, errorName: Error['name']) => { const errorIndex = this.elementsErrors[elementName]?.findIndex((x) => x.name === errorName); if (errorIndex) this.elementsErrors[elementName]?.splice(errorIndex, 1); }; clearErrors = (elementName: Elements) => { this.elementsErrors[elementName]?.clear(); }; }