fix: update services

This commit is contained in:
yassinedorbozgithub 2025-06-12 11:27:07 +01:00
parent 8cff20c861
commit d067a0ffa4
3 changed files with 95 additions and 59 deletions

View File

@ -21,7 +21,9 @@ import { PluginType } from '@/plugins/types';
import { SettingService } from '@/setting/services/setting.service'; import { SettingService } from '@/setting/services/setting.service';
import { FALLBACK_DEFAULT_NLU_PENALTY_FACTOR } from '@/utils/constants/nlp'; import { FALLBACK_DEFAULT_NLU_PENALTY_FACTOR } from '@/utils/constants/nlp';
import { BaseService } from '@/utils/generics/base-service'; import { BaseService } from '@/utils/generics/base-service';
import { getCriteriaIds } from '@/utils/helpers/criteria';
import { getRandomElement } from '@/utils/helpers/safeRandom'; import { getRandomElement } from '@/utils/helpers/safeRandom';
import { TFilterQuery } from '@/utils/types/filter.types';
import { BlockDto } from '../dto/block.dto'; import { BlockDto } from '../dto/block.dto';
import { EnvelopeFactory } from '../helpers/envelope-factory'; import { EnvelopeFactory } from '../helpers/envelope-factory';
@ -778,28 +780,26 @@ export class BlockService extends BaseService<
/** /**
* Updates the `trigger_labels` and `assign_labels` fields of a block when a label is deleted. * Updates the `trigger_labels` and `assign_labels` fields of a block when a label is deleted.
* *
*
* This method removes the deleted label from the `trigger_labels` and `assign_labels` fields of all blocks that have the label. * This method removes the deleted label from the `trigger_labels` and `assign_labels` fields of all blocks that have the label.
* *
* @param label The label that is being deleted. * @param label The label that is being deleted.
*/ */
@OnEvent('hook:label:delete') @OnEvent('hook:label:preDelete')
async handleLabelDelete(labels: Label[]) { async handleLabelDelete(_query: unknown, criteria: TFilterQuery<Label>) {
const blocks = await this.find({ const ids = getCriteriaIds(criteria);
await this.getRepository().model.updateMany(
{
$or: [ $or: [
{ trigger_labels: { $in: labels.map((l) => l.id) } }, { trigger_labels: { $in: ids } },
{ assign_labels: { $in: labels.map((l) => l.id) } }, { assign_labels: { $in: ids } },
], ],
}); },
{
for (const block of blocks) { $pull: {
const trigger_labels = block.trigger_labels.filter( trigger_labels: { $in: ids },
(labelId) => !labels.find((l) => l.id === labelId), assign_labels: { $in: ids },
},
},
); );
const assign_labels = block.assign_labels.filter(
(labelId) => !labels.find((l) => l.id === labelId),
);
await this.updateOne(block.id, { trigger_labels, assign_labels });
}
} }
} }

View File

@ -24,6 +24,8 @@ import {
} from '@/attachment/types'; } from '@/attachment/types';
import { config } from '@/config'; import { config } from '@/config';
import { BaseService } from '@/utils/generics/base-service'; import { BaseService } from '@/utils/generics/base-service';
import { getCriteriaIds } from '@/utils/helpers/criteria';
import { TFilterQuery } from '@/utils/types/filter.types';
import { import {
SocketGet, SocketGet,
SocketPost, SocketPost,
@ -260,22 +262,22 @@ export class SubscriberService extends BaseService<
} }
/** /**
* Updates the `labels` field of a subscriber when a label is deleted. * Before deleting a `Label`, this method updates the `labels` field of a subscriber.
* *
* This method removes the deleted label from the `labels` field of all subscribers that have the label. * @param _query - The Mongoose query object used for deletion.
* @param criteria - The filter criteria for finding the labels to be deleted.
* *
* @param label The label that is being deleted. * @returns {Promise<void>} A promise that resolves once the event is emitted.
*/ */
@OnEvent('hook:label:delete') @OnEvent('hook:label:preDelete')
async handleLabelDelete(labels: Label[]) { async handleLabelDelete(
const subscribers = await this.find({ _query: unknown,
labels: { $in: labels.map((l) => l.id) }, criteria: TFilterQuery<Label>,
}); ): Promise<void> {
for (const subscriber of subscribers) { const ids = getCriteriaIds(criteria);
const updatedLabels = subscriber.labels.filter( await this.getRepository().model.updateMany(
(label) => !labels.find((l) => l.id === label), { labels: { $in: ids } },
{ $pull: { labels: { $in: ids } } },
); );
await this.updateOne(subscriber.id, { labels: updatedLabels });
}
} }
} }

View File

