Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fields to update in update record action #9108

Merged
merged 1 commit into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { SelectOption } from '@/spreadsheet-import/types';
import { MultiSelectDisplay } from '@/ui/field/display/components/MultiSelectDisplay';
import { MultiSelectInput } from '@/ui/field/input/components/MultiSelectInput';
import { InputLabel } from '@/ui/input/components/InputLabel';
import { OverlayContainer } from '@/ui/layout/overlay/components/OverlayContainer';
import { usePreviousHotkeyScope } from '@/ui/utilities/hotkey/hooks/usePreviousHotkeyScope';
import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
import { useId, useState } from 'react';
Expand All @@ -20,9 +21,9 @@ import { isDefined } from '~/utils/isDefined';
type FormMultiSelectFieldInputProps = {
label?: string;
defaultValue: FieldMultiSelectValue | string | undefined;
options: SelectOption[];
onPersist: (value: FieldMultiSelectValue | string) => void;
VariablePicker?: VariablePickerComponent;
options: SelectOption[];
};

const StyledDisplayModeContainer = styled.button`
Expand Down Expand Up @@ -50,9 +51,9 @@ const StyledSelectInputContainer = styled.div`
export const FormMultiSelectFieldInput = ({
label,
defaultValue,
options,
onPersist,
VariablePicker,
options,
}: FormMultiSelectFieldInputProps) => {
const inputId = useId();

Expand Down Expand Up @@ -189,13 +190,15 @@ export const FormMultiSelectFieldInput = ({
<StyledSelectInputContainer>
{draftValue.type === 'static' &&
draftValue.editingMode === 'edit' && (
<MultiSelectInput
hotkeyScope={hotkeyScope}
options={options}
onCancel={onCancel}
onOptionSelected={onOptionSelected}
values={draftValue.value}
/>
<OverlayContainer>
<MultiSelectInput
hotkeyScope={hotkeyScope}
options={options}
onCancel={onCancel}
onOptionSelected={onOptionSelected}
values={draftValue.value}
/>
</OverlayContainer>
)}
</StyledSelectInputContainer>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const MultiSelectDisplay = ({
key={index}
thomtrp marked this conversation as resolved.
Show resolved Hide resolved
color={selectedOption.color ?? 'transparent'}
text={selectedOption.label}
Icon={selectedOption.icon ?? undefined}
/>
))}
</StyledContainer>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ export const MultiSelectInput = ({
selected={values?.includes(option.value) || false}
text={option.label}
color={option.color ?? 'transparent'}
Icon={option.icon ?? undefined}
onClick={() =>
onOptionSelected(formatNewSelectedOptions(option.value))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export type WorkflowUpdateRecordActionSettings = BaseWorkflowActionSettings & {
objectName: string;
objectRecord: ObjectRecord;
objectRecordId: string;
fieldsToUpdate: string[];
};
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,14 @@ import {
useIcons,
} from 'twenty-ui';

import { formatFieldMetadataItemAsFieldDefinition } from '@/object-metadata/utils/formatFieldMetadataItemAsFieldDefinition';
import { FormFieldInput } from '@/object-record/record-field/components/FormFieldInput';
import { FormMultiSelectFieldInput } from '@/object-record/record-field/form-types/components/FormMultiSelectFieldInput';
import { WorkflowStepBody } from '@/workflow/components/WorkflowStepBody';
import { WorkflowVariablePicker } from '@/workflow/components/WorkflowVariablePicker';
import { JsonValue } from 'type-fest';
import { useDebouncedCallback } from 'use-debounce';
import { FieldMetadataType } from '~/generated-metadata/graphql';

type WorkflowEditActionFormUpdateRecordProps = {
action: WorkflowUpdateRecordAction;
Expand All @@ -31,9 +36,23 @@ type WorkflowEditActionFormUpdateRecordProps = {
type UpdateRecordFormData = {
objectName: string;
objectRecordId: string;
fieldsToUpdate: string[];
[field: string]: unknown;
};

const AVAILABLE_FIELD_METADATA_TYPES = [
FieldMetadataType.Text,
FieldMetadataType.Number,
FieldMetadataType.Date,
FieldMetadataType.Boolean,
FieldMetadataType.Select,
FieldMetadataType.MultiSelect,
FieldMetadataType.Emails,
FieldMetadataType.Links,
FieldMetadataType.FullName,
FieldMetadataType.Address,
];

Comment on lines +43 to +55
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the reason behind this static list of field types?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Devessier I do not want the user to select a field a do not see the form to be updated. That would look weird. Some fields such as Rating may not be implemented before we get our first users in Beta. I prefer adding this list and remove it once we have all fields

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense.

export const WorkflowEditActionFormUpdateRecord = ({
action,
actionOptions,
Expand All @@ -53,6 +72,7 @@ export const WorkflowEditActionFormUpdateRecord = ({
const [formData, setFormData] = useState<UpdateRecordFormData>({
objectName: action.settings.input.objectName,
objectRecordId: action.settings.input.objectRecordId,
fieldsToUpdate: action.settings.input.fieldsToUpdate ?? [],
...action.settings.input.objectRecord,
});
thomtrp marked this conversation as resolved.
Show resolved Hide resolved
const isFormDisabled = actionOptions.readonly;
Expand All @@ -75,6 +95,7 @@ export const WorkflowEditActionFormUpdateRecord = ({
setFormData({
objectName: action.settings.input.objectName,
objectRecordId: action.settings.input.objectRecordId,
fieldsToUpdate: action.settings.input.fieldsToUpdate ?? [],
...action.settings.input.objectRecord,
});
}, [action.settings.input]);
Expand All @@ -88,6 +109,27 @@ export const WorkflowEditActionFormUpdateRecord = ({
throw new Error('Should have found the metadata item');
}

const inlineFieldMetadataItems = selectedObjectMetadataItem.fields
.filter(
(fieldMetadataItem) =>
!fieldMetadataItem.isSystem &&
fieldMetadataItem.isActive &&
AVAILABLE_FIELD_METADATA_TYPES.includes(fieldMetadataItem.type),
)
.sort((fieldMetadataItemA, fieldMetadataItemB) =>
fieldMetadataItemA.name.localeCompare(fieldMetadataItemB.name),
);

const inlineFieldDefinitions = inlineFieldMetadataItems.map(
(fieldMetadataItem) =>
formatFieldMetadataItemAsFieldDefinition({
field: fieldMetadataItem,
objectMetadataItem: selectedObjectMetadataItem,
showLabel: true,
labelWidth: 90,
}),
);

const saveAction = useDebouncedCallback(
async (formData: UpdateRecordFormData) => {
if (actionOptions.readonly === true) {
Expand All @@ -97,6 +139,7 @@ export const WorkflowEditActionFormUpdateRecord = ({
const {
objectName: updatedObjectName,
objectRecordId: updatedObjectRecordId,
fieldsToUpdate: updatedFieldsToUpdate,
...updatedOtherFields
} = formData;

Expand All @@ -108,6 +151,7 @@ export const WorkflowEditActionFormUpdateRecord = ({
objectName: updatedObjectName,
objectRecordId: updatedObjectRecordId ?? '',
objectRecord: updatedOtherFields,
fieldsToUpdate: updatedFieldsToUpdate ?? [],
},
},
});
Expand Down Expand Up @@ -154,6 +198,7 @@ export const WorkflowEditActionFormUpdateRecord = ({
const newFormData: UpdateRecordFormData = {
objectName: updatedObjectName,
objectRecordId: '',
fieldsToUpdate: [],
};

setFormData(newFormData);
Expand All @@ -172,6 +217,48 @@ export const WorkflowEditActionFormUpdateRecord = ({
objectNameSingular={formData.objectName}
defaultValue={formData.objectRecordId}
/>

<FormMultiSelectFieldInput
label="Fields to update"
defaultValue={formData.fieldsToUpdate}
options={inlineFieldDefinitions.map((field) => ({
label: field.label,
value: field.metadata.fieldName,
icon: getIcon(field.iconName),
color: 'gray',
}))}
onPersist={(fieldsToUpdate) =>
handleFieldChange('fieldsToUpdate', fieldsToUpdate)
}
/>

<HorizontalSeparator noMargin />

{formData.fieldsToUpdate.map((fieldName) => {
const fieldDefinition = inlineFieldDefinitions.find(
(definition) => definition.metadata.fieldName === fieldName,
);

if (!isDefined(fieldDefinition)) {
return null;
}

const currentValue = formData[
fieldDefinition.metadata.fieldName
] as JsonValue;

return (
<FormFieldInput
key={fieldDefinition.metadata.fieldName}
defaultValue={currentValue}
field={fieldDefinition}
onPersist={(value) => {
handleFieldChange(fieldDefinition.metadata.fieldName, value);
}}
VariablePicker={WorkflowVariablePicker}
/>
);
})}
</WorkflowStepBody>
</>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { v4 } from 'uuid';

import { BASE_TYPESCRIPT_PROJECT_INPUT_SCHEMA } from 'src/engine/core-modules/serverless/drivers/constants/base-typescript-project-input-schema';
import { WorkflowActionDTO } from 'src/engine/core-modules/workflow/dtos/workflow-step.dto';
import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
import { ServerlessFunctionService } from 'src/engine/metadata-modules/serverless-function/serverless-function.service';
Expand All @@ -20,7 +21,6 @@ import {
WorkflowActionType,
} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { isDefined } from 'src/utils/is-defined';
import { BASE_TYPESCRIPT_PROJECT_INPUT_SCHEMA } from 'src/engine/core-modules/serverless/drivers/constants/base-typescript-project-input-schema';

const TRIGGER_STEP_ID = 'trigger';

Expand Down Expand Up @@ -152,6 +152,7 @@ export class WorkflowVersionStepWorkspaceService {
objectName: activeObjectMetadataItem?.nameSingular || '',
objectRecord: {},
objectRecordId: '',
fieldsToUpdate: [],
},
},
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type WorkflowUpdateRecordActionInput = {
objectName: string;
objectRecord: ObjectRecord;
objectRecordId: string;
fieldsToUpdate: string[];
thomtrp marked this conversation as resolved.
Show resolved Hide resolved
};

export type WorkflowDeleteRecordActionInput = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import { Injectable } from '@nestjs/common';

import { WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';

import { getObjectMetadataMapItemByNameSingular } from 'src/engine/metadata-modules/utils/get-object-metadata-map-item-by-name-singular.util';
import { ScopedWorkspaceContextFactory } from 'src/engine/twenty-orm/factories/scoped-workspace-context.factory';
import { TwentyORMManager } from 'src/engine/twenty-orm/twenty-orm.manager';
import { formatData } from 'src/engine/twenty-orm/utils/format-data.util';
import { WorkspaceCacheStorageService } from 'src/engine/workspace-cache-storage/workspace-cache-storage.service';
import {
RecordCRUDActionException,
RecordCRUDActionExceptionCode,
Expand All @@ -12,7 +16,11 @@ import { WorkflowActionResult } from 'src/modules/workflow/workflow-executor/wor

@Injectable()
export class UpdateRecordWorkflowAction implements WorkflowAction {
constructor(private readonly twentyORMManager: TwentyORMManager) {}
constructor(
private readonly twentyORMManager: TwentyORMManager,
private readonly workspaceCacheStorageService: WorkspaceCacheStorageService,
private readonly scopedWorkspaceContextFactory: ScopedWorkspaceContextFactory,
) {}

async execute(
workflowActionInput: WorkflowUpdateRecordActionInput,
Expand All @@ -34,14 +42,85 @@ export class UpdateRecordWorkflowAction implements WorkflowAction {
);
}

const workspaceId = this.scopedWorkspaceContextFactory.create().workspaceId;

if (!workspaceId) {
throw new RecordCRUDActionException(
'Failed to read: Workspace ID is required',
RecordCRUDActionExceptionCode.INVALID_REQUEST,
);
}

const currentCacheVersion =
await this.workspaceCacheStorageService.getMetadataVersion(workspaceId);

if (currentCacheVersion === undefined) {
throw new RecordCRUDActionException(
'Failed to read: Metadata cache version not found',
RecordCRUDActionExceptionCode.INVALID_REQUEST,
);
}

const objectMetadataMaps =
await this.workspaceCacheStorageService.getObjectMetadataMaps(
workspaceId,
currentCacheVersion,
);

if (!objectMetadataMaps) {
throw new RecordCRUDActionException(
'Failed to read: Object metadata collection not found',
RecordCRUDActionExceptionCode.INVALID_REQUEST,
);
}

const objectMetadataItemWithFieldsMaps =
getObjectMetadataMapItemByNameSingular(
objectMetadataMaps,
workflowActionInput.objectName,
);

if (!objectMetadataItemWithFieldsMaps) {
throw new RecordCRUDActionException(
`Failed to read: Object ${workflowActionInput.objectName} not found`,
RecordCRUDActionExceptionCode.INVALID_REQUEST,
);
}

if (workflowActionInput.fieldsToUpdate.length === 0) {
return {
result: {
...objectRecord,
},
};
}
thomtrp marked this conversation as resolved.
Show resolved Hide resolved

const objectRecordWithFilteredFields = Object.keys(
workflowActionInput.objectRecord,
).reduce((acc, key) => {
if (workflowActionInput.fieldsToUpdate.includes(key)) {
return {
...acc,
[key]: workflowActionInput.objectRecord[key],
};
}

return acc;
}, {});

const objectRecordFormatted = formatData(
objectRecordWithFilteredFields,
objectMetadataItemWithFieldsMaps,
);

await repository.update(workflowActionInput.objectRecordId, {
...workflowActionInput.objectRecord,
...objectRecordFormatted,
});

return {
result: {
...objectRecord,
...workflowActionInput.objectRecord,
...objectRecordWithFilteredFields,
},
};
}
Expand Down
Loading
Loading