/
tsps
/
adminka
Обзор
Документация
Войти
/
tsps
/
adminka
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
master
src/hooks/useCreateDocumentImportJob.tsx
134 строки
4 KB
Василий Петров
Поллинг задач импорта документов
26 фев 2026, 23:43
26 фев 2026, 23:43
179a2e8
Код
Авторство
О чём код?
// Хук только для отправки в импорт import { useState, useCallback } from 'react'; import { apiFetch } from '@/lib/api/client'; import { toast } from 'sonner'; import { useImportJobsStore } from '@/store/importJobsStore'; export interface ImportJobParams { judge_id: number | null; court_id: number | null; document_type_id: number | null; date_from: string; date_to: string; } export interface ImportJobResponse { id: number; admin_id: number; status: string; search_params: ImportJobParams; result_summary: string | null; error_message: string | null; created_at: string; updated_at: string; } export function useCreateDocumentImportJob() { const [isOpen, setIsOpen] = useState(false); const [params, setParams] = useState<ImportJobParams>({ judge_id: null, court_id: null, document_type_id: null, date_from: '', date_to: '', }); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState<string | null>(null); const { addActiveJob } = useImportJobsStore(); const open = () => { setIsOpen(true); setError(null); }; const close = () => { setIsOpen(false); setError(null); }; const updateParams = (updates: Partial<ImportJobParams>) => { setParams(prev => ({ ...prev, ...updates })); setError(null); }; const validate = (): string | null => { if (!params.court_id) return 'Выберите суд'; if (!params.judge_id) return 'Выберите судью'; if (!params.document_type_id) return 'Выберите тип документа'; if (!params.date_from || !params.date_to) return 'Укажите период дат'; const from = new Date(params.date_from); const to = new Date(params.date_to); // Проверяем, что даты валидны if (isNaN(from.getTime()) || isNaN(to.getTime())) { return 'Некорректный формат даты'; } const diffDays = Math.ceil((to.getTime() - from.getTime()) / (1000 * 60 * 60 * 24)); if (to < from) return 'Дата окончания не может быть раньше даты начала'; if (diffDays > 7) return 'Интервал дат не может превышать 7 дней'; return null; }; const submit = useCallback(async () => { const validationError = validate(); if (validationError) { setError(validationError); toast.error(validationError); return null; } setIsSubmitting(true); setError(null); try { const data = await apiFetch('/document-import-jobs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(params), }); // регистрируем задачу поллинга addActiveJob(data.id, 'created'); toast.success('Задача на загрузку документов создана', { description: `ID задачи: ${data.id}`, }); close(); return data as ImportJobResponse; } catch (err) { const message = err instanceof Error ? err.message : 'Не удалось создать задачу'; setError(message); toast.error('Ошибка', { description: message }); return null; } finally { setIsSubmitting(false); } }, [params, addActiveJob]); const reset = useCallback(() => { setParams({ judge_id: null, court_id: null, document_type_id: null, date_from: '', date_to: '', }); setError(null); }, []); return { isOpen, open, close, params, updateParams, isSubmitting, error, submit, reset, }; }