From b704beec0aa464db5f5ee10aed3c2058ffa057aa Mon Sep 17 00:00:00 2001
From: Arth <65160206@go.buu.ac.th>
Date: Mon, 24 Mar 2025 22:50:11 +0700
Subject: [PATCH] add itemID and itemType in queue

---
 src/queues/dto/create-queue.dto.ts  |  10 +++
 src/queues/entities/queue.entity.ts |   6 ++
 src/queues/queues.module.ts         |   4 +
 src/queues/queues.service.ts        | 113 ++++++++++++++++++++++++----
 4 files changed, 117 insertions(+), 16 deletions(-)

diff --git a/src/queues/dto/create-queue.dto.ts b/src/queues/dto/create-queue.dto.ts
index 7cb9f5a9..e5020021 100644
--- a/src/queues/dto/create-queue.dto.ts
+++ b/src/queues/dto/create-queue.dto.ts
@@ -42,4 +42,14 @@ export class CreateQueueDto {
   @IsArray()
   @IsNumber({}, { each: true })
   EmployeeIds?: number[];
+
+  // ✅ เพิ่ม itemID
+  @IsNumber()
+  @IsNotEmpty()
+  itemID: number;
+
+  // ✅ เพิ่ม itemType
+  @IsEnum(['PRODUCT', 'MATERIAL'])
+  @IsNotEmpty()
+  itemType: 'PRODUCT' | 'MATERIAL';
 }
diff --git a/src/queues/entities/queue.entity.ts b/src/queues/entities/queue.entity.ts
index ce2347bc..a2c28979 100644
--- a/src/queues/entities/queue.entity.ts
+++ b/src/queues/entities/queue.entity.ts
@@ -65,4 +65,10 @@ export class Queue {
 
   @CreateDateColumn()
   createdAt: Date;
+
+  @Column()
+  itemID: number;
+
+  @Column({ type: 'enum', enum: ['PRODUCT', 'MATERIAL'] })
+  itemType: 'PRODUCT' | 'MATERIAL';
 }
diff --git a/src/queues/queues.module.ts b/src/queues/queues.module.ts
index cf8324b7..838291f1 100644
--- a/src/queues/queues.module.ts
+++ b/src/queues/queues.module.ts
@@ -8,6 +8,8 @@ import { Page } from '@/pages/entities/page.entity';
 import { Order } from '@/orders/entities/order.entity';
 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';
 
 @Module({
   imports: [
@@ -18,6 +20,8 @@ import { QueueType } from '@/queue-types/entities/queue-type.entity';
       Order,
       Employee,
       QueueType,
+      Product,
+      Material,
     ]), // ✅ เพิ่ม Entity ที่เกี่ยวข้อง
   ],
   controllers: [QueuesController],
