/** * TrusteeAbschlussView * * Tab-based closing/review page. Currently one tab (year-end check), * extensible for future use cases. Follows the same pattern as * TrusteeAnalyseView: loads the bootstrapped workflow, executes it, * and shows pipeline status inline. */ import React, { useState, useEffect, useCallback, useRef } from 'react'; import { useSearchParams, useNavigate } from 'react-router-dom'; import { useCurrentInstance } from '../../../hooks/useCurrentInstance'; import { useToast } from '../../../contexts/ToastContext'; import api from '../../../api'; import styles from './TrusteeViews.module.css'; import { useLanguage } from '../../../providers/language/LanguageContext'; import { PeriodPicker, resolvePeriod, type PeriodValue, } from '../../../components/PeriodPicker'; const _DEFAULT_PERIOD_PRESET = { kind: 'lastYear' as const }; // --------------------------------------------------------------------------- // Tab definitions // --------------------------------------------------------------------------- interface TabDef { id: string; templateTag: string | null; icon: string; color: string; comingSoon?: boolean; } const _TABS: TabDef[] = [ { id: 'year-end', templateTag: 'template:trustee-year-end-check', icon: '\u2705', color: '#795548' }, { id: 'vat', templateTag: null, icon: '\uD83E\uDDFE', color: '#9E9E9E', comingSoon: true }, { id: 'reporting', templateTag: null, icon: '\uD83D\uDCEC', color: '#9E9E9E', comingSoon: true }, ]; function _tabLabel(tabId: string, t: (k: string) => string): string { switch (tabId) { case 'year-end': return t('Jahresabschluss prüfen'); case 'vat': return t('MWST-Abrechnung'); case 'reporting': return t('Reporting Behörden'); default: return tabId; } } function _tabDescription(tabId: string, t: (k: string) => string): string { switch (tabId) { case 'year-end': return t('Automatische Prüfungen für den Jahresabschluss: Saldovalidierung, Vorjahresvergleich, gesetzliche Checks.'); case 'vat': return t('Vierteljährliche MWST-Abrechnung vorbereiten und validieren.'); case 'reporting': return t('Meldungen an Behörden vorbereiten (z. B. Lohnausweise, Sozialversicherungen).'); default: return ''; } } // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- interface WorkflowSummary { id: string; label: string; tags: string[]; } type RunState = 'idle' | 'starting' | 'running' | 'completed' | 'error'; // --------------------------------------------------------------------------- // Component // --------------------------------------------------------------------------- export const TrusteeAbschlussView: React.FC = () => { const { t } = useLanguage(); const navigate = useNavigate(); const { instanceId } = useCurrentInstance(); const { showSuccess, showError } = useToast(); const [searchParams, setSearchParams] = useSearchParams(); const activeTab = searchParams.get('tab') || _TABS[0].id; const _setActiveTab = useCallback((tab: string) => { setSearchParams({ tab }, { replace: true }); }, [setSearchParams]); const [workflows, setWorkflows] = useState([]); const [workflowsLoading, setWorkflowsLoading] = useState(true); const [runState, setRunState] = useState('idle'); const [runId, setRunId] = useState(null); const [runSummary, setRunSummary] = useState(''); const [runError, setRunError] = useState(null); const pollTimerRef = useRef(null); const isPollingRef = useRef(false); const [period, setPeriod] = useState(() => { const r = resolvePeriod(_DEFAULT_PERIOD_PRESET); return { preset: _DEFAULT_PERIOD_PRESET, fromDate: r.fromDate, toDate: r.toDate }; }); useEffect(() => { if (!instanceId) return; const _load = async () => { setWorkflowsLoading(true); try { const res = await api.get(`/api/workflows/${instanceId}/workflows`); const items: WorkflowSummary[] = (res.data?.workflows || res.data?.items || []).map((w: any) => ({ id: w.id, label: w.label, tags: w.tags || [], })); setWorkflows(items); } catch { setWorkflows([]); } finally { setWorkflowsLoading(false); } }; _load(); }, [instanceId]); const _findWorkflow = useCallback((tab: string): WorkflowSummary | undefined => { const tabDef = _TABS.find((tabItem) => tabItem.id === tab); if (!tabDef || !tabDef.templateTag) return undefined; const templateTag = tabDef.templateTag; return workflows.find((w) => w.tags.includes(templateTag)); }, [workflows]); const _stopPolling = useCallback(() => { if (pollTimerRef.current !== null) { window.clearInterval(pollTimerRef.current); pollTimerRef.current = null; } isPollingRef.current = false; }, []); const _pollRun = useCallback(async (rid: string) => { if (!instanceId || !rid || isPollingRef.current) return; isPollingRef.current = true; try { const res = await api.get(`/api/workflows/${instanceId}/runs/${rid}/steps`); const steps: any[] = Array.isArray(res?.data?.steps) ? res.data.steps : []; const completed = steps.filter((s) => s.status === 'completed'); const failed = steps.filter((s) => s.status === 'failed'); const running = steps.filter((s) => s.status === 'running'); setRunSummary(`${completed.length}/${steps.length} ${t('Schritte abgeschlossen')}`); if (failed.length > 0) { const errMsg = failed[failed.length - 1].error || t('Schritt fehlgeschlagen'); setRunState('error'); setRunError(errMsg); _stopPolling(); showError(t('Pipeline-Fehler'), errMsg); return; } if (running.length === 0 && completed.length === steps.length && steps.length > 0) { setRunState('completed'); _stopPolling(); showSuccess(t('Abgeschlossen'), t('Prüfungs-Workflow erfolgreich beendet.')); return; } setRunState('running'); } catch (err: any) { if (err?.response?.status === 404) { setRunState('running'); return; } setRunState('error'); setRunError(err.message || t('Abfrage fehlgeschlagen')); _stopPolling(); } finally { isPollingRef.current = false; } }, [instanceId, showError, showSuccess, _stopPolling, t]); useEffect(() => { if (!instanceId || !runId || (runState !== 'running' && runState !== 'starting')) return; void _pollRun(runId); pollTimerRef.current = window.setInterval(() => { void _pollRun(runId); }, 3000); return () => { _stopPolling(); }; }, [instanceId, runId, runState, _pollRun, _stopPolling]); useEffect(() => () => { _stopPolling(); }, [_stopPolling]); useEffect(() => { _stopPolling(); setRunState('idle'); setRunId(null); setRunSummary(''); setRunError(null); }, [activeTab, _stopPolling]); const _handleExecute = useCallback(async () => { const wf = _findWorkflow(activeTab); if (!wf || !instanceId) { showError(t('Fehler'), t('Kein Workflow für diesen Tab gefunden.')); return; } setRunState('starting'); setRunError(null); setRunSummary(t('Workflow wird gestartet…')); try { const res = await api.post(`/api/workflows/${instanceId}/execute`, { workflowId: wf.id, payload: { dateFrom: period.fromDate, dateTo: period.toDate }, }); const rid = res?.data?.runId; if (rid) { setRunId(rid); setRunState('running'); setRunSummary(t('Lauf {prefix} gestartet', { prefix: rid.slice(0, 8) })); } else if (res?.data?.success) { setRunState('completed'); setRunSummary(t('Workflow synchron abgeschlossen.')); showSuccess(t('Abgeschlossen'), t('Prüfungs-Workflow erfolgreich beendet.')); } else { throw new Error(res?.data?.error || t('Unerwartete Antwort')); } } catch (err: any) { const msg = err?.response?.data?.detail || err.message || t('Workflow konnte nicht gestartet werden.'); setRunState('error'); setRunError(typeof msg === 'string' ? msg : JSON.stringify(msg)); showError(t('Fehler'), typeof msg === 'string' ? msg : JSON.stringify(msg)); } }, [activeTab, instanceId, _findWorkflow, period, showError, showSuccess, t]); const currentTab = _TABS.find((tabItem) => tabItem.id === activeTab) || _TABS[0]; const currentWorkflow = _findWorkflow(activeTab); const isComingSoon = !!currentTab.comingSoon; return (

{t('Abschluss & Prüfung')}

{/* Tab bar */} {_TABS.length > 1 && (
{_TABS.map((tab) => ( ))}
)} {/* Tab content */}

{_tabDescription(activeTab, t)}

{isComingSoon ? (

{t('In Kürze verfügbar.')}{' '} {t('Diese Funktion befindet sich in Vorbereitung.')}

) : workflowsLoading ? (

{t('Workflows werden geladen…')}

) : !currentWorkflow ? (

{t('Für diesen Tab wurde kein Workflow in der Instanz gefunden. Der Workflow wird beim Erstellen der Instanz automatisch angelegt.')}

) : ( <>
{currentTab.icon}
{currentWorkflow.label}
{t('Workflow-ID:')} {currentWorkflow.id.slice(0, 8)}…
)} {runState !== 'idle' && (
{t('Status')}:{' '} {runState === 'starting' && t('Wird gestartet…')} {runState === 'running' && t('Läuft')} {runState === 'completed' && t('Abgeschlossen')} {runState === 'error' && t('Fehler')} {runSummary &&
{runSummary}
} {runError &&
{runError}
} {runState === 'completed' && runId && ( )}
)}
); }; export default TrusteeAbschlussView;