100 lines
2.8 KiB
TypeScript
100 lines
2.8 KiB
TypeScript
import { 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 = 'DRAFT'
|
|
ORDER BY created_at DESC
|
|
LIMIT 1
|
|
FOR UPDATE
|
|
`,
|
|
[visitId],
|
|
)) as Array<{ id: string; status: string }>;
|
|
|
|
const [existing] = (await manager.query(
|
|
`
|
|
SELECT included, planning_source AS "planningSource"
|
|
FROM inspection_visit_assets
|
|
WHERE visit_id = $1 AND asset_id = $2
|
|
FOR UPDATE
|
|
`,
|
|
[visitId, assetId],
|
|
)) as Array<{ included: boolean; planningSource: string }>;
|
|
|
|
await manager.query(
|
|
`
|
|
INSERT INTO inspection_visit_assets (
|
|
visit_id, asset_id, included, planning_source, added_by,
|
|
exclusion_reason, excluded_by, excluded_at
|
|
)
|
|
VALUES ($1, $2, true, 'FIELD', $3, NULL, NULL, NULL)
|
|
ON CONFLICT (visit_id, asset_id) DO UPDATE SET
|
|
included = true,
|
|
planning_source = CASE
|
|
WHEN inspection_visit_assets.planning_source IN ('AUTOMATIC','VERIFICATION')
|
|
THEN inspection_visit_assets.planning_source
|
|
ELSE 'FIELD'
|
|
END,
|
|
added_by = EXCLUDED.added_by,
|
|
exclusion_reason = NULL,
|
|
excluded_by = NULL,
|
|
excluded_at = NULL,
|
|
updated_at = CURRENT_TIMESTAMP
|
|
`,
|
|
[visitId, assetId, userId],
|
|
);
|
|
|
|
const eventType = existing && existing.included ? null : 'FIELD_INCLUDED';
|
|
if (eventType) {
|
|
await manager.query(
|
|
`
|
|
INSERT INTO inspection_visit_asset_events (
|
|
visit_id, asset_id, event_type, actor_user_id, metadata
|
|
)
|
|
VALUES ($1, $2, 'FIELD_INCLUDED', $3, $4::jsonb)
|
|
`,
|
|
[
|
|
visitId,
|
|
assetId,
|
|
userId,
|
|
JSON.stringify({
|
|
fieldSelection: true,
|
|
previousPlanningSource: existing?.planningSource ?? null,
|
|
}),
|
|
],
|
|
);
|
|
}
|
|
|
|
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 };
|
|
}
|
|
}
|