Files
dh-inspeccion-v2/web-v2/src/pages/ReportDetailPage.tsx
T

209 lines
13 KiB
TypeScript

import { useEffect, useState } from 'react';
import type { FormEvent } from 'react';
import { Link, useParams } from 'react-router';
import { useAuth } from '../auth/AuthContext';
import { Alert, LoadingBlock, errorMessage } from '../components/Feedback';
import { Icon } from '../components/Icon';
import {
approveInspectionReport,
getInspectionReport,
getInspectionReportReview,
inspectionReportRevisionUrl,
inspectionReportWordUrl,
signFinalInspectionReport,
uploadInspectionReportRevision,
} from '../lib/api';
import type { InspectionReport, InspectionReportReview } from '../lib/api';
import { formatDate } from '../lib/format';
function names(items: Array<{ name: string }>, empty: string): string {
return items.length ? items.map((item) => item.name).join(' · ') : empty;
}
function reviewLabel(value: InspectionReport['reviewStatus']): string {
if (value === 'SIGNED') return 'Firmado';
if (value === 'APPROVED') return 'Aprobado · falta firma';
return 'Pendiente de revisión';
}
function reviewClass(value: InspectionReport['reviewStatus']): string {
if (value === 'SIGNED') return 'active';
if (value === 'APPROVED') return 'observed';
return 'pending';
}
function revisionSource(value: 'AUTO' | 'DIRECTOR_UPLOAD'): string {
return value === 'AUTO' ? 'Automática' : 'Corrección cargada';
}
export function ReportDetailPage() {
const { id } = useParams();
const { hasPermission } = useAuth();
const [report, setReport] = useState<InspectionReport | null>(null);
const [review, setReview] = useState<InspectionReportReview | null>(null);
const [loading, setLoading] = useState(true);
const [working, setWorking] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
const [revisionFile, setRevisionFile] = useState<File | null>(null);
const [changeSummary, setChangeSummary] = useState('');
const [approvalNote, setApprovalNote] = useState('');
const [signatureConfirmed, setSignatureConfirmed] = useState(false);
const canRevise = hasPermission('inspection_reports.revise');
const canReview = hasPermission('inspection_reports.review');
const canSign = hasPermission('inspection_reports.sign_final');
const reload = async () => {
if (!id) return;
const [nextReport, nextReview] = await Promise.all([getInspectionReport(id), getInspectionReportReview(id)]);
setReport(nextReport);
setReview(nextReview);
};
useEffect(() => {
if (!id) return;
setLoading(true);
setError('');
reload()
.catch((requestError) => setError(errorMessage(requestError)))
.finally(() => setLoading(false));
}, [id]);
const uploadRevision = async (event: FormEvent) => {
event.preventDefault();
if (!id || !revisionFile || changeSummary.trim().length < 5) return;
setWorking(true);
setError('');
setSuccess('');
try {
const next = await uploadInspectionReportRevision(id, revisionFile, changeSummary.trim());
setReview(next);
setRevisionFile(null);
setChangeSummary('');
setSuccess(`Versión ${next.currentRevisionNumber} agregada al historial.`);
await reload();
} catch (requestError) {
setError(errorMessage(requestError));
} finally {
setWorking(false);
}
};
const approve = async () => {
if (!id) return;
setWorking(true);
setError('');
setSuccess('');
try {
const next = await approveInspectionReport(id, approvalNote);
setReview(next);
setApprovalNote('');
setSuccess(`Versión ${next.currentRevisionNumber} aprobada por el Director.`);
await reload();
} catch (requestError) {
setError(errorMessage(requestError));
} finally {
setWorking(false);
}
};
const signFinal = async () => {
if (!id || !signatureConfirmed) return;
setWorking(true);
setError('');
setSuccess('');
try {
const next = await signFinalInspectionReport(id);
setReview(next);
setSignatureConfirmed(false);
setSuccess('Informe final firmado electrónicamente. La versión firmada quedó bloqueada.');
await reload();
} catch (requestError) {
setError(errorMessage(requestError));
} finally {
setWorking(false);
}
};
if (loading) return <LoadingBlock label="Cargando informe…" />;
return <section>
<div className="breadcrumb"><Link to="/informes">Informes</Link><span>/</span><span>{report?.code ?? 'Informe'}</span></div>
<div className="page-heading survey-editor-heading">
<div><span className="eyebrow">INFORME DE INSPECCIÓN</span><h1>{report?.title ?? 'Informe'}</h1><p>{report ? `${report.code} · emitido ${formatDate(report.generatedAt)}` : 'Consulta del informe.'}</p></div>
{report && <div className="report-status-stack"><span className={`status-badge large ${report.wordStatus === 'READY' ? 'active' : report.wordStatus === 'FAILED' ? 'danger' : 'pending'}`}>{report.wordStatus === 'READY' ? 'Word disponible' : report.wordStatus === 'FAILED' ? 'Word con error' : 'Word pendiente'}</span><span className={`status-badge large ${reviewClass(report.reviewStatus)}`}>{reviewLabel(report.reviewStatus)}</span></div>}
</div>
{error && <Alert>{error}</Alert>}
{success && <div className="success-banner">{success}</div>}
{report && <>
<div className="temporal-notice"><Icon name="clipboard" /><p><strong>Informe Word automático.</strong> La versión inicial se genera desde la instantánea congelada del Acta. Las correcciones se agregan como nuevas versiones y nunca sobrescriben la anterior.</p></div>
<section className="panel report-summary-panel">
<div className="panel-heading"><div><span className="eyebrow">TRAZABILIDAD DOCUMENTAL</span><h2>{report.code}</h2></div><small className="muted">Versión del Acta: {report.actVersion}</small></div>
<div className="responsible-summary">
<div><small>Empresa</small><strong>{names(report.companies, 'Sin asignar')}</strong></div>
<div><small>Área</small><strong>{names(report.areas, 'Sin asignar')}</strong></div>
<div><small>Hallazgos</small><strong>{report.findingCount}</strong></div>
<div><small>Emitido por</small><strong>{report.generatedBy.firstName} {report.generatedBy.lastName}</strong></div>
</div>
{report.wordStatus === 'READY' && <div className="page-actions"><a className="button secondary" href={inspectionReportWordUrl(report.id)}>Descargar Word automático</a></div>}
<div className="report-linked-documents">
<Link to={`/inspecciones/${report.visitId}`}><span>Inspección</span><strong>{report.visit.code}</strong><Icon name="chevron" /></Link>
<Link to={`/inspecciones/actas/${report.actId}`}><span>Acta incorporada</span><strong>{report.act.code}</strong><small>{report.act.title}</small><Icon name="chevron" /></Link>
<Link to={`/hallazgos?search=${encodeURIComponent(report.act.code)}`}><span>Hallazgos</span><strong>{report.findingCount}</strong><small>Ver seguimiento relacionado</small><Icon name="chevron" /></Link>
</div>
</section>
<section className="panel report-review-panel">
<div className="panel-heading"><div><span className="eyebrow">REVISIÓN DIRECTIVA</span><h2>Versiones y firma final</h2><p className="section-copy">El Acta y los Hallazgos originales permanecen congelados. La revisión sólo versiona el documento Informe.</p></div>{review && <span className={`status-badge large ${reviewClass(review.reviewStatus)}`}>{reviewLabel(review.reviewStatus)}</span>}</div>
{!review ? <LoadingBlock label="Cargando revisión…" /> : <>
<div className="review-flow">
<div className="complete"><span>1</span><strong>Informe automático</strong><small>{review.revisions.length ? 'Versión inicial registrada' : 'Esperando Word'}</small></div>
<div className={review.currentRevisionNumber > 1 ? 'complete' : ''}><span>2</span><strong>Correcciones</strong><small>{review.currentRevisionNumber > 1 ? `${review.currentRevisionNumber - 1} versión/es agregada/s` : 'Sin correcciones'}</small></div>
<div className={review.reviewStatus !== 'PENDING_REVIEW' ? 'complete' : ''}><span>3</span><strong>Aprobación</strong><small>{review.approvedAt ? formatDate(review.approvedAt) : 'Pendiente del Director'}</small></div>
<div className={review.reviewStatus === 'SIGNED' ? 'complete' : ''}><span>4</span><strong>Firma final</strong><small>{review.signature ? formatDate(review.signature.signedAt) : 'Pendiente'}</small></div>
</div>
<div className="report-revision-list">
{review.revisions.map((revision) => <article key={revision.id} className={review.approvedRevisionId === revision.id ? 'approved' : ''}>
<div><span className="status-badge">Versión {revision.revisionNumber}</span><strong>{revision.originalName}</strong><small>{revisionSource(revision.source)} · {revision.createdBy.firstName} {revision.createdBy.lastName} · {formatDate(revision.createdAt)}</small>{revision.changeSummary && <p>{revision.changeSummary}</p>}</div>
<div className="revision-actions"><code title={revision.sha256}>{revision.sha256}</code><a className="button secondary" href={inspectionReportRevisionUrl(revision.id)}>Descargar</a></div>
</article>)}
</div>
{canRevise && review.reviewStatus === 'PENDING_REVIEW' && <form className="report-review-form" onSubmit={uploadRevision}>
<div><span className="eyebrow">NUEVA VERSIÓN</span><h3>Agregar Word corregido</h3><p className="section-copy">Descargá la última versión, realizá la corrección en Word y cargala nuevamente. La versión anterior queda intacta.</p></div>
<label><span>Archivo .docx</span><input type="file" accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document" onChange={(event) => setRevisionFile(event.target.files?.[0] ?? null)} /></label>
<label><span>Resumen de cambios</span><textarea value={changeSummary} onChange={(event) => setChangeSummary(event.target.value)} maxLength={1000} placeholder="Ej.: Se corrigió la conclusión técnica y la referencia del equipo inspeccionado." /></label>
<button className="button primary" disabled={working || !revisionFile || changeSummary.trim().length < 5}>Agregar versión</button>
</form>}
{canReview && review.reviewStatus === 'PENDING_REVIEW' && review.revisions.length > 0 && <div className="report-review-action">
<div><span className="eyebrow">APROBACIÓN</span><h3>Aprobar versión {review.currentRevisionNumber}</h3><p>La aprobación fija esta versión como candidata a firma final. Después de aprobar no se podrán cargar nuevas correcciones.</p></div>
<label><span>Nota de revisión opcional</span><textarea value={approvalNote} onChange={(event) => setApprovalNote(event.target.value)} maxLength={1000} placeholder="Observación interna de aprobación" /></label>
<button type="button" className="button primary" disabled={working} onClick={approve}>Aprobar versión actual</button>
</div>}
{canSign && review.reviewStatus === 'APPROVED' && <div className="report-review-action final-signature-action">
<div><span className="eyebrow">FIRMA FINAL</span><h3>Firma electrónica del Director</h3><p>La firma vincula de forma inmutable al Director, la versión aprobada, el hash del Informe y la fecha. Una vez firmada no admite nuevas versiones.</p></div>
<label className="check-label"><input type="checkbox" checked={signatureConfirmed} onChange={(event) => setSignatureConfirmed(event.target.checked)} /><span>Confirmo que revisé la versión aprobada y firmo electrónicamente el informe final como Director de Hidrocarburos.</span></label>
<button type="button" className="button primary" disabled={working || !signatureConfirmed} onClick={signFinal}>Firmar informe final</button>
</div>}
{review.signature && <div className="signed-report-box"><Icon name="check" /><div><strong>Informe final firmado</strong><p>{review.signature.signedBy.firstName} {review.signature.signedBy.lastName} · {formatDate(review.signature.signedAt)}</p><code title={review.signature.signatureSha256}>{review.signature.signatureSha256}</code></div></div>}
{review.reviewStatus === 'SIGNED' && <div className="temporal-notice"><Icon name="clipboard" /><p><strong>Firma cerrada.</strong> La firma electrónica ya prueba quién aprobó la versión y qué hash fue firmado. La ubicación visual de la rúbrica dentro del documento se resolverá con la plantilla institucional definitiva.</p></div>}
</>}
</section>
<section className="panel report-integrity-panel">
<div className="panel-heading"><div><span className="eyebrow">INTEGRIDAD</span><h2>Contenido congelado</h2><p className="section-copy">El Informe conserva la versión exacta del Acta cerrada y su instantánea documental.</p></div></div>
<dl className="report-integrity-list">
<div><dt>Hash de cierre del Acta</dt><dd>{report.actClosureSha256}</dd></div>
<div><dt>Hash del Informe</dt><dd>{report.frozenSha256}</dd></div>
<div><dt>Estado base</dt><dd>{report.status === 'FROZEN' ? 'Congelado' : 'Cancelado'}</dd></div>
<div><dt>Revisión</dt><dd>{reviewLabel(report.reviewStatus)}</dd></div>
</dl>
</section>
</>}
</section>;
}