65 lines
1.7 KiB
TypeScript
65 lines
1.7 KiB
TypeScript
import { ConflictException, Injectable } from '@nestjs/common';
|
|
import type { EntityManager } from 'typeorm';
|
|
|
|
export interface FieldDiscoveryInspectionLinkResult {
|
|
actId: string | null;
|
|
}
|
|
|
|
@Injectable()
|
|
export class FieldDiscoveryInspectionLinkService {
|
|
async attach(
|
|
manager: EntityManager,
|
|
visitId: string,
|
|
assetId: string,
|
|
userId: string,
|
|
): Promise<FieldDiscoveryInspectionLinkResult> {
|
|
const [act] = (await manager.query(
|
|
`
|
|
SELECT id, status
|
|
FROM inspection_acts
|
|
WHERE visit_id = $1
|
|
AND status <> 'CANCELLED'
|
|
ORDER BY created_at DESC
|
|
LIMIT 1
|
|
FOR UPDATE
|
|
`,
|
|
[visitId],
|
|
)) as Array<{ id: string; status: string }>;
|
|
|
|
if (act && act.status !== 'DRAFT') {
|
|
throw new ConflictException({
|
|
code: 'FIELD_DISCOVERY_ACT_NOT_EDITABLE',
|
|
message: 'El Acta ya no admite nuevos elementos ni Hallazgos',
|
|
});
|
|
}
|
|
|
|
await manager.query(
|
|
`
|
|
INSERT INTO inspection_visit_assets (visit_id, asset_id, included, added_by)
|
|
VALUES ($1, $2, true, $3)
|
|
ON CONFLICT (visit_id, asset_id) DO UPDATE SET
|
|
included = true,
|
|
added_by = EXCLUDED.added_by,
|
|
updated_at = CURRENT_TIMESTAMP
|
|
`,
|
|
[visitId, assetId, userId],
|
|
);
|
|
|
|
if (act) {
|
|
await manager.query(
|
|
`
|
|
INSERT INTO inspection_act_assets (act_id, asset_id, included, added_by)
|
|
VALUES ($1, $2, true, $3)
|
|
ON CONFLICT (act_id, asset_id) DO UPDATE SET
|
|
included = true,
|
|
added_by = EXCLUDED.added_by,
|
|
updated_at = CURRENT_TIMESTAMP
|
|
`,
|
|
[act.id, assetId, userId],
|
|
);
|
|
}
|
|
|
|
return { actId: act?.id ?? null };
|
|
}
|
|
}
|