All files / src/domains/procurement/vendors/services vendor.service.ts

0% Statements 0/69
0% Branches 0/36
0% Functions 0/11
0% Lines 0/62

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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Vendor } from '../schemas/vendor.schema';
import { EventBusService } from '../../../../platform/events/event-bus.service';
import { AuditLogService } from '../../../../platform/audit/audit-log.service';
import * as crypto from 'crypto';
 
const ENCRYPT_KEY = (
  process.env.ENCRYPTION_KEY || 'be-vision-field-level-encrypt-key'
).slice(0, 32);
const IV_LEN = 16;
 
@Injectable()
export class VendorService {
  constructor(
    @InjectModel(Vendor.name)
    private readonly vendorModel: Model<Vendor>,
    private readonly eventBus: EventBusService,
    private readonly auditLog: AuditLogService,
  ) {}
 
  private encrypt(text: string): string {
    const iv = crypto.randomBytes(IV_LEN);
    const cipher = crypto.createCipheriv(
      'aes-256-cbc',
      Buffer.from(ENCRYPT_KEY),
      iv,
    );
    const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
    return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
  }
 
  private decrypt(text: string): string {
    const [ivHex, encHex] = text.split(':');
    const iv = Buffer.from(ivHex, 'hex');
    const enc = Buffer.from(encHex, 'hex');
    const decipher = crypto.createDecipheriv(
      'aes-256-cbc',
      Buffer.from(ENCRYPT_KEY),
      iv,
    );
    return Buffer.concat([decipher.update(enc), decipher.final()]).toString();
  }
 
  async createVendor(tenantId: string, data: any, userId: string): Promise<Vendor> {
    // 1. Uniqueness check for code
    const existing = await this.vendorModel.findOne({ tenantId, code: data.code }).exec();
    if (existing) {
      throw new BadRequestException(`Vendor with code ${data.code} already exists`);
    }
 
    // 2. Duplicate detection by email, phone, name
    const dup = await this.vendorModel.findOne({
      tenantId,
      $or: [
        { email: data.email },
        { phone: data.phone },
        { name: data.name },
      ],
    }).exec();
    if (dup) {
      throw new BadRequestException(`Potential duplicate vendor found matching Email, Phone or Name`);
    }
 
    // 3. Encrypt bank accounts details if present
    const processedBankAccounts = (data.bankAccounts || []).map((ba: any) => {
      const masked = ba.accountNumber.slice(-4).padStart(ba.accountNumber.length, '*');
      return {
        bankName: ba.bankName,
        routingNumber: ba.routingNumber,
        accountHolderName: ba.accountHolderName,
        accountNumberMasked: masked,
        accountNumberEncrypted: this.encrypt(ba.accountNumber),
      };
    });
 
    const vendor = await this.vendorModel.create({
      ...data,
      tenantId,
      bankAccounts: processedBankAccounts,
      status: 'draft',
    });
 
    await this.eventBus.publish('procurement.vendor.created.v1', {
      vendorId: (vendor as any)._id.toString(),
      tenantId,
      code: vendor.code,
    }, tenantId);
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'CREATE',
      resource: 'Vendor',
      resourceId: (vendor as any)._id.toString(),
      newValues: { name: vendor.name, code: vendor.code },
    });
 
    return vendor;
  }
 
  async getVendors(tenantId: string, status?: string): Promise<Vendor[]> {
    const query: any = { tenantId };
    if (status) query.status = status;
    return this.vendorModel.find(query).exec();
  }
 
  async getVendorById(tenantId: string, id: string, userId: string): Promise<Vendor> {
    const vendor = await this.vendorModel.findOne({ _id: id, tenantId }).exec();
    if (!vendor) throw new NotFoundException('Vendor not found');
 
    // Sensitive read audit log
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'READ_SENSITIVE',
      resource: 'Vendor',
      resourceId: id,
      newValues: { details: 'Read vendor sensitive fields (Bank Details)' },
    });
 
    return vendor;
  }
 
  async updateVendor(tenantId: string, id: string, data: any, userId: string): Promise<Vendor> {
    if (data.bankAccounts) {
      data.bankAccounts = data.bankAccounts.map((ba: any) => {
        if (ba.accountNumber && !ba.accountNumber.includes('*')) {
          const masked = ba.accountNumber.slice(-4).padStart(ba.accountNumber.length, '*');
          return {
            bankName: ba.bankName,
            routingNumber: ba.routingNumber,
            accountHolderName: ba.accountHolderName,
            accountNumberMasked: masked,
            accountNumberEncrypted: this.encrypt(ba.accountNumber),
          };
        }
        return ba;
      });
    }
 
    const vendor = await this.vendorModel.findOneAndUpdate({ _id: id, tenantId }, data, { new: true }).exec();
    if (!vendor) throw new NotFoundException('Vendor not found');
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'UPDATE',
      resource: 'Vendor',
      resourceId: id,
      newValues: data,
    });
 
    return vendor;
  }
 
  async approveKyc(tenantId: string, id: string, userId: string): Promise<Vendor> {
    const vendor = await this.vendorModel.findOneAndUpdate(
      { _id: id, tenantId },
      { status: 'approved', kycApprovedBy: userId, kycApprovalDate: new Date() },
      { new: true }
    ).exec();
    if (!vendor) throw new NotFoundException('Vendor not found');
 
    await this.eventBus.publish('procurement.vendor.approved.v1', {
      vendorId: id,
      tenantId,
      code: vendor.code,
    }, tenantId);
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'KYC_APPROVE',
      resource: 'Vendor',
      resourceId: id,
      newValues: { status: 'approved' },
    });
 
    return vendor;
  }
 
  async blockVendor(tenantId: string, id: string, userId: string): Promise<Vendor> {
    const vendor = await this.vendorModel.findOneAndUpdate(
      { _id: id, tenantId },
      { status: 'blocked' },
      { new: true }
    ).exec();
    if (!vendor) throw new NotFoundException('Vendor not found');
 
    await this.eventBus.publish('procurement.vendor.blocked.v1', {
      vendorId: id,
      tenantId,
      code: vendor.code,
    }, tenantId);
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'BLOCK',
      resource: 'Vendor',
      resourceId: id,
      newValues: { status: 'blocked' },
    });
 
    return vendor;
  }
}