Merge pull request #50 from enlineawork/feature/territorial-simple-profile
feat(web): simplificar fichas territoriales
This commit is contained in:
@@ -5,6 +5,7 @@ import { getAsset } from '../lib/api';
|
||||
import type { AssetDetail } from '../lib/api';
|
||||
import { AssetEditorPage } from './AssetEditorPage';
|
||||
import { CompanyInventoryPage } from './CompanyInventoryPage';
|
||||
import { TerritorialInventoryPage, isTerritorialInventoryAsset } from './TerritorialInventoryPage';
|
||||
|
||||
export function InventoryDetailPage() {
|
||||
const { id } = useParams();
|
||||
@@ -30,10 +31,15 @@ export function InventoryDetailPage() {
|
||||
if (loading) return <LoadingBlock label="Cargando registro…" />;
|
||||
if (!asset) return <Alert>{error || 'No se pudo cargar el registro.'}</Alert>;
|
||||
|
||||
const advanced = params.get('advanced') === '1';
|
||||
const isCompany = asset.type.code.toLowerCase() === 'empresa';
|
||||
if (isCompany && params.get('advanced') !== '1') {
|
||||
if (isCompany && !advanced) {
|
||||
return <CompanyInventoryPage initialAsset={asset} />;
|
||||
}
|
||||
|
||||
if (isTerritorialInventoryAsset(asset) && !advanced) {
|
||||
return <TerritorialInventoryPage initialAsset={asset} />;
|
||||
}
|
||||
|
||||
return <AssetEditorPage />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import type { FormEvent } from 'react';
|
||||
import { Link, useSearchParams } from 'react-router';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
import { Alert, LoadingBlock, errorMessage } from '../components/Feedback';
|
||||
import { Icon } from '../components/Icon';
|
||||
import { AssetHistoryPanel } from '../features/assets/AssetHistoryPanel';
|
||||
import { assetStatusClass, assetStatusLabel } from '../features/assets/assetPresentation';
|
||||
import {
|
||||
listAreaCompanyRelations,
|
||||
listAssetTreeChildren,
|
||||
listInspectionVisits,
|
||||
updateAsset,
|
||||
} from '../lib/api';
|
||||
import type { AreaCompanyRelation, AssetDetail, AssetListItem } from '../lib/api';
|
||||
import {
|
||||
listInspectionActsGlobalF4,
|
||||
type InspectionActStatusF4,
|
||||
} from '../lib/inspectionActF4Api';
|
||||
import { listInspectionReportsF4 } from '../lib/reportWorkflowApi';
|
||||
import './territorialInventory.css';
|
||||
|
||||
type TerritoryTab = 'summary' | 'history';
|
||||
|
||||
function normalized(value: string) {
|
||||
return value
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function typeTokens(asset: AssetDetail) {
|
||||
return new Set(`${normalized(asset.type.code)} ${normalized(asset.type.name)}`.split(' ').filter(Boolean));
|
||||
}
|
||||
|
||||
export function isTerritorialInventoryAsset(asset: AssetDetail) {
|
||||
const tokens = typeTokens(asset);
|
||||
return tokens.has('departamento') || tokens.has('area') || tokens.has('yacimiento');
|
||||
}
|
||||
|
||||
function isOperationalArea(asset: AssetDetail) {
|
||||
return typeTokens(asset).has('area');
|
||||
}
|
||||
|
||||
function relationRoleLabel(role: AreaCompanyRelation['relationRole']) {
|
||||
if (role === 'OPERATOR') return 'Operadora';
|
||||
if (role === 'TECHNICAL_OPERATOR') return 'Operadora técnica';
|
||||
if (role === 'CONCESSIONAIRE') return 'Concesionaria / titular';
|
||||
if (role === 'PERMIT_HOLDER') return 'Permisionaria';
|
||||
if (role === 'PARTICIPANT') return 'Participante';
|
||||
return 'Vinculada';
|
||||
}
|
||||
|
||||
export function TerritorialInventoryPage({ initialAsset }: { initialAsset: AssetDetail }) {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const requestedTab = params.get('tab') as TerritoryTab | null;
|
||||
const tab: TerritoryTab = requestedTab === 'history' ? 'history' : 'summary';
|
||||
const { hasPermission } = useAuth();
|
||||
const canEdit = hasPermission('assets.update');
|
||||
const canCreate = hasPermission('assets.create');
|
||||
const canReadHistory = hasPermission('assets.read_history');
|
||||
const canReadRelations = hasPermission('asset_relations.read');
|
||||
const canReadActs = hasPermission('inspection_acts.read');
|
||||
const canReadReports = hasPermission('inspection_reports.read');
|
||||
const canReadInspections = hasPermission('inspections.read');
|
||||
|
||||
const [asset, setAsset] = useState(initialAsset);
|
||||
const [children, setChildren] = useState<AssetListItem[]>([]);
|
||||
const [childrenHasMore, setChildrenHasMore] = useState(false);
|
||||
const [relations, setRelations] = useState<AreaCompanyRelation[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [name, setName] = useState(initialAsset.name);
|
||||
const [description, setDescription] = useState(initialAsset.description ?? '');
|
||||
const [metrics, setMetrics] = useState({ activeInspections: 0, acts: 0, reports: 0 });
|
||||
|
||||
const area = isOperationalArea(asset);
|
||||
const activeRelations = useMemo(() => relations.filter((item) => item.active), [relations]);
|
||||
|
||||
const loadSummary = async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const [childPage, loadedRelations] = await Promise.all([
|
||||
listAssetTreeChildren({ parentId: asset.id, limit: 100 }),
|
||||
area && canReadRelations
|
||||
? listAreaCompanyRelations({ areaId: asset.id, includeHistory: true })
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
setChildren(childPage.data);
|
||||
setChildrenHasMore(childPage.meta.hasMore);
|
||||
setRelations(loadedRelations);
|
||||
} catch (requestError) {
|
||||
setError(errorMessage(requestError));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { void loadSummary(); }, [asset.id, area, canReadRelations]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!area) {
|
||||
setMetrics({ activeInspections: 0, acts: 0, reports: 0 });
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
const loadMetrics = async () => {
|
||||
try {
|
||||
const actStatuses: InspectionActStatusF4[] = ['SEALED', 'CLOSED', 'RECTIFIED'];
|
||||
const [planned, inProgress, actPages, reportPage] = await Promise.all([
|
||||
canReadInspections ? listInspectionVisits({ areaId: asset.id, status: 'PLANNED', pageSize: 1 }) : Promise.resolve(null),
|
||||
canReadInspections ? listInspectionVisits({ areaId: asset.id, status: 'IN_PROGRESS', pageSize: 1 }) : Promise.resolve(null),
|
||||
canReadActs
|
||||
? Promise.all(actStatuses.map((status) => listInspectionActsGlobalF4({ areaId: asset.id, status, pageSize: 1 })))
|
||||
: Promise.resolve([]),
|
||||
canReadReports ? listInspectionReportsF4({ areaId: asset.id, pageSize: 1 }) : Promise.resolve(null),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
setMetrics({
|
||||
activeInspections: (planned?.meta.total ?? 0) + (inProgress?.meta.total ?? 0),
|
||||
acts: actPages.reduce((total, page) => total + page.meta.total, 0),
|
||||
reports: reportPage?.meta.total ?? 0,
|
||||
});
|
||||
} catch {
|
||||
if (!cancelled) setMetrics({ activeInspections: 0, acts: 0, reports: 0 });
|
||||
}
|
||||
};
|
||||
void loadMetrics();
|
||||
return () => { cancelled = true; };
|
||||
}, [asset.id, area, canReadActs, canReadReports, canReadInspections]);
|
||||
|
||||
const save = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!canEdit || !name.trim()) return;
|
||||
setSaving(true); setError(''); setSuccess('');
|
||||
try {
|
||||
const saved = await updateAsset(asset.id, {
|
||||
name: name.trim(),
|
||||
description: description.trim() || null,
|
||||
});
|
||||
setAsset(saved);
|
||||
setName(saved.name);
|
||||
setDescription(saved.description ?? '');
|
||||
setEditing(false);
|
||||
setSuccess('Datos actualizados.');
|
||||
} catch (requestError) {
|
||||
setError(errorMessage(requestError));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const setTab = (next: TerritoryTab) => {
|
||||
const nextParams = new URLSearchParams(params);
|
||||
next === 'summary' ? nextParams.delete('tab') : nextParams.set('tab', next);
|
||||
nextParams.delete('advanced');
|
||||
setParams(nextParams);
|
||||
};
|
||||
|
||||
return <section className="narrow-section territory-page">
|
||||
<nav className="breadcrumb territory-breadcrumb" aria-label="Ruta territorial">
|
||||
<Link to="/inventarios">Inventarios</Link><span>›</span>
|
||||
<Link to="/inventarios?section=territory">Áreas y yacimientos</Link><span>›</span><strong>{asset.name}</strong>
|
||||
</nav>
|
||||
|
||||
<header className="territory-hero">
|
||||
<div>
|
||||
<span className="eyebrow">{asset.type.name.toUpperCase()}</span>
|
||||
<h1>{asset.name}</h1>
|
||||
<p><strong>{asset.code}</strong></p>
|
||||
</div>
|
||||
<div className="territory-hero-actions">
|
||||
<span className={`status-badge ${assetStatusClass(asset.informationStatus)}`}>{assetStatusLabel(asset.informationStatus)}</span>
|
||||
{canEdit && tab === 'summary' && <button type="button" className="button secondary" onClick={() => setEditing((current) => !current)}><Icon name="edit" />{editing ? 'Cancelar edición' : 'Editar'}</button>}
|
||||
{canCreate && tab === 'summary' && <Link className="button primary" to={`/inventarios/nuevo?parentId=${asset.id}`}><Icon name="plus" />Agregar elemento</Link>}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="territory-purpose-note"><Icon name="map" /><span>Este nivel organiza el territorio y la navegación. Los hallazgos se cargan sobre elementos inspeccionables, no sobre {asset.type.name.toLowerCase()}s.</span></div>
|
||||
|
||||
<nav className="territory-tabs" aria-label="Secciones territoriales">
|
||||
<button type="button" className={tab === 'summary' ? 'active' : ''} onClick={() => setTab('summary')}>Resumen</button>
|
||||
{canReadHistory && <button type="button" className={tab === 'history' ? 'active' : ''} onClick={() => setTab('history')}>Historial</button>}
|
||||
</nav>
|
||||
|
||||
{error && <Alert>{error}</Alert>}{success && <Alert type="success">{success}</Alert>}
|
||||
|
||||
{tab === 'summary' && <div className="territory-stack">
|
||||
<article className="panel territory-card">
|
||||
<div className="territory-card-heading">
|
||||
<div><span className="eyebrow">DATOS BÁSICOS</span><h2>Identificación</h2></div>
|
||||
</div>
|
||||
{editing ? <form className="territory-edit-form" onSubmit={save}>
|
||||
<label className="field"><span>Nombre</span><input value={name} onChange={(event) => setName(event.target.value)} required maxLength={200} /></label>
|
||||
<label className="field"><span>Descripción <em>opcional</em></span><textarea value={description} onChange={(event) => setDescription(event.target.value)} rows={3} maxLength={4000} /></label>
|
||||
<div className="form-actions"><button type="button" className="button secondary" onClick={() => { setEditing(false); setName(asset.name); setDescription(asset.description ?? ''); }}>Cancelar</button><button className="button primary" disabled={saving}><Icon name="check" />{saving ? 'Guardando…' : 'Guardar'}</button></div>
|
||||
</form> : <div className="territory-data-grid">
|
||||
<div><small>Tipo</small><strong>{asset.type.name}</strong></div>
|
||||
<div><small>Código DH</small><strong>{asset.code}</strong></div>
|
||||
{asset.description && <div className="wide"><small>Descripción</small><strong>{asset.description}</strong></div>}
|
||||
</div>}
|
||||
</article>
|
||||
|
||||
<article className="panel territory-card">
|
||||
<div className="territory-card-heading">
|
||||
<div><span className="eyebrow">CONTENIDO</span><h2>Registros dentro de {asset.name}</h2><p>Acceso directo a los niveles que dependen de este registro.</p></div>
|
||||
<span className="count-pill">{children.length}{childrenHasMore ? '+' : ''}</span>
|
||||
</div>
|
||||
{loading ? <LoadingBlock label="Cargando contenido…" /> : children.length === 0 ? <div className="inline-empty">Todavía no hay registros dentro de {asset.name}.</div> : <div className="territory-child-list">
|
||||
{children.map((child) => <Link to={`/inventarios/${child.id}`} key={child.id} className="territory-child-row">
|
||||
<span className="asset-symbol"><Icon name="layers" /></span>
|
||||
<span><strong>{child.name}</strong><small>{child.type.name} · {child.code}</small></span>
|
||||
<span className={`status-badge ${assetStatusClass(child.informationStatus)}`}>{assetStatusLabel(child.informationStatus)}</span>
|
||||
<Icon name="chevron" size={16} />
|
||||
</Link>)}
|
||||
</div>}
|
||||
{childrenHasMore && <div className="territory-card-actions"><Link className="button secondary" to={`/inventarios?section=territory&parentId=${asset.id}`}>Ver contenido completo</Link></div>}
|
||||
</article>
|
||||
|
||||
{area && canReadRelations && <article className="panel territory-card">
|
||||
<div className="territory-card-heading"><div><span className="eyebrow">OPERACIÓN</span><h2>Empresas vinculadas</h2><p>Quién opera o participa actualmente en esta área.</p></div><span className="count-pill">{activeRelations.length}</span></div>
|
||||
{loading ? <LoadingBlock label="Cargando empresas…" /> : activeRelations.length === 0 ? <div className="inline-empty">No hay empresas con vínculo vigente.</div> : <div className="territory-company-list">
|
||||
{activeRelations.map((relation) => <Link to={`/inventarios/${relation.company.id}`} key={relation.id} className="territory-company-row"><span><strong>{relation.company.name}</strong><small>{relationRoleLabel(relation.relationRole)}</small></span><Icon name="chevron" size={16} /></Link>)}
|
||||
</div>}
|
||||
</article>}
|
||||
|
||||
{area && (canReadInspections || canReadActs || canReadReports) && <article className="panel territory-card">
|
||||
<div className="territory-card-heading"><div><span className="eyebrow">ACTIVIDAD</span><h2>Actividad del área</h2><p>Resumen documental y operativo, sin mezclarlo con hallazgos de los elementos inspeccionados.</p></div></div>
|
||||
<div className="territory-metrics">
|
||||
{canReadInspections && <div><small>Inspecciones activas</small><strong>{metrics.activeInspections}</strong></div>}
|
||||
{canReadActs && <div><small>Actas emitidas</small><strong>{metrics.acts}</strong></div>}
|
||||
{canReadReports && <div><small>Informes</small><strong>{metrics.reports}</strong></div>}
|
||||
</div>
|
||||
</article>}
|
||||
|
||||
<div className="territory-advanced-link"><span>Los datos estructurales, procedencia, ubicación y opciones técnicas quedan fuera de la vista cotidiana.</span><Link to={`/inventarios/${asset.id}?advanced=1`}>Administración avanzada</Link></div>
|
||||
</div>}
|
||||
|
||||
{tab === 'history' && canReadHistory && <AssetHistoryPanel assetId={asset.id} />}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
.territory-page { display: grid; gap: 18px; }
|
||||
.territory-breadcrumb { margin-bottom: 0; }
|
||||
|
||||
.territory-hero {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
padding: 4px 0 2px;
|
||||
}
|
||||
.territory-hero h1 { margin: 6px 0 5px; font-size: clamp(31px, 3.5vw, 44px); line-height: 1.02; letter-spacing: -.045em; }
|
||||
.territory-hero p { margin: 0; color: var(--muted); font-size: 13px; }
|
||||
.territory-hero-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
|
||||
.territory-purpose-note {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
padding: 11px 13px;
|
||||
border: 1px solid #dbe4f2;
|
||||
border-radius: 10px;
|
||||
color: #536078;
|
||||
background: #f7f9fd;
|
||||
font-size: 11px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.territory-purpose-note .icon { color: var(--blue); flex: 0 0 auto; }
|
||||
|
||||
.territory-tabs {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
overflow-x: auto;
|
||||
padding: 0 0 1px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.territory-tabs button {
|
||||
position: relative;
|
||||
min-height: 43px;
|
||||
padding: 9px 13px;
|
||||
border: 0;
|
||||
color: #566178;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.territory-tabs button:hover { color: var(--ink); }
|
||||
.territory-tabs button.active { color: var(--blue); }
|
||||
.territory-tabs button.active::after { content: ''; position: absolute; left: 10px; right: 10px; bottom: -1px; height: 2px; border-radius: 2px; background: var(--blue); }
|
||||
|
||||
.territory-stack { display: grid; gap: 15px; }
|
||||
.territory-card { padding: 22px; }
|
||||
.territory-card-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; margin-bottom: 16px; }
|
||||
.territory-card-heading h2 { margin: 4px 0; }
|
||||
.territory-card-heading p { max-width: 680px; margin: 0; color: var(--muted); font-size: 12px; line-height: 1.5; }
|
||||
.territory-card-actions { display: flex; justify-content: flex-end; margin-top: 14px; }
|
||||
|
||||
.territory-data-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1px; overflow: hidden; border: 1px solid var(--line); border-radius: 11px; background: var(--line); }
|
||||
.territory-data-grid > div { min-height: 74px; padding: 15px 16px; background: #fff; }
|
||||
.territory-data-grid > div.wide { grid-column: 1 / -1; }
|
||||
.territory-data-grid small, .territory-data-grid strong { display: block; }
|
||||
.territory-data-grid small { margin-bottom: 7px; color: var(--muted); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; }
|
||||
.territory-data-grid strong { font-size: 13px; font-weight: 750; line-height: 1.45; }
|
||||
.territory-edit-form { display: grid; gap: 15px; }
|
||||
|
||||
.territory-child-list, .territory-company-list { display: grid; gap: 8px; }
|
||||
.territory-child-row, .territory-company-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-height: 60px;
|
||||
padding: 11px 13px;
|
||||
border: 1px solid #e2e7ef;
|
||||
border-radius: 10px;
|
||||
color: inherit;
|
||||
background: #fbfcfd;
|
||||
text-decoration: none;
|
||||
}
|
||||
.territory-child-row:hover, .territory-company-row:hover { border-color: #bfd0ee; background: #f7faff; }
|
||||
.territory-child-row > span:nth-child(2), .territory-company-row > span:first-child { flex: 1; min-width: 0; }
|
||||
.territory-child-row strong, .territory-child-row small, .territory-company-row strong, .territory-company-row small { display: block; }
|
||||
.territory-child-row strong, .territory-company-row strong { font-size: 12px; }
|
||||
.territory-child-row small, .territory-company-row small { margin-top: 4px; color: var(--muted); font-size: 10px; }
|
||||
.territory-child-row > .icon:last-child, .territory-company-row > .icon:last-child { color: #8b96aa; }
|
||||
|
||||
.territory-metrics { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
|
||||
.territory-metrics > div { display: grid; gap: 6px; padding: 16px; border: 1px solid #e2e7ef; border-radius: 11px; background: #f8faff; }
|
||||
.territory-metrics small { color: var(--muted); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; }
|
||||
.territory-metrics strong { color: #173b7a; font-size: 25px; line-height: 1; letter-spacing: -.04em; }
|
||||
|
||||
.territory-advanced-link { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 12px 15px; border: 1px dashed #ccd4e2; border-radius: 10px; color: var(--muted); background: rgba(255,255,255,.55); font-size: 11px; }
|
||||
.territory-advanced-link a { color: var(--blue); font-weight: 750; text-decoration: none; }
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.territory-hero { align-items: flex-start; flex-direction: column; }
|
||||
.territory-hero-actions { width: 100%; }
|
||||
.territory-card { padding: 18px; }
|
||||
.territory-card-heading { align-items: flex-start; flex-direction: column; }
|
||||
.territory-data-grid, .territory-metrics { grid-template-columns: 1fr; }
|
||||
.territory-data-grid > div.wide { grid-column: auto; }
|
||||
.territory-child-row { align-items: flex-start; flex-wrap: wrap; }
|
||||
.territory-child-row .status-badge { margin-left: 44px; }
|
||||
.territory-advanced-link { align-items: flex-start; flex-direction: column; }
|
||||
}
|
||||
Reference in New Issue
Block a user