All files / src/domains/manufacturing/services bom-routing.service.ts

0% Statements 0/60
0% Branches 0/63
0% Functions 0/9
0% Lines 0/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143                                                                                                                                                                                                                                                                                             
import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { BillOfMaterial, BomLine, ProductionRouting, RoutingOperation } from '../schemas';
 
@Injectable()
export class BomRoutingService {
  constructor(
    @InjectModel(BillOfMaterial.name) private readonly bomModel: Model<BillOfMaterial>,
    @InjectModel(BomLine.name) private readonly bomLineModel: Model<BomLine>,
    @InjectModel(ProductionRouting.name) private readonly routingModel: Model<ProductionRouting>,
    @InjectModel(RoutingOperation.name) private readonly operationModel: Model<RoutingOperation>
  ) {}
 
  async createBom(tenantId: string, payload: any): Promise<BillOfMaterial> {
    const bom = new this.bomModel({
      tenantId,
      bomCode: payload.bomCode,
      itemCode: payload.itemCode,
      bomName: payload.bomName,
      version: payload.version || 1,
      status: 'Draft',
      bomQuantity: payload.bomQuantity || 1,
    });
    return bom.save();
  }
 
  async addBomLine(tenantId: string, bomId: string, line: any): Promise<BomLine> {
    const bom = await this.bomModel.findOne({ _id: bomId, tenantId }).exec();
    if (!bom) throw new BadRequestException('BOM not found');
    if (bom.status === 'Active') throw new BadRequestException('Cannot modify approved immutable BOM');
 
    // Self-reference check
    if (line.componentItemCode === bom.itemCode) {
      throw new BadRequestException('BOM cannot reference itself');
    }
 
    // Circular BOM detection
    await this.detectCircularBom(tenantId, bom.itemCode, line.componentItemCode);
 
    const bomLine = new this.bomLineModel({
      tenantId,
      bomId: new Types.ObjectId(bomId),
      componentItemCode: line.componentItemCode,
      quantity: line.quantity,
      uom: line.uom,
      scrapFactorPercent: line.scrapFactorPercent || 0,
      isPhantom: line.isPhantom || false,
    });
    return bomLine.save();
  }
 
  async activateBom(tenantId: string, bomId: string): Promise<BillOfMaterial> {
    const bom = await this.bomModel.findOneAndUpdate(
      { _id: bomId, tenantId },
      { status: 'Active' },
      { new: true }
    ).exec();
    if (!bom) throw new BadRequestException('BOM not found');
    return bom;
  }
 
  async explodeBom(tenantId: string, itemCode: string, quantity = 1, depth = 0, visited = new Set<string>()): Promise<any[]> {
    if (visited.has(itemCode)) {
      throw new BadRequestException('Circular dependency detected during BOM explosion');
    }
    visited.add(itemCode);
 
    const activeBom = await this.bomModel.findOne({ tenantId, itemCode, status: 'Active' }).exec();
    if (!activeBom) return [];
 
    const lines = await this.bomLineModel.find({ tenantId, bomId: activeBom._id }).exec();
    const explosion: any[] = [];
 
    for (const line of lines) {
      const lineQty = line.quantity * quantity * (1 + (line.scrapFactorPercent || 0) / 100);
      explosion.push({
        componentItemCode: line.componentItemCode,
        quantityNeeded: lineQty,
        uom: line.uom,
        isPhantom: line.isPhantom,
        depth,
      });
 
      if (line.isPhantom) {
        const subExplosion = await this.explodeBom(tenantId, line.componentItemCode, lineQty, depth + 1, new Set(visited));
        explosion.push(...subExplosion);
      }
    }
    return explosion;
  }
 
  private async detectCircularBom(tenantId: string, parentItemCode: string, childItemCode: string): Promise<void> {
    const visited = new Set<string>();
    const check = async (item: string) => {
      if (item === parentItemCode) {
        throw new BadRequestException('Circular BOM definition detected');
      }
      if (visited.has(item)) return;
      visited.add(item);
 
      const subBom = await this.bomModel.findOne({ tenantId, itemCode: item, status: 'Active' }).exec();
      if (!subBom) return;
 
      const subLines = await this.bomLineModel.find({ tenantId, bomId: subBom._id }).exec();
      for (const line of subLines) {
        await check(line.componentItemCode);
      }
    };
    await check(childItemCode);
  }
 
  async createRouting(tenantId: string, payload: any): Promise<ProductionRouting> {
    const routing = new this.routingModel({
      tenantId,
      routingCode: payload.routingCode,
      itemCode: payload.itemCode,
      routingName: payload.routingName,
      status: 'Active',
    });
    return routing.save();
  }
 
  async addRoutingOperation(tenantId: string, routingId: string, op: any): Promise<RoutingOperation> {
    const operation = new this.operationModel({
      tenantId,
      routingId: new Types.ObjectId(routingId),
      operationCode: op.operationCode,
      operationName: op.operationName,
      sequence: op.sequence,
      workCenterId: new Types.ObjectId(op.workCenterId),
      setupTimeMinutes: op.setupTimeMinutes || 0,
      runTimeMinutes: op.runTimeMinutes || 0,
      laborTimeMinutes: op.laborTimeMinutes || 0,
      machineTimeMinutes: op.machineTimeMinutes || 0,
      subcontracted: op.subcontracted || false,
      qualityInspectionRequired: op.qualityInspectionRequired || false,
      instructions: op.instructions || '',
    });
    return operation.save();
  }
}