Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d17b153808 | ||
|
|
2cfabe0cf0 | ||
|
|
699becc13e |
+63
-64
@@ -80,9 +80,12 @@ jobs:
|
||||
|
||||
docker compose --env-file .env.example up -d db
|
||||
|
||||
# Historical production reset is a one-shot migration that expects the
|
||||
# production admin. Prove the clean chain reaches that exact guard,
|
||||
# mark only that historical reset as applied, then continue the chain.
|
||||
# The historical production reset is a one-shot operational migration,
|
||||
# not a bootstrap migration: it requires production data/configuration
|
||||
# that cannot exist at its timestamp in a database rebuilt from zero.
|
||||
# Prove the clean chain reaches that exact guard, then mark only that
|
||||
# one-shot migration as already applied and continue the reproducible
|
||||
# schema chain. The historical migration itself remains untouched.
|
||||
bootstrap_log="$(mktemp)"
|
||||
set +e
|
||||
docker compose --env-file .env.example --profile tools run --build --rm migrate 2>&1 | tee "$bootstrap_log"
|
||||
@@ -101,14 +104,17 @@ jobs:
|
||||
docker compose --env-file .env.example exec -T db \
|
||||
psql -v ON_ERROR_STOP=1 -U dhv2_owner -d dhv2 <<'SQL'
|
||||
DO $$
|
||||
DECLARE reset_rows integer;
|
||||
DECLARE
|
||||
reset_rows integer;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO reset_rows
|
||||
FROM typeorm_migrations
|
||||
WHERE name = 'ResetProductionOperationalData1788652800000';
|
||||
|
||||
IF reset_rows <> 0 THEN
|
||||
RAISE EXCEPTION 'CI one-shot bypass expected reset migration to be pending, found % rows', reset_rows;
|
||||
END IF;
|
||||
|
||||
INSERT INTO typeorm_migrations ("timestamp", name)
|
||||
VALUES (1788652800000, 'ResetProductionOperationalData1788652800000');
|
||||
END $$;
|
||||
@@ -116,23 +122,17 @@ jobs:
|
||||
|
||||
docker compose --env-file .env.example --profile tools run --rm migrate
|
||||
|
||||
# F5.1 intentionally ends with zero operational/domain instances. The
|
||||
# technical family and finding masters remain, but territory preload,
|
||||
# imports, applicability links and old audits are deliberately gone.
|
||||
docker compose --env-file .env.example exec -T db \
|
||||
psql -v ON_ERROR_STOP=1 -U dhv2_owner -d dhv2 <<'SQL'
|
||||
DO $$
|
||||
DECLARE
|
||||
f5_migrations integer;
|
||||
domain_assets integer;
|
||||
audits integer;
|
||||
applicability integer;
|
||||
territory_sources integer;
|
||||
real_inventory integer;
|
||||
source_areas integer;
|
||||
source_yacimientos integer;
|
||||
source_installations integer;
|
||||
source_subinstallations integer;
|
||||
source_findings integer;
|
||||
department_types integer;
|
||||
area_department_rules integer;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO f5_migrations
|
||||
FROM typeorm_migrations
|
||||
@@ -141,33 +141,28 @@ jobs:
|
||||
'F5CanonicalInventoryHierarchy1790087150000',
|
||||
'F5AuthoritativeTerritory1790087200000',
|
||||
'F5OperationalContextCompatibility1790087250000',
|
||||
'F5AuthoritativeInventoryCatalog1790087300000',
|
||||
'F51CleanManualInventory1790087400000'
|
||||
'F5AuthoritativeInventoryCatalog1790087300000'
|
||||
);
|
||||
IF f5_migrations <> 6 THEN
|
||||
RAISE EXCEPTION 'Expected 6 F5/F5.1 migrations, got %', f5_migrations;
|
||||
IF f5_migrations <> 5 THEN
|
||||
RAISE EXCEPTION 'Expected 5 F5 migrations, got %', f5_migrations;
|
||||
END IF;
|
||||
|
||||
SELECT COUNT(*) INTO domain_assets FROM assets;
|
||||
IF domain_assets <> 0 THEN
|
||||
RAISE EXCEPTION 'F5.1 clean start must contain 0 Assets, got %', domain_assets;
|
||||
SELECT COUNT(*) INTO real_inventory
|
||||
FROM assets WHERE is_inventory_instance=true AND information_status<>'INACTIVE';
|
||||
IF real_inventory <> 0 THEN
|
||||
RAISE EXCEPTION 'Fresh F5 database must start with 0 real Inventory instances, got %', real_inventory;
|
||||
END IF;
|
||||
|
||||
SELECT COUNT(*) INTO audits FROM audit_events;
|
||||
IF audits <> 0 THEN
|
||||
RAISE EXCEPTION 'F5.1 clean start must contain 0 audit events, got %', audits;
|
||||
END IF;
|
||||
|
||||
SELECT COUNT(*) INTO applicability FROM finding_catalog_item_inventory_families;
|
||||
IF applicability <> 0 THEN
|
||||
RAISE EXCEPTION 'F5.1 clean start must contain 0 finding applicability links, got %', applicability;
|
||||
END IF;
|
||||
|
||||
SELECT COUNT(*) INTO territory_sources
|
||||
FROM source_documents
|
||||
WHERE document_number='DH-F5-TERRITORY';
|
||||
IF territory_sources <> 0 THEN
|
||||
RAISE EXCEPTION 'F5.1 must remove the old territory source preload, got % rows', territory_sources;
|
||||
SELECT COUNT(DISTINCT asset.id) FILTER (WHERE type.operational_role='AREA'),
|
||||
COUNT(DISTINCT asset.id) FILTER (WHERE lower(type.code)='yacimiento')
|
||||
INTO source_areas,source_yacimientos
|
||||
FROM source_documents document
|
||||
JOIN asset_source_documents link ON link.document_id=document.id
|
||||
JOIN assets asset ON asset.id=link.asset_id
|
||||
JOIN asset_types type ON type.id=asset.asset_type_id
|
||||
WHERE document.document_number='DH-F5-TERRITORY';
|
||||
IF source_areas <> 64 OR source_yacimientos <> 230 THEN
|
||||
RAISE EXCEPTION 'F5 territory preload mismatch: areas %, yacimientos %', source_areas,source_yacimientos;
|
||||
END IF;
|
||||
|
||||
SELECT COUNT(*) FILTER (WHERE level='INSTALLATION'),
|
||||
@@ -176,7 +171,7 @@ jobs:
|
||||
FROM inventory_families
|
||||
WHERE is_active=true AND source_reference LIKE 'F5:final_modelov2.xlsx%';
|
||||
IF source_installations <> 14 OR source_subinstallations <> 109 THEN
|
||||
RAISE EXCEPTION 'F5.1 must preserve technical family masters: installations %, subinstallations %', source_installations,source_subinstallations;
|
||||
RAISE EXCEPTION 'F5 family preload mismatch: installations %, subinstallations %', source_installations,source_subinstallations;
|
||||
END IF;
|
||||
|
||||
SELECT COUNT(*) INTO source_findings
|
||||
@@ -184,38 +179,42 @@ jobs:
|
||||
JOIN finding_categories category ON category.id=item.category_id
|
||||
WHERE lower(category.code)='f5model' AND item.is_active=true;
|
||||
IF source_findings <> 177 THEN
|
||||
RAISE EXCEPTION 'F5.1 must preserve finding master catalog, got %', source_findings;
|
||||
END IF;
|
||||
|
||||
SELECT COUNT(*) INTO department_types
|
||||
FROM asset_types
|
||||
WHERE lower(code)='departamento' AND can_be_root=true AND is_active=true;
|
||||
IF department_types <> 1 THEN
|
||||
RAISE EXCEPTION 'Expected one active root Departamento type, got %', department_types;
|
||||
END IF;
|
||||
|
||||
SELECT COUNT(*) INTO area_department_rules
|
||||
FROM asset_type_parent_rules rule
|
||||
JOIN asset_types child ON child.id=rule.child_type_id
|
||||
JOIN asset_types parent ON parent.id=rule.parent_type_id
|
||||
WHERE lower(child.code)='area' AND lower(parent.code)='departamento';
|
||||
IF area_department_rules <> 1 THEN
|
||||
RAISE EXCEPTION 'Expected Area → Departamento canonical rule, got %', area_department_rules;
|
||||
RAISE EXCEPTION 'F5 finding preload mismatch: %', source_findings;
|
||||
END IF;
|
||||
END $$;
|
||||
SQL
|
||||
|
||||
# F5.1 is intentionally one-way: production rollback is the PRE database
|
||||
# backup, not migration:revert. Prove instead that the completed chain is
|
||||
# idempotent and has no pending migration on a second run.
|
||||
rerun_log="$(mktemp)"
|
||||
docker compose --env-file .env.example --profile tools run --rm migrate 2>&1 | tee "$rerun_log"
|
||||
grep -Eq 'No pending migrations|Applied migrations: 0' "$rerun_log" || {
|
||||
echo "ERROR: F5.1 migration chain is not idempotent." >&2
|
||||
cat "$rerun_log" >&2
|
||||
exit 1
|
||||
}
|
||||
rm -f "$rerun_log"
|
||||
# Prove the five F5 migrations are actually reversible on a clean state.
|
||||
for _ in 1 2 3 4 5; do
|
||||
docker compose --env-file .env.example --profile tools run --rm migrate npm run migration:revert
|
||||
done
|
||||
|
||||
docker compose --env-file .env.example exec -T db \
|
||||
psql -v ON_ERROR_STOP=1 -U dhv2_owner -d dhv2 <<'SQL'
|
||||
DO $$
|
||||
DECLARE f5_migrations integer; instance_column integer;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO f5_migrations
|
||||
FROM typeorm_migrations
|
||||
WHERE name LIKE 'F5%1790087%';
|
||||
IF f5_migrations <> 0 THEN
|
||||
RAISE EXCEPTION 'F5 rollback left % migration rows behind', f5_migrations;
|
||||
END IF;
|
||||
SELECT COUNT(*) INTO instance_column
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema='public' AND table_name='assets' AND column_name='is_inventory_instance';
|
||||
IF instance_column <> 0 THEN
|
||||
RAISE EXCEPTION 'F5 rollback left is_inventory_instance behind';
|
||||
END IF;
|
||||
END $$;
|
||||
SQL
|
||||
|
||||
# Reapply them once more. Each F5 migration performs its own source/cardinality checks.
|
||||
docker compose --env-file .env.example --profile tools run --rm migrate
|
||||
docker compose --env-file .env.example exec -T db \
|
||||
psql -v ON_ERROR_STOP=1 -U dhv2_owner -d dhv2 -Atc \
|
||||
"SELECT CASE WHEN COUNT(*)=5 THEN 'F5_REAPPLY_OK' ELSE 'F5_REAPPLY_FAILED:'||COUNT(*) END FROM typeorm_migrations WHERE name IN ('F5InventoryPhysicalInstance1790087100000','F5CanonicalInventoryHierarchy1790087150000','F5AuthoritativeTerritory1790087200000','F5OperationalContextCompatibility1790087250000','F5AuthoritativeInventoryCatalog1790087300000');" \
|
||||
| grep -Fx 'F5_REAPPLY_OK'
|
||||
- name: VPS-equivalent isolated API preflight
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dhv2-api",
|
||||
"version": "0.27.0-1",
|
||||
"version": "0.26.0-1",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
|
||||
export const INVENTORY_STRUCTURE_KINDS = [
|
||||
'EMPRESA',
|
||||
'DEPARTAMENTO',
|
||||
'AREA',
|
||||
'YACIMIENTO',
|
||||
'INSTALACION',
|
||||
|
||||
@@ -13,16 +13,6 @@ export class InventoryBrowserController {
|
||||
return this.inventoryBrowser.items(query);
|
||||
}
|
||||
|
||||
@Get('departments')
|
||||
departments(@Query() query: InventoryBrowserQueryDto) {
|
||||
return this.inventoryBrowser.departments(query);
|
||||
}
|
||||
|
||||
@Get('companies')
|
||||
companies(@Query() query: InventoryBrowserQueryDto) {
|
||||
return this.inventoryBrowser.companies(query);
|
||||
}
|
||||
|
||||
@Get('areas')
|
||||
areas(@Query() query: InventoryBrowserQueryDto) {
|
||||
return this.inventoryBrowser.areas(query);
|
||||
|
||||
@@ -16,9 +16,9 @@ export class InventoryBrowserService {
|
||||
async items(query: InventoryBrowserQueryDto) {
|
||||
const params: unknown[] = [];
|
||||
const conditions = [
|
||||
'asset.is_inventory_instance=true',
|
||||
"asset.information_status<>'INACTIVE'",
|
||||
'type.is_active=true',
|
||||
"(type.operational_role='COMPANY' OR lower(type.code) IN ('departamento','area','yacimiento','instalacion','subinstalacion'))",
|
||||
];
|
||||
const add = (value: unknown): string => {
|
||||
params.push(value);
|
||||
@@ -36,21 +36,15 @@ export class InventoryBrowserService {
|
||||
if (query.needsValidation === false) conditions.push("asset.information_status='VALIDATED'");
|
||||
if (query.hasGeometry === true) conditions.push('EXISTS (SELECT 1 FROM asset_geometries geometry_filter WHERE geometry_filter.asset_id=asset.id)');
|
||||
if (query.hasGeometry === false) conditions.push('NOT EXISTS (SELECT 1 FROM asset_geometries geometry_filter WHERE geometry_filter.asset_id=asset.id)');
|
||||
if (query.operationalAreaId) {
|
||||
const area = add(query.operationalAreaId);
|
||||
conditions.push(`(asset.id=${area}::uuid OR asset.operational_area_id=${area}::uuid)`);
|
||||
}
|
||||
if (query.operationalAreaId) conditions.push(`asset.operational_area_id=${add(query.operationalAreaId)}::uuid`);
|
||||
if (query.operatorCompanyId) {
|
||||
const company = add(query.operatorCompanyId);
|
||||
conditions.push(`(
|
||||
asset.id=${company}::uuid
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM area_company_relations relation
|
||||
WHERE (relation.area_id=asset.operational_area_id OR relation.area_id=asset.id)
|
||||
AND relation.company_id=${company}::uuid
|
||||
AND relation.relation_role='OPERATOR'
|
||||
AND relation.valid_until IS NULL
|
||||
)
|
||||
conditions.push(`EXISTS (
|
||||
SELECT 1 FROM area_company_relations relation
|
||||
WHERE relation.area_id=asset.operational_area_id
|
||||
AND relation.company_id=${company}::uuid
|
||||
AND relation.relation_role='OPERATOR'
|
||||
AND relation.valid_until IS NULL
|
||||
)`);
|
||||
}
|
||||
|
||||
@@ -82,8 +76,7 @@ export class InventoryBrowserService {
|
||||
SELECT JSONB_BUILD_OBJECT('id',company.id,'code',company.code,'name',company.name)
|
||||
FROM area_company_relations relation
|
||||
JOIN assets company ON company.id=relation.company_id
|
||||
WHERE relation.area_id=COALESCE(asset.operational_area_id,
|
||||
CASE WHEN type.operational_role='AREA' THEN asset.id ELSE NULL END)
|
||||
WHERE relation.area_id=asset.operational_area_id
|
||||
AND relation.relation_role='OPERATOR'
|
||||
AND relation.valid_until IS NULL
|
||||
ORDER BY relation.valid_from DESC,relation.created_at DESC
|
||||
@@ -91,8 +84,7 @@ export class InventoryBrowserService {
|
||||
) AS "operatorCompany",
|
||||
asset.information_status AS "informationStatus",
|
||||
asset.operational_status AS "operationalStatus",
|
||||
(SELECT COUNT(*)::integer FROM assets child
|
||||
WHERE child.parent_id=asset.id AND child.information_status<>'INACTIVE') AS "childrenCount",
|
||||
0::integer AS "childrenCount",
|
||||
EXISTS (SELECT 1 FROM asset_geometries geometry WHERE geometry.asset_id=asset.id) AS "hasGeometry",
|
||||
CASE WHEN geometry_type.type IS NULL THEN NULL ELSE geometry_type.type END AS "geometryType",
|
||||
(SELECT COUNT(*)::integer FROM asset_media media WHERE media.asset_id=asset.id AND media.deleted_at IS NULL) AS "mediaCount",
|
||||
@@ -112,14 +104,7 @@ export class InventoryBrowserService {
|
||||
LIMIT 1
|
||||
) geometry_type ON true
|
||||
WHERE ${where}
|
||||
ORDER BY CASE
|
||||
WHEN lower(type.code)='departamento' THEN 0
|
||||
WHEN type.operational_role='COMPANY' THEN 1
|
||||
WHEN lower(type.code)='area' THEN 2
|
||||
WHEN lower(type.code)='yacimiento' THEN 3
|
||||
WHEN lower(type.code)='instalacion' THEN 4
|
||||
WHEN lower(type.code)='subinstalacion' THEN 5 ELSE 9 END,
|
||||
asset.name,asset.code
|
||||
ORDER BY asset.name,asset.code
|
||||
LIMIT ${limit} OFFSET ${offsetParam}
|
||||
`,params);
|
||||
|
||||
@@ -134,30 +119,28 @@ export class InventoryBrowserService {
|
||||
};
|
||||
}
|
||||
|
||||
async departments(query: InventoryBrowserQueryDto) {
|
||||
async areas(query: InventoryBrowserQueryDto) {
|
||||
const params: unknown[] = [];
|
||||
const conditions = [
|
||||
"lower(type.code)='departamento'",
|
||||
"department.information_status<>'INACTIVE'",
|
||||
"type.operational_role='AREA'",
|
||||
"area.information_status<>'INACTIVE'",
|
||||
'type.is_active=true',
|
||||
];
|
||||
const add = (value: unknown): string => {
|
||||
params.push(value);
|
||||
return `$${params.length}`;
|
||||
};
|
||||
|
||||
if (query.search?.trim()) {
|
||||
const p = add(`%${query.search.trim()}%`);
|
||||
conditions.push(`(department.code ILIKE ${p} OR department.name ILIKE ${p} OR COALESCE(department.common_name,'') ILIKE ${p})`);
|
||||
conditions.push(`(area.code ILIKE ${p} OR area.name ILIKE ${p} OR COALESCE(area.common_name,'') ILIKE ${p})`);
|
||||
}
|
||||
if (query.operationalAreaId) conditions.push(`area.id=${add(query.operationalAreaId)}::uuid`);
|
||||
if (query.operatorCompanyId) {
|
||||
const p = add(query.operatorCompanyId);
|
||||
conditions.push(`EXISTS (
|
||||
SELECT 1
|
||||
FROM assets area
|
||||
JOIN asset_types atype ON atype.id=area.asset_type_id
|
||||
JOIN area_company_relations relation ON relation.area_id=area.id
|
||||
WHERE area.parent_id=department.id
|
||||
AND lower(atype.code)='area'
|
||||
SELECT 1 FROM area_company_relations relation
|
||||
WHERE relation.area_id=area.id
|
||||
AND relation.company_id=${p}::uuid
|
||||
AND relation.relation_role='OPERATOR'
|
||||
AND relation.valid_until IS NULL
|
||||
@@ -166,86 +149,41 @@ export class InventoryBrowserService {
|
||||
|
||||
const data = await this.dataSource.query(`
|
||||
SELECT
|
||||
department.id,department.code,department.name,department.common_name AS "commonName",
|
||||
area.id,area.code,area.name,area.common_name AS "commonName",
|
||||
JSONB_BUILD_OBJECT('id',type.id,'code',type.code,'name',type.name) AS type,
|
||||
department.information_status AS "informationStatus",
|
||||
department.operational_status AS "operationalStatus",
|
||||
(SELECT COUNT(*)::integer FROM assets area
|
||||
JOIN asset_types atype ON atype.id=area.asset_type_id
|
||||
WHERE area.parent_id=department.id AND lower(atype.code)='area'
|
||||
AND area.information_status<>'INACTIVE') AS "areaCount",
|
||||
(SELECT COUNT(*)::integer FROM assets child
|
||||
WHERE child.parent_id=department.id AND child.information_status<>'INACTIVE') AS "childrenCount"
|
||||
FROM assets department
|
||||
JOIN asset_types type ON type.id=department.asset_type_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
ORDER BY department.name,department.code
|
||||
`, params);
|
||||
return { data, meta: { count: data.length } };
|
||||
}
|
||||
|
||||
async companies(query: InventoryBrowserQueryDto) {
|
||||
const params: unknown[] = [];
|
||||
const conditions = [
|
||||
"type.operational_role='COMPANY'",
|
||||
"company.information_status<>'INACTIVE'",
|
||||
'type.is_active=true',
|
||||
];
|
||||
if (query.search?.trim()) {
|
||||
params.push(`%${query.search.trim()}%`);
|
||||
conditions.push(`(company.code ILIKE $1 OR company.name ILIKE $1 OR COALESCE(company.common_name,'') ILIKE $1)`);
|
||||
}
|
||||
const data = await this.dataSource.query(`
|
||||
SELECT company.id,company.code,company.name,company.common_name AS "commonName",
|
||||
JSONB_BUILD_OBJECT('id',type.id,'code',type.code,'name',type.name) AS type,
|
||||
company.information_status AS "informationStatus",
|
||||
(SELECT COUNT(*)::integer FROM area_company_relations relation
|
||||
WHERE relation.company_id=company.id AND relation.relation_role='OPERATOR'
|
||||
AND relation.valid_until IS NULL) AS "areaCount"
|
||||
FROM assets company
|
||||
JOIN asset_types type ON type.id=company.asset_type_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
ORDER BY company.name,company.code
|
||||
`,params);
|
||||
return { data,meta:{count:data.length} };
|
||||
}
|
||||
|
||||
async areas(query: InventoryBrowserQueryDto) {
|
||||
const params: unknown[] = [];
|
||||
const conditions = [
|
||||
"type.operational_role='AREA'",
|
||||
"area.information_status<>'INACTIVE'",
|
||||
'type.is_active=true',
|
||||
];
|
||||
const add = (value: unknown): string => { params.push(value); return `$${params.length}`; };
|
||||
if (query.search?.trim()) {
|
||||
const p = add(`%${query.search.trim()}%`);
|
||||
conditions.push(`(area.code ILIKE ${p} OR area.name ILIKE ${p} OR COALESCE(area.common_name,'') ILIKE ${p})`);
|
||||
}
|
||||
if (query.operationalAreaId) conditions.push(`area.id=${add(query.operationalAreaId)}::uuid`);
|
||||
if (query.operatorCompanyId) {
|
||||
const p = add(query.operatorCompanyId);
|
||||
conditions.push(`EXISTS (SELECT 1 FROM area_company_relations relation
|
||||
WHERE relation.area_id=area.id AND relation.company_id=${p}::uuid
|
||||
AND relation.relation_role='OPERATOR' AND relation.valid_until IS NULL)`);
|
||||
}
|
||||
const data = await this.dataSource.query(`
|
||||
SELECT area.id,area.code,area.name,area.common_name AS "commonName",
|
||||
JSONB_BUILD_OBJECT('id',type.id,'code',type.code,'name',type.name) AS type,
|
||||
area.information_status AS "informationStatus",area.operational_status AS "operationalStatus",
|
||||
(SELECT JSONB_BUILD_OBJECT('id',company.id,'code',company.code,'name',company.name)
|
||||
FROM area_company_relations relation JOIN assets company ON company.id=relation.company_id
|
||||
WHERE relation.area_id=area.id AND relation.relation_role='OPERATOR' AND relation.valid_until IS NULL
|
||||
ORDER BY relation.valid_from DESC,relation.created_at DESC LIMIT 1) AS "currentOperator",
|
||||
(SELECT COUNT(*)::integer FROM assets yacimiento JOIN asset_types ytype ON ytype.id=yacimiento.asset_type_id
|
||||
WHERE yacimiento.parent_id=area.id AND lower(ytype.code)='yacimiento'
|
||||
AND yacimiento.information_status<>'INACTIVE') AS "yacimientoCount",
|
||||
(SELECT COUNT(*)::integer FROM assets inventory
|
||||
WHERE inventory.information_status<>'INACTIVE' AND inventory.operational_area_id=area.id) AS "inventoryCount"
|
||||
FROM assets area JOIN asset_types type ON type.id=area.asset_type_id
|
||||
area.information_status AS "informationStatus",
|
||||
area.operational_status AS "operationalStatus",
|
||||
(
|
||||
SELECT JSONB_BUILD_OBJECT('id',company.id,'code',company.code,'name',company.name)
|
||||
FROM area_company_relations relation
|
||||
JOIN assets company ON company.id=relation.company_id
|
||||
WHERE relation.area_id=area.id
|
||||
AND relation.relation_role='OPERATOR'
|
||||
AND relation.valid_until IS NULL
|
||||
ORDER BY relation.valid_from DESC,relation.created_at DESC
|
||||
LIMIT 1
|
||||
) AS "currentOperator",
|
||||
(
|
||||
SELECT COUNT(*)::integer
|
||||
FROM assets yacimiento
|
||||
JOIN asset_types ytype ON ytype.id=yacimiento.asset_type_id
|
||||
WHERE yacimiento.parent_id=area.id
|
||||
AND lower(ytype.code)='yacimiento'
|
||||
AND yacimiento.information_status<>'INACTIVE'
|
||||
) AS "yacimientoCount",
|
||||
(
|
||||
SELECT COUNT(*)::integer
|
||||
FROM assets inventory
|
||||
WHERE inventory.is_inventory_instance=true
|
||||
AND inventory.information_status<>'INACTIVE'
|
||||
AND inventory.operational_area_id=area.id
|
||||
) AS "inventoryCount"
|
||||
FROM assets area
|
||||
JOIN asset_types type ON type.id=area.asset_type_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
ORDER BY area.name,area.code
|
||||
`, params);
|
||||
|
||||
return { data, meta: { count: data.length } };
|
||||
}
|
||||
|
||||
@@ -261,6 +199,9 @@ export class InventoryBrowserService {
|
||||
"asset.information_status<>'INACTIVE'",
|
||||
'type.is_active=true',
|
||||
];
|
||||
if (allowedChildType === 'instalacion' || allowedChildType === 'subinstalacion') {
|
||||
conditions.push('asset.is_inventory_instance=true');
|
||||
}
|
||||
if (query.search?.trim()) {
|
||||
params.push(`%${query.search.trim()}%`);
|
||||
const p = `$${params.length}`;
|
||||
@@ -282,12 +223,20 @@ export class InventoryBrowserService {
|
||||
CASE WHEN family.id IS NULL THEN NULL ELSE JSONB_BUILD_OBJECT(
|
||||
'id',family.id,'code',family.code,'name',family.name,'level',family.level
|
||||
) END AS "inventoryFamily",
|
||||
(SELECT COUNT(*)::integer FROM assets child
|
||||
WHERE child.parent_id=asset.id AND child.information_status<>'INACTIVE') AS "childrenCount",
|
||||
CASE WHEN family.id IS NULL THEN 0 ELSE (
|
||||
SELECT COUNT(*)::integer FROM finding_catalog_item_inventory_families mapping
|
||||
WHERE mapping.inventory_family_id=family.id
|
||||
) END AS "findingCount",
|
||||
(
|
||||
SELECT COUNT(*)::integer
|
||||
FROM assets child
|
||||
WHERE child.parent_id=asset.id
|
||||
AND child.information_status<>'INACTIVE'
|
||||
AND (
|
||||
lower(type.code)='area'
|
||||
OR child.is_inventory_instance=true
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM asset_types child_type
|
||||
WHERE child_type.id=child.asset_type_id AND lower(child_type.code)='yacimiento'
|
||||
)
|
||||
)
|
||||
) AS "childrenCount",
|
||||
EXISTS (SELECT 1 FROM asset_geometries geometry WHERE geometry.asset_id=asset.id) AS "hasGeometry",
|
||||
asset.updated_at AS "updatedAt"
|
||||
FROM assets asset
|
||||
@@ -314,10 +263,10 @@ export class InventoryBrowserService {
|
||||
if (!parent) {
|
||||
throw new NotFoundException({ code:'INVENTORY_BROWSER_PARENT_NOT_FOUND',message:'El nivel de Inventario no existe' });
|
||||
}
|
||||
if (!['departamento','area','yacimiento','instalacion','subinstalacion'].includes(parent.typeCode.toLowerCase())) {
|
||||
if (!['area','yacimiento','instalacion','subinstalacion'].includes(parent.typeCode.toLowerCase())) {
|
||||
throw new BadRequestException({
|
||||
code:'INVENTORY_BROWSER_PARENT_TYPE_INVALID',
|
||||
message:'La navegación de Inventarios admite Departamento → Área → Yacimiento → Instalación → Subinstalación',
|
||||
message:'La navegación de Inventarios admite Área → Yacimiento → Instalación → Subinstalación',
|
||||
});
|
||||
}
|
||||
return parent;
|
||||
@@ -325,7 +274,6 @@ export class InventoryBrowserService {
|
||||
|
||||
private allowedChildType(typeCode: string): string | null {
|
||||
switch (typeCode.toLowerCase()) {
|
||||
case 'departamento': return 'area';
|
||||
case 'area': return 'yacimiento';
|
||||
case 'yacimiento': return 'instalacion';
|
||||
case 'instalacion': return 'subinstalacion';
|
||||
|
||||
@@ -38,10 +38,8 @@ type ParentRow = {
|
||||
typeCode: string;
|
||||
inventoryFamilyId: string | null;
|
||||
};
|
||||
type IdRow = { id: string };
|
||||
|
||||
const TYPE_CODE_BY_KIND: Record<Exclude<InventoryStructureKind, 'EMPRESA'>, string> = {
|
||||
DEPARTAMENTO: 'departamento',
|
||||
AREA: 'area',
|
||||
YACIMIENTO: 'yacimiento',
|
||||
INSTALACION: 'instalacion',
|
||||
@@ -49,8 +47,7 @@ const TYPE_CODE_BY_KIND: Record<Exclude<InventoryStructureKind, 'EMPRESA'>, stri
|
||||
};
|
||||
const PARENT_TYPE_BY_KIND: Record<InventoryStructureKind, string | null> = {
|
||||
EMPRESA: null,
|
||||
DEPARTAMENTO: null,
|
||||
AREA: 'departamento',
|
||||
AREA: null,
|
||||
YACIMIENTO: 'area',
|
||||
INSTALACION: 'yacimiento',
|
||||
SUBINSTALACION: 'instalacion',
|
||||
@@ -73,24 +70,22 @@ export class InventoryStructureService {
|
||||
SELECT id,code,name
|
||||
FROM asset_types
|
||||
WHERE (
|
||||
lower(code) IN ('departamento','area','yacimiento','instalacion','subinstalacion')
|
||||
lower(code) IN ('area','yacimiento','instalacion','subinstalacion')
|
||||
OR operational_role='COMPANY'
|
||||
) AND is_active=true
|
||||
ORDER BY CASE
|
||||
WHEN operational_role='COMPANY' THEN 0
|
||||
WHEN lower(code)='departamento' THEN 1
|
||||
WHEN lower(code)='area' THEN 2
|
||||
WHEN lower(code)='yacimiento' THEN 3
|
||||
WHEN lower(code)='instalacion' THEN 4
|
||||
WHEN lower(code)='subinstalacion' THEN 5 ELSE 9 END
|
||||
WHEN lower(code)='area' THEN 1
|
||||
WHEN lower(code)='yacimiento' THEN 2
|
||||
WHEN lower(code)='instalacion' THEN 3
|
||||
WHEN lower(code)='subinstalacion' THEN 4 ELSE 9 END
|
||||
`)) as StructureTypeRow[];
|
||||
const company = types.find((item) => ['empresa','organizacion'].includes(item.code.toLowerCase()));
|
||||
const departamento = types.find((item) => item.code.toLowerCase()==='departamento');
|
||||
const area = types.find((item) => item.code.toLowerCase()==='area');
|
||||
const yacimiento = types.find((item) => item.code.toLowerCase()==='yacimiento');
|
||||
const instalacion = types.find((item) => item.code.toLowerCase()==='instalacion');
|
||||
const subinstalacion = types.find((item) => item.code.toLowerCase()==='subinstalacion');
|
||||
if (!company || !departamento || !area || !yacimiento || !instalacion || !subinstalacion) {
|
||||
if (!company || !area || !yacimiento || !instalacion || !subinstalacion) {
|
||||
throw new ConflictException({
|
||||
code: 'INVENTORY_STRUCTURE_TYPES_INCOMPLETE',
|
||||
message: 'La configuración maestra de Empresa e Inventario todavía no está completa',
|
||||
@@ -114,8 +109,7 @@ export class InventoryStructureService {
|
||||
{ kind: 'EMPRESA', label: 'Empresa', type: company, parentKind: null, requiresFamily: false },
|
||||
],
|
||||
levels: [
|
||||
{ kind: 'DEPARTAMENTO', label: 'Departamento', type: departamento, parentKind: null, requiresFamily: false },
|
||||
{ kind: 'AREA', label: 'Área', type: area, parentKind: 'DEPARTAMENTO', requiresFamily: false },
|
||||
{ kind: 'AREA', label: 'Área', type: area, parentKind: null, requiresFamily: false },
|
||||
{ kind: 'YACIMIENTO', label: 'Yacimiento', type: yacimiento, parentKind: 'AREA', requiresFamily: false },
|
||||
{ kind: 'INSTALACION', label: 'Instalación', type: instalacion, parentKind: 'YACIMIENTO', requiresFamily: true },
|
||||
{ kind: 'SUBINSTALACION', label: 'Subinstalación', type: subinstalacion, parentKind: 'INSTALACION', requiresFamily: true },
|
||||
@@ -127,7 +121,7 @@ export class InventoryStructureService {
|
||||
|
||||
async parents(kindValue: string, search?: string) {
|
||||
const kind = kindValue.toUpperCase() as InventoryStructureKind;
|
||||
if (!(kind in PARENT_TYPE_BY_KIND) || kind === 'DEPARTAMENTO' || kind === 'EMPRESA') {
|
||||
if (!(kind in PARENT_TYPE_BY_KIND) || kind === 'AREA' || kind === 'EMPRESA') {
|
||||
throw new BadRequestException({
|
||||
code: 'INVENTORY_STRUCTURE_PARENT_KIND_INVALID',
|
||||
message: 'El nivel indicado no requiere un registro padre',
|
||||
@@ -159,7 +153,7 @@ export class InventoryStructureService {
|
||||
AND asset.information_status<>'INACTIVE'
|
||||
${searchSql}
|
||||
ORDER BY asset.name,asset.code
|
||||
LIMIT 100
|
||||
LIMIT 80
|
||||
`, parameters);
|
||||
return { data: rows };
|
||||
}
|
||||
@@ -175,9 +169,7 @@ export class InventoryStructureService {
|
||||
const parent = await this.requireParent(manager, dto.kind, dto.parentId ?? null);
|
||||
const family = await this.requireFamily(manager, dto.kind, dto.familyId ?? null, parent);
|
||||
const generatedCode = dto.code?.trim().toUpperCase() || this.generatedCode(dto.kind, dto.name);
|
||||
const operationalAreaId = parent && ['YACIMIENTO','INSTALACION','SUBINSTALACION'].includes(dto.kind)
|
||||
? await this.resolveAreaId(manager, parent)
|
||||
: null;
|
||||
const operationalAreaId = parent ? await this.resolveAreaId(manager, parent) : null;
|
||||
|
||||
const inserted = (await manager.query(`
|
||||
INSERT INTO assets (
|
||||
@@ -201,9 +193,9 @@ export class InventoryStructureService {
|
||||
AssetInformationStatus.DRAFT,
|
||||
AssetOperationalStatus.UNKNOWN,
|
||||
AssetDataOrigin.MANUAL,
|
||||
dto.kind === 'EMPRESA' ? 'Maestro manual de Empresas F5.1' : 'Estructura manual de Inventario F5.1',
|
||||
dto.kind === 'EMPRESA' ? 'Maestro de Empresas F5' : 'Estructura de Inventario F5',
|
||||
dto.kind === 'EMPRESA' ? 'inventory-master:empresa' : `inventory-structure:${dto.kind.toLowerCase()}`,
|
||||
family ? `Clasificación técnica: ${family.code} · ${family.name}` : null,
|
||||
family ? `Familia técnica: ${family.code} · ${family.name}` : null,
|
||||
principal.userId,
|
||||
])) as Array<{ id: string }>;
|
||||
const id = inserted[0]?.id;
|
||||
@@ -233,7 +225,7 @@ export class InventoryStructureService {
|
||||
id,
|
||||
parent?.id ?? null,
|
||||
operationalAreaId,
|
||||
dto.kind === 'EMPRESA' ? 'Alta manual de Empresa independiente F5.1' : 'Alta manual de estructura de Inventario F5.1',
|
||||
dto.kind === 'EMPRESA' ? 'Alta guiada de Empresa independiente F5' : 'Alta guiada de estructura de Inventario F5',
|
||||
versionNumber,
|
||||
request.requestId,
|
||||
principal.userId,
|
||||
@@ -293,7 +285,7 @@ export class InventoryStructureService {
|
||||
code: 'INVENTORY_ROOT_MUST_NOT_HAVE_PARENT',
|
||||
message: kind === 'EMPRESA'
|
||||
? 'Una Empresa es un maestro independiente y no puede tener padre'
|
||||
: 'Un Departamento es un registro raíz y no puede tener padre',
|
||||
: 'Un Área es un registro raíz y no puede tener padre',
|
||||
});
|
||||
}
|
||||
return null;
|
||||
@@ -317,7 +309,7 @@ export class InventoryStructureService {
|
||||
if (parent.typeCode.toLowerCase() !== expectedType) {
|
||||
throw new BadRequestException({
|
||||
code: 'INVENTORY_STRUCTURE_PARENT_INVALID',
|
||||
message: 'La jerarquía requerida es Departamento → Área → Yacimiento → Instalación → Subinstalación',
|
||||
message: 'La jerarquía requerida es Área → Yacimiento → Instalación → Subinstalación',
|
||||
});
|
||||
}
|
||||
return parent;
|
||||
@@ -357,13 +349,13 @@ export class InventoryStructureService {
|
||||
if (!expectedLevel) {
|
||||
if (familyId) throw new BadRequestException({
|
||||
code: 'INVENTORY_STRUCTURE_FAMILY_NOT_ALLOWED',
|
||||
message: 'Empresa, Departamento, Área y Yacimiento no llevan clasificación técnica',
|
||||
message: 'Empresa, Área y Yacimiento no llevan familia técnica',
|
||||
});
|
||||
return null;
|
||||
}
|
||||
if (!familyId) throw new BadRequestException({
|
||||
code: 'INVENTORY_STRUCTURE_FAMILY_REQUIRED',
|
||||
message: `Elegí la clasificación técnica de la ${kind.toLowerCase()}`,
|
||||
message: `Elegí la familia técnica de la ${kind.toLowerCase()}`,
|
||||
});
|
||||
const rows = (await manager.query(`
|
||||
SELECT family.id,family.code,family.name,family.level,
|
||||
@@ -377,27 +369,22 @@ export class InventoryStructureService {
|
||||
LIMIT 1
|
||||
`, [familyId])) as FamilyRow[];
|
||||
const family = rows[0];
|
||||
if (!family) throw new NotFoundException({ code: 'INVENTORY_FAMILY_NOT_FOUND', message: 'La clasificación técnica no existe' });
|
||||
if (!family) throw new NotFoundException({ code: 'INVENTORY_FAMILY_NOT_FOUND', message: 'La familia técnica no existe' });
|
||||
if (family.level !== expectedLevel) throw new BadRequestException({
|
||||
code: 'INVENTORY_FAMILY_LEVEL_INVALID',
|
||||
message: 'La clasificación técnica no corresponde al nivel seleccionado',
|
||||
message: 'La familia técnica no corresponde al nivel seleccionado',
|
||||
});
|
||||
if (kind === 'SUBINSTALACION' && family.parentFamilyId !== parent?.inventoryFamilyId) {
|
||||
throw new BadRequestException({
|
||||
code: 'INVENTORY_SUBINSTALLATION_FAMILY_PARENT_INVALID',
|
||||
message: 'La Subinstalación elegida no pertenece a la clasificación de la Instalación seleccionada',
|
||||
message: 'La Subinstalación elegida no pertenece a la familia de la Instalación seleccionada',
|
||||
});
|
||||
}
|
||||
return family;
|
||||
}
|
||||
|
||||
private generatedCode(kind: InventoryStructureKind, name: string): string {
|
||||
const prefix = kind === 'EMPRESA' ? 'EMP'
|
||||
: kind === 'DEPARTAMENTO' ? 'DEP'
|
||||
: kind === 'AREA' ? 'AREA'
|
||||
: kind === 'YACIMIENTO' ? 'YAC'
|
||||
: kind === 'INSTALACION' ? 'INST'
|
||||
: 'SUB';
|
||||
const prefix = kind === 'EMPRESA' ? 'EMP' : kind === 'YACIMIENTO' ? 'YAC' : kind === 'INSTALACION' ? 'INST' : kind === 'SUBINSTALACION' ? 'SUB' : 'AREA';
|
||||
const readable = name
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
@@ -430,3 +417,5 @@ export class InventoryStructureService {
|
||||
return rows[0];
|
||||
}
|
||||
}
|
||||
|
||||
type IdRow = { id: string };
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class F51CleanManualInventory1790087400000 implements MigrationInterface {
|
||||
name = 'F51CleanManualInventory1790087400000';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
// F5.1 is an intentional clean-start cut. The deployment process creates a
|
||||
// full database backup before migrations, so old domain data is recovered
|
||||
// from that backup rather than by pretending a destructive migration can
|
||||
// reconstruct historical rows.
|
||||
await queryRunner.query('DROP TRIGGER IF EXISTS trg_f5_canonical_asset_hierarchy ON assets');
|
||||
|
||||
// Remove all operational/domain instances and every table that depends on
|
||||
// them (visits, acts, findings, reports, versions, media, relations, etc.).
|
||||
// Users/roles/permissions and technical configuration are deliberately not
|
||||
// part of this TRUNCATE.
|
||||
await queryRunner.query('TRUNCATE TABLE assets CASCADE');
|
||||
|
||||
// Imported territorial/source material must not silently repopulate or
|
||||
// influence the new manually curated structure.
|
||||
await queryRunner.query('TRUNCATE TABLE administrative_departments CASCADE');
|
||||
await queryRunner.query('TRUNCATE TABLE source_documents CASCADE');
|
||||
|
||||
// Start the classification ↔ finding applicability review from zero while
|
||||
// preserving both master catalogs themselves.
|
||||
await queryRunner.query('TRUNCATE TABLE finding_catalog_item_inventory_families');
|
||||
|
||||
// Explicitly clear audit history, including authentication/admin events
|
||||
// accumulated during development. New events continue to be recorded after
|
||||
// this migration.
|
||||
await queryRunner.query('TRUNCATE TABLE audit_events');
|
||||
|
||||
// Import/reconciliation tables can contain rows not connected to a current
|
||||
// Asset. Clear every asset_import_* data table without coupling this cut to
|
||||
// one historical import implementation.
|
||||
await queryRunner.query(`
|
||||
DO $$
|
||||
DECLARE table_name text;
|
||||
BEGIN
|
||||
FOR table_name IN
|
||||
SELECT tablename
|
||||
FROM pg_tables
|
||||
WHERE schemaname = current_schema()
|
||||
AND tablename LIKE 'asset_import_%'
|
||||
LOOP
|
||||
EXECUTE format('TRUNCATE TABLE %I CASCADE', table_name);
|
||||
END LOOP;
|
||||
END $$;
|
||||
`);
|
||||
|
||||
// F5.1 decouples the physical Inventory tree from Empresa. A structural
|
||||
// Asset may therefore inherit an Area while no operator has been assigned
|
||||
// yet. Keep the useful invariant that an operator can never exist without
|
||||
// an Area, but remove the old all-or-nothing pair requirement.
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE asset_context_history
|
||||
DROP CONSTRAINT IF EXISTS chk_asset_context_history_context_pair
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE asset_context_history
|
||||
ADD CONSTRAINT chk_asset_context_history_context_pair
|
||||
CHECK (operator_company_id IS NULL OR operational_area_id IS NOT NULL)
|
||||
`);
|
||||
|
||||
// Departamento becomes the real root of the physical Inventory tree.
|
||||
await queryRunner.query(`
|
||||
INSERT INTO asset_types(code,name,description,can_be_root,is_active,operational_role)
|
||||
SELECT 'departamento','Departamento','Departamento administrativo que contiene Áreas.',true,true,'GENERIC'
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM asset_types WHERE lower(code)='departamento'
|
||||
)
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
UPDATE asset_types
|
||||
SET name='Departamento',
|
||||
description='Departamento administrativo que contiene Áreas.',
|
||||
can_be_root=true,
|
||||
is_active=true,
|
||||
operational_role='GENERIC',
|
||||
updated_at=CURRENT_TIMESTAMP
|
||||
WHERE lower(code)='departamento'
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
UPDATE asset_types
|
||||
SET can_be_root=false,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE lower(code)='area'
|
||||
`);
|
||||
|
||||
// Area has exactly one canonical structural parent kind: Departamento.
|
||||
await queryRunner.query(`
|
||||
DELETE FROM asset_type_parent_rules rule
|
||||
USING asset_types child
|
||||
WHERE rule.child_type_id=child.id AND lower(child.code)='area'
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
INSERT INTO asset_type_parent_rules(child_type_id,parent_type_id)
|
||||
SELECT child.id,parent.id
|
||||
FROM asset_types child CROSS JOIN asset_types parent
|
||||
WHERE lower(child.code)='area' AND lower(parent.code)='departamento'
|
||||
ON CONFLICT (child_type_id,parent_type_id) DO NOTHING
|
||||
`);
|
||||
|
||||
// Database-level guard: UI/API bugs cannot create an invalid physical tree.
|
||||
await queryRunner.query(`
|
||||
CREATE OR REPLACE FUNCTION enforce_f5_canonical_asset_hierarchy()
|
||||
RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE child_code text; parent_code text;
|
||||
BEGIN
|
||||
SELECT lower(code) INTO child_code FROM asset_types WHERE id=NEW.asset_type_id;
|
||||
|
||||
IF child_code IN ('empresa','organizacion','departamento') THEN
|
||||
IF NEW.parent_id IS NOT NULL THEN
|
||||
RAISE EXCEPTION USING ERRCODE='23514',MESSAGE='Empresa y Departamento son maestros raíz independientes';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
IF child_code NOT IN ('area','yacimiento','instalacion','subinstalacion') THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
IF NEW.parent_id IS NULL THEN
|
||||
RAISE EXCEPTION USING ERRCODE='23514',MESSAGE='La estructura requiere Departamento → Área → Yacimiento → Instalación → Subinstalación';
|
||||
END IF;
|
||||
|
||||
SELECT lower(type.code) INTO parent_code
|
||||
FROM assets parent
|
||||
JOIN asset_types type ON type.id=parent.asset_type_id
|
||||
WHERE parent.id=NEW.parent_id;
|
||||
|
||||
IF (child_code='area' AND parent_code<>'departamento')
|
||||
OR (child_code='yacimiento' AND parent_code<>'area')
|
||||
OR (child_code='instalacion' AND parent_code<>'yacimiento')
|
||||
OR (child_code='subinstalacion' AND parent_code<>'instalacion') THEN
|
||||
RAISE EXCEPTION USING ERRCODE='23514',MESSAGE='Jerarquía inválida: Departamento → Área → Yacimiento → Instalación → Subinstalación';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
CREATE TRIGGER trg_f5_canonical_asset_hierarchy
|
||||
BEFORE INSERT OR UPDATE OF asset_type_id,parent_id ON assets
|
||||
FOR EACH ROW EXECUTE FUNCTION enforce_f5_canonical_asset_hierarchy()
|
||||
`);
|
||||
|
||||
const rows = (await queryRunner.query(`
|
||||
SELECT
|
||||
(SELECT COUNT(*)::integer FROM assets) AS assets,
|
||||
(SELECT COUNT(*)::integer FROM audit_events) AS audits,
|
||||
(SELECT COUNT(*)::integer FROM finding_catalog_item_inventory_families) AS applicability,
|
||||
(SELECT COUNT(*)::integer FROM asset_types WHERE lower(code)='departamento' AND can_be_root=true AND is_active=true) AS departments,
|
||||
(SELECT COUNT(*)::integer
|
||||
FROM asset_type_parent_rules rule
|
||||
JOIN asset_types child ON child.id=rule.child_type_id
|
||||
JOIN asset_types parent ON parent.id=rule.parent_type_id
|
||||
WHERE lower(child.code)='area' AND lower(parent.code)='departamento') AS area_rules
|
||||
`)) as Array<{ assets: number; audits: number; applicability: number; departments: number; area_rules: number }>;
|
||||
const check = rows[0];
|
||||
if (!check || Number(check.assets) !== 0 || Number(check.audits) !== 0 || Number(check.applicability) !== 0
|
||||
|| Number(check.departments) !== 1 || Number(check.area_rules) !== 1) {
|
||||
throw new Error(`F5.1 clean-start verification failed: ${JSON.stringify(check ?? {})}`);
|
||||
}
|
||||
}
|
||||
|
||||
public async down(): Promise<void> {
|
||||
throw new Error('F5.1 is an intentional destructive clean-start migration. Restore the pre-deploy database backup to recover previous data.');
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
function source(path: string) {
|
||||
return readFileSync(resolve(process.cwd(), path), 'utf8');
|
||||
}
|
||||
|
||||
test('F5.1 clean start deletes domain instances and audit history but preserves master configuration by contract', () => {
|
||||
const migration = source('src/database/migrations/1790087400000-f5-1-clean-manual-inventory.ts');
|
||||
assert.match(migration, /TRUNCATE TABLE assets CASCADE/);
|
||||
assert.match(migration, /TRUNCATE TABLE audit_events/);
|
||||
assert.match(migration, /TRUNCATE TABLE administrative_departments CASCADE/);
|
||||
assert.match(migration, /TRUNCATE TABLE finding_catalog_item_inventory_families/);
|
||||
assert.doesNotMatch(migration, /TRUNCATE TABLE inventory_families/);
|
||||
assert.doesNotMatch(migration, /TRUNCATE TABLE finding_catalog_items/);
|
||||
assert.doesNotMatch(migration, /TRUNCATE TABLE users/);
|
||||
});
|
||||
|
||||
test('F5.1 canonical hierarchy starts at Departamento and Area is no longer root', () => {
|
||||
const migration = source('src/database/migrations/1790087400000-f5-1-clean-manual-inventory.ts');
|
||||
const dto = source('src/asset-master/dto/create-inventory-structure.dto.ts');
|
||||
const structure = source('src/asset-master/inventory-structure.service.ts');
|
||||
|
||||
assert.match(dto, /'DEPARTAMENTO'/);
|
||||
assert.match(structure, /DEPARTAMENTO: 'departamento'/);
|
||||
assert.match(structure, /AREA: 'departamento'/);
|
||||
assert.match(structure, /Departamento → Área → Yacimiento → Instalación → Subinstalación/);
|
||||
assert.match(migration, /child_code='area' AND parent_code<>'departamento'/);
|
||||
assert.match(migration, /WHERE lower\(code\)='area'/);
|
||||
assert.match(migration, /SET can_be_root=false/);
|
||||
});
|
||||
|
||||
test('F5.1 manual creation permits Area context without requiring an operator', () => {
|
||||
const migration = source('src/database/migrations/1790087400000-f5-1-clean-manual-inventory.ts');
|
||||
const structure = source('src/asset-master/inventory-structure.service.ts');
|
||||
|
||||
assert.match(migration, /DROP CONSTRAINT IF EXISTS chk_asset_context_history_context_pair/);
|
||||
assert.match(migration, /CHECK \(operator_company_id IS NULL OR operational_area_id IS NOT NULL\)/);
|
||||
assert.match(structure, /operator_company_id,inventory_family_id/);
|
||||
assert.match(structure, /asset_context_history/);
|
||||
assert.match(structure, /operational_area_id,operator_company_id/);
|
||||
});
|
||||
|
||||
test('F5.1 Inventory browser exposes every canonical level instead of filtering by is_inventory_instance', () => {
|
||||
const browser = source('src/asset-master/inventory-browser.service.ts');
|
||||
const controller = source('src/asset-master/inventory-browser.controller.ts');
|
||||
|
||||
assert.match(browser, /'departamento','area','yacimiento','instalacion','subinstalacion'/);
|
||||
assert.match(browser, /case 'departamento': return 'area'/);
|
||||
assert.doesNotMatch(browser, /['"]asset\.is_inventory_instance=true['"]/);
|
||||
assert.match(controller, /@Get\('departments'\)/);
|
||||
assert.match(controller, /@Get\('companies'\)/);
|
||||
});
|
||||
|
||||
test('F5.1 Finding Catalog defaults to associated findings and exposes all items only for linking', () => {
|
||||
const panel = source('../web-v2/src/features/inspections/FindingCatalogTypeApplicabilityPanel.tsx');
|
||||
assert.match(panel, /type ViewMode = 'ASSOCIATED' \| 'ALL'/);
|
||||
assert.match(panel, /useState<ViewMode>\('ASSOCIATED'\)/);
|
||||
assert.match(panel, /available\.filter\(\(item\) => savedIds\.has\(item\.id\)\)/);
|
||||
assert.match(panel, /Buscar dentro de \{viewMode === 'ASSOCIATED' \? 'los asociados' : 'todo el Catálogo'\}/);
|
||||
assert.match(panel, /Todos para vincular/);
|
||||
assert.match(panel, /Esta clasificación todavía no tiene Hallazgos asociados/);
|
||||
});
|
||||
|
||||
test('F5.1 Configuration manages findings inline and filters Subinstallations by Installation', () => {
|
||||
const configPage = source('../web-v2/src/pages/AssetTypesPage.tsx');
|
||||
|
||||
assert.match(configPage, /replaceInventoryFamilyFindings/);
|
||||
assert.match(configPage, /Agregar o quitar/);
|
||||
assert.match(configPage, /familyFindingIds/);
|
||||
assert.match(configPage, /selectedInstallationFamilyId/);
|
||||
assert.match(configPage, /family\.parentFamilyId === selectedInstallationFamilyId/);
|
||||
assert.match(configPage, /Filtrar por tipo de Instalación/);
|
||||
});
|
||||
|
||||
test('F5.1 Web creation and configuration expose Departamento as the physical root', () => {
|
||||
const createPage = source('../web-v2/src/pages/InventoryCreatePage.tsx');
|
||||
const configPage = source('../web-v2/src/pages/AssetTypesPage.tsx');
|
||||
assert.match(createPage, /kind: 'DEPARTAMENTO'/);
|
||||
assert.match(createPage, /AREA:'Departamento'/);
|
||||
assert.match(createPage, /Datos opcionales/);
|
||||
assert.match(configPage, /<strong>Departamento<\/strong>/);
|
||||
assert.match(configPage, /familyId=\$\{familyEditor\.id\}/);
|
||||
});
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dhv2-web",
|
||||
"version": "0.22.0-1",
|
||||
"version": "0.21.0-1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
|
||||
@@ -6,13 +6,11 @@ import { Icon } from '../../components/Icon';
|
||||
import { getAssetLineage } from '../../lib/api';
|
||||
import type { AssetLineageItem } from '../../lib/api';
|
||||
import {
|
||||
listInventoryCompanies,
|
||||
listInventoryDepartments,
|
||||
listInventoryAreas,
|
||||
listInventoryChildren,
|
||||
} from '../../lib/inventoryBrowserApi';
|
||||
import type {
|
||||
InventoryBrowserCompany,
|
||||
InventoryBrowserDepartment,
|
||||
InventoryBrowserArea,
|
||||
InventoryBrowserItem,
|
||||
InventoryQuery,
|
||||
} from '../../lib/inventoryBrowserApi';
|
||||
@@ -28,30 +26,28 @@ function navigationHref(base: URLSearchParams, parentId?: string) {
|
||||
return `/inventarios${params.size ? `?${params}` : ''}`;
|
||||
}
|
||||
|
||||
function DepartmentCard({ department, href }: { department: InventoryBrowserDepartment; href: string }) {
|
||||
function AreaCard({ area, href }: { area: InventoryBrowserArea; href: string }) {
|
||||
return <Link className="asset-browser-item" to={href}>
|
||||
<span className="asset-browser-item-icon"><Icon name="map" size={17} /></span>
|
||||
<span className="asset-browser-item-main">
|
||||
<strong>{department.name}</strong>
|
||||
<small>{department.code} · {department.areaCount} Área{department.areaCount === 1 ? '' : 's'}</small>
|
||||
<strong>{area.name}</strong>
|
||||
<small>
|
||||
{area.code} · {area.yacimientoCount} yacimiento{area.yacimientoCount === 1 ? '' : 's'}
|
||||
{area.currentOperator ? ` · Operadora vigente: ${area.currentOperator.name}` : ' · Sin operadora vigente'}
|
||||
</small>
|
||||
</span>
|
||||
<span className="asset-browser-item-status">
|
||||
<strong>{area.inventoryCount}</strong>
|
||||
<small>instancia{area.inventoryCount === 1 ? '' : 's'} real{area.inventoryCount === 1 ? '' : 'es'}</small>
|
||||
</span>
|
||||
<span className="asset-browser-item-status"><span className={`status-badge ${assetStatusClass(department.informationStatus)}`}>{assetStatusLabel(department.informationStatus)}</span></span>
|
||||
<Icon name="chevron" size={16} />
|
||||
</Link>;
|
||||
}
|
||||
|
||||
function CompanyCard({ company }: { company: InventoryBrowserCompany }) {
|
||||
return <Link className="asset-browser-item" to={`/inventarios/${company.id}`}>
|
||||
<span className="asset-browser-item-icon"><Icon name="users" size={17} /></span>
|
||||
<span className="asset-browser-item-main"><strong>{company.name}</strong><small>{company.code} · {company.areaCount} Área{company.areaCount === 1 ? '' : 's'} operada{company.areaCount === 1 ? '' : 's'}</small></span>
|
||||
<span className="asset-browser-item-status"><span className={`status-badge ${assetStatusClass(company.informationStatus)}`}>{assetStatusLabel(company.informationStatus)}</span></span>
|
||||
<Icon name="chevron" size={16} />
|
||||
</Link>;
|
||||
}
|
||||
|
||||
function InventoryCard({ item, href }: { item: InventoryBrowserItem; href: string }) {
|
||||
const structural = !item.isInventoryInstance;
|
||||
return <Link className="asset-browser-item" to={href}>
|
||||
<span className="asset-browser-item-icon"><Icon name={['departamento','area','yacimiento'].includes(item.type.code.toLowerCase()) ? 'map' : 'layers'} size={17} /></span>
|
||||
<span className="asset-browser-item-icon"><Icon name={structural ? 'map' : 'layers'} size={17} /></span>
|
||||
<span className="asset-browser-item-main">
|
||||
<strong>{item.name}</strong>
|
||||
<small>
|
||||
@@ -61,10 +57,9 @@ function InventoryCard({ item, href }: { item: InventoryBrowserItem; href: strin
|
||||
</small>
|
||||
</span>
|
||||
<span className="asset-browser-item-status">
|
||||
<span className={`status-badge ${assetStatusClass(item.informationStatus)}`}>{assetStatusLabel(item.informationStatus)}</span>
|
||||
{item.inventoryFamily
|
||||
? <small>{item.findingCount} Hallazgo{item.findingCount === 1 ? '' : 's'} asociado{item.findingCount === 1 ? '' : 's'}</small>
|
||||
: <small>{item.childrenCount} registro{item.childrenCount === 1 ? '' : 's'} inferior{item.childrenCount === 1 ? '' : 'es'}</small>}
|
||||
{structural
|
||||
? <><span className="tag">Contexto</span><small>{item.childrenCount} nivel{item.childrenCount === 1 ? '' : 'es'} inferior{item.childrenCount === 1 ? '' : 'es'}</small></>
|
||||
: <><span className={`status-badge ${assetStatusClass(item.informationStatus)}`}>{assetStatusLabel(item.informationStatus)}</span><small>{assetOperationalStatusLabel(item.operationalStatus)}</small></>}
|
||||
</span>
|
||||
<Icon name="chevron" size={16} />
|
||||
</Link>;
|
||||
@@ -72,7 +67,6 @@ function InventoryCard({ item, href }: { item: InventoryBrowserItem; href: strin
|
||||
|
||||
function nextLevelLabel(typeCode: string | undefined) {
|
||||
switch (typeCode?.toLowerCase()) {
|
||||
case 'departamento': return 'Áreas';
|
||||
case 'area': return 'Yacimientos';
|
||||
case 'yacimiento': return 'Instalaciones';
|
||||
case 'instalacion': return 'Subinstalaciones';
|
||||
@@ -85,8 +79,7 @@ export function AssetHierarchyView({ filters }: { filters: InventoryQuery }) {
|
||||
const canCreate = hasPermission('assets.create');
|
||||
const [searchParams] = useSearchParams();
|
||||
const parentId = searchParams.get('parentId') ?? '';
|
||||
const [departments, setDepartments] = useState<InventoryBrowserDepartment[]>([]);
|
||||
const [companies, setCompanies] = useState<InventoryBrowserCompany[]>([]);
|
||||
const [areas, setAreas] = useState<InventoryBrowserArea[]>([]);
|
||||
const [children, setChildren] = useState<InventoryBrowserItem[]>([]);
|
||||
const [lineage, setLineage] = useState<AssetLineageItem[]>([]);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
@@ -95,53 +88,66 @@ export function AssetHierarchyView({ filters }: { filters: InventoryQuery }) {
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setLoading(true); setError(''); setDepartments([]); setCompanies([]); setChildren([]); setLineage([]); setHasMore(false);
|
||||
setLoading(true);
|
||||
setError('');
|
||||
setAreas([]);
|
||||
setChildren([]);
|
||||
setLineage([]);
|
||||
setHasMore(false);
|
||||
|
||||
const run = async () => {
|
||||
if (!parentId) {
|
||||
const [loadedDepartments, loadedCompanies] = await Promise.all([
|
||||
listInventoryDepartments({ search: filters.search, operatorCompanyId: filters.operatorCompanyId }),
|
||||
listInventoryCompanies({ search: filters.search }),
|
||||
]);
|
||||
if (active) { setDepartments(loadedDepartments.data); setCompanies(loadedCompanies.data); }
|
||||
const response = await listInventoryAreas({
|
||||
search: filters.search,
|
||||
operationalAreaId: filters.operationalAreaId,
|
||||
operatorCompanyId: filters.operatorCompanyId,
|
||||
});
|
||||
if (active) setAreas(response.data);
|
||||
return;
|
||||
}
|
||||
|
||||
const [loadedLineage, response] = await Promise.all([
|
||||
getAssetLineage(parentId),
|
||||
listInventoryChildren(parentId, { search: filters.search }),
|
||||
]);
|
||||
if (!active) return;
|
||||
setLineage(loadedLineage.filter((item) => ['departamento','area','yacimiento','instalacion','subinstalacion'].includes(item.type.code.toLowerCase())));
|
||||
setChildren(response.data); setHasMore(response.meta.hasMore);
|
||||
setLineage(loadedLineage.filter((item) => ['area','yacimiento','instalacion','subinstalacion'].includes(item.type.code.toLowerCase())));
|
||||
setChildren(response.data);
|
||||
setHasMore(response.meta.hasMore);
|
||||
};
|
||||
run().catch((requestError) => active && setError(errorMessage(requestError))).finally(() => active && setLoading(false));
|
||||
return () => { active = false; };
|
||||
}, [parentId, filters.search, filters.operatorCompanyId]);
|
||||
|
||||
if (loading) return <LoadingBlock label="Cargando Inventarios…" />;
|
||||
run()
|
||||
.catch((requestError) => active && setError(errorMessage(requestError)))
|
||||
.finally(() => active && setLoading(false));
|
||||
return () => { active = false; };
|
||||
}, [parentId, filters.search, filters.operationalAreaId, filters.operatorCompanyId]);
|
||||
|
||||
if (loading) return <LoadingBlock label="Cargando inventarios…" />;
|
||||
|
||||
if (!parentId) {
|
||||
const realTotal = areas.reduce((sum, area) => sum + Number(area.inventoryCount ?? 0), 0);
|
||||
return <div className="asset-browser-panel">
|
||||
{error && <Alert>{error}</Alert>}
|
||||
<div className="asset-browser-section-heading">
|
||||
<div><span className="eyebrow">INVENTARIO COMPLETO</span><h2>Departamentos</h2><p>Entrá por Departamento y navegá Área → Yacimiento → Instalación → Subinstalación hasta llegar a su clasificación y Hallazgos asociados.</p></div>
|
||||
<div className="asset-browser-current-actions"><span className="count-pill">{departments.length} Departamentos</span><span className="count-pill">{companies.length} Empresas</span></div>
|
||||
<div>
|
||||
<span className="eyebrow">ESTRUCTURA TERRITORIAL</span>
|
||||
<h2>Áreas</h2>
|
||||
<p>Las Áreas y Yacimientos son contexto de navegación. El Inventario real comienza en las Instalaciones/Subinstalaciones efectivamente registradas.</p>
|
||||
</div>
|
||||
<div className="asset-browser-current-actions">
|
||||
<span className="count-pill">{realTotal} Inventario real</span>
|
||||
<span className="count-pill">{areas.length} Áreas</span>
|
||||
</div>
|
||||
</div>
|
||||
{departments.length === 0
|
||||
? <EmptyState title="Todavía no hay Departamentos" text="Creá el primer registro para comenzar a construir el Inventario manualmente." />
|
||||
: <div className="asset-browser-list">{departments.map((department) => <DepartmentCard key={department.id} department={department} href={navigationHref(searchParams, department.id)} />)}</div>}
|
||||
|
||||
{areas.length === 0
|
||||
? <EmptyState title="No hay Áreas para mostrar" text="Probá con otra búsqueda o revisá el contexto seleccionado." />
|
||||
: <div className="asset-browser-list">{areas.map((area) => <AreaCard key={area.id} area={area} href={navigationHref(searchParams, area.id)} />)}</div>}
|
||||
<div className="asset-browser-levels" aria-label="Estructura de Inventarios">
|
||||
<div><span>1</span><strong>Departamento</strong><small>raíz territorial</small></div><i>›</i>
|
||||
<div><span>2</span><strong>Área</strong><small>dentro del Departamento</small></div><i>›</i>
|
||||
<div><span>3</span><strong>Yacimiento</strong><small>dentro del Área</small></div><i>›</i>
|
||||
<div><span>4</span><strong>Instalación</strong><small>clasificación técnica</small></div><i>›</i>
|
||||
<div><span>5</span><strong>Subinstalación</strong><small>clasificación técnica</small></div>
|
||||
<div><span>1</span><strong>Área</strong><small>Ancla territorial</small></div><i>›</i>
|
||||
<div><span>2</span><strong>Yacimiento</strong><small>Contexto dentro del Área</small></div><i>›</i>
|
||||
<div><span>3</span><strong>Instalación</strong><small>Inventario real</small></div><i>›</i>
|
||||
<div><span>4</span><strong>Subinstalación</strong><small>Inventario real</small></div>
|
||||
</div>
|
||||
|
||||
<section className="asset-browser-group" style={{ marginTop: 20 }}>
|
||||
<div className="asset-browser-group-heading"><div><h3>Empresas</h3><p>Maestro independiente. La Empresa se vincula al Área como operadora sin alterar la estructura física.</p></div><span>{companies.length}</span></div>
|
||||
{companies.length === 0 ? <div className="inline-empty">Todavía no hay Empresas cargadas.</div> : <div className="asset-browser-list">{companies.map((company) => <CompanyCard key={company.id} company={company} />)}</div>}
|
||||
</section>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -150,7 +156,10 @@ export function AssetHierarchyView({ filters }: { filters: InventoryQuery }) {
|
||||
<Link to="/inventarios">Inventarios</Link>
|
||||
{lineage.map((item,index) => {
|
||||
const isLast=index===lineage.length-1;
|
||||
return <span className="asset-browser-crumb-part" key={item.id}><span>›</span>{isLast ? <strong>{item.name}</strong> : <Link to={navigationHref(searchParams,item.id)}>{item.name}</Link>}</span>;
|
||||
return <span className="asset-browser-crumb-part" key={item.id}>
|
||||
<span>›</span>
|
||||
{isLast ? <strong>{item.name}</strong> : <Link to={navigationHref(searchParams,item.id)}>{item.name}</Link>}
|
||||
</span>;
|
||||
})}
|
||||
</nav>;
|
||||
|
||||
@@ -159,17 +168,31 @@ export function AssetHierarchyView({ filters }: { filters: InventoryQuery }) {
|
||||
{error && <Alert>{error}</Alert>}
|
||||
{hasMore && <Alert type="info">Este nivel tiene más de 200 registros. Usá la búsqueda para acotar el resultado.</Alert>}
|
||||
<div className="asset-browser-current-heading">
|
||||
<div><span className="eyebrow">{current?.type.name ?? 'INVENTARIO'}</span><h2>{current?.name ?? 'Nivel de Inventario'}</h2><p>{current?.code ?? ''}</p></div>
|
||||
<div>
|
||||
<span className="eyebrow">{current?.type.name ?? 'INVENTARIO'}</span>
|
||||
<h2>{current?.name ?? 'Nivel de Inventario'}</h2>
|
||||
<p>{current?.code ?? ''}</p>
|
||||
</div>
|
||||
<div className="asset-browser-current-actions">
|
||||
{current && <Link className="button secondary" to={`/inventarios/${current.id}`}>Ver ficha{['instalacion','subinstalacion'].includes(current.type.code.toLowerCase()) ? ' y Hallazgos' : ''}</Link>}
|
||||
{current && <Link className="button secondary" to={`/inventarios/${current.id}`}>Ver ficha</Link>}
|
||||
{canCreate && current?.type.code.toLowerCase() !== 'subinstalacion' && <Link className="button primary" to={`/inventarios/nuevo?parentId=${parentId}`}><Icon name="plus" />Agregar aquí</Link>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="asset-browser-group">
|
||||
<div className="asset-browser-group-heading"><div><h3>{nextLevelLabel(current?.type.code)}</h3><p>Jerarquía: Departamento → Área → Yacimiento → Instalación → Subinstalación.</p></div><span>{children.length}</span></div>
|
||||
<div className="asset-browser-group-heading">
|
||||
<div><h3>{nextLevelLabel(current?.type.code)}</h3><p>La jerarquía permitida es Área → Yacimiento → Instalación → Subinstalación.</p></div>
|
||||
<span>{children.length}</span>
|
||||
</div>
|
||||
{children.length === 0
|
||||
? <EmptyState title={current?.type.code.toLowerCase() === 'subinstalacion' ? 'Fin de la jerarquía' : 'No hay registros en este nivel'} text={current?.type.code.toLowerCase() === 'subinstalacion' ? 'Abrí la ficha para ver su clasificación y Hallazgos asociados.' : 'Agregá el primer registro de este nivel o revisá la búsqueda actual.'} />
|
||||
? <EmptyState
|
||||
title={current?.type.code.toLowerCase() === 'subinstalacion' ? 'Fin de la jerarquía' : 'No hay registros en este nivel'}
|
||||
text={current?.type.code.toLowerCase() === 'yacimiento'
|
||||
? 'Todavía no hay Instalaciones reales registradas en este Yacimiento.'
|
||||
: current?.type.code.toLowerCase() === 'instalacion'
|
||||
? 'Todavía no hay Subinstalaciones registradas en esta Instalación.'
|
||||
: 'No hay registros que coincidan con la búsqueda actual.'}
|
||||
/>
|
||||
: <div className="asset-browser-list">{children.map((item) => <InventoryCard key={item.id} item={item} href={navigationHref(searchParams,item.id)} />)}</div>}
|
||||
</section>
|
||||
</div>;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { SearchableSelect } from '../../components/SearchableSelect';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { Alert, LoadingBlock, errorMessage } from '../../components/Feedback';
|
||||
import { Icon } from '../../components/Icon';
|
||||
import { getFindingCatalogAdmin } from '../../lib/api';
|
||||
@@ -13,25 +12,19 @@ import type { InventoryFamily } from '../../lib/inventoryStructureApi';
|
||||
|
||||
const EMPTY_CATALOG: FindingAdminCatalog = { categories: [], items: [] };
|
||||
|
||||
type ViewMode = 'ASSOCIATED' | 'ALL';
|
||||
|
||||
export function FindingCatalogTypeApplicabilityPanel() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const requestedFamilyId = searchParams.get('familyId') ?? '';
|
||||
const [families, setFamilies] = useState<InventoryFamily[]>([]);
|
||||
const [catalog, setCatalog] = useState<FindingAdminCatalog>(EMPTY_CATALOG);
|
||||
const [familyId, setFamilyId] = useState('');
|
||||
const [enabled, setEnabled] = useState<Set<string>>(new Set());
|
||||
const [reason, setReason] = useState('Actualización de Hallazgos asociados a la clasificación de Inventario');
|
||||
const [reason, setReason] = useState('Actualización de aplicabilidad por clasificación de Inventario');
|
||||
const [search, setSearch] = useState('');
|
||||
const [viewMode, setViewMode] = useState<ViewMode>('ASSOCIATED');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
|
||||
const selectedFamily = families.find((family) => family.id === familyId) ?? null;
|
||||
const savedIds = useMemo(() => new Set(selectedFamily?.findingItemIds ?? []), [selectedFamily]);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([listInventoryFamiliesAdmin(), getFindingCatalogAdmin()])
|
||||
@@ -39,19 +32,15 @@ export function FindingCatalogTypeApplicabilityPanel() {
|
||||
const activeFamilies = loadedFamilies.filter((family) => family.isActive !== false);
|
||||
setFamilies(activeFamilies);
|
||||
setCatalog(loadedCatalog);
|
||||
setFamilyId(activeFamilies.some((family) => family.id === requestedFamilyId)
|
||||
? requestedFamilyId
|
||||
: activeFamilies[0]?.id ?? '');
|
||||
setFamilyId(activeFamilies[0]?.id ?? '');
|
||||
})
|
||||
.catch((requestError) => setError(errorMessage(requestError)))
|
||||
.finally(() => setLoading(false));
|
||||
}, [requestedFamilyId]);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const selected = families.find((family) => family.id === familyId);
|
||||
setEnabled(new Set(selected?.findingItemIds ?? []));
|
||||
setViewMode('ASSOCIATED');
|
||||
setSearch('');
|
||||
setSuccess('');
|
||||
setError('');
|
||||
}, [familyId, families]);
|
||||
@@ -64,7 +53,7 @@ export function FindingCatalogTypeApplicabilityPanel() {
|
||||
catalog.categories.map((category) => [category.id, category.name]),
|
||||
), [catalog.categories]);
|
||||
|
||||
const available = useMemo(() => {
|
||||
const visible = useMemo(() => {
|
||||
const needle = search.trim().toLocaleLowerCase('es-AR');
|
||||
return catalog.items.filter((item) =>
|
||||
item.isActive
|
||||
@@ -74,23 +63,12 @@ export function FindingCatalogTypeApplicabilityPanel() {
|
||||
);
|
||||
}, [catalog.items, search, activeCategoryIds, categoryName]);
|
||||
|
||||
const visible = useMemo(() => viewMode === 'ASSOCIATED'
|
||||
? available.filter((item) => savedIds.has(item.id))
|
||||
: available,
|
||||
[available, savedIds, viewMode]);
|
||||
|
||||
const toggle = (id: string) => setEnabled((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(id)) next.delete(id); else next.add(id);
|
||||
return next;
|
||||
});
|
||||
|
||||
const selectVisible = () => setEnabled((current) => {
|
||||
const next = new Set(current);
|
||||
visible.forEach((item) => next.add(item.id));
|
||||
return next;
|
||||
});
|
||||
|
||||
const save = async () => {
|
||||
if (!selectedFamily) return;
|
||||
setSaving(true); setError(''); setSuccess('');
|
||||
@@ -104,7 +82,6 @@ export function FindingCatalogTypeApplicabilityPanel() {
|
||||
setFamilies((current) => current.map((family) => family.id === selectedFamily.id
|
||||
? { ...family, findingItemIds: itemIds, findingCount: itemIds.length }
|
||||
: family));
|
||||
setViewMode('ASSOCIATED');
|
||||
setSuccess(`Hallazgos guardados para ${selectedFamily.name}.`);
|
||||
} catch (requestError) {
|
||||
setError(errorMessage(requestError));
|
||||
@@ -121,9 +98,9 @@ export function FindingCatalogTypeApplicabilityPanel() {
|
||||
<div>
|
||||
<span className="eyebrow">APLICABILIDAD POR INSTALACIÓN / SUBINSTALACIÓN</span>
|
||||
<h2>Qué Hallazgos verá el inspector</h2>
|
||||
<p className="section-copy">Al elegir una clasificación se filtra inmediatamente a sus Hallazgos asociados. Para modificar la relación, abrí “Todos para vincular”.</p>
|
||||
<p className="section-copy">Los Hallazgos se vinculan a la clasificación concreta del elemento, no a una “función”. La opción OTROS permanece siempre disponible en la APK.</p>
|
||||
</div>
|
||||
<span className="count-pill">{savedIds.size} vinculados</span>
|
||||
<span className="count-pill">{enabled.size} vinculados</span>
|
||||
</div>
|
||||
{error && <Alert>{error}</Alert>}{success && <Alert type="success">{success}</Alert>}
|
||||
<div className="form-grid finding-applicability-toolbar">
|
||||
@@ -135,39 +112,21 @@ export function FindingCatalogTypeApplicabilityPanel() {
|
||||
</option>)}
|
||||
</SearchableSelect>
|
||||
</label>
|
||||
<label className="field"><span>Buscar dentro de {viewMode === 'ASSOCIATED' ? 'los asociados' : 'todo el Catálogo'}</span><input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Título, código o categoría…" /></label>
|
||||
<label className="field"><span>Buscar Hallazgo</span><input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Título, código o categoría…" /></label>
|
||||
</div>
|
||||
{selectedFamily && <div className="temporal-notice">
|
||||
<Icon name="layers" />
|
||||
<p><strong>{selectedFamily.level === 'INSTALLATION' ? 'Instalación' : 'Subinstalación'}:</strong> {selectedFamily.parentFamilyName ? `${selectedFamily.parentFamilyName} → ` : ''}{selectedFamily.name}. Tiene {savedIds.size} Hallazgo{savedIds.size === 1 ? '' : 's'} asociado{savedIds.size === 1 ? '' : 's'}.</p>
|
||||
<p><strong>{selectedFamily.level === 'INSTALLATION' ? 'Instalación' : 'Subinstalación'}:</strong> {selectedFamily.parentFamilyName ? `${selectedFamily.parentFamilyName} → ` : ''}{selectedFamily.name}. Actualmente tiene {selectedFamily.findingCount ?? enabled.size} Hallazgo{(selectedFamily.findingCount ?? enabled.size) === 1 ? '' : 's'} asociado{(selectedFamily.findingCount ?? enabled.size) === 1 ? '' : 's'}.</p>
|
||||
</div>}
|
||||
|
||||
<div className="quick-view-row" style={{ marginBottom: 12 }}>
|
||||
<button type="button" className={viewMode === 'ASSOCIATED' ? 'active' : ''} onClick={() => { setViewMode('ASSOCIATED'); setSearch(''); }}>Asociados ({savedIds.size})</button>
|
||||
<button type="button" className={viewMode === 'ALL' ? 'active' : ''} onClick={() => { setViewMode('ALL'); setSearch(''); }}>Todos para vincular ({catalog.items.filter((item) => item.isActive && activeCategoryIds.has(item.categoryId)).length})</button>
|
||||
<div className="catalog-selection-actions">
|
||||
<button type="button" className="button secondary" onClick={() => setEnabled(new Set(visible.map((item) => item.id)))}>Seleccionar visibles</button>
|
||||
<button type="button" className="button secondary" onClick={() => setEnabled(new Set())}>Quitar todos</button>
|
||||
</div>
|
||||
|
||||
{viewMode === 'ASSOCIATED' && visible.length === 0
|
||||
? <div className="inline-empty"><strong>{search.trim() ? 'Ningún Hallazgo asociado coincide con la búsqueda.' : 'Esta clasificación todavía no tiene Hallazgos asociados.'}</strong><br />{!search.trim() && 'Abrí “Todos para vincular” para elegirlos.'}</div>
|
||||
: <>
|
||||
{viewMode === 'ALL' && <div className="catalog-selection-actions">
|
||||
<button type="button" className="button secondary" onClick={selectVisible}>Seleccionar visibles</button>
|
||||
<button type="button" className="button secondary" onClick={() => setEnabled(new Set())}>Quitar todos</button>
|
||||
</div>}
|
||||
<div className="finding-selection-list">{visible.map((item) => viewMode === 'ALL'
|
||||
? <label className="finding-selection-row" key={item.id}>
|
||||
<input type="checkbox" checked={enabled.has(item.id)} onChange={() => toggle(item.id)} />
|
||||
<span><strong>{item.title}</strong><small>{categoryName.get(item.categoryId) ?? 'Catálogo'} · {item.code}{item.suggestedSeverity ? ` · gravedad sugerida ${item.suggestedSeverity}/10` : ''}</small></span>
|
||||
</label>
|
||||
: <div className="finding-selection-row" key={item.id}>
|
||||
<span className="asset-symbol"><Icon name="check" size={14} /></span>
|
||||
<span><strong>{item.title}</strong><small>{categoryName.get(item.categoryId) ?? 'Catálogo'} · {item.code}{item.suggestedSeverity ? ` · gravedad sugerida ${item.suggestedSeverity}/10` : ''}</small></span>
|
||||
</div>)}</div>
|
||||
</>}
|
||||
|
||||
{viewMode === 'ALL' && <>
|
||||
<label className="field"><span>Motivo del cambio</span><textarea rows={2} value={reason} onChange={(event) => setReason(event.target.value)} maxLength={2000} /></label>
|
||||
<div className="form-actions"><button type="button" className="button primary" disabled={saving || reason.trim().length < 5 || !selectedFamily} onClick={save}><Icon name="check" />{saving ? 'Guardando…' : `Guardar ${enabled.size} asociados`}</button></div>
|
||||
</>}
|
||||
<div className="finding-selection-list">{visible.map((item) => <label className="finding-selection-row" key={item.id}>
|
||||
<input type="checkbox" checked={enabled.has(item.id)} onChange={() => toggle(item.id)} />
|
||||
<span><strong>{item.title}</strong><small>{categoryName.get(item.categoryId) ?? 'Catálogo'} · {item.code}{item.suggestedSeverity ? ` · gravedad sugerida ${item.suggestedSeverity}/10` : ''}</small></span>
|
||||
</label>)}</div>
|
||||
<label className="field"><span>Motivo del cambio</span><textarea rows={2} value={reason} onChange={(event) => setReason(event.target.value)} maxLength={2000} placeholder="Ej.: Hallazgos aplicables a esta Subinstalación según criterio técnico…" /></label>
|
||||
<div className="form-actions"><button type="button" className="button primary" disabled={saving || reason.trim().length < 5 || !selectedFamily} onClick={save}><Icon name="check" />{saving ? 'Guardando…' : 'Guardar Hallazgos vinculados'}</button></div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -6,28 +6,6 @@ import type {
|
||||
PageMeta,
|
||||
} from './api';
|
||||
|
||||
export interface InventoryBrowserDepartment {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
commonName: string | null;
|
||||
type: { id: string; code: string; name: string };
|
||||
informationStatus: AssetInformationStatus;
|
||||
operationalStatus: AssetOperationalStatus;
|
||||
areaCount: number;
|
||||
childrenCount: number;
|
||||
}
|
||||
|
||||
export interface InventoryBrowserCompany {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
commonName: string | null;
|
||||
type: { id: string; code: string; name: string };
|
||||
informationStatus: AssetInformationStatus;
|
||||
areaCount: number;
|
||||
}
|
||||
|
||||
export interface InventoryBrowserArea {
|
||||
id: string;
|
||||
code: string;
|
||||
@@ -53,7 +31,6 @@ export interface InventoryBrowserItem {
|
||||
isInventoryInstance: boolean;
|
||||
inventoryFamily: { id: string; code: string; name: string; level: string } | null;
|
||||
childrenCount: number;
|
||||
findingCount: number;
|
||||
hasGeometry: boolean;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -108,27 +85,12 @@ function queryString(params: InventoryQuery): string {
|
||||
return query.size ? `?${query}` : '';
|
||||
}
|
||||
|
||||
export function listInventory(params: InventoryQuery = {}) {
|
||||
export function listRealInventory(params: InventoryQuery = {}) {
|
||||
return apiRequest<{ data: InventoryListItem[]; meta: PageMeta }>(
|
||||
`/inventory-browser/items${queryString(params)}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Compatibility alias while old call sites are removed.
|
||||
export const listRealInventory = listInventory;
|
||||
|
||||
export function listInventoryDepartments(params: InventoryQuery = {}) {
|
||||
return apiRequest<{ data: InventoryBrowserDepartment[]; meta: { count: number } }>(
|
||||
`/inventory-browser/departments${queryString(params)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function listInventoryCompanies(params: InventoryQuery = {}) {
|
||||
return apiRequest<{ data: InventoryBrowserCompany[]; meta: { count: number } }>(
|
||||
`/inventory-browser/companies${queryString(params)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function listInventoryAreas(params: InventoryQuery = {}) {
|
||||
return apiRequest<{ data: InventoryBrowserArea[]; meta: { count: number } }>(
|
||||
`/inventory-browser/areas${queryString(params)}`,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { apiRequest } from './api';
|
||||
|
||||
export type InventoryStructureKind = 'EMPRESA' | 'DEPARTAMENTO' | 'AREA' | 'YACIMIENTO' | 'INSTALACION' | 'SUBINSTALACION';
|
||||
export type InventoryStructureKind = 'EMPRESA' | 'AREA' | 'YACIMIENTO' | 'INSTALACION' | 'SUBINSTALACION';
|
||||
|
||||
export interface InventoryFamily {
|
||||
id: string;
|
||||
|
||||
@@ -7,7 +7,6 @@ import { Alert, LoadingBlock, errorMessage } from '../components/Feedback';
|
||||
import { Icon } from '../components/Icon';
|
||||
import {
|
||||
createAssetAttribute,
|
||||
getFindingCatalogAdmin,
|
||||
listAssetTypes,
|
||||
updateAssetAttribute,
|
||||
} from '../lib/api';
|
||||
@@ -15,12 +14,10 @@ import type {
|
||||
AssetAttributeDataType,
|
||||
AssetAttributeDefinition,
|
||||
AssetType,
|
||||
FindingAdminCatalog,
|
||||
} from '../lib/api';
|
||||
import {
|
||||
createInventoryFamily,
|
||||
listInventoryFamiliesAdmin,
|
||||
replaceInventoryFamilyFindings,
|
||||
updateInventoryFamily,
|
||||
} from '../lib/inventoryStructureApi';
|
||||
import type { InventoryFamily } from '../lib/inventoryStructureApi';
|
||||
@@ -34,19 +31,15 @@ const ATTRIBUTE_TYPES: Array<{ value: AssetAttributeDataType; label: string }> =
|
||||
{ value: 'SELECT', label: 'Lista de opciones' },
|
||||
];
|
||||
|
||||
const EMPTY_FINDING_CATALOG: FindingAdminCatalog = { categories: [], items: [] };
|
||||
|
||||
type CanonicalKind = 'EMPRESA' | 'DEPARTAMENTO' | 'AREA' | 'YACIMIENTO' | 'INSTALACION' | 'SUBINSTALACION';
|
||||
type CanonicalKind = 'EMPRESA' | 'AREA' | 'YACIMIENTO' | 'INSTALACION' | 'SUBINSTALACION';
|
||||
type FamilyEditor = InventoryFamily | 'new' | null;
|
||||
type FamilyFindingMode = 'ASSOCIATED' | 'ALL';
|
||||
|
||||
const LEVELS: Array<{ kind: CanonicalKind; label: string; description: string }> = [
|
||||
{ kind: 'EMPRESA', label: 'Empresa', description: 'Maestro independiente. Se vincula temporalmente a un Área.' },
|
||||
{ kind: 'DEPARTAMENTO', label: 'Departamento', description: 'Raíz territorial de la estructura física.' },
|
||||
{ kind: 'AREA', label: 'Área', description: 'Pertenece obligatoriamente a un Departamento.' },
|
||||
{ kind: 'AREA', label: 'Área', description: 'Raíz territorial de la estructura física.' },
|
||||
{ kind: 'YACIMIENTO', label: 'Yacimiento', description: 'Pertenece a un Área; su nombre puede repetirse en otra Área.' },
|
||||
{ kind: 'INSTALACION', label: 'Instalación', description: 'Instancia dentro de un Yacimiento y con clasificación técnica.' },
|
||||
{ kind: 'SUBINSTALACION', label: 'Subinstalación', description: 'Instancia dentro de una Instalación y con clasificación técnica.' },
|
||||
{ kind: 'INSTALACION', label: 'Instalación', description: 'Instancia física dentro de un Yacimiento y con clasificación técnica.' },
|
||||
{ kind: 'SUBINSTALACION', label: 'Subinstalación', description: 'Instancia física dentro de una Instalación y con clasificación técnica.' },
|
||||
];
|
||||
|
||||
function canonicalType(types: AssetType[], kind: CanonicalKind): AssetType | null {
|
||||
@@ -70,9 +63,7 @@ export function AssetTypesPage() {
|
||||
const canManage = hasPermission('asset_types.manage');
|
||||
const [types, setTypes] = useState<AssetType[]>([]);
|
||||
const [families, setFamilies] = useState<InventoryFamily[]>([]);
|
||||
const [findingCatalog, setFindingCatalog] = useState<FindingAdminCatalog>(EMPTY_FINDING_CATALOG);
|
||||
const [selectedKind, setSelectedKind] = useState<CanonicalKind>('INSTALACION');
|
||||
const [selectedInstallationFamilyId, setSelectedInstallationFamilyId] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
@@ -83,9 +74,6 @@ export function AssetTypesPage() {
|
||||
const [familyName, setFamilyName] = useState('');
|
||||
const [familyParentId, setFamilyParentId] = useState('');
|
||||
const [familyActive, setFamilyActive] = useState(true);
|
||||
const [familyFindingIds, setFamilyFindingIds] = useState<Set<string>>(new Set());
|
||||
const [familyFindingMode, setFamilyFindingMode] = useState<FamilyFindingMode>('ASSOCIATED');
|
||||
const [familyFindingSearch, setFamilyFindingSearch] = useState('');
|
||||
|
||||
const [attributeEditor, setAttributeEditor] = useState<AssetAttributeDefinition | 'new' | null>(null);
|
||||
const [attributeCode, setAttributeCode] = useState('');
|
||||
@@ -98,14 +86,12 @@ export function AssetTypesPage() {
|
||||
const [attributeOrder, setAttributeOrder] = useState(0);
|
||||
|
||||
const load = async () => {
|
||||
const [loadedTypes, loadedFamilies, loadedFindingCatalog] = await Promise.all([
|
||||
const [loadedTypes, loadedFamilies] = await Promise.all([
|
||||
listAssetTypes(),
|
||||
listInventoryFamiliesAdmin(),
|
||||
getFindingCatalogAdmin(),
|
||||
]);
|
||||
setTypes(loadedTypes);
|
||||
setFamilies(loadedFamilies);
|
||||
setFindingCatalog(loadedFindingCatalog);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -115,47 +101,17 @@ export function AssetTypesPage() {
|
||||
const selectedType = canonicalType(types, selectedKind);
|
||||
const installationFamilies = useMemo(() => families.filter((item) => item.level === 'INSTALLATION'), [families]);
|
||||
const subinstallationFamilies = useMemo(() => families.filter((item) => item.level === 'SUBINSTALLATION'), [families]);
|
||||
const visibleSubinstallationFamilies = useMemo(() => subinstallationFamilies.filter((family) =>
|
||||
family.isActive !== false && (!selectedInstallationFamilyId || family.parentFamilyId === selectedInstallationFamilyId),
|
||||
), [subinstallationFamilies, selectedInstallationFamilyId]);
|
||||
|
||||
const activeFindingCategoryIds = useMemo(() => new Set(
|
||||
findingCatalog.categories.filter((category) => category.isActive).map((category) => category.id),
|
||||
), [findingCatalog.categories]);
|
||||
const findingCategoryNames = useMemo(() => new Map(
|
||||
findingCatalog.categories.map((category) => [category.id, category.name]),
|
||||
), [findingCatalog.categories]);
|
||||
const visibleFamilyFindings = useMemo(() => {
|
||||
const needle = familyFindingSearch.trim().toLocaleLowerCase('es-AR');
|
||||
return findingCatalog.items.filter((item) => {
|
||||
if (!item.isActive || !activeFindingCategoryIds.has(item.categoryId)) return false;
|
||||
if (familyFindingMode === 'ASSOCIATED' && !familyFindingIds.has(item.id)) return false;
|
||||
if (!needle) return true;
|
||||
return [item.title, item.code, findingCategoryNames.get(item.categoryId) ?? '']
|
||||
.some((value) => value.toLocaleLowerCase('es-AR').includes(needle));
|
||||
});
|
||||
}, [findingCatalog.items, activeFindingCategoryIds, familyFindingMode, familyFindingIds, familyFindingSearch, findingCategoryNames]);
|
||||
|
||||
const openNewFamily = (level: 'INSTALLATION' | 'SUBINSTALLATION') => {
|
||||
setFamilyEditor('new'); setFamilyLevel(level); setFamilyName('');
|
||||
setFamilyParentId(level === 'SUBINSTALLATION' ? selectedInstallationFamilyId : '');
|
||||
setFamilyActive(true); setFamilyFindingIds(new Set()); setFamilyFindingMode('ASSOCIATED'); setFamilyFindingSearch('');
|
||||
setFamilyEditor('new'); setFamilyLevel(level); setFamilyName(''); setFamilyParentId(''); setFamilyActive(true);
|
||||
setError(''); setSuccess('');
|
||||
};
|
||||
const openFamily = (family: InventoryFamily) => {
|
||||
if (family.level === 'INSTALLATION') setSelectedInstallationFamilyId(family.id);
|
||||
setFamilyEditor(family); setFamilyLevel(family.level); setFamilyName(family.name);
|
||||
setFamilyParentId(family.parentFamilyId ?? ''); setFamilyActive(family.isActive !== false);
|
||||
setFamilyFindingIds(new Set(family.findingItemIds ?? [])); setFamilyFindingMode('ASSOCIATED'); setFamilyFindingSearch('');
|
||||
setError(''); setSuccess('');
|
||||
};
|
||||
|
||||
const toggleFamilyFinding = (id: string) => setFamilyFindingIds((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(id)) next.delete(id); else next.add(id);
|
||||
return next;
|
||||
});
|
||||
|
||||
const saveFamily = async (event: FormEvent) => {
|
||||
event.preventDefault(); setSaving(true); setError(''); setSuccess('');
|
||||
try {
|
||||
@@ -172,11 +128,7 @@ export function AssetTypesPage() {
|
||||
parentFamilyId: familyLevel === 'SUBINSTALLATION' ? familyParentId : null,
|
||||
isActive: familyActive,
|
||||
});
|
||||
await replaceInventoryFamilyFindings(familyEditor.id, {
|
||||
itemIds: [...familyFindingIds],
|
||||
reason: 'Actualización desde Configuración de Inventarios',
|
||||
});
|
||||
setSuccess('Clasificación y Hallazgos asociados actualizados.');
|
||||
setSuccess('Clasificación actualizada.');
|
||||
}
|
||||
await load();
|
||||
setFamilyEditor(null);
|
||||
@@ -240,34 +192,32 @@ export function AssetTypesPage() {
|
||||
<div>
|
||||
<span className="eyebrow">ADMINISTRACIÓN</span>
|
||||
<h1>Configuración de Inventarios</h1>
|
||||
<p>Administrá la estructura, los tipos de Instalación/Subinstalación, sus Hallazgos y las columnas de información.</p>
|
||||
<p>Administrá la estructura, los tipos de Instalación/Subinstalación y las columnas que se completan en oficina o desde la APK.</p>
|
||||
</div>
|
||||
{canManage && <Link className="button primary" to="/inventarios/nuevo"><Icon name="plus" />Agregar registro</Link>}
|
||||
</div>
|
||||
{error && <Alert>{error}</Alert>}{success && <Alert type="success">{success}</Alert>}
|
||||
|
||||
<div className="panel" style={{ marginBottom: 18 }}>
|
||||
<div className="panel-heading"><div><span className="eyebrow">MODELO VIGENTE</span><h2>Estructura física</h2><p className="section-copy">Cada nivel tiene un único padre estructural. Empresa queda como maestro independiente y se relaciona con Área.</p></div></div>
|
||||
<div className="panel-heading"><div><span className="eyebrow">MODELO VIGENTE</span><h2>Estructura física</h2><p className="section-copy">Empresa no es padre del Área. La Operadora/Concesionaria se vincula al Área con vigencia temporal.</p></div></div>
|
||||
<div className="asset-browser-levels" aria-label="Estructura de Inventarios">
|
||||
<div><span>1</span><strong>Departamento</strong><small>raíz territorial</small></div><i>›</i>
|
||||
<div><span>2</span><strong>Área</strong><small>dentro del Departamento</small></div><i>›</i>
|
||||
<div><span>3</span><strong>Yacimiento</strong><small>dentro del Área</small></div><i>›</i>
|
||||
<div><span>4</span><strong>Instalación</strong><small>clasificación técnica</small></div><i>›</i>
|
||||
<div><span>5</span><strong>Subinstalación</strong><small>clasificación técnica</small></div>
|
||||
<div><span>1</span><strong>Área</strong><small>raíz territorial</small></div><i>›</i>
|
||||
<div><span>2</span><strong>Yacimiento</strong><small>dentro del Área</small></div><i>›</i>
|
||||
<div><span>3</span><strong>Instalación</strong><small>inventario real</small></div><i>›</i>
|
||||
<div><span>4</span><strong>Subinstalación</strong><small>inventario real</small></div>
|
||||
</div>
|
||||
<div className="temporal-notice" style={{ marginTop: 14 }}><Icon name="users" /><p><strong>Empresa:</strong> maestro independiente. Cambiar la operadora de un Área no mueve ni reescribe la estructura física.</p></div>
|
||||
<div className="temporal-notice" style={{ marginTop: 14 }}><Icon name="users" /><p><strong>Empresa:</strong> maestro independiente. Puede cambiar la Operadora de un Área sin mover ni reescribir Yacimientos, Instalaciones o Subinstalaciones.</p></div>
|
||||
</div>
|
||||
|
||||
<div className="dashboard-grid" style={{ alignItems: 'start' }}>
|
||||
<article className="panel">
|
||||
<div className="panel-heading"><div><span className="eyebrow">CLASIFICACIONES</span><h2>Tipos de Instalación</h2><p className="section-copy">Tocá una Instalación para filtrar sus Subinstalaciones y editar sus Hallazgos.</p></div>{canManage && <button className="button primary" onClick={() => openNewFamily('INSTALLATION')}><Icon name="plus" />Nuevo tipo</button>}</div>
|
||||
<div className="attribute-list">{installationFamilies.filter((family) => family.isActive !== false).map((family) => <button type="button" className={`attribute-card ${selectedInstallationFamilyId === family.id ? 'active' : ''}`} key={family.id} onClick={() => openFamily(family)}><span className="asset-symbol"><Icon name="layers" size={16} /></span><span><strong>{family.name}</strong><small>{family.findingCount ?? 0} Hallazgos asociados</small></span><span className="tag">{family.assetCount ?? 0} registros</span><Icon name="chevron" /></button>)}</div>
|
||||
<div className="panel-heading"><div><span className="eyebrow">CLASIFICACIONES</span><h2>Tipos de Instalación</h2><p className="section-copy">Precargados desde final_modelov2.xlsx y ampliables por Hidrocarburos.</p></div>{canManage && <button className="button primary" onClick={() => openNewFamily('INSTALLATION')}><Icon name="plus" />Nuevo tipo</button>}</div>
|
||||
<div className="attribute-list">{installationFamilies.filter((family) => family.isActive !== false).map((family) => <button type="button" className="attribute-card" key={family.id} onClick={() => openFamily(family)}><span className="asset-symbol"><Icon name="layers" size={16} /></span><span><strong>{family.name}</strong><small>{family.sourceReference?.startsWith('F5:final_modelov2.xlsx') ? 'Precargado desde fuente autorizada' : 'Agregado por Hidrocarburos'} · {family.findingCount ?? 0} Hallazgos</small></span><span className="tag">{family.assetCount ?? 0} registros</span><Icon name="chevron" /></button>)}</div>
|
||||
</article>
|
||||
|
||||
<article className="panel">
|
||||
<div className="panel-heading"><div><span className="eyebrow">CLASIFICACIONES</span><h2>Tipos de Subinstalación</h2><p className="section-copy">Mostrá todas o sólo las que pertenecen a una Instalación.</p></div>{canManage && <button className="button primary" onClick={() => openNewFamily('SUBINSTALLATION')}><Icon name="plus" />Nuevo tipo</button>}</div>
|
||||
<label className="field" style={{ marginBottom: 14 }}><span>Filtrar por tipo de Instalación</span><SearchableSelect value={selectedInstallationFamilyId} onChange={(event) => setSelectedInstallationFamilyId(event.target.value)}><option value="">Todas las Instalaciones</option>{installationFamilies.filter((family) => family.isActive !== false).map((family) => <option key={family.id} value={family.id}>{family.name}</option>)}</SearchableSelect></label>
|
||||
{visibleSubinstallationFamilies.length === 0 ? <div className="inline-empty">{selectedInstallationFamilyId ? 'Esta Instalación todavía no tiene tipos de Subinstalación asociados.' : 'No hay tipos de Subinstalación configurados.'}</div> : <div className="attribute-list" style={{ maxHeight: 560, overflow: 'auto' }}>{visibleSubinstallationFamilies.map((family) => <button type="button" className="attribute-card" key={family.id} onClick={() => openFamily(family)}><span className="asset-symbol"><Icon name="layers" size={16} /></span><span><strong>{family.name}</strong><small>{family.parentFamilyName ?? 'Sin Instalación padre'} · {family.findingCount ?? 0} Hallazgos asociados</small></span><span className="tag">{family.assetCount ?? 0} registros</span><Icon name="chevron" /></button>)}</div>}
|
||||
<div className="panel-heading"><div><span className="eyebrow">CLASIFICACIONES</span><h2>Tipos de Subinstalación</h2><p className="section-copy">Cada tipo queda asociado a un tipo de Instalación.</p></div>{canManage && <button className="button primary" onClick={() => openNewFamily('SUBINSTALLATION')}><Icon name="plus" />Nuevo tipo</button>}</div>
|
||||
<div className="attribute-list" style={{ maxHeight: 560, overflow: 'auto' }}>{subinstallationFamilies.filter((family) => family.isActive !== false).map((family) => <button type="button" className="attribute-card" key={family.id} onClick={() => openFamily(family)}><span className="asset-symbol"><Icon name="layers" size={16} /></span><span><strong>{family.name}</strong><small>{family.parentFamilyName ?? 'Sin Instalación padre'} · {family.findingCount ?? 0} Hallazgos</small></span><span className="tag">{family.assetCount ?? 0} registros</span><Icon name="chevron" /></button>)}</div>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
@@ -278,10 +228,10 @@ export function AssetTypesPage() {
|
||||
{!selectedType ? <Alert>Este nivel todavía no tiene un tipo maestro activo.</Alert> : selectedType.attributes.length === 0 ? <div className="inline-empty">No hay columnas adicionales configuradas para {LEVELS.find((item) => item.kind === selectedKind)?.label}.</div> : <div className="attribute-list">{selectedType.attributes.map((attribute) => <button type="button" className={`attribute-card ${attribute.isActive ? '' : 'disabled'}`} key={attribute.id} onClick={() => openAttribute(attribute)}><span className="attribute-order">{attribute.sortOrder}</span><span><strong>{attribute.name}</strong><small>{attribute.code} · {attributeTypeLabel(attribute.dataType)}{attribute.unit ? ` · ${attribute.unit}` : ''}</small></span><span className="attribute-flags">{attribute.isRequired && <span className="tag">Obligatorio</span>}{!attribute.isActive && <span className="tag">Inactivo</span>}</span><Icon name="chevron" /></button>)}</div>}
|
||||
</article>
|
||||
|
||||
<div className="panel" style={{ marginTop: 18 }}><div className="panel-heading"><div><span className="eyebrow">HALLAZGOS</span><h2>Relación por clasificación</h2><p className="section-copy">Los Hallazgos se pueden revisar y editar directamente dentro de cada tipo. El Catálogo completo sigue disponible para una administración masiva.</p></div><Link className="button secondary" to="/admin/finding-catalog">Abrir Catálogo de hallazgos <Icon name="chevron" /></Link></div></div>
|
||||
<div className="panel" style={{ marginTop: 18 }}><div className="panel-heading"><div><span className="eyebrow">HALLAZGOS</span><h2>Catálogo separado, relación clara</h2><p className="section-copy">Los Hallazgos se crean y editan en su catálogo, y allí se vinculan al tipo de Instalación/Subinstalación correspondiente. OTROS permanece siempre disponible.</p></div><Link className="button secondary" to="/admin/finding-catalog">Abrir Catálogo de hallazgos <Icon name="chevron" /></Link></div></div>
|
||||
|
||||
{familyEditor && <div className="modal-backdrop"><form className="detail-drawer catalog-drawer" onSubmit={saveFamily}><div className="drawer-heading"><div><span className="eyebrow">CLASIFICACIÓN DE INVENTARIO</span><h2>{familyEditor === 'new' ? 'Nuevo tipo' : 'Editar tipo'}</h2></div><button type="button" className="icon-button" onClick={() => setFamilyEditor(null)}>×</button></div><div className="catalog-editor-fields">{familyEditor === 'new' && <label className="field"><span>Nivel</span><SearchableSelect value={familyLevel} onChange={(event) => { setFamilyLevel(event.target.value as 'INSTALLATION' | 'SUBINSTALLATION'); setFamilyParentId(''); }}><option value="INSTALLATION">Instalación</option><option value="SUBINSTALLATION">Subinstalación</option></SearchableSelect></label>}<label className="field"><span>Nombre</span><input value={familyName} onChange={(event) => setFamilyName(event.target.value)} maxLength={240} required placeholder={familyLevel === 'INSTALLATION' ? 'Ej.: Estación, Planta…' : 'Ej.: Tanque, Bomba…'} /></label>{familyLevel === 'SUBINSTALLATION' && <label className="field"><span>Tipo de Instalación padre</span><SearchableSelect value={familyParentId} onChange={(event) => setFamilyParentId(event.target.value)} required><option value="">Seleccionar…</option>{installationFamilies.filter((family) => family.isActive !== false).map((family) => <option value={family.id} key={family.id}>{family.name}</option>)}</SearchableSelect></label>}{familyEditor !== 'new' && <><div className="temporal-notice"><Icon name="alert" /><p><strong>{familyFindingIds.size} Hallazgos asociados.</strong> Se guardan junto con esta clasificación.</p></div><div className="quick-view-row"><button type="button" className={familyFindingMode === 'ASSOCIATED' ? 'active' : ''} onClick={() => setFamilyFindingMode('ASSOCIATED')}>Asociados ({familyFindingIds.size})</button><button type="button" className={familyFindingMode === 'ALL' ? 'active' : ''} onClick={() => setFamilyFindingMode('ALL')}>Agregar o quitar</button></div><label className="field"><span>Buscar Hallazgo</span><input value={familyFindingSearch} onChange={(event) => setFamilyFindingSearch(event.target.value)} placeholder="Título, código o categoría…" /></label>{visibleFamilyFindings.length === 0 ? <div className="inline-empty">{familyFindingMode === 'ASSOCIATED' ? 'No hay Hallazgos asociados. Tocá “Agregar o quitar” para vincularlos.' : 'No hay Hallazgos que coincidan con la búsqueda.'}</div> : <div className="finding-selection-list" style={{ maxHeight: 300, overflow: 'auto' }}>{visibleFamilyFindings.map((item) => familyFindingMode === 'ALL' ? <label className="finding-selection-row" key={item.id}><input type="checkbox" checked={familyFindingIds.has(item.id)} onChange={() => toggleFamilyFinding(item.id)} /><span><strong>{item.title}</strong><small>{findingCategoryNames.get(item.categoryId) ?? 'Catálogo'} · {item.code}</small></span></label> : <div className="finding-selection-row" key={item.id}><span className="asset-symbol"><Icon name="check" size={14} /></span><span><strong>{item.title}</strong><small>{findingCategoryNames.get(item.categoryId) ?? 'Catálogo'} · {item.code}</small></span></div>)}</div>}<Link className="button secondary" to={`/admin/finding-catalog?familyId=${familyEditor.id}`}>Abrir en Catálogo completo <Icon name="chevron" /></Link><label className="check-row"><input type="checkbox" checked={familyActive} onChange={(event) => setFamilyActive(event.target.checked)} /><span><strong>Tipo disponible</strong><small>Al desactivarlo deja de ofrecerse en nuevas altas.</small></span></label></>}</div><div className="form-actions"><button type="button" className="button secondary" onClick={() => setFamilyEditor(null)}>Cancelar</button><button className="button primary" disabled={saving || !familyName.trim() || (familyLevel === 'SUBINSTALLATION' && !familyParentId)}>{saving ? 'Guardando…' : 'Guardar tipo y Hallazgos'}</button></div></form></div>}
|
||||
{familyEditor && <div className="modal-backdrop"><form className="detail-drawer catalog-drawer" onSubmit={saveFamily}><div className="drawer-heading"><div><span className="eyebrow">CLASIFICACIÓN DE INVENTARIO</span><h2>{familyEditor === 'new' ? 'Nuevo tipo' : 'Editar tipo'}</h2></div><button type="button" className="icon-button" onClick={() => setFamilyEditor(null)}>×</button></div><div className="catalog-editor-fields">{familyEditor === 'new' && <label className="field"><span>Nivel</span><SearchableSelect value={familyLevel} onChange={(event) => { setFamilyLevel(event.target.value as 'INSTALLATION' | 'SUBINSTALLATION'); setFamilyParentId(''); }}><option value="INSTALLATION">Instalación</option><option value="SUBINSTALLATION">Subinstalación</option></SearchableSelect></label>}<label className="field"><span>Nombre</span><input value={familyName} onChange={(event) => setFamilyName(event.target.value)} maxLength={240} required placeholder={familyLevel === 'INSTALLATION' ? 'Ej.: Estación, Planta…' : 'Ej.: Tanque, Bomba…'} /></label>{familyLevel === 'SUBINSTALLATION' && <label className="field"><span>Tipo de Instalación padre</span><SearchableSelect value={familyParentId} onChange={(event) => setFamilyParentId(event.target.value)} required><option value="">Seleccionar…</option>{installationFamilies.filter((family) => family.isActive !== false).map((family) => <option value={family.id} key={family.id}>{family.name}</option>)}</SearchableSelect></label>}{familyEditor !== 'new' && <label className="check-row"><input type="checkbox" checked={familyActive} onChange={(event) => setFamilyActive(event.target.checked)} /><span><strong>Tipo disponible</strong><small>Al desactivarlo deja de ofrecerse en nuevas altas, sin borrar registros históricos.</small></span></label>}</div><div className="form-actions"><button type="button" className="button secondary" onClick={() => setFamilyEditor(null)}>Cancelar</button><button className="button primary" disabled={saving || !familyName.trim() || (familyLevel === 'SUBINSTALLATION' && !familyParentId)}>{saving ? 'Guardando…' : 'Guardar tipo'}</button></div></form></div>}
|
||||
|
||||
{attributeEditor && selectedType && <div className="modal-backdrop"><form className="detail-drawer catalog-drawer" onSubmit={saveAttribute}><div className="drawer-heading"><div><span className="eyebrow">COLUMNA DE {LEVELS.find((item) => item.kind === selectedKind)?.label.toUpperCase()}</span><h2>{attributeEditor === 'new' ? 'Nueva columna' : 'Editar columna'}</h2></div><button type="button" className="icon-button" onClick={() => setAttributeEditor(null)}>×</button></div><div className="catalog-editor-fields"><label className="field"><span>Nombre visible</span><input value={attributeName} onChange={(event) => { setAttributeName(event.target.value); if (attributeEditor === 'new') setAttributeCode(attributeCodeFromName(event.target.value)); }} maxLength={160} required /></label><label className="field"><span>Código interno</span><input value={attributeCode} onChange={(event) => setAttributeCode(event.target.value.toLowerCase())} disabled={attributeEditor !== 'new'} maxLength={80} required pattern="[a-z][a-z0-9_]*" /></label><label className="field"><span>Tipo de dato</span><SearchableSelect value={attributeType} onChange={(event) => setAttributeType(event.target.value as AssetAttributeDataType)}>{ATTRIBUTE_TYPES.map((item) => <option value={item.value} key={item.value}>{item.label}</option>)}</SearchableSelect></label>{attributeType === 'SELECT' && <label className="field"><span>Opciones</span><textarea rows={5} value={attributeOptions} onChange={(event) => setAttributeOptions(event.target.value)} placeholder="Una opción por línea" /></label>}<label className="field"><span>Unidad <em>opcional</em></span><input value={attributeUnit} onChange={(event) => setAttributeUnit(event.target.value)} maxLength={40} /></label><label className="field"><span>Orden</span><input type="number" value={attributeOrder} onChange={(event) => setAttributeOrder(Number(event.target.value))} min={0} max={10000} /></label><label className="check-row"><input type="checkbox" checked={attributeRequired} onChange={(event) => setAttributeRequired(event.target.checked)} /><span><strong>Campo obligatorio</strong><small>Debe completarse cuando se registra este nivel.</small></span></label>{attributeEditor !== 'new' && <label className="check-row"><input type="checkbox" checked={attributeActive} onChange={(event) => setAttributeActive(event.target.checked)} /><span><strong>Columna activa</strong><small>Desactivarla conserva los datos actuales.</small></span></label>}</div><div className="form-actions"><button type="button" className="button secondary" onClick={() => setAttributeEditor(null)}>Cancelar</button><button className="button primary" disabled={saving || !attributeName.trim() || !attributeCode}>{saving ? 'Guardando…' : 'Guardar columna'}</button></div></form></div>}
|
||||
{attributeEditor && selectedType && <div className="modal-backdrop"><form className="detail-drawer catalog-drawer" onSubmit={saveAttribute}><div className="drawer-heading"><div><span className="eyebrow">COLUMNA DE {LEVELS.find((item) => item.kind === selectedKind)?.label.toUpperCase()}</span><h2>{attributeEditor === 'new' ? 'Nueva columna' : 'Editar columna'}</h2></div><button type="button" className="icon-button" onClick={() => setAttributeEditor(null)}>×</button></div><div className="catalog-editor-fields"><label className="field"><span>Nombre visible</span><input value={attributeName} onChange={(event) => { setAttributeName(event.target.value); if (attributeEditor === 'new') setAttributeCode(attributeCodeFromName(event.target.value)); }} maxLength={160} required /></label><label className="field"><span>Código interno</span><input value={attributeCode} onChange={(event) => setAttributeCode(event.target.value.toLowerCase())} disabled={attributeEditor !== 'new'} maxLength={80} required pattern="[a-z][a-z0-9_]*" /></label><label className="field"><span>Tipo de dato</span><SearchableSelect value={attributeType} onChange={(event) => setAttributeType(event.target.value as AssetAttributeDataType)}>{ATTRIBUTE_TYPES.map((item) => <option value={item.value} key={item.value}>{item.label}</option>)}</SearchableSelect></label>{attributeType === 'SELECT' && <label className="field"><span>Opciones</span><textarea rows={5} value={attributeOptions} onChange={(event) => setAttributeOptions(event.target.value)} placeholder="Una opción por línea" /></label>}<label className="field"><span>Unidad <em>opcional</em></span><input value={attributeUnit} onChange={(event) => setAttributeUnit(event.target.value)} maxLength={40} /></label><label className="field"><span>Orden</span><input type="number" value={attributeOrder} onChange={(event) => setAttributeOrder(Number(event.target.value))} min={0} max={10000} /></label><label className="check-row"><input type="checkbox" checked={attributeRequired} onChange={(event) => setAttributeRequired(event.target.checked)} /><span><strong>Campo obligatorio</strong><small>Debe completarse cuando se registra este nivel.</small></span></label>{attributeEditor !== 'new' && <label className="check-row"><input type="checkbox" checked={attributeActive} onChange={(event) => setAttributeActive(event.target.checked)} /><span><strong>Columna activa</strong><small>Desactivarla conserva datos históricos.</small></span></label>}</div><div className="form-actions"><button type="button" className="button secondary" onClick={() => setAttributeEditor(null)}>Cancelar</button><button className="button primary" disabled={saving || !attributeName.trim() || !attributeCode}>{saving ? 'Guardando…' : 'Guardar columna'}</button></div></form></div>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import type {
|
||||
AssetType,
|
||||
PageMeta,
|
||||
} from '../lib/api';
|
||||
import { listInventory } from '../lib/inventoryBrowserApi';
|
||||
import { listRealInventory } from '../lib/inventoryBrowserApi';
|
||||
import type { InventoryListItem, InventoryQuery } from '../lib/inventoryBrowserApi';
|
||||
import { formatDate } from '../lib/format';
|
||||
|
||||
@@ -60,19 +60,24 @@ export function AssetsPage() {
|
||||
const effectiveOperationalStatus = quick === 'out' ? 'OUT_OF_SERVICE' as AssetOperationalStatus : operationalStatus;
|
||||
|
||||
useEffect(() => {
|
||||
listAssetTypes().then((data) => setTypes(data.filter((type) =>
|
||||
type.operationalRole === 'COMPANY'
|
||||
|| ['departamento','area','yacimiento','instalacion','subinstalacion'].includes(type.code.toLowerCase()),
|
||||
))).catch(() => undefined);
|
||||
listAssetTypes().then((data) => setTypes(data.filter((type) => ['instalacion','subinstalacion'].includes(type.code.toLowerCase())))).catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (view !== 'list') return;
|
||||
setLoading(true); setError('');
|
||||
listInventory({
|
||||
page, pageSize: 25, search, typeId, status,
|
||||
setLoading(true);
|
||||
setError('');
|
||||
listRealInventory({
|
||||
page,
|
||||
pageSize: 25,
|
||||
search,
|
||||
typeId,
|
||||
status,
|
||||
operationalStatus: effectiveOperationalStatus,
|
||||
operationalAreaId, operatorCompanyId, needsValidation, hasGeometry,
|
||||
operationalAreaId,
|
||||
operatorCompanyId,
|
||||
needsValidation,
|
||||
hasGeometry,
|
||||
})
|
||||
.then((response) => { setAssets(response.data); setMeta(response.meta); })
|
||||
.catch((requestError) => setError(errorMessage(requestError)))
|
||||
@@ -80,26 +85,36 @@ export function AssetsPage() {
|
||||
}, [view, page, search, typeId, status, effectiveOperationalStatus, operationalAreaId, operatorCompanyId, needsValidation, hasGeometry]);
|
||||
|
||||
const filters: InventoryQuery = useMemo(() => ({
|
||||
search, typeId, status, operationalStatus: effectiveOperationalStatus,
|
||||
operationalAreaId, operatorCompanyId, needsValidation, hasGeometry,
|
||||
search,
|
||||
typeId,
|
||||
status,
|
||||
operationalStatus: effectiveOperationalStatus,
|
||||
operationalAreaId,
|
||||
operatorCompanyId,
|
||||
needsValidation,
|
||||
hasGeometry,
|
||||
}), [search, typeId, status, effectiveOperationalStatus, operationalAreaId, operatorCompanyId, needsValidation, hasGeometry]);
|
||||
|
||||
const update = (changes: Record<string, string | null>) => {
|
||||
const next = new URLSearchParams(urlParams);
|
||||
Object.entries(changes).forEach(([key, value]) => value ? next.set(key, value) : next.delete(key));
|
||||
next.delete('page'); setUrlParams(next);
|
||||
next.delete('page');
|
||||
setUrlParams(next);
|
||||
};
|
||||
const applySearch = (event: FormEvent) => { event.preventDefault(); update({ search: draftSearch.trim() || null }); };
|
||||
const setQuick = (key: string) => update({ quick: key === 'all' ? null : key, operationalStatus: key === 'out' ? null : rawOperationalStatus || null });
|
||||
const clearFilters = () => {
|
||||
const next = new URLSearchParams();
|
||||
if (view === 'list') next.set('view', 'list');
|
||||
const parentId=urlParams.get('parentId'); if (parentId) next.set('parentId',parentId);
|
||||
setDraftSearch(''); setUrlParams(next);
|
||||
const parentId=urlParams.get('parentId');
|
||||
if (parentId) next.set('parentId',parentId);
|
||||
setDraftSearch('');
|
||||
setUrlParams(next);
|
||||
};
|
||||
const setPage = (value: number) => {
|
||||
const next = new URLSearchParams(urlParams);
|
||||
value > 1 ? next.set('page', String(value)) : next.delete('page'); setUrlParams(next);
|
||||
value > 1 ? next.set('page', String(value)) : next.delete('page');
|
||||
setUrlParams(next);
|
||||
};
|
||||
const advancedActive = Boolean(typeId || status || rawOperationalStatus);
|
||||
|
||||
@@ -108,7 +123,7 @@ export function AssetsPage() {
|
||||
<div>
|
||||
<span className="eyebrow">INVENTARIOS</span>
|
||||
<h1>Inventarios</h1>
|
||||
<p>Todos los registros: Departamento → Área → Yacimiento → Instalación → Subinstalación, más el maestro independiente de Empresas.</p>
|
||||
<p>Instancias reales registradas en campo, organizadas por Área → Yacimiento → Instalación → Subinstalación.</p>
|
||||
</div>
|
||||
<PermissionGate permission="assets.create"><Link className="button primary" to="/inventarios/nuevo"><Icon name="plus" />Nuevo registro</Link></PermissionGate>
|
||||
</div>
|
||||
@@ -118,7 +133,7 @@ export function AssetsPage() {
|
||||
<div className="asset-center-controls">
|
||||
<form className="asset-center-search" onSubmit={applySearch}>
|
||||
<Icon name="search" />
|
||||
<input value={draftSearch} onChange={(event) => setDraftSearch(event.target.value)} placeholder="Buscar por nombre, código o identificación…" />
|
||||
<input value={draftSearch} onChange={(event) => setDraftSearch(event.target.value)} placeholder="Buscar Inventario, código o identificación…" />
|
||||
<button className="button primary" type="submit">Buscar</button>
|
||||
</form>
|
||||
<div className="quick-view-row" aria-label="Vistas rápidas">
|
||||
@@ -126,7 +141,7 @@ export function AssetsPage() {
|
||||
{view === 'list' && <button type="button" className={advancedOpen || advancedActive ? 'advanced active' : 'advanced'} onClick={() => setAdvancedOpen((current) => !current)}>Más filtros</button>}
|
||||
</div>
|
||||
{view === 'list' && (advancedOpen || advancedActive) && <div className="advanced-filter-panel">
|
||||
<label className="field compact-field"><span>Nivel</span><SearchableSelect value={typeId} onChange={(event) => update({ typeId: event.target.value || null })}><option value="">Todos los niveles</option>{types.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}</SearchableSelect></label>
|
||||
<label className="field compact-field"><span>Nivel</span><SearchableSelect value={typeId} onChange={(event) => update({ typeId: event.target.value || null })}><option value="">Instalaciones y Subinstalaciones</option>{types.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}</SearchableSelect></label>
|
||||
<label className="field compact-field"><span>Estado del dato</span><SearchableSelect value={status} onChange={(event) => update({ status: event.target.value || null })}><option value="">Todos</option>{ASSET_STATUSES.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</SearchableSelect></label>
|
||||
<label className="field compact-field"><span>Estado operativo</span><SearchableSelect value={rawOperationalStatus} onChange={(event) => update({ operationalStatus: event.target.value || null, quick: quick === 'out' ? null : quick === 'all' ? null : quick })}><option value="">Todos</option>{ASSET_OPERATIONAL_STATUSES.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</SearchableSelect></label>
|
||||
<button type="button" className="button text filter-clear" onClick={clearFilters}>Limpiar filtros</button>
|
||||
@@ -137,16 +152,16 @@ export function AssetsPage() {
|
||||
{view === 'hierarchy'
|
||||
? <AssetHierarchyView filters={filters} />
|
||||
: loading
|
||||
? <LoadingBlock label="Cargando Inventarios…" />
|
||||
? <LoadingBlock label="Cargando Inventario real…" />
|
||||
: assets.length === 0
|
||||
? <EmptyState title="Todavía no hay registros" text="La base está lista para comenzar la carga manual desde Departamento." />
|
||||
? <EmptyState title="Todavía no hay Inventario real" text="Las Áreas y Yacimientos precargados son contexto. Las Instalaciones/Subinstalaciones aparecerán aquí cuando sean registradas realmente." />
|
||||
: <div className="table-panel compact-assets-table">
|
||||
<div className="table-summary"><strong>{meta.total} registro{meta.total === 1 ? '' : 's'}</strong><span>Página {meta.page} de {Math.max(meta.totalPages, 1)}</span></div>
|
||||
<div className="table-scroll"><table><thead><tr><th>Registro</th><th>Nivel</th><th>Ubicación / Operadora</th><th>Estado</th><th>Actualizado</th><th aria-label="Acciones" /></tr></thead><tbody>
|
||||
<div className="table-summary"><strong>{meta.total} instancia{meta.total === 1 ? '' : 's'} real{meta.total === 1 ? '' : 'es'}</strong><span>Página {meta.page} de {Math.max(meta.totalPages, 1)}</span></div>
|
||||
<div className="table-scroll"><table><thead><tr><th>Inventario</th><th>Nivel</th><th>Área / Operadora vigente</th><th>Estado</th><th>Actualizado</th><th aria-label="Acciones" /></tr></thead><tbody>
|
||||
{assets.map((asset) => <tr key={asset.id}>
|
||||
<td><div className="asset-cell"><span className="asset-symbol"><Icon name="layers" size={16} /></span><div><Link to={`/inventarios/${asset.id}`} className="table-primary">{asset.name}</Link><small>{asset.code}{asset.parent ? ` · en ${asset.parent.name}` : ''}</small></div></div></td>
|
||||
<td><span className="tag">{asset.type.name}</span></td>
|
||||
<td>{asset.operationalArea ? <span><strong className="table-primary">{asset.operationalArea.name}</strong><small className="cell-subtext">{asset.operatorCompany?.name ?? 'Sin operadora vigente'}</small></span> : asset.operatorCompany ? <span>{asset.operatorCompany.name}</span> : <span className="muted">{asset.parent?.name ?? 'Raíz / maestro independiente'}</span>}</td>
|
||||
<td>{asset.operationalArea ? <span><strong className="table-primary">{asset.operationalArea.name}</strong><small className="cell-subtext">{asset.operatorCompany?.name ?? 'Sin operadora vigente'}</small></span> : <span className="muted">Sin Área</span>}</td>
|
||||
<td><div className="dual-status"><span className={`status-badge ${assetStatusClass(asset.informationStatus)}`}>{assetStatusLabel(asset.informationStatus)}</span><small>{assetOperationalStatusLabel(asset.operationalStatus)}</small></div></td>
|
||||
<td>{formatDate(asset.updatedAt)}</td>
|
||||
<td className="action-cell"><Link className="icon-button" to={`/inventarios/${asset.id}`} aria-label={`Abrir ${asset.name}`}><Icon name="chevron" /></Link></td>
|
||||
|
||||
@@ -18,31 +18,22 @@ import type {
|
||||
InventoryStructureParent,
|
||||
} from '../lib/inventoryStructureApi';
|
||||
|
||||
const KINDS: Array<{ kind: InventoryStructureKind; label: string }> = [
|
||||
{ kind: 'DEPARTAMENTO', label: 'Departamento' },
|
||||
{ kind: 'AREA', label: 'Área' },
|
||||
{ kind: 'YACIMIENTO', label: 'Yacimiento' },
|
||||
{ kind: 'INSTALACION', label: 'Instalación' },
|
||||
{ kind: 'SUBINSTALACION', label: 'Subinstalación' },
|
||||
{ kind: 'EMPRESA', label: 'Empresa' },
|
||||
const STRUCTURE_KINDS: Array<{ kind: InventoryStructureKind; label: string; help: string; step: number }> = [
|
||||
{ kind: 'AREA', label: 'Área', help: 'Nivel territorial raíz.', step: 1 },
|
||||
{ kind: 'YACIMIENTO', label: 'Yacimiento', help: 'Debe pertenecer a un Área.', step: 2 },
|
||||
{ kind: 'INSTALACION', label: 'Instalación', help: 'Debe pertenecer a un Yacimiento.', step: 3 },
|
||||
{ kind: 'SUBINSTALACION', label: 'Subinstalación', help: 'Debe pertenecer a una Instalación.', step: 4 },
|
||||
];
|
||||
|
||||
const childKindByParentType: Record<string, InventoryStructureKind | undefined> = {
|
||||
departamento: 'AREA',
|
||||
area: 'YACIMIENTO',
|
||||
yacimiento: 'INSTALACION',
|
||||
instalacion: 'SUBINSTALACION',
|
||||
};
|
||||
|
||||
const parentLabelByKind: Partial<Record<InventoryStructureKind,string>> = {
|
||||
AREA:'Departamento',
|
||||
YACIMIENTO:'Área',
|
||||
INSTALACION:'Yacimiento',
|
||||
SUBINSTALACION:'Instalación',
|
||||
};
|
||||
|
||||
function kindLabel(kind: InventoryStructureKind) {
|
||||
return KINDS.find((item) => item.kind===kind)?.label ?? kind;
|
||||
function kindLabel(kind: InventoryStructureKind): string {
|
||||
if (kind === 'EMPRESA') return 'Empresa';
|
||||
return STRUCTURE_KINDS.find((item) => item.kind === kind)?.label ?? kind;
|
||||
}
|
||||
|
||||
export function InventoryCreatePage() {
|
||||
@@ -50,14 +41,14 @@ export function InventoryCreatePage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const contextParentId = searchParams.get('parentId');
|
||||
const [options, setOptions] = useState<InventoryStructureOptions | null>(null);
|
||||
const [kind, setKind] = useState<InventoryStructureKind>('DEPARTAMENTO');
|
||||
const [kind, setKind] = useState<InventoryStructureKind>('AREA');
|
||||
const [parents, setParents] = useState<InventoryStructureParent[]>([]);
|
||||
const [parentSearch, setParentSearch] = useState('');
|
||||
const [parentId, setParentId] = useState('');
|
||||
const [familyId, setFamilyId] = useState('');
|
||||
const [familyFindings, setFamilyFindings] = useState<InventoryFamilyFindings | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [commonName, setCommonName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -71,113 +62,224 @@ export function InventoryCreatePage() {
|
||||
if (contextParentId) {
|
||||
const parent = await getAsset(contextParentId);
|
||||
const inferred = childKindByParentType[parent.type.code.toLowerCase()];
|
||||
if (inferred) { setKind(inferred); setParentId(parent.id); }
|
||||
if (inferred) {
|
||||
setKind(inferred);
|
||||
setParentId(parent.id);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((requestError) => setError(errorMessage(requestError)))
|
||||
.finally(() => setLoading(false));
|
||||
}, [contextParentId]);
|
||||
|
||||
const requiresParent = Boolean(parentLabelByKind[kind]);
|
||||
const requiresFamily = kind === 'INSTALACION' || kind === 'SUBINSTALACION';
|
||||
const parentLabel = parentLabelByKind[kind] ?? '';
|
||||
|
||||
useEffect(() => {
|
||||
if (!requiresParent) { setParents([]); setParentId(''); return; }
|
||||
if (kind === 'AREA' || kind === 'EMPRESA') {
|
||||
setParents([]);
|
||||
setParentId('');
|
||||
return;
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
listInventoryStructureParents(kind,parentSearch)
|
||||
listInventoryStructureParents(kind, parentSearch)
|
||||
.then((loaded) => {
|
||||
setParents(loaded);
|
||||
if (contextParentId && loaded.some((item) => item.id===contextParentId)) setParentId(contextParentId);
|
||||
if (contextParentId && loaded.some((item) => item.id === contextParentId)) {
|
||||
setParentId(contextParentId);
|
||||
}
|
||||
})
|
||||
.catch((requestError) => setError(errorMessage(requestError)));
|
||||
},150);
|
||||
}, 180);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [kind,parentSearch,contextParentId,requiresParent]);
|
||||
}, [kind, parentSearch, contextParentId]);
|
||||
|
||||
const selectedParent = parents.find((item) => item.id===parentId) ?? null;
|
||||
const selectedParent = parents.find((item) => item.id === parentId) ?? null;
|
||||
const families = useMemo(() => {
|
||||
if (!options) return [] as InventoryFamily[];
|
||||
if (kind==='INSTALACION') return options.installationFamilies;
|
||||
if (kind==='SUBINSTALACION') {
|
||||
const parentFamilyId=selectedParent?.inventoryFamily?.id;
|
||||
return parentFamilyId ? options.subinstallationFamilies.filter((item)=>item.parentFamilyId===parentFamilyId) : [];
|
||||
if (kind === 'INSTALACION') return options.installationFamilies;
|
||||
if (kind === 'SUBINSTALACION') {
|
||||
const parentFamilyId = selectedParent?.inventoryFamily?.id;
|
||||
return parentFamilyId
|
||||
? options.subinstallationFamilies.filter((item) => item.parentFamilyId === parentFamilyId)
|
||||
: [];
|
||||
}
|
||||
return [];
|
||||
},[options,kind,selectedParent]);
|
||||
const selectedFamily=families.find((item)=>item.id===familyId) ?? null;
|
||||
}, [options, kind, selectedParent]);
|
||||
const selectedFamily = families.find((item) => item.id === familyId) ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!familyId) { setFamilyFindings(null); return; }
|
||||
getInventoryFamilyFindings(familyId).then(setFamilyFindings).catch((requestError)=>setError(errorMessage(requestError)));
|
||||
},[familyId]);
|
||||
if (!familyId) {
|
||||
setFamilyFindings(null);
|
||||
return;
|
||||
}
|
||||
getInventoryFamilyFindings(familyId)
|
||||
.then(setFamilyFindings)
|
||||
.catch((requestError) => setError(errorMessage(requestError)));
|
||||
}, [familyId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!requiresFamily) setFamilyId('');
|
||||
if (kind==='SUBINSTALACION' && familyId && !families.some((item)=>item.id===familyId)) setFamilyId('');
|
||||
},[kind,requiresFamily,families,familyId]);
|
||||
if (kind !== 'INSTALACION' && kind !== 'SUBINSTALACION') setFamilyId('');
|
||||
if (kind === 'SUBINSTALACION' && familyId && !families.some((item) => item.id === familyId)) setFamilyId('');
|
||||
}, [kind, familyId, families]);
|
||||
|
||||
const changeKind=(next:InventoryStructureKind) => {
|
||||
setKind(next); setParentId(''); setParentSearch(''); setFamilyId(''); setFamilyFindings(null); setError('');
|
||||
const chooseKind = (next: InventoryStructureKind) => {
|
||||
setKind(next);
|
||||
setParentId('');
|
||||
setParentSearch('');
|
||||
setFamilyId('');
|
||||
setFamilyFindings(null);
|
||||
setError('');
|
||||
};
|
||||
|
||||
const save=async(event:FormEvent) => {
|
||||
const save = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (requiresParent && !parentId) { setError(`Seleccioná ${parentLabel}.`); return; }
|
||||
if (requiresFamily && !familyId) { setError(`Seleccioná el tipo de ${kindLabel(kind).toLowerCase()}.`); return; }
|
||||
setSaving(true); setError('');
|
||||
const requiresParent = kind !== 'AREA' && kind !== 'EMPRESA';
|
||||
const requiresFamily = kind === 'INSTALACION' || kind === 'SUBINSTALACION';
|
||||
if (requiresParent && !parentId) {
|
||||
setError(`Seleccioná el ${kind === 'YACIMIENTO' ? 'Área' : kind === 'INSTALACION' ? 'Yacimiento' : 'Instalación'} padre.`);
|
||||
return;
|
||||
}
|
||||
if (requiresFamily && !familyId) {
|
||||
setError(`Seleccioná la familia de ${kindLabel(kind).toLowerCase()}.`);
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError('');
|
||||
try {
|
||||
const created=await createInventoryStructure({
|
||||
kind,name:name.trim(),parentId:parentId || null,familyId:familyId || null,
|
||||
code:code.trim() || null,commonName:commonName.trim() || null,description:description.trim() || null,
|
||||
const created = await createInventoryStructure({
|
||||
kind,
|
||||
code: code.trim() || null,
|
||||
name: name.trim(),
|
||||
commonName: commonName.trim() || null,
|
||||
parentId: parentId || null,
|
||||
familyId: familyId || null,
|
||||
description: description.trim() || null,
|
||||
});
|
||||
navigate(`/inventarios/${created.id}`,{replace:true});
|
||||
} catch(requestError) { setError(errorMessage(requestError)); }
|
||||
finally { setSaving(false); }
|
||||
navigate(`/inventarios/${created.id}`, { replace: true });
|
||||
} catch (requestError) {
|
||||
setError(errorMessage(requestError));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <LoadingBlock label="Preparando alta…" />;
|
||||
|
||||
const isIndependentCompany = kind === 'EMPRESA';
|
||||
const parentLabel = kind === 'YACIMIENTO' ? 'Área' : kind === 'INSTALACION' ? 'Yacimiento' : 'Instalación';
|
||||
const currentStep = STRUCTURE_KINDS.find((item) => item.kind === kind)?.step ?? 1;
|
||||
const identificationStep = isIndependentCompany ? '2' : kind === 'AREA' ? '2' : kind === 'YACIMIENTO' ? '3' : '4';
|
||||
const requiresParent = kind !== 'AREA' && kind !== 'EMPRESA';
|
||||
|
||||
return <section className="narrow-section asset-detail-page">
|
||||
<nav className="breadcrumb asset-detail-breadcrumb" aria-label="Ruta del Inventario"><Link to="/inventarios">Inventarios</Link><span>›</span><strong>Nuevo registro</strong></nav>
|
||||
<nav className="breadcrumb asset-detail-breadcrumb" aria-label="Ruta del inventario">
|
||||
<Link to="/inventarios">Inventarios</Link><span>›</span><strong>Nuevo registro</strong>
|
||||
</nav>
|
||||
|
||||
<div className="page-heading asset-editor-heading">
|
||||
<div><span className="eyebrow">CARGA MANUAL</span><h1>Nuevo registro</h1><p>Elegí qué querés crear, dónde va y su nombre. El resto es opcional.</p></div>
|
||||
<div>
|
||||
<span className="eyebrow">CONFIGURACIÓN E INVENTARIO</span>
|
||||
<h1>Agregar registro</h1>
|
||||
<p>Empresa es un maestro independiente. La estructura física es Área → Yacimiento → Instalación → Subinstalación.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <Alert>{error}</Alert>}
|
||||
|
||||
<div className="panel" style={{ marginBottom: 18 }}>
|
||||
<div className="form-section">
|
||||
<div><h2>1. ¿Qué querés crear?</h2><p className="section-copy">Creá una Empresa independiente o agregá un nivel a la estructura física.</p></div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, minmax(0, 1fr))', gap: 10 }}>
|
||||
<button
|
||||
type="button"
|
||||
className={`button ${kind === 'EMPRESA' ? 'primary' : 'secondary'}`}
|
||||
onClick={() => chooseKind('EMPRESA')}
|
||||
style={{ minHeight: 76, display: 'flex', flexDirection: 'column', alignItems: 'flex-start', justifyContent: 'center', gap: 3 }}
|
||||
>
|
||||
<strong>Empresa</strong>
|
||||
<small>Maestro independiente.</small>
|
||||
</button>
|
||||
{STRUCTURE_KINDS.map((item) => <button
|
||||
key={item.kind}
|
||||
type="button"
|
||||
className={`button ${kind === item.kind ? 'primary' : 'secondary'}`}
|
||||
onClick={() => chooseKind(item.kind)}
|
||||
style={{ minHeight: 76, display: 'flex', flexDirection: 'column', alignItems: 'flex-start', justifyContent: 'center', gap: 3 }}
|
||||
>
|
||||
<strong>{item.step}. {item.label}</strong>
|
||||
<small>{item.help}</small>
|
||||
</button>)}
|
||||
</div>
|
||||
{isIndependentCompany ? <div className="temporal-notice" style={{ marginTop: 12 }}>
|
||||
<Icon name="users" />
|
||||
<p><strong>Empresa:</strong> no forma parte de la jerarquía física. Su vínculo con un Área se administra como relación temporal de operación/concesión.</p>
|
||||
</div> : <div className="temporal-notice" style={{ marginTop: 12 }}>
|
||||
<Icon name="layers" />
|
||||
<p><strong>Ruta física:</strong> {STRUCTURE_KINDS.slice(0, currentStep).map((item) => item.label).join(' → ')}</p>
|
||||
</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form className="panel form-panel" onSubmit={save}>
|
||||
<div className="form-section">
|
||||
<div><h2>1. Tipo de registro</h2><p className="section-copy">La estructura física es Departamento → Área → Yacimiento → Instalación → Subinstalación. Empresa es un maestro independiente.</p></div>
|
||||
<label className="field"><span>Crear</span><select value={kind} onChange={(event)=>changeKind(event.target.value as InventoryStructureKind)}>{KINDS.map((item)=><option key={item.kind} value={item.kind}>{item.label}</option>)}</select></label>
|
||||
</div>
|
||||
|
||||
{requiresParent && <div className="form-section">
|
||||
<div><h2>2. Ubicación</h2><p className="section-copy">Elegí el {parentLabel.toLowerCase()} al que pertenece.</p></div>
|
||||
<label className="field"><span>Buscar {parentLabel.toLowerCase()}</span><input value={parentSearch} onChange={(event)=>setParentSearch(event.target.value)} placeholder={`Buscar ${parentLabel.toLowerCase()}…`} /></label>
|
||||
<label className="field"><span>{parentLabel} <em>obligatorio</em></span><select value={parentId} onChange={(event)=>{setParentId(event.target.value);setFamilyId('');}} required><option value="">Seleccionar…</option>{parents.map((parent)=><option key={parent.id} value={parent.id}>{parent.name} · {parent.code}</option>)}</select></label>
|
||||
<div><h2>2. Ubicación en la estructura</h2><p className="section-copy">Primero elegí el {parentLabel} al que pertenece este registro.</p></div>
|
||||
<label className="field">
|
||||
<span>Buscar {parentLabel.toLowerCase()}</span>
|
||||
<input value={parentSearch} onChange={(event) => setParentSearch(event.target.value)} placeholder={`Buscar por nombre o código de ${parentLabel.toLowerCase()}…`} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>{parentLabel} padre <em>obligatorio</em></span>
|
||||
<select value={parentId} onChange={(event) => { setParentId(event.target.value); setFamilyId(''); }} required>
|
||||
<option value="">Seleccionar {parentLabel.toLowerCase()}…</option>
|
||||
{parents.map((parent) => <option key={parent.id} value={parent.id}>{parent.name} · {parent.code}{parent.inventoryFamily ? ` · ${parent.inventoryFamily.name}` : ''}</option>)}
|
||||
</select>
|
||||
<small>No se permiten saltos de nivel ni padres incompatibles.</small>
|
||||
</label>
|
||||
</div>}
|
||||
|
||||
{requiresFamily && <div className="form-section">
|
||||
<div><h2>{requiresParent ? '3' : '2'}. Clasificación</h2><p className="section-copy">Define qué tipo de elemento es y qué Hallazgos le corresponden.</p></div>
|
||||
{kind==='SUBINSTALACION' && !selectedParent?.inventoryFamily
|
||||
? <Alert>La Instalación elegida todavía no tiene clasificación. Asignala antes de crear una Subinstalación.</Alert>
|
||||
: <label className="field"><span>Tipo de {kindLabel(kind).toLowerCase()} <em>obligatorio</em></span><select value={familyId} onChange={(event)=>setFamilyId(event.target.value)} required><option value="">Seleccionar…</option>{families.map((family)=><option key={family.id} value={family.id}>{family.name}</option>)}</select></label>}
|
||||
{selectedFamily && <div className="context-create-banner"><Icon name="alert" /><div><strong>{selectedFamily.name}</strong><span>{familyFindings ? `${familyFindings.count} Hallazgo${familyFindings.count===1?'':'s'} asociado${familyFindings.count===1?'':'s'}` : 'Cargando Hallazgos asociados…'}</span>{familyFindings && familyFindings.items.length>0 && <ul style={{margin:'8px 0 0',paddingLeft:18}}>{familyFindings.items.slice(0,6).map((item)=><li key={item.id}>{item.title}</li>)}{familyFindings.items.length>6 && <li>+ {familyFindings.items.length-6} más</li>}</ul>}</div></div>}
|
||||
{(kind === 'INSTALACION' || kind === 'SUBINSTALACION') && <div className="form-section">
|
||||
<div><h2>3. Clasificación técnica</h2><p className="section-copy">La clasificación no crea otro nivel: define el tipo de Instalación/Subinstalación y los Hallazgos aplicables.</p></div>
|
||||
{kind === 'SUBINSTALACION' && !selectedParent?.inventoryFamily ? <Alert>La Instalación seleccionada todavía no tiene una clasificación técnica. Revisala antes de crear una Subinstalación.</Alert> : <label className="field">
|
||||
<span>Tipo de {kindLabel(kind).toLowerCase()} <em>obligatorio</em></span>
|
||||
<select value={familyId} onChange={(event) => setFamilyId(event.target.value)} required>
|
||||
<option value="">Seleccionar tipo…</option>
|
||||
{families.map((family) => <option key={family.id} value={family.id}>{family.name}</option>)}
|
||||
</select>
|
||||
{kind === 'SUBINSTALACION' && selectedParent?.inventoryFamily && <small>Se muestran sólo las Subinstalaciones válidas para {selectedParent.inventoryFamily.name}.</small>}
|
||||
</label>}
|
||||
|
||||
{selectedFamily && <div className="context-create-banner" style={{ alignItems: 'flex-start' }}>
|
||||
<Icon name="alert" />
|
||||
<div style={{ flex: 1 }}>
|
||||
<strong>Hallazgos asociados automáticamente</strong>
|
||||
<span>{familyFindings ? `${familyFindings.count} Hallazgos aplicables para ${selectedFamily.name}` : 'Cargando catálogo asociado…'}</span>
|
||||
{familyFindings && familyFindings.items.length > 0 && <ul style={{ margin: '8px 0 0', paddingLeft: 18 }}>
|
||||
{familyFindings.items.slice(0, 7).map((item) => <li key={item.id}>{item.title}</li>)}
|
||||
{familyFindings.items.length > 7 && <li><strong>+ {familyFindings.items.length - 7} Hallazgos más</strong></li>}
|
||||
</ul>}
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{selectedFamily && selectedFamily.informationLabels.length > 0 && <div className="temporal-notice">
|
||||
<Icon name="clipboard" />
|
||||
<p><strong>Información técnica esperada:</strong> {selectedFamily.informationLabels.join(' · ')}</p>
|
||||
</div>}
|
||||
</div>}
|
||||
|
||||
<div className="form-section">
|
||||
<div><h2>{requiresFamily ? '4' : requiresParent ? '3' : '2'}. Identificación</h2><p className="section-copy">Para comenzar sólo necesitamos un nombre claro.</p></div>
|
||||
<label className="field"><span>Nombre <em>obligatorio</em></span><input autoFocus value={name} onChange={(event)=>setName(event.target.value)} required maxLength={200} placeholder={`Nombre de ${kindLabel(kind).toLowerCase()}`} /></label>
|
||||
<details style={{marginTop:12}}><summary style={{cursor:'pointer',fontWeight:700}}>Datos opcionales</summary><div style={{marginTop:14}}>
|
||||
<div className="form-grid">
|
||||
<label className="field"><span>Código DH</span><input value={code} onChange={(event)=>setCode(event.target.value.toUpperCase())} maxLength={120} pattern="[A-Z0-9][A-Z0-9._/-]*" placeholder="Se genera solo si lo dejás vacío" /></label>
|
||||
<label className="field"><span>Nombre habitual</span><input value={commonName} onChange={(event)=>setCommonName(event.target.value)} maxLength={200} /></label>
|
||||
</div>
|
||||
<label className="field"><span>Descripción</span><textarea value={description} onChange={(event)=>setDescription(event.target.value)} rows={2} maxLength={4000} /></label>
|
||||
</div></details>
|
||||
<div><h2>{identificationStep}. Identificación</h2><p className="section-copy">{isIndependentCompany ? 'Registrá la denominación de la Empresa.' : 'Usá el nombre real de campo.'} El código DH puede generarse automáticamente.</p></div>
|
||||
<div className="form-grid">
|
||||
<label className="field"><span>Nombre <em>obligatorio</em></span><input value={name} onChange={(event) => setName(event.target.value)} required maxLength={200} placeholder={`Nombre de ${kindLabel(kind).toLowerCase()}`} /></label>
|
||||
<label className="field"><span>Código DH <em>opcional</em></span><input value={code} onChange={(event) => setCode(event.target.value.toUpperCase())} maxLength={120} pattern="[A-Z0-9][A-Z0-9._/-]*" placeholder="Dejar vacío para generar automáticamente" /><small>Si no lo informás, DH genera un código único.</small></label>
|
||||
<label className="field"><span>Nombre habitual / sobrenombre <em>opcional</em></span><input value={commonName} onChange={(event) => setCommonName(event.target.value)} maxLength={200} placeholder={isIndependentCompany ? 'Nombre habitual o abreviado' : 'Nombre usado por los inspectores en campo'} /></label>
|
||||
</div>
|
||||
<label className="field"><span>Descripción <em>opcional</em></span><textarea value={description} onChange={(event) => setDescription(event.target.value)} rows={2} maxLength={4000} /></label>
|
||||
</div>
|
||||
|
||||
<div className="form-actions"><Link className="button secondary" to="/inventarios">Cancelar</Link><button className="button primary" disabled={saving || !name.trim() || (requiresParent && !parentId) || (requiresFamily && !familyId)}><Icon name="check" />{saving?'Creando…':`Crear ${kindLabel(kind)}`}</button></div>
|
||||
<div className="form-actions">
|
||||
<Link className="button secondary" to="/inventarios">Cancelar</Link>
|
||||
<button className="button primary" disabled={saving || !name.trim() || (requiresParent && !parentId) || ((kind === 'INSTALACION' || kind === 'SUBINSTALACION') && !familyId)}>
|
||||
<Icon name="check" />{saving ? 'Creando…' : `Crear ${kindLabel(kind)}`}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user