Move view in metadata-modules/ and create atomic folder + module for each view entity (#14990)
# Introduction Preparing view-filter and view-group introduction in v2 core engine Moving view from `core-modules` to `metadata-modules` ## What happened ### Created dedicated modules for each view entity: - ViewFieldModule - ViewFilterModule - ViewFilterGroupModule - ViewGroupModule - ViewSortModule ### Each module is now completely independent with its own: - Controller - Resolver - Service - Entity ### Created dedicated abstraction metadata module folder for: - flat-view-field - flat-view ### Dependencies - Eleminated circular dep on ViewModule to all others ones - Granular import not importing the whole viewModule anymore everywhere close https://github.com/twentyhq/core-team-issues/issues/1703
This commit is contained in:
+1
@@ -0,0 +1 @@
|
||||
export const FIND_ALL_CORE_VIEWS_GRAPHQL_OPERATION = 'FindAllCoreViews';
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
UseFilters,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
|
||||
import { type APP_LOCALES } from 'twenty-shared/translations';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
|
||||
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
|
||||
import { RequestLocale } from 'src/engine/decorators/locale/request-locale.decorator';
|
||||
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
|
||||
import { resolveObjectMetadataStandardOverride } from 'src/engine/metadata-modules/object-metadata/utils/resolve-object-metadata-standard-override.util';
|
||||
import { CreateViewInput } from 'src/engine/metadata-modules/view/dtos/inputs/create-view.input';
|
||||
import { UpdateViewInput } from 'src/engine/metadata-modules/view/dtos/inputs/update-view.input';
|
||||
import { type ViewDTO } from 'src/engine/metadata-modules/view/dtos/view.dto';
|
||||
import {
|
||||
generateViewExceptionMessage,
|
||||
generateViewUserFriendlyExceptionMessage,
|
||||
ViewException,
|
||||
ViewExceptionCode,
|
||||
ViewExceptionMessageKey,
|
||||
} from 'src/engine/metadata-modules/view/exceptions/view.exception';
|
||||
import { ViewRestApiExceptionFilter } from 'src/engine/metadata-modules/view/filters/view-rest-api-exception.filter';
|
||||
import { ViewService } from 'src/engine/metadata-modules/view/services/view.service';
|
||||
import { WorkspaceMetadataCacheService } from 'src/engine/metadata-modules/workspace-metadata-cache/services/workspace-metadata-cache.service';
|
||||
|
||||
@Controller('rest/metadata/views')
|
||||
@UseGuards(WorkspaceAuthGuard)
|
||||
@UseFilters(ViewRestApiExceptionFilter)
|
||||
export class ViewController {
|
||||
constructor(
|
||||
private readonly viewService: ViewService,
|
||||
private readonly workspaceMetadataCacheService: WorkspaceMetadataCacheService,
|
||||
private readonly i18nService: I18nService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
async findMany(
|
||||
@RequestLocale() locale: keyof typeof APP_LOCALES | undefined,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
@Query('objectMetadataId') objectMetadataId?: string,
|
||||
): Promise<ViewDTO[]> {
|
||||
const views = objectMetadataId
|
||||
? await this.viewService.findByObjectMetadataId(
|
||||
workspace.id,
|
||||
objectMetadataId,
|
||||
)
|
||||
: await this.viewService.findByWorkspaceId(workspace.id);
|
||||
|
||||
return this.processViewsWithTemplates(views, workspace.id, locale);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async findOne(
|
||||
@Param('id') id: string,
|
||||
@RequestLocale() locale: keyof typeof APP_LOCALES | undefined,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
): Promise<ViewDTO> {
|
||||
const view = await this.viewService.findById(id, workspace.id);
|
||||
|
||||
if (!isDefined(view)) {
|
||||
throw new ViewException(
|
||||
generateViewExceptionMessage(
|
||||
ViewExceptionMessageKey.VIEW_NOT_FOUND,
|
||||
id,
|
||||
),
|
||||
ViewExceptionCode.VIEW_NOT_FOUND,
|
||||
{
|
||||
userFriendlyMessage: generateViewUserFriendlyExceptionMessage(
|
||||
ViewExceptionMessageKey.VIEW_NOT_FOUND,
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const processedViews = await this.processViewsWithTemplates(
|
||||
[view],
|
||||
workspace.id,
|
||||
locale,
|
||||
);
|
||||
|
||||
return processedViews[0];
|
||||
}
|
||||
|
||||
@Post()
|
||||
async create(
|
||||
@Body() input: CreateViewInput,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
@RequestLocale() locale?: keyof typeof APP_LOCALES,
|
||||
): Promise<ViewDTO> {
|
||||
const view = await this.viewService.create({
|
||||
...input,
|
||||
workspaceId: workspace.id,
|
||||
});
|
||||
|
||||
const processedViews = await this.processViewsWithTemplates(
|
||||
[view],
|
||||
workspace.id,
|
||||
locale,
|
||||
);
|
||||
|
||||
return processedViews[0];
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
async update(
|
||||
@Param('id') id: string,
|
||||
@Body() input: UpdateViewInput,
|
||||
@RequestLocale() locale: keyof typeof APP_LOCALES | undefined,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
): Promise<ViewDTO> {
|
||||
const updatedView = await this.viewService.update(id, workspace.id, input);
|
||||
|
||||
const processedViews = await this.processViewsWithTemplates(
|
||||
[updatedView],
|
||||
workspace.id,
|
||||
locale,
|
||||
);
|
||||
|
||||
return processedViews[0];
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
async delete(
|
||||
@Param('id') id: string,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
): Promise<{ success: boolean }> {
|
||||
const deletedView = await this.viewService.delete(id, workspace.id);
|
||||
|
||||
return { success: isDefined(deletedView) };
|
||||
}
|
||||
|
||||
private async processViewsWithTemplates(
|
||||
views: ViewDTO[],
|
||||
workspaceId: string,
|
||||
locale?: keyof typeof APP_LOCALES,
|
||||
): Promise<ViewDTO[]> {
|
||||
const hasTemplates = views.some((view) =>
|
||||
view.name.includes('{objectLabelPlural}'),
|
||||
);
|
||||
|
||||
if (!hasTemplates && views.every((view) => view.isCustom)) {
|
||||
return views;
|
||||
}
|
||||
|
||||
const { objectMetadataMaps } =
|
||||
await this.workspaceMetadataCacheService.getExistingOrRecomputeMetadataMaps(
|
||||
{ workspaceId },
|
||||
);
|
||||
|
||||
return views.map((view) => {
|
||||
let processedName = view.name;
|
||||
|
||||
if (view.name.includes('{objectLabelPlural}')) {
|
||||
const objectMetadata = objectMetadataMaps.byId[view.objectMetadataId];
|
||||
|
||||
if (objectMetadata) {
|
||||
const i18n = this.i18nService.getI18nInstance(locale ?? 'en');
|
||||
const translatedObjectLabel = resolveObjectMetadataStandardOverride(
|
||||
{
|
||||
labelPlural: objectMetadata.labelPlural,
|
||||
labelSingular: objectMetadata.labelSingular,
|
||||
description: objectMetadata.description ?? undefined,
|
||||
icon: objectMetadata.icon ?? undefined,
|
||||
isCustom: objectMetadata.isCustom,
|
||||
standardOverrides: objectMetadata.standardOverrides ?? undefined,
|
||||
},
|
||||
'labelPlural',
|
||||
locale,
|
||||
i18n,
|
||||
);
|
||||
|
||||
processedName = this.viewService.processViewNameWithTemplate(
|
||||
view.name,
|
||||
view.isCustom,
|
||||
translatedObjectLabel,
|
||||
locale,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
processedName = this.viewService.processViewNameWithTemplate(
|
||||
view.name,
|
||||
view.isCustom,
|
||||
undefined,
|
||||
locale,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
...view,
|
||||
name: processedName,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// TODO: the destroy endpoint will be implemented when we settle on a strategy
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import { Field, InputType } from '@nestjs/graphql';
|
||||
|
||||
import {
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
} from 'class-validator';
|
||||
|
||||
import { AggregateOperations } from 'src/engine/api/graphql/graphql-query-runner/constants/aggregate-operations.constant';
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
import { IsValidMetadataName } from 'src/engine/decorators/metadata/is-valid-metadata-name.decorator';
|
||||
import { ViewCalendarLayout } from 'src/engine/metadata-modules/view/enums/view-calendar-layout.enum';
|
||||
import { ViewKey } from 'src/engine/metadata-modules/view/enums/view-key.enum';
|
||||
import { ViewOpenRecordIn } from 'src/engine/metadata-modules/view/enums/view-open-record-in';
|
||||
import { ViewType } from 'src/engine/metadata-modules/view/enums/view-type.enum';
|
||||
|
||||
@InputType()
|
||||
export class CreateViewInput {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
id?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@IsValidMetadataName()
|
||||
@Field({ nullable: false })
|
||||
name: string;
|
||||
|
||||
@IsUUID()
|
||||
@Field(() => UUIDScalarType, { nullable: false })
|
||||
objectMetadataId: string;
|
||||
|
||||
@IsEnum(ViewType)
|
||||
@Field(() => ViewType, { nullable: true, defaultValue: ViewType.TABLE })
|
||||
type?: ViewType;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(ViewKey)
|
||||
@Field(() => ViewKey, { nullable: true })
|
||||
key?: ViewKey;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: false })
|
||||
icon: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Field({ nullable: true, defaultValue: 0 })
|
||||
position?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Field({ nullable: true, defaultValue: false })
|
||||
isCompact?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(ViewOpenRecordIn)
|
||||
@Field(() => ViewOpenRecordIn, {
|
||||
nullable: true,
|
||||
defaultValue: ViewOpenRecordIn.SIDE_PANEL,
|
||||
})
|
||||
openRecordIn?: ViewOpenRecordIn;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(AggregateOperations)
|
||||
@Field(() => AggregateOperations, { nullable: true })
|
||||
kanbanAggregateOperation?: AggregateOperations;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
kanbanAggregateOperationFieldMetadataId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
anyFieldFilterValue?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(ViewCalendarLayout)
|
||||
@Field(() => ViewCalendarLayout, { nullable: true })
|
||||
calendarLayout?: ViewCalendarLayout;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
calendarFieldMetadataId?: string;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { InputType } from '@nestjs/graphql';
|
||||
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
import { IsUUID } from 'class-validator';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@InputType()
|
||||
export class DeleteViewInput {
|
||||
@IDField(() => UUIDScalarType, {
|
||||
description: 'The id of the view to delete.',
|
||||
})
|
||||
@IsUUID()
|
||||
id: string;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { InputType } from '@nestjs/graphql';
|
||||
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
import { IsUUID } from 'class-validator';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@InputType()
|
||||
export class DestroyViewInput {
|
||||
@IDField(() => UUIDScalarType, {
|
||||
description: 'The id of the view to destroy.',
|
||||
})
|
||||
@IsUUID()
|
||||
id: string;
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { Field, InputType } from '@nestjs/graphql';
|
||||
|
||||
import {
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
} from 'class-validator';
|
||||
|
||||
import { AggregateOperations } from 'src/engine/api/graphql/graphql-query-runner/constants/aggregate-operations.constant';
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
import { IsValidMetadataName } from 'src/engine/decorators/metadata/is-valid-metadata-name.decorator';
|
||||
import { ViewCalendarLayout } from 'src/engine/metadata-modules/view/enums/view-calendar-layout.enum';
|
||||
import { ViewOpenRecordIn } from 'src/engine/metadata-modules/view/enums/view-open-record-in';
|
||||
import { ViewType } from 'src/engine/metadata-modules/view/enums/view-type.enum';
|
||||
|
||||
// TODO: this should be refactored like for view-field.input.ts
|
||||
// This is a temporary fix as we were extending the CreateViewInput class which was adding default values for the non filled fields
|
||||
@InputType()
|
||||
export class UpdateViewInput {
|
||||
@IsUUID()
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
id: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNotEmpty()
|
||||
@IsValidMetadataName()
|
||||
@Field({ nullable: true })
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(ViewType)
|
||||
@Field(() => ViewType, { nullable: true })
|
||||
type?: ViewType;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
icon?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Field({ nullable: true })
|
||||
position?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Field({ nullable: true })
|
||||
isCompact?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(ViewOpenRecordIn)
|
||||
@Field(() => ViewOpenRecordIn, {
|
||||
nullable: true,
|
||||
})
|
||||
openRecordIn?: ViewOpenRecordIn;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(AggregateOperations)
|
||||
@Field(() => AggregateOperations, { nullable: true })
|
||||
kanbanAggregateOperation?: AggregateOperations;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
kanbanAggregateOperationFieldMetadataId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
anyFieldFilterValue?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(ViewCalendarLayout)
|
||||
@Field(() => ViewCalendarLayout, { nullable: true })
|
||||
calendarLayout?: ViewCalendarLayout;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
calendarFieldMetadataId?: string;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Field, ObjectType, registerEnumType } from '@nestjs/graphql';
|
||||
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
|
||||
import { AggregateOperations } from 'src/engine/api/graphql/graphql-query-runner/constants/aggregate-operations.constant';
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
import { ViewFieldDTO } from 'src/engine/metadata-modules/view-field/dtos/view-field.dto';
|
||||
import { ViewFilterGroupDTO } from 'src/engine/metadata-modules/view-filter-group/dtos/view-filter-group.dto';
|
||||
import { ViewFilterDTO } from 'src/engine/metadata-modules/view-filter/dtos/view-filter.dto';
|
||||
import { ViewGroupDTO } from 'src/engine/metadata-modules/view-group/dtos/view-group.dto';
|
||||
import { ViewSortDTO } from 'src/engine/metadata-modules/view-sort/dtos/view-sort.dto';
|
||||
import { ViewCalendarLayout } from 'src/engine/metadata-modules/view/enums/view-calendar-layout.enum';
|
||||
import { ViewKey } from 'src/engine/metadata-modules/view/enums/view-key.enum';
|
||||
import { ViewOpenRecordIn } from 'src/engine/metadata-modules/view/enums/view-open-record-in';
|
||||
import { ViewType } from 'src/engine/metadata-modules/view/enums/view-type.enum';
|
||||
|
||||
registerEnumType(ViewOpenRecordIn, { name: 'ViewOpenRecordIn' });
|
||||
registerEnumType(ViewType, { name: 'ViewType' });
|
||||
registerEnumType(ViewKey, { name: 'ViewKey' });
|
||||
registerEnumType(ViewCalendarLayout, { name: 'ViewCalendarLayout' });
|
||||
|
||||
@ObjectType('CoreView')
|
||||
export class ViewDTO {
|
||||
@IDField(() => UUIDScalarType)
|
||||
id: string;
|
||||
|
||||
@Field({ nullable: false })
|
||||
name: string;
|
||||
|
||||
@Field(() => UUIDScalarType, { nullable: false })
|
||||
objectMetadataId: string;
|
||||
|
||||
@Field(() => ViewType, { nullable: false, defaultValue: ViewType.TABLE })
|
||||
type: ViewType;
|
||||
|
||||
@Field(() => ViewKey, { nullable: true, defaultValue: ViewKey.INDEX })
|
||||
key: ViewKey | null;
|
||||
|
||||
@Field({ nullable: false })
|
||||
icon: string;
|
||||
|
||||
@Field({ nullable: false, defaultValue: 0 })
|
||||
position: number;
|
||||
|
||||
@Field({ nullable: false, defaultValue: false })
|
||||
isCompact: boolean;
|
||||
|
||||
@Field({ nullable: false, defaultValue: false })
|
||||
isCustom: boolean;
|
||||
|
||||
@Field(() => ViewOpenRecordIn, {
|
||||
nullable: false,
|
||||
defaultValue: ViewOpenRecordIn.SIDE_PANEL,
|
||||
})
|
||||
openRecordIn: ViewOpenRecordIn;
|
||||
|
||||
@Field(() => AggregateOperations, { nullable: true })
|
||||
kanbanAggregateOperation?: AggregateOperations | null;
|
||||
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
kanbanAggregateOperationFieldMetadataId?: string | null;
|
||||
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
calendarFieldMetadataId?: string | null;
|
||||
|
||||
@Field(() => UUIDScalarType, { nullable: false })
|
||||
workspaceId: string;
|
||||
|
||||
@Field(() => String, { nullable: true })
|
||||
anyFieldFilterValue?: string | null;
|
||||
|
||||
@Field(() => ViewCalendarLayout, { nullable: true })
|
||||
calendarLayout: ViewCalendarLayout | null;
|
||||
|
||||
@Field()
|
||||
createdAt: Date;
|
||||
|
||||
@Field()
|
||||
updatedAt: Date;
|
||||
|
||||
@Field(() => Date, { nullable: true })
|
||||
deletedAt?: Date | null;
|
||||
|
||||
@Field(() => [ViewFieldDTO])
|
||||
viewFields?: ViewFieldDTO[];
|
||||
|
||||
@Field(() => [ViewFilterDTO])
|
||||
viewFilters?: ViewFilterDTO[];
|
||||
|
||||
@Field(() => [ViewFilterGroupDTO])
|
||||
viewFilterGroups?: ViewFilterGroupDTO[];
|
||||
|
||||
@Field(() => [ViewSortDTO])
|
||||
viewSorts?: ViewSortDTO[];
|
||||
|
||||
@Field(() => [ViewGroupDTO])
|
||||
viewGroups?: ViewGroupDTO[];
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import {
|
||||
Check,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
DeleteDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
Relation,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
import { SyncableEntity } from 'src/engine/workspace-manager/workspace-sync/interfaces/syncable-entity.interface';
|
||||
|
||||
import { AggregateOperations } from 'src/engine/api/graphql/graphql-query-runner/constants/aggregate-operations.constant';
|
||||
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
|
||||
import { ViewFieldEntity } from 'src/engine/metadata-modules/view-field/entities/view-field.entity';
|
||||
import { ViewFilterGroupEntity } from 'src/engine/metadata-modules/view-filter-group/entities/view-filter-group.entity';
|
||||
import { ViewFilterEntity } from 'src/engine/metadata-modules/view-filter/entities/view-filter.entity';
|
||||
import { ViewGroupEntity } from 'src/engine/metadata-modules/view-group/entities/view-group.entity';
|
||||
import { ViewSortEntity } from 'src/engine/metadata-modules/view-sort/entities/view-sort.entity';
|
||||
import { ViewCalendarLayout } from 'src/engine/metadata-modules/view/enums/view-calendar-layout.enum';
|
||||
import { ViewKey } from 'src/engine/metadata-modules/view/enums/view-key.enum';
|
||||
import { ViewOpenRecordIn } from 'src/engine/metadata-modules/view/enums/view-open-record-in';
|
||||
import { ViewType } from 'src/engine/metadata-modules/view/enums/view-type.enum';
|
||||
|
||||
// We could refactor this type to be dynamic to view type
|
||||
@Entity({ name: 'view', schema: 'core' })
|
||||
@Index('IDX_VIEW_WORKSPACE_ID_OBJECT_METADATA_ID', [
|
||||
'workspaceId',
|
||||
'objectMetadataId',
|
||||
])
|
||||
@Check(
|
||||
'CHK_VIEW_CALENDAR_INTEGRITY',
|
||||
`("type" != 'CALENDAR' OR ("calendarLayout" IS NOT NULL AND "calendarFieldMetadataId" IS NOT NULL))`,
|
||||
)
|
||||
export class ViewEntity extends SyncableEntity implements Required<ViewEntity> {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ nullable: false, type: 'text', default: '' })
|
||||
name: string;
|
||||
|
||||
@Column({ nullable: false, type: 'uuid' })
|
||||
objectMetadataId: string;
|
||||
|
||||
@ManyToOne(() => ObjectMetadataEntity, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'objectMetadataId' })
|
||||
objectMetadata: Relation<ObjectMetadataEntity>;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: Object.values(ViewType),
|
||||
nullable: false,
|
||||
default: ViewType.TABLE,
|
||||
})
|
||||
type: ViewType;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: Object.values(ViewKey),
|
||||
nullable: true,
|
||||
default: null,
|
||||
})
|
||||
key: ViewKey | null;
|
||||
|
||||
@Column({ nullable: false, type: 'text' })
|
||||
icon: string;
|
||||
|
||||
@Column({ nullable: false, type: 'double precision', default: 0 })
|
||||
position: number;
|
||||
|
||||
@Column({ nullable: false, default: false, type: 'boolean' })
|
||||
isCompact: boolean;
|
||||
|
||||
@Column({ nullable: false, default: false, type: 'boolean' })
|
||||
isCustom: boolean;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: Object.values(ViewOpenRecordIn),
|
||||
nullable: false,
|
||||
default: ViewOpenRecordIn.SIDE_PANEL,
|
||||
})
|
||||
openRecordIn: ViewOpenRecordIn;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: Object.values(AggregateOperations),
|
||||
nullable: true,
|
||||
default: null,
|
||||
})
|
||||
kanbanAggregateOperation: AggregateOperations | null;
|
||||
|
||||
@Column({ nullable: true, type: 'uuid' })
|
||||
kanbanAggregateOperationFieldMetadataId: string | null;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: Object.values(ViewCalendarLayout),
|
||||
nullable: true,
|
||||
default: null,
|
||||
})
|
||||
calendarLayout: ViewCalendarLayout | null;
|
||||
|
||||
@Column({ nullable: true, type: 'uuid' })
|
||||
calendarFieldMetadataId: string | null;
|
||||
|
||||
@Column({ nullable: false, type: 'uuid' })
|
||||
workspaceId: string;
|
||||
|
||||
@CreateDateColumn({ type: 'timestamptz' })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ type: 'timestamptz' })
|
||||
updatedAt: Date;
|
||||
|
||||
@DeleteDateColumn({ type: 'timestamptz' })
|
||||
deletedAt: Date | null;
|
||||
|
||||
@Column({ nullable: true, type: 'text', default: null })
|
||||
anyFieldFilterValue: string | null;
|
||||
|
||||
@ManyToOne(() => Workspace, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'workspaceId' })
|
||||
workspace: Relation<Workspace>;
|
||||
|
||||
@OneToMany(() => ViewFieldEntity, (viewField) => viewField.view)
|
||||
viewFields: Relation<ViewFieldEntity[]>;
|
||||
|
||||
@OneToMany(() => ViewFilterEntity, (viewFilter) => viewFilter.view)
|
||||
viewFilters: Relation<ViewFilterEntity[]>;
|
||||
|
||||
@OneToMany(() => ViewSortEntity, (viewSort) => viewSort.view)
|
||||
viewSorts: Relation<ViewSortEntity[]>;
|
||||
|
||||
@OneToMany(() => ViewGroupEntity, (viewGroup) => viewGroup.view)
|
||||
viewGroups: Relation<ViewGroupEntity[]>;
|
||||
|
||||
@OneToMany(
|
||||
() => ViewFilterGroupEntity,
|
||||
(viewFilterGroup) => viewFilterGroup.view,
|
||||
)
|
||||
viewFilterGroups: Relation<ViewFilterGroupEntity[]>;
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export enum ViewCalendarLayout {
|
||||
DAY = 'DAY',
|
||||
WEEK = 'WEEK',
|
||||
MONTH = 'MONTH',
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export enum ViewKey {
|
||||
INDEX = 'INDEX',
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export enum ViewOpenRecordIn {
|
||||
SIDE_PANEL = 'SIDE_PANEL',
|
||||
RECORD_PAGE = 'RECORD_PAGE',
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export enum ViewType {
|
||||
TABLE = 'TABLE',
|
||||
KANBAN = 'KANBAN',
|
||||
CALENDAR = 'CALENDAR',
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import {
|
||||
appendCommonExceptionCode,
|
||||
CustomException,
|
||||
} from 'src/utils/custom-exception';
|
||||
|
||||
export class FlatViewException extends CustomException<
|
||||
keyof typeof FlatViewExceptionCode
|
||||
> {}
|
||||
|
||||
export const FlatViewExceptionCode = appendCommonExceptionCode({
|
||||
VIEW_NOT_FOUND: 'VIEW_NOT_FOUND',
|
||||
VIEW_ALREADY_EXISTS: 'VIEW_ALREADY_EXISTS',
|
||||
} as const);
|
||||
@@ -0,0 +1,56 @@
|
||||
import { t } from '@lingui/core/macro';
|
||||
import { assertUnreachable } from 'twenty-shared/utils';
|
||||
|
||||
import { CustomException } from 'src/utils/custom-exception';
|
||||
|
||||
export class ViewException extends CustomException {
|
||||
declare code: ViewExceptionCode;
|
||||
constructor(
|
||||
message: string,
|
||||
code: ViewExceptionCode,
|
||||
{ userFriendlyMessage }: { userFriendlyMessage?: string } = {},
|
||||
) {
|
||||
super(message, code, { userFriendlyMessage });
|
||||
}
|
||||
}
|
||||
|
||||
export enum ViewExceptionCode {
|
||||
VIEW_NOT_FOUND = 'VIEW_NOT_FOUND',
|
||||
INVALID_VIEW_DATA = 'INVALID_VIEW_DATA',
|
||||
}
|
||||
|
||||
export enum ViewExceptionMessageKey {
|
||||
WORKSPACE_ID_REQUIRED = 'WORKSPACE_ID_REQUIRED',
|
||||
OBJECT_METADATA_ID_REQUIRED = 'OBJECT_METADATA_ID_REQUIRED',
|
||||
VIEW_NOT_FOUND = 'VIEW_NOT_FOUND',
|
||||
INVALID_VIEW_DATA = 'INVALID_VIEW_DATA',
|
||||
}
|
||||
|
||||
export const generateViewExceptionMessage = (
|
||||
key: ViewExceptionMessageKey,
|
||||
id?: string,
|
||||
) => {
|
||||
switch (key) {
|
||||
case ViewExceptionMessageKey.WORKSPACE_ID_REQUIRED:
|
||||
return 'WorkspaceId is required';
|
||||
case ViewExceptionMessageKey.OBJECT_METADATA_ID_REQUIRED:
|
||||
return 'ObjectMetadataId is required';
|
||||
case ViewExceptionMessageKey.VIEW_NOT_FOUND:
|
||||
return `View${id ? ` (id: ${id})` : ''} not found`;
|
||||
case ViewExceptionMessageKey.INVALID_VIEW_DATA:
|
||||
return `Invalid view data${id ? ` for view id: ${id}` : ''}`;
|
||||
default:
|
||||
assertUnreachable(key);
|
||||
}
|
||||
};
|
||||
|
||||
export const generateViewUserFriendlyExceptionMessage = (
|
||||
key: ViewExceptionMessageKey,
|
||||
) => {
|
||||
switch (key) {
|
||||
case ViewExceptionMessageKey.WORKSPACE_ID_REQUIRED:
|
||||
return t`WorkspaceId is required to create a view.`;
|
||||
case ViewExceptionMessageKey.OBJECT_METADATA_ID_REQUIRED:
|
||||
return t`ObjectMetadataId is required to create a view.`;
|
||||
}
|
||||
};
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import {
|
||||
type ArgumentsHost,
|
||||
Catch,
|
||||
type ExceptionFilter,
|
||||
} from '@nestjs/common';
|
||||
|
||||
import { type Response } from 'express';
|
||||
|
||||
import { HttpExceptionHandlerService } from 'src/engine/core-modules/exception-handler/http-exception-handler.service';
|
||||
import {
|
||||
ViewException,
|
||||
ViewExceptionCode,
|
||||
} from 'src/engine/metadata-modules/view/exceptions/view.exception';
|
||||
import { type CustomException } from 'src/utils/custom-exception';
|
||||
|
||||
@Catch(ViewException)
|
||||
export class ViewRestApiExceptionFilter implements ExceptionFilter {
|
||||
constructor(
|
||||
private readonly httpExceptionHandlerService: HttpExceptionHandlerService,
|
||||
) {}
|
||||
|
||||
catch(exception: ViewException, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
|
||||
switch (exception.code) {
|
||||
case ViewExceptionCode.VIEW_NOT_FOUND:
|
||||
return this.httpExceptionHandlerService.handleError(
|
||||
exception as CustomException,
|
||||
response,
|
||||
404,
|
||||
);
|
||||
case ViewExceptionCode.INVALID_VIEW_DATA:
|
||||
return this.httpExceptionHandlerService.handleError(
|
||||
exception as CustomException,
|
||||
response,
|
||||
400,
|
||||
);
|
||||
default:
|
||||
// TODO: change to 500 when we have input validation
|
||||
return this.httpExceptionHandlerService.handleError(
|
||||
exception as CustomException,
|
||||
response,
|
||||
400,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import { UseFilters, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
Args,
|
||||
Context,
|
||||
Mutation,
|
||||
Parent,
|
||||
Query,
|
||||
ResolveField,
|
||||
Resolver,
|
||||
} from '@nestjs/graphql';
|
||||
|
||||
import { isArray } from '@sniptt/guards';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { FeatureFlagKey } from 'src/engine/core-modules/feature-flag/enums/feature-flag-key.enum';
|
||||
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
|
||||
import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
|
||||
import { type I18nContext } from 'src/engine/core-modules/i18n/types/i18n-context.type';
|
||||
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { type IDataloaders } from 'src/engine/dataloaders/dataloader.interface';
|
||||
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
|
||||
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
|
||||
import { resolveObjectMetadataStandardOverride } from 'src/engine/metadata-modules/object-metadata/utils/resolve-object-metadata-standard-override.util';
|
||||
import { ViewFieldDTO } from 'src/engine/metadata-modules/view-field/dtos/view-field.dto';
|
||||
import { ViewFieldService } from 'src/engine/metadata-modules/view-field/services/view-field.service';
|
||||
import { ViewFilterGroupDTO } from 'src/engine/metadata-modules/view-filter-group/dtos/view-filter-group.dto';
|
||||
import { ViewFilterGroupService } from 'src/engine/metadata-modules/view-filter-group/services/view-filter-group.service';
|
||||
import { ViewFilterDTO } from 'src/engine/metadata-modules/view-filter/dtos/view-filter.dto';
|
||||
import { ViewFilterService } from 'src/engine/metadata-modules/view-filter/services/view-filter.service';
|
||||
import { ViewGroupDTO } from 'src/engine/metadata-modules/view-group/dtos/view-group.dto';
|
||||
import { ViewGroupService } from 'src/engine/metadata-modules/view-group/services/view-group.service';
|
||||
import { ViewSortDTO } from 'src/engine/metadata-modules/view-sort/dtos/view-sort.dto';
|
||||
import { ViewSortService } from 'src/engine/metadata-modules/view-sort/services/view-sort.service';
|
||||
import { CreateViewInput } from 'src/engine/metadata-modules/view/dtos/inputs/create-view.input';
|
||||
import { UpdateViewInput } from 'src/engine/metadata-modules/view/dtos/inputs/update-view.input';
|
||||
import { ViewDTO } from 'src/engine/metadata-modules/view/dtos/view.dto';
|
||||
import { ViewV2Service } from 'src/engine/metadata-modules/view/services/view-v2.service';
|
||||
import { ViewService } from 'src/engine/metadata-modules/view/services/view.service';
|
||||
import { ViewGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/view/utils/view-graphql-api-exception.filter';
|
||||
|
||||
@Resolver(() => ViewDTO)
|
||||
@UseFilters(ViewGraphqlApiExceptionFilter)
|
||||
@UseGuards(WorkspaceAuthGuard)
|
||||
export class ViewResolver {
|
||||
constructor(
|
||||
private readonly viewService: ViewService,
|
||||
private readonly viewFieldService: ViewFieldService,
|
||||
private readonly viewFilterService: ViewFilterService,
|
||||
private readonly viewFilterGroupService: ViewFilterGroupService,
|
||||
private readonly viewSortService: ViewSortService,
|
||||
private readonly viewGroupService: ViewGroupService,
|
||||
private readonly i18nService: I18nService,
|
||||
private readonly featureFlagService: FeatureFlagService,
|
||||
private readonly viewV2Service: ViewV2Service,
|
||||
) {}
|
||||
|
||||
@ResolveField(() => String)
|
||||
async name(
|
||||
@Parent() view: ViewDTO,
|
||||
@Context() context: { loaders: IDataloaders } & I18nContext,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
): Promise<string> {
|
||||
if (view.name.includes('{objectLabelPlural}')) {
|
||||
const objectMetadata = await context.loaders.objectMetadataLoader.load({
|
||||
objectMetadataId: view.objectMetadataId,
|
||||
workspaceId: workspace.id,
|
||||
});
|
||||
|
||||
if (objectMetadata) {
|
||||
const i18n = this.i18nService.getI18nInstance(context.req.locale);
|
||||
const translatedObjectLabel = resolveObjectMetadataStandardOverride(
|
||||
{
|
||||
labelPlural: objectMetadata.labelPlural,
|
||||
labelSingular: objectMetadata.labelSingular,
|
||||
description: objectMetadata.description ?? undefined,
|
||||
icon: objectMetadata.icon ?? undefined,
|
||||
isCustom: objectMetadata.isCustom,
|
||||
standardOverrides: objectMetadata.standardOverrides ?? undefined,
|
||||
},
|
||||
'labelPlural',
|
||||
context.req.locale,
|
||||
i18n,
|
||||
);
|
||||
|
||||
return this.viewService.processViewNameWithTemplate(
|
||||
view.name,
|
||||
view.isCustom,
|
||||
translatedObjectLabel,
|
||||
context.req.locale,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return this.viewService.processViewNameWithTemplate(
|
||||
view.name,
|
||||
view.isCustom,
|
||||
undefined,
|
||||
context.req.locale,
|
||||
);
|
||||
}
|
||||
|
||||
@Query(() => [ViewDTO])
|
||||
async getCoreViews(
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
@Args('objectMetadataId', { type: () => String, nullable: true })
|
||||
objectMetadataId?: string,
|
||||
): Promise<ViewDTO[]> {
|
||||
if (objectMetadataId) {
|
||||
return this.viewService.findByObjectMetadataId(
|
||||
workspace.id,
|
||||
objectMetadataId,
|
||||
);
|
||||
}
|
||||
|
||||
return this.viewService.findByWorkspaceId(workspace.id);
|
||||
}
|
||||
|
||||
@Query(() => ViewDTO, { nullable: true })
|
||||
async getCoreView(
|
||||
@Args('id', { type: () => String }) id: string,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
): Promise<ViewDTO | null> {
|
||||
return this.viewService.findById(id, workspace.id);
|
||||
}
|
||||
|
||||
@Mutation(() => ViewDTO)
|
||||
async createCoreView(
|
||||
@Args('input') input: CreateViewInput,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
): Promise<ViewDTO> {
|
||||
const isWorkspaceMigrationV2Enabled =
|
||||
await this.featureFlagService.isFeatureEnabled(
|
||||
FeatureFlagKey.IS_WORKSPACE_MIGRATION_V2_ENABLED,
|
||||
workspace.id,
|
||||
);
|
||||
|
||||
if (isWorkspaceMigrationV2Enabled) {
|
||||
return await this.viewV2Service.createOne({
|
||||
createViewInput: input,
|
||||
workspaceId: workspace.id,
|
||||
});
|
||||
}
|
||||
|
||||
return this.viewService.create({
|
||||
...input,
|
||||
workspaceId: workspace.id,
|
||||
});
|
||||
}
|
||||
|
||||
@Mutation(() => ViewDTO)
|
||||
async updateCoreView(
|
||||
@Args('id', { type: () => String }) id: string,
|
||||
@Args('input') input: UpdateViewInput,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
): Promise<ViewDTO> {
|
||||
const isWorkspaceMigrationV2Enabled =
|
||||
await this.featureFlagService.isFeatureEnabled(
|
||||
FeatureFlagKey.IS_WORKSPACE_MIGRATION_V2_ENABLED,
|
||||
workspace.id,
|
||||
);
|
||||
|
||||
if (isWorkspaceMigrationV2Enabled) {
|
||||
return await this.viewV2Service.updateOne({
|
||||
updateViewInput: { ...input, id },
|
||||
workspaceId: workspace.id,
|
||||
});
|
||||
}
|
||||
|
||||
return this.viewService.update(id, workspace.id, input);
|
||||
}
|
||||
|
||||
@Mutation(() => Boolean)
|
||||
async deleteCoreView(
|
||||
@Args('id', { type: () => String }) id: string,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
): Promise<boolean> {
|
||||
const isWorkspaceMigrationV2Enabled =
|
||||
await this.featureFlagService.isFeatureEnabled(
|
||||
FeatureFlagKey.IS_WORKSPACE_MIGRATION_V2_ENABLED,
|
||||
workspace.id,
|
||||
);
|
||||
|
||||
if (isWorkspaceMigrationV2Enabled) {
|
||||
const deletedView = await this.viewV2Service.deleteOne({
|
||||
deleteViewInput: { id },
|
||||
workspaceId: workspace.id,
|
||||
});
|
||||
|
||||
return isDefined(deletedView);
|
||||
}
|
||||
|
||||
const deletedView = await this.viewService.delete(id, workspace.id);
|
||||
|
||||
return isDefined(deletedView);
|
||||
}
|
||||
|
||||
@Mutation(() => Boolean)
|
||||
async destroyCoreView(
|
||||
@Args('id', { type: () => String }) id: string,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
): Promise<boolean> {
|
||||
const isWorkspaceMigrationV2Enabled =
|
||||
await this.featureFlagService.isFeatureEnabled(
|
||||
FeatureFlagKey.IS_WORKSPACE_MIGRATION_V2_ENABLED,
|
||||
workspace.id,
|
||||
);
|
||||
|
||||
if (isWorkspaceMigrationV2Enabled) {
|
||||
const deletedView = await this.viewV2Service.destroyOne({
|
||||
destroyViewInput: { id },
|
||||
workspaceId: workspace.id,
|
||||
});
|
||||
|
||||
return isDefined(deletedView);
|
||||
}
|
||||
|
||||
const deletedView = await this.viewService.destroy(id, workspace.id);
|
||||
|
||||
return isDefined(deletedView);
|
||||
}
|
||||
|
||||
@ResolveField(() => [ViewFieldDTO])
|
||||
async viewFields(
|
||||
@Parent() view: ViewDTO,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
if (isArray(view.viewFields)) {
|
||||
return view.viewFields;
|
||||
}
|
||||
|
||||
return this.viewFieldService.findByViewId(workspace.id, view.id);
|
||||
}
|
||||
|
||||
@ResolveField(() => [ViewFilterDTO])
|
||||
async viewFilters(
|
||||
@Parent() view: ViewDTO,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
if (isArray(view.viewFilters)) {
|
||||
return view.viewFilters;
|
||||
}
|
||||
|
||||
return this.viewFilterService.findByViewId(workspace.id, view.id);
|
||||
}
|
||||
|
||||
@ResolveField(() => [ViewFilterGroupDTO])
|
||||
async viewFilterGroups(
|
||||
@Parent() view: ViewDTO,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
if (isArray(view.viewFilterGroups)) {
|
||||
return view.viewFilterGroups;
|
||||
}
|
||||
|
||||
return this.viewFilterGroupService.findByViewId(workspace.id, view.id);
|
||||
}
|
||||
|
||||
@ResolveField(() => [ViewSortDTO])
|
||||
async viewSorts(
|
||||
@Parent() view: ViewDTO,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
if (isArray(view.viewSorts)) {
|
||||
return view.viewSorts;
|
||||
}
|
||||
|
||||
return this.viewSortService.findByViewId(workspace.id, view.id);
|
||||
}
|
||||
|
||||
@ResolveField(() => [ViewGroupDTO])
|
||||
async viewGroups(
|
||||
@Parent() view: ViewDTO,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
if (isArray(view.viewGroups)) {
|
||||
return view.viewGroups;
|
||||
}
|
||||
|
||||
return this.viewGroupService.findByViewId(workspace.id, view.id);
|
||||
}
|
||||
}
|
||||
+405
@@ -0,0 +1,405 @@
|
||||
import { Test, type TestingModule } from '@nestjs/testing';
|
||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||
|
||||
import { type Repository } from 'typeorm';
|
||||
|
||||
import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
|
||||
import { ViewEntity } from 'src/engine/metadata-modules/view/entities/view.entity';
|
||||
import { ViewOpenRecordIn } from 'src/engine/metadata-modules/view/enums/view-open-record-in';
|
||||
import { ViewType } from 'src/engine/metadata-modules/view/enums/view-type.enum';
|
||||
import {
|
||||
ViewException,
|
||||
ViewExceptionCode,
|
||||
ViewExceptionMessageKey,
|
||||
generateViewExceptionMessage,
|
||||
generateViewUserFriendlyExceptionMessage,
|
||||
} from 'src/engine/metadata-modules/view/exceptions/view.exception';
|
||||
import { ViewService } from 'src/engine/metadata-modules/view/services/view.service';
|
||||
import { WorkspaceCacheStorageService } from 'src/engine/workspace-cache-storage/workspace-cache-storage.service';
|
||||
|
||||
describe('ViewService', () => {
|
||||
let viewService: ViewService;
|
||||
let viewRepository: Repository<ViewEntity>;
|
||||
let i18nService: I18nService;
|
||||
|
||||
const mockView = {
|
||||
id: 'view-id',
|
||||
name: 'Test View',
|
||||
objectMetadataId: 'object-id',
|
||||
workspaceId: 'workspace-id',
|
||||
type: ViewType.TABLE,
|
||||
icon: 'test-icon',
|
||||
position: 0,
|
||||
isCompact: false,
|
||||
isCustom: true,
|
||||
key: 'INDEX',
|
||||
openRecordIn: ViewOpenRecordIn.SIDE_PANEL,
|
||||
kanbanAggregateOperation: null,
|
||||
kanbanAggregateOperationFieldMetadataId: null,
|
||||
anyFieldFilterValue: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
deletedAt: null,
|
||||
} as ViewEntity;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
ViewService,
|
||||
{
|
||||
provide: getRepositoryToken(ViewEntity),
|
||||
useValue: {
|
||||
find: jest.fn(),
|
||||
findOne: jest.fn(),
|
||||
create: jest.fn(),
|
||||
save: jest.fn(),
|
||||
softDelete: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: WorkspaceCacheStorageService,
|
||||
useValue: {
|
||||
flushGraphQLOperation: jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: I18nService,
|
||||
useValue: {
|
||||
translateMessage: jest.fn(),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
viewService = module.get<ViewService>(ViewService);
|
||||
viewRepository = module.get<Repository<ViewEntity>>(
|
||||
getRepositoryToken(ViewEntity),
|
||||
);
|
||||
i18nService = module.get<I18nService>(I18nService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(viewService).toBeDefined();
|
||||
});
|
||||
|
||||
describe('findByWorkspaceId', () => {
|
||||
it('should return views for a workspace', async () => {
|
||||
const workspaceId = 'workspace-id';
|
||||
const expectedViews = [mockView];
|
||||
|
||||
jest.spyOn(viewRepository, 'find').mockResolvedValue(expectedViews);
|
||||
|
||||
const result = await viewService.findByWorkspaceId(workspaceId);
|
||||
|
||||
expect(viewRepository.find).toHaveBeenCalledWith({
|
||||
where: {
|
||||
workspaceId,
|
||||
deletedAt: expect.anything(),
|
||||
},
|
||||
order: { position: 'ASC' },
|
||||
relations: [
|
||||
'workspace',
|
||||
'viewFields',
|
||||
'viewFilters',
|
||||
'viewSorts',
|
||||
'viewGroups',
|
||||
'viewFilterGroups',
|
||||
],
|
||||
});
|
||||
expect(result).toEqual(expectedViews);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByObjectMetadataId', () => {
|
||||
it('should return views for an object metadata id', async () => {
|
||||
const workspaceId = 'workspace-id';
|
||||
const objectMetadataId = 'object-id';
|
||||
const expectedViews = [mockView];
|
||||
|
||||
jest.spyOn(viewRepository, 'find').mockResolvedValue(expectedViews);
|
||||
|
||||
const result = await viewService.findByObjectMetadataId(
|
||||
workspaceId,
|
||||
objectMetadataId,
|
||||
);
|
||||
|
||||
expect(viewRepository.find).toHaveBeenCalledWith({
|
||||
where: {
|
||||
workspaceId,
|
||||
objectMetadataId,
|
||||
deletedAt: expect.anything(),
|
||||
},
|
||||
order: { position: 'ASC' },
|
||||
relations: [
|
||||
'workspace',
|
||||
'viewFields',
|
||||
'viewFilters',
|
||||
'viewSorts',
|
||||
'viewGroups',
|
||||
'viewFilterGroups',
|
||||
],
|
||||
});
|
||||
expect(result).toEqual(expectedViews);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('should return a view by id', async () => {
|
||||
const id = 'view-id';
|
||||
const workspaceId = 'workspace-id';
|
||||
|
||||
jest.spyOn(viewRepository, 'findOne').mockResolvedValue(mockView);
|
||||
|
||||
const result = await viewService.findById(id, workspaceId);
|
||||
|
||||
expect(viewRepository.findOne).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id,
|
||||
workspaceId,
|
||||
deletedAt: expect.anything(),
|
||||
},
|
||||
relations: [
|
||||
'workspace',
|
||||
'viewFields',
|
||||
'viewFilters',
|
||||
'viewSorts',
|
||||
'viewGroups',
|
||||
'viewFilterGroups',
|
||||
],
|
||||
});
|
||||
expect(result).toEqual(mockView);
|
||||
});
|
||||
|
||||
it('should return null when view is not found', async () => {
|
||||
const id = 'non-existent-id';
|
||||
const workspaceId = 'workspace-id';
|
||||
|
||||
jest.spyOn(viewRepository, 'findOne').mockResolvedValue(null);
|
||||
|
||||
const result = await viewService.findById(id, workspaceId);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
const validViewData = {
|
||||
name: 'Test View',
|
||||
workspaceId: 'workspace-id',
|
||||
objectMetadataId: 'object-id',
|
||||
type: ViewType.TABLE,
|
||||
icon: 'test-icon',
|
||||
};
|
||||
|
||||
it('should create a view successfully', async () => {
|
||||
jest.spyOn(viewRepository, 'create').mockReturnValue(mockView);
|
||||
jest.spyOn(viewRepository, 'save').mockResolvedValue(mockView);
|
||||
|
||||
const result = await viewService.create(validViewData);
|
||||
|
||||
expect(viewRepository.create).toHaveBeenCalledWith({
|
||||
...validViewData,
|
||||
isCustom: true,
|
||||
});
|
||||
expect(viewRepository.save).toHaveBeenCalledWith(mockView);
|
||||
expect(result).toEqual(mockView);
|
||||
});
|
||||
|
||||
it('should throw exception when workspaceId is missing', async () => {
|
||||
const invalidData = { ...validViewData, workspaceId: undefined };
|
||||
|
||||
await expect(viewService.create(invalidData)).rejects.toThrow(
|
||||
new ViewException(
|
||||
generateViewExceptionMessage(
|
||||
ViewExceptionMessageKey.WORKSPACE_ID_REQUIRED,
|
||||
),
|
||||
ViewExceptionCode.INVALID_VIEW_DATA,
|
||||
{
|
||||
userFriendlyMessage: generateViewUserFriendlyExceptionMessage(
|
||||
ViewExceptionMessageKey.WORKSPACE_ID_REQUIRED,
|
||||
),
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw exception when objectMetadataId is missing', async () => {
|
||||
const invalidData = { ...validViewData, objectMetadataId: undefined };
|
||||
|
||||
await expect(viewService.create(invalidData)).rejects.toThrow(
|
||||
new ViewException(
|
||||
generateViewExceptionMessage(
|
||||
ViewExceptionMessageKey.OBJECT_METADATA_ID_REQUIRED,
|
||||
),
|
||||
ViewExceptionCode.INVALID_VIEW_DATA,
|
||||
{
|
||||
userFriendlyMessage: generateViewUserFriendlyExceptionMessage(
|
||||
ViewExceptionMessageKey.OBJECT_METADATA_ID_REQUIRED,
|
||||
),
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('should update a view successfully', async () => {
|
||||
const id = 'view-id';
|
||||
const workspaceId = 'workspace-id';
|
||||
const updateData = { name: 'Updated View' };
|
||||
const updatedView = { ...mockView, ...updateData };
|
||||
|
||||
jest.spyOn(viewService, 'findById').mockResolvedValue(mockView);
|
||||
jest.spyOn(viewRepository, 'save').mockResolvedValue(updatedView);
|
||||
|
||||
const result = await viewService.update(id, workspaceId, updateData);
|
||||
|
||||
expect(viewService.findById).toHaveBeenCalledWith(id, workspaceId);
|
||||
expect(viewRepository.save).toHaveBeenCalledWith({
|
||||
id,
|
||||
...updateData,
|
||||
});
|
||||
expect(result).toEqual({ ...mockView, ...updatedView });
|
||||
});
|
||||
|
||||
it('should throw exception when view is not found', async () => {
|
||||
const id = 'non-existent-id';
|
||||
const workspaceId = 'workspace-id';
|
||||
const updateData = { name: 'Updated View' };
|
||||
|
||||
jest.spyOn(viewService, 'findById').mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
viewService.update(id, workspaceId, updateData),
|
||||
).rejects.toThrow(
|
||||
new ViewException(
|
||||
generateViewExceptionMessage(
|
||||
ViewExceptionMessageKey.VIEW_NOT_FOUND,
|
||||
id,
|
||||
),
|
||||
ViewExceptionCode.VIEW_NOT_FOUND,
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('should delete a view successfully', async () => {
|
||||
const id = 'view-id';
|
||||
const workspaceId = 'workspace-id';
|
||||
|
||||
jest.spyOn(viewService, 'findById').mockResolvedValue(mockView);
|
||||
jest.spyOn(viewRepository, 'softDelete').mockResolvedValue({} as any);
|
||||
|
||||
const result = await viewService.delete(id, workspaceId);
|
||||
|
||||
expect(viewService.findById).toHaveBeenCalledWith(id, workspaceId);
|
||||
expect(viewRepository.softDelete).toHaveBeenCalledWith(id);
|
||||
expect(result).toEqual(mockView);
|
||||
});
|
||||
|
||||
it('should throw exception when view is not found', async () => {
|
||||
const id = 'non-existent-id';
|
||||
const workspaceId = 'workspace-id';
|
||||
|
||||
jest.spyOn(viewService, 'findById').mockResolvedValue(null);
|
||||
|
||||
await expect(viewService.delete(id, workspaceId)).rejects.toThrow(
|
||||
new ViewException(
|
||||
generateViewExceptionMessage(
|
||||
ViewExceptionMessageKey.VIEW_NOT_FOUND,
|
||||
id,
|
||||
),
|
||||
ViewExceptionCode.VIEW_NOT_FOUND,
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('destroy', () => {
|
||||
it('should destroy a view successfully', async () => {
|
||||
const id = 'view-id';
|
||||
const workspaceId = 'workspace-id';
|
||||
|
||||
jest.spyOn(viewService, 'findById').mockResolvedValue(mockView);
|
||||
jest.spyOn(viewRepository, 'delete').mockResolvedValue({} as any);
|
||||
|
||||
const result = await viewService.destroy(id, workspaceId);
|
||||
|
||||
expect(viewService.findById).toHaveBeenCalledWith(id, workspaceId);
|
||||
expect(viewRepository.delete).toHaveBeenCalledWith(id);
|
||||
expect(result).toEqual(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('processViewNameWithTemplate', () => {
|
||||
it('should replace template with objectLabelPlural', () => {
|
||||
const viewName = 'All {objectLabelPlural}';
|
||||
const objectLabelPlural = 'Companies';
|
||||
|
||||
jest.spyOn(i18nService, 'translateMessage').mockImplementation((args) => {
|
||||
return args.messageId;
|
||||
});
|
||||
|
||||
const result = viewService.processViewNameWithTemplate(
|
||||
viewName,
|
||||
false,
|
||||
objectLabelPlural,
|
||||
'en',
|
||||
);
|
||||
|
||||
expect(result).toBe('All Companies');
|
||||
});
|
||||
|
||||
it('should return translated value when translation exists', () => {
|
||||
const viewName = 'All {objectLabelPlural}';
|
||||
const objectLabelPlural = 'Companies';
|
||||
const translatedTemplate = 'Toutes les Companies';
|
||||
|
||||
jest
|
||||
.spyOn(i18nService, 'translateMessage')
|
||||
.mockReturnValue(translatedTemplate);
|
||||
|
||||
const result = viewService.processViewNameWithTemplate(
|
||||
viewName,
|
||||
false,
|
||||
objectLabelPlural,
|
||||
'fr-FR',
|
||||
);
|
||||
|
||||
expect(result).toBe(translatedTemplate);
|
||||
});
|
||||
|
||||
it('should not translate custom views', () => {
|
||||
const viewName = 'My Custom View';
|
||||
|
||||
const result = viewService.processViewNameWithTemplate(
|
||||
viewName,
|
||||
true,
|
||||
undefined,
|
||||
'en',
|
||||
);
|
||||
|
||||
expect(i18nService.translateMessage).not.toHaveBeenCalled();
|
||||
expect(result).toBe(viewName);
|
||||
});
|
||||
|
||||
it('should return original name when no objectLabelPlural provided for template', () => {
|
||||
const viewName = 'All {objectLabelPlural}';
|
||||
|
||||
jest.spyOn(i18nService, 'translateMessage').mockImplementation((args) => {
|
||||
return args.messageId;
|
||||
});
|
||||
|
||||
const result = viewService.processViewNameWithTemplate(
|
||||
viewName,
|
||||
false,
|
||||
undefined,
|
||||
'en',
|
||||
);
|
||||
|
||||
expect(result).toBe(viewName);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,286 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/core-modules/common/services/workspace-many-or-all-flat-entity-maps-cache.service';
|
||||
import { addFlatEntityToFlatEntityMapsOrThrow } from 'src/engine/core-modules/common/utils/add-flat-entity-to-flat-entity-maps-or-throw.util';
|
||||
import { deleteFlatEntityFromFlatEntityMapsOrThrow } from 'src/engine/core-modules/common/utils/delete-flat-entity-from-flat-entity-maps-or-throw.util';
|
||||
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/core-modules/common/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
|
||||
import { getSubFlatEntityMapsOrThrow } from 'src/engine/core-modules/common/utils/get-sub-flat-entity-maps-or-throw.util';
|
||||
import { replaceFlatEntityInFlatEntityMapsOrThrow } from 'src/engine/core-modules/common/utils/replace-flat-entity-in-flat-entity-maps-or-throw.util';
|
||||
import { fromCreateViewInputToFlatViewToCreate } from 'src/engine/metadata-modules/flat-view/utils/from-create-view-input-to-flat-view-to-create.util';
|
||||
import { fromDeleteViewInputToFlatViewOrThrow } from 'src/engine/metadata-modules/flat-view/utils/from-delete-view-input-to-flat-view-or-throw.util';
|
||||
import { fromDestroyViewInputToFlatViewOrThrow } from 'src/engine/metadata-modules/flat-view/utils/from-destroy-view-input-to-flat-view-or-throw.util';
|
||||
import { fromUpdateViewInputToFlatViewToUpdateOrThrow } from 'src/engine/metadata-modules/flat-view/utils/from-update-view-input-to-flat-view-to-update-or-throw.util';
|
||||
import { CreateViewInput } from 'src/engine/metadata-modules/view/dtos/inputs/create-view.input';
|
||||
import { DeleteViewInput } from 'src/engine/metadata-modules/view/dtos/inputs/delete-view.input';
|
||||
import { DestroyViewInput } from 'src/engine/metadata-modules/view/dtos/inputs/destroy-view.input';
|
||||
import { UpdateViewInput } from 'src/engine/metadata-modules/view/dtos/inputs/update-view.input';
|
||||
import { ViewDTO } from 'src/engine/metadata-modules/view/dtos/view.dto';
|
||||
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 ViewV2Service {
|
||||
constructor(
|
||||
private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
|
||||
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
|
||||
) {}
|
||||
|
||||
async createOne({
|
||||
createViewInput,
|
||||
workspaceId,
|
||||
}: {
|
||||
createViewInput: CreateViewInput;
|
||||
workspaceId: string;
|
||||
}): Promise<ViewDTO> {
|
||||
const { flatObjectMetadataMaps, flatViewMaps: existingFlatViewMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatObjectMetadataMaps', 'flatViewMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatViewFromCreateInput = fromCreateViewInputToFlatViewToCreate({
|
||||
createViewInput,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
const toFlatViewMaps = addFlatEntityToFlatEntityMapsOrThrow({
|
||||
flatEntity: flatViewFromCreateInput,
|
||||
flatEntityMaps: existingFlatViewMaps,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
fromToAllFlatEntityMaps: {
|
||||
flatViewMaps: {
|
||||
from: existingFlatViewMaps,
|
||||
to: toFlatViewMaps,
|
||||
},
|
||||
},
|
||||
dependencyAllFlatEntityMaps: {
|
||||
flatObjectMetadataMaps: flatObjectMetadataMaps,
|
||||
},
|
||||
buildOptions: {
|
||||
isSystemBuild: false,
|
||||
inferDeletionFromMissingEntities: false,
|
||||
},
|
||||
workspaceId,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderExceptionV2(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while creating view',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatViewMaps: recomputedExistingFlatViewMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatViewMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: flatViewFromCreateInput.id,
|
||||
flatEntityMaps: recomputedExistingFlatViewMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async updateOne({
|
||||
updateViewInput,
|
||||
workspaceId,
|
||||
}: {
|
||||
updateViewInput: UpdateViewInput;
|
||||
workspaceId: string;
|
||||
}): Promise<ViewDTO> {
|
||||
const { flatViewMaps: existingFlatViewMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatViewMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatViewFromUpdateInput =
|
||||
fromUpdateViewInputToFlatViewToUpdateOrThrow({
|
||||
updateViewInput,
|
||||
flatViewMaps: existingFlatViewMaps,
|
||||
});
|
||||
|
||||
const fromFlatViewMaps = getSubFlatEntityMapsOrThrow({
|
||||
flatEntityIds: [flatViewFromUpdateInput.id],
|
||||
flatEntityMaps: existingFlatViewMaps,
|
||||
});
|
||||
const toFlatViewMaps = replaceFlatEntityInFlatEntityMapsOrThrow({
|
||||
flatEntity: flatViewFromUpdateInput,
|
||||
flatEntityMaps: fromFlatViewMaps,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
fromToAllFlatEntityMaps: {
|
||||
flatViewMaps: {
|
||||
from: fromFlatViewMaps,
|
||||
to: toFlatViewMaps,
|
||||
},
|
||||
},
|
||||
buildOptions: {
|
||||
isSystemBuild: false,
|
||||
inferDeletionFromMissingEntities: false,
|
||||
},
|
||||
workspaceId,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderExceptionV2(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while updating view',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatViewMaps: recomputedExistingFlatViewMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatViewMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: updateViewInput.id,
|
||||
flatEntityMaps: recomputedExistingFlatViewMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteOne({
|
||||
deleteViewInput,
|
||||
workspaceId,
|
||||
}: {
|
||||
deleteViewInput: DeleteViewInput;
|
||||
workspaceId: string;
|
||||
}): Promise<ViewDTO> {
|
||||
const { flatViewMaps: existingFlatViewMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatViewMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatViewFromDeleteInput = fromDeleteViewInputToFlatViewOrThrow({
|
||||
deleteViewInput,
|
||||
flatViewMaps: existingFlatViewMaps,
|
||||
});
|
||||
|
||||
const fromFlatViewMaps = getSubFlatEntityMapsOrThrow({
|
||||
flatEntityIds: [flatViewFromDeleteInput.id],
|
||||
flatEntityMaps: existingFlatViewMaps,
|
||||
});
|
||||
const toFlatViewMaps = replaceFlatEntityInFlatEntityMapsOrThrow({
|
||||
flatEntity: flatViewFromDeleteInput,
|
||||
flatEntityMaps: fromFlatViewMaps,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
fromToAllFlatEntityMaps: {
|
||||
flatViewMaps: {
|
||||
from: fromFlatViewMaps,
|
||||
to: toFlatViewMaps,
|
||||
},
|
||||
},
|
||||
buildOptions: {
|
||||
isSystemBuild: false,
|
||||
inferDeletionFromMissingEntities: true,
|
||||
},
|
||||
workspaceId,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderExceptionV2(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while deleting view',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatViewMaps: recomputedExistingFlatViewMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatViewMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: deleteViewInput.id,
|
||||
flatEntityMaps: recomputedExistingFlatViewMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async destroyOne({
|
||||
destroyViewInput,
|
||||
workspaceId,
|
||||
}: {
|
||||
destroyViewInput: DestroyViewInput;
|
||||
workspaceId: string;
|
||||
}): Promise<ViewDTO> {
|
||||
const { flatViewMaps: existingFlatViewMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatViewMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatViewFromDestroyInput = fromDestroyViewInputToFlatViewOrThrow({
|
||||
destroyViewInput,
|
||||
flatViewMaps: existingFlatViewMaps,
|
||||
});
|
||||
|
||||
const fromFlatViewMaps = getSubFlatEntityMapsOrThrow({
|
||||
flatEntityIds: [flatViewFromDestroyInput.id],
|
||||
flatEntityMaps: existingFlatViewMaps,
|
||||
});
|
||||
const toFlatViewMaps = deleteFlatEntityFromFlatEntityMapsOrThrow({
|
||||
flatEntityMaps: fromFlatViewMaps,
|
||||
entityToDeleteId: flatViewFromDestroyInput.id,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
fromToAllFlatEntityMaps: {
|
||||
flatViewMaps: {
|
||||
from: fromFlatViewMaps,
|
||||
to: toFlatViewMaps,
|
||||
},
|
||||
},
|
||||
buildOptions: {
|
||||
isSystemBuild: false,
|
||||
inferDeletionFromMissingEntities: true,
|
||||
},
|
||||
workspaceId,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderExceptionV2(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while destroying view',
|
||||
);
|
||||
}
|
||||
|
||||
return flatViewFromDestroyInput;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { type APP_LOCALES, SOURCE_LOCALE } from 'twenty-shared/translations';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { IsNull, Repository } from 'typeorm';
|
||||
|
||||
import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
|
||||
import { generateMessageId } from 'src/engine/core-modules/i18n/utils/generateMessageId';
|
||||
import { FIND_ALL_CORE_VIEWS_GRAPHQL_OPERATION } from 'src/engine/metadata-modules/view/constants/find-all-core-views-graphql-operation.constant';
|
||||
import { ViewEntity } from 'src/engine/metadata-modules/view/entities/view.entity';
|
||||
import {
|
||||
ViewException,
|
||||
ViewExceptionCode,
|
||||
ViewExceptionMessageKey,
|
||||
generateViewExceptionMessage,
|
||||
generateViewUserFriendlyExceptionMessage,
|
||||
} from 'src/engine/metadata-modules/view/exceptions/view.exception';
|
||||
import { WorkspaceCacheStorageService } from 'src/engine/workspace-cache-storage/workspace-cache-storage.service';
|
||||
|
||||
@Injectable()
|
||||
export class ViewService {
|
||||
constructor(
|
||||
@InjectRepository(ViewEntity)
|
||||
private readonly viewRepository: Repository<ViewEntity>,
|
||||
private readonly i18nService: I18nService,
|
||||
private readonly workspaceCacheStorageService: WorkspaceCacheStorageService,
|
||||
) {}
|
||||
|
||||
async findByWorkspaceId(workspaceId: string): Promise<ViewEntity[]> {
|
||||
return this.viewRepository.find({
|
||||
where: {
|
||||
workspaceId,
|
||||
deletedAt: IsNull(),
|
||||
},
|
||||
order: { position: 'ASC' },
|
||||
relations: [
|
||||
'workspace',
|
||||
'viewFields',
|
||||
'viewFilters',
|
||||
'viewSorts',
|
||||
'viewGroups',
|
||||
'viewFilterGroups',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
async findByObjectMetadataId(
|
||||
workspaceId: string,
|
||||
objectMetadataId: string,
|
||||
): Promise<ViewEntity[]> {
|
||||
return this.viewRepository.find({
|
||||
where: {
|
||||
workspaceId,
|
||||
objectMetadataId,
|
||||
deletedAt: IsNull(),
|
||||
},
|
||||
order: { position: 'ASC' },
|
||||
relations: [
|
||||
'workspace',
|
||||
'viewFields',
|
||||
'viewFilters',
|
||||
'viewSorts',
|
||||
'viewGroups',
|
||||
'viewFilterGroups',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id: string, workspaceId: string): Promise<ViewEntity | null> {
|
||||
const view = await this.viewRepository.findOne({
|
||||
where: {
|
||||
id,
|
||||
workspaceId,
|
||||
deletedAt: IsNull(),
|
||||
},
|
||||
relations: [
|
||||
'workspace',
|
||||
'viewFields',
|
||||
'viewFilters',
|
||||
'viewSorts',
|
||||
'viewGroups',
|
||||
'viewFilterGroups',
|
||||
],
|
||||
});
|
||||
|
||||
return view || null;
|
||||
}
|
||||
|
||||
async create(viewData: Partial<ViewEntity>): Promise<ViewEntity> {
|
||||
if (!isDefined(viewData.workspaceId)) {
|
||||
throw new ViewException(
|
||||
generateViewExceptionMessage(
|
||||
ViewExceptionMessageKey.WORKSPACE_ID_REQUIRED,
|
||||
),
|
||||
ViewExceptionCode.INVALID_VIEW_DATA,
|
||||
{
|
||||
userFriendlyMessage: generateViewUserFriendlyExceptionMessage(
|
||||
ViewExceptionMessageKey.WORKSPACE_ID_REQUIRED,
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (!isDefined(viewData.objectMetadataId)) {
|
||||
throw new ViewException(
|
||||
generateViewExceptionMessage(
|
||||
ViewExceptionMessageKey.OBJECT_METADATA_ID_REQUIRED,
|
||||
),
|
||||
ViewExceptionCode.INVALID_VIEW_DATA,
|
||||
{
|
||||
userFriendlyMessage: generateViewUserFriendlyExceptionMessage(
|
||||
ViewExceptionMessageKey.OBJECT_METADATA_ID_REQUIRED,
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const view = this.viewRepository.create({
|
||||
...viewData,
|
||||
isCustom: true,
|
||||
});
|
||||
|
||||
const savedView = await this.viewRepository.save(view);
|
||||
|
||||
await this.flushGraphQLCache(viewData.workspaceId);
|
||||
|
||||
return savedView;
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
workspaceId: string,
|
||||
updateData: Partial<ViewEntity>,
|
||||
): Promise<ViewEntity> {
|
||||
const existingView = await this.findById(id, workspaceId);
|
||||
|
||||
if (!isDefined(existingView)) {
|
||||
throw new ViewException(
|
||||
generateViewExceptionMessage(
|
||||
ViewExceptionMessageKey.VIEW_NOT_FOUND,
|
||||
id,
|
||||
),
|
||||
ViewExceptionCode.VIEW_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
const updatedView = await this.viewRepository.save({
|
||||
id,
|
||||
...updateData,
|
||||
});
|
||||
|
||||
await this.flushGraphQLCache(workspaceId);
|
||||
|
||||
return { ...existingView, ...updatedView };
|
||||
}
|
||||
|
||||
async delete(id: string, workspaceId: string): Promise<ViewEntity> {
|
||||
const view = await this.findById(id, workspaceId);
|
||||
|
||||
if (!isDefined(view)) {
|
||||
throw new ViewException(
|
||||
generateViewExceptionMessage(
|
||||
ViewExceptionMessageKey.VIEW_NOT_FOUND,
|
||||
id,
|
||||
),
|
||||
ViewExceptionCode.VIEW_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
await this.viewRepository.softDelete(id);
|
||||
|
||||
await this.flushGraphQLCache(workspaceId);
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
async destroy(id: string, workspaceId: string): Promise<boolean> {
|
||||
const view = await this.findById(id, workspaceId);
|
||||
|
||||
if (!isDefined(view)) {
|
||||
throw new ViewException(
|
||||
generateViewExceptionMessage(
|
||||
ViewExceptionMessageKey.VIEW_NOT_FOUND,
|
||||
id,
|
||||
),
|
||||
ViewExceptionCode.VIEW_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
await this.viewRepository.delete(id);
|
||||
await this.flushGraphQLCache(workspaceId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
processViewNameWithTemplate(
|
||||
viewName: string,
|
||||
isCustom: boolean,
|
||||
objectLabelPlural?: string,
|
||||
locale?: keyof typeof APP_LOCALES,
|
||||
): string {
|
||||
if (viewName.includes('{objectLabelPlural}') && objectLabelPlural) {
|
||||
const messageId = generateMessageId(viewName);
|
||||
const translatedTemplate = this.i18nService.translateMessage({
|
||||
messageId,
|
||||
values: {
|
||||
objectLabelPlural,
|
||||
},
|
||||
locale: locale ?? SOURCE_LOCALE,
|
||||
});
|
||||
|
||||
if (translatedTemplate !== messageId) {
|
||||
return translatedTemplate;
|
||||
}
|
||||
|
||||
return viewName.replace('{objectLabelPlural}', objectLabelPlural);
|
||||
}
|
||||
|
||||
if (!isCustom) {
|
||||
const messageId = generateMessageId(viewName);
|
||||
const translatedMessage = this.i18nService.translateMessage({
|
||||
messageId,
|
||||
locale: locale ?? SOURCE_LOCALE,
|
||||
});
|
||||
|
||||
if (translatedMessage !== messageId) {
|
||||
return translatedMessage;
|
||||
}
|
||||
}
|
||||
|
||||
return viewName;
|
||||
}
|
||||
|
||||
async flushGraphQLCache(workspaceId: string): Promise<void> {
|
||||
await this.workspaceCacheStorageService.flushGraphQLOperation({
|
||||
operationName: FIND_ALL_CORE_VIEWS_GRAPHQL_OPERATION,
|
||||
workspaceId,
|
||||
});
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
import { assertUnreachable } from 'twenty-shared/utils';
|
||||
|
||||
import {
|
||||
NotFoundError,
|
||||
UserInputError,
|
||||
} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
|
||||
import {
|
||||
ViewFieldException,
|
||||
ViewFieldExceptionCode,
|
||||
} from 'src/engine/metadata-modules/view-field/exceptions/view-field.exception';
|
||||
import {
|
||||
ViewFilterGroupException,
|
||||
ViewFilterGroupExceptionCode,
|
||||
} from 'src/engine/metadata-modules/view-filter-group/exceptions/view-filter-group.exception';
|
||||
import {
|
||||
ViewFilterException,
|
||||
ViewFilterExceptionCode,
|
||||
} from 'src/engine/metadata-modules/view-filter/exceptions/view-filter.exception';
|
||||
import {
|
||||
ViewGroupException,
|
||||
ViewGroupExceptionCode,
|
||||
} from 'src/engine/metadata-modules/view-group/exceptions/view-group.exception';
|
||||
import {
|
||||
ViewSortException,
|
||||
ViewSortExceptionCode,
|
||||
} from 'src/engine/metadata-modules/view-sort/exceptions/view-sort.exception';
|
||||
import {
|
||||
ViewException,
|
||||
ViewExceptionCode,
|
||||
} from 'src/engine/metadata-modules/view/exceptions/view.exception';
|
||||
import { WorkspaceMigrationBuilderExceptionV2 } from 'src/engine/workspace-manager/workspace-migration-v2/exceptions/workspace-migration-builder-exception-v2';
|
||||
import { workspaceMigrationBuilderExceptionV2Formatter } from 'src/engine/workspace-manager/workspace-migration-v2/interceptors/workspace-migration-builder-exception-v2-formatter';
|
||||
|
||||
export const viewGraphqlApiExceptionHandler = (error: Error) => {
|
||||
if (error instanceof WorkspaceMigrationBuilderExceptionV2) {
|
||||
return workspaceMigrationBuilderExceptionV2Formatter(error);
|
||||
}
|
||||
|
||||
if (error instanceof ViewException) {
|
||||
switch (error.code) {
|
||||
case ViewExceptionCode.VIEW_NOT_FOUND:
|
||||
throw new NotFoundError(error.message);
|
||||
case ViewExceptionCode.INVALID_VIEW_DATA:
|
||||
throw new UserInputError(error.message, {
|
||||
userFriendlyMessage: error.userFriendlyMessage,
|
||||
});
|
||||
default: {
|
||||
return assertUnreachable(error.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof ViewFieldException) {
|
||||
switch (error.code) {
|
||||
case ViewFieldExceptionCode.VIEW_FIELD_NOT_FOUND:
|
||||
throw new NotFoundError(error.message);
|
||||
case ViewFieldExceptionCode.INVALID_VIEW_FIELD_DATA:
|
||||
throw new UserInputError(error.message, {
|
||||
userFriendlyMessage: error.userFriendlyMessage,
|
||||
});
|
||||
default: {
|
||||
return assertUnreachable(error.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof ViewFilterException) {
|
||||
switch (error.code) {
|
||||
case ViewFilterExceptionCode.VIEW_FILTER_NOT_FOUND:
|
||||
throw new NotFoundError(error.message);
|
||||
case ViewFilterExceptionCode.INVALID_VIEW_FILTER_DATA:
|
||||
throw new UserInputError(error.message, {
|
||||
userFriendlyMessage: error.userFriendlyMessage,
|
||||
});
|
||||
default: {
|
||||
return assertUnreachable(error.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof ViewFilterGroupException) {
|
||||
switch (error.code) {
|
||||
case ViewFilterGroupExceptionCode.VIEW_FILTER_GROUP_NOT_FOUND:
|
||||
throw new NotFoundError(error.message);
|
||||
case ViewFilterGroupExceptionCode.INVALID_VIEW_FILTER_GROUP_DATA:
|
||||
throw new UserInputError(error.message, {
|
||||
userFriendlyMessage: error.userFriendlyMessage,
|
||||
});
|
||||
default: {
|
||||
return assertUnreachable(error.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof ViewGroupException) {
|
||||
switch (error.code) {
|
||||
case ViewGroupExceptionCode.VIEW_GROUP_NOT_FOUND:
|
||||
throw new NotFoundError(error.message);
|
||||
case ViewGroupExceptionCode.INVALID_VIEW_GROUP_DATA:
|
||||
throw new UserInputError(error.message, {
|
||||
userFriendlyMessage: error.userFriendlyMessage,
|
||||
});
|
||||
default: {
|
||||
return assertUnreachable(error.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof ViewSortException) {
|
||||
switch (error.code) {
|
||||
case ViewSortExceptionCode.VIEW_SORT_NOT_FOUND:
|
||||
throw new NotFoundError(error.message);
|
||||
case ViewSortExceptionCode.INVALID_VIEW_SORT_DATA:
|
||||
throw new UserInputError(error.message, {
|
||||
userFriendlyMessage: error.userFriendlyMessage,
|
||||
});
|
||||
default: {
|
||||
return assertUnreachable(error.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
};
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { Catch, type ExceptionFilter } from '@nestjs/common';
|
||||
|
||||
import { ViewFieldException } from 'src/engine/metadata-modules/view-field/exceptions/view-field.exception';
|
||||
import { ViewFilterGroupException } from 'src/engine/metadata-modules/view-filter-group/exceptions/view-filter-group.exception';
|
||||
import { ViewFilterException } from 'src/engine/metadata-modules/view-filter/exceptions/view-filter.exception';
|
||||
import { ViewGroupException } from 'src/engine/metadata-modules/view-group/exceptions/view-group.exception';
|
||||
import { ViewSortException } from 'src/engine/metadata-modules/view-sort/exceptions/view-sort.exception';
|
||||
import { ViewException } from 'src/engine/metadata-modules/view/exceptions/view.exception';
|
||||
import { viewGraphqlApiExceptionHandler } from 'src/engine/metadata-modules/view/utils/view-graphql-api-exception-handler.util';
|
||||
import { WorkspaceMigrationBuilderExceptionV2 } from 'src/engine/workspace-manager/workspace-migration-v2/exceptions/workspace-migration-builder-exception-v2';
|
||||
|
||||
@Catch(
|
||||
ViewException,
|
||||
ViewFieldException,
|
||||
ViewFilterException,
|
||||
ViewFilterGroupException,
|
||||
ViewGroupException,
|
||||
ViewSortException,
|
||||
WorkspaceMigrationBuilderExceptionV2,
|
||||
)
|
||||
export class ViewGraphqlApiExceptionFilter implements ExceptionFilter {
|
||||
catch(
|
||||
exception:
|
||||
| ViewException
|
||||
| ViewFieldException
|
||||
| ViewFilterException
|
||||
| ViewFilterGroupException
|
||||
| ViewGroupException
|
||||
| ViewSortException
|
||||
| WorkspaceMigrationBuilderExceptionV2,
|
||||
) {
|
||||
return viewGraphqlApiExceptionHandler(exception);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/core-modules/common/services/workspace-many-or-all-flat-entity-maps-cache.module';
|
||||
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
|
||||
import { I18nModule } from 'src/engine/core-modules/i18n/i18n.module';
|
||||
import { FlatViewModule } from 'src/engine/metadata-modules/flat-view/flat-view.module';
|
||||
import { ViewFieldModule } from 'src/engine/metadata-modules/view-field/view-field.module';
|
||||
import { ViewFilterGroupModule } from 'src/engine/metadata-modules/view-filter-group/view-filter-group.module';
|
||||
import { ViewFilterModule } from 'src/engine/metadata-modules/view-filter/view-filter.module';
|
||||
import { ViewGroupModule } from 'src/engine/metadata-modules/view-group/view-group.module';
|
||||
import { ViewSortModule } from 'src/engine/metadata-modules/view-sort/view-sort.module';
|
||||
import { ViewController } from 'src/engine/metadata-modules/view/controllers/view.controller';
|
||||
import { ViewEntity } from 'src/engine/metadata-modules/view/entities/view.entity';
|
||||
import { ViewResolver } from 'src/engine/metadata-modules/view/resolvers/view.resolver';
|
||||
import { ViewV2Service } from 'src/engine/metadata-modules/view/services/view-v2.service';
|
||||
import { ViewService } from 'src/engine/metadata-modules/view/services/view.service';
|
||||
import { WorkspaceMetadataCacheModule } from 'src/engine/metadata-modules/workspace-metadata-cache/workspace-metadata-cache.module';
|
||||
import { WorkspaceCacheStorageModule } from 'src/engine/workspace-cache-storage/workspace-cache-storage.module';
|
||||
import { WorkspaceMigrationV2Module } from 'src/engine/workspace-manager/workspace-migration-v2/workspace-migration-v2.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([ViewEntity]),
|
||||
ViewFieldModule,
|
||||
ViewFilterModule,
|
||||
ViewFilterGroupModule,
|
||||
ViewGroupModule,
|
||||
ViewSortModule,
|
||||
I18nModule,
|
||||
FeatureFlagModule,
|
||||
WorkspaceMetadataCacheModule,
|
||||
WorkspaceCacheStorageModule,
|
||||
WorkspaceMigrationV2Module,
|
||||
FlatViewModule,
|
||||
WorkspaceManyOrAllFlatEntityMapsCacheModule,
|
||||
],
|
||||
controllers: [ViewController],
|
||||
providers: [ViewService, ViewResolver, ViewV2Service],
|
||||
exports: [ViewService, ViewV2Service, TypeOrmModule.forFeature([ViewEntity])],
|
||||
})
|
||||
export class ViewModule {}
|
||||
Reference in New Issue
Block a user