import { useState, useEffect } from 'react'; import { Box, Button, Divider, MenuItem, Autocomplete, Stack, TextField, } from '@mui/material'; import Modal from '../../../../components/common/Modal/Modal'; import { DangerOutlinedButton, PrimaryButton, } from '../../../../components/common/Buttons/Buttons'; import { useAuth } from '../../../../app/context/AuthProvider'; import { ROLES_NAME_ID } from '../../../../constants'; import { ModalContainer, FieldContainer, FieldLabel, StyledTextField, StyledMultilineTextField, StyledDatePicker, } from './Modal.style'; const ModalEditAddVsp = ({ open, onClose, onSave, onDelete, initialData = null, ssps = [], loading = false, }) => { const { user } = useAuth(); const [formData, setFormData] = useState({ registration_number: '', ssp_id: null, vsp_type: '', address: '', approved_format: '', open_date: null, close_date: null, notes: '', location_form: '', numbers: '', area: null, rent_contract_num: '', rent_end_date: null, system_code: '', }); const [errors, setErrors] = useState({}); const isExecutor = user?.role_id !== ROLES_NAME_ID.admin; const canSelectSsp = !isExecutor; const readOnlyFields = [ 'system_code', 'registration_number', 'ssp_id', 'vsp_type', 'address', 'approved_format', 'open_date', 'close_date', 'notes', ]; // Только эти поля readOnly для executor_rf const isReadOnlyField = (fieldName) => { if (!isExecutor) return false; return readOnlyFields.includes(fieldName); }; const locationFormOptions = [ { value: 'аренда', label: 'Аренда' }, { value: 'субаренда', label: 'Субаренда' }, { value: 'встроенное помещение', label: 'Встроенное помещение' }, ]; useEffect(() => { if (initialData) { setFormData({ registration_number: initialData.registration_number || '', ssp_id: initialData.ssp_id || null, vsp_type: initialData.vsp_type || '', address: initialData.address || '', approved_format: initialData.approved_format || '', open_date: initialData.open_date ? new Date(initialData.open_date) : null, close_date: initialData.close_date ? new Date(initialData.close_date) : null, notes: initialData.notes || '', location_form: initialData.location_form || '', numbers: initialData.staff_count?.toString() || '', area: initialData.area || null, rent_contract_num: initialData.rent_contract_num || '', rent_end_date: initialData.rent_end_date ? new Date(initialData.rent_end_date) : null, system_code: initialData.system_code || '', }); } else { setFormData({ registration_number: '', ssp_id: isExecutor ? user?.ssp_id : null, address: '', vsp_type: '', location: '', approved_format: '', open_date: null, close_date: null, notes: '', location_form: '', numbers: '', area: null, rent_contract_num: '', rent_end_date: null, system_code: '', }); } setErrors({}); }, [initialData, open, user, isExecutor]); // Валидация только для registration_number и ssp_id const validateForm = () => { const newErrors = {}; if (!formData.registration_number || !formData.registration_number.trim()) { newErrors.registration_number = 'Регистрационный номер ВСП обязателен'; } if (canSelectSsp && !formData.ssp_id) { newErrors.ssp_id = 'Региональный филиал обязателен'; } if (isExecutor && !formData.ssp_id) { newErrors.ssp_id = 'Региональный филиал не найден'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleChange = (field) => (event) => { if (isReadOnlyField(field)) return; setFormData({ ...formData, [field]: event.target.value, }); if (errors[field]) { setErrors({ ...errors, [field]: '', }); } }; const handleNumberChange = (field) => (event) => { if (isReadOnlyField(field)) return; const inputValue = event.target.value; const isValidInput = /^\d*\.?\d*$/.test(inputValue) || inputValue === ''; if (isValidInput) { setFormData({ ...formData, [field]: inputValue, }); if (errors[field]) { setErrors({ ...errors, [field]: '', }); } } }; const handleSspChange = (event, newValue) => { if (isReadOnlyField('ssp_id')) return; setFormData({ ...formData, ssp_id: newValue?.id || null, }); if (errors.ssp_id) { setErrors({ ...errors, ssp_id: '', }); } }; const handleDateChange = (field) => (date) => { if (isReadOnlyField(field)) return; setFormData({ ...formData, [field]: date, }); if (errors[field]) { setErrors({ ...errors, [field]: '', }); } }; const handleSubmit = async () => { // Выполняем валидацию перед отправкой if (!validateForm()) return; const submitData = { ...formData, numbers: formData.staff_count ? parseInt(formData.staff_count, 10) : null, area: formData.area ? parseFloat(formData.area) : null, open_date: formData.open_date ? formData.open_date.toLocaleDateString('en-CA') : null, close_date: formData.close_date ? formData.close_date.toLocaleDateString('en-CA') : null, rent_end_date: formData.rent_end_date ? formData.rent_end_date.toLocaleDateString('en-CA') : null, }; if (user.role_id !== ROLES_NAME_ID.admin) { const submitDataForExecutor = Object.fromEntries( Object.entries(submitData).filter( ([key]) => !readOnlyFields.includes(key), ), ); await onSave(submitDataForExecutor); } else { await onSave(submitData); } if (!loading) { handleClose(); } }; const handleClose = () => { if (!loading) { setFormData({ registration_number: '', ssp_id: null, vsp_type: '', location: '', approved_format: '', open_date: null, close_date: null, notes: '', location_form: '', numbers: '', area: '', rent_contract_num: '', rent_end_date: null, system_code: '', }); setErrors({}); onClose(); } }; const handleDelete = () => { onDelete?.(initialData.id); handleClose(); }; const selectedSsp = ssps.find((ssp) => ssp.id === formData.ssp_id) || null; const showActions = true; const showDeleteButton = !isExecutor; return ( {showDeleteButton && ( Удалить )} {!showDeleteButton && } {/* Спейсер для выравнивания */} {loading ? 'Сохранение...' : initialData ? 'Сохранить' : 'Создать'} ) } > Код РФ Регистрационный номер ВСП * {canSelectSsp && ( Региональный филиал * option.title || option.name || ''} value={selectedSsp} onChange={handleSspChange} disabled={loading || isReadOnlyField('ssp_id')} getOptionKey={(option) => option.id || option.name || option.title } renderInput={(params) => ( )} noOptionsText="Не найдено" sx={{ width: '100%' }} /> )} Вид ВСП Адрес ВСП Утвержденный формат Дата открытия ВСП Дата закрытия ВСП Примечания Форма расположения ВСП {locationFormOptions.map((option) => ( {option.label} ))} Штатная численность ВСП Площадь помещений ВСП Номер договора аренды Срок окончания договора аренды ); }; export default ModalEditAddVsp;