All files / src/domains/crm/services product-pricing.service.ts

0% Statements 0/55
0% Branches 0/50
0% Functions 0/17
0% Lines 0/49

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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types, FilterQuery } from 'mongoose';
import {
  CrmProduct,
  CrmProductCategory,
  PriceBook,
  PriceBookEntry,
  VolumeTier,
  DiscountSchedule,
  LossReason,
} from '../schemas/product-pricing.schema';
 
@Injectable()
export class ProductPricingService {
  private readonly logger = new Logger(ProductPricingService.name);
 
  constructor(
    @InjectModel(CrmProduct.name)
    private readonly productModel: Model<CrmProduct>,
    @InjectModel(CrmProductCategory.name)
    private readonly categoryModel: Model<CrmProductCategory>,
    @InjectModel(PriceBook.name)
    private readonly priceBookModel: Model<PriceBook>,
    @InjectModel(PriceBookEntry.name)
    private readonly priceBookEntryModel: Model<PriceBookEntry>,
    @InjectModel(VolumeTier.name)
    private readonly volumeTierModel: Model<VolumeTier>,
    @InjectModel(DiscountSchedule.name)
    private readonly discountScheduleModel: Model<DiscountSchedule>,
    @InjectModel(LossReason.name)
    private readonly lossReasonModel: Model<LossReason>,
  ) {}
 
  // ════════════════════════════════════════════════════════════
  // CATEGORIES
  // ════════════════════════════════════════════════════════════
 
  async createCategory(
    tenantId: Types.ObjectId,
    data: Partial<CrmProductCategory>,
  ): Promise<CrmProductCategory> {
    return this.categoryModel.create({ ...data, tenantId });
  }
 
  async listCategories(
    tenantId: Types.ObjectId,
  ): Promise<CrmProductCategory[]> {
    return this.categoryModel
      .find({ tenantId, active: true })
      .sort({ sortOrder: 1 })
      .exec();
  }
 
  // ════════════════════════════════════════════════════════════
  // PRODUCTS
  // ════════════════════════════════════════════════════════════
 
  async createProduct(
    tenantId: Types.ObjectId,
    data: Partial<CrmProduct>,
  ): Promise<CrmProduct> {
    return this.productModel.create({ ...data, tenantId });
  }
 
  async getProductById(
    tenantId: Types.ObjectId,
    productId: string,
  ): Promise<CrmProduct> {
    const product = await this.productModel
      .findOne({ _id: productId, tenantId })
      .exec();
    if (!product) throw new NotFoundException('Product not found');
    return product;
  }
 
  async updateProduct(
    tenantId: Types.ObjectId,
    productId: string,
    updates: Partial<CrmProduct>,
  ): Promise<CrmProduct> {
    const product = await this.productModel
      .findOneAndUpdate(
        { _id: productId, tenantId },
        { $set: updates },
        { new: true },
      )
      .exec();
    if (!product) throw new NotFoundException('Product not found');
    return product;
  }
 
  async listProducts(
    tenantId: Types.ObjectId,
    filters: {
      categoryId?: string;
      active?: boolean;
      search?: string;
      type?: string;
    },
    page = 1,
    limit = 25,
  ): Promise<{
    data: CrmProduct[];
    total: number;
    page: number;
    pages: number;
  }> {
    const query: FilterQuery<CrmProduct> = { tenantId };
    if (filters.categoryId)
      query.categoryId = new Types.ObjectId(filters.categoryId);
    if (filters.active !== undefined) query.active = filters.active;
    if (filters.type) query.productType = filters.type;
    if (filters.search) {
      query.$or = [
        { productName: { $regex: filters.search, $options: 'i' } },
        { productCode: { $regex: filters.search, $options: 'i' } },
      ];
    }
 
    const [data, total] = await Promise.all([
      this.productModel
        .find(query)
        .sort({ productName: 1 })
        .skip((page - 1) * limit)
        .limit(limit)
        .exec(),
      this.productModel.countDocuments(query).exec(),
    ]);
    return { data, total, page, pages: Math.ceil(total / limit) };
  }
 
