Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e55684bf4f | ||
|
|
ddf3b158e7 | ||
|
|
8564f1933c | ||
|
|
ea890cb807 | ||
|
|
ce27cd01e9 | ||
|
|
a155d9e075 | ||
|
|
e89d815868 | ||
|
|
ff0b6d83db | ||
|
|
d894391d97 | ||
|
|
c79537def9 | ||
|
|
83c9e2ca3e | ||
|
|
9254583154 | ||
|
|
0b21e6bc50 | ||
|
|
350e26566f | ||
|
|
ba79fbf9ae | ||
|
|
77def3b511 |
@@ -48,7 +48,7 @@ jobs:
|
|||||||
run: sdkmanager 'platforms;android-36' 'build-tools;36.0.0'
|
run: sdkmanager 'platforms;android-36' 'build-tools;36.0.0'
|
||||||
|
|
||||||
- name: Gradle 8.13
|
- name: Gradle 8.13
|
||||||
uses: gradle/actions/setup-gradle@v4
|
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
|
||||||
with:
|
with:
|
||||||
gradle-version: '8.13'
|
gradle-version: '8.13'
|
||||||
|
|
||||||
|
|||||||
@@ -309,9 +309,14 @@ jobs:
|
|||||||
docker compose --env-file .env.example build api
|
docker compose --env-file .env.example build api
|
||||||
docker compose --env-file .env.example up -d api
|
docker compose --env-file .env.example up -d api
|
||||||
|
|
||||||
|
# In containerized runners (Gitea DinD), 127.0.0.1 of the job
|
||||||
|
# is not the Docker daemon host. Probe the production API from
|
||||||
|
# inside its own container so this barrier works on GitHub and Gitea.
|
||||||
api_ready=0
|
api_ready=0
|
||||||
for _ in $(seq 1 30); do
|
for _ in $(seq 1 30); do
|
||||||
if curl -fsS http://127.0.0.1:3101/api/v3/health >/tmp/dhv2-health.json 2>/dev/null; then
|
if docker compose --env-file .env.example exec -T api \
|
||||||
|
node -e 'fetch(`http://127.0.0.1:${process.env.API_PORT}/api/v3/health`).then(async r => { const t = await r.text(); process.stdout.write(t); if (!r.ok) process.exit(1); }).catch(() => process.exit(1))' \
|
||||||
|
>/tmp/dhv2-health.json 2>/dev/null; then
|
||||||
api_ready=1
|
api_ready=1
|
||||||
break
|
break
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -0,0 +1,407 @@
|
|||||||
|
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||||
|
import { DataSource } from 'typeorm';
|
||||||
|
|
||||||
|
type DossierRecord = Record<string, any>;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ActivityDossierService {
|
||||||
|
private readonly logger = new Logger(ActivityDossierService.name);
|
||||||
|
|
||||||
|
constructor(private readonly dataSource: DataSource) {}
|
||||||
|
|
||||||
|
async dossier(id: string): Promise<Record<string, unknown>> {
|
||||||
|
const assetRows = (await this.dataSource.query(
|
||||||
|
`SELECT id, code, name, common_name AS "commonName", created_at AS "createdAt"
|
||||||
|
FROM assets
|
||||||
|
WHERE id = $1`,
|
||||||
|
[id],
|
||||||
|
)) as Array<{ id: string; code: string; name: string; commonName: string | null; createdAt: Date }>;
|
||||||
|
const asset = assetRows[0];
|
||||||
|
if (!asset) {
|
||||||
|
throw new NotFoundException({
|
||||||
|
code: 'ASSET_NOT_FOUND',
|
||||||
|
message: 'Activo no encontrado',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const failedFacets: string[] = [];
|
||||||
|
const safeQuery = async (facet: string, sql: string): Promise<DossierRecord[]> => {
|
||||||
|
try {
|
||||||
|
return (await this.dataSource.query(sql, [id])) as DossierRecord[];
|
||||||
|
} catch (error) {
|
||||||
|
failedFacets.push(facet);
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
this.logger.error(`No se pudo cargar la faceta ${facet} del expediente ${id}: ${message}`);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const [
|
||||||
|
visits,
|
||||||
|
acts,
|
||||||
|
findings,
|
||||||
|
evidence,
|
||||||
|
communications,
|
||||||
|
verificationResults,
|
||||||
|
documents,
|
||||||
|
inspectionReports,
|
||||||
|
media,
|
||||||
|
versions,
|
||||||
|
] = await Promise.all([
|
||||||
|
safeQuery('visits', `
|
||||||
|
SELECT visit.id, visit.code, visit.status,
|
||||||
|
visit.planned_start_at AS "plannedStartAt",
|
||||||
|
visit.actual_started_at AS "actualStartedAt",
|
||||||
|
visit.actual_closed_at AS "actualClosedAt",
|
||||||
|
visit.created_at AS "createdAt"
|
||||||
|
FROM inspection_visits visit
|
||||||
|
WHERE visit.scope_asset_id = $1
|
||||||
|
OR EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM inspection_visit_assets visit_asset
|
||||||
|
WHERE visit_asset.visit_id = visit.id
|
||||||
|
AND visit_asset.asset_id = $1
|
||||||
|
AND visit_asset.included = true
|
||||||
|
)
|
||||||
|
OR EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM inspection_acts act
|
||||||
|
JOIN inspection_act_assets act_asset
|
||||||
|
ON act_asset.act_id = act.id AND act_asset.included = true
|
||||||
|
WHERE act.visit_id = visit.id
|
||||||
|
AND act_asset.asset_id = $1
|
||||||
|
)
|
||||||
|
OR EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM inspection_acts act
|
||||||
|
JOIN inspection_findings finding ON finding.act_id = act.id
|
||||||
|
WHERE act.visit_id = visit.id
|
||||||
|
AND finding.asset_id = $1
|
||||||
|
)
|
||||||
|
ORDER BY COALESCE(visit.actual_started_at, visit.planned_start_at, visit.created_at) DESC
|
||||||
|
LIMIT 200
|
||||||
|
`),
|
||||||
|
safeQuery('acts', `
|
||||||
|
SELECT act.id, act.visit_id AS "visitId", act.code, act.status,
|
||||||
|
act.occurred_at AS "occurredAt", act.title, act.summary,
|
||||||
|
act.closed_at AS "closedAt", act.current_version AS "currentVersion",
|
||||||
|
visit.code AS "visitCode"
|
||||||
|
FROM inspection_acts act
|
||||||
|
JOIN inspection_visits visit ON visit.id = act.visit_id
|
||||||
|
WHERE EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM inspection_act_assets act_asset
|
||||||
|
WHERE act_asset.act_id = act.id
|
||||||
|
AND act_asset.asset_id = $1
|
||||||
|
AND act_asset.included = true
|
||||||
|
)
|
||||||
|
OR EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM inspection_findings finding
|
||||||
|
WHERE finding.act_id = act.id
|
||||||
|
AND finding.asset_id = $1
|
||||||
|
)
|
||||||
|
ORDER BY act.occurred_at DESC
|
||||||
|
LIMIT 200
|
||||||
|
`),
|
||||||
|
safeQuery('findings', `
|
||||||
|
SELECT finding.id, finding.act_id AS "actId", finding.code, finding.status,
|
||||||
|
finding.title, finding.description,
|
||||||
|
finding.correction_due_on AS "correctionDueOn",
|
||||||
|
finding.company_response_received_on AS "companyResponseReceivedOn",
|
||||||
|
finding.next_control_on AS "nextControlOn",
|
||||||
|
finding.closed_at AS "closedAt", finding.closure_notes AS "closureNotes",
|
||||||
|
finding.created_at AS "createdAt", finding.updated_at AS "updatedAt",
|
||||||
|
act.code AS "actCode", act.occurred_at AS "actOccurredAt",
|
||||||
|
visit.id AS "visitId", visit.code AS "visitCode"
|
||||||
|
FROM inspection_findings finding
|
||||||
|
JOIN inspection_acts act ON act.id = finding.act_id
|
||||||
|
JOIN inspection_visits visit ON visit.id = act.visit_id
|
||||||
|
WHERE finding.asset_id = $1
|
||||||
|
ORDER BY finding.created_at DESC
|
||||||
|
LIMIT 500
|
||||||
|
`),
|
||||||
|
safeQuery('evidence', `
|
||||||
|
SELECT evidence.id, evidence.finding_id AS "findingId", evidence.communication_id AS "communicationId",
|
||||||
|
evidence.kind, evidence.purpose, evidence.original_name AS "originalName",
|
||||||
|
evidence.title, evidence.description, evidence.captured_at AS "capturedAt",
|
||||||
|
evidence.created_at AS "createdAt", finding.code AS "findingCode",
|
||||||
|
finding.title AS "findingTitle"
|
||||||
|
FROM inspection_finding_evidence evidence
|
||||||
|
JOIN inspection_findings finding ON finding.id = evidence.finding_id
|
||||||
|
WHERE finding.asset_id = $1
|
||||||
|
ORDER BY COALESCE(evidence.captured_at, evidence.created_at) DESC
|
||||||
|
LIMIT 500
|
||||||
|
`),
|
||||||
|
safeQuery('communications', `
|
||||||
|
SELECT communication.id, communication.finding_id AS "findingId",
|
||||||
|
communication.direction, communication.channel, communication.type,
|
||||||
|
communication.occurred_at AS "occurredAt", communication.subject,
|
||||||
|
communication.details, communication.contact_name AS "contactName",
|
||||||
|
communication.created_at AS "createdAt", finding.code AS "findingCode",
|
||||||
|
finding.title AS "findingTitle"
|
||||||
|
FROM inspection_finding_communications communication
|
||||||
|
JOIN inspection_findings finding ON finding.id = communication.finding_id
|
||||||
|
WHERE finding.asset_id = $1
|
||||||
|
ORDER BY communication.occurred_at DESC
|
||||||
|
LIMIT 500
|
||||||
|
`),
|
||||||
|
safeQuery('verificationResults', `
|
||||||
|
SELECT verification_link.id,
|
||||||
|
verification_link.finding_id AS "findingId",
|
||||||
|
verification_link.visit_id AS "visitId",
|
||||||
|
verification_link.target_control_on AS "targetControlOn",
|
||||||
|
verification_link.outcome,
|
||||||
|
verification_link.result_notes AS "resultNotes",
|
||||||
|
verification_link.verified_at AS "verifiedAt",
|
||||||
|
verification_link.result_recorded_at AS "resultRecordedAt",
|
||||||
|
verification_link.rescheduled_control_on AS "rescheduledControlOn",
|
||||||
|
finding.code AS "findingCode", finding.title AS "findingTitle",
|
||||||
|
visit.code AS "visitCode", visit.status AS "visitStatus",
|
||||||
|
(SELECT COUNT(*)::integer
|
||||||
|
FROM inspection_finding_evidence verification_evidence
|
||||||
|
WHERE verification_evidence.finding_id = finding.id
|
||||||
|
AND verification_evidence.verification_visit_id = visit.id
|
||||||
|
AND verification_evidence.purpose = 'VERIFICATION') AS "evidenceCount"
|
||||||
|
FROM inspection_finding_verification_visits verification_link
|
||||||
|
JOIN inspection_findings finding ON finding.id = verification_link.finding_id
|
||||||
|
JOIN inspection_visits visit ON visit.id = verification_link.visit_id
|
||||||
|
WHERE finding.asset_id = $1 AND verification_link.outcome IS NOT NULL
|
||||||
|
ORDER BY verification_link.verified_at DESC NULLS LAST, verification_link.result_recorded_at DESC
|
||||||
|
LIMIT 500
|
||||||
|
`),
|
||||||
|
safeQuery('documents', `
|
||||||
|
SELECT document.id, document.document_type AS "documentType",
|
||||||
|
document.document_number AS "documentNumber", document.title,
|
||||||
|
document.issuer, document.document_date AS "documentDate",
|
||||||
|
document.external_reference AS "externalReference",
|
||||||
|
link.relation_type AS "relationType", link.notes,
|
||||||
|
link.created_at AS "linkedAt"
|
||||||
|
FROM asset_source_documents link
|
||||||
|
JOIN source_documents document ON document.id = link.document_id
|
||||||
|
WHERE link.asset_id = $1
|
||||||
|
ORDER BY COALESCE(document.document_date::timestamptz, link.created_at) DESC
|
||||||
|
LIMIT 300
|
||||||
|
`),
|
||||||
|
safeQuery('inspectionReports', `
|
||||||
|
SELECT report.id, report.code, report.status,
|
||||||
|
report.pdf_status AS "pdfStatus", report.title,
|
||||||
|
report.generated_at AS "generatedAt", report.frozen_sha256 AS "frozenSha256",
|
||||||
|
act.id AS "actId", act.code AS "actCode",
|
||||||
|
visit.id AS "visitId", visit.code AS "visitCode"
|
||||||
|
FROM inspection_reports report
|
||||||
|
JOIN inspection_acts act ON act.id = report.act_id
|
||||||
|
JOIN inspection_visits visit ON visit.id = report.visit_id
|
||||||
|
WHERE visit.scope_asset_id = $1
|
||||||
|
OR EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM inspection_act_assets act_asset
|
||||||
|
WHERE act_asset.act_id = act.id
|
||||||
|
AND act_asset.asset_id = $1
|
||||||
|
AND act_asset.included = true
|
||||||
|
)
|
||||||
|
OR EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM inspection_findings finding
|
||||||
|
WHERE finding.act_id = act.id
|
||||||
|
AND finding.asset_id = $1
|
||||||
|
)
|
||||||
|
ORDER BY report.generated_at DESC
|
||||||
|
LIMIT 200
|
||||||
|
`),
|
||||||
|
safeQuery('media', `
|
||||||
|
SELECT media.id, media.kind, media.original_name AS "originalName",
|
||||||
|
media.title, media.description, media.captured_at AS "capturedAt",
|
||||||
|
media.created_at AS "createdAt", media.source
|
||||||
|
FROM asset_media media
|
||||||
|
WHERE media.asset_id = $1 AND media.deleted_at IS NULL
|
||||||
|
ORDER BY COALESCE(media.captured_at, media.created_at) DESC
|
||||||
|
LIMIT 500
|
||||||
|
`),
|
||||||
|
safeQuery('versions', `
|
||||||
|
SELECT version.id, version.version_number AS "versionNumber",
|
||||||
|
version.change_type AS "changeType", version.changed_fields AS "changedFields",
|
||||||
|
version.occurred_at AS "occurredAt", version.actor_username AS "actorUsername",
|
||||||
|
version.source
|
||||||
|
FROM asset_versions version
|
||||||
|
WHERE version.asset_id = $1
|
||||||
|
ORDER BY version.occurred_at DESC
|
||||||
|
LIMIT 500
|
||||||
|
`),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const timeline: DossierRecord[] = [];
|
||||||
|
const push = (event: DossierRecord) => timeline.push(event);
|
||||||
|
|
||||||
|
versions.forEach((version) => push({
|
||||||
|
id: `version:${String(version.id)}`,
|
||||||
|
kind: 'INVENTORY_CHANGE',
|
||||||
|
occurredAt: version.occurredAt,
|
||||||
|
title: version.changeType === 'CREATED' || version.changeType === 'BASELINE'
|
||||||
|
? 'Registro incorporado al inventario'
|
||||||
|
: 'Inventario actualizado',
|
||||||
|
description: Array.isArray(version.changedFields) && version.changedFields.length > 0
|
||||||
|
? `Campos: ${(version.changedFields as string[]).join(', ')}`
|
||||||
|
: null,
|
||||||
|
meta: {
|
||||||
|
versionNumber: version.versionNumber,
|
||||||
|
changeType: version.changeType,
|
||||||
|
actorUsername: version.actorUsername,
|
||||||
|
source: version.source,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
visits.forEach((visit) => push({
|
||||||
|
id: `visit:${String(visit.id)}`,
|
||||||
|
kind: 'INSPECTION',
|
||||||
|
occurredAt: visit.actualStartedAt ?? visit.plannedStartAt ?? visit.createdAt,
|
||||||
|
title: `Inspección ${String(visit.code)}`,
|
||||||
|
description: null,
|
||||||
|
href: `/inspecciones/${String(visit.id)}`,
|
||||||
|
meta: { status: visit.status },
|
||||||
|
}));
|
||||||
|
acts.forEach((act) => push({
|
||||||
|
id: `act:${String(act.id)}`,
|
||||||
|
kind: 'ACT',
|
||||||
|
occurredAt: act.occurredAt,
|
||||||
|
title: `Acta ${String(act.code)}`,
|
||||||
|
description: act.title,
|
||||||
|
href: `/inspecciones/actas/${String(act.id)}`,
|
||||||
|
meta: { status: act.status, visitCode: act.visitCode },
|
||||||
|
}));
|
||||||
|
findings.forEach((finding) => {
|
||||||
|
push({
|
||||||
|
id: `finding:${String(finding.id)}`,
|
||||||
|
kind: 'FINDING',
|
||||||
|
occurredAt: finding.createdAt,
|
||||||
|
title: `Hallazgo ${String(finding.code)}`,
|
||||||
|
description: finding.title,
|
||||||
|
href: `/hallazgos/${String(finding.id)}`,
|
||||||
|
meta: { status: finding.status, actCode: finding.actCode },
|
||||||
|
});
|
||||||
|
if (finding.closedAt) {
|
||||||
|
push({
|
||||||
|
id: `finding-close:${String(finding.id)}`,
|
||||||
|
kind: 'FINDING_CLOSED',
|
||||||
|
occurredAt: finding.closedAt,
|
||||||
|
title: `Hallazgo ${String(finding.code)} cerrado`,
|
||||||
|
description: finding.closureNotes,
|
||||||
|
href: `/hallazgos/${String(finding.id)}`,
|
||||||
|
meta: { status: finding.status },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
verificationResults.forEach((verification) => push({
|
||||||
|
id: `verification:${String(verification.id)}`,
|
||||||
|
kind: 'VERIFICATION',
|
||||||
|
occurredAt: verification.verifiedAt ?? verification.resultRecordedAt,
|
||||||
|
title: verification.outcome === 'RESOLVED'
|
||||||
|
? `Verificación conforme · ${String(verification.findingCode)}`
|
||||||
|
: verification.outcome === 'NOT_RESOLVED'
|
||||||
|
? `Verificación no conforme · ${String(verification.findingCode)}`
|
||||||
|
: `Verificación reprogramada · ${String(verification.findingCode)}`,
|
||||||
|
description: verification.resultNotes,
|
||||||
|
href: `/hallazgos/${String(verification.findingId)}`,
|
||||||
|
meta: {
|
||||||
|
outcome: verification.outcome,
|
||||||
|
visitCode: verification.visitCode,
|
||||||
|
targetControlOn: verification.targetControlOn,
|
||||||
|
rescheduledControlOn: verification.rescheduledControlOn,
|
||||||
|
evidenceCount: verification.evidenceCount,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
communications.forEach((communication) => push({
|
||||||
|
id: `communication:${String(communication.id)}`,
|
||||||
|
kind: 'COMMUNICATION',
|
||||||
|
occurredAt: communication.occurredAt,
|
||||||
|
title: communication.type === 'COMPANY_RESPONSE'
|
||||||
|
? 'Respuesta de la empresa'
|
||||||
|
: String(communication.subject),
|
||||||
|
description: communication.details,
|
||||||
|
href: `/hallazgos/${String(communication.findingId)}`,
|
||||||
|
meta: {
|
||||||
|
findingCode: communication.findingCode,
|
||||||
|
direction: communication.direction,
|
||||||
|
channel: communication.channel,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
evidence.forEach((item) => push({
|
||||||
|
id: `evidence:${String(item.id)}`,
|
||||||
|
kind: item.kind === 'PHOTO' ? 'PHOTO' : 'DOCUMENT',
|
||||||
|
occurredAt: item.capturedAt ?? item.createdAt,
|
||||||
|
title: item.kind === 'PHOTO' ? 'Fotografía / evidencia' : 'Documento incorporado',
|
||||||
|
description: item.title ?? item.originalName,
|
||||||
|
href: `/hallazgos/${String(item.findingId)}`,
|
||||||
|
meta: { findingCode: item.findingCode, purpose: item.purpose },
|
||||||
|
}));
|
||||||
|
inspectionReports.forEach((report) => push({
|
||||||
|
id: `inspection-report:${String(report.id)}`,
|
||||||
|
kind: 'REPORT',
|
||||||
|
occurredAt: report.generatedAt,
|
||||||
|
title: `Informe ${String(report.code)}`,
|
||||||
|
description: report.title,
|
||||||
|
href: `/informes/${String(report.id)}`,
|
||||||
|
meta: { status: report.status, pdfStatus: report.pdfStatus, actCode: report.actCode },
|
||||||
|
}));
|
||||||
|
documents.forEach((document) => push({
|
||||||
|
id: `source-document:${String(document.id)}`,
|
||||||
|
kind: document.documentType === 'TECHNICAL_REPORT' ? 'REPORT' : 'SOURCE_DOCUMENT',
|
||||||
|
occurredAt: document.documentDate ?? document.linkedAt,
|
||||||
|
title: String(document.title),
|
||||||
|
description: document.documentNumber
|
||||||
|
? `Documento ${String(document.documentNumber)}`
|
||||||
|
: 'Documento vinculado al inventario',
|
||||||
|
meta: { documentType: document.documentType, relationType: document.relationType },
|
||||||
|
}));
|
||||||
|
media.forEach((item) => push({
|
||||||
|
id: `asset-media:${String(item.id)}`,
|
||||||
|
kind: item.kind === 'PHOTO' ? 'PHOTO' : 'DOCUMENT',
|
||||||
|
occurredAt: item.capturedAt ?? item.createdAt,
|
||||||
|
title: item.kind === 'PHOTO' ? 'Fotografía del inventario' : 'Archivo del inventario',
|
||||||
|
description: item.title ?? item.originalName,
|
||||||
|
meta: { source: item.source },
|
||||||
|
}));
|
||||||
|
|
||||||
|
timeline.sort(
|
||||||
|
(a, b) => new Date(String(b.occurredAt ?? 0)).getTime() - new Date(String(a.occurredAt ?? 0)).getTime(),
|
||||||
|
);
|
||||||
|
|
||||||
|
const openFindings = findings.filter((finding) => finding.status === 'OPEN').length;
|
||||||
|
const closedFindings = findings.filter((finding) => finding.status === 'CLOSED').length;
|
||||||
|
const reports = documents.filter((document) => document.documentType === 'TECHNICAL_REPORT');
|
||||||
|
|
||||||
|
return {
|
||||||
|
asset: {
|
||||||
|
id: asset.id,
|
||||||
|
code: asset.code,
|
||||||
|
name: asset.name,
|
||||||
|
commonName: asset.commonName,
|
||||||
|
},
|
||||||
|
counters: {
|
||||||
|
inspections: visits.length,
|
||||||
|
acts: acts.length,
|
||||||
|
findings: findings.length,
|
||||||
|
verifications: verificationResults.length,
|
||||||
|
openFindings,
|
||||||
|
closedFindings,
|
||||||
|
evidence: evidence.length,
|
||||||
|
documents: documents.length + media.filter((item) => item.kind === 'DOCUMENT').length,
|
||||||
|
photos: evidence.filter((item) => item.kind === 'PHOTO').length
|
||||||
|
+ media.filter((item) => item.kind === 'PHOTO').length,
|
||||||
|
reports: reports.length + inspectionReports.length,
|
||||||
|
},
|
||||||
|
visits,
|
||||||
|
acts,
|
||||||
|
findings,
|
||||||
|
evidence,
|
||||||
|
communications,
|
||||||
|
verificationResults,
|
||||||
|
documents,
|
||||||
|
inspectionReports,
|
||||||
|
reports,
|
||||||
|
media,
|
||||||
|
versions,
|
||||||
|
timeline: timeline.slice(0, 500),
|
||||||
|
warnings: failedFacets,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,6 +32,7 @@ import { InventoryTechnicalValuesService } from './inventory-technical-values.se
|
|||||||
import { InventoryFunctionService } from './inventory-function.service';
|
import { InventoryFunctionService } from './inventory-function.service';
|
||||||
import { FieldInventoryMergeController, InventoryMergeController } from './inventory-merge.controller';
|
import { FieldInventoryMergeController, InventoryMergeController } from './inventory-merge.controller';
|
||||||
import { InventoryMergeService } from './inventory-merge.service';
|
import { InventoryMergeService } from './inventory-merge.service';
|
||||||
|
import { ActivityDossierService } from './activity-dossier.service';
|
||||||
import { MergedInventoryDossierService } from './merged-inventory-dossier.service';
|
import { MergedInventoryDossierService } from './merged-inventory-dossier.service';
|
||||||
import { InventoryBrowserController } from './inventory-browser.controller';
|
import { InventoryBrowserController } from './inventory-browser.controller';
|
||||||
import { InventoryBrowserService } from './inventory-browser.service';
|
import { InventoryBrowserService } from './inventory-browser.service';
|
||||||
@@ -66,6 +67,7 @@ import { InventoryBrowserService } from './inventory-browser.service';
|
|||||||
InventoryFunctionService,
|
InventoryFunctionService,
|
||||||
InventoryBrowserService,
|
InventoryBrowserService,
|
||||||
InventoryMergeService,
|
InventoryMergeService,
|
||||||
|
ActivityDossierService,
|
||||||
MergedInventoryDossierService,
|
MergedInventoryDossierService,
|
||||||
AssetGeometriesService,
|
AssetGeometriesService,
|
||||||
AssetHistoryService,
|
AssetHistoryService,
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { ActivityDossierService } from './activity-dossier.service';
|
||||||
import { AssetsService } from './assets.service';
|
import { AssetsService } from './assets.service';
|
||||||
import { InventoryFunctionService } from './inventory-function.service';
|
import { InventoryFunctionService } from './inventory-function.service';
|
||||||
import { InventoryMergeService } from './inventory-merge.service';
|
import { InventoryMergeService } from './inventory-merge.service';
|
||||||
|
|
||||||
type LooseRecord = Record<string, any>;
|
type LooseRecord = Record<string, any>;
|
||||||
|
|
||||||
|
const MERGEABLE_DOSSIER_TYPES = new Set(['instalacion', 'subinstalacion']);
|
||||||
|
|
||||||
function dedupeById<T extends LooseRecord>(items: T[]): T[] {
|
function dedupeById<T extends LooseRecord>(items: T[]): T[] {
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
const result: T[] = [];
|
const result: T[] = [];
|
||||||
@@ -29,11 +32,22 @@ function sortDesc(items: LooseRecord[], fieldCandidates: string[]): LooseRecord[
|
|||||||
export class MergedInventoryDossierService {
|
export class MergedInventoryDossierService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly assets: AssetsService,
|
private readonly assets: AssetsService,
|
||||||
|
private readonly activity: ActivityDossierService,
|
||||||
private readonly merges: InventoryMergeService,
|
private readonly merges: InventoryMergeService,
|
||||||
private readonly functions: InventoryFunctionService,
|
private readonly functions: InventoryFunctionService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async dossier(requestedAssetId: string): Promise<Record<string, unknown>> {
|
async dossier(requestedAssetId: string): Promise<Record<string, unknown>> {
|
||||||
|
const requestedAsset = await this.assets.getById(requestedAssetId);
|
||||||
|
const requestedTypeCode = requestedAsset.type.code.trim().toLowerCase();
|
||||||
|
|
||||||
|
// La conciliación/fusión existe sólo para Instalaciones y Subinstalaciones.
|
||||||
|
// Los registros territoriales (Departamento, Área, Yacimiento) deben poder
|
||||||
|
// abrir su Actividad sin depender del subsistema de merge.
|
||||||
|
if (!MERGEABLE_DOSSIER_TYPES.has(requestedTypeCode)) {
|
||||||
|
return await this.activity.dossier(requestedAssetId);
|
||||||
|
}
|
||||||
|
|
||||||
const mergeStatus = await this.merges.status(requestedAssetId) as LooseRecord;
|
const mergeStatus = await this.merges.status(requestedAssetId) as LooseRecord;
|
||||||
const canonical = mergeStatus.canonical as LooseRecord;
|
const canonical = mergeStatus.canonical as LooseRecord;
|
||||||
const requested = mergeStatus.requested as LooseRecord;
|
const requested = mergeStatus.requested as LooseRecord;
|
||||||
@@ -44,7 +58,7 @@ export class MergedInventoryDossierService {
|
|||||||
.filter((value, index, all) => all.indexOf(value) === index);
|
.filter((value, index, all) => all.indexOf(value) === index);
|
||||||
|
|
||||||
const dossiers = await Promise.all(inventoryIds.map(async (assetId) => {
|
const dossiers = await Promise.all(inventoryIds.map(async (assetId) => {
|
||||||
const dossier = await this.assets.dossier(assetId) as LooseRecord;
|
const dossier = await this.activity.dossier(assetId) as LooseRecord;
|
||||||
const identity = dossier.asset as LooseRecord;
|
const identity = dossier.asset as LooseRecord;
|
||||||
const functionDossier = await this.functions.getForAsset(assetId).catch(() => null) as LooseRecord | null;
|
const functionDossier = await this.functions.getForAsset(assetId).catch(() => null) as LooseRecord | null;
|
||||||
return { assetId, identity, dossier, functionDossier };
|
return { assetId, identity, dossier, functionDossier };
|
||||||
@@ -145,6 +159,9 @@ export class MergedInventoryDossierService {
|
|||||||
const reports = documents.filter((document) => document.documentType === 'TECHNICAL_REPORT');
|
const reports = documents.filter((document) => document.documentType === 'TECHNICAL_REPORT');
|
||||||
const openFindings = findings.filter((finding) => finding.status === 'OPEN').length;
|
const openFindings = findings.filter((finding) => finding.status === 'OPEN').length;
|
||||||
const closedFindings = findings.filter((finding) => finding.status === 'CLOSED').length;
|
const closedFindings = findings.filter((finding) => finding.status === 'CLOSED').length;
|
||||||
|
const warnings = dossiers.flatMap(({ assetId, dossier }) =>
|
||||||
|
((dossier.warnings ?? []) as string[]).map((facet) => `${assetId}:${facet}`),
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
asset: {
|
asset: {
|
||||||
@@ -194,6 +211,7 @@ export class MergedInventoryDossierService {
|
|||||||
media,
|
media,
|
||||||
versions,
|
versions,
|
||||||
timeline: timeline.slice(0, 1000),
|
timeline: timeline.slice(0, 1000),
|
||||||
|
warnings,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { ActivityDossierService } from '../../src/asset-master/activity-dossier.service';
|
||||||
|
|
||||||
|
test('F7 Actividad no usa DISTINCT con ORDER BY COALESCE en visitas', () => {
|
||||||
|
const source = readFileSync('src/asset-master/activity-dossier.service.ts', 'utf8');
|
||||||
|
assert.doesNotMatch(source, /SELECT\s+DISTINCT\s+visit\.id/i);
|
||||||
|
assert.match(source, /ORDER BY COALESCE\(visit\.actual_started_at, visit\.planned_start_at, visit\.created_at\) DESC/);
|
||||||
|
assert.match(source, /EXISTS \(\s*SELECT 1\s*FROM inspection_visit_assets/s);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F7 una faceta auxiliar defectuosa no derriba todo el expediente', async () => {
|
||||||
|
const dataSource = {
|
||||||
|
query: async (sql: string) => {
|
||||||
|
if (sql.includes('FROM assets\n WHERE id = $1')) {
|
||||||
|
return [{
|
||||||
|
id: 'bcba740f-cc84-48b3-8d06-88a9c439e25c',
|
||||||
|
code: 'YAC-0005',
|
||||||
|
name: 'Agua Botada',
|
||||||
|
commonName: null,
|
||||||
|
createdAt: new Date('2026-01-01T00:00:00Z'),
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
if (sql.includes('inspection_finding_communications')) {
|
||||||
|
throw new Error('simulated optional facet failure');
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const service = new ActivityDossierService(dataSource as never);
|
||||||
|
const dossier = await service.dossier('bcba740f-cc84-48b3-8d06-88a9c439e25c') as {
|
||||||
|
asset: { code: string; name: string };
|
||||||
|
counters: { inspections: number; findings: number };
|
||||||
|
warnings: string[];
|
||||||
|
timeline: unknown[];
|
||||||
|
};
|
||||||
|
|
||||||
|
assert.equal(dossier.asset.code, 'YAC-0005');
|
||||||
|
assert.equal(dossier.asset.name, 'Agua Botada');
|
||||||
|
assert.equal(dossier.counters.inspections, 0);
|
||||||
|
assert.equal(dossier.counters.findings, 0);
|
||||||
|
assert.deepEqual(dossier.warnings, ['communications']);
|
||||||
|
assert.deepEqual(dossier.timeline, []);
|
||||||
|
});
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
|
||||||
|
const mergedDossier = readFileSync('src/asset-master/merged-inventory-dossier.service.ts', 'utf8');
|
||||||
|
const dossierPanel = readFileSync('../web-v2/src/features/assets/AssetDossierPanel.tsx', 'utf8');
|
||||||
|
const simpleDetail = readFileSync('../web-v2/src/pages/SimpleInventoryDetailPage.tsx', 'utf8');
|
||||||
|
|
||||||
|
test('F7 mantiene Actividad disponible para Yacimiento', () => {
|
||||||
|
assert.match(simpleDetail, /kind === 'YACIMIENTO'/);
|
||||||
|
assert.match(simpleDetail, /setTab\('activity'\)/);
|
||||||
|
assert.match(simpleDetail, /AssetDossierPanel assetId=\{asset\.id\}/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F7 no hace depender el dossier territorial del subsistema de fusión', () => {
|
||||||
|
assert.match(mergedDossier, /MERGEABLE_DOSSIER_TYPES = new Set\(\['instalacion', 'subinstalacion'\]\)/);
|
||||||
|
assert.match(mergedDossier, /if \(!MERGEABLE_DOSSIER_TYPES\.has\(requestedTypeCode\)\)/);
|
||||||
|
assert.match(mergedDossier, /private readonly activity: ActivityDossierService/);
|
||||||
|
assert.match(mergedDossier, /return await this\.activity\.dossier\(requestedAssetId\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F7 la consulta auxiliar de merge nunca bloquea la carga de Actividad', () => {
|
||||||
|
assert.match(dossierPanel, /getInventoryMergeStatus\(assetId\)\.catch\(\(\) => null\)/);
|
||||||
|
assert.match(dossierPanel, /getAssetDossier\(assetId\)/);
|
||||||
|
});
|
||||||
Executable
+327
@@ -0,0 +1,327 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
APP="/var/www/dhv2.korexlabs.com"
|
||||||
|
BACKUP_ROOT="/root/DH_V2_BACKUPS"
|
||||||
|
LOCK="/var/lock/dhv2-deploy.lock"
|
||||||
|
|
||||||
|
exec 9>"$LOCK"
|
||||||
|
|
||||||
|
if ! flock -n 9; then
|
||||||
|
echo "Otro deploy de DH V2 ya está en curso. No se realiza ninguna modificación."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
DEPLOY_REF="${DHV2_DEPLOY_REF:-deploy}"
|
||||||
|
STAMP="$(date +%Y%m%d_%H%M%S)"
|
||||||
|
BACKUP="$BACKUP_ROOT/GITEA_DEPLOY_${STAMP}"
|
||||||
|
STAGE="/root/dhv2-gitea-stage-${STAMP}"
|
||||||
|
LOG="/tmp/dhv2-gitea-deploy-${STAMP}.log"
|
||||||
|
API_TEST_IMAGE="dhv2-api:gitea-${STAMP}"
|
||||||
|
WEB_TEST_IMAGE="dhv2-web:gitea-${STAMP}"
|
||||||
|
PHASE="bootstrap"
|
||||||
|
PREV_SHA=""
|
||||||
|
TARGET_SHA=""
|
||||||
|
EXPECTED_API_VERSION=""
|
||||||
|
EXPECTED_WEB_VERSION=""
|
||||||
|
APP_TOUCHED=0
|
||||||
|
|
||||||
|
cd "$APP"
|
||||||
|
exec > >(tee -a "$LOG") 2>&1
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
set +e
|
||||||
|
git worktree remove --force "$STAGE" >/dev/null 2>&1 || true
|
||||||
|
rm -rf "$STAGE"
|
||||||
|
docker image rm "$API_TEST_IMAGE" "$WEB_TEST_IMAGE" >/dev/null 2>&1 || true
|
||||||
|
}
|
||||||
|
|
||||||
|
publish_status() {
|
||||||
|
local rc="${1:-1}"
|
||||||
|
set +e
|
||||||
|
|
||||||
|
local outcome="failure"
|
||||||
|
[ "$rc" -eq 0 ] && outcome="success"
|
||||||
|
local current="unknown"
|
||||||
|
current="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
|
||||||
|
local status_file log_file status_blob log_blob tree commit
|
||||||
|
|
||||||
|
status_file="$(mktemp /tmp/dhv2-status.XXXXXX)"
|
||||||
|
log_file="$(mktemp /tmp/dhv2-log.XXXXXX)"
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "status=$outcome"
|
||||||
|
echo "exit_code=$rc"
|
||||||
|
echo "phase=$PHASE"
|
||||||
|
echo "timestamp=$(date --iso-8601=seconds)"
|
||||||
|
echo "deploy_ref=$DEPLOY_REF"
|
||||||
|
echo "previous_sha=${PREV_SHA:-unknown}"
|
||||||
|
echo "target_sha=${TARGET_SHA:-unknown}"
|
||||||
|
echo "current_sha=$current"
|
||||||
|
echo "api_version=${EXPECTED_API_VERSION:-unknown}"
|
||||||
|
echo "web_version=${EXPECTED_WEB_VERSION:-unknown}"
|
||||||
|
echo "app_touched=$APP_TOUCHED"
|
||||||
|
echo "backup=${BACKUP:-unknown}"
|
||||||
|
} > "$status_file"
|
||||||
|
|
||||||
|
tail -n 500 "$LOG" > "$log_file" 2>/dev/null || true
|
||||||
|
status_blob="$(git hash-object -w "$status_file" 2>/dev/null || true)"
|
||||||
|
log_blob="$(git hash-object -w "$log_file" 2>/dev/null || true)"
|
||||||
|
|
||||||
|
if [ -n "$status_blob" ] && [ -n "$log_blob" ]; then
|
||||||
|
tree="$(printf '100644 blob %s\tdeploy.log\n100644 blob %s\tstatus.txt\n' "$log_blob" "$status_blob" | git mktree 2>/dev/null || true)"
|
||||||
|
if [ -n "$tree" ]; then
|
||||||
|
commit="$(printf 'deploy-status: %s · phase %s\n' "$outcome" "$PHASE" | git -c user.name='DH V2 Deploy Bot' -c user.email='deploy@dhv2.local' commit-tree "$tree" 2>/dev/null || true)"
|
||||||
|
[ -z "$commit" ] || git push --force origin "$commit:refs/heads/deploy-status" >/dev/null 2>&1 || true
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
rm -f "$status_file" "$log_file"
|
||||||
|
}
|
||||||
|
|
||||||
|
on_exit() {
|
||||||
|
local rc=$?
|
||||||
|
trap - EXIT ERR
|
||||||
|
cleanup
|
||||||
|
publish_status "$rc"
|
||||||
|
exit "$rc"
|
||||||
|
}
|
||||||
|
trap on_exit EXIT
|
||||||
|
|
||||||
|
rollback() {
|
||||||
|
local rc=$?
|
||||||
|
trap - ERR
|
||||||
|
PHASE="rollback"
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "============================================================"
|
||||||
|
echo " DH V2 · DEPLOY FALLÓ · ROLLBACK"
|
||||||
|
echo "============================================================"
|
||||||
|
|
||||||
|
cd "$APP"
|
||||||
|
if [ "$APP_TOUCHED" -eq 1 ] && [ -n "${PREV_SHA:-}" ]; then
|
||||||
|
echo "Restaurando aplicación al commit previo: $PREV_SHA"
|
||||||
|
git reset --hard "$PREV_SHA" || true
|
||||||
|
docker compose build api web </dev/null || true
|
||||||
|
docker compose up -d --no-deps --force-recreate api web </dev/null || true
|
||||||
|
else
|
||||||
|
echo "El candidato falló antes de modificar producción; no se reconstruye ni reinicia la aplicación activa."
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "Estado actual:"
|
||||||
|
docker compose ps -a </dev/null || true
|
||||||
|
|
||||||
|
if [ "$APP_TOUCHED" -eq 1 ]; then
|
||||||
|
echo
|
||||||
|
echo "Últimos logs:"
|
||||||
|
docker compose logs --tail=160 api web </dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
if [ -d "$BACKUP" ]; then
|
||||||
|
echo "Backup PRE disponible en: $BACKUP"
|
||||||
|
echo "Las migraciones son forward-only; database-before.dump queda disponible para restauración manual si hiciera falta."
|
||||||
|
else
|
||||||
|
echo "No fue necesario crear backup PRE: el fallo ocurrió durante el preflight del candidato, antes de tocar producción."
|
||||||
|
fi
|
||||||
|
exit "$rc"
|
||||||
|
}
|
||||||
|
trap rollback ERR
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "============================================================"
|
||||||
|
echo " DH V2 · DEPLOY DESDE GITEA · $DEPLOY_REF"
|
||||||
|
echo "============================================================"
|
||||||
|
|
||||||
|
for cmd in git docker curl tar node; do
|
||||||
|
command -v "$cmd" >/dev/null || { echo "ERROR: falta $cmd"; false; }
|
||||||
|
done
|
||||||
|
[ -d .git ] || { echo "ERROR: $APP no es repositorio Git"; false; }
|
||||||
|
[ -f .env ] || { echo "ERROR: falta $APP/.env"; false; }
|
||||||
|
|
||||||
|
ORIGIN_URL="$(git remote get-url origin)"
|
||||||
|
EXPECTED_ORIGIN="https://git.korexlabs.com.ar/admin/dh-inspeccion-v2.git"
|
||||||
|
|
||||||
|
if [ "$ORIGIN_URL" != "$EXPECTED_ORIGIN" ]; then
|
||||||
|
echo "ERROR: origin no apunta al Gitea autorizado."
|
||||||
|
echo "Actual: $ORIGIN_URL"
|
||||||
|
echo "Esperado: $EXPECTED_ORIGIN"
|
||||||
|
false
|
||||||
|
fi
|
||||||
|
|
||||||
|
git config --global --get-all safe.directory 2>/dev/null | grep -Fxq "$APP" || git config --global --add safe.directory "$APP"
|
||||||
|
|
||||||
|
if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
|
||||||
|
echo "ERROR: hay cambios locales versionados en producción."
|
||||||
|
git status --short
|
||||||
|
false
|
||||||
|
fi
|
||||||
|
|
||||||
|
PREV_SHA="$(git rev-parse HEAD)"
|
||||||
|
PHASE="fetch"
|
||||||
|
git fetch origin "$DEPLOY_REF"
|
||||||
|
TARGET_SHA="$(git rev-parse "origin/$DEPLOY_REF")"
|
||||||
|
|
||||||
|
echo "Actual: $PREV_SHA"
|
||||||
|
echo "Objetivo: $TARGET_SHA"
|
||||||
|
|
||||||
|
if [ "$TARGET_SHA" = "$PREV_SHA" ]; then
|
||||||
|
echo "Producción ya está en el commit autorizado."
|
||||||
|
PHASE="complete"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! git merge-base --is-ancestor "$PREV_SHA" "$TARGET_SHA"; then
|
||||||
|
echo "ERROR: origin/$DEPLOY_REF no es fast-forward desde producción."
|
||||||
|
false
|
||||||
|
fi
|
||||||
|
|
||||||
|
PHASE="candidate-preflight"
|
||||||
|
rm -rf "$STAGE"
|
||||||
|
git worktree add --detach "$STAGE" "$TARGET_SHA" >/dev/null
|
||||||
|
|
||||||
|
EXPECTED_API_VERSION="$(node -p "require('$STAGE/api-v3/package.json').version")"
|
||||||
|
EXPECTED_WEB_VERSION="$(node -p "require('$STAGE/web-v2/package.json').version")"
|
||||||
|
|
||||||
|
echo "API candidata: $EXPECTED_API_VERSION"
|
||||||
|
echo "WEB candidata: $EXPECTED_WEB_VERSION"
|
||||||
|
|
||||||
|
docker compose --env-file "$APP/.env" -f "$STAGE/docker-compose.yml" config >/dev/null
|
||||||
|
|
||||||
|
while IFS= read -r -d '' script; do
|
||||||
|
bash -n "$script"
|
||||||
|
done < <(find "$STAGE/scripts" -type f -name '*.sh' -print0)
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "========== TEST API CANDIDATA =========="
|
||||||
|
docker build --target builder -t "$API_TEST_IMAGE" "$STAGE/api-v3" </dev/null
|
||||||
|
docker run --rm \
|
||||||
|
-v "$STAGE/api-v3/test:/app/test:ro" \
|
||||||
|
-v "$STAGE/api-v3/tsconfig.test.json:/app/tsconfig.test.json:ro" \
|
||||||
|
-v "$STAGE/docker-compose.yml:/docker-compose.yml:ro" \
|
||||||
|
-v "$STAGE/web-v2:/web-v2:ro" \
|
||||||
|
-v "$STAGE/android-app:/android-app:ro" \
|
||||||
|
"$API_TEST_IMAGE" npm test </dev/null
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "========== BUILD WEB CANDIDATA =========="
|
||||||
|
docker build -t "$WEB_TEST_IMAGE" "$STAGE/web-v2" </dev/null
|
||||||
|
|
||||||
|
PHASE="backup"
|
||||||
|
echo
|
||||||
|
echo "========== BACKUP PRE =========="
|
||||||
|
install -d -m 700 "$BACKUP"
|
||||||
|
docker compose exec -T db sh -lc 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' </dev/null > "$BACKUP/database-before.dump"
|
||||||
|
tar \
|
||||||
|
--exclude='./.git' \
|
||||||
|
--exclude='./.env' \
|
||||||
|
--exclude='*/node_modules' \
|
||||||
|
--exclude='*/dist' \
|
||||||
|
--exclude='*.zip' \
|
||||||
|
--exclude='*.tar.gz' \
|
||||||
|
--exclude='*.tgz' \
|
||||||
|
-czf "$BACKUP/source-before.tar.gz" .
|
||||||
|
install -m 600 .env "$BACKUP/.env"
|
||||||
|
git rev-parse HEAD > "$BACKUP/previous.sha"
|
||||||
|
printf '%s\n' "$TARGET_SHA" > "$BACKUP/target.sha"
|
||||||
|
docker compose ps -a > "$BACKUP/docker-before.txt"
|
||||||
|
(
|
||||||
|
cd "$BACKUP"
|
||||||
|
sha256sum database-before.dump source-before.tar.gz .env previous.sha target.sha docker-before.txt > SHA256SUMS.txt
|
||||||
|
sha256sum -c SHA256SUMS.txt
|
||||||
|
)
|
||||||
|
chmod 600 "$BACKUP"/* "$BACKUP/.env" 2>/dev/null || true
|
||||||
|
|
||||||
|
PHASE="fast-forward"
|
||||||
|
echo
|
||||||
|
echo "========== FAST-FORWARD =========="
|
||||||
|
git log --oneline --no-decorate "$PREV_SHA..$TARGET_SHA"
|
||||||
|
APP_TOUCHED=1
|
||||||
|
git merge --ff-only "origin/$DEPLOY_REF"
|
||||||
|
|
||||||
|
PHASE="build"
|
||||||
|
echo
|
||||||
|
echo "========== BUILD PRODUCCIÓN =========="
|
||||||
|
docker compose build api migrate web </dev/null
|
||||||
|
|
||||||
|
PHASE="migrations"
|
||||||
|
echo
|
||||||
|
echo "========== MIGRACIONES =========="
|
||||||
|
docker compose --profile tools run --rm migrate </dev/null
|
||||||
|
docker compose --profile tools run --rm migrate npm run migration:show </dev/null | tee "$BACKUP/migrations.txt"
|
||||||
|
grep -Fq 'Pending migrations: no' "$BACKUP/migrations.txt"
|
||||||
|
|
||||||
|
PHASE="recreate"
|
||||||
|
echo
|
||||||
|
echo "========== RECREATE API + WEB =========="
|
||||||
|
docker compose up -d --no-deps --force-recreate api web </dev/null
|
||||||
|
|
||||||
|
PHASE="health"
|
||||||
|
echo
|
||||||
|
echo "========== HEALTH =========="
|
||||||
|
HEALTH_OK=0
|
||||||
|
for _ in $(seq 1 60); do
|
||||||
|
if curl -fsS --max-time 5 http://127.0.0.1:3101/api/v3/health > "$BACKUP/health.json" 2>/dev/null; then
|
||||||
|
if grep -Fq '"status":"ok"' "$BACKUP/health.json" \
|
||||||
|
&& grep -Fq "\"version\":\"$EXPECTED_API_VERSION\"" "$BACKUP/health.json" \
|
||||||
|
&& grep -Fq '"database":"ok"' "$BACKUP/health.json"; then
|
||||||
|
HEALTH_OK=1
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
|
||||||
|
CURRENT_API_VERSION="$(node -e 'try { const h = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); process.stdout.write(String(h.version || "unknown")); } catch { process.stdout.write("invalid"); }' "$BACKUP/health.json")"
|
||||||
|
echo "API respondió pero aún no es la candidata (actual=$CURRENT_API_VERSION, esperada=$EXPECTED_API_VERSION). Reintentando..."
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "$HEALTH_OK" -ne 1 ]; then
|
||||||
|
echo "ERROR: API candidata no pasó healthcheck/version/database dentro del plazo."
|
||||||
|
[ ! -f "$BACKUP/health.json" ] || cat "$BACKUP/health.json"
|
||||||
|
docker compose logs --tail=180 api
|
||||||
|
false
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat "$BACKUP/health.json"
|
||||||
|
echo
|
||||||
|
|
||||||
|
grep -Fq "\"version\":\"$EXPECTED_API_VERSION\"" "$BACKUP/health.json"
|
||||||
|
grep -Fq '"database":"ok"' "$BACKUP/health.json"
|
||||||
|
|
||||||
|
WEB_CODE="$(curl -sS -o /dev/null -w '%{http_code}' --max-time 10 http://127.0.0.1:8182/)"
|
||||||
|
[ "$WEB_CODE" = "200" ] || { echo "ERROR: WEB HTTP $WEB_CODE"; false; }
|
||||||
|
|
||||||
|
PHASE="verify"
|
||||||
|
echo
|
||||||
|
echo "========== VERIFICACIÓN FINAL =========="
|
||||||
|
docker compose ps -a | tee "$BACKUP/docker-after.txt"
|
||||||
|
if docker compose ps --status running --services | grep -Fxq api && docker compose ps --status running --services | grep -Fxq web && docker compose ps --status running --services | grep -Fxq db; then
|
||||||
|
echo "Servicios críticos: OK"
|
||||||
|
else
|
||||||
|
echo "ERROR: falta un servicio crítico en ejecución."
|
||||||
|
false
|
||||||
|
fi
|
||||||
|
|
||||||
|
PHASE="post-backup"
|
||||||
|
docker compose exec -T db sh -lc 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' </dev/null > "$BACKUP/database-after.dump"
|
||||||
|
git rev-parse HEAD > "$BACKUP/deployed.sha"
|
||||||
|
printf 'API=%s\nWEB=%s\n' "$EXPECTED_API_VERSION" "$EXPECTED_WEB_VERSION" > "$BACKUP/deployed-versions.txt"
|
||||||
|
(
|
||||||
|
cd "$BACKUP"
|
||||||
|
sha256sum database-after.dump deployed.sha deployed-versions.txt health.json migrations.txt docker-after.txt >> SHA256SUMS.txt
|
||||||
|
sha256sum -c SHA256SUMS.txt
|
||||||
|
)
|
||||||
|
chmod 600 "$BACKUP"/* "$BACKUP/.env" 2>/dev/null || true
|
||||||
|
|
||||||
|
PHASE="complete"
|
||||||
|
trap - ERR
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "============================================================"
|
||||||
|
echo " DH V2 · DEPLOY OK"
|
||||||
|
echo "============================================================"
|
||||||
|
echo "Commit: $TARGET_SHA"
|
||||||
|
echo "API: $EXPECTED_API_VERSION"
|
||||||
|
echo "WEB: $EXPECTED_WEB_VERSION"
|
||||||
|
echo "Backup: $BACKUP"
|
||||||
|
echo "============================================================"
|
||||||
@@ -81,10 +81,12 @@ export function AssetDossierPanel({ assetId }: { assetId: string }) {
|
|||||||
const load = () => {
|
const load = () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError('');
|
setError('');
|
||||||
|
setMergeStatus(null);
|
||||||
Promise.all([
|
Promise.all([
|
||||||
getAssetDossier(assetId),
|
getAssetDossier(assetId),
|
||||||
getAsset(assetId),
|
getAsset(assetId),
|
||||||
getInventoryMergeStatus(assetId),
|
// La conciliación es auxiliar: nunca debe bloquear la Actividad del Inventario.
|
||||||
|
getInventoryMergeStatus(assetId).catch(() => null),
|
||||||
])
|
])
|
||||||
.then(([loadedDossier, loadedAsset, loadedMerge]) => {
|
.then(([loadedDossier, loadedAsset, loadedMerge]) => {
|
||||||
setDossier(loadedDossier as ExtendedDossier);
|
setDossier(loadedDossier as ExtendedDossier);
|
||||||
|
|||||||
@@ -245,8 +245,8 @@ export function AuthoritativeInventoryConfigPage() {
|
|||||||
{canManage && <div style={{ marginTop: 18, borderTop: '1px solid var(--border)', paddingTop: 18 }}>
|
{canManage && <div style={{ marginTop: 18, borderTop: '1px solid var(--border)', paddingTop: 18 }}>
|
||||||
<h3 style={{ marginTop: 0 }}>+ Nuevo tipo</h3>
|
<h3 style={{ marginTop: 0 }}>+ Nuevo tipo</h3>
|
||||||
<label className="field"><span>Nombre</span><input value={newTypeName} onChange={(event) => setNewTypeName(event.target.value)} placeholder={level === 'INSTALLATION' ? 'Ej. Planta de tratamiento' : 'Ej. Bomba centrífuga'} /></label>
|
<label className="field"><span>Nombre</span><input value={newTypeName} onChange={(event) => setNewTypeName(event.target.value)} placeholder={level === 'INSTALLATION' ? 'Ej. Planta de tratamiento' : 'Ej. Bomba centrífuga'} /></label>
|
||||||
{level === 'SUBINSTALLATION' && <div className="field"><span>Puede estar dentro de</span><div style={{ display: 'grid', gap: 8, marginTop: 8 }}>
|
{level === 'SUBINSTALLATION' && <div className="field"><span>Puede estar dentro de</span><div className="inventory-parent-options">
|
||||||
{installationFamilies.filter((family) => family.isActive !== false).map((family) => <label key={family.id} style={{ display: 'flex', alignItems: 'center', gap: 8 }}><input type="checkbox" checked={newTypeParents.includes(family.id)} onChange={() => toggleParent(family.id)} />{family.name}</label>)}
|
{installationFamilies.filter((family) => family.isActive !== false).map((family) => <label key={family.id} className="inventory-parent-option"><input type="checkbox" checked={newTypeParents.includes(family.id)} onChange={() => toggleParent(family.id)} /><span>{family.name}</span></label>)}
|
||||||
</div></div>}
|
</div></div>}
|
||||||
<button type="button" className="button primary" disabled={saving || !newTypeName.trim()} onClick={() => void createType()}><Icon name="plus" />Crear tipo</button>
|
<button type="button" className="button primary" disabled={saving || !newTypeName.trim()} onClick={() => void createType()}><Icon name="plus" />Crear tipo</button>
|
||||||
</div>}
|
</div>}
|
||||||
@@ -265,10 +265,10 @@ export function AuthoritativeInventoryConfigPage() {
|
|||||||
|
|
||||||
{selectedFamily.level === 'SUBINSTALLATION' && <div style={{ marginBottom: 22 }}>
|
{selectedFamily.level === 'SUBINSTALLATION' && <div style={{ marginBottom: 22 }}>
|
||||||
<strong>Puede estar dentro de:</strong>
|
<strong>Puede estar dentro de:</strong>
|
||||||
<div style={{ display: 'grid', gap: 8, marginTop: 10 }}>
|
<div className="inventory-parent-options">
|
||||||
{installationFamilies.filter((family) => family.isActive !== false).map((family) => <label key={family.id} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
{installationFamilies.filter((family) => family.isActive !== false).map((family) => <label key={family.id} className="inventory-parent-option">
|
||||||
<input type="checkbox" disabled={!canManage || saving} checked={selectedFamily.parentFamilyIds.includes(family.id)} onChange={() => void toggleSelectedParent(family.id)} />
|
<input type="checkbox" disabled={!canManage || saving} checked={selectedFamily.parentFamilyIds.includes(family.id)} onChange={() => void toggleSelectedParent(family.id)} />
|
||||||
{family.name}
|
<span>{family.name}</span>
|
||||||
</label>)}
|
</label>)}
|
||||||
</div>
|
</div>
|
||||||
</div>}
|
</div>}
|
||||||
|
|||||||
@@ -1296,3 +1296,55 @@ code { color: #5e6677; font-family: ui-monospace, monospace; font-size: 9px; }
|
|||||||
/* D5.6.4 · combobox buscable global */
|
/* D5.6.4 · combobox buscable global */
|
||||||
.searchable-select{position:relative;width:100%;min-width:0}.searchable-select-native{position:absolute!important;inset:0;width:1px!important;height:1px!important;opacity:0;pointer-events:none}.searchable-select-trigger{display:flex;width:100%;min-height:41px;align-items:center;justify-content:space-between;gap:10px;padding:9px 11px;border:1px solid #d7dce5;border-radius:8px;background:#fff;color:var(--ink);font-size:13px;text-align:left;cursor:pointer;outline:none}.searchable-select-trigger:hover{border-color:#bcc6d6}.searchable-select-trigger:focus-visible{border-color:#6b95ed;box-shadow:0 0 0 3px rgba(40,100,220,.1)}.searchable-select-trigger:disabled{cursor:not-allowed;color:#9199a8;background:#f1f3f6}.searchable-select-trigger>span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.searchable-select-trigger .placeholder{color:#7e8796}.searchable-select-trigger .icon{flex:0 0 auto;transform:rotate(90deg)}.searchable-select-popup{position:fixed;z-index:10000;max-height:315px;padding:6px;border:1px solid #ccd4e0;border-radius:10px;background:#fff;box-shadow:0 14px 40px rgba(18,31,53,.18)}.searchable-select-search{display:flex;align-items:center;gap:7px;padding:5px 7px 7px;border-bottom:1px solid var(--line)}.searchable-select-search input{width:100%;min-width:0;height:34px;padding:6px 8px;border:0;outline:0;background:transparent;color:var(--ink);font-size:12px}.searchable-select-options{max-height:245px;overflow:auto;padding-top:4px}.searchable-select-options>button{display:flex;width:100%;align-items:center;justify-content:space-between;gap:8px;padding:8px 9px;border:0;border-radius:7px;background:transparent;color:var(--ink);font-size:12px;text-align:left;cursor:pointer}.searchable-select-options>button:hover,.searchable-select-options>button:focus-visible{background:#f2f5fa;outline:none}.searchable-select-options>button.selected{background:#eef4ff;color:#174ea6;font-weight:750}.searchable-select-options>button:disabled{cursor:not-allowed;color:#a0a7b3;background:transparent}.searchable-select-empty{padding:14px 10px;color:var(--muted);font-size:11px;text-align:center}.select-field>.searchable-select{width:100%}.survey-inline-select.searchable-select{min-width:130px;margin-top:6px;padding:0;border:0;background:transparent}.survey-inline-select.wide.searchable-select{min-width:175px;margin-top:0}.survey-inline-select .searchable-select-trigger{min-height:33px;padding:6px 8px;border-radius:7px;font-size:9px}.operational-context-selectors .searchable-select-trigger{min-height:36px;padding:7px 9px;font-size:10px}.parent-picker .searchable-select-trigger{border-radius:5px 5px 8px 8px}
|
.searchable-select{position:relative;width:100%;min-width:0}.searchable-select-native{position:absolute!important;inset:0;width:1px!important;height:1px!important;opacity:0;pointer-events:none}.searchable-select-trigger{display:flex;width:100%;min-height:41px;align-items:center;justify-content:space-between;gap:10px;padding:9px 11px;border:1px solid #d7dce5;border-radius:8px;background:#fff;color:var(--ink);font-size:13px;text-align:left;cursor:pointer;outline:none}.searchable-select-trigger:hover{border-color:#bcc6d6}.searchable-select-trigger:focus-visible{border-color:#6b95ed;box-shadow:0 0 0 3px rgba(40,100,220,.1)}.searchable-select-trigger:disabled{cursor:not-allowed;color:#9199a8;background:#f1f3f6}.searchable-select-trigger>span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.searchable-select-trigger .placeholder{color:#7e8796}.searchable-select-trigger .icon{flex:0 0 auto;transform:rotate(90deg)}.searchable-select-popup{position:fixed;z-index:10000;max-height:315px;padding:6px;border:1px solid #ccd4e0;border-radius:10px;background:#fff;box-shadow:0 14px 40px rgba(18,31,53,.18)}.searchable-select-search{display:flex;align-items:center;gap:7px;padding:5px 7px 7px;border-bottom:1px solid var(--line)}.searchable-select-search input{width:100%;min-width:0;height:34px;padding:6px 8px;border:0;outline:0;background:transparent;color:var(--ink);font-size:12px}.searchable-select-options{max-height:245px;overflow:auto;padding-top:4px}.searchable-select-options>button{display:flex;width:100%;align-items:center;justify-content:space-between;gap:8px;padding:8px 9px;border:0;border-radius:7px;background:transparent;color:var(--ink);font-size:12px;text-align:left;cursor:pointer}.searchable-select-options>button:hover,.searchable-select-options>button:focus-visible{background:#f2f5fa;outline:none}.searchable-select-options>button.selected{background:#eef4ff;color:#174ea6;font-weight:750}.searchable-select-options>button:disabled{cursor:not-allowed;color:#a0a7b3;background:transparent}.searchable-select-empty{padding:14px 10px;color:var(--muted);font-size:11px;text-align:center}.select-field>.searchable-select{width:100%}.survey-inline-select.searchable-select{min-width:130px;margin-top:6px;padding:0;border:0;background:transparent}.survey-inline-select.wide.searchable-select{min-width:175px;margin-top:0}.survey-inline-select .searchable-select-trigger{min-height:33px;padding:6px 8px;border-radius:7px;font-size:9px}.operational-context-selectors .searchable-select-trigger{min-height:36px;padding:7px 9px;font-size:10px}.parent-picker .searchable-select-trigger{border-radius:5px 5px 8px 8px}
|
||||||
.inspection-quick-create{max-width:980px;margin-left:auto;margin-right:auto}.inspection-quick-create .form-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.inspection-generated-code{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px;padding:10px 12px;border:1px solid var(--line);border-radius:9px;background:var(--soft)}.inspection-generated-code small{color:var(--muted);font-weight:700}.inspection-generated-code strong{font-size:15px;letter-spacing:.02em}@media(max-width:760px){.inspection-quick-create .form-grid{grid-template-columns:1fr}}
|
.inspection-quick-create{max-width:980px;margin-left:auto;margin-right:auto}.inspection-quick-create .form-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.inspection-generated-code{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px;padding:10px 12px;border:1px solid var(--line);border-radius:9px;background:var(--soft)}.inspection-generated-code small{color:var(--muted);font-weight:700}.inspection-generated-code strong{font-size:15px;letter-spacing:.02em}@media(max-width:760px){.inspection-quick-create .form-grid{grid-template-columns:1fr}}
|
||||||
|
|
||||||
|
/* Parent choices need fixed-size controls even inside a generic form field. */
|
||||||
|
.inventory-parent-options {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 210px), 1fr));
|
||||||
|
gap: 8px;
|
||||||
|
margin: 10px 0 14px;
|
||||||
|
}
|
||||||
|
.inventory-parent-option {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-start;
|
||||||
|
gap: 10px;
|
||||||
|
min-width: 0;
|
||||||
|
min-height: 42px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #fff;
|
||||||
|
color: var(--ink);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.4;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.inventory-parent-option input[type="checkbox"] {
|
||||||
|
flex: 0 0 17px;
|
||||||
|
width: 17px;
|
||||||
|
height: 17px;
|
||||||
|
min-height: 17px;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
accent-color: var(--blue);
|
||||||
|
cursor: inherit;
|
||||||
|
}
|
||||||
|
.inventory-parent-option > span {
|
||||||
|
display: block;
|
||||||
|
min-width: 0;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.inventory-parent-option:has(input:checked) {
|
||||||
|
border-color: #9db9ed;
|
||||||
|
background: #eef4ff;
|
||||||
|
}
|
||||||
|
.inventory-parent-option:has(input:focus-visible) {
|
||||||
|
outline: 2px solid var(--blue);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
.inventory-parent-option:has(input:disabled) {
|
||||||
|
cursor: default;
|
||||||
|
opacity: .65;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user