refactor: Move integration attribute async components to /web (#27341)

* calendar switch

* wip

* wip

* wip

* fix
This commit is contained in:
Benny Joo authored and GitHub committed 2026-01-28 10:44:18 -03:00
1 parent 8e5a5629a4
commit 1a31f9136b
14 files changed
+40 -42

No files matched your search

@@ -0,0 +1,57 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { showToast } from "@calcom/ui/components/toast";
import type { IntegrationAttributeSync, ISyncFormData } from "@calcom/features/ee/integration-attribute-sync/repositories/IIntegrationAttributeSyncRepository";
import IntegrationAttributeSyncCard from "./IntegrationAttributeSyncCard";
import type { IIntegrationAttributeSyncCardProps } from "./IntegrationAttributeSyncCard";
type IEditIntegrationAttributeSyncCardProps = Pick<
IIntegrationAttributeSyncCardProps,
"credentialOptions" | "teamOptions" | "attributes" | "organizationId" | "attributeOptions"
> & {
sync: IntegrationAttributeSync;
};
const EditIntegrationAttributeSyncCard = (props: IEditIntegrationAttributeSyncCardProps) => {
const { t } = useLocale();
const utils = trpc.useUtils();
const updateMutation = trpc.viewer.attributeSync.updateAttributeSync.useMutation({
onSuccess: () => {
utils.viewer.attributeSync.getAllAttributeSyncs.invalidate();
showToast(t("attribute_sync_updated_successfully"), "success");
},
onError: (error) => {
showToast(error.message, "error");
},
});
const deleteMutation = trpc.viewer.attributeSync.deleteAttributeSync.useMutation({
onSuccess: () => {
utils.viewer.attributeSync.getAllAttributeSyncs.invalidate();
showToast(t("attribute_sync_deleted_successfully"), "success");
},
onError: (error) => {
showToast(error.message, "error");
},
});
const onSubmit = (data: ISyncFormData) => {
updateMutation.mutate({ ...data });
};
const onDelete = () => {
deleteMutation.mutate({ id: props.sync.id });
};
return (
<IntegrationAttributeSyncCard
{...props}
onSubmit={onSubmit}
onDelete={onDelete}
isSubmitting={updateMutation.isPending}
/>
);
};
export default EditIntegrationAttributeSyncCard;
@@ -0,0 +1,196 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { Input, Select, Switch } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { getDefaultFieldMapping } from "@calcom/features/ee/integration-attribute-sync/lib/fieldMappingHelpers";
import type {
IFieldMappingFormState,
IFieldMappingWithOptionalId,
} from "@calcom/features/ee/integration-attribute-sync/repositories/IIntegrationAttributeSyncRepository";
type AttributeOptions = {
label: string;
value: string;
}[];
interface FieldMappingBuilderProps {
value: IFieldMappingFormState;
onChange: (value: IFieldMappingFormState) => void;
attributeOptions: AttributeOptions;
isLoadingAttributes?: boolean;
}
interface MappingRowProps {
mapping: IFieldMappingWithOptionalId;
onChange: (mapping: IFieldMappingWithOptionalId) => void;
onRemove: () => void;
attributeOptions: AttributeOptions;
isLoading?: boolean;
error?: string;
}
const MappingRow = ({ mapping, onChange, onRemove, attributeOptions, isLoading, error }: MappingRowProps) => {
const { t } = useLocale();
const selectedAttribute = attributeOptions.find((opt) => opt.value === mapping.attributeId);
const handleFieldNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
onChange({
...mapping,
integrationFieldName: e.target.value,
});
};
const handleAttributeChange = (selected: { value: string; label: string } | null) => {
if (!selected) return;
onChange({
...mapping,
attributeId: selected.value,
});
};
const handleEnabledChange = (checked: boolean) => {
onChange({
...mapping,
enabled: checked,
});
};
return (
<div>
<div
className={`bg-default border-subtle flex flex-wrap items-center gap-3 rounded-lg border p-3 ${error ? "border-red-500" : ""}`}>
<div className="flex-1" style={{ minWidth: "200px" }}>
<Input
type="text"
value={mapping.integrationFieldName}
onChange={handleFieldNameChange}
disabled={isLoading}
placeholder={t("attribute_sync_field_placeholder")}
className="h-7 text-sm"
/>
</div>
<Icon name="arrow-right" className="text-subtle h-4 w-4" />
<div className="flex-1" style={{ minWidth: "200px" }}>
<Select
size="sm"
placeholder={t("attribute_sync_select_attribute")}
options={attributeOptions}
value={selectedAttribute}
onChange={handleAttributeChange}
isLoading={isLoading}
isDisabled={isLoading}
className="w-full"
/>
</div>
<Switch checked={mapping.enabled} onCheckedChange={handleEnabledChange} disabled={isLoading} />
<Button
color="minimal"
size="sm"
StartIcon="trash-2"
onClick={onRemove}
disabled={isLoading}
className="text-subtle hover:text-default"
aria-label={t("remove")}
/>
</div>
{error && <p className="mt-1 text-xs text-red-600">{error}</p>}
</div>
);
};
export const FieldMappingBuilder = ({
value,
onChange,
attributeOptions,
isLoadingAttributes,
}: FieldMappingBuilderProps) => {
const { t } = useLocale();
// Find indices of rows with duplicate attribute mappings
const duplicateIndices = new Set<number>();
const seenAttributes = new Map<string, number>(); // attributeId -> first index
value.mappings.forEach((mapping: IFieldMappingWithOptionalId, index: number) => {
if (mapping.attributeId) {
const firstIndex = seenAttributes.get(mapping.attributeId);
if (firstIndex !== undefined) {
// Mark both the first occurrence and current as duplicates
duplicateIndices.add(firstIndex);
duplicateIndices.add(index);
} else {
seenAttributes.set(mapping.attributeId, index);
}
}
});
const handleAddMapping = () => {
onChange({
...value,
mappings: [...value.mappings, getDefaultFieldMapping()],
});
};
const handleMappingChange = (index: number, newMapping: IFieldMappingWithOptionalId) => {
const newMappings = [...value.mappings];
newMappings[index] = newMapping;
onChange({
...value,
mappings: newMappings,
});
};
const handleRemoveMapping = (index: number) => {
onChange({
...value,
mappings: value.mappings.filter((_: IFieldMappingWithOptionalId, i: number) => i !== index),
});
};
return (
<div className="bg-default border-subtle rounded-2xl border p-2">
<div className="ml-2 flex items-center gap-0.5">
<div className="border-subtle rounded-lg border p-1">
<Icon name="link" className="text-subtle h-4 w-4" />
</div>
<span className="text-emphasis ml-2 text-sm font-medium">{t("attribute_sync_field_mappings")}</span>
</div>
<div className="bg-muted mt-2 space-y-2 rounded-xl p-2">
{value.mappings.length === 0 ? (
<div className="text-subtle py-6 text-center text-sm">{t("attribute_sync_no_mappings")}</div>
) : (
value.mappings.map((mapping: IFieldMappingWithOptionalId, index: number) => (
<MappingRow
key={mapping.id || `new-${index}`}
mapping={mapping}
onChange={(newMapping) => handleMappingChange(index, newMapping)}
onRemove={() => handleRemoveMapping(index)}
attributeOptions={attributeOptions}
isLoading={isLoadingAttributes}
error={
duplicateIndices.has(index)
? t("attribute_sync_duplicate_attribute_mapping")
: undefined
}
/>
))
)}
</div>
<Button
color="minimal"
size="sm"
StartIcon="plus"
className="mt-2"
onClick={handleAddMapping}
disabled={isLoadingAttributes}>
{t("attribute_sync_add_mapping")}
</Button>
</div>
);
};
@@ -0,0 +1,312 @@
import { useEffect, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { Attribute } from "@calcom/app-store/routing-forms/types/types";
import { Button } from "@calcom/ui/components/button";
import { FormCard, FormCardBody } from "@calcom/ui/components/card";
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
import { SelectField, Switch } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import {
type IntegrationAttributeSync,
type ISyncFormData,
RuleOperatorEnum,
} from "@calcom/features/ee/integration-attribute-sync/repositories/IIntegrationAttributeSyncRepository";
import { FieldMappingBuilder } from "./FieldMappingBuilder";
import { RuleBuilder } from "./RuleBuilder";
export interface IIntegrationAttributeSyncCardProps {
sync?: IntegrationAttributeSync; // Optional for create mode
credentialOptions: {
value: string;
label: string;
}[];
teamOptions: {
value: string;
label: string;
}[];
attributes: Attribute[];
attributeOptions: {
value: string;
label: string;
}[];
organizationId: number;
onSubmit: (data: ISyncFormData) => void;
isSubmitting: boolean;
onCancel?: () => void;
onDelete?: () => void;
}
const IntegrationAttributeSyncCard = (
props: IIntegrationAttributeSyncCardProps
) => {
const {
sync,
credentialOptions,
teamOptions,
attributes,
attributeOptions,
organizationId,
onSubmit,
onCancel,
onDelete,
isSubmitting,
} = props;
const { t } = useLocale();
const isCreateMode = !sync;
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
// Initialize form with sync data or defaults
const form = useForm<ISyncFormData>({
defaultValues: sync
? {
id: sync.id,
name: sync.name,
credentialId: sync.credentialId ?? undefined,
enabled: sync.enabled,
organizationId: sync.organizationId,
ruleId: sync.attributeSyncRule?.id || "",
rule: sync.attributeSyncRule?.rule || {
operator: RuleOperatorEnum.AND,
conditions: [],
},
syncFieldMappings: Array.isArray(sync.syncFieldMappings)
? sync.syncFieldMappings
: [],
}
: {
id: "",
name: t("attribute_sync_new_integration_sync"),
credentialId: undefined,
enabled: true,
organizationId,
ruleId: "",
rule: { operator: RuleOperatorEnum.AND, conditions: [] },
syncFieldMappings: [],
},
});
// Update form when sync prop changes (after refetch with new IDs)
useEffect(() => {
if (sync) {
form.reset({
id: sync.id,
name: sync.name,
credentialId: sync.credentialId ?? undefined,
enabled: sync.enabled,
organizationId: sync.organizationId,
ruleId: sync.attributeSyncRule?.id || "",
rule: sync.attributeSyncRule?.rule || {
operator: RuleOperatorEnum.AND,
conditions: [],
},
syncFieldMappings: Array.isArray(sync.syncFieldMappings)
? sync.syncFieldMappings
: [],
});
}
// Only need to run if the sync changes
}, [sync?.id]);
const onFormSubmit = (data: ISyncFormData) => {
onSubmit(data);
};
const handleDelete = () => {
if (!sync) return;
setShowDeleteDialog(true);
};
const confirmDelete = () => {
if (!sync || !onDelete) return;
onDelete();
setShowDeleteDialog(false);
};
const formName = form.watch("name");
const isPending = isSubmitting;
return (
<>
<form onSubmit={form.handleSubmit(onFormSubmit)}>
<FormCard
label={formName}
leftIcon="link"
collapsible={true}
isLabelEditable={true}
onLabelChange={(label) => {
form.setValue("name", label, { shouldDirty: true });
}}
customActions={
<Controller
name="enabled"
control={form.control}
render={({ field }) => (
<Switch
checked={field.value}
onCheckedChange={field.onChange}
onClick={(e) => e.stopPropagation()}
/>
)}
/>
}
deleteField={
!isCreateMode && onDelete
? {
check: () => true,
fn: handleDelete,
}
: undefined
}
>
<FormCardBody>
<div className="space-y-4">
<div className="bg-default border-subtle rounded-2xl border p-2">
<div className="ml-2 flex items-center gap-0.5">
<div className="border-subtle rounded-lg border p-1">
<Icon name="key" className="text-subtle h-4 w-4" />
</div>
<span className="text-emphasis ml-2 text-sm font-medium">
{t("attribute_sync_credential")}
</span>
</div>
<div className="mt-2">
<Controller
name="credentialId"
control={form.control}
rules={{
required: t("attribute_sync_credential_required"),
validate: (value) => {
if (!value || value <= 0) {
return t("attribute_sync_credential_validation");
}
return true;
},
}}
render={({ field, fieldState }) => (
<>
<SelectField
placeholder={t("attribute_sync_select_credential")}
options={credentialOptions}
value={
credentialOptions.find(
(opt) => Number(opt.value) === field.value
) || null
}
onChange={(option) =>
field.onChange(Number(option?.value))
}
/>
{fieldState.error && (
<p className="mt-1 text-xs text-red-600">
{fieldState.error.message}
</p>
)}
</>
)}
/>
<p className="text-subtle mt-1 text-xs">
{t("attribute_sync_credential_description")}
</p>
</div>
</div>
<div>
<label className="text-emphasis mb-2 block text-sm font-medium">
{t("attribute_sync_user_filter_rules")}
</label>
<Controller
name="rule"
control={form.control}
render={({ field }) => (
<RuleBuilder
value={field.value}
onChange={field.onChange}
teamOptions={teamOptions}
attributes={attributes ?? []}
/>
)}
/>
<p className="text-subtle mt-1 text-xs">
{t("attribute_sync_user_filter_rules_description")}
</p>
</div>
<div>
<label className="text-emphasis mb-2 block text-sm font-medium">
{t("attribute_sync_field_mappings")}
</label>
<Controller
name="syncFieldMappings"
control={form.control}
rules={{
validate: (mappings) => {
const seenAttributes = new Set<string>();
for (const mapping of mappings || []) {
if (
mapping.attributeId &&
seenAttributes.has(mapping.attributeId)
) {
return t(
"attribute_sync_duplicate_attribute_mapping"
);
}
if (mapping.attributeId)
seenAttributes.add(mapping.attributeId);
}
return true;
},
}}
render={({ field }) => (
<FieldMappingBuilder
value={{ mappings: field.value || [] }}
onChange={(fieldMappings) =>
field.onChange(fieldMappings.mappings)
}
attributeOptions={attributeOptions}
/>
)}
/>
<p className="text-subtle mt-1 text-xs">
{t("attribute_sync_field_mappings_description")}
</p>
</div>
<div className="border-subtle flex justify-end gap-2 border-t pt-4">
{isCreateMode && onCancel && (
<Button type="button" color="secondary" onClick={onCancel}>
{t("cancel")}
</Button>
)}
<Button
type="submit"
loading={isPending}
disabled={!form.formState.isDirty}
>
{isCreateMode ? t("create") : t("save")}
</Button>
</div>
</div>
</FormCardBody>
</FormCard>
</form>
<Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<ConfirmationDialogContent
variety="danger"
title={t("attribute_sync_delete_title")}
confirmBtnText={t("delete")}
onConfirm={confirmDelete}
>
{t("attribute_sync_delete_confirmation")}
</ConfirmationDialogContent>
</Dialog>
</>
);
};
export default IntegrationAttributeSyncCard;
@@ -0,0 +1,106 @@
"use client";
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { Attribute } from "@calcom/app-store/routing-forms/types/types";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import EditIntegrationAttributeSyncCard from "./EditIntegrationAttributeSyncCard";
import NewIntegrationAttributeSyncCard from "./NewIntegrationAttributeSyncCard";
import type { IntegrationAttributeSync } from "@calcom/features/ee/integration-attribute-sync/repositories/IIntegrationAttributeSyncRepository";
interface IIntegrationAttributeSyncViewProps {
credentialsData: {
id: number;
type: string;
team: {
name: string;
} | null;
}[];
initialIntegrationAttributeSyncs: IntegrationAttributeSync[];
organizationTeams: {
id: number;
name: string;
}[];
attributes: Attribute[];
organizationId: number;
}
const IntegrationAttributeSyncView = (props: IIntegrationAttributeSyncViewProps) => {
const { credentialsData, initialIntegrationAttributeSyncs, organizationTeams, attributes, organizationId } =
props;
const { t } = useLocale();
const [showNewSync, setShowNewSync] = useState(false);
const { data: integrationAttributeSyncs } = trpc.viewer.attributeSync.getAllAttributeSyncs.useQuery(
{},
{
initialData: initialIntegrationAttributeSyncs,
}
);
const credentialOptions =
credentialsData?.map((cred) => ({
value: String(cred.id),
label: `${cred.type} ${cred.team?.name ? `(${cred.team.name})` : ""}`,
})) ?? [];
const teamOptions =
organizationTeams?.map((team) => ({
value: String(team.id),
label: team.name,
})) ?? [];
const attributeOptions =
attributes?.map((attr) => ({
value: attr.id,
label: attr.name,
})) ?? [];
const handleAddNewSync = () => {
setShowNewSync(true);
};
const handleCancel = () => {
setShowNewSync(false);
};
return (
<>
{integrationAttributeSyncs && integrationAttributeSyncs.length > 0 && (
<div className="mb-4 space-y-2">
{integrationAttributeSyncs.map((sync) => (
<EditIntegrationAttributeSyncCard
key={sync.id}
sync={sync}
credentialOptions={credentialOptions}
teamOptions={teamOptions}
attributes={attributes}
attributeOptions={attributeOptions}
organizationId={organizationId}
/>
))}
</div>
)}
{showNewSync && (
<NewIntegrationAttributeSyncCard
credentialOptions={credentialOptions}
teamOptions={teamOptions}
attributes={attributes}
attributeOptions={attributeOptions}
organizationId={organizationId}
onCancel={handleCancel}
/>
)}
<Button StartIcon="plus" onClick={handleAddNewSync}>
{t("attribute_sync_add_new")}
</Button>
</>
);
};
export default IntegrationAttributeSyncView;
@@ -0,0 +1,47 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { showToast } from "@calcom/ui/components/toast";
import type { ISyncFormData } from "@calcom/features/ee/integration-attribute-sync/repositories/IIntegrationAttributeSyncRepository";
import IntegrationAttributeSyncCard from "./IntegrationAttributeSyncCard";
import type { IIntegrationAttributeSyncCardProps } from "./IntegrationAttributeSyncCard";
type INewIntegrationAttributeSyncCardProps = Pick<
IIntegrationAttributeSyncCardProps,
"credentialOptions" | "teamOptions" | "attributes" | "organizationId" | "onCancel" | "attributeOptions"
>;
const NewIntegrationAttributeSyncCard = (props: INewIntegrationAttributeSyncCardProps) => {
const { t } = useLocale();
const utils = trpc.useUtils();
const createMutation = trpc.viewer.attributeSync.createAttributeSync.useMutation({
onSuccess: () => {
utils.viewer.attributeSync.getAllAttributeSyncs.invalidate();
showToast(t("attribute_sync_created_successfully"), "success");
props.onCancel?.();
},
onError: (error) => {
showToast(error.message, "error");
},
});
const onSubmit = (data: ISyncFormData) => {
if (!data.credentialId) {
showToast(t("attribute_sync_credential_required"), "error");
return;
}
createMutation.mutate({
name: data.name,
credentialId: data.credentialId,
rule: data.rule,
syncFieldMappings: data.syncFieldMappings,
enabled: data.enabled,
});
};
return (
<IntegrationAttributeSyncCard {...props} onSubmit={onSubmit} isSubmitting={createMutation.isPending} />
);
};
export default NewIntegrationAttributeSyncCard;
@@ -0,0 +1,495 @@
import type { MultiValue, SingleValue } from "react-select";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { Attribute } from "@calcom/app-store/routing-forms/types/types";
import { Button } from "@calcom/ui/components/button";
import { Input, Select } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import {
formatConditionValue,
generateConditionId,
getConditionTypeOptions,
getDefaultAttributeCondition,
getDefaultTeamCondition,
getOperatorOptionsForAttributeType,
getParentOperatorOptions,
getTeamOperatorOptions,
isArrayOperator,
isTeamCondition,
type TAttributeSyncRuleConditionWithId,
} from "@calcom/features/ee/integration-attribute-sync/lib/ruleHelpers";
import {
ConditionIdentifierEnum,
type ConditionOperatorEnum,
type IAttributeCondition,
type IAttributeSyncRule,
type ITeamCondition,
type RuleOperatorEnum,
type TAttributeSyncRuleCondition,
} from "@calcom/features/ee/integration-attribute-sync/repositories/IIntegrationAttributeSyncRepository";
const ensureConditionHasId = (condition: TAttributeSyncRuleCondition): TAttributeSyncRuleConditionWithId => {
if ("_id" in condition && condition._id) {
return condition as TAttributeSyncRuleConditionWithId;
}
return { ...condition, _id: generateConditionId() } as TAttributeSyncRuleConditionWithId;
};
interface RuleBuilderProps {
value: IAttributeSyncRule;
onChange: (value: IAttributeSyncRule) => void;
teamOptions: { value: string; label: string }[];
attributes: Attribute[];
isLoadingTeams?: boolean;
isLoadingAttributes?: boolean;
}
interface ConditionComponentProps {
condition: TAttributeSyncRuleCondition;
onChange: (condition: TAttributeSyncRuleCondition) => void;
onRemove: () => void;
teamOptions: { value: string; label: string }[];
attributes: Attribute[];
isLoading?: boolean;
}
const ConditionComponent = ({
condition,
onChange,
onRemove,
teamOptions,
attributes,
isLoading,
}: ConditionComponentProps) => {
const { t } = useLocale();
const conditionTypeOptions = getConditionTypeOptions(t);
const conditionTypeOption = conditionTypeOptions.find((opt: { value: ConditionIdentifierEnum; label: string }) => opt.value === condition.identifier);
const handleTypeChange = (newType: { value: ConditionIdentifierEnum; label: string } | null) => {
if (!newType) return;
if (newType.value === ConditionIdentifierEnum.TEAM_ID) {
onChange(getDefaultTeamCondition());
} else {
onChange(getDefaultAttributeCondition());
}
};
return (
<div className="bg-default border-subtle flex flex-wrap items-center gap-2 rounded-lg border p-3">
{/* Condition type selector */}
<Select
size="sm"
className="w-32"
value={conditionTypeOption}
onChange={handleTypeChange}
options={conditionTypeOptions}
isDisabled={isLoading}
/>
{/* Render team or attribute specific fields */}
{isTeamCondition(condition) ? (
<TeamConditionFields
condition={condition}
onChange={onChange}
teamOptions={teamOptions}
isLoading={isLoading}
/>
) : (
<AttributeConditionFields
condition={condition}
onChange={onChange}
attributes={attributes}
isLoading={isLoading}
/>
)}
<Button
color="minimal"
size="sm"
StartIcon="trash-2"
onClick={onRemove}
disabled={isLoading}
className="text-subtle hover:text-default"
/>
</div>
);
};
interface TeamConditionFieldsProps {
condition: ITeamCondition;
onChange: (condition: TAttributeSyncRuleCondition) => void;
teamOptions: { value: string; label: string }[];
isLoading?: boolean;
}
const TeamConditionFields = ({ condition, onChange, teamOptions, isLoading }: TeamConditionFieldsProps) => {
const { t } = useLocale();
const teamOperatorOptions = getTeamOperatorOptions(t);
const operatorOption = teamOperatorOptions.find((opt: { value: ConditionOperatorEnum; label: string }) => opt.value === condition.operator);
const isMulti = isArrayOperator(condition.operator);
const selectedTeams = isMulti
? teamOptions.filter((opt) => condition.value.includes(Number(opt.value)))
: teamOptions.find((opt) => Number(opt.value) === condition.value[0]);
const handleOperatorChange = (newOperator: { value: ConditionOperatorEnum; label: string } | null) => {
if (!newOperator) return;
const formattedValue = formatConditionValue(newOperator.value, condition.value) as number[];
onChange({
...condition,
operator: newOperator.value,
value: formattedValue,
});
};
const handleTeamsChange = (
selected: MultiValue<{ value: string; label: string }> | SingleValue<{ value: string; label: string }>
) => {
if (!selected) {
onChange({ ...condition, value: [] });
return;
}
if (Array.isArray(selected)) {
onChange({
...condition,
value: selected.map((s) => Number(s.value)),
});
} else {
const singleValue = selected as { value: string; label: string };
onChange({
...condition,
value: [Number(singleValue.value)],
});
}
};
return (
<>
<span className="text-default text-sm">{t("team").toLowerCase()}</span>
<Select
size="sm"
className="w-40"
value={operatorOption}
onChange={handleOperatorChange}
options={teamOperatorOptions}
isDisabled={isLoading}
/>
<div className="flex-1" style={{ minWidth: "200px" }}>
<Select
size="sm"
isMulti={isMulti}
value={selectedTeams}
onChange={handleTeamsChange}
options={teamOptions}
isLoading={isLoading}
isDisabled={isLoading}
placeholder={t("attribute_sync_select_teams")}
className="w-full"
/>
</div>
</>
);
};
interface AttributeConditionFieldsProps {
condition: IAttributeCondition;
onChange: (condition: TAttributeSyncRuleCondition) => void;
attributes: Attribute[];
isLoading?: boolean;
}
const AttributeConditionFields = ({
condition,
onChange,
attributes,
isLoading,
}: AttributeConditionFieldsProps) => {
const { t } = useLocale();
const selectedAttribute = attributes.find((attr) => attr.id === condition.attributeId);
const attributeOptions = attributes.map((attr) => ({
value: attr.id,
label: attr.name,
}));
const operatorOptions = selectedAttribute
? getOperatorOptionsForAttributeType(selectedAttribute.type, t)
: [];
const operatorOption = operatorOptions.find((opt: { value: ConditionOperatorEnum; label: string }) => opt.value === condition.operator);
const handleAttributeChange = (selected: { value: string; label: string } | null) => {
if (!selected) return;
const newAttribute = attributes.find((attr) => attr.id === selected.value);
if (!newAttribute) return;
// Reset operator and value when attribute changes
const defaultOperator = getOperatorOptionsForAttributeType(newAttribute.type, t)[0];
onChange({
...condition,
attributeId: selected.value,
operator: defaultOperator.value,
value: [],
});
};
const handleOperatorChange = (newOperator: { value: ConditionOperatorEnum; label: string } | null) => {
if (!newOperator) return;
const formattedValue = formatConditionValue(newOperator.value, condition.value) as string[];
onChange({
...condition,
operator: newOperator.value,
value: formattedValue,
});
};
const handleValueChange = (
selected: MultiValue<{ value: string; label: string }> | SingleValue<{ value: string; label: string }>
) => {
if (!selected) {
onChange({ ...condition, value: [] });
return;
}
if (Array.isArray(selected)) {
onChange({
...condition,
value: selected.map((s) => s.value),
});
} else {
const singleValue = selected as { value: string; label: string };
onChange({
...condition,
value: [singleValue.value],
});
}
};
const handleTextValueChange = (e: React.ChangeEvent<HTMLInputElement>) => {
onChange({
...condition,
value: [e.target.value],
});
};
const handleNumberValueChange = (e: React.ChangeEvent<HTMLInputElement>) => {
onChange({
...condition,
value: [e.target.value],
});
};
// Render value input based on attribute type
const renderValueInput = () => {
if (!selectedAttribute) {
return (
<div className="text-subtle flex-1 text-sm" style={{ minWidth: "200px" }}>
{t("attribute_sync_select_attribute_first")}
</div>
);
}
const isMulti = isArrayOperator(condition.operator);
switch (selectedAttribute.type) {
case "SINGLE_SELECT":
case "MULTI_SELECT": {
const valueOptions = selectedAttribute.options.map((opt: { id: string; value: string }) => ({
value: opt.id,
label: opt.value,
}));
const selectedValues = isMulti
? valueOptions.filter((opt: { value: string; label: string }) => condition.value.includes(opt.value))
: valueOptions.find((opt: { value: string; label: string }) => condition.value[0] === opt.value);
return (
<div className="flex-1" style={{ minWidth: "200px" }}>
<Select
size="sm"
isMulti={isMulti}
value={selectedValues}
onChange={handleValueChange}
options={valueOptions}
isLoading={isLoading}
isDisabled={isLoading}
placeholder={t("attribute_sync_select_values")}
className="w-full"
/>
</div>
);
}
case "TEXT":
return (
<div className="flex-1" style={{ minWidth: "200px" }}>
<Input
type="text"
value={condition.value[0] || ""}
onChange={handleTextValueChange}
disabled={isLoading}
placeholder={t("attribute_sync_enter_text_value")}
className="h-7 text-sm"
/>
</div>
);
case "NUMBER":
return (
<div className="flex-1" style={{ minWidth: "200px" }}>
<Input
type="number"
value={condition.value[0] || ""}
onChange={handleNumberValueChange}
disabled={isLoading}
placeholder={t("attribute_sync_enter_number_value")}
className="h-7 text-sm"
/>
</div>
);
}
};
return (
<>
<span className="text-default text-sm">{t("attribute").toLowerCase()}</span>
<Select
size="sm"
className="w-48"
value={attributeOptions.find((opt) => opt.value === condition.attributeId)}
onChange={handleAttributeChange}
options={attributeOptions}
isLoading={isLoading}
isDisabled={isLoading}
placeholder={t("attribute_sync_select_attribute")}
/>
{selectedAttribute && (
<>
<Select
size="sm"
className="w-40"
value={operatorOption}
onChange={handleOperatorChange}
options={operatorOptions}
isDisabled={isLoading}
/>
{renderValueInput()}
</>
)}
</>
);
};
export const RuleBuilder = ({
value,
onChange,
teamOptions,
attributes,
isLoadingTeams,
isLoadingAttributes,
}: RuleBuilderProps) => {
const { t } = useLocale();
const parentOperatorOptions = getParentOperatorOptions(t);
const parentOperatorOption = parentOperatorOptions.find((opt: { value: RuleOperatorEnum; label: string }) => opt.value === value.operator);
const isLoading = isLoadingTeams || isLoadingAttributes;
const handleOperatorChange = (newOperator: { value: RuleOperatorEnum; label: string } | null) => {
if (!newOperator) return;
onChange({
...value,
operator: newOperator.value,
});
};
const handleAddCondition = () => {
onChange({
...value,
conditions: [...value.conditions, getDefaultTeamCondition()],
});
};
const handleConditionChange = (index: number, newCondition: TAttributeSyncRuleCondition) => {
const newConditions = [...value.conditions];
newConditions[index] = newCondition;
onChange({
...value,
conditions: newConditions,
});
};
const handleRemoveCondition = (index: number) => {
onChange({
...value,
conditions: value.conditions.filter((_: TAttributeSyncRuleCondition, i: number) => i !== index),
});
};
return (
<div className="bg-default border-subtle rounded-2xl border p-2">
<div className="ml-2 flex items-center gap-0.5">
<div className="border-subtle rounded-lg border p-1">
<Icon name="filter" className="text-subtle h-4 w-4" />
</div>
<span className="text-emphasis ml-2 text-sm font-medium">{t("attribute_sync_user_filter_rules")}</span>
</div>
<div className="mt-2 flex flex-wrap items-center gap-2 px-2">
<span className="text-default text-sm">{t("attribute_sync_sync_users_where")}</span>
<Select
size="sm"
className="w-28"
value={parentOperatorOption}
onChange={handleOperatorChange}
options={parentOperatorOptions}
isDisabled={isLoading}
/>
<span className="text-default text-sm">{t("attribute_sync_conditions_match")}</span>
</div>
<div className="bg-muted mt-2 space-y-2 rounded-xl p-2">
{value.conditions.length === 0 ? (
<div className="text-subtle py-6 text-center text-sm">
{t("attribute_sync_no_conditions")}
</div>
) : (
value.conditions.map((condition: TAttributeSyncRuleCondition, index: number) => {
const conditionWithId = ensureConditionHasId(condition);
return (
<ConditionComponent
key={conditionWithId._id}
condition={conditionWithId}
onChange={(newCondition) => handleConditionChange(index, newCondition)}
onRemove={() => handleRemoveCondition(index)}
teamOptions={teamOptions}
attributes={attributes}
isLoading={isLoading}
/>
);
})
)}
</div>
<Button
color="minimal"
size="sm"
StartIcon="plus"
className="mt-2"
onClick={handleAddCondition}
disabled={isLoading}>
{t("attribute_sync_add_condition")}
</Button>
</div>
);
};