The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
import { isNumber } from '@sniptt/guards';
import {
AggregateOperations,
ObjectRecordGroupByDateGranularity,
PageLayoutTabLayoutMode,
ViewFilterOperand,
WidgetType,
} from 'twenty-shared/types';
import { z } from 'zod';
import { AxisNameDisplay } from 'src/engine/metadata-modules/page-layout-widget/enums/axis-name-display.enum';
import { BarChartGroupMode } from 'src/engine/metadata-modules/page-layout-widget/enums/bar-chart-group-mode.enum';
import { BarChartLayout } from 'src/engine/metadata-modules/page-layout-widget/enums/bar-chart-layout.enum';
import { ChartNumberFormat } from 'src/engine/metadata-modules/page-layout-widget/enums/chart-number-format.enum';
import { GraphOrderBy } from 'src/engine/metadata-modules/page-layout-widget/enums/graph-order-by.enum';
import { WidgetConfigurationType } from 'src/engine/metadata-modules/page-layout-widget/enums/widget-configuration-type.type';
// Chart color options (MAIN_COLOR_NAMES plus 'auto').
// should we export MAIN_COLOR_NAMES from twenty-ui to twenty-shared and use that here?
const CHART_COLORS = [
'auto',
'red',
'ruby',
'crimson',
'tomato',
'orange',
'amber',
'yellow',
'lime',
'grass',
'green',
'jade',
'mint',
'turquoise',
'cyan',
'sky',
'blue',
'iris',
'violet',
'purple',
'plum',
'pink',
'bronze',
'gold',
'brown',
'gray',
] as const;
const DATE_GRANULARITY_OPTIONS = [
ObjectRecordGroupByDateGranularity.DAY,
ObjectRecordGroupByDateGranularity.WEEK,
ObjectRecordGroupByDateGranularity.MONTH,
ObjectRecordGroupByDateGranularity.QUARTER,
ObjectRecordGroupByDateGranularity.YEAR,
ObjectRecordGroupByDateGranularity.DAY_OF_THE_WEEK,
ObjectRecordGroupByDateGranularity.MONTH_OF_THE_YEAR,
ObjectRecordGroupByDateGranularity.QUARTER_OF_THE_YEAR,
] as const;
const GRAPH_ORDER_BY_OPTIONS = Object.values(GraphOrderBy) as [
GraphOrderBy,
...GraphOrderBy[],
];
const AXIS_NAME_DISPLAY_OPTIONS = Object.values(AxisNameDisplay) as [
AxisNameDisplay,
...AxisNameDisplay[],
];
const CHART_NUMBER_FORMAT_OPTIONS = Object.values(ChartNumberFormat) as [
ChartNumberFormat,
...ChartNumberFormat[],
];
const BAR_CHART_GROUP_MODE_OPTIONS = Object.values(BarChartGroupMode) as [
BarChartGroupMode,
...BarChartGroupMode[],
];
const BAR_CHART_LAYOUT_OPTIONS = Object.values(BarChartLayout) as [
BarChartLayout,
...BarChartLayout[],
];
const AGGREGATE_OPERATION_OPTIONS = Object.values(AggregateOperations) as [
AggregateOperations,
...AggregateOperations[],
];
const FILTER_OPERAND_OPTIONS = Object.values(ViewFilterOperand) as [
ViewFilterOperand,
...ViewFilterOperand[],
];
const chartRecordFilterSchema = z.object({
fieldMetadataId: z
.uuid()
.optional()
.describe(
'Field UUID to filter on (must belong to the widget object). Provide this or fieldName.',
),
fieldName: z
.string()
.optional()
.describe(
'Field name to filter on (resolved to a UUID against the widget object). Alternative to fieldMetadataId.',
),
operand: z
.enum(FILTER_OPERAND_OPTIONS)
.describe(
'Filter operator. Valid operators per field type — TEXT: CONTAINS, DOES_NOT_CONTAIN, IS, IS_NOT, IS_EMPTY, IS_NOT_EMPTY. EMAILS/FULL_NAME/ARRAY/PHONES: CONTAINS, DOES_NOT_CONTAIN, IS_EMPTY, IS_NOT_EMPTY. NUMBER/CURRENCY/RATING: GREATER_THAN_OR_EQUAL, LESS_THAN_OR_EQUAL, IS, IS_NOT, IS_EMPTY, IS_NOT_EMPTY. DATE/DATE_TIME: IS, IS_RELATIVE, IS_IN_PAST, IS_IN_FUTURE, IS_TODAY, IS_BEFORE, IS_AFTER, IS_EMPTY, IS_NOT_EMPTY. SELECT: IS, IS_NOT, IS_EMPTY, IS_NOT_EMPTY. MULTI_SELECT: CONTAINS, DOES_NOT_CONTAIN, IS_EMPTY, IS_NOT_EMPTY. RELATION: IS, IS_NOT, IS_EMPTY, IS_NOT_EMPTY. BOOLEAN: IS.',
),
value: z
.string()
.optional()
.describe(
'Filter value as a string. TEXT: plain string. NUMBER/CURRENCY: numeric string (CURRENCY value is the major unit, e.g. "1000"). BOOLEAN: "true" or "false". SELECT/MULTI_SELECT/RELATION: JSON array string of option values or record UUIDs, e.g. \'["OPTION_1","OPTION_2"]\'. Relative dates (operand IS_RELATIVE): "DIRECTION_AMOUNT_UNIT" where DIRECTION is PAST|THIS|NEXT and UNIT is DAY|WEEK|MONTH|QUARTER|YEAR — e.g. "PAST_7_DAY", "THIS_1_MONTH", "NEXT_3_WEEK" (use THIS_1_<UNIT> for the current period). Absolute dates (IS/IS_BEFORE/IS_AFTER): ISO date string. Omit for IS_EMPTY/IS_NOT_EMPTY/IS_TODAY/IS_IN_PAST/IS_IN_FUTURE.',
),
subFieldName: z
.string()
.optional()
.describe(
'Required for composite fields — e.g. "amountMicros" or "currencyCode" for CURRENCY, "addressCity" for ADDRESS, "firstName"/"lastName" for FULL_NAME.',
),
recordFilterGroupId: z
.string()
.optional()
.describe(
'ID of the record filter group this rule belongs to (for AND/OR grouping). Must match an id in recordFilterGroups. Omit when recordFilterGroups is not used.',
),
});
const chartRecordFilterGroupSchema = z.object({
id: z
.string()
.describe(
'Unique id for this filter group, referenced by recordFilterGroupId on filter rules.',
),
logicalOperator: z
.enum(['AND', 'OR'])
.describe('How rules within this group are combined.'),
parentRecordFilterGroupId: z
.string()
.optional()
.describe('Parent group id, for nested grouping.'),
});
export const chartFilterSchema = z
.object({
recordFilters: z
.array(chartRecordFilterSchema)
.optional()
.describe(
'Filter rules applied to the records feeding this chart. Multiple rules with no recordFilterGroups are combined with AND.',
),
recordFilterGroups: z
.array(chartRecordFilterGroupSchema)
.optional()
.describe(
'Optional groups to combine filter rules with AND/OR logic. Omit for a simple list of ANDed rules.',
),
})
.describe(
'Filter restricting which records are included in this chart. All filtered fields must belong to the widget object.',
)
.meta({ id: 'chartFilter' });
const displayDataLabelSchema = z.boolean().optional();
const displayLegendSchema = z.boolean().optional();
const chartNumberFormatSchema = z
.enum(CHART_NUMBER_FORMAT_OPTIONS)
.optional()
.describe(
'Display format for data label values: SHORT abbreviates large numbers (1.3m), FULL shows the complete number (1,300,090). Tooltips always show the full value.',
);
const showCenterMetricSchema = z
.boolean()
.optional()
.describe('Show aggregate value in center');
const hideEmptyCategorySchema = z
.boolean()
.optional()
.describe('Hide slices with zero values');
type PrimarySecondaryManualSortFields = {
primaryAxisOrderBy?: GraphOrderBy;
primaryAxisManualSortOrder?: string[];
secondaryAxisOrderBy?: GraphOrderBy;
secondaryAxisManualSortOrder?: string[];
};
type ManualSortFields = {
orderBy?: GraphOrderBy;
manualSortOrder?: string[];
};
type RangeMinMaxFields = {
rangeMin?: number;
rangeMax?: number;
};
const ratioAggregateConfigSchema = z.object({
fieldMetadataId: z
.uuid()
.optional()
.describe('Field UUID. Provide this or fieldName.'),
fieldName: z
.string()
.optional()
.describe(
'Field name (resolved to a UUID). Alternative to fieldMetadataId.',
),
optionValue: z.string(),
});
const withPrimarySecondaryManualSortRefinements = <
T extends z.ZodType<PrimarySecondaryManualSortFields>,
>(
schema: T,
) =>
schema
.refine(
(data) =>
data.primaryAxisOrderBy !== GraphOrderBy.MANUAL ||
(Array.isArray(data.primaryAxisManualSortOrder) &&
data.primaryAxisManualSortOrder.length > 0),
{
message:
'primaryAxisManualSortOrder must be a non-empty array when primaryAxisOrderBy is MANUAL',
path: ['primaryAxisManualSortOrder'],
},
)
.refine(
(data) =>
data.secondaryAxisOrderBy !== GraphOrderBy.MANUAL ||
(Array.isArray(data.secondaryAxisManualSortOrder) &&
data.secondaryAxisManualSortOrder.length > 0),
{
message:
'secondaryAxisManualSortOrder must be a non-empty array when secondaryAxisOrderBy is MANUAL',
path: ['secondaryAxisManualSortOrder'],
},
);
const withManualSortRefinement = <T extends z.ZodType<ManualSortFields>>(
schema: T,
) =>
schema.refine(
(data) =>
data.orderBy !== GraphOrderBy.MANUAL ||
(Array.isArray(data.manualSortOrder) && data.manualSortOrder.length > 0),
{
message:
'manualSortOrder must be a non-empty array when orderBy is MANUAL',
path: ['manualSortOrder'],
},
);
const withRangeMinMaxRefinement = <T extends z.ZodType<RangeMinMaxFields>>(
schema: T,
) =>
schema.refine(
(data) =>
!(
isNumber(data.rangeMin) &&
isNumber(data.rangeMax) &&
data.rangeMin > data.rangeMax
),
{
message: 'rangeMin must be less than or equal to rangeMax',
path: ['rangeMin'],
},
);
export const widgetPositionSchema = z.object({
layoutMode: z.literal(PageLayoutTabLayoutMode.GRID),
row: z.number().min(0).describe('Row position (0-based)'),
column: z
.number()
.min(0)
.max(11)
.describe('Column position (0-11 for 12-column grid)'),
rowSpan: z.number().min(1).describe('Number of rows the widget spans'),
columnSpan: z
.number()
.min(1)
.max(12)
.describe('Number of columns the widget spans (1-12)'),
});
export const widgetTypeSchema = z.enum([
WidgetType.VIEW,
WidgetType.GRAPH,
WidgetType.IFRAME,
WidgetType.STANDALONE_RICH_TEXT,
WidgetType.RECORD_TABLE,
]);
const aggregateChartConfigSchemaBase = z.object({
configurationType: z.literal(WidgetConfigurationType.AGGREGATE_CHART),
aggregateFieldMetadataId: z
.uuid()
.optional()
.describe(
'Field UUID to aggregate (must be from the widget object). Provide this or aggregateFieldName.',
),
aggregateFieldName: z
.string()
.optional()
.describe(
'Field name to aggregate (resolved to a UUID against the widget object). Alternative to aggregateFieldMetadataId.',
),
aggregateOperation: z
.enum(AGGREGATE_OPERATION_OPTIONS)
.describe('Aggregation operation: COUNT, SUM, AVG, MIN, MAX, etc.'),
label: z.string().optional(),
displayDataLabel: displayDataLabelSchema,
numberFormat: z
.enum(CHART_NUMBER_FORMAT_OPTIONS)
.optional()
.describe(
'Display format for the value: SHORT abbreviates large numbers (1.3m), FULL shows the complete number (1,300,090)',
),
prefix: z.string().optional(),
suffix: z.string().optional(),
ratioAggregateConfig: ratioAggregateConfigSchema.optional(),
filter: chartFilterSchema.optional(),
});
const aggregateChartConfigSchema = aggregateChartConfigSchemaBase.extend({
displayDataLabel: displayDataLabelSchema.default(true),
});
const aggregateChartConfigSchemaWithoutDefaults =
aggregateChartConfigSchemaBase;
const barChartConfigSchemaCore = z.object({
configurationType: z.literal(WidgetConfigurationType.BAR_CHART),
aggregateFieldMetadataId: z
.uuid()
.optional()
.describe('Field UUID to aggregate. Provide this or aggregateFieldName.'),
aggregateFieldName: z
.string()
.optional()
.describe(
'Field name to aggregate (resolved to a UUID). Alternative to aggregateFieldMetadataId.',
),
aggregateOperation: z.enum(AGGREGATE_OPERATION_OPTIONS),
primaryAxisGroupByFieldMetadataId: z
.uuid()
.optional()
.describe(
'Field UUID to group by on primary axis. Provide this or primaryAxisGroupByFieldName.',
),
primaryAxisGroupByFieldName: z
.string()
.optional()
.describe(
'Field name to group by on primary axis (resolved to a UUID). Alternative to primaryAxisGroupByFieldMetadataId.',
),
primaryAxisGroupBySubFieldName: z
.string()
.optional()
.describe(
'Optional for relation fields: omit it to group by the related record itself, labelled with its display name; provide it (e.g. "name", "address.addressCity") to group by that attribute instead. REQUIRED for composite fields (e.g. "addressCity").',
),
secondaryAxisGroupByFieldMetadataId: z.uuid().optional(),
secondaryAxisGroupByFieldName: z
.string()
.optional()
.describe(
'Field name to group by on secondary axis (resolved to a UUID). Alternative to secondaryAxisGroupByFieldMetadataId.',
),
secondaryAxisGroupBySubFieldName: z
.string()
.optional()
.describe(
'Optional for relation fields: omit it to group by the related record itself, labelled with its display name; provide it (e.g. "name", "stage") to group by that attribute instead. REQUIRED for composite fields (e.g. "addressCity").',
),
primaryAxisOrderBy: z.enum(GRAPH_ORDER_BY_OPTIONS).optional(),
primaryAxisManualSortOrder: z.array(z.string()).optional(),
secondaryAxisOrderBy: z.enum(GRAPH_ORDER_BY_OPTIONS).optional(),
secondaryAxisManualSortOrder: z.array(z.string()).optional(),
omitNullValues: z.boolean().optional(),
primaryAxisDateGranularity: z
.enum(DATE_GRANULARITY_OPTIONS)
.optional()
.describe('Date grouping granularity for X axis'),
secondaryAxisGroupByDateGranularity: z
.enum(DATE_GRANULARITY_OPTIONS)
.optional()
.describe('Date grouping granularity for secondary grouping'),
color: z.enum(CHART_COLORS).optional().describe('Chart color theme'),
axisNameDisplay: z
.enum(AXIS_NAME_DISPLAY_OPTIONS)
.optional()
.describe('Which axis labels to show'),
displayDataLabel: displayDataLabelSchema,
displayLegend: displayLegendSchema,
numberFormat: chartNumberFormatSchema,
groupMode: z
.enum(BAR_CHART_GROUP_MODE_OPTIONS)
.optional()
.describe('Bar display mode when using secondary grouping'),
isCumulative: z.boolean().optional().describe('Show running totals'),
rangeMin: z.number().optional().describe('Y axis minimum value'),
rangeMax: z.number().optional().describe('Y axis maximum value'),
layout: z
.enum(BAR_CHART_LAYOUT_OPTIONS)
.describe('Layout orientation for bar charts'),
filter: chartFilterSchema.optional(),
});
const barChartConfigSchemaWithoutDefaults = withRangeMinMaxRefinement(
withPrimarySecondaryManualSortRefinements(barChartConfigSchemaCore),
);
const barChartConfigSchema = withRangeMinMaxRefinement(
withPrimarySecondaryManualSortRefinements(
barChartConfigSchemaCore.extend({
displayDataLabel: displayDataLabelSchema.default(false),
displayLegend: displayLegendSchema.default(true),
}),
),
);
const lineChartConfigSchemaCore = z.object({
configurationType: z.literal(WidgetConfigurationType.LINE_CHART),
aggregateFieldMetadataId: z
.uuid()
.optional()
.describe('Field UUID to aggregate. Provide this or aggregateFieldName.'),
aggregateFieldName: z
.string()
.optional()
.describe(
'Field name to aggregate (resolved to a UUID). Alternative to aggregateFieldMetadataId.',
),
aggregateOperation: z.enum(AGGREGATE_OPERATION_OPTIONS),
primaryAxisGroupByFieldMetadataId: z
.uuid()
.optional()
.describe(
'Field UUID to group by on primary axis. Provide this or primaryAxisGroupByFieldName.',
),
primaryAxisGroupByFieldName: z
.string()
.optional()
.describe(
'Field name to group by on primary axis (resolved to a UUID). Alternative to primaryAxisGroupByFieldMetadataId.',
),
primaryAxisGroupBySubFieldName: z
.string()
.optional()
.describe(
'Optional for relation fields: omit it to group by the related record itself, labelled with its display name; provide it (e.g. "name", "address.addressCity") to group by that attribute instead. REQUIRED for composite fields (e.g. "addressCity").',
),
secondaryAxisGroupByFieldMetadataId: z.uuid().optional(),
secondaryAxisGroupByFieldName: z
.string()
.optional()
.describe(
'Field name to group by on secondary axis (resolved to a UUID). Alternative to secondaryAxisGroupByFieldMetadataId.',
),
secondaryAxisGroupBySubFieldName: z
.string()
.optional()
.describe(
'Optional for relation fields: omit it to group by the related record itself, labelled with its display name; provide it (e.g. "name", "stage") to group by that attribute instead. REQUIRED for composite fields (e.g. "addressCity").',
),
primaryAxisOrderBy: z.enum(GRAPH_ORDER_BY_OPTIONS).optional(),
primaryAxisManualSortOrder: z.array(z.string()).optional(),
secondaryAxisOrderBy: z.enum(GRAPH_ORDER_BY_OPTIONS).optional(),
secondaryAxisManualSortOrder: z.array(z.string()).optional(),
omitNullValues: z.boolean().optional(),
primaryAxisDateGranularity: z
.enum(DATE_GRANULARITY_OPTIONS)
.optional()
.describe('Date grouping granularity for X axis'),
secondaryAxisGroupByDateGranularity: z
.enum(DATE_GRANULARITY_OPTIONS)
.optional()
.describe('Date grouping granularity for secondary grouping'),
color: z.enum(CHART_COLORS).optional().describe('Line color theme'),
axisNameDisplay: z
.enum(AXIS_NAME_DISPLAY_OPTIONS)
.optional()
.describe('Which axis labels to show'),
displayDataLabel: displayDataLabelSchema,
displayLegend: displayLegendSchema,
numberFormat: chartNumberFormatSchema,
isStacked: z.boolean().optional().describe('Stack multiple lines'),
isCumulative: z.boolean().optional().describe('Show running totals'),
rangeMin: z.number().optional().describe('Y axis minimum value'),
rangeMax: z.number().optional().describe('Y axis maximum value'),
filter: chartFilterSchema.optional(),
});
const lineChartConfigSchemaWithoutDefaults = withRangeMinMaxRefinement(
withPrimarySecondaryManualSortRefinements(lineChartConfigSchemaCore),
);
const lineChartConfigSchema = withRangeMinMaxRefinement(
withPrimarySecondaryManualSortRefinements(
lineChartConfigSchemaCore.extend({
displayDataLabel: displayDataLabelSchema.default(false),
displayLegend: displayLegendSchema.default(true),
}),
),
);
const pieChartConfigSchemaCore = z.object({
configurationType: z.literal(WidgetConfigurationType.PIE_CHART),
aggregateFieldMetadataId: z
.uuid()
.optional()
.describe('Field UUID to aggregate. Provide this or aggregateFieldName.'),
aggregateFieldName: z
.string()
.optional()
.describe(
'Field name to aggregate (resolved to a UUID). Alternative to aggregateFieldMetadataId.',
),
aggregateOperation: z.enum(AGGREGATE_OPERATION_OPTIONS),
groupByFieldMetadataId: z
.uuid()
.optional()
.describe('Field UUID to slice by. Provide this or groupByFieldName.'),
groupByFieldName: z
.string()
.optional()
.describe(
'Field name to slice by (resolved to a UUID). Alternative to groupByFieldMetadataId.',
),
groupBySubFieldName: z
.string()
.optional()
.describe(
'Optional for relation fields: omit it to group by the related record itself, labelled with its display name; provide it (e.g. "name", "stage") to group by that attribute instead. REQUIRED for composite fields (e.g. "addressCity").',
),
orderBy: z.enum(GRAPH_ORDER_BY_OPTIONS).optional(),
manualSortOrder: z.array(z.string()).optional(),
dateGranularity: z
.enum(DATE_GRANULARITY_OPTIONS)
.optional()
.describe('Date grouping granularity when slicing by date'),
color: z.enum(CHART_COLORS).optional().describe('Chart color theme'),
displayDataLabel: displayDataLabelSchema,
displayLegend: displayLegendSchema,
numberFormat: chartNumberFormatSchema,
showCenterMetric: showCenterMetricSchema,
hideEmptyCategory: hideEmptyCategorySchema,
filter: chartFilterSchema.optional(),
});
const pieChartConfigSchemaWithoutDefaults = withManualSortRefinement(
pieChartConfigSchemaCore,
);
const pieChartConfigSchema = withManualSortRefinement(
pieChartConfigSchemaCore.extend({
displayDataLabel: displayDataLabelSchema.default(true),
displayLegend: displayLegendSchema.default(true),
showCenterMetric: showCenterMetricSchema.default(true),
hideEmptyCategory: hideEmptyCategorySchema.default(false),
}),
);
const recordTableConfigSchema = z.object({
configurationType: z.literal(WidgetConfigurationType.RECORD_TABLE),
viewId: z
.uuid()
.describe(
'UUID of the dedicated view created for this widget. Must be created with create_view before creating the widget. Never reuse a record index view.',
),
recordLimit: z
.number()
.int()
.min(1)
.optional()
.describe('Maximum number of records displayed in the table widget.'),
});
const iframeConfigSchema = z.object({
configurationType: z.literal(WidgetConfigurationType.IFRAME),
url: z.string().url().optional().describe('URL to embed'),
});
const richTextConfigSchema = z.object({
configurationType: z.literal(WidgetConfigurationType.STANDALONE_RICH_TEXT),
body: z
.object({
markdown: z
.string()
.nullable()
.optional()
.describe(
'Markdown content string (preferred for AI). Supports headings, bold, lists, links, etc.',
),
})
.describe(
'Rich text content. Use { "markdown": "your content here" } for text. Supports full markdown syntax.',
),
});
export const graphConfigurationSchema = z.discriminatedUnion(
'configurationType',
[
aggregateChartConfigSchema,
barChartConfigSchema,
lineChartConfigSchema,
pieChartConfigSchema,
],
);
export const graphConfigurationSchemaWithoutDefaults = z.discriminatedUnion(
'configurationType',
[
aggregateChartConfigSchemaWithoutDefaults,
barChartConfigSchemaWithoutDefaults,
lineChartConfigSchemaWithoutDefaults,
pieChartConfigSchemaWithoutDefaults,
],
);
export const widgetConfigurationSchema = z
.discriminatedUnion('configurationType', [
aggregateChartConfigSchema,
barChartConfigSchema,
lineChartConfigSchema,
pieChartConfigSchema,
iframeConfigSchema,
richTextConfigSchema,
recordTableConfigSchema,
])
.optional()
.describe('Widget configuration - structure depends on widget type');
export const widgetConfigurationSchemaWithoutDefaults = z
.discriminatedUnion('configurationType', [
aggregateChartConfigSchemaWithoutDefaults,
barChartConfigSchemaWithoutDefaults,
lineChartConfigSchemaWithoutDefaults,
pieChartConfigSchemaWithoutDefaults,
iframeConfigSchema,
richTextConfigSchema,
recordTableConfigSchema,
])
.optional()
.describe('Widget configuration - structure depends on widget type');
export { AggregateOperations, WidgetConfigurationType };