Merge branch 'main' into 754-issue---frontend-packages-vulnerabilities-issue

This commit is contained in:
yassinedorbozgithub
2025-06-24 06:39:53 +01:00
99 changed files with 1755 additions and 3365 deletions

View File

@@ -6,8 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import {
botstatsFixtures,
installBotStatsFixtures,
@@ -18,9 +16,7 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { BotStatsRepository } from '../repositories/bot-stats.repository';
import { BotStatsModel, BotStatsType } from '../schemas/bot-stats.schema';
import { BotStatsService } from '../services/bot-stats.service';
import { BotStatsType } from '../schemas/bot-stats.schema';
import { BotStatsController } from './bot-stats.controller';
@@ -29,12 +25,9 @@ describe('BotStatsController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [BotStatsController],
imports: [
rootMongooseTestModule(installBotStatsFixtures),
MongooseModule.forFeature([BotStatsModel]),
],
providers: [BotStatsService, BotStatsRepository],
imports: [rootMongooseTestModule(installBotStatsFixtures)],
});
[botStatsController] = await getMocks([BotStatsController]);
});

View File

@@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { getModelToken, MongooseModule } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
@@ -19,11 +19,7 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import {
BotStats,
BotStatsModel,
BotStatsType,
} from '../schemas/bot-stats.schema';
import { BotStats, BotStatsType } from '../schemas/bot-stats.schema';
import { BotStatsRepository } from './bot-stats.repository';
@@ -33,10 +29,8 @@ describe('BotStatsRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installBotStatsFixtures),
MongooseModule.forFeature([BotStatsModel]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installBotStatsFixtures)],
providers: [BotStatsRepository],
});
[botStatsRepository, botStatsModel] = await getMocks([

View File

@@ -6,8 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import {
botstatsFixtures,
installBotStatsFixtures,
@@ -18,8 +16,7 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { BotStatsRepository } from '../repositories/bot-stats.repository';
import { BotStatsModel, BotStatsType } from '../schemas/bot-stats.schema';
import { BotStatsType } from '../schemas/bot-stats.schema';
import { BotStatsService } from './bot-stats.service';
@@ -28,11 +25,9 @@ describe('BotStatsService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installBotStatsFixtures),
MongooseModule.forFeature([BotStatsModel]),
],
providers: [BotStatsService, BotStatsRepository],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installBotStatsFixtures)],
providers: [BotStatsService],
});
[botStatsService] = await getMocks([BotStatsService]);
});

View File

