The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
import { Injectable } from '@nestjs/common';
import { fromArrayToUniqueKeyRecord, isDefined } from 'twenty-shared/utils';
import { FindManyOptions, FindOneOptions } from 'typeorm';
import { v4 } from 'uuid';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { findFlatEntityByUniversalIdentifierOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier-or-throw.util';
import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
import { findManyFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-many-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
import { FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';
import { FlatView } from 'src/engine/metadata-modules/flat-view/types/flat-view.type';
import { computeInitialObjectViewOperationsOnObjectCreation } from 'src/engine/metadata-modules/view/utils/compute-initial-object-view-operations-on-object-creation.util';
import { FlatNavigationMenuItem } from 'src/engine/metadata-modules/flat-navigation-menu-item/types/flat-navigation-menu-item.type';
import { FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import { fromCreateObjectInputToFlatObjectMetadataAndFlatFieldMetadatasToCreate } from 'src/engine/metadata-modules/flat-object-metadata/utils/from-create-object-input-to-flat-object-metadata-and-flat-field-metadatas-to-create.util';
import { fromDeleteObjectInputToFlatFieldMetadatasToDelete } from 'src/engine/metadata-modules/flat-object-metadata/utils/from-delete-object-input-to-flat-field-metadatas-to-delete.util';
import { fromUpdateObjectInputToFlatObjectMetadataAndRelatedFlatEntities } from 'src/engine/metadata-modules/flat-object-metadata/utils/from-update-object-input-to-flat-object-metadata-and-related-flat-entities.util';
import { NavigationMenuItemType } from 'src/engine/metadata-modules/navigation-menu-item/enums/navigation-menu-item-type.enum';
import { CreateObjectInput } from 'src/engine/metadata-modules/object-metadata/dtos/create-object.input';
import { DeleteOneObjectInput } from 'src/engine/metadata-modules/object-metadata/dtos/delete-object.input';
import { UpdateOneObjectInput } from 'src/engine/metadata-modules/object-metadata/dtos/update-object.input';
import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
import { validateUpdateObjectInputs } from 'src/engine/metadata-modules/object-metadata/utils/validate-update-object-inputs.util';
import {
ObjectMetadataException,
ObjectMetadataExceptionCode,
} from 'src/engine/metadata-modules/object-metadata/object-metadata.exception';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';
import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
import { type UniversalFlatFieldMetadata } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-field-metadata.type';
import { type UniversalFlatObjectMetadata } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-object-metadata.type';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
const MAX_OBJECTS_PER_BATCH_UPDATE = 100;
const NON_BATCHABLE_UPDATE_PROPERTIES = [
'nameSingular',
'namePlural',
'labelIdentifierFieldMetadataId',
] as const;
@Injectable()
export class ObjectMetadataService {
constructor(
@InjectWorkspaceScopedRepository(ObjectMetadataEntity)
private readonly objectMetadataRepository: WorkspaceScopedRepository<ObjectMetadataEntity>,
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly applicationService: ApplicationService,
) {}
// One migration for the whole batch: one update per item would validate, build
// and run a migration each time, and refetch the flat entity maps with it.
async updateManyObjects({
updateObjectInputs,
workspaceId,
ownerFlatApplication,
}: {
workspaceId: string;
updateObjectInputs: UpdateOneObjectInput[];
ownerFlatApplication?: FlatApplication;
}): Promise<FlatObjectMetadata[]> {
if (updateObjectInputs.length === 0) {
return [];
}
if (updateObjectInputs.length > MAX_OBJECTS_PER_BATCH_UPDATE) {
throw new ObjectMetadataException(
`Cannot update more than ${MAX_OBJECTS_PER_BATCH_UPDATE} objects in one batch`,
ObjectMetadataExceptionCode.INVALID_OBJECT_INPUT,
);
}
validateUpdateObjectInputs(updateObjectInputs);
const objectMetadataIds = updateObjectInputs.map(({ id }) => id);
if (new Set(objectMetadataIds).size !== objectMetadataIds.length) {
throw new ObjectMetadataException(
'Cannot update the same object twice in one batch',
ObjectMetadataExceptionCode.INVALID_OBJECT_INPUT,
);
}
// These rewrite state beyond the object itself, so several of them in one
// migration either collide or hold locks across tables: a rename rewrites
// indexes and morph fields on related objects and can emit the same index
// twice, and a new label identifier rebuilds the search vector, rewriting
// the table and holding it locked until the whole batch commits. Splitting
// into one migration per object would commit each separately and leave the
// workspace half updated on a later failure, so the batch is refused.
const [nonBatchableUpdatedProperty] = updateObjectInputs.flatMap(
({ update }) =>
NON_BATCHABLE_UPDATE_PROPERTIES.filter((property) =>
isDefined(update[property]),
),
);
if (
isDefined(nonBatchableUpdatedProperty) &&
updateObjectInputs.length > 1
) {
throw new ObjectMetadataException(
`Cannot update ${nonBatchableUpdatedProperty} in a batch of several objects, send it one at a time`,
ObjectMetadataExceptionCode.INVALID_OBJECT_INPUT,
);
}
return await this.updateObjectsInOneMigration({
updateObjectInputs,
workspaceId,
ownerFlatApplication,
});
}
private async updateObjectsInOneMigration({
updateObjectInputs,
workspaceId,
ownerFlatApplication,
}: {
workspaceId: string;
updateObjectInputs: UpdateOneObjectInput[];
ownerFlatApplication?: FlatApplication;
}): Promise<FlatObjectMetadata[]> {
const { workspaceCustomFlatApplication } =
await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
{ workspaceId },
);
const resolvedOwnerFlatApplication =
ownerFlatApplication ?? workspaceCustomFlatApplication;
const {
flatObjectMetadataMaps: existingFlatObjectMetadataMaps,
flatIndexMaps: existingFlatIndexMaps,
flatFieldMetadataMaps: existingFlatFieldMetadataMaps,
flatViewFieldMaps: existingFlatViewFieldMaps,
flatViewMaps: existingFlatViewMaps,
flatSearchFieldMetadataMaps: existingFlatSearchFieldMetadataMaps,
} = await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
{
workspaceId,
flatMapsKeys: [
'flatObjectMetadataMaps',
'flatIndexMaps',
'flatFieldMetadataMaps',
'flatViewFieldMaps',
'flatViewMaps',
'flatSearchFieldMetadataMaps',
],
},
);
const conversions = updateObjectInputs.map((updateObjectInput) =>
fromUpdateObjectInputToFlatObjectMetadataAndRelatedFlatEntities({
flatFieldMetadataMaps: existingFlatFieldMetadataMaps,
flatObjectMetadataMaps: existingFlatObjectMetadataMaps,
updateObjectInput,
flatIndexMaps: existingFlatIndexMaps,
flatViewFieldMaps: existingFlatViewFieldMaps,
flatViewMaps: existingFlatViewMaps,
flatSearchFieldMetadataMaps: existingFlatSearchFieldMetadataMaps,
workspaceCustomApplicationUniversalIdentifier:
workspaceCustomFlatApplication.universalIdentifier,
}),
);
const validateAndBuildResult =
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
{
allFlatEntityOperationByMetadataName: {
objectMetadata: {
flatEntityToCreate: [],
flatEntityToDelete: [],
flatEntityToUpdate: conversions.map(
({ flatObjectMetadataToUpdate }) => flatObjectMetadataToUpdate,
),
},
index: {
flatEntityToCreate: [],
flatEntityToDelete: [],
flatEntityToUpdate: conversions.flatMap(
({ flatIndexMetadatasToUpdate }) => flatIndexMetadatasToUpdate,
),
},
fieldMetadata: {
flatEntityToCreate: [],
flatEntityToDelete: [],
flatEntityToUpdate: conversions.flatMap(
({ otherObjectFlatFieldMetadatasToUpdate }) =>
otherObjectFlatFieldMetadatasToUpdate,
),
},
viewField: {
flatEntityToCreate: conversions.flatMap(
({ flatViewFieldsToCreate }) => flatViewFieldsToCreate,
),
flatEntityToDelete: [],
flatEntityToUpdate: conversions.flatMap(
({ flatViewFieldsToUpdate }) => flatViewFieldsToUpdate,
),
},
searchFieldMetadata: {
flatEntityToCreate: conversions.flatMap(
({ searchFieldMetadatasToCreate }) =>
searchFieldMetadatasToCreate,
),
flatEntityToDelete: [],
flatEntityToUpdate: [],
},
},
workspaceId,
isSystemBuild: false,
applicationUniversalIdentifier:
resolvedOwnerFlatApplication.universalIdentifier,
},
);
if (validateAndBuildResult.status === 'fail') {
throw new WorkspaceMigrationBuilderException(
validateAndBuildResult,
`Multiple validation errors occurred while updating object${updateObjectInputs.length > 1 ? 's' : ''}`,
);
}
const { flatObjectMetadataMaps: recomputedFlatObjectMetadataMaps } =
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
{
workspaceId,
flatMapsKeys: ['flatObjectMetadataMaps'],
},
);
const updatedFlatObjectMetadatas = conversions.map(
({ flatObjectMetadataToUpdate }) => {
const updatedFlatObjectMetadata = findFlatEntityByUniversalIdentifier({
universalIdentifier: flatObjectMetadataToUpdate.universalIdentifier,
flatEntityMaps: recomputedFlatObjectMetadataMaps,
});
if (!isDefined(updatedFlatObjectMetadata)) {
throw new ObjectMetadataException(
'Updated object metadata not found in recomputed cache',
ObjectMetadataExceptionCode.INTERNAL_SERVER_ERROR,
);
}
return updatedFlatObjectMetadata;
},
);
if (
updateObjectInputs.some(({ update }) =>
isDefined(update.labelIdentifierFieldMetadataId),
)
) {
await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
'rolesPermissions',
]);
}
if (updateObjectInputs.some(({ update }) => isDefined(update.isActive))) {
await this.flatEntityMapsCacheService.invalidateFlatEntityMaps({
workspaceId,
flatMapsKeys: ['flatNavigationMenuItemMaps', 'flatCommandMenuItemMaps'],
});
}
return updatedFlatObjectMetadatas;
}
async updateOneObject({
updateObjectInput,
workspaceId,
ownerFlatApplication,
}: {
workspaceId: string;
updateObjectInput: UpdateOneObjectInput;
ownerFlatApplication?: FlatApplication;
}): Promise<FlatObjectMetadata> {
const [updatedFlatObjectMetadata] = await this.updateManyObjects({
updateObjectInputs: [updateObjectInput],
workspaceId,
ownerFlatApplication,
});
return updatedFlatObjectMetadata;
}
async deleteOneObject({
deleteObjectInput,
workspaceId,
isSystemBuild = false,
ownerFlatApplication,
shouldDeferActions,
}: {
deleteObjectInput: DeleteOneObjectInput;
workspaceId: string;
isSystemBuild?: boolean;
ownerFlatApplication?: FlatApplication;
shouldDeferActions?: boolean;
}): Promise<FlatObjectMetadata> {
const deletedObjectMetadataDtos = await this.deleteManyObjectMetadatas({
deleteObjectInputs: [deleteObjectInput],
workspaceId,
isSystemBuild,
ownerFlatApplication,
shouldDeferActions,
});
if (deletedObjectMetadataDtos.length !== 1) {
throw new ObjectMetadataException(
'Could not retrieve deleted object metadata dto',
ObjectMetadataExceptionCode.INTERNAL_SERVER_ERROR,
);
}
const [deletedObjectMetadataDto] = deletedObjectMetadataDtos;
return deletedObjectMetadataDto;
}
private async deleteManyObjectMetadatas({
workspaceId,
deleteObjectInputs,
isSystemBuild = false,
ownerFlatApplication,
shouldDeferActions,
}: {
deleteObjectInputs: DeleteOneObjectInput[];
workspaceId: string;
isSystemBuild?: boolean;
ownerFlatApplication?: FlatApplication;
shouldDeferActions?: boolean;
}): Promise<FlatObjectMetadata[]> {
if (deleteObjectInputs.length === 0) {
return [];
}
const resolvedOwnerFlatApplication =
ownerFlatApplication ??
(
await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
{ workspaceId },
)
).workspaceCustomFlatApplication;
const {
flatObjectMetadataMaps,
flatFieldMetadataMaps,
flatIndexMaps,
flatViewMaps,
} =
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
{
workspaceId,
flatMapsKeys: [
'flatObjectMetadataMaps',
'flatIndexMaps',
'flatFieldMetadataMaps',
'flatViewMaps',
],
},
);
const initialAccumulator: {
flatFieldMetadatasToDeleteByUniversalIdentifier: Record<
string,
UniversalFlatFieldMetadata
>;
flatObjectMetadatasToDeleteByUniversalIdentifier: Record<
string,
UniversalFlatObjectMetadata
>;
flatIndexToDeleteByUniversalIdentifier: Record<string, FlatIndexMetadata>;
flatViewToDeleteByUniversalIdentifier: Record<string, FlatView>;
} = {
flatFieldMetadatasToDeleteByUniversalIdentifier: {},
flatIndexToDeleteByUniversalIdentifier: {},
flatObjectMetadatasToDeleteByUniversalIdentifier: {},
flatViewToDeleteByUniversalIdentifier: {},
};
const {
flatFieldMetadatasToDeleteByUniversalIdentifier,
flatIndexToDeleteByUniversalIdentifier,
flatObjectMetadatasToDeleteByUniversalIdentifier,
flatViewToDeleteByUniversalIdentifier,
} = deleteObjectInputs.reduce((accumulator, deleteObjectInput) => {
const {
flatFieldMetadatasToDelete,
flatObjectMetadataToDelete,
flatIndexToDelete,
flatViewToDelete,
} = fromDeleteObjectInputToFlatFieldMetadatasToDelete({
flatObjectMetadataMaps,
flatIndexMaps,
flatFieldMetadataMaps,
flatViewMaps,
deleteObjectInput,
});
return {
flatFieldMetadatasToDeleteByUniversalIdentifier: {
...accumulator.flatFieldMetadatasToDeleteByUniversalIdentifier,
...fromArrayToUniqueKeyRecord({
array: flatFieldMetadatasToDelete,
uniqueKey: 'universalIdentifier',
}),
},
flatIndexToDeleteByUniversalIdentifier: {
...accumulator.flatIndexToDeleteByUniversalIdentifier,
...fromArrayToUniqueKeyRecord({
array: flatIndexToDelete,
uniqueKey: 'universalIdentifier',
}),
},
flatObjectMetadatasToDeleteByUniversalIdentifier: {
...accumulator.flatObjectMetadatasToDeleteByUniversalIdentifier,
[flatObjectMetadataToDelete.universalIdentifier]:
flatObjectMetadataToDelete,
},
flatViewToDeleteByUniversalIdentifier: {
...accumulator.flatViewToDeleteByUniversalIdentifier,
...fromArrayToUniqueKeyRecord({
array: flatViewToDelete,
uniqueKey: 'universalIdentifier',
}),
},
};
}, initialAccumulator);
const {
flatFieldMetadatasToDelete,
flatObjectMetadatasToDelete,
flatIndexToDelete,
} = {
flatFieldMetadatasToDelete: Object.values(
flatFieldMetadatasToDeleteByUniversalIdentifier,
),
flatObjectMetadatasToDelete: Object.values(
flatObjectMetadatasToDeleteByUniversalIdentifier,
),
flatIndexToDelete: Object.values(flatIndexToDeleteByUniversalIdentifier),
};
const deletedFlatObjectMetadatas = flatObjectMetadatasToDelete.map(
(flatObjectMetadataToDelete) =>
findFlatEntityByUniversalIdentifierOrThrow({
universalIdentifier: flatObjectMetadataToDelete.universalIdentifier,
flatEntityMaps: flatObjectMetadataMaps,
}),
);
const validateAndBuildResult =
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
{
shouldDeferActions,
allFlatEntityOperationByMetadataName: {
objectMetadata: {
flatEntityToCreate: [],
flatEntityToDelete: flatObjectMetadatasToDelete,
flatEntityToUpdate: [],
},
index: {
flatEntityToCreate: [],
flatEntityToDelete: flatIndexToDelete,
flatEntityToUpdate: [],
},
fieldMetadata: {
flatEntityToCreate: [],
flatEntityToDelete: flatFieldMetadatasToDelete,
flatEntityToUpdate: [],
},
view: {
flatEntityToCreate: [],
flatEntityToDelete: Object.values(
flatViewToDeleteByUniversalIdentifier,
),
flatEntityToUpdate: [],
},
},
workspaceId,
isSystemBuild,
applicationUniversalIdentifier:
resolvedOwnerFlatApplication.universalIdentifier,
},
);
if (validateAndBuildResult.status === 'fail') {
throw new WorkspaceMigrationBuilderException(
validateAndBuildResult,
`Multiple validation errors occurred while deleting object${deleteObjectInputs.length > 1 ? 's' : ''}`,
);
}
return deletedFlatObjectMetadatas;
}
async createOneObject({
createObjectInput,
workspaceId,
ownerFlatApplication,
shouldDeferActions,
}: {
createObjectInput: CreateObjectInput;
workspaceId: string;
ownerFlatApplication?: FlatApplication;
shouldDeferActions?: boolean;
}): Promise<FlatObjectMetadata> {
const { workspaceCustomFlatApplication } =
await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
{
workspaceId,
},
);
const resolvedOwnerFlatApplication =
ownerFlatApplication ?? workspaceCustomFlatApplication;
const { flatObjectMetadataToCreate, flatFieldMetadataToCreateOnObject } =
fromCreateObjectInputToFlatObjectMetadataAndFlatFieldMetadatasToCreate({
createObjectInput,
flatApplication: resolvedOwnerFlatApplication,
});
const flatNavigationMenuItemToCreate =
await this.computeFlatNavigationMenuItemToCreate({
objectMetadata: flatObjectMetadataToCreate,
workspaceId,
workspaceCustomApplicationId: workspaceCustomFlatApplication.id,
workspaceCustomApplicationUniversalIdentifier:
workspaceCustomFlatApplication.universalIdentifier,
});
const isWorkspaceCustomApplicationBuild =
resolvedOwnerFlatApplication.universalIdentifier ===
workspaceCustomFlatApplication.universalIdentifier;
const initialObjectViewOperations = isWorkspaceCustomApplicationBuild
? computeInitialObjectViewOperationsOnObjectCreation({
flatObjectMetadataToCreate,
callerFlatFieldMetadatasToCreate: flatFieldMetadataToCreateOnObject,
})
: undefined;
const validateAndBuildResult =
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
{
shouldDeferActions,
allFlatEntityOperationByMetadataName: {
objectMetadata: {
flatEntityToCreate: [flatObjectMetadataToCreate],
flatEntityToDelete: [],
flatEntityToUpdate: [],
},
fieldMetadata: {
flatEntityToCreate: [...flatFieldMetadataToCreateOnObject],
flatEntityToDelete: [],
flatEntityToUpdate: [],
},
index: {
flatEntityToCreate: [],
flatEntityToDelete: [],
flatEntityToUpdate: [],
},
...(isDefined(initialObjectViewOperations)
? {
view: {
flatEntityToCreate: [
initialObjectViewOperations.flatInitialViewToCreate,
],
flatEntityToDelete: [],
flatEntityToUpdate: [],
},
viewField: {
flatEntityToCreate:
initialObjectViewOperations.flatInitialViewFieldsToCreate,
flatEntityToDelete: [],
flatEntityToUpdate: [],
},
}
: {}),
...(isDefined(flatNavigationMenuItemToCreate)
? {
navigationMenuItem: {
flatEntityToCreate: [flatNavigationMenuItemToCreate],
flatEntityToDelete: [],
flatEntityToUpdate: [],
},
}
: {}),
},
workspaceId,
isSystemBuild: false,
applicationUniversalIdentifier:
resolvedOwnerFlatApplication.universalIdentifier,
},
);
if (validateAndBuildResult.status === 'fail') {
throw new WorkspaceMigrationBuilderException(
validateAndBuildResult,
'Multiple validation errors occurred while creating object',
);
}
const { flatObjectMetadataMaps: recomputedFlatObjectMetadataMaps } =
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
{
workspaceId,
flatMapsKeys: ['flatObjectMetadataMaps'],
},
);
const createdFlatObjectMetadata = findFlatEntityByIdInFlatEntityMaps({
flatEntityId: flatObjectMetadataToCreate.id,
flatEntityMaps: recomputedFlatObjectMetadataMaps,
});
if (!isDefined(createdFlatObjectMetadata)) {
throw new ObjectMetadataException(
'Created object metadata not found in recomputed cache',
ObjectMetadataExceptionCode.INTERNAL_SERVER_ERROR,
);
}
return createdFlatObjectMetadata;
}
private async computeFlatNavigationMenuItemToCreate({
objectMetadata,
workspaceId,
workspaceCustomApplicationId,
workspaceCustomApplicationUniversalIdentifier,
}: {
objectMetadata: { id: string; universalIdentifier: string };
workspaceId: string;
workspaceCustomApplicationId: string;
workspaceCustomApplicationUniversalIdentifier: string;
}): Promise<FlatNavigationMenuItem> {
const { flatNavigationMenuItemMaps } =
await this.workspaceCacheService.getOrRecompute(workspaceId, [
'flatNavigationMenuItemMaps',
]);
const workspaceLevelItems = Object.values(
flatNavigationMenuItemMaps.byUniversalIdentifier,
).filter(
(item): item is FlatNavigationMenuItem =>
isDefined(item) && !isDefined(item.userWorkspaceId),
);
const nextPosition =
workspaceLevelItems.length > 0
? Math.max(...workspaceLevelItems.map((item) => item.position)) + 1
: 0;
const newId = v4();
const now = new Date().toISOString();
return {
id: newId,
type: NavigationMenuItemType.OBJECT,
universalIdentifier: newId,
userWorkspaceId: null,
targetRecordId: null,
targetObjectMetadataId: objectMetadata.id,
targetObjectMetadataUniversalIdentifier:
objectMetadata.universalIdentifier,
viewId: null,
viewUniversalIdentifier: null,
folderId: null,
folderUniversalIdentifier: null,
pageLayoutId: null,
pageLayoutUniversalIdentifier: null,
agentChatChannelId: null,
agentChatChannelUniversalIdentifier: null,
name: null,
link: null,
icon: null,
color: null,
position: nextPosition,
workspaceId,
applicationId: workspaceCustomApplicationId,
applicationUniversalIdentifier:
workspaceCustomApplicationUniversalIdentifier,
createdAt: now,
updatedAt: now,
};
}
public async findOneWithinWorkspace(
workspaceId: string,
options: FindOneOptions<ObjectMetadataEntity>,
): Promise<ObjectMetadataEntity | null> {
return this.objectMetadataRepository.findOne(workspaceId, {
relations: [
'fields',
'indexMetadatas',
'indexMetadatas.indexFieldMetadatas',
],
...options,
});
}
public async findManyWithinWorkspace(
workspaceId: string,
options?: FindManyOptions<ObjectMetadataEntity>,
): Promise<FlatObjectMetadata[]> {
const objectMetadataEntities = await this.objectMetadataRepository.find(
workspaceId,
{
...options,
order: {
...options?.order,
},
select: { id: true },
},
);
const objectMetadataIds = objectMetadataEntities.map(
(objectMetadata) => objectMetadata.id,
);
const { flatObjectMetadataMaps } =
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
{
workspaceId,
flatMapsKeys: ['flatObjectMetadataMaps'],
},
);
const filteredOutAndSortedFlatObjectMetadataMaps =
findManyFlatEntityByIdInFlatEntityMapsOrThrow({
flatEntityMaps: flatObjectMetadataMaps,
flatEntityIds: objectMetadataIds,
});
return filteredOutAndSortedFlatObjectMetadataMaps;
}
}