import React, { useState, useEffect } from 'react'; import { useRouter } from 'next/router'; import { useQuery, useMutation } from '@apollo/client'; import Header from '../components/Header'; import ProfileSidebar from '../components/ProfileSidebar'; import { GET_CLIENT_ME, UPDATE_CLIENT_PERSONAL_DATA, CREATE_CLIENT_LEGAL_ENTITY, UPDATE_CLIENT_LEGAL_ENTITY, DELETE_CLIENT_LEGAL_ENTITY } from '../lib/graphql'; interface PersonalData { name: string; phone: string; email: string; emailNotifications: boolean; smsNotifications: boolean; pushNotifications: boolean; } interface LegalEntity { id: string; shortName: string; fullName: string; form: string; legalAddress: string; actualAddress?: string; taxSystem: string; responsiblePhone?: string; responsiblePosition?: string; responsibleName?: string; accountant?: string; signatory?: string; registrationReasonCode?: string; ogrn?: string; inn: string; vatPercent: number; } interface NewLegalEntity { shortName: string; fullName: string; form: string; legalAddress: string; actualAddress?: string; taxSystem: string; responsiblePhone?: string; responsiblePosition?: string; responsibleName?: string; accountant?: string; signatory?: string; registrationReasonCode?: string; ogrn?: string; inn: string; vatPercent?: number; } const ProfileSettings: React.FC = () => { const router = useRouter(); const [isAuthenticated, setIsAuthenticated] = useState(false); const [showAddModal, setShowAddModal] = useState(false); const [editingEntity, setEditingEntity] = useState(null); const [clientId, setClientId] = useState(''); const [personalData, setPersonalData] = useState({ name: '', phone: '', email: '', emailNotifications: true, smsNotifications: false, pushNotifications: false }); const [newEntity, setNewEntity] = useState({ shortName: '', fullName: '', form: '', legalAddress: '', actualAddress: '', taxSystem: '', responsiblePhone: '', responsiblePosition: '', responsibleName: '', accountant: '', signatory: '', registrationReasonCode: '', ogrn: '', inn: '', vatPercent: 0 }); // GraphQL запросы и мутации const { data: clientData, loading: clientLoading, error: clientError, refetch } = useQuery(GET_CLIENT_ME, { skip: !isAuthenticated, onCompleted: (data) => { console.log('GET_CLIENT_ME onCompleted:', data); if (data?.clientMe) { setPersonalData({ name: data.clientMe.name || '', phone: data.clientMe.phone || '', email: data.clientMe.email || '', emailNotifications: data.clientMe.emailNotifications ?? true, smsNotifications: data.clientMe.smsNotifications ?? false, pushNotifications: data.clientMe.pushNotifications ?? false }); } }, onError: (error) => { console.error('GET_CLIENT_ME onError:', error); } }); const [updatePersonalData] = useMutation(UPDATE_CLIENT_PERSONAL_DATA); const [createLegalEntity] = useMutation(CREATE_CLIENT_LEGAL_ENTITY); const [updateLegalEntity] = useMutation(UPDATE_CLIENT_LEGAL_ENTITY); const [deleteLegalEntity] = useMutation(DELETE_CLIENT_LEGAL_ENTITY); useEffect(() => { const checkAuth = () => { const userData = localStorage.getItem('userData'); if (userData) { const user = JSON.parse(userData); setIsAuthenticated(true); setClientId(user.id); } else { router.push('/'); return; } }; checkAuth(); }, [router]); const handlePersonalDataChange = (field: keyof PersonalData, value: string | boolean) => { setPersonalData(prev => ({ ...prev, [field]: value })); }; const handleNewEntityChange = (field: keyof NewLegalEntity, value: string | number) => { setNewEntity(prev => ({ ...prev, [field]: value })); }; const handleSavePersonalData = async () => { try { await updatePersonalData({ variables: { input: { type: 'INDIVIDUAL', // Добавляем обязательное поле name: personalData.name, email: personalData.email, phone: personalData.phone, emailNotifications: personalData.emailNotifications, smsNotifications: personalData.smsNotifications, pushNotifications: personalData.pushNotifications } } }); alert('Персональные данные сохранены'); } catch (error) { console.error('Ошибка сохранения данных:', error); alert('Ошибка сохранения данных'); } }; const handleAddEntity = async () => { if (!newEntity.shortName || !newEntity.inn) { alert('Заполните обязательные поля'); return; } try { await createLegalEntity({ variables: { input: newEntity } }); resetForm(); setShowAddModal(false); refetch(); } catch (error) { console.error('Ошибка создания юр. лица:', error); alert('Ошибка создания юридического лица'); } }; const resetForm = () => { setNewEntity({ shortName: '', fullName: '', form: '', legalAddress: '', actualAddress: '', taxSystem: '', responsiblePhone: '', responsiblePosition: '', responsibleName: '', accountant: '', signatory: '', registrationReasonCode: '', ogrn: '', inn: '', vatPercent: 0 }); setEditingEntity(null); }; const handleDeleteEntity = async (id: string) => { if (window.confirm('Удалить юридическое лицо?')) { try { await deleteLegalEntity({ variables: { id } }); refetch(); } catch (error) { console.error('Ошибка удаления юр. лица:', error); alert('Ошибка удаления юридического лица'); } } }; const handleEditEntity = (entity: LegalEntity) => { setEditingEntity(entity); setNewEntity({ shortName: entity.shortName, fullName: entity.fullName, form: entity.form, legalAddress: entity.legalAddress, actualAddress: entity.actualAddress || '', taxSystem: entity.taxSystem, responsiblePhone: entity.responsiblePhone || '', responsiblePosition: entity.responsiblePosition || '', responsibleName: entity.responsibleName || '', accountant: entity.accountant || '', signatory: entity.signatory || '', registrationReasonCode: entity.registrationReasonCode || '', ogrn: entity.ogrn || '', inn: entity.inn, vatPercent: entity.vatPercent }); setShowAddModal(true); }; const handleUpdateEntity = async () => { if (!editingEntity || !newEntity.shortName || !newEntity.inn) { alert('Заполните обязательные поля'); return; } try { await updateLegalEntity({ variables: { id: editingEntity.id, input: newEntity } }); resetForm(); setShowAddModal(false); refetch(); } catch (error) { console.error('Ошибка обновления юр. лица:', error); alert('Ошибка обновления юридического лица'); } }; const closeModal = () => { setShowAddModal(false); resetForm(); }; if (clientLoading || !isAuthenticated) { return (
Загрузка...
); } if (clientError) { console.error('GraphQL Error:', clientError); return (
Ошибка загрузки данных: {clientError.message}
); } const legalEntities = clientData?.clientMe?.legalEntities || []; return (
{/* Хлебные крошки */}
Главная Личный кабинет Настройки аккаунта

Настройки аккаунта

{/* Основной контент */}
{/* Персональные данные */}

Персональные данные

handlePersonalDataChange('name', e.target.value)} className="form-input" />
handlePersonalDataChange('phone', e.target.value)} className="form-input" />
handlePersonalDataChange('email', e.target.value)} placeholder="@" className="form-input email-input" />
{/* Юридические лица */}

