All files / src/domains/procurement/vendor-bills/services vendor-bill.service.ts

0% Statements 0/63
0% Branches 0/42
0% Functions 0/7
0% Lines 0/57

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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161                                                                                                                                                                                                                                                                                                                                 
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { VendorBill } from '../schemas/vendor-bill.schema';
import { ConfigurationService } from '../../configuration/services/configuration.service';
import { PurchaseOrderService } from '../../purchase-orders/services/purchase-order.service';
import { ReceiptService } from '../../receipts/services/receipt.service';
import { EventBusService } from '../../../../platform/events/event-bus.service';
import { AuditLogService } from '../../../../platform/audit/audit-log.service';
 
@Injectable()
export class VendorBillService {
  constructor(
    @InjectModel(VendorBill.name)
    private readonly billModel: Model<VendorBill>,
    private readonly configService: ConfigurationService,
    private readonly poService: PurchaseOrderService,
    private readonly receiptService: ReceiptService,
    private readonly eventBus: EventBusService,
    private readonly auditLog: AuditLogService,
  ) {}
 
  async createBill(tenantId: string, data: any, userId: string): Promise<VendorBill> {
    const existing = await this.billModel.findOne({
      tenantId,
      vendorId: data.vendorId,
      vendorInvoiceNumber: data.vendorInvoiceNumber,
    }).exec();
 
    if (existing) {
      throw new BadRequestException(`Duplicate invoice number ${data.vendorInvoiceNumber} for vendor`);
    }
 
    const count = await this.billModel.countDocuments({ tenantId }).exec();
    const billNumber = `BIL-${new Date().getFullYear()}-${(count + 1).toString().padStart(5, '0')}`;
 
    const subtotal = data.lines.reduce((sum: number, line: any) => sum + line.total, 0);
    const tax = subtotal * 0.1;
    const totalAmount = subtotal + tax;
 
    let matchStatus = 'matched';
    let holdReason = '';
    let held = false;
 
    // 3-Way Match Check if PO is provided
    if (data.purchaseOrderId) {
      const po = await this.poService.getPurchaseOrderById(tenantId, data.purchaseOrderId);
      const config = await this.configService.getConfiguration(tenantId);
 
      // Price Variance Check
      const baseDiffPercent = Math.abs((totalAmount - po.totalAmount) / po.totalAmount) * 100;
      if (baseDiffPercent > config.priceVarianceTolerancePercent) {
        matchStatus = 'variance_held';
        holdReason = `Price variance of ${baseDiffPercent.toFixed(2)}% exceeds tolerance of ${config.priceVarianceTolerancePercent}%`;
        held = true;
      }
    }
 
    const bill = await this.billModel.create({
      ...data,
      tenantId,
      billNumber,
      subtotal,
      tax,
      totalAmount,
      status: 'draft',
      match: {
        purchaseOrderId: data.purchaseOrderId || null,
        goodsReceiptId: data.goodsReceiptId || null,
        status: matchStatus,
        varianceReason: holdReason,
      },
      held,
      holdReason,
    });
 
    await this.eventBus.publish('procurement.vendor-bill.created.v1', {
      billId: (bill as any)._id.toString(),
      tenantId,
      totalAmount,
    }, tenantId);
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'CREATE_BILL',
      resource: 'VendorBill',
      resourceId: (bill as any)._id.toString(),
      newValues: { billNumber, totalAmount, held },
    });
 
    return bill;
  }
 
  async getBills(tenantId: string): Promise<VendorBill[]> {
    return this.billModel.find({ tenantId }).exec();
  }
 
  async getBillById(tenantId: string, id: string): Promise<VendorBill> {
    const bill = await this.billModel.findOne({ _id: id, tenantId }).exec();
    if (!bill) throw new NotFoundException('Vendor Bill not found');
    return bill;
  }
 
  async approveBill(tenantId: string, id: string, userId: string): Promise<VendorBill> {
    const bill = await this.billModel.findOne({ _id: id, tenantId }).exec();
    if (!bill) throw new NotFoundException('Vendor Bill not found');
 
    if (bill.held) {
      throw new BadRequestException(`Cannot approve bill ${bill.billNumber} because it has active matching holds: ${bill.holdReason}`);
    }
 
    bill.status = 'approved';
    await bill.save();
 
    await this.eventBus.publish('procurement.vendor-bill.approved.v1', {
      billId: id,
      tenantId,
      totalAmount: bill.totalAmount,
    }, tenantId);
 
    // Accounts Payable Export event
    await this.eventBus.publish('procurement.ap-export.generated.v1', {
      billId: id,
      tenantId,
      exportedAt: new Date(),
    }, tenantId);
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'APPROVE_BILL',
      resource: 'VendorBill',
      resourceId: id,
      newValues: { status: 'approved' },
    });
 
    return bill;
  }
 
  async releaseHold(tenantId: string, id: string, userId: string): Promise<VendorBill> {
    const bill = await this.billModel.findOneAndUpdate(
      { _id: id, tenantId },
      { held: false, holdReason: '', 'match.status': 'matched' },
      { new: true }
    ).exec();
    if (!bill) throw new NotFoundException('Vendor Bill not found');
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'RELEASE_HOLD',
      resource: 'VendorBill',
      resourceId: id,
      newValues: { held: false },
    });
 
    return bill;
  }
}