All files / src/domains/mdm/application/services unit-of-measure.service.ts

0% Statements 0/50
0% Branches 0/46
0% Functions 0/8
0% Lines 0/45

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                                                                                                                                                                                                                                                                                   
import {
  Injectable,
  Logger,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import {
  UnitCategory,
  UnitOfMeasure,
  UnitConversion,
  UnitRoundingRule,
} from '../../infrastructure/schemas/unit-of-measure.schema';
import { UomConverter } from '../../domain/interfaces/master-data-provider.interface';
 
@Injectable()
export class UnitOfMeasureService implements UomConverter {
  private readonly logger = new Logger(UnitOfMeasureService.name);
 
  constructor(
    @InjectModel(UnitCategory.name)
    private readonly categoryModel: Model<UnitCategory>,
    @InjectModel(UnitOfMeasure.name)
    private readonly uomModel: Model<UnitOfMeasure>,
    @InjectModel(UnitConversion.name)
    private readonly conversionModel: Model<UnitConversion>,
    @InjectModel(UnitRoundingRule.name)
    private readonly roundingModel: Model<UnitRoundingRule>,
  ) {}
 
  async listCategories(): Promise<any[]> {
    return this.categoryModel
      .find({ active: true })
      .sort({ categoryName: 1 })
      .lean()
      .exec();
  }
 
  async listUnits(categoryCode?: string, tenantId?: string): Promise<any[]> {
    const query: any = { active: true };
    if (categoryCode) query.categoryCode = categoryCode;
    if (tenantId) {
      query.$or = [
        { tenantId: new Types.ObjectId(tenantId) },
        { tenantId: null },
      ];
    } else {
      query.tenantId = null;
    }
    return this.uomModel.find(query).sort({ unitName: 1 }).lean().exec();
  }
 
  async bulkUpsertUnits(units: any[]): Promise<number> {
    const ops = units.map((u) => ({
      updateOne: {
        filter: {
          unitCode: u.unitCode,
          tenantId: u.tenantId ? new Types.ObjectId(u.tenantId) : null,
        },
        update: { $set: u, $setOnInsert: { systemManaged: true } },
        upsert: true,
      },
    }));
    const result = await this.uomModel.bulkWrite(ops, { ordered: false });
    return result.upsertedCount + result.modifiedCount;
  }
 
  async bulkUpsertCategories(categories: any[]): Promise<number> {
    const ops = categories.map((c) => ({
      updateOne: {
        filter: { categoryCode: c.categoryCode },
        update: { $set: c, $setOnInsert: { systemManaged: true } },
        upsert: true,
      },
    }));
    const result = await this.categoryModel.bulkWrite(ops, { ordered: false });
    return result.upsertedCount + result.modifiedCount;
  }
 
  // ════════ UOM CONVERTER (interface implementation) ════════
 
  async convert(params: {
    value: string;
    fromUnit: string;
    toUnit: string;
    precision?: number;
  }): Promise<{ convertedValue: string; isExact: boolean }> {
    const from = params.fromUnit.toUpperCase();
    const to = params.toUnit.toUpperCase();
 
    if (from === to) {
      return { convertedValue: params.value, isExact: true };
    }
 
    // Try explicit conversion lookup first
    const direct = await this.conversionModel
      .findOne({ fromUnitCode: from, toUnitCode: to, active: true })
      .lean()
      .exec();
    if (direct) {
      const multiplier = parseFloat(direct.multiplier);
      const offset = parseFloat(direct.offset || '0');
      const val = parseFloat(params.value) * multiplier + offset;
      const rounded = val.toFixed(params.precision ?? direct.precision ?? 4);
      return { convertedValue: rounded, isExact: direct.isExact };
    }
 
    // fallback: convert via Base Unit
    const fromUom = await this.uomModel
      .findOne({ unitCode: from })
      .lean()
      .exec();
    const toUom = await this.uomModel.findOne({ unitCode: to }).lean().exec();
 
    if (!fromUom || !toUom || fromUom.categoryCode !== toUom.categoryCode) {
      throw new BadRequestException(
        `Cannot convert units across different categories: ${from} ↔ ${to}`,
      );
    }
 
    // Val in Base Unit = val * fromFactor + fromOffset
    const fromFactor = parseFloat(fromUom.conversionFactor || '1');
    const fromOffset = parseFloat(fromUom.conversionOffset || '0');
    const valInBase = parseFloat(params.value) * fromFactor + fromOffset;
 
    // Converted Val = (valInBase - toOffset) / toFactor
    const toFactor = parseFloat(toUom.conversionFactor || '1');
    const toOffset = parseFloat(toUom.conversionOffset || '0');
    const resultVal = (valInBase - toOffset) / toFactor;
 
    return {
      convertedValue: resultVal.toFixed(params.precision ?? 4),
      isExact: false,
    };
  }
}