Юридические лица

{legalEntities.length > 0 ? (
{legalEntities.map((entity: LegalEntity) => (

{entity.shortName}

ИНН {entity.inn}

))}
) : (

У вас пока нет добавленных юридических лиц

)}
{/* Кнопки управления */}
{/* Модальное окно */} {showAddModal && (

{editingEntity ? 'Редактирование юридического лица' : 'Добавление юридического лица'}

handleNewEntityChange('inn', e.target.value)} placeholder="ИНН" className="form-input" />
handleNewEntityChange('shortName', e.target.value)} placeholder="Название компании" className="form-input" />
handleNewEntityChange('ogrn', e.target.value)} placeholder="ОГРН" className="form-input" />
handleNewEntityChange('legalAddress', e.target.value)} placeholder="Юридический адрес" className="form-input" />
handleNewEntityChange('fullName', e.target.value)} placeholder="Полное наименование" className="form-input" />
handleNewEntityChange('actualAddress', e.target.value)} placeholder="Фактический адрес" className="form-input" />
handleNewEntityChange('vatPercent', parseFloat(e.target.value) || 0)} placeholder="0" className="form-input" />
handleNewEntityChange('accountant', e.target.value)} placeholder="ФИО" className="form-input" />
handleNewEntityChange('responsibleName', e.target.value)} placeholder="ФИО" className="form-input" />
handleNewEntityChange('responsiblePosition', e.target.value)} placeholder="Должность" className="form-input" />
handleNewEntityChange('responsiblePhone', e.target.value)} placeholder="+7" className="form-input" />
handleNewEntityChange('signatory', e.target.value)} placeholder="ФИО" className="form-input" />
)}
); }; export default ProfileSettings;