@ -12,11 +12,13 @@ import { OnEvent } from '@nestjs/event-emitter';
import { HelperService } from '@/helper/helper.service'; import { HelperService } from '@/helper/helper.service';
import { HelperType, NLU } from '@/helper/types'; import { HelperType, NLU } from '@/helper/types';
import { LoggerService } from '@/logger/logger.service'; import { LoggerService } from '@/logger/logger.service';
import { TFilterQuery } from '@/utils/types/filter.types';
import { NlpEntity, NlpEntityDocument } from '../schemas/nlp-entity.schema'; import { NlpEntity, NlpEntityDocument } from '../schemas/nlp-entity.schema';
import { NlpValue, NlpValueDocument } from '../schemas/nlp-value.schema'; import { NlpValue, NlpValueDocument } from '../schemas/nlp-value.schema';
import { NlpEntityService } from './nlp-entity.service'; import { NlpEntityService } from './nlp-entity.service';
import { NlpSampleEntityService } from './nlp-sample-entity.service';
import { NlpSampleService } from './nlp-sample.service'; import { NlpSampleService } from './nlp-sample.service';
import { NlpValueService } from './nlp-value.service'; import { NlpValueService } from './nlp-value.service';
@ -28,6 +30,7 @@ export class NlpService {
protected readonly nlpEntityService: NlpEntityService, protected readonly nlpEntityService: NlpEntityService,
protected readonly nlpValueService: NlpValueService, protected readonly nlpValueService: NlpValueService,
protected readonly helperService: HelperService, protected readonly helperService: HelperService,
protected readonly nlpSampleEntityService: NlpSampleEntityService,
) {} ) {}
/** /**
@ -106,22 +109,36 @@ export class NlpService {
* *
* @param entity - The NLP entity to be deleted. * @param entity - The NLP entity to be deleted.
*/ */
@OnEvent('hook:nlpEntity:delete') @OnEvent('hook:nlpEntity:preDelete')
async handleEntityDelete(entity: NlpEntity) { async handleEntityDelete(_query: unknown, criteria: TFilterQuery<NlpValue>) {
if (criteria._id) {
await this.nlpValueService.deleteMany({ entity: criteria._id });
await this.nlpSampleEntityService.deleteMany({ entity: criteria._id });
const entities = await this.nlpEntityService.find({
...(typeof criteria === 'string' ? { _id: criteria } : criteria),
builtin: false,
});
const helper = await this.helperService.getDefaultHelper(HelperType.NLU);
for (const entity of entities) {
// Synchonize new entity with NLP provider // Synchonize new entity with NLP provider
try { try {
if (entity.foreign_id) { if (entity.foreign_id) {
const helper = await this.helperService.getDefaultNluHelper();
await helper.deleteEntity(entity.foreign_id); await helper.deleteEntity(entity.foreign_id);
this.logger.debug('Deleted entity successfully synced!', entity); this.logger.debug('Deleted entity successfully synced!', entity);
} else { } else {
this.logger.error(`Entity ${entity} is missing foreign_id`); this.logger.error(`Entity ${entity} is missing foreign_id`);
throw new NotFoundException(`Entity ${entity} is missing foreign_id`); throw new NotFoundException(
`Entity ${entity} is missing foreign_id`,
);
} }
} catch (err) { } catch (err) {
this.logger.error('Unable to sync deleted entity', err); this.logger.error('Unable to sync deleted entity', err);
} }
} }
}
}
/** /**
* Handles the event triggered when a new NLP value is created. Synchronizes the value with the external NLP provider. * Handles the event triggered when a new NLP value is created. Synchronizes the value with the external NLP provider.
@ -168,11 +185,22 @@ export class NlpService {
* *
* @param value - The NLP value to be deleted. * @param value - The NLP value to be deleted.
*/ */
@OnEvent('hook:nlpValue:delete') @OnEvent('hook:nlpValue:preDelete')
async handleValueDelete(value: NlpValue) { async handleValueDelete(_query: unknown, criteria: TFilterQuery<NlpValue>) {
if (criteria._id) {
await this.nlpSampleEntityService.deleteMany({
value: criteria._id,
});
const values = await this.nlpValueService.find({
...(typeof criteria === 'string' ? { _id: criteria } : criteria),
builtin: false,
});
const helper = await this.helperService.getDefaultHelper(HelperType.NLU);
for (const value of values) {
// Synchonize new value with NLP provider // Synchonize new value with NLP provider
try { try {
const helper = await this.helperService.getDefaultNluHelper();
const populatedValue = await this.nlpValueService.findOneAndPopulate( const populatedValue = await this.nlpValueService.findOneAndPopulate(
value.id, value.id,
); );
@ -184,4 +212,10 @@ export class NlpService {
this.logger.error('Unable to sync deleted value', err); this.logger.error('Unable to sync deleted value', err);
} }
} }
} else if (criteria.entity) {
// Do nothing : cascading deletes coming from Nlp Sample Entity
} else {
throw new Error('Attempted to delete a NLP value using unknown criteria');
}
}
} }