All files / src/domains/mdm/application/services master-data-duplicate.service.ts

0% Statements 0/115
0% Branches 0/63
0% Functions 0/12
0% Lines 0/98

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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import {
  Injectable,
  Logger,
  BadRequestException,
  NotFoundException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { MasterDuplicateCandidate } from '../../infrastructure/schemas/master-data-change.schema';
import { MasterMergeRequest } from '../../infrastructure/schemas/master-data-change.schema';
import { MasterDataRecord } from '../../infrastructure/schemas/master-data-record.schema';
import { MasterDataAlias } from '../../infrastructure/schemas/master-data-record.schema';
import { EventBusService } from '../../../../platform/events/event-bus.service';
 
@Injectable()
export class MasterDataDuplicateService {
  private readonly logger = new Logger(MasterDataDuplicateService.name);
 
  constructor(
    @InjectModel(MasterDuplicateCandidate.name)
    private readonly dupModel: Model<MasterDuplicateCandidate>,
    @InjectModel(MasterMergeRequest.name)
    private readonly mergeModel: Model<MasterMergeRequest>,
    @InjectModel(MasterDataRecord.name)
    private readonly recordModel: Model<MasterDataRecord>,
    @InjectModel('MasterDataAlias')
    private readonly aliasModel: Model<MasterDataAlias>,
    private readonly eventBus: EventBusService,
  ) {}
 
  // ────────────────────────────────────────────────────────────────
  // SCAN FOR DUPLICATES
  // ────────────────────────────────────────────────────────────────
 
  async scanForDuplicates(
    definitionKey: string,
    options?: { scopeType?: string; scopeId?: string },
  ): Promise<number> {
    const query: any = { definitionKey, active: true, status: 'published' };
    if (options?.scopeType) query.scopeType = options.scopeType;
    if (options?.scopeId) query.scopeId = new Types.ObjectId(options.scopeId);
 
    const records = await this.recordModel.find(query).lean().exec();
    if (records.length < 2) return 0;
 
    let candidateCount = 0;
 
    // Simple O(n²) scan — suitable for master data volumes (typically < 10k records per definition)
    for (let i = 0; i < records.length; i++) {
      for (let j = i + 1; j < records.length; j++) {
        const r1 = records[i];
        const r2 = records[j];
 
        const matchResult = this.matchRecords(r1, r2);
        if (matchResult.score >= 80) {
          // Check if candidate already exists
          const existing = await this.dupModel
            .findOne({
              definitionKey,
              record1Id: r1._id,
              record2Id: r2._id,
              status: { $in: ['pending', 'confirmed_duplicate'] },
            })
            .lean()
            .exec();
 
          if (!existing) {
            await this.dupModel.create({
              definitionKey,
              record1Id: r1._id,
              record1Code: r1.recordCode,
              record2Id: r2._id,
              record2Code: r2.recordCode,
              matchType: matchResult.type,
              matchScore: matchResult.score,
              status: 'pending',
            });
            candidateCount++;
          }
        }
      }
    }
 
    this.logger.log(
      `Duplicate scan for ${definitionKey}: found ${candidateCount} candidates`,
    );
    return candidateCount;
  }
 
  // ────────────────────────────────────────────────────────────────
  // MATCH LOGIC
  // ────────────────────────────────────────────────────────────────
 
  private matchRecords(
    r1: any,
    r2: any,
  ): { score: number; type: 'exact' | 'normalized' | 'fuzzy' } {
    // Exact match on code
    if (r1.recordCode === r2.recordCode) {
      return { score: 100, type: 'exact' };
    }
 
    // Normalized match (case-insensitive, whitespace-trimmed)
    const norm1 = this.normalize(r1.recordName);
    const norm2 = this.normalize(r2.recordName);
    if (norm1 === norm2) {
      return { score: 95, type: 'normalized' };
    }
 
    // Fuzzy match (Levenshtein distance ratio)
    const similarity = this.levenshteinSimilarity(norm1, norm2);
    if (similarity >= 0.85) {
      return { score: Math.round(similarity * 100), type: 'fuzzy' };
    }
 
    return { score: 0, type: 'fuzzy' };
  }
 
  private normalize(str: string): string {
    return (str || '').toLowerCase().trim().replace(/\s+/g, ' ');
  }
 
  private levenshteinSimilarity(s1: string, s2: string): number {
    if (!s1.length || !s2.length) return 0;
    const maxLen = Math.max(s1.length, s2.length);
    const distance = this.levenshteinDistance(s1, s2);
    return (maxLen - distance) / maxLen;
  }
 
  private levenshteinDistance(s1: string, s2: string): number {
    const len1 = s1.length;
    const len2 = s2.length;
    const dp: number[][] = Array.from({ length: len1 + 1 }, () =>
      Array(len2 + 1).fill(0),
    );
    for (let i = 0; i <= len1; i++) dp[i][0] = i;
    for (let j = 0; j <= len2; j++) dp[0][j] = j;
    for (let i = 1; i <= len1; i++) {
      for (let j = 1; j <= len2; j++) {
        const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
        dp[i][j] = Math.min(
          dp[i - 1][j] + 1,
          dp[i][j - 1] + 1,
          dp[i - 1][j - 1] + cost,
        );
      }
    }
    return dp[len1][len2];
  }
 
  // ────────────────────────────────────────────────────────────────
  // REVIEW DUPLICATES
  // ────────────────────────────────────────────────────────────────
 
  async listCandidates(
    definitionKey: string,
    status = 'pending',
    page = 1,
    limit = 20,
  ): Promise<{ candidates: any[]; total: number }> {
    const query: any = { definitionKey, status };
    const [candidates, total] = await Promise.all([
      this.dupModel
        .find(query)
        .sort({ matchScore: -1 })
        .skip((page - 1) * limit)
        .limit(limit)
        .lean()
        .exec(),
      this.dupModel.countDocuments(query).exec(),
    ]);
    return { candidates, total };
  }
 
  async markFalsePositive(
    candidateId: string,
    reviewerId: string,
  ): Promise<void> {
    const candidate = await this.dupModel.findById(candidateId).exec();
    if (!candidate)
      throw new NotFoundException('Duplicate candidate not found');
    candidate.status = 'false_positive';
    candidate.reviewedBy = reviewerId as any;
    candidate.reviewedAt = new Date();
    await candidate.save();
  }
 
  // ────────────────────────────────────────────────────────────────
  // MERGE
  // ────────────────────────────────────────────────────────────────
 
  async requestMerge(params: {
    definitionKey: string;
    sourceRecordIds: string[];
    survivingRecordId: string;
    mergeStrategy?: any;
    requestedBy: string;
  }): Promise<any> {
    // Validate
    const surviving = await this.recordModel
      .findById(params.survivingRecordId)
      .lean()
      .exec();
    if (!surviving) throw new NotFoundException('Surviving record not found');
    if (surviving.systemManaged)
      throw new BadRequestException(
        'Cannot merge into a system-managed record',
      );
 
    const merge = await this.mergeModel.create({
      definitionKey: params.definitionKey,
      sourceRecordIds: params.sourceRecordIds.map(
        (id) => new Types.ObjectId(id),
      ),
      survivingRecordId: new Types.ObjectId(params.survivingRecordId),
      mergeStrategy: params.mergeStrategy,
      status: 'draft',
      requestedBy: params.requestedBy,
    });
 
    return merge.toObject();
  }
 
  async executeMerge(mergeRequestId: string, userId: string): Promise<any> {
    const merge = await this.mergeModel.findById(mergeRequestId).exec();
    if (!merge) throw new NotFoundException('Merge request not found');
    if (merge.status !== 'draft' && merge.status !== 'approved') {
      throw new BadRequestException(
        `Merge in status '${merge.status}' cannot be executed`,
      );
    }
 
    const surviving = await this.recordModel
      .findById(merge.survivingRecordId)
      .lean()
      .exec();
    if (!surviving)
      throw new BadRequestException('Surviving record no longer exists');
 
    // Archive source records and create aliases
    for (const sourceId of merge.sourceRecordIds) {
      const source = await this.recordModel.findById(sourceId).exec();
      if (!source) continue;
 
      // Create alias redirect
      await this.aliasModel.create({
        definitionKey: merge.definitionKey,
        aliasCode: source.recordCode,
        targetRecordId: merge.survivingRecordId,
        targetRecordCode: surviving.recordCode,
        aliasReason: 'merge',
        active: true,
      });
 
      // Archive the source
      source.status = 'archived';
      source.active = false;
      source.deletedAt = new Date();
      await source.save();
    }
 
    merge.status = 'completed';
    merge.completedAt = new Date();
    merge.mergeResult = {
      archivedCount: merge.sourceRecordIds.length,
      aliasesCreated: merge.sourceRecordIds.length,
      survivingRecordCode: surviving.recordCode,
    };
    await merge.save();
 
    // Update any duplicate candidates
    await this.dupModel.updateMany(
      {
        definitionKey: merge.definitionKey,
        $or: [
          { record1Id: { $in: merge.sourceRecordIds } },
          { record2Id: { $in: merge.sourceRecordIds } },
        ],
        status: { $in: ['pending', 'confirmed_duplicate'] },
      },
      { $set: { status: 'merged' } },
    );
 
    await this.eventBus.publish(
      'mdm.records.merged.v1',
      {
        definitionKey: merge.definitionKey,
        survivingRecordCode: surviving.recordCode,
        mergedRecordCount: merge.sourceRecordIds.length,
      },
      'SYSTEM',
    );
 
    this.logger.log(
      `Merge completed: ${merge.sourceRecordIds.length} records merged into ${surviving.recordCode}`,
    );
    return merge.toObject();
  }
}