fix(F6.1): unificar contexto operativo Área–Operadora (#33)
Cierra inconsistencias residuales del contexto operativo F6.1. Inventario queda ligado al Área física; la Operadora vigente se resuelve por relaciones temporales. Incluye correcciones pre-merge de búsquedas WEB, alta contextual, merge de duplicados y barreras CI/runtime. Producción permanece sin desplegar.
This commit is contained in:
@@ -19,8 +19,11 @@ on:
|
|||||||
paths:
|
paths:
|
||||||
- 'android-app/**'
|
- 'android-app/**'
|
||||||
- 'api-v3/src/auth/**'
|
- 'api-v3/src/auth/**'
|
||||||
|
- 'api-v3/src/asset-master/**'
|
||||||
- 'api-v3/src/inspection-visits/**'
|
- 'api-v3/src/inspection-visits/**'
|
||||||
- 'api-v3/src/inspection-acts/**'
|
- 'api-v3/src/inspection-acts/**'
|
||||||
|
- 'api-v3/src/inspection-findings/**'
|
||||||
|
- 'api-v3/src/inspection-verifications/**'
|
||||||
- '.github/workflows/android.yml'
|
- '.github/workflows/android.yml'
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
@@ -66,4 +69,4 @@ jobs:
|
|||||||
name: DH-Inspeccion-F6.1-0.15.0-debug
|
name: DH-Inspeccion-F6.1-0.15.0-debug
|
||||||
path: android-app/app/build/outputs/apk/debug/app-debug.apk
|
path: android-app/app/build/outputs/apk/debug/app-debug.apk
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
retention-days: 30
|
retention-days: 30
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ jobs:
|
|||||||
grep -Fq -- '$STAGE/android-app:/android-app:ro' scripts/deploy-github.sh
|
grep -Fq -- '$STAGE/android-app:/android-app:ro' scripts/deploy-github.sh
|
||||||
- name: Validate Compose
|
- name: Validate Compose
|
||||||
run: docker compose --env-file .env.example config >/dev/null
|
run: docker compose --env-file .env.example config >/dev/null
|
||||||
- name: Rehearse migrations on clean PostGIS
|
- name: Rehearse migrations and real API startup on clean PostGIS
|
||||||
run: |
|
run: |
|
||||||
set -Eeuo pipefail
|
set -Eeuo pipefail
|
||||||
cleanup() {
|
cleanup() {
|
||||||
@@ -216,7 +216,35 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
rm -f "$rerun_log"
|
rm -f "$rerun_log"
|
||||||
- name: VPS-equivalent isolated API preflight
|
|
||||||
|
# A build-only preflight cannot catch Nest dependency-injection or
|
||||||
|
# runtime configuration failures. Start the production API image against
|
||||||
|
# the migrated database and require the public health endpoint to answer.
|
||||||
|
export JWT_ACCESS_SECRET='CI_ACCESS_SECRET_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
|
||||||
|
export REFRESH_TOKEN_PEPPER='CI_REFRESH_PEPPER_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
|
||||||
|
export SMTP_SETTINGS_MASTER_KEY=''
|
||||||
|
docker compose --env-file .env.example build api
|
||||||
|
docker compose --env-file .env.example up -d api
|
||||||
|
|
||||||
|
api_ready=0
|
||||||
|
for _ in $(seq 1 30); do
|
||||||
|
if curl -fsS http://127.0.0.1:3101/api/v3/health >/tmp/dhv2-health.json 2>/dev/null; then
|
||||||
|
api_ready=1
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
if [ "$api_ready" -ne 1 ]; then
|
||||||
|
echo 'ERROR: production API image did not become healthy.' >&2
|
||||||
|
docker compose --env-file .env.example logs --no-color api >&2 || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
grep -Fq '"status":"ok"' /tmp/dhv2-health.json || {
|
||||||
|
echo 'ERROR: /api/v3/health did not report status ok.' >&2
|
||||||
|
cat /tmp/dhv2-health.json >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
- name: Isolated builder test preflight
|
||||||
run: |
|
run: |
|
||||||
set -Eeuo pipefail
|
set -Eeuo pipefail
|
||||||
image="dhv2-api:ci-vps-preflight-${GITHUB_SHA::12}"
|
image="dhv2-api:ci-vps-preflight-${GITHUB_SHA::12}"
|
||||||
|
|||||||
@@ -170,20 +170,9 @@ export class AssetOperationalRelationsService {
|
|||||||
RETURNING id
|
RETURNING id
|
||||||
`, [dto.areaId, dto.companyId, dto.relationRole, dto.participationPercent ?? null, dto.legalInstrument ?? null, dto.sourceDocumentId ?? null, dto.reason, principal.userId])) as Array<{ id: string }>;
|
`, [dto.areaId, dto.companyId, dto.relationRole, dto.participationPercent ?? null, dto.legalInstrument ?? null, dto.sourceDocumentId ?? null, dto.reason, principal.userId])) as Array<{ id: string }>;
|
||||||
|
|
||||||
// Compatibility snapshot only. This does not move or re-parent Inventory.
|
// F5/F6: changing the Area operator is a temporal relation event only.
|
||||||
// area_company_relations remains the temporal source of truth.
|
// Existing Inventory keeps its creation/historical operator snapshot and
|
||||||
if (dto.relationRole === AreaOrganizationRole.OPERATOR) {
|
// physical hierarchy unchanged. Runtime ownership must resolve this row.
|
||||||
await manager.query(`
|
|
||||||
UPDATE assets asset
|
|
||||||
SET operator_company_id=$2::uuid,updated_at=CURRENT_TIMESTAMP,updated_by=$3::uuid
|
|
||||||
FROM asset_types type
|
|
||||||
WHERE type.id=asset.asset_type_id
|
|
||||||
AND type.operational_role='GENERIC'
|
|
||||||
AND asset.operational_area_id=$1::uuid
|
|
||||||
AND asset.operator_company_id IS DISTINCT FROM $2::uuid
|
|
||||||
`,[dto.areaId,dto.companyId,principal.userId]);
|
|
||||||
}
|
|
||||||
|
|
||||||
const created = await this.loadRelation(manager, row.id);
|
const created = await this.loadRelation(manager, row.id);
|
||||||
await this.audit.record({
|
await this.audit.record({
|
||||||
...administrationAuditContext(principal, request),
|
...administrationAuditContext(principal, request),
|
||||||
@@ -192,7 +181,7 @@ export class AssetOperationalRelationsService {
|
|||||||
entityId: row.id,
|
entityId: row.id,
|
||||||
afterData: this.auditView(created),
|
afterData: this.auditView(created),
|
||||||
metadata: dto.relationRole === AreaOrganizationRole.OPERATOR
|
metadata: dto.relationRole === AreaOrganizationRole.OPERATOR
|
||||||
? { inventoryHierarchyChanged:false, operatorSnapshotSynchronized:true }
|
? { inventoryHierarchyChanged:false, operatorSnapshotPreserved:true }
|
||||||
: undefined,
|
: undefined,
|
||||||
}, manager);
|
}, manager);
|
||||||
return created;
|
return created;
|
||||||
@@ -223,8 +212,8 @@ export class AssetOperationalRelationsService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// F5: physical Inventory belongs to Area/Yacimiento hierarchy, not to Company.
|
// F5/F6: physical Inventory belongs to Area/Yacimiento hierarchy, not to Company.
|
||||||
// Ending an operator relation must never be blocked by existing Inventory.
|
// Ending an operator relation never moves, rewrites or blocks existing Inventory.
|
||||||
await manager.query(`
|
await manager.query(`
|
||||||
UPDATE area_company_relations
|
UPDATE area_company_relations
|
||||||
SET valid_until = CURRENT_TIMESTAMP,
|
SET valid_until = CURRENT_TIMESTAMP,
|
||||||
|
|||||||
@@ -137,21 +137,41 @@ export class AssetTemporalService {
|
|||||||
if (!row) throw temporalAssetNotFound();
|
if (!row) throw temporalAssetNotFound();
|
||||||
const asOf = new Date(query.at);
|
const asOf = new Date(query.at);
|
||||||
row.asOf = asOf;
|
row.asOf = asOf;
|
||||||
|
|
||||||
|
// Physical context is reconstructed from the Inventory history, while the
|
||||||
|
// operator is resolved independently from the temporal Area↔Empresa ledger.
|
||||||
|
// This keeps historical operator changes from rewriting the Inventory.
|
||||||
const [context] = (await this.dataSource.query(`
|
const [context] = (await this.dataSource.query(`
|
||||||
SELECT
|
SELECT
|
||||||
CASE WHEN parent.id IS NULL THEN NULL ELSE JSONB_BUILD_OBJECT('id',parent.id,'code',parent.code,'name',parent.name) END AS parent,
|
CASE WHEN parent.id IS NULL THEN NULL ELSE JSONB_BUILD_OBJECT('id',parent.id,'code',parent.code,'name',parent.name) END AS parent,
|
||||||
CASE WHEN area.id IS NULL THEN NULL ELSE JSONB_BUILD_OBJECT('id',area.id,'code',area.code,'name',area.name) END AS "operationalArea",
|
CASE WHEN area.id IS NULL THEN NULL ELSE JSONB_BUILD_OBJECT('id',area.id,'code',area.code,'name',area.name) END AS "operationalArea",
|
||||||
CASE WHEN company.id IS NULL THEN NULL ELSE JSONB_BUILD_OBJECT('id',company.id,'code',company.code,'name',company.name) END AS "operatorCompany"
|
CASE WHEN operator_company.id IS NULL THEN NULL ELSE JSONB_BUILD_OBJECT(
|
||||||
|
'id',operator_company.id,'code',operator_company.code,'name',operator_company.name
|
||||||
|
) END AS "operatorCompany"
|
||||||
FROM asset_context_history history
|
FROM asset_context_history history
|
||||||
LEFT JOIN assets parent ON parent.id=history.parent_id
|
LEFT JOIN assets parent ON parent.id=history.parent_id
|
||||||
LEFT JOIN assets area ON area.id=history.operational_area_id
|
LEFT JOIN assets area ON area.id=history.operational_area_id
|
||||||
LEFT JOIN assets company ON company.id=history.operator_company_id
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT relation.company_id
|
||||||
|
FROM area_company_relations relation
|
||||||
|
WHERE relation.area_id=history.operational_area_id
|
||||||
|
AND relation.relation_role='OPERATOR'
|
||||||
|
AND relation.valid_from <= $2
|
||||||
|
AND (relation.valid_until IS NULL OR relation.valid_until > $2)
|
||||||
|
ORDER BY relation.valid_from DESC, relation.created_at DESC, relation.id DESC
|
||||||
|
LIMIT 1
|
||||||
|
) operator_relation ON true
|
||||||
|
LEFT JOIN assets operator_company ON operator_company.id=operator_relation.company_id
|
||||||
WHERE history.asset_id=$1
|
WHERE history.asset_id=$1
|
||||||
AND history.valid_from <= $2
|
AND history.valid_from <= $2
|
||||||
AND (history.valid_until IS NULL OR history.valid_until > $2)
|
AND (history.valid_until IS NULL OR history.valid_until > $2)
|
||||||
ORDER BY history.valid_from DESC
|
ORDER BY history.valid_from DESC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
`, [assetId, asOf])) as Array<{ parent: Record<string, unknown> | null; operationalArea: Record<string, unknown> | null; operatorCompany: Record<string, unknown> | null }>;
|
`, [assetId, asOf])) as Array<{
|
||||||
|
parent: Record<string, unknown> | null;
|
||||||
|
operationalArea: Record<string, unknown> | null;
|
||||||
|
operatorCompany: Record<string, unknown> | null;
|
||||||
|
}>;
|
||||||
if (context && row.snapshot) {
|
if (context && row.snapshot) {
|
||||||
row.snapshot = {
|
row.snapshot = {
|
||||||
...row.snapshot,
|
...row.snapshot,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Transform, Type } from 'class-transformer';
|
import { Transform, Type } from 'class-transformer';
|
||||||
import { IsDate, IsOptional, IsString, IsUUID, MaxLength, MinLength } from 'class-validator';
|
import { IsDate, IsEmpty, IsOptional, IsString, IsUUID, MaxLength, MinLength } from 'class-validator';
|
||||||
|
|
||||||
export class ChangeAssetContextDto {
|
export class ChangeAssetContextDto {
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@@ -10,8 +10,13 @@ export class ChangeAssetContextDto {
|
|||||||
@IsUUID('4')
|
@IsUUID('4')
|
||||||
operationalAreaId?: string | null;
|
operationalAreaId?: string | null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compatibilidad de contrato únicamente. F5/F6 separa la ubicación física
|
||||||
|
* del Inventario de la Operadora temporal del Área, por lo que este valor no
|
||||||
|
* puede modificarse desde un cambio de contexto del Inventario.
|
||||||
|
*/
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsUUID('4')
|
@IsEmpty({ message: 'La Operadora se administra en la relación temporal del Área, no en el Inventario' })
|
||||||
operatorCompanyId?: string | null;
|
operatorCompanyId?: string | null;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Transform } from 'class-transformer';
|
import { Transform } from 'class-transformer';
|
||||||
import { IsBoolean, IsEnum, IsOptional, IsString, IsUUID, MaxLength } from 'class-validator';
|
import { IsBoolean, IsEmpty, IsEnum, IsOptional, IsString, IsUUID, MaxLength } from 'class-validator';
|
||||||
import { AssetInformationStatus, AssetOperationalStatus } from '../../database/entities';
|
import { AssetInformationStatus, AssetOperationalStatus } from '../../database/entities';
|
||||||
|
|
||||||
export class ListAssetTreeQueryDto {
|
export class ListAssetTreeQueryDto {
|
||||||
@@ -24,8 +24,12 @@ export class ListAssetTreeQueryDto {
|
|||||||
@IsUUID('4')
|
@IsUUID('4')
|
||||||
operationalAreaId?: string;
|
operationalAreaId?: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retenido sólo para compatibilidad tipada. El árbol operativo no puede
|
||||||
|
* filtrar por el snapshot histórico de Empresa del Inventario.
|
||||||
|
*/
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsUUID('4')
|
@IsEmpty({ message: 'Filtrá la Operadora mediante la relación temporal del Área, no mediante el snapshot del Inventario' })
|
||||||
operatorCompanyId?: string;
|
operatorCompanyId?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Transform, Type } from 'class-transformer';
|
import { Transform, Type } from 'class-transformer';
|
||||||
import {
|
import {
|
||||||
IsBoolean,
|
IsBoolean,
|
||||||
|
IsEmpty,
|
||||||
IsEnum,
|
IsEnum,
|
||||||
IsInt,
|
IsInt,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
@@ -66,7 +67,12 @@ export class ListAssetsQueryDto {
|
|||||||
@IsUUID('4')
|
@IsUUID('4')
|
||||||
operationalAreaId?: string;
|
operationalAreaId?: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retenido sólo para compatibilidad tipada con consumidores históricos.
|
||||||
|
* F5/F6 no permite buscar ownership actual por el snapshot de Empresa del
|
||||||
|
* Inventario; la navegación Área↔Operadora usa area_company_relations.
|
||||||
|
*/
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsUUID('4')
|
@IsEmpty({ message: 'Filtrá la Operadora mediante la relación temporal del Área, no mediante el snapshot del Inventario' })
|
||||||
operatorCompanyId?: string;
|
operatorCompanyId?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Transform } from 'class-transformer';
|
import { Transform } from 'class-transformer';
|
||||||
import {
|
import {
|
||||||
|
IsEmpty,
|
||||||
IsObject,
|
IsObject,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
@@ -47,8 +48,12 @@ export class UpdateAssetDto {
|
|||||||
@IsUUID('4')
|
@IsUUID('4')
|
||||||
operationalAreaId?: string | null;
|
operationalAreaId?: string | null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Snapshot histórico/de compatibilidad. La Operadora vigente pertenece a la
|
||||||
|
* relación temporal Área↔Empresa y no puede editarse como propiedad física.
|
||||||
|
*/
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsUUID('4')
|
@IsEmpty({ message: 'La Operadora se administra en la relación temporal del Área, no en el Inventario' })
|
||||||
operatorCompanyId?: string | null;
|
operatorCompanyId?: string | null;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
|
|||||||
@@ -154,41 +154,26 @@ export class InspectionActsService {
|
|||||||
SELECT 1
|
SELECT 1
|
||||||
FROM inspection_act_assets search_link
|
FROM inspection_act_assets search_link
|
||||||
INNER JOIN assets search_asset ON search_asset.id = search_link.asset_id
|
INNER JOIN assets search_asset ON search_asset.id = search_link.asset_id
|
||||||
LEFT JOIN assets search_company ON search_company.id = search_asset.operator_company_id
|
|
||||||
LEFT JOIN assets search_area ON search_area.id = search_asset.operational_area_id
|
|
||||||
WHERE search_link.act_id = act.id
|
WHERE search_link.act_id = act.id
|
||||||
AND search_link.included = true
|
AND search_link.included = true
|
||||||
AND (
|
AND (search_asset.code ILIKE ${search} OR search_asset.name ILIKE ${search})
|
||||||
search_asset.code ILIKE ${search}
|
)
|
||||||
OR search_asset.name ILIKE ${search}
|
OR EXISTS (
|
||||||
OR search_company.name ILIKE ${search}
|
SELECT 1 FROM assets search_company
|
||||||
OR search_area.name ILIKE ${search}
|
WHERE search_company.id=visit.operator_company_id
|
||||||
)
|
AND search_company.name ILIKE ${search}
|
||||||
|
)
|
||||||
|
OR EXISTS (
|
||||||
|
SELECT 1 FROM assets search_area
|
||||||
|
WHERE search_area.id=visit.operational_area_id
|
||||||
|
AND search_area.name ILIKE ${search}
|
||||||
)
|
)
|
||||||
)`);
|
)`);
|
||||||
}
|
}
|
||||||
if (query.status) conditions.push(`act.status = ${add(query.status)}`);
|
if (query.status) conditions.push(`act.status = ${add(query.status)}`);
|
||||||
if (query.year) conditions.push(`act.act_year = ${add(query.year)}`);
|
if (query.year) conditions.push(`act.act_year = ${add(query.year)}`);
|
||||||
if (query.companyId) {
|
if (query.companyId) conditions.push(`visit.operator_company_id = ${add(query.companyId)}::uuid`);
|
||||||
conditions.push(`EXISTS (
|
if (query.areaId) conditions.push(`visit.operational_area_id = ${add(query.areaId)}::uuid`);
|
||||||
SELECT 1
|
|
||||||
FROM inspection_act_assets company_link
|
|
||||||
INNER JOIN assets company_asset ON company_asset.id = company_link.asset_id
|
|
||||||
WHERE company_link.act_id = act.id
|
|
||||||
AND company_link.included = true
|
|
||||||
AND company_asset.operator_company_id = ${add(query.companyId)}::uuid
|
|
||||||
)`);
|
|
||||||
}
|
|
||||||
if (query.areaId) {
|
|
||||||
conditions.push(`EXISTS (
|
|
||||||
SELECT 1
|
|
||||||
FROM inspection_act_assets area_link
|
|
||||||
INNER JOIN assets area_asset ON area_asset.id = area_link.asset_id
|
|
||||||
WHERE area_link.act_id = act.id
|
|
||||||
AND area_link.included = true
|
|
||||||
AND area_asset.operational_area_id = ${add(query.areaId)}::uuid
|
|
||||||
)`);
|
|
||||||
}
|
|
||||||
if (query.inspectorId) {
|
if (query.inspectorId) {
|
||||||
const inspector = add(query.inspectorId);
|
const inspector = add(query.inspectorId);
|
||||||
conditions.push(`(
|
conditions.push(`(
|
||||||
@@ -245,24 +230,8 @@ export class InspectionActsService {
|
|||||||
}
|
}
|
||||||
if (query.status) conditions.push(`act.status = ${add(query.status)}`);
|
if (query.status) conditions.push(`act.status = ${add(query.status)}`);
|
||||||
if (query.year) conditions.push(`act.act_year = ${add(query.year)}`);
|
if (query.year) conditions.push(`act.act_year = ${add(query.year)}`);
|
||||||
if (query.companyId) {
|
if (query.companyId) conditions.push(`visit.operator_company_id = ${add(query.companyId)}::uuid`);
|
||||||
conditions.push(`EXISTS (
|
if (query.areaId) conditions.push(`visit.operational_area_id = ${add(query.areaId)}::uuid`);
|
||||||
SELECT 1 FROM inspection_act_assets company_link
|
|
||||||
INNER JOIN assets company_asset ON company_asset.id = company_link.asset_id
|
|
||||||
WHERE company_link.act_id = act.id
|
|
||||||
AND company_link.included = true
|
|
||||||
AND company_asset.operator_company_id = ${add(query.companyId)}::uuid
|
|
||||||
)`);
|
|
||||||
}
|
|
||||||
if (query.areaId) {
|
|
||||||
conditions.push(`EXISTS (
|
|
||||||
SELECT 1 FROM inspection_act_assets area_link
|
|
||||||
INNER JOIN assets area_asset ON area_asset.id = area_link.asset_id
|
|
||||||
WHERE area_link.act_id = act.id
|
|
||||||
AND area_link.included = true
|
|
||||||
AND area_asset.operational_area_id = ${add(query.areaId)}::uuid
|
|
||||||
)`);
|
|
||||||
}
|
|
||||||
if (query.inspectorId) {
|
if (query.inspectorId) {
|
||||||
const inspector = add(query.inspectorId);
|
const inspector = add(query.inspectorId);
|
||||||
conditions.push(`(
|
conditions.push(`(
|
||||||
@@ -548,21 +517,16 @@ export class InspectionActsService {
|
|||||||
LEFT JOIN inspection_reports report ON report.act_id = act.id
|
LEFT JOIN inspection_reports report ON report.act_id = act.id
|
||||||
LEFT JOIN LATERAL (
|
LEFT JOIN LATERAL (
|
||||||
SELECT
|
SELECT
|
||||||
COALESCE(JSONB_AGG(DISTINCT JSONB_BUILD_OBJECT(
|
CASE WHEN company.id IS NULL THEN '[]'::jsonb ELSE JSONB_BUILD_ARRAY(
|
||||||
'id', company.id,
|
JSONB_BUILD_OBJECT('id',company.id,'code',company.code,'name',company.name)
|
||||||
'code', company.code,
|
) END AS companies,
|
||||||
'name', company.name
|
CASE WHEN area.id IS NULL THEN '[]'::jsonb ELSE JSONB_BUILD_ARRAY(
|
||||||
)) FILTER (WHERE company.id IS NOT NULL), '[]'::jsonb) AS companies,
|
JSONB_BUILD_OBJECT('id',area.id,'code',area.code,'name',area.name)
|
||||||
COALESCE(JSONB_AGG(DISTINCT JSONB_BUILD_OBJECT(
|
) END AS areas
|
||||||
'id', area.id,
|
FROM inspection_visits context_visit
|
||||||
'code', area.code,
|
LEFT JOIN assets company ON company.id=context_visit.operator_company_id
|
||||||
'name', area.name
|
LEFT JOIN assets area ON area.id=context_visit.operational_area_id
|
||||||
)) FILTER (WHERE area.id IS NOT NULL), '[]'::jsonb) AS areas
|
WHERE context_visit.id=act.visit_id
|
||||||
FROM inspection_act_assets context_link
|
|
||||||
INNER JOIN assets context_asset ON context_asset.id = context_link.asset_id
|
|
||||||
LEFT JOIN assets company ON company.id = context_asset.operator_company_id
|
|
||||||
LEFT JOIN assets area ON area.id = context_asset.operational_area_id
|
|
||||||
WHERE context_link.act_id = act.id AND context_link.included = true
|
|
||||||
) context ON true
|
) context ON true
|
||||||
LEFT JOIN LATERAL (
|
LEFT JOIN LATERAL (
|
||||||
SELECT COUNT(*) AS total
|
SELECT COUNT(*) AS total
|
||||||
@@ -813,6 +777,8 @@ export class InspectionActsService {
|
|||||||
'code', visit.code,
|
'code', visit.code,
|
||||||
'status', visit.status,
|
'status', visit.status,
|
||||||
'scopeAssetId', visit.scope_asset_id,
|
'scopeAssetId', visit.scope_asset_id,
|
||||||
|
'operationalAreaId', visit.operational_area_id,
|
||||||
|
'operatorCompanyId', visit.operator_company_id,
|
||||||
'actualStartedAt', visit.actual_started_at
|
'actualStartedAt', visit.actual_started_at
|
||||||
),
|
),
|
||||||
'assets', COALESCE((
|
'assets', COALESCE((
|
||||||
|
|||||||
@@ -153,13 +153,16 @@ export class InspectionFindingWorklistService {
|
|||||||
workflowFilters.push(`finding.status = 'OPEN'`);
|
workflowFilters.push(`finding.status = 'OPEN'`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Hallazgo, Acta e Inspección forman un hecho histórico. Empresa y Área se
|
||||||
|
// leen del contexto congelado de la Inspección que originó el Hallazgo, no
|
||||||
|
// del snapshot de compatibilidad del Inventario.
|
||||||
const joins = `
|
const joins = `
|
||||||
INNER JOIN inspection_acts act ON act.id = finding.act_id
|
INNER JOIN inspection_acts act ON act.id = finding.act_id
|
||||||
INNER JOIN inspection_visits visit ON visit.id = act.visit_id
|
INNER JOIN inspection_visits visit ON visit.id = act.visit_id
|
||||||
INNER JOIN assets asset ON asset.id = finding.asset_id
|
INNER JOIN assets asset ON asset.id = finding.asset_id
|
||||||
INNER JOIN asset_types asset_type ON asset_type.id = asset.asset_type_id
|
INNER JOIN asset_types asset_type ON asset_type.id = asset.asset_type_id
|
||||||
LEFT JOIN assets company ON company.id = asset.operator_company_id
|
LEFT JOIN assets company ON company.id = visit.operator_company_id
|
||||||
LEFT JOIN assets area ON area.id = asset.operational_area_id
|
LEFT JOIN assets area ON area.id = visit.operational_area_id
|
||||||
`;
|
`;
|
||||||
const filters = [...contextFilters, ...workflowFilters];
|
const filters = [...contextFilters, ...workflowFilters];
|
||||||
const where = filters.length ? `WHERE ${filters.join(' AND ')}` : '';
|
const where = filters.length ? `WHERE ${filters.join(' AND ')}` : '';
|
||||||
|
|||||||
@@ -408,30 +408,24 @@ export class InspectionReportsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private contextFilter(column: 'operator_company_id' | 'operational_area_id', parameter: string): string {
|
private contextFilter(column: 'operator_company_id' | 'operational_area_id', parameter: string): string {
|
||||||
return `EXISTS (
|
// Reports are historical documents. Their Area/Company filters must use the
|
||||||
SELECT 1
|
// parent Inspection snapshot, never the mutable/current Inventory context.
|
||||||
FROM inspection_act_assets context_filter_link
|
return `visit.${column} = ${parameter}::uuid`;
|
||||||
INNER JOIN assets context_filter_asset ON context_filter_asset.id = context_filter_link.asset_id
|
|
||||||
WHERE context_filter_link.act_id = act.id
|
|
||||||
AND context_filter_link.included = true
|
|
||||||
AND context_filter_asset.${column} = ${parameter}::uuid
|
|
||||||
)`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private contextSelect(): string {
|
private contextSelect(): string {
|
||||||
return `
|
return `
|
||||||
SELECT
|
SELECT
|
||||||
COALESCE(JSONB_AGG(DISTINCT JSONB_BUILD_OBJECT(
|
CASE WHEN company.id IS NULL THEN '[]'::jsonb ELSE JSONB_BUILD_ARRAY(
|
||||||
'id',company.id,'code',company.code,'name',company.name
|
JSONB_BUILD_OBJECT('id',company.id,'code',company.code,'name',company.name)
|
||||||
)) FILTER (WHERE company.id IS NOT NULL),'[]'::jsonb) AS companies,
|
) END AS companies,
|
||||||
COALESCE(JSONB_AGG(DISTINCT JSONB_BUILD_OBJECT(
|
CASE WHEN area.id IS NULL THEN '[]'::jsonb ELSE JSONB_BUILD_ARRAY(
|
||||||
'id',area.id,'code',area.code,'name',area.name
|
JSONB_BUILD_OBJECT('id',area.id,'code',area.code,'name',area.name)
|
||||||
)) FILTER (WHERE area.id IS NOT NULL),'[]'::jsonb) AS areas
|
) END AS areas
|
||||||
FROM inspection_act_assets context_link
|
FROM inspection_visits context_visit
|
||||||
INNER JOIN assets context_asset ON context_asset.id=context_link.asset_id
|
LEFT JOIN assets company ON company.id=context_visit.operator_company_id
|
||||||
LEFT JOIN assets company ON company.id=context_asset.operator_company_id
|
LEFT JOIN assets area ON area.id=context_visit.operational_area_id
|
||||||
LEFT JOIN assets area ON area.id=context_asset.operational_area_id
|
WHERE context_visit.id=act.visit_id
|
||||||
WHERE context_link.act_id=act.id AND context_link.included=true
|
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -66,9 +66,6 @@ interface LockedFindingRow {
|
|||||||
assetId: string;
|
assetId: string;
|
||||||
assetCode: string;
|
assetCode: string;
|
||||||
assetName: string;
|
assetName: string;
|
||||||
companyId: string | null;
|
|
||||||
companyCode: string | null;
|
|
||||||
companyName: string | null;
|
|
||||||
areaId: string | null;
|
areaId: string | null;
|
||||||
areaCode: string | null;
|
areaCode: string | null;
|
||||||
areaName: string | null;
|
areaName: string | null;
|
||||||
@@ -76,6 +73,12 @@ interface LockedFindingRow {
|
|||||||
status: string;
|
status: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface PlannedOperatorRow {
|
||||||
|
companyId: string;
|
||||||
|
companyCode: string;
|
||||||
|
companyName: string;
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class InspectionVerificationsService {
|
export class InspectionVerificationsService {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -142,8 +145,19 @@ export class InspectionVerificationsService {
|
|||||||
INNER JOIN inspection_visits source_visit ON source_visit.id = act.visit_id
|
INNER JOIN inspection_visits source_visit ON source_visit.id = act.visit_id
|
||||||
INNER JOIN assets asset ON asset.id = finding.asset_id
|
INNER JOIN assets asset ON asset.id = finding.asset_id
|
||||||
INNER JOIN asset_types asset_type ON asset_type.id = asset.asset_type_id
|
INNER JOIN asset_types asset_type ON asset_type.id = asset.asset_type_id
|
||||||
LEFT JOIN assets company ON company.id = asset.operator_company_id
|
|
||||||
LEFT JOIN assets area ON area.id = asset.operational_area_id
|
LEFT JOIN assets area ON area.id = asset.operational_area_id
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT operator_company.id,operator_company.code,operator_company.name
|
||||||
|
FROM area_company_relations relation
|
||||||
|
INNER JOIN assets operator_company ON operator_company.id=relation.company_id
|
||||||
|
WHERE relation.area_id=asset.operational_area_id
|
||||||
|
AND relation.relation_role='OPERATOR'
|
||||||
|
AND relation.valid_from <= CURRENT_TIMESTAMP
|
||||||
|
AND (relation.valid_until IS NULL OR relation.valid_until > CURRENT_TIMESTAMP)
|
||||||
|
AND operator_company.information_status<>'INACTIVE'
|
||||||
|
ORDER BY relation.valid_from DESC,relation.created_at DESC,relation.id DESC
|
||||||
|
LIMIT 1
|
||||||
|
) company ON true
|
||||||
${activeVisitJoin}
|
${activeVisitJoin}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -495,15 +509,11 @@ export class InspectionVerificationsService {
|
|||||||
finding.next_control_on AS "nextControlOn",
|
finding.next_control_on AS "nextControlOn",
|
||||||
asset.code AS "assetCode",
|
asset.code AS "assetCode",
|
||||||
asset.name AS "assetName",
|
asset.name AS "assetName",
|
||||||
company.id AS "companyId",
|
|
||||||
company.code AS "companyCode",
|
|
||||||
company.name AS "companyName",
|
|
||||||
area.id AS "areaId",
|
area.id AS "areaId",
|
||||||
area.code AS "areaCode",
|
area.code AS "areaCode",
|
||||||
area.name AS "areaName"
|
area.name AS "areaName"
|
||||||
FROM inspection_findings finding
|
FROM inspection_findings finding
|
||||||
INNER JOIN assets asset ON asset.id = finding.asset_id
|
INNER JOIN assets asset ON asset.id = finding.asset_id
|
||||||
LEFT JOIN assets company ON company.id = asset.operator_company_id
|
|
||||||
LEFT JOIN assets area ON area.id = asset.operational_area_id
|
LEFT JOIN assets area ON area.id = asset.operational_area_id
|
||||||
WHERE finding.id = ANY($1::uuid[])
|
WHERE finding.id = ANY($1::uuid[])
|
||||||
FOR UPDATE OF finding
|
FOR UPDATE OF finding
|
||||||
@@ -519,25 +529,51 @@ export class InspectionVerificationsService {
|
|||||||
message: `${invalid.code} necesita estar abierto y tener una fecha de control para planificar su verificación`,
|
message: `${invalid.code} necesita estar abierto y tener una fecha de control para planificar su verificación`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const missingContext = rows.find((row) => !row.companyId || !row.areaId);
|
const missingArea = rows.find((row) => !row.areaId);
|
||||||
if (missingContext) {
|
if (missingArea) {
|
||||||
throw new BadRequestException({
|
throw new BadRequestException({
|
||||||
code: 'VERIFICATION_CONTEXT_REQUIRED',
|
code: 'VERIFICATION_CONTEXT_REQUIRED',
|
||||||
message: `${missingContext.code} necesita empresa y área operativa antes de planificar la visita`,
|
message: `${missingArea.code} necesita un Área física antes de planificar la visita`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const companyId = rows[0]?.companyId;
|
|
||||||
const areaId = rows[0]?.areaId;
|
const areaId = rows[0]?.areaId;
|
||||||
if (!companyId || !areaId) {
|
if (!areaId) {
|
||||||
throw new BadRequestException({ code: 'VERIFICATION_CONTEXT_REQUIRED', message: 'Los hallazgos necesitan empresa y área operativa' });
|
throw new BadRequestException({ code: 'VERIFICATION_CONTEXT_REQUIRED', message: 'Los hallazgos necesitan un Área física' });
|
||||||
}
|
}
|
||||||
if (rows.some((row) => row.companyId !== companyId || row.areaId !== areaId)) {
|
if (rows.some((row) => row.areaId !== areaId)) {
|
||||||
throw new BadRequestException({
|
throw new BadRequestException({
|
||||||
code: 'VERIFICATION_CONTEXT_MIXED',
|
code: 'VERIFICATION_CONTEXT_MIXED',
|
||||||
message: 'Seleccioná hallazgos de una misma empresa y área para crear una visita de verificación',
|
message: 'Seleccioná hallazgos de una misma Área para crear una visita de verificación',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A verification visit is a new operational act. Its operator is therefore
|
||||||
|
// the Company valid for the Area at the planned visit date, never the
|
||||||
|
// historical compatibility snapshot stored on the Inventory.
|
||||||
|
const [operator] = await manager.query(`
|
||||||
|
SELECT
|
||||||
|
company.id AS "companyId",
|
||||||
|
company.code AS "companyCode",
|
||||||
|
company.name AS "companyName"
|
||||||
|
FROM area_company_relations relation
|
||||||
|
INNER JOIN assets company ON company.id=relation.company_id
|
||||||
|
WHERE relation.area_id=$1::uuid
|
||||||
|
AND relation.relation_role='OPERATOR'
|
||||||
|
AND relation.valid_from <= $2::timestamptz
|
||||||
|
AND (relation.valid_until IS NULL OR relation.valid_until > $2::timestamptz)
|
||||||
|
AND company.information_status<>'INACTIVE'
|
||||||
|
ORDER BY relation.valid_from DESC,relation.created_at DESC,relation.id DESC
|
||||||
|
LIMIT 1
|
||||||
|
FOR SHARE OF relation
|
||||||
|
`, [areaId, plannedStartAt]) as PlannedOperatorRow[];
|
||||||
|
if (!operator) {
|
||||||
|
throw new ConflictException({
|
||||||
|
code: 'VERIFICATION_OPERATOR_NOT_ACTIVE',
|
||||||
|
message: 'El Área no tiene una Operadora vigente para la fecha prevista de la verificación',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const companyId = operator.companyId;
|
||||||
|
|
||||||
const activeLinks = await manager.query(`
|
const activeLinks = await manager.query(`
|
||||||
SELECT verification_link.finding_id AS "findingId", visit.code
|
SELECT verification_link.finding_id AS "findingId", visit.code
|
||||||
FROM inspection_finding_verification_visits verification_link
|
FROM inspection_finding_verification_visits verification_link
|
||||||
@@ -552,7 +588,7 @@ export class InspectionVerificationsService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const companyName = rows[0]?.companyName ?? 'Empresa';
|
const companyName = operator.companyName;
|
||||||
const areaName = rows[0]?.areaName ?? 'Área';
|
const areaName = rows[0]?.areaName ?? 'Área';
|
||||||
const code = await nextInspectionVisitCode(manager, plannedStartAt);
|
const code = await nextInspectionVisitCode(manager, plannedStartAt);
|
||||||
const findingCodes = rows.map((row) => row.code).join(', ');
|
const findingCodes = rows.map((row) => row.code).join(', ');
|
||||||
@@ -637,6 +673,7 @@ export class InspectionVerificationsService {
|
|||||||
areaId,
|
areaId,
|
||||||
findingIds,
|
findingIds,
|
||||||
assetIds,
|
assetIds,
|
||||||
|
operatorSource: 'area_company_relations',
|
||||||
},
|
},
|
||||||
}, manager);
|
}, manager);
|
||||||
|
|
||||||
@@ -647,7 +684,7 @@ export class InspectionVerificationsService {
|
|||||||
status: visit.status,
|
status: visit.status,
|
||||||
plannedStartAt: visit.plannedStartAt,
|
plannedStartAt: visit.plannedStartAt,
|
||||||
},
|
},
|
||||||
company: { id: companyId, code: rows[0]?.companyCode ?? '', name: companyName },
|
company: { id: companyId, code: operator.companyCode, name: companyName },
|
||||||
area: { id: areaId, code: rows[0]?.areaCode ?? '', name: areaName },
|
area: { id: areaId, code: rows[0]?.areaCode ?? '', name: areaName },
|
||||||
findingCount: findingIds.length,
|
findingCount: findingIds.length,
|
||||||
assetCount: assetIds.length,
|
assetCount: assetIds.length,
|
||||||
|
|||||||
@@ -33,13 +33,15 @@ test('D5.3 API enforces active relation, exclusive pair and physical ancestry',
|
|||||||
assert.match(assets, /OPERATIONAL_ANCHOR_IN_USE/);
|
assert.match(assets, /OPERATIONAL_ANCHOR_IN_USE/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('D5.3/F5 relation lifecycle stays historical and audited without making Empresa physical ownership', async () => {
|
test('D5.3/F6.1 relation lifecycle stays historical and audited without making Empresa physical ownership', async () => {
|
||||||
const service = await source('asset-master/asset-operational-relations.service.ts');
|
const service = await source('asset-master/asset-operational-relations.service.ts');
|
||||||
assert.match(service, /INSERT INTO area_company_relations/);
|
assert.match(service, /INSERT INTO area_company_relations/);
|
||||||
assert.match(service, /valid_until = CURRENT_TIMESTAMP/);
|
assert.match(service, /valid_until = CURRENT_TIMESTAMP/);
|
||||||
assert.match(service, /Ending an operator relation must never be blocked by existing Inventory/);
|
assert.match(service, /Ending an operator relation never moves, rewrites or blocks existing Inventory/);
|
||||||
|
assert.match(service, /operatorSnapshotPreserved:true/);
|
||||||
assert.match(service, /retainedCompatibilitySnapshotCount: before\.assignedAssetCount/);
|
assert.match(service, /retainedCompatibilitySnapshotCount: before\.assignedAssetCount/);
|
||||||
assert.doesNotMatch(service, /AREA_COMPANY_RELATION_IN_USE/);
|
assert.doesNotMatch(service, /AREA_COMPANY_RELATION_IN_USE/);
|
||||||
|
assert.doesNotMatch(service, /UPDATE assets asset[\s\S]*SET operator_company_id=/);
|
||||||
assert.match(service, /ASSET_AREA_COMPANY_RELATION_CREATED/);
|
assert.match(service, /ASSET_AREA_COMPANY_RELATION_CREATED/);
|
||||||
assert.match(service, /ASSET_AREA_COMPANY_RELATION_ENDED/);
|
assert.match(service, /ASSET_AREA_COMPANY_RELATION_ENDED/);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
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): string {
|
||||||
|
return readFileSync(resolve(process.cwd(), path), 'utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
test('F6.1 preserves Inventory operator snapshots and changes operator only through Area relations', () => {
|
||||||
|
const relations = source('src/asset-master/asset-operational-relations.service.ts');
|
||||||
|
const migration = source('src/database/migrations/1790087250000-f5-operational-context-compatibility.ts');
|
||||||
|
|
||||||
|
assert.match(migration, /Runtime ownership and search MUST NOT depend on it/);
|
||||||
|
assert.match(migration, /La Empresa se cambia en la relación temporal del Área, no en el Inventario/);
|
||||||
|
assert.match(relations, /operatorSnapshotPreserved:true/);
|
||||||
|
assert.doesNotMatch(relations, /UPDATE assets asset[\s\S]*SET operator_company_id=/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F6.1 blocks operator mutation through generic Inventory edit DTOs', () => {
|
||||||
|
const updateDto = source('src/asset-master/dto/update-asset.dto.ts');
|
||||||
|
const contextDto = source('src/asset-master/dto/change-asset-context.dto.ts');
|
||||||
|
|
||||||
|
for (const dto of [updateDto, contextDto]) {
|
||||||
|
assert.match(dto, /@IsEmpty/);
|
||||||
|
assert.match(dto, /La Operadora se administra en la relación temporal del Área, no en el Inventario/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F6.1 rejects legacy Inventory searches that filter by operator snapshot', () => {
|
||||||
|
const listDto = source('src/asset-master/dto/list-assets-query.dto.ts');
|
||||||
|
const treeDto = source('src/asset-master/dto/list-asset-tree-query.dto.ts');
|
||||||
|
|
||||||
|
for (const dto of [listDto, treeDto]) {
|
||||||
|
assert.match(dto, /operatorCompanyId\?: string/);
|
||||||
|
assert.match(dto, /@IsEmpty/);
|
||||||
|
assert.match(dto, /Filtrá la Operadora mediante la relación temporal del Área/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F6.1 resolves temporal Inventory operator from Area relation history', () => {
|
||||||
|
const temporal = source('src/asset-master/asset-temporal.service.ts');
|
||||||
|
|
||||||
|
assert.match(temporal, /FROM area_company_relations relation/);
|
||||||
|
assert.match(temporal, /relation\.valid_from <= \$2/);
|
||||||
|
assert.match(temporal, /relation\.valid_until IS NULL OR relation\.valid_until > \$2/);
|
||||||
|
assert.match(temporal, /operator_company\.id=operator_relation\.company_id/);
|
||||||
|
assert.doesNotMatch(temporal, /operator_company\.id=history\.operator_company_id/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F6.1 verification planning uses Area relation truth instead of Inventory operator snapshot', () => {
|
||||||
|
const verification = source('src/inspection-verifications/inspection-verifications.service.ts');
|
||||||
|
|
||||||
|
assert.match(verification, /FROM area_company_relations relation/);
|
||||||
|
assert.match(verification, /relation\.valid_from <= \$2::timestamptz/);
|
||||||
|
assert.match(verification, /VERIFICATION_OPERATOR_NOT_ACTIVE/);
|
||||||
|
assert.match(verification, /operatorSource: 'area_company_relations'/);
|
||||||
|
assert.doesNotMatch(verification, /company\.id = asset\.operator_company_id/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F6.1 historical operational lists read Company and Area from the parent Inspection', () => {
|
||||||
|
const acts = source('src/inspection-acts/inspection-acts.service.ts');
|
||||||
|
const findings = source('src/inspection-findings/inspection-finding-worklist.service.ts');
|
||||||
|
const reports = source('src/inspection-reports/inspection-reports.service.ts');
|
||||||
|
|
||||||
|
assert.match(acts, /visit\.operator_company_id/);
|
||||||
|
assert.match(acts, /visit\.operational_area_id/);
|
||||||
|
assert.doesNotMatch(acts, /context_asset\.operator_company_id/);
|
||||||
|
assert.match(findings, /company\.id = visit\.operator_company_id/);
|
||||||
|
assert.match(findings, /area\.id = visit\.operational_area_id/);
|
||||||
|
assert.doesNotMatch(findings, /company\.id = asset\.operator_company_id/);
|
||||||
|
assert.match(reports, /visit\.\$\{column\} = \$\{parameter\}::uuid/);
|
||||||
|
assert.match(reports, /company\.id=context_visit\.operator_company_id/);
|
||||||
|
assert.match(reports, /area\.id=context_visit\.operational_area_id/);
|
||||||
|
assert.doesNotMatch(reports, /context_asset\.operator_company_id/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F6.1 WEB Inventory searches use physical Area and never the operator snapshot filter', () => {
|
||||||
|
const inspectionEditor = source('../web-v2/src/pages/InspectionVisitEditorF4Page.tsx');
|
||||||
|
const fieldDiscoveries = source('../web-v2/src/pages/FieldDiscoveriesPage.tsx');
|
||||||
|
const inventoryMerge = source('../web-v2/src/lib/inventoryMergeApi.ts');
|
||||||
|
|
||||||
|
for (const page of [inspectionEditor, fieldDiscoveries, inventoryMerge]) {
|
||||||
|
assert.match(page, /listAssets\(\{[\s\S]{0,300}operationalAreaId:/);
|
||||||
|
assert.doesNotMatch(page, /listAssets\(\{[\s\S]{0,300}operatorCompanyId:/);
|
||||||
|
}
|
||||||
|
assert.doesNotMatch(inventoryMerge, /source\.operatorCompany/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F6.1 WEB derives the creation snapshot from the active Area operator and removes it from Inventory edits', () => {
|
||||||
|
const editor = source('../web-v2/src/pages/AssetEditorPage.tsx');
|
||||||
|
const contextPanel = source('../web-v2/src/features/assets/AssetContextHistoryPanel.tsx');
|
||||||
|
|
||||||
|
assert.match(editor, /createAsset\(\{[\s\S]*operatorCompanyId: operatorCompanyId \|\| null/);
|
||||||
|
assert.doesNotMatch(editor, /updateAsset\(id, \{[^}]*operatorCompanyId/);
|
||||||
|
assert.doesNotMatch(editor, /parent\.operatorCompany/);
|
||||||
|
assert.match(editor, /listCompaniesForArea\(operationalAreaId\)\.then\(\(loadedCompanies\)/);
|
||||||
|
assert.match(editor, /loadedCompanies\.length === 1 \? \(loadedCompanies\[0\]\?\.id \?\? ''\) : ''/);
|
||||||
|
assert.match(editor, /Snapshot histórico de alta/);
|
||||||
|
assert.match(contextPanel, /Cambiar contexto físico/);
|
||||||
|
assert.doesNotMatch(contextPanel, /operatorCompanyId:/);
|
||||||
|
});
|
||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
changeAssetContext,
|
changeAssetContext,
|
||||||
listAssetContextHistory,
|
listAssetContextHistory,
|
||||||
listAssetParentOptions,
|
listAssetParentOptions,
|
||||||
listCompaniesForArea,
|
|
||||||
listOperationalAreas,
|
listOperationalAreas,
|
||||||
} from '../../lib/api';
|
} from '../../lib/api';
|
||||||
import type {
|
import type {
|
||||||
@@ -29,7 +28,6 @@ function contextLabel(item: AssetContextHistoryItem) {
|
|||||||
const parts = [
|
const parts = [
|
||||||
item.parent ? `Padre: ${item.parent.name}` : 'Sin padre',
|
item.parent ? `Padre: ${item.parent.name}` : 'Sin padre',
|
||||||
item.operationalArea ? `Área: ${item.operationalArea.name}` : null,
|
item.operationalArea ? `Área: ${item.operationalArea.name}` : null,
|
||||||
item.operatorCompany ? `Operadora: ${item.operatorCompany.name}` : null,
|
|
||||||
].filter(Boolean);
|
].filter(Boolean);
|
||||||
return parts.join(' · ');
|
return parts.join(' · ');
|
||||||
}
|
}
|
||||||
@@ -55,9 +53,7 @@ export function AssetContextHistoryPanel({
|
|||||||
const [parentSearch, setParentSearch] = useState('');
|
const [parentSearch, setParentSearch] = useState('');
|
||||||
const [parents, setParents] = useState<AssetListItem[]>([]);
|
const [parents, setParents] = useState<AssetListItem[]>([]);
|
||||||
const [operationalAreaId, setOperationalAreaId] = useState(asset.operationalArea?.id ?? '');
|
const [operationalAreaId, setOperationalAreaId] = useState(asset.operationalArea?.id ?? '');
|
||||||
const [operatorCompanyId, setOperatorCompanyId] = useState(asset.operatorCompany?.id ?? '');
|
|
||||||
const [areas, setAreas] = useState<OperationalAssetSummary[]>([]);
|
const [areas, setAreas] = useState<OperationalAssetSummary[]>([]);
|
||||||
const [companies, setCompanies] = useState<OperationalAssetSummary[]>([]);
|
|
||||||
const [effectiveAt, setEffectiveAt] = useState(localDateTimeNow());
|
const [effectiveAt, setEffectiveAt] = useState(localDateTimeNow());
|
||||||
const [reason, setReason] = useState('');
|
const [reason, setReason] = useState('');
|
||||||
|
|
||||||
@@ -94,29 +90,14 @@ export function AssetContextHistoryPanel({
|
|||||||
setAreas(items);
|
setAreas(items);
|
||||||
if (operationalAreaId && !items.some((item) => item.id === operationalAreaId)) {
|
if (operationalAreaId && !items.some((item) => item.id === operationalAreaId)) {
|
||||||
setOperationalAreaId('');
|
setOperationalAreaId('');
|
||||||
setOperatorCompanyId('');
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((requestError) => setError(errorMessage(requestError)));
|
.catch((requestError) => setError(errorMessage(requestError)));
|
||||||
}, [editing, genericContext, parentId]);
|
}, [editing, genericContext, parentId]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!editing || !genericContext || !operationalAreaId) {
|
|
||||||
setCompanies([]);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
listCompaniesForArea(operationalAreaId)
|
|
||||||
.then((items) => {
|
|
||||||
setCompanies(items);
|
|
||||||
if (operatorCompanyId && !items.some((item) => item.id === operatorCompanyId)) setOperatorCompanyId('');
|
|
||||||
})
|
|
||||||
.catch((requestError) => setError(errorMessage(requestError)));
|
|
||||||
}, [editing, genericContext, operationalAreaId]);
|
|
||||||
|
|
||||||
const beginEdit = () => {
|
const beginEdit = () => {
|
||||||
setParentId(asset.parent?.id ?? '');
|
setParentId(asset.parent?.id ?? '');
|
||||||
setOperationalAreaId(asset.operationalArea?.id ?? '');
|
setOperationalAreaId(asset.operationalArea?.id ?? '');
|
||||||
setOperatorCompanyId(asset.operatorCompany?.id ?? '');
|
|
||||||
setEffectiveAt(localDateTimeNow());
|
setEffectiveAt(localDateTimeNow());
|
||||||
setReason('');
|
setReason('');
|
||||||
setError('');
|
setError('');
|
||||||
@@ -133,13 +114,12 @@ export function AssetContextHistoryPanel({
|
|||||||
const saved = await changeAssetContext(asset.id, {
|
const saved = await changeAssetContext(asset.id, {
|
||||||
parentId: parentId || null,
|
parentId: parentId || null,
|
||||||
operationalAreaId: genericContext ? operationalAreaId || null : asset.operationalArea?.id ?? null,
|
operationalAreaId: genericContext ? operationalAreaId || null : asset.operationalArea?.id ?? null,
|
||||||
operatorCompanyId: genericContext ? operatorCompanyId || null : asset.operatorCompany?.id ?? null,
|
|
||||||
effectiveAt: effectiveAt ? new Date(effectiveAt).toISOString() : undefined,
|
effectiveAt: effectiveAt ? new Date(effectiveAt).toISOString() : undefined,
|
||||||
reason,
|
reason,
|
||||||
});
|
});
|
||||||
onChanged(saved);
|
onChanged(saved);
|
||||||
setEditing(false);
|
setEditing(false);
|
||||||
setSuccess('Contexto actualizado. La asignación anterior quedó preservada en el historial.');
|
setSuccess('Contexto físico actualizado. La asignación anterior quedó preservada en el historial.');
|
||||||
loadHistory();
|
loadHistory();
|
||||||
} catch (requestError) {
|
} catch (requestError) {
|
||||||
setError(errorMessage(requestError));
|
setError(errorMessage(requestError));
|
||||||
@@ -150,30 +130,29 @@ export function AssetContextHistoryPanel({
|
|||||||
|
|
||||||
return <article className="panel asset-history-panel">
|
return <article className="panel asset-history-panel">
|
||||||
<div className="panel-heading">
|
<div className="panel-heading">
|
||||||
<div><span className="eyebrow">CONTEXTO TEMPORAL</span><h2>Jerarquía, Área y Operadora</h2></div>
|
<div><span className="eyebrow">CONTEXTO TEMPORAL</span><h2>Jerarquía y Área</h2></div>
|
||||||
{canManage && !editing && <button type="button" className="button secondary" onClick={beginEdit}><Icon name="edit" />Cambiar contexto</button>}
|
{canManage && !editing && <button type="button" className="button secondary" onClick={beginEdit}><Icon name="edit" />Cambiar contexto físico</button>}
|
||||||
</div>
|
</div>
|
||||||
<p className="section-copy">Los cambios no reemplazan la historia. Cada asignación conserva desde cuándo fue válida y qué relación la reemplazó.</p>
|
<p className="section-copy">Los cambios físicos no reemplazan la historia. La Operadora se administra por separado en las relaciones temporales del Área.</p>
|
||||||
{error && <Alert>{error}</Alert>}
|
{error && <Alert>{error}</Alert>}
|
||||||
{success && <Alert type="success">{success}</Alert>}
|
{success && <Alert type="success">{success}</Alert>}
|
||||||
|
|
||||||
{current && <div className="temporal-notice"><Icon name="layers" /><p><strong>Contexto vigente.</strong> {contextLabel(current)}</p></div>}
|
{current && <div className="temporal-notice"><Icon name="layers" /><p><strong>Contexto físico vigente.</strong> {contextLabel(current)}</p></div>}
|
||||||
|
|
||||||
{editing && <form className="form-section" onSubmit={save}>
|
{editing && <form className="form-section" onSubmit={save}>
|
||||||
<div><h3>Cambiar contexto vigente</h3><p className="section-copy">Indicá el nuevo lugar dentro del Inventario y el motivo. La relación anterior se cierra automáticamente.</p></div>
|
<div><h3>Cambiar contexto físico vigente</h3><p className="section-copy">Indicá la nueva ubicación dentro del Inventario y el motivo. La relación física anterior se cierra automáticamente.</p></div>
|
||||||
<div className="form-grid">
|
<div className="form-grid">
|
||||||
<div className="field parent-picker"><span>Registro padre</span><input className="parent-search" value={parentSearch} onChange={(event) => setParentSearch(event.target.value)} placeholder="Buscar registro padre…" /><SearchableSelect value={parentId} onChange={(event) => { setParentId(event.target.value); setParentSearch(''); }} required={!type.canBeRoot}><option value="">{type.canBeRoot ? 'Sin padre · registro raíz' : 'Seleccionar registro padre…'}</option>{parents.map((parent) => <option key={parent.id} value={parent.id}>{parent.name} · {parent.code} ({parent.type.name})</option>)}</SearchableSelect></div>
|
<div className="field parent-picker"><span>Registro padre</span><input className="parent-search" value={parentSearch} onChange={(event) => setParentSearch(event.target.value)} placeholder="Buscar registro padre…" /><SearchableSelect value={parentId} onChange={(event) => { setParentId(event.target.value); setParentSearch(''); }} required={!type.canBeRoot}><option value="">{type.canBeRoot ? 'Sin padre · registro raíz' : 'Seleccionar registro padre…'}</option>{parents.map((parent) => <option key={parent.id} value={parent.id}>{parent.name} · {parent.code} ({parent.type.name})</option>)}</SearchableSelect></div>
|
||||||
<label className="field"><span>Vigente desde</span><input type="datetime-local" value={effectiveAt} onChange={(event) => setEffectiveAt(event.target.value)} required /><small>Puede registrarse una vigencia pasada si corresponde a un cambio ya ocurrido.</small></label>
|
<label className="field"><span>Vigente desde</span><input type="datetime-local" value={effectiveAt} onChange={(event) => setEffectiveAt(event.target.value)} required /><small>Puede registrarse una vigencia pasada si corresponde a un cambio ya ocurrido.</small></label>
|
||||||
</div>
|
</div>
|
||||||
{genericContext && <div className="form-grid">
|
{genericContext && <div className="form-grid">
|
||||||
<label className="field"><span>Área</span><SearchableSelect value={operationalAreaId} onChange={(event) => { setOperationalAreaId(event.target.value); setOperatorCompanyId(''); }} required><option value="">Seleccionar Área…</option>{areas.map((area) => <option key={area.id} value={area.id}>{area.name}</option>)}</SearchableSelect></label>
|
<label className="field"><span>Área</span><SearchableSelect value={operationalAreaId} onChange={(event) => setOperationalAreaId(event.target.value)} required><option value="">Seleccionar Área…</option>{areas.map((area) => <option key={area.id} value={area.id}>{area.name}</option>)}</SearchableSelect><small>La Operadora vigente se resuelve desde la relación temporal del Área.</small></label>
|
||||||
<label className="field"><span>Operadora</span><SearchableSelect value={operatorCompanyId} onChange={(event) => setOperatorCompanyId(event.target.value)} required disabled={!operationalAreaId}><option value="">{operationalAreaId ? 'Seleccionar Operadora…' : 'Primero seleccioná un Área'}</option>{companies.map((company) => <option key={company.id} value={company.id}>{company.name}</option>)}</SearchableSelect></label>
|
|
||||||
</div>}
|
</div>}
|
||||||
<label className="field"><span>Motivo del cambio</span><textarea value={reason} onChange={(event) => setReason(event.target.value)} minLength={5} maxLength={2000} rows={3} required placeholder="Ej.: transferencia operativa, corrección documental, reubicación física…" /></label>
|
<label className="field"><span>Motivo del cambio</span><textarea value={reason} onChange={(event) => setReason(event.target.value)} minLength={5} maxLength={2000} rows={3} required placeholder="Ej.: corrección documental, reubicación física, ajuste de jerarquía…" /></label>
|
||||||
<div className="form-actions"><button type="button" className="button secondary" onClick={() => setEditing(false)} disabled={saving}>Cancelar</button><button className="button primary" disabled={saving || reason.trim().length < 5}><Icon name="check" />{saving ? 'Registrando…' : 'Registrar cambio'}</button></div>
|
<div className="form-actions"><button type="button" className="button secondary" onClick={() => setEditing(false)} disabled={saving}>Cancelar</button><button className="button primary" disabled={saving || reason.trim().length < 5}><Icon name="check" />{saving ? 'Registrando…' : 'Registrar cambio físico'}</button></div>
|
||||||
</form>}
|
</form>}
|
||||||
|
|
||||||
<div className="form-section"><div><h3>Historial de contexto</h3><p className="section-copy">Se muestra la secuencia completa de relaciones conocidas del elemento.</p></div>
|
<div className="form-section"><div><h3>Historial de contexto físico</h3><p className="section-copy">Se muestra la secuencia completa de ubicaciones conocidas del elemento.</p></div>
|
||||||
{loading ? <LoadingBlock label="Cargando contexto…" /> : history.length === 0 ? <div className="inline-empty">Todavía no hay contexto histórico registrado.</div> : <div className="asset-timeline">{history.map((item) => <div className="timeline-entry" key={item.id}><span className={`timeline-dot ${item.isCurrent ? 'current' : ''}`} /><span><strong>{item.isCurrent ? 'Vigente' : 'Histórico'} · v{item.assetVersionNumber}</strong><small>{formatDate(item.validFrom)} → {item.validUntil ? formatDate(item.validUntil) : 'actualidad'}{item.creator ? ` · ${item.creator.username}` : ''}</small><span>{contextLabel(item)}</span><small>{item.changeReason}</small></span></div>)}</div>}
|
{loading ? <LoadingBlock label="Cargando contexto…" /> : history.length === 0 ? <div className="inline-empty">Todavía no hay contexto histórico registrado.</div> : <div className="asset-timeline">{history.map((item) => <div className="timeline-entry" key={item.id}><span className={`timeline-dot ${item.isCurrent ? 'current' : ''}`} /><span><strong>{item.isCurrent ? 'Vigente' : 'Histórico'} · v{item.assetVersionNumber}</strong><small>{formatDate(item.validFrom)} → {item.validUntil ? formatDate(item.validUntil) : 'actualidad'}{item.creator ? ` · ${item.creator.username}` : ''}</small><span>{contextLabel(item)}</span><small>{item.changeReason}</small></span></div>)}</div>}
|
||||||
</div>
|
</div>
|
||||||
</article>;
|
</article>;
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ export async function searchInventoryMergeCandidates(
|
|||||||
source: AssetDetail,
|
source: AssetDetail,
|
||||||
search = '',
|
search = '',
|
||||||
): Promise<AssetListItem[]> {
|
): Promise<AssetListItem[]> {
|
||||||
if (!source.parent?.id || !source.operationalArea?.id || !source.operatorCompany?.id) return [];
|
if (!source.parent?.id || !source.operationalArea?.id) return [];
|
||||||
const page = await listAssets({
|
const page = await listAssets({
|
||||||
page: 1,
|
page: 1,
|
||||||
pageSize: 80,
|
pageSize: 80,
|
||||||
@@ -78,7 +78,6 @@ export async function searchInventoryMergeCandidates(
|
|||||||
typeId: source.type.id,
|
typeId: source.type.id,
|
||||||
parentId: source.parent.id,
|
parentId: source.parent.id,
|
||||||
operationalAreaId: source.operationalArea.id,
|
operationalAreaId: source.operationalArea.id,
|
||||||
operatorCompanyId: source.operatorCompany.id,
|
|
||||||
});
|
});
|
||||||
return page.data.filter((candidate) =>
|
return page.data.filter((candidate) =>
|
||||||
candidate.id !== source.id && candidate.informationStatus !== 'INACTIVE',
|
candidate.id !== source.id && candidate.informationStatus !== 'INACTIVE',
|
||||||
|
|||||||
@@ -144,7 +144,6 @@ export function AssetEditorPage() {
|
|||||||
const parentType = types.find((type) => type.id === parent.type.id);
|
const parentType = types.find((type) => type.id === parent.type.id);
|
||||||
if (parentType?.operationalRole === 'AREA') setOperationalAreaId(parent.id);
|
if (parentType?.operationalRole === 'AREA') setOperationalAreaId(parent.id);
|
||||||
else if (parent.operationalArea) setOperationalAreaId(parent.operationalArea.id);
|
else if (parent.operationalArea) setOperationalAreaId(parent.operationalArea.id);
|
||||||
if (parent.operatorCompany) setOperatorCompanyId(parent.operatorCompany.id);
|
|
||||||
}
|
}
|
||||||
}).catch((requestError) => setError(errorMessage(requestError)));
|
}).catch((requestError) => setError(errorMessage(requestError)));
|
||||||
}, [editing, contextParentId, types]);
|
}, [editing, contextParentId, types]);
|
||||||
@@ -158,21 +157,36 @@ export function AssetEditorPage() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!canReadRelations || selectedType?.operationalRole !== 'GENERIC' || !parentId) {
|
if (!canReadRelations || selectedType?.operationalRole !== 'GENERIC' || !parentId) {
|
||||||
setOperationalAreas([]);
|
setOperationalAreas([]);
|
||||||
if (!parentId) { setOperationalAreaId(''); setOperatorCompanyId(''); }
|
if (!parentId) { setOperationalAreaId(''); if (!editing) setOperatorCompanyId(''); }
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
listOperationalAreas(parentId).then((loadedAreas) => {
|
listOperationalAreas(parentId).then((loadedAreas) => {
|
||||||
setOperationalAreas(loadedAreas);
|
setOperationalAreas(loadedAreas);
|
||||||
if (operationalAreaId && !loadedAreas.some((area) => area.id === operationalAreaId)) { setOperationalAreaId(''); setOperatorCompanyId(''); }
|
if (operationalAreaId && !loadedAreas.some((area) => area.id === operationalAreaId)) {
|
||||||
|
setOperationalAreaId('');
|
||||||
|
if (!editing) setOperatorCompanyId('');
|
||||||
|
}
|
||||||
}).catch((requestError) => setError(errorMessage(requestError)));
|
}).catch((requestError) => setError(errorMessage(requestError)));
|
||||||
}, [canReadRelations, selectedType?.operationalRole, parentId]);
|
}, [canReadRelations, selectedType?.operationalRole, parentId, editing]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!canReadRelations || !operationalAreaId || selectedType?.operationalRole !== 'GENERIC') { setOperationalCompanies([]); return; }
|
if (editing || !canReadRelations || !operationalAreaId || selectedType?.operationalRole !== 'GENERIC') {
|
||||||
listCompaniesForArea(operationalAreaId).then(setOperationalCompanies).catch((requestError) => setError(errorMessage(requestError)));
|
setOperationalCompanies([]);
|
||||||
}, [canReadRelations, operationalAreaId, selectedType?.operationalRole]);
|
return;
|
||||||
|
}
|
||||||
|
listCompaniesForArea(operationalAreaId).then((loadedCompanies) => {
|
||||||
|
setOperationalCompanies(loadedCompanies);
|
||||||
|
setOperatorCompanyId((current) => loadedCompanies.some((company) => company.id === current)
|
||||||
|
? current
|
||||||
|
: loadedCompanies.length === 1 ? (loadedCompanies[0]?.id ?? '') : '');
|
||||||
|
}).catch((requestError) => {
|
||||||
|
setOperationalCompanies([]);
|
||||||
|
setOperatorCompanyId('');
|
||||||
|
setError(errorMessage(requestError));
|
||||||
|
});
|
||||||
|
}, [editing, canReadRelations, operationalAreaId, selectedType?.operationalRole]);
|
||||||
|
|
||||||
const changeType = (nextTypeId: string) => { setTypeId(nextTypeId); setParentId(''); setOperationalAreaId(''); setOperatorCompanyId(''); setAttributeValues({}); setParentSearch(''); };
|
const changeType = (nextTypeId: string) => { setTypeId(nextTypeId); setParentId(''); setOperationalAreaId(''); if (!editing) setOperatorCompanyId(''); setAttributeValues({}); setParentSearch(''); };
|
||||||
const setAttribute = (definitionId: string, value: unknown) => setAttributeValues((current) => ({ ...current, [definitionId]: value }));
|
const setAttribute = (definitionId: string, value: unknown) => setAttributeValues((current) => ({ ...current, [definitionId]: value }));
|
||||||
|
|
||||||
const save = async (event: FormEvent) => {
|
const save = async (event: FormEvent) => {
|
||||||
@@ -182,7 +196,7 @@ export function AssetEditorPage() {
|
|||||||
const attributes = normalizeAttributeValues(definitions, attributeValues);
|
const attributes = normalizeAttributeValues(definitions, attributeValues);
|
||||||
let saved: AssetDetail;
|
let saved: AssetDetail;
|
||||||
if (editing && id) {
|
if (editing && id) {
|
||||||
if (canEdit) saved = await updateAsset(id, { typeId: canDirectContextEdit ? typeId : undefined, code, name, commonName: commonName.trim() || null, parentId: canDirectContextEdit ? parentId || null : undefined, operationalAreaId: canDirectContextEdit ? operationalAreaId || null : undefined, operatorCompanyId: canDirectContextEdit ? operatorCompanyId || null : undefined, description: description.trim() || null, attributes });
|
if (canEdit) saved = await updateAsset(id, { typeId: canDirectContextEdit ? typeId : undefined, code, name, commonName: commonName.trim() || null, parentId: canDirectContextEdit ? parentId || null : undefined, operationalAreaId: canDirectContextEdit ? operationalAreaId || null : undefined, description: description.trim() || null, attributes });
|
||||||
else if (asset) saved = asset; else return;
|
else if (asset) saved = asset; else return;
|
||||||
if (canChangeStatus && saved.informationStatus !== status) saved = await updateAssetInformationStatus(id, status);
|
if (canChangeStatus && saved.informationStatus !== status) saved = await updateAssetInformationStatus(id, status);
|
||||||
if (canChangeOperationalStatus && saved.operationalStatus !== operationalStatus) saved = await updateAssetOperationalStatus(id, operationalStatus);
|
if (canChangeOperationalStatus && saved.operationalStatus !== operationalStatus) saved = await updateAssetOperationalStatus(id, operationalStatus);
|
||||||
@@ -229,9 +243,9 @@ export function AssetEditorPage() {
|
|||||||
<form className="panel form-panel" onSubmit={save}>
|
<form className="panel form-panel" onSubmit={save}>
|
||||||
<div className="form-section"><div><h2>Identificación</h2><p className="section-copy">Conservá el nombre técnico y, cuando exista, agregá el nombre habitual usado en campo.</p></div><div className="form-grid"><label className="field"><span>Código DH</span><input value={code} onChange={(event) => setCode(event.target.value.toUpperCase())} disabled={!canEdit} required maxLength={120} pattern="[A-Z0-9][A-Z0-9._/-]*" /></label><label className="field"><span>Nombre técnico</span><input value={name} onChange={(event) => setName(event.target.value)} disabled={!canEdit} required maxLength={200} /></label><label className="field"><span>Nombre habitual / sobrenombre <em>opcional</em></span><input value={commonName} onChange={(event) => setCommonName(event.target.value)} disabled={!canEdit} maxLength={200} placeholder="Ej.: tanque grande, ET vieja, batería norte…" /><small>También se usa en las búsquedas del Inventario.</small></label></div><label className="field"><span>Descripción <em>opcional</em></span><textarea value={description} onChange={(event) => setDescription(event.target.value)} disabled={!canEdit} maxLength={4000} rows={2} /></label></div>
|
<div className="form-section"><div><h2>Identificación</h2><p className="section-copy">Conservá el nombre técnico y, cuando exista, agregá el nombre habitual usado en campo.</p></div><div className="form-grid"><label className="field"><span>Código DH</span><input value={code} onChange={(event) => setCode(event.target.value.toUpperCase())} disabled={!canEdit} required maxLength={120} pattern="[A-Z0-9][A-Z0-9._/-]*" /></label><label className="field"><span>Nombre técnico</span><input value={name} onChange={(event) => setName(event.target.value)} disabled={!canEdit} required maxLength={200} /></label><label className="field"><span>Nombre habitual / sobrenombre <em>opcional</em></span><input value={commonName} onChange={(event) => setCommonName(event.target.value)} disabled={!canEdit} maxLength={200} placeholder="Ej.: tanque grande, ET vieja, batería norte…" /><small>También se usa en las búsquedas del Inventario.</small></label></div><label className="field"><span>Descripción <em>opcional</em></span><textarea value={description} onChange={(event) => setDescription(event.target.value)} disabled={!canEdit} maxLength={4000} rows={2} /></label></div>
|
||||||
|
|
||||||
<div className="form-section"><div><h2>Ubicación en la estructura</h2><p className="section-copy">Elegí qué es y dónde está contenido. El contexto Área–Operadora se completa a partir de esa ubicación cuando es posible. Los registros ya consolidados cambian de contexto desde el bloque histórico inferior.</p></div><div className="form-grid"><label className="field"><span>Tipo de elemento</span><SearchableSelect value={typeId} onChange={(event) => changeType(event.target.value)} disabled={(editing && !(asset?.dataOrigin === 'FIELD_SURVEY' && asset.informationStatus === 'DRAFT')) || !canEdit} required><option value="">Seleccionar…</option>{types.filter((type) => type.isActive || type.id === typeId).map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}</SearchableSelect></label><div className="field parent-picker"><span>Registro padre {!selectedType?.canBeRoot && <em>obligatorio</em>}</span><input className="parent-search" value={parentSearch} onChange={(event) => setParentSearch(event.target.value)} disabled={!canEdit || !canDirectContextEdit} placeholder="Buscar planta, batería, estación…" /><SearchableSelect value={parentId} onChange={(event) => { setParentId(event.target.value); setParentSearch(''); }} disabled={!canEdit || !canDirectContextEdit} required={!selectedType?.canBeRoot}><option value="">{selectedType?.canBeRoot ? 'Sin padre · registro raíz' : 'Seleccionar registro padre…'}</option>{parents.map((parent) => <option key={parent.id} value={parent.id}>{parent.name} · {parent.code} ({parent.type.name})</option>)}</SearchableSelect><small>Escribí para buscar entre los registros compatibles.</small></div></div><div className="form-grid">{canChangeStatus && <label className="field"><span>Estado del dato</span><SearchableSelect value={status} onChange={(event) => setStatus(event.target.value as AssetInformationStatus)} disabled={!canEdit && !canChangeStatus}>{ASSET_STATUSES.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</SearchableSelect><small>Calidad y validación del registro.</small></label>}{editing && canChangeOperationalStatus && <label className="field"><span>Estado operativo</span><SearchableSelect value={operationalStatus} onChange={(event) => setOperationalStatus(event.target.value as AssetOperationalStatus)}>{ASSET_OPERATIONAL_STATUSES.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</SearchableSelect><small>Situación física u operativa del elemento.</small></label>}</div></div>
|
<div className="form-section"><div><h2>Ubicación en la estructura</h2><p className="section-copy">Elegí qué es y dónde está contenido. La ubicación física es independiente de la Operadora del Área. Los registros ya consolidados cambian de ubicación desde el bloque histórico inferior.</p></div><div className="form-grid"><label className="field"><span>Tipo de elemento</span><SearchableSelect value={typeId} onChange={(event) => changeType(event.target.value)} disabled={(editing && !(asset?.dataOrigin === 'FIELD_SURVEY' && asset.informationStatus === 'DRAFT')) || !canEdit} required><option value="">Seleccionar…</option>{types.filter((type) => type.isActive || type.id === typeId).map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}</SearchableSelect></label><div className="field parent-picker"><span>Registro padre {!selectedType?.canBeRoot && <em>obligatorio</em>}</span><input className="parent-search" value={parentSearch} onChange={(event) => setParentSearch(event.target.value)} disabled={!canEdit || !canDirectContextEdit} placeholder="Buscar planta, batería, estación…" /><SearchableSelect value={parentId} onChange={(event) => { setParentId(event.target.value); setParentSearch(''); }} disabled={!canEdit || !canDirectContextEdit} required={!selectedType?.canBeRoot}><option value="">{selectedType?.canBeRoot ? 'Sin padre · registro raíz' : 'Seleccionar registro padre…'}</option>{parents.map((parent) => <option key={parent.id} value={parent.id}>{parent.name} · {parent.code} ({parent.type.name})</option>)}</SearchableSelect><small>Escribí para buscar entre los registros compatibles.</small></div></div><div className="form-grid">{canChangeStatus && <label className="field"><span>Estado del dato</span><SearchableSelect value={status} onChange={(event) => setStatus(event.target.value as AssetInformationStatus)} disabled={!canEdit && !canChangeStatus}>{ASSET_STATUSES.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</SearchableSelect><small>Calidad y validación del registro.</small></label>}{editing && canChangeOperationalStatus && <label className="field"><span>Estado operativo</span><SearchableSelect value={operationalStatus} onChange={(event) => setOperationalStatus(event.target.value as AssetOperationalStatus)}>{ASSET_OPERATIONAL_STATUSES.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</SearchableSelect><small>Situación física u operativa del elemento.</small></label>}</div></div>
|
||||||
|
|
||||||
{selectedType?.operationalRole === 'GENERIC' && canReadRelations && <div className="form-section"><div><h2>Área y operadora</h2><p className="section-copy">Sólo necesitás revisar estos campos. La jerarquía física sigue siendo independiente.</p></div><div className="form-grid"><label className="field"><span>Área</span><SearchableSelect value={operationalAreaId} onChange={(event) => { setOperationalAreaId(event.target.value); setOperatorCompanyId(''); }} disabled={!canEdit || !canDirectContextEdit}><option value="">Sin asignación operativa</option>{operationalAreas.map((area) => <option key={area.id} value={area.id}>{area.name}</option>)}</SearchableSelect></label><label className="field"><span>Operadora {operationalAreaId && <em>obligatoria</em>}</span><SearchableSelect value={operatorCompanyId} onChange={(event) => setOperatorCompanyId(event.target.value)} disabled={!canEdit || !canDirectContextEdit || !operationalAreaId} required={Boolean(operationalAreaId)}><option value="">{operationalAreaId ? 'Seleccionar operadora…' : 'Primero seleccioná un área'}</option>{operationalCompanies.map((company) => <option key={company.id} value={company.id}>{company.name}</option>)}</SearchableSelect></label></div>{operationalAreaId && operatorCompanyId && <div className="temporal-notice"><Icon name="check" /><p><strong>Contexto confirmado.</strong> El registro pertenece a esta Área y tiene una única Operadora activa.</p></div>}</div>}
|
{selectedType?.operationalRole === 'GENERIC' && canReadRelations && <div className="form-section"><div><h2>{editing ? 'Área física' : 'Área y operadora al alta'}</h2><p className="section-copy">{editing ? 'El Inventario pertenece físicamente al Área. La Operadora vigente se administra en las relaciones temporales del Área y no se reescribe dentro del Inventario.' : 'Al crear el registro, la Operadora activa del Área queda guardada únicamente como snapshot histórico de alta.'}</p></div><div className="form-grid"><label className="field"><span>Área</span><SearchableSelect value={operationalAreaId} onChange={(event) => { setOperationalAreaId(event.target.value); if (!editing) setOperatorCompanyId(''); }} disabled={!canEdit || !canDirectContextEdit}><option value="">Sin asignación operativa</option>{operationalAreas.map((area) => <option key={area.id} value={area.id}>{area.name}</option>)}</SearchableSelect>{editing && <small>La Operadora se resuelve por la relación Área↔Empresa vigente.</small>}</label>{!editing && <label className="field"><span>Operadora {operationalAreaId && <em>obligatoria</em>}</span><SearchableSelect value={operatorCompanyId} onChange={(event) => setOperatorCompanyId(event.target.value)} disabled={!canEdit || !operationalAreaId} required={Boolean(operationalAreaId)}><option value="">{operationalAreaId ? 'Seleccionar operadora…' : 'Primero seleccioná un área'}</option>{operationalCompanies.map((company) => <option key={company.id} value={company.id}>{company.name}</option>)}</SearchableSelect></label>}</div>{!editing && operationalAreaId && operatorCompanyId && <div className="temporal-notice"><Icon name="check" /><p><strong>Contexto de alta confirmado.</strong> La Operadora seleccionada se conservará como referencia histórica; futuros cambios se harán en la relación temporal del Área.</p></div>}{editing && asset?.operatorCompany && <div className="temporal-notice"><Icon name="layers" /><p><strong>Snapshot histórico de alta:</strong> {asset.operatorCompany.name}. No se modifica desde este registro.</p></div>}</div>}
|
||||||
|
|
||||||
<div className="form-section"><div><h2>Datos técnicos</h2><p className="section-copy">Campos definidos para el tipo seleccionado.</p></div>{definitions.length === 0 ? <div className="inline-empty">Este tipo no requiere datos técnicos adicionales.</div> : <div className="dynamic-attributes">{definitions.map((definition) => { const value = attributeValues[definition.id]; const label = <span>{definition.name}{definition.unit ? ` (${definition.unit})` : ''}{definition.isRequired ? <em>obligatorio</em> : <em>opcional</em>}</span>; if (definition.dataType === 'BOOLEAN') return <label className="check-row attribute-check" key={definition.id}><input type="checkbox" checked={Boolean(value)} onChange={(event) => setAttribute(definition.id, event.target.checked)} disabled={!canEdit} /><span><strong>{definition.name}</strong><small>{definition.code}</small></span></label>; if (definition.dataType === 'SELECT') return <label className="field" key={definition.id}>{label}<SearchableSelect value={String(value ?? '')} onChange={(event) => setAttribute(definition.id, event.target.value)} disabled={!canEdit} required={definition.isRequired}><option value="">Seleccionar…</option>{definition.options?.map((option) => <option key={option} value={option}>{option}</option>)}</SearchableSelect></label>; const inputType = definition.dataType === 'NUMBER' ? 'number' : definition.dataType === 'DATE' ? 'date' : definition.dataType === 'DATETIME' ? 'datetime-local' : 'text'; return <label className="field" key={definition.id}>{label}<input type={inputType} value={String(value ?? '')} onChange={(event) => setAttribute(definition.id, event.target.value)} disabled={!canEdit} required={definition.isRequired} step={definition.dataType === 'NUMBER' ? 'any' : undefined} maxLength={definition.dataType === 'TEXT' ? 4000 : undefined} /></label>; })}</div>}</div>
|
<div className="form-section"><div><h2>Datos técnicos</h2><p className="section-copy">Campos definidos para el tipo seleccionado.</p></div>{definitions.length === 0 ? <div className="inline-empty">Este tipo no requiere datos técnicos adicionales.</div> : <div className="dynamic-attributes">{definitions.map((definition) => { const value = attributeValues[definition.id]; const label = <span>{definition.name}{definition.unit ? ` (${definition.unit})` : ''}{definition.isRequired ? <em>obligatorio</em> : <em>opcional</em>}</span>; if (definition.dataType === 'BOOLEAN') return <label className="check-row attribute-check" key={definition.id}><input type="checkbox" checked={Boolean(value)} onChange={(event) => setAttribute(definition.id, event.target.checked)} disabled={!canEdit} /><span><strong>{definition.name}</strong><small>{definition.code}</small></span></label>; if (definition.dataType === 'SELECT') return <label className="field" key={definition.id}>{label}<SearchableSelect value={String(value ?? '')} onChange={(event) => setAttribute(definition.id, event.target.value)} disabled={!canEdit} required={definition.isRequired}><option value="">Seleccionar…</option>{definition.options?.map((option) => <option key={option} value={option}>{option}</option>)}</SearchableSelect></label>; const inputType = definition.dataType === 'NUMBER' ? 'number' : definition.dataType === 'DATE' ? 'date' : definition.dataType === 'DATETIME' ? 'datetime-local' : 'text'; return <label className="field" key={definition.id}>{label}<input type={inputType} value={String(value ?? '')} onChange={(event) => setAttribute(definition.id, event.target.value)} disabled={!canEdit} required={definition.isRequired} step={definition.dataType === 'NUMBER' ? 'any' : undefined} maxLength={definition.dataType === 'TEXT' ? 4000 : undefined} /></label>; })}</div>}</div>
|
||||||
{canSave && <div className="form-actions"><Link className="button secondary" to="/inventarios">Cancelar</Link><button className="button primary" disabled={saving}><Icon name="check" />{saving ? 'Guardando…' : editing && !canEdit ? 'Actualizar estado' : editing ? 'Guardar cambios' : 'Crear registro'}</button></div>}
|
{canSave && <div className="form-actions"><Link className="button secondary" to="/inventarios">Cancelar</Link><button className="button primary" disabled={saving}><Icon name="check" />{saving ? 'Guardando…' : editing && !canEdit ? 'Actualizar estado' : editing ? 'Guardar cambios' : 'Crear registro'}</button></div>}
|
||||||
|
|||||||
@@ -86,7 +86,6 @@ export function FieldDiscoveriesPage() {
|
|||||||
pageSize: 12,
|
pageSize: 12,
|
||||||
search: matchSearch.trim(),
|
search: matchSearch.trim(),
|
||||||
operationalAreaId: matchFor.asset.operationalAreaId ?? undefined,
|
operationalAreaId: matchFor.asset.operationalAreaId ?? undefined,
|
||||||
operatorCompanyId: matchFor.asset.operatorCompanyId ?? undefined,
|
|
||||||
});
|
});
|
||||||
setCandidates(response.data.filter((candidate) => candidate.id !== matchFor.asset.id && candidate.informationStatus !== 'INACTIVE'));
|
setCandidates(response.data.filter((candidate) => candidate.id !== matchFor.asset.id && candidate.informationStatus !== 'INACTIVE'));
|
||||||
} catch (requestError) { setError(errorMessage(requestError)); }
|
} catch (requestError) { setError(errorMessage(requestError)); }
|
||||||
@@ -147,7 +146,7 @@ export function FieldDiscoveriesPage() {
|
|||||||
</div>}
|
</div>}
|
||||||
|
|
||||||
{matchFor && <div className="panel field-discovery-match-panel">
|
{matchFor && <div className="panel field-discovery-match-panel">
|
||||||
<div className="panel-heading"><div><span className="eyebrow">CONCILIAR</span><h2>Buscar registro existente</h2><p className="section-copy">Buscá dentro de la misma Empresa y Área. El alta de campo se archivará, pero su historial no se elimina.</p></div><button className="button text" onClick={() => setMatchFor(null)}>Cerrar</button></div>
|
<div className="panel-heading"><div><span className="eyebrow">CONCILIAR</span><h2>Buscar registro existente</h2><p className="section-copy">Buscá dentro de la misma Área física. El alta de campo se archivará, pero su historial no se elimina.</p></div><button className="button text" onClick={() => setMatchFor(null)}>Cerrar</button></div>
|
||||||
<form className="asset-center-search" onSubmit={searchMatches}><Icon name="search" /><input value={matchSearch} onChange={(event) => setMatchSearch(event.target.value)} placeholder="Nombre, sobrenombre o código existente…" /><button className="button primary" disabled={matchLoading}>{matchLoading ? 'Buscando…' : 'Buscar'}</button></form>
|
<form className="asset-center-search" onSubmit={searchMatches}><Icon name="search" /><input value={matchSearch} onChange={(event) => setMatchSearch(event.target.value)} placeholder="Nombre, sobrenombre o código existente…" /><button className="button primary" disabled={matchLoading}>{matchLoading ? 'Buscando…' : 'Buscar'}</button></form>
|
||||||
{candidates.length > 0 && <div className="table-scroll"><table><thead><tr><th>Registro existente</th><th>Tipo</th><th /></tr></thead><tbody>{candidates.map((candidate) => <tr key={candidate.id}><td><strong>{candidate.name}</strong><small className="cell-subtext">{candidate.code}{candidate.commonName ? ` · ${candidate.commonName}` : ''}</small></td><td>{candidate.type.name}</td><td className="action-cell"><button className="button primary compact" onClick={() => chooseMatch(candidate)}>Usar esta coincidencia</button></td></tr>)}</tbody></table></div>}
|
{candidates.length > 0 && <div className="table-scroll"><table><thead><tr><th>Registro existente</th><th>Tipo</th><th /></tr></thead><tbody>{candidates.map((candidate) => <tr key={candidate.id}><td><strong>{candidate.name}</strong><small className="cell-subtext">{candidate.code}{candidate.commonName ? ` · ${candidate.commonName}` : ''}</small></td><td>{candidate.type.name}</td><td className="action-cell"><button className="button primary compact" onClick={() => chooseMatch(candidate)}>Usar esta coincidencia</button></td></tr>)}</tbody></table></div>}
|
||||||
</div>}
|
</div>}
|
||||||
|
|||||||
@@ -175,7 +175,6 @@ export function InspectionVisitEditorF4Page() {
|
|||||||
pageSize: 100,
|
pageSize: 100,
|
||||||
search: assetSearch.trim(),
|
search: assetSearch.trim(),
|
||||||
operationalAreaId: form.operationalAreaId,
|
operationalAreaId: form.operationalAreaId,
|
||||||
operatorCompanyId: form.operatorCompanyId,
|
|
||||||
}).then((response) => setAssets(response.data)).catch(() => undefined);
|
}).then((response) => setAssets(response.data)).catch(() => undefined);
|
||||||
}, 220);
|
}, 220);
|
||||||
return () => window.clearTimeout(timer);
|
return () => window.clearTimeout(timer);
|
||||||
|
|||||||
Reference in New Issue
Block a user