From 56a53c95bd18b0c416ca1ad773cfb73da835da9f Mon Sep 17 00:00:00 2001 From: Kritkhanin Anantakul <65160144@go.buu.ac.th> Date: Tue, 25 Mar 2025 14:06:23 +0700 Subject: [PATCH] fix queue service --- src/app.module.ts | 2 +- src/queues/queues.module.ts | 2 + src/queues/queues.service.ts | 116 +++++++++++++++++++++++++---------- 3 files changed, 88 insertions(+), 32 deletions(-) diff --git a/src/app.module.ts b/src/app.module.ts index eeb0491d..2cf65574 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -85,7 +85,7 @@ import { QueueType } from './queue-types/entities/queue-type.entity'; ProductionTarget, QueueType, ], - synchronize: true, + synchronize: false, }), ServeStaticModule.forRoot({ rootPath: join(__dirname, '..', 'public'), diff --git a/src/queues/queues.module.ts b/src/queues/queues.module.ts index 838291f1..b2ab21be 100644 --- a/src/queues/queues.module.ts +++ b/src/queues/queues.module.ts @@ -10,6 +10,7 @@ import { Employee } from '@/employees/entities/employee.entity'; import { QueueType } from '@/queue-types/entities/queue-type.entity'; import { Product } from '@/products/entities/product.entity'; import { Material } from '@/materials/entities/material.entity'; +import { ProductionTarget } from '@/production_targets/entities/production_target.entity'; @Module({ imports: [ @@ -22,6 +23,7 @@ import { Material } from '@/materials/entities/material.entity'; QueueType, Product, Material, + ProductionTarget ]), // ✅ เพิ่ม Entity ที่เกี่ยวข้อง ], controllers: [QueuesController], diff --git a/src/queues/queues.service.ts b/src/queues/queues.service.ts index d28c0cd7..8d9b2fe8 100644 --- a/src/queues/queues.service.ts +++ b/src/queues/queues.service.ts @@ -16,6 +16,7 @@ import { Employee } from '@/employees/entities/employee.entity'; import { QueueType } from '@/queue-types/entities/queue-type.entity'; import { Product } from '@/products/entities/product.entity'; import { Material } from '@/materials/entities/material.entity'; +import { ProductionTarget } from '@/production_targets/entities/production_target.entity'; @Injectable() export class QueuesService { @@ -49,6 +50,9 @@ export class QueuesService { @InjectRepository(Material) private readonly materialRepository: Repository<Material>, + + @InjectRepository(ProductionTarget) + private readonly productionTargetRepository: Repository<ProductionTarget>, ) {} async getLatestQueuesFromDate(dateStr?: string): Promise<Queue[]> { @@ -225,11 +229,11 @@ export class QueuesService { async createMultiple(createQueueDtos: CreateQueueDto[]) { const newQueues = []; - + if (!Array.isArray(createQueueDtos)) { throw new BadRequestException('Request body must be an array of queues'); } - + for (const createQueueDto of createQueueDtos) { const { MachineID, @@ -238,39 +242,37 @@ export class QueuesService { EmployeeIds, itemID, itemType, + startTime, + finishTime, ...queueData } = createQueueDto; - - // ✅ แปลงค่าเบื้องต้น + const machineId = Number(MachineID); const orderId = Number(OrderID); const pageId = Number(PageID); - + if (isNaN(machineId)) throw new BadRequestException(`Invalid MachineID: ${MachineID}`); if (isNaN(orderId)) throw new BadRequestException(`Invalid OrderID: ${OrderID}`); if (isNaN(pageId)) throw new BadRequestException(`Invalid PageID: ${PageID}`); - - // ✅ หา Machine + const machine = await this.machineRepository.findOne({ where: { MachineID: machineId }, }); if (!machine) throw new NotFoundException(`Machine with ID ${machineId} not found`); - - // ✅ หา Page + const page = await this.pageRepository.findOne({ where: { PageID: pageId }, }); if (!page) throw new NotFoundException(`Page with ID ${pageId} not found`); - - // ✅ เช็คประเภทคิว และหา Order (ถ้ามี) + let order = null; let queueTypeName = 'ORDER'; - + if (orderId === -1) { queueTypeName = 'ผลิตเผื่อ'; } else { @@ -280,45 +282,41 @@ export class QueuesService { if (!order) throw new NotFoundException(`Order with ID ${orderId} not found`); } - - // ✅ หา QueueType ตามประเภท + const queueType = await this.queueTypeRepository.findOne({ where: { TypeName: queueTypeName }, }); if (!queueType) throw new NotFoundException(`QueueType '${queueTypeName}' not found`); - - // ✅ ตรวจสอบ EmployeeIds (optional) + let validEmployeeIds: number[] = []; let employees = []; - + if (Array.isArray(EmployeeIds) && EmployeeIds.length > 0) { validEmployeeIds = EmployeeIds.map((id) => Number(id)).filter( (id) => !isNaN(id) && id > 0, ); - + if (validEmployeeIds.length !== EmployeeIds.length) { throw new BadRequestException( `Invalid EmployeeIds provided: ${EmployeeIds}`, ); } - + employees = await this.employeeRepository.findByIds(validEmployeeIds); - + const foundIds = employees.map((e) => e.EmployeeID); const missingIds = validEmployeeIds.filter( (id) => !foundIds.includes(id), ); - + if (missingIds.length > 0) { - console.error(`❌ Missing EmployeeIDs: ${missingIds.join(', ')}`); throw new NotFoundException( `Employees not found: ${missingIds.join(', ')}`, ); } } - - // ✅ ตรวจสอบ item ตาม itemType + if (itemType === 'PRODUCT') { const product = await this.productRepository.findOne({ where: { ProductID: itemID }, @@ -336,30 +334,86 @@ export class QueuesService { } else { throw new BadRequestException(`Invalid itemType: ${itemType}`); } - - // ✅ สร้าง Queue object พร้อม itemID และ itemType + const newQueue = this.queueRepository.create({ ...queueData, machine, page, order: queueTypeName === 'ORDER' ? order : null, employees, - QueueType: queueType, // ชื่อต้องตรงกับ property ใน entity + QueueType: queueType, itemID, itemType, + startTime: startTime ? new Date(startTime) : undefined, + finishTime: finishTime ? new Date(finishTime) : undefined, }); - + newQueues.push(newQueue); } - - // ✅ บันทึกทั้งหมดพร้อมกัน + const savedQueues = await this.queueRepository.save(newQueues); + + const groupedTargetsMap = new Map<string, ProductionTarget>(); + + for (const queue of savedQueues) { + const key = `${queue.order?.OrderID || 'none'}|${queue.itemID}|${queue.itemType}`; + + const existing = groupedTargetsMap.get(key); + + const producedQty = queue.producedQuantity || 0; + + if (existing) { + // รวม TargetProduced + existing.TargetProduced += producedQty; + + // ขยายช่วงเวลา start/end (หาค่าน้อยสุด/มากสุด) + if (queue.startTime && (!existing.startTime || queue.startTime < existing.startTime)) { + existing.startTime = queue.startTime; + existing.Date = queue.startTime; // อัปเดตด้วย + } + + if (queue.finishTime && (!existing.endTime || queue.finishTime > existing.endTime)) { + existing.endTime = queue.finishTime; + } + + // อัปเดตเวลาใหม่ + if (existing.startTime && existing.endTime) { + existing.totalProductionHours = + (existing.endTime.getTime() - existing.startTime.getTime()) / 3600000; + } + } else { + const target = this.productionTargetRepository.create({ + itemID: queue.itemID, + itemType: queue.itemType, + order: queue.order ?? null, + page: queue.page, + TargetProduced: producedQty, + ActualProduced: 0, + startTime: queue.startTime, + endTime: queue.finishTime, + totalProductionHours: + queue.startTime && queue.finishTime + ? (queue.finishTime.getTime() - queue.startTime.getTime()) / 3600000 + : null, + Status: 'กำลังรอ', + Date: queue.startTime, + }); + + groupedTargetsMap.set(key, target); + } + } + + const newTargets = Array.from(groupedTargetsMap.values()); + await this.productionTargetRepository.save(newTargets); + return { - message: `${savedQueues.length} queues created successfully`, + message: `${savedQueues.length} queues and production targets created successfully`, queues: savedQueues, + Target: newTargets, }; } + // ✅ Fetch all Queues with relationships async findAll() { -- GitLab