3ed67b825e
## Overview
This PR implements **generic many-to-many relation support** through
junction tables (also known as associative entities or join tables).
This replaces the need for hardcoded taskTarget/noteTarget logic and
provides a flexible foundation for modeling complex entity
relationships.
## Architecture
### Data Model
Many-to-many relationships are implemented using a **junction object
pattern**:
```
┌─────────┐ ┌──────────────────┐ ┌─────────┐
│ Pet │──────>│ PetRocket │<──────│ Rocket │
│ │ 1:N │ (junction) │ N:1 │ │
│ rockets ├───────┤ pet : Pet ├───────┤ │
└─────────┘ │ rocket : Rocket │ └─────────┘
└──────────────────┘
```
The junction object (PetRocket) has:
- A `MANY_TO_ONE` relation to **Pet** (the source)
- A `MANY_TO_ONE` relation to **Rocket** (the target)
The source object (Pet) has a `ONE_TO_MANY` relation pointing to the
junction, with **field settings** that specify which target field to
follow.
### Field Settings Schema
Junction configuration is stored in `FieldMetadataRelationSettings`:
```typescript
{
relationType: "ONE_TO_MANY",
// Points to the target field on the junction object
junctionTargetFieldId?: string; // For regular relations
junctionTargetMorphId?: string; // For polymorphic relations
}
```
**Two configuration modes:**
1. **`junctionTargetFieldId`** - References a specific `RELATION` field
on the junction
2. **`junctionTargetMorphId`** - References a `morphId` group for
polymorphic targets (e.g., link to Person OR Company)
### GraphQL Query Generation
When a junction relation is detected, the GraphQL fields are generated
to fetch the nested target:
```graphql
query GetPetWithRockets {
pet(id: "...") {
rockets { # ONE_TO_MANY to junction
id
rocket { # Target field on junction
id
name
__typename
}
}
}
}
```
For polymorphic junction targets:
```graphql
caretakerPerson { id, name }
caretakerCompany { id, name }
```
## Frontend Architecture
### Display Flow
1. **Detection**: `hasJunctionConfig()` checks if field has junction
settings
2. **Config Resolution**: `getJunctionConfig()` resolves junction object
metadata and target fields
3. **Record Extraction**: `extractTargetRecordsFromJunction()` extracts
target records from junction records
4. **Rendering**: Target records displayed as chips (not junction
records)
### Edit Flow
1. **Picker Opening**: Initializes the multi-record picker with:
- Searchable object types (derived from junction target fields)
- Pre-selected items (extracted from existing junction records)
2. **Selection Handling**: Manages create/delete of junction records:
- **Select**: Creates new junction record with source + target IDs
- **Deselect**: Finds and deletes the junction record
- **Optimistic Updates**: Manually updates Recoil store before API call
### Key Trade-offs
| Decision | Trade-off |
|----------|-----------|
| Junction records managed manually | More control over optimistic
updates, but requires manual cache management |
| Settings stored per-field | Flexible (same junction can power
different views), but requires UI to configure |
| Polymorphic via morphId groups | Supports N target types, but adds
query complexity |
| Feature flag gated | Safe rollout, but requires flag management |
## Backend Changes
- **Validation**: Junction target field must exist and be a valid
`MANY_TO_ONE` relation
- **Settings**: Extended `FieldMetadataRelationSettings` type with
junction fields
- **Dev Seeder**: Added sample junction objects (PetRocket,
EmploymentHistory, PetCareAgreement) for testing
## How to Test
1. Enable the `IS_JUNCTION_RELATIONS_ENABLED` feature flag
2. Create objects with junction pattern (Pet → PetRocket → Rocket)
3. Configure the junction target in field settings (advanced mode)
4. Verify:
- Display shows target objects (Rockets), not junction records
(PetRockets)
- Picker allows selecting/deselecting targets
- Changes persist correctly
https://github.com/user-attachments/assets/d04f057a-228c-4de8-af48-76bb2d72cac1
---------
Co-authored-by: Charles Bochet <charles@twenty.com>
130 lines
3.7 KiB
TypeScript
130 lines
3.7 KiB
TypeScript
import { createOneFieldMetadata } from 'test/integration/metadata/suites/field-metadata/utils/create-one-field-metadata.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 { updateOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/update-one-object-metadata.util';
|
|
import { extractRecordIdsAndDatesAsExpectAny } from 'test/utils/extract-record-ids-and-dates-as-expect-any';
|
|
import {
|
|
eachTestingContextFilter,
|
|
type EachTestingContext,
|
|
} from 'twenty-shared/testing';
|
|
import { FieldMetadataType } from 'twenty-shared/types';
|
|
|
|
import { type UpdateObjectPayload } from 'src/engine/metadata-modules/object-metadata/dtos/update-object.input';
|
|
|
|
type TestingRuntimeContext = {
|
|
objectMetadataId: string;
|
|
numberFieldMetadataId: string;
|
|
};
|
|
|
|
type CreateOneObjectMetadataItemTestingContext = EachTestingContext<
|
|
| ((args: TestingRuntimeContext) => Partial<UpdateObjectPayload>)
|
|
| Partial<UpdateObjectPayload>
|
|
>[];
|
|
|
|
const labelIdentifierFailingTestsUseCase: CreateOneObjectMetadataItemTestingContext =
|
|
[
|
|
{
|
|
title: 'when labelIdentifier is not a uuid',
|
|
context: {
|
|
labelIdentifierFieldMetadataId: 'not-a-uuid',
|
|
},
|
|
},
|
|
{
|
|
title: 'when labelIdentifier is not a known field metadata id',
|
|
context: {
|
|
labelIdentifierFieldMetadataId: '42422020-f49c-4159-8751-76a24f47b360',
|
|
},
|
|
},
|
|
{
|
|
title: 'when labelIdentifier is null',
|
|
context: {
|
|
labelIdentifierFieldMetadataId: null as any,
|
|
},
|
|
},
|
|
{
|
|
title: 'when labelIdentifier is not a TEXT or NAME field',
|
|
context: ({ numberFieldMetadataId }) => ({
|
|
labelIdentifierFieldMetadataId: numberFieldMetadataId,
|
|
}),
|
|
},
|
|
];
|
|
|
|
const allTestsUseCases = [...labelIdentifierFailingTestsUseCase];
|
|
|
|
describe('Object metadata update should fail', () => {
|
|
let objectMetadataId: string;
|
|
let numberFieldMetadataId: string;
|
|
|
|
beforeAll(async () => {
|
|
const { data } = await createOneObjectMetadata({
|
|
expectToFail: false,
|
|
input: {
|
|
labelPlural: 'whatevers',
|
|
labelSingular: 'whatever',
|
|
namePlural: 'whatevers',
|
|
nameSingular: 'whatever',
|
|
},
|
|
});
|
|
|
|
objectMetadataId = data.createOneObject.id;
|
|
|
|
const {
|
|
data: { createOneField },
|
|
} = await createOneFieldMetadata({
|
|
expectToFail: false,
|
|
input: {
|
|
objectMetadataId: objectMetadataId,
|
|
name: 'testName',
|
|
label: 'Test name',
|
|
isLabelSyncedWithName: true,
|
|
type: FieldMetadataType.NUMBER,
|
|
},
|
|
});
|
|
|
|
numberFieldMetadataId = createOneField.id;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await updateOneObjectMetadata({
|
|
expectToFail: false,
|
|
input: {
|
|
idToUpdate: objectMetadataId,
|
|
updatePayload: {
|
|
isActive: false,
|
|
},
|
|
},
|
|
});
|
|
await deleteOneObjectMetadata({
|
|
input: {
|
|
idToDelete: objectMetadataId,
|
|
},
|
|
});
|
|
});
|
|
|
|
it.each(eachTestingContextFilter(allTestsUseCases))(
|
|
'$title',
|
|
async ({ context }) => {
|
|
const updatePayload =
|
|
typeof context === 'function'
|
|
? context({
|
|
numberFieldMetadataId,
|
|
objectMetadataId,
|
|
})
|
|
: context;
|
|
|
|
const { errors } = await updateOneObjectMetadata({
|
|
input: {
|
|
idToUpdate: objectMetadataId,
|
|
updatePayload,
|
|
},
|
|
expectToFail: true,
|
|
});
|
|
|
|
expect(errors).toBeDefined();
|
|
expect(errors).toMatchSnapshot(
|
|
extractRecordIdsAndDatesAsExpectAny(errors),
|
|
);
|
|
},
|
|
);
|
|
});
|