Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
253a3f5395 | ||
|
|
cabfcaf13d | ||
|
|
2743514346 | ||
|
|
6a5236bb56 | ||
|
|
7377cd52e8 | ||
|
|
541ef5698e | ||
|
|
f79b16b87b |
@@ -1,12 +1,22 @@
|
||||
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuditModule } from '../audit/audit.module';
|
||||
import { ActAdministrationController, ActAdministrationQueueController, ActCompanyResponseContentController } from './act-administration.controller';
|
||||
import {
|
||||
ActAdministrationController,
|
||||
ActAdministrationQueueController,
|
||||
ActCompanyResponseContentController,
|
||||
} from './act-administration.controller';
|
||||
import { ActAdministrationService } from './act-administration.service';
|
||||
import { FieldBriefingController } from './field-briefing.controller';
|
||||
import { FieldBriefingService } from './field-briefing.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuditModule],
|
||||
controllers: [ActAdministrationQueueController, ActAdministrationController, ActCompanyResponseContentController],
|
||||
providers: [ActAdministrationService],
|
||||
controllers: [
|
||||
ActAdministrationQueueController,
|
||||
ActAdministrationController,
|
||||
ActCompanyResponseContentController,
|
||||
FieldBriefingController,
|
||||
],
|
||||
providers: [ActAdministrationService, FieldBriefingService],
|
||||
})
|
||||
export class ActAdministrationModule {}
|
||||
|
||||
+1
-1
@@ -9,6 +9,6 @@ export class FieldBriefingController {
|
||||
@Get()
|
||||
@RequirePermissions('inspections.read')
|
||||
get(@Param('visitId', new ParseUUIDPipe({ version: '4' })) visitId: string) {
|
||||
return this.briefing.getForVisit(visitId);
|
||||
return this.briefing.forVisit(visitId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
export type FieldBriefingActState =
|
||||
| 'ACT_RESPONSE_OVERDUE'
|
||||
| 'ACT_RESPONSE_DUE_SOON'
|
||||
| 'WAITING_RESPONSE'
|
||||
| 'COMPANY_COMMITMENT_OVERDUE'
|
||||
| 'VERIFICATION_PENDING'
|
||||
| 'RESPONSE_RECEIVED';
|
||||
|
||||
export interface FieldBriefingFinding {
|
||||
id: string;
|
||||
code: string;
|
||||
title: string;
|
||||
status: string;
|
||||
severity: number | null;
|
||||
nextControlOn: string | null;
|
||||
asset: {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
typeName: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface FieldBriefingAct {
|
||||
actId: string;
|
||||
actCode: string;
|
||||
occurredAt: Date;
|
||||
adminState: FieldBriefingActState;
|
||||
responseDueOn: string | null;
|
||||
responseReceivedOn: string | null;
|
||||
committedCorrectionOn: string | null;
|
||||
latestResponseId: string | null;
|
||||
findings: FieldBriefingFinding[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class FieldBriefingService {
|
||||
constructor(private readonly dataSource: DataSource) {}
|
||||
|
||||
async forVisit(visitId: string) {
|
||||
const [visit] = (await this.dataSource.query(`
|
||||
SELECT
|
||||
visit.id,
|
||||
visit.code,
|
||||
visit.status,
|
||||
visit.planned_start_at AS "plannedStartAt",
|
||||
visit.operational_area_id AS "areaId",
|
||||
visit.operator_company_id AS "companyId",
|
||||
area.code AS "areaCode",
|
||||
area.name AS "areaName",
|
||||
company.code AS "companyCode",
|
||||
COALESCE(profile.legal_name, company.name) AS "companyName"
|
||||
FROM inspection_visits visit
|
||||
LEFT JOIN assets area ON area.id = visit.operational_area_id
|
||||
LEFT JOIN assets company ON company.id = visit.operator_company_id
|
||||
LEFT JOIN organization_profiles profile ON profile.asset_id = company.id
|
||||
WHERE visit.id = $1
|
||||
`, [visitId])) as Array<Record<string, unknown>>;
|
||||
|
||||
if (!visit) {
|
||||
throw new NotFoundException({
|
||||
code: 'INSPECTION_VISIT_NOT_FOUND',
|
||||
message: 'Inspección no encontrada',
|
||||
});
|
||||
}
|
||||
|
||||
const plannedOn = String(visit.plannedStartAt ?? new Date().toISOString()).slice(0, 10);
|
||||
|
||||
const rows = (await this.dataSource.query(`
|
||||
WITH prior_acts AS (
|
||||
SELECT
|
||||
act.id AS act_id,
|
||||
act.code AS act_code,
|
||||
act.occurred_at,
|
||||
deadline.response_due_on,
|
||||
response.id AS latest_response_id,
|
||||
response.received_on AS response_received_on,
|
||||
response.committed_correction_on,
|
||||
finding.id AS finding_id,
|
||||
finding.code AS finding_code,
|
||||
finding.title AS finding_title,
|
||||
finding.status AS finding_status,
|
||||
finding.severity,
|
||||
finding.next_control_on,
|
||||
asset.id AS asset_id,
|
||||
asset.code AS asset_code,
|
||||
asset.name AS asset_name,
|
||||
asset_type.name AS asset_type_name,
|
||||
CASE
|
||||
WHEN response.id IS NULL
|
||||
AND deadline.response_due_on IS NOT NULL
|
||||
AND deadline.response_due_on < $4::date
|
||||
THEN 'ACT_RESPONSE_OVERDUE'
|
||||
WHEN response.id IS NULL
|
||||
AND deadline.response_due_on IS NOT NULL
|
||||
AND deadline.response_due_on BETWEEN $4::date AND ($4::date + 3)
|
||||
THEN 'ACT_RESPONSE_DUE_SOON'
|
||||
WHEN response.id IS NOT NULL
|
||||
AND response.committed_correction_on IS NOT NULL
|
||||
AND response.committed_correction_on < $4::date
|
||||
THEN 'COMPANY_COMMITMENT_OVERDUE'
|
||||
WHEN response.id IS NOT NULL
|
||||
AND finding.next_control_on IS NULL
|
||||
THEN 'VERIFICATION_PENDING'
|
||||
WHEN response.id IS NOT NULL
|
||||
THEN 'RESPONSE_RECEIVED'
|
||||
ELSE 'WAITING_RESPONSE'
|
||||
END AS admin_state
|
||||
FROM inspection_acts act
|
||||
INNER JOIN inspection_visits source_visit ON source_visit.id = act.visit_id
|
||||
INNER JOIN inspection_findings finding ON finding.act_id = act.id
|
||||
AND finding.status = 'OPEN'
|
||||
INNER JOIN assets asset ON asset.id = finding.asset_id
|
||||
INNER JOIN asset_types asset_type ON asset_type.id = asset.asset_type_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT event.response_due_on
|
||||
FROM inspection_act_deadline_events event
|
||||
WHERE event.act_id = act.id
|
||||
ORDER BY event.created_at DESC, event.id DESC
|
||||
LIMIT 1
|
||||
) deadline ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT company_response.id, company_response.received_on, company_response.committed_correction_on
|
||||
FROM inspection_act_company_responses company_response
|
||||
WHERE company_response.act_id = act.id
|
||||
ORDER BY company_response.received_on DESC, company_response.created_at DESC, company_response.id DESC
|
||||
LIMIT 1
|
||||
) response ON true
|
||||
WHERE act.status IN ('CLOSED', 'RECTIFIED')
|
||||
AND source_visit.id <> $1
|
||||
AND source_visit.operational_area_id = $2::uuid
|
||||
AND source_visit.operator_company_id = $3::uuid
|
||||
)
|
||||
SELECT *
|
||||
FROM prior_acts
|
||||
WHERE admin_state IN (
|
||||
'ACT_RESPONSE_OVERDUE',
|
||||
'ACT_RESPONSE_DUE_SOON',
|
||||
'COMPANY_COMMITMENT_OVERDUE',
|
||||
'VERIFICATION_PENDING',
|
||||
'RESPONSE_RECEIVED'
|
||||
)
|
||||
OR next_control_on IS NOT NULL
|
||||
ORDER BY
|
||||
CASE admin_state
|
||||
WHEN 'ACT_RESPONSE_OVERDUE' THEN 1
|
||||
WHEN 'COMPANY_COMMITMENT_OVERDUE' THEN 2
|
||||
WHEN 'VERIFICATION_PENDING' THEN 3
|
||||
WHEN 'ACT_RESPONSE_DUE_SOON' THEN 4
|
||||
ELSE 5
|
||||
END,
|
||||
response_due_on NULLS LAST,
|
||||
occurred_at,
|
||||
act_code,
|
||||
finding_code
|
||||
`, [visitId, visit.areaId, visit.companyId, plannedOn])) as Array<{
|
||||
act_id: string;
|
||||
act_code: string;
|
||||
occurred_at: Date;
|
||||
response_due_on: string | null;
|
||||
latest_response_id: string | null;
|
||||
response_received_on: string | null;
|
||||
committed_correction_on: string | null;
|
||||
finding_id: string;
|
||||
finding_code: string;
|
||||
finding_title: string;
|
||||
finding_status: string;
|
||||
severity: number | null;
|
||||
next_control_on: string | null;
|
||||
asset_id: string;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
asset_type_name: string;
|
||||
admin_state: FieldBriefingActState;
|
||||
}>;
|
||||
|
||||
const byAct = new Map<string, FieldBriefingAct>();
|
||||
for (const row of rows) {
|
||||
let act = byAct.get(row.act_id);
|
||||
if (!act) {
|
||||
act = {
|
||||
actId: row.act_id,
|
||||
actCode: row.act_code,
|
||||
occurredAt: row.occurred_at,
|
||||
adminState: row.admin_state,
|
||||
responseDueOn: row.response_due_on,
|
||||
responseReceivedOn: row.response_received_on,
|
||||
committedCorrectionOn: row.committed_correction_on,
|
||||
latestResponseId: row.latest_response_id,
|
||||
findings: [],
|
||||
};
|
||||
byAct.set(row.act_id, act);
|
||||
}
|
||||
act.findings.push({
|
||||
id: row.finding_id,
|
||||
code: row.finding_code,
|
||||
title: row.finding_title,
|
||||
status: row.finding_status,
|
||||
severity: row.severity,
|
||||
nextControlOn: row.next_control_on,
|
||||
asset: {
|
||||
id: row.asset_id,
|
||||
code: row.asset_code,
|
||||
name: row.asset_name,
|
||||
typeName: row.asset_type_name,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const acts = [...byAct.values()];
|
||||
const assetIds = new Set<string>();
|
||||
let findingCount = 0;
|
||||
for (const act of acts) {
|
||||
findingCount += act.findings.length;
|
||||
for (const finding of act.findings) assetIds.add(finding.asset.id);
|
||||
}
|
||||
|
||||
return {
|
||||
inspection: {
|
||||
id: visit.id,
|
||||
code: visit.code,
|
||||
status: visit.status,
|
||||
plannedStartAt: visit.plannedStartAt,
|
||||
area: visit.areaId ? { id: visit.areaId, code: visit.areaCode, name: visit.areaName } : null,
|
||||
operatorCompany: visit.companyId ? { id: visit.companyId, code: visit.companyCode, name: visit.companyName } : null,
|
||||
},
|
||||
plannedOn,
|
||||
summary: {
|
||||
acts: acts.length,
|
||||
findings: findingCount,
|
||||
inventoryItems: assetIds.size,
|
||||
responseOverdue: acts.filter((item) => item.adminState === 'ACT_RESPONSE_OVERDUE').length,
|
||||
commitmentOverdue: acts.filter((item) => item.adminState === 'COMPANY_COMMITMENT_OVERDUE').length,
|
||||
verificationPending: acts.filter((item) => item.adminState === 'VERIFICATION_PENDING').length,
|
||||
},
|
||||
acts,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,6 @@ import { AssetImportsModule } from './asset-imports/asset-imports.module';
|
||||
import { InspectionReportsModule } from './inspection-reports/inspection-reports.module';
|
||||
import { InspectionVerificationsModule } from './inspection-verifications/inspection-verifications.module';
|
||||
import { ActAdministrationModule } from './act-administration/act-administration.module';
|
||||
import { FieldBriefingModule } from './field-briefing/field-briefing.module';
|
||||
|
||||
function required(config: ConfigService, key: string): string {
|
||||
const value = config.get<string>(key);
|
||||
@@ -79,7 +78,6 @@ function required(config: ConfigService, key: string): string {
|
||||
InspectionReportsModule,
|
||||
InspectionVerificationsModule,
|
||||
ActAdministrationModule,
|
||||
FieldBriefingModule,
|
||||
AssetImportsModule,
|
||||
],
|
||||
controllers: [HealthController],
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { FieldBriefingController } from './field-briefing.controller';
|
||||
import { FieldBriefingService } from './field-briefing.service';
|
||||
|
||||
@Module({
|
||||
controllers: [FieldBriefingController],
|
||||
providers: [FieldBriefingService],
|
||||
})
|
||||
export class FieldBriefingModule {}
|
||||
@@ -1,310 +0,0 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
export type FieldBriefingAdminState =
|
||||
| 'NEW'
|
||||
| 'WAITING_RESPONSE'
|
||||
| 'DUE_SOON'
|
||||
| 'OVERDUE'
|
||||
| 'RESPONSE_RECEIVED'
|
||||
| 'VERIFICATION_PENDING'
|
||||
| 'COMMITMENT_OVERDUE';
|
||||
|
||||
export type FieldBriefingReviewState = 'REQUIRED' | 'UPCOMING' | 'CONTEXT';
|
||||
|
||||
interface BriefingVisitRow {
|
||||
id: string;
|
||||
code: string;
|
||||
status: string;
|
||||
plannedStartAt: Date | null;
|
||||
areaId: string | null;
|
||||
areaCode: string | null;
|
||||
areaName: string | null;
|
||||
companyId: string | null;
|
||||
companyCode: string | null;
|
||||
companyName: string | null;
|
||||
}
|
||||
|
||||
interface BriefingFindingRow {
|
||||
sourceActId: string;
|
||||
sourceActCode: string;
|
||||
sourceActOccurredAt: Date;
|
||||
sourceVisitId: string;
|
||||
sourceVisitCode: string;
|
||||
responseDueOn: string | null;
|
||||
responseReceivedOn: string | null;
|
||||
committedCorrectionOn: string | null;
|
||||
latestResponseId: string | null;
|
||||
responseHasPdf: boolean;
|
||||
adminState: FieldBriefingAdminState;
|
||||
reviewState: FieldBriefingReviewState;
|
||||
reviewReason: string;
|
||||
priority: number;
|
||||
findingId: string;
|
||||
findingCode: string;
|
||||
findingTitle: string;
|
||||
severity: number | null;
|
||||
nextControlOn: string | null;
|
||||
latestVerificationOutcome: string | null;
|
||||
assetId: string;
|
||||
assetCode: string;
|
||||
assetName: string;
|
||||
assetTypeName: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class FieldBriefingService {
|
||||
constructor(private readonly dataSource: DataSource) {}
|
||||
|
||||
async getForVisit(visitId: string) {
|
||||
const [visit] = (await this.dataSource.query(`
|
||||
SELECT
|
||||
visit.id,
|
||||
visit.code,
|
||||
visit.status,
|
||||
visit.planned_start_at AS "plannedStartAt",
|
||||
visit.operational_area_id AS "areaId",
|
||||
area.code AS "areaCode",
|
||||
area.name AS "areaName",
|
||||
visit.operator_company_id AS "companyId",
|
||||
company.code AS "companyCode",
|
||||
COALESCE(profile.legal_name, company.name) AS "companyName"
|
||||
FROM inspection_visits visit
|
||||
LEFT JOIN assets area ON area.id = visit.operational_area_id
|
||||
LEFT JOIN assets company ON company.id = visit.operator_company_id
|
||||
LEFT JOIN organization_profiles profile ON profile.asset_id = company.id
|
||||
WHERE visit.id = $1
|
||||
`, [visitId])) as BriefingVisitRow[];
|
||||
|
||||
if (!visit) {
|
||||
throw new NotFoundException({
|
||||
code: 'INSPECTION_VISIT_NOT_FOUND',
|
||||
message: 'Inspección no encontrada',
|
||||
});
|
||||
}
|
||||
if (!visit.areaId || !visit.companyId) {
|
||||
throw new BadRequestException({
|
||||
code: 'FIELD_BRIEFING_CONTEXT_REQUIRED',
|
||||
message: 'La inspección debe tener Área y Operadora antes de preparar el paquete de campo',
|
||||
});
|
||||
}
|
||||
|
||||
const referenceAt = visit.plannedStartAt ?? new Date();
|
||||
const referenceDate = referenceAt.toISOString().slice(0, 10);
|
||||
|
||||
const rows = (await this.dataSource.query(`
|
||||
SELECT
|
||||
act.id AS "sourceActId",
|
||||
act.code AS "sourceActCode",
|
||||
act.occurred_at AS "sourceActOccurredAt",
|
||||
source_visit.id AS "sourceVisitId",
|
||||
source_visit.code AS "sourceVisitCode",
|
||||
deadline.response_due_on AS "responseDueOn",
|
||||
response.received_on AS "responseReceivedOn",
|
||||
response.committed_correction_on AS "committedCorrectionOn",
|
||||
response.id AS "latestResponseId",
|
||||
(response.stored_name IS NOT NULL) AS "responseHasPdf",
|
||||
CASE
|
||||
WHEN response.id IS NOT NULL
|
||||
AND response.committed_correction_on IS NOT NULL
|
||||
AND response.committed_correction_on < $5::date
|
||||
THEN 'COMMITMENT_OVERDUE'
|
||||
WHEN response.id IS NOT NULL AND finding.next_control_on IS NULL
|
||||
THEN 'VERIFICATION_PENDING'
|
||||
WHEN response.id IS NOT NULL THEN 'RESPONSE_RECEIVED'
|
||||
WHEN deadline.id IS NULL THEN 'NEW'
|
||||
WHEN deadline.response_due_on < $5::date THEN 'OVERDUE'
|
||||
WHEN deadline.response_due_on <= ($5::date + 3) THEN 'DUE_SOON'
|
||||
ELSE 'WAITING_RESPONSE'
|
||||
END AS "adminState",
|
||||
CASE
|
||||
WHEN COALESCE(verification.outcome, '') <> 'RESOLVED'
|
||||
AND finding.next_control_on IS NOT NULL
|
||||
AND finding.next_control_on <= $5::date
|
||||
THEN 'REQUIRED'
|
||||
WHEN response.id IS NOT NULL
|
||||
AND response.committed_correction_on IS NOT NULL
|
||||
AND response.committed_correction_on <= $5::date
|
||||
THEN 'REQUIRED'
|
||||
WHEN response.id IS NOT NULL AND finding.next_control_on IS NULL
|
||||
THEN 'REQUIRED'
|
||||
WHEN COALESCE(verification.outcome, '') <> 'RESOLVED'
|
||||
AND finding.next_control_on IS NOT NULL
|
||||
AND finding.next_control_on <= ($5::date + 30)
|
||||
THEN 'UPCOMING'
|
||||
ELSE 'CONTEXT'
|
||||
END AS "reviewState",
|
||||
CASE
|
||||
WHEN COALESCE(verification.outcome, '') <> 'RESOLVED'
|
||||
AND finding.next_control_on IS NOT NULL
|
||||
AND finding.next_control_on <= $5::date
|
||||
THEN 'CONTROL_OVERDUE'
|
||||
WHEN response.id IS NOT NULL
|
||||
AND response.committed_correction_on IS NOT NULL
|
||||
AND response.committed_correction_on <= $5::date
|
||||
THEN 'COMMITMENT_REACHED'
|
||||
WHEN response.id IS NOT NULL AND finding.next_control_on IS NULL
|
||||
THEN 'RESPONSE_WITHOUT_CONTROL'
|
||||
WHEN COALESCE(verification.outcome, '') <> 'RESOLVED'
|
||||
AND finding.next_control_on IS NOT NULL
|
||||
AND finding.next_control_on <= ($5::date + 30)
|
||||
THEN 'CONTROL_UPCOMING'
|
||||
WHEN response.id IS NULL
|
||||
AND deadline.response_due_on IS NOT NULL
|
||||
AND deadline.response_due_on < $5::date
|
||||
THEN 'ADMIN_RESPONSE_OVERDUE'
|
||||
ELSE 'CONTEXT_ONLY'
|
||||
END AS "reviewReason",
|
||||
CASE
|
||||
WHEN COALESCE(verification.outcome, '') <> 'RESOLVED'
|
||||
AND finding.next_control_on IS NOT NULL
|
||||
AND finding.next_control_on <= $5::date THEN 1
|
||||
WHEN response.id IS NOT NULL
|
||||
AND response.committed_correction_on IS NOT NULL
|
||||
AND response.committed_correction_on <= $5::date THEN 2
|
||||
WHEN response.id IS NOT NULL AND finding.next_control_on IS NULL THEN 3
|
||||
WHEN COALESCE(verification.outcome, '') <> 'RESOLVED'
|
||||
AND finding.next_control_on IS NOT NULL
|
||||
AND finding.next_control_on <= ($5::date + 30) THEN 4
|
||||
WHEN response.id IS NULL
|
||||
AND deadline.response_due_on IS NOT NULL
|
||||
AND deadline.response_due_on < $5::date THEN 5
|
||||
ELSE 6
|
||||
END AS priority,
|
||||
finding.id AS "findingId",
|
||||
finding.code AS "findingCode",
|
||||
finding.title AS "findingTitle",
|
||||
finding.severity,
|
||||
finding.next_control_on AS "nextControlOn",
|
||||
verification.outcome AS "latestVerificationOutcome",
|
||||
asset.id AS "assetId",
|
||||
asset.code AS "assetCode",
|
||||
asset.name AS "assetName",
|
||||
asset_type.name AS "assetTypeName"
|
||||
FROM inspection_acts act
|
||||
INNER JOIN inspection_visits source_visit ON source_visit.id = act.visit_id
|
||||
INNER JOIN inspection_findings finding ON finding.act_id = act.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
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT event.id, event.response_due_on
|
||||
FROM inspection_act_deadline_events event
|
||||
WHERE event.act_id = act.id
|
||||
ORDER BY event.created_at DESC, event.id DESC
|
||||
LIMIT 1
|
||||
) deadline ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT company_response.id, company_response.received_on,
|
||||
company_response.committed_correction_on, company_response.stored_name
|
||||
FROM inspection_act_company_responses company_response
|
||||
WHERE company_response.act_id = act.id
|
||||
ORDER BY company_response.received_on DESC,
|
||||
company_response.created_at DESC,
|
||||
company_response.id DESC
|
||||
LIMIT 1
|
||||
) response ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT verification_visit.outcome
|
||||
FROM inspection_finding_verification_visits verification_visit
|
||||
WHERE verification_visit.finding_id = finding.id
|
||||
AND verification_visit.outcome IS NOT NULL
|
||||
ORDER BY verification_visit.result_recorded_at DESC NULLS LAST,
|
||||
verification_visit.created_at DESC,
|
||||
verification_visit.id DESC
|
||||
LIMIT 1
|
||||
) verification ON true
|
||||
WHERE source_visit.operational_area_id = $2
|
||||
AND source_visit.operator_company_id = $3
|
||||
AND source_visit.id <> $1
|
||||
AND act.status IN ('CLOSED', 'RECTIFIED')
|
||||
AND finding.status = 'OPEN'
|
||||
AND COALESCE(act.closed_at, act.occurred_at) <= $4::timestamptz
|
||||
ORDER BY priority, act.occurred_at, act.act_number, finding.finding_number
|
||||
`, [visit.id, visit.areaId, visit.companyId, referenceAt.toISOString(), referenceDate])) as BriefingFindingRow[];
|
||||
|
||||
const actMap = new Map<string, {
|
||||
actId: string;
|
||||
actCode: string;
|
||||
occurredAt: Date;
|
||||
sourceVisit: { id: string; code: string };
|
||||
adminState: FieldBriefingAdminState;
|
||||
responseDueOn: string | null;
|
||||
latestResponse: null | {
|
||||
id: string;
|
||||
receivedOn: string;
|
||||
committedCorrectionOn: string | null;
|
||||
hasPdf: boolean;
|
||||
};
|
||||
findings: Array<Record<string, unknown>>;
|
||||
}>();
|
||||
|
||||
for (const row of rows) {
|
||||
let act = actMap.get(row.sourceActId);
|
||||
if (!act) {
|
||||
act = {
|
||||
actId: row.sourceActId,
|
||||
actCode: row.sourceActCode,
|
||||
occurredAt: row.sourceActOccurredAt,
|
||||
sourceVisit: { id: row.sourceVisitId, code: row.sourceVisitCode },
|
||||
adminState: row.adminState,
|
||||
responseDueOn: row.responseDueOn,
|
||||
latestResponse: row.latestResponseId && row.responseReceivedOn ? {
|
||||
id: row.latestResponseId,
|
||||
receivedOn: row.responseReceivedOn,
|
||||
committedCorrectionOn: row.committedCorrectionOn,
|
||||
hasPdf: Boolean(row.responseHasPdf),
|
||||
} : null,
|
||||
findings: [],
|
||||
};
|
||||
actMap.set(row.sourceActId, act);
|
||||
}
|
||||
act.findings.push({
|
||||
id: row.findingId,
|
||||
code: row.findingCode,
|
||||
title: row.findingTitle,
|
||||
severity: row.severity,
|
||||
nextControlOn: row.nextControlOn,
|
||||
latestVerificationOutcome: row.latestVerificationOutcome,
|
||||
reviewState: row.reviewState,
|
||||
reviewReason: row.reviewReason,
|
||||
priority: Number(row.priority),
|
||||
asset: {
|
||||
id: row.assetId,
|
||||
code: row.assetCode,
|
||||
name: row.assetName,
|
||||
typeName: row.assetTypeName,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const acts = Array.from(actMap.values());
|
||||
const uniqueAssets = new Set(rows.map((row) => row.assetId));
|
||||
const required = rows.filter((row) => row.reviewState === 'REQUIRED').length;
|
||||
const upcoming = rows.filter((row) => row.reviewState === 'UPCOMING').length;
|
||||
const adminAttention = rows.filter((row) =>
|
||||
['OVERDUE', 'DUE_SOON', 'COMMITMENT_OVERDUE'].includes(row.adminState),
|
||||
).length;
|
||||
|
||||
return {
|
||||
visit: {
|
||||
id: visit.id,
|
||||
code: visit.code,
|
||||
status: visit.status,
|
||||
plannedStartAt: visit.plannedStartAt,
|
||||
operationalArea: { id: visit.areaId, code: visit.areaCode, name: visit.areaName },
|
||||
operatorCompany: { id: visit.companyId, code: visit.companyCode, name: visit.companyName },
|
||||
},
|
||||
referenceDate,
|
||||
generatedAt: new Date().toISOString(),
|
||||
summary: {
|
||||
actCount: acts.length,
|
||||
openFindingCount: rows.length,
|
||||
fieldReviewRequired: required,
|
||||
fieldReviewUpcoming: upcoming,
|
||||
administrativeAttention: adminAttention,
|
||||
assetCount: uniqueAssets.size,
|
||||
},
|
||||
acts,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,37 +1,30 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { test } from 'node:test';
|
||||
|
||||
const source = (path: string) => readFileSync(resolve(process.cwd(), path), 'utf8');
|
||||
const service = source('src/field-briefing/field-briefing.service.ts');
|
||||
const controller = source('src/field-briefing/field-briefing.controller.ts');
|
||||
const service = readFileSync('src/act-administration/field-briefing.service.ts', 'utf8');
|
||||
const controller = readFileSync('src/act-administration/field-briefing.controller.ts', 'utf8');
|
||||
const moduleSource = readFileSync('src/act-administration/act-administration.module.ts', 'utf8');
|
||||
|
||||
test('F1.3 prepares field briefing from prior Acts in the same operational context', () => {
|
||||
assert.match(service, /source_visit\.operational_area_id = \$2/);
|
||||
assert.match(service, /source_visit\.operator_company_id = \$3/);
|
||||
assert.match(service, /source_visit\.id <> \$1/);
|
||||
});
|
||||
|
||||
test('F1.3 uses Act-level deadline and company response ledgers', () => {
|
||||
test('F1.3 agrupa pendientes de campo por Acta y Hallazgo', () => {
|
||||
assert.match(service, /inspection_act_deadline_events/);
|
||||
assert.match(service, /inspection_act_company_responses/);
|
||||
assert.doesNotMatch(service, /company_response_received_on/);
|
||||
assert.match(service, /source_visit\.operational_area_id = \$2::uuid/);
|
||||
assert.match(service, /source_visit\.operator_company_id = \$3::uuid/);
|
||||
assert.match(service, /ACT_RESPONSE_OVERDUE/);
|
||||
assert.match(service, /COMPANY_COMMITMENT_OVERDUE/);
|
||||
assert.match(service, /VERIFICATION_PENDING/);
|
||||
assert.match(service, /findings: \[\]/);
|
||||
});
|
||||
|
||||
test('F1.3 only turns open findings from closed Acts into pending field context', () => {
|
||||
assert.match(service, /act\.status IN \('CLOSED', 'RECTIFIED'\)/);
|
||||
assert.match(service, /finding\.status = 'OPEN'/);
|
||||
test('F1.3 expone el briefing para una inspección planificada', () => {
|
||||
assert.match(controller, /inspection-visits\/:visitId\/field-briefing/);
|
||||
assert.match(controller, /RequirePermissions\('inspections\.read'\)/);
|
||||
assert.match(moduleSource, /FieldBriefingController/);
|
||||
assert.match(moduleSource, /FieldBriefingService/);
|
||||
});
|
||||
|
||||
test('F1.3 separates required field review, upcoming review and administrative context', () => {
|
||||
assert.match(service, /'REQUIRED'/);
|
||||
assert.match(service, /'UPCOMING'/);
|
||||
assert.match(service, /'CONTEXT'/);
|
||||
assert.match(service, /ADMIN_RESPONSE_OVERDUE/);
|
||||
});
|
||||
|
||||
test('F1.3 exposes the briefing through the inspection read contract', () => {
|
||||
assert.match(controller, /field-briefing/);
|
||||
assert.match(controller, /inspections\.read/);
|
||||
test('F1.3 no usa el plazo del Hallazgo como plazo administrativo', () => {
|
||||
assert.doesNotMatch(service, /correction_due_on/);
|
||||
assert.match(service, /deadline\.response_due_on/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# F1.3 · Planificación inteligente de pendientes
|
||||
|
||||
Objetivo: al planificar una inspección para un Área/Yacimiento + Operadora, generar un paquete de campo con pendientes administrativos y operativos provenientes de Actas anteriores del mismo contexto.
|
||||
|
||||
Reglas:
|
||||
- La unidad administrativa es el Acta.
|
||||
- Los hallazgos se muestran dentro de su Acta de origen.
|
||||
- El checklist de planificación incluye Actas con respuesta vencida o por vencer, respuestas de empresa con fecha comprometida de regularización, y hallazgos con control/verificación pendiente.
|
||||
- El inspector puede ver antecedentes antes de salir y en la APK.
|
||||
- La planificación no modifica ni cierra Actas/hallazgos previos.
|
||||
- La verificación en campo se registra append-only.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dhv2-web",
|
||||
"version": "0.20.0-3",
|
||||
"version": "0.20.0-2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
|
||||
@@ -34,11 +34,10 @@ import { ReportDetailPage } from '../pages/ReportDetailPage';
|
||||
import { VerificationPlanningPage } from '../pages/VerificationPlanningPage';
|
||||
import { ActAdministrationPage } from '../pages/ActAdministrationPage';
|
||||
import { ActAdministrationDetailPage } from '../pages/ActAdministrationDetailPage';
|
||||
import { FieldBriefingsPage } from '../pages/FieldBriefingsPage';
|
||||
|
||||
const MapPage = lazy(() => import('../pages/MapPage').then((module) => ({ default: module.MapPage })));
|
||||
const DocumentDeliveryPage = lazy(() => import('../pages/DocumentDeliveryPage').then((module) => ({ default: module.DocumentDeliveryPage })));
|
||||
|
||||
const DocumentDeliveryPage = lazy(() => import('../pages/DocumentDeliveryPage').then((module) => ({ default: module.DocumentDeliveryPage })));
|
||||
export function App() {
|
||||
return <Suspense fallback={<div className="loading-block"><span className="spinner" />Cargando módulo…</div>}><Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
@@ -66,7 +65,6 @@ export function App() {
|
||||
<Route element={<PermissionRoute permission="inspections.read" />}>
|
||||
<Route path="/inspecciones" element={<InspectionVisitsPage />} />
|
||||
<Route path="/inspecciones/:id" element={<InspectionVisitEditorPage />} />
|
||||
<Route path="/preparacion-campo" element={<FieldBriefingsPage />} />
|
||||
</Route>
|
||||
<Route element={<PermissionRoute permission="inspections.manage" />}><Route path="/inspecciones/nueva" element={<InspectionVisitEditorPage />} /></Route>
|
||||
<Route element={<PermissionRoute permission="inspection_acts.read" />}>
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export const APP_VERSION = '0.20.0-3';
|
||||
export const APP_PHASE = 'Fase F1.3 · Preparación inteligente de campo';
|
||||
export const APP_VERSION = '0.20.0-2';
|
||||
export const APP_PHASE = 'Fase F1.2 · Seguimiento administrativo por Acta';
|
||||
|
||||
@@ -16,7 +16,6 @@ interface NavItem {
|
||||
const operational: NavItem[] = [
|
||||
{ to: '/', label: 'Inicio', icon: 'home', permission: 'dashboard.read' },
|
||||
{ to: '/inspecciones', label: 'Inspecciones', icon: 'clipboard', permission: 'inspections.read' },
|
||||
{ to: '/preparacion-campo', label: 'Preparación de campo', icon: 'clipboard', permission: 'inspections.read' },
|
||||
];
|
||||
|
||||
const followUp: NavItem[] = [
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { SearchableSelect } from '../components/SearchableSelect';
|
||||
import { Alert, EmptyState, LoadingBlock } from '../components/Feedback';
|
||||
import { formatDate, formatDateOnly } from '../lib/format';
|
||||
|
||||
type ReviewState = 'REQUIRED' | 'UPCOMING' | 'CONTEXT';
|
||||
|
||||
interface VisitOption {
|
||||
id: string;
|
||||
code: string;
|
||||
status: string;
|
||||
plannedStartAt: string | null;
|
||||
operationalArea: { name: string } | null;
|
||||
operatorCompany: { name: string } | null;
|
||||
}
|
||||
|
||||
interface BriefingFinding {
|
||||
id: string;
|
||||
code: string;
|
||||
title: string;
|
||||
severity: number | null;
|
||||
nextControlOn: string | null;
|
||||
reviewState: ReviewState;
|
||||
reviewReason: string;
|
||||
asset: { id: string; code: string; name: string; typeName: string };
|
||||
}
|
||||
|
||||
interface BriefingAct {
|
||||
actId: string;
|
||||
actCode: string;
|
||||
occurredAt: string;
|
||||
adminState: string;
|
||||
responseDueOn: string | null;
|
||||
latestResponse: null | { id: string; receivedOn: string; committedCorrectionOn: string | null; hasPdf: boolean };
|
||||
findings: BriefingFinding[];
|
||||
}
|
||||
|
||||
interface Briefing {
|
||||
visit: {
|
||||
id: string;
|
||||
code: string;
|
||||
status: string;
|
||||
plannedStartAt: string | null;
|
||||
operationalArea: { id: string; code: string | null; name: string | null };
|
||||
operatorCompany: { id: string; code: string | null; name: string | null };
|
||||
};
|
||||
referenceDate: string;
|
||||
generatedAt: string;
|
||||
summary: {
|
||||
actCount: number;
|
||||
openFindingCount: number;
|
||||
fieldReviewRequired: number;
|
||||
fieldReviewUpcoming: number;
|
||||
administrativeAttention: number;
|
||||
assetCount: number;
|
||||
};
|
||||
acts: BriefingAct[];
|
||||
}
|
||||
|
||||
async function json<T>(url: string): Promise<T> {
|
||||
const response = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json' } });
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
const message = typeof payload?.message === 'string'
|
||||
? payload.message
|
||||
: 'No se pudo cargar la preparación de campo.';
|
||||
throw new Error(message);
|
||||
}
|
||||
return payload as T;
|
||||
}
|
||||
|
||||
function reviewLabel(state: ReviewState) {
|
||||
if (state === 'REQUIRED') return 'Revisar en campo';
|
||||
if (state === 'UPCOMING') return 'Próximo control';
|
||||
return 'Antecedente';
|
||||
}
|
||||
|
||||
function reasonLabel(reason: string) {
|
||||
const labels: Record<string, string> = {
|
||||
CONTROL_OVERDUE: 'Control vencido',
|
||||
COMMITMENT_REACHED: 'Compromiso de empresa alcanzado',
|
||||
RESPONSE_WITHOUT_CONTROL: 'Respuesta recibida sin control programado',
|
||||
CONTROL_UPCOMING: 'Control próximo',
|
||||
ADMIN_RESPONSE_OVERDUE: 'Respuesta administrativa vencida',
|
||||
CONTEXT_ONLY: 'Antecedente abierto',
|
||||
};
|
||||
return labels[reason] ?? reason;
|
||||
}
|
||||
|
||||
export function FieldBriefingsPage() {
|
||||
const [visits, setVisits] = useState<VisitOption[]>([]);
|
||||
const [visitId, setVisitId] = useState('');
|
||||
const [briefing, setBriefing] = useState<Briefing | null>(null);
|
||||
const [loadingVisits, setLoadingVisits] = useState(true);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
setLoadingVisits(true);
|
||||
Promise.all([
|
||||
json<{ data: VisitOption[] }>('/api/v3/inspection-visits?status=PLANNED&page=1&pageSize=100'),
|
||||
json<{ data: VisitOption[] }>('/api/v3/inspection-visits?status=DRAFT&page=1&pageSize=100'),
|
||||
]).then(([planned, drafts]) => {
|
||||
const all = [...planned.data, ...drafts.data]
|
||||
.sort((a, b) => String(a.plannedStartAt ?? '').localeCompare(String(b.plannedStartAt ?? '')));
|
||||
setVisits(all);
|
||||
const onlyVisit = all[0];
|
||||
if (all.length === 1 && onlyVisit) setVisitId(onlyVisit.id);
|
||||
}).catch((cause) => setError(cause instanceof Error ? cause.message : String(cause)))
|
||||
.finally(() => setLoadingVisits(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!visitId) {
|
||||
setBriefing(null);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError('');
|
||||
json<Briefing>(`/api/v3/inspection-visits/${visitId}/field-briefing`)
|
||||
.then(setBriefing)
|
||||
.catch((cause) => setError(cause instanceof Error ? cause.message : String(cause)))
|
||||
.finally(() => setLoading(false));
|
||||
}, [visitId]);
|
||||
|
||||
const selected = useMemo(() => visits.find((visit) => visit.id === visitId) ?? null, [visits, visitId]);
|
||||
|
||||
return <section className="field-briefing-page">
|
||||
<div className="page-heading">
|
||||
<div>
|
||||
<span className="eyebrow">ANTES DE SALIR A CAMPO</span>
|
||||
<h1>Preparación de campo</h1>
|
||||
<p>Actas anteriores y hallazgos abiertos del mismo Área/Yacimiento y Operadora, ordenados por lo que el inspector debe revisar.</p>
|
||||
</div>
|
||||
{briefing && <button className="button secondary" type="button" onClick={() => window.print()}>Imprimir preparación</button>}
|
||||
</div>
|
||||
|
||||
<div className="form-card no-print">
|
||||
<label>Inspección planificada</label>
|
||||
{loadingVisits ? <LoadingBlock label="Cargando inspecciones…" /> : <SearchableSelect
|
||||
value={visitId}
|
||||
onChange={(event) => setVisitId(event.target.value)}
|
||||
searchPlaceholder="Buscar por código, Área u Operadora…"
|
||||
>
|
||||
<option value="">Seleccionar inspección…</option>
|
||||
{visits.map((visit) => <option key={visit.id} value={visit.id}>
|
||||
{visit.code} · {visit.operationalArea?.name ?? 'Sin Área'} · {visit.operatorCompany?.name ?? 'Sin Operadora'}
|
||||
</option>)}
|
||||
</SearchableSelect>}
|
||||
{selected?.plannedStartAt && <small className="block-muted">Salida prevista: {formatDate(selected.plannedStartAt)}</small>}
|
||||
</div>
|
||||
|
||||
{error && <Alert>{error}</Alert>}
|
||||
{loading && <LoadingBlock label="Armando paquete de campo…" />}
|
||||
{!loading && !briefing && !error && <EmptyState title="Seleccioná una inspección" text="El sistema reunirá automáticamente los pendientes de inspecciones anteriores." />}
|
||||
{!loading && briefing && <>
|
||||
<div className="page-heading compact">
|
||||
<div>
|
||||
<span className="eyebrow">{briefing.visit.code}</span>
|
||||
<h2>{briefing.visit.operationalArea.name ?? 'Área'} · {briefing.visit.operatorCompany.name ?? 'Operadora'}</h2>
|
||||
<p>Referencia: {formatDateOnly(briefing.referenceDate)} · generado {formatDate(briefing.generatedAt)}</p>
|
||||
</div>
|
||||
<Link className="button secondary no-print" to={`/inspecciones/${briefing.visit.id}`}>Abrir planificación</Link>
|
||||
</div>
|
||||
|
||||
<div className="status-tabs briefing-summary">
|
||||
<span>Actas <strong>{briefing.summary.actCount}</strong></span>
|
||||
<span>Hallazgos abiertos <strong>{briefing.summary.openFindingCount}</strong></span>
|
||||
<span>Revisar en campo <strong>{briefing.summary.fieldReviewRequired}</strong></span>
|
||||
<span>Próximos <strong>{briefing.summary.fieldReviewUpcoming}</strong></span>
|
||||
<span>Inventario involucrado <strong>{briefing.summary.assetCount}</strong></span>
|
||||
</div>
|
||||
|
||||
{briefing.acts.length === 0 ? <EmptyState title="Sin pendientes anteriores" text="No hay hallazgos abiertos de Actas anteriores para este contexto." /> : briefing.acts.map((act) => <article className="table-panel" key={act.actId}>
|
||||
<div className="table-summary">
|
||||
<div><strong>{act.actCode}</strong><small className="block-muted">{formatDate(act.occurredAt)} · {act.adminState}</small></div>
|
||||
<div><small>Plazo empresa</small><strong>{act.responseDueOn ? formatDateOnly(act.responseDueOn) : 'Sin definir'}</strong></div>
|
||||
<div><small>Respuesta</small><strong>{act.latestResponse ? formatDateOnly(act.latestResponse.receivedOn) : 'Pendiente'}</strong></div>
|
||||
</div>
|
||||
<div className="table-scroll"><table><thead><tr><th>Prioridad</th><th>Hallazgo</th><th>Inventario</th><th>Próximo control</th></tr></thead><tbody>
|
||||
{act.findings.map((finding) => <tr key={finding.id}>
|
||||
<td><span className={`status-badge ${finding.reviewState === 'REQUIRED' ? 'danger' : 'pending'}`}>{reviewLabel(finding.reviewState)}</span><small className="block-muted">{reasonLabel(finding.reviewReason)}</small></td>
|
||||
<td><strong>{finding.code}</strong><small className="block-muted">{finding.title}</small></td>
|
||||
<td><strong>{finding.asset.code}</strong><small className="block-muted">{finding.asset.name} · {finding.asset.typeName}</small></td>
|
||||
<td>{finding.nextControlOn ? formatDateOnly(finding.nextControlOn) : 'Sin fecha'}</td>
|
||||
</tr>)}
|
||||
</tbody></table></div>
|
||||
</article>)}
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
Reference in New Issue
Block a user