All files / sales sales.service.ts

100% Statements 73/73
80.28% Branches 57/71
100% Functions 11/11
100% Lines 67/67

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 1961x 1x 1x 1x             1x 1x     1x     11x   11x   11x   11x   11x   11x   11x   11x   11x 11x         3x 3x 3x     2x 1x     1x 1x   1x           1x         3x 3x 3x     2x 1x     1x 1x   1x         1x 1x                 1x 1x 1x                     1x           1x       2x 2x           2x   1x           1x         3x 3x     3x                 3x 1x       2x 2x   1x         1x 1x                   1x           1x         1x 1x   1x 1x 1x   1x   1x 1x 1x        
import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import {
  SalesOrder,
  SalesOrderLine,
  SalesSubscription,
  SalesPartner,
  SalesTerritory
} from './schemas';
import { Quotation, Contract, CrmProduct, VolumeTier } from '../crm/schemas';
import { EventBusService } from '../../platform/events/event-bus.service';
 
@Injectable()
export class SalesService {
  constructor(
    @InjectModel(SalesOrder.name)
    private readonly orderModel: Model<SalesOrder>,
    @InjectModel(SalesOrderLine.name)
    private readonly orderLineModel: Model<SalesOrderLine>,
    @InjectModel(SalesSubscription.name)
    private readonly subscriptionModel: Model<SalesSubscription>,
    @InjectModel(SalesPartner.name)
    private readonly partnerModel: Model<SalesPartner>,
    @InjectModel(SalesTerritory.name)
    private readonly territoryModel: Model<SalesTerritory>,
    @InjectModel(Quotation.name)
    private readonly quotationModel: Model<Quotation>,
    @InjectModel(Contract.name)
    private readonly contractModel: Model<Contract>,
    @InjectModel(CrmProduct.name)
    private readonly productModel: Model<CrmProduct>,
    @InjectModel(VolumeTier.name)
    private readonly volumeTierModel: Model<VolumeTier>,
    private readonly eventBus: EventBusService
  ) {}
 
  // 1. Immutable Quotations Gate
  async reviseQuotation(tenantId: string, quotationId: string, updates: any): Promise<Quotation> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const quote = await this.quotationModel.findOne({ _id: new Types.ObjectId(quotationId), tenantId: tenantObjId }).exec();
    if (!quote) throw new NotFoundException('Quotation not found');
 
    // Immutability check
    if (quote.status === 'accepted' || quote.status === 'revised' || quote.status === 'cancelled') {
      throw new BadRequestException(`Quotations are immutable after acceptance or revisions. Status: ${quote.status}`);
    }
 
    Object.assign(quote, updates);
    await quote.save();
 
    await this.eventBus.publish(
      'sales.quote.created.v1',
      { quotationId, status: quote.status },
      tenantId
    );
 
    return quote;
  }
 
  // 2. Immutable Active Contracts Gate
  async amendContract(tenantId: string, contractId: string, updates: any): Promise<Contract> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const contract = await this.contractModel.findOne({ _id: new Types.ObjectId(contractId), tenantId: tenantObjId }).exec();
    if (!contract) throw new NotFoundException('Contract not found');
 
    // Active Contract check
    if (contract.status === 'active' || contract.status === 'terminated') {
      throw new BadRequestException(`Active or terminated contracts cannot be modified. Status: ${contract.status}`);
    }
 
    Object.assign(contract, updates);
    await contract.save();
 
    return contract;
  }
 
  // 3. Sales Order lifecycle & approvals
  async createSalesOrder(tenantId: string, data: any): Promise<SalesOrder> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const order = await this.orderModel.create({
      tenantId: tenantObjId,
      orderCode: `SO-${Date.now()}`,
      accountId: new Types.ObjectId(data.accountId),
      quotationId: data.quotationId ? new Types.ObjectId(data.quotationId) : undefined,
      totalAmountMinor: data.totalAmountMinor || 0,
      status: 'pending_approval' // Forces approval
    });
 
    Eif (data.lines && Array.isArray(data.lines)) {
      for (const line of data.lines) {
        await this.orderLineModel.create({
          tenantId: tenantObjId,
          orderId: order._id,
          productId: new Types.ObjectId(line.productId),
          quantity: line.quantity,
          unitPriceMinor: line.unitPriceMinor,
          lineTotalMinor: line.quantity * line.unitPriceMinor
        });
      }
    }
 
    await this.eventBus.publish(
      'sales.order.created.v1',
      { orderId: order._id.toString(), orderCode: order.orderCode },
      tenantId
    );
 
    return order;
  }
 
  async approveSalesOrder(tenantId: string, orderId: string, managerId: string): Promise<SalesOrder> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const order = await this.orderModel.findOneAndUpdate(
      { _id: new Types.ObjectId(orderId), tenantId: tenantObjId, status: 'pending_approval' },
      { status: 'approved', approvedBy: new Types.ObjectId(managerId) },
      { new: true }
    ).exec();
 
    if (!order) throw new NotFoundException('Sales Order not found or already processed');
 
    await this.eventBus.publish(
      'sales.order.approved.v1',
      { orderId, orderCode: order.orderCode },
      tenantId
    );
 
    return order;
  }
 
  // 4. CPQ Pricing Rules Engine
  async calculateCPQPrice(tenantId: string, productId: string, quantity: number, priceBookId?: string): Promise<number> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const prodObjId = new Types.ObjectId(productId);
 
    // Look for Volume / Tier discount rules
    const tier = await this.volumeTierModel.findOne({
      tenantId: tenantObjId,
      productId: prodObjId,
      priceBookId: priceBookId ? new Types.ObjectId(priceBookId) : undefined,
      minQuantity: { $lte: quantity },
      maxQuantity: { $gte: quantity },
      active: true
    }).exec();
 
    if (tier) {
      return tier.unitPriceMinor; // Pricing matches rule
    }
 
    // Default price check
    const product = await this.productModel.findOne({ _id: prodObjId, tenantId: tenantObjId }).exec();
    if (!product) throw new NotFoundException('Product not found');
 
    return product.unitPriceMinor;
  }
 
  // 5. Subscriptions Renewals
  async createSubscription(tenantId: string, data: any): Promise<SalesSubscription> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const sub = await this.subscriptionModel.create({
      tenantId: tenantObjId,
      accountId: new Types.ObjectId(data.accountId),
      productId: new Types.ObjectId(data.productId),
      planName: data.planName,
      billingAmountMinor: data.billingAmountMinor,
      billingFrequency: data.billingFrequency || 'monthly',
      nextRenewalDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30 days
    });
 
    await this.eventBus.publish(
      'sales.subscription.created.v1',
      { subscriptionId: sub._id.toString() },
      tenantId
    );
 
    return sub;
  }
 
  // 6. Customer 360 Aggregator
  async getCustomer360Profile(tenantId: string, accountId: string): Promise<any> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const accObjId = new Types.ObjectId(accountId);
 
    const subscriptions = await this.subscriptionModel.find({ tenantId: tenantObjId, accountId: accObjId }).exec();
    const orders = await this.orderModel.find({ tenantId: tenantObjId, accountId: accObjId }).exec();
    const contracts = await this.contractModel.find({ tenantId: tenantObjId, accountId: accObjId }).exec();
 
    return {
      accountId,
      activeSubscriptionsCount: subscriptions.filter(s => s.status === 'active').length,
      lifetimeOrderValue: orders.reduce((sum, o) => sum + o.totalAmountMinor, 0),
      contractsSummary: contracts.map(c => ({ contractCode: c.contractCode, status: c.status }))
    };
  }
}