Display a CTA to view the existing duplicate when adding a duplicate email/domain. (#16483)
Closes [89](https://github.com/twentyhq/core-team-issues/issues/89) ## Problem When users attempt to create or update a record with a duplicate value for a unique field (e.g., duplicate email or domain name), they receive a generic error message: "This record already exists. Please check your data and try again." This provides no actionable way to locate and view the existing conflicting record, forcing users to manually search for it. ## Solution This PR enhances duplicate key constraint error handling to automatically detect the conflicting record and display a "View existing record" link in the error notification. When clicked, users are navigated directly to the existing record's detail page. ## Backend Changes ### 1. PostgreSQL Error Parsing (`parse-postgres-constraint-error.util.ts`) - Extracts structured information from PostgreSQL `QueryFailedError` messages. ### 2. Conflicting Record Lookup (`find-conflicting-record.util.ts`) - Queries the database to find the existing record with the conflicting value ### 3. Error Handling Orchestration (`handle-duplicate-key-error.util.ts`) - Parses PostgreSQL error to extract column name and conflicting value - Attempts to find the conflicting record - Enriches `TwentyORMException` with `conflictingRecordId` and `conflictingObjectNameSingular` if found ### 4. Exception Computation Updates (`compute-twenty-orm-exception.ts`) - Made function `async` and added optional `entityManager` and `internalContext` parameters - Needed to support async database queries for conflicting record lookup ### 5. GraphQL Error Handler (`twenty-orm-graphql-api-exception-handler.util.ts`) - **Changes**: Enhanced `DUPLICATE_ENTRY_DETECTED` case to include `conflictingRecordId` and `conflictingObjectNameSingular` in GraphQL error extensions ## Frontend Changes ### 1. Error Extraction Utility (`get-conflicting-record-from-apollo-error.util.ts`) - Accesses GraphQL error extensions - Validates that both `conflictingRecordId` and `conflictingObjectNameSingular` exist and are strings - Returns `null` if validation fails ### 2. SnackBar Enhancement (`useSnackBar.ts`) - Extracts conflicting record info from Apollo error - Constructs URL using `getAppPath` utility - Adds link object to snackbar options with text "View existing record" <img width="931" height="858" alt="image" src="https://github.com/user-attachments/assets/28137dc7-18ab-4ffe-b669-1f2d4ec264d1" />
This commit is contained in:
+76
@@ -0,0 +1,76 @@
|
||||
import { compositeTypeDefinitions } from 'twenty-shared/types';
|
||||
import { capitalize } from 'twenty-shared/utils';
|
||||
|
||||
import { type WorkspaceInternalContext } from 'src/engine/twenty-orm/interfaces/workspace-internal-context.interface';
|
||||
|
||||
import { getFlatFieldsFromFlatObjectMetadata } from 'src/engine/api/graphql/workspace-schema-builder/utils/get-flat-fields-for-flat-object-metadata.util';
|
||||
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
|
||||
import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';
|
||||
|
||||
export const findConflictingRecord = async (
|
||||
columnName: string,
|
||||
conflictingValue: string,
|
||||
objectMetadata: FlatObjectMetadata,
|
||||
internalContext: WorkspaceInternalContext,
|
||||
entityManager: WorkspaceEntityManager,
|
||||
): Promise<{ conflictingRecordId: string; fieldLabel: string } | null> => {
|
||||
const flatFields = getFlatFieldsFromFlatObjectMetadata(
|
||||
objectMetadata,
|
||||
internalContext.flatFieldMetadataMaps,
|
||||
);
|
||||
|
||||
const uniqueFields = flatFields.filter((field) => field.isUnique);
|
||||
|
||||
const matchingField = uniqueFields.find((field) => {
|
||||
const compositeType = compositeTypeDefinitions.get(field.type);
|
||||
|
||||
if (!compositeType) {
|
||||
return field.name === columnName;
|
||||
}
|
||||
|
||||
const property = compositeType.properties.find(
|
||||
(prop) => prop.isIncludedInUniqueConstraint,
|
||||
);
|
||||
|
||||
if (!property) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const expectedColumnName = `${field.name}${capitalize(property.name)}`;
|
||||
|
||||
return expectedColumnName === columnName;
|
||||
});
|
||||
|
||||
if (!matchingField) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const queryBuilder = entityManager.createQueryBuilder(
|
||||
objectMetadata.nameSingular,
|
||||
objectMetadata.nameSingular,
|
||||
undefined,
|
||||
{
|
||||
shouldBypassPermissionChecks: true,
|
||||
},
|
||||
);
|
||||
|
||||
queryBuilder.where(`"${columnName}" = :value`, { value: conflictingValue });
|
||||
queryBuilder.andWhere('"deletedAt" IS NULL');
|
||||
|
||||
try {
|
||||
const conflictingRecord = await queryBuilder.getOne();
|
||||
|
||||
if (!conflictingRecord) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
conflictingRecordId: conflictingRecord.id,
|
||||
fieldLabel: matchingField.label,
|
||||
};
|
||||
} catch {
|
||||
// If query fails (e.g., permission denied, record not found), return null
|
||||
// This allows the duplicate error to still be shown without conflicting record link
|
||||
return null;
|
||||
}
|
||||
};
|
||||
+52
-11
@@ -1,27 +1,68 @@
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { type QueryFailedError } from 'typeorm';
|
||||
|
||||
import { type WorkspaceInternalContext } from 'src/engine/twenty-orm/interfaces/workspace-internal-context.interface';
|
||||
|
||||
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
|
||||
import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';
|
||||
import {
|
||||
TwentyORMException,
|
||||
TwentyORMExceptionCode,
|
||||
} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
|
||||
|
||||
interface PostgreSQLError extends QueryFailedError {
|
||||
detail?: string;
|
||||
import { findConflictingRecord } from './find-conflicting-record.util';
|
||||
import {
|
||||
parsePostgresConstraintError,
|
||||
type PostgreSQLError,
|
||||
} from './parse-postgres-constraint-error.util';
|
||||
|
||||
interface DuplicateKeyErrorWithMetadata extends TwentyORMException {
|
||||
conflictingRecordId?: string;
|
||||
conflictingObjectNameSingular?: string;
|
||||
}
|
||||
|
||||
export const handleDuplicateKeyError = (
|
||||
_error: PostgreSQLError,
|
||||
_objectMetadata: FlatObjectMetadata,
|
||||
) => {
|
||||
// Since we no longer have indexMetadatas in FlatObjectMetadata,
|
||||
// we provide a generic error message
|
||||
throw new TwentyORMException(
|
||||
export const handleDuplicateKeyError = async (
|
||||
error: PostgreSQLError,
|
||||
objectMetadata: FlatObjectMetadata,
|
||||
internalContext: WorkspaceInternalContext,
|
||||
entityManager: WorkspaceEntityManager,
|
||||
): Promise<DuplicateKeyErrorWithMetadata> => {
|
||||
const parsedError = parsePostgresConstraintError(error);
|
||||
|
||||
if (!parsedError) {
|
||||
return new TwentyORMException(
|
||||
`A duplicate entry was detected`,
|
||||
TwentyORMExceptionCode.DUPLICATE_ENTRY_DETECTED,
|
||||
{
|
||||
userFriendlyMessage: msg`This record already exists. Please check your data and try again.`,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const conflictingRecord = await findConflictingRecord(
|
||||
parsedError.columnName,
|
||||
parsedError.conflictingValue,
|
||||
objectMetadata,
|
||||
internalContext,
|
||||
entityManager,
|
||||
);
|
||||
|
||||
const fieldLabel = conflictingRecord?.fieldLabel;
|
||||
const userFriendlyMessage = fieldLabel
|
||||
? msg`This ${fieldLabel} value is already in use. Please check your data and try again.`
|
||||
: msg`This record already exists. Please check your data and try again.`;
|
||||
|
||||
const exception: DuplicateKeyErrorWithMetadata = new TwentyORMException(
|
||||
`A duplicate entry was detected`,
|
||||
TwentyORMExceptionCode.DUPLICATE_ENTRY_DETECTED,
|
||||
{
|
||||
userFriendlyMessage: msg`This record already exists. Please check your data and try again.`,
|
||||
userFriendlyMessage,
|
||||
},
|
||||
);
|
||||
|
||||
if (conflictingRecord) {
|
||||
exception.conflictingRecordId = conflictingRecord.conflictingRecordId;
|
||||
exception.conflictingObjectNameSingular = objectMetadata.nameSingular;
|
||||
}
|
||||
|
||||
return exception;
|
||||
};
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { type QueryFailedError } from 'typeorm';
|
||||
|
||||
export type PostgreSQLError = QueryFailedError & {
|
||||
detail?: string;
|
||||
driverError?: Error & {
|
||||
detail?: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type ParsedConstraintError = {
|
||||
columnName: string;
|
||||
conflictingValue: string;
|
||||
};
|
||||
|
||||
export const parsePostgresConstraintError = (
|
||||
error: PostgreSQLError,
|
||||
): ParsedConstraintError | null => {
|
||||
const errorDetail = error.detail;
|
||||
|
||||
if (!errorDetail) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const detailMatch = errorDetail.match(/Key \(([^)]+)\)=\(([^)]+)\)/);
|
||||
|
||||
if (!detailMatch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const columnName = detailMatch[1].replace(/^["']|["']$/g, '');
|
||||
const conflictingValue = detailMatch[2];
|
||||
|
||||
return {
|
||||
columnName,
|
||||
conflictingValue,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user