Skip to content

The open alternative to Salesforce, designed for AI.

Create PageLayoutWidget resolver and controller (#14315)

Raphaël Bosi9445256eee0e
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 65096cd334f..a680ae48dcf 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -715,6 +715,15 @@ export type CreatePageLayoutTabInput = {
title: Scalars['String'];
};
+export type CreatePageLayoutWidgetInput = {
+ configuration?: InputMaybe<Scalars['JSON']>;
+ gridPosition: GridPositionInput;
+ objectMetadataId?: InputMaybe<Scalars['UUID']>;
+ pageLayoutTabId: Scalars['UUID'];
+ title: Scalars['String'];
+ type?: InputMaybe<WidgetType>;
+};
+
export type CreateRemoteServerInput = {
foreignDataWrapperOptions: Scalars['JSON'];
foreignDataWrapperType: Scalars['String'];
@@ -1187,6 +1196,21 @@ export type GetWebhookDto = {
id: Scalars['UUID'];
};
+export type GridPosition = {
+ __typename?: 'GridPosition';
+ column: Scalars['Float'];
+ columnSpan: Scalars['Float'];
+ row: Scalars['Float'];
+ rowSpan: Scalars['Float'];
+};
+
+export type GridPositionInput = {
+ column: Scalars['Float'];
+ columnSpan: Scalars['Float'];
+ row: Scalars['Float'];
+ rowSpan: Scalars['Float'];
+};
+
export enum HealthIndicatorId {
app = 'app',
connectedAccount = 'connectedAccount',
@@ -1396,6 +1420,7 @@ export type Mutation = {
createOneServerlessFunction: ServerlessFunction;
createPageLayout: PageLayout;
createPageLayoutTab: PageLayoutTab;
+ createPageLayoutWidget: PageLayoutWidget;
createSAMLIdentityProvider: SetupSsoOutput;
createWebhook: Webhook;
createWorkflowVersionEdge: WorkflowVersionStepChanges;
@@ -1419,6 +1444,7 @@ export type Mutation = {
deleteOneServerlessFunction: ServerlessFunction;
deletePageLayout: PageLayout;
deletePageLayoutTab: Scalars['Boolean'];
+ deletePageLayoutWidget: PageLayoutWidget;
deleteSSOIdentityProvider: DeleteSsoOutput;
deleteTwoFactorAuthenticationMethod: DeleteTwoFactorAuthenticationMethodOutput;
deleteUser: User;
@@ -1434,6 +1460,7 @@ export type Mutation = {
destroyCoreViewSort: Scalars['Boolean'];
destroyPageLayout: Scalars['Boolean'];
destroyPageLayoutTab: Scalars['Boolean'];
+ destroyPageLayoutWidget: Scalars['Boolean'];
disablePostgresProxy: PostgresCredentials;
editSSOIdentityProvider: EditSsoOutput;
emailPasswordResetLink: EmailPasswordResetLink;
@@ -1459,6 +1486,7 @@ export type Mutation = {
resendWorkspaceInvitation: SendInvitationsOutput;
restorePageLayout: PageLayout;
restorePageLayoutTab: PageLayoutTab;
+ restorePageLayoutWidget: PageLayoutWidget;
revokeApiKey?: Maybe<ApiKey>;
runWorkflowVersion: WorkflowRun;
saveImapSmtpCaldavAccount: ImapSmtpCaldavConnectionSuccess;
@@ -1493,6 +1521,7 @@ export type Mutation = {
updateOneServerlessFunction: ServerlessFunction;
updatePageLayout: PageLayout;
updatePageLayoutTab: PageLayoutTab;
+ updatePageLayoutWidget: PageLayoutWidget;
updatePasswordViaResetToken: InvalidatePassword;
updateSubscriptionItemPrice: BillingUpdateOutput;
updateWebhook?: Maybe<Webhook>;
@@ -1681,6 +1710,11 @@ export type MutationCreatePageLayoutTabArgs = {
};
+export type MutationCreatePageLayoutWidgetArgs = {
+ input: CreatePageLayoutWidgetInput;
+};
+
+
export type MutationCreateSamlIdentityProviderArgs = {
input: SetupSamlSsoInput;
};
@@ -1791,6 +1825,11 @@ export type MutationDeletePageLayoutTabArgs = {
};
+export type MutationDeletePageLayoutWidgetArgs = {
+ id: Scalars['String'];
+};
+
+
export type MutationDeleteSsoIdentityProviderArgs = {
input: DeleteSsoInput;
};
@@ -1861,6 +1900,11 @@ export type MutationDestroyPageLayoutTabArgs = {
};
+export type MutationDestroyPageLayoutWidgetArgs = {
+ id: Scalars['String'];
+};
+
+
export type MutationEditSsoIdentityProviderArgs = {
input: EditSsoInput;
};
@@ -1980,6 +2024,11 @@ export type MutationRestorePageLayoutTabArgs = {
};
+export type MutationRestorePageLayoutWidgetArgs = {
+ id: Scalars['String'];
+};
+
+
export type MutationRevokeApiKeyArgs = {
input: RevokeApiKeyDto;
};
@@ -2155,6 +2204,12 @@ export type MutationUpdatePageLayoutTabArgs = {
};
+export type MutationUpdatePageLayoutWidgetArgs = {
+ id: Scalars['String'];
+ input: UpdatePageLayoutWidgetInput;
+};
+
+
export type MutationUpdatePasswordViaResetTokenArgs = {
newPassword: Scalars['String'];
passwordResetToken: Scalars['String'];
@@ -2431,7 +2486,6 @@ export type PageLayout = {
tabs?: Maybe<Array<PageLayoutTab>>;
type: PageLayoutType;
updatedAt: Scalars['DateTime'];
- workspaceId: Scalars['UUID'];
};
export type PageLayoutTab = {
@@ -2443,7 +2497,6 @@ export type PageLayoutTab = {
position: Scalars['Float'];
title: Scalars['String'];
updatedAt: Scalars['DateTime'];
- workspaceId: Scalars['UUID'];
};
export enum PageLayoutType {
@@ -2452,6 +2505,20 @@ export enum PageLayoutType {
RECORD_PAGE = 'RECORD_PAGE'
}
+export type PageLayoutWidget = {
+ __typename?: 'PageLayoutWidget';
+ configuration?: Maybe<Scalars['JSON']>;
+ createdAt: Scalars['DateTime'];
+ deletedAt?: Maybe<Scalars['DateTime']>;
+ gridPosition: GridPosition;
+ id: Scalars['UUID'];
+ objectMetadataId?: Maybe<Scalars['UUID']>;
+ pageLayoutTabId: Scalars['UUID'];
+ title: Scalars['String'];
+ type: WidgetType;
+ updatedAt: Scalars['DateTime'];
+};
+
export type PermissionFlag = {
__typename?: 'PermissionFlag';
flag: PermissionFlagType;
@@ -2573,6 +2640,8 @@ export type Query = {
getPageLayout?: Maybe<PageLayout>;
getPageLayoutTab: PageLayoutTab;
getPageLayoutTabs: Array<PageLayoutTab>;
+ getPageLayoutWidget: PageLayoutWidget;
+ getPageLayoutWidgets: Array<PageLayoutWidget>;
getPageLayouts: Array<PageLayout>;
getPostgresCredentials?: Maybe<PostgresCredentials>;
getPublicWorkspaceDataByDomain: PublicWorkspaceDataOutput;
@@ -2797,6 +2866,16 @@ export type QueryGetPageLayoutTabsArgs = {
};
+export type QueryGetPageLayoutWidgetArgs = {
+ id: Scalars['String'];
+};
+
+
+export type QueryGetPageLayoutWidgetsArgs = {
+ pageLayoutTabId: Scalars['String'];
+};
+
+
export type QueryGetPageLayoutsArgs = {
objectMetadataId?: InputMaybe<Scalars['String']>;
};
@@ -3429,6 +3508,14 @@ export type UpdatePageLayoutTabInput = {
title?: InputMaybe<Scalars['String']>;
};
+export type UpdatePageLayoutWidgetInput = {
+ configuration?: InputMaybe<Scalars['JSON']>;
+ gridPosition?: InputMaybe<GridPositionInput>;
+ objectMetadataId?: InputMaybe<Scalars['UUID']>;
+ title?: InputMaybe<Scalars['String']>;
+ type?: InputMaybe<WidgetType>;
+};
+
export type UpdateRemoteServerInput = {
foreignDataWrapperOptions?: InputMaybe<Scalars['JSON']>;
id: Scalars['UUID'];
@@ -3747,6 +3834,13 @@ export type Webhook = {
workspaceId: Scalars['UUID'];
};
+export enum WidgetType {
+ FIELDS = 'FIELDS',
+ GRAPH = 'GRAPH',
+ IFRAME = 'IFRAME',
+ VIEW = 'VIEW'
+}
+
export type WorkerQueueMetrics = {
__typename?: 'WorkerQueueMetrics';
active: Scalars['Float'];
diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.ts
index 3e53467d789..bdf21cbd08a 100644
--- a/packages/twenty-front/src/generated/graphql.ts
+++ b/packages/twenty-front/src/generated/graphql.ts
@@ -687,6 +687,15 @@ export type CreatePageLayoutTabInput = {
title: Scalars['String'];
};
+export type CreatePageLayoutWidgetInput = {
+ configuration?: InputMaybe<Scalars['JSON']>;
+ gridPosition: GridPositionInput;
+ objectMetadataId?: InputMaybe<Scalars['UUID']>;
+ pageLayoutTabId: Scalars['UUID'];
+ title: Scalars['String'];
+ type?: InputMaybe<WidgetType>;
+};
+
export type CreateRoleInput = {
canAccessAllTools?: InputMaybe<Scalars['Boolean']>;
canBeAssignedToAgents?: InputMaybe<Scalars['Boolean']>;
@@ -1144,6 +1153,21 @@ export type GetWebhookDto = {
id: Scalars['UUID'];
};
+export type GridPosition = {
+ __typename?: 'GridPosition';
+ column: Scalars['Float'];
+ columnSpan: Scalars['Float'];
+ row: Scalars['Float'];
+ rowSpan: Scalars['Float'];
+};
+
+export type GridPositionInput = {
+ column: Scalars['Float'];
+ columnSpan: Scalars['Float'];
+ row: Scalars['Float'];
+ rowSpan: Scalars['Float'];
+};
+
export enum HealthIndicatorId {
app = 'app',
connectedAccount = 'connectedAccount',
@@ -1352,6 +1376,7 @@ export type Mutation = {
createOneServerlessFunction: ServerlessFunction;
createPageLayout: PageLayout;
createPageLayoutTab: PageLayoutTab;
+ createPageLayoutWidget: PageLayoutWidget;
createSAMLIdentityProvider: SetupSsoOutput;
createWebhook: Webhook;
createWorkflowVersionEdge: WorkflowVersionStepChanges;
@@ -1374,6 +1399,7 @@ export type Mutation = {
deleteOneServerlessFunction: ServerlessFunction;
deletePageLayout: PageLayout;
deletePageLayoutTab: Scalars['Boolean'];
+ deletePageLayoutWidget: PageLayoutWidget;
deleteSSOIdentityProvider: DeleteSsoOutput;
deleteTwoFactorAuthenticationMethod: DeleteTwoFactorAuthenticationMethodOutput;
deleteUser: User;
@@ -1389,6 +1415,7 @@ export type Mutation = {
destroyCoreViewSort: Scalars['Boolean'];
destroyPageLayout: Scalars['Boolean'];
destroyPageLayoutTab: Scalars['Boolean'];
+ destroyPageLayoutWidget: Scalars['Boolean'];
disablePostgresProxy: PostgresCredentials;
editSSOIdentityProvider: EditSsoOutput;
emailPasswordResetLink: EmailPasswordResetLink;
@@ -1414,6 +1441,7 @@ export type Mutation = {
resendWorkspaceInvitation: SendInvitationsOutput;
restorePageLayout: PageLayout;
restorePageLayoutTab: PageLayoutTab;
+ restorePageLayoutWidget: PageLayoutWidget;
revokeApiKey?: Maybe<ApiKey>;
runWorkflowVersion: WorkflowRun;
saveImapSmtpCaldavAccount: ImapSmtpCaldavConnectionSuccess;
@@ -1444,6 +1472,7 @@ export type Mutation = {
updateOneServerlessFunction: ServerlessFunction;
updatePageLayout: PageLayout;
updatePageLayoutTab: PageLayoutTab;
+ updatePageLayoutWidget: PageLayoutWidget;
updatePasswordViaResetToken: InvalidatePassword;
updateSubscriptionItemPrice: BillingUpdateOutput;
updateWebhook?: Maybe<Webhook>;
@@ -1617,6 +1646,11 @@ export type MutationCreatePageLayoutTabArgs = {
};
+export type MutationCreatePageLayoutWidgetArgs = {
+ input: CreatePageLayoutWidgetInput;
+};
+
+
export type MutationCreateSamlIdentityProviderArgs = {
input: SetupSamlSsoInput;
};
@@ -1722,6 +1756,11 @@ export type MutationDeletePageLayoutTabArgs = {
};
+export type MutationDeletePageLayoutWidgetArgs = {
+ id: Scalars['String'];
+};
+
+
export type MutationDeleteSsoIdentityProviderArgs = {
input: DeleteSsoInput;
};
@@ -1792,6 +1831,11 @@ export type MutationDestroyPageLayoutTabArgs = {
};
+export type MutationDestroyPageLayoutWidgetArgs = {
+ id: Scalars['String'];
+};
+
+
export type MutationEditSsoIdentityProviderArgs = {
input: EditSsoInput;
};
@@ -1911,6 +1955,11 @@ export type MutationRestorePageLayoutTabArgs = {
};
+export type MutationRestorePageLayoutWidgetArgs = {
+ id: Scalars['String'];
+};
+
+
export type MutationRevokeApiKeyArgs = {
input: RevokeApiKeyDto;
};
@@ -2066,6 +2115,12 @@ export type MutationUpdatePageLayoutTabArgs = {
};
+export type MutationUpdatePageLayoutWidgetArgs = {
+ id: Scalars['String'];
+ input: UpdatePageLayoutWidgetInput;
+};
+
+
export type MutationUpdatePasswordViaResetTokenArgs = {
newPassword: Scalars['String'];
passwordResetToken: Scalars['String'];
@@ -2342,7 +2397,6 @@ export type PageLayout = {
tabs?: Maybe<Array<PageLayoutTab>>;
type: PageLayoutType;
updatedAt: Scalars['DateTime'];
- workspaceId: Scalars['UUID'];
};
export type PageLayoutTab = {
@@ -2354,7 +2408,6 @@ export type PageLayoutTab = {
position: Scalars['Float'];
title: Scalars['String'];
updatedAt: Scalars['DateTime'];
- workspaceId: Scalars['UUID'];
};
export enum PageLayoutType {
@@ -2363,6 +2416,20 @@ export enum PageLayoutType {
RECORD_PAGE = 'RECORD_PAGE'
}
+export type PageLayoutWidget = {
+ __typename?: 'PageLayoutWidget';
+ configuration?: Maybe<Scalars['JSON']>;
+ createdAt: Scalars['DateTime'];
+ deletedAt?: Maybe<Scalars['DateTime']>;
+ gridPosition: GridPosition;
+ id: Scalars['UUID'];
+ objectMetadataId?: Maybe<Scalars['UUID']>;
+ pageLayoutTabId: Scalars['UUID'];
+ title: Scalars['String'];
+ type: WidgetType;
+ updatedAt: Scalars['DateTime'];
+};
+
export type PermissionFlag = {
__typename?: 'PermissionFlag';
flag: PermissionFlagType;
@@ -2481,6 +2548,8 @@ export type Query = {
getPageLayout?: Maybe<PageLayout>;
getPageLayoutTab: PageLayoutTab;
getPageLayoutTabs: Array<PageLayoutTab>;
+ getPageLayoutWidget: PageLayoutWidget;
+ getPageLayoutWidgets: Array<PageLayoutWidget>;
getPageLayouts: Array<PageLayout>;
getPostgresCredentials?: Maybe<PostgresCredentials>;
getPublicWorkspaceDataByDomain: PublicWorkspaceDataOutput;
@@ -2679,6 +2748,16 @@ export type QueryGetPageLayoutTabsArgs = {
};
+export type QueryGetPageLayoutWidgetArgs = {
+ id: Scalars['String'];
+};
+
+
+export type QueryGetPageLayoutWidgetsArgs = {
+ pageLayoutTabId: Scalars['String'];
+};
+
+
export type QueryGetPageLayoutsArgs = {
objectMetadataId?: InputMaybe<Scalars['String']>;
};
@@ -3275,6 +3354,14 @@ export type UpdatePageLayoutTabInput = {
title?: InputMaybe<Scalars['String']>;
};
+export type UpdatePageLayoutWidgetInput = {
+ configuration?: InputMaybe<Scalars['JSON']>;
+ gridPosition?: InputMaybe<GridPositionInput>;
+ objectMetadataId?: InputMaybe<Scalars['UUID']>;
+ title?: InputMaybe<Scalars['String']>;
+ type?: InputMaybe<WidgetType>;
+};
+
export type UpdateRoleInput = {
/** The id of the role to update */
id: Scalars['UUID'];
@@ -3575,6 +3662,13 @@ export type Webhook = {
workspaceId: Scalars['UUID'];
};
+export enum WidgetType {
+ FIELDS = 'FIELDS',
+ GRAPH = 'GRAPH',
+ IFRAME = 'IFRAME',
+ VIEW = 'VIEW'
+}
+
export type WorkerQueueMetrics = {
__typename?: 'WorkerQueueMetrics';
active: Scalars['Float'];
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/controllers/page-layout-widget.controller.ts b/packages/twenty-server/src/engine/core-modules/page-layout/controllers/page-layout-widget.controller.ts
new file mode 100644
index 00000000000..fed9074902e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/controllers/page-layout-widget.controller.ts
@@ -0,0 +1,91 @@
+import {
+ Body,
+ Controller,
+ Delete,
+ Get,
+ Param,
+ Patch,
+ Post,
+ Query,
+ UseFilters,
+ UseGuards,
+} from '@nestjs/common';
+
+import { isDefined } from 'class-validator';
+
+import { CreatePageLayoutWidgetInput } from 'src/engine/core-modules/page-layout/dtos/inputs/create-page-layout-widget.input';
+import { UpdatePageLayoutWidgetInput } from 'src/engine/core-modules/page-layout/dtos/inputs/update-page-layout-widget.input';
+import { type PageLayoutWidgetDTO } from 'src/engine/core-modules/page-layout/dtos/page-layout-widget.dto';
+import {
+ generatePageLayoutWidgetExceptionMessage,
+ PageLayoutWidgetException,
+ PageLayoutWidgetExceptionCode,
+ PageLayoutWidgetExceptionMessageKey,
+} from 'src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception';
+import { PageLayoutWidgetRestApiExceptionFilter } from 'src/engine/core-modules/page-layout/filters/page-layout-widget-rest-api-exception.filter';
+import { PageLayoutWidgetService } from 'src/engine/core-modules/page-layout/services/page-layout-widget.service';
+import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
+import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
+
+@Controller('rest/metadata/page-layout-widgets')
+@UseGuards(WorkspaceAuthGuard)
+@UseFilters(PageLayoutWidgetRestApiExceptionFilter)
+export class PageLayoutWidgetController {
+ constructor(
+ private readonly pageLayoutWidgetService: PageLayoutWidgetService,
+ ) {}
+
+ @Get()
+ async findMany(
+ @AuthWorkspace() workspace: Workspace,
+ @Query('pageLayoutTabId') pageLayoutTabId: string,
+ ): Promise<PageLayoutWidgetDTO[]> {
+ if (!isDefined(pageLayoutTabId)) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_TAB_ID_REQUIRED,
+ ),
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ }
+
+ return this.pageLayoutWidgetService.findByPageLayoutTabId(
+ workspace.id,
+ pageLayoutTabId,
+ );
+ }
+
+ @Get(':id')
+ async findOne(
+ @Param('id') id: string,
+ @AuthWorkspace() workspace: Workspace,
+ ): Promise<PageLayoutWidgetDTO | null> {
+ return this.pageLayoutWidgetService.findByIdOrThrow(id, workspace.id);
+ }
+
+ @Post()
+ async create(
+ @Body() input: CreatePageLayoutWidgetInput,
+ @AuthWorkspace() workspace: Workspace,
+ ): Promise<PageLayoutWidgetDTO> {
+ return this.pageLayoutWidgetService.create(input, workspace.id);
+ }
+
+ @Patch(':id')
+ async update(
+ @Param('id') id: string,
+ @Body() input: UpdatePageLayoutWidgetInput,
+ @AuthWorkspace() workspace: Workspace,
+ ): Promise<PageLayoutWidgetDTO> {
+ return this.pageLayoutWidgetService.update(id, workspace.id, input);
+ }
+
+ @Delete(':id')
+ async delete(
+ @Param('id') id: string,
+ @AuthWorkspace() workspace: Workspace,
+ ): Promise<PageLayoutWidgetDTO> {
+ return this.pageLayoutWidgetService.delete(id, workspace.id);
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/dtos/inputs/create-page-layout-widget.input.ts b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/inputs/create-page-layout-widget.input.ts
new file mode 100644
index 00000000000..b56f752148a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/inputs/create-page-layout-widget.input.ts
@@ -0,0 +1,50 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { Type } from 'class-transformer';
+import {
+ IsEnum,
+ IsNotEmpty,
+ IsObject,
+ IsOptional,
+ IsString,
+ IsUUID,
+ ValidateNested,
+} from 'class-validator';
+import { GraphQLJSON } from 'graphql-type-json';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { GridPositionInput } from 'src/engine/core-modules/page-layout/dtos/inputs/grid-position.input';
+import { WidgetType } from 'src/engine/core-modules/page-layout/enums/widget-type.enum';
+
+@InputType()
+export class CreatePageLayoutWidgetInput {
+ @Field(() => UUIDScalarType, { nullable: false })
+ @IsUUID()
+ @IsNotEmpty()
+ pageLayoutTabId: string;
+
+ @Field({ nullable: false })
+ @IsString()
+ @IsNotEmpty()
+ title: string;
+
+ @Field(() => WidgetType, { nullable: true, defaultValue: WidgetType.VIEW })
+ @IsEnum(WidgetType)
+ @IsOptional()
+ type?: WidgetType;
+
+ @Field(() => UUIDScalarType, { nullable: true })
+ @IsUUID()
+ @IsOptional()
+ objectMetadataId?: string | null;
+
+ @Field(() => GridPositionInput, { nullable: false })
+ @ValidateNested()
+ @Type(() => GridPositionInput)
+ gridPosition: GridPositionInput;
+
+ @Field(() => GraphQLJSON, { nullable: true })
+ @IsObject()
+ @IsOptional()
+ configuration?: Record<string, unknown> | null;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/dtos/inputs/grid-position.input.ts b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/inputs/grid-position.input.ts
new file mode 100644
index 00000000000..df647b8a888
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/inputs/grid-position.input.ts
@@ -0,0 +1,32 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { IsNotEmpty, IsNumber, Min } from 'class-validator';
+
+import { GridPosition } from 'src/engine/core-modules/page-layout/types/grid-position.type';
+
+@InputType('GridPositionInput')
+export class GridPositionInput implements GridPosition {
+ @Field()
+ @IsNumber()
+ @Min(0)
+ @IsNotEmpty()
+ row: number;
+
+ @Field()
+ @IsNumber()
+ @Min(0)
+ @IsNotEmpty()
+ column: number;
+
+ @Field()
+ @IsNumber()
+ @Min(1)
+ @IsNotEmpty()
+ rowSpan: number;
+
+ @Field()
+ @IsNumber()
+ @Min(1)
+ @IsNotEmpty()
+ columnSpan: number;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/dtos/inputs/update-page-layout-widget.input.ts b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/inputs/update-page-layout-widget.input.ts
new file mode 100644
index 00000000000..3765f5488ac
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/inputs/update-page-layout-widget.input.ts
@@ -0,0 +1,45 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { Type } from 'class-transformer';
+import {
+ IsEnum,
+ IsObject,
+ IsOptional,
+ IsString,
+ IsUUID,
+ ValidateNested,
+} from 'class-validator';
+import { GraphQLJSON } from 'graphql-type-json';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { GridPositionInput } from 'src/engine/core-modules/page-layout/dtos/inputs/grid-position.input';
+import { WidgetType } from 'src/engine/core-modules/page-layout/enums/widget-type.enum';
+
+@InputType()
+export class UpdatePageLayoutWidgetInput {
+ @Field({ nullable: true })
+ @IsString()
+ @IsOptional()
+ title?: string;
+
+ @Field(() => WidgetType, { nullable: true })
+ @IsEnum(WidgetType)
+ @IsOptional()
+ type?: WidgetType;
+
+ @Field(() => UUIDScalarType, { nullable: true })
+ @IsUUID()
+ @IsOptional()
+ objectMetadataId?: string | null;
+
+ @Field(() => GridPositionInput, { nullable: true })
+ @ValidateNested()
+ @Type(() => GridPositionInput)
+ @IsOptional()
+ gridPosition?: GridPositionInput;
+
+ @Field(() => GraphQLJSON, { nullable: true })
+ @IsObject()
+ @IsOptional()
+ configuration?: Record<string, unknown> | null;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout-tab.dto.ts b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout-tab.dto.ts
index eb84280f5e3..f346e116897 100644
--- a/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout-tab.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout-tab.dto.ts
@@ -18,9 +18,6 @@ export class PageLayoutTabDTO {
@Field(() => UUIDScalarType, { nullable: false })
pageLayoutId: string;
- @Field(() => UUIDScalarType, { nullable: false })
- workspaceId: string;
-
@Field()
createdAt: Date;
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout-widget.dto.ts b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout-widget.dto.ts
new file mode 100644
index 00000000000..217cdee4090
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout-widget.dto.ts
@@ -0,0 +1,57 @@
+import { Field, ObjectType, registerEnumType } from '@nestjs/graphql';
+
+import { IDField } from '@ptc-org/nestjs-query-graphql';
+import { GraphQLJSON } from 'graphql-type-json';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { WidgetType } from 'src/engine/core-modules/page-layout/enums/widget-type.enum';
+
+registerEnumType(WidgetType, { name: 'WidgetType' });
+
+@ObjectType('GridPosition')
+export class GridPositionDTO {
+ @Field()
+ row: number;
+
+ @Field()
+ column: number;
+
+ @Field()
+ rowSpan: number;
+
+ @Field()
+ columnSpan: number;
+}
+
+@ObjectType('PageLayoutWidget')
+export class PageLayoutWidgetDTO {
+ @IDField(() => UUIDScalarType)
+ id: string;
+
+ @Field(() => UUIDScalarType, { nullable: false })
+ pageLayoutTabId: string;
+
+ @Field({ nullable: false })
+ title: string;
+
+ @Field(() => WidgetType, { nullable: false })
+ type: WidgetType;
+
+ @Field(() => UUIDScalarType, { nullable: true })
+ objectMetadataId: string | null;
+
+ @Field(() => GridPositionDTO, { nullable: false })
+ gridPosition: GridPositionDTO;
+
+ @Field(() => GraphQLJSON, { nullable: true })
+ configuration: Record<string, unknown> | null;
+
+ @Field()
+ createdAt: Date;
+
+ @Field()
+ updatedAt: Date;
+
+ @Field(() => Date, { nullable: true })
+ deletedAt?: Date | null;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout.dto.ts b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout.dto.ts
index faa9ff17600..dc0d197e313 100644
--- a/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/dtos/page-layout.dto.ts
@@ -16,9 +16,6 @@ export class PageLayoutDTO {
@Field({ nullable: false })
name: string;
- @Field(() => UUIDScalarType, { nullable: false })
- workspaceId: string;
-
@Field(() => PageLayoutType, {
nullable: false,
defaultValue: PageLayoutType.RECORD_PAGE,
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception.ts b/packages/twenty-server/src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception.ts
new file mode 100644
index 00000000000..fc9f2292b2c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception.ts
@@ -0,0 +1,41 @@
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { CustomException } from 'src/utils/custom-exception';
+
+export enum PageLayoutWidgetExceptionCode {
+ PAGE_LAYOUT_WIDGET_NOT_FOUND = 'PAGE_LAYOUT_WIDGET_NOT_FOUND',
+ INVALID_PAGE_LAYOUT_WIDGET_DATA = 'INVALID_PAGE_LAYOUT_WIDGET_DATA',
+}
+
+export enum PageLayoutWidgetExceptionMessageKey {
+ PAGE_LAYOUT_WIDGET_NOT_FOUND = 'PAGE_LAYOUT_WIDGET_NOT_FOUND',
+ TITLE_REQUIRED = 'TITLE_REQUIRED',
+ PAGE_LAYOUT_TAB_ID_REQUIRED = 'PAGE_LAYOUT_TAB_ID_REQUIRED',
+ PAGE_LAYOUT_TAB_NOT_FOUND = 'PAGE_LAYOUT_TAB_NOT_FOUND',
+ PAGE_LAYOUT_WIDGET_NOT_DELETED = 'PAGE_LAYOUT_WIDGET_NOT_DELETED',
+ GRID_POSITION_REQUIRED = 'GRID_POSITION_REQUIRED',
+}
+
+export class PageLayoutWidgetException extends CustomException<PageLayoutWidgetExceptionCode> {}
+
+export const generatePageLayoutWidgetExceptionMessage = (
+ key: PageLayoutWidgetExceptionMessageKey,
+ value?: string,
+): string => {
+ switch (key) {
+ case PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND:
+ return `Page layout widget with ID "${value}" not found`;
+ case PageLayoutWidgetExceptionMessageKey.TITLE_REQUIRED:
+ return 'Page layout widget title is required';
+ case PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_TAB_ID_REQUIRED:
+ return 'Page layout tab ID is required';
+ case PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_TAB_NOT_FOUND:
+ return 'Page layout tab not found';
+ case PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_DELETED:
+ return 'Page layout widget is not deleted and cannot be restored';
+ case PageLayoutWidgetExceptionMessageKey.GRID_POSITION_REQUIRED:
+ return 'Grid position is required';
+ default:
+ assertUnreachable(key);
+ }
+};
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/filters/page-layout-widget-rest-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/page-layout/filters/page-layout-widget-rest-api-exception.filter.ts
new file mode 100644
index 00000000000..bd659dbdd4b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/filters/page-layout-widget-rest-api-exception.filter.ts
@@ -0,0 +1,47 @@
+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 {
+ PageLayoutWidgetException,
+ PageLayoutWidgetExceptionCode,
+} from 'src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception';
+
+@Catch(PageLayoutWidgetException)
+export class PageLayoutWidgetRestApiExceptionFilter implements ExceptionFilter {
+ constructor(
+ private readonly httpExceptionHandlerService: HttpExceptionHandlerService,
+ ) {}
+
+ catch(exception: PageLayoutWidgetException, host: ArgumentsHost) {
+ const ctx = host.switchToHttp();
+ const response = ctx.getResponse<Response>();
+
+ switch (exception.code) {
+ case PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND:
+ return this.httpExceptionHandlerService.handleError(
+ exception,
+ response,
+ 404,
+ );
+ case PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA:
+ return this.httpExceptionHandlerService.handleError(
+ exception,
+ response,
+ 400,
+ );
+ default:
+ // TODO: change to 500 when we have input validation
+ return this.httpExceptionHandlerService.handleError(
+ exception,
+ response,
+ 400,
+ );
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/page-layout.module.ts b/packages/twenty-server/src/engine/core-modules/page-layout/page-layout.module.ts
index 8d1c734f3c8..b53e5390124 100644
--- a/packages/twenty-server/src/engine/core-modules/page-layout/page-layout.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/page-layout.module.ts
@@ -2,13 +2,16 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PageLayoutTabController } from 'src/engine/core-modules/page-layout/controllers/page-layout-tab.controller';
+import { PageLayoutWidgetController } from 'src/engine/core-modules/page-layout/controllers/page-layout-widget.controller';
import { PageLayoutController } from 'src/engine/core-modules/page-layout/controllers/page-layout.controller';
import { PageLayoutTabEntity } from 'src/engine/core-modules/page-layout/entities/page-layout-tab.entity';
import { PageLayoutWidgetEntity } from 'src/engine/core-modules/page-layout/entities/page-layout-widget.entity';
import { PageLayoutEntity } from 'src/engine/core-modules/page-layout/entities/page-layout.entity';
import { PageLayoutTabResolver } from 'src/engine/core-modules/page-layout/resolvers/page-layout-tab.resolver';
+import { PageLayoutWidgetResolver } from 'src/engine/core-modules/page-layout/resolvers/page-layout-widget.resolver';
import { PageLayoutResolver } from 'src/engine/core-modules/page-layout/resolvers/page-layout.resolver';
import { PageLayoutTabService } from 'src/engine/core-modules/page-layout/services/page-layout-tab.service';
+import { PageLayoutWidgetService } from 'src/engine/core-modules/page-layout/services/page-layout-widget.service';
import { PageLayoutService } from 'src/engine/core-modules/page-layout/services/page-layout.service';
@Module({
@@ -19,13 +22,19 @@ import { PageLayoutService } from 'src/engine/core-modules/page-layout/services/
PageLayoutWidgetEntity,
]),
],
- controllers: [PageLayoutController, PageLayoutTabController],
+ controllers: [
+ PageLayoutController,
+ PageLayoutTabController,
+ PageLayoutWidgetController,
+ ],
providers: [
PageLayoutService,
PageLayoutTabService,
+ PageLayoutWidgetService,
PageLayoutResolver,
PageLayoutTabResolver,
+ PageLayoutWidgetResolver,
],
- exports: [PageLayoutService, PageLayoutTabService],
+ exports: [PageLayoutService, PageLayoutTabService, PageLayoutWidgetService],
})
export class PageLayoutModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/resolvers/page-layout-widget.resolver.ts b/packages/twenty-server/src/engine/core-modules/page-layout/resolvers/page-layout-widget.resolver.ts
new file mode 100644
index 00000000000..2ac958327e1
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/resolvers/page-layout-widget.resolver.ts
@@ -0,0 +1,80 @@
+import { UseFilters, UseGuards } from '@nestjs/common';
+import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
+
+import { CreatePageLayoutWidgetInput } from 'src/engine/core-modules/page-layout/dtos/inputs/create-page-layout-widget.input';
+import { UpdatePageLayoutWidgetInput } from 'src/engine/core-modules/page-layout/dtos/inputs/update-page-layout-widget.input';
+import { PageLayoutWidgetDTO } from 'src/engine/core-modules/page-layout/dtos/page-layout-widget.dto';
+import { PageLayoutWidgetService } from 'src/engine/core-modules/page-layout/services/page-layout-widget.service';
+import { PageLayoutGraphqlApiExceptionFilter } from 'src/engine/core-modules/page-layout/utils/page-layout-graphql-api-exception.filter';
+import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
+import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
+
+@Resolver(() => PageLayoutWidgetDTO)
+@UseFilters(PageLayoutGraphqlApiExceptionFilter)
+@UseGuards(WorkspaceAuthGuard)
+export class PageLayoutWidgetResolver {
+ constructor(
+ private readonly pageLayoutWidgetService: PageLayoutWidgetService,
+ ) {}
+
+ @Query(() => [PageLayoutWidgetDTO])
+ async getPageLayoutWidgets(
+ @AuthWorkspace() workspace: Workspace,
+ @Args('pageLayoutTabId', { type: () => String }) pageLayoutTabId: string,
+ ): Promise<PageLayoutWidgetDTO[]> {
+ return this.pageLayoutWidgetService.findByPageLayoutTabId(
+ workspace.id,
+ pageLayoutTabId,
+ );
+ }
+
+ @Query(() => PageLayoutWidgetDTO)
+ async getPageLayoutWidget(
+ @Args('id', { type: () => String }) id: string,
+ @AuthWorkspace() workspace: Workspace,
+ ): Promise<PageLayoutWidgetDTO> {
+ return this.pageLayoutWidgetService.findByIdOrThrow(id, workspace.id);
+ }
+
+ @Mutation(() => PageLayoutWidgetDTO)
+ async createPageLayoutWidget(
+ @Args('input') input: CreatePageLayoutWidgetInput,
+ @AuthWorkspace() workspace: Workspace,
+ ): Promise<PageLayoutWidgetDTO> {
+ return this.pageLayoutWidgetService.create(input, workspace.id);
+ }
+
+ @Mutation(() => PageLayoutWidgetDTO)
+ async updatePageLayoutWidget(
+ @Args('id', { type: () => String }) id: string,
+ @Args('input') input: UpdatePageLayoutWidgetInput,
+ @AuthWorkspace() workspace: Workspace,
+ ): Promise<PageLayoutWidgetDTO> {
+ return this.pageLayoutWidgetService.update(id, workspace.id, input);
+ }
+
+ @Mutation(() => PageLayoutWidgetDTO)
+ async deletePageLayoutWidget(
+ @Args('id', { type: () => String }) id: string,
+ @AuthWorkspace() workspace: Workspace,
+ ): Promise<PageLayoutWidgetDTO> {
+ return this.pageLayoutWidgetService.delete(id, workspace.id);
+ }
+
+ @Mutation(() => Boolean)
+ async destroyPageLayoutWidget(
+ @Args('id', { type: () => String }) id: string,
+ @AuthWorkspace() workspace: Workspace,
+ ): Promise<boolean> {
+ return this.pageLayoutWidgetService.destroy(id, workspace.id);
+ }
+
+ @Mutation(() => PageLayoutWidgetDTO)
+ async restorePageLayoutWidget(
+ @Args('id', { type: () => String }) id: string,
+ @AuthWorkspace() workspace: Workspace,
+ ): Promise<PageLayoutWidgetDTO> {
+ return this.pageLayoutWidgetService.restore(id, workspace.id);
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/services/page-layout-tab.service.ts b/packages/twenty-server/src/engine/core-modules/page-layout/services/page-layout-tab.service.ts
index efd68cb0fae..b11cf09747f 100644
--- a/packages/twenty-server/src/engine/core-modules/page-layout/services/page-layout-tab.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/services/page-layout-tab.service.ts
@@ -182,6 +182,7 @@ export class PageLayoutTabService {
select: {
id: true,
deletedAt: true,
+ pageLayoutId: true,
},
where: {
id,
@@ -209,6 +210,26 @@ export class PageLayoutTabService {
);
}
+ try {
+ await this.pageLayoutService.findByIdOrThrow(
+ pageLayoutTab.pageLayoutId,
+ workspaceId,
+ );
+ } catch (error) {
+ if (
+ error instanceof PageLayoutException &&
+ error.code === PageLayoutExceptionCode.PAGE_LAYOUT_NOT_FOUND
+ ) {
+ throw new PageLayoutTabException(
+ generatePageLayoutTabExceptionMessage(
+ PageLayoutTabExceptionMessageKey.PAGE_LAYOUT_NOT_FOUND,
+ ),
+ PageLayoutTabExceptionCode.INVALID_PAGE_LAYOUT_TAB_DATA,
+ );
+ }
+ throw error;
+ }
+
await this.pageLayoutTabRepository.restore(id);
const restoredPageLayoutTab = await this.findByIdOrThrow(id, workspaceId);
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/services/page-layout-widget.service.ts b/packages/twenty-server/src/engine/core-modules/page-layout/services/page-layout-widget.service.ts
new file mode 100644
index 00000000000..3c11b0fd32c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/services/page-layout-widget.service.ts
@@ -0,0 +1,259 @@
+import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { isDefined } from 'twenty-shared/utils';
+import { IsNull, Repository } from 'typeorm';
+import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
+
+import { UpdatePageLayoutWidgetInput } from 'src/engine/core-modules/page-layout/dtos/inputs/update-page-layout-widget.input';
+import { PageLayoutWidgetEntity } from 'src/engine/core-modules/page-layout/entities/page-layout-widget.entity';
+import {
+ PageLayoutTabException,
+ PageLayoutTabExceptionCode,
+} from 'src/engine/core-modules/page-layout/exceptions/page-layout-tab.exception';
+import {
+ PageLayoutWidgetException,
+ PageLayoutWidgetExceptionCode,
+ PageLayoutWidgetExceptionMessageKey,
+ generatePageLayoutWidgetExceptionMessage,
+} from 'src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception';
+import { PageLayoutTabService } from 'src/engine/core-modules/page-layout/services/page-layout-tab.service';
+
+@Injectable()
+export class PageLayoutWidgetService {
+ constructor(
+ @InjectRepository(PageLayoutWidgetEntity)
+ private readonly pageLayoutWidgetRepository: Repository<PageLayoutWidgetEntity>,
+ private readonly pageLayoutTabService: PageLayoutTabService,
+ ) {}
+
+ async findByPageLayoutTabId(
+ workspaceId: string,
+ pageLayoutTabId: string,
+ ): Promise<PageLayoutWidgetEntity[]> {
+ return this.pageLayoutWidgetRepository.find({
+ where: {
+ pageLayoutTabId,
+ workspaceId,
+ deletedAt: IsNull(),
+ },
+ order: { createdAt: 'ASC' },
+ });
+ }
+
+ async findByIdOrThrow(
+ id: string,
+ workspaceId: string,
+ ): Promise<PageLayoutWidgetEntity> {
+ const pageLayoutWidget = await this.pageLayoutWidgetRepository.findOne({
+ where: {
+ id,
+ workspaceId,
+ deletedAt: IsNull(),
+ },
+ });
+
+ if (!isDefined(pageLayoutWidget)) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ id,
+ ),
+ PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ );
+ }
+
+ return pageLayoutWidget;
+ }
+
+ async create(
+ pageLayoutWidgetData: Partial<PageLayoutWidgetEntity>,
+ workspaceId: string,
+ ): Promise<PageLayoutWidgetEntity> {
+ if (!isDefined(pageLayoutWidgetData.title)) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.TITLE_REQUIRED,
+ ),
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ }
+
+ if (!isDefined(pageLayoutWidgetData.pageLayoutTabId)) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_TAB_ID_REQUIRED,
+ ),
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ }
+
+ if (!isDefined(pageLayoutWidgetData.gridPosition)) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.GRID_POSITION_REQUIRED,
+ ),
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ }
+
+ try {
+ await this.pageLayoutTabService.findByIdOrThrow(
+ pageLayoutWidgetData.pageLayoutTabId,
+ workspaceId,
+ );
+
+ const pageLayoutWidget = this.pageLayoutWidgetRepository.create({
+ ...pageLayoutWidgetData,
+ workspaceId,
+ });
+
+ return this.pageLayoutWidgetRepository.save(pageLayoutWidget);
+ } catch (error) {
+ if (
+ error instanceof PageLayoutTabException &&
+ error.code === PageLayoutTabExceptionCode.PAGE_LAYOUT_TAB_NOT_FOUND
+ ) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_TAB_NOT_FOUND,
+ ),
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ }
+ throw error;
+ }
+ }
+
+ async update(
+ id: string,
+ workspaceId: string,
+ updateData: UpdatePageLayoutWidgetInput,
+ ): Promise<PageLayoutWidgetEntity> {
+ const existingWidget = await this.pageLayoutWidgetRepository.findOne({
+ where: {
+ id,
+ workspaceId,
+ deletedAt: IsNull(),
+ },
+ });
+
+ if (!isDefined(existingWidget)) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ id,
+ ),
+ PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ );
+ }
+
+ await this.pageLayoutWidgetRepository.update(
+ { id },
+ updateData as QueryDeepPartialEntity<PageLayoutWidgetEntity>,
+ );
+
+ return this.findByIdOrThrow(id, workspaceId);
+ }
+
+ async delete(
+ id: string,
+ workspaceId: string,
+ ): Promise<PageLayoutWidgetEntity> {
+ const pageLayoutWidget = await this.findByIdOrThrow(id, workspaceId);
+
+ await this.pageLayoutWidgetRepository.softDelete(id);
+
+ return pageLayoutWidget;
+ }
+
+ async destroy(id: string, workspaceId: string): Promise<boolean> {
+ const pageLayoutWidget = await this.pageLayoutWidgetRepository.findOne({
+ where: {
+ id,
+ workspaceId,
+ },
+ withDeleted: true,
+ });
+
+ if (!isDefined(pageLayoutWidget)) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ id,
+ ),
+ PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ );
+ }
+
+ await this.pageLayoutWidgetRepository.delete(id);
+
+ return true;
+ }
+
+ async restore(
+ id: string,
+ workspaceId: string,
+ ): Promise<PageLayoutWidgetEntity> {
+ const pageLayoutWidget = await this.pageLayoutWidgetRepository.findOne({
+ select: {
+ id: true,
+ deletedAt: true,
+ pageLayoutTabId: true,
+ },
+ where: {
+ id,
+ workspaceId,
+ },
+ withDeleted: true,
+ });
+
+ if (!isDefined(pageLayoutWidget)) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ id,
+ ),
+ PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ );
+ }
+
+ if (!isDefined(pageLayoutWidget.deletedAt)) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_DELETED,
+ ),
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ }
+
+ try {
+ await this.pageLayoutTabService.findByIdOrThrow(
+ pageLayoutWidget.pageLayoutTabId,
+ workspaceId,
+ );
+ } catch (error) {
+ if (
+ error instanceof PageLayoutTabException &&
+ error.code === PageLayoutTabExceptionCode.PAGE_LAYOUT_TAB_NOT_FOUND
+ ) {
+ throw new PageLayoutWidgetException(
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_TAB_NOT_FOUND,
+ ),
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ }
+ throw error;
+ }
+
+ await this.pageLayoutWidgetRepository.restore(id);
+
+ const restoredPageLayoutWidget = await this.findByIdOrThrow(
+ id,
+ workspaceId,
+ );
+
+ return restoredPageLayoutWidget;
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/services/tests/page-layout-tab.service.spec.ts b/packages/twenty-server/src/engine/core-modules/page-layout/services/tests/page-layout-tab.service.spec.ts
index 37abf6e81f8..c340b26667c 100644
--- a/packages/twenty-server/src/engine/core-modules/page-layout/services/tests/page-layout-tab.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/services/tests/page-layout-tab.service.spec.ts
@@ -7,8 +7,10 @@ import { PageLayoutTabEntity } from 'src/engine/core-modules/page-layout/entitie
import { type PageLayoutWidgetEntity } from 'src/engine/core-modules/page-layout/entities/page-layout-widget.entity';
import { WidgetType } from 'src/engine/core-modules/page-layout/enums/widget-type.enum';
import {
+ generatePageLayoutTabExceptionMessage,
PageLayoutTabException,
PageLayoutTabExceptionCode,
+ PageLayoutTabExceptionMessageKey,
} from 'src/engine/core-modules/page-layout/exceptions/page-layout-tab.exception';
import {
PageLayoutException,
@@ -493,6 +495,7 @@ describe('PageLayoutTabService', () => {
select: {
id: true,
deletedAt: true,
+ pageLayoutId: true,
},
where: {
id,
@@ -540,5 +543,50 @@ describe('PageLayoutTabService', () => {
PageLayoutTabExceptionCode.INVALID_PAGE_LAYOUT_TAB_DATA,
);
});
+
+ it('should throw an exception when parent page layout is not accessible', async () => {
+ const id = 'page-layout-tab-id';
+ const workspaceId = 'workspace-id';
+ const deletedTab = {
+ ...mockPageLayoutTab,
+ deletedAt: new Date(),
+ pageLayoutId: 'deleted-page-layout-id',
+ };
+
+ jest
+ .spyOn(pageLayoutTabRepository, 'findOne')
+ .mockResolvedValue(deletedTab);
+ jest
+ .spyOn(pageLayoutService, 'findByIdOrThrow')
+ .mockRejectedValue(
+ new PageLayoutException(
+ 'Page layout not found',
+ PageLayoutExceptionCode.PAGE_LAYOUT_NOT_FOUND,
+ ),
+ );
+
+ await expect(
+ pageLayoutTabService.restore(id, workspaceId),
+ ).rejects.toThrow(PageLayoutTabException);
+ await expect(
+ pageLayoutTabService.restore(id, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutTabExceptionCode.INVALID_PAGE_LAYOUT_TAB_DATA,
+ );
+ await expect(
+ pageLayoutTabService.restore(id, workspaceId),
+ ).rejects.toHaveProperty(
+ 'message',
+ generatePageLayoutTabExceptionMessage(
+ PageLayoutTabExceptionMessageKey.PAGE_LAYOUT_NOT_FOUND,
+ ),
+ );
+
+ expect(pageLayoutService.findByIdOrThrow).toHaveBeenCalledWith(
+ 'deleted-page-layout-id',
+ workspaceId,
+ );
+ });
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/services/tests/page-layout-widget.service.spec.ts b/packages/twenty-server/src/engine/core-modules/page-layout/services/tests/page-layout-widget.service.spec.ts
new file mode 100644
index 00000000000..e4d614e7319
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/services/tests/page-layout-widget.service.spec.ts
@@ -0,0 +1,584 @@
+import { Test, type TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+
+import { IsNull, type Repository } from 'typeorm';
+
+import { PageLayoutWidgetEntity } from 'src/engine/core-modules/page-layout/entities/page-layout-widget.entity';
+import { WidgetType } from 'src/engine/core-modules/page-layout/enums/widget-type.enum';
+import {
+ PageLayoutTabException,
+ PageLayoutTabExceptionCode,
+} from 'src/engine/core-modules/page-layout/exceptions/page-layout-tab.exception';
+import {
+ generatePageLayoutWidgetExceptionMessage,
+ PageLayoutWidgetException,
+ PageLayoutWidgetExceptionCode,
+ PageLayoutWidgetExceptionMessageKey,
+} from 'src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception';
+import { PageLayoutTabService } from 'src/engine/core-modules/page-layout/services/page-layout-tab.service';
+import { PageLayoutWidgetService } from 'src/engine/core-modules/page-layout/services/page-layout-widget.service';
+
+describe('PageLayoutWidgetService', () => {
+ let pageLayoutWidgetService: PageLayoutWidgetService;
+ let pageLayoutWidgetRepository: Repository<PageLayoutWidgetEntity>;
+ let pageLayoutTabService: PageLayoutTabService;
+
+ const mockPageLayoutWidget = {
+ id: 'page-layout-widget-id',
+ title: 'Test Widget',
+ type: WidgetType.VIEW,
+ pageLayoutTabId: 'page-layout-tab-id',
+ pageLayoutTab: {} as any,
+ objectMetadataId: 'object-metadata-id',
+ objectMetadata: null,
+ gridPosition: { row: 0, column: 0, rowSpan: 4, columnSpan: 4 },
+ configuration: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ deletedAt: null,
+ } as PageLayoutWidgetEntity;
+
+ const mockPageLayoutTab = {
+ id: 'page-layout-tab-id',
+ title: 'Test Tab',
+ position: 0,
+ pageLayoutId: 'page-layout-id',
+ pageLayout: { workspaceId: 'workspace-id' },
+ widgets: [],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ deletedAt: null,
+ };
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ PageLayoutWidgetService,
+ {
+ provide: getRepositoryToken(PageLayoutWidgetEntity),
+ useValue: {
+ find: jest.fn(),
+ findOne: jest.fn(),
+ create: jest.fn(),
+ save: jest.fn(),
+ update: jest.fn(),
+ softDelete: jest.fn(),
+ delete: jest.fn(),
+ restore: jest.fn(),
+ },
+ },
+ {
+ provide: PageLayoutTabService,
+ useValue: {
+ findByIdOrThrow: jest.fn(),
+ },
+ },
+ ],
+ }).compile();
+
+ pageLayoutWidgetService = module.get<PageLayoutWidgetService>(
+ PageLayoutWidgetService,
+ );
+ pageLayoutWidgetRepository = module.get<Repository<PageLayoutWidgetEntity>>(
+ getRepositoryToken(PageLayoutWidgetEntity),
+ );
+ pageLayoutTabService =
+ module.get<PageLayoutTabService>(PageLayoutTabService);
+ });
+
+ it('should be defined', () => {
+ expect(pageLayoutWidgetService).toBeDefined();
+ });
+
+ describe('findByPageLayoutTabId', () => {
+ it('should return page layout widgets for a page layout tab id', async () => {
+ const workspaceId = 'workspace-id';
+ const pageLayoutTabId = 'page-layout-tab-id';
+ const expectedWidgets = [mockPageLayoutWidget];
+
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'find')
+ .mockResolvedValue(expectedWidgets);
+
+ const result = await pageLayoutWidgetService.findByPageLayoutTabId(
+ workspaceId,
+ pageLayoutTabId,
+ );
+
+ expect(pageLayoutWidgetRepository.find).toHaveBeenCalledWith({
+ where: {
+ pageLayoutTabId,
+ workspaceId,
+ deletedAt: IsNull(),
+ },
+ order: { createdAt: 'ASC' },
+ });
+ expect(result).toEqual(expectedWidgets);
+ });
+
+ it('should return empty array when no widgets are found', async () => {
+ const workspaceId = 'workspace-id';
+ const pageLayoutTabId = 'page-layout-tab-id';
+
+ jest.spyOn(pageLayoutWidgetRepository, 'find').mockResolvedValue([]);
+
+ const result = await pageLayoutWidgetService.findByPageLayoutTabId(
+ workspaceId,
+ pageLayoutTabId,
+ );
+
+ expect(result).toEqual([]);
+ });
+ });
+
+ describe('findByIdOrThrow', () => {
+ it('should return page layout widget when found', async () => {
+ const id = 'page-layout-widget-id';
+ const workspaceId = 'workspace-id';
+
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'findOne')
+ .mockResolvedValue(mockPageLayoutWidget);
+
+ const result = await pageLayoutWidgetService.findByIdOrThrow(
+ id,
+ workspaceId,
+ );
+
+ expect(pageLayoutWidgetRepository.findOne).toHaveBeenCalledWith({
+ where: {
+ id,
+ workspaceId,
+ deletedAt: IsNull(),
+ },
+ });
+ expect(result).toEqual(mockPageLayoutWidget);
+ });
+
+ it('should throw exception when page layout widget is not found', async () => {
+ const id = 'non-existent-id';
+ const workspaceId = 'workspace-id';
+
+ jest.spyOn(pageLayoutWidgetRepository, 'findOne').mockResolvedValue(null);
+
+ await expect(
+ pageLayoutWidgetService.findByIdOrThrow(id, workspaceId),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.findByIdOrThrow(id, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ );
+ });
+ });
+
+ describe('create', () => {
+ const validPageLayoutWidgetData = {
+ title: 'New Widget',
+ pageLayoutTabId: 'page-layout-tab-id',
+ gridPosition: { row: 0, column: 0, rowSpan: 4, columnSpan: 4 },
+ type: WidgetType.VIEW,
+ };
+
+ it('should create a new page layout widget successfully', async () => {
+ const workspaceId = 'workspace-id';
+
+ jest
+ .spyOn(pageLayoutTabService, 'findByIdOrThrow')
+ .mockResolvedValue(mockPageLayoutTab as any);
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'create')
+ .mockReturnValue(mockPageLayoutWidget);
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'save')
+ .mockResolvedValue(mockPageLayoutWidget);
+
+ const result = await pageLayoutWidgetService.create(
+ validPageLayoutWidgetData,
+ workspaceId,
+ );
+
+ expect(pageLayoutTabService.findByIdOrThrow).toHaveBeenCalledWith(
+ validPageLayoutWidgetData.pageLayoutTabId,
+ workspaceId,
+ );
+ expect(pageLayoutWidgetRepository.create).toHaveBeenCalledWith({
+ ...validPageLayoutWidgetData,
+ workspaceId,
+ });
+ expect(pageLayoutWidgetRepository.save).toHaveBeenCalledWith(
+ mockPageLayoutWidget,
+ );
+ expect(result).toEqual(mockPageLayoutWidget);
+ });
+
+ it('should throw an exception when title is not provided', async () => {
+ const workspaceId = 'workspace-id';
+ const pageLayoutWidgetData = {
+ ...validPageLayoutWidgetData,
+ title: undefined,
+ };
+
+ await expect(
+ pageLayoutWidgetService.create(pageLayoutWidgetData, workspaceId),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.create(pageLayoutWidgetData, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ });
+
+ it('should throw an exception when pageLayoutTabId is not provided', async () => {
+ const workspaceId = 'workspace-id';
+ const pageLayoutWidgetData = {
+ ...validPageLayoutWidgetData,
+ pageLayoutTabId: undefined,
+ };
+
+ await expect(
+ pageLayoutWidgetService.create(pageLayoutWidgetData, workspaceId),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.create(pageLayoutWidgetData, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ });
+
+ it('should throw an exception when gridPosition is not provided', async () => {
+ const workspaceId = 'workspace-id';
+ const pageLayoutWidgetData = {
+ ...validPageLayoutWidgetData,
+ gridPosition: undefined,
+ };
+
+ await expect(
+ pageLayoutWidgetService.create(pageLayoutWidgetData, workspaceId),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.create(pageLayoutWidgetData, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ });
+
+ it('should throw an exception when page layout tab does not exist', async () => {
+ const workspaceId = 'workspace-id';
+
+ jest
+ .spyOn(pageLayoutTabService, 'findByIdOrThrow')
+ .mockRejectedValue(
+ new PageLayoutTabException(
+ 'Page layout tab not found',
+ PageLayoutTabExceptionCode.PAGE_LAYOUT_TAB_NOT_FOUND,
+ ),
+ );
+
+ await expect(
+ pageLayoutWidgetService.create(validPageLayoutWidgetData, workspaceId),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.create(validPageLayoutWidgetData, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ });
+
+ it('should rethrow other errors', async () => {
+ const workspaceId = 'workspace-id';
+ const unexpectedError = new Error('Unexpected error');
+
+ jest
+ .spyOn(pageLayoutTabService, 'findByIdOrThrow')
+ .mockRejectedValue(unexpectedError);
+
+ await expect(
+ pageLayoutWidgetService.create(validPageLayoutWidgetData, workspaceId),
+ ).rejects.toThrow(unexpectedError);
+ });
+ });
+
+ describe('update', () => {
+ it('should update a page layout widget successfully', async () => {
+ const id = 'page-layout-widget-id';
+ const workspaceId = 'workspace-id';
+ const updateData = { title: 'Updated Widget' };
+ const updatedWidget = {
+ ...mockPageLayoutWidget,
+ title: 'Updated Widget',
+ };
+
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'findOne')
+ .mockResolvedValueOnce(mockPageLayoutWidget)
+ .mockResolvedValueOnce(updatedWidget);
+ jest.spyOn(pageLayoutWidgetRepository, 'update').mockResolvedValue({
+ affected: 1,
+ generatedMaps: [],
+ raw: {},
+ });
+
+ const result = await pageLayoutWidgetService.update(
+ id,
+ workspaceId,
+ updateData,
+ );
+
+ expect(pageLayoutWidgetRepository.findOne).toHaveBeenCalledTimes(2);
+ expect(pageLayoutWidgetRepository.findOne).toHaveBeenNthCalledWith(1, {
+ where: {
+ id,
+ workspaceId,
+ deletedAt: IsNull(),
+ },
+ });
+ expect(pageLayoutWidgetRepository.findOne).toHaveBeenNthCalledWith(2, {
+ where: {
+ id,
+ workspaceId,
+ deletedAt: IsNull(),
+ },
+ });
+ expect(pageLayoutWidgetRepository.update).toHaveBeenCalledWith(
+ { id },
+ updateData,
+ );
+ expect(result).toEqual(updatedWidget);
+ });
+
+ it('should throw an exception when widget to update is not found', async () => {
+ const id = 'non-existent-id';
+ const workspaceId = 'workspace-id';
+ const updateData = { title: 'Updated Widget' };
+
+ jest.spyOn(pageLayoutWidgetRepository, 'findOne').mockResolvedValue(null);
+
+ await expect(
+ pageLayoutWidgetService.update(id, workspaceId, updateData),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.update(id, workspaceId, updateData),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ );
+ });
+ });
+
+ describe('delete', () => {
+ it('should soft delete a page layout widget successfully', async () => {
+ const id = 'page-layout-widget-id';
+ const workspaceId = 'workspace-id';
+
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'findOne')
+ .mockResolvedValue(mockPageLayoutWidget);
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'softDelete')
+ .mockResolvedValue({ affected: 1, generatedMaps: [], raw: {} });
+
+ const result = await pageLayoutWidgetService.delete(id, workspaceId);
+
+ expect(pageLayoutWidgetRepository.findOne).toHaveBeenCalledWith({
+ where: {
+ id,
+ workspaceId,
+ deletedAt: IsNull(),
+ },
+ });
+ expect(pageLayoutWidgetRepository.softDelete).toHaveBeenCalledWith(id);
+ expect(result).toEqual(mockPageLayoutWidget);
+ });
+
+ it('should throw an exception when widget to delete is not found', async () => {
+ const id = 'non-existent-id';
+ const workspaceId = 'workspace-id';
+
+ jest.spyOn(pageLayoutWidgetRepository, 'findOne').mockResolvedValue(null);
+
+ await expect(
+ pageLayoutWidgetService.delete(id, workspaceId),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.delete(id, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ );
+ });
+ });
+
+ describe('destroy', () => {
+ it('should permanently delete a page layout widget successfully', async () => {
+ const id = 'page-layout-widget-id';
+ const workspaceId = 'workspace-id';
+
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'findOne')
+ .mockResolvedValue(mockPageLayoutWidget);
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'delete')
+ .mockResolvedValue({ affected: 1, generatedMaps: [], raw: {} });
+
+ const result = await pageLayoutWidgetService.destroy(id, workspaceId);
+
+ expect(pageLayoutWidgetRepository.findOne).toHaveBeenCalledWith({
+ where: {
+ id,
+ workspaceId,
+ },
+ withDeleted: true,
+ });
+ expect(pageLayoutWidgetRepository.delete).toHaveBeenCalledWith(id);
+ expect(result).toBe(true);
+ });
+
+ it('should throw an exception when widget to destroy is not found', async () => {
+ const id = 'non-existent-id';
+ const workspaceId = 'workspace-id';
+
+ jest.spyOn(pageLayoutWidgetRepository, 'findOne').mockResolvedValue(null);
+
+ await expect(
+ pageLayoutWidgetService.destroy(id, workspaceId),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.destroy(id, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ );
+ });
+ });
+
+ describe('restore', () => {
+ it('should restore a deleted page layout widget successfully', async () => {
+ const id = 'page-layout-widget-id';
+ const workspaceId = 'workspace-id';
+ const deletedWidget = { ...mockPageLayoutWidget, deletedAt: new Date() };
+
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'findOne')
+ .mockResolvedValueOnce(deletedWidget) // First call in restore method to check if deleted
+ .mockResolvedValueOnce(mockPageLayoutWidget); // Second call in findByIdOrThrow
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'restore')
+ .mockResolvedValue({ affected: 1, generatedMaps: [], raw: {} });
+
+ const result = await pageLayoutWidgetService.restore(id, workspaceId);
+
+ expect(pageLayoutWidgetRepository.findOne).toHaveBeenCalledTimes(2);
+ expect(pageLayoutWidgetRepository.findOne).toHaveBeenNthCalledWith(1, {
+ select: {
+ id: true,
+ deletedAt: true,
+ pageLayoutTabId: true,
+ },
+ where: {
+ id,
+ workspaceId,
+ },
+ withDeleted: true,
+ });
+ expect(pageLayoutWidgetRepository.findOne).toHaveBeenNthCalledWith(2, {
+ where: {
+ id,
+ workspaceId,
+ deletedAt: IsNull(),
+ },
+ });
+ expect(pageLayoutWidgetRepository.restore).toHaveBeenCalledWith(id);
+ expect(result).toEqual(mockPageLayoutWidget);
+ });
+
+ it('should throw an exception when widget to restore is not found', async () => {
+ const id = 'non-existent-id';
+ const workspaceId = 'workspace-id';
+
+ jest.spyOn(pageLayoutWidgetRepository, 'findOne').mockResolvedValue(null);
+
+ await expect(
+ pageLayoutWidgetService.restore(id, workspaceId),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.restore(id, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ );
+ });
+
+ it('should throw an exception when widget is not deleted', async () => {
+ const id = 'page-layout-widget-id';
+ const workspaceId = 'workspace-id';
+ const notDeletedWidget = { ...mockPageLayoutWidget, deletedAt: null };
+
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'findOne')
+ .mockResolvedValue(notDeletedWidget);
+
+ await expect(
+ pageLayoutWidgetService.restore(id, workspaceId),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.restore(id, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ });
+
+ it('should throw an exception when parent tab is not accessible', async () => {
+ const id = 'page-layout-widget-id';
+ const workspaceId = 'workspace-id';
+ const deletedWidget = {
+ ...mockPageLayoutWidget,
+ deletedAt: new Date(),
+ pageLayoutTabId: 'deleted-tab-id',
+ };
+
+ jest
+ .spyOn(pageLayoutWidgetRepository, 'findOne')
+ .mockResolvedValue(deletedWidget);
+ jest
+ .spyOn(pageLayoutTabService, 'findByIdOrThrow')
+ .mockRejectedValue(
+ new PageLayoutTabException(
+ 'Page layout tab not found',
+ PageLayoutTabExceptionCode.PAGE_LAYOUT_TAB_NOT_FOUND,
+ ),
+ );
+
+ await expect(
+ pageLayoutWidgetService.restore(id, workspaceId),
+ ).rejects.toThrow(PageLayoutWidgetException);
+ await expect(
+ pageLayoutWidgetService.restore(id, workspaceId),
+ ).rejects.toHaveProperty(
+ 'code',
+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,
+ );
+ await expect(
+ pageLayoutWidgetService.restore(id, workspaceId),
+ ).rejects.toHaveProperty(
+ 'message',
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_TAB_NOT_FOUND,
+ ),
+ );
+
+ expect(pageLayoutTabService.findByIdOrThrow).toHaveBeenCalledWith(
+ 'deleted-tab-id',
+ workspaceId,
+ );
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/utils/page-layout-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/page-layout/utils/page-layout-graphql-api-exception-handler.util.ts
index c27d4933f72..9e28d0c2198 100644
--- a/packages/twenty-server/src/engine/core-modules/page-layout/utils/page-layout-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/utils/page-layout-graphql-api-exception-handler.util.ts
@@ -8,6 +8,10 @@ import {
PageLayoutTabException,
PageLayoutTabExceptionCode,
} from 'src/engine/core-modules/page-layout/exceptions/page-layout-tab.exception';
+import {
+ PageLayoutWidgetException,
+ PageLayoutWidgetExceptionCode,
+} from 'src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception';
import {
PageLayoutException,
PageLayoutExceptionCode,
@@ -42,5 +46,19 @@ export const pageLayoutGraphqlApiExceptionHandler = (error: Error) => {
}
}
+ if (error instanceof PageLayoutWidgetException) {
+ switch (error.code) {
+ case PageLayoutWidgetExceptionCode.PAGE_LAYOUT_WIDGET_NOT_FOUND:
+ throw new NotFoundError(error.message);
+ case PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA:
+ throw new UserInputError(error.message, {
+ userFriendlyMessage: error.userFriendlyMessage,
+ });
+ default: {
+ return assertUnreachable(error.code);
+ }
+ }
+ }
+
throw error;
};
diff --git a/packages/twenty-server/src/engine/core-modules/page-layout/utils/page-layout-graphql-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/page-layout/utils/page-layout-graphql-api-exception.filter.ts
index 9246ae503bc..56e0281e36b 100644
--- a/packages/twenty-server/src/engine/core-modules/page-layout/utils/page-layout-graphql-api-exception.filter.ts
+++ b/packages/twenty-server/src/engine/core-modules/page-layout/utils/page-layout-graphql-api-exception.filter.ts
@@ -2,13 +2,17 @@ import { ArgumentsHost, Catch } from '@nestjs/common';
import { GqlExceptionFilter } from '@nestjs/graphql';
import { PageLayoutTabException } from 'src/engine/core-modules/page-layout/exceptions/page-layout-tab.exception';
+import { PageLayoutWidgetException } from 'src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception';
import { PageLayoutException } from 'src/engine/core-modules/page-layout/exceptions/page-layout.exception';
import { pageLayoutGraphqlApiExceptionHandler } from 'src/engine/core-modules/page-layout/utils/page-layout-graphql-api-exception-handler.util';
-@Catch(PageLayoutException, PageLayoutTabException)
+@Catch(PageLayoutException, PageLayoutTabException, PageLayoutWidgetException)
export class PageLayoutGraphqlApiExceptionFilter implements GqlExceptionFilter {
catch(
- exception: PageLayoutException | PageLayoutTabException,
+ exception:
+ | PageLayoutException
+ | PageLayoutTabException
+ | PageLayoutWidgetException,
_host: ArgumentsHost,
) {
return pageLayoutGraphqlApiExceptionHandler(exception);
diff --git a/packages/twenty-server/test/integration/constants/page-layout-gql-fields.constants.ts b/packages/twenty-server/test/integration/constants/page-layout-gql-fields.constants.ts
index c51445808b6..e0095fd7b12 100644
--- a/packages/twenty-server/test/integration/constants/page-layout-gql-fields.constants.ts
+++ b/packages/twenty-server/test/integration/constants/page-layout-gql-fields.constants.ts
@@ -1,7 +1,6 @@
export const PAGE_LAYOUT_GQL_FIELDS = `
id
name
- workspaceId
type
objectMetadataId
createdAt
@@ -11,7 +10,6 @@ export const PAGE_LAYOUT_GQL_FIELDS = `
export const PAGE_LAYOUT_TAB_GQL_FIELDS = `
id
- workspaceId
title
position
pageLayoutId
@@ -19,3 +17,21 @@ export const PAGE_LAYOUT_TAB_GQL_FIELDS = `
updatedAt
deletedAt
`;
+
+export const PAGE_LAYOUT_WIDGET_GQL_FIELDS = `
+ id
+ title
+ type
+ pageLayoutTabId
+ objectMetadataId
+ gridPosition {
+ row
+ column
+ rowSpan
+ columnSpan
+ }
+ configuration
+ createdAt
+ updatedAt
+ deletedAt
+`;
diff --git a/packages/twenty-server/test/integration/constants/test-page-layout-widget-ids.constants.ts b/packages/twenty-server/test/integration/constants/test-page-layout-widget-ids.constants.ts
new file mode 100644
index 00000000000..7ce6998dd8d
--- /dev/null
+++ b/packages/twenty-server/test/integration/constants/test-page-layout-widget-ids.constants.ts
@@ -0,0 +1,7 @@
+export const TEST_PAGE_LAYOUT_WIDGET_1_ID =
+ '20202020-1c8f-4b5a-8f08-82c1e17f9b04';
+export const TEST_PAGE_LAYOUT_WIDGET_2_ID =
+ '20202020-6ee6-4ccd-a58b-810e55fee801';
+
+export const TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID =
+ '20202020-8068-4c0b-a4c9-d029102d3679';
diff --git a/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-resolver.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-resolver.integration-spec.ts
index 64cb840d14c..70e6d584c89 100644
--- a/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-resolver.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-resolver.integration-spec.ts
@@ -439,7 +439,6 @@ describe('Page Layout Resolver', () => {
id
name
type
- workspaceId
createdAt
updatedAt
deletedAt
diff --git a/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-tab-resolver.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-tab-resolver.integration-spec.ts
index 7fef7bb9f25..0c029d1b59d 100644
--- a/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-tab-resolver.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-tab-resolver.integration-spec.ts
@@ -1,5 +1,6 @@
import { TEST_NOT_EXISTING_PAGE_LAYOUT_TAB_ID } from 'test/integration/constants/test-page-layout-tab-ids.constants';
import { createPageLayoutTabOperationFactory } from 'test/integration/graphql/utils/create-page-layout-tab-operation-factory.util';
+import { deletePageLayoutOperationFactory } from 'test/integration/graphql/utils/delete-page-layout-operation-factory.util';
import { deletePageLayoutTabOperationFactory } from 'test/integration/graphql/utils/delete-page-layout-tab-operation-factory.util';
import { destroyPageLayoutTabOperationFactory } from 'test/integration/graphql/utils/destroy-page-layout-tab-operation-factory.util';
import { findPageLayoutTabOperationFactory } from 'test/integration/graphql/utils/find-page-layout-tab-operation-factory.util';
@@ -402,5 +403,46 @@ describe('Page Layout Tab Resolver', () => {
),
);
});
+
+ it('should throw an error when restoring tab with deleted parent page layout', async () => {
+ const separatePageLayout = await createTestPageLayoutWithGraphQL({
+ name: 'Page Layout for Tab Restore Test',
+ type: PageLayoutType.RECORD_PAGE,
+ objectMetadataId: testObjectMetadataId,
+ });
+
+ const input = {
+ title: 'Tab with Deleted Page Layout',
+ pageLayoutId: separatePageLayout.id,
+ position: 0,
+ };
+
+ const tab = await createTestPageLayoutTabWithGraphQL(input);
+
+ const deleteTabOperation = deletePageLayoutTabOperationFactory({
+ pageLayoutTabId: tab.id,
+ });
+
+ await makeGraphqlAPIRequest(deleteTabOperation);
+
+ const deletePageLayoutOperation = deletePageLayoutOperationFactory({
+ pageLayoutId: separatePageLayout.id,
+ });
+
+ await makeGraphqlAPIRequest(deletePageLayoutOperation);
+
+ const restoreOperation = restorePageLayoutTabOperationFactory({
+ pageLayoutTabId: tab.id,
+ });
+ const restoreResponse = await makeGraphqlAPIRequest(restoreOperation);
+
+ assertGraphQLErrorResponse(
+ restoreResponse,
+ ErrorCode.BAD_USER_INPUT,
+ generatePageLayoutTabExceptionMessage(
+ PageLayoutTabExceptionMessageKey.PAGE_LAYOUT_NOT_FOUND,
+ ),
+ );
+ });
});
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-widget-resolver.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-widget-resolver.integration-spec.ts
new file mode 100644
index 00000000000..0fbe0fb2bc7
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-widget-resolver.integration-spec.ts
@@ -0,0 +1,491 @@
+import { TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID } from 'test/integration/constants/test-page-layout-widget-ids.constants';
+import { createPageLayoutWidgetOperationFactory } from 'test/integration/graphql/utils/create-page-layout-widget-operation-factory.util';
+import { deletePageLayoutTabOperationFactory } from 'test/integration/graphql/utils/delete-page-layout-tab-operation-factory.util';
+import { deletePageLayoutWidgetOperationFactory } from 'test/integration/graphql/utils/delete-page-layout-widget-operation-factory.util';
+import { destroyPageLayoutWidgetOperationFactory } from 'test/integration/graphql/utils/destroy-page-layout-widget-operation-factory.util';
+import { findPageLayoutWidgetOperationFactory } from 'test/integration/graphql/utils/find-page-layout-widget-operation-factory.util';
+import { findPageLayoutWidgetsOperationFactory } from 'test/integration/graphql/utils/find-page-layout-widgets-operation-factory.util';
+import {
+ assertGraphQLErrorResponse,
+ assertGraphQLSuccessfulResponse,
+} from 'test/integration/graphql/utils/graphql-test-assertions.util';
+import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import {
+ cleanupPageLayoutRecordsWithGraphQL,
+ createTestPageLayoutWithGraphQL,
+} from 'test/integration/graphql/utils/page-layout-graphql.util';
+import { createTestPageLayoutTabWithGraphQL } from 'test/integration/graphql/utils/page-layout-tab-graphql.util';
+import {
+ cleanupPageLayoutWidgetRecordsWithGraphQL,
+ createTestPageLayoutWidgetWithGraphQL,
+} from 'test/integration/graphql/utils/page-layout-widget-graphql.util';
+import { restorePageLayoutWidgetOperationFactory } from 'test/integration/graphql/utils/restore-page-layout-widget-operation-factory.util';
+import { updatePageLayoutWidgetOperationFactory } from 'test/integration/graphql/utils/update-page-layout-widget-operation-factory.util';
+import { createOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/create-one-object-metadata.util';
+import { deleteOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/delete-one-object-metadata.util';
+import { assertPageLayoutWidgetStructure } from 'test/integration/utils/page-layout-widget-test.util';
+
+import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { PageLayoutType } from 'src/engine/core-modules/page-layout/enums/page-layout-type.enum';
+import { WidgetType } from 'src/engine/core-modules/page-layout/enums/widget-type.enum';
+import {
+ PageLayoutWidgetExceptionMessageKey,
+ generatePageLayoutWidgetExceptionMessage,
+} from 'src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception';
+
+describe('Page Layout Widget Resolver', () => {
+ let testObjectMetadataId: string;
+ let testPageLayoutId: string;
+ let testPageLayoutTabId: string;
+
+ beforeAll(async () => {
+ const {
+ data: {
+ createOneObject: { id: objectMetadataId },
+ },
+ } = await createOneObjectMetadata({
+ input: {
+ nameSingular: 'myTestPageLayoutWidgetObject',
+ namePlural: 'myTestPageLayoutWidgetObjects',
+ labelSingular: 'My Test Page Layout Widget Object',
+ labelPlural: 'My Test Page Layout Widget Objects',
+ icon: 'IconWidget',
+ },
+ });
+
+ testObjectMetadataId = objectMetadataId;
+
+ const pageLayout = await createTestPageLayoutWithGraphQL({
+ name: 'Test Page Layout for Widgets',
+ type: PageLayoutType.RECORD_PAGE,
+ objectMetadataId: testObjectMetadataId,
+ });
+
+ testPageLayoutId = pageLayout.id;
+
+ const pageLayoutTab = await createTestPageLayoutTabWithGraphQL({
+ title: 'Test Tab for Widgets',
+ position: 0,
+ pageLayoutId: testPageLayoutId,
+ });
+
+ testPageLayoutTabId = pageLayoutTab.id;
+ });
+
+ afterAll(async () => {
+ await cleanupPageLayoutRecordsWithGraphQL();
+ await deleteOneObjectMetadata({
+ input: { idToDelete: testObjectMetadataId },
+ });
+ });
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ afterEach(async () => {
+ await cleanupPageLayoutWidgetRecordsWithGraphQL(testPageLayoutTabId);
+ });
+
+ describe('getPageLayoutWidgets', () => {
+ it('should return empty array when no page layout widgets exist', async () => {
+ const operation = findPageLayoutWidgetsOperationFactory({
+ pageLayoutTabId: testPageLayoutTabId,
+ });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLSuccessfulResponse(response);
+ expect(response.body.data.getPageLayoutWidgets).toEqual([]);
+ });
+
+ it('should return all page layout widgets for a specific page layout tab', async () => {
+ const widgetTitle1 = 'Widget 1';
+ const widgetTitle2 = 'Widget 2';
+
+ await Promise.all([
+ createTestPageLayoutWidgetWithGraphQL({
+ title: widgetTitle1,
+ type: WidgetType.VIEW,
+ pageLayoutTabId: testPageLayoutTabId,
+ gridPosition: { row: 0, column: 0, rowSpan: 2, columnSpan: 3 },
+ }),
+ createTestPageLayoutWidgetWithGraphQL({
+ title: widgetTitle2,
+ type: WidgetType.GRAPH,
+ pageLayoutTabId: testPageLayoutTabId,
+ gridPosition: { row: 0, column: 3, rowSpan: 1, columnSpan: 2 },
+ }),
+ ]);
+
+ const operation = findPageLayoutWidgetsOperationFactory({
+ pageLayoutTabId: testPageLayoutTabId,
+ });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLSuccessfulResponse(response);
+ expect(response.body.data.getPageLayoutWidgets).toHaveLength(2);
+
+ const widgets = response.body.data.getPageLayoutWidgets;
+
+ assertPageLayoutWidgetStructure(widgets[0], {
+ title: widgetTitle1,
+ type: WidgetType.VIEW,
+ pageLayoutTabId: testPageLayoutTabId,
+ });
+ assertPageLayoutWidgetStructure(widgets[1], {
+ title: widgetTitle2,
+ type: WidgetType.GRAPH,
+ pageLayoutTabId: testPageLayoutTabId,
+ });
+ });
+ });
+
+ describe('getPageLayoutWidget', () => {
+ it('should throw when page layout widget does not exist', async () => {
+ const operation = findPageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLErrorResponse(
+ response,
+ ErrorCode.NOT_FOUND,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ ),
+ );
+ });
+
+ it('should return page layout widget when it exists', async () => {
+ const widgetTitle = 'Widget';
+
+ const input = {
+ title: widgetTitle,
+ type: WidgetType.FIELDS,
+ pageLayoutTabId: testPageLayoutTabId,
+ objectMetadataId: testObjectMetadataId,
+ gridPosition: { row: 1, column: 1, rowSpan: 1, columnSpan: 2 },
+ configuration: {},
+ };
+
+ const widget = await createTestPageLayoutWidgetWithGraphQL(input);
+
+ const operation = findPageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLSuccessfulResponse(response);
+ assertPageLayoutWidgetStructure(
+ response.body.data.getPageLayoutWidget,
+ input,
+ );
+ });
+ });
+
+ describe('createPageLayoutWidget', () => {
+ it('should create a new page layout widget with all properties', async () => {
+ const input = {
+ title: 'New Widget',
+ type: WidgetType.FIELDS,
+ pageLayoutTabId: testPageLayoutTabId,
+ objectMetadataId: testObjectMetadataId,
+ gridPosition: { row: 2, column: 1, rowSpan: 3, columnSpan: 4 },
+ configuration: { theme: 'dark', showBorders: true },
+ };
+
+ const operation = createPageLayoutWidgetOperationFactory({ data: input });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLSuccessfulResponse(response);
+
+ const createdWidget = response.body.data.createPageLayoutWidget;
+
+ assertPageLayoutWidgetStructure(createdWidget, input);
+ });
+
+ it('should create a page layout widget with minimum required fields', async () => {
+ const input = {
+ title: 'Widget',
+ type: WidgetType.VIEW,
+ pageLayoutTabId: testPageLayoutTabId,
+ gridPosition: { row: 0, column: 0, rowSpan: 1, columnSpan: 1 },
+ };
+
+ const operation = createPageLayoutWidgetOperationFactory({ data: input });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLSuccessfulResponse(response);
+
+ const createdWidget = response.body.data.createPageLayoutWidget;
+
+ assertPageLayoutWidgetStructure(createdWidget, input);
+ });
+ });
+
+ describe('updatePageLayoutWidget', () => {
+ it('should update an existing page layout widget', async () => {
+ const widget = await createTestPageLayoutWidgetWithGraphQL({
+ title: 'Widget',
+ type: WidgetType.VIEW,
+ pageLayoutTabId: testPageLayoutTabId,
+ gridPosition: { row: 0, column: 0, rowSpan: 1, columnSpan: 1 },
+ });
+
+ const updateInput = {
+ title: 'Updated Widget',
+ type: WidgetType.IFRAME,
+ gridPosition: { row: 1, column: 2, rowSpan: 2, columnSpan: 3 },
+ configuration: { url: 'https://twenty.com' },
+ };
+
+ const operation = updatePageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ data: updateInput,
+ });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLSuccessfulResponse(response);
+ assertPageLayoutWidgetStructure(
+ response.body.data.updatePageLayoutWidget,
+ updateInput,
+ );
+ });
+
+ it('should update only provided fields', async () => {
+ const widget = await createTestPageLayoutWidgetWithGraphQL({
+ title: 'Widget',
+ type: WidgetType.VIEW,
+ pageLayoutTabId: testPageLayoutTabId,
+ gridPosition: { row: 0, column: 0, rowSpan: 1, columnSpan: 1 },
+ });
+
+ const updateInput = {
+ title: 'Updated Widget',
+ };
+
+ const operation = updatePageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ data: updateInput,
+ });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLSuccessfulResponse(response);
+ assertPageLayoutWidgetStructure(
+ response.body.data.updatePageLayoutWidget,
+ updateInput,
+ );
+ });
+
+ it('should throw error when updating non-existent page layout widget', async () => {
+ const operation = updatePageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ data: { title: 'Non-existent Widget' },
+ });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLErrorResponse(
+ response,
+ ErrorCode.NOT_FOUND,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ ),
+ );
+ });
+ });
+
+ describe('deletePageLayoutWidget', () => {
+ it('should delete an existing page layout widget (soft delete)', async () => {
+ const input = {
+ title: 'Widget',
+ type: WidgetType.VIEW,
+ pageLayoutTabId: testPageLayoutTabId,
+ gridPosition: { row: 0, column: 0, rowSpan: 1, columnSpan: 1 },
+ };
+
+ const widget = await createTestPageLayoutWidgetWithGraphQL(input);
+
+ const deleteOperation = deletePageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ });
+ const deleteResponse = await makeGraphqlAPIRequest(deleteOperation);
+
+ assertGraphQLSuccessfulResponse(deleteResponse);
+ assertPageLayoutWidgetStructure(
+ deleteResponse.body.data.deletePageLayoutWidget,
+ input,
+ );
+
+ const getOperation = findPageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ });
+ const getResponse = await makeGraphqlAPIRequest(getOperation);
+
+ assertGraphQLErrorResponse(
+ getResponse,
+ ErrorCode.NOT_FOUND,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ widget.id,
+ ),
+ );
+ });
+
+ it('should throw an error when deleting non-existent page layout widget', async () => {
+ const operation = deletePageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLErrorResponse(
+ response,
+ ErrorCode.NOT_FOUND,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ ),
+ );
+ });
+ });
+
+ describe('destroyPageLayoutWidget', () => {
+ it('should destroy an existing page layout widget (hard delete)', async () => {
+ const input = {
+ title: 'Widget',
+ type: WidgetType.VIEW,
+ pageLayoutTabId: testPageLayoutTabId,
+ gridPosition: { row: 0, column: 0, rowSpan: 1, columnSpan: 1 },
+ };
+
+ const widget = await createTestPageLayoutWidgetWithGraphQL(input);
+
+ const destroyOperation = destroyPageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ });
+ const destroyResponse = await makeGraphqlAPIRequest(destroyOperation);
+
+ assertGraphQLSuccessfulResponse(destroyResponse);
+ expect(destroyResponse.body.data.destroyPageLayoutWidget).toBe(true);
+ });
+
+ it('should throw an error when destroying non-existent page layout widget', async () => {
+ const operation = destroyPageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLErrorResponse(
+ response,
+ ErrorCode.NOT_FOUND,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ ),
+ );
+ });
+ });
+
+ describe('restorePageLayoutWidget', () => {
+ it('should restore a soft deleted page layout widget', async () => {
+ const input = {
+ title: 'Widget',
+ type: WidgetType.GRAPH,
+ pageLayoutTabId: testPageLayoutTabId,
+ gridPosition: { row: 2, column: 1, rowSpan: 1, columnSpan: 2 },
+ configuration: {},
+ };
+
+ const widget = await createTestPageLayoutWidgetWithGraphQL(input);
+
+ const deleteOperation = deletePageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ });
+ const deleteResponse = await makeGraphqlAPIRequest(deleteOperation);
+
+ assertGraphQLSuccessfulResponse(deleteResponse);
+
+ const restoreOperation = restorePageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ });
+ const restoreResponse = await makeGraphqlAPIRequest(restoreOperation);
+
+ assertGraphQLSuccessfulResponse(restoreResponse);
+ assertPageLayoutWidgetStructure(
+ restoreResponse.body.data.restorePageLayoutWidget,
+ input,
+ );
+
+ const getOperation = findPageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ });
+ const getResponse = await makeGraphqlAPIRequest(getOperation);
+
+ assertGraphQLSuccessfulResponse(getResponse);
+ assertPageLayoutWidgetStructure(
+ getResponse.body.data.getPageLayoutWidget,
+ input,
+ );
+ });
+
+ it('should throw an error when restoring non-existent page layout widget', async () => {
+ const operation = restorePageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ assertGraphQLErrorResponse(
+ response,
+ ErrorCode.NOT_FOUND,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ ),
+ );
+ });
+
+ it('should throw an error when restoring widget with deleted parent tab', async () => {
+ const separateTab = await createTestPageLayoutTabWithGraphQL({
+ title: 'Tab for Widget Restore Test',
+ pageLayoutId: testPageLayoutId,
+ position: 1,
+ });
+
+ const input = {
+ title: 'Widget with Deleted Tab',
+ type: WidgetType.GRAPH,
+ pageLayoutTabId: separateTab.id,
+ gridPosition: { row: 1, column: 1, rowSpan: 1, columnSpan: 1 },
+ configuration: {},
+ };
+
+ const widget = await createTestPageLayoutWidgetWithGraphQL(input);
+
+ const deleteWidgetOperation = deletePageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ });
+
+ await makeGraphqlAPIRequest(deleteWidgetOperation);
+
+ const deleteTabOperation = deletePageLayoutTabOperationFactory({
+ pageLayoutTabId: separateTab.id,
+ });
+
+ await makeGraphqlAPIRequest(deleteTabOperation);
+
+ const restoreOperation = restorePageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: widget.id,
+ });
+ const restoreResponse = await makeGraphqlAPIRequest(restoreOperation);
+
+ assertGraphQLErrorResponse(
+ restoreResponse,
+ ErrorCode.BAD_USER_INPUT,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_TAB_NOT_FOUND,
+ ),
+ );
+ });
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/utils/create-page-layout-widget-operation-factory.util.ts b/packages/twenty-server/test/integration/graphql/utils/create-page-layout-widget-operation-factory.util.ts
new file mode 100644
index 00000000000..6fe920341d5
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/create-page-layout-widget-operation-factory.util.ts
@@ -0,0 +1,25 @@
+import gql from 'graphql-tag';
+import { PAGE_LAYOUT_WIDGET_GQL_FIELDS } from 'test/integration/constants/page-layout-gql-fields.constants';
+
+import { type CreatePageLayoutWidgetInput } from 'src/engine/core-modules/page-layout/dtos/inputs/create-page-layout-widget.input';
+
+type CreatePageLayoutWidgetOperationFactoryParams = {
+ gqlFields?: string;
+ data: CreatePageLayoutWidgetInput;
+};
+
+export const createPageLayoutWidgetOperationFactory = ({
+ gqlFields = PAGE_LAYOUT_WIDGET_GQL_FIELDS,
+ data,
+}: CreatePageLayoutWidgetOperationFactoryParams) => ({
+ query: gql`
+ mutation CreatePageLayoutWidget($input: CreatePageLayoutWidgetInput!) {
+ createPageLayoutWidget(input: $input) {
+ ${gqlFields}
+ }
+ }
+ `,
+ variables: {
+ input: data,
+ },
+});
diff --git a/packages/twenty-server/test/integration/graphql/utils/delete-page-layout-widget-operation-factory.util.ts b/packages/twenty-server/test/integration/graphql/utils/delete-page-layout-widget-operation-factory.util.ts
new file mode 100644
index 00000000000..1a3e1d2f196
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/delete-page-layout-widget-operation-factory.util.ts
@@ -0,0 +1,23 @@
+import gql from 'graphql-tag';
+import { PAGE_LAYOUT_WIDGET_GQL_FIELDS } from 'test/integration/constants/page-layout-gql-fields.constants';
+
+type DeletePageLayoutWidgetOperationFactoryParams = {
+ gqlFields?: string;
+ pageLayoutWidgetId: string;
+};
+
+export const deletePageLayoutWidgetOperationFactory = ({
+ gqlFields = PAGE_LAYOUT_WIDGET_GQL_FIELDS,
+ pageLayoutWidgetId,
+}: DeletePageLayoutWidgetOperationFactoryParams) => ({
+ query: gql`
+ mutation DeletePageLayoutWidget($id: String!) {
+ deletePageLayoutWidget(id: $id) {
+ ${gqlFields}
+ }
+ }
+ `,
+ variables: {
+ id: pageLayoutWidgetId,
+ },
+});
diff --git a/packages/twenty-server/test/integration/graphql/utils/destroy-page-layout-widget-operation-factory.util.ts b/packages/twenty-server/test/integration/graphql/utils/destroy-page-layout-widget-operation-factory.util.ts
new file mode 100644
index 00000000000..fee75d0e449
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/destroy-page-layout-widget-operation-factory.util.ts
@@ -0,0 +1,18 @@
+import gql from 'graphql-tag';
+
+type DestroyPageLayoutWidgetOperationFactoryParams = {
+ pageLayoutWidgetId: string;
+};
+
+export const destroyPageLayoutWidgetOperationFactory = ({
+ pageLayoutWidgetId,
+}: DestroyPageLayoutWidgetOperationFactoryParams) => ({
+ query: gql`
+ mutation DestroyPageLayoutWidget($id: String!) {
+ destroyPageLayoutWidget(id: $id)
+ }
+ `,
+ variables: {
+ id: pageLayoutWidgetId,
+ },
+});
diff --git a/packages/twenty-server/test/integration/graphql/utils/find-page-layout-widget-operation-factory.util.ts b/packages/twenty-server/test/integration/graphql/utils/find-page-layout-widget-operation-factory.util.ts
new file mode 100644
index 00000000000..d36d371f68d
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/find-page-layout-widget-operation-factory.util.ts
@@ -0,0 +1,23 @@
+import gql from 'graphql-tag';
+import { PAGE_LAYOUT_WIDGET_GQL_FIELDS } from 'test/integration/constants/page-layout-gql-fields.constants';
+
+type FindPageLayoutWidgetOperationFactoryParams = {
+ gqlFields?: string;
+ pageLayoutWidgetId: string;
+};
+
+export const findPageLayoutWidgetOperationFactory = ({
+ gqlFields = PAGE_LAYOUT_WIDGET_GQL_FIELDS,
+ pageLayoutWidgetId,
+}: FindPageLayoutWidgetOperationFactoryParams) => ({
+ query: gql`
+ query GetPageLayoutWidget($id: String!) {
+ getPageLayoutWidget(id: $id) {
+ ${gqlFields}
+ }
+ }
+ `,
+ variables: {
+ id: pageLayoutWidgetId,
+ },
+});
diff --git a/packages/twenty-server/test/integration/graphql/utils/find-page-layout-widgets-operation-factory.util.ts b/packages/twenty-server/test/integration/graphql/utils/find-page-layout-widgets-operation-factory.util.ts
new file mode 100644
index 00000000000..45dfdafa8fa
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/find-page-layout-widgets-operation-factory.util.ts
@@ -0,0 +1,23 @@
+import gql from 'graphql-tag';
+import { PAGE_LAYOUT_WIDGET_GQL_FIELDS } from 'test/integration/constants/page-layout-gql-fields.constants';
+
+type FindPageLayoutWidgetsOperationFactoryParams = {
+ gqlFields?: string;
+ pageLayoutTabId: string;
+};
+
+export const findPageLayoutWidgetsOperationFactory = ({
+ gqlFields = PAGE_LAYOUT_WIDGET_GQL_FIELDS,
+ pageLayoutTabId,
+}: FindPageLayoutWidgetsOperationFactoryParams) => ({
+ query: gql`
+ query GetPageLayoutWidgets($pageLayoutTabId: String!) {
+ getPageLayoutWidgets(pageLayoutTabId: $pageLayoutTabId) {
+ ${gqlFields}
+ }
+ }
+ `,
+ variables: {
+ pageLayoutTabId,
+ },
+});
diff --git a/packages/twenty-server/test/integration/graphql/utils/graphql-test-assertions.util.ts b/packages/twenty-server/test/integration/graphql/utils/graphql-test-assertions.util.ts
index e94ca407d2c..a1fb797bf9e 100644
--- a/packages/twenty-server/test/integration/graphql/utils/graphql-test-assertions.util.ts
+++ b/packages/twenty-server/test/integration/graphql/utils/graphql-test-assertions.util.ts
@@ -36,7 +36,7 @@ export const assertGraphQLErrorResponse = <T extends Record<string, unknown>>(
expect(response.body.errors).toHaveLength(1);
if (expectedErrorCode && response.body.errors) {
- expect(response.body.errors[0].extensions.code).toBe(expectedErrorCode);
+ expect(response.body.errors[0].extensions?.code).toBe(expectedErrorCode);
}
if (expectedErrorMessage && response.body.errors) {
diff --git a/packages/twenty-server/test/integration/graphql/utils/page-layout-widget-graphql.util.ts b/packages/twenty-server/test/integration/graphql/utils/page-layout-widget-graphql.util.ts
new file mode 100644
index 00000000000..b3d65c43a15
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/page-layout-widget-graphql.util.ts
@@ -0,0 +1,78 @@
+import { type GraphQLResponse } from 'test/integration/graphql/utils/graphql-test-assertions.util';
+import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+
+import { type PageLayoutWidgetEntity } from 'src/engine/core-modules/page-layout/entities/page-layout-widget.entity';
+import { WidgetType } from 'src/engine/core-modules/page-layout/enums/widget-type.enum';
+
+import { createPageLayoutWidgetOperationFactory } from './create-page-layout-widget-operation-factory.util';
+import { destroyPageLayoutWidgetOperationFactory } from './destroy-page-layout-widget-operation-factory.util';
+import { findPageLayoutWidgetsOperationFactory } from './find-page-layout-widgets-operation-factory.util';
+
+interface CreatePageLayoutWidgetResponse extends Record<string, unknown> {
+ createPageLayoutWidget: PageLayoutWidgetEntity;
+}
+
+export const createTestPageLayoutWidgetWithGraphQL = async (data: {
+ title: string;
+ type?: WidgetType;
+ pageLayoutTabId: string;
+ objectMetadataId?: string | null;
+ gridPosition?: {
+ row: number;
+ column: number;
+ rowSpan: number;
+ columnSpan: number;
+ };
+ configuration?: Record<string, unknown> | null;
+}): Promise<PageLayoutWidgetEntity> => {
+ const operation = createPageLayoutWidgetOperationFactory({
+ data: {
+ title: data.title,
+ type: data.type || WidgetType.VIEW,
+ pageLayoutTabId: data.pageLayoutTabId,
+ objectMetadataId: data.objectMetadataId || null,
+ gridPosition: data.gridPosition || {
+ row: 0,
+ column: 0,
+ rowSpan: 1,
+ columnSpan: 1,
+ },
+ configuration: data.configuration || null,
+ },
+ });
+
+ const response = (await makeGraphqlAPIRequest(
+ operation,
+ )) as GraphQLResponse<CreatePageLayoutWidgetResponse>;
+
+ if (response.body.errors) {
+ throw new Error(
+ `Failed to create test page layout widget: ${JSON.stringify(response.body.errors)}`,
+ );
+ }
+
+ if (!response.body.data) {
+ throw new Error(
+ 'No data returned from createTestPageLayoutWidgetWithGraphQL',
+ );
+ }
+
+ return response.body.data.createPageLayoutWidget;
+};
+
+export const cleanupPageLayoutWidgetRecordsWithGraphQL = async (
+ pageLayoutTabId: string,
+): Promise<void> => {
+ const operation = findPageLayoutWidgetsOperationFactory({ pageLayoutTabId });
+ const response = await makeGraphqlAPIRequest(operation);
+
+ if (response.body.data?.getPageLayoutWidgets) {
+ for (const pageLayoutWidget of response.body.data.getPageLayoutWidgets) {
+ const destroyOperation = destroyPageLayoutWidgetOperationFactory({
+ pageLayoutWidgetId: pageLayoutWidget.id,
+ });
+
+ await makeGraphqlAPIRequest(destroyOperation);
+ }
+ }
+};
diff --git a/packages/twenty-server/test/integration/graphql/utils/restore-page-layout-widget-operation-factory.util.ts b/packages/twenty-server/test/integration/graphql/utils/restore-page-layout-widget-operation-factory.util.ts
new file mode 100644
index 00000000000..49e083adb9f
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/restore-page-layout-widget-operation-factory.util.ts
@@ -0,0 +1,23 @@
+import gql from 'graphql-tag';
+import { PAGE_LAYOUT_WIDGET_GQL_FIELDS } from 'test/integration/constants/page-layout-gql-fields.constants';
+
+type RestorePageLayoutWidgetOperationFactoryParams = {
+ gqlFields?: string;
+ pageLayoutWidgetId: string;
+};
+
+export const restorePageLayoutWidgetOperationFactory = ({
+ gqlFields = PAGE_LAYOUT_WIDGET_GQL_FIELDS,
+ pageLayoutWidgetId,
+}: RestorePageLayoutWidgetOperationFactoryParams) => ({
+ query: gql`
+ mutation RestorePageLayoutWidget($id: String!) {
+ restorePageLayoutWidget(id: $id) {
+ ${gqlFields}
+ }
+ }
+ `,
+ variables: {
+ id: pageLayoutWidgetId,
+ },
+});
diff --git a/packages/twenty-server/test/integration/graphql/utils/update-page-layout-widget-operation-factory.util.ts b/packages/twenty-server/test/integration/graphql/utils/update-page-layout-widget-operation-factory.util.ts
new file mode 100644
index 00000000000..d95f4def10b
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/update-page-layout-widget-operation-factory.util.ts
@@ -0,0 +1,28 @@
+import gql from 'graphql-tag';
+import { PAGE_LAYOUT_WIDGET_GQL_FIELDS } from 'test/integration/constants/page-layout-gql-fields.constants';
+
+import { type UpdatePageLayoutWidgetInput } from 'src/engine/core-modules/page-layout/dtos/inputs/update-page-layout-widget.input';
+
+type UpdatePageLayoutWidgetOperationFactoryParams = {
+ gqlFields?: string;
+ pageLayoutWidgetId: string;
+ data: UpdatePageLayoutWidgetInput;
+};
+
+export const updatePageLayoutWidgetOperationFactory = ({
+ gqlFields = PAGE_LAYOUT_WIDGET_GQL_FIELDS,
+ pageLayoutWidgetId,
+ data,
+}: UpdatePageLayoutWidgetOperationFactoryParams) => ({
+ query: gql`
+ mutation UpdatePageLayoutWidget($id: String!, $input: UpdatePageLayoutWidgetInput!) {
+ updatePageLayoutWidget(id: $id, input: $input) {
+ ${gqlFields}
+ }
+ }
+ `,
+ variables: {
+ id: pageLayoutWidgetId,
+ input: data,
+ },
+});
diff --git a/packages/twenty-server/test/integration/rest/suites/page-layout-widget.integration-spec.ts b/packages/twenty-server/test/integration/rest/suites/page-layout-widget.integration-spec.ts
new file mode 100644
index 00000000000..91580624b3b
--- /dev/null
+++ b/packages/twenty-server/test/integration/rest/suites/page-layout-widget.integration-spec.ts
@@ -0,0 +1,493 @@
+import { TEST_NOT_EXISTING_PAGE_LAYOUT_TAB_ID } from 'test/integration/constants/test-page-layout-tab-ids.constants';
+import { TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID } from 'test/integration/constants/test-page-layout-widget-ids.constants';
+import { createOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/create-one-object-metadata.util';
+import { deleteOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/delete-one-object-metadata.util';
+import { makeRestAPIRequest } from 'test/integration/rest/utils/make-rest-api-request.util';
+import {
+ createTestPageLayoutWithRestApi,
+ deleteTestPageLayoutWithRestApi,
+} from 'test/integration/rest/utils/page-layout-rest-api.util';
+import {
+ createTestPageLayoutTabWithRestApi,
+ deleteTestPageLayoutTabWithRestApi,
+} from 'test/integration/rest/utils/page-layout-tab-rest-api.util';
+import {
+ createTestPageLayoutWidgetWithRestApi,
+ deleteTestPageLayoutWidgetWithRestApi,
+} from 'test/integration/rest/utils/page-layout-widget-rest-api.util';
+import {
+ assertRestApiErrorResponse,
+ assertRestApiSuccessfulResponse,
+} from 'test/integration/rest/utils/rest-test-assertions.util';
+import { generateRecordName } from 'test/integration/utils/generate-record-name';
+import {
+ assertPageLayoutWidgetStructure,
+ cleanupPageLayoutWidgetRecords,
+} from 'test/integration/utils/page-layout-widget-test.util';
+
+import { PageLayoutType } from 'src/engine/core-modules/page-layout/enums/page-layout-type.enum';
+import { WidgetType } from 'src/engine/core-modules/page-layout/enums/widget-type.enum';
+import {
+ PageLayoutWidgetExceptionMessageKey,
+ generatePageLayoutWidgetExceptionMessage,
+} from 'src/engine/core-modules/page-layout/exceptions/page-layout-widget.exception';
+
+describe('Page Layout Widget REST API', () => {
+ let testObjectMetadataId: string;
+ let testPageLayoutId: string;
+ let testPageLayoutTabId: string;
+
+ beforeAll(async () => {
+ const {
+ data: {
+ createOneObject: { id: objectMetadataId },
+ },
+ } = await createOneObjectMetadata({
+ input: {
+ nameSingular: 'myTestPageLayoutWidgetObject',
+ namePlural: 'myTestPageLayoutWidgetObjects',
+ labelSingular: 'My Test Page Layout Widget Object',
+ labelPlural: 'My Test Page Layout Widget Objects',
+ icon: 'IconLayout',
+ },
+ });
+
+ testObjectMetadataId = objectMetadataId;
+
+ const testPageLayout = await createTestPageLayoutWithRestApi({
+ name: generateRecordName('Test Page Layout for Widgets'),
+ type: PageLayoutType.RECORD_PAGE,
+ objectMetadataId: testObjectMetadataId,
+ });
+
+ testPageLayoutId = testPageLayout.id;
+
+ const testPageLayoutTab = await createTestPageLayoutTabWithRestApi({
+ title: generateRecordName('Test Page Layout Tab for Widgets'),
+ pageLayoutId: testPageLayoutId,
+ position: 0,
+ });
+
+ testPageLayoutTabId = testPageLayoutTab.id;
+ });
+
+ afterAll(async () => {
+ await deleteTestPageLayoutTabWithRestApi(testPageLayoutTabId);
+ await deleteTestPageLayoutWithRestApi(testPageLayoutId);
+ await deleteOneObjectMetadata({
+ input: { idToDelete: testObjectMetadataId },
+ });
+ });
+
+ afterEach(async () => {
+ await cleanupPageLayoutWidgetRecords();
+ });
+
+ describe('GET /rest/metadata/page-layout-widgets', () => {
+ it('should return page layout widgets filtered by pageLayoutTabId', async () => {
+ const input1 = {
+ title: 'Widget 1',
+ pageLayoutTabId: testPageLayoutTabId,
+ type: WidgetType.VIEW,
+ gridPosition: {
+ row: 0,
+ column: 0,
+ rowSpan: 1,
+ columnSpan: 1,
+ },
+ };
+ const input2 = {
+ title: 'Widget 2',
+ pageLayoutTabId: testPageLayoutTabId,
+ type: WidgetType.IFRAME,
+ gridPosition: {
+ row: 0,
+ column: 1,
+ rowSpan: 1,
+ columnSpan: 1,
+ },
+ };
+
+ await createTestPageLayoutWidgetWithRestApi(input1);
+ await createTestPageLayoutWidgetWithRestApi(input2);
+
+ const response = await makeRestAPIRequest({
+ method: 'get',
+ path: `/metadata/page-layout-widgets?pageLayoutTabId=${testPageLayoutTabId}`,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiSuccessfulResponse(response);
+ expect(Array.isArray(response.body)).toBe(true);
+ expect(response.body.length).toBeGreaterThanOrEqual(2);
+
+ if (response.body.length > 0) {
+ assertPageLayoutWidgetStructure(response.body[0]);
+ expect(response.body[0].pageLayoutTabId).toBe(testPageLayoutTabId);
+ }
+ });
+
+ it('should return empty array when no page layout widgets match pageLayoutTabId', async () => {
+ const response = await makeRestAPIRequest({
+ method: 'get',
+ path: `/metadata/page-layout-widgets?pageLayoutTabId=${TEST_NOT_EXISTING_PAGE_LAYOUT_TAB_ID}`,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiSuccessfulResponse(response);
+ expect(Array.isArray(response.body)).toBe(true);
+ expect(response.body).toHaveLength(0);
+ });
+
+ it('should return error when pageLayoutTabId is missing', async () => {
+ const response = await makeRestAPIRequest({
+ method: 'get',
+ path: '/metadata/page-layout-widgets',
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiErrorResponse(
+ response,
+ 400,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_TAB_ID_REQUIRED,
+ ),
+ );
+ });
+ });
+
+ describe('POST /rest/metadata/page-layout-widgets', () => {
+ it('should create a new page layout widget with all properties', async () => {
+ const input = {
+ title: 'Test Widget',
+ pageLayoutTabId: testPageLayoutTabId,
+ type: WidgetType.GRAPH,
+ objectMetadataId: testObjectMetadataId,
+ gridPosition: {
+ row: 1,
+ column: 1,
+ rowSpan: 2,
+ columnSpan: 2,
+ },
+ configuration: { theme: 'dark', showLegend: true },
+ };
+
+ const pageLayoutWidget =
+ await createTestPageLayoutWidgetWithRestApi(input);
+
+ assertPageLayoutWidgetStructure(pageLayoutWidget, input);
+
+ await deleteTestPageLayoutWidgetWithRestApi(pageLayoutWidget.id);
+ });
+
+ it('should create a page layout widget with minimum required fields', async () => {
+ const input = {
+ title: 'Minimal Widget',
+ pageLayoutTabId: testPageLayoutTabId,
+ gridPosition: {
+ row: 0,
+ column: 0,
+ rowSpan: 1,
+ columnSpan: 1,
+ },
+ };
+
+ const pageLayoutWidget = await createTestPageLayoutWidgetWithRestApi({
+ title: input.title,
+ pageLayoutTabId: input.pageLayoutTabId,
+ gridPosition: input.gridPosition,
+ });
+
+ assertPageLayoutWidgetStructure(pageLayoutWidget, {
+ ...input,
+ type: WidgetType.VIEW,
+ objectMetadataId: null,
+ configuration: null,
+ });
+
+ await deleteTestPageLayoutWidgetWithRestApi(pageLayoutWidget.id);
+ });
+
+ it('should return error when creating widget with invalid pageLayoutTabId', async () => {
+ const pageLayoutWidgetData = {
+ title: 'Invalid Widget',
+ pageLayoutTabId: TEST_NOT_EXISTING_PAGE_LAYOUT_TAB_ID,
+ gridPosition: {
+ row: 0,
+ column: 0,
+ rowSpan: 1,
+ columnSpan: 1,
+ },
+ };
+
+ const response = await makeRestAPIRequest({
+ method: 'post',
+ path: '/metadata/page-layout-widgets',
+ body: pageLayoutWidgetData,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiErrorResponse(
+ response,
+ 400,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_TAB_NOT_FOUND,
+ ),
+ );
+ });
+
+ it('should return error when creating widget without title', async () => {
+ const pageLayoutWidgetData = {
+ pageLayoutTabId: testPageLayoutTabId,
+ gridPosition: {
+ row: 0,
+ column: 0,
+ rowSpan: 1,
+ columnSpan: 1,
+ },
+ };
+
+ const response = await makeRestAPIRequest({
+ method: 'post',
+ path: '/metadata/page-layout-widgets',
+ body: pageLayoutWidgetData,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiErrorResponse(response, 400);
+ });
+
+ it('should return error when creating widget without gridPosition', async () => {
+ const pageLayoutWidgetData = {
+ title: 'Widget Without Grid Position',
+ pageLayoutTabId: testPageLayoutTabId,
+ };
+
+ const response = await makeRestAPIRequest({
+ method: 'post',
+ path: '/metadata/page-layout-widgets',
+ body: pageLayoutWidgetData,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiErrorResponse(response, 400);
+ });
+ });
+
+ describe('GET /rest/metadata/page-layout-widgets/:id', () => {
+ it('should return a page layout widget by id', async () => {
+ const input = {
+ title: 'Widget For Get',
+ pageLayoutTabId: testPageLayoutTabId,
+ type: WidgetType.FIELDS,
+ gridPosition: {
+ row: 2,
+ column: 2,
+ rowSpan: 1,
+ columnSpan: 3,
+ },
+ };
+ const pageLayoutWidget =
+ await createTestPageLayoutWidgetWithRestApi(input);
+
+ const response = await makeRestAPIRequest({
+ method: 'get',
+ path: `/metadata/page-layout-widgets/${pageLayoutWidget.id}`,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiSuccessfulResponse(response);
+ assertPageLayoutWidgetStructure(response.body, {
+ id: pageLayoutWidget.id,
+ ...input,
+ });
+
+ await deleteTestPageLayoutWidgetWithRestApi(pageLayoutWidget.id);
+ });
+
+ it('should return error for non-existent page layout widget', async () => {
+ const response = await makeRestAPIRequest({
+ method: 'get',
+ path: `/metadata/page-layout-widgets/${TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID}`,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiErrorResponse(
+ response,
+ 404,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ ),
+ );
+ });
+ });
+
+ describe('PATCH /rest/metadata/page-layout-widgets/:id', () => {
+ it('should update an existing page layout widget', async () => {
+ const input = {
+ title: 'Test Widget for Update',
+ pageLayoutTabId: testPageLayoutTabId,
+ type: WidgetType.VIEW,
+ gridPosition: {
+ row: 0,
+ column: 0,
+ rowSpan: 1,
+ columnSpan: 1,
+ },
+ };
+ const pageLayoutWidget =
+ await createTestPageLayoutWidgetWithRestApi(input);
+
+ const updateData = {
+ title: 'Updated Widget',
+ type: WidgetType.GRAPH,
+ gridPosition: {
+ row: 1,
+ column: 1,
+ rowSpan: 2,
+ columnSpan: 3,
+ },
+ configuration: { updated: true },
+ };
+
+ const response = await makeRestAPIRequest({
+ method: 'patch',
+ path: `/metadata/page-layout-widgets/${pageLayoutWidget.id}`,
+ body: updateData,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiSuccessfulResponse(response);
+ assertPageLayoutWidgetStructure(response.body, {
+ id: pageLayoutWidget.id,
+ pageLayoutTabId: testPageLayoutTabId,
+ ...updateData,
+ });
+
+ await deleteTestPageLayoutWidgetWithRestApi(pageLayoutWidget.id);
+ });
+
+ it('should update only provided fields', async () => {
+ const input = {
+ title: 'Original Widget',
+ pageLayoutTabId: testPageLayoutTabId,
+ type: WidgetType.IFRAME,
+ gridPosition: {
+ row: 1,
+ column: 1,
+ rowSpan: 1,
+ columnSpan: 1,
+ },
+ };
+ const pageLayoutWidget =
+ await createTestPageLayoutWidgetWithRestApi(input);
+
+ const updatedTitle = 'Updated Title Only';
+ const updateData = {
+ title: updatedTitle,
+ };
+
+ const response = await makeRestAPIRequest({
+ method: 'patch',
+ path: `/metadata/page-layout-widgets/${pageLayoutWidget.id}`,
+ body: updateData,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiSuccessfulResponse(response);
+ assertPageLayoutWidgetStructure(response.body, {
+ id: pageLayoutWidget.id,
+ title: updatedTitle,
+ pageLayoutTabId: testPageLayoutTabId,
+ type: WidgetType.IFRAME,
+ gridPosition: input.gridPosition,
+ });
+
+ await deleteTestPageLayoutWidgetWithRestApi(pageLayoutWidget.id);
+ });
+
+ it('should return error when updating non-existent page layout widget', async () => {
+ const updateData = {
+ title: 'Updated Widget',
+ type: WidgetType.GRAPH,
+ };
+
+ const response = await makeRestAPIRequest({
+ method: 'patch',
+ path: `/metadata/page-layout-widgets/${TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID}`,
+ body: updateData,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiErrorResponse(
+ response,
+ 404,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ ),
+ );
+ });
+ });
+
+ describe('DELETE /rest/metadata/page-layout-widgets/:id', () => {
+ it('should delete an existing page layout widget', async () => {
+ const pageLayoutWidgetTitle = generateRecordName(
+ 'Test Widget for Delete',
+ );
+ const pageLayoutWidget = await createTestPageLayoutWidgetWithRestApi({
+ title: pageLayoutWidgetTitle,
+ pageLayoutTabId: testPageLayoutTabId,
+ type: WidgetType.FIELDS,
+ gridPosition: {
+ row: 0,
+ column: 0,
+ rowSpan: 1,
+ columnSpan: 1,
+ },
+ });
+
+ const deleteResponse = await makeRestAPIRequest({
+ method: 'delete',
+ path: `/metadata/page-layout-widgets/${pageLayoutWidget.id}`,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiSuccessfulResponse(deleteResponse);
+ assertPageLayoutWidgetStructure(deleteResponse.body, pageLayoutWidget);
+
+ const getResponse = await makeRestAPIRequest({
+ method: 'get',
+ path: `/metadata/page-layout-widgets/${pageLayoutWidget.id}`,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiErrorResponse(
+ getResponse,
+ 404,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ pageLayoutWidget.id,
+ ),
+ );
+ });
+
+ it('should return error when deleting non-existent page layout widget', async () => {
+ const response = await makeRestAPIRequest({
+ method: 'delete',
+ path: `/metadata/page-layout-widgets/${TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID}`,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ assertRestApiErrorResponse(
+ response,
+ 404,
+ generatePageLayoutWidgetExceptionMessage(
+ PageLayoutWidgetExceptionMessageKey.PAGE_LAYOUT_WIDGET_NOT_FOUND,
+ TEST_NOT_EXISTING_PAGE_LAYOUT_WIDGET_ID,
+ ),
+ );
+ });
+ });
+});
diff --git a/packages/twenty-server/test/integration/rest/utils/page-layout-widget-rest-api.util.ts b/packages/twenty-server/test/integration/rest/utils/page-layout-widget-rest-api.util.ts
new file mode 100644
index 00000000000..2d2fa06dc34
--- /dev/null
+++ b/packages/twenty-server/test/integration/rest/utils/page-layout-widget-rest-api.util.ts
@@ -0,0 +1,46 @@
+import { makeRestAPIRequest } from 'test/integration/rest/utils/make-rest-api-request.util';
+import { generateRecordName } from 'test/integration/utils/generate-record-name';
+
+import { type PageLayoutWidgetEntity } from 'src/engine/core-modules/page-layout/entities/page-layout-widget.entity';
+import { WidgetType } from 'src/engine/core-modules/page-layout/enums/widget-type.enum';
+
+export const createTestPageLayoutWidgetWithRestApi = async (
+ overrides: Partial<PageLayoutWidgetEntity> = {},
+): Promise<PageLayoutWidgetEntity> => {
+ const pageLayoutWidgetData = {
+ title: generateRecordName('Test Page Layout Widget'),
+ type: WidgetType.VIEW,
+ gridPosition: {
+ row: 0,
+ column: 0,
+ rowSpan: 1,
+ columnSpan: 1,
+ },
+ ...overrides,
+ };
+
+ const response = await makeRestAPIRequest({
+ method: 'post',
+ path: '/metadata/page-layout-widgets',
+ body: pageLayoutWidgetData,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+
+ if (response.status !== 201) {
+ throw new Error(
+ `Failed to create test page layout widget: ${response.status} - ${JSON.stringify(response.body)}`,
+ );
+ }
+
+ return response.body;
+};
+
+export const deleteTestPageLayoutWidgetWithRestApi = async (
+ pageLayoutWidgetId: string,
+): Promise<void> => {
+ await makeRestAPIRequest({
+ method: 'delete',
+ path: `/metadata/page-layout-widgets/${pageLayoutWidgetId}`,
+ bearer: API_KEY_ACCESS_TOKEN,
+ });
+};
diff --git a/packages/twenty-server/test/integration/utils/page-layout-test.util.ts b/packages/twenty-server/test/integration/utils/page-layout-test.util.ts
index 4ba370f27f3..099f341ef40 100644
--- a/packages/twenty-server/test/integration/utils/page-layout-test.util.ts
+++ b/packages/twenty-server/test/integration/utils/page-layout-test.util.ts
@@ -14,7 +14,6 @@ export const assertPageLayoutStructure = (
expect(pageLayout.id).toEqual(expect.any(String));
expect(pageLayout.name).toEqual(expect.any(String));
expect(Object.values(PageLayoutType)).toContain(pageLayout.type);
- expect(pageLayout.workspaceId).toEqual(expect.any(String));
expect(pageLayout.createdAt).toEqual(expect.any(String));
expect(pageLayout.updatedAt).toEqual(expect.any(String));
diff --git a/packages/twenty-server/test/integration/utils/page-layout-widget-test.util.ts b/packages/twenty-server/test/integration/utils/page-layout-widget-test.util.ts
new file mode 100644
index 00000000000..e86d9572b63
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/page-layout-widget-test.util.ts
@@ -0,0 +1,28 @@
+import { type PageLayoutWidgetEntity } from 'src/engine/core-modules/page-layout/entities/page-layout-widget.entity';
+
+export const cleanupPageLayoutWidgetRecords = async (): Promise<void> => {
+ // @ts-expect-error legacy noImplicitAny
+ await global.testDataSource.query(`DELETE from "core"."pageLayoutWidget"`);
+};
+
+export const assertPageLayoutWidgetStructure = (
+ pageLayoutWidget: PageLayoutWidgetEntity,
+ expectedFields?: Partial<PageLayoutWidgetEntity>,
+) => {
+ expect(pageLayoutWidget).toBeDefined();
+ expect(pageLayoutWidget.id).toEqual(expect.any(String));
+ expect(pageLayoutWidget.title).toEqual(expect.any(String));
+ expect(pageLayoutWidget.type).toBeDefined();
+ expect(pageLayoutWidget.pageLayoutTabId).toEqual(expect.any(String));
+ expect(pageLayoutWidget.gridPosition).toBeDefined();
+ expect(pageLayoutWidget.gridPosition.row).toEqual(expect.any(Number));
+ expect(pageLayoutWidget.gridPosition.column).toEqual(expect.any(Number));
+ expect(pageLayoutWidget.gridPosition.rowSpan).toEqual(expect.any(Number));
+ expect(pageLayoutWidget.gridPosition.columnSpan).toEqual(expect.any(Number));
+ expect(pageLayoutWidget.createdAt).toEqual(expect.any(String));
+ expect(pageLayoutWidget.updatedAt).toEqual(expect.any(String));
+
+ if (expectedFields) {
+ expect(pageLayoutWidget).toMatchObject(expectedFields);
+ }
+};