All files / src/domains/crm/services crm-config.service.ts

0% Statements 0/52
0% Branches 0/38
0% Functions 0/11
0% Lines 0/50

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                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { Injectable, Logger, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import {
  CrmConfiguration,
  CrmConfigurationVersion,
  CrmNumberingRule,
  CrmNumberSequence,
} from '../schemas/crm-config.schema';
 
@Injectable()
export class CrmConfigService {
  private readonly logger = new Logger(CrmConfigService.name);
 
  constructor(
    @InjectModel(CrmConfiguration.name)
    private readonly configModel: Model<CrmConfiguration>,
    @InjectModel(CrmConfigurationVersion.name)
    private readonly configVersionModel: Model<CrmConfigurationVersion>,
    @InjectModel(CrmNumberingRule.name)
    private readonly numberingRuleModel: Model<CrmNumberingRule>,
    @InjectModel(CrmNumberSequence.name)
    private readonly numberSequenceModel: Model<CrmNumberSequence>,
  ) {}
 
  // ────────────────────────────────────────────────────────────
  // CONFIGURATION CRUD
  // ────────────────────────────────────────────────────────────
 
  async getConfiguration(tenantId: Types.ObjectId): Promise<CrmConfiguration> {
    let config = await this.configModel.findOne({ tenantId }).exec();
    if (!config) {
      config = await this.configModel.create({ tenantId });
      this.logger.log(
        `Created default CRM configuration for tenant ${tenantId}`,
      );
    }
    return config;
  }
 
  async updateConfiguration(
    tenantId: Types.ObjectId,
    updates: Partial<CrmConfiguration>,
  ): Promise<CrmConfiguration> {
    const config = await this.configModel
      .findOneAndUpdate(
        { tenantId },
        { $set: updates },
        { new: true, upsert: true },
      )
      .exec();
    return config;
  }
 
  async publishConfiguration(
    tenantId: Types.ObjectId,
    userId: Types.ObjectId,
    description?: string,
  ): Promise<CrmConfigurationVersion> {
    const config = await this.getConfiguration(tenantId);
    const lastVersion = await this.configVersionModel
      .findOne({ tenantId })
      .sort({ versionNumber: -1 })
      .exec();
    const nextVersion = (lastVersion?.versionNumber ?? 0) + 1;
 
    const version = await this.configVersionModel.create({
      tenantId,
      versionNumber: nextVersion,
      configurationData: config.toObject(),
      publishedBy: userId,
      description,
    });
 
    this.logger.log(
      `Published CRM config version ${nextVersion} for tenant ${tenantId}`,
    );
    return version;
  }
 
  async getConfigurationVersions(
    tenantId: Types.ObjectId,
    page = 1,
    limit = 20,
  ): Promise<{ data: CrmConfigurationVersion[]; total: number }> {
    const [data, total] = await Promise.all([
      this.configVersionModel
        .find({ tenantId })
        .sort({ versionNumber: -1 })
        .skip((page - 1) * limit)
        .limit(limit)
        .exec(),
      this.configVersionModel.countDocuments({ tenantId }).exec(),
    ]);
    return { data, total };
  }
 
  // ────────────────────────────────────────────────────────────
  // NUMBERING RULES
  // ────────────────────────────────────────────────────────────
 
  async getNumberingRule(
    tenantId: Types.ObjectId,
    entityType: string,
  ): Promise<CrmNumberingRule | null> {
    return this.numberingRuleModel.findOne({ tenantId, entityType }).exec();
  }
 
  async upsertNumberingRule(
    tenantId: Types.ObjectId,
    entityType: string,
    data: { prefix: string; paddingLength?: number; startNumber?: number },
  ): Promise<CrmNumberingRule> {
    const rule = await this.numberingRuleModel
      .findOneAndUpdate(
        { tenantId, entityType },
        { $set: { ...data, tenantId, entityType } },
        { new: true, upsert: true },
      )
      .exec();
    return rule;
  }
 
  async listNumberingRules(
    tenantId: Types.ObjectId,
  ): Promise<CrmNumberingRule[]> {
    return this.numberingRuleModel.find({ tenantId }).exec();
  }
 
  // ────────────────────────────────────────────────────────────
  // CONCURRENCY-SAFE SEQUENCE GENERATOR
  // ────────────────────────────────────────────────────────────
 
  /**
   * Generates the next unique code for a given entity type using MongoDB's
   * atomic findOneAndUpdate to prevent race conditions.
   *
   * Example output: "LEAD-000042"
   */
  async generateNextCode(
    tenantId: Types.ObjectId,
    entityType: string,
  ): Promise<string> {
    // Get the numbering rule (or use defaults)
    const rule = await this.getNumberingRule(tenantId, entityType);
    const prefix = rule?.prefix ?? `${entityType.toUpperCase()}-`;
    const padding = rule?.paddingLength ?? 6;
    const startNumber = rule?.startNumber ?? 1;
 
    // Atomic increment — no race conditions
    const sequence = await this.numberSequenceModel
      .findOneAndUpdate(
        { tenantId, entityType },
        {
          $inc: { currentNumber: 1 },
          $setOnInsert: { tenantId, entityType },
        },
        { new: true, upsert: true },
      )
      .exec();
 
    if (!sequence) {
      throw new BadRequestException(
        `Failed to generate sequence for ${entityType}`,
      );
    }
 
    const effectiveNumber = Math.max(sequence.currentNumber, startNumber);
    const paddedNumber = String(effectiveNumber).padStart(padding, '0');
    const code = `${prefix}${paddedNumber}`;
 
    this.logger.debug(
      `Generated code ${code} for tenant ${tenantId}, entity ${entityType}`,
    );
    return code;
  }
 
  /**
   * Preview what the next code would be (without consuming a number).
   */
  async previewNextCode(
    tenantId: Types.ObjectId,
    entityType: string,
  ): Promise<string> {
    const rule = await this.getNumberingRule(tenantId, entityType);
    const prefix = rule?.prefix ?? `${entityType.toUpperCase()}-`;
    const padding = rule?.paddingLength ?? 6;
    const startNumber = rule?.startNumber ?? 1;
 
    const sequence = await this.numberSequenceModel
      .findOne({ tenantId, entityType })
      .exec();
 
    const nextNumber = Math.max(
      (sequence?.currentNumber ?? 0) + 1,
      startNumber,
    );
    return `${prefix}${String(nextNumber).padStart(padding, '0')}`;
  }
 
  /**
   * Reset a sequence counter (admin-only, audited externally).
   */
  async resetSequence(
    tenantId: Types.ObjectId,
    entityType: string,
    newStart: number,
  ): Promise<void> {
    await this.numberSequenceModel
      .findOneAndUpdate(
        { tenantId, entityType },
        { $set: { currentNumber: newStart - 1 } },
        { upsert: true },
      )
      .exec();
    this.logger.warn(
      `Reset sequence for ${entityType} to ${newStart} for tenant ${tenantId}`,
    );
  }
}