Compare commits

..
Author SHA1 Message Date
admin b8c002f36a fix(F1.3): asegurar visita única en build estricto 2026-09-05 17:08:27 -03:00
admin da7d8a9149 F1.3 · Preparación inteligente de campo
Agrega paquete de campo por inspección con Actas anteriores del mismo contexto, hallazgos abiertos priorizados para verificación y vista web imprimible.
2026-09-05 17:05:46 -03:00
admin 4c5742c548 F1.2 · Seguimiento administrativo por Acta
Plazo único por Acta, respuestas de empresa con PDF, fecha comprometida, estados administrativos, cola y calendario por Acta.
2026-09-05 16:47:46 -03:00
25 changed files with 1041 additions and 12 deletions
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "dhv2-api",
"version": "0.19.6-4",
"version": "0.20.0-2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dhv2-api",
"version": "0.19.6-4",
"version": "0.20.0-2",
"license": "UNLICENSED",
"dependencies": {
"@nestjs/common": "^11.0.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dhv2-api",
"version": "0.20.0-1",
"version": "0.20.0-3",
"private": true,
"license": "UNLICENSED",
"scripts": {
@@ -0,0 +1,47 @@
import { Body, Controller, Get, Param, ParseUUIDPipe, Patch, Post, Query, Req, Res, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
import { CurrentAuth } from '../auth/decorators/current-auth.decorator';
import { RequirePermissions } from '../authorization/decorators/require-permissions.decorator';
import type { AuthPrincipal, RequestWithContext } from '../common/http/request-context';
import { ActAdministrationService, MAX_ACT_RESPONSE_BYTES, type UploadedActResponseFile } from './act-administration.service';
import { CreateActCompanyResponseDto } from './dto/create-act-company-response.dto';
import { ListActAdministrationQueryDto } from './dto/list-act-administration-query.dto';
import { SetActResponseDeadlineDto } from './dto/set-act-response-deadline.dto';
@Controller('act-administration')
export class ActAdministrationQueueController {
constructor(private readonly administration: ActAdministrationService) {}
@Get('queue') @RequirePermissions('inspection_acts.read') queue(@Query() query: ListActAdministrationQueryDto) { return this.administration.queue(query); }
@Get('calendar') @RequirePermissions('inspection_acts.read') calendar(@Query('from') from?: string, @Query('to') to?: string) { return this.administration.calendar(from, to); }
}
@Controller('inspection-acts/:actId/administration')
export class ActAdministrationController {
constructor(private readonly administration: ActAdministrationService) {}
@Get() @RequirePermissions('inspection_acts.read') get(@Param('actId', new ParseUUIDPipe({ version: '4' })) actId: string) { return this.administration.detail(actId); }
@Patch('deadline') @RequirePermissions('inspection_findings.follow_up')
setDeadline(@Param('actId', new ParseUUIDPipe({ version: '4' })) actId: string, @Body() dto: SetActResponseDeadlineDto, @CurrentAuth() principal: AuthPrincipal, @Req() request: RequestWithContext) { return this.administration.setDeadline(actId, dto, principal, request); }
@Post('responses') @RequirePermissions('inspection_findings.follow_up')
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_ACT_RESPONSE_BYTES, files: 1 } }))
addResponse(@Param('actId', new ParseUUIDPipe({ version: '4' })) actId: string, @Body() dto: CreateActCompanyResponseDto, @UploadedFile() file: UploadedActResponseFile | undefined, @CurrentAuth() principal: AuthPrincipal, @Req() request: RequestWithContext) { return this.administration.addResponse(actId, dto, file, principal, request); }
}
@Controller('act-company-responses')
export class ActCompanyResponseContentController {
constructor(private readonly administration: ActAdministrationService) {}
@Get(':responseId/content') @RequirePermissions('inspection_acts.read')
async content(@Param('responseId', new ParseUUIDPipe({ version: '4' })) responseId: string, @Query('download') download: string | undefined, @Res() response: Response): Promise<void> {
const item = await this.administration.responseContent(responseId);
const disposition = download === '1' ? 'attachment' : 'inline';
const fallbackName = item.originalName.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_');
response.setHeader('Content-Type', 'application/pdf');
response.setHeader('Content-Length', String(item.sizeBytes));
response.setHeader('Content-Disposition', `${disposition}; filename="${fallbackName}"; filename*=UTF-8''${encodeURIComponent(item.originalName)}`);
response.setHeader('Cache-Control', 'private, no-store');
response.setHeader('X-Content-Type-Options', 'nosniff');
response.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
await new Promise<void>((resolveSend, rejectSend) => response.sendFile(item.filePath, (error) => error ? rejectSend(error) : resolveSend()));
}
}
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { AuditModule } from '../audit/audit.module';
import { ActAdministrationController, ActAdministrationQueueController, ActCompanyResponseContentController } from './act-administration.controller';
import { ActAdministrationService } from './act-administration.service';
@Module({
imports: [AuditModule],
controllers: [ActAdministrationQueueController, ActAdministrationController, ActCompanyResponseContentController],
providers: [ActAdministrationService],
})
export class ActAdministrationModule {}
@@ -0,0 +1,180 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { createHash, randomUUID } from 'crypto';
import { mkdir, stat, unlink, writeFile } from 'fs/promises';
import { join, resolve } from 'path';
import { DataSource } from 'typeorm';
import { AuditService } from '../audit/audit.service';
import type { AuthPrincipal, RequestWithContext } from '../common/http/request-context';
import { CreateActCompanyResponseDto } from './dto/create-act-company-response.dto';
import { ListActAdministrationQueryDto } from './dto/list-act-administration-query.dto';
import { SetActResponseDeadlineDto } from './dto/set-act-response-deadline.dto';
export const MAX_ACT_RESPONSE_BYTES = 15 * 1024 * 1024;
export interface UploadedActResponseFile { originalname: string; mimetype: string; size: number; buffer: Buffer }
const STORAGE = resolve(process.env.ACT_COMPANY_RESPONSE_STORAGE_DIR ?? '/app/storage/act-company-responses');
@Injectable()
export class ActAdministrationService {
constructor(private readonly dataSource: DataSource, private readonly audit: AuditService) {}
private baseCte() {
return `
WITH act_rows AS (
SELECT ia.id AS "actId", ia.code AS "actCode", ia.status AS "actStatus", ia.occurred_at AS "occurredAt",
ia.closed_at AS "closedAt", v.id AS "visitId", v.code AS "visitCode",
v.operational_area_id AS "areaId", v.operator_company_id AS "companyId",
area.name AS "areaName", COALESCE(op.legal_name, company.name) AS "companyName",
dl.id AS "deadlineEventId", dl.response_due_on AS "responseDueOn", dl.reason AS "deadlineReason",
dl.created_at AS "deadlineSetAt", rsp.id AS "latestResponseId", rsp.received_on AS "responseReceivedOn",
rsp.committed_correction_on AS "committedCorrectionOn",
COALESCE(fc.finding_count, 0)::int AS "findingCount",
COALESCE(fc.open_count, 0)::int AS "openFindingCount",
COALESCE(fc.scheduled_control_count, 0)::int AS "scheduledControlCount"
FROM inspection_acts ia
JOIN inspection_visits v ON v.id = ia.visit_id
LEFT JOIN assets area ON area.id = v.operational_area_id
LEFT JOIN assets company ON company.id = v.operator_company_id
LEFT JOIN organization_profiles op ON op.asset_id = v.operator_company_id
LEFT JOIN LATERAL (
SELECT d.* FROM inspection_act_deadline_events d WHERE d.act_id = ia.id ORDER BY d.created_at DESC, d.id DESC LIMIT 1
) dl ON true
LEFT JOIN LATERAL (
SELECT r.* FROM inspection_act_company_responses r WHERE r.act_id = ia.id ORDER BY r.received_on DESC, r.created_at DESC, r.id DESC LIMIT 1
) rsp ON true
LEFT JOIN LATERAL (
SELECT COUNT(*) FILTER (WHERE f.status <> 'VOIDED') AS finding_count,
COUNT(*) FILTER (WHERE f.status = 'OPEN') AS open_count,
COUNT(*) FILTER (WHERE f.status = 'OPEN' AND f.next_control_on IS NOT NULL) AS scheduled_control_count
FROM inspection_findings f WHERE f.act_id = ia.id
) fc ON true
WHERE ia.status IN ('CLOSED', 'RECTIFIED')
), classified AS (
SELECT *, CASE
WHEN "findingCount" > 0 AND "openFindingCount" = 0 THEN 'REGULARIZED'
WHEN "latestResponseId" IS NOT NULL AND "committedCorrectionOn" IS NOT NULL AND "committedCorrectionOn" < CURRENT_DATE AND "openFindingCount" > 0 THEN 'COMMITMENT_OVERDUE'
WHEN "latestResponseId" IS NOT NULL AND "openFindingCount" > 0 AND "scheduledControlCount" = 0 THEN 'VERIFICATION_PENDING'
WHEN "latestResponseId" IS NOT NULL THEN 'RESPONSE_RECEIVED'
WHEN "responseDueOn" IS NULL THEN 'NEW'
WHEN "responseDueOn" < CURRENT_DATE THEN 'OVERDUE'
WHEN "responseDueOn" <= CURRENT_DATE + 3 THEN 'DUE_SOON'
ELSE 'WAITING_RESPONSE'
END AS "adminState"
FROM act_rows
)`;
}
async queue(query: ListActAdministrationQueryDto) {
const page = query.page ?? 1;
const pageSize = query.pageSize ?? 25;
const filters: string[] = [];
const args: unknown[] = [];
const add = (sql: string, value: unknown) => { args.push(value); filters.push(sql.replace('?', `$${args.length}`)); };
if (query.areaId) add('"areaId" = ?', query.areaId);
if (query.companyId) add('"companyId" = ?', query.companyId);
if (query.state && query.state !== 'ALL') add('"adminState" = ?', query.state);
const where = filters.length ? `WHERE ${filters.join(' AND ')}` : '';
const rows = await this.dataSource.query(
`${this.baseCte()} SELECT *, COUNT(*) OVER()::int AS "totalRows" FROM classified ${where} ORDER BY "responseDueOn" ASC NULLS FIRST, "occurredAt" DESC LIMIT $${args.length + 1} OFFSET $${args.length + 2}`,
[...args, pageSize, (page - 1) * pageSize],
) as Array<Record<string, unknown>>;
const total = Number(rows[0]?.totalRows ?? 0);
const counterFilters: string[] = [];
const counterArgs: unknown[] = [];
if (query.areaId) { counterArgs.push(query.areaId); counterFilters.push(`"areaId" = $${counterArgs.length}`); }
if (query.companyId) { counterArgs.push(query.companyId); counterFilters.push(`"companyId" = $${counterArgs.length}`); }
const countersRaw = await this.dataSource.query(
`${this.baseCte()} SELECT "adminState" AS state, COUNT(*)::int AS count FROM classified ${counterFilters.length ? `WHERE ${counterFilters.join(' AND ')}` : ''} GROUP BY "adminState"`,
counterArgs,
) as Array<{ state: string; count: number }>;
const counters = Object.fromEntries(countersRaw.map((r) => [r.state, Number(r.count)]));
return {
data: rows.map(({ totalRows: _ignored, ...row }) => row),
counters,
meta: { page, pageSize, total, totalPages: Math.ceil(total / pageSize) },
};
}
async detail(actId: string) {
const rows = await this.dataSource.query(`${this.baseCte()} SELECT * FROM classified WHERE "actId" = $1`, [actId]);
const act = rows[0];
if (!act) throw new NotFoundException({ code: 'ACT_ADMIN_NOT_FOUND', message: 'El Acta no está disponible para seguimiento administrativo.' });
const deadlines = await this.dataSource.query(`SELECT id, response_due_on AS "responseDueOn", reason, created_by AS "createdBy", created_at AS "createdAt" FROM inspection_act_deadline_events WHERE act_id = $1 ORDER BY created_at DESC`, [actId]);
const responses = await this.dataSource.query(`SELECT id, received_on AS "receivedOn", details, committed_correction_on AS "committedCorrectionOn", contact_name AS "contactName", contact_email AS "contactEmail", original_name AS "originalName", mime_type AS "mimeType", size_bytes AS "sizeBytes", sha256, created_by AS "createdBy", created_at AS "createdAt" FROM inspection_act_company_responses WHERE act_id = $1 ORDER BY received_on DESC, created_at DESC`, [actId]);
const findings = await this.dataSource.query(`SELECT id, code, title, status, next_control_on AS "nextControlOn" FROM inspection_findings WHERE act_id = $1 AND status <> 'VOIDED' ORDER BY finding_number`, [actId]);
return { act, deadlines, responses, findings };
}
private async ensureClosedAct(actId: string) {
const rows = await this.dataSource.query(`SELECT id, code, status FROM inspection_acts WHERE id = $1`, [actId]);
const act = rows[0];
if (!act) throw new NotFoundException({ code: 'ACT_NOT_FOUND', message: 'Acta inexistente.' });
if (!['CLOSED', 'RECTIFIED'].includes(act.status)) throw new BadRequestException({ code: 'ACT_ADMIN_REQUIRES_CLOSED', message: 'El seguimiento administrativo comienza cuando el Acta está cerrada.' });
return act;
}
async setDeadline(actId: string, dto: SetActResponseDeadlineDto, principal: AuthPrincipal, request: RequestWithContext) {
const act = await this.ensureClosedAct(actId);
const rows = await this.dataSource.query(
`INSERT INTO inspection_act_deadline_events (id, act_id, response_due_on, reason, created_by) VALUES ($1,$2,$3,$4,$5) RETURNING id, response_due_on AS "responseDueOn", reason, created_at AS "createdAt"`,
[randomUUID(), actId, dto.responseDueOn, dto.reason, principal.userId],
);
await this.audit.record({ actorUserId: principal.userId, actorUsername: principal.username, action: 'ACT_RESPONSE_DEADLINE_SET', entityType: 'inspection_act', entityId: actId, requestId: request.requestId, afterData: { actCode: act.code, responseDueOn: dto.responseDueOn, reason: dto.reason } });
return rows[0];
}
async addResponse(actId: string, dto: CreateActCompanyResponseDto, file: UploadedActResponseFile | undefined, principal: AuthPrincipal, request: RequestWithContext) {
const act = await this.ensureClosedAct(actId);
let storedName: string | null = null;
let sha256: string | null = null;
if (file) {
if (file.size <= 0 || file.size > MAX_ACT_RESPONSE_BYTES) throw new BadRequestException({ code: 'ACT_RESPONSE_FILE_SIZE', message: 'El PDF supera el límite permitido.' });
if (file.mimetype !== 'application/pdf' || file.buffer.subarray(0, 5).toString('ascii') !== '%PDF-') throw new BadRequestException({ code: 'ACT_RESPONSE_FILE_TYPE', message: 'La respuesta adjunta debe ser un PDF válido.' });
await mkdir(STORAGE, { recursive: true });
sha256 = createHash('sha256').update(file.buffer).digest('hex');
storedName = `${randomUUID()}.pdf`;
await writeFile(join(STORAGE, storedName), file.buffer, { flag: 'wx' });
}
try {
const rows = await this.dataSource.query(
`INSERT INTO inspection_act_company_responses (id, act_id, received_on, details, committed_correction_on, contact_name, contact_email, original_name, stored_name, mime_type, size_bytes, sha256, created_by)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
RETURNING id, received_on AS "receivedOn", details, committed_correction_on AS "committedCorrectionOn", contact_name AS "contactName", contact_email AS "contactEmail", original_name AS "originalName", size_bytes AS "sizeBytes", sha256, created_at AS "createdAt"`,
[randomUUID(), actId, dto.receivedOn, dto.details ?? null, dto.committedCorrectionOn ?? null, dto.contactName ?? null, dto.contactEmail ?? null, file?.originalname ?? null, storedName, file ? 'application/pdf' : null, file?.size ?? null, sha256, principal.userId],
);
await this.audit.record({ actorUserId: principal.userId, actorUsername: principal.username, action: 'ACT_COMPANY_RESPONSE_RECORDED', entityType: 'inspection_act', entityId: actId, requestId: request.requestId, afterData: { actCode: act.code, receivedOn: dto.receivedOn, committedCorrectionOn: dto.committedCorrectionOn ?? null, hasPdf: Boolean(file), sha256 } });
return rows[0];
} catch (error) {
if (storedName) await unlink(join(STORAGE, storedName)).catch(() => undefined);
throw error;
}
}
async responseContent(responseId: string) {
const rows = await this.dataSource.query(`SELECT original_name AS "originalName", stored_name AS "storedName", size_bytes AS "sizeBytes" FROM inspection_act_company_responses WHERE id = $1 AND stored_name IS NOT NULL`, [responseId]);
const row = rows[0];
if (!row) throw new NotFoundException({ code: 'ACT_RESPONSE_FILE_NOT_FOUND', message: 'PDF de respuesta inexistente.' });
const filePath = join(STORAGE, row.storedName);
const info = await stat(filePath).catch(() => null);
if (!info?.isFile()) throw new NotFoundException({ code: 'ACT_RESPONSE_FILE_NOT_FOUND', message: 'El archivo de respuesta no está disponible.' });
return { originalName: row.originalName as string, sizeBytes: Number(row.sizeBytes), filePath };
}
async calendar(from?: string, to?: string) {
const dateRe = /^\d{4}-\d{2}-\d{2}$/;
if ((from && !dateRe.test(from)) || (to && !dateRe.test(to))) throw new BadRequestException({ code: 'INVALID_DATE_RANGE', message: 'Las fechas deben usar YYYY-MM-DD.' });
const start = from ?? new Date().toISOString().slice(0, 10);
const endDate = new Date(`${to ?? start}T00:00:00Z`);
if (!to) endDate.setUTCDate(endDate.getUTCDate() + 60);
const end = endDate.toISOString().slice(0, 10);
if (start > end) throw new BadRequestException({ code: 'INVALID_DATE_RANGE', message: 'El rango de fechas es inválido.' });
const rows = await this.dataSource.query(`${this.baseCte()} SELECT * FROM classified WHERE ("responseDueOn" BETWEEN $1 AND $2) OR ("committedCorrectionOn" BETWEEN $1 AND $2) ORDER BY COALESCE("responseDueOn", "committedCorrectionOn")`, [start, end]);
const events: Array<Record<string, unknown>> = [];
for (const row of rows) {
if (row.responseDueOn && row.responseDueOn >= start && row.responseDueOn <= end) events.push({ type: 'RESPONSE_DUE', date: row.responseDueOn, actId: row.actId, actCode: row.actCode, areaName: row.areaName, companyName: row.companyName, state: row.adminState });
if (row.committedCorrectionOn && row.committedCorrectionOn >= start && row.committedCorrectionOn <= end) events.push({ type: 'COMMITMENT_DUE', date: row.committedCorrectionOn, actId: row.actId, actCode: row.actCode, areaName: row.areaName, companyName: row.companyName, state: row.adminState });
}
return { from: start, to: end, data: events.sort((a, b) => String(a.date).localeCompare(String(b.date))) };
}
}
@@ -0,0 +1,31 @@
import { Transform } from 'class-transformer';
import { IsDateString, IsEmail, IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
export class CreateActCompanyResponseDto {
@IsDateString()
receivedOn!: string;
@IsOptional()
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
@IsString()
@MinLength(3)
@MaxLength(8000)
details?: string;
@IsOptional()
@IsDateString()
committedCorrectionOn?: string;
@IsOptional()
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
@IsString()
@MaxLength(200)
contactName?: string;
@IsOptional()
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
@IsEmail()
@MaxLength(320)
contactEmail?: string;
}
@@ -0,0 +1,17 @@
import { Transform } from 'class-transformer';
import { IsIn, IsInt, IsOptional, IsUUID, Max, Min } from 'class-validator';
export const ACT_ADMIN_STATES = [
'ALL', 'NEW', 'WAITING_RESPONSE', 'DUE_SOON', 'OVERDUE',
'RESPONSE_RECEIVED', 'VERIFICATION_PENDING', 'COMMITMENT_OVERDUE', 'REGULARIZED',
] as const;
export type ActAdministrationState = typeof ACT_ADMIN_STATES[number];
export class ListActAdministrationQueryDto {
@IsOptional() @IsIn(ACT_ADMIN_STATES) state?: ActAdministrationState;
@IsOptional() @IsUUID('4') areaId?: string;
@IsOptional() @IsUUID('4') companyId?: string;
@IsOptional() @Transform(({ value }) => Number(value)) @IsInt() @Min(1) page?: number;
@IsOptional() @Transform(({ value }) => Number(value)) @IsInt() @Min(1) @Max(100) pageSize?: number;
}
@@ -0,0 +1,14 @@
import { Transform } from 'class-transformer';
import { IsDateString, IsString, MaxLength, MinLength } from 'class-validator';
export class SetActResponseDeadlineDto {
@IsDateString()
responseDueOn!: string;
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
@IsString()
@MinLength(3)
@MaxLength(1000)
reason!: string;
}
+4
View File
@@ -24,6 +24,8 @@ import { InspectionClosingModule } from './inspection-closing/inspection-closing
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);
@@ -76,6 +78,8 @@ function required(config: ConfigService, key: string): string {
InspectionClosingModule,
InspectionReportsModule,
InspectionVerificationsModule,
ActAdministrationModule,
FieldBriefingModule,
AssetImportsModule,
],
controllers: [HealthController],
@@ -0,0 +1,39 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class PhaseF12ActAdministration1789581600000 implements MigrationInterface {
name = 'PhaseF12ActAdministration1789581600000';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE inspection_act_deadline_events (
id uuid PRIMARY KEY, act_id uuid NOT NULL REFERENCES inspection_acts(id) ON DELETE RESTRICT,
response_due_on date NOT NULL, reason text NOT NULL, created_by uuid NULL REFERENCES users(id) ON DELETE SET NULL,
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
)`);
await queryRunner.query(`CREATE INDEX idx_act_deadline_events_act_created ON inspection_act_deadline_events (act_id, created_at DESC)`);
await queryRunner.query(`CREATE INDEX idx_act_deadline_events_due ON inspection_act_deadline_events (response_due_on)`);
await queryRunner.query(`CREATE TABLE inspection_act_company_responses (
id uuid PRIMARY KEY, act_id uuid NOT NULL REFERENCES inspection_acts(id) ON DELETE RESTRICT,
received_on date NOT NULL, details text NULL, committed_correction_on date NULL,
contact_name varchar(200) NULL, contact_email varchar(320) NULL,
original_name varchar(255) NULL, stored_name varchar(100) NULL, mime_type varchar(120) NULL,
size_bytes bigint NULL, sha256 char(64) NULL, created_by uuid NULL REFERENCES users(id) ON DELETE SET NULL,
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT chk_act_company_response_file CHECK ((stored_name IS NULL AND original_name IS NULL AND mime_type IS NULL AND size_bytes IS NULL AND sha256 IS NULL) OR (stored_name IS NOT NULL AND original_name IS NOT NULL AND mime_type = 'application/pdf' AND size_bytes > 0 AND sha256 IS NOT NULL))
)`);
await queryRunner.query(`CREATE INDEX idx_act_company_responses_act_received ON inspection_act_company_responses (act_id, received_on DESC, created_at DESC)`);
await queryRunner.query(`CREATE INDEX idx_act_company_responses_commitment ON inspection_act_company_responses (committed_correction_on)`);
await queryRunner.query(`INSERT INTO inspection_act_deadline_events (id, act_id, response_due_on, reason, created_by, created_at)
SELECT gen_random_uuid(), act_id, MIN(correction_due_on), 'Migrado desde plazo histórico coincidente de hallazgos', NULL, CURRENT_TIMESTAMP
FROM inspection_findings WHERE correction_due_on IS NOT NULL GROUP BY act_id HAVING COUNT(DISTINCT correction_due_on) = 1`);
await queryRunner.query(`CREATE OR REPLACE FUNCTION prevent_f12_append_only_mutation() RETURNS trigger AS $$ BEGIN RAISE EXCEPTION 'F1.2 append-only: update/delete no permitido'; END; $$ LANGUAGE plpgsql`);
await queryRunner.query(`CREATE TRIGGER trg_act_deadline_events_append_only BEFORE UPDATE OR DELETE ON inspection_act_deadline_events FOR EACH ROW EXECUTE FUNCTION prevent_f12_append_only_mutation()`);
await queryRunner.query(`CREATE TRIGGER trg_act_company_responses_append_only BEFORE UPDATE OR DELETE ON inspection_act_company_responses FOR EACH ROW EXECUTE FUNCTION prevent_f12_append_only_mutation()`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TRIGGER IF EXISTS trg_act_company_responses_append_only ON inspection_act_company_responses`);
await queryRunner.query(`DROP TRIGGER IF EXISTS trg_act_deadline_events_append_only ON inspection_act_deadline_events`);
await queryRunner.query(`DROP FUNCTION IF EXISTS prevent_f12_append_only_mutation()`);
await queryRunner.query(`DROP TABLE inspection_act_company_responses`);
await queryRunner.query(`DROP TABLE inspection_act_deadline_events`);
}
}
@@ -0,0 +1,14 @@
import { Controller, Get, Param, ParseUUIDPipe } from '@nestjs/common';
import { RequirePermissions } from '../authorization/decorators/require-permissions.decorator';
import { FieldBriefingService } from './field-briefing.service';
@Controller('inspection-visits/:visitId/field-briefing')
export class FieldBriefingController {
constructor(private readonly briefing: FieldBriefingService) {}
@Get()
@RequirePermissions('inspections.read')
get(@Param('visitId', new ParseUUIDPipe({ version: '4' })) visitId: string) {
return this.briefing.getForVisit(visitId);
}
}
@@ -0,0 +1,9 @@
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 {}
@@ -0,0 +1,310 @@
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,
};
}
}
+2 -2
View File
@@ -1,2 +1,2 @@
export const API_VERSION = '0.20.0-1';
export const API_PHASE = 'F1.1';
export const API_VERSION = '0.20.0-3';
export const API_PHASE = 'F1.3';
@@ -0,0 +1,42 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import test from 'node:test';
import { validate } from 'class-validator';
import { plainToInstance } from 'class-transformer';
import { SetActResponseDeadlineDto } from '../../src/act-administration/dto/set-act-response-deadline.dto';
import { CreateActCompanyResponseDto } from '../../src/act-administration/dto/create-act-company-response.dto';
const source = (path: string) => readFileSync(resolve(process.cwd(), path), 'utf8');
const migration = source('src/database/migrations/1789581600000-phase-f1-2-act-administration.ts');
const service = source('src/act-administration/act-administration.service.ts');
const controller = source('src/act-administration/act-administration.controller.ts');
test('F1.2 stores one append-only administrative deadline ledger per Act', () => {
assert.match(migration, /inspection_act_deadline_events/);
assert.match(migration, /append_only/);
assert.match(service, /ACT_RESPONSE_DEADLINE_SET/);
});
test('F1.2 preserves ambiguous historical finding deadlines instead of collapsing them', () => {
assert.match(migration, /HAVING COUNT\(DISTINCT correction_due_on\) = 1/);
});
test('F1.2 stores company responses and protected PDF metadata at Act level', () => {
assert.match(migration, /inspection_act_company_responses/);
assert.match(service, /%PDF-/);
assert.match(controller, /inspection-acts\/:actId\/administration/);
});
test('F1.2 deadline and company response DTOs reject invalid office input', async () => {
const deadline = plainToInstance(SetActResponseDeadlineDto, { responseDueOn: 'bad', reason: 'x' });
assert.ok((await validate(deadline)).length >= 2);
const response = plainToInstance(CreateActCompanyResponseDto, { receivedOn: 'bad', contactEmail: 'bad' });
assert.ok((await validate(response)).length >= 2);
});
test('F1.2 derives administrative queues from Acts instead of replacing finding history', () => {
assert.match(service, /WAITING_RESPONSE/);
assert.match(service, /COMMITMENT_OVERDUE/);
assert.match(service, /inspection_findings/);
});
@@ -0,0 +1,37 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
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');
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', () => {
assert.match(service, /inspection_act_deadline_events/);
assert.match(service, /inspection_act_company_responses/);
assert.doesNotMatch(service, /company_response_received_on/);
});
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 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/);
});
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "dhv2-web",
"version": "0.19.6-4",
"version": "0.20.0-2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dhv2-web",
"version": "0.19.6-4",
"version": "0.20.0-2",
"dependencies": {
"maplibre-gl": "^6.0.0",
"react": "^19.0.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dhv2-web",
"version": "0.20.0-1",
"version": "0.20.0-3",
"private": true,
"type": "module",
"engines": {
+6 -2
View File
@@ -32,10 +32,13 @@ import { ActsPage } from '../pages/ActsPage';
import { ReportsPage } from '../pages/ReportsPage';
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 })));
export function App() {
return <Suspense fallback={<div className="loading-block"><span className="spinner" />Cargando módulo</div>}><Routes>
<Route path="/login" element={<LoginPage />} />
@@ -63,6 +66,7 @@ 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" />}>
@@ -71,7 +75,7 @@ export function App() {
</Route>
<Route element={<PermissionRoute permission="inspection_findings.read" />}><Route path="/hallazgos" element={<FindingsPage />} /><Route path="/hallazgos/:id" element={<FindingDetailPage />} /></Route>
<Route element={<PermissionRoute permission="inspection_verifications.plan" />}><Route path="/hallazgos/planificacion" element={<VerificationPlanningPage />} /></Route>
<Route element={<PermissionRoute permission="inspection_acts.read" />}><Route path="/actas" element={<ActsPage />} /></Route>
<Route element={<PermissionRoute permission="inspection_acts.read" />}><Route path="/actas" element={<ActsPage />} /><Route path="/seguimiento-actas" element={<ActAdministrationPage />} /><Route path="/seguimiento-actas/:actId" element={<ActAdministrationDetailPage />} /></Route>
<Route element={<PermissionRoute permission="inspection_reports.read" />}><Route path="/informes" element={<ReportsPage />} /><Route path="/informes/:id" element={<ReportDetailPage />} /></Route>
<Route element={<PermissionRoute permission="assets.read_history" />}><Route path="/historial" element={<HistoryPage />} /></Route>
<Route element={<PermissionRoute permission="assets.read_temporal" />}><Route path="/consulta-temporal" element={<TemporalAssetsPage />} /></Route>
+2 -2
View File
@@ -1,2 +1,2 @@
export const APP_VERSION = '0.20.0-1';
export const APP_PHASE = 'Fase F1.1 · Inspección multi-Acta y firma diferida';
export const APP_VERSION = '0.20.0-3';
export const APP_PHASE = 'Fase F1.3 · Preparación inteligente de campo';
+2
View File
@@ -16,9 +16,11 @@ 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[] = [
{ to: '/seguimiento-actas', label: 'Seguimiento de actas', icon: 'clipboard', permission: 'inspection_acts.read' },
{ to: '/hallazgos', label: 'Hallazgos', icon: 'alert', permission: 'inspection_findings.read' },
];
+33
View File
@@ -3096,3 +3096,36 @@ export function updateDocumentDeliverySettings(input:{officeEmail?:string|null;d
export function listDocumentDeliveries(){return apiRequest<{data:DocumentDeliveryItem[]}>('/document-delivery/outbox');}
export function retryDocumentDelivery(id:string){return apiRequest<DocumentDeliveryItem>(`/document-delivery/outbox/${id}/retry`,{method:'POST'});}
export function retryPendingDocumentDeliveries(){return apiRequest<{processed:number}>('/document-delivery/outbox/retry-pending',{method:'POST'});}
export type ActAdministrationState = 'NEW' | 'WAITING_RESPONSE' | 'DUE_SOON' | 'OVERDUE' | 'RESPONSE_RECEIVED' | 'VERIFICATION_PENDING' | 'COMMITMENT_OVERDUE' | 'REGULARIZED';
export interface ActAdministrationQueueItem {
actId: string; actCode: string; actStatus: string; occurredAt: string; closedAt: string | null;
visitId: string; visitCode: string; areaId: string | null; companyId: string | null; areaName: string | null; companyName: string | null;
responseDueOn: string | null; deadlineReason: string | null; responseReceivedOn: string | null; committedCorrectionOn: string | null;
findingCount: number; openFindingCount: number; scheduledControlCount: number; adminState: ActAdministrationState;
}
export interface ActAdministrationQueuePage { data: ActAdministrationQueueItem[]; counters: Partial<Record<ActAdministrationState, number>>; meta: PageMeta }
export interface ActAdministrationDetail {
act: ActAdministrationQueueItem;
deadlines: Array<{ id:string; responseDueOn:string; reason:string; createdAt:string }>;
responses: Array<{ id:string; receivedOn:string; details:string|null; committedCorrectionOn:string|null; contactName:string|null; contactEmail:string|null; originalName:string|null; sizeBytes:number|null; sha256:string|null; createdAt:string }>;
findings: Array<{ id:string; code:string; title:string; status:string; nextControlOn:string|null }>;
}
export function listActAdministrationQueue(params: { state?: ActAdministrationState | 'ALL'; areaId?: string; companyId?: string; page?: number; pageSize?: number } = {}) {
const q = new URLSearchParams({ page: String(params.page ?? 1), pageSize: String(params.pageSize ?? 25) });
if (params.state && params.state !== 'ALL') q.set('state', params.state);
if (params.areaId) q.set('areaId', params.areaId);
if (params.companyId) q.set('companyId', params.companyId);
return apiRequest<ActAdministrationQueuePage>(`/act-administration/queue?${q}`);
}
export function getActAdministration(actId: string) { return apiRequest<ActAdministrationDetail>(`/inspection-acts/${actId}/administration`); }
export function setActResponseDeadline(actId: string, input: { responseDueOn: string; reason: string }) { return apiRequest(`/inspection-acts/${actId}/administration/deadline`, { method: 'PATCH', body: JSON.stringify(input) }); }
export function addActCompanyResponse(actId: string, input: { receivedOn: string; details?: string; committedCorrectionOn?: string; contactName?: string; contactEmail?: string; file?: File }) {
const body = new FormData(); body.append('receivedOn', input.receivedOn);
if (input.details) body.append('details', input.details); if (input.committedCorrectionOn) body.append('committedCorrectionOn', input.committedCorrectionOn);
if (input.contactName) body.append('contactName', input.contactName); if (input.contactEmail) body.append('contactEmail', input.contactEmail); if (input.file) body.append('file', input.file);
return apiRequest(`/inspection-acts/${actId}/administration/responses`, { method: 'POST', body });
}
export function actCompanyResponseContentUrl(responseId: string) { return `${API_BASE}/act-company-responses/${responseId}/content`; }
export function listActAdministrationCalendar(from?: string, to?: string) { const q=new URLSearchParams(); if(from)q.set('from',from); if(to)q.set('to',to); return apiRequest<{from:string;to:string;data:Array<{type:'RESPONSE_DUE'|'COMMITMENT_DUE';date:string;actId:string;actCode:string;areaName:string|null;companyName:string|null;state:ActAdministrationState}>}>(`/act-administration/calendar${q.size?`?${q}`:''}`); }
@@ -0,0 +1,20 @@
import { useEffect, useState } from 'react';
import type { FormEvent } from 'react';
import { Link, useParams } from 'react-router';
import { Alert, LoadingBlock, errorMessage } from '../components/Feedback';
import { addActCompanyResponse, actCompanyResponseContentUrl, getActAdministration, setActResponseDeadline } from '../lib/api';
import type { ActAdministrationDetail } from '../lib/api';
import { formatDate } from '../lib/format';
export function ActAdministrationDetailPage(){
const {actId=''}=useParams(); const [data,setData]=useState<ActAdministrationDetail|null>(null); const [error,setError]=useState(''); const [busy,setBusy]=useState(false); const [due,setDue]=useState(''); const [reason,setReason]=useState('Plazo administrativo otorgado a la empresa'); const [received,setReceived]=useState(new Date().toISOString().slice(0,10)); const [details,setDetails]=useState(''); const [commitment,setCommitment]=useState(''); const [file,setFile]=useState<File|undefined>();
const load=()=>getActAdministration(actId).then(setData).catch(e=>setError(errorMessage(e))); useEffect(()=>{void load()},[actId]);
const deadline=async(e:FormEvent)=>{e.preventDefault();setBusy(true);setError('');try{await setActResponseDeadline(actId,{responseDueOn:due,reason});setDue('');await load()}catch(err){setError(errorMessage(err))}finally{setBusy(false)}};
const response=async(e:FormEvent)=>{e.preventDefault();setBusy(true);setError('');try{await addActCompanyResponse(actId,{receivedOn:received,details:details||undefined,committedCorrectionOn:commitment||undefined,file});setDetails('');setCommitment('');setFile(undefined);await load()}catch(err){setError(errorMessage(err))}finally{setBusy(false)}};
if(!data&&!error)return <LoadingBlock label="Cargando expediente administrativo…"/>;
return <section>{error&&<Alert>{error}</Alert>}{data&&<><div className="page-heading"><div><span className="eyebrow">EXPEDIENTE ADMINISTRATIVO</span><h1>{data.act.actCode}</h1><p>{data.act.areaName??'Área sin asignar'} · {data.act.companyName??'Empresa sin asignar'} · {data.act.openFindingCount} hallazgos abiertos</p></div><Link className="button secondary" to={`/inspecciones/actas/${data.act.actId}`}>Ver Acta</Link></div>
<div className="detail-grid"><div className="card"><h2>Plazo de respuesta</h2><p>El plazo aplica al conjunto completo de hallazgos del Acta.</p><form className="form-grid" onSubmit={deadline}><label><span>Vencimiento *</span><input type="date" required value={due} onChange={e=>setDue(e.target.value)}/></label><label className="full"><span>Motivo *</span><textarea required minLength={3} value={reason} onChange={e=>setReason(e.target.value)}/></label><button className="button primary" disabled={busy}>Registrar nuevo plazo</button></form>{data.deadlines.length>0&&<div className="stack-list">{data.deadlines.map(d=><div key={d.id}><strong>{formatDate(d.responseDueOn)}</strong><small>{d.reason}</small></div>)}</div>}</div>
<div className="card"><h2>Respuesta de la empresa</h2><form className="form-grid" onSubmit={response}><label><span>Recibida el *</span><input type="date" required value={received} onChange={e=>setReceived(e.target.value)}/></label><label><span>Fecha comprometida</span><input type="date" value={commitment} onChange={e=>setCommitment(e.target.value)}/></label><label className="full"><span>Detalle</span><textarea value={details} onChange={e=>setDetails(e.target.value)} placeholder="Resumen de la presentación de la empresa"/></label><label className="full"><span>PDF presentado</span><input type="file" accept="application/pdf,.pdf" onChange={e=>setFile(e.target.files?.[0])}/></label><button className="button primary" disabled={busy}>Registrar respuesta</button></form>{data.responses.length>0&&<div className="stack-list">{data.responses.map(r=><div key={r.id}><strong>{formatDate(r.receivedOn)}</strong><small>{r.details??'Sin detalle'}{r.committedCorrectionOn?` · compromiso ${formatDate(r.committedCorrectionOn)}`:''}</small>{r.originalName&&<a className="text-link" href={actCompanyResponseContentUrl(r.id)} target="_blank" rel="noreferrer">Abrir PDF</a>}</div>)}</div>}</div></div>
<div className="card"><h2>Hallazgos del Acta</h2><div className="table-scroll"><table><thead><tr><th>Código</th><th>Hallazgo</th><th>Estado</th><th>Próximo control</th></tr></thead><tbody>{data.findings.map(f=><tr key={f.id}><td><Link className="text-link" to={`/hallazgos/${f.id}`}>{f.code}</Link></td><td>{f.title}</td><td>{f.status}</td><td>{f.nextControlOn?formatDate(f.nextControlOn):'Sin programar'}</td></tr>)}</tbody></table></div></div></>}</section>;
}
@@ -0,0 +1,22 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router';
import { Alert, EmptyState, LoadingBlock, errorMessage } from '../components/Feedback';
import { useOperationalContext } from '../context/OperationalContext';
import { listActAdministrationQueue } from '../lib/api';
import type { ActAdministrationQueueItem, ActAdministrationState, PageMeta } from '../lib/api';
import { formatDate } from '../lib/format';
const states: Array<{value:'ALL'|ActAdministrationState;label:string}> = [
{value:'ALL',label:'Todas'}, {value:'NEW',label:'Nuevas'}, {value:'WAITING_RESPONSE',label:'Esperando respuesta'},
{value:'DUE_SOON',label:'Próximas a vencer'}, {value:'OVERDUE',label:'Vencidas'}, {value:'RESPONSE_RECEIVED',label:'Respondidas'},
{value:'VERIFICATION_PENDING',label:'A verificar'}, {value:'COMMITMENT_OVERDUE',label:'Compromiso vencido'}, {value:'REGULARIZED',label:'Regularizadas'},
];
const label=(s:ActAdministrationState)=>states.find(x=>x.value===s)?.label??s;
export function ActAdministrationPage(){
const ctx=useOperationalContext(); const [state,setState]=useState<'ALL'|ActAdministrationState>('ALL'); const [items,setItems]=useState<ActAdministrationQueueItem[]>([]); const [meta,setMeta]=useState<PageMeta>({page:1,pageSize:25,total:0,totalPages:0}); const [counters,setCounters]=useState<Partial<Record<ActAdministrationState,number>>>({}); const [loading,setLoading]=useState(true); const [error,setError]=useState('');
useEffect(()=>{setLoading(true);setError('');listActAdministrationQueue({state,areaId:ctx.areaId||undefined,companyId:ctx.companyId||undefined,page:1,pageSize:50}).then(r=>{setItems(r.data);setMeta(r.meta);setCounters(r.counters)}).catch(e=>setError(errorMessage(e))).finally(()=>setLoading(false));},[state,ctx.areaId,ctx.companyId]);
return <section><div className="page-heading"><div><span className="eyebrow">SEGUIMIENTO ADMINISTRATIVO</span><h1>Seguimiento de Actas</h1><p>El plazo y la respuesta de la empresa se gestionan sobre el Acta completa. Los hallazgos quedan dentro de su expediente.</p></div></div>
<div className="status-tabs">{states.map(s=><button key={s.value} className={state===s.value?'active':''} onClick={()=>setState(s.value)}>{s.label}{s.value!=='ALL'&&<small>{counters[s.value]??0}</small>}</button>)}</div>
{error&&<Alert>{error}</Alert>}{loading?<LoadingBlock label="Cargando seguimiento…"/>:items.length===0?<EmptyState title="Sin actas" text="No hay actas en este estado para el contexto seleccionado."/>:<div className="table-panel"><div className="table-summary"><strong>{meta.total} acta{meta.total===1?'':'s'}</strong></div><div className="table-scroll"><table><thead><tr><th>Acta</th><th>Área / empresa</th><th>Hallazgos</th><th>Plazo empresa</th><th>Respuesta</th><th>Estado</th><th/></tr></thead><tbody>{items.map(a=><tr key={a.actId}><td><strong>{a.actCode}</strong><small className="block-muted">{formatDate(a.occurredAt)}</small></td><td><strong>{a.areaName??'—'}</strong><small className="block-muted">{a.companyName??'—'}</small></td><td>{a.openFindingCount} abiertos / {a.findingCount}</td><td>{a.responseDueOn?formatDate(a.responseDueOn):'Sin definir'}</td><td>{a.responseReceivedOn?formatDate(a.responseReceivedOn):'Pendiente'}</td><td><span className={`status-badge ${a.adminState==='OVERDUE'||a.adminState==='COMMITMENT_OVERDUE'?'danger':'pending'}`}>{label(a.adminState)}</span></td><td><Link className="button secondary" to={`/seguimiento-actas/${a.actId}`}>Gestionar</Link></td></tr>)}</tbody></table></div></div>}</section>;
}
+192
View File
@@ -0,0 +1,192 @@
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>;
}