diff --git a/src/queues/queues.service.ts b/src/queues/queues.service.ts
index 28865ac1..d28c0cd7 100644
--- a/src/queues/queues.service.ts
+++ b/src/queues/queues.service.ts
@@ -14,6 +14,8 @@ import { Page } from '@/pages/entities/page.entity';
 import { Order } from '@/orders/entities/order.entity';
 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';
 
 @Injectable()
 export class QueuesService {
@@ -41,6 +43,12 @@ export class QueuesService {
 
     @InjectRepository(QueueType) // ✅ เพิ่มบรรทัดนี้
     private readonly queueTypeRepository: Repository<QueueType>,
+
+    @InjectRepository(Product)
+    private readonly productRepository: Repository<Product>,
+
+    @InjectRepository(Material)
+    private readonly materialRepository: Repository<Material>,
   ) {}
 
   async getLatestQueuesFromDate(dateStr?: string): Promise<Queue[]> {
@@ -102,10 +110,11 @@ export class QueuesService {
       PageID,
       OrderID,
       EmployeeIds = [],
+      itemID,
+      itemType,
       ...queueData
     } = createQueueDto;
 
-    // ✅ แปลง ID ให้แน่ใจว่าเป็นตัวเลข
     const machineId = Number(MachineID);
     const pageId = Number(PageID);
     const orderId = Number(OrderID);
@@ -117,20 +126,17 @@ export class QueuesService {
     if (isNaN(orderId))
       throw new BadRequestException(`Invalid OrderID: ${OrderID}`);
 
-    // 🔍 หา 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 หรือ BUFFER
     let order = null;
     let queueTypeName = 'ORDER';
 
@@ -144,13 +150,33 @@ export class QueuesService {
         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`);
 
+    // ✅ ตรวจสอบว่า itemID และ itemType มีอยู่จริง
+    let validItem = null;
+
+    if (itemType === 'PRODUCT') {
+      validItem = await this.productRepository.findOne({
+        where: { ProductID: itemID },
+      });
+      if (!validItem) {
+        throw new NotFoundException(`Product with ID ${itemID} not found`);
+      }
+    } else if (itemType === 'MATERIAL') {
+      validItem = await this.materialRepository.findOne({
+        where: { MaterialID: itemID },
+      });
+      if (!validItem) {
+        throw new NotFoundException(`Material with ID ${itemID} not found`);
+      }
+    } else {
+      throw new BadRequestException(`Invalid itemType: ${itemType}`);
+    }
+
     // ✅ เตรียม employees
     let employees = [];
 
@@ -177,14 +203,16 @@ export class QueuesService {
       }
     }
 
-    // ✅ สร้าง Queue object
+    // ✅ สร้าง Queue object พร้อม itemID + itemType
     const newQueue = this.queueRepository.create({
       ...queueData,
       machine,
       page,
       order: queueTypeName === 'ORDER' ? order : null,
       employees,
-      QueueType: queueType, // 👈 ชื่อต้องตรงกับ entity
+      QueueType: queueType,
+      itemID,
+      itemType,
     });
 
     const savedQueue = await this.queueRepository.save(newQueue);
@@ -203,8 +231,15 @@ export class QueuesService {
     }
 
     for (const createQueueDto of createQueueDtos) {
-      const { MachineID, PageID, OrderID, EmployeeIds, ...queueData } =
-        createQueueDto;
+      const {
+        MachineID,
+        PageID,
+        OrderID,
+        EmployeeIds,
+        itemID,
+        itemType,
+        ...queueData
+      } = createQueueDto;
 
       // ✅ แปลงค่าเบื้องต้น
       const machineId = Number(MachineID);
@@ -283,14 +318,35 @@ export class QueuesService {
         }
       }
 
-      // ✅ สร้าง Queue object
+      // ✅ ตรวจสอบ item ตาม itemType
+      if (itemType === 'PRODUCT') {
+        const product = await this.productRepository.findOne({
+          where: { ProductID: itemID },
+        });
+        if (!product) {
+          throw new NotFoundException(`Product with ID ${itemID} not found`);
+        }
+      } else if (itemType === 'MATERIAL') {
+        const material = await this.materialRepository.findOne({
+          where: { MaterialID: itemID },
+        });
+        if (!material) {
+          throw new NotFoundException(`Material with ID ${itemID} not found`);
+        }
+      } 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, // ชื่อต้องตรงกับ property ใน entity
+        itemID,
+        itemType,
       });
 
       newQueues.push(newQueue);
@@ -307,19 +363,33 @@ export class QueuesService {
 
   // ✅ Fetch all Queues with relationships
   async findAll() {
-    return await this.queueRepository.find({
+    const queues = await this.queueRepository.find({
       relations: [
         'machine',
         'page',
         'order',
-        'order.customer', // 👈 เพิ่มแบบนี้ ไม่ใช่ 'customer'
+        'order.customer',
         'employees',
         'QueueType',
       ],
     });
+
+    // Map เพื่อแนบ item เข้าไปในแต่ละ queue
+    for (const queue of queues) {
+      if (queue.itemType === 'PRODUCT') {
+        queue['item'] = await this.productRepository.findOne({
+          where: { ProductID: queue.itemID },
+        });
+      } else if (queue.itemType === 'MATERIAL') {
+        queue['item'] = await this.materialRepository.findOne({
+          where: { MaterialID: queue.itemID },
+        });
+      }
+    }
+
+    return queues;
   }
 
-  // ✅ Fetch a single Queue by ID
   async findOne(id: number) {
     const queue = await this.queueRepository.findOne({
       where: { QueueID: id },
@@ -327,9 +397,9 @@ export class QueuesService {
         'machine',
         'page',
         'order',
-        'order.customer', // 👈 ดึง customer ผ่าน order
+        'order.customer',
         'employees',
-        'QueueType', // เพิ่มอันนี้ด้วยถ้าอยากได้ type มาด้วยนะ
+        'QueueType',
       ],
     });
 
@@ -337,6 +407,17 @@ export class QueuesService {
       throw new NotFoundException(`Queue with ID ${id} not found`);
     }
 
+    // ✅ แนบ item ให้ด้วยตาม itemType
+    if (queue.itemType === 'PRODUCT') {
+      queue['item'] = await this.productRepository.findOne({
+        where: { ProductID: queue.itemID },
+      });
+    } else if (queue.itemType === 'MATERIAL') {
+      queue['item'] = await this.materialRepository.findOne({
+        where: { MaterialID: queue.itemID },
+      });
+    }
+
     return queue;
   }
 
-- 
GitLab