@@ -8,26 +8,17 @@
import fs from 'fs';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import {
BadRequestException,
MethodNotAllowedException,
} from '@nestjs/common/exceptions';
import { NotFoundException } from '@nestjs/common/exceptions/not-found.exception';
import { MongooseModule } from '@nestjs/mongoose';
import { Request } from 'express';
import LocalStorageHelper from '@/extensions/helpers/local-storage/index.helper';
import { HelperService } from '@/helper/helper.service';
import { LoggerService } from '@/logger/logger.service';
import { SettingRepository } from '@/setting/repositories/setting.repository';
import { SettingModel } from '@/setting/schemas/setting.schema';
import { SettingSeeder } from '@/setting/seeds/setting.seed';
import { SettingService } from '@/setting/services/setting.service';
import { ModelRepository } from '@/user/repositories/model.repository';
import { PermissionRepository } from '@/user/repositories/permission.repository';
import { ModelModel } from '@/user/schemas/model.schema';
import { PermissionModel } from '@/user/schemas/permission.schema';
import { ModelService } from '@/user/services/model.service';
import { PermissionService } from '@/user/services/permission.service';
import { NOT_FOUND_ID } from '@/utils/constants/mock';
@@ -44,8 +35,7 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { attachment, attachmentFile } from '../mocks/attachment.mock';
import { AttachmentRepository } from '../repositories/attachment.repository';
import { Attachment, AttachmentModel } from '../schemas/attachment.schema';
import { Attachment } from '../schemas/attachment.schema';
import { AttachmentService } from '../services/attachment.service';
import {
AttachmentAccess,
@@ -64,39 +54,15 @@ describe('AttachmentController', () => {
beforeAll(async () => {
const { getMocks, resolveMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers', 'providers'],
controllers: [AttachmentController],
imports: [
rootMongooseTestModule(async () => {
await installSettingFixtures();
await installAttachmentFixtures();
}),
MongooseModule.forFeature([
AttachmentModel,
PermissionModel,
ModelModel,
SettingModel,
]),
],
providers: [
AttachmentService,
AttachmentRepository,
PermissionService,
PermissionRepository,
SettingRepository,
ModelService,
ModelRepository,
SettingSeeder,
SettingService,
HelperService,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
providers: [PermissionService, ModelService],
});
[attachmentController, attachmentService, helperService, settingService] =
await getMocks([

View File

@@ -8,7 +8,7 @@
import { Readable, Stream } from 'stream';
import { Injectable, Optional, StreamableFile } from '@nestjs/common';
import { Injectable, StreamableFile } from '@nestjs/common';
import { HelperService } from '@/helper/helper.service';
import { HelperType } from '@/helper/types';
@@ -22,7 +22,7 @@ import { Attachment } from '../schemas/attachment.schema';
export class AttachmentService extends BaseService<Attachment> {
constructor(
readonly repository: AttachmentRepository,
@Optional() private readonly helperService: HelperService,
private readonly helperService: HelperService,
) {
super(repository);
}

View File

@@ -92,7 +92,6 @@ export const isAttachmentResourceRef = (
): resourceRef is AttachmentResourceRef => {
return Object.values(AttachmentResourceRef).includes(resourceRef);
};
AttachmentResourceRef;
/**
* Checks if the given list is an array of TAttachmentResourceRef.

View File

@@ -6,34 +6,9 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { NotFoundException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { ContentRepository } from '@/cms/repositories/content.repository';
import { ContentModel } from '@/cms/schemas/content.schema';
import { ContentService } from '@/cms/services/content.service';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { LanguageModel } from '@/i18n/schemas/language.schema';
import { I18nService } from '@/i18n/services/i18n.service';
import { LanguageService } from '@/i18n/services/language.service';
import { NlpService } from '@/nlp/services/nlp.service';
import { PluginService } from '@/plugins/plugins.service';
import { SettingService } from '@/setting/services/setting.service';
import { InvitationRepository } from '@/user/repositories/invitation.repository';
import { PermissionRepository } from '@/user/repositories/permission.repository';
import { RoleRepository } from '@/user/repositories/role.repository';
import { UserRepository } from '@/user/repositories/user.repository';
import { InvitationModel } from '@/user/schemas/invitation.schema';
import { PermissionModel } from '@/user/schemas/permission.schema';
import { RoleModel } from '@/user/schemas/role.schema';
import { UserModel } from '@/user/schemas/user.schema';
import { PermissionService } from '@/user/services/permission.service';
import { RoleService } from '@/user/services/role.service';
import { UserService } from '@/user/services/user.service';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import { getUpdateOneError } from '@/utils/test/errors/messages';
import {
@@ -47,17 +22,12 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { BlockCreateDto, BlockUpdateDto } from '../dto/block.dto';
import { BlockRepository } from '../repositories/block.repository';
import { CategoryRepository } from '../repositories/category.repository';
import { LabelRepository } from '../repositories/label.repository';
import { Block, BlockModel } from '../schemas/block.schema';
import { LabelModel } from '../schemas/label.schema';
import { Block } from '../schemas/block.schema';
import { PayloadType } from '../schemas/types/button';
import { BlockService } from '../services/block.service';
import { CategoryService } from '../services/category.service';
import { LabelService } from '../services/label.service';
import { Category, CategoryModel } from './../schemas/category.schema';
import { Category } from './../schemas/category.schema';
import { BlockController } from './block.controller';
describe('BlockController', () => {
@@ -80,70 +50,16 @@ describe('BlockController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [BlockController],
imports: [
rootMongooseTestModule(installBlockFixtures),
MongooseModule.forFeature([
BlockModel,
LabelModel,
CategoryModel,
ContentModel,
InvitationModel,
AttachmentModel,
UserModel,
RoleModel,
PermissionModel,
LanguageModel,
]),
],
imports: [rootMongooseTestModule(installBlockFixtures)],
providers: [
BlockRepository,
LabelRepository,
CategoryRepository,
ContentRepository,
AttachmentRepository,
UserRepository,
RoleRepository,
PermissionRepository,
InvitationRepository,
LanguageRepository,
BlockService,
LabelService,
CategoryService,
ContentService,
AttachmentService,
UserService,
RoleService,
PermissionService,
LanguageService,
PluginService,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: SettingService,
useValue: {
getConfig: jest.fn(() => ({
chatbot: { lang: { default: 'fr' } },
})),
getSettings: jest.fn(() => ({})),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
{
provide: NlpService,
useValue: {},
},
],
});
[blockController, blockService, categoryService] = await getMocks([

View File

@@ -7,17 +7,8 @@
*/
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { ContentRepository } from '@/cms/repositories/content.repository';
import { ContentModel } from '@/cms/schemas/content.schema';
import { ContentService } from '@/cms/services/content.service';
import { I18nService } from '@/i18n/services/i18n.service';
import { PluginService } from '@/plugins/plugins.service';
import { SettingService } from '@/setting/services/setting.service';
import {
categoryFixtures,
installCategoryFixtures,
@@ -31,14 +22,9 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { CategoryCreateDto, CategoryUpdateDto } from '../dto/category.dto';
import { BlockRepository } from '../repositories/block.repository';
import { CategoryRepository } from '../repositories/category.repository';
import { BlockModel } from '../schemas/block.schema';
import { LabelModel } from '../schemas/label.schema';
import { BlockService } from '../services/block.service';
import { CategoryService } from '../services/category.service';
import { Category, CategoryModel } from './../schemas/category.schema';
import { Category } from './../schemas/category.schema';
import { CategoryController } from './category.controller';
describe('CategoryController', () => {
@@ -49,51 +35,16 @@ describe('CategoryController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [CategoryController],
imports: [
rootMongooseTestModule(installCategoryFixtures),
MongooseModule.forFeature([
BlockModel,
LabelModel,
CategoryModel,
ContentModel,
AttachmentModel,
]),
],
imports: [rootMongooseTestModule(installCategoryFixtures)],
providers: [
BlockRepository,
CategoryRepository,
ContentRepository,
AttachmentRepository,
BlockService,
CategoryService,
ContentService,
AttachmentService,
{
provide: PluginService,
useValue: {},
},
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: SettingService,
useValue: {
getConfig: jest.fn(() => ({
chatbot: { lang: { default: 'fr' } },
})),
getSettings: jest.fn(() => ({})),
},
},
{
provide: BlockService,
useValue: {
findOne: jest.fn(),
},
},
],
});
[categoryService, categoryController] = await getMocks([

View File

@@ -7,8 +7,8 @@
*/
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { I18nService } from '@/i18n/services/i18n.service';
import { getUpdateOneError } from '@/utils/test/errors/messages';
import {
contextVarFixtures,
@@ -26,8 +26,7 @@ import {
ContextVarCreateDto,
ContextVarUpdateDto,
} from '../dto/context-var.dto';
import { ContextVarRepository } from '../repositories/context-var.repository';
import { ContextVar, ContextVarModel } from '../schemas/context-var.schema';
import { ContextVar } from '../schemas/context-var.schema';
import { ContextVarService } from '../services/context-var.service';
import { ContextVarController } from './context-var.controller';
@@ -40,12 +39,17 @@ describe('ContextVarController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [ContextVarController],
imports: [
rootMongooseTestModule(installContextVarFixtures),
MongooseModule.forFeature([ContextVarModel]),
imports: [rootMongooseTestModule(installContextVarFixtures)],
providers: [
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
],
providers: [ContextVarService, ContextVarRepository],
});
[contextVarController, contextVarService] = await getMocks([
ContextVarController,

View File

@@ -7,20 +7,7 @@
*/
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { InvitationRepository } from '@/user/repositories/invitation.repository';
import { RoleRepository } from '@/user/repositories/role.repository';
import { UserRepository } from '@/user/repositories/user.repository';
import { InvitationModel } from '@/user/schemas/invitation.schema';
import { PermissionModel } from '@/user/schemas/permission.schema';
import { RoleModel } from '@/user/schemas/role.schema';
import { UserModel } from '@/user/schemas/user.schema';
import { RoleService } from '@/user/services/role.service';
import { UserService } from '@/user/services/user.service';
import { NOT_FOUND_ID } from '@/utils/constants/mock';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import { getUpdateOneError } from '@/utils/test/errors/messages';
@@ -35,10 +22,7 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { LabelCreateDto, LabelUpdateDto } from '../dto/label.dto';
import { LabelRepository } from '../repositories/label.repository';
import { SubscriberRepository } from '../repositories/subscriber.repository';
import { Label, LabelModel } from '../schemas/label.schema';
import { SubscriberModel } from '../schemas/subscriber.schema';
import { Label } from '../schemas/label.schema';
import { LabelService } from '../services/label.service';
import { SubscriberService } from '../services/subscriber.service';
@@ -54,33 +38,10 @@ describe('LabelController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers', 'providers'],
controllers: [LabelController],
imports: [
rootMongooseTestModule(installSubscriberFixtures),
MongooseModule.forFeature([
LabelModel,
UserModel,
RoleModel,
PermissionModel,
SubscriberModel,
InvitationModel,
AttachmentModel,
]),
],
providers: [
LabelController,
LabelService,
LabelRepository,
UserService,
UserRepository,
RoleService,
RoleRepository,
InvitationRepository,
SubscriberService,
SubscriberRepository,
AttachmentService,
AttachmentRepository,
],
imports: [rootMongooseTestModule(installSubscriberFixtures)],
providers: [SubscriberService],
});
[labelService, subscriberService, labelController] = await getMocks([
LabelService,

View File

@@ -6,27 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { ChannelService } from '@/channel/channel.service';
import { MenuRepository } from '@/cms/repositories/menu.repository';
import { MenuModel } from '@/cms/schemas/menu.schema';
import { MenuService } from '@/cms/services/menu.service';
import { I18nService } from '@/i18n/services/i18n.service';
import { NlpService } from '@/nlp/services/nlp.service';
import { SettingService } from '@/setting/services/setting.service';
import { InvitationRepository } from '@/user/repositories/invitation.repository';
import { RoleRepository } from '@/user/repositories/role.repository';
import { UserRepository } from '@/user/repositories/user.repository';
import { InvitationModel } from '@/user/schemas/invitation.schema';
import { PermissionModel } from '@/user/schemas/permission.schema';
import { RoleModel } from '@/user/schemas/role.schema';
import { User, UserModel } from '@/user/schemas/user.schema';
import { RoleService } from '@/user/services/role.service';
import { User } from '@/user/schemas/user.schema';
import { UserService } from '@/user/services/user.service';
import {
installMessageFixtures,
@@ -39,10 +19,8 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { MessageRepository } from '../repositories/message.repository';
import { SubscriberRepository } from '../repositories/subscriber.repository';
import { Message, MessageModel } from '../schemas/message.schema';
import { Subscriber, SubscriberModel } from '../schemas/subscriber.schema';
import { Message } from '../schemas/message.schema';
import { Subscriber } from '../schemas/subscriber.schema';
import { MessageService } from '../services/message.service';
import { SubscriberService } from '../services/subscriber.service';
@@ -63,66 +41,10 @@ describe('MessageController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers', 'providers'],
controllers: [MessageController],
imports: [
rootMongooseTestModule(installMessageFixtures),
MongooseModule.forFeature([
SubscriberModel,
MessageModel,
UserModel,
RoleModel,
InvitationModel,
PermissionModel,
AttachmentModel,
MenuModel,
]),
],
providers: [
MessageController,
MessageRepository,
MessageService,
SubscriberService,
UserService,
UserRepository,
RoleService,
RoleRepository,
InvitationRepository,
SubscriberRepository,
ChannelService,
AttachmentService,
AttachmentRepository,
MenuService,
MenuRepository,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: NlpService,
useValue: {
getNLP: jest.fn(() => undefined),
},
},
{
provide: SettingService,
useValue: {
getConfig: jest.fn(() => ({
chatbot: { lang: { default: 'fr' } },
})),
getSettings: jest.fn(() => ({})),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
imports: [rootMongooseTestModule(installMessageFixtures)],
providers: [UserService],
});
[messageService, userService, subscriberService, messageController] =
await getMocks([

View File

@@ -6,19 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { InvitationRepository } from '@/user/repositories/invitation.repository';
import { RoleRepository } from '@/user/repositories/role.repository';
import { UserRepository } from '@/user/repositories/user.repository';
import { InvitationModel } from '@/user/schemas/invitation.schema';
import { PermissionModel } from '@/user/schemas/permission.schema';
import { RoleModel } from '@/user/schemas/role.schema';
import { User, UserModel } from '@/user/schemas/user.schema';
import { RoleService } from '@/user/services/role.service';
import { User } from '@/user/schemas/user.schema';
import {
installSubscriberFixtures,
subscriberFixtures,
@@ -30,13 +18,9 @@ import {
rootMongooseTestModule,
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { SocketEventDispatcherService } from '@/websocket/services/socket-event-dispatcher.service';
import { WebsocketGateway } from '@/websocket/websocket.gateway';
import { LabelRepository } from '../repositories/label.repository';
import { SubscriberRepository } from '../repositories/subscriber.repository';
import { Label, LabelModel } from '../schemas/label.schema';
import { Subscriber, SubscriberModel } from '../schemas/subscriber.schema';
import { Label } from '../schemas/label.schema';
import { Subscriber } from '../schemas/subscriber.schema';
import { SubscriberService } from '../services/subscriber.service';
import { UserService } from './../../user/services/user.service';
@@ -55,34 +39,10 @@ describe('SubscriberController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers', 'providers'],
controllers: [SubscriberController],
imports: [
rootMongooseTestModule(installSubscriberFixtures),
MongooseModule.forFeature([
SubscriberModel,
LabelModel,
UserModel,
RoleModel,
InvitationModel,
PermissionModel,
AttachmentModel,
]),
],
providers: [
SubscriberRepository,
SubscriberService,
LabelService,
LabelRepository,
UserService,
WebsocketGateway,
SocketEventDispatcherService,
UserRepository,
RoleService,
RoleRepository,
InvitationRepository,
AttachmentService,
AttachmentRepository,
],
imports: [rootMongooseTestModule(installSubscriberFixtures)],
providers: [LabelService, UserService],
});
[subscriberService, labelService, userService, subscriberController] =
await getMocks([

View File

@@ -6,9 +6,10 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { I18nService } from '@/i18n/services/i18n.service';
import {
blockFixtures,
installBlockFixtures,
@@ -19,9 +20,8 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { Block, BlockModel } from '../schemas/block.schema';
import { Category, CategoryModel } from '../schemas/category.schema';
import { LabelModel } from '../schemas/label.schema';
import { Block } from '../schemas/block.schema';
import { Category } from '../schemas/category.schema';
import { BlockRepository } from './block.repository';
import { CategoryRepository } from './category.repository';
@@ -39,11 +39,19 @@ describe('BlockRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installBlockFixtures),
MongooseModule.forFeature([BlockModel, CategoryModel, LabelModel]),
models: ['LabelModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installBlockFixtures)],
providers: [
BlockRepository,
CategoryRepository,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
],
providers: [BlockRepository, CategoryRepository],
});
[blockRepository, categoryRepository, blockModel] = await getMocks([
BlockRepository,

View File

@@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { ForbiddenException, Injectable, Optional } from '@nestjs/common';
import { ForbiddenException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Document, Model, Query } from 'mongoose';
@@ -24,14 +24,11 @@ export class CategoryRepository extends BaseRepository<
never,
CategoryDto
> {
private readonly blockService: BlockService;
constructor(
@InjectModel(Category.name) readonly model: Model<Category>,
@Optional() blockService?: BlockService,
private readonly blockService: BlockService,
) {
super(model, Category);
this.blockService = blockService!;
}
/**
@@ -42,7 +39,7 @@ export class CategoryRepository extends BaseRepository<
* @param criteria - The filter criteria for finding blocks to delete.
*/
async preDelete(
query: Query<
_query: Query<
DeleteResult,
Document<Category, any, any>,
unknown,
@@ -51,23 +48,18 @@ export class CategoryRepository extends BaseRepository<
>,
criteria: TFilterQuery<Category>,
) {
criteria = query.getQuery();
const ids = Array.isArray(criteria._id?.$in)
? criteria._id.$in
: Array.isArray(criteria._id)
? criteria._id
: [criteria._id];
for (const id of ids) {
const associatedBlocks = await this.blockService.findOne({
category: id,
if (criteria._id) {
const block = await this.blockService.findOneAndPopulate({
category: criteria._id,
});
if (associatedBlocks) {
const category = await this.findOne({ _id: id });
if (block) {
throw new ForbiddenException(
`Category ${category?.label || id} has blocks associated with it`,
`Category ${block.category?.label} has at least one associated block`,
);
}
} else {
throw new Error('Attempted to delete category using unknown criteria');
}
}
}

View File

@@ -10,7 +10,6 @@ import {
ForbiddenException,
Injectable,
NotFoundException,
Optional,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Document, Model, Query } from 'mongoose';
@@ -29,14 +28,11 @@ export class ContextVarRepository extends BaseRepository<
never,
ContextVarDto
> {
private readonly blockService: BlockService;
constructor(
@InjectModel(ContextVar.name) readonly model: Model<ContextVar>,
@Optional() blockService?: BlockService,
private readonly blockService: BlockService,
) {
super(model, ContextVar);
if (blockService) this.blockService = blockService;
}
/**
@@ -65,7 +61,7 @@ export class ContextVarRepository extends BaseRepository<
throw new NotFoundException(`Context var with ID ${id} not found.`);
}
const associatedBlocks = await this.blockService?.find({
const associatedBlocks = await this.blockService.find({
capture_vars: { $elemMatch: { context_var: contextVar.name } },
});

View File

@@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { labelFixtures } from '@/utils/test/fixtures/label';
@@ -19,8 +19,8 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { Label, LabelFull, LabelModel } from '../schemas/label.schema';
import { Subscriber, SubscriberModel } from '../schemas/subscriber.schema';
import { Label, LabelFull } from '../schemas/label.schema';
import { Subscriber } from '../schemas/subscriber.schema';
import { LabelRepository } from './label.repository';
import { SubscriberRepository } from './subscriber.repository';
@@ -33,10 +33,8 @@ describe('LabelRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installSubscriberFixtures),
MongooseModule.forFeature([LabelModel, SubscriberModel]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installSubscriberFixtures)],
providers: [LabelRepository, SubscriberRepository],
});
[labelRepository, subscriberRepository, labelModel] = await getMocks([

View File

@@ -8,16 +8,14 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Document, Model, Query } from 'mongoose';
import { Model } from 'mongoose';
import { BaseRepository, DeleteResult } from '@/utils/generics/base-repository';
import { TFilterQuery } from '@/utils/types/filter.types';
import { BaseRepository } from '@/utils/generics/base-repository';
import { LabelDto } from '../dto/label.dto';
import {
Label,
LABEL_POPULATE,
LabelDocument,
LabelFull,
LabelPopulate,
} from '../schemas/label.schema';
@@ -32,59 +30,4 @@ export class LabelRepository extends BaseRepository<
constructor(@InjectModel(Label.name) readonly model: Model<Label>) {
super(model, Label, LABEL_POPULATE, LabelFull);
}
/**
* After creating a `Label`, this method emits an event and updates the `label_id` field.
*
* @param created - The created label document instance.
*
* @returns A promise that resolves when the update operation is complete.
*/
async postCreate(created: LabelDocument): Promise<void> {
this.eventEmitter.emit(
'hook:label:create',
created,
async (result: Record<string, any>) => {
await this.model.updateOne(
{ _id: created._id },
{
$set: {
label_id: {
...(created.label_id || {}),
...result,
},
},
},
);
},
);
}
/**
* Before deleting a label, this method fetches the label(s) based on the given criteria and emits a delete event.
*
* @param query - The Mongoose query object used for deletion.
* @param criteria - The filter criteria for finding the labels to be deleted.
*
* @returns {Promise<void>} A promise that resolves once the event is emitted.
*/
async preDelete(
_query: Query<
DeleteResult,
Document<Label, any, any>,
unknown,
Label,
'deleteOne' | 'deleteMany'
>,
_criteria: TFilterQuery<Label>,
): Promise<void> {
const ids = Array.isArray(_criteria._id?.$in)
? _criteria._id.$in
: Array.isArray(_criteria._id)
? _criteria._id
: [_criteria._id];
const labels = await this.find({ _id: { $in: ids } });
this.eventEmitter.emit('hook:label:delete', labels);
}
}

View File

@@ -6,11 +6,10 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { UserRepository } from '@/user/repositories/user.repository';
import { UserModel } from '@/user/schemas/user.schema';
import {
installMessageFixtures,
messageFixtures,
@@ -22,8 +21,7 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { Message, MessageModel } from '../schemas/message.schema';
import { SubscriberModel } from '../schemas/subscriber.schema';
import { Message } from '../schemas/message.schema';
import { AnyMessage } from '../schemas/types/message';
import { MessageRepository } from './message.repository';
@@ -37,10 +35,8 @@ describe('MessageRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installMessageFixtures),
MongooseModule.forFeature([MessageModel, SubscriberModel, UserModel]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installMessageFixtures)],
providers: [MessageRepository, SubscriberRepository, UserRepository],
});
[messageRepository, userRepository, subscriberRepository, messageModel] =

View File

@@ -6,17 +6,13 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import {
Attachment,
AttachmentModel,
} from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { Attachment } from '@/attachment/schemas/attachment.schema';
import { UserRepository } from '@/user/repositories/user.repository';
import { User, UserModel } from '@/user/schemas/user.schema';
import { User } from '@/user/schemas/user.schema';
import {
installSubscriberFixtures,
subscriberFixtures,
@@ -29,12 +25,8 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { Label, LabelModel } from '../schemas/label.schema';
import {
Subscriber,
SubscriberFull,
SubscriberModel,
} from '../schemas/subscriber.schema';
import { Label } from '../schemas/label.schema';
import { Subscriber, SubscriberFull } from '../schemas/subscriber.schema';
import { LabelRepository } from './label.repository';
import { SubscriberRepository } from './subscriber.repository';
@@ -53,20 +45,12 @@ describe('SubscriberRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installSubscriberFixtures),
MongooseModule.forFeature([
SubscriberModel,
LabelModel,
UserModel,
AttachmentModel,
]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installSubscriberFixtures)],
providers: [
SubscriberRepository,
LabelRepository,
UserRepository,
AttachmentService,
AttachmentRepository,
],
});

View File

@@ -6,47 +6,19 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import {
subscriberWithLabels,
subscriberWithoutLabels,
} from '@/channel/lib/__test__/subscriber.mock';
import { ButtonType, PayloadType } from '@/chat/schemas/types/button';
import { ContentTypeRepository } from '@/cms/repositories/content-type.repository';
import { ContentRepository } from '@/cms/repositories/content.repository';
import { ContentTypeModel } from '@/cms/schemas/content-type.schema';
import { Content, ContentModel } from '@/cms/schemas/content.schema';
import { Content } from '@/cms/schemas/content.schema';
import { ContentTypeService } from '@/cms/services/content-type.service';
import { ContentService } from '@/cms/services/content.service';
import WebChannelHandler from '@/extensions/channels/web/index.channel';
import { WEB_CHANNEL_NAME } from '@/extensions/channels/web/settings';
import { Web } from '@/extensions/channels/web/types';
import WebEventWrapper from '@/extensions/channels/web/wrapper';
import { HelperService } from '@/helper/helper.service';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { LanguageModel } from '@/i18n/schemas/language.schema';
import { I18nService } from '@/i18n/services/i18n.service';
import { LanguageService } from '@/i18n/services/language.service';
import { NlpEntityRepository } from '@/nlp/repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '@/nlp/repositories/nlp-sample-entity.repository';
import { NlpSampleRepository } from '@/nlp/repositories/nlp-sample.repository';
import { NlpValueRepository } from '@/nlp/repositories/nlp-value.repository';
import { NlpEntityModel } from '@/nlp/schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '@/nlp/schemas/nlp-sample-entity.schema';
import { NlpSampleModel } from '@/nlp/schemas/nlp-sample.schema';
import { NlpValueModel } from '@/nlp/schemas/nlp-value.schema';
import { NlpEntityService } from '@/nlp/services/nlp-entity.service';
import { NlpSampleEntityService } from '@/nlp/services/nlp-sample-entity.service';
import { NlpSampleService } from '@/nlp/services/nlp-sample.service';
import { NlpValueService } from '@/nlp/services/nlp-value.service';
import { NlpService } from '@/nlp/services/nlp.service';
import { PluginService } from '@/plugins/plugins.service';
import { SettingService } from '@/setting/services/setting.service';
import { FALLBACK_DEFAULT_NLU_PENALTY_FACTOR } from '@/utils/constants/nlp';
import {
blockFixtures,
@@ -83,9 +55,8 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { BlockRepository } from '../repositories/block.repository';
import { Block, BlockFull, BlockModel } from '../schemas/block.schema';
import { Category, CategoryModel } from '../schemas/category.schema';
import { LabelModel } from '../schemas/label.schema';
import { Block, BlockFull } from '../schemas/block.schema';
import { Category } from '../schemas/category.schema';
import { Subscriber } from '../schemas/subscriber.schema';
import { FileType } from '../schemas/types/attachment';
import { Context } from '../schemas/types/context';
@@ -97,7 +68,6 @@ import { QuickReplyType } from '../schemas/types/quick-reply';
import { CategoryRepository } from './../repositories/category.repository';
import { BlockService } from './block.service';
import { CategoryService } from './category.service';
function makeMockBlock(overrides: Partial<Block>): Block {
return {
@@ -135,53 +105,19 @@ describe('BlockService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
models: ['LabelModel'],
autoInjectFrom: ['providers'],
imports: [
rootMongooseTestModule(async () => {
await installContentFixtures();
await installBlockFixtures();
await installNlpValueFixtures();
}),
MongooseModule.forFeature([
BlockModel,
CategoryModel,
ContentTypeModel,
ContentModel,
AttachmentModel,
LabelModel,
LanguageModel,
NlpEntityModel,
NlpSampleEntityModel,
NlpValueModel,
NlpSampleModel,
]),
],
providers: [
BlockRepository,
CategoryRepository,
ContentTypeRepository,
ContentRepository,
AttachmentRepository,
LanguageRepository,
BlockService,
CategoryService,
ContentTypeService,
ContentService,
AttachmentService,
LanguageService,
NlpEntityRepository,
NlpValueRepository,
NlpSampleRepository,
NlpSampleEntityRepository,
NlpEntityService,
NlpValueService,
NlpSampleService,
NlpSampleEntityService,
NlpService,
HelperService,
{
provide: PluginService,
useValue: {},
},
CategoryRepository,
{
provide: I18nService,
useValue: {
@@ -190,26 +126,6 @@ describe('BlockService', () => {
}),
},
},
{
provide: SettingService,
useValue: {
getConfig: jest.fn(() => ({
chatbot: { lang: { default: 'fr' } },
})),
getSettings: jest.fn(() => ({
contact: { company_name: 'Your company name' },
chatbot_settings: { default_nlu_penalty_factor: 0.95 },
})),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
});
[

View File

@@ -22,6 +22,7 @@ import { SettingService } from '@/setting/services/setting.service';
import { FALLBACK_DEFAULT_NLU_PENALTY_FACTOR } from '@/utils/constants/nlp';
import { BaseService } from '@/utils/generics/base-service';
import { getRandomElement } from '@/utils/helpers/safeRandom';
import { TFilterQuery } from '@/utils/types/filter.types';
import { getDefaultFallbackOptions } from '../constants/block';
import { BlockDto } from '../dto/block.dto';
@@ -790,28 +791,31 @@ export class BlockService extends BaseService<
/**
* 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.
*
* @param label The label that is being deleted.
* @param _query - The Mongoose query object used for deletion.
* @param criteria - The filter criteria for finding the labels to be deleted.
*/
@OnEvent('hook:label:delete')
async handleLabelDelete(labels: Label[]) {
const blocks = await this.find({
$or: [
{ trigger_labels: { $in: labels.map((l) => l.id) } },
{ assign_labels: { $in: labels.map((l) => l.id) } },
],
});
for (const block of blocks) {
const trigger_labels = block.trigger_labels.filter(
(labelId) => !labels.find((l) => l.id === labelId),
@OnEvent('hook:label:preDelete')
async handleLabelPreDelete(
_query: unknown,
criteria: TFilterQuery<Label>,
): Promise<void> {
if (criteria._id) {
await this.getRepository().model.updateMany(
{
$or: [
{ trigger_labels: criteria._id },
{ assign_labels: criteria._id },
],
},
{
$pull: {
trigger_labels: criteria._id,
assign_labels: criteria._id,
},
},
);
const assign_labels = block.assign_labels.filter(
(labelId) => !labels.find((l) => l.id === labelId),
);
await this.updateOne(block.id, { trigger_labels, assign_labels });
} else {
throw new Error('Attempted to delete label using unknown criteria');
}
}
}

View File

@@ -6,48 +6,14 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { JwtModule } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { JwtService } from '@nestjs/jwt';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { ChannelService } from '@/channel/channel.service';
import { ContentTypeRepository } from '@/cms/repositories/content-type.repository';
import { ContentRepository } from '@/cms/repositories/content.repository';
import { MenuRepository } from '@/cms/repositories/menu.repository';
import { ContentTypeModel } from '@/cms/schemas/content-type.schema';
import { ContentModel } from '@/cms/schemas/content.schema';
import { MenuModel } from '@/cms/schemas/menu.schema';
import { ContentTypeService } from '@/cms/services/content-type.service';
import { ContentService } from '@/cms/services/content.service';
import { MenuService } from '@/cms/services/menu.service';
import { webEventText } from '@/extensions/channels/web/__test__/events.mock';
import WebChannelHandler from '@/extensions/channels/web/index.channel';
import { WEB_CHANNEL_NAME } from '@/extensions/channels/web/settings';
import WebEventWrapper from '@/extensions/channels/web/wrapper';
import { HelperService } from '@/helper/helper.service';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { LanguageModel } from '@/i18n/schemas/language.schema';
import { I18nService } from '@/i18n/services/i18n.service';
import { LanguageService } from '@/i18n/services/language.service';
import { NlpEntityRepository } from '@/nlp/repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '@/nlp/repositories/nlp-sample-entity.repository';
import { NlpSampleRepository } from '@/nlp/repositories/nlp-sample.repository';
import { NlpValueRepository } from '@/nlp/repositories/nlp-value.repository';
import { NlpEntityModel } from '@/nlp/schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '@/nlp/schemas/nlp-sample-entity.schema';
import { NlpSampleModel } from '@/nlp/schemas/nlp-sample.schema';
import { NlpValueModel } from '@/nlp/schemas/nlp-value.schema';
import { NlpEntityService } from '@/nlp/services/nlp-entity.service';
import { NlpSampleEntityService } from '@/nlp/services/nlp-sample-entity.service';
import { NlpSampleService } from '@/nlp/services/nlp-sample.service';
import { NlpValueService } from '@/nlp/services/nlp-value.service';
import { NlpService } from '@/nlp/services/nlp.service';
import { PluginService } from '@/plugins/plugins.service';
import { SettingService } from '@/setting/services/setting.service';
import { installBlockFixtures } from '@/utils/test/fixtures/block';
import { installContentFixtures } from '@/utils/test/fixtures/content';
import { installSubscriberFixtures } from '@/utils/test/fixtures/subscriber';
@@ -63,33 +29,13 @@ import {
rootMongooseTestModule,
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { SocketEventDispatcherService } from '@/websocket/services/socket-event-dispatcher.service';
import { WebsocketGateway } from '@/websocket/websocket.gateway';
import { BlockRepository } from '../repositories/block.repository';
import { ContextVarRepository } from '../repositories/context-var.repository';
import { ConversationRepository } from '../repositories/conversation.repository';
import { MessageRepository } from '../repositories/message.repository';
import { SubscriberRepository } from '../repositories/subscriber.repository';
import { BlockFull, BlockModel } from '../schemas/block.schema';
import { CategoryModel } from '../schemas/category.schema';
import { ContextVarModel } from '../schemas/context-var.schema';
import {
Conversation,
ConversationFull,
ConversationModel,
} from '../schemas/conversation.schema';
import { LabelModel } from '../schemas/label.schema';
import { MessageModel } from '../schemas/message.schema';
import { SubscriberModel } from '../schemas/subscriber.schema';
import { BlockFull } from '../schemas/block.schema';
import { Conversation, ConversationFull } from '../schemas/conversation.schema';
import { CategoryRepository } from './../repositories/category.repository';
import { BlockService } from './block.service';
import { BotService } from './bot.service';
import { CategoryService } from './category.service';
import { ContextVarService } from './context-var.service';
import { ConversationService } from './conversation.service';
import { MessageService } from './message.service';
import { SubscriberService } from './subscriber.service';
describe('BotService', () => {
@@ -102,102 +48,25 @@ describe('BotService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
models: ['LabelModel', 'CategoryModel'],
autoInjectFrom: ['providers'],
imports: [
rootMongooseTestModule(async () => {
await installSubscriberFixtures();
await installContentFixtures();
await installBlockFixtures();
}),
MongooseModule.forFeature([
BlockModel,
CategoryModel,
ContentTypeModel,
ContentModel,
AttachmentModel,
LabelModel,
ConversationModel,
SubscriberModel,
MessageModel,
MenuModel,
ContextVarModel,
LanguageModel,
NlpEntityModel,
NlpSampleEntityModel,
NlpValueModel,
NlpSampleModel,
]),
JwtModule,
],
providers: [
BlockRepository,
CategoryRepository,
WebsocketGateway,
SocketEventDispatcherService,
ConversationRepository,
ContentTypeRepository,
ContentRepository,
AttachmentRepository,
SubscriberRepository,
MessageRepository,
MenuRepository,
LanguageRepository,
ContextVarRepository,
NlpEntityRepository,
NlpSampleEntityRepository,
NlpValueRepository,
NlpSampleRepository,
BlockService,
CategoryService,
ContentTypeService,
ContentService,
AttachmentService,
SubscriberService,
ConversationService,
JwtService,
BotService,
ChannelService,
MessageService,
MenuService,
WebChannelHandler,
ContextVarService,
LanguageService,
NlpEntityService,
NlpValueService,
NlpSampleService,
NlpSampleEntityService,
NlpService,
{
provide: HelperService,
useValue: {},
},
{
provide: PluginService,
useValue: {},
},
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: SettingService,
useValue: {
getConfig: jest.fn(() => ({
chatbot: { lang: { default: 'fr' } },
})),
getSettings: jest.fn(() => ({
contact: { company_name: 'Your company name' },
})),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
});
[
@@ -217,7 +86,7 @@ describe('BotService', () => {
]);
});
afterEach(jest.clearAllMocks);
afterEach(jest.resetAllMocks);
afterAll(closeInMongodConnection);
describe('startConversation', () => {
afterAll(() => {

View File

@@ -11,6 +11,8 @@ import { EventEmitter2 } from '@nestjs/event-emitter';
import { BotStatsType } from '@/analytics/schemas/bot-stats.schema';
import EventWrapper from '@/channel/lib/EventWrapper';
import { HelperService } from '@/helper/helper.service';
import { FlowEscape, HelperType } from '@/helper/types';
import { LoggerService } from '@/logger/logger.service';
import { SettingService } from '@/setting/services/setting.service';
@@ -24,7 +26,7 @@ import {
OutgoingMessageFormat,
StdOutgoingMessageEnvelope,
} from '../schemas/types/message';
import { BlockOptions, FallbackOptions } from '../schemas/types/options';
import { FallbackOptions } from '../schemas/types/options';
import { BlockService } from './block.service';
import { ConversationService } from './conversation.service';
@@ -39,6 +41,7 @@ export class BotService {
private readonly conversationService: ConversationService,
private readonly subscriberService: SubscriberService,
private readonly settingService: SettingService,
private readonly helperService: HelperService,
) {}
/**
@@ -244,10 +247,12 @@ export class BotService {
/**
* Handles advancing the conversation to the specified *next* block.
*
* 1. Updates “popular blocks” stats.
* 2. Persists the updated conversation context.
* 3. Triggers the next block.
* 4. Ends the conversation if an unrecoverable error occurs.
* @param convo - The current conversation object containing context and state.
* @param next - The next block to proceed to in the conversation flow.
* @param event - The incoming event that triggered the conversation flow.
* @param fallback - Boolean indicating if this is a fallback response in case no appropriate reply was found.
*
* @returns A promise that resolves to a boolean indicating whether the next block was successfully triggered.
*/
async proceedToNextBlock(
convo: ConversationFull,
@@ -258,10 +263,7 @@ export class BotService {
// Increment stats about popular blocks
this.eventEmitter.emit('hook:stats:entry', BotStatsType.popular, next.name);
this.logger.debug(
'Proceeding to next block ',
next.id,
' for conversation ',
convo.id,
`Proceeding to next block ${next.id} for conversation ${convo.id}`,
);
try {
@@ -348,45 +350,16 @@ export class BotService {
) {
try {
let fallback = false;
const currentBlock = convo.current;
const fallbackOptions: BlockOptions['fallback'] = convo.current?.options
?.fallback
? convo.current.options.fallback
: {
active: false,
max_attempts: 0,
message: [],
};
// We will avoid having multiple matches when we are not at the start of a conversation
// and only if local fallback is enabled
const canHaveMultipleMatches = !fallbackOptions.active;
// Find the next block that matches
const nextBlocks = await this.blockService.findAndPopulate({
_id: { $in: convo.next.map(({ id }) => id) },
});
const matchedBlock = await this.blockService.match(
nextBlocks,
event,
canHaveMultipleMatches,
);
// If there is no match in next block then loopback (current fallback)
// This applies only to text messages + there's a max attempt to be specified
this.logger.debug('Handling ongoing conversation message ...', convo.id);
const matchedBlock = await this.findNextMatchingBlock(convo, event);
let fallbackBlock: BlockFull | undefined = undefined;
if (!matchedBlock && this.shouldAttemptLocalFallback(convo, event)) {
// Trigger block fallback
// NOTE : current is not populated, this may cause some anomaly
fallbackBlock = {
...currentBlock,
nextBlocks: convo.next,
// If there's labels, they should be already have been assigned
assign_labels: [],
trigger_labels: [],
attachedBlock: null,
category: null,
previousBlocks: [],
};
fallback = true;
const fallbackResult = await this.handleFlowEscapeFallback(
convo,
event,
);
fallbackBlock = fallbackResult.nextBlock;
fallback = fallbackResult.fallback;
}
const next = matchedBlock || fallbackBlock;
@@ -410,6 +383,91 @@ export class BotService {
}
}
/**
* Handles the flow escape fallback logic for a conversation.
*
* This method adjudicates the flow escape event and helps determine the next block to execute based on the helper's response.
* It can coerce the event to a specific next block, create a new context, or reprompt the user with a fallback message.
* If the helper cannot handle the flow escape, it returns a fallback block with the current conversation's state.
*
* @param convo - The current conversation object.
* @param event - The incoming event that triggered the fallback.
*
* @returns An object containing the next block to execute (if any) and a flag indicating if a fallback should occur.
*/
async handleFlowEscapeFallback(
convo: ConversationFull,
event: EventWrapper<any, any>,
): Promise<{ nextBlock?: BlockFull; fallback: boolean }> {
const currentBlock = convo.current;
const fallbackOptions: FallbackOptions =
this.blockService.getFallbackOptions(currentBlock);
const fallbackBlock: BlockFull = {
...currentBlock,
nextBlocks: convo.next,
assign_labels: [],
trigger_labels: [],
attachedBlock: null,
category: null,
previousBlocks: [],
};
try {
const helper = await this.helperService.getDefaultHelper(
HelperType.FLOW_ESCAPE,
);
if (!helper.canHandleFlowEscape(currentBlock)) {
return { nextBlock: fallbackBlock, fallback: true };
}
// Adjudicate the flow escape event
this.logger.debug(
`Adjudicating flow escape for block '${currentBlock.id}' in conversation '${convo.id}'.`,
);
const result = await helper.adjudicate(event, currentBlock);
switch (result.action) {
case FlowEscape.Action.COERCE: {
// Coerce the option to the next block
this.logger.debug(`Coercing option to the next block ...`, convo.id);
const proxiedEvent = new Proxy(event, {
get(target, prop, receiver) {
if (prop === 'getText') {
return () => result.coercedOption + '';
}
return Reflect.get(target, prop, receiver);
},
});
const matchedBlock = await this.findNextMatchingBlock(
convo,
proxiedEvent,
);
return { nextBlock: matchedBlock, fallback: false };
}
case FlowEscape.Action.NEW_CTX:
return { nextBlock: undefined, fallback: false };
case FlowEscape.Action.REPROMPT:
default:
if (result.repromptMessage) {
fallbackBlock.options.fallback = {
...fallbackOptions,
message: [result.repromptMessage],
};
}
return { nextBlock: fallbackBlock, fallback: true };
}
} catch (err) {
this.logger.warn(
'Unable to handle flow escape, using default local fallback ...',
err,
);
return { nextBlock: fallbackBlock, fallback: true };
}
}
/**
* Determines if the incoming message belongs to an active conversation and processes it accordingly.
* If an active conversation is found, the message is handled as part of that conversation.

View File

@@ -6,12 +6,8 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import EventWrapper from '@/channel/lib/EventWrapper';
import { I18nService } from '@/i18n/services/i18n.service';
import { installContextVarFixtures } from '@/utils/test/fixtures/contextvar';
import { installConversationTypeFixtures } from '@/utils/test/fixtures/conversation';
import {
@@ -21,16 +17,9 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { VIEW_MORE_PAYLOAD } from '../helpers/constants';
import { ContextVarRepository } from '../repositories/context-var.repository';
import { ConversationRepository } from '../repositories/conversation.repository';
import { SubscriberRepository } from '../repositories/subscriber.repository';
import { Block } from '../schemas/block.schema';
import { ContextVarModel } from '../schemas/context-var.schema';
import { ConversationModel } from '../schemas/conversation.schema';
import { SubscriberModel } from '../schemas/subscriber.schema';
import { OutgoingMessageFormat } from '../schemas/types/message';
import { ContextVarService } from './context-var.service';
import { ConversationService } from './conversation.service';
import { SubscriberService } from './subscriber.service';
@@ -45,30 +34,21 @@ describe('ConversationService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['providers'],
imports: [
rootMongooseTestModule(async () => {
await installContextVarFixtures();
await installConversationTypeFixtures();
}),
MongooseModule.forFeature([
// LabelModel,
SubscriberModel,
ConversationModel,
AttachmentModel,
ContextVarModel,
]),
],
providers: [
// LabelService,
// LabelRepository,
AttachmentService,
SubscriberService,
ConversationService,
ContextVarService,
AttachmentRepository,
SubscriberRepository,
ConversationRepository,
ContextVarRepository,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
],
});
[conversationService, subscriberService] = await getMocks([

View File

@@ -6,11 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import {
installLabelFixtures,
labelFixtures,
@@ -24,12 +19,11 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { LabelRepository } from '../repositories/label.repository';
import { Label, LabelFull, LabelModel } from '../schemas/label.schema';
import { Subscriber, SubscriberModel } from '../schemas/subscriber.schema';
import { Label, LabelFull } from '../schemas/label.schema';
import { Subscriber } from '../schemas/subscriber.schema';
import { SubscriberRepository } from './../repositories/subscriber.repository';
import { LabelService } from './label.service';
import { SubscriberService } from './subscriber.service';
describe('LabelService', () => {
let labelRepository: LabelRepository;
@@ -41,22 +35,9 @@ describe('LabelService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installLabelFixtures),
MongooseModule.forFeature([
LabelModel,
SubscriberModel,
AttachmentModel,
]),
],
providers: [
LabelService,
LabelRepository,
SubscriberService,
AttachmentService,
AttachmentRepository,
SubscriberRepository,
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installLabelFixtures)],
providers: [LabelService, SubscriberRepository],
});
[labelService, labelRepository, subscriberRepository] = await getMocks([
LabelService,

View File

@@ -6,20 +6,8 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { InvitationRepository } from '@/user/repositories/invitation.repository';
import { RoleRepository } from '@/user/repositories/role.repository';
import { UserRepository } from '@/user/repositories/user.repository';
import { InvitationModel } from '@/user/schemas/invitation.schema';
import { PermissionModel } from '@/user/schemas/permission.schema';
import { RoleModel } from '@/user/schemas/role.schema';
import { User, UserModel } from '@/user/schemas/user.schema';
import { RoleService } from '@/user/services/role.service';
import { UserService } from '@/user/services/user.service';
import { User } from '@/user/schemas/user.schema';
import {
installMessageFixtures,
messageFixtures,
@@ -36,12 +24,11 @@ import { Room } from '@/websocket/types';
import { WebsocketGateway } from '@/websocket/websocket.gateway';
import { MessageRepository } from '../repositories/message.repository';
import { Message, MessageModel } from '../schemas/message.schema';
import { Subscriber, SubscriberModel } from '../schemas/subscriber.schema';
import { Message } from '../schemas/message.schema';
import { Subscriber } from '../schemas/subscriber.schema';
import { SubscriberRepository } from './../repositories/subscriber.repository';
import { MessageService } from './message.service';
import { SubscriberService } from './subscriber.service';
describe('MessageService', () => {
let messageRepository: MessageRepository;
@@ -66,31 +53,9 @@ describe('MessageService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installMessageFixtures),
MongooseModule.forFeature([
UserModel,
RoleModel,
PermissionModel,
InvitationModel,
SubscriberModel,
MessageModel,
AttachmentModel,
]),
],
providers: [
AttachmentService,
AttachmentRepository,
UserService,
UserRepository,
RoleService,
RoleRepository,
InvitationRepository,
SubscriberService,
SubscriberRepository,
MessageService,
MessageRepository,
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installMessageFixtures)],
providers: [MessageService, SubscriberRepository, UserRepository],
});
[messageService, messageRepository, subscriberRepository, userRepository] =
await getMocks([

View File

@@ -6,11 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import {
Injectable,
InternalServerErrorException,
Optional,
} from '@nestjs/common';
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { BaseService } from '@/utils/generics/base-service';
import {
@@ -36,14 +32,11 @@ export class MessageService extends BaseService<
MessagePopulate,
MessageFull
> {
private readonly gateway: WebsocketGateway;
constructor(
private readonly messageRepository: MessageRepository,
@Optional() gateway?: WebsocketGateway,
private readonly gateway: WebsocketGateway,
) {
super(messageRepository);
if (gateway) this.gateway = gateway;
}
/**

View File

@@ -6,14 +6,9 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import mime from 'mime';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import {
Attachment,
AttachmentModel,
} from '@/attachment/schemas/attachment.schema';
import { Attachment } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import {
AttachmentAccess,
@@ -21,15 +16,8 @@ import {
AttachmentFile,
AttachmentResourceRef,
} from '@/attachment/types';
import { InvitationRepository } from '@/user/repositories/invitation.repository';
import { RoleRepository } from '@/user/repositories/role.repository';
import { UserRepository } from '@/user/repositories/user.repository';
import { InvitationModel } from '@/user/schemas/invitation.schema';
import { PermissionModel } from '@/user/schemas/permission.schema';
import { RoleModel } from '@/user/schemas/role.schema';
import { User, UserModel } from '@/user/schemas/user.schema';
import { RoleService } from '@/user/services/role.service';
import { UserService } from '@/user/services/user.service';
import { User } from '@/user/schemas/user.schema';
import { installSubscriberFixtures } from '@/utils/test/fixtures/subscriber';
import { getPageQuery } from '@/utils/test/pagination';
import { sortRowsBy } from '@/utils/test/sort';
@@ -44,10 +32,9 @@ import { WebsocketGateway } from '@/websocket/websocket.gateway';
import { LabelRepository } from '../repositories/label.repository';
import { SubscriberRepository } from '../repositories/subscriber.repository';
import { Label, LabelModel } from '../schemas/label.schema';
import { Subscriber, SubscriberModel } from '../schemas/subscriber.schema';
import { Label } from '../schemas/label.schema';
import { Subscriber } from '../schemas/subscriber.schema';
import { LabelService } from './label.service';
import { SubscriberService } from './subscriber.service';
jest.mock('uuid', () => ({ v4: jest.fn(() => 'test-uuid') }));
@@ -71,31 +58,9 @@ describe('SubscriberService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installSubscriberFixtures),
MongooseModule.forFeature([
SubscriberModel,
LabelModel,
UserModel,
RoleModel,
InvitationModel,
PermissionModel,
AttachmentModel,
]),
],
providers: [
SubscriberService,
SubscriberRepository,
LabelService,
LabelRepository,
UserService,
UserRepository,
RoleService,
RoleRepository,
InvitationRepository,
AttachmentService,
AttachmentRepository,
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installSubscriberFixtures)],
providers: [SubscriberService, LabelRepository, UserRepository],
});
[
labelRepository,

View File

@@ -6,11 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import {
Injectable,
InternalServerErrorException,
Optional,
} from '@nestjs/common';
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import mime from 'mime';
import { v4 as uuidv4 } from 'uuid';
@@ -24,6 +20,7 @@ import {
} from '@/attachment/types';
import { config } from '@/config';
import { BaseService } from '@/utils/generics/base-service';
import { TFilterQuery } from '@/utils/types/filter.types';
import {
SocketGet,
SocketPost,
@@ -52,15 +49,12 @@ export class SubscriberService extends BaseService<
SubscriberFull,
SubscriberDto
> {
private readonly gateway: WebsocketGateway;
constructor(
readonly repository: SubscriberRepository,
protected readonly attachmentService: AttachmentService,
@Optional() gateway?: WebsocketGateway,
private readonly gateway: WebsocketGateway,
) {
super(repository);
if (gateway) this.gateway = gateway;
}
/**
@@ -260,22 +254,23 @@ 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 label The label that is being deleted.
* @param _query - The Mongoose query object used for deletion.
* @param criteria - The filter criteria for finding the labels to be deleted.
*/
@OnEvent('hook:label:delete')
async handleLabelDelete(labels: Label[]) {
const subscribers = await this.find({
labels: { $in: labels.map((l) => l.id) },
});
for (const subscriber of subscribers) {
const updatedLabels = subscriber.labels.filter(
(label) => !labels.find((l) => l.id === label),
@OnEvent('hook:label:preDelete')
async handleLabelDelete(
_query: unknown,
criteria: TFilterQuery<Label>,
): Promise<void> {
if (criteria._id) {
await this.getRepository().model.updateMany(
{ labels: criteria._id },
{ $pull: { labels: criteria._id } },
);
await this.updateOne(subscriber.id, { labels: updatedLabels });
} else {
throw new Error('Attempted to delete label using unknown criteria');
}
}
}

View File

@@ -7,12 +7,9 @@
*/
import { NotFoundException } from '@nestjs/common/exceptions';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { BlockService } from '@/chat/services/block.service';
import { I18nService } from '@/i18n/services/i18n.service';
import { FieldType } from '@/setting/schemas/types';
import { NOT_FOUND_ID } from '@/utils/constants/mock';
import { getUpdateOneError } from '@/utils/test/errors/messages';
@@ -26,10 +23,7 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { ContentTypeCreateDto } from '../dto/contentType.dto';
import { ContentTypeRepository } from '../repositories/content-type.repository';
import { ContentRepository } from '../repositories/content.repository';
import { ContentType, ContentTypeModel } from '../schemas/content-type.schema';
import { ContentModel } from '../schemas/content.schema';
import { ContentType } from '../schemas/content-type.schema';
import { ContentTypeService } from '../services/content-type.service';
import { ContentService } from '../services/content.service';
@@ -44,26 +38,14 @@ describe('ContentTypeController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [ContentTypeController],
imports: [
rootMongooseTestModule(installContentFixtures),
MongooseModule.forFeature([
ContentTypeModel,
ContentModel,
AttachmentModel,
]),
],
imports: [rootMongooseTestModule(installContentFixtures)],
providers: [
ContentTypeRepository,
ContentRepository,
AttachmentRepository,
ContentTypeService,
ContentService,
AttachmentService,
{
provide: BlockService,
provide: I18nService,
useValue: {
findOne: jest.fn(),
t: jest.fn().mockImplementation((t) => t),
},
},
],

View File

@@ -7,8 +7,8 @@
*/
import { NotFoundException } from '@nestjs/common/exceptions';
import { MongooseModule } from '@nestjs/mongoose';
import { I18nService } from '@/i18n/services/i18n.service';
import { NOT_FOUND_ID } from '@/utils/constants/mock';
import { PageQueryDto } from '@/utils/pagination/pagination-query.dto';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
@@ -25,10 +25,8 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { ContentCreateDto } from '../dto/content.dto';
import { ContentTypeRepository } from '../repositories/content-type.repository';
import { ContentRepository } from '../repositories/content.repository';
import { ContentType, ContentTypeModel } from '../schemas/content-type.schema';
import { Content, ContentModel } from '../schemas/content.schema';
import { ContentType } from '../schemas/content-type.schema';
import { Content } from '../schemas/content.schema';
import { ContentTypeService } from '../services/content-type.service';
import { ContentService } from '../services/content.service';
@@ -45,16 +43,16 @@ describe('ContentController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [ContentController],
imports: [
rootMongooseTestModule(installContentFixtures),
MongooseModule.forFeature([ContentTypeModel, ContentModel]),
],
imports: [rootMongooseTestModule(installContentFixtures)],
providers: [
ContentTypeService,
ContentService,
ContentRepository,
ContentTypeRepository,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
],
});
[contentController, contentService, contentTypeService] = await getMocks([

View File

@@ -6,9 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import {
installMenuFixtures,
offerMenuFixture,
@@ -21,8 +18,6 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { MenuRepository } from '../repositories/menu.repository';
import { MenuModel } from '../schemas/menu.schema';
import { MenuType } from '../schemas/types/menu';
import { MenuService } from '../services/menu.service';
import { verifyTree } from '../utilities/verifyTree';
@@ -34,22 +29,8 @@ describe('MenuController', () => {
let menuService: MenuService;
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installMenuFixtures),
MongooseModule.forFeature([MenuModel]),
],
providers: [
MenuRepository,
MenuService,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
autoInjectFrom: ['controllers'],
imports: [rootMongooseTestModule(installMenuFixtures)],
controllers: [MenuController],
});
[menuController, menuService] = await getMocks([

View File

@@ -6,27 +6,22 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { BlockRepository } from '@/chat/repositories/block.repository';
import { BlockModel } from '@/chat/schemas/block.schema';
import { BlockService } from '@/chat/services/block.service';
import {
ContentType,
ContentTypeModel,
} from '@/cms/schemas/content-type.schema';
import { ContentType } from '@/cms/schemas/content-type.schema';
import { I18nService } from '@/i18n/services/i18n.service';
import {
closeInMongodConnection,
rootMongooseTestModule,
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { Content, ContentModel } from '../schemas/content.schema';
import { Content } from '../schemas/content.schema';
import { installContentFixtures } from './../../utils/test/fixtures/content';
import { ContentTypeRepository } from './content-type.repository';
import { ContentRepository } from './content.repository';
describe('ContentTypeRepository', () => {
let contentTypeRepository: ContentTypeRepository;
@@ -36,19 +31,14 @@ describe('ContentTypeRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installContentFixtures),
MongooseModule.forFeature([ContentTypeModel, ContentModel, BlockModel]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installContentFixtures)],
providers: [
ContentRepository,
ContentTypeRepository,
BlockService,
BlockRepository,
{
provide: BlockService,
provide: I18nService,
useValue: {
findOne: jest.fn(),
t: jest.fn().mockImplementation((t) => t),
},
},
],

View File

@@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { ForbiddenException, Injectable, Optional } from '@nestjs/common';
import { ForbiddenException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Document, Model, Query } from 'mongoose';
@@ -28,7 +28,7 @@ export class ContentTypeRepository extends BaseRepository<
constructor(
@InjectModel(ContentType.name) readonly model: Model<ContentType>,
@InjectModel(Content.name) private readonly contentModel: Model<Content>,
@Optional() private readonly blockService?: BlockService,
private readonly blockService: BlockService,
) {
super(model, ContentType);
}
@@ -52,14 +52,15 @@ export class ContentTypeRepository extends BaseRepository<
>,
criteria: TFilterQuery<ContentType>,
) {
const entityId: string = criteria._id as string;
const associatedBlocks = await this.blockService?.findOne({
'options.content.entity': entityId,
});
if (associatedBlocks) {
throw new ForbiddenException(`Content type have blocks associated to it`);
}
if (criteria._id) {
const associatedBlock = await this.blockService.findOne({
'options.content.entity': criteria._id,
});
if (associatedBlock) {
throw new ForbiddenException(
'Content type have blocks associated to it',
);
}
await this.contentModel.deleteMany({ entity: criteria._id });
} else {
throw new Error(

View File

@@ -6,13 +6,10 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
ContentType,
ContentTypeModel,
} from '@/cms/schemas/content-type.schema';
import { ContentType } from '@/cms/schemas/content-type.schema';
import { contentTypeFixtures } from '@/utils/test/fixtures/contenttype';
import { getPageQuery } from '@/utils/test/pagination';
import {
@@ -21,7 +18,7 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { Content, ContentModel } from '../schemas/content.schema';
import { Content } from '../schemas/content.schema';
import {
contentFixtures,
@@ -36,10 +33,9 @@ describe('ContentRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installContentFixtures),
MongooseModule.forFeature([ContentTypeModel, ContentModel]),
],
models: ['ContentTypeModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installContentFixtures)],
providers: [ContentRepository],
});
[contentRepository, contentModel, contentTypeModel] = await getMocks([

View File

@@ -6,8 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import {
installMenuFixtures,
rootMenuFixtures,
@@ -18,7 +16,6 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { MenuModel } from '../schemas/menu.schema';
import { MenuType } from '../schemas/types/menu';
import { MenuRepository } from './menu.repository';
@@ -27,10 +24,8 @@ describe('MenuRepository', () => {
let menuRepository: MenuRepository;
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installMenuFixtures),
MongooseModule.forFeature([MenuModel]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installMenuFixtures)],
providers: [MenuRepository],
});
[menuRepository] = await getMocks([MenuRepository]);

View File

@@ -6,12 +6,8 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { BlockService } from '@/chat/services/block.service';
import { I18nService } from '@/i18n/services/i18n.service';
import { installContentFixtures } from '@/utils/test/fixtures/content';
import {
closeInMongodConnection,
@@ -20,9 +16,6 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { ContentTypeRepository } from '../repositories/content-type.repository';
import { ContentRepository } from '../repositories/content.repository';
import { ContentTypeModel } from '../schemas/content-type.schema';
import { ContentModel } from '../schemas/content.schema';
import { ContentTypeService } from './content-type.service';
import { ContentService } from './content.service';
@@ -35,25 +28,14 @@ describe('ContentTypeService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installContentFixtures),
MongooseModule.forFeature([
ContentTypeModel,
ContentModel,
AttachmentModel,
]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installContentFixtures)],
providers: [
ContentTypeRepository,
ContentRepository,
AttachmentRepository,
ContentTypeService,
ContentService,
AttachmentService,
{
provide: BlockService,
provide: I18nService,
useValue: {
findOne: jest.fn(),
t: jest.fn().mockImplementation((t) => t),
},
},
],

View File

@@ -6,10 +6,9 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import { OutgoingMessageFormat } from '@/chat/schemas/types/message';
import { ContentOptions } from '@/chat/schemas/types/options';
import { I18nService } from '@/i18n/services/i18n.service';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import {
contentFixtures,
@@ -22,10 +21,8 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { ContentTypeRepository } from '../repositories/content-type.repository';
import { ContentRepository } from '../repositories/content.repository';
import { ContentTypeModel } from '../schemas/content-type.schema';
import { Content, ContentModel } from '../schemas/content.schema';
import { Content } from '../schemas/content.schema';
import { ContentTypeService } from './content-type.service';
import { ContentService } from './content.service';
@@ -37,15 +34,16 @@ describe('ContentService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installContentFixtures),
MongooseModule.forFeature([ContentTypeModel, ContentModel]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installContentFixtures)],
providers: [
ContentTypeRepository,
ContentRepository,
ContentTypeService,
ContentService,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
],
});
[contentService, contentTypeService, contentRepository] = await getMocks([

View File

@@ -6,9 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { NotFoundException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import {
installMenuFixtures,
@@ -21,7 +19,6 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { MenuRepository } from '../repositories/menu.repository';
import { MenuModel } from '../schemas/menu.schema';
import { MenuType } from '../schemas/types/menu';
import { verifyTree } from '../utilities/verifyTree';
@@ -32,22 +29,9 @@ describe('MenuService', () => {
let menuRepository: MenuRepository;
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installMenuFixtures),
MongooseModule.forFeature([MenuModel]),
],
providers: [
MenuRepository,
MenuService,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installMenuFixtures)],
providers: [MenuService],
});
[menuService, menuRepository] = await getMocks([
MenuService,

View File

@@ -6,22 +6,10 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { ChannelService } from '@/channel/channel.service';
import { SubscriberRepository } from '@/chat/repositories/subscriber.repository';
import { SubscriberModel } from '@/chat/schemas/subscriber.schema';
import { SubscriberService } from '@/chat/services/subscriber.service';
import LocalStorageHelper from '@/extensions/helpers/local-storage/index.helper';
import { HelperService } from '@/helper/helper.service';
import { LoggerService } from '@/logger/logger.service';
import { SettingRepository } from '@/setting/repositories/setting.repository';
import { Setting, SettingModel } from '@/setting/schemas/setting.schema';
import { SettingSeeder } from '@/setting/seeds/setting.seed';
import { Setting } from '@/setting/schemas/setting.schema';
import { SettingService } from '@/setting/services/setting.service';
import { installSettingFixtures } from '@/utils/test/fixtures/setting';
import {
@@ -41,34 +29,9 @@ describe('CleanupService', () => {
beforeAll(async () => {
const { getMocks, resolveMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installSettingFixtures),
MongooseModule.forFeature([
SettingModel,
SubscriberModel,
AttachmentModel,
]),
],
providers: [
CleanupService,
HelperService,
SettingService,
SettingRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
SettingSeeder,
SubscriberService,
SubscriberRepository,
AttachmentService,
AttachmentRepository,
ChannelService,
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installSettingFixtures)],
providers: [CleanupService],
});
[cleanupService, settingService, helperService] = await getMocks([
CleanupService,

View File

@@ -6,15 +6,9 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { JwtModule } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { ChannelService } from '@/channel/channel.service';
import {
attachmentMessage,
buttonsMessage,
@@ -22,30 +16,17 @@ import {
quickRepliesMessage,
textMessage,
} from '@/channel/lib/__test__/common.mock';
import { MessageRepository } from '@/chat/repositories/message.repository';
import { SubscriberRepository } from '@/chat/repositories/subscriber.repository';
import { LabelModel } from '@/chat/schemas/label.schema';
import { MessageModel } from '@/chat/schemas/message.schema';
import { SubscriberModel } from '@/chat/schemas/subscriber.schema';
import { OutgoingMessageFormat } from '@/chat/schemas/types/message';
import { MessageService } from '@/chat/services/message.service';
import { SubscriberService } from '@/chat/services/subscriber.service';
import { MenuRepository } from '@/cms/repositories/menu.repository';
import { MenuModel } from '@/cms/schemas/menu.schema';
import { MenuService } from '@/cms/services/menu.service';
import { I18nService } from '@/i18n/services/i18n.service';
import { SettingService } from '@/setting/services/setting.service';
import { UserModel } from '@/user/schemas/user.schema';
import { installMessageFixtures } from '@/utils/test/fixtures/message';
import {
closeInMongodConnection,
rootMongooseTestModule,
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { SocketEventDispatcherService } from '@/websocket/services/socket-event-dispatcher.service';
import { SocketRequest } from '@/websocket/utils/socket-request';
import { SocketResponse } from '@/websocket/utils/socket-response';
import { WebsocketGateway } from '@/websocket/websocket.gateway';
import WebChannelHandler from '../index.channel';
@@ -61,47 +42,18 @@ import {
describe('WebChannelHandler', () => {
let subscriberService: SubscriberService;
let handler: WebChannelHandler;
const webSettings = {};
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
models: ['LabelModel', 'UserModel'],
autoInjectFrom: ['providers'],
imports: [
rootMongooseTestModule(async () => {
await installMessageFixtures();
}),
MongooseModule.forFeature([
SubscriberModel,
AttachmentModel,
MessageModel,
MenuModel,
LabelModel,
UserModel,
]),
JwtModule,
],
providers: [
{
provide: SettingService,
useValue: {
getConfig: jest.fn(() => ({
chatbot: { lang: { default: 'fr' } },
})),
getSettings: jest.fn(() => ({
web: webSettings,
})),
},
},
ChannelService,
WebsocketGateway,
SocketEventDispatcherService,
SubscriberService,
SubscriberRepository,
AttachmentService,
AttachmentRepository,
MessageService,
MessageRepository,
MenuService,
MenuRepository,
JwtService,
WebChannelHandler,
{
provide: I18nService,
@@ -109,14 +61,6 @@ describe('WebChannelHandler', () => {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
});
[subscriberService, handler] = await getMocks([

View File

@@ -6,41 +6,20 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { JwtModule } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { JwtService } from '@nestjs/jwt';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import {
Attachment,
AttachmentModel,
} from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { ChannelService } from '@/channel/channel.service';
import { MessageRepository } from '@/chat/repositories/message.repository';
import { SubscriberRepository } from '@/chat/repositories/subscriber.repository';
import { MessageModel } from '@/chat/schemas/message.schema';
import { SubscriberModel } from '@/chat/schemas/subscriber.schema';
import { Attachment } from '@/attachment/schemas/attachment.schema';
import {
IncomingMessageType,
StdEventType,
} from '@/chat/schemas/types/message';
import { MessageService } from '@/chat/services/message.service';
import { SubscriberService } from '@/chat/services/subscriber.service';
import { MenuRepository } from '@/cms/repositories/menu.repository';
import { MenuModel } from '@/cms/schemas/menu.schema';
import { MenuService } from '@/cms/services/menu.service';
import { I18nService } from '@/i18n/services/i18n.service';
import { NlpService } from '@/nlp/services/nlp.service';
import { SettingService } from '@/setting/services/setting.service';
import { installSubscriberFixtures } from '@/utils/test/fixtures/subscriber';
import {
closeInMongodConnection,
rootMongooseTestModule,
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { SocketEventDispatcherService } from '@/websocket/services/socket-event-dispatcher.service';
import { WebsocketGateway } from '@/websocket/websocket.gateway';
import WebChannelHandler from '../index.channel';
import { WEB_CHANNEL_NAME } from '../settings';
@@ -50,48 +29,12 @@ import { webEvents } from './events.mock';
describe(`Web event wrapper`, () => {
let handler: WebChannelHandler;
const webSettings = {};
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installSubscriberFixtures),
MongooseModule.forFeature([
SubscriberModel,
AttachmentModel,
MessageModel,
MenuModel,
]),
JwtModule,
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installSubscriberFixtures)],
providers: [
{
provide: SettingService,
useValue: {
getConfig: jest.fn(() => ({
chatbot: { lang: { default: 'fr' } },
})),
getSettings: jest.fn(() => ({
web: webSettings,
})),
},
},
{
provide: NlpService,
useValue: {
getNLP: jest.fn(() => undefined),
},
},
ChannelService,
SubscriberService,
SubscriberRepository,
WebsocketGateway,
SocketEventDispatcherService,
AttachmentService,
AttachmentRepository,
MessageService,
MessageRepository,
MenuService,
MenuRepository,
JwtService,
WebChannelHandler,
{
provide: I18nService,
@@ -99,14 +42,6 @@ describe(`Web event wrapper`, () => {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
});
[handler] = await getMocks([WebChannelHandler]);

View File

@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
@@ -10,6 +10,8 @@ import { HttpModule } from '@nestjs/axios';
import { Global, Module } from '@nestjs/common';
import { InjectDynamicProviders } from 'nestjs-dynamic-providers';
import { ChatModule } from '@/chat/chat.module';
import { CmsModule } from '@/cms/cms.module';
import { NlpModule } from '@/nlp/nlp.module';
import { HelperController } from './helper.controller';
@@ -25,7 +27,7 @@ import { HelperService } from './helper.service';
'dist/.hexabot/custom/extensions/helpers/**/*.helper.js',
)
@Module({
imports: [HttpModule, NlpModule],
imports: [HttpModule, NlpModule, CmsModule, ChatModule],
controllers: [HelperController],
providers: [HelperService],
exports: [HelperService],

View File

@@ -36,7 +36,7 @@ export default abstract class BaseFlowEscapeHelper<
* @param _blockMessage - The block message to check.
* @returns - Whether the helper can handle the flow escape for the given block message.
*/
abstract canHandleFlowEscape<T extends BlockStub>(_blockMessage: T): boolean;
abstract canHandleFlowEscape<T extends BlockStub>(block: T): boolean;
/**
* Adjudicates the flow escape event.
@@ -46,7 +46,7 @@ export default abstract class BaseFlowEscapeHelper<
* @returns - A promise that resolves to a FlowEscape.AdjudicationResult.
*/
abstract adjudicate<T extends BlockStub>(
_event: EventWrapper<any, any>,
_block: T,
event: EventWrapper<any, any>,
block: T,
): Promise<FlowEscape.AdjudicationResult>;
}

View File

@@ -6,11 +6,8 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { BadRequestException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { I18nService } from '@/i18n/services/i18n.service';
import { NOT_FOUND_ID } from '@/utils/constants/mock';
import { getUpdateOneError } from '@/utils/test/errors/messages';
import {
@@ -25,8 +22,7 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { LanguageUpdateDto } from '../dto/language.dto';
import { LanguageRepository } from '../repositories/language.repository';
import { Language, LanguageModel } from '../schemas/language.schema';
import { Language } from '../schemas/language.schema';
import { LanguageService } from '../services/language.service';
import { LanguageController } from './language.controller';
@@ -38,30 +34,9 @@ describe('LanguageController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installLanguageFixtures),
MongooseModule.forFeature([LanguageModel]),
],
providers: [
LanguageController,
LanguageService,
LanguageRepository,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
initDynamicLanguages: jest.fn(),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
autoInjectFrom: ['controllers'],
imports: [rootMongooseTestModule(installLanguageFixtures)],
controllers: [LanguageController],
});
[languageService, languageController] = await getMocks([
LanguageService,

View File

@@ -6,41 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { ChannelService } from '@/channel/channel.service';
import { MessageController } from '@/chat/controllers/message.controller';
import { BlockRepository } from '@/chat/repositories/block.repository';
import { MessageRepository } from '@/chat/repositories/message.repository';
import { SubscriberRepository } from '@/chat/repositories/subscriber.repository';
import { BlockModel } from '@/chat/schemas/block.schema';
import { MessageModel } from '@/chat/schemas/message.schema';
import { SubscriberModel } from '@/chat/schemas/subscriber.schema';
import { BlockService } from '@/chat/services/block.service';
import { MessageService } from '@/chat/services/message.service';
import { SubscriberService } from '@/chat/services/subscriber.service';
import { ContentRepository } from '@/cms/repositories/content.repository';
import { MenuRepository } from '@/cms/repositories/menu.repository';
import { ContentModel } from '@/cms/schemas/content.schema';
import { MenuModel } from '@/cms/schemas/menu.schema';
import { ContentService } from '@/cms/services/content.service';
import { MenuService } from '@/cms/services/menu.service';
import { I18nService } from '@/i18n/services/i18n.service';
import { NlpEntityRepository } from '@/nlp/repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '@/nlp/repositories/nlp-sample-entity.repository';
import { NlpValueRepository } from '@/nlp/repositories/nlp-value.repository';
import { NlpEntityModel } from '@/nlp/schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '@/nlp/schemas/nlp-sample-entity.schema';
import { NlpValueModel } from '@/nlp/schemas/nlp-value.schema';
import { NlpEntityService } from '@/nlp/services/nlp-entity.service';
import { NlpValueService } from '@/nlp/services/nlp-value.service';
import { NlpService } from '@/nlp/services/nlp.service';
import { PluginService } from '@/plugins/plugins.service';
import { SettingService } from '@/setting/services/setting.service';
import { NOT_FOUND_ID } from '@/utils/constants/mock';
import { getUpdateOneError } from '@/utils/test/errors/messages';
import {
@@ -55,11 +20,8 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { TranslationUpdateDto } from '../dto/translation.dto';
import { LanguageRepository } from '../repositories/language.repository';
import { TranslationRepository } from '../repositories/translation.repository';
import { LanguageModel } from '../schemas/language.schema';
import { Translation, TranslationModel } from '../schemas/translation.schema';
import { LanguageService } from '../services/language.service';
import { Translation } from '../schemas/translation.schema';
import { I18nService } from '../services/i18n.service';
import { TranslationService } from '../services/translation.service';
import { TranslationController } from './translation.controller';
@@ -71,59 +33,10 @@ describe('TranslationController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
controllers: [MessageController],
imports: [
rootMongooseTestModule(installTranslationFixtures),
MongooseModule.forFeature([
SubscriberModel,
TranslationModel,
MessageModel,
AttachmentModel,
MenuModel,
BlockModel,
ContentModel,
LanguageModel,
NlpEntityModel,
NlpSampleEntityModel,
NlpValueModel,
]),
],
autoInjectFrom: ['controllers'],
controllers: [TranslationController],
imports: [rootMongooseTestModule(installTranslationFixtures)],
providers: [
TranslationController,
TranslationService,
TranslationRepository,
MessageService,
MessageRepository,
SubscriberService,
SubscriberRepository,
ChannelService,
AttachmentService,
AttachmentRepository,
MenuService,
MenuRepository,
{
provide: NlpService,
useValue: {
getNLP: jest.fn(() => undefined),
},
},
{
provide: SettingService,
useValue: {
getConfig: jest.fn(() => ({
chatbot: { lang: { default: 'fr' } },
})),
getSettings: jest.fn(() => ({})),
},
},
BlockService,
BlockRepository,
ContentService,
ContentRepository,
{
provide: PluginService,
useValue: {},
},
{
provide: I18nService,
useValue: {
@@ -131,21 +44,6 @@ describe('TranslationController', () => {
refreshDynamicTranslations: jest.fn(),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
LanguageService,
LanguageRepository,
NlpEntityRepository,
NlpEntityService,
NlpValueRepository,
NlpValueService,
NlpSampleEntityRepository,
],
});
[translationService, translationController] = await getMocks([

View File

@@ -10,12 +10,10 @@ import fs from 'fs';
import { HttpService } from '@nestjs/axios';
import { ModuleRef } from '@nestjs/core';
import { getModelToken, MongooseModule } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { LoggerService } from '@/logger/logger.service';
import { MetadataRepository } from '@/setting/repositories/metadata.repository';
import { Metadata, MetadataModel } from '@/setting/schemas/metadata.schema';
import { Metadata } from '@/setting/schemas/metadata.schema';
import { MetadataService } from '@/setting/services/metadata.service';
import {
closeInMongodConnection,
@@ -23,7 +21,7 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { Migration, MigrationModel } from './migration.schema';
import { Migration } from './migration.schema';
import { MigrationService } from './migration.service';
import { MigrationAction } from './types';
@@ -34,13 +32,9 @@ describe('MigrationService', () => {
beforeAll(async () => {
const { getMocks, resolveMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(async () => await Promise.resolve()),
MongooseModule.forFeature([MetadataModel, MigrationModel]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(async () => await Promise.resolve())],
providers: [
MetadataRepository,
MetadataService,
MigrationService,
{
provide: LoggerService,
@@ -53,10 +47,6 @@ describe('MigrationService', () => {
provide: HttpService,
useValue: {},
},
{
provide: AttachmentService,
useValue: {},
},
{
provide: ModuleRef,
useValue: {

View File

@@ -6,14 +6,12 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import {
BadRequestException,
ConflictException,
MethodNotAllowedException,
NotFoundException,
} from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import { nlpEntityFixtures } from '@/utils/test/fixtures/nlpentity';
@@ -30,16 +28,7 @@ import { TFixtures } from '@/utils/test/types';
import { buildTestingMocks } from '@/utils/test/utils';
import { NlpEntityCreateDto, NlpEntityUpdateDto } from '../dto/nlp-entity.dto';
import { NlpEntityRepository } from '../repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '../repositories/nlp-sample-entity.repository';
import { NlpValueRepository } from '../repositories/nlp-value.repository';
import {
NlpEntity,
NlpEntityFull,
NlpEntityModel,
} from '../schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '../schemas/nlp-sample-entity.schema';
import { NlpValueModel } from '../schemas/nlp-value.schema';
import { NlpEntity, NlpEntityFull } from '../schemas/nlp-entity.schema';
import { NlpEntityService } from '../services/nlp-entity.service';
import { NlpValueService } from '../services/nlp-value.service';
@@ -54,28 +43,9 @@ describe('NlpEntityController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [NlpEntityController],
imports: [
rootMongooseTestModule(installNlpValueFixtures),
MongooseModule.forFeature([
NlpEntityModel,
NlpSampleEntityModel,
NlpValueModel,
]),
],
providers: [
NlpEntityService,
NlpEntityRepository,
NlpValueService,
NlpSampleEntityRepository,
NlpValueRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
},
},
],
imports: [rootMongooseTestModule(installNlpValueFixtures)],
});
[nlpEntityController, nlpValueService, nlpEntityService] = await getMocks([
NlpEntityController,

View File

@@ -6,20 +6,11 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { NlpValueMatchPattern } from '@/chat/schemas/types/pattern';
import { HelperService } from '@/helper/helper.service';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { Language, LanguageModel } from '@/i18n/schemas/language.schema';
import { I18nService } from '@/i18n/services/i18n.service';
import { Language } from '@/i18n/schemas/language.schema';
import { LanguageService } from '@/i18n/services/language.service';
import { SettingRepository } from '@/setting/repositories/setting.repository';
import { SettingModel } from '@/setting/schemas/setting.schema';
import { SettingSeeder } from '@/setting/seeds/setting.seed';
import { SettingService } from '@/setting/services/setting.service';
import { getUpdateOneError } from '@/utils/test/errors/messages';
import { installAttachmentFixtures } from '@/utils/test/fixtures/attachment';
import { nlpSampleFixtures } from '@/utils/test/fixtures/nlpsample';
@@ -33,18 +24,7 @@ import { TFixtures } from '@/utils/test/types';
import { buildTestingMocks } from '@/utils/test/utils';
import { NlpSampleDto } from '../dto/nlp-sample.dto';
import { NlpEntityRepository } from '../repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '../repositories/nlp-sample-entity.repository';
import { NlpSampleRepository } from '../repositories/nlp-sample.repository';
import { NlpValueRepository } from '../repositories/nlp-value.repository';
import { NlpEntityModel } from '../schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '../schemas/nlp-sample-entity.schema';
import {
NlpSample,
NlpSampleFull,
NlpSampleModel,
} from '../schemas/nlp-sample.schema';
import { NlpValueModel } from '../schemas/nlp-value.schema';
import { NlpSample, NlpSampleFull } from '../schemas/nlp-sample.schema';
import { NlpSampleState } from '../schemas/types';
import { NlpEntityService } from '../services/nlp-entity.service';
import { NlpSampleEntityService } from '../services/nlp-sample-entity.service';
@@ -65,50 +45,13 @@ describe('NlpSampleController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [NlpSampleController],
imports: [
rootMongooseTestModule(async () => {
await installNlpSampleEntityFixtures();
await installAttachmentFixtures();
}),
MongooseModule.forFeature([
NlpSampleModel,
NlpSampleEntityModel,
NlpEntityModel,
NlpValueModel,
SettingModel,
LanguageModel,
]),
],
providers: [
NlpSampleRepository,
NlpSampleEntityRepository,
NlpEntityService,
NlpEntityRepository,
NlpValueService,
NlpValueRepository,
NlpSampleService,
NlpSampleEntityService,
LanguageRepository,
LanguageService,
HelperService,
SettingRepository,
SettingService,
SettingSeeder,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
});
[

View File

@@ -6,9 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { getUpdateOneError } from '@/utils/test/errors/messages';
import {
@@ -22,12 +20,7 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { NlpValueCreateDto } from '../dto/nlp-value.dto';
import { NlpEntityRepository } from '../repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '../repositories/nlp-sample-entity.repository';
import { NlpValueRepository } from '../repositories/nlp-value.repository';
import { NlpEntityModel } from '../schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '../schemas/nlp-sample-entity.schema';
import { NlpValue, NlpValueModel } from '../schemas/nlp-value.schema';
import { NlpValue } from '../schemas/nlp-value.schema';
import { NlpEntityService } from '../services/nlp-entity.service';
import { NlpValueService } from '../services/nlp-value.service';
@@ -43,28 +36,9 @@ describe('NlpValueController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [NlpValueController],
imports: [
rootMongooseTestModule(installNlpValueFixtures),
MongooseModule.forFeature([
NlpValueModel,
NlpSampleEntityModel,
NlpEntityModel,
]),
],
providers: [
NlpValueRepository,
NlpValueService,
NlpSampleEntityRepository,
NlpEntityService,
NlpEntityRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
},
},
],
imports: [rootMongooseTestModule(installNlpValueFixtures)],
});
[nlpValueController, nlpValueService, nlpEntityService] = await getMocks([
NlpValueController,

View File

@@ -6,8 +6,10 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import LlmNluHelper from '@/extensions/helpers/llm-nlu/index.helper';
import { HelperService } from '@/helper/helper.service';
import { SettingService } from '@/setting/services/setting.service';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import { nlpEntityFixtures } from '@/utils/test/fixtures/nlpentity';
import { installNlpValueFixtures } from '@/utils/test/fixtures/nlpvalue';
import { getPageQuery } from '@/utils/test/pagination';
@@ -17,42 +19,53 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { NlpEntity, NlpEntityModel } from '../schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '../schemas/nlp-sample-entity.schema';
import { NlpValueModel } from '../schemas/nlp-value.schema';
import { NlpEntity } from '../schemas/nlp-entity.schema';
import { NlpEntityService } from '../services/nlp-entity.service';
import { NlpService } from '../services/nlp.service';
import { NlpEntityRepository } from './nlp-entity.repository';
import { NlpSampleEntityRepository } from './nlp-sample-entity.repository';
import { NlpValueRepository } from './nlp-value.repository';
describe('NlpEntityRepository', () => {
let nlpEntityRepository: NlpEntityRepository;
let nlpValueRepository: NlpValueRepository;
let firstNameNlpEntity: NlpEntity | null;
let nlpService: NlpService;
let llmNluHelper: LlmNluHelper;
let nlpEntityService: NlpEntityService;
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installNlpValueFixtures),
MongooseModule.forFeature([
NlpEntityModel,
NlpValueModel,
NlpSampleEntityModel,
]),
],
const { getMocks, module } = await buildTestingMocks({
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installNlpValueFixtures)],
providers: [
NlpEntityRepository,
NlpValueRepository,
NlpSampleEntityRepository,
NlpService,
LlmNluHelper,
{
provide: SettingService,
useValue: {
getSettings: jest.fn(() => ({
chatbot_settings: {
default_nlu_helper: 'llm-nlu-helper',
},
})),
},
},
],
});
[nlpEntityRepository, nlpValueRepository] = await getMocks([
NlpEntityRepository,
NlpValueRepository,
]);
[nlpEntityRepository, nlpValueRepository, nlpService, nlpEntityService] =
await getMocks([
NlpEntityRepository,
NlpValueRepository,
NlpService,
NlpEntityService,
]);
firstNameNlpEntity = await nlpEntityRepository.findOne({
name: 'firstname',
});
llmNluHelper = module.get(LlmNluHelper);
module.get(HelperService).register(llmNluHelper);
});
afterAll(closeInMongodConnection);
@@ -61,6 +74,12 @@ describe('NlpEntityRepository', () => {
describe('The deleteCascadeOne function', () => {
it('should delete a nlp entity', async () => {
nlpValueRepository.eventEmitter.once(
'hook:nlpEntity:preDelete',
async (...[query, criteria]) => {
await nlpService.handleEntityDelete(query, criteria);
},
);
const intentNlpEntity = await nlpEntityRepository.findOne({
name: 'intent',
});
@@ -112,4 +131,83 @@ describe('NlpEntityRepository', () => {
]);
});
});
describe('postCreate', () => {
it('should create and attach a foreign_id to the newly created nlp entity', async () => {
nlpEntityRepository.eventEmitter.once(
'hook:nlpEntity:postCreate',
async (...[created]) => {
const helperSpy = jest.spyOn(llmNluHelper, 'addEntity');
jest.spyOn(nlpEntityService, 'updateOne');
await nlpService.handleEntityPostCreate(created);
expect(helperSpy).toHaveBeenCalledWith(created);
expect(nlpEntityService.updateOne).toHaveBeenCalledWith(
{
_id: created._id,
},
{ foreign_id: await helperSpy.mock.results[0].value },
);
},
);
const result = await nlpEntityRepository.create({
name: 'test1',
});
const intentNlpEntity = await nlpEntityRepository.findOne(result.id);
expect(intentNlpEntity?.foreign_id).toBeDefined();
expect(intentNlpEntity).toEqualPayload(result, [
...IGNORED_TEST_FIELDS,
'foreign_id',
]);
});
it('should not create and attach a foreign_id to the newly created nlp entity with builtin set to true', async () => {
nlpEntityRepository.eventEmitter.once(
'hook:nlpEntity:postCreate',
async (...[created]) => {
await nlpService.handleEntityPostCreate(created);
},
);
const result = await nlpEntityRepository.create({
name: 'test2',
builtin: true,
});
const nlpEntity = await nlpEntityRepository.findOne(result.id);
expect(nlpEntity?.foreign_id).toBeUndefined();
expect(nlpEntity).toEqualPayload(result);
});
});
describe('postUpdate', () => {
it('should update an NlpEntity and trigger a postUpdate event', async () => {
jest.spyOn(nlpService, 'handleEntityPostUpdate');
jest.spyOn(llmNluHelper, 'updateEntity');
nlpEntityRepository.eventEmitter.once(
'hook:nlpEntity:postUpdate',
async (...[query, updated]) => {
await nlpService.handleEntityPostUpdate(query, updated);
expect(llmNluHelper.updateEntity).toHaveBeenCalledWith(updated);
},
);
const updatedNlpEntity = await nlpEntityRepository.updateOne(
{
name: 'test2',
},
{ value: 'test3' },
);
expect(nlpService.handleEntityPostUpdate).toHaveBeenCalledTimes(1);
expect(llmNluHelper.updateEntity).toHaveBeenCalledTimes(1);
const result = await nlpEntityRepository.findOne(updatedNlpEntity.id);
expect(result).toEqualPayload(updatedNlpEntity);
});
});
});

View File

@@ -8,23 +8,18 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Document, Model, Query } from 'mongoose';
import { Model } from 'mongoose';
import { BaseRepository, DeleteResult } from '@/utils/generics/base-repository';
import { TFilterQuery } from '@/utils/types/filter.types';
import { BaseRepository } from '@/utils/generics/base-repository';
import { NlpEntityDto } from '../dto/nlp-entity.dto';
import {
NLP_ENTITY_POPULATE,
NlpEntity,
NlpEntityDocument,
NlpEntityFull,
NlpEntityPopulate,
} from '../schemas/nlp-entity.schema';
import { NlpSampleEntityRepository } from './nlp-sample-entity.repository';
import { NlpValueRepository } from './nlp-value.repository';
@Injectable()
export class NlpEntityRepository extends BaseRepository<
NlpEntity,
@@ -32,85 +27,7 @@ export class NlpEntityRepository extends BaseRepository<
NlpEntityFull,
NlpEntityDto
> {
constructor(
@InjectModel(NlpEntity.name) readonly model: Model<NlpEntity>,
private readonly nlpValueRepository: NlpValueRepository,
private readonly nlpSampleEntityRepository: NlpSampleEntityRepository,
) {
constructor(@InjectModel(NlpEntity.name) readonly model: Model<NlpEntity>) {
super(model, NlpEntity, NLP_ENTITY_POPULATE, NlpEntityFull);
}
/**
* Post-create hook that triggers after an NLP entity is created.
* Emits an event to notify other parts of the system about the creation.
* Bypasses built-in entities.
*
* @param created - The newly created NLP entity document.
*/
async postCreate(_created: NlpEntityDocument): Promise<void> {
if (!_created.builtin) {
// Bypass builtin entities (probably fixtures)
this.eventEmitter.emit('hook:nlpEntity:create', _created);
}
}
/**
* Post-update hook that triggers after an NLP entity is updated.
* Emits an event to notify other parts of the system about the update.
* Bypasses built-in entities.
*
* @param query - The query used to find and update the entity.
* @param updated - The updated NLP entity document.
*/
async postUpdate(
_query: Query<
Document<NlpEntity, any, any>,
Document<NlpEntity, any, any>,
unknown,
NlpEntity,
'findOneAndUpdate'
>,
updated: NlpEntity,
): Promise<void> {
if (!updated?.builtin) {
// Bypass builtin entities (probably fixtures)
this.eventEmitter.emit('hook:nlpEntity:update', updated);
}
}
/**
* Pre-delete hook that triggers before an NLP entity is deleted.
* Deletes related NLP values and sample entities before the entity deletion.
* Emits an event to notify other parts of the system about the deletion.
* Bypasses built-in entities.
*
* @param query The query used to delete the entity.
* @param criteria The filter criteria used to find the entity for deletion.
*/
async preDelete(
_query: Query<
DeleteResult,
Document<NlpEntity, any, any>,
unknown,
NlpEntity,
'deleteOne' | 'deleteMany'
>,
criteria: TFilterQuery<NlpEntity>,
): Promise<void> {
if (criteria._id) {
await this.nlpValueRepository.deleteMany({ entity: criteria._id });
await this.nlpSampleEntityRepository.deleteMany({ entity: criteria._id });
const entities = await this.find(
typeof criteria === 'string' ? { _id: criteria } : criteria,
);
entities
.filter((e) => !e.builtin)
.map((e) => {
this.eventEmitter.emit('hook:nlpEntity:delete', e);
});
} else {
throw new Error('Attempted to delete NLP entity using unknown criteria');
}
}
}

View File

@@ -6,10 +6,8 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { Language, LanguageModel } from '@/i18n/schemas/language.schema';
import { Language } from '@/i18n/schemas/language.schema';
import { nlpSampleFixtures } from '@/utils/test/fixtures/nlpsample';
import {
installNlpSampleEntityFixtures,
@@ -24,18 +22,15 @@ import {
import { TFixtures } from '@/utils/test/types';
import { buildTestingMocks } from '@/utils/test/utils';
import { NlpEntity, NlpEntityModel } from '../schemas/nlp-entity.schema';
import { NlpEntity } from '../schemas/nlp-entity.schema';
import {
NlpSampleEntity,
NlpSampleEntityFull,
NlpSampleEntityModel,
} from '../schemas/nlp-sample-entity.schema';
import { NlpSampleModel } from '../schemas/nlp-sample.schema';
import { NlpValueModel, NlpValueStub } from '../schemas/nlp-value.schema';
import { NlpValueStub } from '../schemas/nlp-value.schema';
import { NlpEntityRepository } from './nlp-entity.repository';
import { NlpSampleEntityRepository } from './nlp-sample-entity.repository';
import { NlpValueRepository } from './nlp-value.repository';
describe('NlpSampleEntityRepository', () => {
let nlpSampleEntityRepository: NlpSampleEntityRepository;
@@ -47,20 +42,12 @@ describe('NlpSampleEntityRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installNlpSampleEntityFixtures),
MongooseModule.forFeature([
NlpSampleEntityModel,
NlpEntityModel,
NlpValueModel,
NlpSampleModel,
LanguageModel,
]),
],
models: ['NlpSampleModel', 'NlpValueModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installNlpSampleEntityFixtures)],
providers: [
NlpSampleEntityRepository,
NlpEntityRepository,
NlpValueRepository,
LanguageRepository,
],
});

View File

@@ -6,11 +6,10 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import { Types } from 'mongoose';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { Language, LanguageModel } from '@/i18n/schemas/language.schema';
import { Language } from '@/i18n/schemas/language.schema';
import { PageQueryDto } from '@/utils/pagination/pagination-query.dto';
import { nlpSampleFixtures } from '@/utils/test/fixtures/nlpsample';
import { installNlpSampleEntityFixtures } from '@/utils/test/fixtures/nlpsampleentity';
@@ -22,16 +21,9 @@ import {
import { TFixtures } from '@/utils/test/types';
import { buildTestingMocks } from '@/utils/test/utils';
import {
NlpSampleEntity,
NlpSampleEntityModel,
} from '../schemas/nlp-sample-entity.schema';
import {
NlpSample,
NlpSampleFull,
NlpSampleModel,
} from '../schemas/nlp-sample.schema';
import { NlpValue, NlpValueModel } from '../schemas/nlp-value.schema';
import { NlpSampleEntity } from '../schemas/nlp-sample-entity.schema';
import { NlpSample, NlpSampleFull } from '../schemas/nlp-sample.schema';
import { NlpValue } from '../schemas/nlp-value.schema';
import { NlpSampleEntityRepository } from './nlp-sample-entity.repository';
import { NlpSampleRepository } from './nlp-sample.repository';
@@ -48,20 +40,13 @@ describe('NlpSampleRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installNlpSampleEntityFixtures),
MongooseModule.forFeature([
NlpSampleModel,
NlpSampleEntityModel,
NlpValueModel,
LanguageModel,
]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installNlpSampleEntityFixtures)],
providers: [
NlpSampleRepository,
NlpSampleEntityRepository,
NlpValueRepository,
LanguageRepository,
NlpSampleEntityRepository,
],
});
[

View File

@@ -24,6 +24,7 @@ import { PageQueryDto } from '@/utils/pagination/pagination-query.dto';
import { TFilterQuery } from '@/utils/types/filter.types';
import { TNlpSampleDto } from '../dto/nlp-sample.dto';
import { NlpSampleEntity } from '../schemas/nlp-sample-entity.schema';
import {
NLP_SAMPLE_POPULATE,
NlpSample,
@@ -33,8 +34,6 @@ import {
} from '../schemas/nlp-sample.schema';
import { NlpValue } from '../schemas/nlp-value.schema';
import { NlpSampleEntityRepository } from './nlp-sample-entity.repository';
@Injectable()
export class NlpSampleRepository extends BaseRepository<
NlpSample,
@@ -44,7 +43,8 @@ export class NlpSampleRepository extends BaseRepository<
> {
constructor(
@InjectModel(NlpSample.name) readonly model: Model<NlpSample>,
private readonly nlpSampleEntityRepository: NlpSampleEntityRepository,
@InjectModel(NlpSampleEntity.name)
private readonly nlpSampleEntityModel: Model<NlpSampleEntity>,
) {
super(model, NlpSample, NLP_SAMPLE_POPULATE, NlpSampleFull);
}
@@ -310,7 +310,7 @@ export class NlpSampleRepository extends BaseRepository<
criteria: TFilterQuery<NlpSample>,
) {
if (criteria._id) {
await this.nlpSampleEntityRepository.deleteMany({
await this.nlpSampleEntityModel.deleteMany({
sample: criteria._id,
});
} else {

View File

@@ -6,8 +6,10 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import LlmNluHelper from '@/extensions/helpers/llm-nlu/index.helper';
import { HelperService } from '@/helper/helper.service';
import { SettingService } from '@/setting/services/setting.service';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import { nlpEntityFixtures } from '@/utils/test/fixtures/nlpentity';
import { installNlpSampleEntityFixtures } from '@/utils/test/fixtures/nlpsampleentity';
import { nlpValueFixtures } from '@/utils/test/fixtures/nlpvalue';
@@ -19,14 +21,11 @@ import {
import { TFixtures } from '@/utils/test/types';
import { buildTestingMocks } from '@/utils/test/utils';
import { NlpEntityModel } from '../schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '../schemas/nlp-sample-entity.schema';
import {
NlpValue,
NlpValueFull,
NlpValueModel,
} from '../schemas/nlp-value.schema';
import { NlpValue, NlpValueFull } from '../schemas/nlp-value.schema';
import { NlpValueService } from '../services/nlp-value.service';
import { NlpService } from '../services/nlp.service';
import { NlpEntityRepository } from './nlp-entity.repository';
import { NlpSampleEntityRepository } from './nlp-sample-entity.repository';
import { NlpValueRepository } from './nlp-value.repository';
@@ -34,25 +33,47 @@ describe('NlpValueRepository', () => {
let nlpValueRepository: NlpValueRepository;
let nlpSampleEntityRepository: NlpSampleEntityRepository;
let nlpValues: NlpValue[];
let nlpService: NlpService;
let nlpEntityRepository: NlpEntityRepository;
let llmNluHelper: LlmNluHelper;
let nlpValueService: NlpValueService;
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installNlpSampleEntityFixtures),
MongooseModule.forFeature([
NlpValueModel,
NlpSampleEntityModel,
NlpEntityModel,
]),
const { getMocks, module } = await buildTestingMocks({
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installNlpSampleEntityFixtures)],
providers: [
NlpService,
LlmNluHelper,
{
provide: SettingService,
useValue: {
getSettings: jest.fn(() => ({
chatbot_settings: {
default_nlu_helper: 'llm-nlu-helper',
},
})),
},
},
],
providers: [NlpValueRepository, NlpSampleEntityRepository],
});
[nlpValueRepository, nlpSampleEntityRepository] = await getMocks([
[
nlpValueRepository,
nlpSampleEntityRepository,
nlpService,
nlpEntityRepository,
nlpValueService,
] = await getMocks([
NlpValueRepository,
NlpSampleEntityRepository,
NlpService,
NlpEntityRepository,
NlpValueService,
]);
nlpValues = await nlpValueRepository.findAll();
llmNluHelper = module.get(LlmNluHelper);
module.get(HelperService).register(llmNluHelper);
});
afterAll(closeInMongodConnection);
@@ -107,7 +128,14 @@ describe('NlpValueRepository', () => {
describe('The deleteCascadeOne function', () => {
it('should delete a nlp Value', async () => {
nlpValueRepository.eventEmitter.once(
'hook:nlpValue:preDelete',
async (...[query, criteria]) => {
await nlpService.handleValueDelete(query, criteria);
},
);
const result = await nlpValueRepository.deleteOne(nlpValues[1].id);
expect(result.deletedCount).toEqual(1);
const sampleEntities = await nlpSampleEntityRepository.find({
value: nlpValues[1].id,
@@ -115,4 +143,93 @@ describe('NlpValueRepository', () => {
expect(sampleEntities.length).toEqual(0);
});
});
describe('postCreate', () => {
it('should create and attach a foreign_id to the newly created nlp value', async () => {
nlpValueRepository.eventEmitter.once(
'hook:nlpValue:postCreate',
async (...[created]) => {
const helperSpy = jest.spyOn(llmNluHelper, 'addValue');
jest.spyOn(nlpValueService, 'updateOne');
await nlpService.handleValuePostCreate(created);
expect(helperSpy).toHaveBeenCalledWith(created);
expect(nlpValueService.updateOne).toHaveBeenCalledWith(
{
_id: created._id,
},
{ foreign_id: await helperSpy.mock.results[0].value },
);
},
);
const createdNlpEntity = await nlpEntityRepository.create({
name: 'test1',
});
const result = await nlpValueRepository.create({
entity: createdNlpEntity.id,
value: 'test',
});
const intentNlpEntity = await nlpValueRepository.findOne(result.id);
expect(intentNlpEntity?.foreign_id).toBeDefined();
expect(intentNlpEntity).toEqualPayload(result, [
...IGNORED_TEST_FIELDS,
'foreign_id',
]);
});
it('should not create and attach a foreign_id to the newly created nlp value with builtin set to true', async () => {
nlpValueRepository.eventEmitter.once(
'hook:nlpValue:postCreate',
async (...[created]) => {
await nlpService.handleValuePostCreate(created);
},
);
const createdNlpEntity = await nlpEntityRepository.create({
name: 'nlpEntityTest2',
});
const result = await nlpValueRepository.create({
entity: createdNlpEntity.id,
value: 'nlpValueTest2',
builtin: true,
});
const nlpValue = await nlpValueRepository.findOne(result.id);
expect(nlpValue?.foreign_id).toBeUndefined();
expect(nlpValue).toEqualPayload(result);
});
});
describe('postUpdate', () => {
it('should update an NlpValue and trigger a postUpdate event', async () => {
jest.spyOn(nlpService, 'handleValuePostUpdate');
jest.spyOn(llmNluHelper, 'updateValue');
nlpValueRepository.eventEmitter.once(
'hook:nlpValue:postUpdate',
async (...[query, updated]) => {
await nlpService.handleValuePostUpdate(query, updated);
expect(llmNluHelper.updateValue).toHaveBeenCalledWith(updated);
},
);
const updatedNlpValue = await nlpValueRepository.updateOne(
{
value: 'test',
},
{ value: 'test2' },
);
expect(nlpService.handleValuePostUpdate).toHaveBeenCalledTimes(1);
expect(llmNluHelper.updateValue).toHaveBeenCalledTimes(1);
const result = await nlpValueRepository.findOne(updatedNlpValue.id);
expect(result).toEqualPayload(updatedNlpValue);
});
});
});

View File

@@ -9,16 +9,9 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { plainToInstance } from 'class-transformer';
import {
Document,
Model,
PipelineStage,
Query,
SortOrder,
Types,
} from 'mongoose';
import { Model, PipelineStage, SortOrder, Types } from 'mongoose';
import { BaseRepository, DeleteResult } from '@/utils/generics/base-repository';
import { BaseRepository } from '@/utils/generics/base-repository';
import { PageQueryDto } from '@/utils/pagination/pagination-query.dto';
import { TFilterQuery } from '@/utils/types/filter.types';
import { Format } from '@/utils/types/format.types';
@@ -27,7 +20,6 @@ import { NlpValueDto } from '../dto/nlp-value.dto';
import {
NLP_VALUE_POPULATE,
NlpValue,
NlpValueDocument,
NlpValueFull,
NlpValueFullWithCount,
NlpValuePopulate,
@@ -35,8 +27,6 @@ import {
TNlpValueCount,
} from '../schemas/nlp-value.schema';
import { NlpSampleEntityRepository } from './nlp-sample-entity.repository';
@Injectable()
export class NlpValueRepository extends BaseRepository<
NlpValue,
@@ -44,82 +34,10 @@ export class NlpValueRepository extends BaseRepository<
NlpValueFull,
NlpValueDto
> {
constructor(
@InjectModel(NlpValue.name) readonly model: Model<NlpValue>,
private readonly nlpSampleEntityRepository: NlpSampleEntityRepository,
) {
constructor(@InjectModel(NlpValue.name) readonly model: Model<NlpValue>) {
super(model, NlpValue, NLP_VALUE_POPULATE, NlpValueFull);
}
/**
* Emits an event after a new NLP value is created, bypassing built-in values.
*
* @param created - The newly created NLP value document.
*/
async postCreate(created: NlpValueDocument): Promise<void> {
if (!created.builtin) {
// Bypass builtin entities (probably fixtures)
this.eventEmitter.emit('hook:nlpValue:create', created);
}
}
/**
* Emits an event after an NLP value is updated, bypassing built-in values.
*
* @param query - The query that was used to update the NLP value.
* @param updated - The updated NLP value document.
*/
async postUpdate(
_query: Query<
Document<NlpValue, any, any>,
Document<NlpValue, any, any>,
unknown,
NlpValue,
'findOneAndUpdate'
>,
updated: NlpValue,
): Promise<void> {
if (!updated?.builtin) {
// Bypass builtin entities (probably fixtures)
this.eventEmitter.emit('hook:nlpValue:update', updated);
}
}
/**
* Handles deletion of NLP values and associated entities. If the criteria includes an ID,
* emits an event for each deleted entity.
*
* @param _query - The query used to delete the NLP value(s).
* @param criteria - The filter criteria used to identify the NLP value(s) to delete.
*/
async preDelete(
_query: Query<
DeleteResult,
Document<NlpValue, any, any>,
unknown,
NlpValue,
'deleteOne' | 'deleteMany'
>,
criteria: TFilterQuery<NlpValue>,
): Promise<void> {
if (criteria._id) {
await this.nlpSampleEntityRepository.deleteMany({ value: criteria._id });
const entities = await this.find(
typeof criteria === 'string' ? { _id: criteria } : criteria,
);
entities
.filter((e) => !e.builtin)
.map((e) => {
this.eventEmitter.emit('hook:nlpValue:delete', e);
});
} 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');
}
}
private getSortDirection(sortOrder: SortOrder) {
return typeof sortOrder === 'number'
? sortOrder

View File

@@ -6,9 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { NOT_FOUND_ID } from '@/utils/constants/mock';
import { nlpEntityFixtures } from '@/utils/test/fixtures/nlpentity';
import { installNlpValueFixtures } from '@/utils/test/fixtures/nlpvalue';
@@ -20,14 +17,10 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { NlpEntityRepository } from '../repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '../repositories/nlp-sample-entity.repository';
import { NlpValueRepository } from '../repositories/nlp-value.repository';
import { NlpEntity, NlpEntityModel } from '../schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '../schemas/nlp-sample-entity.schema';
import { NlpValueModel } from '../schemas/nlp-value.schema';
import { NlpEntity } from '../schemas/nlp-entity.schema';
import { NlpEntityService } from './nlp-entity.service';
import { NlpValueService } from './nlp-value.service';
describe('NlpEntityService', () => {
let nlpEntityService: NlpEntityService;
@@ -36,29 +29,9 @@ describe('NlpEntityService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installNlpValueFixtures),
MongooseModule.forFeature([
NlpEntityModel,
NlpValueModel,
NlpSampleEntityModel,
]),
],
providers: [
NlpEntityService,
NlpEntityRepository,
NlpValueService,
NlpValueRepository,
NlpSampleEntityRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
set: jest.fn(),
get: jest.fn(),
},
},
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installNlpValueFixtures)],
providers: [NlpEntityService],
});
[nlpEntityService, nlpEntityRepository, nlpValueRepository] =
await getMocks([

View File

@@ -6,11 +6,8 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { Language, LanguageModel } from '@/i18n/schemas/language.schema';
import { Language } from '@/i18n/schemas/language.schema';
import { nlpSampleFixtures } from '@/utils/test/fixtures/nlpsample';
import {
installNlpSampleEntityFixtures,
@@ -28,19 +25,13 @@ import { buildTestingMocks } from '@/utils/test/utils';
import { NlpSampleEntityCreateDto } from '../dto/nlp-sample-entity.dto';
import { NlpEntityRepository } from '../repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '../repositories/nlp-sample-entity.repository';
import { NlpValueRepository } from '../repositories/nlp-value.repository';
import { NlpEntity, NlpEntityModel } from '../schemas/nlp-entity.schema';
import { NlpEntity } from '../schemas/nlp-entity.schema';
import {
NlpSampleEntity,
NlpSampleEntityFull,
NlpSampleEntityModel,
} from '../schemas/nlp-sample-entity.schema';
import { NlpSample, NlpSampleModel } from '../schemas/nlp-sample.schema';
import {
NlpValue,
NlpValueModel,
NlpValueStub,
} from '../schemas/nlp-value.schema';
import { NlpSample } from '../schemas/nlp-sample.schema';
import { NlpValue, NlpValueStub } from '../schemas/nlp-value.schema';
import { NlpEntityService } from './nlp-entity.service';
import { NlpSampleEntityService } from './nlp-sample-entity.service';
@@ -59,38 +50,16 @@ describe('NlpSampleEntityService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installNlpSampleEntityFixtures),
MongooseModule.forFeature([
NlpSampleEntityModel,
NlpEntityModel,
NlpSampleModel,
NlpValueModel,
LanguageModel,
]),
],
providers: [
NlpSampleEntityRepository,
NlpEntityRepository,
NlpValueRepository,
LanguageRepository,
NlpSampleEntityService,
NlpEntityService,
NlpValueService,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
},
},
],
models: ['NlpSampleModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installNlpSampleEntityFixtures)],
providers: [NlpSampleEntityService, LanguageRepository],
});
[
nlpSampleEntityService,
nlpSampleEntityRepository,
nlpEntityRepository,
languageRepository,
nlpSampleEntityService,
nlpEntityService,
nlpValueService,
] = await getMocks([
@@ -98,7 +67,6 @@ describe('NlpSampleEntityService', () => {
NlpSampleEntityRepository,
NlpEntityRepository,
LanguageRepository,
NlpSampleEntityService,
NlpEntityService,
NlpValueService,
]);

View File

@@ -6,13 +6,11 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { NlpValueMatchPattern } from '@/chat/schemas/types/pattern';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { Language, LanguageModel } from '@/i18n/schemas/language.schema';
import { Language } from '@/i18n/schemas/language.schema';
import { LanguageService } from '@/i18n/services/language.service';
import { PageQueryDto } from '@/utils/pagination/pagination-query.dto';
import { nlpSampleFixtures } from '@/utils/test/fixtures/nlpsample';
@@ -25,25 +23,11 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { NlpSampleEntityCreateDto } from '../dto/nlp-sample-entity.dto';
import { NlpEntityRepository } from '../repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '../repositories/nlp-sample-entity.repository';
import { NlpSampleRepository } from '../repositories/nlp-sample.repository';
import { NlpValueRepository } from '../repositories/nlp-value.repository';
import {
NlpEntity,
NlpEntityFull,
NlpEntityModel,
} from '../schemas/nlp-entity.schema';
import {
NlpSampleEntity,
NlpSampleEntityModel,
} from '../schemas/nlp-sample-entity.schema';
import {
NlpSample,
NlpSampleFull,
NlpSampleModel,
} from '../schemas/nlp-sample.schema';
import { NlpValueModel } from '../schemas/nlp-value.schema';
import { NlpEntity, NlpEntityFull } from '../schemas/nlp-entity.schema';
import { NlpSampleEntity } from '../schemas/nlp-sample-entity.schema';
import { NlpSample, NlpSampleFull } from '../schemas/nlp-sample.schema';
import { NlpEntityService } from './nlp-entity.service';
import { NlpSampleEntityService } from './nlp-sample-entity.service';
@@ -65,37 +49,9 @@ describe('NlpSampleService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installNlpSampleEntityFixtures),
MongooseModule.forFeature([
NlpSampleModel,
NlpSampleEntityModel,
NlpValueModel,
NlpEntityModel,
LanguageModel,
]),
],
providers: [
NlpSampleRepository,
NlpSampleEntityRepository,
NlpEntityRepository,
NlpValueRepository,
LanguageRepository,
NlpSampleService,
NlpSampleEntityService,
NlpEntityService,
NlpValueService,
LanguageService,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installNlpSampleEntityFixtures)],
providers: [NlpSampleService],
});
[
nlpEntityService,

View File

@@ -6,9 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { BaseSchema } from '@/utils/generics/base-schema';
import { nlpEntityFixtures } from '@/utils/test/fixtures/nlpentity';
import {
@@ -23,15 +20,9 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { NlpEntityRepository } from '../repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '../repositories/nlp-sample-entity.repository';
import { NlpValueRepository } from '../repositories/nlp-value.repository';
import { NlpEntity, NlpEntityModel } from '../schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '../schemas/nlp-sample-entity.schema';
import {
NlpValue,
NlpValueFull,
NlpValueModel,
} from '../schemas/nlp-value.schema';
import { NlpEntity } from '../schemas/nlp-entity.schema';
import { NlpValue, NlpValueFull } from '../schemas/nlp-value.schema';
import { NlpEntityService } from './nlp-entity.service';
import { NlpValueService } from './nlp-value.service';
@@ -45,29 +36,9 @@ describe('NlpValueService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installNlpValueFixtures),
MongooseModule.forFeature([
NlpValueModel,
NlpSampleEntityModel,
NlpEntityModel,
]),
],
providers: [
NlpValueRepository,
NlpSampleEntityRepository,
NlpEntityRepository,
NlpValueService,
NlpEntityService,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
set: jest.fn(),
get: jest.fn(),
},
},
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installNlpValueFixtures)],
providers: [NlpValueService, NlpEntityService],
});
[
nlpValueService,

View File

@@ -6,17 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { HelperService } from '@/helper/helper.service';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { LanguageModel } from '@/i18n/schemas/language.schema';
import { LanguageService } from '@/i18n/services/language.service';
import { SettingRepository } from '@/setting/repositories/setting.repository';
import { SettingModel } from '@/setting/schemas/setting.schema';
import { SettingSeeder } from '@/setting/seeds/setting.seed';
import { SettingService } from '@/setting/services/setting.service';
import { installNlpValueFixtures } from '@/utils/test/fixtures/nlpvalue';
import {
closeInMongodConnection,
@@ -24,19 +13,6 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { NlpEntityRepository } from '../repositories/nlp-entity.repository';
import { NlpSampleEntityRepository } from '../repositories/nlp-sample-entity.repository';
import { NlpSampleRepository } from '../repositories/nlp-sample.repository';
import { NlpValueRepository } from '../repositories/nlp-value.repository';
import { NlpEntityModel } from '../schemas/nlp-entity.schema';
import { NlpSampleEntityModel } from '../schemas/nlp-sample-entity.schema';
import { NlpSampleModel } from '../schemas/nlp-sample.schema';
import { NlpValueModel } from '../schemas/nlp-value.schema';
import { NlpEntityService } from './nlp-entity.service';
import { NlpSampleEntityService } from './nlp-sample-entity.service';
import { NlpSampleService } from './nlp-sample.service';
import { NlpValueService } from './nlp-value.service';
import { NlpService } from './nlp.service';
describe('NlpService', () => {
@@ -44,42 +20,9 @@ describe('NlpService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installNlpValueFixtures),
MongooseModule.forFeature([
NlpEntityModel,
NlpValueModel,
NlpSampleEntityModel,
NlpSampleModel,
LanguageModel,
SettingModel,
]),
],
providers: [
NlpService,
NlpEntityService,
NlpEntityRepository,
NlpValueService,
NlpSampleService,
NlpSampleEntityService,
HelperService,
LanguageService,
SettingService,
NlpValueRepository,
NlpSampleEntityRepository,
NlpSampleRepository,
SettingRepository,
SettingSeeder,
LanguageRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
set: jest.fn(),
get: jest.fn(),
},
},
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installNlpValueFixtures)],
providers: [NlpService],
});
[nlpService] = await getMocks([NlpService]);
});

View File

@@ -8,15 +8,18 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { Document, Query } from 'mongoose';
import { HelperService } from '@/helper/helper.service';
import { HelperType, NLU } from '@/helper/types';
import { LoggerService } from '@/logger/logger.service';
import { TFilterQuery } from '@/utils/types/filter.types';
import { NlpEntity, NlpEntityDocument } from '../schemas/nlp-entity.schema';
import { NlpValue, NlpValueDocument } from '../schemas/nlp-value.schema';
import { NlpEntityService } from './nlp-entity.service';
import { NlpSampleEntityService } from './nlp-sample-entity.service';
import { NlpSampleService } from './nlp-sample.service';
import { NlpValueService } from './nlp-value.service';
@@ -28,6 +31,7 @@ export class NlpService {
protected readonly nlpEntityService: NlpEntityService,
protected readonly nlpValueService: NlpValueService,
protected readonly helperService: HelperService,
protected readonly nlpSampleEntityService: NlpSampleEntityService,
) {}
/**
@@ -66,21 +70,25 @@ export class NlpService {
*
* @param entity - The NLP entity to be created.
*/
@OnEvent('hook:nlpEntity:create')
async handleEntityCreate(entity: NlpEntityDocument) {
// Synchonize new entity with NLP
try {
const helper = await this.helperService.getDefaultHelper(HelperType.NLU);
const foreignId = await helper.addEntity(entity);
this.logger.debug('New entity successfully synced!', foreignId);
await this.nlpEntityService.updateOne(
{ _id: entity._id },
{
foreign_id: foreignId,
},
);
} catch (err) {
this.logger.error('Unable to sync a new entity', err);
@OnEvent('hook:nlpEntity:postCreate')
async handleEntityPostCreate(created: NlpEntityDocument) {
if (!created.builtin) {
// Synchonize new entity with NLP
try {
const helper = await this.helperService.getDefaultHelper(
HelperType.NLU,
);
const foreignId = await helper.addEntity(created);
this.logger.debug('New entity successfully synced!', foreignId);
await this.nlpEntityService.updateOne(
{ _id: created._id },
{
foreign_id: foreignId,
},
);
} catch (err) {
this.logger.error('Unable to sync a new entity', err);
}
}
}
@@ -89,37 +97,68 @@ export class NlpService {
*
* @param entity - The NLP entity to be updated.
*/
@OnEvent('hook:nlpEntity:update')
async handleEntityUpdate(entity: NlpEntity) {
// Synchonize new entity with NLP provider
try {
const helper = await this.helperService.getDefaultNluHelper();
await helper.updateEntity(entity);
this.logger.debug('Updated entity successfully synced!', entity);
} catch (err) {
this.logger.error('Unable to sync updated entity', err);
@OnEvent('hook:nlpEntity:postUpdate')
async handleEntityPostUpdate(
_query: Query<
Document<NlpEntity>,
Document<NlpEntity>,
unknown,
NlpEntity,
'findOneAndUpdate'
>,
updated: NlpEntity,
) {
if (!updated?.builtin) {
// Synchonize new entity with NLP provider
try {
const helper = await this.helperService.getDefaultHelper(
HelperType.NLU,
);
await helper.updateEntity(updated);
this.logger.debug('Updated entity successfully synced!', updated);
} catch (err) {
this.logger.error('Unable to sync updated entity', err);
}
}
}
/**
* Handles the event triggered when an NLP entity is deleted. Synchronizes the deletion with the external NLP provider.
* Before deleting a `nlpEntity`, this method deletes the related `nlpValue` and `nlpSampleEntity`. Synchronizes the deletion with the external NLP provider
*
* @param entity - The NLP entity to be deleted.
* @param _query - The Mongoose query object used for deletion.
* @param criteria - The filter criteria for finding the nlpEntities to be deleted.
*/
@OnEvent('hook:nlpEntity:delete')
async handleEntityDelete(entity: NlpEntity) {
// Synchonize new entity with NLP provider
try {
if (entity.foreign_id) {
const helper = await this.helperService.getDefaultNluHelper();
await helper.deleteEntity(entity.foreign_id);
this.logger.debug('Deleted entity successfully synced!', entity);
} else {
this.logger.error(`Entity ${entity} is missing foreign_id`);
throw new NotFoundException(`Entity ${entity} is missing foreign_id`);
@OnEvent('hook:nlpEntity:preDelete')
async handleEntityDelete(
_query: unknown,
criteria: TFilterQuery<NlpEntity>,
): Promise<void> {
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
try {
if (entity.foreign_id) {
await helper.deleteEntity(entity.foreign_id);
this.logger.debug('Deleted entity successfully synced!', entity);
} else {
this.logger.error(`Entity ${entity} is missing foreign_id`);
throw new NotFoundException(
`Entity ${entity} is missing foreign_id`,
);
}
} catch (err) {
this.logger.error('Unable to sync deleted entity', err);
}
}
} catch (err) {
this.logger.error('Unable to sync deleted entity', err);
}
}
@@ -128,21 +167,25 @@ export class NlpService {
*
* @param value - The NLP value to be created.
*/
@OnEvent('hook:nlpValue:create')
async handleValueCreate(value: NlpValueDocument) {
// Synchonize new value with NLP provider
try {
const helper = await this.helperService.getDefaultNluHelper();
const foreignId = await helper.addValue(value);
this.logger.debug('New value successfully synced!', foreignId);
await this.nlpValueService.updateOne(
{ _id: value._id },
{
foreign_id: foreignId,
},
);
} catch (err) {
this.logger.error('Unable to sync a new value', err);
@OnEvent('hook:nlpValue:postCreate')
async handleValuePostCreate(created: NlpValueDocument) {
if (!created.builtin) {
// Synchonize new value with NLP provider
try {
const helper = await this.helperService.getDefaultHelper(
HelperType.NLU,
);
const foreignId = await helper.addValue(created);
this.logger.debug('New value successfully synced!', foreignId);
await this.nlpValueService.updateOne(
{ _id: created._id },
{
foreign_id: foreignId,
},
);
} catch (err) {
this.logger.error('Unable to sync a new value', err);
}
}
}
@@ -151,37 +194,71 @@ export class NlpService {
*
* @param value - The NLP value to be updated.
*/
@OnEvent('hook:nlpValue:update')
async handleValueUpdate(value: NlpValue) {
// Synchonize new value with NLP provider
try {
const helper = await this.helperService.getDefaultNluHelper();
await helper.updateValue(value);
this.logger.debug('Updated value successfully synced!', value);
} catch (err) {
this.logger.error('Unable to sync updated value', err);
@OnEvent('hook:nlpValue:postUpdate')
async handleValuePostUpdate(
_query: Query<
Document<NlpValue, any, any>,
Document<NlpValue, any, any>,
unknown,
NlpValue,
'findOneAndUpdate'
>,
updated: NlpValue,
) {
if (!updated?.builtin) {
// Synchonize new value with NLP provider
try {
const helper = await this.helperService.getDefaultHelper(
HelperType.NLU,
);
await helper.updateValue(updated);
this.logger.debug('Updated value successfully synced!', updated);
} catch (err) {
this.logger.error('Unable to sync updated value', err);
}
}
}
/**
* Handles the event triggered when an NLP value is deleted. Synchronizes the deletion with the external NLP provider.
* Before deleting a `nlpValue`, this method deletes the related `nlpSampleEntity`. Synchronizes the deletion with the external NLP provider
*
* @param value - The NLP value to be deleted.
* @param _query - The Mongoose query object used for deletion.
* @param criteria - The filter criteria for finding the nlpValues to be deleted.
*/
@OnEvent('hook:nlpValue:delete')
async handleValueDelete(value: NlpValue) {
// Synchonize new value with NLP provider
try {
const helper = await this.helperService.getDefaultNluHelper();
const populatedValue = await this.nlpValueService.findOneAndPopulate(
value.id,
);
if (populatedValue) {
await helper.deleteValue(populatedValue);
this.logger.debug('Deleted value successfully synced!', value);
@OnEvent('hook:nlpValue:preDelete')
async handleValueDelete(
_query: unknown,
criteria: TFilterQuery<NlpValue>,
): Promise<void> {
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
try {
const populatedValue = await this.nlpValueService.findOneAndPopulate(
value.id,
);
if (populatedValue) {
await helper.deleteValue(populatedValue);
this.logger.debug('Deleted value successfully synced!', value);
}
} catch (err) {
this.logger.error('Unable to sync deleted value', err);
}
}
} catch (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');
}
}
}

View File

@@ -6,9 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { I18nService } from '@/i18n/services/i18n.service';
import {
installSettingFixtures,
@@ -20,9 +17,7 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { SettingRepository } from '../repositories/setting.repository';
import { Setting, SettingModel } from '../schemas/setting.schema';
import { SettingSeeder } from '../seeds/setting.seed';
import { Setting } from '../schemas/setting.schema';
import { SettingService } from '../services/setting.service';
import { SettingController } from './setting.controller';
@@ -33,29 +28,16 @@ describe('SettingController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [SettingController],
imports: [
rootMongooseTestModule(installSettingFixtures),
MongooseModule.forFeature([SettingModel]),
],
imports: [rootMongooseTestModule(installSettingFixtures)],
providers: [
SettingService,
SettingRepository,
SettingSeeder,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
});
[settingController, settingService] = await getMocks([

View File

@@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { getModelToken, MongooseModule } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { installSettingFixtures } from '@/utils/test/fixtures/setting';
@@ -16,7 +16,7 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { Setting, SettingModel } from '../schemas/setting.schema';
import { Setting } from '../schemas/setting.schema';
import { SettingType } from '../schemas/types';
import { SettingRepository } from './setting.repository';
@@ -27,10 +27,8 @@ describe('SettingRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installSettingFixtures),
MongooseModule.forFeature([SettingModel]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installSettingFixtures)],
providers: [SettingRepository],
});
[settingRepository, settingModel] = await getMocks([

View File

@@ -6,9 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { I18nService } from '@/i18n/services/i18n.service';
import {
installSettingFixtures,
@@ -21,9 +18,8 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { SettingRepository } from '../repositories/setting.repository';
import { Setting, SettingModel } from '../schemas/setting.schema';
import { Setting } from '../schemas/setting.schema';
import { SettingType } from '../schemas/types';
import { SettingSeeder } from '../seeds/setting.seed';
import { SettingService } from './setting.service';
@@ -39,28 +35,16 @@ describe('SettingService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installSettingFixtures),
MongooseModule.forFeature([SettingModel]),
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installSettingFixtures)],
providers: [
SettingService,
SettingRepository,
SettingSeeder,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
});
[settingService, settingRepository] = await getMocks([

View File

@@ -6,24 +6,16 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import {
InternalServerErrorException,
UnauthorizedException,
} from '@nestjs/common';
import { BadRequestException } from '@nestjs/common/exceptions/bad-request.exception';
import { JwtService } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { ISendMailOptions, MailerService } from '@nestjs-modules/mailer';
import { SentMessageInfo } from 'nodemailer';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { LanguageModel } from '@/i18n/schemas/language.schema';
import { I18nService } from '@/i18n/services/i18n.service';
import { LanguageService } from '@/i18n/services/language.service';
import { getRandom } from '@/utils/helpers/safeRandom';
import { installLanguageFixtures } from '@/utils/test/fixtures/language';
import { installUserFixtures } from '@/utils/test/fixtures/user';
@@ -32,23 +24,12 @@ import {
rootMongooseTestModule,
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { SocketEventDispatcherService } from '@/websocket/services/socket-event-dispatcher.service';
import { WebsocketGateway } from '@/websocket/websocket.gateway';
import { UserCreateDto } from '../dto/user.dto';
import { InvitationRepository } from '../repositories/invitation.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { Role, RoleModel } from '../schemas/role.schema';
import { UserModel } from '../schemas/user.schema';
import { Role } from '../schemas/role.schema';
import { InvitationService } from '../services/invitation.service';
import { PermissionService } from '../services/permission.service';
import { RoleService } from '../services/role.service';
import { UserService } from '../services/user.service';
import { ValidateAccountService } from '../services/validate-account.service';
import { LocalAuthController } from './auth.controller';
@@ -63,37 +44,17 @@ describe('AuthController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
models: ['PermissionModel'],
autoInjectFrom: ['controllers', 'providers'],
controllers: [LocalAuthController],
imports: [
rootMongooseTestModule(async () => {
await installLanguageFixtures();
await installUserFixtures();
}),
MongooseModule.forFeature([
UserModel,
RoleModel,
PermissionModel,
InvitationModel,
AttachmentModel,
LanguageModel,
]),
],
providers: [
UserService,
WebsocketGateway,
SocketEventDispatcherService,
AttachmentService,
AttachmentRepository,
UserRepository,
PermissionService,
RoleService,
RoleRepository,
PermissionRepository,
InvitationRepository,
InvitationService,
LanguageRepository,
LanguageService,
JwtService,
{
provide: MailerService,
useValue: {
@@ -102,15 +63,6 @@ describe('AuthController', () => {
},
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
ValidateAccountService,
{
provide: I18nService,
useValue: {

View File

@@ -6,12 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import {
installModelFixtures,
modelFixtures,
@@ -22,20 +16,9 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { InvitationRepository } from '../repositories/invitation.repository';
import { ModelRepository } from '../repositories/model.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { ModelFull, ModelModel } from '../schemas/model.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { RoleModel } from '../schemas/role.schema';
import { UserModel } from '../schemas/user.schema';
import { ModelFull } from '../schemas/model.schema';
import { ModelService } from '../services/model.service';
import { PermissionService } from '../services/permission.service';
import { RoleService } from '../services/role.service';
import { UserService } from '../services/user.service';
import { ModelController } from './model.controller';
@@ -46,39 +29,11 @@ describe('ModelController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
models: ['PermissionModel'],
autoInjectFrom: ['controllers', 'providers'],
controllers: [ModelController],
imports: [
rootMongooseTestModule(installModelFixtures),
MongooseModule.forFeature([
UserModel,
RoleModel,
PermissionModel,
InvitationModel,
ModelModel,
AttachmentModel,
]),
],
providers: [
PermissionService,
AttachmentService,
AttachmentRepository,
ModelService,
ModelRepository,
UserService,
UserRepository,
RoleService,
RoleRepository,
InvitationRepository,
PermissionRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
imports: [rootMongooseTestModule(installModelFixtures)],
providers: [PermissionService],
});
[modelController, modelService, permissionService] = await getMocks([
ModelController,

View File

@@ -6,9 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { NotFoundException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { installPermissionFixtures } from '@/utils/test/fixtures/permission';
import {
@@ -18,18 +16,9 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { PermissionCreateDto } from '../dto/permission.dto';
import { InvitationRepository } from '../repositories/invitation.repository';
import { ModelRepository } from '../repositories/model.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { Model, ModelModel } from '../schemas/model.schema';
import {
Permission,
PermissionFull,
PermissionModel,
} from '../schemas/permission.schema';
import { Role, RoleModel } from '../schemas/role.schema';
import { Model } from '../schemas/model.schema';
import { Permission, PermissionFull } from '../schemas/permission.schema';
import { Role } from '../schemas/role.schema';
import { ModelService } from '../services/model.service';
import { PermissionService } from '../services/permission.service';
import { RoleService } from '../services/role.service';
@@ -50,33 +39,10 @@ describe('PermissionController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
models: ['InvitationModel'],
autoInjectFrom: ['controllers'],
controllers: [PermissionController],
imports: [
rootMongooseTestModule(installPermissionFixtures),
MongooseModule.forFeature([
PermissionModel,
ModelModel,
RoleModel,
InvitationModel,
]),
],
providers: [
RoleService,
ModelService,
PermissionService,
PermissionRepository,
RoleRepository,
InvitationRepository,
ModelRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
imports: [rootMongooseTestModule(installPermissionFixtures)],
});
[permissionController, roleService, modelService, permissionService] =
await getMocks([

View File

@@ -6,14 +6,9 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { ForbiddenException, NotFoundException } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { Request } from 'express';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { installPermissionFixtures } from '@/utils/test/fixtures/permission';
import { roleFixtures } from '@/utils/test/fixtures/role';
import { getPageQuery } from '@/utils/test/pagination';
@@ -24,14 +19,7 @@ import {
import { buildTestingMocks } from '@/utils/test/utils';
import { RoleCreateDto, RoleUpdateDto } from '../dto/role.dto';
import { InvitationRepository } from '../repositories/invitation.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { Role, RoleFull, RoleModel } from '../schemas/role.schema';
import { UserModel } from '../schemas/user.schema';
import { Role, RoleFull } from '../schemas/role.schema';
import { PermissionService } from '../services/permission.service';
import { RoleService } from '../services/role.service';
import { UserService } from '../services/user.service';
@@ -48,36 +36,11 @@ describe('RoleController', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
models: ['InvitationModel'],
autoInjectFrom: ['controllers', 'providers'],
controllers: [RoleController],
imports: [
rootMongooseTestModule(installPermissionFixtures),
MongooseModule.forFeature([
RoleModel,
PermissionModel,
UserModel,
InvitationModel,
AttachmentModel,
]),
],
providers: [
PermissionService,
UserService,
UserRepository,
RoleService,
RoleRepository,
InvitationRepository,
PermissionRepository,
AttachmentService,
AttachmentRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
imports: [rootMongooseTestModule(installPermissionFixtures)],
providers: [PermissionService],
});
[roleController, roleService, permissionService, userService] =
await getMocks([

View File

@@ -6,21 +6,13 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { ForbiddenException, NotFoundException } from '@nestjs/common';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { JwtService } from '@nestjs/jwt';
import { ISendMailOptions, MailerService } from '@nestjs-modules/mailer';
import { Session as ExpressSession } from 'express-session';
import { SentMessageInfo } from 'nodemailer';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { LanguageModel } from '@/i18n/schemas/language.schema';
import { I18nService } from '@/i18n/services/i18n.service';
import { LanguageService } from '@/i18n/services/language.service';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import { installLanguageFixtures } from '@/utils/test/fixtures/language';
import { installPermissionFixtures } from '@/utils/test/fixtures/permission';
@@ -38,19 +30,11 @@ import {
UserEditProfileDto,
UserUpdateStateAndRolesDto,
} from '../dto/user.dto';
import { InvitationRepository } from '../repositories/invitation.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { Role, RoleModel } from '../schemas/role.schema';
import { User, UserFull, UserModel } from '../schemas/user.schema';
import { Role } from '../schemas/role.schema';
import { User, UserFull } from '../schemas/user.schema';
import { PasswordResetService } from '../services/passwordReset.service';
import { PermissionService } from '../services/permission.service';
import { RoleService } from '../services/role.service';
import { UserService } from '../services/user.service';
import { ValidateAccountService } from '../services/validate-account.service';
import { InvitationService } from './../services/invitation.service';
import { ReadWriteUserController } from './user.controller';
@@ -68,28 +52,15 @@ describe('UserController', () => {
let jwtService: JwtService;
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['controllers'],
controllers: [ReadWriteUserController],
imports: [
rootMongooseTestModule(async () => {
await installLanguageFixtures();
await installPermissionFixtures();
}),
MongooseModule.forFeature([
UserModel,
RoleModel,
PermissionModel,
InvitationModel,
AttachmentModel,
LanguageModel,
]),
JwtModule,
],
providers: [
RoleService,
UserService,
InvitationService,
PasswordResetService,
PermissionService,
{
provide: MailerService,
useValue: {
@@ -98,23 +69,6 @@ describe('UserController', () => {
},
},
},
UserRepository,
RoleRepository,
PermissionRepository,
InvitationRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
AttachmentService,
AttachmentRepository,
LanguageService,
LanguageRepository,
ValidateAccountService,
{
provide: I18nService,
useValue: {

View File

@@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { PageQueryDto } from '@/utils/pagination/pagination-query.dto';
@@ -21,16 +21,9 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import {
Invitation,
InvitationFull,
InvitationModel,
} from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { RoleModel } from '../schemas/role.schema';
import { Invitation, InvitationFull } from '../schemas/invitation.schema';
import { InvitationRepository } from './invitation.repository';
import { PermissionRepository } from './permission.repository';
import { RoleRepository } from './role.repository';
describe('InvitationRepository', () => {
@@ -39,15 +32,10 @@ describe('InvitationRepository', () => {
let invitationModel: Model<Invitation>;
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installInvitationFixtures),
MongooseModule.forFeature([
RoleModel,
PermissionModel,
InvitationModel,
]),
],
providers: [RoleRepository, InvitationRepository, PermissionRepository],
models: ['PermissionModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installInvitationFixtures)],
providers: [RoleRepository, InvitationRepository],
});
[roleRepository, invitationRepository, invitationModel] = await getMocks([
RoleRepository,

View File

@@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { modelFixtures } from '@/utils/test/fixtures/model';
@@ -19,8 +19,8 @@ import { buildTestingMocks } from '@/utils/test/utils';
import { ModelRepository } from '../repositories/model.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { ModelFull, ModelModel } from '../schemas/model.schema';
import { Permission, PermissionModel } from '../schemas/permission.schema';
import { ModelFull } from '../schemas/model.schema';
import { Permission } from '../schemas/permission.schema';
import { Model as ModelType } from './../schemas/model.schema';
@@ -33,10 +33,9 @@ describe('ModelRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installPermissionFixtures),
MongooseModule.forFeature([ModelModel, PermissionModel]),
],
autoInjectFrom: ['providers'],
models: ['PermissionModel'],
imports: [rootMongooseTestModule(installPermissionFixtures)],
providers: [ModelRepository, PermissionRepository],
});
[permissionRepository, modelRepository, modelModel] = await getMocks([

View File

@@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
@@ -22,18 +22,11 @@ import { buildTestingMocks } from '@/utils/test/utils';
import { ModelRepository } from '../repositories/model.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { ModelModel, Model as ModelSchema } from '../schemas/model.schema';
import {
Permission,
PermissionFull,
PermissionModel,
} from '../schemas/permission.schema';
import { Role, RoleModel } from '../schemas/role.schema';
import { Model as ModelSchema } from '../schemas/model.schema';
import { Permission, PermissionFull } from '../schemas/permission.schema';
import { Role } from '../schemas/role.schema';
import { Action } from '../types/action.type';
import { InvitationRepository } from './invitation.repository';
describe('PermissionRepository', () => {
let modelRepository: ModelRepository;
let roleRepository: RoleRepository;
@@ -44,21 +37,10 @@ describe('PermissionRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installPermissionFixtures),
MongooseModule.forFeature([
ModelModel,
PermissionModel,
RoleModel,
InvitationModel,
]),
],
providers: [
ModelRepository,
RoleRepository,
PermissionRepository,
InvitationRepository,
],
models: ['InvitationModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installPermissionFixtures)],
providers: [ModelRepository, RoleRepository, PermissionRepository],
});
[roleRepository, modelRepository, permissionRepository, permissionModel] =
await getMocks([

View File

@@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { installPermissionFixtures } from '@/utils/test/fixtures/permission';
@@ -20,13 +20,10 @@ import { buildTestingMocks } from '@/utils/test/utils';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { Role, RoleFull, RoleModel } from '../schemas/role.schema';
import { User, UserModel } from '../schemas/user.schema';
import { Role, RoleFull } from '../schemas/role.schema';
import { User } from '../schemas/user.schema';
import { roleFixtures } from './../../utils/test/fixtures/role';
import { InvitationRepository } from './invitation.repository';
describe('RoleRepository', () => {
let roleRepository: RoleRepository;
@@ -39,21 +36,10 @@ describe('RoleRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installPermissionFixtures),
MongooseModule.forFeature([
UserModel,
PermissionModel,
RoleModel,
InvitationModel,
]),
],
providers: [
UserRepository,
RoleRepository,
InvitationRepository,
PermissionRepository,
],
models: ['UserModel', 'InvitationModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installPermissionFixtures)],
providers: [UserRepository, RoleRepository, PermissionRepository],
});
[roleRepository, userRepository, permissionRepository, roleModel] =
await getMocks([

View File

@@ -6,11 +6,9 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import { installPermissionFixtures } from '@/utils/test/fixtures/permission';
import { userFixtures } from '@/utils/test/fixtures/user';
@@ -21,15 +19,10 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { Role, RoleModel } from '../schemas/role.schema';
import { User, UserFull, UserModel } from '../schemas/user.schema';
import { InvitationRepository } from './invitation.repository';
import { Role } from '../schemas/role.schema';
import { User, UserFull } from '../schemas/user.schema';
describe('UserRepository', () => {
let roleRepository: RoleRepository;
@@ -52,30 +45,10 @@ describe('UserRepository', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installPermissionFixtures),
MongooseModule.forFeature([
UserModel,
PermissionModel,
RoleModel,
InvitationModel,
AttachmentModel,
]),
],
providers: [
UserRepository,
RoleRepository,
InvitationRepository,
PermissionRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
models: ['PermissionModel', 'InvitationModel', 'AttachmentModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installPermissionFixtures)],
providers: [UserRepository, RoleRepository],
});
[roleRepository, userRepository, userModel] = await getMocks([
RoleRepository,

View File

@@ -6,12 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { JwtService } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { installUserFixtures } from '@/utils/test/fixtures/user';
import {
closeInMongodConnection,
@@ -19,17 +13,9 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { InvitationRepository } from '../repositories/invitation.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { RoleModel } from '../schemas/role.schema';
import { UserModel } from '../schemas/user.schema';
import { AuthService } from './auth.service';
import { RoleService } from './role.service';
import { UserService } from './user.service';
describe('AuthService', () => {
let authService: AuthService;
@@ -37,27 +23,9 @@ describe('AuthService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installUserFixtures),
MongooseModule.forFeature([
UserModel,
RoleModel,
PermissionModel,
InvitationModel,
AttachmentModel,
]),
],
providers: [
AuthService,
UserService,
UserRepository,
RoleService,
RoleRepository,
InvitationRepository,
JwtService,
AttachmentService,
AttachmentRepository,
],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installUserFixtures)],
providers: [AuthService],
});
[authService, userRepository] = await getMocks([
AuthService,

View File

@@ -6,16 +6,11 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { ISendMailOptions, MailerService } from '@nestjs-modules/mailer';
import { SentMessageInfo } from 'nodemailer';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { LanguageModel } from '@/i18n/schemas/language.schema';
import { I18nService } from '@/i18n/services/i18n.service';
import { LanguageService } from '@/i18n/services/language.service';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import {
installInvitationFixtures,
@@ -30,15 +25,9 @@ import { buildTestingMocks } from '@/utils/test/utils';
import { InvitationCreateDto } from '../dto/invitation.dto';
import { InvitationRepository } from '../repositories/invitation.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { RoleModel } from '../schemas/role.schema';
import { InvitationService } from './invitation.service';
import { PermissionService } from './permission.service';
import { RoleService } from './role.service';
describe('InvitationService', () => {
let invitationService: InvitationService;
@@ -50,35 +39,24 @@ describe('InvitationService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
models: ['PermissionModel'],
autoInjectFrom: ['providers'],
imports: [
rootMongooseTestModule(async () => {
await installLanguageFixtures();
await installInvitationFixtures();
}),
MongooseModule.forFeature([
RoleModel,
PermissionModel,
InvitationModel,
LanguageModel,
]),
JwtModule,
],
providers: [
PermissionService,
RoleService,
RoleRepository,
PermissionRepository,
InvitationRepository,
InvitationService,
LanguageRepository,
LanguageService,
RoleRepository,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
InvitationRepository,
{
provide: MailerService,
useValue: {
@@ -88,14 +66,6 @@ describe('InvitationService', () => {
),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
});
[

View File

@@ -6,8 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import { modelFixtures } from '@/utils/test/fixtures/model';
import { installPermissionFixtures } from '@/utils/test/fixtures/permission';
import {
@@ -18,8 +16,8 @@ import { buildTestingMocks } from '@/utils/test/utils';
import { ModelRepository } from '../repositories/model.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { Model, ModelFull, ModelModel } from '../schemas/model.schema';
import { Permission, PermissionModel } from '../schemas/permission.schema';
import { Model, ModelFull } from '../schemas/model.schema';
import { Permission } from '../schemas/permission.schema';
import { ModelService } from './model.service';
@@ -32,11 +30,10 @@ describe('ModelService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installPermissionFixtures),
MongooseModule.forFeature([ModelModel, PermissionModel]),
],
providers: [ModelService, ModelRepository, PermissionRepository],
models: ['PermissionModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installPermissionFixtures)],
providers: [ModelService, PermissionRepository],
});
[modelService, permissionRepository, modelRepository] = await getMocks([
ModelService,

View File

@@ -6,22 +6,15 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { NotFoundException } from '@nestjs/common';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { JwtService } from '@nestjs/jwt';
import { getModelToken } from '@nestjs/mongoose';
import { ISendMailOptions, MailerService } from '@nestjs-modules/mailer';
import { compareSync } from 'bcryptjs';
import { Model } from 'mongoose';
import { SentMessageInfo } from 'nodemailer';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { LanguageModel } from '@/i18n/schemas/language.schema';
import { I18nService } from '@/i18n/services/i18n.service';
import { LanguageService } from '@/i18n/services/language.service';
import { installLanguageFixtures } from '@/utils/test/fixtures/language';
import { installUserFixtures, users } from '@/utils/test/fixtures/user';
import {
@@ -30,17 +23,9 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { InvitationRepository } from '../repositories/invitation.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { RoleModel } from '../schemas/role.schema';
import { User, UserModel } from '../schemas/user.schema';
import { User } from '../schemas/user.schema';
import { PasswordResetService } from './passwordReset.service';
import { RoleService } from './role.service';
import { UserService } from './user.service';
describe('PasswordResetService', () => {
let passwordResetService: PasswordResetService;
@@ -49,31 +34,14 @@ describe('PasswordResetService', () => {
let userModel: Model<User>;
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['providers'],
imports: [
rootMongooseTestModule(async () => {
await installLanguageFixtures();
await installUserFixtures();
}),
MongooseModule.forFeature([
UserModel,
RoleModel,
PermissionModel,
AttachmentModel,
LanguageModel,
InvitationModel,
]),
JwtModule,
],
providers: [
UserService,
UserRepository,
RoleService,
AttachmentService,
AttachmentRepository,
RoleRepository,
InvitationRepository,
LanguageService,
LanguageRepository,
PasswordResetService,
{
provide: MailerService,
@@ -90,14 +58,6 @@ describe('PasswordResetService', () => {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
});
[passwordResetService, mailerService, jwtService, userModel] =

View File

@@ -81,7 +81,7 @@ export class PasswordResetService {
'Could not send email',
e.message,
e.stack,
'InvitationService',
'PasswordResetService',
);
throw new InternalServerErrorException('Could not send email');
}

View File

@@ -6,9 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import {
installPermissionFixtures,
permissionFixtures,
@@ -19,18 +16,12 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { InvitationRepository } from '../repositories/invitation.repository';
import { ModelRepository } from '../repositories/model.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { ModelModel, Model as ModelSchema } from '../schemas/model.schema';
import {
Permission,
PermissionFull,
PermissionModel,
} from '../schemas/permission.schema';
import { Role, RoleModel } from '../schemas/role.schema';
import { Model as ModelSchema } from '../schemas/model.schema';
import { Permission, PermissionFull } from '../schemas/permission.schema';
import { Role } from '../schemas/role.schema';
import { Action } from '../types/action.type';
import { PermissionService } from './permission.service';
@@ -44,30 +35,10 @@ describe('PermissionService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installPermissionFixtures),
MongooseModule.forFeature([
ModelModel,
PermissionModel,
RoleModel,
InvitationModel,
]),
],
providers: [
ModelRepository,
PermissionService,
RoleRepository,
InvitationRepository,
PermissionRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
models: ['InvitationModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installPermissionFixtures)],
providers: [PermissionService, RoleRepository, ModelRepository],
});
[permissionService, roleRepository, modelRepository, permissionRepository] =
await getMocks([

View File

@@ -6,8 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { MongooseModule } from '@nestjs/mongoose';
import { installPermissionFixtures } from '@/utils/test/fixtures/permission';
import { getPageQuery } from '@/utils/test/pagination';
import {
@@ -16,14 +14,12 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { InvitationRepository } from '../repositories/invitation.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { Permission, PermissionModel } from '../schemas/permission.schema';
import { Role, RoleFull, RoleModel } from '../schemas/role.schema';
import { User, UserModel } from '../schemas/user.schema';
import { Permission } from '../schemas/permission.schema';
import { Role, RoleFull } from '../schemas/role.schema';
import { User } from '../schemas/user.schema';
import { roleFixtures } from './../../utils/test/fixtures/role';
import { RoleService } from './role.service';
@@ -39,22 +35,10 @@ describe('RoleService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installPermissionFixtures),
MongooseModule.forFeature([
UserModel,
PermissionModel,
RoleModel,
InvitationModel,
]),
],
providers: [
UserRepository,
RoleService,
RoleRepository,
InvitationRepository,
PermissionRepository,
],
models: ['PermissionModel', 'InvitationModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installPermissionFixtures)],
providers: [RoleService, UserRepository, PermissionRepository],
});
[roleService, roleRepository, userRepository, permissionRepository] =
await getMocks([

View File

@@ -6,12 +6,6 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { MongooseModule } from '@nestjs/mongoose';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import { installPermissionFixtures } from '@/utils/test/fixtures/permission';
import { userFixtures } from '@/utils/test/fixtures/user';
@@ -22,17 +16,11 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { InvitationRepository } from '../repositories/invitation.repository';
import { PermissionRepository } from '../repositories/permission.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { Role, RoleModel } from '../schemas/role.schema';
import { User, UserFull, UserModel } from '../schemas/user.schema';
import { Role } from '../schemas/role.schema';
import { User, UserFull } from '../schemas/user.schema';
import { PermissionService } from './permission.service';
import { RoleService } from './role.service';
import { UserService } from './user.service';
describe('UserService', () => {
@@ -55,35 +43,10 @@ describe('UserService', () => {
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
imports: [
rootMongooseTestModule(installPermissionFixtures),
MongooseModule.forFeature([
UserModel,
PermissionModel,
RoleModel,
InvitationModel,
AttachmentModel,
]),
],
providers: [
UserService,
AttachmentService,
AttachmentRepository,
UserRepository,
PermissionService,
RoleService,
RoleRepository,
InvitationRepository,
PermissionRepository,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
models: ['PermissionModel', 'InvitationModel', 'AttachmentModel'],
autoInjectFrom: ['providers'],
imports: [rootMongooseTestModule(installPermissionFixtures)],
providers: [UserService, RoleRepository],
});
[userService, roleRepository, userRepository] = await getMocks([
UserService,

View File

@@ -6,19 +6,10 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { JwtModule } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { ISendMailOptions, MailerService } from '@nestjs-modules/mailer';
import { SentMessageInfo } from 'nodemailer';
import { AttachmentRepository } from '@/attachment/repositories/attachment.repository';
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { LanguageRepository } from '@/i18n/repositories/language.repository';
import { LanguageModel } from '@/i18n/schemas/language.schema';
import { I18nService } from '@/i18n/services/i18n.service';
import { LanguageService } from '@/i18n/services/language.service';
import { installLanguageFixtures } from '@/utils/test/fixtures/language';
import { installUserFixtures, users } from '@/utils/test/fixtures/user';
import {
@@ -27,16 +18,6 @@ import {
} from '@/utils/test/test';
import { buildTestingMocks } from '@/utils/test/utils';
import { InvitationRepository } from '../repositories/invitation.repository';
import { RoleRepository } from '../repositories/role.repository';
import { UserRepository } from '../repositories/user.repository';
import { InvitationModel } from '../schemas/invitation.schema';
import { PermissionModel } from '../schemas/permission.schema';
import { RoleModel } from '../schemas/role.schema';
import { UserModel } from '../schemas/user.schema';
import { RoleService } from './role.service';
import { UserService } from './user.service';
import { ValidateAccountService } from './validate-account.service';
describe('ValidateAccountService', () => {
@@ -44,31 +25,16 @@ describe('ValidateAccountService', () => {
let mailerService: MailerService;
beforeAll(async () => {
const { getMocks } = await buildTestingMocks({
autoInjectFrom: ['providers'],
imports: [
rootMongooseTestModule(async () => {
await installLanguageFixtures();
await installUserFixtures();
}),
MongooseModule.forFeature([
UserModel,
RoleModel,
PermissionModel,
InvitationModel,
AttachmentModel,
LanguageModel,
]),
JwtModule,
],
providers: [
UserService,
AttachmentService,
AttachmentRepository,
UserRepository,
RoleService,
RoleRepository,
InvitationRepository,
LanguageService,
LanguageRepository,
ValidateAccountService,
{
provide: MailerService,
useValue: {
@@ -78,21 +44,12 @@ describe('ValidateAccountService', () => {
),
},
},
ValidateAccountService,
{
provide: I18nService,
useValue: {
t: jest.fn().mockImplementation((t) => t),
},
},
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
});
[validateAccountService, mailerService] = await getMocks([

View File

@@ -10,6 +10,8 @@ import { ModelDefinition } from '@nestjs/mongoose';
import { LifecycleHookManager } from './lifecycle-hook-manager';
afterEach(jest.clearAllMocks);
describe('LifecycleHookManager', () => {
let modelMock: ModelDefinition;
@@ -42,8 +44,10 @@ describe('LifecycleHookManager', () => {
});
it('should return hooks attached to a specific model', () => {
// Attach hooks to mock model
LifecycleHookManager.attach(modelMock);
if (!LifecycleHookManager.getModel(modelMock.name)) {
// Attach hooks to mock model
LifecycleHookManager.attach(modelMock);
}
// Retrieve hooks
const hooks = LifecycleHookManager.getHooks('TestModel');

View File

@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
@@ -39,6 +39,20 @@ interface Registry {
export class LifecycleHookManager {
private static registry: Registry = {};
private static models = new Map<string, ModelDefinition>();
public static getModel(name: string) {
return LifecycleHookManager.models.get(name);
}
private static addModel(model: ModelDefinition) {
if (LifecycleHookManager.models.has(model.name)) {
throw new Error(`Model with name ${model.name} already exists`);
}
LifecycleHookManager.models.set(model.name, model);
}
private static createLifecycleCallback<H = PreHook | PostHook>(): H {
let currentCallback = (..._args: any[]) => {};
@@ -57,6 +71,7 @@ export class LifecycleHookManager {
}
public static attach(model: ModelDefinition): ModelDefinition {
LifecycleHookManager.addModel(model);
const { name, schema } = model;
const operations: {
[key in LifecycleOperation]: ('pre' | 'post')[];

View File

@@ -81,7 +81,7 @@ const position = {
y: 0,
};
export const baseBlockInstance = {
export const baseBlockInstance: Partial<BlockFull> = {
trigger_labels: [labelMock],
assign_labels: [labelMock],
options: blockOptions,
@@ -90,7 +90,7 @@ export const baseBlockInstance = {
position,
builtin: true,
attachedBlock: null,
category: undefined,
category: null,
previousBlocks: [],
trigger_channels: [],
nextBlocks: [],

View File

@@ -6,18 +6,53 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { ModuleMetadata } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { ModuleMetadata, Provider } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { ModelDefinition, MongooseModule } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
import { LoggerService } from '@/logger/logger.service';
import { LifecycleHookManager } from '../generics/lifecycle-hook-manager';
type TTypeOrToken = [
new (...args: any[]) => any,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
...(new (...args: any[]) => any[]),
];
type TModel = ModelDefinition | `${string}Model`;
type ToUnionArray<T> = (NonNullable<T> extends (infer U)[] ? U : never)[];
type buildTestingMocksProps<
P extends ModuleMetadata['providers'] = ModuleMetadata['providers'],
C extends ModuleMetadata['controllers'] = ModuleMetadata['controllers'],
> = ModuleMetadata & {
models?: TModel[];
} & (
| {
providers: NonNullable<P>;
controllers: NonNullable<C>;
autoInjectFrom: ('providers' | 'controllers')[];
}
| {
providers: NonNullable<P>;
autoInjectFrom?: 'providers'[];
}
| {
controllers: NonNullable<C>;
autoInjectFrom?: 'controllers'[];
}
| {
providers?: never;
controllers?: never;
autoInjectFrom?: never;
}
);
const findInstances = async <T extends TTypeOrToken>(
type: keyof TestingModule,
module: TestingModule,
@@ -34,15 +69,232 @@ const extractInstances =
async <T extends TTypeOrToken>(types: T) =>
await findInstances(type, module, types);
/**
* Retrieves constructor parameter types (dependencies) of a NestJS provider class.
* Useful for inspecting dependencies to dynamically build NestJS testing modules.
*
* @param provider - The NestJS provider class to introspect.
* @returns An array of parameter types representing the constructor dependencies.
*/
const getParamTypes = (provider: Provider) =>
Reflect.getMetadata('design:paramtypes', provider) || [];
/**
* Recursively resolves all unique dependencies required by a NestJS provider.
* Essential for automating provider inclusion in NestJS unit tests.
*
* @param parentClass - The root provider class whose dependency graph is resolved.
* @returns A complete array of unique provider dependencies.
*/
const getClassDependencies = (parentClass: Provider): Provider[] => {
const dependencies: Provider[] = [];
const seenClasses = new Set<Provider>();
const classQueue: Provider[] = [parentClass];
while (classQueue.length > 0) {
const currentClass = classQueue.pop()!;
if (seenClasses.has(currentClass)) {
continue;
}
seenClasses.add(currentClass);
if (currentClass) {
getParamTypes(currentClass).forEach((paramType: Provider) => {
if (paramType && !seenClasses.has(paramType)) {
classQueue.push(paramType);
dependencies.push(paramType);
}
});
}
}
return dependencies;
};
/**
* Retrieves a Mongoose model definition from the LifecycleHookManager.
*
* @param name - The name of the model.
* @param suffix - Optional suffix to trim from the name.
* @returns The model definition.
* @throws If the model cannot be found.
*/
const getModel = (name: string, suffix = ''): ModelDefinition => {
const modelName = name.replace(suffix, '');
const model = LifecycleHookManager.getModel(modelName);
if (!model) {
throw new Error(`Unable to find model for name '${modelName}!'`);
}
return model;
};
/**
* Extracts nested Mongoose models from a collection of providers.
* Typically used for automating inclusion of models in test modules.
*
* @param extendedProviders - Array of providers to inspect.
* @param suffix - Suffix identifying relevant providers (e.g., 'Repository').
* @returns An array of model definitions.
*/
const getNestedModels = (
extendedProviders: Provider[],
suffix = '',
): ModelDefinition[] =>
extendedProviders.reduce((acc, extendedProvider) => {
if ('name' in extendedProvider && extendedProvider.name.endsWith(suffix)) {
const model = getModel(extendedProvider.name, suffix);
acc.push(model);
}
return acc;
}, [] as ModelDefinition[]);
const filterNestedDependencies = (dependency: Provider) =>
dependency.valueOf().toString().slice(0, 6) === 'class ';
/**
* Identifies nested class-based dependencies to be automatically injected into test modules.
*
* @param providers - Array of initial providers.
* @returns Array of additional nested dependencies.
*/
const getNestedDependencies = (providers: Provider[]): Provider[] => {
const nestedDependencies = new Set<Provider>();
providers.filter(filterNestedDependencies).forEach((provider) => {
getClassDependencies(provider)
.filter(filterNestedDependencies)
.forEach((dependency) => {
if (
!providers.includes(dependency) &&
!providers.find(
(provider) =>
'provide' in provider && provider.provide === dependency,
)
) {
nestedDependencies.add(dependency);
}
});
});
return [...nestedDependencies];
};
/**
* Determines if models can be automatically injected based on imports.
* Specifically checks for presence of MongooseModule.
*
* @param imports - Modules imported in the test context.
* @returns True if MongooseModule is included, enabling automatic model injection.
*/
const canInjectModels = (imports: buildTestingMocksProps['imports']): boolean =>
(imports || []).some(
(module) => 'module' in module && module.module.name === 'MongooseModule',
);
/**
* Retrieves model definitions for the provided models array.
* Supports both string references and explicit ModelDefinition objects.
*
* @param models - Array of models specified by name or definition.
* @returns Array of resolved model definitions.
*/
const getModels = (models: TModel[]): ModelDefinition[] =>
models.map((model) =>
typeof model === 'string' ? getModel(model, 'Model') : model,
);
const defaultProviders = [
LoggerService,
EventEmitter2,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
set: jest.fn(),
get: jest.fn(),
},
},
];
/**
* Dynamically builds a NestJS TestingModule for unit tests with automated dependency resolution.
* Includes functionality to inject models and nested providers/controllers based on provided configuration.
*
* @param props - Configuration for testing module setup.
* @returns An object containing the compiled NestJS TestingModule and helpers to retrieve or resolve mock instances.
*
* @example
* ```typescript
* describe('UserService', () => {
* let userService: UserService;
*
* beforeAll(async () => {
* const { getMocks } = await buildTestingMocks({
* autoInjectFrom: ['providers'],
* imports: [MongooseModule.forRoot('mongodb://localhost/test')],
* providers: [UserService],
* });
*
* [userService] = await getMocks([UserService]);
* });
*
* it('should be defined', () => {
* expect(userService).toBeDefined();
* });
* });
* ```
*/
export const buildTestingMocks = async ({
providers,
models = [],
imports = [],
providers = [],
controllers = [],
autoInjectFrom,
...rest
}: ModuleMetadata) => {
}: buildTestingMocksProps) => {
const extendedProviders = new Set<Provider>();
const dynamicProviders = new Set<Provider>();
const injectionFrom = autoInjectFrom as ToUnionArray<typeof autoInjectFrom>;
if (injectionFrom?.includes('providers')) {
[...getNestedDependencies(providers)].forEach((provider) =>
extendedProviders.add(provider),
);
}
if (injectionFrom?.includes('controllers')) {
[...getNestedDependencies(controllers)].forEach((controller) =>
extendedProviders.add(controller),
);
}
providers.forEach((provider) => extendedProviders.add(provider));
[...defaultProviders, ...extendedProviders].forEach((provider) => {
dynamicProviders.add(provider);
});
const module = await Test.createTestingModule({
imports: [
...(canInjectModels(imports)
? [
MongooseModule.forFeature([
...getModels(models),
...(autoInjectFrom
? getNestedModels([...dynamicProviders], 'Repository')
: []),
]),
]
: []),
...imports,
],
providers: [...dynamicProviders],
controllers,
...rest,
...(providers && {
providers: [LoggerService, EventEmitter2, ...providers],
}),
}).compile();
return {

View File

@@ -19,7 +19,7 @@ import type { Block, BlockFull } from '@/chat/schemas/block.schema';
import { type Category } from '@/chat/schemas/category.schema';
import { type ContextVar } from '@/chat/schemas/context-var.schema';
import { type Conversation } from '@/chat/schemas/conversation.schema';
import type { Label, LabelDocument } from '@/chat/schemas/label.schema';
import type { Label } from '@/chat/schemas/label.schema';
import { type Message } from '@/chat/schemas/message.schema';
import { type Subscriber } from '@/chat/schemas/subscriber.schema';
import { type ContentType } from '@/cms/schemas/content-type.schema';
@@ -27,16 +27,10 @@ import { type Content } from '@/cms/schemas/content.schema';
import { type Menu } from '@/cms/schemas/menu.schema';
import { type Language } from '@/i18n/schemas/language.schema';
import { type Translation } from '@/i18n/schemas/translation.schema';
import type {
NlpEntity,
NlpEntityDocument,
} from '@/nlp/schemas/nlp-entity.schema';
import type { NlpEntity } from '@/nlp/schemas/nlp-entity.schema';
import { type NlpSampleEntity } from '@/nlp/schemas/nlp-sample-entity.schema';
import { type NlpSample } from '@/nlp/schemas/nlp-sample.schema';
import type {
NlpValue,
NlpValueDocument,
} from '@/nlp/schemas/nlp-value.schema';
import type { NlpValue } from '@/nlp/schemas/nlp-value.schema';
import { type Setting } from '@/setting/schemas/setting.schema';
import { type Invitation } from '@/user/schemas/invitation.schema';
import { type Model } from '@/user/schemas/model.schema';
@@ -130,35 +124,18 @@ declare module '@nestjs/event-emitter' {
category: TDefinition<Category>;
contextVar: TDefinition<ContextVar>;
conversation: TDefinition<Conversation, { end: unknown; close: unknown }>;
label: TDefinition<
Label,
{ create: LabelDocument; delete: Label | Label[] }
>;
label: TDefinition<Label>;
message: TDefinition<Message>;
subscriber: TDefinition<Subscriber, { assign: SubscriberUpdateDto }>;
contentType: TDefinition<ContentType>;
content: TDefinition<Content>;
menu: TDefinition<Menu>;
language: TDefinition<Language, { delete: Language | Language[] }>;
language: TDefinition<Language>;
translation: TDefinition<Translation>;
nlpEntity: TDefinition<
NlpEntity,
{
create: NlpEntityDocument;
update: NlpEntity;
delete: NlpEntity | NlpEntity[];
}
>;
nlpEntity: TDefinition<NlpEntity>;
nlpSampleEntity: TDefinition<NlpSampleEntity>;
nlpSample: TDefinition<NlpSample>;
nlpValue: TDefinition<
NlpValue,
{
create: NlpValueDocument;
update: NlpValue;
delete: NlpValue | NlpValue[];
}
>;
nlpValue: TDefinition<NlpValue>;
setting: TDefinition<Setting>;
invitation: TDefinition<Invitation>;
model: TDefinition<Model>;
@@ -212,7 +189,8 @@ declare module '@nestjs/event-emitter' {
type TPostUpdateValidate<T> = FilterQuery<T>;
type TPostUpdate<T> = THydratedDocument<T>;
// TODO this type will be optimized soon in a separated PR
type TPostUpdate<T> = T & any;
type TPostDelete = DeleteResult;

View File

@@ -29,6 +29,7 @@ export const DialogFormButtons = ({
return (
<Grid
p="0.3rem 1rem"
gap={1}
width="100%"
display="flex"
justifyContent="space-between"
@@ -40,7 +41,7 @@ export const DialogFormButtons = ({
startIcon={<CloseIcon />}
{...cancelButtonProps}
>
{t(cancelButtonTitle)}
{cancelButtonProps?.text || t(cancelButtonTitle)}
</Button>
<Button
variant="contained"
@@ -48,7 +49,7 @@ export const DialogFormButtons = ({
startIcon={<CheckIcon />}
{...confirmButtonProps}
>
{t(confirmButtonTitle)}
{confirmButtonProps?.text || t(confirmButtonTitle)}
</Button>
</Grid>
);

View File

@@ -25,18 +25,19 @@ import {
const SelectableBox = styled(Box)({
position: "relative",
height: "30px",
marginBottom: "1rem",
"& .highlight, & .editable": {
position: "absolute",
top: 0,
display: "block",
width: "100%",
padding: "4px",
padding: "0 4px",
lineHeight: 1.5,
whiteSpaceCollapse: "preserve",
},
"& .editable": {
position: "relative",
backgroundColor: "transparent",
padding: "0px 4px",
color: "#000",
},
});
@@ -169,10 +170,10 @@ const Selectable: FC<SelectableProps> = ({
) {
const inputContainer = editableRef.current;
let substring: string = "";
let input: HTMLInputElement | null = null;
let input: HTMLTextAreaElement | null = null;
if (inputContainer) {
input = inputContainer.querySelector("input");
input = inputContainer.querySelector("textarea");
if (
input &&
@@ -267,6 +268,7 @@ const Selectable: FC<SelectableProps> = ({
/>
))}
<Input
multiline
ref={editableRef}
className="editable"
fullWidth

View File

@@ -184,7 +184,6 @@ export default function NlpSample() {
{ defaultValues: data },
{
maxWidth: "md",
hasButtons: false,
},
);
},

View File

@@ -6,20 +6,55 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { FC, Fragment } from "react";
import AddIcon from "@mui/icons-material/Add";
import DeleteIcon from "@mui/icons-material/Delete";
import {
Box,
Button,
Chip,
debounce,
FormControl,
FormControlLabel,
FormLabel,
IconButton,
Radio,
RadioGroup,
Typography,
} from "@mui/material";
import { FC, Fragment, useCallback, useEffect, useMemo, useState } from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import { useQuery } from "react-query";
import { ContentContainer, ContentItem } from "@/app-components/dialogs";
import AutoCompleteEntitySelect from "@/app-components/inputs/AutoCompleteEntitySelect";
import AutoCompleteSelect from "@/app-components/inputs/AutoCompleteSelect";
import Selectable from "@/app-components/inputs/Selectable";
import { useCreate } from "@/hooks/crud/useCreate";
import { useGetFromCache } from "@/hooks/crud/useGet";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { useApiClient } from "@/hooks/useApiClient";
import { useNlp } from "@/hooks/useNlp";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType } from "@/services/types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
import { EntityType, Format } from "@/services/types";
import {
ComponentFormProps,
FormButtonsProps,
} from "@/types/common/dialogs.types";
import { ILanguage } from "@/types/language.types";
import { INlpEntity } from "@/types/nlp-entity.types";
import {
INlpDatasetKeywordEntity,
INlpDatasetPatternEntity,
INlpDatasetSample,
INlpDatasetSampleAttributes,
INlpDatasetTraitEntity,
INlpSample,
INlpSampleFormAttributes,
INlpSampleFull,
NlpSampleType,
} from "@/types/nlp-sample.types";
import NlpDatasetSample from "./NlpTrainForm";
import { INlpValue } from "@/types/nlp-value.types";
export const NlpSampleForm: FC<ComponentFormProps<INlpDatasetSample>> = ({
data: { defaultValues: nlpDatasetSample },
@@ -29,18 +64,134 @@ export const NlpSampleForm: FC<ComponentFormProps<INlpDatasetSample>> = ({
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const { mutate: updateSample } = useUpdate<
EntityType.NLP_SAMPLE,
INlpDatasetSampleAttributes
>(EntityType.NLP_SAMPLE, {
const options = {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess: () => {
toast.success(t("message.success_save"));
},
};
const { mutate: createSample } = useCreate<
EntityType.NLP_SAMPLE,
INlpDatasetSampleAttributes,
INlpSample,
INlpSampleFull
>(EntityType.NLP_SAMPLE, {
...options,
onSuccess: () => {
options.onSuccess();
refetchAllEntities();
reset({
...defaultValues,
text: "",
});
},
});
const onSubmitForm = (form: INlpSampleFormAttributes) => {
const { mutate: updateSample } = useUpdate<
EntityType.NLP_SAMPLE,
INlpDatasetSampleAttributes
>(EntityType.NLP_SAMPLE, options);
const {
allTraitEntities,
allKeywordEntities,
allPatternEntities,
refetchAllEntities,
} = useNlp();
const getNlpValueFromCache = useGetFromCache(EntityType.NLP_VALUE);
const defaultValues: INlpSampleFormAttributes = useMemo(
() => ({
type: nlpDatasetSample?.type || NlpSampleType.train,
text: nlpDatasetSample?.text || "",
language: nlpDatasetSample?.language || null,
traitEntities: [...allTraitEntities.values()].map((e) => {
return {
entity: e.name,
value:
(nlpDatasetSample?.entities || []).find(
(se) => se.entity === e.name,
)?.value || "",
};
}) as INlpDatasetTraitEntity[],
keywordEntities: (nlpDatasetSample?.entities || []).filter((e) =>
allKeywordEntities.has(e.entity),
) as INlpDatasetKeywordEntity[],
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[allKeywordEntities, allTraitEntities, JSON.stringify(nlpDatasetSample)],
);
const { handleSubmit, control, register, reset, setValue, watch } =
useForm<INlpSampleFormAttributes>({
defaultValues,
});
const currentText = watch("text");
const currentType = watch("type");
const { apiClient } = useApiClient();
const [patternEntities, setPatternEntities] = useState<
INlpDatasetPatternEntity[]
>([]);
const { fields: traitEntities, update: updateTraitEntity } = useFieldArray({
control,
name: "traitEntities",
});
const {
fields: keywordEntities,
insert: insertKeywordEntity,
update: updateKeywordEntity,
remove: removeKeywordEntity,
} = useFieldArray({
control,
name: "keywordEntities",
});
// Auto-predict on text change
const debounceSetText = useCallback(
debounce((text: string) => {
setValue("text", text);
}, 400),
[setValue],
);
const { isLoading } = useQuery({
queryKey: ["nlp-prediction", currentText],
queryFn: async () => {
return await apiClient.predictNlp(currentText);
},
onSuccess: (prediction) => {
const predictedTraitEntities: INlpDatasetTraitEntity[] =
prediction.entities.filter((e) => allTraitEntities.has(e.entity));
const predictedKeywordEntities = prediction.entities.filter((e) =>
allKeywordEntities.has(e.entity),
) as INlpDatasetKeywordEntity[];
const predictedPatternEntities = prediction.entities.filter((e) =>
allPatternEntities.has(e.entity),
) as INlpDatasetKeywordEntity[];
const language = prediction.entities.find(
({ entity }) => entity === "language",
);
setValue("language", language?.value || "");
setValue("traitEntities", predictedTraitEntities);
setValue("keywordEntities", predictedKeywordEntities);
setPatternEntities(predictedPatternEntities);
},
enabled:
// Inbox sample update
nlpDatasetSample?.type === "inbox" ||
// New sample
(!nlpDatasetSample && !!currentText),
});
const findInsertIndex = (newItem: INlpDatasetKeywordEntity): number => {
const index = keywordEntities.findIndex(
(entity) => entity.start && newItem.start && entity.start > newItem.start,
);
return index === -1 ? keywordEntities.length : index;
};
const [selection, setSelection] = useState<{
value: string;
start: number;
end: number;
} | null>(null);
const onSubmitForm = async (form: INlpSampleFormAttributes) => {
if (nlpDatasetSample?.id) {
updateSample(
{
@@ -58,15 +209,328 @@ export const NlpSampleForm: FC<ComponentFormProps<INlpDatasetSample>> = ({
},
},
);
} else {
createSample({
text: form.text,
type: form.type,
entities: [...form.traitEntities, ...form.keywordEntities],
language: form.language,
});
}
};
useEffect(() => {
reset(defaultValues);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [JSON.stringify(defaultValues)]);
const cancelButtonProps = {
sx: {
display: "inline-block",
overflow: "hidden",
textAlign: "left",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
"& .MuiButton-startIcon": {
top: "4px",
margin: "auto 4px auto auto",
display: "inline-block",
position: "relative",
},
},
color: "secondary",
variant: "contained",
onClick: () => {
const newKeywordEntity = {
...selection,
entity: "",
} as INlpDatasetKeywordEntity;
const newIndex = findInsertIndex(newKeywordEntity);
selection && insertKeywordEntity(newIndex, newKeywordEntity);
setSelection(null);
},
disabled: !selection?.value,
startIcon: <AddIcon />,
} satisfies FormButtonsProps["cancelButtonProps"];
const confirmButtonProps = {
sx: { minWidth: "120px" },
value: "button.validate",
variant: "contained",
disabled: !(
currentText !== "" &&
currentType !== NlpSampleType.inbox &&
traitEntities.every((e) => e.value !== "") &&
keywordEntities.every((e) => e.value !== "")
),
onClick: handleSubmit(onSubmitForm),
} satisfies FormButtonsProps["confirmButtonProps"];
return (
<Wrapper onSubmit={() => {}} {...WrapperProps}>
<NlpDatasetSample
sample={nlpDatasetSample || undefined}
submitForm={onSubmitForm}
/>
<Wrapper
onSubmit={() => {}}
{...WrapperProps}
cancelButtonProps={{
...WrapperProps?.cancelButtonProps,
text: !selection?.value
? t("button.select_some_text")
: t("button.add_nlp_entity", { 0: selection.value }),
...cancelButtonProps,
}}
confirmButtonProps={{
...WrapperProps?.confirmButtonProps,
...confirmButtonProps,
}}
>
<form onSubmit={handleSubmit(onSubmitForm)}>
<ContentContainer>
<ContentItem
display="flex"
flexDirection="row"
justifyContent="space-between"
>
<Typography variant="h6" display="inline-block">
{t("title.nlp_train")}
</Typography>
<FormControl>
<FormLabel>{t("label.type")}</FormLabel>
<RadioGroup
row
defaultValue={
nlpDatasetSample?.type === NlpSampleType.test
? NlpSampleType.test
: NlpSampleType.train
}
>
{Object.values(NlpSampleType)
.filter((type) => type !== "inbox")
.map((type, index) => (
<FormControlLabel
key={index}
value={type}
control={<Radio {...register("type")} />}
label={t(`label.${type}`)}
/>
))}
</RadioGroup>
</FormControl>
</ContentItem>
<ContentItem>
<Selectable
defaultValue={currentText}
keywordEntities={keywordEntities}
patternEntities={patternEntities}
placeholder={t("placeholder.nlp_sample_text")}
onSelect={(newSelection, start, end) => {
newSelection !== selection?.value &&
setSelection({
value: newSelection,
start,
end,
});
}}
onChange={({ text, entities }) => {
debounceSetText(text);
setValue(
"keywordEntities",
entities.map(({ entity, value, start, end }) => ({
entity,
value,
start,
end,
})),
);
setPatternEntities([]);
}}
loading={isLoading}
/>
</ContentItem>
<Box display="flex" flexDirection="column">
<ContentItem
display="flex"
flexDirection="row"
maxWidth="50%"
gap={2}
>
<Controller
name="language"
control={control}
render={({ field }) => {
const { onChange, ...rest } = field;
return (
<AutoCompleteEntitySelect<ILanguage, "title", false>
fullWidth={true}
autoFocus
searchFields={["title", "code"]}
entity={EntityType.LANGUAGE}
format={Format.BASIC}
labelKey="title"
idKey="code"
label={t("label.language")}
multiple={false}
{...field}
onChange={(_e, selected) => {
onChange(selected?.code);
}}
{...rest}
/>
);
}}
/>
</ContentItem>
{traitEntities.map((traitEntity, index) => (
<ContentItem
key={traitEntity.id}
display="flex"
flexDirection="row"
maxWidth="50%"
gap={2}
>
<Controller
name={`traitEntities.${index}`}
rules={{ required: true }}
control={control}
render={({ field }) => {
const { onChange: _, value, ...rest } = field;
const options = (
allTraitEntities.get(traitEntity.entity)?.values || []
).map((v) => getNlpValueFromCache(v)!);
return (
<>
<AutoCompleteSelect<INlpValue, "value", false>
fullWidth={true}
options={options}
idKey="value"
labelKey="value"
label={value.entity}
multiple={false}
value={value.value}
onChange={(_e, selected, ..._) => {
updateTraitEntity(index, {
entity: value.entity,
value: selected?.value || "",
});
}}
{...rest}
/>
{value?.confidence &&
typeof value?.confidence === "number" && (
<Chip
sx={{ marginTop: 0.5 }}
variant="available"
label={`${(value?.confidence * 100).toFixed(
2,
)}% ${t("label.confidence")}`}
/>
)}
</>
);
}}
/>
</ContentItem>
))}
</Box>
<Box display="flex" flexDirection="column">
{keywordEntities.map((keywordEntity, index) => (
<ContentItem
key={keywordEntity.id}
display="flex"
maxWidth="50%"
gap={2}
>
<IconButton onClick={() => removeKeywordEntity(index)}>
<DeleteIcon />
</IconButton>
<Controller
name={`keywordEntities.${index}.entity`}
control={control}
render={({ field }) => {
const { onChange: _, ...rest } = field;
const options = [...allKeywordEntities.values()];
return (
<AutoCompleteSelect<INlpEntity, "name", false>
fullWidth={true}
options={options}
idKey="name"
labelKey="name"
label={t("label.nlp_entity")}
multiple={false}
onChange={(_e, selected, ..._) => {
updateKeywordEntity(index, {
...keywordEntities[index],
entity: selected?.name || "",
});
}}
{...rest}
/>
);
}}
/>
<Controller
name={`keywordEntities.${index}.value`}
control={control}
render={({ field }) => {
const { onChange: _, value, ...rest } = field;
const options = (
allKeywordEntities.get(keywordEntity.entity)?.values || []
).map((v) => getNlpValueFromCache(v)!);
return (
<AutoCompleteSelect<
INlpValue,
"value",
false,
false,
true
>
sx={{ width: "50%" }}
idKey="value"
labelKey="value"
label={t("label.value")}
multiple={false}
options={options}
value={value}
freeSolo={true}
getOptionLabel={(option) => {
return typeof option === "string"
? option
: option.value;
}}
onChange={(_e, selected, ..._) => {
selected &&
updateKeywordEntity(index, {
...keywordEntity,
value:
typeof selected === "string"
? selected
: selected.value,
});
}}
{...rest}
/>
);
}}
/>
</ContentItem>
))}
</Box>
</ContentContainer>
<ContentItem display="flex" justifyContent="space-between">
{nlpDatasetSample ? null : (
<>
<Button {...cancelButtonProps}>
{!selection?.value
? t("button.select_some_text")
: t("button.add_nlp_entity", { 0: selection.value })}
</Button>
<Button {...confirmButtonProps}>{t("button.validate")}</Button>
</>
)}
</ContentItem>
</form>
</Wrapper>
);
};

View File

@@ -1,460 +0,0 @@
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import AddIcon from "@mui/icons-material/Add";
import Check from "@mui/icons-material/Check";
import DeleteIcon from "@mui/icons-material/Delete";
import {
Box,
Button,
Chip,
debounce,
FormControl,
FormControlLabel,
FormLabel,
IconButton,
Radio,
RadioGroup,
Typography,
} from "@mui/material";
import { FC, useCallback, useEffect, useMemo, useState } from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import { useQuery } from "react-query";
import { ContentContainer, ContentItem } from "@/app-components/dialogs";
import AutoCompleteEntitySelect from "@/app-components/inputs/AutoCompleteEntitySelect";
import AutoCompleteSelect from "@/app-components/inputs/AutoCompleteSelect";
import Selectable from "@/app-components/inputs/Selectable";
import { useGetFromCache } from "@/hooks/crud/useGet";
import { useApiClient } from "@/hooks/useApiClient";
import { useNlp } from "@/hooks/useNlp";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType, Format } from "@/services/types";
import { ILanguage } from "@/types/language.types";
import { INlpEntity } from "@/types/nlp-entity.types";
import {
INlpDatasetKeywordEntity,
INlpDatasetPatternEntity,
INlpDatasetSample,
INlpDatasetTraitEntity,
INlpSampleFormAttributes,
NlpSampleType,
} from "@/types/nlp-sample.types";
import { INlpValue } from "@/types/nlp-value.types";
type NlpDatasetSampleProps = {
sample?: INlpDatasetSample;
submitForm: (params: INlpSampleFormAttributes) => void;
};
const NlpDatasetSample: FC<NlpDatasetSampleProps> = ({
sample,
submitForm,
}) => {
const { t } = useTranslate();
const {
allTraitEntities,
allKeywordEntities,
allPatternEntities,
refetchAllEntities,
} = useNlp();
const getNlpValueFromCache = useGetFromCache(EntityType.NLP_VALUE);
const defaultValues: INlpSampleFormAttributes = useMemo(
() => ({
type: sample?.type || NlpSampleType.train,
text: sample?.text || "",
language: sample?.language || null,
traitEntities: [...allTraitEntities.values()].map((e) => {
return {
entity: e.name,
value:
(sample?.entities || []).find((se) => se.entity === e.name)
?.value || "",
};
}) as INlpDatasetTraitEntity[],
keywordEntities: (sample?.entities || []).filter((e) =>
allKeywordEntities.has(e.entity),
) as INlpDatasetKeywordEntity[],
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[allKeywordEntities, allTraitEntities, JSON.stringify(sample)],
);
const { handleSubmit, control, register, reset, setValue, watch } =
useForm<INlpSampleFormAttributes>({
defaultValues,
});
const currentText = watch("text");
const currentType = watch("type");
const { apiClient } = useApiClient();
const [patternEntities, setPatternEntities] = useState<
INlpDatasetPatternEntity[]
>([]);
const { fields: traitEntities, update: updateTraitEntity } = useFieldArray({
control,
name: "traitEntities",
});
const {
fields: keywordEntities,
insert: insertKeywordEntity,
update: updateKeywordEntity,
remove: removeKeywordEntity,
} = useFieldArray({
control,
name: "keywordEntities",
});
// Auto-predict on text change
const debounceSetText = useCallback(
debounce((text: string) => {
setValue("text", text);
}, 400),
[setValue],
);
const { isLoading } = useQuery({
queryKey: ["nlp-prediction", currentText],
queryFn: async () => {
return await apiClient.predictNlp(currentText);
},
onSuccess: (prediction) => {
const predictedTraitEntities: INlpDatasetTraitEntity[] =
prediction.entities.filter((e) => allTraitEntities.has(e.entity));
const predictedKeywordEntities = prediction.entities.filter((e) =>
allKeywordEntities.has(e.entity),
) as INlpDatasetKeywordEntity[];
const predictedPatternEntities = prediction.entities.filter((e) =>
allPatternEntities.has(e.entity),
) as INlpDatasetKeywordEntity[];
const language = prediction.entities.find(
({ entity }) => entity === "language",
);
setValue("language", language?.value || "");
setValue("traitEntities", predictedTraitEntities);
setValue("keywordEntities", predictedKeywordEntities);
setPatternEntities(predictedPatternEntities);
},
enabled:
// Inbox sample update
sample?.type === "inbox" ||
// New sample
(!sample && !!currentText),
});
const findInsertIndex = (newItem: INlpDatasetKeywordEntity): number => {
const index = keywordEntities.findIndex(
(entity) => entity.start && newItem.start && entity.start > newItem.start,
);
return index === -1 ? keywordEntities.length : index;
};
const [selection, setSelection] = useState<{
value: string;
start: number;
end: number;
} | null>(null);
const onSubmitForm = (form: INlpSampleFormAttributes) => {
submitForm(form);
refetchAllEntities();
reset({
...defaultValues,
text: "",
});
};
useEffect(() => {
reset(defaultValues);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [JSON.stringify(defaultValues)]);
return (
<Box className="nlp-train" sx={{ position: "relative", p: 2 }}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<ContentContainer>
<ContentItem
display="flex"
flexDirection="row"
justifyContent="space-between"
>
<Typography variant="h6" display="inline-block">
{t("title.nlp_train")}
</Typography>
<FormControl>
<FormLabel>{t("label.type")}</FormLabel>
<RadioGroup
row
defaultValue={
sample?.type === NlpSampleType.test
? NlpSampleType.test
: NlpSampleType.train
}
>
{Object.values(NlpSampleType)
.filter((type) => type !== "inbox")
.map((type, index) => (
<FormControlLabel
key={index}
value={type}
control={<Radio {...register("type")} />}
label={t(`label.${type}`)}
/>
))}
</RadioGroup>
</FormControl>
</ContentItem>
<ContentItem>
<Selectable
defaultValue={currentText}
keywordEntities={keywordEntities}
patternEntities={patternEntities}
placeholder={t("placeholder.nlp_sample_text")}
onSelect={(selection, start, end) => {
setSelection({
value: selection,
start,
end,
});
}}
onChange={({ text, entities }) => {
debounceSetText(text);
setValue(
"keywordEntities",
entities.map(({ entity, value, start, end }) => ({
entity,
value,
start,
end,
})),
);
setPatternEntities([]);
}}
loading={isLoading}
/>
</ContentItem>
<Box display="flex" flexDirection="column">
{/* Language selection */}
<ContentItem
display="flex"
flexDirection="row"
maxWidth="50%"
gap={2}
>
<Controller
name="language"
control={control}
render={({ field }) => {
const { onChange, ...rest } = field;
return (
<AutoCompleteEntitySelect<ILanguage, "title", false>
fullWidth={true}
autoFocus
searchFields={["title", "code"]}
entity={EntityType.LANGUAGE}
format={Format.BASIC}
labelKey="title"
idKey="code"
label={t("label.language")}
multiple={false}
{...field}
onChange={(_e, selected) => {
onChange(selected?.code);
}}
{...rest}
/>
);
}}
/>
</ContentItem>
{/* Trait entities */}
{traitEntities.map((traitEntity, index) => (
<ContentItem
key={traitEntity.id}
display="flex"
flexDirection="row"
maxWidth="50%"
gap={2}
>
<Controller
name={`traitEntities.${index}`}
rules={{ required: true }}
control={control}
render={({ field }) => {
const { onChange: _, value, ...rest } = field;
const options = (
allTraitEntities.get(traitEntity.entity)?.values || []
).map((v) => getNlpValueFromCache(v)!);
return (
<>
<AutoCompleteSelect<INlpValue, "value", false>
fullWidth={true}
options={options}
idKey="value"
labelKey="value"
label={value.entity}
multiple={false}
value={value.value}
onChange={(_e, selected, ..._) => {
updateTraitEntity(index, {
entity: value.entity,
value: selected?.value || "",
});
}}
{...rest}
/>
{value?.confidence &&
typeof value?.confidence === "number" && (
<Chip
sx={{ marginTop: 0.5 }}
variant="available"
label={`${(value?.confidence * 100).toFixed(
2,
)}% ${t("label.confidence")}`}
/>
)}
</>
);
}}
/>
</ContentItem>
))}
</Box>
{
/* Keyword entities */
}
<Box display="flex" flexDirection="column">
{keywordEntities.map((keywordEntity, index) => (
<ContentItem
key={keywordEntity.id}
display="flex"
maxWidth="50%"
gap={2}
>
<IconButton onClick={() => removeKeywordEntity(index)}>
<DeleteIcon />
</IconButton>
<Controller
name={`keywordEntities.${index}.entity`}
control={control}
render={({ field }) => {
const { onChange: _, ...rest } = field;
const options = [...allKeywordEntities.values()];
return (
<AutoCompleteSelect<INlpEntity, "name", false>
fullWidth={true}
options={options}
idKey="name"
labelKey="name"
label={t("label.nlp_entity")}
multiple={false}
onChange={(_e, selected, ..._) => {
updateKeywordEntity(index, {
...keywordEntities[index],
entity: selected?.name || "",
});
}}
{...rest}
/>
);
}}
/>
<Controller
name={`keywordEntities.${index}.value`}
control={control}
render={({ field }) => {
const { onChange: _, value, ...rest } = field;
const options = (
allKeywordEntities.get(keywordEntity.entity)?.values || []
).map((v) => getNlpValueFromCache(v)!);
return (
<AutoCompleteSelect<
INlpValue,
"value",
false,
false,
true
>
sx={{ width: "50%" }}
idKey="value"
labelKey="value"
label={t("label.value")}
multiple={false}
options={options}
value={value}
freeSolo={true}
getOptionLabel={(option) => {
return typeof option === "string"
? option
: option.value;
}}
onChange={(_e, selected, ..._) => {
selected &&
updateKeywordEntity(index, {
...keywordEntity,
value:
typeof selected === "string"
? selected
: selected.value,
});
}}
{...rest}
/>
);
}}
/>
</ContentItem>
))}
</Box>
</ContentContainer>
<ContentItem display="flex" justifyContent="space-between">
<Button
startIcon={<AddIcon />}
color="secondary"
variant="contained"
disabled={!selection?.value}
onClick={() => {
const newKeywordEntity = {
...selection,
entity: "",
} as INlpDatasetKeywordEntity;
const newIndex = findInsertIndex(newKeywordEntity);
selection && insertKeywordEntity(newIndex, newKeywordEntity);
setSelection(null);
}}
>
{!selection?.value
? t("button.select_some_text")
: t("button.add_nlp_entity", { 0: selection.value })}
</Button>
<Button
variant="contained"
startIcon={<Check />}
onClick={handleSubmit(onSubmitForm)}
disabled={
!(
currentText !== "" &&
currentType !== NlpSampleType.inbox &&
traitEntities.every((e) => e.value !== "") &&
keywordEntities.every((e) => e.value !== "")
)
}
type="submit"
>
{t("button.validate")}
</Button>
</ContentItem>
</form>
</Box>
);
};
NlpDatasetSample.displayName = "NlpTrain";
export default NlpDatasetSample;

View File

@@ -13,22 +13,14 @@ import { useRouter } from "next/router";
import React from "react";
import { TabPanel } from "@/app-components/tabs/TabPanel";
import { useCreate } from "@/hooks/crud/useCreate";
import { useFind } from "@/hooks/crud/useFind";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { PageHeader } from "@/layout/content/PageHeader";
import { EntityType, Format } from "@/services/types";
import {
INlpDatasetSampleAttributes,
INlpSample,
INlpSampleFormAttributes,
INlpSampleFull,
} from "@/types/nlp-sample.types";
import NlpDatasetCounter from "./components/NlpDatasetCounter";
import NlpSample from "./components/NlpSample";
import NlpDatasetSample from "./components/NlpTrainForm";
import { NlpSampleForm } from "./components/NlpSampleForm";
import { NlpValues } from "./components/NlpValue";
const NlpEntity = dynamic(() => import("./components/NlpEntity"));
@@ -61,28 +53,6 @@ export const Nlp = ({
);
};
const { t } = useTranslate();
const { toast } = useToast();
const { mutate: createSample } = useCreate<
EntityType.NLP_SAMPLE,
INlpDatasetSampleAttributes,
INlpSample,
INlpSampleFull
>(EntityType.NLP_SAMPLE, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess: () => {
toast.success(t("message.success_save"));
},
});
const onSubmitForm = (params: INlpSampleFormAttributes) => {
createSample({
text: params.text,
type: params.type,
entities: [...params.traitEntities, ...params.keywordEntities],
language: params.language,
});
};
return (
<Grid container gap={2} flexDirection="column">
@@ -90,8 +60,8 @@ export const Nlp = ({
<Grid item xs={12}>
<Grid container flexDirection="row">
<Grid item xs={7}>
<Paper>
<NlpDatasetSample submitForm={onSubmitForm} />
<Paper sx={{ px: 3, py: 2 }}>
<NlpSampleForm data={{ defaultValues: null }} />
</Paper>
</Grid>
<Grid item xs={5} pl={2}>
@@ -116,12 +86,18 @@ export const Nlp = ({
{/* NLP SAMPLES */}
<Grid sx={{ padding: "20px" }}>
<TabPanel value={selectedTab} index="sample">
<NlpSample />
{selectedTab === "sample" ? <NlpSample /> : null}
</TabPanel>
{/* NLP ENTITIES */}
<TabPanel value={selectedTab} index="entity">
{entityId ? <NlpValues entityId={entityId} /> : <NlpEntity />}
{selectedTab === "entity" ? (
entityId ? (
<NlpValues entityId={entityId} />
) : (
<NlpEntity />
)
) : null}
</TabPanel>
</Grid>
</Paper>

View File

@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
@@ -48,17 +48,7 @@ const QuickRepliesInput: FC<QuickRepliesInput> = ({
const updatedQuickReplies = [...quickReplies];
updatedQuickReplies.splice(index, 1);
setQuickReplies(
updatedQuickReplies.length
? updatedQuickReplies
: [
createValueWithId({
content_type: QuickReplyType.text,
title: "",
payload: "",
}),
],
);
setQuickReplies(updatedQuickReplies);
};
const updateInput = (index: number) => (p: StdQuickReply) => {
quickReplies[index].value = p;

View File

@@ -162,8 +162,8 @@ export interface FormDialogProps
export interface FormButtonsProps {
onSubmit?: (e: BaseSyntheticEvent) => void;
onCancel?: () => void;
cancelButtonProps?: ButtonProps;
confirmButtonProps?: ButtonProps;
cancelButtonProps?: ButtonProps & { text?: string };
confirmButtonProps?: ButtonProps & { text?: string };
}
export type TPayload<D, P = unknown> = {

View File

@@ -55,6 +55,8 @@
.sc-message--wrapper {
display: flex;
flex-direction: column;
overflow: hidden;
word-break: break-all;
.sc-message--text {
padding: 10px 20px;