All files / src/domains/inventory/replenishment/services replenishment.service.ts

0% Statements 0/24
0% Branches 0/18
0% Functions 0/3
0% Lines 0/21

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                                                                                                     
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { StockBalance } from '../../stock-ledger/schemas/ledger.schema';
import { InventoryItem } from '../../items/schemas/item.schema';
import { EventBusService } from '../../../../platform/events/event-bus.service';
 
@Injectable()
export class ReplenishmentService {
  constructor(
    @InjectModel(StockBalance.name)
    private readonly balanceModel: Model<StockBalance>,
    @InjectModel(InventoryItem.name)
    private readonly itemModel: Model<InventoryItem>,
    private readonly eventBus: EventBusService
  ) {}
 
  async calculateReplenishmentSuggestions(tenantId: string): Promise<any[]> {
    const items = await this.itemModel.find({ tenantId, active: true }).exec();
    const suggestions: any[] = [];
 
    for (const item of items) {
      const balances = await this.balanceModel.find({ tenantId, itemCode: item.itemCode }).exec();
      const totalAvailable = balances.reduce((sum, b) => sum + b.quantityAvailable, 0);
 
      // Check low stock
      if (totalAvailable < item.reorderPoint) {
        const orderQty = item.maxStock - totalAvailable;
        const suggestion = {
          itemCode: item.itemCode,
          itemName: item.itemName,
          currentQuantity: totalAvailable,
          reorderPoint: item.reorderPoint,
          suggestedOrderQuantity: orderQty > 0 ? orderQty : item.reorderPoint,
        };
        suggestions.push(suggestion);
 
        // Publish suggestion event
        await this.eventBus.publish('inventory.requisition-suggested.v1', {
          tenantId,
          itemCode: item.itemCode,
          suggestedQuantity: orderQty > 0 ? orderQty : item.reorderPoint,
          occurredAt: new Date(),
        }, tenantId);
      }
    }
 
    return suggestions;
  }
}