feat: implement skills system for AI agents (#16865)
## Summary This PR introduces a Skills system for AI agents, inspired by the [Agent Skills specification](https://agentskills.io/specification). ## Changes ### Backend - **SkillEntity**: New database entity with migration for storing skills - **V2 Sync Mechanism**: Implemented FlatSkill, builders, validators, and action handlers following the v2 flat entity pattern - **Standard Skills**: Pre-defined skills (workflow-building, data-manipulation, dashboard-building, metadata-building, research, code-interpreter, xlsx, pdf, docx, pptx) - **GraphQL API**: CRUD operations for skills with proper guards and permissions - **Workspace Cache**: Integrated skills into the workspace cache system ### Frontend - **Skills Table**: Searchable table in AI settings showing all skills - **Skill Form**: Create/edit page with Label (primary), Description, and Content (markdown editor) - **API Name**: Following existing patterns, name is derived from label with advanced settings toggle for custom API names - **Standard vs Custom**: Standard skills are read-only, custom skills can be edited/deleted ## Key Design Decisions - Skills are stored in the database (Salesforce-like approach) rather than files - Name is derived from Label by default (isLabelSyncedWithName pattern) - Skills reference functions/files via @ mentions in markdown content rather than explicit relations - Standard skills are synced from code, custom skills are created via UI ## Screenshots Skills table and form UI follow existing settings patterns. ## Testing - [x] Lint passes - [x] Typecheck passes - [ ] CI tests
This commit is contained in:
+2
-2
@@ -1,2 +1,2 @@
|
||||
// Configuration: $0.00001 = 1 credit
|
||||
export const DOLLAR_TO_CREDIT_MULTIPLIER = 1_000_000; // 1 / 0.000001 = 1 000 000 credits per dollar
|
||||
// Configuration: $0.000_001 = 1 credit
|
||||
export const DOLLAR_TO_CREDIT_MULTIPLIER = 1_000_000; // 1 / 0.000_001 = 1_000_000 credits per dollar
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@ import { DOLLAR_TO_CREDIT_MULTIPLIER } from 'src/engine/metadata-modules/ai/ai-b
|
||||
|
||||
// Converts cost in cents to cost in credits
|
||||
// Formula: credits = (cents / 100) * DOLLAR_TO_CREDIT_MULTIPLIER
|
||||
// Where DOLLAR_TO_CREDIT_MULTIPLIER = 1000000 (so $0.00001 = 1 credit)
|
||||
// Example: 1 cent = (1 / 100) * 1000000 = 10000 credits
|
||||
// Where DOLLAR_TO_CREDIT_MULTIPLIER = 1_000_000 (so $0.000_001 = 1 credit)
|
||||
// Example: 1 cent = (1 / 100) * 1_000_000 = 10_000 credits
|
||||
export const convertCentsToBillingCredits = (cents: number): number =>
|
||||
(cents / 100) * DOLLAR_TO_CREDIT_MULTIPLIER;
|
||||
|
||||
@@ -8,7 +8,7 @@ import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-
|
||||
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
|
||||
import { FileUploadModule } from 'src/engine/core-modules/file/file-upload/file-upload.module';
|
||||
import { FileModule } from 'src/engine/core-modules/file/file.module';
|
||||
import { SkillsModule } from 'src/engine/core-modules/skills/skills.module';
|
||||
import { SkillModule } from 'src/engine/metadata-modules/skill/skill.module';
|
||||
import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';
|
||||
import { ToolProviderModule } from 'src/engine/core-modules/tool-provider/tool-provider.module';
|
||||
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
|
||||
@@ -44,7 +44,7 @@ import { ChatExecutionService } from './services/chat-execution.service';
|
||||
FileUploadModule,
|
||||
FileModule,
|
||||
PermissionsModule,
|
||||
SkillsModule,
|
||||
SkillModule,
|
||||
WorkspaceCacheStorageModule,
|
||||
WorkspaceCacheModule,
|
||||
WorkspaceDomainsModule,
|
||||
|
||||
+6
@@ -10,6 +10,12 @@ Tool usage strategy:
|
||||
- Don't give up after first failure - be persistent
|
||||
- Validate assumptions before making changes
|
||||
|
||||
Database vs HTTP tools:
|
||||
- Use database tools (find_*, create_*, update_*, delete_*) for ALL Twenty CRM data operations
|
||||
- NEVER guess or construct API URLs - always use the appropriate database tool
|
||||
- The \`http_request\` tool is ONLY for external third-party APIs (not for Twenty's own data)
|
||||
- If you need to look up a record, load and use the corresponding find_one_* or find_many_* tool
|
||||
|
||||
Error recovery:
|
||||
- Analyze error messages to understand what went wrong
|
||||
- Adjust parameters or try different tools
|
||||
|
||||
+13
-10
@@ -17,7 +17,6 @@ import { getAppPath } from 'twenty-shared/utils';
|
||||
import { type CodeExecutionStreamEmitter } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider.interface';
|
||||
|
||||
import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
|
||||
import { SkillsService } from 'src/engine/core-modules/skills/skills.service';
|
||||
import {
|
||||
type ToolIndexEntry,
|
||||
ToolRegistryService,
|
||||
@@ -46,6 +45,8 @@ import {
|
||||
} from 'src/engine/metadata-modules/ai/ai-models/constants/ai-models.const';
|
||||
import { AI_TELEMETRY_CONFIG } from 'src/engine/metadata-modules/ai/ai-models/constants/ai-telemetry.const';
|
||||
import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
|
||||
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
|
||||
import { SkillService } from 'src/engine/metadata-modules/skill/skill.service';
|
||||
|
||||
export type ChatExecutionOptions = {
|
||||
workspace: WorkspaceEntity;
|
||||
@@ -61,7 +62,7 @@ export type ChatExecutionResult = {
|
||||
modelConfig: AIModelConfig;
|
||||
};
|
||||
|
||||
const COMMON_PRELOAD_TOOLS = ['http_request', 'search_help_center'];
|
||||
const COMMON_PRELOAD_TOOLS = ['search_help_center'];
|
||||
|
||||
@Injectable()
|
||||
export class ChatExecutionService {
|
||||
@@ -69,7 +70,7 @@ export class ChatExecutionService {
|
||||
|
||||
constructor(
|
||||
private readonly toolRegistry: ToolRegistryService,
|
||||
private readonly skillsService: SkillsService,
|
||||
private readonly skillService: SkillService,
|
||||
private readonly aiModelRegistryService: AiModelRegistryService,
|
||||
private readonly aiBillingService: AIBillingService,
|
||||
private readonly agentActorContextService: AgentActorContextService,
|
||||
@@ -108,7 +109,9 @@ export class ChatExecutionService {
|
||||
{ userId, userWorkspaceId },
|
||||
);
|
||||
|
||||
const skillCatalog = this.skillsService.getAllSkills();
|
||||
const skillCatalog = await this.skillService.findAllFlatSkills(
|
||||
workspace.id,
|
||||
);
|
||||
|
||||
this.logger.log(
|
||||
`Built tool catalog with ${toolCatalog.length} tools, ${skillCatalog.length} skills available`,
|
||||
@@ -150,7 +153,7 @@ export class ChatExecutionService {
|
||||
},
|
||||
),
|
||||
[LOAD_SKILL_TOOL_NAME]: createLoadSkillTool((skillNames) =>
|
||||
this.skillsService.getSkillsByNames(skillNames),
|
||||
this.skillService.findFlatSkillsByNames(skillNames, workspace.id),
|
||||
),
|
||||
};
|
||||
|
||||
@@ -283,7 +286,7 @@ export class ChatExecutionService {
|
||||
|
||||
private buildSystemPrompt(
|
||||
toolCatalog: ToolIndexEntry[],
|
||||
skillCatalog: Array<{ name: string; label: string; description: string }>,
|
||||
skillCatalog: FlatSkill[],
|
||||
preloadedTools: string[],
|
||||
contextString?: string,
|
||||
storedFiles?: Array<{ filename: string; storagePath: string; url: string }>,
|
||||
@@ -333,15 +336,15 @@ ${filesJson}
|
||||
In your Python code, access files at \`/home/user/{filename}\`.`;
|
||||
}
|
||||
|
||||
private buildSkillCatalogSection(
|
||||
skillCatalog: Array<{ name: string; label: string; description: string }>,
|
||||
): string {
|
||||
private buildSkillCatalogSection(skillCatalog: FlatSkill[]): string {
|
||||
if (skillCatalog.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const skillsList = skillCatalog
|
||||
.map((skill) => `- \`${skill.name}\`: ${skill.description}`)
|
||||
.map(
|
||||
(skill) => `- \`${skill.name}\`: ${skill.description ?? skill.label}`,
|
||||
)
|
||||
.join('\n');
|
||||
|
||||
return `
|
||||
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
// Configuration: $0.00001 = 1 credit
|
||||
export const DOLLAR_TO_CREDIT_MULTIPLIER = 1000000; // 1 / 0.000001 = 1000000 credits per dollar
|
||||
// Configuration: $0.00_001 = 1 credit
|
||||
export const DOLLAR_TO_CREDIT_MULTIPLIER = 1_000_000; // 1 / 0.00_0001 = 1_000_000 credits per dollar
|
||||
|
||||
+5
@@ -13,6 +13,7 @@ import { FLAT_ROLE_TARGET_EDITABLE_PROPERTIES } from 'src/engine/metadata-module
|
||||
import { FLAT_ROLE_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-role/constants/flat-role-editable-properties.constant';
|
||||
import { FLAT_ROW_LEVEL_PERMISSION_PREDICATE_GROUP_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-row-level-permission-predicate-group/constants/flat-row-level-permission-predicate-group-editable-properties.constant';
|
||||
import { FLAT_ROW_LEVEL_PERMISSION_PREDICATE_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-row-level-permission-predicate/constants/flat-row-level-permission-predicate-editable-properties.constant';
|
||||
import { FLAT_SKILL_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-skill/constants/flat-skill-editable-properties.constant';
|
||||
import { FLAT_VIEW_FIELD_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-view-field/constants/flat-view-field-editable-properties.constant';
|
||||
import { FLAT_VIEW_FILTER_GROUP_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-view-filter-group/constants/flat-view-filter-group-editable-properties.constant';
|
||||
import { FLAT_VIEW_FILTER_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-view-filter/constants/flat-view-filter-editable-properties.constant';
|
||||
@@ -135,6 +136,10 @@ export const ALL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY = {
|
||||
],
|
||||
propertiesToStringify: [],
|
||||
},
|
||||
skill: {
|
||||
propertiesToCompare: [...FLAT_SKILL_EDITABLE_PROPERTIES],
|
||||
propertiesToStringify: [],
|
||||
},
|
||||
rowLevelPermissionPredicate: {
|
||||
propertiesToCompare: [
|
||||
...FLAT_ROW_LEVEL_PERMISSION_PREDICATE_EDITABLE_PROPERTIES,
|
||||
|
||||
+1
@@ -113,6 +113,7 @@ export const ALL_METADATA_RELATED_METADATA_BY_FOREIGN_KEY = {
|
||||
},
|
||||
},
|
||||
agent: {},
|
||||
skill: {},
|
||||
pageLayout: {},
|
||||
pageLayoutWidget: {
|
||||
pageLayoutTabId: {
|
||||
|
||||
+4
@@ -8,6 +8,10 @@ export const ALL_METADATA_RELATION_PROPERTIES = {
|
||||
workspace: true,
|
||||
application: true,
|
||||
},
|
||||
skill: {
|
||||
workspace: true,
|
||||
application: true,
|
||||
},
|
||||
fieldMetadata: {
|
||||
relationTargetFieldMetadata: true,
|
||||
relationTargetObjectMetadata: true,
|
||||
|
||||
+1
@@ -62,6 +62,7 @@ export const ALL_METADATA_REQUIRED_METADATA_FOR_VALIDATION = {
|
||||
agent: {
|
||||
role: true,
|
||||
},
|
||||
skill: {},
|
||||
pageLayout: {},
|
||||
pageLayoutTab: {
|
||||
pageLayout: true,
|
||||
|
||||
+16
@@ -13,6 +13,7 @@ import { type FlatPageLayoutWidget } from 'src/engine/metadata-modules/flat-page
|
||||
import { type FlatPageLayout } from 'src/engine/metadata-modules/flat-page-layout/types/flat-page-layout.type';
|
||||
import { type FlatRoleTarget } from 'src/engine/metadata-modules/flat-role-target/types/flat-role-target.type';
|
||||
import { type FlatRole } from 'src/engine/metadata-modules/flat-role/types/flat-role.type';
|
||||
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
|
||||
import { type FlatViewField } from 'src/engine/metadata-modules/flat-view-field/types/flat-view-field.type';
|
||||
import { type FlatViewFilterGroup } from 'src/engine/metadata-modules/flat-view-filter-group/types/flat-view-filter-group.type';
|
||||
import { type FlatViewFilter } from 'src/engine/metadata-modules/flat-view-filter/types/flat-view-filter.type';
|
||||
@@ -33,6 +34,7 @@ import { type FlatRowLevelPermissionPredicateGroup } from 'src/engine/metadata-m
|
||||
import { type FlatRowLevelPermissionPredicate } from 'src/engine/metadata-modules/row-level-permission-predicate/types/flat-row-level-permission-predicate.type';
|
||||
import { type ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { type FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
import { type SkillEntity } from 'src/engine/metadata-modules/skill/entities/skill.entity';
|
||||
import { type ViewFieldEntity } from 'src/engine/metadata-modules/view-field/entities/view-field.entity';
|
||||
import { type ViewFilterGroupEntity } from 'src/engine/metadata-modules/view-filter-group/entities/view-filter-group.entity';
|
||||
import { type ViewFilterEntity } from 'src/engine/metadata-modules/view-filter/entities/view-filter.entity';
|
||||
@@ -113,6 +115,11 @@ import {
|
||||
type DeleteServerlessFunctionAction,
|
||||
type UpdateServerlessFunctionAction,
|
||||
} from 'src/engine/workspace-manager/workspace-migration-v2/workspace-migration-builder-v2/builders/serverless-function/types/workspace-migration-serverless-function-action-v2.type';
|
||||
import {
|
||||
type CreateSkillAction,
|
||||
type DeleteSkillAction,
|
||||
type UpdateSkillAction,
|
||||
} from 'src/engine/workspace-manager/workspace-migration-v2/workspace-migration-builder-v2/builders/skill/types/workspace-migration-v2-skill-action.type';
|
||||
import {
|
||||
type CreateViewFieldAction,
|
||||
type DeleteViewFieldAction,
|
||||
@@ -295,6 +302,15 @@ export type AllFlatEntityTypesByMetadataName = {
|
||||
flatEntity: FlatAgent;
|
||||
entity: AgentEntity;
|
||||
};
|
||||
skill: {
|
||||
actions: {
|
||||
created: CreateSkillAction;
|
||||
updated: UpdateSkillAction;
|
||||
deleted: DeleteSkillAction;
|
||||
};
|
||||
flatEntity: FlatSkill;
|
||||
entity: SkillEntity;
|
||||
};
|
||||
pageLayout: {
|
||||
actions: {
|
||||
created: CreatePageLayoutAction;
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
|
||||
|
||||
export const FLAT_SKILL_EDITABLE_PROPERTIES = [
|
||||
'name',
|
||||
'label',
|
||||
'icon',
|
||||
'description',
|
||||
'content',
|
||||
'isActive',
|
||||
] as const satisfies (keyof FlatSkill)[];
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
|
||||
import { WorkspaceFlatSkillMapCacheService } from 'src/engine/metadata-modules/flat-skill/services/workspace-flat-skill-map-cache.service';
|
||||
import { SkillEntity } from 'src/engine/metadata-modules/skill/entities/skill.entity';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([SkillEntity]),
|
||||
WorkspaceManyOrAllFlatEntityMapsCacheModule,
|
||||
],
|
||||
providers: [WorkspaceFlatSkillMapCacheService],
|
||||
exports: [WorkspaceFlatSkillMapCacheService],
|
||||
})
|
||||
export class FlatSkillModule {}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
import { WorkspaceCacheProvider } from 'src/engine/workspace-cache/interfaces/workspace-cache-provider.service';
|
||||
|
||||
import { type FlatSkillMaps } from 'src/engine/metadata-modules/flat-skill/types/flat-skill-maps.type';
|
||||
import { transformSkillEntityToFlatSkill } from 'src/engine/metadata-modules/flat-skill/utils/transform-skill-entity-to-flat-skill.util';
|
||||
import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
|
||||
import { SkillEntity } from 'src/engine/metadata-modules/skill/entities/skill.entity';
|
||||
import { WorkspaceCache } from 'src/engine/workspace-cache/decorators/workspace-cache.decorator';
|
||||
import { addFlatEntityToFlatEntityMapsThroughMutationOrThrow } from 'src/engine/workspace-manager/workspace-migration-v2/utils/add-flat-entity-to-flat-entity-maps-through-mutation-or-throw.util';
|
||||
|
||||
@Injectable()
|
||||
@WorkspaceCache('flatSkillMaps')
|
||||
export class WorkspaceFlatSkillMapCacheService extends WorkspaceCacheProvider<FlatSkillMaps> {
|
||||
constructor(
|
||||
@InjectRepository(SkillEntity)
|
||||
private readonly skillRepository: Repository<SkillEntity>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async computeForCache(workspaceId: string): Promise<FlatSkillMaps> {
|
||||
const skills = await this.skillRepository.find({
|
||||
where: { workspaceId },
|
||||
withDeleted: true,
|
||||
});
|
||||
|
||||
const flatSkillMaps = createEmptyFlatEntityMaps();
|
||||
|
||||
for (const skillEntity of skills) {
|
||||
const flatSkill = transformSkillEntityToFlatSkill(skillEntity);
|
||||
|
||||
addFlatEntityToFlatEntityMapsThroughMutationOrThrow({
|
||||
flatEntity: flatSkill,
|
||||
flatEntityMapsToMutate: flatSkillMaps,
|
||||
});
|
||||
}
|
||||
|
||||
return flatSkillMaps;
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
|
||||
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
|
||||
|
||||
export type FlatSkillMaps = FlatEntityMaps<FlatSkill>;
|
||||
@@ -0,0 +1,4 @@
|
||||
import { type SkillEntity } from 'src/engine/metadata-modules/skill/entities/skill.entity';
|
||||
import { type FlatEntityFrom } from 'src/engine/metadata-modules/flat-entity/types/flat-entity.type';
|
||||
|
||||
export type FlatSkill = FlatEntityFrom<SkillEntity>;
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
import { trimAndRemoveDuplicatedWhitespacesFromObjectStringProperties } from 'twenty-shared/utils';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
|
||||
import { type CreateSkillInput } from 'src/engine/metadata-modules/skill/dtos/create-skill.input';
|
||||
|
||||
export const fromCreateSkillInputToFlatSkillToCreate = ({
|
||||
createSkillInput,
|
||||
workspaceId,
|
||||
applicationId,
|
||||
}: {
|
||||
createSkillInput: CreateSkillInput;
|
||||
workspaceId: string;
|
||||
applicationId: string;
|
||||
}): FlatSkill => {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const { name, label, icon, description } =
|
||||
trimAndRemoveDuplicatedWhitespacesFromObjectStringProperties(
|
||||
createSkillInput,
|
||||
['name', 'label', 'icon', 'description'],
|
||||
);
|
||||
|
||||
// Content is markdown - only trim, don't collapse whitespace (preserve newlines)
|
||||
const content = createSkillInput.content.trim();
|
||||
|
||||
const id = v4();
|
||||
|
||||
return {
|
||||
id,
|
||||
standardId: null,
|
||||
name,
|
||||
label,
|
||||
icon: icon ?? null,
|
||||
description: description ?? null,
|
||||
content,
|
||||
isCustom: true,
|
||||
isActive: true,
|
||||
workspaceId,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
universalIdentifier: id,
|
||||
applicationId,
|
||||
};
|
||||
};
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
|
||||
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
|
||||
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
|
||||
import {
|
||||
SkillException,
|
||||
SkillExceptionCode,
|
||||
} from 'src/engine/metadata-modules/skill/skill.exception';
|
||||
|
||||
export const fromDeleteSkillInputToFlatSkillOrThrow = ({
|
||||
flatSkillMaps,
|
||||
skillId,
|
||||
}: {
|
||||
flatSkillMaps: FlatEntityMaps<FlatSkill>;
|
||||
skillId: string;
|
||||
}): FlatSkill => {
|
||||
const existingFlatSkill = findFlatEntityByIdInFlatEntityMaps({
|
||||
flatEntityId: skillId,
|
||||
flatEntityMaps: flatSkillMaps,
|
||||
});
|
||||
|
||||
if (!isDefined(existingFlatSkill)) {
|
||||
throw new SkillException(
|
||||
'Skill not found',
|
||||
SkillExceptionCode.SKILL_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
if (!existingFlatSkill.isCustom) {
|
||||
throw new SkillException(
|
||||
'Cannot delete standard skill',
|
||||
SkillExceptionCode.SKILL_IS_STANDARD,
|
||||
);
|
||||
}
|
||||
|
||||
return existingFlatSkill;
|
||||
};
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
|
||||
import { type SkillDTO } from 'src/engine/metadata-modules/skill/dtos/skill.dto';
|
||||
|
||||
export const fromFlatSkillToSkillDto = (flatSkill: FlatSkill): SkillDTO => ({
|
||||
id: flatSkill.id,
|
||||
standardId: flatSkill.standardId,
|
||||
name: flatSkill.name,
|
||||
label: flatSkill.label,
|
||||
icon: flatSkill.icon ?? undefined,
|
||||
description: flatSkill.description ?? undefined,
|
||||
content: flatSkill.content,
|
||||
isCustom: flatSkill.isCustom,
|
||||
isActive: flatSkill.isActive,
|
||||
workspaceId: flatSkill.workspaceId,
|
||||
applicationId: flatSkill.applicationId ?? undefined,
|
||||
createdAt: new Date(flatSkill.createdAt),
|
||||
updatedAt: new Date(flatSkill.updatedAt),
|
||||
});
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
|
||||
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
|
||||
import { FLAT_SKILL_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-skill/constants/flat-skill-editable-properties.constant';
|
||||
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
|
||||
import { type UpdateSkillInput } from 'src/engine/metadata-modules/skill/dtos/update-skill.input';
|
||||
import {
|
||||
SkillException,
|
||||
SkillExceptionCode,
|
||||
} from 'src/engine/metadata-modules/skill/skill.exception';
|
||||
import { mergeUpdateInExistingRecord } from 'src/utils/merge-update-in-existing-record.util';
|
||||
|
||||
export const fromUpdateSkillInputToFlatSkillToUpdateOrThrow = ({
|
||||
flatSkillMaps,
|
||||
updateSkillInput,
|
||||
}: {
|
||||
flatSkillMaps: FlatEntityMaps<FlatSkill>;
|
||||
updateSkillInput: UpdateSkillInput;
|
||||
}): FlatSkill => {
|
||||
const existingFlatSkill = findFlatEntityByIdInFlatEntityMaps({
|
||||
flatEntityId: updateSkillInput.id,
|
||||
flatEntityMaps: flatSkillMaps,
|
||||
});
|
||||
|
||||
if (!isDefined(existingFlatSkill)) {
|
||||
throw new SkillException(
|
||||
'Skill not found',
|
||||
SkillExceptionCode.SKILL_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
if (!existingFlatSkill.isCustom) {
|
||||
throw new SkillException(
|
||||
'Cannot update standard skill',
|
||||
SkillExceptionCode.SKILL_IS_STANDARD,
|
||||
);
|
||||
}
|
||||
|
||||
const { id: _id, ...updates } = updateSkillInput;
|
||||
|
||||
return {
|
||||
...mergeUpdateInExistingRecord({
|
||||
existing: existingFlatSkill,
|
||||
properties: [...FLAT_SKILL_EDITABLE_PROPERTIES],
|
||||
update: updates,
|
||||
}),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
};
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { type SkillEntity } from 'src/engine/metadata-modules/skill/entities/skill.entity';
|
||||
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
|
||||
|
||||
export const transformSkillEntityToFlatSkill = (
|
||||
skillEntity: SkillEntity,
|
||||
): FlatSkill => {
|
||||
return {
|
||||
createdAt: skillEntity.createdAt.toISOString(),
|
||||
updatedAt: skillEntity.updatedAt.toISOString(),
|
||||
id: skillEntity.id,
|
||||
standardId: skillEntity.standardId,
|
||||
name: skillEntity.name,
|
||||
label: skillEntity.label,
|
||||
icon: skillEntity.icon,
|
||||
description: skillEntity.description,
|
||||
content: skillEntity.content,
|
||||
workspaceId: skillEntity.workspaceId,
|
||||
isCustom: skillEntity.isCustom,
|
||||
isActive: skillEntity.isActive,
|
||||
universalIdentifier: skillEntity.standardId || skillEntity.id,
|
||||
applicationId: skillEntity.applicationId,
|
||||
};
|
||||
};
|
||||
@@ -15,6 +15,7 @@ import { RouteTriggerModule } from 'src/engine/metadata-modules/route-trigger/ro
|
||||
import { SearchFieldMetadataModule } from 'src/engine/metadata-modules/search-field-metadata/search-field-metadata.module';
|
||||
import { ServerlessFunctionLayerModule } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.module';
|
||||
import { ServerlessFunctionModule } from 'src/engine/metadata-modules/serverless-function/serverless-function.module';
|
||||
import { SkillModule } from 'src/engine/metadata-modules/skill/skill.module';
|
||||
import { ViewModule } from 'src/engine/metadata-modules/view/view.module';
|
||||
import { WorkspaceMetadataVersionModule } from 'src/engine/metadata-modules/workspace-metadata-version/workspace-metadata-version.module';
|
||||
import { WorkspaceMigrationModule } from 'src/engine/metadata-modules/workspace-migration/workspace-migration.module';
|
||||
@@ -27,6 +28,7 @@ import { WorkspaceMigrationModule } from 'src/engine/metadata-modules/workspace-
|
||||
SearchFieldMetadataModule,
|
||||
ServerlessFunctionModule,
|
||||
ServerlessFunctionLayerModule,
|
||||
SkillModule,
|
||||
AiAgentModule,
|
||||
AiAgentMonitorModule,
|
||||
AiChatModule,
|
||||
@@ -47,6 +49,7 @@ import { WorkspaceMigrationModule } from 'src/engine/metadata-modules/workspace-
|
||||
ObjectMetadataModule,
|
||||
SearchFieldMetadataModule,
|
||||
ServerlessFunctionModule,
|
||||
SkillModule,
|
||||
AiAgentModule,
|
||||
AiChatModule,
|
||||
ViewModule,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Field, InputType } from '@nestjs/graphql';
|
||||
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
@InputType()
|
||||
export class CreateSkillInput {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Field()
|
||||
name: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Field()
|
||||
label: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
icon?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
description?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Field()
|
||||
content: string;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Field, HideField, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
import {
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
IsNotEmpty,
|
||||
IsString,
|
||||
IsUUID,
|
||||
} from 'class-validator';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@ObjectType('Skill')
|
||||
export class SkillDTO {
|
||||
@IsUUID()
|
||||
@IsNotEmpty()
|
||||
@Field(() => UUIDScalarType)
|
||||
id: string;
|
||||
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
standardId?: string | null;
|
||||
|
||||
@IsString()
|
||||
@Field()
|
||||
name: string;
|
||||
|
||||
@IsString()
|
||||
@Field()
|
||||
label: string;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
icon?: string;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
description?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Field()
|
||||
content: string;
|
||||
|
||||
@IsBoolean()
|
||||
@Field()
|
||||
isCustom: boolean;
|
||||
|
||||
@IsBoolean()
|
||||
@Field()
|
||||
isActive: boolean;
|
||||
|
||||
@HideField()
|
||||
workspaceId: string;
|
||||
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
applicationId?: string;
|
||||
|
||||
@IsDateString()
|
||||
@Field()
|
||||
createdAt: Date;
|
||||
|
||||
@IsDateString()
|
||||
@Field()
|
||||
updatedAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Field, InputType } from '@nestjs/graphql';
|
||||
|
||||
import {
|
||||
IsBoolean,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
} from 'class-validator';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@InputType()
|
||||
export class UpdateSkillInput {
|
||||
@IsUUID()
|
||||
@IsNotEmpty()
|
||||
@Field(() => UUIDScalarType)
|
||||
id: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
name?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
label?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
icon?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
description?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
content?: string;
|
||||
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
isActive?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
import { SyncableEntity } from 'src/engine/workspace-manager/workspace-sync/types/syncable-entity.interface';
|
||||
|
||||
@Entity('skill')
|
||||
@Index('IDX_SKILL_ID_IS_ACTIVE', ['id', 'isActive'])
|
||||
@Index('IDX_SKILL_NAME_WORKSPACE_ID_UNIQUE', ['name', 'workspaceId'], {
|
||||
unique: true,
|
||||
where: '"isActive" = true',
|
||||
})
|
||||
export class SkillEntity
|
||||
extends SyncableEntity
|
||||
implements Required<SkillEntity>
|
||||
{
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ nullable: true, type: 'uuid' })
|
||||
standardId: string | null;
|
||||
|
||||
@Column({ nullable: false })
|
||||
name: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
label: string;
|
||||
|
||||
@Column({ nullable: true, type: 'varchar' })
|
||||
icon: string | null;
|
||||
|
||||
@Column({ nullable: true, type: 'text' })
|
||||
description: string | null;
|
||||
|
||||
@Column({ nullable: false, type: 'text' })
|
||||
content: string;
|
||||
|
||||
@Column({ default: false })
|
||||
isCustom: boolean;
|
||||
|
||||
@Column({ default: true })
|
||||
isActive: boolean;
|
||||
|
||||
@CreateDateColumn({ type: 'timestamptz' })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ type: 'timestamptz' })
|
||||
updatedAt: Date;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import {
|
||||
type CallHandler,
|
||||
type ExecutionContext,
|
||||
Injectable,
|
||||
type NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
|
||||
import { type Observable, catchError } from 'rxjs';
|
||||
|
||||
import { skillGraphqlApiExceptionHandler } from 'src/engine/metadata-modules/skill/utils/skill-graphql-api-exception-handler.util';
|
||||
|
||||
@Injectable()
|
||||
export class SkillGraphqlApiExceptionInterceptor implements NestInterceptor {
|
||||
intercept(
|
||||
_context: ExecutionContext,
|
||||
next: CallHandler,
|
||||
): Observable<unknown> {
|
||||
return next.handle().pipe(catchError(skillGraphqlApiExceptionHandler));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { type MessageDescriptor } from '@lingui/core';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { assertUnreachable } from 'twenty-shared/utils';
|
||||
|
||||
import { CustomException } from 'src/utils/custom-exception';
|
||||
|
||||
export enum SkillExceptionCode {
|
||||
SKILL_NOT_FOUND = 'SKILL_NOT_FOUND',
|
||||
SKILL_ALREADY_EXISTS = 'SKILL_ALREADY_EXISTS',
|
||||
SKILL_IS_STANDARD = 'SKILL_IS_STANDARD',
|
||||
INVALID_SKILL_INPUT = 'INVALID_SKILL_INPUT',
|
||||
}
|
||||
|
||||
const getSkillExceptionUserFriendlyMessage = (code: SkillExceptionCode) => {
|
||||
switch (code) {
|
||||
case SkillExceptionCode.SKILL_NOT_FOUND:
|
||||
return msg`Skill not found.`;
|
||||
case SkillExceptionCode.SKILL_ALREADY_EXISTS:
|
||||
return msg`A skill with this name already exists.`;
|
||||
case SkillExceptionCode.SKILL_IS_STANDARD:
|
||||
return msg`Standard skills cannot be modified.`;
|
||||
case SkillExceptionCode.INVALID_SKILL_INPUT:
|
||||
return msg`Invalid skill input.`;
|
||||
default:
|
||||
assertUnreachable(code);
|
||||
}
|
||||
};
|
||||
|
||||
export class SkillException extends CustomException<SkillExceptionCode> {
|
||||
constructor(
|
||||
message: string,
|
||||
code: SkillExceptionCode,
|
||||
{ userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
|
||||
) {
|
||||
super(message, code, {
|
||||
userFriendlyMessage:
|
||||
userFriendlyMessage ?? getSkillExceptionUserFriendlyMessage(code),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
|
||||
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
|
||||
import { FlatSkillModule } from 'src/engine/metadata-modules/flat-skill/flat-skill.module';
|
||||
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
|
||||
import { SkillGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/skill/interceptors/skill-graphql-api-exception.interceptor';
|
||||
import { SkillResolver } from 'src/engine/metadata-modules/skill/skill.resolver';
|
||||
import { SkillService } from 'src/engine/metadata-modules/skill/skill.service';
|
||||
import { WorkspaceMigrationBuilderGraphqlApiExceptionInterceptor } from 'src/engine/workspace-manager/workspace-migration-v2/interceptors/workspace-migration-builder-graphql-api-exception.interceptor';
|
||||
import { WorkspaceMigrationV2Module } from 'src/engine/workspace-manager/workspace-migration-v2/workspace-migration-v2.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
WorkspaceManyOrAllFlatEntityMapsCacheModule,
|
||||
WorkspaceMigrationV2Module,
|
||||
ApplicationModule,
|
||||
PermissionsModule,
|
||||
FlatSkillModule,
|
||||
],
|
||||
providers: [
|
||||
SkillService,
|
||||
SkillResolver,
|
||||
SkillGraphqlApiExceptionInterceptor,
|
||||
WorkspaceMigrationBuilderGraphqlApiExceptionInterceptor,
|
||||
],
|
||||
exports: [SkillService],
|
||||
})
|
||||
export class SkillModule {}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { UseGuards, UseInterceptors } from '@nestjs/common';
|
||||
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
|
||||
|
||||
import { PermissionFlagType } from 'twenty-shared/constants';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
|
||||
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
|
||||
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
|
||||
import { CreateSkillInput } from 'src/engine/metadata-modules/skill/dtos/create-skill.input';
|
||||
import { SkillDTO } from 'src/engine/metadata-modules/skill/dtos/skill.dto';
|
||||
import { UpdateSkillInput } from 'src/engine/metadata-modules/skill/dtos/update-skill.input';
|
||||
import { SkillGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/skill/interceptors/skill-graphql-api-exception.interceptor';
|
||||
import { SkillService } from 'src/engine/metadata-modules/skill/skill.service';
|
||||
import { WorkspaceMigrationBuilderGraphqlApiExceptionInterceptor } from 'src/engine/workspace-manager/workspace-migration-v2/interceptors/workspace-migration-builder-graphql-api-exception.interceptor';
|
||||
|
||||
@UseGuards(WorkspaceAuthGuard, SettingsPermissionGuard(PermissionFlagType.AI))
|
||||
@UseInterceptors(
|
||||
WorkspaceMigrationBuilderGraphqlApiExceptionInterceptor,
|
||||
SkillGraphqlApiExceptionInterceptor,
|
||||
)
|
||||
@Resolver(() => SkillDTO)
|
||||
export class SkillResolver {
|
||||
constructor(private readonly skillService: SkillService) {}
|
||||
|
||||
@Query(() => [SkillDTO])
|
||||
async skills(
|
||||
@AuthWorkspace() workspace: WorkspaceEntity,
|
||||
): Promise<SkillDTO[]> {
|
||||
return this.skillService.findAll(workspace.id);
|
||||
}
|
||||
|
||||
@Query(() => SkillDTO, { nullable: true })
|
||||
async skill(
|
||||
@Args('id', { type: () => UUIDScalarType }) id: string,
|
||||
@AuthWorkspace() workspace: WorkspaceEntity,
|
||||
): Promise<SkillDTO | null> {
|
||||
return this.skillService.findById(id, workspace.id);
|
||||
}
|
||||
|
||||
@Mutation(() => SkillDTO)
|
||||
async createSkill(
|
||||
@Args('input') input: CreateSkillInput,
|
||||
@AuthWorkspace() workspace: WorkspaceEntity,
|
||||
): Promise<SkillDTO> {
|
||||
return this.skillService.create(input, workspace.id);
|
||||
}
|
||||
|
||||
@Mutation(() => SkillDTO)
|
||||
async updateSkill(
|
||||
@Args('input') input: UpdateSkillInput,
|
||||
@AuthWorkspace() workspace: WorkspaceEntity,
|
||||
): Promise<SkillDTO> {
|
||||
return this.skillService.update(input, workspace.id);
|
||||
}
|
||||
|
||||
@Mutation(() => SkillDTO)
|
||||
async deleteSkill(
|
||||
@Args('id', { type: () => UUIDScalarType }) id: string,
|
||||
@AuthWorkspace() workspace: WorkspaceEntity,
|
||||
): Promise<SkillDTO> {
|
||||
return this.skillService.delete(id, workspace.id);
|
||||
}
|
||||
|
||||
@Mutation(() => SkillDTO)
|
||||
async activateSkill(
|
||||
@Args('id', { type: () => UUIDScalarType }) id: string,
|
||||
@AuthWorkspace() workspace: WorkspaceEntity,
|
||||
): Promise<SkillDTO> {
|
||||
return this.skillService.activate(id, workspace.id);
|
||||
}
|
||||
|
||||
@Mutation(() => SkillDTO)
|
||||
async deactivateSkill(
|
||||
@Args('id', { type: () => UUIDScalarType }) id: string,
|
||||
@AuthWorkspace() workspace: WorkspaceEntity,
|
||||
): Promise<SkillDTO> {
|
||||
return this.skillService.deactivate(id, workspace.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
|
||||
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
|
||||
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
|
||||
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
|
||||
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
|
||||
import { fromCreateSkillInputToFlatSkillToCreate } from 'src/engine/metadata-modules/flat-skill/utils/from-create-skill-input-to-flat-skill-to-create.util';
|
||||
import { fromDeleteSkillInputToFlatSkillOrThrow } from 'src/engine/metadata-modules/flat-skill/utils/from-delete-skill-input-to-flat-skill-or-throw.util';
|
||||
import { fromFlatSkillToSkillDto } from 'src/engine/metadata-modules/flat-skill/utils/from-flat-skill-to-skill-dto.util';
|
||||
import { fromUpdateSkillInputToFlatSkillToUpdateOrThrow } from 'src/engine/metadata-modules/flat-skill/utils/from-update-skill-input-to-flat-skill-to-update-or-throw.util';
|
||||
import { type CreateSkillInput } from 'src/engine/metadata-modules/skill/dtos/create-skill.input';
|
||||
import { type SkillDTO } from 'src/engine/metadata-modules/skill/dtos/skill.dto';
|
||||
import { type UpdateSkillInput } from 'src/engine/metadata-modules/skill/dtos/update-skill.input';
|
||||
import {
|
||||
SkillException,
|
||||
SkillExceptionCode,
|
||||
} from 'src/engine/metadata-modules/skill/skill.exception';
|
||||
import { WorkspaceMigrationBuilderExceptionV2 } from 'src/engine/workspace-manager/workspace-migration-v2/exceptions/workspace-migration-builder-exception-v2';
|
||||
import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration-v2/services/workspace-migration-validate-build-and-run-service';
|
||||
|
||||
@Injectable()
|
||||
export class SkillService {
|
||||
constructor(
|
||||
private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
|
||||
private readonly workspaceManyOrAllFlatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
|
||||
private readonly applicationService: ApplicationService,
|
||||
) {}
|
||||
|
||||
async findAll(workspaceId: string): Promise<SkillDTO[]> {
|
||||
const { flatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return Object.values(flatSkillMaps.byId)
|
||||
.filter(isDefined)
|
||||
.sort((a, b) => a.label.localeCompare(b.label))
|
||||
.map(fromFlatSkillToSkillDto);
|
||||
}
|
||||
|
||||
async findById(id: string, workspaceId: string): Promise<SkillDTO | null> {
|
||||
const { flatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatSkill = findFlatEntityByIdInFlatEntityMaps({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: flatSkillMaps,
|
||||
});
|
||||
|
||||
if (!isDefined(flatSkill)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return fromFlatSkillToSkillDto(flatSkill);
|
||||
}
|
||||
|
||||
async create(
|
||||
input: CreateSkillInput,
|
||||
workspaceId: string,
|
||||
): Promise<SkillDTO> {
|
||||
const { workspaceCustomFlatApplication } =
|
||||
await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
|
||||
{ workspaceId },
|
||||
);
|
||||
|
||||
const flatSkillToCreate = fromCreateSkillInputToFlatSkillToCreate({
|
||||
createSkillInput: input,
|
||||
workspaceId,
|
||||
applicationId: workspaceCustomFlatApplication.id,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
skill: {
|
||||
flatEntityToCreate: [flatSkillToCreate],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderExceptionV2(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while creating skill',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatSkillMaps: recomputedFlatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return fromFlatSkillToSkillDto(
|
||||
findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: flatSkillToCreate.id,
|
||||
flatEntityMaps: recomputedFlatSkillMaps,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async update(
|
||||
input: UpdateSkillInput,
|
||||
workspaceId: string,
|
||||
): Promise<SkillDTO> {
|
||||
const { flatSkillMaps: existingFlatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatSkillToUpdate = fromUpdateSkillInputToFlatSkillToUpdateOrThrow({
|
||||
flatSkillMaps: existingFlatSkillMaps,
|
||||
updateSkillInput: input,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
skill: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [flatSkillToUpdate],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderExceptionV2(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while updating skill',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatSkillMaps: recomputedFlatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return fromFlatSkillToSkillDto(
|
||||
findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: input.id,
|
||||
flatEntityMaps: recomputedFlatSkillMaps,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async delete(id: string, workspaceId: string): Promise<SkillDTO> {
|
||||
const { flatSkillMaps: existingFlatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatSkillToDelete = fromDeleteSkillInputToFlatSkillOrThrow({
|
||||
flatSkillMaps: existingFlatSkillMaps,
|
||||
skillId: id,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
skill: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [flatSkillToDelete],
|
||||
flatEntityToUpdate: [],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderExceptionV2(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while deleting skill',
|
||||
);
|
||||
}
|
||||
|
||||
return fromFlatSkillToSkillDto(flatSkillToDelete);
|
||||
}
|
||||
|
||||
async findAllFlatSkills(workspaceId: string): Promise<FlatSkill[]> {
|
||||
const { flatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return Object.values(flatSkillMaps.byId)
|
||||
.filter(isDefined)
|
||||
.filter((flatSkill) => flatSkill.isActive)
|
||||
.sort((a, b) => a.label.localeCompare(b.label));
|
||||
}
|
||||
|
||||
async findFlatSkillsByNames(
|
||||
names: string[],
|
||||
workspaceId: string,
|
||||
): Promise<FlatSkill[]> {
|
||||
if (names.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const { flatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return Object.values(flatSkillMaps.byId)
|
||||
.filter(isDefined)
|
||||
.filter(
|
||||
(flatSkill) => names.includes(flatSkill.name) && flatSkill.isActive,
|
||||
);
|
||||
}
|
||||
|
||||
async activate(id: string, workspaceId: string): Promise<SkillDTO> {
|
||||
const { flatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatSkill = findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: flatSkillMaps,
|
||||
});
|
||||
|
||||
const flatSkillToUpdate: FlatSkill = {
|
||||
...existingFlatSkill,
|
||||
isActive: true,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
skill: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [flatSkillToUpdate],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderExceptionV2(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while activating skill',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatSkillMaps: recomputedFlatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return fromFlatSkillToSkillDto(
|
||||
findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: recomputedFlatSkillMaps,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async deactivate(id: string, workspaceId: string): Promise<SkillDTO> {
|
||||
const { flatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatSkill = findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: flatSkillMaps,
|
||||
});
|
||||
|
||||
const flatSkillToUpdate: FlatSkill = {
|
||||
...existingFlatSkill,
|
||||
isActive: false,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
skill: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [flatSkillToUpdate],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderExceptionV2(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while deactivating skill',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatSkillMaps: recomputedFlatSkillMaps } =
|
||||
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatSkillMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return fromFlatSkillToSkillDto(
|
||||
findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: recomputedFlatSkillMaps,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async findByIdOrThrow(id: string, workspaceId: string): Promise<SkillDTO> {
|
||||
const skill = await this.findById(id, workspaceId);
|
||||
|
||||
if (!isDefined(skill)) {
|
||||
throw new SkillException(
|
||||
'Skill not found',
|
||||
SkillExceptionCode.SKILL_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
return skill;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { assertUnreachable } from 'twenty-shared/utils';
|
||||
|
||||
import {
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
UserInputError,
|
||||
} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
|
||||
import {
|
||||
SkillException,
|
||||
SkillExceptionCode,
|
||||
} from 'src/engine/metadata-modules/skill/skill.exception';
|
||||
|
||||
export const skillGraphqlApiExceptionHandler = (error: Error) => {
|
||||
if (error instanceof SkillException) {
|
||||
switch (error.code) {
|
||||
case SkillExceptionCode.SKILL_NOT_FOUND:
|
||||
throw new NotFoundError(error);
|
||||
case SkillExceptionCode.INVALID_SKILL_INPUT:
|
||||
throw new UserInputError(error);
|
||||
case SkillExceptionCode.SKILL_ALREADY_EXISTS:
|
||||
throw new ConflictError(error);
|
||||
case SkillExceptionCode.SKILL_IS_STANDARD:
|
||||
throw new ForbiddenError(error);
|
||||
default: {
|
||||
return assertUnreachable(error.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
};
|
||||
Reference in New Issue
Block a user