  // ════════════════════════════════════════════════════════════
  // PRICE BOOKS
  // ════════════════════════════════════════════════════════════
 
  async createPriceBook(
    tenantId: Types.ObjectId,
    data: Partial<PriceBook>,
  ): Promise<PriceBook> {
    return this.priceBookModel.create({ ...data, tenantId });
  }
 
  async listPriceBooks(tenantId: Types.ObjectId): Promise<PriceBook[]> {
    return this.priceBookModel.find({ tenantId, active: true }).exec();
  }
 
  async addPriceBookEntry(
    tenantId: Types.ObjectId,
    data: Partial<PriceBookEntry>,
  ): Promise<PriceBookEntry> {
    return this.priceBookEntryModel.create({ ...data, tenantId });
  }
 
  async getPriceBookEntries(
    tenantId: Types.ObjectId,
    priceBookId: string,
  ): Promise<PriceBookEntry[]> {
    return this.priceBookEntryModel
      .find({
        tenantId,
        priceBookId: new Types.ObjectId(priceBookId),
        active: true,
      })
      .exec();
  }
 
  /**
   * Resolves the effective unit price for a product given a price book and quantity.
   * Falls back to the product's list price if no price book entry or volume tier is found.
   */
  async resolvePrice(
    tenantId: Types.ObjectId,
    productId: string,
    quantity: number,
    priceBookId?: string,
  ): Promise<{ unitPriceMinor: number; source: string }> {
    // 1) Try volume tier first
    const volumeTier = await this.volumeTierModel
      .findOne({
        tenantId,
        productId: new Types.ObjectId(productId),
        ...(priceBookId
          ? { priceBookId: new Types.ObjectId(priceBookId) }
          : {}),
        minQuantity: { $lte: quantity },
        maxQuantity: { $gte: quantity },
        active: true,
      })
      .exec();
 
    if (volumeTier) {
      return {
        unitPriceMinor: volumeTier.unitPriceMinor,
        source: 'volume_tier',
      };
    }
 
    // 2) Try price book entry
    if (priceBookId) {
      const entry = await this.priceBookEntryModel
        .findOne({
          tenantId,
          priceBookId: new Types.ObjectId(priceBookId),
          productId: new Types.ObjectId(productId),
          active: true,
        })
        .exec();
 
      if (entry) {
        return { unitPriceMinor: entry.unitPriceMinor, source: 'price_book' };
      }
    }
 
    // 3) Fall back to product list price
    const product = await this.getProductById(tenantId, productId);
    return { unitPriceMinor: product.unitPriceMinor, source: 'list_price' };
  }
 
  // ════════════════════════════════════════════════════════════
  // VOLUME TIERS & DISCOUNTS
  // ════════════════════════════════════════════════════════════
 
  async createVolumeTier(
    tenantId: Types.ObjectId,
    data: Partial<VolumeTier>,
  ): Promise<VolumeTier> {
    return this.volumeTierModel.create({ ...data, tenantId });
  }
 
  async createDiscountSchedule(
    tenantId: Types.ObjectId,
    data: Partial<DiscountSchedule>,
  ): Promise<DiscountSchedule> {
    return this.discountScheduleModel.create({ ...data, tenantId });
  }
 
  async listDiscountSchedules(
    tenantId: Types.ObjectId,
  ): Promise<DiscountSchedule[]> {
    return this.discountScheduleModel.find({ tenantId, active: true }).exec();
  }
 
  // ════════════════════════════════════════════════════════════
  // LOSS REASONS
  // ════════════════════════════════════════════════════════════
 
  async createLossReason(
    tenantId: Types.ObjectId,
    data: Partial<LossReason>,
  ): Promise<LossReason> {
    return this.lossReasonModel.create({ ...data, tenantId });
  }
 
  async listLossReasons(tenantId: Types.ObjectId): Promise<LossReason[]> {
    return this.lossReasonModel.find({ tenantId, active: true }).exec();
  }
}