import { AppDataSource } from "../database/data-source"; import { CommandRecive } from "../entities/CommandRecive"; import { Command } from "../entities/Command"; /** * เรียงลำดับผู้ได้รับคำสั่งใหม่หลังจากลบรายการ และอัพเดทสถานะคำสั่งถ้าไม่มีผู้ได้รับคำสั่งเหลือ * @param refId refId ของผู้ได้รับคำสั่ง * @param code ประเภทคำสั่ง * @returns Promise */ export async function reOrderCommandRecivesAndDelete( refId: string ): Promise { const commandReciveRepo = AppDataSource.getRepository(CommandRecive); const commandRepo = AppDataSource.getRepository(Command); // ค้นหาข้อมูลผู้ได้รับคำสั่งตาม refId const commandRecive = await commandReciveRepo.findOne({ where: { refId: refId }, relations: { command: true}, }); if (commandRecive == null) return; const commandId = commandRecive.commandId; // ลบตาม refId await commandReciveRepo.delete(commandRecive.id); const commandReciveList = await commandReciveRepo.find({ where: { commandId: commandId }, order: { order: "ASC" }, }); // ลำดับผู้ได้รับคำสั่งใหม่ if (commandReciveList.length > 0) { await Promise.all( commandReciveList.map(async (p, i) => { p.order = i + 1; await commandReciveRepo.save(p); }) ); } else { // ถ้าไม่มีผู้ได้รับคำสั่งเหลือเลย ให้ยกเลิกคำสั่ง await commandRepo.update({ id: commandId }, { status: "CANCEL" }); } }