import * as React from 'react'; import { Company, Department, RequestType, TemplateRoute } from '../../models'; import { texts } from '../../texts'; import { useAsyncSubmit } from '../../hooks/useAsyncSubmit'; import { ApprovalRouteApi } from '../../services/api'; import { Checkbox, Field, FormGrid, FormModal, SearchableSelect, Select } from '../ui'; export interface IRouteFormModalProps { api: ApprovalRouteApi; /** Undefined — создание нового маршрута, иначе редактирование существующего. */ editing?: TemplateRoute; /** Тип заявки, под которым открыли форму создания (например, из активного фильтра списка). */ initialRequestTypeId: string; requestTypes: RequestType[]; companies: Company[]; departments: Department[]; dictionaryLoading: boolean; onSaved: () => void; onClose: () => void; } interface IFormState { requestTypeId: string; companyId: string; departmentId: string; byProject: boolean; requiresControl: boolean; } function toFormState(editing: TemplateRoute | undefined, initialRequestTypeId: string): IFormState { if (!editing) { return { requestTypeId: initialRequestTypeId, companyId: '', departmentId: '', byProject: false, requiresControl: false }; } return { requestTypeId: String(editing.requestTypeId), companyId: editing.companyId ?? '', departmentId: editing.departmentId ?? '', byProject: editing.byProject, requiresControl: editing.requiresControl }; } /** Форма создания/редактирования маршрута — вынесена из RoutesScreen, чтобы тот не разрастался. */ export const RouteFormModal: React.FC = ({ api, editing, initialRequestTypeId, requestTypes, companies, departments, dictionaryLoading, onSaved, onClose }) => { const [form, setForm] = React.useState(() => toFormState(editing, initialRequestTypeId)); const submit = useAsyncSubmit(); // Отдел принадлежит компании, поэтому список сужаем под выбранную: // иначе пользователь листает ~700 позиций из всех юрлиц сразу. const departmentsForSelectedCompany = React.useMemo( () => (form.companyId ? departments.filter(d => d.companyId === form.companyId) : []), [departments, form.companyId] ); const submitForm = (): void => { if (!editing && !form.requestTypeId) { submit.fail(texts.routes.validationRequestType); return; } const companyId = form.companyId.trim() ? form.companyId.trim() : null; const departmentId = form.departmentId.trim() ? form.departmentId.trim() : null; const request = editing ? api.templateRoutes.update(editing.id, { companyId, departmentId, byProject: form.byProject, requiresControl: form.requiresControl }) : api.templateRoutes.create({ requestTypeId: Number(form.requestTypeId), companyId, departmentId, byProject: form.byProject, requiresControl: form.requiresControl }); submit.run(() => request.then(() => { onSaved(); onClose(); }) ); }; return (