From 44f60028693d838a77241111fd19061c71a8de06 Mon Sep 17 00:00:00 2001 From: enlineawork Date: Wed, 9 Sep 2026 15:07:17 -0300 Subject: [PATCH] fix(f6.1): resolve temporal operator from area relation history --- .../asset-master/asset-temporal.service.ts | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/api-v3/src/asset-master/asset-temporal.service.ts b/api-v3/src/asset-master/asset-temporal.service.ts index 215d2f1..d1e53eb 100644 --- a/api-v3/src/asset-master/asset-temporal.service.ts +++ b/api-v3/src/asset-master/asset-temporal.service.ts @@ -137,21 +137,41 @@ export class AssetTemporalService { if (!row) throw temporalAssetNotFound(); const asOf = new Date(query.at); 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(` 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 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 LEFT JOIN assets parent ON parent.id=history.parent_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 AND history.valid_from <= $2 AND (history.valid_until IS NULL OR history.valid_until > $2) ORDER BY history.valid_from DESC LIMIT 1 - `, [assetId, asOf])) as Array<{ parent: Record | null; operationalArea: Record | null; operatorCompany: Record | null }>; + `, [assetId, asOf])) as Array<{ + parent: Record | null; + operationalArea: Record | null; + operatorCompany: Record | null; + }>; if (context && row.snapshot) { row.snapshot = { ...row.snapshot,