diff --git a/apps/api/src/app/review/usecases/replace/replace.usecase.ts b/apps/api/src/app/review/usecases/replace/replace.usecase.ts index 31d410a9..fcb894d6 100644 --- a/apps/api/src/app/review/usecases/replace/replace.usecase.ts +++ b/apps/api/src/app/review/usecases/replace/replace.usecase.ts @@ -64,22 +64,32 @@ export class Replace { }, }; replaceOperation = { - $cond: { - if: { $eq: [formattedReplace, ''] }, - then: null, - else: { - $cond: { - if: { $eq: [{ $type: '$' + path }, 'number'] }, - then: { - $toDouble: { - $replaceAll: { - input: { $toString: '$' + path }, - find: find, - replacement: formattedReplace, - }, - }, + $let: { + vars: { + stringValue: { $toString: '$' + path }, + replacedValue: { + $replaceAll: { + input: { $toString: '$' + path }, + find: find, + replacement: { $toString: formattedReplace }, }, - else: formattedReplace, + }, + }, + in: { + $switch: { + branches: [ + // Case 1: No change + { case: { $eq: ['$$stringValue', '$$replacedValue'] }, then: `$${path}` }, + // Case 2: Result is empty + { case: { $eq: ['$$replacedValue', ''] }, then: null }, + // Case 3: Result is a valid number + { + case: { $regexMatch: { input: '$$replacedValue', regex: /^-?\d*\.?\d+$/ } }, + then: { $toDouble: '$$replacedValue' }, + }, + ], + // Default: Keep as string if not a valid number + default: '$$replacedValue', }, }, }, @@ -111,13 +121,19 @@ export class Replace { }, }); + // Update the 'updated' flag only if _oldRecord exists and the value has changed updateStages.push({ $set: { [`updated.${fieldName}`]: { $cond: { - if: { $ne: [`$record.${fieldName}`, `$_oldRecord.${fieldName}`] }, + if: { + $and: [ + { $ifNull: ['$_oldRecord', false] }, + { $ne: [`$record.${fieldName}`, `$_oldRecord.${fieldName}`] }, + ], + }, then: true, - else: '$$REMOVE', + else: { $ifNull: [`$updated.${fieldName}`, '$$REMOVE'] }, }, }, },