chore: rename feature elements

rename automations > triggers
rename blueprints > automations

chore: add link to documentation
This commit is contained in:
Carlos Valente
2025-01-20 19:22:00 +01:00
committed by Carlos Valente
parent f4f266dbd4
commit efe5ac16f2
30 changed files with 1125 additions and 1155 deletions
@@ -1,136 +1,457 @@
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { Button, Input, Select } from '@chakra-ui/react';
import { AutomationDTO, NormalisedAutomationBlueprint, TimerLifeCycle } from 'ontime-types';
import { useEffect, useMemo } from 'react';
import { Controller, useFieldArray, useForm } from 'react-hook-form';
import {
Alert,
AlertDescription,
AlertIcon,
Button,
IconButton,
Input,
Radio,
RadioGroup,
Select,
} from '@chakra-ui/react';
import { IoAdd } from '@react-icons/all-files/io5/IoAdd';
import { IoTrash } from '@react-icons/all-files/io5/IoTrash';
import { Automation, AutomationDTO, HTTPOutput, isHTTPOutput, isOSCOutput, OSCOutput } from 'ontime-types';
import { addAutomation, editAutomation } from '../../../../common/api/automation';
import { addAutomation, editAutomation, testOutput } from '../../../../common/api/automation';
import { maybeAxiosError } from '../../../../common/api/utils';
import ExternalLink from '../../../../common/components/external-link/ExternalLink';
import Tag from '../../../../common/components/tag/Tag';
import useAutomationSettings from '../../../../common/hooks-query/useAutomationSettings';
import useCustomFields from '../../../../common/hooks-query/useCustomFields';
import { preventEscape } from '../../../../common/utils/keyEvent';
import { startsWithHttp } from '../../../../common/utils/regex';
import * as Panel from '../../panel-utils/PanelUtils';
import { cycles } from './automationUtils';
import { isAutomation, makeFieldList } from './automationUtils';
import style from './AutomationForm.module.scss';
const integrationsDocsUrl = 'https://docs.getontime.no/api/integrations/#using-variables-in-integrations';
interface AutomationFormProps {
blueprints: NormalisedAutomationBlueprint;
initialId?: string;
initialTitle?: string;
initialBlueprint?: string;
initialTrigger?: TimerLifeCycle;
onCancel: () => void;
postSubmit: () => void;
automation: Automation | AutomationDTO;
onClose: () => void;
}
export default function AutomationForm(props: AutomationFormProps) {
const { blueprints, initialId, initialTitle, initialBlueprint, initialTrigger, onCancel, postSubmit } = props;
const { automation, onClose } = props;
const isEdit = isAutomation(automation);
const { data } = useCustomFields();
const { refetch } = useAutomationSettings();
const fieldList = useMemo(() => makeFieldList(data), [data]);
const {
control,
handleSubmit,
getValues,
register,
setFocus,
setError,
formState: { errors, isSubmitting, isValid, isDirty },
setFocus,
formState: { errors, isSubmitting, isDirty, isValid },
} = useForm<AutomationDTO>({
mode: 'onChange',
defaultValues: {
title: initialTitle,
trigger: initialTrigger,
blueprintId: initialBlueprint,
title: automation?.title ?? '',
filterRule: automation?.filterRule ?? 'all',
filters: automation?.filters ?? [],
outputs: automation?.outputs ?? [],
},
resetOptions: {
keepDirtyValues: true,
},
});
const {
fields: fieldFilters,
append: appendFilter,
remove: removeFilter,
} = useFieldArray({
name: 'filters',
control,
});
const {
fields: fieldOutputs,
append: appendOutput,
remove: removeOutput,
} = useFieldArray({
name: 'outputs',
control,
});
// give initial focus to the title field
useEffect(() => {
setFocus('title');
// eslint-disable-next-line react-hooks/exhaustive-deps -- focus on mount
}, []);
}, [setFocus]);
const onSubmit = async (values: AutomationDTO) => {
// if we were passed an ID we are editing a blueprint
if (initialId) {
try {
await editAutomation(initialId, { id: initialId, ...values });
postSubmit();
} catch (error) {
setError('root', { message: `Failed to save changes to automation ${maybeAxiosError(error)}` });
}
return;
}
const handleAddNewFilter = () => {
appendFilter({ field: '', operator: 'equals', value: '' });
};
// otherwise we are creating a new automation
const handleAddNewOSCOutput = () => {
// @ts-expect-error -- we dont want to pass a port to the new object
appendOutput({ type: 'osc', targetIP: '', targetPort: undefined, address: '', args: '' });
};
const handleAddNewHTTPOutput = () => {
appendOutput({ type: 'http', url: '' });
};
const handleTestOSCOutput = async (index: number) => {
try {
await addAutomation(values);
postSubmit();
} catch (error) {
setError('root', { message: `Failed to save automation ${maybeAxiosError(error)}` });
const values = getValues(`outputs.${index}`) as OSCOutput;
if (!values.targetIP || !values.targetPort || !values.address) {
return;
}
await testOutput({
type: 'osc',
targetIP: values.targetIP,
targetPort: values.targetPort,
address: values.address,
args: values.args,
});
} catch (_error) {
/** we dont handle errors here, users should use the network tab */
}
};
const blueprintSelect = Object.keys(blueprints).map((blueprint) => {
return {
value: blueprint,
label: blueprints[blueprint].title,
};
});
const handleTestHTTPOutput = async (index: number) => {
try {
const values = getValues(`outputs.${index}`) as HTTPOutput;
if (!values.url) {
return;
}
await testOutput({
type: 'http',
url: values.url,
});
} catch (_error) {
/** we dont handle errors here, users should use the network tab */
}
};
const canSubmit = isDirty && isValid;
const onSubmit = async (values: AutomationDTO) => {
if (isAutomation(automation)) {
await handleEdit(automation.id, { id: automation.id, ...values });
} else {
await handleCreate(values);
}
refetch();
async function handleEdit(id: string, values: Automation) {
try {
await editAutomation(id, values);
onClose();
} catch (error) {
setError('root', { message: maybeAxiosError(error) });
}
}
async function handleCreate(values: AutomationDTO) {
try {
await addAutomation(values);
onClose();
} catch (error) {
setError('root', { message: maybeAxiosError(error) });
}
}
};
const canSubmit = !isSubmitting && isDirty && isValid;
return (
<Panel.Indent
as='form'
name='automation-form'
onSubmit={handleSubmit(onSubmit)}
onKeyDown={(event) => preventEscape(event, onCancel)}
className={style.outerColumn}
onKeyDown={(event) => preventEscape(event, onClose)}
>
<Panel.SubHeader>{initialId ? 'Edit automation' : 'Create automation'}</Panel.SubHeader>
<label>
Title
<Input
{...register('title', { required: { value: true, message: 'Required field' } })}
size='sm'
variant='ontime-filled'
autoComplete='off'
defaultValue={initialTitle}
/>
<Panel.Error>{errors.title?.message}</Panel.Error>
</label>
<label>
Trigger
<Select
size='sm'
variant='ontime'
defaultValue={initialTrigger}
{...register('trigger', { required: { value: true, message: 'Required field' } })}
>
{cycles.map((cycle) => (
<option key={cycle.id} value={cycle.value}>
{cycle.label}
</option>
<Panel.SubHeader>{isEdit ? 'Edit automation' : 'Create automation'}</Panel.SubHeader>
<div className={style.innerSection}>
<h3>Automation options</h3>
<div className={style.titleSection}>
<label>
Title
<Input
{...register('title', { required: { value: true, message: 'Required field' } })}
variant='ontime-filled'
size='sm'
placeholder='Load preset'
autoComplete='off'
/>
</label>
<Panel.Error>{errors.title?.message}</Panel.Error>
</div>
</div>
<div className={style.innerSection}>
<h3>Filters</h3>
<div className={style.ruleSection}>
<label>
Trigger outputs if
<Controller
name='filterRule'
control={control}
render={({ field }) => (
<RadioGroup {...field} size='sm' className={style.matchRadio} variant='ontime'>
<Radio value='all'>All filters pass</Radio>
<Radio value='any'>Any filter passes</Radio>
</RadioGroup>
)}
/>
</label>
{fieldFilters.map((field, index) => (
<div key={field.id} className={style.filterSection}>
<label>
Runtime data source
<Select
{...register(`filters.${index}.field`, { required: { value: true, message: 'Required field' } })}
size='sm'
variant='ontime'
placeholder='Event field'
>
{fieldList.map(({ value, label }) => (
<option key={value} value={value}>
{label}
</option>
))}
</Select>
<Panel.Error>{errors.filters?.[index]?.field?.message}</Panel.Error>
</label>
<label>
Matching condition
<Select
{...register(`filters.${index}.operator`, { required: { value: true, message: 'Required field' } })}
size='sm'
variant='ontime'
placeholder='Operator'
>
<option value='equals'>equals</option>
<option value='not_equals'>not equals</option>
<option value='contains'>contains</option>
<option value='greater_than'>greater than</option>
<option value='less_than'>less than</option>
</Select>
<Panel.Error>{errors.filters?.[index]?.operator?.message}</Panel.Error>
</label>
<label>
Value to match
<Input
{...register(`filters.${index}.value`)}
variant='ontime-filled'
size='sm'
placeholder='<no value>'
autoComplete='off'
/>
</label>
<IconButton
aria-label='Delete'
icon={<IoTrash />}
variant='ontime-ghosted'
size='sm'
color='#FA5656' // $red-500
onClick={() => removeFilter(index)}
isDisabled={false}
isLoading={false}
/>
</div>
))}
</Select>
<Panel.Error>{errors.trigger?.message}</Panel.Error>
</label>
<label>
Blueprint title
<Select
size='sm'
variant='ontime'
defaultValue={initialBlueprint}
{...register('blueprintId', { required: { value: true, message: 'Required field' } })}
>
{blueprintSelect.map((blueprint) => (
<option key={blueprint.value} value={blueprint.value}>
{blueprint.label}
</option>
))}
</Select>
<Panel.Error>{errors.blueprintId?.message}</Panel.Error>
</label>
<div>
<Button
variant='ontime-subtle'
size='sm'
type='submit'
rightIcon={<IoAdd />}
onClick={handleAddNewFilter}
isDisabled={false}
isLoading={false}
>
Add filter
</Button>
</div>
</div>
</div>
<div className={style.innerColumn}>
<h3>Outputs</h3>
<Alert status='info' variant='ontime-on-dark-info'>
<AlertIcon />
<AlertDescription>
Automation outputs can be used to send data from Ontime to external software.
<ExternalLink href={integrationsDocsUrl}>See the documentation for templates</ExternalLink>
</AlertDescription>
</Alert>
{fieldOutputs.map((output, index) => {
if (isOSCOutput(output)) {
const rowErrors = errors.outputs?.[index] as
| {
targetIP?: { message?: string };
targetPort?: { message?: string };
address?: { message?: string };
args?: { message?: string };
}
| undefined;
return (
<div key={output.id} className={style.outputCard}>
<Tag>OSC</Tag>
<div className={style.oscSection}>
<label>
Target IP
<Input
{...register(`outputs.${index}.targetIP`, {
required: { value: true, message: 'Required field' },
})}
variant='ontime-filled'
size='sm'
placeholder='127.0.0.1'
autoComplete='off'
/>
<Panel.Error>{rowErrors?.targetIP?.message}</Panel.Error>
</label>
<label>
Target Port
<Input
{...register(`outputs.${index}.targetPort`, {
required: { value: true, message: 'Required field' },
setValueAs: (value) => (value === '' ? 0 : Number(value)),
max: { value: 65535, message: 'Port must be within range 1024 - 65535' },
min: { value: 1024, message: 'Port must be within range 1024 - 65535' },
})}
variant='ontime-filled'
size='sm'
type='number'
maxLength={5}
placeholder='8000'
autoComplete='off'
/>
<Panel.Error>{rowErrors?.targetPort?.message}</Panel.Error>
</label>
<label>
Address
<Input
{...register(`outputs.${index}.address`)}
variant='ontime-filled'
size='sm'
placeholder='/cue/start'
autoComplete='off'
/>
<Panel.Error>{rowErrors?.address?.message}</Panel.Error>
</label>
<label>
Parameters
<Input
{...register(`outputs.${index}.args`)}
variant='ontime-filled'
size='sm'
placeholder='1'
autoComplete='off'
/>
<Panel.Error>{rowErrors?.args?.message}</Panel.Error>
</label>
<Panel.InlineElements relation='inner'>
<Button size='sm' variant='ontime-ghosted' onClick={() => handleTestOSCOutput(index)}>
Test
</Button>
<IconButton
aria-label='Delete'
icon={<IoTrash />}
variant='ontime-ghosted'
size='sm'
onClick={() => removeOutput(index)}
color='#FA5656' // $red-500
isDisabled={false}
isLoading={false}
/>
</Panel.InlineElements>
</div>
</div>
);
}
if (isHTTPOutput(output)) {
const rowErrors = errors.outputs?.[index] as
| {
url?: { message?: string };
}
| undefined;
return (
<div key={output.id} className={style.outputCard}>
<Tag>HTTP</Tag>
<div className={style.httpSection}>
<label>
Target URL
<Input
{...register(`outputs.${index}.url`, {
required: { value: true, message: 'Required field' },
pattern: {
value: startsWithHttp,
message: 'HTTP messages should target http:// or https://',
},
})}
variant='ontime-filled'
size='sm'
placeholder='http://127.0.0.1/start/1'
autoComplete='off'
/>
<Panel.Error>{rowErrors?.url?.message}</Panel.Error>
</label>
<Panel.InlineElements relation='inner'>
<Button size='sm' variant='ontime-ghosted' onClick={() => handleTestHTTPOutput(index)}>
Test
</Button>
<IconButton
aria-label='Delete'
icon={<IoTrash />}
variant='ontime-ghosted'
size='sm'
onClick={() => removeOutput(index)}
color='#FA5656' // $red-500
isDisabled={false}
isLoading={false}
/>
</Panel.InlineElements>
</div>
</div>
);
}
// there should be no other output types
return null;
})}
<Panel.InlineElements relation='inner'>
<Button
variant='ontime-subtle'
rightIcon={<IoAdd />}
size='sm'
onClick={handleAddNewOSCOutput}
isDisabled={false}
isLoading={false}
>
OSC
</Button>
<Button
variant='ontime-subtle'
rightIcon={<IoAdd />}
size='sm'
onClick={handleAddNewHTTPOutput}
isDisabled={false}
isLoading={false}
>
HTTP
</Button>
</Panel.InlineElements>
</div>
<Panel.InlineElements align='end'>
<Button size='sm' variant='ontime-subtle' isDisabled={isSubmitting} onClick={onCancel}>
{errors?.root && <Panel.Error>{errors.root.message}</Panel.Error>}
<Button variant='ontime-subtle' size='sm' onClick={onClose}>
Cancel
</Button>
<Button type='submit' size='sm' variant='ontime-filled' isDisabled={!canSubmit} isLoading={isSubmitting}>
<Button variant='ontime-filled' size='sm' type='submit' isDisabled={!canSubmit} isLoading={isSubmitting}>
Save
</Button>
</Panel.InlineElements>
@@ -5,13 +5,13 @@ import * as Panel from '../../panel-utils/PanelUtils';
import AutomationSettingsForm from './AutomationSettingsForm';
import AutomationsList from './AutomationsList';
import BlueprintsList from './BlueprintsList';
import TriggersList from './TriggersList';
export default function AutomationPanel({ location }: PanelBaseProps) {
const { data, status } = useAutomationSettings();
const settingsRef = useScrollIntoView<HTMLDivElement>('settings', location);
const automationRef = useScrollIntoView<HTMLDivElement>('automations', location);
const blueprintsRef = useScrollIntoView<HTMLDivElement>('blueprints', location);
const triggersRef = useScrollIntoView<HTMLDivElement>('triggers', location);
const automationsRef = useScrollIntoView<HTMLDivElement>('automations', location);
const isLoading = status === 'pending';
@@ -27,11 +27,11 @@ export default function AutomationPanel({ location }: PanelBaseProps) {
oscPortIn={data.oscPortIn}
/>
</div>
<div ref={automationRef}>
<AutomationsList automations={data.automations} blueprints={data.blueprints} />
<div ref={triggersRef}>
<TriggersList triggers={data.triggers} automations={data.automations} />
</div>
<div ref={blueprintsRef}>
<BlueprintsList blueprints={data.blueprints} />
<div ref={automationsRef}>
<AutomationsList automations={data.automations} />
</div>
</Panel.Section>
</>
@@ -62,7 +62,7 @@ export default function AutomationSettingsForm(props: AutomationSettingsProps) {
variant='ontime-filled'
size='sm'
type='submit'
form='automation-form'
form='automation-settings-form'
isDisabled={!canSubmit}
isLoading={isSubmitting}
>
@@ -87,7 +87,7 @@ export default function AutomationSettingsForm(props: AutomationSettingsProps) {
<Panel.Section
as='form'
id='automation-form'
id='automation-settings-form'
onSubmit={handleSubmit(onSubmit)}
onKeyDown={(event) => preventEscape(event, onReset)}
>
@@ -1,30 +1,38 @@
import { Fragment, useMemo, useState } from 'react';
import { Button } from '@chakra-ui/react';
import { Fragment, useState } from 'react';
import { Button, IconButton } from '@chakra-ui/react';
import { IoAdd } from '@react-icons/all-files/io5/IoAdd';
import { Automation, NormalisedAutomationBlueprint } from 'ontime-types';
import { IoPencil } from '@react-icons/all-files/io5/IoPencil';
import { IoTrash } from '@react-icons/all-files/io5/IoTrash';
import { AutomationDTO, NormalisedAutomation } from 'ontime-types';
import { deleteAutomation } from '../../../../common/api/automation';
import { maybeAxiosError } from '../../../../common/api/utils';
import Tag from '../../../../common/components/tag/Tag';
import useAutomationSettings from '../../../../common/hooks-query/useAutomationSettings';
import * as Panel from '../../panel-utils/PanelUtils';
import AutomationForm from './AutomationForm';
import AutomationsListItem from './AutomationsListItem';
import { checkDuplicates } from './automationUtils';
const automationPlaceholder: AutomationDTO = {
title: '',
filterRule: 'all',
filters: [],
outputs: [],
};
interface AutomationsListProps {
automations: Automation[];
blueprints: NormalisedAutomationBlueprint;
automations: NormalisedAutomation;
}
export default function AutomationsList(props: AutomationsListProps) {
const { automations, blueprints } = props;
const [showForm, setShowForm] = useState(false);
const { automations } = props;
const { refetch } = useAutomationSettings();
const [automationFormData, setAutomationFormData] = useState<AutomationDTO | null>(null);
const [deleteError, setDeleteError] = useState<string | null>(null);
const handleDelete = async (id: string) => {
try {
setDeleteError(null);
await deleteAutomation(id);
} catch (error) {
setDeleteError(maybeAxiosError(error));
@@ -33,15 +41,7 @@ export default function AutomationsList(props: AutomationsListProps) {
}
};
const postSubmit = () => {
setShowForm(false);
refetch();
};
const duplicates = useMemo(() => checkDuplicates(automations), [automations]);
// there is no point letting user creating an automation if there are no blueprints
const canAdd = Object.keys(blueprints).length > 0;
const arrayAutomations = Object.keys(automations);
return (
<Panel.Card>
@@ -52,66 +52,77 @@ export default function AutomationsList(props: AutomationsListProps) {
rightIcon={<IoAdd />}
size='sm'
type='submit'
form='automation-form'
isDisabled={!canAdd}
isLoading={false}
onClick={() => setShowForm(true)}
isDisabled={Boolean(automationFormData)}
onClick={() => setAutomationFormData(automationPlaceholder)}
>
New
</Button>
</Panel.SubHeader>
<Panel.Divider />
<Panel.Section>
{duplicates && (
<Panel.Error>
You have created multiple links between the same trigger and blueprint which can performance issues.
</Panel.Error>
)}
{showForm && (
<AutomationForm blueprints={blueprints} onCancel={() => setShowForm(false)} postSubmit={postSubmit} />
)}
<Panel.Table>
<thead>
<tr>
<th style={{ width: '35%' }}>Title</th>
<th style={{ width: '20%' }}>Trigger</th>
<th style={{ width: '30%' }}>Blueprint</th>
<th />
</tr>
</thead>
<tbody>
{!showForm && automations.length === 0 && (
<Panel.TableEmpty
label='Create a blueprint before adding automations'
handleClick={canAdd ? () => setShowForm(true) : undefined}
/>
)}
{automations.map((automation, index) => {
return (
<Fragment key={automation.id}>
<AutomationsListItem
blueprints={blueprints}
id={automation.id}
title={automation.title}
trigger={automation.trigger}
blueprintId={automation.blueprintId}
duplicate={duplicates?.includes(index)}
handleDelete={() => handleDelete(automation.id)}
postSubmit={postSubmit}
/>
{deleteError && (
<tr>
<td colSpan={5}>
<Panel.Error>{deleteError}</Panel.Error>
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</Panel.Table>
</Panel.Section>
{automationFormData !== null && (
<AutomationForm automation={automationFormData} onClose={() => setAutomationFormData(null)} />
)}
<Panel.Table>
<thead>
<tr>
<th style={{ width: '45%' }}>Title</th>
<th style={{ width: '15%' }}>Trigger rule</th>
<th style={{ width: '15%' }}>Filters</th>
<th style={{ width: '15%' }}>Outputs</th>
<th />
</tr>
</thead>
<tbody>
{arrayAutomations.length === 0 && (
<Panel.TableEmpty handleClick={() => setAutomationFormData(automationPlaceholder)} />
)}
{arrayAutomations.map((automationId) => {
if (!Object.hasOwn(automations, automationId)) {
return null;
}
return (
<Fragment key={automationId}>
<tr>
<td>{automations[automationId].title}</td>
<td>
<Tag>{automations[automationId].filterRule}</Tag>
</td>
<td>{automations[automationId].filters.length}</td>
<td>{automations[automationId].outputs.length}</td>
<Panel.InlineElements align='end' relation='inner' as='td'>
<IconButton
size='sm'
variant='ontime-ghosted'
color='#e2e2e2' // $gray-200
icon={<IoPencil />}
aria-label='Edit entry'
onClick={() => setAutomationFormData(automations[automationId])}
/>
<IconButton
size='sm'
variant='ontime-ghosted'
color='#FA5656' // $red-500
icon={<IoTrash />}
aria-label='Delete entry'
onClick={() => handleDelete(automationId)}
/>
</Panel.InlineElements>
</tr>
{deleteError && (
<tr>
<td colSpan={5}>
<Panel.Error>{deleteError}</Panel.Error>
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</Panel.Table>
</Panel.Card>
);
}
@@ -1,483 +0,0 @@
import { useEffect, useMemo } from 'react';
import { Controller, useFieldArray, useForm } from 'react-hook-form';
import { Button, IconButton, Input, Radio, RadioGroup, Select } from '@chakra-ui/react';
import { IoAdd } from '@react-icons/all-files/io5/IoAdd';
import { IoTrash } from '@react-icons/all-files/io5/IoTrash';
import {
AutomationBlueprint,
AutomationBlueprintDTO,
CustomFields,
HTTPOutput,
isHTTPOutput,
isOSCOutput,
OntimeEvent,
OSCOutput,
} from 'ontime-types';
import { addBlueprint, editBlueprint, testOutput } from '../../../../common/api/automation';
import { maybeAxiosError } from '../../../../common/api/utils';
import Tag from '../../../../common/components/tag/Tag';
import useAutomationSettings from '../../../../common/hooks-query/useAutomationSettings';
import useCustomFields from '../../../../common/hooks-query/useCustomFields';
import { preventEscape } from '../../../../common/utils/keyEvent';
import { startsWithHttp } from '../../../../common/utils/regex';
import * as Panel from '../../panel-utils/PanelUtils';
import { isBlueprint, makeFieldList } from './automationUtils';
import style from './BlueprintForm.module.scss';
interface BlueprintFormProps {
blueprint: AutomationBlueprintDTO | AutomationBlueprint;
onClose: () => void;
}
export default function BlueprintForm(props: BlueprintFormProps) {
const { blueprint, onClose } = props;
const isEdit = isBlueprint(blueprint);
const { data } = useCustomFields();
const { refetch } = useAutomationSettings();
const fieldList = useMemo(() => makeFieldList(data), [data]);
const {
control,
handleSubmit,
getValues,
register,
setError,
setFocus,
formState: { errors, isSubmitting, isDirty, isValid },
} = useForm<AutomationBlueprintDTO>({
mode: 'onChange',
defaultValues: {
title: blueprint?.title ?? '',
filterRule: blueprint?.filterRule ?? 'all',
filters: blueprint?.filters ?? [],
outputs: blueprint?.outputs ?? [],
},
resetOptions: {
keepDirtyValues: true,
},
});
const {
fields: fieldFilters,
append: appendFilter,
remove: removeFilter,
} = useFieldArray({
name: 'filters',
control,
});
const {
fields: fieldOutputs,
append: appendOutput,
remove: removeOutput,
} = useFieldArray({
name: 'outputs',
control,
});
// give initial focus to the title field
useEffect(() => {
setFocus('title');
}, [setFocus]);
const handleAddNewFilter = () => {
appendFilter({ field: '', operator: 'equals', value: '' });
};
const handleAddNewOSCOutput = () => {
// @ts-expect-error -- we dont want to pass a port to the new object
appendOutput({ type: 'osc', targetIP: '', targetPort: undefined, address: '', args: '' });
};
const handleAddNewHTTPOutput = () => {
appendOutput({ type: 'http', url: '' });
};
const handleTestOSCOutput = async (index: number) => {
try {
const values = getValues(`outputs.${index}`) as OSCOutput;
if (!values.targetIP || !values.targetPort || !values.address) {
return;
}
await testOutput({
type: 'osc',
targetIP: values.targetIP,
targetPort: values.targetPort,
address: values.address,
args: values.args,
});
} catch (_error) {
/** we dont handle errors here, users should use the network tab */
}
};
const handleTestHTTPOutput = async (index: number) => {
try {
const values = getValues(`outputs.${index}`) as HTTPOutput;
if (!values.url) {
return;
}
await testOutput({
type: 'http',
url: values.url,
});
} catch (_error) {
/** we dont handle errors here, users should use the network tab */
}
};
const onSubmit = async (values: AutomationBlueprintDTO) => {
if (isBlueprint(blueprint)) {
await handleEdit(blueprint.id, { id: blueprint.id, ...values });
} else {
await handleCreate(values);
}
refetch();
async function handleEdit(id: string, values: AutomationBlueprint) {
try {
await editBlueprint(id, values);
onClose();
} catch (error) {
setError('root', { message: maybeAxiosError(error) });
}
}
async function handleCreate(values: AutomationBlueprintDTO) {
try {
await addBlueprint(values);
onClose();
} catch (error) {
setError('root', { message: maybeAxiosError(error) });
}
}
};
const canSubmit = !isSubmitting && isDirty && isValid;
return (
<Panel.Indent
as='form'
name='blueprint-form'
onSubmit={handleSubmit(onSubmit)}
className={style.outerColumn}
onKeyDown={(event) => preventEscape(event, onClose)}
>
<Panel.SubHeader>{isEdit ? 'Edit blueprint' : 'Create blueprint'}</Panel.SubHeader>
<div className={style.innerSection}>
<h3>Blueprint options</h3>
<div className={style.titleSection}>
<label>
Title
<Input
{...register('title', { required: { value: true, message: 'Required field' } })}
variant='ontime-filled'
size='sm'
placeholder='Load preset'
autoComplete='off'
/>
</label>
<Panel.Error>{errors.title?.message}</Panel.Error>
</div>
</div>
<div className={style.innerSection}>
<h3>Filters</h3>
<div className={style.ruleSection}>
<label>
Trigger outputs if
<Controller
name='filterRule'
control={control}
render={({ field }) => (
<RadioGroup {...field} size='sm' className={style.matchRadio} variant='ontime'>
<Radio value='all'>All filters pass</Radio>
<Radio value='any'>Any filter passes</Radio>
</RadioGroup>
)}
/>
</label>
{fieldFilters.map((field, index) => (
<div key={field.id} className={style.filterSection}>
<label>
Runtime data source
<Select
{...register(`filters.${index}.field`, { required: { value: true, message: 'Required field' } })}
size='sm'
variant='ontime'
placeholder='Event field'
>
{fieldList.map(({ value, label }) => (
<option key={value} value={value}>
{label}
</option>
))}
</Select>
<Panel.Error>{errors.filters?.[index]?.field?.message}</Panel.Error>
</label>
<label>
Matching condition
<Select
{...register(`filters.${index}.operator`, { required: { value: true, message: 'Required field' } })}
size='sm'
variant='ontime'
placeholder='Operator'
>
<option value='equals'>equals</option>
<option value='not_equals'>not equals</option>
<option value='contains'>contains</option>
<option value='greater_than'>greater than</option>
<option value='less_than'>less than</option>
</Select>
<Panel.Error>{errors.filters?.[index]?.operator?.message}</Panel.Error>
</label>
<label>
Value to match
<Input
{...register(`filters.${index}.value`)}
variant='ontime-filled'
size='sm'
placeholder='<no value>'
autoComplete='off'
/>
</label>
<IconButton
aria-label='Delete'
icon={<IoTrash />}
variant='ontime-ghosted'
size='sm'
color='#FA5656' // $red-500
onClick={() => removeFilter(index)}
isDisabled={false}
isLoading={false}
/>
</div>
))}
<div>
<Button
variant='ontime-subtle'
size='sm'
type='submit'
rightIcon={<IoAdd />}
onClick={handleAddNewFilter}
isDisabled={false}
isLoading={false}
>
Add filter
</Button>
</div>
</div>
</div>
<div className={style.innerColumn}>
<h3>Outputs</h3>
{fieldOutputs.map((output, index) => {
if (isOSCOutput(output)) {
const rowErrors = errors.outputs?.[index] as
| {
targetIP?: { message?: string };
targetPort?: { message?: string };
address?: { message?: string };
args?: { message?: string };
}
| undefined;
return (
<div key={output.id} className={style.outputCard}>
<Tag>OSC</Tag>
<div className={style.oscSection}>
<label>
Target IP
<Input
{...register(`outputs.${index}.targetIP`, {
required: { value: true, message: 'Required field' },
})}
variant='ontime-filled'
size='sm'
placeholder='127.0.0.1'
autoComplete='off'
/>
<Panel.Error>{rowErrors?.targetIP?.message}</Panel.Error>
</label>
<label>
Target Port
<Input
{...register(`outputs.${index}.targetPort`, {
required: { value: true, message: 'Required field' },
setValueAs: (value) => (value === '' ? 0 : Number(value)),
max: { value: 65535, message: 'Port must be within range 1024 - 65535' },
min: { value: 1024, message: 'Port must be within range 1024 - 65535' },
})}
variant='ontime-filled'
size='sm'
type='number'
maxLength={5}
placeholder='8000'
autoComplete='off'
/>
<Panel.Error>{rowErrors?.targetPort?.message}</Panel.Error>
</label>
<label>
Address
<Input
{...register(`outputs.${index}.address`)}
variant='ontime-filled'
size='sm'
placeholder='/cue/start'
autoComplete='off'
/>
<Panel.Error>{rowErrors?.address?.message}</Panel.Error>
</label>
<label>
Parameters
<Input
{...register(`outputs.${index}.args`)}
variant='ontime-filled'
size='sm'
placeholder='1'
autoComplete='off'
/>
<Panel.Error>{rowErrors?.args?.message}</Panel.Error>
</label>
<Panel.InlineElements relation='inner'>
<Button size='sm' variant='ontime-ghosted' onClick={() => handleTestOSCOutput(index)}>
Test
</Button>
<IconButton
aria-label='Delete'
icon={<IoTrash />}
variant='ontime-ghosted'
size='sm'
onClick={() => removeOutput(index)}
color='#FA5656' // $red-500
isDisabled={false}
isLoading={false}
/>
</Panel.InlineElements>
</div>
</div>
);
}
if (isHTTPOutput(output)) {
const rowErrors = errors.outputs?.[index] as
| {
url?: { message?: string };
}
| undefined;
return (
<div key={output.id} className={style.outputCard}>
<Tag>HTTP</Tag>
<div className={style.httpSection}>
<label>
Target URL
<Input
{...register(`outputs.${index}.url`, {
required: { value: true, message: 'Required field' },
pattern: {
value: startsWithHttp,
message: 'HTTP messages should target http:// or https://',
},
})}
variant='ontime-filled'
size='sm'
placeholder='http://127.0.0.1/start/1'
autoComplete='off'
/>
<Panel.Error>{rowErrors?.url?.message}</Panel.Error>
</label>
<Panel.InlineElements relation='inner'>
<Button size='sm' variant='ontime-ghosted' onClick={() => handleTestHTTPOutput(index)}>
Test
</Button>
<IconButton
aria-label='Delete'
icon={<IoTrash />}
variant='ontime-ghosted'
size='sm'
onClick={() => removeOutput(index)}
color='#FA5656' // $red-500
isDisabled={false}
isLoading={false}
/>
</Panel.InlineElements>
</div>
</div>
);
}
// there should be no other output types
return null;
})}
<Panel.InlineElements relation='inner'>
<Button
variant='ontime-subtle'
rightIcon={<IoAdd />}
size='sm'
onClick={handleAddNewOSCOutput}
isDisabled={false}
isLoading={false}
>
OSC
</Button>
<Button
variant='ontime-subtle'
rightIcon={<IoAdd />}
size='sm'
onClick={handleAddNewHTTPOutput}
isDisabled={false}
isLoading={false}
>
HTTP
</Button>
</Panel.InlineElements>
</div>
<Panel.InlineElements align='end'>
{errors?.root && <Panel.Error>{errors.root.message}</Panel.Error>}
<Button variant='ontime-subtle' size='sm' onClick={onClose}>
Cancel
</Button>
<Button variant='ontime-filled' size='sm' type='submit' isDisabled={!canSubmit} isLoading={isSubmitting}>
Save
</Button>
</Panel.InlineElements>
</Panel.Indent>
);
}
/**
* We use this guard to find out if the form is receiving an existing blueprint or creating a DTO
* We do this by checking whether an ID has been generated
*/
function isBlueprint(blueprint: AutomationBlueprintDTO | AutomationBlueprint): blueprint is AutomationBlueprint {
return Object.hasOwn(blueprint, 'id');
}
export const staticSelectProperties = [
{ value: 'id', label: 'ID' },
{ value: 'title', label: 'Title' },
{ value: 'cue', label: 'Cue' },
{ value: 'countToEnd', label: 'Count to end' },
{ value: 'isPublic', label: 'Is public' },
{ value: 'skip', label: 'Skip' },
{ value: 'note', label: 'Note' },
{ value: 'colour', label: 'Colour' },
{ value: 'endAction', label: 'End action' },
{ value: 'timerType', label: 'Timer type' },
{ value: 'timeWarning', label: 'Time warning' },
{ value: 'timeDanger', label: 'Time danger' },
];
type SelectableField = {
value: keyof OntimeEvent | string; // string for custom fields
label: string;
};
function makeFieldList(customFields: CustomFields): SelectableField[] {
return [
...staticSelectProperties,
...Object.entries(customFields).map(([key, { label }]) => ({ value: key, label: `Custom: ${label}` })),
];
}
@@ -1,130 +0,0 @@
import { Fragment, useState } from 'react';
import { Button, IconButton } from '@chakra-ui/react';
import { IoAdd } from '@react-icons/all-files/io5/IoAdd';
import { IoPencil } from '@react-icons/all-files/io5/IoPencil';
import { IoTrash } from '@react-icons/all-files/io5/IoTrash';
import { AutomationBlueprintDTO, NormalisedAutomationBlueprint } from 'ontime-types';
import { deleteBlueprint } from '../../../../common/api/automation';
import { maybeAxiosError } from '../../../../common/api/utils';
import Tag from '../../../../common/components/tag/Tag';
import useAutomationSettings from '../../../../common/hooks-query/useAutomationSettings';
import * as Panel from '../../panel-utils/PanelUtils';
import BlueprintForm from './BlueprintForm';
const automationBlueprintPlaceholder: AutomationBlueprintDTO = {
title: '',
filterRule: 'all',
filters: [],
outputs: [],
};
interface BlueprintsListProps {
blueprints: NormalisedAutomationBlueprint;
}
export default function BlueprintsList(props: BlueprintsListProps) {
const { blueprints } = props;
const { refetch } = useAutomationSettings();
const [blueprintFormData, setBlueprintFormData] = useState<AutomationBlueprintDTO | AutomationBlueprintDTO | null>(
null,
);
const [deleteError, setDeleteError] = useState<string | null>(null);
const handleDelete = async (id: string) => {
try {
setDeleteError(null);
await deleteBlueprint(id);
} catch (error) {
setDeleteError(maybeAxiosError(error));
} finally {
refetch();
}
};
const arrayBlueprints = Object.keys(blueprints);
return (
<Panel.Card>
<Panel.SubHeader>
Manage blueprints
<Button
variant='ontime-subtle'
rightIcon={<IoAdd />}
size='sm'
type='submit'
isDisabled={Boolean(blueprintFormData)}
onClick={() => setBlueprintFormData(automationBlueprintPlaceholder)}
>
New
</Button>
</Panel.SubHeader>
<Panel.Divider />
{blueprintFormData !== null && (
<BlueprintForm blueprint={blueprintFormData} onClose={() => setBlueprintFormData(null)} />
)}
<Panel.Table>
<thead>
<tr>
<th style={{ width: '45%' }}>Title</th>
<th style={{ width: '15%' }}>Trigger rule</th>
<th style={{ width: '15%' }}>Filters</th>
<th style={{ width: '15%' }}>Outputs</th>
<th />
</tr>
</thead>
<tbody>
{arrayBlueprints.length === 0 && (
<Panel.TableEmpty handleClick={() => setBlueprintFormData(automationBlueprintPlaceholder)} />
)}
{arrayBlueprints.map((blueprintId) => {
if (!Object.hasOwn(blueprints, blueprintId)) {
return null;
}
return (
<Fragment key={blueprintId}>
<tr>
<td>{blueprints[blueprintId].title}</td>
<td>
<Tag>{blueprints[blueprintId].filterRule}</Tag>
</td>
<td>{blueprints[blueprintId].filters.length}</td>
<td>{blueprints[blueprintId].outputs.length}</td>
<Panel.InlineElements align='end' relation='inner' as='td'>
<IconButton
size='sm'
variant='ontime-ghosted'
color='#e2e2e2' // $gray-200
icon={<IoPencil />}
aria-label='Edit entry'
onClick={() => setBlueprintFormData(blueprints[blueprintId])}
/>
<IconButton
size='sm'
variant='ontime-ghosted'
color='#FA5656' // $red-500
icon={<IoTrash />}
aria-label='Delete entry'
onClick={() => handleDelete(blueprintId)}
/>
</Panel.InlineElements>
</tr>
{deleteError && (
<tr>
<td colSpan={5}>
<Panel.Error>{deleteError}</Panel.Error>
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</Panel.Table>
</Panel.Card>
);
}
@@ -0,0 +1,139 @@
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { Button, Input, Select } from '@chakra-ui/react';
import { NormalisedAutomation, TimerLifeCycle, TriggerDTO } from 'ontime-types';
import { addTrigger, editTrigger } from '../../../../common/api/automation';
import { maybeAxiosError } from '../../../../common/api/utils';
import { preventEscape } from '../../../../common/utils/keyEvent';
import * as Panel from '../../panel-utils/PanelUtils';
import { cycles } from './automationUtils';
interface TriggerFormProps {
automations: NormalisedAutomation;
initialId?: string;
initialTitle?: string;
initialAutomationId?: string;
initialTrigger?: TimerLifeCycle;
onCancel: () => void;
postSubmit: () => void;
}
export default function TriggerForm(props: TriggerFormProps) {
const { automations, initialId, initialTitle, initialAutomationId, initialTrigger, onCancel, postSubmit } = props;
const {
handleSubmit,
register,
setFocus,
setError,
formState: { errors, isSubmitting, isValid, isDirty },
} = useForm<TriggerDTO>({
defaultValues: {
title: initialTitle,
trigger: initialTrigger,
automationId: initialAutomationId,
},
resetOptions: {
keepDirtyValues: true,
},
});
// give initial focus to the title field
useEffect(() => {
setFocus('title');
// eslint-disable-next-line react-hooks/exhaustive-deps -- focus on mount
}, []);
const onSubmit = async (values: TriggerDTO) => {
// if we were passed an ID we are editing a Trigger
if (initialId) {
try {
await editTrigger(initialId, { id: initialId, ...values });
postSubmit();
} catch (error) {
setError('root', { message: `Failed to save changes to trigger ${maybeAxiosError(error)}` });
}
return;
}
// otherwise we are creating a new automation
try {
await addTrigger(values);
postSubmit();
} catch (error) {
setError('root', { message: `Failed to save trigger ${maybeAxiosError(error)}` });
}
};
const automationSelect = Object.keys(automations).map((automation) => {
return {
value: automation,
label: automations[automation].title,
};
});
const canSubmit = isDirty && isValid;
return (
<Panel.Indent
as='form'
name='trigger-form'
onSubmit={handleSubmit(onSubmit)}
onKeyDown={(event) => preventEscape(event, onCancel)}
>
<Panel.SubHeader>{initialId ? 'Edit trigger' : 'Create trigger'}</Panel.SubHeader>
<label>
Title
<Input
{...register('title', { required: { value: true, message: 'Required field' } })}
size='sm'
variant='ontime-filled'
autoComplete='off'
defaultValue={initialTitle}
/>
<Panel.Error>{errors.title?.message}</Panel.Error>
</label>
<label>
Lifecycle trigger
<Select
size='sm'
variant='ontime'
defaultValue={initialTrigger}
{...register('trigger', { required: { value: true, message: 'Required field' } })}
>
{cycles.map((cycle) => (
<option key={cycle.id} value={cycle.value}>
{cycle.label}
</option>
))}
</Select>
<Panel.Error>{errors.trigger?.message}</Panel.Error>
</label>
<label>
Automation title
<Select
size='sm'
variant='ontime'
defaultValue={initialAutomationId}
{...register('automationId', { required: { value: true, message: 'Required field' } })}
>
{automationSelect.map((automation) => (
<option key={automation.value} value={automation.value}>
{automation.label}
</option>
))}
</Select>
<Panel.Error>{errors.automationId?.message}</Panel.Error>
</label>
<Panel.InlineElements align='end'>
<Button size='sm' variant='ontime-subtle' isDisabled={isSubmitting} onClick={onCancel}>
Cancel
</Button>
<Button type='submit' size='sm' variant='ontime-filled' isDisabled={!canSubmit} isLoading={isSubmitting}>
Save
</Button>
</Panel.InlineElements>
</Panel.Indent>
);
}
@@ -0,0 +1,117 @@
import { Fragment, useMemo, useState } from 'react';
import { Button } from '@chakra-ui/react';
import { IoAdd } from '@react-icons/all-files/io5/IoAdd';
import { NormalisedAutomation, Trigger } from 'ontime-types';
import { deleteTrigger } from '../../../../common/api/automation';
import { maybeAxiosError } from '../../../../common/api/utils';
import useAutomationSettings from '../../../../common/hooks-query/useAutomationSettings';
import * as Panel from '../../panel-utils/PanelUtils';
import { checkDuplicates } from './automationUtils';
import AutomationForm from './TriggerForm';
import TriggersListItem from './TriggersListItem';
interface TriggersListProps {
triggers: Trigger[];
automations: NormalisedAutomation;
}
export default function TriggersList(props: TriggersListProps) {
const { triggers, automations } = props;
const [showForm, setShowForm] = useState(false);
const { refetch } = useAutomationSettings();
const [deleteError, setDeleteError] = useState<string | null>(null);
const handleDelete = async (id: string) => {
try {
await deleteTrigger(id);
} catch (error) {
setDeleteError(maybeAxiosError(error));
} finally {
refetch();
}
};
const postSubmit = () => {
setShowForm(false);
refetch();
};
const duplicates = useMemo(() => checkDuplicates(triggers), [triggers]);
// there is no point letting user creating a trigger if there are no automations
const canAdd = Object.keys(automations).length > 0;
return (
<Panel.Card>
<Panel.SubHeader>
Manage triggers
<Button
variant='ontime-subtle'
rightIcon={<IoAdd />}
size='sm'
type='submit'
form='trigger-form'
isDisabled={!canAdd}
isLoading={false}
onClick={() => setShowForm(true)}
>
New
</Button>
</Panel.SubHeader>
<Panel.Divider />
<Panel.Section>
{duplicates && (
<Panel.Error>
You have created multiple links between the same trigger and automation which can performance issues.
</Panel.Error>
)}
{showForm && (
<AutomationForm automations={automations} onCancel={() => setShowForm(false)} postSubmit={postSubmit} />
)}
<Panel.Table>
<thead>
<tr>
<th style={{ width: '35%' }}>Title</th>
<th style={{ width: '25%' }}>Lifecycle trigger</th>
<th style={{ width: '25%' }}>Automation</th>
<th />
</tr>
</thead>
<tbody>
{!showForm && triggers.length === 0 && (
<Panel.TableEmpty
label='Create an automation before to attach triggers to'
handleClick={canAdd ? () => setShowForm(true) : undefined}
/>
)}
{triggers.map((trigger, index) => {
return (
<Fragment key={trigger.id}>
<TriggersListItem
automations={automations}
id={trigger.id}
title={trigger.title}
trigger={trigger.trigger}
automationId={trigger.automationId}
duplicate={duplicates?.includes(index)}
handleDelete={() => handleDelete(trigger.id)}
postSubmit={postSubmit}
/>
{deleteError && (
<tr>
<td colSpan={5}>
<Panel.Error>{deleteError}</Panel.Error>
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</Panel.Table>
</Panel.Section>
</Panel.Card>
);
}
@@ -3,27 +3,27 @@ import { IconButton } from '@chakra-ui/react';
import { IoPencil } from '@react-icons/all-files/io5/IoPencil';
import { IoTrash } from '@react-icons/all-files/io5/IoTrash';
import { IoWarningOutline } from '@react-icons/all-files/io5/IoWarningOutline';
import { NormalisedAutomationBlueprint, TimerLifeCycle } from 'ontime-types';
import { NormalisedAutomation, TimerLifeCycle } from 'ontime-types';
import Tag from '../../../../common/components/tag/Tag';
import * as Panel from '../../panel-utils/PanelUtils';
import AutomationForm from './AutomationForm';
import { cycles } from './automationUtils';
import AutomationForm from './TriggerForm';
interface AutomationsListItemProps {
blueprints: NormalisedAutomationBlueprint;
interface TriggersListItemProps {
automations: NormalisedAutomation;
id: string;
title: string;
trigger: TimerLifeCycle;
blueprintId: string;
automationId: string;
duplicate?: boolean;
handleDelete: () => void;
postSubmit: () => void;
}
export default function AutomationsListItem(props: AutomationsListItemProps) {
const { blueprints, id, title, trigger, blueprintId, duplicate, handleDelete, postSubmit } = props;
export default function TriggersListItem(props: TriggersListItemProps) {
const { automations, id, title, trigger, automationId, duplicate, handleDelete, postSubmit } = props;
const [isEditing, setIsEditing] = useState(false);
if (isEditing) {
@@ -31,11 +31,11 @@ export default function AutomationsListItem(props: AutomationsListItemProps) {
<tr>
<td colSpan={99}>
<AutomationForm
blueprints={blueprints}
automations={automations}
initialId={id}
initialTitle={title}
initialTrigger={trigger}
initialBlueprint={blueprintId}
initialAutomationId={automationId}
onCancel={() => setIsEditing(false)}
postSubmit={() => {
setIsEditing(false);
@@ -47,7 +47,6 @@ export default function AutomationsListItem(props: AutomationsListItemProps) {
);
}
const blueprintTitle = blueprints?.[blueprintId]?.title;
return (
<tr data-warn={duplicate}>
<Panel.InlineElements as='td' relation='inner'>
@@ -62,7 +61,7 @@ export default function AutomationsListItem(props: AutomationsListItemProps) {
<Tag>{cycles.find((cycle) => cycle.value === trigger)?.label}</Tag>
</td>
<td>
<Tag>{blueprintTitle}</Tag>
<Tag>{automations?.[automationId]?.title}</Tag>
</td>
<Panel.InlineElements align='end' relation='inner' as='td'>
<IconButton
@@ -1,24 +1,24 @@
import { Automation, TimerLifeCycle } from 'ontime-types';
import { TimerLifeCycle, Trigger } from 'ontime-types';
import { checkDuplicates } from '../automationUtils';
describe('checkDuplicates', () => {
it('should return undefined if there are no duplicates', () => {
const automations: Automation[] = [
{ id: '1', title: 'First', trigger: TimerLifeCycle.onClock, blueprintId: '1' },
{ id: '2', title: 'Second', trigger: TimerLifeCycle.onDanger, blueprintId: '2' },
{ id: '3', title: 'Third', trigger: TimerLifeCycle.onLoad, blueprintId: '3' },
const triggers: Trigger[] = [
{ id: '1', title: 'First', trigger: TimerLifeCycle.onClock, automationId: '1' },
{ id: '2', title: 'Second', trigger: TimerLifeCycle.onDanger, automationId: '2' },
{ id: '3', title: 'Third', trigger: TimerLifeCycle.onLoad, automationId: '3' },
];
expect(checkDuplicates(automations)).toBeUndefined();
expect(checkDuplicates(triggers)).toBeUndefined();
});
it('should return list of titles of duplicates', () => {
const automations: Automation[] = [
{ id: '1', title: 'First', trigger: TimerLifeCycle.onClock, blueprintId: '1' },
{ id: '2', title: 'Second', trigger: TimerLifeCycle.onDanger, blueprintId: '2' },
{ id: '3', title: 'Third', trigger: TimerLifeCycle.onClock, blueprintId: '1' },
{ id: '3', title: 'Third', trigger: TimerLifeCycle.onPause, blueprintId: '1' },
const triggers: Trigger[] = [
{ id: '1', title: 'First', trigger: TimerLifeCycle.onClock, automationId: '1' },
{ id: '2', title: 'Second', trigger: TimerLifeCycle.onDanger, automationId: '2' },
{ id: '3', title: 'Third', trigger: TimerLifeCycle.onClock, automationId: '1' },
{ id: '3', title: 'Third', trigger: TimerLifeCycle.onPause, automationId: '1' },
];
expect(checkDuplicates(automations)).toStrictEqual([2]);
expect(checkDuplicates(triggers)).toStrictEqual([2]);
});
});
@@ -1,10 +1,10 @@
import {
Automation,
AutomationBlueprint,
AutomationBlueprintDTO,
AutomationDTO,
CustomFields,
OntimeEvent,
TimerLifeCycle,
Trigger,
} from 'ontime-types';
type CycleLabel = {
@@ -26,11 +26,11 @@ export const cycles: CycleLabel[] = [
];
/**
* We use this guard to find out if the form is receiving an existing blueprint or creating a DTO
* We use this guard to find out if the form is receiving an existing automation or creating a DTO
* We do this by checking whether an ID has been generated
*/
export function isBlueprint(blueprint: AutomationBlueprintDTO | AutomationBlueprint): blueprint is AutomationBlueprint {
return Object.hasOwn(blueprint, 'id');
export function isAutomation(automation: AutomationDTO | Automation): automation is Automation {
return Object.hasOwn(automation, 'id');
}
export const staticSelectProperties = [
@@ -61,22 +61,22 @@ export function makeFieldList(customFields: CustomFields): SelectableField[] {
}
/**
* We warn the user if they have created multiple links between the same blueprint and automation
* We warn the user if they have created multiple links between the same automation and a trigger
*/
export function checkDuplicates(automations: Automation[]) {
const automationMap: Record<string, string[]> = {};
export function checkDuplicates(triggers: Trigger[]) {
const triggersMap: Record<string, string[]> = {};
const duplicates = [];
for (let i = 0; i < automations.length; i++) {
const automation = automations[i];
if (!Object.hasOwn(automationMap, automation.trigger)) {
automationMap[automation.trigger] = [];
for (let i = 0; i < triggers.length; i++) {
const trigger = triggers[i];
if (!Object.hasOwn(triggersMap, trigger.trigger)) {
triggersMap[trigger.trigger] = [];
}
if (automationMap[automation.trigger].includes(automation.blueprintId)) {
if (triggersMap[trigger.trigger].includes(trigger.automationId)) {
duplicates.push(i);
} else {
automationMap[automation.trigger].push(automation.blueprintId);
triggersMap[trigger.trigger].push(trigger.automationId);
}
}
return duplicates.length > 0 ? duplicates : undefined;
@@ -51,8 +51,8 @@ const staticOptions = [
label: 'Automation',
secondary: [
{ id: 'automation__settings', label: 'Automation settings' },
{ id: 'automation__triggers', label: 'Manage triggers' },
{ id: 'automation__automations', label: 'Manage automations' },
{ id: 'automation__blueprints', label: 'Manage blueprints' },
],
},
{