Skip to content

v4 transactions #1628

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions apps/client/src/common/api/customFields.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import axios from 'axios';
import { CustomField, CustomFieldLabel, CustomFields } from 'ontime-types';
import { CustomField, CustomFieldKey, CustomFields } from 'ontime-types';

import { apiEntryUrl } from './constants';

Expand All @@ -24,15 +24,15 @@ export async function postCustomField(newField: CustomField): Promise<CustomFiel
/**
* Edits single custom field
*/
export async function editCustomField(label: CustomFieldLabel, newField: CustomField): Promise<CustomFields> {
const res = await axios.put(`${customFieldsPath}/${label}`, { ...newField });
export async function editCustomField(key: CustomFieldKey, newField: CustomField): Promise<CustomFields> {
const res = await axios.put(`${customFieldsPath}/${key}`, { ...newField });
return res.data;
}

/**
* Deletes single custom field
*/
export async function deleteCustomField(label: CustomFieldLabel): Promise<CustomFields> {
const res = await axios.delete(`${customFieldsPath}/${label}`);
export async function deleteCustomField(key: CustomFieldKey): Promise<CustomFields> {
const res = await axios.delete(`${customFieldsPath}/${key}`);
return res.data;
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useState } from 'react';
import { IoPencil, IoTrash } from 'react-icons/io5';
import { IconButton } from '@chakra-ui/react';
import { CustomField, CustomFieldLabel } from 'ontime-types';
import { CustomField, CustomFieldKey } from 'ontime-types';

import CopyTag from '../../../../../common/components/copy-tag/CopyTag';
import Swatch from '../../../../../common/components/input/colour-input/Swatch';
Expand All @@ -17,8 +17,8 @@ interface CustomFieldEntryProps {
label: string;
fieldKey: string;
type: 'string' | 'image';
onEdit: (label: CustomFieldLabel, patch: CustomField) => Promise<void>;
onDelete: (label: CustomFieldLabel) => Promise<void>;
onEdit: (key: CustomFieldKey, patch: CustomField) => Promise<void>;
onDelete: (key: CustomFieldKey) => Promise<void>;
}

export default function CustomFieldEntry(props: CustomFieldEntryProps) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useState } from 'react';
import { IoAdd } from 'react-icons/io5';
import { Button } from '@chakra-ui/react';
import { CustomField, CustomFieldLabel } from 'ontime-types';
import { CustomField, CustomFieldKey } from 'ontime-types';

import { deleteCustomField, editCustomField, postCustomField } from '../../../../../common/api/customFields';
import Info from '../../../../../common/components/info/Info';
Expand Down Expand Up @@ -31,14 +31,14 @@ export default function CustomFields() {
setIsAdding(false);
};

const handleEditField = async (label: CustomFieldLabel, customField: CustomField) => {
await editCustomField(label, customField);
const handleEditField = async (key: CustomFieldKey, customField: CustomField) => {
await editCustomField(key, customField);
refetch();
};

const handleDelete = async (label: string) => {
const handleDelete = async (key: CustomFieldKey) => {
try {
await deleteCustomField(label);
await deleteCustomField(key);
refetch();
} catch (_error) {
/** we do not handle errors here */
Expand Down
5 changes: 3 additions & 2 deletions apps/client/src/features/rundown/event-editor/EventEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback } from 'react';
import { CustomFieldLabel, OntimeEvent } from 'ontime-types';
import { OntimeEvent } from 'ontime-types';

import AppLink from '../../../common/components/link/app-link/AppLink';
import { useEntryActions } from '../../../common/hooks/useEntryAction';
Expand All @@ -14,7 +14,8 @@ import EventEditorEmpty from './EventEditorEmpty';

import style from './EventEditor.module.scss';

export type EditorUpdateFields = 'cue' | 'title' | 'note' | 'colour' | CustomFieldLabel;
// any of the titles + custom field labels
export type EditorUpdateFields = 'cue' | 'title' | 'note' | 'colour' | string;

interface EventEditorProps {
event: OntimeEvent;
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/api-data/assets/assets.validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Request, Response, NextFunction } from 'express';
import { body, validationResult } from 'express-validator';

export const validatePostCss = [
body('css').exists().isString().trim(),
body('css').isString().trim(),

(req: Request, res: Response, next: NextFunction) => {
const errors = validationResult(req);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { TriggerDTO, TimerLifeCycle, AutomationDTO, Automation } from 'ontime-types';
import { TriggerDTO, TimerLifeCycle, AutomationDTO, Automation, EntryId } from 'ontime-types';

import { makeRundown } from '../../rundown/__mocks__/rundown.mocks.js';

import {
addTrigger,
Expand All @@ -12,6 +14,7 @@ import {
getAutomationTriggers,
getAutomations,
} from '../automation.dao.js';

import { makeOSCAction, makeHTTPAction } from './testUtils.js';

beforeAll(() => {
Expand Down Expand Up @@ -186,47 +189,25 @@ describe('editAutomation()', async () => {
});

describe('deleteAutomation()', () => {
// saving the ID of the added automation
let firstAutomation: Automation;
beforeEach(async () => {
await deleteAll();
firstAutomation = await addAutomation({
await addAutomation({
title: 'test-osc',
filterRule: 'all',
filters: [],
outputs: [],
});
});

it('should remove m automation from the list', async () => {
it('should remove an automation from the list', async () => {
const automations = getAutomations();
expect(Object.keys(automations).length).toEqual(1);

await deleteAutomation(Object.keys(automations)[0]);
const rundown = makeRundown({});
const timedEventOrder: EntryId[] = [];

await deleteAutomation(rundown, timedEventOrder, Object.keys(automations)[0]);
const removed = getAutomations();
expect(Object.keys(removed).length).toEqual(0);
});

it('should not remove an automation which is in use', async () => {
const automations = getAutomations();
await addTrigger({
title: 'test-automation',
trigger: TimerLifeCycle.onLoad,
automationId: firstAutomation.id,
});

const automationKeys = Object.keys(automations);
const automationId = automationKeys[0];
expect(automationId).toEqual(firstAutomation.id);
expect(automationKeys.length).toEqual(1);
expect(automations[automationId]).toMatchObject({
id: automationId,
title: 'test-osc',
filterRule: 'all',
filters: expect.any(Array),
outputs: expect.any(Array),
});

await expect(deleteAutomation(automationId)).rejects.toThrowError();
});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { parseTemplateNested, stringToOSCArgs } from '../automation.utils.js';
import { TimerLifeCycle } from 'ontime-types';
import { makeOntimeEvent, makeRundown } from '../../rundown/__mocks__/rundown.mocks.js';
import { isAutomationUsed, parseTemplateNested, stringToOSCArgs } from '../automation.utils.js';

describe('parseTemplateNested()', () => {
it('parses string with a single-level variable name', () => {
Expand Down Expand Up @@ -245,3 +247,53 @@ describe('test stringToOSCArgs()', () => {
expect(stringToOSCArgs(test)).toStrictEqual(expected);
});
});

describe('isAutomationUsed()', () => {
it('returns the first event which uses an automation', () => {
const rundown = makeRundown({
entries: {
'1': makeOntimeEvent({
id: '1',
triggers: [
{
id: 'trigger-1',
title: 'Trigger 1',
trigger: TimerLifeCycle.onClock,
automationId: 'test-automation',
},
],
}),
},
});

const timedEventOrder = ['1'];
const automationId = 'test-automation';

const result = isAutomationUsed(rundown, timedEventOrder, automationId);
expect(result).toBe('1');
});

it('returns returns undefined if there are no matches', () => {
const rundown = makeRundown({
entries: {
'1': makeOntimeEvent({
id: '1',
triggers: [
{
id: 'trigger-1',
title: 'Trigger 1',
trigger: TimerLifeCycle.onClock,
automationId: 'test-automation',
},
],
}),
},
});

const timedEventOrder = ['1'];
const automationId = 'does-not-exist';

const result = isAutomationUsed(rundown, timedEventOrder, automationId);
expect(result).toBeUndefined();
});
});
7 changes: 6 additions & 1 deletion apps/server/src/api-data/automation/automation.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { Request, Response } from 'express';

import { oscServer } from '../../adapters/OscAdapter.js';

import { getCurrentRundown, getRundownMetadata } from '../rundown/rundown.dao.js';

import * as automationDao from './automation.dao.js';
import * as automationService from './automation.service.js';
import { parseOutput } from './automation.validation.js';
Expand Down Expand Up @@ -106,7 +108,10 @@ export async function editAutomation(req: Request, res: Response<Automation | Er

export async function deleteAutomation(req: Request, res: Response<void | ErrorResponse>) {
try {
await automationDao.deleteAutomation(req.params.id);
const rundown = getCurrentRundown();
const { timedEventOrder } = getRundownMetadata();

await automationDao.deleteAutomation(rundown, timedEventOrder, req.params.id);
res.status(204).send();
} catch (error) {
const message = getErrorMessage(error);
Expand Down
17 changes: 8 additions & 9 deletions apps/server/src/api-data/automation/automation.dao.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ import type {
Automation,
AutomationDTO,
AutomationSettings,
EntryId,
NormalisedAutomation,
Rundown,
Trigger,
TriggerDTO,
} from 'ontime-types';
import { deleteAtIndex, generateId } from 'ontime-utils';

import { getDataProvider } from '../../classes/data-provider/DataProvider.js';
import { getTimedEvents } from '../../services/rundown-service/rundownUtils.js';

import { isAutomationUsed } from './automation.utils.js';

/**
* Gets a copy of the stored automation settings
Expand Down Expand Up @@ -133,7 +136,7 @@ export async function editAutomation(id: string, newAutomation: AutomationDTO):
/**
* Deletes a automation given its ID
*/
export async function deleteAutomation(id: string): Promise<void> {
export async function deleteAutomation(rundown: Rundown, timedEventOrder: EntryId[], id: string): Promise<void> {
const automations = getAutomations();
// ignore request if automation does not exist
if (!Object.hasOwn(automations, id)) {
Expand All @@ -149,13 +152,9 @@ export async function deleteAutomation(id: string): Promise<void> {
}

// prevent deleting a automation that is in use in events
const events = getTimedEvents().filter(
(event) => event.triggers && event.triggers.some((trigger) => trigger.automationId === id),
);
if (events.length) {
throw new Error(
`Unable to delete automation used in event: ${events[0].id}${events.length > 1 ? ` and ${events.length - 1} more` : ''}`,
);
const isInUse = isAutomationUsed(rundown, timedEventOrder, id);
if (isInUse) {
throw new Error(`Unable to delete automation used in event with ID ${isInUse}`);
}

delete automations[id];
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/api-data/automation/automation.parser.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DatabaseModel, AutomationSettings, NormalisedAutomation, Trigger } from 'ontime-types';

import { dbModel } from '../../models/dataModel.js';
import type { ErrorEmitter } from '../../utils/parser.js';
import type { ErrorEmitter } from '../../utils/parserUtils.js';

interface LegacyData extends Partial<DatabaseModel> {
http?: unknown;
Expand Down
24 changes: 23 additions & 1 deletion apps/server/src/api-data/automation/automation.utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FilterRule, MaybeNumber, OntimeAction } from 'ontime-types';
import { EntryId, FilterRule, isOntimeEvent, MaybeNumber, OntimeAction, Rundown } from 'ontime-types';
import { millisToString, removeLeadingZero, splitWhitespace, getPropertyFromPath } from 'ontime-utils';
import type { OscArgOrArrayInput, OscArgInput } from 'osc-min';

Expand Down Expand Up @@ -195,3 +195,25 @@ export function isBooleanEquals(a: boolean, b: string): boolean {
}
return false;
}

/**
* Checks is an automation is used in a rundown
* TODO(v4): this currently only checks the current rundown, we will need to check all rundowns in the future
*/
export function isAutomationUsed(
rundown: Rundown,
timedEventOrder: EntryId[],
automationId: string,
): EntryId | undefined {
for (let i = 0; i < timedEventOrder.length; i++) {
const eventId = timedEventOrder[i];
const event = rundown.entries[eventId];
if (isOntimeEvent(event) && event.triggers) {
for (const trigger of event.triggers) {
if (trigger.automationId === automationId) {
return eventId;
}
}
}
}
}
Loading