ff-admin-server/src/command/unit/inspection/inspectionPointCommandHandler.ts

74 lines
2.6 KiB
TypeScript

import { dataSource } from "../../../data-source";
import { inspectionPoint } from "../../../entity/unit/inspection/inspectionPoint";
import DatabaseActionException from "../../../exceptions/databaseActionException";
import InspectionPointService from "../../../service/unit/inspection/inspectionPointService";
import { CreateInspectionPointCommand } from "./inspectionPointCommand";
export default abstract class InspectionPointCommandHandler {
/**
* @description create inspectionPoint
* @param {CreateInspectionPointCommand} createInspectionPoint
* @returns {Promise<number>}
*/
static async create(createInspectionPoint: CreateInspectionPointCommand): Promise<number> {
return await dataSource
.createQueryBuilder()
.insert()
.into(inspectionPoint)
.values({
title: createInspectionPoint.title,
description: createInspectionPoint.description,
type: createInspectionPoint.type,
min: createInspectionPoint.min,
max: createInspectionPoint.max,
sort: createInspectionPoint.sort,
versionedPlanId: createInspectionPoint.versionedPointId,
})
.execute()
.then((result) => {
return result.identifiers[0].id;
})
.catch((err) => {
throw new DatabaseActionException("CREATE", "inspectionPoint", err);
});
}
/**
* @description sync points
* @param {string} versionedPlanId
* @param {Array<CreateInspectionPointCommand>} sync
* @returns {Promise<void>}
*/
static async sync(versionedPlanId: string, sync: Array<CreateInspectionPointCommand>): Promise<void> {
let points = await InspectionPointService.getAllForVersionedPlan(versionedPlanId);
await dataSource
.transaction(async (manager) => {
let remove = points.filter((r) => !sync.some((cp) => cp.id == r.id));
await manager
.createQueryBuilder()
.insert()
.into(inspectionPoint)
.values(
sync.map((s) => ({
...s,
id: points.some((p) => p.id == s.id) ? s.id : undefined,
versionedPlanId,
}))
)
.orUpdate(["title", "description", "min", "max", "others", "sort"], ["id"])
.execute();
if (remove.length != 0)
await manager
.createQueryBuilder()
.delete()
.from(inspectionPoint)
.where("id IN (:...ids)", { ids: remove.map((r) => r.id) })
.andWhere({ versionedPlanId })
.execute();
})
.catch((err) => {
throw new DatabaseActionException("SYNC", "inspectionPoint", err);
});
}
}