Compare commits

...
Author SHA1 Message Date
Charles Bochet aa8113a1f0 Merge branch 'main' into c--improve-permissions-and-RLS-coverage 2026-02-18 22:21:32 +01:00
Charles BochetandGitHub 9a2dc45eb7 Fix website build (#18052) 2026-02-18 22:15:30 +01:00
neo773andGitHub 7de565f70c Prevent SSRF via IMAP/SMTP/CalDAV (#17973)
Prevents leaking of internal services by filtering out private IPs, same
way we do for webhooks
2026-02-18 22:15:10 +01:00
Félix MalfaitGitHubCursorclaude[bot] <41898282+claude[bot]@users.noreply.github.com>
67074a7581 Harden server-side input validation and auth defaults (#18018)
## Summary

- **File storage (LocalDriver):** Add realpath resolution and symlink
rejection to `writeFile`, `downloadFile`, and `downloadFolder` — brings
them in line with the existing `readFile` protections. Includes unit
tests.
- **JWT:** Pin signing/verification to HS256 explicitly.
- **Auth:** Revoke active refresh tokens when a user changes their
password.
- **Logic functions:** Validate `handlerName` as a safe JS identifier at
both DTO and runtime level, preventing injection into the generated
runner script.
- **User entity:** Remove `passwordHash` from the GraphQL schema
(`@Field` decorator removed, column stays).
- **Query params:** Use `crypto.randomBytes` instead of `Math.random`
for SQL parameter name generation.
- **Exception filter:** Mirror the request `Origin` header instead of
sending `Access-Control-Allow-Origin: *`.

## Test plan

- [x] `local.driver.spec.ts` — writeFile rejects symlinks, downloadFile
rejects paths outside storage
- [ ] Verify JWT auth flow still works (login, token refresh)
- [ ] Verify password change invalidates existing sessions
- [ ] Verify logic function creation with valid/invalid handler names
- [ ] Verify file upload/download in dev environment


Made with [Cursor](https://cursor.com)

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
2026-02-18 21:41:01 +01:00
Charles BochetandGitHub 330737aa2e Fix impossible scroll in sdk app:dev (#18051)
Issue is that we are refreshing the terminal because of icons animations
2026-02-18 21:39:21 +01:00
4cb64c6aa5 Restore old favorite design (#18049)
Issue : With IS_NAVIGATION_MENU_ITEM_ENABLED:true +
IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED:false, nav menu design is
changed after 1.18.0 release : views expansion removed, system object
displayed, position re-ordered

We prefer keeping the same "old" favorite behaviour and design state

- After 1.18.0 all workspaces have up-to-date navigation menu items
(migrated)
- IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED becomes the FF for nav menu
new design

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2026-02-18 21:35:17 +01:00
6b3ef404b0 i18n - docs translations (#18050)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-02-18 21:31:54 +01:00
6aaafb76b6 fix: show "Not shared" for junction relation fields when target or intermediate object is not readable (#18025)
When a user's role lacks read permission on the target object (e.g.,
Company) or the intermediate junction object (e.g., EmploymentHistory),
junction relation fields like "Previous Companies" displayed as blank
instead of showing "Not shared."

- In RecordFieldList, junction fields now check the junction object's
read permission and set isForbidden on the field context so FieldDisplay
renders "Not shared" instead of an empty field.
- In RelationFromManyFieldDisplay, if junction records exist but all
nested target records are null (permission-denied by the API), the
component renders "Not shared" instead of an empty list.

---------

Co-authored-by: Félix Malfait <felix@twenty.com>
2026-02-18 21:05:45 +01:00
Thomas des FrancsandGitHub 7ec4508d5f Add currency hover tooltip in CurrencyDisplay (#18045)
https://github.com/user-attachments/assets/af768ecb-b5e9-4e8d-a9f9-fee1a08ea9a0

Fixes https://github.com/twentyhq/twenty/issues/17756
2026-02-18 20:25:34 +01:00
Thomas des FrancsandGitHub a05a9c8f79 refactor workflow action messaging with callout (#18038)
## Summary
- remove the dedicated `WorkflowMessage` component and story
- update workflow action editor components to use the shared callout
patterns
- adjust `Callout` and its stories to support the new usage in workflow
actions

## Before/After

<img width="525" height="548" alt="image"
src="https://github.com/user-attachments/assets/ce57a84f-f070-4149-85ef-a4d162b2d878"
/>


<img width="518" height="593" alt="image"
src="https://github.com/user-attachments/assets/f7249cd0-221f-496d-9deb-d9966ee43382"
/>
2026-02-18 20:23:38 +01:00
Charles BochetandGitHub ce1ffa8550 Refactor page layout types (#18042)
## Refactor page layout widget types into shared package and expose from
SDK

### Why

Widget configuration types were defined only on the server, forcing SDK
consumer apps to import from deep internal `twenty-shared/dist` paths —
fragile and breaks on structural changes. Server DTOs also had no
compile-time guarantee they matched the canonical types.

### What changed

- **`twenty-shared`**: Migrated `ChartFilter`, `GridPosition`,
`RatioAggregateConfig` and all 20 widget configuration variants into
`twenty-shared/types`. `PageLayoutWidgetConfiguration` (base, with
`SerializedRelation`) and `PageLayoutWidgetUniversalConfiguration`
(derived via `FormatRecordSerializedRelationProperties`) are now the
single source of truth.
- **`twenty-sdk`**: Re-exported `AggregateOperations`,
`ObjectRecordGroupByDateGranularity`, `PageLayoutTabLayoutMode`, and
`PageLayoutWidgetUniversalConfiguration` so consumer apps import from
`twenty-sdk` directly.
- **`twenty-server`**: All widget DTOs now `implements` their shared
type for compile-time enforcement. Added helpers to convert nested
`fieldMetadataId` ↔ `fieldMetadataUniversalIdentifier` inside chart
filters. Removed redundant local type re-exports.
2026-02-18 20:17:40 +01:00
martmullandGitHub 2cc3c75c7e Add example in create-twenty-app (#18043)
- add interactive mode to create-twenty-app
- by default create an example for each entities

<img width="1181" height="168" alt="image"
src="https://github.com/user-attachments/assets/a2490d8f-66a1-4cd5-bf41-57166cc20a1e"
/>
2026-02-18 18:04:19 +00:00
Thomas TrompetteandGitHub 9733ff1b8e Add missing objects to rich app integration tests (#18039)
Updating rich app so it also create:
- a many to many relation
- views
- navigation items

The app was built successfully.

Will still be missing front component examples

<img width="1498" height="660" alt="Capture d’écran 2026-02-18 à 17 47
25"
src="https://github.com/user-attachments/assets/acd5193f-3a36-4eb7-8276-3154e4e60f5e"
/>
2026-02-18 18:01:14 +00:00
e4075caa65 i18n - docs translations (#18048)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-02-18 19:42:34 +01:00
Charles BochetandGitHub 80f87300f0 Merge branch 'main' into c--improve-permissions-and-RLS-coverage 2026-02-09 22:30:00 +01:00
Félix MalfaitandGitHub e26f398f34 Merge branch 'main' into c--improve-permissions-and-RLS-coverage 2026-02-05 14:12:38 +01:00
Weiko e77de316e5 Improve permissions and RLS coverage 2026-02-05 13:34:39 +01:00
167 changed files with 4585 additions and 1097 deletions
+44 -8
View File
@@ -61,20 +61,56 @@ yarn twenty function:execute --postInstall
yarn twenty app:uninstall
```
## Scaffolding modes
Control which example files are included when creating a new app:
| Flag | Behavior |
|------|----------|
| `-e, --exhaustive` | **(default)** Creates all example files without prompting |
| `-m, --minimal` | Creates only core files (`application-config.ts` and `default-role.ts`) |
| `-i, --interactive` | Prompts you to select which examples to include |
```bash
# Default: all examples included
npx create-twenty-app@latest my-app
# Minimal: only core files
npx create-twenty-app@latest my-app -m
# Interactive: choose which examples to include
npx create-twenty-app@latest my-app -i
```
In interactive mode, you can pick from:
- **Example object** — a custom CRM object definition (`objects/example-object.ts`)
- **Example field** — a custom field on the example object (`fields/example-field.ts`)
- **Example logic function** — a server-side handler with HTTP trigger (`logic-functions/hello-world.ts`)
- **Example front component** — a React UI component (`front-components/hello-world.tsx`)
- **Example view** — a saved view for the example object (`views/example-view.ts`)
- **Example navigation menu item** — a sidebar link (`navigation-menu-items/example-navigation-menu-item.ts`)
## What gets scaffolded
- A minimal app structure ready for Twenty with example files:
- `application-config.ts` - Application metadata configuration
- `roles/default-role.ts` - Default role for logic functions
- `logic-functions/hello-world.ts` - Example logic function with HTTP trigger
- `logic-functions/post-install.ts` - Post-install logic function (runs after app installation)
- `front-components/hello-world.tsx` - Example front component
- TypeScript configuration
**Core files (always created):**
- `application-config.ts` — Application metadata configuration
- `roles/default-role.ts` — Default role for logic functions
- `logic-functions/post-install.ts` Post-install logic function (runs after app installation)
- TypeScript configuration, ESLint, package.json, .gitignore
- A prewired `twenty` script that delegates to the `twenty` CLI from twenty-sdk
**Example files (controlled by scaffolding mode):**
- `objects/example-object.ts` — Example custom object with a text field
- `fields/example-field.ts` — Example standalone field extending the example object
- `logic-functions/hello-world.ts` — Example logic function with HTTP trigger
- `front-components/hello-world.tsx` — Example front component
- `views/example-view.ts` — Example saved view for the example object
- `navigation-menu-items/example-navigation-menu-item.ts` — Example sidebar navigation link
## Next steps
- Run `yarn twenty help` to see all available commands.
- Use `yarn twenty auth:login` to authenticate with your Twenty workspace.
- Explore the generated project and add your first entity with `yarn twenty entity:add` (logic functions, front components, objects, roles).
- Explore the generated project and add your first entity with `yarn twenty entity:add` (logic functions, front components, objects, roles, views, navigation menu items).
- Use `yarn twenty app:dev` while you iterate — it watches, builds, and syncs changes to your workspace in real time.
- Types are autogenerated by `yarn twenty app:dev` and stored in `node_modules/twenty-sdk/generated`.
+52 -11
View File
@@ -2,6 +2,7 @@
import chalk from 'chalk';
import { Command, CommanderError } from 'commander';
import { CreateAppCommand } from '@/create-app.command';
import { type ScaffoldingMode } from '@/types/scaffolding-options';
import packageJson from '../package.json';
const program = new Command(packageJson.name)
@@ -12,18 +13,58 @@ const program = new Command(packageJson.name)
'Output the current version of create-twenty-app.',
)
.argument('[directory]')
.option('-e, --exhaustive', 'Create all example entities (default)')
.option(
'-m, --minimal',
'Create only core entities (application-config and default-role)',
)
.option(
'-i, --interactive',
'Interactively choose which entity examples to include',
)
.helpOption('-h, --help', 'Display this help message.')
.action(async (directory?: string) => {
if (directory && !/^[a-z0-9-]+$/.test(directory)) {
console.error(
chalk.red(
`Invalid directory "${directory}". Must contain only lowercase letters, numbers, and hyphens`,
),
);
process.exit(1);
}
await new CreateAppCommand().execute(directory);
});
.action(
async (
directory?: string,
options?: {
exhaustive?: boolean;
minimal?: boolean;
interactive?: boolean;
},
) => {
const modeFlags = [
options?.exhaustive,
options?.minimal,
options?.interactive,
].filter(Boolean);
if (modeFlags.length > 1) {
console.error(
chalk.red(
'Error: --exhaustive, --minimal, and --interactive are mutually exclusive.',
),
);
process.exit(1);
}
if (directory && !/^[a-z0-9-]+$/.test(directory)) {
console.error(
chalk.red(
`Invalid directory "${directory}". Must contain only lowercase letters, numbers, and hyphens`,
),
);
process.exit(1);
}
const mode: ScaffoldingMode = options?.minimal
? 'minimal'
: options?.interactive
? 'interactive'
: 'exhaustive';
await new CreateAppCommand().execute(directory, mode);
},
);
program.exitOverride();
@@ -30,7 +30,7 @@ yarn twenty auth:list # List all configured workspaces
# Application
yarn twenty app:dev # Start dev mode (watch, build, sync, and auto-generate typed client)
yarn twenty entity:add # Add a new entity (function, front-component, object, role)
yarn twenty entity:add # Add a new entity (object, field, function, front-component, role, view, navigation-menu-item)
yarn twenty function:logs # Stream function logs
yarn twenty function:execute # Execute a function with JSON payload
yarn twenty app:uninstall # Uninstall app from workspace
@@ -8,14 +8,24 @@ import inquirer from 'inquirer';
import kebabCase from 'lodash.kebabcase';
import * as path from 'path';
import {
type ExampleOptions,
type ScaffoldingMode,
} from '@/types/scaffolding-options';
const CURRENT_EXECUTION_DIRECTORY = process.env.INIT_CWD || process.cwd();
export class CreateAppCommand {
async execute(directory?: string): Promise<void> {
async execute(
directory?: string,
mode: ScaffoldingMode = 'exhaustive',
): Promise<void> {
try {
const { appName, appDisplayName, appDirectory, appDescription } =
await this.getAppInfos(directory);
const exampleOptions = await this.resolveExampleOptions(mode);
await this.validateDirectory(appDirectory);
this.logCreationInfo({ appDirectory, appName });
@@ -27,6 +37,7 @@ export class CreateAppCommand {
appDisplayName,
appDescription,
appDirectory,
exampleOptions,
});
await install(appDirectory);
@@ -92,6 +103,95 @@ export class CreateAppCommand {
return { appName, appDisplayName, appDirectory, appDescription };
}
private async resolveExampleOptions(
mode: ScaffoldingMode,
): Promise<ExampleOptions> {
if (mode === 'minimal') {
return {
includeExampleObject: false,
includeExampleField: false,
includeExampleLogicFunction: false,
includeExampleFrontComponent: false,
includeExampleView: false,
includeExampleNavigationMenuItem: false,
};
}
if (mode === 'exhaustive') {
return {
includeExampleObject: true,
includeExampleField: true,
includeExampleLogicFunction: true,
includeExampleFrontComponent: true,
includeExampleView: true,
includeExampleNavigationMenuItem: true,
};
}
const { selectedExamples } = await inquirer.prompt([
{
type: 'checkbox',
name: 'selectedExamples',
message: 'Select which example files to include:',
choices: [
{
name: 'Example object (custom object definition)',
value: 'object',
checked: true,
},
{
name: 'Example field (custom field on the example object)',
value: 'field',
checked: true,
},
{
name: 'Example logic function (server-side handler)',
value: 'logicFunction',
checked: true,
},
{
name: 'Example front component (React UI component)',
value: 'frontComponent',
checked: true,
},
{
name: 'Example view (saved view for the example object)',
value: 'view',
checked: true,
},
{
name: 'Example navigation menu item (sidebar link)',
value: 'navigationMenuItem',
checked: true,
},
],
},
]);
const includeField = selectedExamples.includes('field');
const includeView = selectedExamples.includes('view');
const includeObject =
selectedExamples.includes('object') || includeField || includeView;
if ((includeField || includeView) && !selectedExamples.includes('object')) {
console.log(
chalk.yellow(
'Note: Example object auto-included because example field/view depends on it.',
),
);
}
return {
includeExampleObject: includeObject,
includeExampleField: includeField,
includeExampleLogicFunction: selectedExamples.includes('logicFunction'),
includeExampleFrontComponent: selectedExamples.includes('frontComponent'),
includeExampleView: includeView,
includeExampleNavigationMenuItem:
selectedExamples.includes('navigationMenuItem'),
};
}
private async validateDirectory(appDirectory: string): Promise<void> {
if (!(await fs.pathExists(appDirectory))) {
return;
@@ -0,0 +1,10 @@
export type ScaffoldingMode = 'exhaustive' | 'minimal' | 'interactive';
export type ExampleOptions = {
includeExampleObject: boolean;
includeExampleField: boolean;
includeExampleLogicFunction: boolean;
includeExampleFrontComponent: boolean;
includeExampleView: boolean;
includeExampleNavigationMenuItem: boolean;
};
@@ -2,6 +2,7 @@ import * as fs from 'fs-extra';
import { join } from 'path';
import { tmpdir } from 'os';
import { copyBaseApplicationProject } from '@/utils/app-template';
import { type ExampleOptions } from '@/types/scaffolding-options';
// Mock fs-extra's copy function to skip copying base template (not available during tests)
jest.mock('fs-extra', () => {
@@ -15,6 +16,24 @@ jest.mock('fs-extra', () => {
const APPLICATION_FILE_NAME = 'application-config.ts';
const DEFAULT_ROLE_FILE_NAME = 'default-role.ts';
const ALL_EXAMPLES: ExampleOptions = {
includeExampleObject: true,
includeExampleField: true,
includeExampleLogicFunction: true,
includeExampleFrontComponent: true,
includeExampleView: true,
includeExampleNavigationMenuItem: true,
};
const NO_EXAMPLES: ExampleOptions = {
includeExampleObject: false,
includeExampleField: false,
includeExampleLogicFunction: false,
includeExampleFrontComponent: false,
includeExampleView: false,
includeExampleNavigationMenuItem: false,
};
describe('copyBaseApplicationProject', () => {
let testAppDirectory: string;
@@ -41,6 +60,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
// Verify src/ folder exists
@@ -62,6 +82,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const packageJsonPath = join(testAppDirectory, 'package.json');
@@ -80,6 +101,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const gitignorePath = join(testAppDirectory, '.gitignore');
@@ -96,6 +118,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const yarnLockPath = join(testAppDirectory, 'yarn.lock');
@@ -111,6 +134,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const appConfigPath = join(testAppDirectory, 'src', APPLICATION_FILE_NAME);
@@ -148,6 +172,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const roleConfigPath = join(
@@ -192,6 +217,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
// Verify fs.copy was called with correct destination
@@ -208,6 +234,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'My Test App',
appDescription: '',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const appConfigPath = join(testAppDirectory, 'src', APPLICATION_FILE_NAME);
@@ -225,6 +252,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'App One',
appDescription: 'First app',
appDirectory: firstAppDir,
exampleOptions: ALL_EXAMPLES,
});
// Create second app
@@ -235,6 +263,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'App Two',
appDescription: 'Second app',
appDirectory: secondAppDir,
exampleOptions: ALL_EXAMPLES,
});
// Read both app configs
@@ -267,6 +296,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'App One',
appDescription: 'First app',
appDirectory: firstAppDir,
exampleOptions: ALL_EXAMPLES,
});
// Create second app
@@ -277,6 +307,7 @@ describe('copyBaseApplicationProject', () => {
appDisplayName: 'App Two',
appDescription: 'Second app',
appDirectory: secondAppDir,
exampleOptions: ALL_EXAMPLES,
});
const firstRoleConfig = await fs.readFile(
@@ -299,4 +330,345 @@ describe('copyBaseApplicationProject', () => {
expect(secondUuid).toBeDefined();
expect(firstUuid).not.toBe(secondUuid);
});
describe('scaffolding modes', () => {
describe('exhaustive mode (all examples)', () => {
it('should create all example files when all options are enabled', async () => {
await copyBaseApplicationProject({
appName: 'my-test-app',
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const srcPath = join(testAppDirectory, 'src');
expect(
await fs.pathExists(join(srcPath, 'objects', 'example-object.ts')),
).toBe(true);
expect(
await fs.pathExists(join(srcPath, 'fields', 'example-field.ts')),
).toBe(true);
expect(
await fs.pathExists(
join(srcPath, 'logic-functions', 'hello-world.ts'),
),
).toBe(true);
expect(
await fs.pathExists(
join(srcPath, 'front-components', 'hello-world.tsx'),
),
).toBe(true);
expect(
await fs.pathExists(join(srcPath, 'views', 'example-view.ts')),
).toBe(true);
expect(
await fs.pathExists(
join(
srcPath,
'navigation-menu-items',
'example-navigation-menu-item.ts',
),
),
).toBe(true);
});
});
describe('minimal mode (no examples)', () => {
it('should create only core files when no examples are enabled', async () => {
await copyBaseApplicationProject({
appName: 'my-test-app',
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: NO_EXAMPLES,
});
const srcPath = join(testAppDirectory, 'src');
// Core files should exist
expect(await fs.pathExists(join(srcPath, APPLICATION_FILE_NAME))).toBe(
true,
);
expect(
await fs.pathExists(join(srcPath, 'roles', DEFAULT_ROLE_FILE_NAME)),
).toBe(true);
// Example files should not exist
expect(
await fs.pathExists(join(srcPath, 'objects', 'example-object.ts')),
).toBe(false);
expect(
await fs.pathExists(join(srcPath, 'fields', 'example-field.ts')),
).toBe(false);
expect(
await fs.pathExists(
join(srcPath, 'logic-functions', 'hello-world.ts'),
),
).toBe(false);
expect(
await fs.pathExists(
join(srcPath, 'front-components', 'hello-world.tsx'),
),
).toBe(false);
expect(
await fs.pathExists(join(srcPath, 'views', 'example-view.ts')),
).toBe(false);
expect(
await fs.pathExists(
join(
srcPath,
'navigation-menu-items',
'example-navigation-menu-item.ts',
),
),
).toBe(false);
});
});
describe('selective examples', () => {
it('should create only front component when only that option is enabled', async () => {
await copyBaseApplicationProject({
appName: 'my-test-app',
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: {
includeExampleObject: false,
includeExampleField: false,
includeExampleLogicFunction: false,
includeExampleFrontComponent: true,
includeExampleView: false,
includeExampleNavigationMenuItem: false,
},
});
const srcPath = join(testAppDirectory, 'src');
expect(
await fs.pathExists(
join(srcPath, 'front-components', 'hello-world.tsx'),
),
).toBe(true);
expect(
await fs.pathExists(join(srcPath, 'objects', 'example-object.ts')),
).toBe(false);
expect(
await fs.pathExists(join(srcPath, 'fields', 'example-field.ts')),
).toBe(false);
expect(
await fs.pathExists(
join(srcPath, 'logic-functions', 'hello-world.ts'),
),
).toBe(false);
});
it('should create only logic function when only that option is enabled', async () => {
await copyBaseApplicationProject({
appName: 'my-test-app',
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: {
includeExampleObject: false,
includeExampleField: false,
includeExampleLogicFunction: true,
includeExampleFrontComponent: false,
includeExampleView: false,
includeExampleNavigationMenuItem: false,
},
});
const srcPath = join(testAppDirectory, 'src');
expect(
await fs.pathExists(
join(srcPath, 'logic-functions', 'hello-world.ts'),
),
).toBe(true);
expect(
await fs.pathExists(join(srcPath, 'objects', 'example-object.ts')),
).toBe(false);
});
});
});
describe('example object', () => {
it('should create example-object.ts with defineObject and correct structure', async () => {
await copyBaseApplicationProject({
appName: 'my-test-app',
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const objectPath = join(
testAppDirectory,
'src',
'objects',
'example-object.ts',
);
expect(await fs.pathExists(objectPath)).toBe(true);
const content = await fs.readFile(objectPath, 'utf8');
expect(content).toContain(
"import { defineObject, FieldType } from 'twenty-sdk'",
);
expect(content).toContain('export default defineObject({');
expect(content).toContain(
'export const EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER',
);
expect(content).toContain('export const NAME_FIELD_UNIVERSAL_IDENTIFIER');
expect(content).toContain("nameSingular: 'exampleItem'");
expect(content).toContain("namePlural: 'exampleItems'");
expect(content).toContain('FieldType.TEXT');
expect(content).toContain(
'labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UNIVERSAL_IDENTIFIER',
);
});
it('should generate unique UUIDs for example objects across apps', async () => {
const firstAppDir = join(testAppDirectory, 'app1');
await fs.ensureDir(firstAppDir);
await copyBaseApplicationProject({
appName: 'app-one',
appDisplayName: 'App One',
appDescription: 'First app',
appDirectory: firstAppDir,
exampleOptions: ALL_EXAMPLES,
});
const secondAppDir = join(testAppDirectory, 'app2');
await fs.ensureDir(secondAppDir);
await copyBaseApplicationProject({
appName: 'app-two',
appDisplayName: 'App Two',
appDescription: 'Second app',
appDirectory: secondAppDir,
exampleOptions: ALL_EXAMPLES,
});
const firstContent = await fs.readFile(
join(firstAppDir, 'src', 'objects', 'example-object.ts'),
'utf8',
);
const secondContent = await fs.readFile(
join(secondAppDir, 'src', 'objects', 'example-object.ts'),
'utf8',
);
const uuidRegex =
/EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER =\s*'([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})'/;
const firstUuid = firstContent.match(uuidRegex)?.[1];
const secondUuid = secondContent.match(uuidRegex)?.[1];
expect(firstUuid).toBeDefined();
expect(secondUuid).toBeDefined();
expect(firstUuid).not.toBe(secondUuid);
});
});
describe('example field', () => {
it('should create example-field.ts with defineField referencing the object', async () => {
await copyBaseApplicationProject({
appName: 'my-test-app',
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const fieldPath = join(
testAppDirectory,
'src',
'fields',
'example-field.ts',
);
expect(await fs.pathExists(fieldPath)).toBe(true);
const content = await fs.readFile(fieldPath, 'utf8');
expect(content).toContain(
"import { defineField, FieldType } from 'twenty-sdk'",
);
expect(content).toContain(
"import { EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/example-object'",
);
expect(content).toContain('export default defineField({');
expect(content).toContain(
'objectUniversalIdentifier: EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER',
);
expect(content).toContain('FieldType.NUMBER');
expect(content).toContain("name: 'priority'");
});
});
describe('example view', () => {
it('should create example-view.ts with defineView referencing the object', async () => {
await copyBaseApplicationProject({
appName: 'my-test-app',
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const viewPath = join(
testAppDirectory,
'src',
'views',
'example-view.ts',
);
expect(await fs.pathExists(viewPath)).toBe(true);
const content = await fs.readFile(viewPath, 'utf8');
expect(content).toContain("import { defineView } from 'twenty-sdk'");
expect(content).toContain(
"import { EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/example-object'",
);
expect(content).toContain('export default defineView({');
expect(content).toContain(
'objectUniversalIdentifier: EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER',
);
expect(content).toContain("name: 'example-view'");
});
});
describe('example navigation menu item', () => {
it('should create example-navigation-menu-item.ts with defineNavigationMenuItem', async () => {
await copyBaseApplicationProject({
appName: 'my-test-app',
appDisplayName: 'My Test App',
appDescription: 'A test application',
appDirectory: testAppDirectory,
exampleOptions: ALL_EXAMPLES,
});
const navPath = join(
testAppDirectory,
'src',
'navigation-menu-items',
'example-navigation-menu-item.ts',
);
expect(await fs.pathExists(navPath)).toBe(true);
const content = await fs.readFile(navPath, 'utf8');
expect(content).toContain(
"import { defineNavigationMenuItem } from 'twenty-sdk'",
);
expect(content).toContain('export default defineNavigationMenuItem({');
expect(content).toContain("name: 'example-navigation-menu-item'");
expect(content).toContain("icon: 'IconList'");
expect(content).toContain('position: 0');
});
});
});
@@ -3,6 +3,8 @@ import { join } from 'path';
import { v4 } from 'uuid';
import { ASSETS_DIR } from 'twenty-shared/application';
import { type ExampleOptions } from '@/types/scaffolding-options';
const SRC_FOLDER = 'src';
export const copyBaseApplicationProject = async ({
@@ -10,11 +12,13 @@ export const copyBaseApplicationProject = async ({
appDisplayName,
appDescription,
appDirectory,
exampleOptions,
}: {
appName: string;
appDisplayName: string;
appDescription: string;
appDirectory: string;
exampleOptions: ExampleOptions;
}) => {
await fs.copy(join(__dirname, './constants/base-application'), appDirectory);
@@ -37,17 +41,53 @@ export const copyBaseApplicationProject = async ({
fileName: 'default-role.ts',
});
await createDefaultFrontComponent({
appDirectory: sourceFolderPath,
fileFolder: 'front-components',
fileName: 'hello-world.tsx',
});
if (exampleOptions.includeExampleObject) {
await createExampleObject({
appDirectory: sourceFolderPath,
fileFolder: 'objects',
fileName: 'example-object.ts',
});
}
await createDefaultFunction({
appDirectory: sourceFolderPath,
fileFolder: 'logic-functions',
fileName: 'hello-world.ts',
});
if (exampleOptions.includeExampleField) {
await createExampleField({
appDirectory: sourceFolderPath,
fileFolder: 'fields',
fileName: 'example-field.ts',
});
}
if (exampleOptions.includeExampleLogicFunction) {
await createDefaultFunction({
appDirectory: sourceFolderPath,
fileFolder: 'logic-functions',
fileName: 'hello-world.ts',
});
}
if (exampleOptions.includeExampleFrontComponent) {
await createDefaultFrontComponent({
appDirectory: sourceFolderPath,
fileFolder: 'front-components',
fileName: 'hello-world.tsx',
});
}
if (exampleOptions.includeExampleView) {
await createExampleView({
appDirectory: sourceFolderPath,
fileFolder: 'views',
fileName: 'example-view.ts',
});
}
if (exampleOptions.includeExampleNavigationMenuItem) {
await createExampleNavigationMenuItem({
appDirectory: sourceFolderPath,
fileFolder: 'navigation-menu-items',
fileName: 'example-navigation-menu-item.ts',
});
}
await createDefaultPostInstallFunction({
appDirectory: sourceFolderPath,
@@ -252,6 +292,138 @@ export default defineLogicFunction({
await fs.writeFile(join(appDirectory, fileFolder ?? '', fileName), content);
};
const createExampleObject = async ({
appDirectory,
fileFolder,
fileName,
}: {
appDirectory: string;
fileFolder?: string;
fileName: string;
}) => {
const objectUniversalIdentifier = v4();
const nameFieldUniversalIdentifier = v4();
const content = `import { defineObject, FieldType } from 'twenty-sdk';
export const EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER =
'${objectUniversalIdentifier}';
export const NAME_FIELD_UNIVERSAL_IDENTIFIER =
'${nameFieldUniversalIdentifier}';
export default defineObject({
universalIdentifier: EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER,
nameSingular: 'exampleItem',
namePlural: 'exampleItems',
labelSingular: 'Example item',
labelPlural: 'Example items',
description: 'A sample custom object',
icon: 'IconBox',
labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UNIVERSAL_IDENTIFIER,
fields: [
{
universalIdentifier: NAME_FIELD_UNIVERSAL_IDENTIFIER,
type: FieldType.TEXT,
name: 'name',
label: 'Name',
description: 'Name of the example item',
icon: 'IconAbc',
},
],
});
`;
await fs.ensureDir(join(appDirectory, fileFolder ?? ''));
await fs.writeFile(join(appDirectory, fileFolder ?? '', fileName), content);
};
const createExampleField = async ({
appDirectory,
fileFolder,
fileName,
}: {
appDirectory: string;
fileFolder?: string;
fileName: string;
}) => {
const universalIdentifier = v4();
const content = `import { defineField, FieldType } from 'twenty-sdk';
import { EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/example-object';
export default defineField({
objectUniversalIdentifier: EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER,
universalIdentifier: '${universalIdentifier}',
type: FieldType.NUMBER,
name: 'priority',
label: 'Priority',
description: 'Priority level for the example item (1-10)',
});
`;
await fs.ensureDir(join(appDirectory, fileFolder ?? ''));
await fs.writeFile(join(appDirectory, fileFolder ?? '', fileName), content);
};
const createExampleView = async ({
appDirectory,
fileFolder,
fileName,
}: {
appDirectory: string;
fileFolder?: string;
fileName: string;
}) => {
const universalIdentifier = v4();
const content = `import { defineView } from 'twenty-sdk';
import { EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/example-object';
export default defineView({
universalIdentifier: '${universalIdentifier}',
name: 'example-view',
objectUniversalIdentifier: EXAMPLE_OBJECT_UNIVERSAL_IDENTIFIER,
icon: 'IconList',
position: 0,
});
`;
await fs.ensureDir(join(appDirectory, fileFolder ?? ''));
await fs.writeFile(join(appDirectory, fileFolder ?? '', fileName), content);
};
const createExampleNavigationMenuItem = async ({
appDirectory,
fileFolder,
fileName,
}: {
appDirectory: string;
fileFolder?: string;
fileName: string;
}) => {
const universalIdentifier = v4();
const content = `import { defineNavigationMenuItem } from 'twenty-sdk';
export default defineNavigationMenuItem({
universalIdentifier: '${universalIdentifier}',
name: 'example-navigation-menu-item',
icon: 'IconList',
position: 0,
// Link to a view:
// viewUniversalIdentifier: '...',
// Or link to an object:
// targetObjectUniversalIdentifier: '...',
// Or link to an external URL:
// link: 'https://example.com',
});
`;
await fs.ensureDir(join(appDirectory, fileFolder ?? ''));
await fs.writeFile(join(appDirectory, fileFolder ?? '', fileName), content);
};
const createApplicationConfig = async ({
displayName,
description,
@@ -20,8 +20,11 @@ ENV KEYSTATIC_GITHUB_CLIENT_SECRET="<fake build value>"
ENV KEYSTATIC_SECRET="<fake build value>"
ENV NEXT_PUBLIC_KEYSTATIC_GITHUB_APP_SLUG="<fake build value>"
COPY ./packages/twenty-shared /app/packages/twenty-shared
COPY ./packages/twenty-ui /app/packages/twenty-ui
COPY ./packages/twenty-website /app/packages/twenty-website
RUN npx nx build twenty-shared
RUN npx nx build twenty-ui
RUN npx nx build twenty-website
FROM node:24-alpine AS twenty-website
@@ -26,7 +26,7 @@ Apps let you build and manage Twenty customizations **as code**. Instead of conf
Create a new app using the official scaffolder, then authenticate and start developing:
```bash filename="Terminal"
# Scaffold a new app
# Scaffold a new app (includes all examples by default)
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
@@ -41,6 +41,19 @@ yarn twenty auth:login
yarn twenty app:dev
```
The scaffolder supports three modes for controlling which example files are included:
```bash filename="Terminal"
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item)
npx create-twenty-app@latest my-app
# Minimal: only core files (application-config.ts and default-role.ts)
npx create-twenty-app@latest my-app --minimal
# Interactive: select which examples to include
npx create-twenty-app@latest my-app --interactive
```
From here you can:
```bash filename="Terminal"
@@ -72,9 +85,9 @@ When you run `npx create-twenty-app@latest my-twenty-app`, the scaffolder:
- Copies a minimal base application into `my-twenty-app/`
- Adds a local `twenty-sdk` dependency and Yarn 4 configuration
- Creates config files and scripts wired to the `twenty` CLI
- Generates a default application config, a default function role, and a post-install function
- Generates core files (application config, default function role, post-install function) plus example files based on the scaffolding mode
A freshly scaffolded app looks like this:
A freshly scaffolded app with the default `--exhaustive` mode looks like this:
```text filename="my-twenty-app/"
my-twenty-app/
@@ -93,13 +106,23 @@ my-twenty-app/
├── application-config.ts # Required - main application configuration
├── roles/
│ └── default-role.ts # Default role for logic functions
├── objects/
│ └── example-object.ts # Example custom object definition
├── fields/
│ └── example-field.ts # Example standalone field definition
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ └── post-install.ts # Post-install logic function
── front-components/
└── hello-world.tsx # Example front component
── front-components/
└── hello-world.tsx # Example front component
├── views/
│ └── example-view.ts # Example saved view definition
└── navigation-menu-items/
└── example-navigation-menu-item.ts # Example sidebar navigation link
```
With `--minimal`, only the core files are created (`application-config.ts`, `roles/default-role.ts`, and `logic-functions/post-install.ts`). With `--interactive`, you choose which example files to include.
At a high level:
- **package.json**: Declares the app name, version, engines (Node 24+, Yarn 4), and adds `twenty-sdk` plus a `twenty` script that delegates to the local `twenty` CLI. Run `yarn twenty help` to list all available commands.
@@ -122,6 +145,8 @@ The SDK detects entities by parsing your TypeScript files for **`export default
| `defineFrontComponent()` | Front component definitions |
| `defineRole()` | Role definitions |
| `defineField()` | Field extensions for existing objects |
| `defineView()` | Saved view definitions |
| `defineNavigationMenuItem()` | Navigation menu item definitions |
<Note>
**File naming is flexible.** Entity detection is AST-based — the SDK scans your source files for the `export default define<Entity>({...})` pattern. You can organize your files and folders however you like. Grouping by entity type (e.g., `logic-functions/`, `roles/`) is just a convention for code organization, not a requirement.
@@ -193,6 +218,8 @@ The SDK provides helper functions for defining your app entities. As described i
| `defineFrontComponent()` | Define front components for custom UI |
| `defineRole()` | Configure role permissions and object access |
| `defineField()` | Extend existing objects with additional fields |
| `defineView()` | Define saved views for objects |
| `defineNavigationMenuItem()` | Define sidebar navigation links |
These functions validate your configuration at build time and provide IDE autocompletion and type safety.
@@ -27,7 +27,7 @@ description: أنشئ وأدِر تخصيصات Twenty على هيئة كود.
أنشئ تطبيقًا جديدًا باستخدام المُهيئ الرسمي، ثم قم بالمصادقة وابدأ التطوير:
```bash filename="Terminal"
# إنشاء تطبيق جديد
# إنشاء تطبيق جديد (يتضمن جميع الأمثلة افتراضيًا)
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
@@ -42,6 +42,19 @@ yarn twenty auth:login
yarn twenty app:dev
```
يدعم المُنشئ ثلاثة أوضاع للتحكم في ملفات الأمثلة التي سيتم تضمينها:
```bash filename="Terminal"
# الافتراضي (شامل): جميع الأمثلة (كائن، حقل، دالة منطقية، مكوّن الواجهة الأمامية، عرض، عنصر قائمة التنقل)
npx create-twenty-app@latest my-app
# الأدنى: الملفات الأساسية فقط (application-config.ts و default-role.ts)
npx create-twenty-app@latest my-app --minimal
# التفاعلي: اختر الأمثلة التي تريد تضمينها
npx create-twenty-app@latest my-app --interactive
```
من هنا يمكنك:
```bash filename="Terminal"
@@ -73,9 +86,9 @@ yarn twenty help
* ينسخ تطبيقًا أساسيًا مصغّرًا إلى `my-twenty-app/`
* يضيف اعتمادًا محليًا `twenty-sdk` وتهيئة Yarn 4
* ينشئ ملفات ضبط ونصوصًا مرتبطة بـ `twenty` CLI
* Generates a default application config, a default function role, and a post-install function
* يُنشئ الملفات الأساسية (تهيئة التطبيق، دور الدالة الافتراضي، دالة ما بعد التثبيت) بالإضافة إلى ملفات الأمثلة بحسب وضع الإنشاء
يبدو التطبيق المُنشأ حديثًا بالقالب كما يلي:
يبدو التطبيق المُنشأ حديثًا باستخدام الوضع الافتراضي `--exhaustive` كما يلي:
```text filename="my-twenty-app/"
my-twenty-app/
@@ -89,18 +102,28 @@ my-twenty-app/
eslint.config.mjs
tsconfig.json
README.md
public/ # Public assets folder (images, fonts, etc.)
public/ # مجلد الأصول العامة (صور، خطوط، إلخ)
src/
├── application-config.ts # Required - main application configuration
├── application-config.ts # مطلوب - إعدادات التطبيق الرئيسية
├── roles/
│ └── default-role.ts # Default role for logic functions
│ └── default-role.ts # الدور الافتراضي للدوال المنطقية
├── objects/
│ └── example-object.ts # تعريف كائن مخصص — مثال
├── fields/
│ └── example-field.ts # تعريف حقل مستقل — مثال
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ └── post-install.ts # Post-install logic function
── front-components/
└── hello-world.tsx # Example front component
│ ├── hello-world.ts # دالة منطقية — مثال
│ └── post-install.ts # دالة منطقية لما بعد التثبيت
── front-components/
└── hello-world.tsx # مكوّن واجهة أمامية — مثال
├── views/
│ └── example-view.ts # تعريف عرض محفوظ — مثال
└── navigation-menu-items/
└── example-navigation-menu-item.ts # رابط تنقّل في الشريط الجانبي — مثال
```
مع `--minimal`، سيتم إنشاء الملفات الأساسية فقط (`application-config.ts` و`roles/default-role.ts` و`logic-functions/post-install.ts`). مع `--interactive`، تختار ملفات الأمثلة التي تريد تضمينها.
بشكل عام:
* **package.json**: يصرّح باسم التطبيق والإصدار والمحرّكات (Node 24+، Yarn 4)، ويضيف `twenty-sdk` بالإضافة إلى نص برمجي `twenty` يفوِّض إلى `twenty` CLI المحلي. شغِّل `yarn twenty help` لعرض جميع الأوامر المتاحة.
@@ -116,13 +139,15 @@ my-twenty-app/
يكتشف SDK الكيانات عبر تحليل ملفات TypeScript الخاصة بك بحثًا عن استدعاءات **`export default define<Entity>({...})`**. يحتوي كل نوع كيان على دالة مساعدة مقابلة يتم تصديرها من `twenty-sdk`:
| دالة مساعدة | نوع الكيان |
| ------------------------ | --------------------------------- |
| `defineObject()` | تعريفات كائنات مخصصة |
| `defineLogicFunction()` | تعريفات الوظائف المنطقية |
| `defineFrontComponent()` | Front component definitions |
| `defineRole()` | تعريفات الأدوار |
| `defineField()` | امتدادات الحقول للكائنات الموجودة |
| دالة مساعدة | نوع الكيان |
| ---------------------------- | --------------------------------- |
| `defineObject()` | تعريفات كائنات مخصصة |
| `defineLogicFunction()` | تعريفات الوظائف المنطقية |
| `defineFrontComponent()` | Front component definitions |
| `defineRole()` | تعريفات الأدوار |
| `defineField()` | امتدادات الحقول للكائنات الموجودة |
| `defineView()` | تعريفات العروض المحفوظة |
| `defineNavigationMenuItem()` | تعريفات عناصر قائمة التنقل |
<Note>
**تسمية الملفات مرنة.** يعتمد اكتشاف الكيانات على بنية الشجرة المجردة (AST) — إذ يقوم SDK بفحص ملفات المصدر لديك بحثًا عن النمط `export default define<Entity>({...})`. يمكنك تنظيم ملفاتك ومجلداتك كيفما تشاء. التجميع حسب نوع الكيان (مثلًا، `logic-functions/` و`roles/`) هو مجرد عرف لتنظيم الشيفرة، وليس مطلبًا إلزاميًا.
@@ -187,14 +212,16 @@ yarn twenty auth:status
يوفّر SDK دوالًا مساعدة لتعريف كيانات تطبيقك. كما هو موضح في [اكتشاف الكيانات](#entity-detection)، يجب استخدام `export default define<Entity>({...})` كي يتم اكتشاف كياناتك:
| دالة | الغرض |
| ------------------------ | ---------------------------------------------------- |
| `defineApplication()` | تهيئة بيانات التعريف للتطبيق (مطلوب، واحد لكل تطبيق) |
| `defineObject()` | تعريف كائنات مخصصة مع حقول |
| `defineLogicFunction()` | تعريف وظائف منطقية مع معالجات |
| `defineFrontComponent()` | عرِّف مكوّنات أمامية لواجهة مستخدم مخصّصة |
| `defineRole()` | تهيئة صلاحيات الدور والوصول إلى الكائنات |
| `defineField()` | وسّع الكائنات الموجودة بحقول إضافية |
| دالة | الغرض |
| ---------------------------- | ---------------------------------------------------- |
| `defineApplication()` | تهيئة بيانات التعريف للتطبيق (مطلوب، واحد لكل تطبيق) |
| `defineObject()` | تعريف كائنات مخصصة مع حقول |
| `defineLogicFunction()` | تعريف وظائف منطقية مع معالجات |
| `defineFrontComponent()` | عرِّف مكوّنات أمامية لواجهة مستخدم مخصّصة |
| `defineRole()` | تهيئة صلاحيات الدور والوصول إلى الكائنات |
| `defineField()` | وسّع الكائنات الموجودة بحقول إضافية |
| `defineView()` | تعريف العروض المحفوظة للكائنات |
| `defineNavigationMenuItem()` | تعريف روابط التنقل في الشريط الجانبي |
تتحقق هذه الدوال من تكوينك وقت البناء وتوفّر إكمالًا تلقائيًا في بيئة التطوير وأمان الأنواع.
@@ -470,7 +497,7 @@ export default defineLogicFunction({
A post-install function is a logic function that runs automatically after your app is installed on a workspace. This is useful for one-time setup tasks such as seeding default data, creating initial records, or configuring workspace settings.
When you scaffold a new app with `create-twenty-app`, a post-install function is generated for you at `src/logic-functions/post-install.ts`:
عند إنشاء هيكل تطبيق جديد باستخدام `create-twenty-app`، يتم إنشاء دالة ما بعد التثبيت لك في `src/logic-functions/post-install.ts`:
```typescript
// src/logic-functions/post-install.ts
@@ -491,7 +518,7 @@ export default defineLogicFunction({
});
```
The function is wired into your app by referencing its universal identifier in `application-config.ts`:
يتم ربط الدالة بتطبيقك من خلال الإشارة إلى المعرِّف العالمي الخاص بها في `application-config.ts`:
```typescript
import { POST_INSTALL_UNIVERSAL_IDENTIFIER } from 'src/logic-functions/post-install';
@@ -502,7 +529,7 @@ export default defineApplication({
});
```
You can also manually execute the post-install function at any time using the CLI:
يمكنك أيضًا تنفيذ دالة ما بعد التثبيت يدويًا في أي وقت باستخدام CLI:
```bash filename="Terminal"
yarn twenty function:execute --postInstall
@@ -510,10 +537,10 @@ yarn twenty function:execute --postInstall
النقاط الرئيسية:
* Post-install functions are standard logic functions — they use `defineLogicFunction()` like any other function.
* The `postInstallLogicFunctionUniversalIdentifier` field in `defineApplication()` is optional. If omitted, no function runs after installation.
* The default timeout is set to 300 seconds (5 minutes) to allow for longer setup tasks like data seeding.
* Post-install functions do not need triggers — they are invoked by the platform during installation or manually via `function:execute --postInstall`.
* دوال ما بعد التثبيت هي دوال منطقية قياسية — فهي تستخدم `defineLogicFunction()` مثل أي دالة أخرى.
* حقل `postInstallLogicFunctionUniversalIdentifier` في `defineApplication()` اختياري. إذا تم تجاهله، لن يتم تشغيل أي دالة بعد التثبيت.
* تم تعيين مهلة افتراضية إلى 300 ثانية (5 دقائق) للسماح بمهام الإعداد الأطول مثل تهيئة البيانات.
* لا تحتاج دوال ما بعد التثبيت إلى مُشغِّلات — حيث يستدعيها النظام الأساسي أثناء التثبيت أو يدويًا عبر `function:execute --postInstall`.
### حمولة مشغل المسار
@@ -27,7 +27,7 @@ Aplikace vám umožňují vytvářet a spravovat přizpůsobení Twenty **jako k
Vytvořte novou aplikaci pomocí oficiálního scaffolderu, poté se ověřte a začněte vyvíjet:
```bash filename="Terminal"
# Vygenerujte kostru nové aplikace
# Vygenerujte kostru nové aplikace (ve výchozím nastavení zahrnuje všechny příklady)
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
@@ -42,25 +42,38 @@ yarn twenty auth:login
yarn twenty app:dev
```
Nástroj pro generování kostry podporuje tři režimy pro řízení toho, které ukázkové soubory jsou zahrnuty:
```bash filename="Terminal"
# Výchozí (úplný): všechny příklady (objekt, pole, logická funkce, front-endová komponenta, zobrazení, položka navigační nabídky)
npx create-twenty-app@latest my-app
# Minimální: pouze základní soubory (application-config.ts a default-role.ts)
npx create-twenty-app@latest my-app --minimal
# Interaktivní: vyberte, které příklady zahrnout
npx create-twenty-app@latest my-app --interactive
```
Odtud můžete:
```bash filename="Terminal"
# Add a new entity to your application (guided)
# Přidejte do vaší aplikace novou entitu (s průvodcem)
yarn twenty entity:add
# Watch your application's function logs
# Sledujte logy funkcí vaší aplikace
yarn twenty function:logs
# Execute a function by name
# Spusťte funkci podle názvu
yarn twenty function:execute -n my-function -p '{"name": "test"}'
# Execute the post-install function
# Spusťte postinstalační funkci
yarn twenty function:execute --postInstall
# Uninstall the application from the current workspace
# Odinstalujte aplikaci z aktuálního pracovního prostoru
yarn twenty app:uninstall
# Display commands' help
# Zobrazte nápovědu k příkazům
yarn twenty help
```
@@ -73,9 +86,9 @@ Když spustíte `npx create-twenty-app@latest my-twenty-app`, scaffolder:
* Zkopíruje minimální základní aplikaci do `my-twenty-app/`
* Přidá lokální závislost `twenty-sdk` a konfiguraci pro Yarn 4
* Vytvoří konfigurační soubory a skripty napojené na `twenty` CLI
* Generates a default application config, a default function role, and a post-install function
* Vygeneruje základní soubory (konfigurace aplikace, výchozí role funkcí, postinstalační funkce) a k nim ukázkové soubory podle zvoleného režimu generování kostry
Čerstvě vytvořená aplikace vypadá takto:
Čerstvě vygenerovaná aplikace s výchozím režimem `--exhaustive` vypadá takto:
```text filename="my-twenty-app/"
my-twenty-app/
@@ -89,18 +102,28 @@ my-twenty-app/
eslint.config.mjs
tsconfig.json
README.md
public/ # Public assets folder (images, fonts, etc.)
public/ # Složka s veřejnými prostředky (obrázky, písma apod.)
src/
├── application-config.ts # Required - main application configuration
├── application-config.ts # Povinné hlavní konfigurace aplikace
├── roles/
│ └── default-role.ts # Default role for logic functions
│ └── default-role.ts # Výchozí role pro logic funkce
├── objects/
│ └── example-object.ts # Ukázková definice vlastního objektu
├── fields/
│ └── example-field.ts # Ukázková samostatná definice pole
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ └── post-install.ts # Post-install logic function
── front-components/
└── hello-world.tsx # Example front component
│ ├── hello-world.ts # Ukázková logic funkce
│ └── post-install.ts # Postinstalační logic funkce
── front-components/
└── hello-world.tsx # Ukázková front-endová komponenta
├── views/
│ └── example-view.ts # Ukázková definice uloženého zobrazení
└── navigation-menu-items/
└── example-navigation-menu-item.ts # Ukázkový odkaz postranní navigace
```
S volbou `--minimal` se vytvoří pouze základní soubory (`application-config.ts`, `roles/default-role.ts` a `logic-functions/post-install.ts`). S volbou `--interactive` si vyberete, které ukázkové soubory chcete zahrnout.
V kostce:
* **package.json**: Deklaruje název aplikace, verzi, engines (Node 24+, Yarn 4) a přidává `twenty-sdk` plus skript `twenty`, který deleguje na lokální `twenty` CLI. Spusťte `yarn twenty help` pro výpis všech dostupných příkazů.
@@ -116,13 +139,15 @@ V kostce:
SDK detekuje entity analýzou vašich souborů TypeScript a hledá volání **`export default define<Entity>({...})`**. Každý typ entity má odpovídající pomocnou funkci exportovanou z `twenty-sdk`:
| Pomocná funkce | Typ entity |
| ------------------------ | ------------------------------------- |
| `defineObject()` | Definice vlastních objektů |
| `defineLogicFunction()` | Definice logických funkcí |
| `defineFrontComponent()` | Definice frontendových komponent |
| `defineRole()` | Definice rolí |
| `defineField()` | Rozšíření polí u existujících objektů |
| Pomocná funkce | Typ entity |
| ---------------------------- | ------------------------------------- |
| `defineObject()` | Definice vlastních objektů |
| `defineLogicFunction()` | Definice logických funkcí |
| `defineFrontComponent()` | Definice frontendových komponent |
| `defineRole()` | Definice rolí |
| `defineField()` | Rozšíření polí u existujících objektů |
| `defineView()` | Definice uložených zobrazení |
| `defineNavigationMenuItem()` | Definice položek navigační nabídky |
<Note>
**Pojmenování souborů je flexibilní.** Detekce entit je založená na AST — SDK prochází vaše zdrojové soubory a hledá vzor `export default define<Entity>({...})`. Soubory a složky můžete organizovat, jak chcete. Seskupování podle typu entity (např. `logic-functions/`, `roles/`) je pouze konvence pro organizaci kódu, nikoli požadavek.
@@ -187,14 +212,16 @@ twenty-sdk poskytuje typované stavební bloky a pomocné funkce, které použí
SDK poskytuje pomocné funkce pro definování entit vaší aplikace. Jak je popsáno v [Detekce entit](#entity-detection), musíte použít `export default define<Entity>({...})`, aby byly vaše entity detekovány:
| Funkce | Účel |
| ------------------------ | ----------------------------------------------------------------- |
| `defineApplication()` | Nakonfigurujte metadata aplikace (povinné, jedno na aplikaci) |
| `defineObject()` | Definice vlastních objektů s poli |
| `defineLogicFunction()` | Definice logických funkcí s obslužnými funkcemi |
| `defineFrontComponent()` | Definujte frontendové komponenty pro vlastní uživatelské rozhraní |
| `defineRole()` | Konfigurace oprávnění rolí a přístupu k objektům |
| `defineField()` | Rozšiřte existující objekty o další pole |
| Funkce | Účel |
| ---------------------------- | ----------------------------------------------------------------- |
| `defineApplication()` | Nakonfigurujte metadata aplikace (povinné, jedno na aplikaci) |
| `defineObject()` | Definice vlastních objektů s poli |
| `defineLogicFunction()` | Definice logických funkcí s obslužnými funkcemi |
| `defineFrontComponent()` | Definujte frontendové komponenty pro vlastní uživatelské rozhraní |
| `defineRole()` | Konfigurace oprávnění rolí a přístupu k objektům |
| `defineField()` | Rozšiřte existující objekty o další pole |
| `defineView()` | Definujte uložená zobrazení pro objekty |
| `defineNavigationMenuItem()` | Definujte odkazy postranní navigace |
Tyto funkce validují vaši konfiguraci v době sestavení a poskytují automatické doplňování v IDE a typovou bezpečnost.
@@ -294,7 +321,7 @@ Každá aplikace má jeden soubor `application-config.ts`, který popisuje:
* **Identitu aplikace**: identifikátory, zobrazovaný název a popis.
* **Jak běží její funkce**: kterou roli používají pro oprávnění.
* **(Volitelné) proměnné**: dvojice klíč–hodnota zpřístupněné vašim funkcím jako proměnné prostředí.
* **(Optional) post-install function**: a logic function that runs after the app is installed.
* **(Volitelná) postinstalační funkce**: logic funkce, která se spouští po instalaci aplikace.
Use `defineApplication()` to define your application configuration:
@@ -327,7 +354,7 @@ Poznámky:
* Pole `universalIdentifier` jsou deterministická ID, která vlastníte; vygenerujte je jednou a udržujte je stabilní napříč synchronizacemi.
* `applicationVariables` se stanou proměnnými prostředí pro vaše funkce (například `DEFAULT_RECIPIENT_NAME` je dostupné jako `process.env.DEFAULT_RECIPIENT_NAME`).
* `defaultRoleUniversalIdentifier` se musí shodovat se souborem role (viz níže).
* `postInstallLogicFunctionUniversalIdentifier` (optional) points to a logic function that runs automatically after the app is installed. See [Post-install functions](#post-install-functions).
* `postInstallLogicFunctionUniversalIdentifier` (volitelné) odkazuje na logickou funkci, která se automaticky spustí po instalaci aplikace. Viz [Postinstalační funkce](#post-install-functions).
#### Role a oprávnění
@@ -466,11 +493,11 @@ Poznámky:
* Pole `triggers` je volitelné. Funkce bez spouštěčů lze použít jako pomocné funkce volané jinými funkcemi.
* V jedné funkci můžete kombinovat více typů spouštěčů.
### Post-install functions
### Postinstalační funkce
A post-install function is a logic function that runs automatically after your app is installed on a workspace. This is useful for one-time setup tasks such as seeding default data, creating initial records, or configuring workspace settings.
Postinstalační funkce je logic funkce, která se automaticky spouští po instalaci vaší aplikace do pracovního prostoru. To je užitečné pro jednorázové úlohy nastavení, jako je naplnění výchozími daty, vytvoření počátečních záznamů nebo konfigurace nastavení pracovního prostoru.
When you scaffold a new app with `create-twenty-app`, a post-install function is generated for you at `src/logic-functions/post-install.ts`:
Když vygenerujete kostru nové aplikace pomocí `create-twenty-app`, vytvoří se pro vás postinstalační funkce v `src/logic-functions/post-install.ts`:
```typescript
// src/logic-functions/post-install.ts
@@ -491,7 +518,7 @@ export default defineLogicFunction({
});
```
The function is wired into your app by referencing its universal identifier in `application-config.ts`:
Funkce je připojena do vaší aplikace odkazem na její univerzální identifikátor v `application-config.ts`:
```typescript
import { POST_INSTALL_UNIVERSAL_IDENTIFIER } from 'src/logic-functions/post-install';
@@ -502,7 +529,7 @@ export default defineApplication({
});
```
You can also manually execute the post-install function at any time using the CLI:
Postinstalační funkci můžete také kdykoli spustit ručně pomocí CLI:
```bash filename="Terminal"
yarn twenty function:execute --postInstall
@@ -510,10 +537,10 @@ yarn twenty function:execute --postInstall
Hlavní body:
* Post-install functions are standard logic functions — they use `defineLogicFunction()` like any other function.
* The `postInstallLogicFunctionUniversalIdentifier` field in `defineApplication()` is optional. If omitted, no function runs after installation.
* The default timeout is set to 300 seconds (5 minutes) to allow for longer setup tasks like data seeding.
* Post-install functions do not need triggers — they are invoked by the platform during installation or manually via `function:execute --postInstall`.
* Postinstalační funkce jsou standard logic funkce — používají `defineLogicFunction()` stejně jako jakákoli jiná funkce.
* Pole `postInstallLogicFunctionUniversalIdentifier` v `defineApplication()` je volitelné. Pokud je vynecháno, po instalaci se nespustí žádná funkce.
* Výchozí časový limit je nastaven na 300 sekund (5 minut), aby umožnil delší úlohy nastavení, jako je naplnění daty.
* Postinstalační funkce nepotřebují spouštěče — jsou spouštěny platformou během instalace nebo ručně pomocí `function:execute --postInstall`.
### Payload spouštěče trasy
@@ -27,7 +27,7 @@ Mit Apps können Sie Twenty-Anpassungen **als Code** erstellen und verwalten. An
Erstellen Sie mit dem offiziellen Scaffolder eine neue App, authentifizieren Sie sich und beginnen Sie mit der Entwicklung:
```bash filename="Terminal"
# Eine neue App erstellen
# Eine neue App erstellen (enthält standardmäßig alle Beispiele)
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
@@ -42,25 +42,38 @@ yarn twenty auth:login
yarn twenty app:dev
```
Das Scaffolding-Tool unterstützt drei Modi, um zu steuern, welche Beispieldateien enthalten sind:
```bash filename="Terminal"
# Standard (umfassend): alle Beispiele (Objekt, Feld, Logikfunktion, Frontend-Komponente, View, Navigationsmenüeintrag)
npx create-twenty-app@latest my-app
# Minimal: nur Kerndateien (application-config.ts und default-role.ts)
npx create-twenty-app@latest my-app --minimal
# Interaktiv: wähle aus, welche Beispiele enthalten sein sollen
npx create-twenty-app@latest my-app --interactive
```
Von hier aus können Sie:
```bash filename="Terminal"
# Add a new entity to your application (guided)
# Eine neue Entität zu Ihrer Anwendung hinzufügen (geführt)
yarn twenty entity:add
# Watch your application's function logs
# Die Funktionsprotokolle Ihrer Anwendung überwachen
yarn twenty function:logs
# Execute a function by name
# Eine Funktion anhand ihres Namens ausführen
yarn twenty function:execute -n my-function -p '{"name": "test"}'
# Execute the post-install function
# Die Post-Installationsfunktion ausführen
yarn twenty function:execute --postInstall
# Uninstall the application from the current workspace
# Die Anwendung aus dem aktuellen Arbeitsbereich deinstallieren
yarn twenty app:uninstall
# Display commands' help
# Hilfe zu Befehlen anzeigen
yarn twenty help
```
@@ -73,9 +86,9 @@ Wenn Sie `npx create-twenty-app@latest my-twenty-app` ausführen, erledigt der S
* Kopiert eine minimale Basisanwendung nach `my-twenty-app/`
* Fügt eine lokale `twenty-sdk`-Abhängigkeit und die Yarn-4-Konfiguration hinzu
* Erstellt Konfigurationsdateien und Skripte, die an die `twenty`-CLI angebunden sind
* Generates a default application config, a default function role, and a post-install function
* Erzeugt Kerndateien (Anwendungskonfiguration, Standardrolle für Logikfunktionen, Post-Installationsfunktion) sowie Beispieldateien entsprechend dem Scaffolding-Modus
Eine frisch erzeugte App sieht so aus:
Eine frisch erstellte App mit dem Standardmodus `--exhaustive` sieht so aus:
```text filename="my-twenty-app/"
my-twenty-app/
@@ -89,18 +102,28 @@ my-twenty-app/
eslint.config.mjs
tsconfig.json
README.md
public/ # Public assets folder (images, fonts, etc.)
public/ # Ordner für öffentliche Assets (Bilder, Schriftarten usw.)
src/
├── application-config.ts # Required - main application configuration
├── roles/
│ └── default-role.ts # Default role for logic functions
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ └── post-install.ts # Post-install logic function
└── front-components/
└── hello-world.tsx # Example front component
application-config.ts # Erforderlich  Hauptkonfiguration der Anwendung
roles/
 default-role.ts # Standardrolle für Logikfunktionen
objects/
 example-object.ts # Beispiel für eine benutzerdefinierte Objektdefinition
fields/
 example-field.ts # Beispiel für eine eigenständige Felddefinition
logic-functions/
 hello-world.ts # Beispiel für eine Logikfunktion
 post-install.ts # Post-Installations-Logikfunktion
front-components/
 hello-world.tsx # Beispiel für eine Frontend-Komponente
views/
 example-view.ts # Beispiel für eine gespeicherte View-Definition
navigation-menu-items/
example-navigation-menu-item.ts # Beispiel für einen Navigationslink in der Seitenleiste
```
Mit `--minimal` werden nur die Kerndateien erstellt (`application-config.ts`, `roles/default-role.ts` und `logic-functions/post-install.ts`). Mit `--interactive` wählst du aus, welche Beispieldateien enthalten sein sollen.
Auf hoher Ebene:
* **package.json**: Deklariert den App-Namen, die Version und die Engines (Node 24+, Yarn 4) und fügt `twenty-sdk` sowie ein `twenty`-Skript hinzu, das an die lokale `twenty`-CLI delegiert. Führe `yarn twenty help` aus, um alle verfügbaren Befehle aufzulisten.
@@ -116,13 +139,15 @@ Auf hoher Ebene:
Das SDK erkennt Entitäten, indem es Ihre TypeScript-Dateien nach Aufrufen von **`export default define<Entity>({...})`** parst. Für jeden Entitätstyp gibt es eine entsprechende Hilfsfunktion, die aus `twenty-sdk` exportiert wird:
| Hilfsfunktion | Entitätstyp |
| ------------------------ | ---------------------------------------- |
| `defineObject()` | Benutzerdefinierte Objektdefinitionen |
| `defineLogicFunction()` | Definitionen von Logikfunktionen |
| `defineFrontComponent()` | Definitionen von Frontend-Komponenten |
| `defineRole()` | Rollendefinitionen |
| `defineField()` | Felderweiterungen für bestehende Objekte |
| Hilfsfunktion | Entitätstyp |
| ---------------------------- | ----------------------------------------- |
| `defineObject()` | Benutzerdefinierte Objektdefinitionen |
| `defineLogicFunction()` | Definitionen von Logikfunktionen |
| `defineFrontComponent()` | Definitionen von Frontend-Komponenten |
| `defineRole()` | Rollendefinitionen |
| `defineField()` | Felderweiterungen für bestehende Objekte |
| `defineView()` | Gespeicherte View-Definitionen |
| `defineNavigationMenuItem()` | Definitionen von Navigationsmenüeinträgen |
<Note>
**Dateibenennung ist flexibel.** Die Entitätserkennung ist AST-basiert — das SDK durchsucht Ihre Quelldateien nach dem Muster `export default define<Entity>({...})`. Sie können Ihre Dateien und Ordner nach Belieben organisieren. Die Gruppierung nach Entitätstyp (z. B. `logic-functions/`, `roles/`) ist lediglich eine Konvention zur Codeorganisation, keine Voraussetzung.
@@ -187,14 +212,16 @@ Das twenty-sdk stellt typisierte Bausteine und Hilfsfunktionen bereit, die Sie i
Das SDK stellt Hilfsfunktionen bereit, um die Entitäten Ihrer App zu definieren. Wie in [Entitätserkennung](#entity-detection) beschrieben, müssen Sie `export default define<Entity>({...})` verwenden, damit Ihre Entitäten erkannt werden:
| Funktion | Zweck |
| ------------------------ | -------------------------------------------------------------- |
| `defineApplication()` | Anwendungsmetadaten konfigurieren (erforderlich, eine pro App) |
| `defineObject()` | Benutzerdefinierte Objekte mit Feldern definieren |
| `defineLogicFunction()` | Logikfunktionen mit Handlern definieren |
| `defineFrontComponent()` | Frontend-Komponenten für benutzerdefinierte UI definieren |
| `defineRole()` | Rollenberechtigungen und Objektzugriff konfigurieren |
| `defineField()` | Bestehende Objekte mit zusätzlichen Feldern erweitern |
| Funktion | Zweck |
| ---------------------------- | -------------------------------------------------------------- |
| `defineApplication()` | Anwendungsmetadaten konfigurieren (erforderlich, eine pro App) |
| `defineObject()` | Benutzerdefinierte Objekte mit Feldern definieren |
| `defineLogicFunction()` | Logikfunktionen mit Handlern definieren |
| `defineFrontComponent()` | Frontend-Komponenten für benutzerdefinierte UI definieren |
| `defineRole()` | Rollenberechtigungen und Objektzugriff konfigurieren |
| `defineField()` | Bestehende Objekte mit zusätzlichen Feldern erweitern |
| `defineView()` | Gespeicherte Views für Objekte definieren |
| `defineNavigationMenuItem()` | Seitenleisten-Navigationslinks definieren |
Diese Funktionen validieren Ihre Konfiguration zur Build-Zeit und bieten IDE-Autovervollständigung sowie Typsicherheit.
@@ -294,7 +321,7 @@ Jede App hat eine einzelne Datei `application-config.ts`, die Folgendes beschrei
* **Was die App ist**: Bezeichner, Anzeigename und Beschreibung.
* **Wie ihre Funktionen ausgeführt werden**: welche Rolle sie für Berechtigungen verwenden.
* **(Optional) Variablen**: SchlüsselWert-Paare, die Ihren Funktionen als Umgebungsvariablen zur Verfügung gestellt werden.
* **(Optional) post-install function**: a logic function that runs after the app is installed.
* **(Optional) Post-Installationsfunktion**: eine Logikfunktion, die nach der Installation der App ausgeführt wird.
Verwenden Sie `defineApplication()`, um Ihre Anwendungskonfiguration zu definieren:
@@ -327,7 +354,7 @@ Notizen:
* `universalIdentifier`-Felder sind deterministische IDs, die Sie besitzen; generieren Sie sie einmal und halten Sie sie über Synchronisierungen hinweg stabil.
* `applicationVariables` werden zu Umgebungsvariablen für Ihre Funktionen (zum Beispiel ist `DEFAULT_RECIPIENT_NAME` als `process.env.DEFAULT_RECIPIENT_NAME` verfügbar).
* `defaultRoleUniversalIdentifier` muss mit der Rollendatei übereinstimmen (siehe unten).
* `postInstallLogicFunctionUniversalIdentifier` (optional) points to a logic function that runs automatically after the app is installed. See [Post-install functions](#post-install-functions).
* `postInstallLogicFunctionUniversalIdentifier` (optional) verweist auf eine Logikfunktion, die nach der Installation der App automatisch ausgeführt wird. Siehe [Post-Installationsfunktionen](#post-install-functions).
#### Rollen und Berechtigungen
@@ -466,11 +493,11 @@ Notizen:
* Das Array `triggers` ist optional. Funktionen ohne Trigger können als von anderen Funktionen aufgerufene Utility-Funktionen verwendet werden.
* Sie können mehrere Trigger-Typen in einer Funktion kombinieren.
### Post-install functions
### Post-Installationsfunktionen
A post-install function is a logic function that runs automatically after your app is installed on a workspace. This is useful for one-time setup tasks such as seeding default data, creating initial records, or configuring workspace settings.
Eine Post-Installationsfunktion ist eine Logikfunktion, die automatisch ausgeführt wird, nachdem Ihre App in einem Arbeitsbereich installiert wurde. Dies ist nützlich für einmalige Einrichtungsvorgänge wie das Befüllen mit Standarddaten, das Erstellen erster Datensätze oder das Konfigurieren von Arbeitsbereichseinstellungen.
When you scaffold a new app with `create-twenty-app`, a post-install function is generated for you at `src/logic-functions/post-install.ts`:
Wenn du mit `create-twenty-app` eine neue App erstellst, wird für dich eine Post-Installationsfunktion unter `src/logic-functions/post-install.ts` erzeugt:
```typescript
// src/logic-functions/post-install.ts
@@ -491,7 +518,7 @@ export default defineLogicFunction({
});
```
The function is wired into your app by referencing its universal identifier in `application-config.ts`:
Die Funktion wird in deine App eingebunden, indem ihr universeller Bezeichner in `application-config.ts` referenziert wird:
```typescript
import { POST_INSTALL_UNIVERSAL_IDENTIFIER } from 'src/logic-functions/post-install';
@@ -502,7 +529,7 @@ export default defineApplication({
});
```
You can also manually execute the post-install function at any time using the CLI:
Du kannst die Post-Installationsfunktion auch jederzeit manuell über die CLI ausführen:
```bash filename="Terminal"
yarn twenty function:execute --postInstall
@@ -510,10 +537,10 @@ yarn twenty function:execute --postInstall
Hauptpunkte:
* Post-install functions are standard logic functionsthey use `defineLogicFunction()` like any other function.
* The `postInstallLogicFunctionUniversalIdentifier` field in `defineApplication()` is optional. If omitted, no function runs after installation.
* The default timeout is set to 300 seconds (5 minutes) to allow for longer setup tasks like data seeding.
* Post-install functions do not need triggersthey are invoked by the platform during installation or manually via `function:execute --postInstall`.
* Post-Installationsfunktionen sind Standard-Logikfunktionensie verwenden `defineLogicFunction()` wie jede andere Funktion.
* Das Feld `postInstallLogicFunctionUniversalIdentifier` in `defineApplication()` ist optional. Wenn es weggelassen wird, wird nach der Installation keine Funktion ausgeführt.
* Das standardmäßige Timeout ist auf 300 Sekunden (5 Minuten) festgelegt, um längere Einrichtungsvorgänge wie Daten-Seeding zu ermöglichen.
* Post-Installationsfunktionen benötigen keine Trigger — sie werden von der Plattform während der Installation oder manuell über `function:execute --postInstall` aufgerufen.
### Routen-Trigger-Payload
@@ -27,40 +27,53 @@ Le app ti consentono di creare e gestire le personalizzazioni di Twenty **come c
Crea una nuova app utilizzando lo scaffolder ufficiale, quindi autenticati e inizia a sviluppare:
```bash filename="Terminal"
# Crea lo scaffold di una nuova app
# Scaffold a new app (includes all examples by default)
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
# Se non usi yarn@4
# If you don't use yarn@4
corepack enable
yarn install
# Autenticati usando la tua API key (ti verrà richiesto)
# Authenticate using your API key (you'll be prompted)
yarn twenty auth:login
# Avvia la modalità di sviluppo: sincronizza automaticamente le modifiche locali con il tuo workspace
# Start dev mode: automatically syncs local changes to your workspace
yarn twenty app:dev
```
The scaffolder supports three modes for controlling which example files are included:
```bash filename="Terminal"
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item)
npx create-twenty-app@latest my-app
# Minimal: only core files (application-config.ts and default-role.ts)
npx create-twenty-app@latest my-app --minimal
# Interactive: select which examples to include
npx create-twenty-app@latest my-app --interactive
```
Da qui puoi:
```bash filename="Terminal"
# Add a new entity to your application (guided)
# Aggiungi una nuova entità alla tua applicazione (guidata)
yarn twenty entity:add
# Watch your application's function logs
# Monitora i log delle funzioni della tua applicazione
yarn twenty function:logs
# Execute a function by name
# Esegui una funzione per nome
yarn twenty function:execute -n my-function -p '{"name": "test"}'
# Execute the post-install function
# Esegui la funzione post-installazione
yarn twenty function:execute --postInstall
# Uninstall the application from the current workspace
# Disinstalla l'applicazione dallo spazio di lavoro corrente
yarn twenty app:uninstall
# Display commands' help
# Mostra l'aiuto dei comandi
yarn twenty help
```
@@ -73,9 +86,9 @@ Quando esegui `npx create-twenty-app@latest my-twenty-app`, lo scaffolder:
* Copia un'applicazione base minimale in `my-twenty-app/`
* Aggiunge una dipendenza locale `twenty-sdk` e la configurazione di Yarn 4
* Crea file di configurazione e script collegati alla CLI `twenty`
* Generates a default application config, a default function role, and a post-install function
* Generates core files (application config, default function role, post-install function) plus example files based on the scaffolding mode
Un'app appena generata dallo scaffolder si presenta così:
A freshly scaffolded app with the default `--exhaustive` mode looks like this:
```text filename="my-twenty-app/"
my-twenty-app/
@@ -94,13 +107,23 @@ my-twenty-app/
├── application-config.ts # Required - main application configuration
├── roles/
│ └── default-role.ts # Default role for logic functions
├── objects/
│ └── example-object.ts # Example custom object definition
├── fields/
│ └── example-field.ts # Example standalone field definition
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ └── post-install.ts # Post-install logic function
── front-components/
└── hello-world.tsx # Example front component
── front-components/
└── hello-world.tsx # Example front component
├── views/
│ └── example-view.ts # Example saved view definition
└── navigation-menu-items/
└── example-navigation-menu-item.ts # Example sidebar navigation link
```
With `--minimal`, only the core files are created (`application-config.ts`, `roles/default-role.ts`, and `logic-functions/post-install.ts`). With `--interactive`, you choose which example files to include.
A livello generale:
* **package.json**: Dichiara il nome dell'app, la versione, i motori (Node 24+, Yarn 4) e aggiunge `twenty-sdk` più uno script `twenty` che delega alla CLI locale `twenty`. Esegui `yarn twenty help` per elencare tutti i comandi disponibili.
@@ -116,13 +139,15 @@ A livello generale:
L'SDK rileva le entità analizzando i tuoi file TypeScript alla ricerca di chiamate **`export default define<Entity>({...})`**. Ogni tipo di entità ha una corrispondente funzione helper esportata da `twenty-sdk`:
| Funzione helper | Tipo di entità |
| ------------------------ | ----------------------------------------- |
| `defineObject()` | Definizioni di oggetti personalizzati |
| `defineLogicFunction()` | Definizioni di funzioni logiche |
| `defineFrontComponent()` | Definizioni dei componenti front-end |
| `defineRole()` | Definizioni di ruoli |
| `defineField()` | Estensioni di campo per oggetti esistenti |
| Funzione helper | Tipo di entità |
| ---------------------------- | ----------------------------------------- |
| `defineObject()` | Definizioni di oggetti personalizzati |
| `defineLogicFunction()` | Definizioni di funzioni logiche |
| `defineFrontComponent()` | Definizioni dei componenti front-end |
| `defineRole()` | Definizioni di ruoli |
| `defineField()` | Estensioni di campo per oggetti esistenti |
| `defineView()` | Saved view definitions |
| `defineNavigationMenuItem()` | Navigation menu item definitions |
<Note>
**La denominazione dei file è flessibile.** Il rilevamento delle entità è basato sull'AST — l'SDK esegue la scansione dei file sorgente alla ricerca del pattern `export default define<Entity>({...})`. Puoi organizzare file e cartelle come preferisci. Raggruppare per tipo di entità (ad es., `logic-functions/`, `roles/`) è solo una convenzione per l'organizzazione del codice, non un requisito.
@@ -187,14 +212,16 @@ Il pacchetto twenty-sdk fornisce blocchi tipizzati e funzioni helper da usare ne
L'SDK fornisce funzioni helper per definire le entità della tua app. Come descritto in [Rilevamento delle entità](#entity-detection), devi usare `export default define<Entity>({...})` affinché le tue entità vengano rilevate:
| Funzione | Scopo |
| ------------------------ | ----------------------------------------------------------------------- |
| `defineApplication()` | Configura i metadati dell'applicazione (obbligatorio, uno per app) |
| `defineObject()` | Definisci oggetti personalizzati con campi |
| `defineLogicFunction()` | Definisci funzioni logiche con handler |
| `defineFrontComponent()` | Definisci componenti front-end per un'interfaccia utente personalizzata |
| `defineRole()` | Configura i permessi dei ruoli e l'accesso agli oggetti |
| `defineField()` | Estendi gli oggetti esistenti con campi aggiuntivi |
| Funzione | Scopo |
| ---------------------------- | ----------------------------------------------------------------------- |
| `defineApplication()` | Configura i metadati dell'applicazione (obbligatorio, uno per app) |
| `defineObject()` | Definisci oggetti personalizzati con campi |
| `defineLogicFunction()` | Definisci funzioni logiche con handler |
| `defineFrontComponent()` | Definisci componenti front-end per un'interfaccia utente personalizzata |
| `defineRole()` | Configura i permessi dei ruoli e l'accesso agli oggetti |
| `defineField()` | Estendi gli oggetti esistenti con campi aggiuntivi |
| `defineView()` | Define saved views for objects |
| `defineNavigationMenuItem()` | Define sidebar navigation links |
Queste funzioni convalidano la configurazione in fase di build e offrono il completamento automatico nell'IDE e la sicurezza dei tipi.
@@ -294,7 +321,7 @@ Ogni app ha un singolo file `application-config.ts` che descrive:
* **Identità dell'app**: identificatori, nome visualizzato e descrizione.
* **Come vengono eseguite le sue funzioni**: quale ruolo usano per i permessi.
* **Variabili (opzionali)**: coppie chiavevalore esposte alle funzioni come variabili d'ambiente.
* **(Optional) post-install function**: a logic function that runs after the app is installed.
* **(Opzionale) funzione post-installazione**: una funzione logica che viene eseguita dopo l'installazione dell'app.
Usa `defineApplication()` per definire la configurazione della tua applicazione:
@@ -327,7 +354,7 @@ Note:
* I campi `universalIdentifier` sono ID deterministici sotto il tuo controllo; generali una volta e mantienili stabili tra le sincronizzazioni.
* `applicationVariables` diventano variabili d'ambiente per le tue funzioni (ad esempio, `DEFAULT_RECIPIENT_NAME` è disponibile come `process.env.DEFAULT_RECIPIENT_NAME`).
* `defaultRoleUniversalIdentifier` deve corrispondere al file del ruolo (vedi sotto).
* `postInstallLogicFunctionUniversalIdentifier` (optional) points to a logic function that runs automatically after the app is installed. See [Post-install functions](#post-install-functions).
* `postInstallLogicFunctionUniversalIdentifier` (opzionale) fa riferimento a una funzione logica che viene eseguita automaticamente dopo l'installazione dell'app. Vedi [Funzioni post-installazione](#post-install-functions).
#### Ruoli e permessi
@@ -466,9 +493,9 @@ Note:
* L'array `triggers` è facoltativo. Le funzioni senza trigger possono essere utilizzate come funzioni di utilità richiamate da altre funzioni.
* Puoi combinare più tipi di trigger in un'unica funzione.
### Post-install functions
### Funzioni post-installazione
A post-install function is a logic function that runs automatically after your app is installed on a workspace. This is useful for one-time setup tasks such as seeding default data, creating initial records, or configuring workspace settings.
Una funzione post-installazione è una funzione logica che viene eseguita automaticamente dopo che la tua app è stata installata in uno spazio di lavoro. Questo è utile per attività di configurazione una tantum come il popolamento di dati predefiniti, la creazione di record iniziali o la configurazione delle impostazioni dello spazio di lavoro.
When you scaffold a new app with `create-twenty-app`, a post-install function is generated for you at `src/logic-functions/post-install.ts`:
@@ -27,7 +27,7 @@ Os aplicativos permitem criar e gerenciar personalizações do Twenty **como có
Crie um novo aplicativo usando o gerador oficial, depois autentique-se e comece a desenvolver:
```bash filename="Terminal"
# Scaffold a new app
# Scaffold a new app (includes all examples by default)
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
@@ -42,25 +42,38 @@ yarn twenty auth:login
yarn twenty app:dev
```
The scaffolder supports three modes for controlling which example files are included:
```bash filename="Terminal"
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item)
npx create-twenty-app@latest my-app
# Minimal: only core files (application-config.ts and default-role.ts)
npx create-twenty-app@latest my-app --minimal
# Interactive: select which examples to include
npx create-twenty-app@latest my-app --interactive
```
A partir daqui você pode:
```bash filename="Terminal"
# Add a new entity to your application (guided)
# Adicionar uma nova entidade à sua aplicação (assistido)
yarn twenty entity:add
# Watch your application's function logs
# Acompanhar os logs das funções da sua aplicação
yarn twenty function:logs
# Execute a function by name
yarn twenty function:execute -n my-function -p '{"name": "test"}'
# Executar uma função pelo nome
yarn twenty function:execute -n my-function -p '{\"name\": \"test\"}'
# Execute the post-install function
# Executar a função de pós-instalação
yarn twenty function:execute --postInstall
# Uninstall the application from the current workspace
# Desinstalar a aplicação do espaço de trabalho atual
yarn twenty app:uninstall
# Display commands' help
# Exibir a ajuda dos comandos
yarn twenty help
```
@@ -73,9 +86,9 @@ Ao executar `npx create-twenty-app@latest my-twenty-app`, o gerador:
* Copia um aplicativo base mínimo para `my-twenty-app/`
* Adiciona uma dependência local `twenty-sdk` e a configuração do Yarn 4
* Cria arquivos de configuração e scripts conectados à CLI `twenty`
* Generates a default application config, a default function role, and a post-install function
* Generates core files (application config, default function role, post-install function) plus example files based on the scaffolding mode
Um aplicativo recém-criado pelo scaffold fica assim:
A freshly scaffolded app with the default `--exhaustive` mode looks like this:
```text filename="my-twenty-app/"
my-twenty-app/
@@ -94,13 +107,23 @@ my-twenty-app/
├── application-config.ts # Required - main application configuration
├── roles/
│ └── default-role.ts # Default role for logic functions
├── objects/
│ └── example-object.ts # Example custom object definition
├── fields/
│ └── example-field.ts # Example standalone field definition
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ └── post-install.ts # Post-install logic function
── front-components/
└── hello-world.tsx # Example front component
── front-components/
└── hello-world.tsx # Example front component
├── views/
│ └── example-view.ts # Example saved view definition
└── navigation-menu-items/
└── example-navigation-menu-item.ts # Example sidebar navigation link
```
With `--minimal`, only the core files are created (`application-config.ts`, `roles/default-role.ts`, and `logic-functions/post-install.ts`). With `--interactive`, you choose which example files to include.
Em alto nível:
* **package.json**: Declara o nome do app, versão, engines (Node 24+, Yarn 4), e adiciona `twenty-sdk` além de um script `twenty` que delega para a CLI `twenty` local. Execute `yarn twenty help` para listar todos os comandos disponíveis.
@@ -116,13 +139,15 @@ Em alto nível:
O SDK detecta entidades analisando seus arquivos TypeScript em busca de chamadas **`export default define<Entity>({...})`**. Cada tipo de entidade tem uma função utilitária correspondente exportada de `twenty-sdk`:
| Função utilitária | Tipo de entidade |
| ------------------------ | ------------------------------------------- |
| `defineObject()` | Definições de objetos personalizados |
| `defineLogicFunction()` | Definições de funções de lógica |
| `defineFrontComponent()` | Definições de componentes de front-end |
| `defineRole()` | Definições de papéis |
| `defineField()` | Extensões de campos para objetos existentes |
| Função utilitária | Tipo de entidade |
| ---------------------------- | ------------------------------------------- |
| `defineObject()` | Definições de objetos personalizados |
| `defineLogicFunction()` | Definições de funções de lógica |
| `defineFrontComponent()` | Definições de componentes de front-end |
| `defineRole()` | Definições de papéis |
| `defineField()` | Extensões de campos para objetos existentes |
| `defineView()` | Saved view definitions |
| `defineNavigationMenuItem()` | Navigation menu item definitions |
<Note>
**A nomeação de arquivos é flexível.** A detecção de entidades é baseada em AST — o SDK varre seus arquivos fonte em busca do padrão `export default define<Entity>({...})`. Você pode organizar seus arquivos e pastas como quiser. Agrupar por tipo de entidade (por exemplo, `logic-functions/`, `roles/`) é apenas uma convenção para organização do código, não um requisito.
@@ -187,14 +212,16 @@ O twenty-sdk fornece blocos de construção tipados e funções utilitárias que
O SDK fornece funções utilitárias para definir as entidades do seu app. Conforme descrito em [Detecção de entidades](#entity-detection), você deve usar `export default define<Entity>({...})` para que suas entidades sejam detectadas:
| Função | Finalidade |
| ------------------------ | ------------------------------------------------------------ |
| `defineApplication()` | Configurar metadados do aplicativo (obrigatório, um por app) |
| `defineObject()` | Define objetos personalizados com campos |
| `defineLogicFunction()` | Defina funções de lógica com handlers |
| `defineFrontComponent()` | Definir componentes de front-end para UI personalizada |
| `defineRole()` | Configura permissões de papéis e acesso a objetos |
| `defineField()` | Estender objetos existentes com campos adicionais |
| Função | Finalidade |
| ---------------------------- | ------------------------------------------------------------ |
| `defineApplication()` | Configurar metadados do aplicativo (obrigatório, um por app) |
| `defineObject()` | Define objetos personalizados com campos |
| `defineLogicFunction()` | Defina funções de lógica com handlers |
| `defineFrontComponent()` | Definir componentes de front-end para UI personalizada |
| `defineRole()` | Configura permissões de papéis e acesso a objetos |
| `defineField()` | Estender objetos existentes com campos adicionais |
| `defineView()` | Define saved views for objects |
| `defineNavigationMenuItem()` | Define sidebar navigation links |
Essas funções validam sua configuração em tempo de compilação e oferecem autocompletar na IDE e segurança de tipos.
@@ -294,7 +321,7 @@ Todo aplicativo tem um único arquivo `application-config.ts` que descreve:
* **O que é o aplicativo**: identificadores, nome de exibição e descrição.
* **Como suas funções são executadas**: qual papel usam para permissões.
* **Variáveis (opcional)**: pares chavevalor expostos às suas funções como variáveis de ambiente.
* **(Optional) post-install function**: a logic function that runs after the app is installed.
* **(Opcional) função de pós-instalação**: uma função de lógica que é executada após a instalação da aplicação.
Use `defineApplication()` to define your application configuration:
@@ -327,7 +354,7 @@ Notas:
* `universalIdentifier` são IDs determinísticos que você controla; gere-os uma vez e mantenha-os estáveis entre sincronizações.
* `applicationVariables` tornam-se variáveis de ambiente para suas funções (por exemplo, `DEFAULT_RECIPIENT_NAME` fica disponível como `process.env.DEFAULT_RECIPIENT_NAME`).
* `defaultRoleUniversalIdentifier` deve corresponder ao arquivo do papel (veja abaixo).
* `postInstallLogicFunctionUniversalIdentifier` (optional) points to a logic function that runs automatically after the app is installed. See [Post-install functions](#post-install-functions).
* `postInstallLogicFunctionUniversalIdentifier` (opcional) aponta para uma função de lógica que é executada automaticamente após a instalação da aplicação. Consulte [Funções de pós-instalação](#post-install-functions).
#### Papéis e permissões
@@ -466,9 +493,9 @@ Notas:
* O array `triggers` é opcional. Funções sem gatilhos podem ser usadas como funções utilitárias chamadas por outras funções.
* Você pode misturar vários tipos de gatilho em uma única função.
### Post-install functions
### Funções de pós-instalação
A post-install function is a logic function that runs automatically after your app is installed on a workspace. This is useful for one-time setup tasks such as seeding default data, creating initial records, or configuring workspace settings.
Uma função de pós-instalação é uma função de lógica que é executada automaticamente após a sua aplicação ser instalada em um espaço de trabalho. Isso é útil para tarefas de configuração únicas, como preencher dados padrão, criar registros iniciais ou configurar as configurações do espaço de trabalho.
When you scaffold a new app with `create-twenty-app`, a post-install function is generated for you at `src/logic-functions/post-install.ts`:
@@ -27,7 +27,7 @@ Aplicațiile vă permit să construiți și să gestionați personalizările Twe
Creați o aplicație nouă folosind generatorul oficial, apoi autentificați-vă și începeți să dezvoltați:
```bash filename="Terminal"
# Creează scheletul unei aplicații noi
# Creează scheletul unei aplicații noi (include toate exemplele în mod implicit)
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
@@ -42,6 +42,19 @@ yarn twenty auth:login
yarn twenty app:dev
```
Generatorul de schelet acceptă trei moduri pentru a controla ce fișiere de exemplu sunt incluse:
```bash filename="Terminal"
# Implicit (exhaustiv): toate exemplele (obiect, câmp, funcție logică, componentă de interfață, vizualizare, element de meniu de navigare)
npx create-twenty-app@latest my-app
# Minimal: doar fișierele de bază (application-config.ts și default-role.ts)
npx create-twenty-app@latest my-app --minimal
# Interactiv: selectezi ce exemple să incluzi
npx create-twenty-app@latest my-app --interactive
```
De aici puteți:
```bash filename="Terminal"
@@ -73,9 +86,9 @@ Când rulați `npx create-twenty-app@latest my-twenty-app`, generatorul:
* Copiază o aplicație de bază minimală în `my-twenty-app/`
* Adaugă o dependență locală `twenty-sdk` și configurația Yarn 4
* Creează fișiere de configurare și scripturi conectate la CLI-ul `twenty`
* Generează o configurație implicită a aplicației, un rol implicit pentru funcții și o funcție post-instalare
* Generează fișierele de bază (configurația aplicației, rolul implicit al funcțiilor, funcția post-instalare) plus fișiere de exemplu în funcție de modul de generare a scheletului
O aplicație nou generată arată astfel:
O aplicație proaspăt generată cu modul implicit `--exhaustive` arată astfel:
```text filename="my-twenty-app/"
my-twenty-app/
@@ -94,13 +107,23 @@ my-twenty-app/
├── application-config.ts # Obligatoriu - configurația principală a aplicației
├── roles/
│ └── default-role.ts # Rol implicit pentru funcțiile logice
├── objects/
│ └── example-object.ts # Exemplu de definiție a unui obiect personalizat
├── fields/
│ └── example-field.ts # Exemplu de definiție de câmp independent
├── logic-functions/
│ ├── hello-world.ts # Exemplu de funcție logică
│ └── post-install.ts # Funcție logică post-instalare
── front-components/
└── hello-world.tsx # Exemplu de componentă de interfață
── front-components/
└── hello-world.tsx # Exemplu de componentă de interfață
├── views/
│ └── example-view.ts # Exemplu de definiție a unei vizualizări salvate
└── navigation-menu-items/
└── example-navigation-menu-item.ts # Exemplu de link de navigare în bara laterală
```
Cu `--minimal`, sunt create doar fișierele de bază (`application-config.ts`, `roles/default-role.ts` și `logic-functions/post-install.ts`). Cu `--interactive`, alegi ce fișiere de exemplu să incluzi.
Pe scurt:
* **package.json**: Declară numele aplicației, versiunea, motoarele (Node 24+, Yarn 4) și adaugă `twenty-sdk` plus un script `twenty` care deleagă către CLI-ul local `twenty`. Rulează `yarn twenty help` pentru a lista toate comenzile disponibile.
@@ -116,13 +139,15 @@ Pe scurt:
SDK-ul detectează entitățile analizând fișierele TypeScript pentru apeluri **`export default define<Entity>({...})`**. Fiecare tip de entitate are o funcție ajutătoare corespunzătoare, exportată din `twenty-sdk`:
| Funcție ajutătoare | Tipul entității |
| ------------------------ | ------------------------------------------- |
| `defineObject()` | Definiții de obiecte personalizate |
| `defineLogicFunction()` | Definiții de funcții de logică |
| `defineFrontComponent()` | Definiții ale componentelor de interfață |
| `defineRole()` | Definiții de rol |
| `defineField()` | Extensii de câmp pentru obiectele existente |
| Funcție ajutătoare | Tipul entității |
| ---------------------------- | ---------------------------------------------- |
| `defineObject()` | Definiții de obiecte personalizate |
| `defineLogicFunction()` | Definiții de funcții de logică |
| `defineFrontComponent()` | Definiții ale componentelor de interfață |
| `defineRole()` | Definiții de rol |
| `defineField()` | Extensii de câmp pentru obiectele existente |
| `defineView()` | Definiții pentru vizualizări salvate |
| `defineNavigationMenuItem()` | Definiții pentru elemente de meniu de navigare |
<Note>
**Denumirea fișierelor este flexibilă.** Detectarea entităților se bazează pe AST — SDK-ul scanează fișierele sursă pentru tiparul `export default define<Entity>({...})`. Puteți organiza fișierele și folderele cum doriți. Gruparea după tipul de entitate (de exemplu, `logic-functions/`, `roles/`) este doar o convenție pentru organizarea codului, nu o cerință.
@@ -187,14 +212,16 @@ Biblioteca twenty-sdk oferă blocuri de bază tipizate și funcții ajutătoare
SDK-ul oferă funcții ajutătoare pentru definirea entităților aplicației. După cum este descris în [Detectarea entităților](#entity-detection), trebuie să folosiți `export default define<Entity>({...})` pentru ca entitățile să fie detectate:
| Funcție | Scop |
| ------------------------ | ---------------------------------------------------------------------- |
| `defineApplication()` | Configurați metadatele aplicației (obligatoriu, una per aplicație) |
| `defineObject()` | Definiți obiecte personalizate cu câmpuri |
| `defineLogicFunction()` | Definiți funcții de logică cu handleri |
| `defineFrontComponent()` | Definiți componente Front pentru interfața de utilizator personalizată |
| `defineRole()` | Configurați permisiunile rolurilor și accesul la obiecte |
| `defineField()` | Extindeți obiectele existente cu câmpuri suplimentare |
| Funcție | Scop |
| ---------------------------- | ---------------------------------------------------------------------- |
| `defineApplication()` | Configurați metadatele aplicației (obligatoriu, una per aplicație) |
| `defineObject()` | Definiți obiecte personalizate cu câmpuri |
| `defineLogicFunction()` | Definiți funcții de logică cu handleri |
| `defineFrontComponent()` | Definiți componente Front pentru interfața de utilizator personalizată |
| `defineRole()` | Configurați permisiunile rolurilor și accesul la obiecte |
| `defineField()` | Extindeți obiectele existente cu câmpuri suplimentare |
| `defineView()` | Definește vizualizări salvate pentru obiecte |
| `defineNavigationMenuItem()` | Definește linkuri de navigare în bara laterală |
Aceste funcții validează configurația în timpul build-ului și oferă completare automată în IDE și siguranța tipurilor.
@@ -470,7 +497,7 @@ Notițe:
O funcție post-instalare este o funcție logică care rulează automat după instalarea aplicației într-un spațiu de lucru. Aceasta este utilă pentru sarcini de configurare unice, cum ar fi popularea cu date implicite, crearea înregistrărilor inițiale sau configurarea setărilor spațiului de lucru.
When you scaffold a new app with `create-twenty-app`, a post-install function is generated for you at `src/logic-functions/post-install.ts`:
Când creezi scheletul unei aplicații noi cu `create-twenty-app`, este generată o funcție post-instalare la `src/logic-functions/post-install.ts`:
```typescript
// src/logic-functions/post-install.ts
@@ -491,7 +518,7 @@ export default defineLogicFunction({
});
```
The function is wired into your app by referencing its universal identifier in `application-config.ts`:
Funcția este integrată în aplicația ta prin referirea la identificatorul său universal în `application-config.ts`:
```typescript
import { POST_INSTALL_UNIVERSAL_IDENTIFIER } from 'src/logic-functions/post-install';
@@ -502,7 +529,7 @@ export default defineApplication({
});
```
You can also manually execute the post-install function at any time using the CLI:
Poți, de asemenea, să execuți manual funcția post-instalare oricând folosind CLI:
```bash filename="Terminal"
yarn twenty function:execute --postInstall
@@ -510,10 +537,10 @@ yarn twenty function:execute --postInstall
Puncte cheie:
* Post-install functions are standard logic functions — they use `defineLogicFunction()` like any other function.
* The `postInstallLogicFunctionUniversalIdentifier` field in `defineApplication()` is optional. If omitted, no function runs after installation.
* The default timeout is set to 300 seconds (5 minutes) to allow for longer setup tasks like data seeding.
* Post-install functions do not need triggers — they are invoked by the platform during installation or manually via `function:execute --postInstall`.
* Funcțiile post-instalare sunt funcții logice standard — folosesc `defineLogicFunction()` la fel ca orice altă funcție.
* Câmpul `postInstallLogicFunctionUniversalIdentifier` din `defineApplication()` este opțional. Dacă este omis, nu rulează nicio funcție după instalare.
* Timpul de expirare implicit este setat la 300 de secunde (5 minute) pentru a permite sarcini de configurare mai lungi, cum ar fi popularea datelor.
* Funcțiile post-instalare nu au nevoie de declanșatoare — sunt invocate de platformă în timpul instalării sau manual prin `function:execute --postInstall`.
### Payload-ul declanșatorului de rută
@@ -27,40 +27,53 @@ description: Создавайте и управляйте настройками
Создайте новое приложение с помощью официального генератора, затем выполните аутентификацию и начните разработку:
```bash filename="Terminal"
# Создать каркас нового приложения
# Scaffold a new app (includes all examples by default)
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
# Если вы не используете yarn@4
# If you don't use yarn@4
corepack enable
yarn install
# Аутентифицироваться с помощью вашего API-ключа (вам будет предложено)
# Authenticate using your API key (you'll be prompted)
yarn twenty auth:login
# Запустить режим разработки: автоматически синхронизирует локальные изменения с вашим рабочим пространством
# Start dev mode: automatically syncs local changes to your workspace
yarn twenty app:dev
```
The scaffolder supports three modes for controlling which example files are included:
```bash filename="Terminal"
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item)
npx create-twenty-app@latest my-app
# Minimal: only core files (application-config.ts and default-role.ts)
npx create-twenty-app@latest my-app --minimal
# Interactive: select which examples to include
npx create-twenty-app@latest my-app --interactive
```
Отсюда вы можете:
```bash filename="Terminal"
# Add a new entity to your application (guided)
# Добавить новую сущность в ваше приложение (с мастером)
yarn twenty entity:add
# Watch your application's function logs
# Просматривать логи функций вашего приложения
yarn twenty function:logs
# Execute a function by name
yarn twenty function:execute -n my-function -p '{"name": "test"}'
# Выполнить функцию по имени
yarn twenty function:execute -n my-function -p '{\"name\": \"test\"}'
# Execute the post-install function
# Выполнить послеустановочную функцию
yarn twenty function:execute --postInstall
# Uninstall the application from the current workspace
# Удалить приложение из текущего рабочего пространства
yarn twenty app:uninstall
# Display commands' help
# Показать справку по командам
yarn twenty help
```
@@ -73,9 +86,9 @@ yarn twenty help
* Копирует минимальное базовое приложение в `my-twenty-app/`
* Добавляет локальную зависимость `twenty-sdk` и конфигурацию Yarn 4
* Создаёт файлы конфигурации и скрипты, подключённые к CLI `twenty`
* Generates a default application config, a default function role, and a post-install function
* Generates core files (application config, default function role, post-install function) plus example files based on the scaffolding mode
Свежесгенерированное приложение выглядит так:
A freshly scaffolded app with the default `--exhaustive` mode looks like this:
```text filename="my-twenty-app/"
my-twenty-app/
@@ -94,13 +107,23 @@ my-twenty-app/
├── application-config.ts # Required - main application configuration
├── roles/
│ └── default-role.ts # Default role for logic functions
├── objects/
│ └── example-object.ts # Example custom object definition
├── fields/
│ └── example-field.ts # Example standalone field definition
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ └── post-install.ts # Post-install logic function
── front-components/
└── hello-world.tsx # Example front component
── front-components/
└── hello-world.tsx # Example front component
├── views/
│ └── example-view.ts # Example saved view definition
└── navigation-menu-items/
└── example-navigation-menu-item.ts # Example sidebar navigation link
```
With `--minimal`, only the core files are created (`application-config.ts`, `roles/default-role.ts`, and `logic-functions/post-install.ts`). With `--interactive`, you choose which example files to include.
В общих чертах:
* **package.json**: Объявляет имя приложения, версию, движки (Node 24+, Yarn 4) и добавляет `twenty-sdk`, а также скрипт `twenty`, который делегирует выполнение локальному CLI `twenty`. Выполните `yarn twenty help`, чтобы вывести список всех доступных команд.
@@ -116,13 +139,15 @@ my-twenty-app/
SDK обнаруживает сущности, разбирая ваши файлы TypeScript в поисках вызовов **`export default define<Entity>({...})`**. Для каждого типа сущности существует соответствующая вспомогательная функция, экспортируемая из `twenty-sdk`:
| Вспомогательная функция | Тип сущности |
| ------------------------ | ------------------------------------------ |
| `defineObject()` | Определения пользовательских объектов |
| `defineLogicFunction()` | Определения логических функций |
| `defineFrontComponent()` | Определения компонентов фронтенда |
| `defineRole()` | Определения ролей |
| `defineField()` | Расширения полей для существующих объектов |
| Вспомогательная функция | Тип сущности |
| ---------------------------- | ------------------------------------------ |
| `defineObject()` | Определения пользовательских объектов |
| `defineLogicFunction()` | Определения логических функций |
| `defineFrontComponent()` | Определения компонентов фронтенда |
| `defineRole()` | Определения ролей |
| `defineField()` | Расширения полей для существующих объектов |
| `defineView()` | Saved view definitions |
| `defineNavigationMenuItem()` | Navigation menu item definitions |
<Note>
**Имена файлов заданы гибко.** Обнаружение сущностей основано на AST — SDK сканирует ваши исходные файлы в поисках шаблона `export default define<Entity>({...})`. Вы можете организовывать файлы и папки как угодно. Группировка по типу сущности (например, `logic-functions/`, `roles/`) — это лишь соглашение для организации кода, а не требование.
@@ -187,14 +212,16 @@ yarn twenty auth:status
SDK предоставляет вспомогательные функции для определения сущностей вашего приложения. Как описано в [Обнаружение сущностей](#entity-detection), вы должны использовать `export default define<Entity>({...})`, чтобы ваши сущности были обнаружены:
| Функция | Назначение |
| ------------------------ | ---------------------------------------------------------------------- |
| `defineApplication()` | Настройка метаданных приложения (обязательно, по одному на приложение) |
| `defineObject()` | Определяет пользовательские объекты с полями |
| `defineLogicFunction()` | Определение логических функций с обработчиками |
| `defineFrontComponent()` | Определение фронт-компонентов для настраиваемого интерфейса |
| `defineRole()` | Настраивает права роли и доступ к объектам |
| `defineField()` | Расширение существующих объектов дополнительными полями |
| Функция | Назначение |
| ---------------------------- | ---------------------------------------------------------------------- |
| `defineApplication()` | Настройка метаданных приложения (обязательно, по одному на приложение) |
| `defineObject()` | Определяет пользовательские объекты с полями |
| `defineLogicFunction()` | Определение логических функций с обработчиками |
| `defineFrontComponent()` | Определение фронт-компонентов для настраиваемого интерфейса |
| `defineRole()` | Настраивает права роли и доступ к объектам |
| `defineField()` | Расширение существующих объектов дополнительными полями |
| `defineView()` | Define saved views for objects |
| `defineNavigationMenuItem()` | Define sidebar navigation links |
Эти функции проверяют вашу конфигурацию на этапе сборки и обеспечивают автодополнение в IDE и безопасность типов.
@@ -294,7 +321,7 @@ export default defineObject({
* **Что это за приложение**: идентификаторы, отображаемое имя и описание.
* **Как запускаются его функции**: какую роль они используют для прав доступа.
* **(Необязательно) переменные**: пары ключ-значение, предоставляемые вашим функциям как переменные окружения.
* **(Optional) post-install function**: a logic function that runs after the app is installed.
* **(Необязательно) послеустановочная функция**: функция логики, которая запускается после установки приложения.
Используйте `defineApplication()` для определения конфигурации вашего приложения:
@@ -327,7 +354,7 @@ export default defineApplication({
* `universalIdentifier` — это детерминированные идентификаторы, которыми вы управляете; сгенерируйте их один раз и сохраняйте стабильными между синхронизациями.
* `applicationVariables` становятся переменными окружения для ваших функций (например, `DEFAULT_RECIPIENT_NAME` доступна как `process.env.DEFAULT_RECIPIENT_NAME`).
* `defaultRoleUniversalIdentifier` должен соответствовать файлу роли (см. ниже).
* `postInstallLogicFunctionUniversalIdentifier` (optional) points to a logic function that runs automatically after the app is installed. See [Post-install functions](#post-install-functions).
* `postInstallLogicFunctionUniversalIdentifier` (необязательно) указывает на логическую функцию, которая автоматически выполняется после установки приложения. См. [Послеустановочные функции](#post-install-functions).
#### Роли и разрешения
@@ -466,9 +493,9 @@ export default defineLogicFunction({
* Массив `triggers` необязателен. Функции без триггеров можно использовать как вспомогательные, вызываемые другими функциями.
* Вы можете сочетать несколько типов триггеров в одной функции.
### Post-install functions
### Послеустановочные функции
A post-install function is a logic function that runs automatically after your app is installed on a workspace. This is useful for one-time setup tasks such as seeding default data, creating initial records, or configuring workspace settings.
Послеустановочная функция — это функция логики, которая автоматически выполняется после установки вашего приложения в рабочем пространстве. Это полезно для одноразовых задач настройки, таких как инициализация данных по умолчанию, создание начальных записей или настройка параметров рабочего пространства.
When you scaffold a new app with `create-twenty-app`, a post-install function is generated for you at `src/logic-functions/post-install.ts`:
@@ -27,7 +27,7 @@ Uygulamalar, Twenty özelleştirmelerini **kod olarak** oluşturup yönetmenizi
Resmi scaffolder aracını kullanarak yeni bir uygulama oluşturun, ardından kimlik doğrulaması yapıp geliştirmeye başlayın:
```bash filename="Terminal"
# Scaffold a new app
# Scaffold a new app (includes all examples by default)
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
@@ -42,6 +42,19 @@ yarn twenty auth:login
yarn twenty app:dev
```
The scaffolder supports three modes for controlling which example files are included:
```bash filename="Terminal"
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item)
npx create-twenty-app@latest my-app
# Minimal: only core files (application-config.ts and default-role.ts)
npx create-twenty-app@latest my-app --minimal
# Interactive: select which examples to include
npx create-twenty-app@latest my-app --interactive
```
Buradan şunları yapabilirsiniz:
```bash filename="Terminal"
@@ -73,9 +86,9 @@ Ayrıca bkz.: [create-twenty-app](https://www.npmjs.com/package/create-twenty-ap
* Minimal bir temel uygulamayı `my-twenty-app/` içine kopyalar
* Yerel bir `twenty-sdk` bağımlılığı ve Yarn 4 yapılandırması ekler
* `twenty` CLI ile bağlantılı yapılandırma dosyaları ve betikler oluşturur
* Generates a default application config, a default function role, and a post-install function
* Generates core files (application config, default function role, post-install function) plus example files based on the scaffolding mode
Yeni şablondan oluşturulan bir uygulama şöyle görünür:
A freshly scaffolded app with the default `--exhaustive` mode looks like this:
```text filename="my-twenty-app/"
my-twenty-app/
@@ -94,13 +107,23 @@ my-twenty-app/
├── application-config.ts # Required - main application configuration
├── roles/
│ └── default-role.ts # Default role for logic functions
├── objects/
│ └── example-object.ts # Example custom object definition
├── fields/
│ └── example-field.ts # Example standalone field definition
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ └── post-install.ts # Post-install logic function
── front-components/
└── hello-world.tsx # Example front component
── front-components/
└── hello-world.tsx # Example front component
├── views/
│ └── example-view.ts # Example saved view definition
└── navigation-menu-items/
└── example-navigation-menu-item.ts # Example sidebar navigation link
```
With `--minimal`, only the core files are created (`application-config.ts`, `roles/default-role.ts`, and `logic-functions/post-install.ts`). With `--interactive`, you choose which example files to include.
Genel hatlarıyla:
* **package.json**: Uygulama adını, sürümünü, motorları (Node 24+, Yarn 4) bildirir ve `twenty-sdk` ile yerel `twenty` CLI'sine yetki devreden bir `twenty` betiği ekler. Tüm mevcut komutları listelemek için `yarn twenty help` komutunu çalıştırın.
@@ -116,13 +139,15 @@ Genel hatlarıyla:
SDK, TypeScript dosyalarınızı **`export default define<Entity>({...})`** çağrılarını arayarak ayrıştırıp varlıkları algılar. Her varlık türünün, `twenty-sdk` tarafından dışa aktarılan karşılık gelen bir yardımcı fonksiyonu vardır:
| Yardımcı fonksiyon | Varlık türü |
| ------------------------ | ---------------------------------------- |
| `defineObject()` | Özel nesne tanımları |
| `defineLogicFunction()` | Mantık fonksiyon tanımları |
| `defineFrontComponent()` | Front component definitions |
| `defineRole()` | Rol tanımları |
| `defineField()` | Mevcut nesneler için alan genişletmeleri |
| Yardımcı fonksiyon | Varlık türü |
| ---------------------------- | ---------------------------------------- |
| `defineObject()` | Özel nesne tanımları |
| `defineLogicFunction()` | Mantık fonksiyon tanımları |
| `defineFrontComponent()` | Front component definitions |
| `defineRole()` | Rol tanımları |
| `defineField()` | Mevcut nesneler için alan genişletmeleri |
| `defineView()` | Saved view definitions |
| `defineNavigationMenuItem()` | Navigation menu item definitions |
<Note>
**Dosya adlandırma esnektir.** Varlık algılama AST tabanlıdır — SDK, kaynak dosyalarınızı `export default define<Entity>({...})` desenini bulmak için tarar. Dosyalarınızı ve klasörlerinizi dilediğiniz gibi düzenleyebilirsiniz. Varlık türüne göre gruplama (örn. `logic-functions/`, `roles/`) bir gereklilik değil, yalnızca kod organizasyonu için bir gelenektir.
@@ -187,14 +212,16 @@ twenty-sdk, uygulamanız içinde kullandığınız türlendirilmiş yapı taşla
SDK, uygulama varlıklarınızı tanımlamak için yardımcı fonksiyonlar sağlar. [Varlık algılama](#entity-detection) bölümünde açıklandığı gibi, varlıklarınızın algılanması için `export default define<Entity>({...})` kullanmalısınız:
| Fonksiyon | Amaç |
| ------------------------ | ------------------------------------------------------------------------- |
| `defineApplication()` | Uygulama meta verilerini yapılandırın (zorunlu, uygulama başına bir adet) |
| `defineObject()` | Alanlara sahip özel nesneler tanımlayın |
| `defineLogicFunction()` | İşleyicilerle mantık fonksiyonları tanımlayın |
| `defineFrontComponent()` | Özel kullanıcı arayüzü için ön uç bileşenlerini tanımlayın |
| `defineRole()` | Rol izinlerini ve nesne erişimini yapılandırın |
| `defineField()` | Mevcut nesneleri ek alanlarla genişletin |
| Fonksiyon | Amaç |
| ---------------------------- | ------------------------------------------------------------------------- |
| `defineApplication()` | Uygulama meta verilerini yapılandırın (zorunlu, uygulama başına bir adet) |
| `defineObject()` | Alanlara sahip özel nesneler tanımlayın |
| `defineLogicFunction()` | İşleyicilerle mantık fonksiyonları tanımlayın |
| `defineFrontComponent()` | Özel kullanıcı arayüzü için ön uç bileşenlerini tanımlayın |
| `defineRole()` | Rol izinlerini ve nesne erişimini yapılandırın |
| `defineField()` | Mevcut nesneleri ek alanlarla genişletin |
| `defineView()` | Define saved views for objects |
| `defineNavigationMenuItem()` | Define sidebar navigation links |
Bu fonksiyonlar, derleme zamanında yapılandırmanızı doğrular ve IDE otomatik tamamlama ile tür güvenliği sağlar.
@@ -294,7 +321,7 @@ Her uygulamanın aşağıdakileri açıklayan tek bir `application-config.ts` do
* **Uygulamanın kim olduğu**: tanımlayıcılar, görünen ad ve açıklama.
* **Fonksiyonlarının nasıl çalıştığı**: izinler için hangi rolü kullandıkları.
* **(İsteğe bağlı) değişkenler**: fonksiyonlarınıza ortam değişkenleri olarak sunulan anahtardeğer çiftleri.
* **(Optional) post-install function**: a logic function that runs after the app is installed.
* **(İsteğe bağlı) kurulum sonrası işlev**: uygulama yüklendikten sonra çalışan bir mantık işlevi.
Uygulama yapılandırmanızı tanımlamak için `defineApplication()` kullanın:
@@ -327,7 +354,7 @@ Notlar:
* `universalIdentifier` alanları size ait belirleyici kimliklerdir; bunları bir kez oluşturun ve eşitlemeler boyunca kararlı tutun.
* `applicationVariables`, fonksiyonlarınız için ortam değişkenlerine dönüşür (örneğin, `DEFAULT_RECIPIENT_NAME` değeri `process.env.DEFAULT_RECIPIENT_NAME` olarak kullanılabilir).
* `defaultRoleUniversalIdentifier`, rol dosyasıyla eşleşmelidir (aşağıya bakın).
* `postInstallLogicFunctionUniversalIdentifier` (optional) points to a logic function that runs automatically after the app is installed. See [Post-install functions](#post-install-functions).
* `postInstallLogicFunctionUniversalIdentifier` (isteğe bağlı), uygulama yüklendikten sonra otomatik olarak çalışan bir mantık işlevine işaret eder. Bkz. [Kurulum sonrası işlevler](#post-install-functions).
#### Roller ve izinler
@@ -466,9 +493,9 @@ Notlar:
* `triggers` dizisi isteğe bağlıdır. Tetikleyicisi olmayan fonksiyonlar, diğer fonksiyonlar tarafından çağrılan yardımcı fonksiyonlar olarak kullanılabilir.
* Tek bir fonksiyonda birden çok tetikleyici türünü birleştirebilirsiniz.
### Post-install functions
### Kurulum sonrası işlevler
A post-install function is a logic function that runs automatically after your app is installed on a workspace. This is useful for one-time setup tasks such as seeding default data, creating initial records, or configuring workspace settings.
Kurulum sonrası işlev, uygulamanız bir çalışma alanına yüklendikten sonra otomatik olarak çalışan bir mantık işlevidir. Bu, varsayılan verileri tohumlama, ilk kayıtları oluşturma veya çalışma alanı ayarlarını yapılandırma gibi tek seferlik kurulum görevleri için yararlıdır.
When you scaffold a new app with `create-twenty-app`, a post-install function is generated for you at `src/logic-functions/post-install.ts`:
@@ -27,40 +27,53 @@ description: 以代码的形式构建并管理 Twenty 自定义项。
使用官方脚手架创建一个新应用,然后进行身份验证并开始开发:
```bash filename="Terminal"
# 搭建一个新应用
# Scaffold a new app (includes all examples by default)
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
# 如果你不使用 yarn@4
# If you don't use yarn@4
corepack enable
yarn install
# 使用你的 API 密钥进行身份验证(系统会提示你)
# Authenticate using your API key (you'll be prompted)
yarn twenty auth:login
# 启动开发模式:会将本地更改自动同步到你的工作区
# Start dev mode: automatically syncs local changes to your workspace
yarn twenty app:dev
```
The scaffolder supports three modes for controlling which example files are included:
```bash filename="Terminal"
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item)
npx create-twenty-app@latest my-app
# Minimal: only core files (application-config.ts and default-role.ts)
npx create-twenty-app@latest my-app --minimal
# Interactive: select which examples to include
npx create-twenty-app@latest my-app --interactive
```
从这里您可以:
```bash filename="Terminal"
# Add a new entity to your application (guided)
# 向你的应用添加一个新实体(引导式)
yarn twenty entity:add
# Watch your application's function logs
# 监听你的应用函数日志
yarn twenty function:logs
# Execute a function by name
yarn twenty function:execute -n my-function -p '{"name": "test"}'
# 按名称执行一个函数
yarn twenty function:execute -n my-function -p '{\"name\": \"test\"}'
# Execute the post-install function
# 执行安装后函数
yarn twenty function:execute --postInstall
# Uninstall the application from the current workspace
# 从当前工作区卸载该应用
yarn twenty app:uninstall
# Display commands' help
# 显示命令帮助
yarn twenty help
```
@@ -73,9 +86,9 @@ yarn twenty help
* 将一个最小的基础应用复制到 `my-twenty-app/` 中
* 添加本地 `twenty-sdk` 依赖和 Yarn 4 配置
* 创建与 `twenty` CLI 关联的配置文件和脚本
* Generates a default application config, a default function role, and a post-install function
* Generates core files (application config, default function role, post-install function) plus example files based on the scaffolding mode
一个新生成的脚手架应用如下所示:
A freshly scaffolded app with the default `--exhaustive` mode looks like this:
```text filename="my-twenty-app/"
my-twenty-app/
@@ -94,13 +107,23 @@ my-twenty-app/
├── application-config.ts # Required - main application configuration
├── roles/
│ └── default-role.ts # Default role for logic functions
├── objects/
│ └── example-object.ts # Example custom object definition
├── fields/
│ └── example-field.ts # Example standalone field definition
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ └── post-install.ts # Post-install logic function
── front-components/
└── hello-world.tsx # Example front component
── front-components/
└── hello-world.tsx # Example front component
├── views/
│ └── example-view.ts # Example saved view definition
└── navigation-menu-items/
└── example-navigation-menu-item.ts # Example sidebar navigation link
```
With `--minimal`, only the core files are created (`application-config.ts`, `roles/default-role.ts`, and `logic-functions/post-install.ts`). With `--interactive`, you choose which example files to include.
总体来说:
* **package.json**:声明应用名称、版本、引擎(Node 24+、Yarn 4),并添加 `twenty-sdk` 以及一个 `twenty` 脚本,该脚本会委托给本地的 `twenty` CLI。 运行 `yarn twenty help` 以列出所有可用命令。
@@ -116,13 +139,15 @@ my-twenty-app/
该 SDK 通过在你的 TypeScript 文件中解析 **`export default define<Entity>({...})`** 调用来检测实体。 每种实体类型都有一个从 `twenty-sdk` 导出的对应辅助函数:
| 辅助函数 | 实体类型 |
| ------------------------ | --------- |
| `defineObject()` | 自定义对象定义 |
| `defineLogicFunction()` | 逻辑函数定义 |
| `defineFrontComponent()` | 前端组件定义 |
| `defineRole()` | 角色定义 |
| `defineField()` | 现有对象的字段扩展 |
| 辅助函数 | 实体类型 |
| ---------------------------- | -------------------------------- |
| `defineObject()` | 自定义对象定义 |
| `defineLogicFunction()` | 逻辑函数定义 |
| `defineFrontComponent()` | 前端组件定义 |
| `defineRole()` | 角色定义 |
| `defineField()` | 现有对象的字段扩展 |
| `defineView()` | Saved view definitions |
| `defineNavigationMenuItem()` | Navigation menu item definitions |
<Note>
**文件命名是灵活的。** 实体检测基于 AST — SDK 会扫描你的源文件以查找 `export default define<Entity>({...})` 模式。 你可以按照自己的喜好组织文件和文件夹。 按实体类型分组(例如 `logic-functions/`、`roles/`)只是代码组织的一种约定,并非必需。
@@ -187,14 +212,16 @@ twenty-sdk 提供你在应用中使用的类型化构件和辅助函数。 以
该 SDK 提供辅助函数用于定义你的应用实体。 如 [实体检测](#entity-detection) 中所述,你必须使用 `export default define<Entity>({...})` 才能让你的实体被检测到:
| 函数 | 目的 |
| ------------------------ | ------------------ |
| `defineApplication()` | 配置应用元数据(必需,每个应用一个) |
| `defineObject()` | 定义带字段的自定义对象 |
| `defineLogicFunction()` | 定义带处理程序的逻辑函数 |
| `defineFrontComponent()` | 为自定义 UI 定义前端组件 |
| `defineRole()` | 配置角色权限和对象访问 |
| `defineField()` | 为现有对象扩展额外字段 |
| 函数 | 目的 |
| ---------------------------- | ------------------------------- |
| `defineApplication()` | 配置应用元数据(必需,每个应用一个) |
| `defineObject()` | 定义带字段的自定义对象 |
| `defineLogicFunction()` | 定义带处理程序的逻辑函数 |
| `defineFrontComponent()` | 为自定义 UI 定义前端组件 |
| `defineRole()` | 配置角色权限和对象访问 |
| `defineField()` | 为现有对象扩展额外字段 |
| `defineView()` | Define saved views for objects |
| `defineNavigationMenuItem()` | Define sidebar navigation links |
这些函数会在构建时校验你的配置,并提供 IDE 自动补全和类型安全。
@@ -294,7 +321,7 @@ export default defineObject({
* **应用的身份**:标识符、显示名称和描述。
* **函数如何运行**:它们用于权限的角色。
* **(可选)变量**:以环境变量形式提供给函数的键值对。
* **(Optional) post-install function**: a logic function that runs after the app is installed.
* **(可选)安装后函数**:在应用安装后运行的逻辑函数。
使用 `defineApplication()` 定义你的应用配置:
@@ -327,7 +354,7 @@ export default defineApplication({
* `universalIdentifier` 字段是你拥有的确定性 ID;生成一次并在多次同步中保持稳定。
* `applicationVariables` 会变成函数可用的环境变量(例如,`DEFAULT_RECIPIENT_NAME` 可作为 `process.env.DEFAULT_RECIPIENT_NAME` 使用)。
* `defaultRoleUniversalIdentifier` 必须与角色文件一致(见下文)。
* `postInstallLogicFunctionUniversalIdentifier` (optional) points to a logic function that runs automatically after the app is installed. See [Post-install functions](#post-install-functions).
* `postInstallLogicFunctionUniversalIdentifier`(可选)指向一个在应用安装后自动运行的逻辑函数。 参见 [安装后函数](#post-install-functions)
#### 角色和权限
@@ -466,9 +493,9 @@ export default defineLogicFunction({
* `triggers` 数组是可选的。 没有触发器的函数可作为实用函数,被其他函数调用。
* 你可以在单个函数中混用多种触发器类型。
### Post-install functions
### 安装后函数
A post-install function is a logic function that runs automatically after your app is installed on a workspace. This is useful for one-time setup tasks such as seeding default data, creating initial records, or configuring workspace settings.
安装后函数是在你的应用安装到工作区后自动运行的逻辑函数。 这对于一次性设置任务很有用,例如填充默认数据、创建初始记录或配置工作区设置。
When you scaffold a new app with `create-twenty-app`, a post-install function is generated for you at `src/logic-functions/post-install.ts`:
@@ -4874,7 +4874,6 @@ export type User = {
lastName: Scalars['String'];
locale: Scalars['String'];
onboardingStatus?: Maybe<OnboardingStatus>;
passwordHash?: Maybe<Scalars['String']>;
supportUserHash?: Maybe<Scalars['String']>;
updatedAt: Scalars['DateTime'];
userVars?: Maybe<Scalars['JSONObject']>;
@@ -2,24 +2,16 @@ import { Action } from '@/action-menu/actions/components/Action';
import { useSelectedRecordIdOrThrow } from '@/action-menu/actions/record-actions/single-record/hooks/useSelectedRecordIdOrThrow';
import { useContextStoreObjectMetadataItemOrThrow } from '@/context-store/hooks/useContextStoreObjectMetadataItemOrThrow';
import { useCreateFavorite } from '@/favorites/hooks/useCreateFavorite';
import { useCreateNavigationMenuItem } from '@/navigation-menu-item/hooks/useCreateNavigationMenuItem';
import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import { useRecoilValue } from 'recoil';
import { isDefined } from 'twenty-shared/utils';
import { FeatureFlagKey } from '~/generated-metadata/graphql';
export const AddToFavoritesSingleRecordAction = () => {
const { objectMetadataItem } = useContextStoreObjectMetadataItemOrThrow();
const recordId = useSelectedRecordIdOrThrow();
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
);
const { createFavorite } = useCreateFavorite();
const { createNavigationMenuItem } = useCreateNavigationMenuItem();
const selectedRecord = useRecoilValue(recordStoreFamilyState(recordId));
@@ -28,11 +20,7 @@ export const AddToFavoritesSingleRecordAction = () => {
return;
}
if (isNavigationMenuItemEnabled) {
createNavigationMenuItem(selectedRecord, objectMetadataItem.nameSingular);
} else {
createFavorite(selectedRecord, objectMetadataItem.nameSingular);
}
createFavorite(selectedRecord, objectMetadataItem.nameSingular);
};
return <Action onClick={handleClick} />;
@@ -8,9 +8,7 @@ import { useDeleteOneRecord } from '@/object-record/hooks/useDeleteOneRecord';
import { useRemoveSelectedRecordsFromRecordBoard } from '@/object-record/record-board/hooks/useRemoveSelectedRecordsFromRecordBoard';
import { useRecordIndexIdFromCurrentContextStore } from '@/object-record/record-index/hooks/useRecordIndexIdFromCurrentContextStore';
import { useResetTableRowSelection } from '@/object-record/record-table/hooks/internal/useResetTableRowSelection';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import { isDefined } from 'twenty-shared/utils';
import { FeatureFlagKey } from '~/generated-metadata/graphql';
export const DeleteSingleRecordAction = () => {
const { recordIndexId, objectMetadataItem } =
@@ -29,9 +27,7 @@ export const DeleteSingleRecordAction = () => {
const { sortedFavorites: favorites } = useFavorites();
const { deleteFavorite } = useDeleteFavorite();
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
);
const { navigationMenuItems, workspaceNavigationMenuItems } =
usePrefetchedNavigationMenuItemsData();
const { removeNavigationMenuItemsByTargetRecordIds } =
@@ -50,15 +46,13 @@ export const DeleteSingleRecordAction = () => {
deleteFavorite(foundFavorite.id);
}
if (isNavigationMenuItemEnabled) {
const foundNavigationMenuItem = [
...navigationMenuItems,
...workspaceNavigationMenuItems,
].find((item) => item.targetRecordId === recordId);
const foundNavigationMenuItem = [
...navigationMenuItems,
...workspaceNavigationMenuItems,
].find((item) => item.targetRecordId === recordId);
if (isDefined(foundNavigationMenuItem)) {
removeNavigationMenuItemsByTargetRecordIds([recordId]);
}
if (isDefined(foundNavigationMenuItem)) {
removeNavigationMenuItemsByTargetRecordIds([recordId]);
}
await deleteOneRecord(recordId);
@@ -5,9 +5,7 @@ import { useDeleteFavorite } from '@/favorites/hooks/useDeleteFavorite';
import { useFavorites } from '@/favorites/hooks/useFavorites';
import { useDeleteNavigationMenuItem } from '@/navigation-menu-item/hooks/useDeleteNavigationMenuItem';
import { usePrefetchedNavigationMenuItemsData } from '@/navigation-menu-item/hooks/usePrefetchedNavigationMenuItemsData';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import { isDefined } from 'twenty-shared/utils';
import { FeatureFlagKey } from '~/generated-metadata/graphql';
export const RemoveFromFavoritesSingleRecordAction = () => {
const recordId = useSelectedRecordIdOrThrow();
@@ -16,9 +14,6 @@ export const RemoveFromFavoritesSingleRecordAction = () => {
const { sortedFavorites: favorites } = useFavorites();
const { navigationMenuItems, workspaceNavigationMenuItems } =
usePrefetchedNavigationMenuItemsData();
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
);
const { deleteFavorite } = useDeleteFavorite();
const { deleteNavigationMenuItem } = useDeleteNavigationMenuItem();
@@ -27,28 +22,21 @@ export const RemoveFromFavoritesSingleRecordAction = () => {
(favorite) => favorite.recordId === recordId,
);
const foundNavigationMenuItem = isNavigationMenuItemEnabled
? [...navigationMenuItems, ...workspaceNavigationMenuItems].find(
(item) =>
item.targetRecordId === recordId &&
item.targetObjectMetadataId === objectMetadataItem.id,
)
: undefined;
const foundNavigationMenuItem = [
...navigationMenuItems,
...workspaceNavigationMenuItems,
].find(
(item) =>
item.targetRecordId === recordId &&
item.targetObjectMetadataId === objectMetadataItem.id,
);
const handleClick = () => {
if (isNavigationMenuItemEnabled) {
if (!isDefined(foundNavigationMenuItem)) {
return;
}
deleteNavigationMenuItem(foundNavigationMenuItem.id);
return;
}
if (!isDefined(foundFavorite)) {
if (!isDefined(foundNavigationMenuItem) || !isDefined(foundFavorite)) {
return;
}
deleteNavigationMenuItem(foundNavigationMenuItem.id);
deleteFavorite(foundFavorite.id);
};
@@ -29,8 +29,8 @@ export const useShouldActionBeRegisteredParams = ({
}): ShouldBeRegisteredFunctionParams => {
const { sortedFavorites: favorites } = useFavorites();
const { navigationMenuItems } = usePrefetchedNavigationMenuItemsData();
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
const contextStoreTargetedRecordsRule = useRecoilComponentValue(
@@ -47,7 +47,7 @@ export const useShouldActionBeRegisteredParams = ({
return false;
}
if (isNavigationMenuItemEnabled && isDefined(objectMetadataItem)) {
if (isNavigationMenuItemEditingEnabled && isDefined(objectMetadataItem)) {
const foundNavigationMenuItem = navigationMenuItems?.find(
(item) =>
item.targetRecordId === recordId &&
@@ -62,7 +62,7 @@ export const useShouldActionBeRegisteredParams = ({
return !!foundFavorite;
}, [
recordId,
isNavigationMenuItemEnabled,
isNavigationMenuItemEditingEnabled,
objectMetadataItem,
navigationMenuItems,
favorites,
@@ -5,6 +5,7 @@ import { generateCreateOneRecordMutation } from '@/object-metadata/utils/generat
import { generateUpdateOneRecordMutation } from '@/object-metadata/utils/generateUpdateOneRecordMutation';
import { ColorScheme } from '@/workspace-member/types/WorkspaceMember';
import { AvatarType } from 'twenty-ui/display';
import { CreateNavigationMenuItemDocument } from '~/generated-metadata/graphql';
import { generatedMockObjectMetadataItems } from '~/testing/utils/generatedMockObjectMetadataItems';
import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
@@ -105,7 +106,8 @@ export const sortedFavorites = [
},
];
const favoriteObjectMetadataItem = getMockObjectMetadataItemOrThrow('favorite')
const favoriteObjectMetadataItem = getMockObjectMetadataItemOrThrow('favorite');
const personObjectMetadataItem = getMockObjectMetadataItemOrThrow('person');
const UPDATE_ONE_FAVORITE_MUTATION = generateUpdateOneRecordMutation(
{
@@ -240,6 +242,41 @@ export const mocks = [
},
})),
},
{
request: {
query: CreateNavigationMenuItemDocument,
variables: {
input: {
targetRecordId: favoriteTargetObjectId,
targetObjectMetadataId: personObjectMetadataItem.id,
userWorkspaceId: '1',
folderId: undefined,
position: 1,
},
},
},
result: jest.fn(() => ({
data: {
createNavigationMenuItem: {
__typename: 'NavigationMenuItem',
id: mockId,
userWorkspaceId: '1',
targetRecordId: favoriteTargetObjectId,
targetObjectMetadataId: personObjectMetadataItem.id,
viewId: null,
folderId: null,
name: null,
link: null,
icon: null,
position: 1,
applicationId: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
},
})),
},
];
export const mockWorkspaceMember = {
@@ -23,6 +23,23 @@ jest.mock('@/object-record/hooks/useFindManyRecords', () => ({
useFindManyRecords: () => ({ records: initialFavorites }),
}));
jest.mock(
'@/navigation-menu-item/hooks/usePrefetchedNavigationMenuItemsData',
() => ({
usePrefetchedNavigationMenuItemsData: () => ({
navigationMenuItems: [],
workspaceNavigationMenuItems: [],
currentWorkspaceMemberId: '1',
}),
}),
);
jest.mock('@/favorites/hooks/usePrefetchedFavoritesFoldersData', () => ({
usePrefetchedFavoritesFoldersData: () => ({
favoriteFolders: [],
}),
}));
const Wrapper = getJestMetadataAndApolloMocksWrapper({
apolloMocks: mocks,
});
@@ -1,15 +1,31 @@
import { usePrefetchedNavigationMenuItemsData } from '@/navigation-menu-item/hooks/usePrefetchedNavigationMenuItemsData';
import { isNavigationMenuItemFolder } from '@/navigation-menu-item/utils/isNavigationMenuItemFolder';
import { CoreObjectNameSingular } from '@/object-metadata/types/CoreObjectNameSingular';
import { useCreateOneRecord } from '@/object-record/hooks/useCreateOneRecord';
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
import { useRecoilValue } from 'recoil';
import { isDefined } from 'twenty-shared/utils';
import { useCreateNavigationMenuItemMutation } from '~/generated-metadata/graphql';
import { objectMetadataItemsState } from '@/object-metadata/states/objectMetadataItemsState';
import { usePrefetchedFavoritesData } from './usePrefetchedFavoritesData';
import { usePrefetchedFavoritesFoldersData } from './usePrefetchedFavoritesFoldersData';
export const useCreateFavorite = () => {
const { favorites, currentWorkspaceMemberId } = usePrefetchedFavoritesData();
const { favoriteFolders } = usePrefetchedFavoritesFoldersData();
const { navigationMenuItems } = usePrefetchedNavigationMenuItemsData();
const objectMetadataItems = useRecoilValue(objectMetadataItemsState);
const { createOneRecord: createOneFavorite } = useCreateOneRecord({
objectNameSingular: CoreObjectNameSingular.Favorite,
});
const createFavorite = (
const [createNavigationMenuItemMutation] =
useCreateNavigationMenuItemMutation({
refetchQueries: ['FindManyNavigationMenuItems'],
});
const createFavorite = async (
targetRecord: ObjectRecord,
targetObjectNameSingular: string,
favoriteFolderId?: string,
@@ -25,12 +41,78 @@ export const useCreateFavorite = () => {
0,
);
createOneFavorite({
await createOneFavorite({
[`${targetObjectNameSingular}Id`]: targetRecord.id,
position: maxPosition + 1,
forWorkspaceMemberId: currentWorkspaceMemberId,
favoriteFolderId,
});
let navigationMenuItemFolderId: string | undefined;
if (isDefined(favoriteFolderId)) {
const favoriteFolder = favoriteFolders.find(
(folder) => folder.id === favoriteFolderId,
);
if (isDefined(favoriteFolder)) {
const matchingNavigationMenuItemFolder = navigationMenuItems.find(
(item) =>
isNavigationMenuItemFolder(item) &&
item.name === favoriteFolder.name &&
item.userWorkspaceId === currentWorkspaceMemberId,
);
navigationMenuItemFolderId = matchingNavigationMenuItemFolder?.id;
}
}
const relevantNavigationMenuItems = navigationMenuItemFolderId
? navigationMenuItems.filter(
(item) => item.folderId === navigationMenuItemFolderId,
)
: navigationMenuItems.filter(
(item) =>
!item.folderId && item.userWorkspaceId === currentWorkspaceMemberId,
);
const maxNavigationMenuItemPosition = Math.max(
...relevantNavigationMenuItems.map((item) => item.position),
0,
);
const isView = targetObjectNameSingular === 'view';
if (isView) {
await createNavigationMenuItemMutation({
variables: {
input: {
viewId: targetRecord.id,
userWorkspaceId: currentWorkspaceMemberId,
folderId: navigationMenuItemFolderId,
position: maxNavigationMenuItemPosition + 1,
},
},
});
} else {
const objectMetadataItem = objectMetadataItems.find(
(item) => item.nameSingular === targetObjectNameSingular,
);
if (isDefined(objectMetadataItem)) {
await createNavigationMenuItemMutation({
variables: {
input: {
targetRecordId: targetRecord.id,
targetObjectMetadataId: objectMetadataItem.id,
userWorkspaceId: currentWorkspaceMemberId,
folderId: navigationMenuItemFolderId,
position: maxNavigationMenuItemPosition + 1,
},
},
});
}
}
};
return { createFavorite };
@@ -1,5 +1,8 @@
import { usePrefetchedNavigationMenuItemsData } from '@/navigation-menu-item/hooks/usePrefetchedNavigationMenuItemsData';
import { CoreObjectNameSingular } from '@/object-metadata/types/CoreObjectNameSingular';
import { useCreateOneRecord } from '@/object-record/hooks/useCreateOneRecord';
import { isDefined } from 'twenty-shared/utils';
import { useCreateNavigationMenuItemMutation } from '~/generated-metadata/graphql';
import { usePrefetchedFavoritesData } from './usePrefetchedFavoritesData';
import { usePrefetchedFavoritesFoldersData } from './usePrefetchedFavoritesFoldersData';
@@ -10,6 +13,12 @@ export const useCreateFavoriteFolder = () => {
const { currentWorkspaceMemberId } = usePrefetchedFavoritesData();
const { favoriteFolders } = usePrefetchedFavoritesFoldersData();
const { navigationMenuItems } = usePrefetchedNavigationMenuItemsData();
const [createNavigationMenuItemMutation] =
useCreateNavigationMenuItemMutation({
refetchQueries: ['FindManyNavigationMenuItems'],
});
const createNewFavoriteFolder = async (name: string): Promise<void> => {
if (!name || !currentWorkspaceMemberId) {
@@ -25,6 +34,34 @@ export const useCreateFavoriteFolder = () => {
name,
position: maxPosition + 1,
});
const folderNavigationMenuItems = navigationMenuItems.filter(
(item) =>
isDefined(item.name) &&
!item.folderId &&
!item.targetRecordId &&
!item.targetObjectMetadataId &&
!item.viewId &&
item.userWorkspaceId === currentWorkspaceMemberId,
);
const maxNavigationMenuItemPosition = Math.max(
...folderNavigationMenuItems.map((item) => item.position),
0,
);
await createNavigationMenuItemMutation({
variables: {
input: {
name,
targetRecordId: null,
targetObjectMetadataId: null,
userWorkspaceId: currentWorkspaceMemberId,
folderId: null,
position: maxNavigationMenuItemPosition + 1,
},
},
});
};
return { createNewFavoriteFolder };
@@ -5,11 +5,11 @@ import { CurrentWorkspaceMemberNavigationMenuItemFolders } from '@/navigation-me
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
export const CurrentWorkspaceMemberNavigationMenuItemFoldersDispatcher = () => {
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
if (isNavigationMenuItemEnabled) {
if (isNavigationMenuItemEditingEnabled) {
return <CurrentWorkspaceMemberNavigationMenuItemFolders />;
}
@@ -20,11 +20,11 @@ export const NavigationMenuItemFolderContentDispatcherEffect = ({
favorites,
navigationMenuItems,
}: NavigationMenuItemFolderContentDispatcherEffectProps) => {
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
if (isNavigationMenuItemEnabled && isDefined(navigationMenuItems)) {
if (isNavigationMenuItemEditingEnabled && isDefined(navigationMenuItems)) {
return (
<NavigationMenuItemFolderContent
folderId={folderId}
@@ -5,11 +5,11 @@ import { WorkspaceNavigationMenuItems } from '@/navigation-menu-item/components/
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
export const WorkspaceNavigationMenuItemsDispatcher = () => {
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
if (isNavigationMenuItemEnabled) {
if (isNavigationMenuItemEditingEnabled) {
return <WorkspaceNavigationMenuItems />;
}
@@ -1,5 +1,5 @@
import { useRecoilValue } from 'recoil';
import styled from '@emotion/styled';
import { useRecoilValue } from 'recoil';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useFavoritesByFolder } from '@/favorites/hooks/useFavoritesByFolder';
@@ -31,8 +31,8 @@ export const MainNavigationDrawer = ({ className }: { className?: string }) => {
);
const { favoritesByFolder } = useFavoritesByFolder();
const { navigationMenuItemsByFolder } = useNavigationMenuItemsByFolder();
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
const openedFavoriteFolder = favoritesByFolder.find(
@@ -43,7 +43,7 @@ export const MainNavigationDrawer = ({ className }: { className?: string }) => {
(f) => f.id === currentNavigationMenuItemFolderId,
);
const openedFolder = isNavigationMenuItemEnabled
const openedFolder = isNavigationMenuItemEditingEnabled
? openedNavigationMenuItemFolder
: openedFavoriteFolder;
@@ -59,7 +59,7 @@ export const MainNavigationDrawer = ({ className }: { className?: string }) => {
</NavigationDrawerFixedContent>
<NavigationDrawerScrollableContent>
{isNavigationMenuItemEnabled ? (
{isNavigationMenuItemEditingEnabled ? (
<StyledScrollableContent>
{openedFolder ? (
<NavigationMenuItemFolderContentDispatcherEffect
@@ -20,8 +20,8 @@ type NavbarDragProviderProps = {
};
export const NavbarDragProvider = ({ children }: NavbarDragProviderProps) => {
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
const [isDragging, setIsDragging] = useState(false);
const [sourceDroppableId, setSourceDroppableId] = useState<string | null>(
@@ -42,7 +42,7 @@ export const NavbarDragProvider = ({ children }: NavbarDragProviderProps) => {
setIsDragging(false);
setSourceDroppableId(null);
if (isNavigationMenuItemEnabled) {
if (isNavigationMenuItemEditingEnabled) {
const isWorkspaceDrop =
(result.source?.droppableId?.startsWith('workspace-') ?? false) &&
(result.destination?.droppableId?.startsWith('workspace-') ?? false);
@@ -35,8 +35,8 @@ type PageDragDropProviderProps = {
export const PageDragDropProvider = ({
children,
}: PageDragDropProviderProps) => {
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
const [isDragging, setIsDragging] = useState(false);
const [sourceDroppableId, setSourceDroppableId] = useState<string | null>(
@@ -136,7 +136,7 @@ export const PageDragDropProvider = ({
return;
}
if (isNavigationMenuItemEnabled) {
if (isNavigationMenuItemEditingEnabled) {
const isWorkspaceDrop =
isWorkspaceDroppableId(result.source?.droppableId) &&
isWorkspaceDroppableId(result.destination?.droppableId);
@@ -1,3 +1,5 @@
import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';
import { contextStoreCurrentViewIdComponentState } from '@/context-store/states/contextStoreCurrentViewIdComponentState';
import { ObjectIconWithViewOverlay } from '@/navigation-menu-item/components/ObjectIconWithViewOverlay';
import { NavigationMenuItemType } from '@/navigation-menu-item/constants/NavigationMenuItemType';
import { getNavigationMenuItemIconColors } from '@/navigation-menu-item/utils/getNavigationMenuItemIconColors';
@@ -6,6 +8,11 @@ import { lastVisitedViewPerObjectMetadataItemState } from '@/navigation/states/l
import { CoreObjectNameSingular } from '@/object-metadata/types/CoreObjectNameSingular';
import { type ObjectMetadataItem } from '@/object-metadata/types/ObjectMetadataItem';
import { NavigationDrawerItem } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerItem';
import { NavigationDrawerItemsCollapsableContainer } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerItemsCollapsableContainer';
import { NavigationDrawerSubItem } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerSubItem';
import { getNavigationSubItemLeftAdornment } from '@/ui/navigation/navigation-drawer/utils/getNavigationSubItemLeftAdornment';
import { useRecoilComponentValue } from '@/ui/utilities/state/component-state/hooks/useRecoilComponentValue';
import { coreViewsFromObjectMetadataItemFamilySelector } from '@/views/states/selectors/coreViewsFromObjectMetadataItemFamilySelector';
import { ViewKey } from '@/views/types/ViewKey';
import { useTheme } from '@emotion/react';
import { useLocation } from 'react-router-dom';
@@ -13,6 +20,7 @@ import { useRecoilValue } from 'recoil';
import { AppPath } from 'twenty-shared/types';
import { getAppPath, isDefined } from 'twenty-shared/utils';
import { Avatar, useIcons } from 'twenty-ui/display';
import { AnimatedExpandableContainer } from 'twenty-ui/layout';
import { FeatureFlagKey } from '~/generated-metadata/graphql';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
@@ -45,6 +53,17 @@ export const NavigationDrawerItemForObjectMetadataItem = ({
lastVisitedViewPerObjectMetadataItemState,
);
const views = useRecoilValue(
coreViewsFromObjectMetadataItemFamilySelector({
objectMetadataItemId: objectMetadataItem.id,
}),
);
const contextStoreCurrentViewId = useRecoilComponentValue(
contextStoreCurrentViewIdComponentState,
MAIN_CONTEXT_STORE_INSTANCE_ID,
);
const lastVisitedViewId =
lastVisitedViewPerObjectMetadataItem?.[objectMetadataItem.id];
@@ -136,6 +155,60 @@ export const NavigationDrawerItemForObjectMetadataItem = ({
? objectMetadataItem.labelSingular
: undefined;
const shouldSubItemsBeDisplayed =
!isNavigationMenuItemEditingEnabled && isActive && views.length > 1;
const sortedObjectMetadataViews = [...views].sort(
(viewA, viewB) => viewA.position - viewB.position,
);
const selectedSubItemIndex = sortedObjectMetadataViews.findIndex(
(view) => contextStoreCurrentViewId === view.id,
);
const subItemArrayLength = sortedObjectMetadataViews.length;
if (!isNavigationMenuItemEditingEnabled) {
return (
<NavigationDrawerItemsCollapsableContainer
isGroup={shouldSubItemsBeDisplayed}
>
<NavigationDrawerItem
key={objectMetadataItem.id}
label={objectMetadataItem.labelPlural}
to={navigationPath}
Icon={getIcon(objectMetadataItem.icon)}
active={isActive}
/>
<AnimatedExpandableContainer
isExpanded={shouldSubItemsBeDisplayed}
dimension="height"
mode="fit-content"
containAnimation
>
{sortedObjectMetadataViews.map((view, index) => (
<NavigationDrawerSubItem
label={view.name}
to={getAppPath(
AppPath.RecordIndexPage,
{ objectNamePlural: objectMetadataItem.namePlural },
{ viewId: view.id },
)}
active={contextStoreCurrentViewId === view.id}
subItemState={getNavigationSubItemLeftAdornment({
index,
arrayLength: subItemArrayLength,
selectedIndex: selectedSubItemIndex,
})}
Icon={getIcon(view.icon)}
key={view.id}
/>
))}
</AnimatedExpandableContainer>
</NavigationDrawerItemsCollapsableContainer>
);
}
return (
<NavigationDrawerItem
label={label}
@@ -29,8 +29,8 @@ export const NavigationDrawerOpenedSection = () => {
const { workspaceFavoritesObjectMetadataItems } = useWorkspaceFavorites();
const { workspaceNavigationMenuItemsObjectMetadataItems } =
useWorkspaceNavigationMenuItems();
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
const {
@@ -52,7 +52,7 @@ export const NavigationDrawerOpenedSection = () => {
return;
}
const workspaceItemsToExclude = isNavigationMenuItemEnabled
const workspaceItemsToExclude = isNavigationMenuItemEditingEnabled
? workspaceNavigationMenuItemsObjectMetadataItems
: workspaceFavoritesObjectMetadataItems;
@@ -1,4 +1,5 @@
import { triggerUpdateRecordOptimisticEffectByBatch } from '@/apollo/optimistic-effect/utils/triggerUpdateRecordOptimisticEffectByBatch';
import { dispatchObjectRecordOperationBrowserEvent } from '@/browser-event/utils/dispatchObjectRecordOperationBrowserEvent';
import { apiConfigState } from '@/client-config/states/apiConfigState';
import { useRemoveNavigationMenuItemByTargetRecordId } from '@/navigation-menu-item/hooks/useRemoveNavigationMenuItemByTargetRecordId';
import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';
@@ -15,12 +16,9 @@ import { useObjectPermissions } from '@/object-record/hooks/useObjectPermissions
import { useRefetchAggregateQueries } from '@/object-record/hooks/useRefetchAggregateQueries';
import { useUpsertRecordsInStore } from '@/object-record/record-store/hooks/useUpsertRecordsInStore';
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
import { dispatchObjectRecordOperationBrowserEvent } from '@/browser-event/utils/dispatchObjectRecordOperationBrowserEvent';
import { getDeleteManyRecordsMutationResponseField } from '@/object-record/utils/getDeleteManyRecordsMutationResponseField';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import { useRecoilValue } from 'recoil';
import { isDefined } from 'twenty-shared/utils';
import { FeatureFlagKey } from '~/generated-metadata/graphql';
import { sleep } from '~/utils/sleep';
type useDeleteManyRecordProps = {
@@ -60,9 +58,7 @@ export const useDeleteManyRecords = ({
const { objectMetadataItems } = useObjectMetadataItems();
const { objectPermissionsByObjectMetadataId } = useObjectPermissions();
const { refetchAggregateQueries } = useRefetchAggregateQueries();
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
);
const { removeNavigationMenuItemsByTargetRecordIds } =
useRemoveNavigationMenuItemByTargetRecordId();
@@ -231,9 +227,7 @@ export const useDeleteManyRecords = ({
objectMetadataNamePlural: objectMetadataItem.namePlural,
});
if (isNavigationMenuItemEnabled) {
removeNavigationMenuItemsByTargetRecordIds(recordIdsToDelete);
}
removeNavigationMenuItemsByTargetRecordIds(recordIdsToDelete);
dispatchObjectRecordOperationBrowserEvent({
objectMetadataItem,
@@ -1,6 +1,8 @@
import { triggerCreateRecordsOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerCreateRecordsOptimisticEffect';
import { triggerDestroyRecordsOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerDestroyRecordsOptimisticEffect';
import { dispatchObjectRecordOperationBrowserEvent } from '@/browser-event/utils/dispatchObjectRecordOperationBrowserEvent';
import { apiConfigState } from '@/client-config/states/apiConfigState';
import { useRemoveNavigationMenuItemByTargetRecordId } from '@/navigation-menu-item/hooks/useRemoveNavigationMenuItemByTargetRecordId';
import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';
import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataItem';
import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';
@@ -11,12 +13,8 @@ import { useObjectPermissions } from '@/object-record/hooks/useObjectPermissions
import { useRefetchAggregateQueries } from '@/object-record/hooks/useRefetchAggregateQueries';
import { useUpsertRecordsInStore } from '@/object-record/record-store/hooks/useUpsertRecordsInStore';
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
import { dispatchObjectRecordOperationBrowserEvent } from '@/browser-event/utils/dispatchObjectRecordOperationBrowserEvent';
import { getDestroyManyRecordsMutationResponseField } from '@/object-record/utils/getDestroyManyRecordsMutationResponseField';
import { useRemoveNavigationMenuItemByTargetRecordId } from '@/navigation-menu-item/hooks/useRemoveNavigationMenuItemByTargetRecordId';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import { useRecoilValue } from 'recoil';
import { FeatureFlagKey } from '~/generated-metadata/graphql';
import { capitalize, isDefined } from 'twenty-shared/utils';
import { sleep } from '~/utils/sleep';
@@ -55,9 +53,6 @@ export const useDestroyManyRecords = ({
const { objectMetadataItems } = useObjectMetadataItems();
const { objectPermissionsByObjectMetadataId } = useObjectPermissions();
const { refetchAggregateQueries } = useRefetchAggregateQueries();
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
);
const { removeNavigationMenuItemsByTargetRecordIds } =
useRemoveNavigationMenuItemByTargetRecordId();
@@ -152,9 +147,7 @@ export const useDestroyManyRecords = ({
objectMetadataNamePlural: objectMetadataItem.namePlural,
});
if (isNavigationMenuItemEnabled) {
removeNavigationMenuItemsByTargetRecordIds(recordIdsToDestroy);
}
removeNavigationMenuItemsByTargetRecordIds(recordIdsToDestroy);
dispatchObjectRecordOperationBrowserEvent({
objectMetadataItem,
@@ -1,4 +1,5 @@
import { triggerUpdateRecordOptimisticEffectByBatch } from '@/apollo/optimistic-effect/utils/triggerUpdateRecordOptimisticEffectByBatch';
import { dispatchObjectRecordOperationBrowserEvent } from '@/browser-event/utils/dispatchObjectRecordOperationBrowserEvent';
import { useRemoveNavigationMenuItemByTargetRecordId } from '@/navigation-menu-item/hooks/useRemoveNavigationMenuItemByTargetRecordId';
import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';
import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataItem';
@@ -16,11 +17,8 @@ import { useObjectPermissions } from '@/object-record/hooks/useObjectPermissions
import { useRefetchAggregateQueries } from '@/object-record/hooks/useRefetchAggregateQueries';
import { useUpsertRecordsInStore } from '@/object-record/record-store/hooks/useUpsertRecordsInStore';
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
import { dispatchObjectRecordOperationBrowserEvent } from '@/browser-event/utils/dispatchObjectRecordOperationBrowserEvent';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import { useCallback } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { FeatureFlagKey } from '~/generated-metadata/graphql';
import { sleep } from '~/utils/sleep';
const DEFAULT_DELAY_BETWEEN_MUTATIONS_MS = 50;
@@ -64,9 +62,6 @@ export const useIncrementalDeleteManyRecords = <T>({
const { objectMetadataItems } = useObjectMetadataItems();
const { objectPermissionsByObjectMetadataId } = useObjectPermissions();
const { refetchAggregateQueries } = useRefetchAggregateQueries();
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
);
const { removeNavigationMenuItemsByTargetRecordIds } =
useRemoveNavigationMenuItemByTargetRecordId();
@@ -244,9 +239,7 @@ export const useIncrementalDeleteManyRecords = <T>({
objectMetadataNamePlural: objectMetadataItem.namePlural,
});
if (isNavigationMenuItemEnabled) {
removeNavigationMenuItemsByTargetRecordIds(allDeletedRecordIds);
}
removeNavigationMenuItemsByTargetRecordIds(allDeletedRecordIds);
dispatchObjectRecordOperationBrowserEvent({
objectMetadataItem,
@@ -1,5 +1,6 @@
import { ActivityTargetsInlineCell } from '@/activities/inline-cell/components/ActivityTargetsInlineCell';
import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataItem';
import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';
import { type CoreObjectNameSingular } from '@/object-metadata/types/CoreObjectNameSingular';
import { formatFieldMetadataItemAsColumnDefinition } from '@/object-metadata/utils/formatFieldMetadataItemAsColumnDefinition';
import { useObjectPermissions } from '@/object-record/hooks/useObjectPermissions';
@@ -15,6 +16,7 @@ import { RecordFieldListComponentInstanceContext } from '@/object-record/record-
import { recordFieldListHoverPositionComponentState } from '@/object-record/record-field-list/states/recordFieldListHoverPositionComponentState';
import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';
import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';
import { isJunctionRelationForbidden } from '@/object-record/record-field/ui/utils/junction/isJunctionRelationForbidden';
import { RecordInlineCell } from '@/object-record/record-inline-cell/components/RecordInlineCell';
import { PropertyBox } from '@/object-record/record-inline-cell/property-box/components/PropertyBox';
import { PropertyBoxSkeletonLoader } from '@/object-record/record-inline-cell/property-box/components/PropertyBoxSkeletonLoader';
@@ -53,6 +55,7 @@ export const RecordFieldList = ({
});
const { objectPermissionsByObjectMetadataId } = useObjectPermissions();
const { objectMetadataItems } = useObjectMetadataItems();
const { useUpdateOneObjectRecordMutation } = useRecordShowContainerActions({
objectNameSingular,
@@ -187,6 +190,12 @@ export const RecordFieldList = ({
fieldName: fieldMetadataItem.name,
prefix: instanceId,
})}`,
isForbidden: isJunctionRelationForbidden({
fieldMetadataItem,
sourceObjectMetadataId: objectMetadataItem.id,
objectMetadataItems,
objectPermissionsByObjectMetadataId,
}),
}}
>
<RecordFieldComponentInstanceContext.Provider
@@ -10,6 +10,7 @@ import { isActivityTargetField } from '@/object-record/record-field-list/utils/c
import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';
import { useFieldFocus } from '@/object-record/record-field/ui/hooks/useFieldFocus';
import { useRelationFromManyFieldDisplay } from '@/object-record/record-field/ui/meta-types/hooks/useRelationFromManyFieldDisplay';
import { ForbiddenFieldDisplay } from '@/object-record/record-field/ui/meta-types/display/components/ForbiddenFieldDisplay';
import { extractTargetRecordsFromJunction } from '@/object-record/record-field/ui/utils/junction/extractTargetRecordsFromJunction';
import { getJunctionConfig } from '@/object-record/record-field/ui/utils/junction/getJunctionConfig';
import { hasJunctionConfig } from '@/object-record/record-field/ui/utils/junction/hasJunctionConfig';
@@ -144,6 +145,10 @@ export const RelationFromManyFieldDisplay = () => {
})
.filter(isDefined);
if (fieldValue.some(isDefined) && targetRecordsWithMetadata.length === 0) {
return <ForbiddenFieldDisplay />;
}
return (
<ExpandableList isChipCountDisplayed={isFocused}>
{targetRecordsWithMetadata.map(({ record, objectMetadata }) => (
@@ -0,0 +1,75 @@
import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem';
import { getObjectPermissionsForObject } from '@/object-metadata/utils/getObjectPermissionsForObject';
import { getJunctionConfig } from '@/object-record/record-field/ui/utils/junction/getJunctionConfig';
import { getTargetObjectMetadataIdsFromField } from '@/object-record/record-field/ui/utils/junction/getTargetObjectMetadataIdsFromField';
import { hasJunctionConfig } from '@/object-record/record-field/ui/utils/junction/hasJunctionConfig';
import { type ObjectPermissions } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { type JunctionObjectMetadataItem } from './getJunctionConfig';
type ObjectPermissionsByObjectMetadataId = Record<
string,
ObjectPermissions & { objectMetadataId: string }
>;
// Returns true if a junction field's intermediate or final target object
// is not readable by the current user.
export const isJunctionRelationForbidden = ({
fieldMetadataItem,
sourceObjectMetadataId,
objectMetadataItems,
objectPermissionsByObjectMetadataId,
}: {
fieldMetadataItem: Pick<FieldMetadataItem, 'settings' | 'relation'>;
sourceObjectMetadataId: string;
objectMetadataItems: JunctionObjectMetadataItem[];
objectPermissionsByObjectMetadataId: ObjectPermissionsByObjectMetadataId;
}): boolean => {
if (!hasJunctionConfig(fieldMetadataItem.settings)) {
return false;
}
const junctionObjectMetadataId =
fieldMetadataItem.relation?.targetObjectMetadata.id;
if (!isDefined(junctionObjectMetadataId)) {
return false;
}
const junctionPermissions = getObjectPermissionsForObject(
objectPermissionsByObjectMetadataId,
junctionObjectMetadataId,
);
if (!junctionPermissions.canReadObjectRecords) {
return true;
}
const junctionConfig = getJunctionConfig({
settings: fieldMetadataItem.settings,
relationObjectMetadataId: junctionObjectMetadataId,
sourceObjectMetadataId,
objectMetadataItems,
});
if (!isDefined(junctionConfig)) {
return false;
}
const targetObjectMetadataIds = junctionConfig.targetFields.flatMap(
getTargetObjectMetadataIdsFromField,
);
if (targetObjectMetadataIds.length === 0) {
return false;
}
return !targetObjectMetadataIds.some(
(targetId) =>
getObjectPermissionsForObject(
objectPermissionsByObjectMetadataId,
targetId,
).canReadObjectRecords,
);
};
@@ -1,6 +1,8 @@
import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';
import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem';
import { type ObjectMetadataItem } from '@/object-metadata/types/ObjectMetadataItem';
import { formatFieldMetadataItemAsColumnDefinition } from '@/object-metadata/utils/formatFieldMetadataItemAsColumnDefinition';
import { useObjectPermissions } from '@/object-record/hooks/useObjectPermissions';
import { useUpdateOneRecord } from '@/object-record/hooks/useUpdateOneRecord';
import { useIsRecordFieldReadOnly } from '@/object-record/read-only/hooks/useIsRecordFieldReadOnly';
import {
@@ -10,6 +12,7 @@ import {
} from '@/object-record/record-field/ui/contexts/FieldContext';
import { FieldFocusContextProvider } from '@/object-record/record-field/ui/contexts/FieldFocusContextProvider';
import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';
import { isJunctionRelationForbidden } from '@/object-record/record-field/ui/utils/junction/isJunctionRelationForbidden';
import { RecordInlineCellAnchoredPortalContext } from '@/object-record/record-inline-cell/components/RecordInlineCellAnchoredPortalContext';
import { RecordInlineCellCloseOnCommandMenuOpeningEffect } from '@/object-record/record-inline-cell/components/RecordInlineCellCloseOnCommandMenuOpeningEffect';
import { getRecordFieldInputInstanceId } from '@/object-record/utils/getRecordFieldInputId';
@@ -19,7 +22,14 @@ import { isDefined } from 'twenty-shared/utils';
type RecordInlineCellAnchoredPortalProps = {
fieldMetadataItem: Pick<
FieldMetadataItem,
'id' | 'name' | 'type' | 'createdAt' | 'updatedAt' | 'label'
| 'id'
| 'name'
| 'type'
| 'createdAt'
| 'updatedAt'
| 'label'
| 'settings'
| 'relation'
>;
objectMetadataItem: ObjectMetadataItem;
recordId: string;
@@ -52,6 +62,16 @@ export const RecordInlineCellAnchoredPortal = ({
recordId: recordId ?? '',
});
const { objectPermissionsByObjectMetadataId } = useObjectPermissions();
const { objectMetadataItems } = useObjectMetadataItems();
const isForbidden = isJunctionRelationForbidden({
fieldMetadataItem,
sourceObjectMetadataId: objectMetadataItem.id,
objectMetadataItems,
objectPermissionsByObjectMetadataId,
});
const { updateOneRecord } = useUpdateOneRecord();
const useUpdateOneObjectRecordMutation: RecordUpdateHook = () => {
@@ -88,6 +108,7 @@ export const RecordInlineCellAnchoredPortal = ({
useUpdateRecord: useUpdateOneObjectRecordMutation,
isDisplayModeFixHeight: true,
isRecordFieldReadOnly,
isForbidden,
onCloseEditMode,
}}
>
@@ -1,8 +1,11 @@
import { css } from '@emotion/react';
import styled from '@emotion/styled';
import { useContext } from 'react';
import { FieldDisplay } from '@/object-record/record-field/ui/components/FieldDisplay';
import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';
import { useFieldFocus } from '@/object-record/record-field/ui/hooks/useFieldFocus';
import { ForbiddenFieldDisplay } from '@/object-record/record-field/ui/meta-types/display/components/ForbiddenFieldDisplay';
import { useRecordInlineCellContext } from '@/object-record/record-inline-cell/components/RecordInlineCellContext';
import { RecordInlineCellDisplayMode } from '@/object-record/record-inline-cell/components/RecordInlineCellDisplayMode';
import { RecordInlineCellSkeletonLoader } from '@/object-record/record-inline-cell/components/RecordInlineCellSkeletonLoader';
@@ -33,11 +36,16 @@ export const RecordInlineCellValue = () => {
const { readonly, loading, isCentered, onOpenEditMode } =
useRecordInlineCellContext();
const { isFocused } = useFieldFocus();
const { isForbidden } = useContext(FieldContext);
if (loading === true) {
return <RecordInlineCellSkeletonLoader />;
}
if (isForbidden === true) {
return <ForbiddenFieldDisplay />;
}
return (
<StyledClickableContainer readonly={readonly} isCentered={isCentered}>
<RecordInlineCellDisplayMode
@@ -1,3 +1,4 @@
import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';
import { getObjectPermissionsForObject } from '@/object-metadata/utils/getObjectPermissionsForObject';
import { isLabelIdentifierField } from '@/object-metadata/utils/isLabelIdentifierField';
import { isRecordFieldReadOnly } from '@/object-record/read-only/utils/isRecordFieldReadOnly';
@@ -5,11 +6,15 @@ import { type RecordField } from '@/object-record/record-field/types/RecordField
import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';
import { isFieldRelationManyToOne } from '@/object-record/record-field/ui/types/guards/isFieldRelationManyToOne';
import { isFieldRelationOneToMany } from '@/object-record/record-field/ui/types/guards/isFieldRelationOneToMany';
import { getJunctionConfig } from '@/object-record/record-field/ui/utils/junction/getJunctionConfig';
import { getTargetObjectMetadataIdsFromField } from '@/object-record/record-field/ui/utils/junction/getTargetObjectMetadataIdsFromField';
import { hasJunctionConfig } from '@/object-record/record-field/ui/utils/junction/hasJunctionConfig';
import { useRecordIndexContextOrThrow } from '@/object-record/record-index/contexts/RecordIndexContext';
import { RecordUpdateContext } from '@/object-record/record-table/contexts/EntityUpdateMutationHookContext';
import { useRecordTableContextOrThrow } from '@/object-record/record-table/contexts/RecordTableContext';
import { useRecordTableRowContextOrThrow } from '@/object-record/record-table/contexts/RecordTableRowContext';
import { useContext, type ReactNode } from 'react';
import { isDefined } from 'twenty-shared/utils';
type RecordTableCellFieldContextGenericProps = {
recordField: RecordField;
@@ -30,6 +35,8 @@ export const RecordTableCellFieldContextGeneric = ({
fieldDefinitionByFieldMetadataItemId,
} = useRecordIndexContextOrThrow();
const { objectMetadataItems } = useObjectMetadataItems();
const fieldDefinition =
fieldDefinitionByFieldMetadataItemId[recordField.fieldMetadataItemId];
@@ -51,6 +58,34 @@ export const RecordTableCellFieldContextGeneric = ({
);
hasObjectReadPermissions = relationObjectPermissions.canReadObjectRecords;
if (
hasObjectReadPermissions &&
hasJunctionConfig(fieldDefinition.metadata.settings)
) {
const junctionConfig = getJunctionConfig({
settings: fieldDefinition.metadata.settings,
relationObjectMetadataId,
sourceObjectMetadataId: objectMetadataItem.id,
objectMetadataItems,
});
if (isDefined(junctionConfig)) {
const targetObjectMetadataIds = junctionConfig.targetFields.flatMap(
getTargetObjectMetadataIdsFromField,
);
if (targetObjectMetadataIds.length > 0) {
hasObjectReadPermissions = targetObjectMetadataIds.some(
(targetId) =>
getObjectPermissionsForObject(
objectPermissionsByObjectMetadataId,
targetId,
).canReadObjectRecords,
);
}
}
}
}
return (
@@ -1,5 +1,6 @@
import { ActivityTargetsInlineCell } from '@/activities/inline-cell/components/ActivityTargetsInlineCell';
import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataItem';
import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';
import { type CoreObjectNameSingular } from '@/object-metadata/types/CoreObjectNameSingular';
import { formatFieldMetadataItemAsColumnDefinition } from '@/object-metadata/utils/formatFieldMetadataItemAsColumnDefinition';
import { useObjectPermissions } from '@/object-record/hooks/useObjectPermissions';
@@ -11,6 +12,7 @@ import { recordFieldListHoverPositionComponentState } from '@/object-record/reco
import { isActivityTargetField } from '@/object-record/record-field-list/utils/categorizeRelationFields';
import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';
import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';
import { isJunctionRelationForbidden } from '@/object-record/record-field/ui/utils/junction/isJunctionRelationForbidden';
import { RecordInlineCell } from '@/object-record/record-inline-cell/components/RecordInlineCell';
import { PropertyBoxSkeletonLoader } from '@/object-record/record-inline-cell/property-box/components/PropertyBoxSkeletonLoader';
import { useRecordShowContainerActions } from '@/object-record/record-show/hooks/useRecordShowContainerActions';
@@ -73,6 +75,7 @@ export const FieldsWidget = ({ widget }: FieldsWidgetProps) => {
});
const { objectPermissionsByObjectMetadataId } = useObjectPermissions();
const { objectMetadataItems } = useObjectMetadataItems();
const { useUpdateOneObjectRecordMutation } = useRecordShowContainerActions({
objectNameSingular: targetRecord.targetObjectNameSingular,
@@ -181,6 +184,12 @@ export const FieldsWidget = ({ widget }: FieldsWidgetProps) => {
fieldName: fieldMetadataItem.name,
prefix: instanceId,
})}`,
isForbidden: isJunctionRelationForbidden({
fieldMetadataItem,
sourceObjectMetadataId: objectMetadataItem.id,
objectMetadataItems,
objectPermissionsByObjectMetadataId,
}),
}}
>
{isActivityTarget ? (
@@ -23,8 +23,8 @@ import { FeatureFlagKey } from '~/generated-metadata/graphql';
import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
export const PrefetchRunFavoriteQueriesEffect = () => {
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
const showAuthModal = useShowAuthModal();
const isSettingsPage = useIsSettingsPage();
@@ -64,7 +64,7 @@ export const PrefetchRunFavoriteQueriesEffect = () => {
showAuthModal ||
isSettingsPage ||
!isWorkspaceActive ||
isNavigationMenuItemEnabled,
isNavigationMenuItemEditingEnabled,
});
const { records: favoriteFolders } = useFindManyRecords({
@@ -75,7 +75,7 @@ export const PrefetchRunFavoriteQueriesEffect = () => {
showAuthModal ||
isSettingsPage ||
!isWorkspaceActive ||
isNavigationMenuItemEnabled,
isNavigationMenuItemEditingEnabled,
});
const setPrefetchFavoritesState = useRecoilCallback(
@@ -18,8 +18,8 @@ import {
import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
export const PrefetchRunNavigationMenuItemQueriesEffect = () => {
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
const showAuthModal = useShowAuthModal();
@@ -37,7 +37,7 @@ export const PrefetchRunNavigationMenuItemQueriesEffect = () => {
showAuthModal ||
isSettingsPage ||
!isWorkspaceActive ||
!isNavigationMenuItemEnabled,
!isNavigationMenuItemEditingEnabled,
fetchPolicy: 'cache-and-network',
});
@@ -1,4 +1,7 @@
import { useTheme } from '@emotion/react';
import { useId, useState } from 'react';
import { createPortal } from 'react-dom';
import { AppTooltip, TooltipDelay, TooltipPosition } from 'twenty-ui/display';
import { useNumberFormat } from '@/localization/hooks/useNumberFormat';
import { type FieldDefinition } from '@/object-record/record-field/ui/types/FieldDefinition';
@@ -22,10 +25,14 @@ export const CurrencyDisplay = ({
fieldDefinition,
}: CurrencyDisplayProps) => {
const theme = useTheme();
const instanceId = useId();
const [shouldRenderTooltip, setShouldRenderTooltip] = useState(false);
const CurrencyIcon = isDefined(currencyValue?.currencyCode)
? SETTINGS_FIELD_CURRENCY_CODES[currencyValue?.currencyCode]?.Icon
const currencyCode = currencyValue?.currencyCode;
const currencyMetadata = isDefined(currencyCode)
? SETTINGS_FIELD_CURRENCY_CODES[currencyCode]
: null;
const CurrencyIcon = currencyMetadata?.Icon ?? null;
const amountToDisplay = isUndefinedOrNull(currencyValue?.amountMicros)
? null
@@ -36,23 +43,51 @@ export const CurrencyDisplay = ({
const decimalsToUse = decimals ?? DEFAULT_DECIMAL_VALUE;
const { formatNumber } = useNumberFormat();
const tooltipAnchorId = `currency-icon-${instanceId.replace(/[^a-zA-Z0-9-_]/g, '-')}`;
const currencyTooltipContent = isDefined(currencyCode)
? `${currencyCode}${currencyMetadata?.label ? ` - ${currencyMetadata.label}` : ''}`
: undefined;
const shouldShowCurrencyTooltip =
isDefined(CurrencyIcon) &&
amountToDisplay !== null &&
isDefined(currencyTooltipContent);
return (
<EllipsisDisplay>
{isDefined(CurrencyIcon) && amountToDisplay !== null && (
<>
<CurrencyIcon
color={theme.font.color.primary}
size={theme.icon.size.md}
stroke={theme.icon.stroke.sm}
/>{' '}
</>
)}
{amountToDisplay !== null
? !isDefined(format) || format === 'short'
? formatToShortNumber(amountToDisplay)
: formatNumber(amountToDisplay, { decimals: decimalsToUse })
: null}
</EllipsisDisplay>
<>
<EllipsisDisplay>
{shouldShowCurrencyTooltip && (
<>
<span
id={tooltipAnchorId}
onMouseEnter={() => setShouldRenderTooltip(true)}
onMouseLeave={() => setShouldRenderTooltip(false)}
>
<CurrencyIcon
color={theme.font.color.primary}
size={theme.icon.size.md}
stroke={theme.icon.stroke.sm}
/>
</span>{' '}
</>
)}
{amountToDisplay !== null
? !isDefined(format) || format === 'short'
? formatToShortNumber(amountToDisplay)
: formatNumber(amountToDisplay, { decimals: decimalsToUse })
: null}
</EllipsisDisplay>
{shouldRenderTooltip &&
shouldShowCurrencyTooltip &&
createPortal(
<AppTooltip
anchorSelect={`#${tooltipAnchorId}`}
content={currencyTooltipContent}
delay={TooltipDelay.shortDelay}
place={TooltipPosition.Top}
positionStrategy="fixed"
/>,
document.body,
)}
</>
);
};
@@ -1,6 +1,5 @@
import { useCreateFavorite } from '@/favorites/hooks/useCreateFavorite';
import { useFavorites } from '@/favorites/hooks/useFavorites';
import { useCreateNavigationMenuItem } from '@/navigation-menu-item/hooks/useCreateNavigationMenuItem';
import { usePrefetchedNavigationMenuItemsData } from '@/navigation-menu-item/hooks/usePrefetchedNavigationMenuItemsData';
import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';
import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
@@ -24,8 +23,8 @@ import {
import { MenuItem } from 'twenty-ui/navigation';
import {
FeatureFlagKey,
ViewVisibility,
PermissionFlagType,
ViewVisibility,
} from '~/generated-metadata/graphql';
type ViewPickerOptionDropdownProps = {
@@ -63,10 +62,9 @@ export const ViewPickerOptionDropdown = ({
const { sortedFavorites: favorites } = useFavorites();
const { createFavorite } = useCreateFavorite();
const isNavigationMenuItemEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_ENABLED,
const isNavigationMenuItemEditingEnabled = useIsFeatureEnabled(
FeatureFlagKey.IS_NAVIGATION_MENU_ITEM_EDITING_ENABLED,
);
const { createNavigationMenuItem } = useCreateNavigationMenuItem();
const { navigationMenuItems, currentWorkspaceMemberId } =
usePrefetchedNavigationMenuItemsData();
@@ -75,7 +73,7 @@ export const ViewPickerOptionDropdown = ({
const canEditView =
hasViewsPermission || view.visibility === ViewVisibility.UNLISTED;
const isFavorite = isNavigationMenuItemEnabled
const isFavorite = isNavigationMenuItemEditingEnabled
? navigationMenuItems.some(
(item) =>
item.viewId === view.id &&
@@ -94,11 +92,7 @@ export const ViewPickerOptionDropdown = ({
const handleAddToFavorites = () => {
if (!isFavorite) {
if (isNavigationMenuItemEnabled) {
createNavigationMenuItem(view, 'view');
} else {
createFavorite(view, 'view');
}
createFavorite(view, 'view');
} else {
setViewPickerReferenceViewId(view.id);
setViewPickerMode('favorite-folders-picker');
@@ -1,72 +0,0 @@
import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import styled from '@emotion/styled';
const StyledMessageContainer = styled.div`
padding-bottom: ${({ theme }) => theme.spacing(4)};
padding-inline: ${({ theme }) => theme.spacing(7)};
padding-top: ${({ theme }) => theme.spacing(2)};
`;
const StyledMessageContentContainer = styled.div`
flex-direction: column;
color: ${({ theme }) => theme.font.color.secondary};
display: flex;
gap: ${({ theme }) => theme.spacing(4)};
width: 100%;
padding: ${({ theme }) => theme.spacing(4)};
line-height: normal;
`;
const StyledMessageTitle = styled.div`
color: ${({ theme }) => theme.font.color.primary};
font-weight: ${({ theme }) => theme.font.weight.medium};
line-height: 13px;
`;
const StyledMessageDescription = styled.div`
color: ${({ theme }) => theme.font.color.secondary};
font-weight: ${({ theme }) => theme.font.weight.regular};
`;
const StyledFieldContainer = styled.div`
align-items: center;
background: transparent;
border: none;
display: flex;
font-family: inherit;
width: 100%;
`;
export const WorkflowMessage = ({
title,
description,
}: {
title: string;
description: string;
}) => {
return (
<StyledMessageContainer>
<FormFieldInputContainer>
<FormFieldInputRowContainer multiline maxHeight={145}>
<FormFieldInputInnerContainer
formFieldInputInstanceId="workflow-message"
hasRightElement={false}
>
<StyledFieldContainer>
<StyledMessageContentContainer>
<StyledMessageTitle data-testid="workflow-message-title">
{title}
</StyledMessageTitle>
<StyledMessageDescription data-testid="workflow-message-description">
{description}
</StyledMessageDescription>
</StyledMessageContentContainer>
</StyledFieldContainer>
</FormFieldInputInnerContainer>
</FormFieldInputRowContainer>
</FormFieldInputContainer>
</StyledMessageContainer>
);
};
@@ -1,31 +0,0 @@
import { WorkflowMessage } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowMessage';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, within } from 'storybook/test';
const meta: Meta<typeof WorkflowMessage> = {
title: 'Modules/Workflow/Actions/Form/WorkflowMessage',
component: WorkflowMessage,
parameters: {
layout: 'centered',
},
decorators: [],
};
export default meta;
type Story = StoryObj<typeof WorkflowMessage>;
export const Default: Story = {
args: {},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const messageTitleContainer = await canvas.findByTestId(
'workflow-message-title',
);
const messageDescriptionContainer = await canvas.findByTestId(
'workflow-message-description',
);
expect(messageTitleContainer).toBeVisible();
expect(messageDescriptionContainer).toBeVisible();
},
};
@@ -11,7 +11,6 @@ import {
} from '@/workflow/types/Workflow';
import { WorkflowStepBody } from '@/workflow/workflow-steps/components/WorkflowStepBody';
import { WorkflowStepFooter } from '@/workflow/workflow-steps/components/WorkflowStepFooter';
import { WorkflowMessage } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowMessage';
import { WorkflowEditActionFormFieldSettings } from '@/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormFieldSettings';
import { type WorkflowFormActionField } from '@/workflow/workflow-steps/workflow-actions/form-action/types/WorkflowFormActionField';
import { getDefaultFormFieldSettings } from '@/workflow/workflow-steps/workflow-actions/form-action/utils/getDefaultFormFieldSettings';
@@ -25,6 +24,7 @@ import { FieldMetadataType } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import {
Callout,
IconAlertTriangle,
IconChevronDown,
IconGripVertical,
IconPlus,
@@ -51,7 +51,8 @@ type FormData = WorkflowFormActionField[];
const StyledWorkflowStepBody = styled(WorkflowStepBody)`
display: block;
padding-inline: ${({ theme }) => theme.spacing(2)};
padding-left: ${({ theme }) => theme.spacing(2)};
padding-right: ${({ theme }) => theme.spacing(2)};
`;
const StyledFormFieldContainer = styled.div`
@@ -98,7 +99,8 @@ const StyledFieldContainer = styled.div<{
border: none;
display: flex;
font-family: inherit;
padding-inline: ${({ theme }) => theme.spacing(2)};
padding-left: ${({ theme }) => theme.spacing(2)};
padding-right: ${({ theme }) => theme.spacing(2)};
width: 100%;
cursor: ${({ readonly }) => (readonly ? 'default' : 'pointer')};
@@ -118,7 +120,8 @@ const StyledPlaceholder = styled(FormFieldPlaceholder)`
`;
const StyledAddFieldButtonContainer = styled.div`
padding-inline: ${({ theme }) => theme.spacing(7)};
padding-left: ${({ theme }) => theme.spacing(7)};
padding-right: ${({ theme }) => theme.spacing(7)};
padding-top: ${({ theme }) => theme.spacing(2)};
`;
@@ -132,6 +135,17 @@ const StyledAddFieldButtonContentContainer = styled.div`
width: 100%;
`;
const StyledCalloutContainer = styled.div`
padding-bottom: ${({ theme }) => theme.spacing(2)};
padding-left: ${({ theme }) => theme.spacing(7)};
padding-right: ${({ theme }) => theme.spacing(7)};
padding-top: ${({ theme }) => theme.spacing(2)};
`;
const StyledNotClosableCalloutContainer = styled(StyledCalloutContainer)`
padding-bottom: ${({ theme }) => theme.spacing(4)};
`;
export const WorkflowEditActionFormBuilder = ({
triggerType,
action,
@@ -221,27 +235,35 @@ export const WorkflowEditActionFormBuilder = ({
<>
<StyledWorkflowStepBody>
{triggerType && triggerType !== 'MANUAL' && isCalloutVisible && (
<Callout
variant={'warning'}
title={t`This form will appear in workflow runs.`}
description={t`Because this workflow is not using a manual trigger, the form will not open on top of the interface. To fill it, open the corresponding workflow run and complete the form there.`}
onClose={() => setIsCalloutVisible(false)}
action={{
label: t`Learn more`,
onClick: () =>
window.open(
'https://docs.twenty.com/user-guide/workflows/capabilities/workflow-actions#form',
'_blank',
'noopener,noreferrer',
),
}}
/>
<StyledCalloutContainer>
<Callout
variant={'warning'}
Icon={IconAlertTriangle}
title={t`This form will appear in workflow runs.`}
description={t`Because this workflow is not using a manual trigger, the form will not open on top of the interface. To fill it, open the corresponding workflow run and complete the form there.`}
isClosable
onClose={() => setIsCalloutVisible(false)}
action={{
label: t`Learn more`,
onClick: () =>
window.open(
'https://docs.twenty.com/user-guide/workflows/capabilities/workflow-actions#form',
'_blank',
'noopener,noreferrer',
),
}}
/>
</StyledCalloutContainer>
)}
{formData.length === 0 && (
<WorkflowMessage
title={t`Add inputs to your form`}
description={t`Click on "Add Field" below to add the first input to your form. The form will pop up on the user's screen when the workflow is launched from a manual trigger. For other types of triggers, it will be displayed in the Workflow run record page.`}
/>
<StyledNotClosableCalloutContainer>
<Callout
variant={'neutral'}
isClosable={false}
title={t`Add inputs to your form`}
description={t`Click on "Add Field" below to add the first input to your form. The form will pop up on the user's screen when the workflow is launched from a manual trigger. For other types of triggers, it will be displayed in the Workflow run record page.`}
/>
</StyledNotClosableCalloutContainer>
)}
<DraggableList
onDragEnd={handleDragEnd}
@@ -179,9 +179,7 @@ export const EmptyForm: Story = {
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const messageContainer = await canvas.findByTestId(
'workflow-message-title',
);
const messageContainer = await canvas.findByText('Add inputs to your form');
expect(messageContainer).toBeVisible();
@@ -6,13 +6,13 @@ import { WorkflowStepBody } from '@/workflow/workflow-steps/components/WorkflowS
import { WorkflowStepFooter } from '@/workflow/workflow-steps/components/WorkflowStepFooter';
import { WorkflowEditActionCodeFields } from '@/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowEditActionCodeFields';
import { setNestedValue } from '@/workflow/workflow-steps/workflow-actions/code-action/utils/setNestedValue';
import { WorkflowMessage } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowMessage';
import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
import styled from '@emotion/styled';
import { useLingui } from '@lingui/react/macro';
import { isObject } from '@sniptt/guards';
import { useMemo } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { Callout } from 'twenty-ui/display';
import { useDebouncedCallback } from 'use-debounce';
const StyledContainer = styled.div`
@@ -118,7 +118,8 @@ export const WorkflowEditActionLogicFunction = ({
fullWidth
/>
) : (
<WorkflowMessage
<Callout
variant={'neutral'}
title={t`No input fields for this action`}
description={t`You can see the function logic in your application settings.`}
/>
+10 -1
View File
@@ -130,14 +130,17 @@ Application development commands.
- `twenty entity:add [entityType]` — Add a new entity to your application.
- Arguments:
- `entityType`: one of `function`, `front-component`, `object`, or `role`. If omitted, an interactive prompt is shown.
- `entityType`: one of `object`, `field`, `function`, `front-component`, `role`, `view`, or `navigation-menu-item`. If omitted, an interactive prompt is shown.
- Options:
- `--path <path>`: The path where the entity file should be created (relative to the current directory).
- Behavior:
- `object`: prompts for singular/plural names and labels, then creates a `*.object.ts` definition file.
- `field`: prompts for name, label, type, and target object, then creates a `*.field.ts` definition file.
- `function`: prompts for a name and scaffolds a `*.function.ts` logic function file.
- `front-component`: prompts for a name and scaffolds a `*.front-component.tsx` file.
- `role`: prompts for a name and scaffolds a `*.role.ts` role definition file.
- `view`: prompts for a name and target object, then creates a `*.view.ts` definition file.
- `navigation-menu-item`: prompts for a name and scaffolds a `*.navigation-menu-item.ts` file.
### Function
@@ -171,6 +174,12 @@ twenty entity:add function
# Add a new front component
twenty entity:add front-component
# Add a new view
twenty entity:add view
# Add a new navigation menu item
twenty entity:add navigation-menu-item
# Uninstall the app from the workspace
twenty app:uninstall
@@ -1,9 +1,15 @@
import { FieldType } from '@/sdk';
import type { Manifest } from 'twenty-shared/application';
import { PermissionFlagType } from 'twenty-shared/constants';
import { FieldMetadataType } from 'twenty-shared/types';
import {
FieldMetadataType,
RelationOnDeleteAction,
RelationType,
ViewType,
} from 'twenty-shared/types';
export const EXPECTED_MANIFEST: Manifest = {
pageLayouts: [],
publicAssets: [
{
checksum: '99496069dcc2a1488e1cae9f826d2707',
@@ -70,6 +76,50 @@ export const EXPECTED_MANIFEST: Manifest = {
],
fields: [
{
label: 'Post Card',
name: 'postCard',
objectUniversalIdentifier: 'e1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5e',
relationTargetFieldMetadataUniversalIdentifier:
'a1a2b3c4-0001-4a7b-8c9d-0e1f2a3b4c5d',
relationTargetObjectMetadataUniversalIdentifier:
'54b589ca-eeed-4950-a176-358418b85c05',
type: FieldType.RELATION,
universalIdentifier: 'a1a2b3c4-0002-4a7b-8c9d-0e1f2a3b4c5d',
universalSettings: {
joinColumnName: 'postCardId',
onDelete: RelationOnDeleteAction.CASCADE,
relationType: RelationType.MANY_TO_ONE,
},
},
{
label: 'Post Card Recipients',
name: 'postCardRecipients',
objectUniversalIdentifier: '54b589ca-eeed-4950-a176-358418b85c05',
relationTargetFieldMetadataUniversalIdentifier:
'a1a2b3c4-0002-4a7b-8c9d-0e1f2a3b4c5d',
relationTargetObjectMetadataUniversalIdentifier:
'e1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5e',
type: FieldType.RELATION,
universalIdentifier: 'a1a2b3c4-0001-4a7b-8c9d-0e1f2a3b4c5d',
universalSettings: {
relationType: RelationType.ONE_TO_MANY,
},
},
{
label: 'Post Card Recipients',
name: 'postCardRecipients',
objectUniversalIdentifier: 'd1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
relationTargetFieldMetadataUniversalIdentifier:
'a1a2b3c4-0004-4a7b-8c9d-0e1f2a3b4c5d',
relationTargetObjectMetadataUniversalIdentifier:
'e1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5e',
type: FieldType.RELATION,
universalIdentifier: 'a1a2b3c4-0003-4a7b-8c9d-0e1f2a3b4c5d',
universalSettings: {
relationType: RelationType.ONE_TO_MANY,
},
},
{
objectUniversalIdentifier: '54b589ca-eeed-4950-a176-358418b85c05',
description: 'Post card category',
@@ -78,18 +128,21 @@ export const EXPECTED_MANIFEST: Manifest = {
options: [
{
color: 'blue',
id: 'c1d2e3f4-0001-4000-8000-000000000001',
label: 'Personal',
position: 0,
value: 'PERSONAL',
},
{
color: 'green',
id: 'c1d2e3f4-0002-4000-8000-000000000002',
label: 'Business',
position: 1,
value: 'BUSINESS',
},
{
color: 'orange',
id: 'c1d2e3f4-0003-4000-8000-000000000003',
label: 'Promotional',
position: 2,
value: 'PROMOTIONAL',
@@ -106,6 +159,22 @@ export const EXPECTED_MANIFEST: Manifest = {
type: FieldType.NUMBER,
universalIdentifier: '7a8b9c0d-1e2f-3a4b-5c6d-7e8f9a0b1c2d',
},
{
label: 'Recipient',
name: 'recipient',
objectUniversalIdentifier: 'e1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5e',
relationTargetFieldMetadataUniversalIdentifier:
'a1a2b3c4-0003-4a7b-8c9d-0e1f2a3b4c5d',
relationTargetObjectMetadataUniversalIdentifier:
'd1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
type: FieldType.RELATION,
universalIdentifier: 'a1a2b3c4-0004-4a7b-8c9d-0e1f2a3b4c5d',
universalSettings: {
joinColumnName: 'recipientId',
onDelete: RelationOnDeleteAction.CASCADE,
relationType: RelationType.MANY_TO_ONE,
},
},
],
objects: [
{
@@ -209,6 +278,104 @@ export const EXPECTED_MANIFEST: Manifest = {
nameSingular: 'rootNote',
universalIdentifier: 'b0b1b2b3-b4b5-4000-8000-000000000001',
},
{
description: 'Junction object linking post cards to their recipients',
fields: [
{
defaultValue: null,
icon: 'IconClock',
isNullable: true,
label: 'Sent at',
name: 'sentAt',
type: FieldType.DATE_TIME,
universalIdentifier: 'e2a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5e',
},
{
defaultValue: 'uuid',
description: 'Id',
icon: 'Icon123',
isNullable: false,
label: 'Id',
name: 'id',
type: FieldMetadataType.UUID,
universalIdentifier: '2809d745-deb3-5ac0-8328-ea6256ec22b3',
},
{
defaultValue: null,
description: 'Name',
icon: 'IconAbc',
isNullable: true,
label: 'Name',
name: 'name',
type: FieldMetadataType.TEXT,
universalIdentifier: 'a6ee6cc8-b9a0-5e23-a39e-bc3fee2aa3d3',
},
{
defaultValue: 'now',
description: 'Creation date',
icon: 'IconCalendar',
isNullable: false,
label: 'Creation date',
name: 'createdAt',
type: FieldMetadataType.DATE_TIME,
universalIdentifier: '87ad23b6-b04e-5dc1-9907-c1eca54ea6d6',
},
{
defaultValue: 'now',
description: 'Last time the record was changed',
icon: 'IconCalendarClock',
isNullable: false,
label: 'Last update',
name: 'updatedAt',
type: FieldMetadataType.DATE_TIME,
universalIdentifier: '6d7523dc-c097-5b75-96eb-37502d09cc19',
},
{
defaultValue: null,
description: 'Deletion date',
icon: 'IconCalendarClock',
isNullable: true,
label: 'Deleted at',
name: 'deletedAt',
type: FieldMetadataType.DATE_TIME,
universalIdentifier: 'bd4fe2fa-373a-5fdd-ba09-cb5435781e4c',
},
{
defaultValue: {
name: "''",
source: "'MANUAL'",
},
description: 'The creator of the record',
icon: 'IconCreativeCommonsSa',
isNullable: false,
label: 'Created by',
name: 'createdBy',
type: FieldMetadataType.ACTOR,
universalIdentifier: 'c5026f20-ab7a-54e0-900e-37a2d5381aee',
},
{
defaultValue: {
name: "''",
source: "'MANUAL'",
},
description: 'The workspace member who last updated the record',
icon: 'IconUserCircle',
isNullable: false,
label: 'Updated by',
name: 'updatedBy',
type: FieldMetadataType.ACTOR,
universalIdentifier: '1dd75ff5-5fd0-51df-b3a3-a12e3aff30df',
},
],
icon: 'IconLink',
labelIdentifierFieldMetadataUniversalIdentifier:
'a6ee6cc8-b9a0-5e23-a39e-bc3fee2aa3d3',
labelPlural: 'Post Card Recipients',
labelSingular: 'Post Card Recipient',
namePlural: 'postCardRecipients',
nameSingular: 'postCardRecipient',
universalIdentifier: 'e1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5e',
},
{
description: 'A post card object',
fields: [
@@ -242,24 +409,28 @@ export const EXPECTED_MANIFEST: Manifest = {
options: [
{
color: 'gray',
id: 'a1b2c3d4-0001-4000-8000-000000000001',
label: 'Draft',
position: 0,
value: 'DRAFT',
},
{
color: 'orange',
id: 'a1b2c3d4-0002-4000-8000-000000000002',
label: 'Sent',
position: 1,
value: 'SENT',
},
{
color: 'green',
id: 'a1b2c3d4-0003-4000-8000-000000000003',
label: 'Delivered',
position: 2,
value: 'DELIVERED',
},
{
color: 'orange',
id: 'a1b2c3d4-0004-4000-8000-000000000004',
label: 'Returned',
position: 3,
value: 'RETURNED',
@@ -363,6 +534,109 @@ export const EXPECTED_MANIFEST: Manifest = {
nameSingular: 'postCard',
universalIdentifier: '54b589ca-eeed-4950-a176-358418b85c05',
},
{
description: 'A person or organization that receives post cards',
fields: [
{
icon: 'IconMail',
label: 'Email',
name: 'email',
type: FieldType.EMAILS,
universalIdentifier: 'd2a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
},
{
icon: 'IconHome',
label: 'Address',
name: 'address',
type: FieldType.ADDRESS,
universalIdentifier: 'd3a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
},
{
defaultValue: 'uuid',
description: 'Id',
icon: 'Icon123',
isNullable: false,
label: 'Id',
name: 'id',
type: FieldMetadataType.UUID,
universalIdentifier: '71aa41d7-54d0-5447-bf98-f37435b62bc4',
},
{
defaultValue: null,
description: 'Name',
icon: 'IconAbc',
isNullable: true,
label: 'Name',
name: 'name',
type: FieldMetadataType.TEXT,
universalIdentifier: 'ff07c707-df79-58fa-91a4-c60c31f90e6e',
},
{
defaultValue: 'now',
description: 'Creation date',
icon: 'IconCalendar',
isNullable: false,
label: 'Creation date',
name: 'createdAt',
type: FieldMetadataType.DATE_TIME,
universalIdentifier: '8dd42a57-7aca-5e60-89c1-6e0e430dad43',
},
{
defaultValue: 'now',
description: 'Last time the record was changed',
icon: 'IconCalendarClock',
isNullable: false,
label: 'Last update',
name: 'updatedAt',
type: FieldMetadataType.DATE_TIME,
universalIdentifier: 'a81e915c-f21d-5163-a547-f04029655bf0',
},
{
defaultValue: null,
description: 'Deletion date',
icon: 'IconCalendarClock',
isNullable: true,
label: 'Deleted at',
name: 'deletedAt',
type: FieldMetadataType.DATE_TIME,
universalIdentifier: '33ba5fa8-dbc3-5a08-b0e0-d85b18ff15e0',
},
{
defaultValue: {
name: "''",
source: "'MANUAL'",
},
description: 'The creator of the record',
icon: 'IconCreativeCommonsSa',
isNullable: false,
label: 'Created by',
name: 'createdBy',
type: FieldMetadataType.ACTOR,
universalIdentifier: '7c377262-63b7-5a79-ba54-f7b8acd804dc',
},
{
defaultValue: {
name: "''",
source: "'MANUAL'",
},
description: 'The workspace member who last updated the record',
icon: 'IconUserCircle',
isNullable: false,
label: 'Updated by',
name: 'updatedBy',
type: FieldMetadataType.ACTOR,
universalIdentifier: '8da8e149-b60e-52e2-878d-73d05c8312b2',
},
],
icon: 'IconUser',
labelIdentifierFieldMetadataUniversalIdentifier:
'ff07c707-df79-58fa-91a4-c60c31f90e6e',
labelPlural: 'Recipients',
labelSingular: 'Recipient',
namePlural: 'recipients',
nameSingular: 'recipient',
universalIdentifier: 'd1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
},
],
roles: [
{
@@ -410,9 +684,87 @@ export const EXPECTED_MANIFEST: Manifest = {
universalIdentifier: 'b648f87b-1d26-4961-b974-0908fd991061',
},
],
views: [],
navigationMenuItems: [],
pageLayouts: [],
views: [
{
fields: [
{
fieldMetadataUniversalIdentifier:
'e2a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5e',
isVisible: true,
position: 0,
size: 200,
universalIdentifier: 'bf1a2b3c-0004-4a7b-8c9d-0e1f2a3b4c5d',
},
],
icon: 'IconLink',
name: 'All Post Card Recipients',
objectUniversalIdentifier: 'e1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5e',
position: 2,
type: ViewType.TABLE,
universalIdentifier: 'b1a2b3c4-0003-4a7b-8c9d-0e1f2a3b4c5d',
},
{
fields: [
{
fieldMetadataUniversalIdentifier:
'58a0a314-d7ea-4865-9850-7fb84e72f30b',
isVisible: true,
position: 0,
size: 200,
universalIdentifier: 'bf1a2b3c-0001-4a7b-8c9d-0e1f2a3b4c5d',
},
{
fieldMetadataUniversalIdentifier:
'87b675b8-dd8c-4448-b4ca-20e5a2234a1e',
isVisible: true,
position: 1,
size: 150,
universalIdentifier: 'bf1a2b3c-0002-4a7b-8c9d-0e1f2a3b4c5d',
},
],
icon: 'IconMail',
name: 'All Post Cards',
objectUniversalIdentifier: '54b589ca-eeed-4950-a176-358418b85c05',
position: 0,
type: ViewType.TABLE,
universalIdentifier: 'b1a2b3c4-0001-4a7b-8c9d-0e1f2a3b4c5d',
},
{
fields: [
{
fieldMetadataUniversalIdentifier:
'd2a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
isVisible: true,
position: 0,
size: 200,
universalIdentifier: 'bf1a2b3c-0003-4a7b-8c9d-0e1f2a3b4c5d',
},
],
icon: 'IconUser',
name: 'All Recipients',
objectUniversalIdentifier: 'd1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
position: 1,
type: ViewType.TABLE,
universalIdentifier: 'b1a2b3c4-0002-4a7b-8c9d-0e1f2a3b4c5d',
},
],
navigationMenuItems: [
{
position: 2,
universalIdentifier: 'c1a2b3c4-0003-4a7b-8c9d-0e1f2a3b4c5d',
viewUniversalIdentifier: 'b1a2b3c4-0003-4a7b-8c9d-0e1f2a3b4c5d',
},
{
position: 0,
universalIdentifier: 'c1a2b3c4-0001-4a7b-8c9d-0e1f2a3b4c5d',
viewUniversalIdentifier: 'b1a2b3c4-0001-4a7b-8c9d-0e1f2a3b4c5d',
},
{
position: 1,
universalIdentifier: 'c1a2b3c4-0002-4a7b-8c9d-0e1f2a3b4c5d',
viewUniversalIdentifier: 'b1a2b3c4-0002-4a7b-8c9d-0e1f2a3b4c5d',
},
],
logicFunctions: [
{
builtHandlerChecksum: '[checksum]',
@@ -444,6 +796,39 @@ export const EXPECTED_MANIFEST: Manifest = {
},
universalIdentifier: '9d412d9e-2caf-487c-8b66-d1585883dd4e',
},
{
builtHandlerChecksum: '[checksum]',
builtHandlerPath: 'src/logic-functions/lookup-recipient.function.mjs',
description: 'Look up a recipient by name to find their details',
handlerName: 'default.config.handler',
isTool: true,
name: 'lookup-recipient',
sourceHandlerPath: 'src/logic-functions/lookup-recipient.function.ts',
timeoutSeconds: 5,
toolInputSchema: {
type: 'object',
properties: {
recipientName: {
type: 'string',
},
},
},
universalIdentifier: 'a1b2c3d4-1001-4a7b-8c9d-0e1f2a3b4c5d',
},
{
builtHandlerChecksum: '[checksum]',
builtHandlerPath: 'src/logic-functions/on-post-card-created.function.mjs',
databaseEventTriggerSettings: {
eventName: 'postCard.created',
},
description: 'Triggered when a new post card is created',
handlerName: 'default.config.handler',
name: 'on-post-card-created',
sourceHandlerPath: 'src/logic-functions/on-post-card-created.function.ts',
timeoutSeconds: 5,
toolInputSchema: { type: 'object', properties: {} },
universalIdentifier: 'a1b2c3d4-db01-4a7b-8c9d-0e1f2a3b4c5d',
},
{
builtHandlerChecksum: '[checksum]',
builtHandlerPath: 'src/logic-functions/test-function-2.function.mjs',
@@ -25,6 +25,10 @@ export const defineEntitiesTests = (appPath: string): void => {
'src/logic-functions',
'src/logic-functions/greeting.function.mjs',
'src/logic-functions/greeting.function.mjs.map',
'src/logic-functions/lookup-recipient.function.mjs',
'src/logic-functions/lookup-recipient.function.mjs.map',
'src/logic-functions/on-post-card-created.function.mjs',
'src/logic-functions/on-post-card-created.function.mjs.map',
'src/logic-functions/test-function-2.function.mjs',
'src/logic-functions/test-function-2.function.mjs.map',
'src/logic-functions/test-function.function.mjs',
@@ -42,11 +42,13 @@ export const defineManifestTests = (appPath: string): void => {
it('should load all entity types', async () => {
const manifest = await fs.readJson(manifestOutputPath);
expect(manifest.objects).toHaveLength(2);
expect(manifest.logicFunctions).toHaveLength(4);
expect(manifest.objects).toHaveLength(4);
expect(manifest.logicFunctions).toHaveLength(6);
expect(manifest.frontComponents).toHaveLength(4);
expect(manifest.roles).toHaveLength(2);
expect(manifest.fields).toHaveLength(2);
expect(manifest.fields).toHaveLength(6);
expect(manifest.views).toHaveLength(3);
expect(manifest.navigationMenuItems).toHaveLength(3);
});
});
};
@@ -0,0 +1,24 @@
import {
POST_CARD_ON_POST_CARD_RECIPIENT_ID,
POST_CARD_RECIPIENTS_ON_POST_CARD_ID,
} from '@/cli/__tests__/apps/rich-app/src/fields/post-card-recipients-on-post-card.field';
import { POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/post-card-recipient.object';
import { defineField, FieldType, OnDeleteAction, RelationType } from '@/sdk';
import { POST_CARD_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/post-card.object';
export default defineField({
universalIdentifier: POST_CARD_ON_POST_CARD_RECIPIENT_ID,
objectUniversalIdentifier: POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'postCard',
label: 'Post Card',
relationTargetObjectMetadataUniversalIdentifier:
POST_CARD_UNIVERSAL_IDENTIFIER,
relationTargetFieldMetadataUniversalIdentifier:
POST_CARD_RECIPIENTS_ON_POST_CARD_ID,
universalSettings: {
relationType: RelationType.MANY_TO_ONE,
onDelete: OnDeleteAction.CASCADE,
joinColumnName: 'postCardId',
},
});
@@ -0,0 +1,23 @@
import { POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/post-card-recipient.object';
import { defineField, FieldType, RelationType } from '@/sdk';
import { POST_CARD_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/post-card.object';
export const POST_CARD_RECIPIENTS_ON_POST_CARD_ID =
'a1a2b3c4-0001-4a7b-8c9d-0e1f2a3b4c5d';
export const POST_CARD_ON_POST_CARD_RECIPIENT_ID =
'a1a2b3c4-0002-4a7b-8c9d-0e1f2a3b4c5d';
export default defineField({
universalIdentifier: POST_CARD_RECIPIENTS_ON_POST_CARD_ID,
objectUniversalIdentifier: POST_CARD_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'postCardRecipients',
label: 'Post Card Recipients',
relationTargetObjectMetadataUniversalIdentifier:
POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER,
relationTargetFieldMetadataUniversalIdentifier:
POST_CARD_ON_POST_CARD_RECIPIENT_ID,
universalSettings: {
relationType: RelationType.ONE_TO_MANY,
},
});
@@ -0,0 +1,23 @@
import { defineField, FieldType, RelationType } from '@/sdk';
import { RECIPIENT_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/recipient.object';
import { POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/post-card-recipient.object';
export const POST_CARD_RECIPIENTS_ON_RECIPIENT_ID =
'a1a2b3c4-0003-4a7b-8c9d-0e1f2a3b4c5d';
export const RECIPIENT_ON_POST_CARD_RECIPIENT_ID =
'a1a2b3c4-0004-4a7b-8c9d-0e1f2a3b4c5d';
export default defineField({
universalIdentifier: POST_CARD_RECIPIENTS_ON_RECIPIENT_ID,
objectUniversalIdentifier: RECIPIENT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'postCardRecipients',
label: 'Post Card Recipients',
relationTargetObjectMetadataUniversalIdentifier:
POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER,
relationTargetFieldMetadataUniversalIdentifier:
RECIPIENT_ON_POST_CARD_RECIPIENT_ID,
universalSettings: {
relationType: RelationType.ONE_TO_MANY,
},
});
@@ -1,5 +1,5 @@
import { defineField, FieldType } from '@/sdk';
import { POST_CARD_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/postCard.object';
import { POST_CARD_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/post-card.object';
export default defineField({
objectUniversalIdentifier: POST_CARD_UNIVERSAL_IDENTIFIER,
@@ -9,9 +9,22 @@ export default defineField({
label: 'Category',
description: 'Post card category',
options: [
{ value: 'PERSONAL', label: 'Personal', color: 'blue', position: 0 },
{ value: 'BUSINESS', label: 'Business', color: 'green', position: 1 },
{
id: 'c1d2e3f4-0001-4000-8000-000000000001',
value: 'PERSONAL',
label: 'Personal',
color: 'blue',
position: 0,
},
{
id: 'c1d2e3f4-0002-4000-8000-000000000002',
value: 'BUSINESS',
label: 'Business',
color: 'green',
position: 1,
},
{
id: 'c1d2e3f4-0003-4000-8000-000000000003',
value: 'PROMOTIONAL',
label: 'Promotional',
color: 'orange',
@@ -1,5 +1,5 @@
import { defineField, FieldType } from '@/sdk';
import { POST_CARD_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/postCard.object';
import { POST_CARD_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/post-card.object';
export default defineField({
objectUniversalIdentifier: POST_CARD_UNIVERSAL_IDENTIFIER,
@@ -0,0 +1,24 @@
import { defineField, FieldType, RelationType, OnDeleteAction } from '@/sdk';
import { RECIPIENT_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/recipient.object';
import { POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER } from '@/cli/__tests__/apps/rich-app/src/objects/post-card-recipient.object';
import {
POST_CARD_RECIPIENTS_ON_RECIPIENT_ID,
RECIPIENT_ON_POST_CARD_RECIPIENT_ID,
} from '@/cli/__tests__/apps/rich-app/src/fields/post-card-recipients-on-recipient.field';
export default defineField({
universalIdentifier: RECIPIENT_ON_POST_CARD_RECIPIENT_ID,
objectUniversalIdentifier: POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'recipient',
label: 'Recipient',
relationTargetObjectMetadataUniversalIdentifier:
RECIPIENT_UNIVERSAL_IDENTIFIER,
relationTargetFieldMetadataUniversalIdentifier:
POST_CARD_RECIPIENTS_ON_RECIPIENT_ID,
universalSettings: {
relationType: RelationType.MANY_TO_ONE,
onDelete: OnDeleteAction.CASCADE,
joinColumnName: 'recipientId',
},
});
@@ -0,0 +1,14 @@
import { defineLogicFunction } from '@/sdk';
const handler = async (params: { recipientName: string }) => {
return { found: true, name: params.recipientName };
};
export default defineLogicFunction({
universalIdentifier: 'a1b2c3d4-1001-4a7b-8c9d-0e1f2a3b4c5d',
name: 'lookup-recipient',
description: 'Look up a recipient by name to find their details',
timeoutSeconds: 5,
handler,
isTool: true,
});
@@ -0,0 +1,16 @@
import { defineLogicFunction } from '@/sdk';
const handler = async () => {
return { processed: true };
};
export default defineLogicFunction({
universalIdentifier: 'a1b2c3d4-db01-4a7b-8c9d-0e1f2a3b4c5d',
name: 'on-post-card-created',
description: 'Triggered when a new post card is created',
timeoutSeconds: 5,
handler,
databaseEventTriggerSettings: {
eventName: 'postCard.created',
},
});
@@ -0,0 +1,8 @@
import { defineNavigationMenuItem } from '@/sdk';
import { ALL_POST_CARD_RECIPIENTS_VIEW_ID } from '@/cli/__tests__/apps/rich-app/src/views/all-post-card-recipients.view';
export default defineNavigationMenuItem({
universalIdentifier: 'c1a2b3c4-0003-4a7b-8c9d-0e1f2a3b4c5d',
position: 2,
viewUniversalIdentifier: ALL_POST_CARD_RECIPIENTS_VIEW_ID,
});
@@ -0,0 +1,8 @@
import { defineNavigationMenuItem } from '@/sdk';
import { ALL_POST_CARDS_VIEW_ID } from '@/cli/__tests__/apps/rich-app/src/views/all-post-cards.view';
export default defineNavigationMenuItem({
universalIdentifier: 'c1a2b3c4-0001-4a7b-8c9d-0e1f2a3b4c5d',
position: 0,
viewUniversalIdentifier: ALL_POST_CARDS_VIEW_ID,
});
@@ -0,0 +1,8 @@
import { defineNavigationMenuItem } from '@/sdk';
import { ALL_RECIPIENTS_VIEW_ID } from '@/cli/__tests__/apps/rich-app/src/views/all-recipients.view';
export default defineNavigationMenuItem({
universalIdentifier: 'c1a2b3c4-0002-4a7b-8c9d-0e1f2a3b4c5d',
position: 1,
viewUniversalIdentifier: ALL_RECIPIENTS_VIEW_ID,
});
@@ -0,0 +1,28 @@
import { defineObject, FieldType } from '@/sdk';
export const POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER =
'e1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5e';
export const SENT_AT_FIELD_UNIVERSAL_IDENTIFIER =
'e2a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5e';
export default defineObject({
universalIdentifier: POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER,
nameSingular: 'postCardRecipient',
namePlural: 'postCardRecipients',
labelSingular: 'Post Card Recipient',
labelPlural: 'Post Card Recipients',
description: 'Junction object linking post cards to their recipients',
icon: 'IconLink',
fields: [
{
universalIdentifier: SENT_AT_FIELD_UNIVERSAL_IDENTIFIER,
type: FieldType.DATE_TIME,
label: 'Sent at',
name: 'sentAt',
icon: 'IconClock',
isNullable: true,
defaultValue: null,
},
],
});
@@ -53,24 +53,28 @@ export default defineObject({
defaultValue: `'${PostCardStatus.DRAFT}'`,
options: [
{
id: 'a1b2c3d4-0001-4000-8000-000000000001',
value: PostCardStatus.DRAFT,
label: 'Draft',
position: 0,
color: 'gray',
},
{
id: 'a1b2c3d4-0002-4000-8000-000000000002',
value: PostCardStatus.SENT,
label: 'Sent',
position: 1,
color: 'orange',
},
{
id: 'a1b2c3d4-0003-4000-8000-000000000003',
value: PostCardStatus.DELIVERED,
label: 'Delivered',
position: 2,
color: 'green',
},
{
id: 'a1b2c3d4-0004-4000-8000-000000000004',
value: PostCardStatus.RETURNED,
label: 'Returned',
position: 3,
@@ -0,0 +1,33 @@
import { defineObject, FieldType } from '@/sdk';
export const RECIPIENT_UNIVERSAL_IDENTIFIER =
'd1a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5d';
export const RECIPIENT_EMAIL_FIELD_UNIVERSAL_IDENTIFIER =
'd2a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5d';
export default defineObject({
universalIdentifier: RECIPIENT_UNIVERSAL_IDENTIFIER,
nameSingular: 'recipient',
namePlural: 'recipients',
labelSingular: 'Recipient',
labelPlural: 'Recipients',
description: 'A person or organization that receives post cards',
icon: 'IconUser',
fields: [
{
universalIdentifier: RECIPIENT_EMAIL_FIELD_UNIVERSAL_IDENTIFIER,
type: FieldType.EMAILS,
label: 'Email',
name: 'email',
icon: 'IconMail',
},
{
universalIdentifier: 'd3a2b3c4-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
type: FieldType.ADDRESS,
label: 'Address',
name: 'address',
icon: 'IconHome',
},
],
});
@@ -2,7 +2,7 @@ import { PermissionFlag, defineRole } from '@/sdk';
import {
CONTENT_FIELD_UNIVERSAL_IDENTIFIER,
POST_CARD_UNIVERSAL_IDENTIFIER,
} from '@/cli/__tests__/apps/rich-app/src/objects/postCard.object';
} from '@/cli/__tests__/apps/rich-app/src/objects/post-card.object';
export const DEFAULT_ROLE_UNIVERSAL_IDENTIFIER =
'b648f87b-1d26-4961-b974-0908fd991061';
@@ -0,0 +1,27 @@
import {
POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER,
SENT_AT_FIELD_UNIVERSAL_IDENTIFIER,
} from '@/cli/__tests__/apps/rich-app/src/objects/post-card-recipient.object';
import { defineView } from '@/sdk';
import { ViewType } from 'twenty-shared/types';
export const ALL_POST_CARD_RECIPIENTS_VIEW_ID =
'b1a2b3c4-0003-4a7b-8c9d-0e1f2a3b4c5d';
export default defineView({
universalIdentifier: ALL_POST_CARD_RECIPIENTS_VIEW_ID,
name: 'All Post Card Recipients',
objectUniversalIdentifier: POST_CARD_RECIPIENT_UNIVERSAL_IDENTIFIER,
type: ViewType.TABLE,
icon: 'IconLink',
position: 2,
fields: [
{
universalIdentifier: 'bf1a2b3c-0004-4a7b-8c9d-0e1f2a3b4c5d',
fieldMetadataUniversalIdentifier: SENT_AT_FIELD_UNIVERSAL_IDENTIFIER,
position: 0,
isVisible: true,
size: 200,
},
],
});
@@ -0,0 +1,33 @@
import { defineView } from '@/sdk';
import {
CONTENT_FIELD_UNIVERSAL_IDENTIFIER,
POST_CARD_UNIVERSAL_IDENTIFIER,
} from '@/cli/__tests__/apps/rich-app/src/objects/post-card.object';
import { ViewType } from 'twenty-shared/types';
export const ALL_POST_CARDS_VIEW_ID = 'b1a2b3c4-0001-4a7b-8c9d-0e1f2a3b4c5d';
export default defineView({
universalIdentifier: ALL_POST_CARDS_VIEW_ID,
name: 'All Post Cards',
objectUniversalIdentifier: POST_CARD_UNIVERSAL_IDENTIFIER,
type: ViewType.TABLE,
icon: 'IconMail',
position: 0,
fields: [
{
universalIdentifier: 'bf1a2b3c-0001-4a7b-8c9d-0e1f2a3b4c5d',
fieldMetadataUniversalIdentifier: CONTENT_FIELD_UNIVERSAL_IDENTIFIER,
position: 0,
isVisible: true,
size: 200,
},
{
universalIdentifier: 'bf1a2b3c-0002-4a7b-8c9d-0e1f2a3b4c5d',
fieldMetadataUniversalIdentifier: '87b675b8-dd8c-4448-b4ca-20e5a2234a1e',
position: 1,
isVisible: true,
size: 150,
},
],
});
@@ -0,0 +1,27 @@
import {
RECIPIENT_EMAIL_FIELD_UNIVERSAL_IDENTIFIER,
RECIPIENT_UNIVERSAL_IDENTIFIER,
} from '@/cli/__tests__/apps/rich-app/src/objects/recipient.object';
import { defineView } from '@/sdk';
import { ViewType } from 'twenty-shared/types';
export const ALL_RECIPIENTS_VIEW_ID = 'b1a2b3c4-0002-4a7b-8c9d-0e1f2a3b4c5d';
export default defineView({
universalIdentifier: ALL_RECIPIENTS_VIEW_ID,
name: 'All Recipients',
objectUniversalIdentifier: RECIPIENT_UNIVERSAL_IDENTIFIER,
type: ViewType.TABLE,
icon: 'IconUser',
position: 1,
fields: [
{
universalIdentifier: 'bf1a2b3c-0003-4a7b-8c9d-0e1f2a3b4c5d',
fieldMetadataUniversalIdentifier:
RECIPIENT_EMAIL_FIELD_UNIVERSAL_IDENTIFIER,
position: 0,
isVisible: true,
size: 200,
},
],
});
@@ -1,10 +1,12 @@
import { CURRENT_EXECUTION_DIRECTORY } from '@/cli/utilities/config/current-execution-directory';
import { getFrontComponentBaseFile } from '@/cli/utilities/entity/entity-front-component-template';
import { getLogicFunctionBaseFile } from '@/cli/utilities/entity/entity-logic-function-template';
import { getNavigationMenuItemBaseFile } from '@/cli/utilities/entity/entity-navigation-menu-item-template';
import { convertToLabel } from '@/cli/utilities/entity/entity-label';
import { getObjectBaseFile } from '@/cli/utilities/entity/entity-object-template';
import { getPageLayoutBaseFile } from '@/cli/utilities/entity/entity-page-layout-template';
import { getRoleBaseFile } from '@/cli/utilities/entity/entity-role-template';
import { getViewBaseFile } from '@/cli/utilities/entity/entity-view-template';
import chalk from 'chalk';
import * as fs from 'fs-extra';
import inquirer from 'inquirer';
@@ -114,13 +116,34 @@ export class EntityAddCommand {
return { name, file };
}
case SyncableEntity.View: {
const entityData = await this.getViewData();
const name = entityData.name;
const file = getViewBaseFile({
name,
});
return { name, file };
}
case SyncableEntity.NavigationMenuItem: {
const name = await this.getEntityName(entity);
const file = getNavigationMenuItemBaseFile({
name,
});
return { name, file };
}
case SyncableEntity.PageLayout: {
const name = await this.getEntityName(entity);
const file = getPageLayoutBaseFile({
name,
});
return { name, file };
}
@@ -302,6 +325,39 @@ export class EntityAddCommand {
]);
}
private async getViewData() {
return inquirer.prompt<{
name: string;
objectUniversalIdentifier: string;
}>([
{
type: 'input',
name: 'name',
message: 'Enter a name for your view:',
default: '',
validate: (input: string) => {
if (!input || input.trim().length === 0) {
return 'Please enter a non empty string';
}
return true;
},
},
{
type: 'input',
name: 'objectUniversalIdentifier',
message:
'Enter the universalIdentifier of the object this view belongs to:',
default: 'fill-later',
validate: (input: string) => {
if (!input || input.trim().length === 0) {
return 'Please enter a non empty string';
}
return true;
},
},
]);
}
getFolderName(entity: SyncableEntity) {
return `${kebabcase(entity)}s`;
}
@@ -69,6 +69,8 @@ const ENTITY_TYPE_TO_SYNCABLE: Record<string, SyncableEntity | undefined> = {
logicFunctions: SyncableEntity.LogicFunction,
frontComponents: SyncableEntity.FrontComponent,
roles: SyncableEntity.Role,
views: SyncableEntity.View,
navigationMenuItems: SyncableEntity.NavigationMenuItem,
pageLayouts: SyncableEntity.PageLayout,
};
@@ -97,6 +97,8 @@ export const ENTITY_LABELS: Record<SyncableEntity, string> = {
[SyncableEntity.LogicFunction]: 'Logic functions',
[SyncableEntity.FrontComponent]: 'Front components',
[SyncableEntity.Role]: 'Roles',
[SyncableEntity.View]: 'Views',
[SyncableEntity.NavigationMenuItem]: 'Navigation menu items',
[SyncableEntity.PageLayout]: 'Page layouts',
};
@@ -7,24 +7,38 @@ import {
UPLOAD_FRAMES,
} from '@/cli/utilities/dev/ui/dev-ui-constants';
export const useAnimatedFrame = (frames: string[], interval = 80): string => {
export const useAnimatedFrame = (
frames: string[],
interval = 80,
enabled = true,
): string => {
const [frameIndex, setFrameIndex] = useState(0);
useEffect(() => {
if (!enabled) return;
const timer = setInterval(() => {
setFrameIndex((currentIndex) => (currentIndex + 1) % frames.length);
}, interval);
return () => clearInterval(timer);
}, [frames, interval]);
}, [frames, interval, enabled]);
return frames[frameIndex];
};
export const useStatusIcon = (uiStatus: DevUiStatus): string => {
const spinnerFrame = useAnimatedFrame(SPINNER_FRAMES, 80);
const uploadFrame = useAnimatedFrame(UPLOAD_FRAMES, 200);
const config = DEV_UI_STATUS_CONFIG[uiStatus];
const spinnerFrame = useAnimatedFrame(
SPINNER_FRAMES,
80,
config.icon === 'spinner',
);
const uploadFrame = useAnimatedFrame(
UPLOAD_FRAMES,
200,
config.icon === 'upload',
);
if (config.icon === 'spinner') return spinnerFrame;
if (config.icon === 'upload') return uploadFrame;
@@ -0,0 +1,28 @@
import kebabCase from 'lodash.kebabcase';
import { v4 } from 'uuid';
export const getNavigationMenuItemBaseFile = ({
name,
universalIdentifier = v4(),
}: {
name: string;
universalIdentifier?: string;
}) => {
const kebabCaseName = kebabCase(name);
return `import { defineNavigationMenuItem } from 'twenty-sdk';
export default defineNavigationMenuItem({
universalIdentifier: '${universalIdentifier}',
name: '${kebabCaseName}',
icon: 'IconList',
position: 0,
// Link to a view:
// viewUniversalIdentifier: '...',
// Or link to an object:
// targetObjectUniversalIdentifier: '...',
// Or link to an external URL:
// link: 'https://example.com',
});
`;
};
@@ -10,7 +10,6 @@ export default definePageLayout({
{
universalIdentifier: '${uuidv4()}',
title: 'Overview',
position: 0,
widgets: [],
},
],
@@ -0,0 +1,39 @@
import kebabCase from 'lodash.kebabcase';
import { v4 } from 'uuid';
export const getViewBaseFile = ({
name,
universalIdentifier = v4(),
}: {
name: string;
universalIdentifier?: string;
}) => {
const kebabCaseName = kebabCase(name);
return `import { defineView } from 'twenty-sdk';
export default defineView({
universalIdentifier: '${universalIdentifier}',
name: '${kebabCaseName}',
objectUniversalIdentifier: 'fill-later',
icon: 'IconList',
position: 0,
// fields: [
// {
// universalIdentifier: '...',
// fieldMetadataUniversalIdentifier: '...',
// position: 0,
// isVisible: true,
// },
// ],
// filters: [
// {
// universalIdentifier: '...',
// fieldMetadataUniversalIdentifier: '...',
// operand: 'Contains',
// value: '',
// },
// ],
});
`;
};
+7 -1
View File
@@ -47,9 +47,15 @@ export type {
export type { RoutePayload } from './logic-functions/triggers/route-payload-type';
export { defineNavigationMenuItem } from './navigation-menu-items/define-navigation-menu-item';
export { defineObject } from './objects/define-object';
export { STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from './objects/standard-object-ids';
export { definePageLayout } from './page-layouts/define-page-layout';
export type { PageLayoutConfig } from './page-layouts/page-layout-config';
export { STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from './objects/standard-object-ids';
export {
AggregateOperations,
ObjectRecordGroupByDateGranularity,
PageLayoutTabLayoutMode,
} from 'twenty-shared/types';
export type { PageLayoutWidgetUniversalConfiguration } from 'twenty-shared/types';
export { defineRole } from './roles/define-role';
export { PermissionFlag } from './roles/permission-flag-type';
export { defineView } from './views/define-view';
@@ -1,3 +1,5 @@
import { randomBytes } from 'crypto';
import { type FieldMetadataType } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { type ObjectLiteral } from 'typeorm';
@@ -33,9 +35,9 @@ export const computeWhereConditionParts = ({
fieldMetadataType: FieldMetadataType;
useDirectTableReference?: boolean;
}): WhereConditionParts => {
const uuid = Math.random().toString(36).slice(2, 7);
const paramSuffix = randomBytes(5).toString('hex');
const secondUuid = Math.random().toString(36).slice(2, 7);
const secondParamSuffix = randomBytes(5).toString('hex');
const fieldReference = useDirectTableReference
? `"${key}"`
@@ -58,99 +60,99 @@ export const computeWhereConditionParts = ({
};
case 'eq':
return {
sql: `${fieldReference} = :${key}${uuid}${hasNullEquivalentFieldValue ? ` OR ${fieldReference} IS NULL` : ''}`,
params: { [`${key}${uuid}`]: value },
sql: `${fieldReference} = :${key}${paramSuffix}${hasNullEquivalentFieldValue ? ` OR ${fieldReference} IS NULL` : ''}`,
params: { [`${key}${paramSuffix}`]: value },
};
case 'neq':
return {
sql: `${fieldReference} != :${key}${uuid}${hasNullEquivalentFieldValue ? ` OR ${fieldReference} IS NOT NULL` : ''}`,
params: { [`${key}${uuid}`]: value },
sql: `${fieldReference} != :${key}${paramSuffix}${hasNullEquivalentFieldValue ? ` OR ${fieldReference} IS NOT NULL` : ''}`,
params: { [`${key}${paramSuffix}`]: value },
};
case 'gt':
return {
sql: `${fieldReference} > :${key}${uuid}`,
params: { [`${key}${uuid}`]: value },
sql: `${fieldReference} > :${key}${paramSuffix}`,
params: { [`${key}${paramSuffix}`]: value },
};
case 'gte':
return {
sql: `${fieldReference} >= :${key}${uuid}`,
params: { [`${key}${uuid}`]: value },
sql: `${fieldReference} >= :${key}${paramSuffix}`,
params: { [`${key}${paramSuffix}`]: value },
};
case 'lt':
return {
sql: `${fieldReference} < :${key}${uuid}`,
params: { [`${key}${uuid}`]: value },
sql: `${fieldReference} < :${key}${paramSuffix}`,
params: { [`${key}${paramSuffix}`]: value },
};
case 'lte':
return {
sql: `${fieldReference} <= :${key}${uuid}`,
params: { [`${key}${uuid}`]: value },
sql: `${fieldReference} <= :${key}${paramSuffix}`,
params: { [`${key}${paramSuffix}`]: value },
};
case 'in':
return {
sql: `${fieldReference} IN (:...${key}${uuid})`,
params: { [`${key}${uuid}`]: value },
sql: `${fieldReference} IN (:...${key}${paramSuffix})`,
params: { [`${key}${paramSuffix}`]: value },
};
case 'is':
return {
sql: `${fieldReference} IS ${value === 'NULL' ? 'NULL' : 'NOT NULL'}${hasNullEquivalentFieldValue ? ` OR ${fieldReference} = :${key}${secondUuid}` : ''}`,
sql: `${fieldReference} IS ${value === 'NULL' ? 'NULL' : 'NOT NULL'}${hasNullEquivalentFieldValue ? ` OR ${fieldReference} = :${key}${secondParamSuffix}` : ''}`,
params: hasNullEquivalentFieldValue
? { [`${key}${secondUuid}`]: nullEquivalentFieldValue }
? { [`${key}${secondParamSuffix}`]: nullEquivalentFieldValue }
: {},
};
case 'like':
return {
sql: `${fieldReference}::text LIKE :${key}${uuid}${hasNullEquivalentFieldValue ? ` OR ${fieldReference} IS NULL` : ''}`,
params: { [`${key}${uuid}`]: `${value}` },
sql: `${fieldReference}::text LIKE :${key}${paramSuffix}${hasNullEquivalentFieldValue ? ` OR ${fieldReference} IS NULL` : ''}`,
params: { [`${key}${paramSuffix}`]: `${value}` },
};
case 'ilike':
return {
sql: `${fieldReference}::text ILIKE :${key}${uuid}${hasNullEquivalentFieldValue ? ` OR ${fieldReference} IS NULL` : ''}`,
params: { [`${key}${uuid}`]: `${value}` },
sql: `${fieldReference}::text ILIKE :${key}${paramSuffix}${hasNullEquivalentFieldValue ? ` OR ${fieldReference} IS NULL` : ''}`,
params: { [`${key}${paramSuffix}`]: `${value}` },
};
case 'startsWith':
return {
sql: `${fieldReference}::text ^@ :${key}${uuid}`,
params: { [`${key}${uuid}`]: `${value}` },
sql: `${fieldReference}::text ^@ :${key}${paramSuffix}`,
params: { [`${key}${paramSuffix}`]: `${value}` },
};
case 'endsWith':
return {
sql: `RIGHT(${fieldReference}::text, LENGTH(:${key}${uuid})) = :${key}${uuid}`,
params: { [`${key}${uuid}`]: `${value}` },
sql: `RIGHT(${fieldReference}::text, LENGTH(:${key}${paramSuffix})) = :${key}${paramSuffix}`,
params: { [`${key}${paramSuffix}`]: `${value}` },
};
case 'contains':
return {
sql: `${fieldReference} @> ARRAY[:...${key}${uuid}]`,
params: { [`${key}${uuid}`]: value },
sql: `${fieldReference} @> ARRAY[:...${key}${paramSuffix}]`,
params: { [`${key}${paramSuffix}`]: value },
};
case 'search': {
const tsQuery = formatSearchTerms(value, 'and');
return {
sql: `(
${fieldReference} @@ to_tsquery('simple', public.unaccent_immutable(:${key}${uuid}Ts)) OR
public.unaccent_immutable(${fieldReference}::text) ILIKE public.unaccent_immutable(:${key}${uuid}Like)
${fieldReference} @@ to_tsquery('simple', public.unaccent_immutable(:${key}${paramSuffix}Ts)) OR
public.unaccent_immutable(${fieldReference}::text) ILIKE public.unaccent_immutable(:${key}${paramSuffix}Like)
)`,
params: {
[`${key}${uuid}Ts`]: tsQuery,
[`${key}${uuid}Like`]: `%${value}%`,
[`${key}${paramSuffix}Ts`]: tsQuery,
[`${key}${paramSuffix}Like`]: `%${value}%`,
},
};
}
case 'notContains':
return {
sql: `NOT (${fieldReference}::text[] && ARRAY[:...${key}${uuid}]::text[])`,
params: { [`${key}${uuid}`]: value },
sql: `NOT (${fieldReference}::text[] && ARRAY[:...${key}${paramSuffix}]::text[])`,
params: { [`${key}${paramSuffix}`]: value },
};
case 'containsAny':
return {
sql: `${fieldReference}::text[] && ARRAY[:...${key}${uuid}]::text[]`,
params: { [`${key}${uuid}`]: value },
sql: `${fieldReference}::text[] && ARRAY[:...${key}${paramSuffix}]::text[]`,
params: { [`${key}${paramSuffix}`]: value },
};
case 'containsIlike':
return {
sql: `EXISTS (SELECT 1 FROM unnest(${fieldReference}) AS elem WHERE elem ILIKE :${key}${uuid})`,
params: { [`${key}${uuid}`]: value },
sql: `EXISTS (SELECT 1 FROM unnest(${fieldReference}) AS elem WHERE elem ILIKE :${key}${paramSuffix})`,
params: { [`${key}${paramSuffix}`]: value },
};
default:
throw new GraphqlQueryRunnerException(
@@ -24,7 +24,7 @@ export const fromPageLayoutWidgetManifestToUniversalFlatPageLayoutWidget = ({
pageLayoutWidgetManifest.objectUniversalIdentifier ?? null,
conditionalDisplay: pageLayoutWidgetManifest.conditionalDisplay ?? null,
gridPosition: { row: 0, column: 0, rowSpan: 1, columnSpan: 1 },
position: pageLayoutWidgetManifest.position ?? null,
position: null,
universalConfiguration:
pageLayoutWidgetManifest.configuration as UniversalFlatPageLayoutWidget['universalConfiguration'],
createdAt: now,
@@ -11,7 +11,7 @@ import { PasswordUpdateNotifyEmail } from 'twenty-emails';
import { PermissionFlagType } from 'twenty-shared/constants';
import { AppPath } from 'twenty-shared/types';
import { assertIsDefinedOrThrow, isDefined } from 'twenty-shared/utils';
import { Repository } from 'typeorm';
import { IsNull, Repository } from 'typeorm';
import { NodeEnvironment } from 'src/engine/core-modules/twenty-config/interfaces/node-environment.interface';
@@ -618,6 +618,18 @@ export class AuthService {
passwordHash: newPasswordHash,
});
// Invalidate all existing refresh tokens for this user across all workspaces
await this.appTokenRepository.update(
{
userId,
type: AppTokenType.RefreshToken,
revokedAt: IsNull(),
},
{
revokedAt: new Date(),
},
);
const emailTemplate = PasswordUpdateNotifyEmail({
userName: `${user.firstName} ${user.lastName}`,
email: user.email,
@@ -0,0 +1,81 @@
import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import path from 'path';
import { FileStorageExceptionCode } from 'src/engine/core-modules/file-storage/interfaces/file-storage-exception';
import { LocalDriver } from 'src/engine/core-modules/file-storage/drivers/local.driver';
describe('LocalDriver security hardening', () => {
const cleanupPaths: string[] = [];
const createTempDirectory = async (prefix: string) => {
const dir = await mkdtemp(path.join(tmpdir(), prefix));
cleanupPaths.push(dir);
return dir;
};
afterAll(async () => {
await Promise.all(
cleanupPaths.map(async (directoryPath) => {
await rm(directoryPath, { recursive: true, force: true });
}),
);
});
it('should reject writeFile when target is a symlink', async () => {
const storagePath = await createTempDirectory('local-driver-storage-');
const outsidePath = await createTempDirectory('local-driver-outside-');
const outsideFilePath = path.join(outsidePath, 'outside.txt');
const symlinkFolderPath = path.join(storagePath, 'workspace', 'app');
const symlinkFilePath = path.join(symlinkFolderPath, 'target.txt');
await mkdir(symlinkFolderPath, { recursive: true });
await writeFile(outsideFilePath, 'outside');
await symlink(outsideFilePath, symlinkFilePath);
const driver = new LocalDriver({ storagePath });
await expect(
driver.writeFile({
filePath: 'workspace/app/target.txt',
sourceFile: Buffer.from('new-content'),
mimeType: undefined,
}),
).rejects.toMatchObject({
code: FileStorageExceptionCode.ACCESS_DENIED,
});
await expect(readFile(outsideFilePath, 'utf8')).resolves.toBe('outside');
});
it('should reject downloadFile when path resolves outside storage', async () => {
const storagePath = await createTempDirectory('local-driver-storage-');
const outsidePath = await createTempDirectory('local-driver-outside-');
const outsideFilePath = path.join(outsidePath, 'outside.txt');
const symlinkFolderPath = path.join(storagePath, 'workspace', 'app');
const symlinkFilePath = path.join(symlinkFolderPath, 'target.txt');
const downloadDestinationPath = path.join(
storagePath,
'download',
'file.txt',
);
await mkdir(symlinkFolderPath, { recursive: true });
await writeFile(outsideFilePath, 'outside');
await symlink(outsideFilePath, symlinkFilePath);
const driver = new LocalDriver({ storagePath });
await expect(
driver.downloadFile({
onStoragePath: 'workspace/app/target.txt',
localPath: downloadDestinationPath,
}),
).rejects.toMatchObject({
code: FileStorageExceptionCode.ACCESS_DENIED,
});
});
});
@@ -74,17 +74,49 @@ export class LocalDriver implements StorageDriver {
await this.createFolder(folderPath);
await fs.writeFile(filePath, params.sourceFile);
const realFolderPath = realpathSync(folderPath);
const realFilePath = path.join(realFolderPath, path.basename(filePath));
this.assertRealPathIsWithinStorage(realFilePath);
try {
const stats = await fs.lstat(realFilePath);
if (stats.isSymbolicLink()) {
throw new FileStorageException(
'Access denied',
FileStorageExceptionCode.ACCESS_DENIED,
);
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
throw error;
}
}
await fs.writeFile(realFilePath, params.sourceFile);
}
async downloadFile(params: {
onStoragePath: string;
localPath: string;
}): Promise<void> {
const filePath = path.resolve(
const resolvedPath = path.resolve(
this.options.storagePath,
params.onStoragePath,
);
let filePath: string;
try {
filePath = realpathSync(resolvedPath);
} catch {
throw new FileStorageException(
'File not found',
FileStorageExceptionCode.FILE_NOT_FOUND,
);
}
this.assertRealPathIsWithinStorage(filePath);
await this.createFolder(dirname(params.localPath));
@@ -97,26 +129,57 @@ export class LocalDriver implements StorageDriver {
onStoragePath: string;
localPath: string;
}): Promise<void> {
const rootFolderPath = path.resolve(
const resolvedPath = path.resolve(
this.options.storagePath,
params.onStoragePath,
);
let rootFolderPath: string;
try {
rootFolderPath = realpathSync(resolvedPath);
} catch {
throw new FileStorageException(
'File not found',
FileStorageExceptionCode.FILE_NOT_FOUND,
);
}
this.assertRealPathIsWithinStorage(rootFolderPath);
await this.createFolder(params.localPath);
const resources = await fs.readdir(rootFolderPath);
await this.downloadFolderFromRealPath({
rootFolderPath,
localPath: params.localPath,
});
}
private async downloadFolderFromRealPath(params: {
rootFolderPath: string;
localPath: string;
}): Promise<void> {
await this.createFolder(params.localPath);
const resources = await fs.readdir(params.rootFolderPath);
for (const resource of resources) {
const resourcePath = path.join(rootFolderPath, resource);
const stats = await fs.stat(resourcePath);
const resourcePath = path.join(params.rootFolderPath, resource);
const stats = await fs.lstat(resourcePath);
if (stats.isSymbolicLink()) {
throw new FileStorageException(
'Access denied',
FileStorageExceptionCode.ACCESS_DENIED,
);
}
if (stats.isFile()) {
const content = await fs.readFile(resourcePath);
await fs.writeFile(path.join(params.localPath, resource), content);
} else {
await this.downloadFolder({
onStoragePath: path.join(params.onStoragePath, resource),
await this.downloadFolderFromRealPath({
rootFolderPath: resourcePath,
localPath: path.join(params.localPath, resource),
});
}
@@ -107,7 +107,7 @@ export class ImapSmtpCaldavResolver {
if (params) {
validatedParams[protocol] =
this.mailConnectionValidatorService.validateProtocolConnectionParams(
await this.mailConnectionValidatorService.validateProtocolConnectionParams(
params,
);
const validatedProtocolParams = validatedParams[protocol];
@@ -1,8 +1,11 @@
import { Module } from '@nestjs/common';
import { SecureHttpClientModule } from 'src/engine/core-modules/secure-http-client/secure-http-client.module';
import { ImapSmtpCaldavValidatorService } from './imap-smtp-caldav-connection-validator.service';
@Module({
imports: [SecureHttpClientModule],
providers: [ImapSmtpCaldavValidatorService],
exports: [ImapSmtpCaldavValidatorService],
})
@@ -4,10 +4,15 @@ import { msg } from '@lingui/core/macro';
import { z } from 'zod';
import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';
import { type ConnectionParameters } from 'src/engine/core-modules/imap-smtp-caldav-connection/types/imap-smtp-caldav-connection.type';
@Injectable()
export class ImapSmtpCaldavValidatorService {
constructor(
private readonly secureHttpClientService: SecureHttpClientService,
) {}
private readonly protocolConnectionSchema = z.object({
host: z.string().min(1, 'Host is required'),
port: z.int().positive('Port must be a positive number'),
@@ -16,9 +21,9 @@ export class ImapSmtpCaldavValidatorService {
secure: z.boolean().optional(),
});
validateProtocolConnectionParams(
async validateProtocolConnectionParams(
params: ConnectionParameters,
): ConnectionParameters {
): Promise<ConnectionParameters> {
if (!params) {
throw new UserInputError('Protocol connection parameters are required', {
userFriendlyMessage: msg`Please provide connection details to configure your email account.`,
@@ -26,8 +31,25 @@ export class ImapSmtpCaldavValidatorService {
}
try {
return this.protocolConnectionSchema.parse(params);
const validated = this.protocolConnectionSchema.parse(params);
try {
await this.secureHttpClientService.getValidatedHost(validated.host);
} catch {
throw new UserInputError(
'Connection to private or internal network addresses is not allowed',
{
userFriendlyMessage: msg`The server address you entered is not allowed. Please use a public server address.`,
},
);
}
return validated;
} catch (error) {
if (error instanceof UserInputError) {
throw error;
}
if (error instanceof z.ZodError) {
const errorMessages = error.issues
.map((err) => `${err.path.join('.')}: ${err.message}`)
@@ -10,8 +10,12 @@ const InternalJwtModule = NestJwtModule.registerAsync({
return {
secret: twentyConfigService.get('APP_SECRET'),
signOptions: {
algorithm: 'HS256',
expiresIn: twentyConfigService.get('ACCESS_TOKEN_EXPIRES_IN'),
},
verifyOptions: {
algorithms: ['HS256'],
},
};
},
inject: [TwentyConfigService],
@@ -215,6 +215,12 @@ export class LocalDriver implements LogicFunctionDriver {
builtFileAbsPath: string;
handlerName: string;
}) {
if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(handlerName)) {
throw new Error(
`Invalid handlerName "${handlerName}": must be a valid JavaScript identifier`,
);
}
const runnerPath = join(dir, '__runner.cjs');
const code = `
// Auto-generated. Do not edit.
@@ -3,6 +3,7 @@ import { Injectable, Logger } from '@nestjs/common';
import axios, { type AxiosInstance, type CreateAxiosDefaults } from 'axios';
import { createSsrfSafeAgent } from 'src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util';
import { resolveAndValidateHostname } from 'src/engine/core-modules/secure-http-client/utils/resolve-and-validate-hostname.util';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { type OutboundRequestContext } from './outbound-request-context.type';
@@ -60,4 +61,28 @@ export class SecureHttpClientService {
getInternalHttpClient(config?: CreateAxiosDefaults): AxiosInstance {
return axios.create(config);
}
async getValidatedHost(hostnameOrUrl: string): Promise<string> {
if (!this.isSafeModeEnabled()) {
return hostnameOrUrl;
}
return resolveAndValidateHostname(hostnameOrUrl);
}
async getValidatedUrl(serverUrl: string): Promise<string> {
if (!this.isSafeModeEnabled()) {
return serverUrl;
}
const resolvedIp = await resolveAndValidateHostname(serverUrl);
const url = new URL(serverUrl);
url.hostname = resolvedIp;
return url.toString();
}
private isSafeModeEnabled(): boolean {
return this.twentyConfigService.get('OUTBOUND_HTTP_SAFE_MODE_ENABLED');
}
}
@@ -0,0 +1,60 @@
import { resolveAndValidateHostname } from 'src/engine/core-modules/secure-http-client/utils/resolve-and-validate-hostname.util';
describe('resolveAndValidateHostname', () => {
let mockDnsLookup: jest.Mock;
beforeEach(() => {
jest.clearAllMocks();
mockDnsLookup = jest.fn();
});
it('should resolve a plain hostname and pass it to DNS lookup', async () => {
mockDnsLookup.mockResolvedValue({ address: '93.184.216.34', family: 4 });
await resolveAndValidateHostname('imap.fastmail.com', mockDnsLookup);
expect(mockDnsLookup).toHaveBeenCalledWith('imap.fastmail.com');
});
it('should extract hostname from a full URL before resolving', async () => {
mockDnsLookup.mockResolvedValue({ address: '93.184.216.34', family: 4 });
await resolveAndValidateHostname(
'https://caldav.example.com:8443/dav/principals',
mockDnsLookup,
);
expect(mockDnsLookup).toHaveBeenCalledWith('caldav.example.com');
});
it('should throw when the resolved IP is private', async () => {
mockDnsLookup.mockResolvedValue({ address: '10.0.0.1', family: 4 });
await expect(
resolveAndValidateHostname('evil.example.com', mockDnsLookup),
).rejects.toThrow(
'Connection to internal IP address 10.0.0.1 is not allowed.',
);
});
it('should return the resolved public IP', async () => {
mockDnsLookup.mockResolvedValue({ address: '93.184.216.34', family: 4 });
const result = await resolveAndValidateHostname(
'mail.example.com',
mockDnsLookup,
);
expect(result).toBe('93.184.216.34');
});
it('should propagate DNS resolution failures', async () => {
mockDnsLookup.mockRejectedValue(
new Error('getaddrinfo ENOTFOUND bogus.invalid'),
);
await expect(
resolveAndValidateHostname('bogus.invalid', mockDnsLookup),
).rejects.toThrow('getaddrinfo ENOTFOUND bogus.invalid');
});
});
@@ -0,0 +1,28 @@
import * as dns from 'dns/promises';
import { isPrivateIp } from 'src/engine/core-modules/secure-http-client/utils/is-private-ip.util';
export const resolveAndValidateHostname = async (
hostnameOrUrl: string,
dnsLookup: typeof dns.lookup = dns.lookup,
): Promise<string> => {
let hostname: string;
try {
const url = new URL(hostnameOrUrl);
hostname = url.hostname;
} catch {
hostname = hostnameOrUrl;
}
const { address: resolvedIp } = await dnsLookup(hostname);
if (isPrivateIp(resolvedIp)) {
throw new Error(
`Connection to internal IP address ${resolvedIp} is not allowed.`,
);
}
return resolvedIp;
};
@@ -72,7 +72,7 @@ export class ConfigVariables {
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.OTHER,
description:
'Enable safe mode for outbound HTTP requests (prevents private IPs and other security risks). Applies to HTTP workflow actions and webhooks.',
'Enable safe mode for outbound requests (prevents private IPs and other security risks). Applies to HTTP workflow actions, webhooks, and IMAP/SMTP/CalDAV connections.',
type: ConfigVariableType.BOOLEAN,
})
@IsOptional()
@@ -70,7 +70,6 @@ export class UserEntity {
@Column({ default: false })
disabled: boolean;
@Field({ nullable: true })
@Column({ nullable: true })
passwordHash: string;
@@ -1,3 +1,7 @@
import {
type ChartFilter,
type UniversalChartFilter,
} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import {
@@ -39,6 +43,33 @@ const getFieldMetadataUniversalIdentifier = ({
return universalIdentifier;
};
const convertChartFilterToUniversalFilter = ({
filter,
fieldMetadataUniversalIdentifierById,
}: {
filter: ChartFilter | undefined;
fieldMetadataUniversalIdentifierById: Partial<Record<string, string>>;
shouldThrowOnMissingIdentifier: boolean;
}): UniversalChartFilter | undefined => {
if (!isDefined(filter)) {
return undefined;
}
return {
...filter,
recordFilters: filter.recordFilters?.map(
({ fieldMetadataId, ...rest }) => ({
...rest,
fieldMetadataUniversalIdentifier: getFieldMetadataUniversalIdentifier({
fieldMetadataId,
fieldMetadataUniversalIdentifierById,
shouldThrowOnMissingIdentifier: false,
}),
}),
),
};
};
export const fromPageLayoutWidgetConfigurationToUniversalConfiguration = ({
configuration,
fieldMetadataUniversalIdentifierById,
@@ -52,8 +83,12 @@ export const fromPageLayoutWidgetConfigurationToUniversalConfiguration = ({
}): UniversalPageLayoutWidgetConfiguration => {
switch (configuration.configurationType) {
case WidgetConfigurationType.AGGREGATE_CHART: {
const { aggregateFieldMetadataId, ratioAggregateConfig, ...rest } =
configuration;
const {
aggregateFieldMetadataId,
ratioAggregateConfig,
filter,
...rest
} = configuration;
const aggregateFieldMetadataUniversalIdentifier =
getFieldMetadataUniversalIdentifier({
@@ -78,11 +113,16 @@ export const fromPageLayoutWidgetConfigurationToUniversalConfiguration = ({
...rest,
aggregateFieldMetadataUniversalIdentifier,
ratioAggregateConfig: universalRatioAggregateConfig,
filter: convertChartFilterToUniversalFilter({
filter,
fieldMetadataUniversalIdentifierById,
shouldThrowOnMissingIdentifier,
}),
};
}
case WidgetConfigurationType.GAUGE_CHART: {
const { aggregateFieldMetadataId, ...rest } = configuration;
const { aggregateFieldMetadataId, filter, ...rest } = configuration;
const aggregateFieldMetadataUniversalIdentifier =
getFieldMetadataUniversalIdentifier({
@@ -94,12 +134,21 @@ export const fromPageLayoutWidgetConfigurationToUniversalConfiguration = ({
return {
...rest,
aggregateFieldMetadataUniversalIdentifier,
filter: convertChartFilterToUniversalFilter({
filter,
fieldMetadataUniversalIdentifierById,
shouldThrowOnMissingIdentifier,
}),
};
}
case WidgetConfigurationType.PIE_CHART: {
const { aggregateFieldMetadataId, groupByFieldMetadataId, ...rest } =
configuration;
const {
aggregateFieldMetadataId,
groupByFieldMetadataId,
filter,
...rest
} = configuration;
const aggregateFieldMetadataUniversalIdentifier =
getFieldMetadataUniversalIdentifier({
@@ -119,6 +168,11 @@ export const fromPageLayoutWidgetConfigurationToUniversalConfiguration = ({
...rest,
aggregateFieldMetadataUniversalIdentifier,
groupByFieldMetadataUniversalIdentifier,
filter: convertChartFilterToUniversalFilter({
filter,
fieldMetadataUniversalIdentifierById,
shouldThrowOnMissingIdentifier,
}),
};
}
@@ -127,6 +181,7 @@ export const fromPageLayoutWidgetConfigurationToUniversalConfiguration = ({
aggregateFieldMetadataId,
primaryAxisGroupByFieldMetadataId,
secondaryAxisGroupByFieldMetadataId,
filter,
...rest
} = configuration;
@@ -159,6 +214,11 @@ export const fromPageLayoutWidgetConfigurationToUniversalConfiguration = ({
aggregateFieldMetadataUniversalIdentifier,
primaryAxisGroupByFieldMetadataUniversalIdentifier,
secondaryAxisGroupByFieldMetadataUniversalIdentifier,
filter: convertChartFilterToUniversalFilter({
filter,
fieldMetadataUniversalIdentifierById,
shouldThrowOnMissingIdentifier,
}),
};
}
@@ -167,6 +227,7 @@ export const fromPageLayoutWidgetConfigurationToUniversalConfiguration = ({
aggregateFieldMetadataId,
primaryAxisGroupByFieldMetadataId,
secondaryAxisGroupByFieldMetadataId,
filter,
...rest
} = configuration;
@@ -199,6 +260,11 @@ export const fromPageLayoutWidgetConfigurationToUniversalConfiguration = ({
aggregateFieldMetadataUniversalIdentifier,
primaryAxisGroupByFieldMetadataUniversalIdentifier,
secondaryAxisGroupByFieldMetadataUniversalIdentifier,
filter: convertChartFilterToUniversalFilter({
filter,
fieldMetadataUniversalIdentifierById,
shouldThrowOnMissingIdentifier,
}),
};
}

Some files were not shown because too many files have changed in this diff Show More