Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74ff64182c | ||
|
|
a9e300d6a4 | ||
|
|
143db53552 | ||
|
|
d9fbd95da3 | ||
|
|
b744a77f49 | ||
|
|
082354320b | ||
|
|
71dda05c20 | ||
|
|
b88855860d | ||
|
|
ec84f42a74 | ||
|
|
b859278ad0 | ||
|
|
32fc5bc60d |
@@ -14,7 +14,7 @@ import { AccessDeniedPage, NotFoundPage } from '../pages/SystemPages';
|
|||||||
import { UserDetailPage } from '../pages/UserDetailPage';
|
import { UserDetailPage } from '../pages/UserDetailPage';
|
||||||
import { UsersPage } from '../pages/UsersPage';
|
import { UsersPage } from '../pages/UsersPage';
|
||||||
import { AssetsPage } from '../pages/AssetsPage';
|
import { AssetsPage } from '../pages/AssetsPage';
|
||||||
import { AssetEditorPage } from '../pages/AssetEditorPage';
|
import { InventoryDetailPage } from '../pages/InventoryDetailPage';
|
||||||
import { InventoryCreatePage } from '../pages/InventoryCreatePage';
|
import { InventoryCreatePage } from '../pages/InventoryCreatePage';
|
||||||
import { FieldDiscoveriesPage } from '../pages/FieldDiscoveriesPage';
|
import { FieldDiscoveriesPage } from '../pages/FieldDiscoveriesPage';
|
||||||
import { AuthoritativeInventoryConfigPage } from '../pages/AuthoritativeInventoryConfigPage';
|
import { AuthoritativeInventoryConfigPage } from '../pages/AuthoritativeInventoryConfigPage';
|
||||||
@@ -49,9 +49,9 @@ export function App() {
|
|||||||
<Route element={<PermissionRoute permission="assets.read" />}><Route path="/mapa" element={<MapPage />} /></Route>
|
<Route element={<PermissionRoute permission="assets.read" />}><Route path="/mapa" element={<MapPage />} /></Route>
|
||||||
<Route element={<PermissionRoute permission="assets.read" />}>
|
<Route element={<PermissionRoute permission="assets.read" />}>
|
||||||
<Route path="/inventarios" element={<AssetsPage />} />
|
<Route path="/inventarios" element={<AssetsPage />} />
|
||||||
<Route path="/inventarios/:id" element={<AssetEditorPage />} />
|
<Route path="/inventarios/:id" element={<InventoryDetailPage />} />
|
||||||
<Route path="/activos" element={<Navigate to="/inventarios" replace />} />
|
<Route path="/activos" element={<Navigate to="/inventarios" replace />} />
|
||||||
<Route path="/activos/:id" element={<AssetEditorPage />} />
|
<Route path="/activos/:id" element={<InventoryDetailPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route element={<PermissionRoute permission="assets.change_status" />}><Route path="/inventarios/revision-campo" element={<FieldDiscoveriesPage />} /></Route>
|
<Route element={<PermissionRoute permission="assets.change_status" />}><Route path="/inventarios/revision-campo" element={<FieldDiscoveriesPage />} /></Route>
|
||||||
<Route element={<PermissionRoute permission="assets.create" />}><Route path="/inventarios/nuevo" element={<InventoryCreatePage />} /><Route path="/activos/nuevo" element={<Navigate to="/inventarios/nuevo" replace />} /></Route>
|
<Route element={<PermissionRoute permission="assets.create" />}><Route path="/inventarios/nuevo" element={<InventoryCreatePage />} /><Route path="/activos/nuevo" element={<Navigate to="/inventarios/nuevo" replace />} /></Route>
|
||||||
|
|||||||
@@ -34,10 +34,10 @@ function supportsFunctionChange(code: string, name: string): boolean {
|
|||||||
|
|
||||||
export function AssetHistoryPanel({
|
export function AssetHistoryPanel({
|
||||||
assetId,
|
assetId,
|
||||||
refreshKey,
|
refreshKey = 0,
|
||||||
}: {
|
}: {
|
||||||
assetId: string;
|
assetId: string;
|
||||||
refreshKey: number;
|
refreshKey?: number;
|
||||||
}) {
|
}) {
|
||||||
const [versions, setVersions] = useState<AssetVersionSummary[]>([]);
|
const [versions, setVersions] = useState<AssetVersionSummary[]>([]);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
|
|||||||
@@ -52,12 +52,12 @@ export function AssetMediaPanel({
|
|||||||
assetId,
|
assetId,
|
||||||
assetName,
|
assetName,
|
||||||
canManage,
|
canManage,
|
||||||
onChanged,
|
onChanged = () => undefined,
|
||||||
}: {
|
}: {
|
||||||
assetId: string;
|
assetId: string;
|
||||||
assetName: string;
|
assetName: string;
|
||||||
canManage: boolean;
|
canManage: boolean;
|
||||||
onChanged: () => void;
|
onChanged?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const fileRef = useRef<HTMLInputElement | null>(null);
|
const fileRef = useRef<HTMLInputElement | null>(null);
|
||||||
const [items, setItems] = useState<AssetMedia[]>([]);
|
const [items, setItems] = useState<AssetMedia[]>([]);
|
||||||
|
|||||||
@@ -0,0 +1,437 @@
|
|||||||
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
import type { FormEvent } from 'react';
|
||||||
|
import { Link, useSearchParams } from 'react-router';
|
||||||
|
import { useAuth } from '../auth/AuthContext';
|
||||||
|
import { Alert, EmptyState, LoadingBlock, errorMessage } from '../components/Feedback';
|
||||||
|
import { Icon } from '../components/Icon';
|
||||||
|
import { SearchableSelect } from '../components/SearchableSelect';
|
||||||
|
import { AssetHistoryPanel } from '../features/assets/AssetHistoryPanel';
|
||||||
|
import { AssetMediaPanel } from '../features/assets/AssetMediaPanel';
|
||||||
|
import { assetStatusClass, assetStatusLabel } from '../features/assets/assetPresentation';
|
||||||
|
import {
|
||||||
|
createAreaCompanyRelation,
|
||||||
|
endAreaCompanyRelation,
|
||||||
|
getAssetRegistry,
|
||||||
|
listAreaCompanyRelations,
|
||||||
|
listInspectionVisits,
|
||||||
|
listOperationalAreas,
|
||||||
|
updateAsset,
|
||||||
|
upsertOrganizationProfile,
|
||||||
|
} from '../lib/api';
|
||||||
|
import type {
|
||||||
|
AreaCompanyRelation,
|
||||||
|
AssetDetail,
|
||||||
|
AssetRegistry,
|
||||||
|
OperationalAssetSummary,
|
||||||
|
OrganizationKind,
|
||||||
|
} from '../lib/api';
|
||||||
|
import {
|
||||||
|
listInspectionActsGlobalF4,
|
||||||
|
type InspectionActListItemF4,
|
||||||
|
type InspectionActStatusF4,
|
||||||
|
} from '../lib/inspectionActF4Api';
|
||||||
|
import {
|
||||||
|
listInspectionReportsF4,
|
||||||
|
type InspectionReportDetailF4,
|
||||||
|
} from '../lib/reportWorkflowApi';
|
||||||
|
import { formatDate } from '../lib/format';
|
||||||
|
import './companyInventory.css';
|
||||||
|
|
||||||
|
type CompanyTab = 'summary' | 'issued' | 'documents' | 'history';
|
||||||
|
|
||||||
|
const organizationLabels: Record<OrganizationKind, string> = {
|
||||||
|
COMPANY: 'Empresa',
|
||||||
|
UTE: 'UTE',
|
||||||
|
PUBLIC_ENTITY: 'Entidad pública',
|
||||||
|
OTHER: 'Otra organización',
|
||||||
|
};
|
||||||
|
|
||||||
|
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 'Otro vínculo';
|
||||||
|
}
|
||||||
|
|
||||||
|
function reportStatusLabel(report: InspectionReportDetailF4) {
|
||||||
|
if (report.status === 'OFFICIALIZED') return report.gedoIfIdentifier ? `GEDO · ${report.gedoIfIdentifier}` : 'Oficializado en GEDO';
|
||||||
|
if (report.status === 'WORKING') return 'INF en preparación';
|
||||||
|
if (report.status === 'CANCELLED') return 'Cancelado';
|
||||||
|
return 'Informe histórico';
|
||||||
|
}
|
||||||
|
|
||||||
|
function reportStatusClass(report: InspectionReportDetailF4) {
|
||||||
|
if (report.status === 'OFFICIALIZED') return 'active';
|
||||||
|
if (report.status === 'CANCELLED') return 'danger';
|
||||||
|
return 'pending';
|
||||||
|
}
|
||||||
|
|
||||||
|
function areaLabel(items: Array<{ name: string }>) {
|
||||||
|
if (!items.length) return 'Área sin informar';
|
||||||
|
const first = items[0];
|
||||||
|
if (!first) return 'Área sin informar';
|
||||||
|
return items.length === 1 ? first.name : `${first.name} +${items.length - 1}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAllActs(companyId: string): Promise<InspectionActListItemF4[]> {
|
||||||
|
const statuses: InspectionActStatusF4[] = ['SEALED', 'CLOSED', 'RECTIFIED'];
|
||||||
|
const groups = await Promise.all(statuses.map(async (status) => {
|
||||||
|
const collected: InspectionActListItemF4[] = [];
|
||||||
|
let page = 1;
|
||||||
|
let totalPages = 1;
|
||||||
|
do {
|
||||||
|
const response = await listInspectionActsGlobalF4({ companyId, status, page, pageSize: 100 });
|
||||||
|
collected.push(...response.data);
|
||||||
|
totalPages = response.meta.totalPages;
|
||||||
|
page += 1;
|
||||||
|
} while (page <= totalPages);
|
||||||
|
return collected;
|
||||||
|
}));
|
||||||
|
return groups.flat().sort((a, b) => new Date(b.occurredAt).getTime() - new Date(a.occurredAt).getTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAllReports(companyId: string): Promise<InspectionReportDetailF4[]> {
|
||||||
|
const collected: InspectionReportDetailF4[] = [];
|
||||||
|
let page = 1;
|
||||||
|
let totalPages = 1;
|
||||||
|
do {
|
||||||
|
const response = await listInspectionReportsF4({ companyId, page, pageSize: 100 });
|
||||||
|
collected.push(...response.data);
|
||||||
|
totalPages = response.meta.totalPages;
|
||||||
|
page += 1;
|
||||||
|
} while (page <= totalPages);
|
||||||
|
return collected
|
||||||
|
.filter((item) => item.status !== 'CANCELLED')
|
||||||
|
.sort((a, b) => new Date(b.generatedAt).getTime() - new Date(a.generatedAt).getTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CompanyInventoryPage({ initialAsset }: { initialAsset: AssetDetail }) {
|
||||||
|
const [params, setParams] = useSearchParams();
|
||||||
|
const requestedTab = params.get('tab') as CompanyTab | null;
|
||||||
|
const tab: CompanyTab = requestedTab && ['summary', 'issued', 'documents', 'history'].includes(requestedTab)
|
||||||
|
? requestedTab
|
||||||
|
: 'summary';
|
||||||
|
const { hasPermission } = useAuth();
|
||||||
|
const canEditAsset = hasPermission('assets.update');
|
||||||
|
const canReadRegistry = hasPermission('asset_registry.read');
|
||||||
|
const canManageRegistry = hasPermission('asset_registry.manage');
|
||||||
|
const canReadRelations = hasPermission('asset_relations.read');
|
||||||
|
const canManageRelations = hasPermission('asset_relations.manage');
|
||||||
|
const canReadActs = hasPermission('inspection_acts.read');
|
||||||
|
const canReadReports = hasPermission('inspection_reports.read');
|
||||||
|
const canReadInspections = hasPermission('inspections.read');
|
||||||
|
const canReadMedia = hasPermission('assets.read_media');
|
||||||
|
const canManageMedia = hasPermission('assets.manage_media');
|
||||||
|
const canReadHistory = hasPermission('assets.read_history');
|
||||||
|
|
||||||
|
const [asset, setAsset] = useState(initialAsset);
|
||||||
|
const [registry, setRegistry] = useState<AssetRegistry | null>(null);
|
||||||
|
const [relations, setRelations] = useState<AreaCompanyRelation[]>([]);
|
||||||
|
const [areas, setAreas] = useState<OperationalAssetSummary[]>([]);
|
||||||
|
const [loadingContext, setLoadingContext] = useState(true);
|
||||||
|
const [contextError, setContextError] = useState('');
|
||||||
|
const [success, setSuccess] = useState('');
|
||||||
|
const [editing, setEditing] = useState(false);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [companyForm, setCompanyForm] = useState({
|
||||||
|
name: initialAsset.name,
|
||||||
|
commonName: initialAsset.commonName ?? '',
|
||||||
|
organizationKind: 'COMPANY' as OrganizationKind,
|
||||||
|
legalName: initialAsset.name,
|
||||||
|
taxId: '',
|
||||||
|
notificationEmail: '',
|
||||||
|
notes: '',
|
||||||
|
});
|
||||||
|
const [relationForm, setRelationForm] = useState({ areaId: '', reason: '' });
|
||||||
|
const [metrics, setMetrics] = useState({ acts: 0, reports: 0, activeInspections: 0 });
|
||||||
|
const [acts, setActs] = useState<InspectionActListItemF4[]>([]);
|
||||||
|
const [reports, setReports] = useState<InspectionReportDetailF4[]>([]);
|
||||||
|
const [documentsLoading, setDocumentsLoading] = useState(false);
|
||||||
|
const [documentsError, setDocumentsError] = useState('');
|
||||||
|
const [documentSearch, setDocumentSearch] = useState('');
|
||||||
|
|
||||||
|
const activeRelations = useMemo(() => relations.filter((item) => item.active), [relations]);
|
||||||
|
|
||||||
|
const loadContext = async () => {
|
||||||
|
setLoadingContext(true);
|
||||||
|
setContextError('');
|
||||||
|
try {
|
||||||
|
const [loadedRegistry, loadedRelations, loadedAreas] = await Promise.all([
|
||||||
|
canReadRegistry ? getAssetRegistry(asset.id) : Promise.resolve(null),
|
||||||
|
canReadRelations ? listAreaCompanyRelations({ companyId: asset.id, includeHistory: true }) : Promise.resolve([]),
|
||||||
|
canManageRelations ? listOperationalAreas() : Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
setRegistry(loadedRegistry);
|
||||||
|
setRelations(loadedRelations);
|
||||||
|
setAreas(loadedAreas);
|
||||||
|
if (loadedRegistry?.organizationProfile) {
|
||||||
|
const profile = loadedRegistry.organizationProfile;
|
||||||
|
setCompanyForm({
|
||||||
|
name: asset.name,
|
||||||
|
commonName: asset.commonName ?? '',
|
||||||
|
organizationKind: profile.organizationKind,
|
||||||
|
legalName: profile.legalName ?? asset.name,
|
||||||
|
taxId: profile.taxId ?? '',
|
||||||
|
notificationEmail: profile.notificationEmail ?? '',
|
||||||
|
notes: profile.notes ?? '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (requestError) {
|
||||||
|
setContextError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setLoadingContext(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => { void loadContext(); }, [asset.id]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
const loadMetrics = async () => {
|
||||||
|
try {
|
||||||
|
const [sealed, closed, rectified, reportPage, planned, inProgress] = await Promise.all([
|
||||||
|
canReadActs ? listInspectionActsGlobalF4({ companyId: asset.id, status: 'SEALED', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadActs ? listInspectionActsGlobalF4({ companyId: asset.id, status: 'CLOSED', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadActs ? listInspectionActsGlobalF4({ companyId: asset.id, status: 'RECTIFIED', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadReports ? listInspectionReportsF4({ companyId: asset.id, pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadInspections ? listInspectionVisits({ companyId: asset.id, status: 'PLANNED', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadInspections ? listInspectionVisits({ companyId: asset.id, status: 'IN_PROGRESS', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
]);
|
||||||
|
if (cancelled) return;
|
||||||
|
setMetrics({
|
||||||
|
acts: (sealed?.meta.total ?? 0) + (closed?.meta.total ?? 0) + (rectified?.meta.total ?? 0),
|
||||||
|
reports: reportPage?.meta.total ?? 0,
|
||||||
|
activeInspections: (planned?.meta.total ?? 0) + (inProgress?.meta.total ?? 0),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
if (!cancelled) setMetrics({ acts: 0, reports: 0, activeInspections: 0 });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
void loadMetrics();
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [asset.id, canReadActs, canReadReports, canReadInspections]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (tab !== 'issued' || (!canReadActs && !canReadReports)) return;
|
||||||
|
let cancelled = false;
|
||||||
|
setDocumentsLoading(true);
|
||||||
|
setDocumentsError('');
|
||||||
|
Promise.all([
|
||||||
|
canReadActs ? loadAllActs(asset.id) : Promise.resolve([]),
|
||||||
|
canReadReports ? loadAllReports(asset.id) : Promise.resolve([]),
|
||||||
|
])
|
||||||
|
.then(([loadedActs, loadedReports]) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
setActs(loadedActs);
|
||||||
|
setReports(loadedReports);
|
||||||
|
})
|
||||||
|
.catch((requestError) => { if (!cancelled) setDocumentsError(errorMessage(requestError)); })
|
||||||
|
.finally(() => { if (!cancelled) setDocumentsLoading(false); });
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [tab, asset.id, canReadActs, canReadReports]);
|
||||||
|
|
||||||
|
const saveCompany = async (event: FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
setSaving(true); setContextError(''); setSuccess('');
|
||||||
|
try {
|
||||||
|
let savedAsset = asset;
|
||||||
|
if (canEditAsset) {
|
||||||
|
savedAsset = await updateAsset(asset.id, {
|
||||||
|
name: companyForm.name.trim(),
|
||||||
|
commonName: companyForm.commonName.trim() || null,
|
||||||
|
});
|
||||||
|
setAsset(savedAsset);
|
||||||
|
}
|
||||||
|
if (canManageRegistry) {
|
||||||
|
await upsertOrganizationProfile(asset.id, {
|
||||||
|
organizationKind: companyForm.organizationKind,
|
||||||
|
legalName: companyForm.legalName.trim() || null,
|
||||||
|
taxId: companyForm.taxId.trim() || null,
|
||||||
|
notificationEmail: companyForm.notificationEmail.trim() || null,
|
||||||
|
notes: companyForm.notes.trim() || null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setEditing(false);
|
||||||
|
setSuccess('Datos de la empresa actualizados.');
|
||||||
|
await loadContext();
|
||||||
|
} catch (requestError) {
|
||||||
|
setContextError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const addRelation = async (event: FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!relationForm.areaId || relationForm.reason.trim().length < 3) return;
|
||||||
|
setSaving(true); setContextError(''); setSuccess('');
|
||||||
|
try {
|
||||||
|
await createAreaCompanyRelation({
|
||||||
|
areaId: relationForm.areaId,
|
||||||
|
companyId: asset.id,
|
||||||
|
reason: relationForm.reason.trim(),
|
||||||
|
});
|
||||||
|
setRelationForm({ areaId: '', reason: '' });
|
||||||
|
setSuccess('Área vinculada a la empresa.');
|
||||||
|
await loadContext();
|
||||||
|
} catch (requestError) {
|
||||||
|
setContextError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const endRelation = async (relation: AreaCompanyRelation) => {
|
||||||
|
const reason = window.prompt(`Motivo para finalizar el vínculo con ${relation.area.name}`);
|
||||||
|
if (!reason?.trim() || reason.trim().length < 3) return;
|
||||||
|
setSaving(true); setContextError(''); setSuccess('');
|
||||||
|
try {
|
||||||
|
await endAreaCompanyRelation(relation.id, reason.trim());
|
||||||
|
setSuccess('Vínculo finalizado. El historial quedó conservado.');
|
||||||
|
await loadContext();
|
||||||
|
} catch (requestError) {
|
||||||
|
setContextError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const setTab = (next: CompanyTab) => {
|
||||||
|
const nextParams = new URLSearchParams(params);
|
||||||
|
next === 'summary' ? nextParams.delete('tab') : nextParams.set('tab', next);
|
||||||
|
nextParams.delete('advanced');
|
||||||
|
setParams(nextParams);
|
||||||
|
};
|
||||||
|
|
||||||
|
const reportByAct = useMemo(() => new Map(reports.map((report) => [report.actId, report])), [reports]);
|
||||||
|
const filteredActs = useMemo(() => {
|
||||||
|
const needle = documentSearch.trim().toLocaleLowerCase('es');
|
||||||
|
if (!needle) return acts;
|
||||||
|
return acts.filter((act) => [
|
||||||
|
act.code,
|
||||||
|
act.title,
|
||||||
|
act.visit.code,
|
||||||
|
...act.areas.map((item) => item.name),
|
||||||
|
reportByAct.get(act.id)?.code ?? '',
|
||||||
|
reportByAct.get(act.id)?.gedoIfIdentifier ?? '',
|
||||||
|
].join(' ').toLocaleLowerCase('es').includes(needle));
|
||||||
|
}, [acts, documentSearch, reportByAct]);
|
||||||
|
|
||||||
|
const usedAreaIds = new Set(activeRelations.map((relation) => relation.area.id));
|
||||||
|
const availableAreas = areas.filter((item) => !usedAreaIds.has(item.id));
|
||||||
|
const profile = registry?.organizationProfile ?? null;
|
||||||
|
|
||||||
|
return <section className="narrow-section company-page">
|
||||||
|
<nav className="breadcrumb company-breadcrumb" aria-label="Ruta de empresa">
|
||||||
|
<Link to="/inventarios">Inventarios</Link><span>›</span>
|
||||||
|
<Link to="/inventarios?section=companies">Empresas</Link><span>›</span><strong>{asset.name}</strong>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header className="company-hero">
|
||||||
|
<div>
|
||||||
|
<span className="eyebrow">EMPRESA</span>
|
||||||
|
<h1>{asset.name}</h1>
|
||||||
|
<p><strong>{asset.code}</strong>{profile?.taxId ? ` · CUIT ${profile.taxId}` : ''}</p>
|
||||||
|
</div>
|
||||||
|
<div className="company-hero-actions">
|
||||||
|
<span className={`status-badge ${assetStatusClass(asset.informationStatus)}`}>{assetStatusLabel(asset.informationStatus)}</span>
|
||||||
|
{(canEditAsset || canManageRegistry) && tab === 'summary' && <button type="button" className="button primary" onClick={() => setEditing((current) => !current)}><Icon name="edit" />{editing ? 'Cerrar edición' : 'Editar empresa'}</button>}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<nav className="company-tabs" aria-label="Secciones de la empresa">
|
||||||
|
<button type="button" className={tab === 'summary' ? 'active' : ''} onClick={() => setTab('summary')}>Resumen</button>
|
||||||
|
{(canReadActs || canReadReports) && <button type="button" className={tab === 'issued' ? 'active' : ''} onClick={() => setTab('issued')}>Actas e informes</button>}
|
||||||
|
{(canReadRegistry || canReadMedia) && <button type="button" className={tab === 'documents' ? 'active' : ''} onClick={() => setTab('documents')}>Documentación</button>}
|
||||||
|
{canReadHistory && <button type="button" className={tab === 'history' ? 'active' : ''} onClick={() => setTab('history')}>Historial</button>}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{contextError && <Alert>{contextError}</Alert>}
|
||||||
|
{success && <Alert type="success">{success}</Alert>}
|
||||||
|
|
||||||
|
{tab === 'summary' && <div className="company-stack">
|
||||||
|
{loadingContext ? <LoadingBlock label="Cargando empresa…" /> : <>
|
||||||
|
<article className="panel company-card">
|
||||||
|
<div className="company-card-heading">
|
||||||
|
<div><span className="eyebrow">IDENTIDAD</span><h2>Datos de la empresa</h2><p>La información que se usa para identificarla y enviar documentación oficial.</p></div>
|
||||||
|
</div>
|
||||||
|
{editing ? <form className="company-edit-form" onSubmit={saveCompany}>
|
||||||
|
<div className="form-grid">
|
||||||
|
<label className="field"><span>Nombre</span><input value={companyForm.name} disabled={!canEditAsset} onChange={(event) => setCompanyForm({ ...companyForm, name: event.target.value })} required /></label>
|
||||||
|
<label className="field"><span>Nombre corto / sigla <em>opcional</em></span><input value={companyForm.commonName} disabled={!canEditAsset} onChange={(event) => setCompanyForm({ ...companyForm, commonName: event.target.value })} placeholder="Ej.: EMESA" /></label>
|
||||||
|
<label className="field"><span>Tipo</span><SearchableSelect value={companyForm.organizationKind} disabled={!canManageRegistry} onChange={(event) => setCompanyForm({ ...companyForm, organizationKind: event.target.value as OrganizationKind })}>{Object.entries(organizationLabels).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</SearchableSelect></label>
|
||||||
|
<label className="field"><span>Razón social <em>opcional</em></span><input value={companyForm.legalName} disabled={!canManageRegistry} onChange={(event) => setCompanyForm({ ...companyForm, legalName: event.target.value })} /></label>
|
||||||
|
<label className="field"><span>CUIT <em>opcional</em></span><input value={companyForm.taxId} disabled={!canManageRegistry} onChange={(event) => setCompanyForm({ ...companyForm, taxId: event.target.value })} /></label>
|
||||||
|
<label className="field"><span>Email oficial para actas <em>opcional</em></span><input type="email" value={companyForm.notificationEmail} disabled={!canManageRegistry} onChange={(event) => setCompanyForm({ ...companyForm, notificationEmail: event.target.value })} /></label>
|
||||||
|
</div>
|
||||||
|
<label className="field"><span>Notas <em>opcional</em></span><textarea rows={2} value={companyForm.notes} disabled={!canManageRegistry} onChange={(event) => setCompanyForm({ ...companyForm, notes: event.target.value })} /></label>
|
||||||
|
<div className="form-actions"><button type="button" className="button secondary" onClick={() => setEditing(false)}>Cancelar</button><button className="button primary" disabled={saving}>{saving ? 'Guardando…' : 'Guardar cambios'}</button></div>
|
||||||
|
</form> : <div className="company-data-grid">
|
||||||
|
<div><small>Razón social</small><strong>{profile?.legalName || asset.name}</strong></div>
|
||||||
|
<div><small>Tipo</small><strong>{organizationLabels[profile?.organizationKind ?? 'COMPANY']}</strong></div>
|
||||||
|
<div><small>CUIT</small><strong>{profile?.taxId || 'Sin informar'}</strong></div>
|
||||||
|
<div><small>Email oficial para actas</small><strong>{profile?.notificationEmail || 'Sin informar'}</strong></div>
|
||||||
|
</div>}
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article className="panel company-card">
|
||||||
|
<div className="company-card-heading">
|
||||||
|
<div><span className="eyebrow">OPERACIÓN</span><h2>Áreas donde opera</h2><p>Estas relaciones indican dónde participa la empresa. No cambian la jerarquía física del Inventario.</p></div>
|
||||||
|
<span className="count-pill">{activeRelations.length}</span>
|
||||||
|
</div>
|
||||||
|
{activeRelations.length === 0 ? <EmptyState title="Sin áreas vinculadas" text="Todavía no hay áreas operativas asociadas a esta empresa." /> : <div className="company-area-list">{activeRelations.map((relation) => <div className="company-area-row" key={relation.id}>
|
||||||
|
<Link to={`/inventarios/${relation.area.id}`}><strong>{relation.area.name}</strong><small>{relation.area.code} · {relationRoleLabel(relation.relationRole)}</small></Link>
|
||||||
|
<div><span className="status-badge active">Activa</span>{canManageRelations && <button type="button" className="button text compact" disabled={saving} onClick={() => void endRelation(relation)}>Finalizar</button>}</div>
|
||||||
|
</div>)}</div>}
|
||||||
|
{canManageRelations && <details className="company-inline-action"><summary><Icon name="plus" size={15} />Vincular otra área</summary><form onSubmit={addRelation}><div className="form-grid"><label className="field"><span>Área</span><SearchableSelect value={relationForm.areaId} onChange={(event) => setRelationForm({ ...relationForm, areaId: event.target.value })} required><option value="">Seleccionar área…</option>{availableAreas.map((item) => <option key={item.id} value={item.id}>{item.name} · {item.code}</option>)}</SearchableSelect></label><label className="field"><span>Motivo</span><input value={relationForm.reason} onChange={(event) => setRelationForm({ ...relationForm, reason: event.target.value })} minLength={3} required placeholder="Ej.: operación vigente" /></label></div><button className="button primary" disabled={saving || !relationForm.areaId || relationForm.reason.trim().length < 3}>Vincular área</button></form></details>}
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article className="panel company-card company-activity-card">
|
||||||
|
<div className="company-card-heading"><div><span className="eyebrow">INSPECCIONES</span><h2>Actividad de la empresa</h2><p>Acceso rápido a la documentación que ya fue emitida.</p></div></div>
|
||||||
|
<div className="company-metrics">
|
||||||
|
<div><small>Actas emitidas</small><strong>{metrics.acts}</strong></div>
|
||||||
|
<div><small>Informes</small><strong>{metrics.reports}</strong></div>
|
||||||
|
<div><small>Inspecciones activas</small><strong>{metrics.activeInspections}</strong></div>
|
||||||
|
</div>
|
||||||
|
{(canReadActs || canReadReports) && <div className="company-card-actions"><button type="button" className="button primary" onClick={() => setTab('issued')}>Ver actas e informes <Icon name="chevron" /></button></div>}
|
||||||
|
</article>
|
||||||
|
</>}
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{tab === 'issued' && <div className="company-stack">
|
||||||
|
<article className="panel company-card">
|
||||||
|
<div className="company-card-heading company-doc-heading"><div><span className="eyebrow">DOCUMENTACIÓN EMITIDA</span><h2>Actas e informes</h2><p>Historial documental de esta empresa. Sólo se muestran Actas ya emitidas y sus Informes asociados.</p></div><div className="company-doc-counts"><span>{acts.length} actas</span><span>{reports.length} informes</span></div></div>
|
||||||
|
<label className="company-document-search"><Icon name="search" /><input value={documentSearch} onChange={(event) => setDocumentSearch(event.target.value)} placeholder="Buscar por acta, informe, inspección, área o GEDO" /></label>
|
||||||
|
{documentsError && <Alert>{documentsError}</Alert>}
|
||||||
|
{documentsLoading ? <LoadingBlock label="Cargando documentación emitida…" /> : filteredActs.length === 0 ? <EmptyState title="Sin documentación emitida" text="Todavía no hay Actas selladas para esta empresa." /> : <div className="table-scroll company-doc-table"><table><thead><tr><th>Fecha</th><th>Área</th><th>Acta</th><th>Inspección</th><th>Informe</th><th>Oficialización</th><th /></tr></thead><tbody>{filteredActs.map((act) => {
|
||||||
|
const report = reportByAct.get(act.id);
|
||||||
|
return <tr key={act.id}>
|
||||||
|
<td>{formatDate(act.occurredAt)}</td>
|
||||||
|
<td><strong className="table-primary">{areaLabel(act.areas)}</strong></td>
|
||||||
|
<td><Link className="text-link" to={`/inspecciones/actas/${act.id}`}>{act.code}</Link></td>
|
||||||
|
<td><Link className="text-link" to={`/inspecciones/${act.visitId}`}>{act.visit.code}</Link></td>
|
||||||
|
<td>{report ? <Link className="text-link" to={`/informes/${report.id}`}>{report.code}</Link> : <span className="status-badge pending">Pendiente de INF</span>}</td>
|
||||||
|
<td>{report ? <span className={`status-badge ${reportStatusClass(report)}`}>{reportStatusLabel(report)}</span> : <span className="muted">—</span>}</td>
|
||||||
|
<td className="action-cell"><Link className="icon-button" to={`/inspecciones/actas/${act.id}`} aria-label={`Abrir ${act.code}`}><Icon name="chevron" /></Link></td>
|
||||||
|
</tr>;
|
||||||
|
})}</tbody></table></div>}
|
||||||
|
</article>
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{tab === 'documents' && <div className="company-stack">
|
||||||
|
{loadingContext ? <LoadingBlock label="Cargando documentación…" /> : <>
|
||||||
|
{canReadRegistry && <article className="panel company-card">
|
||||||
|
<div className="company-card-heading"><div><span className="eyebrow">RESPALDO</span><h2>Documentos de la empresa</h2><p>Documentos e identificadores que respaldan los datos institucionales.</p></div><Link className="button secondary" to={`/inventarios/${asset.id}?advanced=1&tab=registry`}>Administrar</Link></div>
|
||||||
|
{registry?.sourceDocuments.length ? <div className="company-document-list">{registry.sourceDocuments.map((document) => <div key={document.linkId}><div><strong>{document.title}</strong><small>{document.documentNumber || document.documentType}{document.issuer ? ` · ${document.issuer}` : ''}</small></div><span className="tag">{document.relationType}</span></div>)}</div> : <div className="inline-empty">Todavía no hay documentos respaldatorios vinculados.</div>}
|
||||||
|
{registry?.externalIdentifiers.length ? <details className="company-more"><summary>Ver identificadores externos ({registry.externalIdentifiers.length})</summary><div className="company-identifier-list">{registry.externalIdentifiers.map((item) => <div key={item.id}><strong>{item.namespace}</strong><span>{item.value}</span><small>{item.validUntil ? 'Histórico' : 'Vigente'}</small></div>)}</div></details> : null}
|
||||||
|
</article>}
|
||||||
|
{canReadMedia && <AssetMediaPanel assetId={asset.id} assetName={asset.name} canManage={canManageMedia} />}
|
||||||
|
<div className="company-advanced-link"><span>¿Necesitás procedencia, composición UTE u otros datos técnicos?</span><Link to={`/inventarios/${asset.id}?advanced=1&tab=registry`}>Abrir administración avanzada</Link></div>
|
||||||
|
</>}
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{tab === 'history' && canReadHistory && <AssetHistoryPanel assetId={asset.id} />}
|
||||||
|
</section>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useParams, useSearchParams } from 'react-router';
|
||||||
|
import { Alert, LoadingBlock, errorMessage } from '../components/Feedback';
|
||||||
|
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();
|
||||||
|
const [params] = useSearchParams();
|
||||||
|
const [asset, setAsset] = useState<AssetDetail | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!id) {
|
||||||
|
setError('No se encontró el registro solicitado.');
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
getAsset(id)
|
||||||
|
.then(setAsset)
|
||||||
|
.catch((requestError) => setError(errorMessage(requestError)))
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
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 && !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,105 @@
|
|||||||
|
.company-page { display: grid; gap: 18px; }
|
||||||
|
.company-breadcrumb { margin-bottom: 0; }
|
||||||
|
|
||||||
|
.company-hero {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-end;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 24px;
|
||||||
|
padding: 4px 0 2px;
|
||||||
|
}
|
||||||
|
.company-hero h1 { margin: 6px 0 5px; font-size: clamp(31px, 3.5vw, 44px); line-height: 1.02; letter-spacing: -.045em; }
|
||||||
|
.company-hero p { margin: 0; color: var(--muted); font-size: 13px; }
|
||||||
|
.company-hero-actions { display: flex; align-items: center; gap: 12px; }
|
||||||
|
|
||||||
|
.company-tabs {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
overflow-x: auto;
|
||||||
|
padding: 0 0 1px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.company-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;
|
||||||
|
}
|
||||||
|
.company-tabs button:hover { color: var(--ink); }
|
||||||
|
.company-tabs button.active { color: var(--blue); }
|
||||||
|
.company-tabs button.active::after { content: ''; position: absolute; left: 10px; right: 10px; bottom: -1px; height: 2px; border-radius: 2px; background: var(--blue); }
|
||||||
|
|
||||||
|
.company-stack { display: grid; gap: 15px; }
|
||||||
|
.company-card { padding: 23px; }
|
||||||
|
.company-card-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; margin-bottom: 18px; }
|
||||||
|
.company-card-heading h2 { margin: 4px 0 4px; }
|
||||||
|
.company-card-heading p { max-width: 680px; margin: 0; color: var(--muted); font-size: 12px; line-height: 1.5; }
|
||||||
|
.company-card-actions { display: flex; justify-content: flex-end; margin-top: 17px; }
|
||||||
|
|
||||||
|
.company-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); }
|
||||||
|
.company-data-grid > div { min-height: 78px; padding: 15px 16px; background: #fff; }
|
||||||
|
.company-data-grid small, .company-data-grid strong { display: block; }
|
||||||
|
.company-data-grid small { margin-bottom: 7px; color: var(--muted); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; }
|
||||||
|
.company-data-grid strong { font-size: 13px; font-weight: 750; }
|
||||||
|
.company-edit-form { display: grid; gap: 16px; }
|
||||||
|
|
||||||
|
.company-area-list { display: grid; gap: 8px; }
|
||||||
|
.company-area-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-height: 62px; padding: 12px 14px; border: 1px solid #e3e7ee; border-radius: 10px; background: #fafbfc; }
|
||||||
|
.company-area-row > a { min-width: 0; text-decoration: none; }
|
||||||
|
.company-area-row > a:hover strong { color: var(--blue); }
|
||||||
|
.company-area-row strong, .company-area-row small { display: block; }
|
||||||
|
.company-area-row strong { font-size: 13px; }
|
||||||
|
.company-area-row small { margin-top: 4px; color: var(--muted); font-size: 10px; }
|
||||||
|
.company-area-row > div { display: flex; align-items: center; gap: 7px; }
|
||||||
|
.company-inline-action { margin-top: 13px; border: 1px dashed #cfd7e5; border-radius: 10px; background: #fbfcfe; }
|
||||||
|
.company-inline-action summary { display: flex; align-items: center; gap: 7px; padding: 13px 14px; cursor: pointer; color: var(--blue); font-size: 12px; font-weight: 750; list-style: none; }
|
||||||
|
.company-inline-action summary::-webkit-details-marker { display: none; }
|
||||||
|
.company-inline-action form { display: grid; gap: 13px; padding: 0 14px 14px; }
|
||||||
|
|
||||||
|
.company-metrics { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
|
||||||
|
.company-metrics > div { display: grid; gap: 6px; padding: 16px; border: 1px solid #e2e7ef; border-radius: 11px; background: #f8faff; }
|
||||||
|
.company-metrics small { color: var(--muted); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; }
|
||||||
|
.company-metrics strong { color: #173b7a; font-size: 25px; line-height: 1; letter-spacing: -.04em; }
|
||||||
|
|
||||||
|
.company-doc-heading { align-items: center; }
|
||||||
|
.company-doc-counts { display: flex; gap: 7px; }
|
||||||
|
.company-doc-counts span { padding: 6px 9px; border-radius: 999px; color: #536078; background: #f0f3f8; font-size: 10px; font-weight: 750; }
|
||||||
|
.company-document-search { display: flex; align-items: center; gap: 9px; width: 100%; margin-bottom: 17px; padding: 0 12px; border: 1px solid #d8dee8; border-radius: 10px; background: white; }
|
||||||
|
.company-document-search .icon { color: #818ba0; }
|
||||||
|
.company-document-search input { width: 100%; min-height: 43px; border: 0; outline: 0; background: transparent; font-size: 12px; }
|
||||||
|
.company-doc-table table { min-width: 870px; }
|
||||||
|
.company-doc-table td { vertical-align: middle; }
|
||||||
|
|
||||||
|
.company-document-list { display: grid; gap: 8px; }
|
||||||
|
.company-document-list > div { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 13px 14px; border: 1px solid #e2e6ed; border-radius: 10px; background: #fbfcfd; }
|
||||||
|
.company-document-list strong, .company-document-list small { display: block; }
|
||||||
|
.company-document-list strong { font-size: 12px; }
|
||||||
|
.company-document-list small { margin-top: 4px; color: var(--muted); font-size: 10px; }
|
||||||
|
.company-more { margin-top: 13px; }
|
||||||
|
.company-more summary { cursor: pointer; color: #59657b; font-size: 11px; font-weight: 750; }
|
||||||
|
.company-identifier-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 8px; margin-top: 10px; }
|
||||||
|
.company-identifier-list > div { display: grid; gap: 3px; padding: 11px 12px; border: 1px solid var(--line); border-radius: 9px; background: #fafbfc; }
|
||||||
|
.company-identifier-list strong { font-size: 10px; color: var(--blue); }
|
||||||
|
.company-identifier-list span { font-size: 12px; font-weight: 750; }
|
||||||
|
.company-identifier-list small { color: var(--muted); font-size: 9px; }
|
||||||
|
.company-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; }
|
||||||
|
.company-advanced-link a { color: var(--blue); font-weight: 750; text-decoration: none; }
|
||||||
|
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.company-hero { align-items: flex-start; flex-direction: column; }
|
||||||
|
.company-hero-actions { width: 100%; justify-content: space-between; }
|
||||||
|
.company-card { padding: 18px; }
|
||||||
|
.company-card-heading { align-items: flex-start; flex-direction: column; }
|
||||||
|
.company-data-grid, .company-metrics { grid-template-columns: 1fr; }
|
||||||
|
.company-area-row { align-items: flex-start; flex-direction: column; }
|
||||||
|
.company-area-row > div { width: 100%; justify-content: space-between; }
|
||||||
|
.company-doc-counts { width: 100%; }
|
||||||
|
.company-advanced-link { align-items: flex-start; flex-direction: column; }
|
||||||
|
}
|
||||||
@@ -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