mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-12 02:43:50 +00:00
feat(import): add merge strategy and new-rundown destination to spreadsheet import
Co-authored-by: Carlos Valente <34649812+cpvalente@users.noreply.github.com>
This commit is contained in:
@@ -1,8 +1,18 @@
|
||||
import { EndAction, OntimeEvent, TimeStrategy, TimerType } from 'ontime-types';
|
||||
import {
|
||||
EndAction,
|
||||
OntimeEvent,
|
||||
OntimeGroup,
|
||||
OntimeMilestone,
|
||||
TimeStrategy,
|
||||
TimerLifeCycle,
|
||||
TimerType,
|
||||
Trigger,
|
||||
} from 'ontime-types';
|
||||
import { MILLIS_PER_HOUR, createEvent } from 'ontime-utils';
|
||||
import { assertType } from 'vitest';
|
||||
|
||||
import { makeOntimeEvent, makeOntimeGroup, makeRundown } from '../__mocks__/rundown.mocks.js';
|
||||
import { makeOntimeEvent, makeOntimeGroup, makeOntimeMilestone, makeRundown } from '../__mocks__/rundown.mocks.js';
|
||||
import { parseRundown } from '../rundown.parser.js';
|
||||
import {
|
||||
calculateDayOffset,
|
||||
deleteById,
|
||||
@@ -10,6 +20,8 @@ import {
|
||||
getIntegerAndFraction,
|
||||
hasChanges,
|
||||
makeDeepClone,
|
||||
mergeRundownPreservingFields,
|
||||
isLoadedPlayable,
|
||||
} from '../rundown.utils.js';
|
||||
|
||||
describe('test event validator', () => {
|
||||
@@ -287,3 +299,314 @@ describe('getIntegerAndFraction()', () => {
|
||||
expect(getIntegerAndFraction('123.')).toStrictEqual({ integer: 123, faction: 0, precision: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The merge strategy takes the incoming (spreadsheet) rundown as the source of truth for structure
|
||||
* and order. For a matched event it only applies the fields the spreadsheet mapped (providedFields);
|
||||
* any field it does not provide (e.g. automations) is kept from the existing event.
|
||||
*/
|
||||
describe('mergeRundownPreservingFields()', () => {
|
||||
const automation: Trigger = {
|
||||
id: 'trigger-onair',
|
||||
title: 'Go on air',
|
||||
trigger: TimerLifeCycle.onStart,
|
||||
automationId: 'automation-onair',
|
||||
};
|
||||
|
||||
it('keeps the current rundown identity but takes structure and order from the incoming rundown', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
title: 'Main show',
|
||||
revision: 3,
|
||||
order: ['welcome', 'keynote'],
|
||||
entries: {
|
||||
welcome: makeOntimeEvent({ id: 'welcome', title: 'Welcome' }),
|
||||
keynote: makeOntimeEvent({ id: 'keynote', title: 'Keynote' }),
|
||||
},
|
||||
});
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
title: 'From spreadsheet',
|
||||
revision: 0,
|
||||
order: ['welcome', 'lunch'],
|
||||
entries: {
|
||||
welcome: makeOntimeEvent({ id: 'welcome', title: 'Welcome' }),
|
||||
lunch: makeOntimeEvent({ id: 'lunch', title: 'Lunch' }),
|
||||
},
|
||||
});
|
||||
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['title'], custom: [] });
|
||||
|
||||
// identity and revision come from the current rundown
|
||||
expect(merged.id).toBe('show-rundown');
|
||||
expect(merged.title).toBe('Main show');
|
||||
expect(merged.revision).toBe(4);
|
||||
// structure and order come from the incoming rundown
|
||||
expect(merged.order).toEqual(['welcome', 'lunch']);
|
||||
expect(merged.flatOrder).toEqual(incoming.flatOrder);
|
||||
});
|
||||
|
||||
it('deletes current entries that are absent from the incoming rundown', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['welcome', 'keynote'],
|
||||
entries: {
|
||||
welcome: makeOntimeEvent({ id: 'welcome' }),
|
||||
keynote: makeOntimeEvent({ id: 'keynote' }),
|
||||
},
|
||||
});
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['welcome'],
|
||||
entries: { welcome: makeOntimeEvent({ id: 'welcome' }) },
|
||||
});
|
||||
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['title'], custom: [] });
|
||||
|
||||
expect(merged.entries.welcome).toBeDefined();
|
||||
expect(merged.entries.keynote).toBeUndefined();
|
||||
});
|
||||
|
||||
it('replaces an entry entirely with the incoming data when the id is kept but the type changes', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', title: 'Keynote', triggers: [automation] }) },
|
||||
});
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeGroup({ id: 'keynote', title: 'Keynote group' }) },
|
||||
});
|
||||
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['title'], custom: [] });
|
||||
|
||||
// the incoming group fully replaces the previous event, no old data is carried over
|
||||
expect(merged.entries.keynote).toEqual(incoming.entries.keynote);
|
||||
});
|
||||
|
||||
it('applies the provided fields to a matched event, including when the incoming value is empty', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', title: 'Keynote', note: 'in the green room' }) },
|
||||
});
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', title: 'Opening keynote', note: '' }) },
|
||||
});
|
||||
|
||||
// the sheet mapped title and note
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['title', 'note'], custom: [] });
|
||||
const keynote = merged.entries.keynote as OntimeEvent;
|
||||
|
||||
expect(keynote.title).toBe('Opening keynote');
|
||||
// an empty provided value replaces the current one
|
||||
expect(keynote.note).toBe('');
|
||||
});
|
||||
|
||||
it('keeps fields the sheet did not map on a matched event, regardless of the incoming values', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['keynote'],
|
||||
entries: {
|
||||
keynote: makeOntimeEvent({ id: 'keynote', title: 'Keynote', note: 'green room', triggers: [automation] }),
|
||||
},
|
||||
});
|
||||
// the preview always fully populates an entry, so the incoming carries a note and triggers; what
|
||||
// the sheet actually supplied is providedFields, not the values that happen to be on the entry
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['keynote'],
|
||||
entries: {
|
||||
keynote: makeOntimeEvent({
|
||||
id: 'keynote',
|
||||
title: 'Opening keynote',
|
||||
note: 'from a stale column',
|
||||
triggers: [],
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// only title is mapped, so note and automations keep the existing values, not the incoming ones
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['title'], custom: [] });
|
||||
const keynote = merged.entries.keynote as OntimeEvent;
|
||||
|
||||
expect(keynote.title).toBe('Opening keynote');
|
||||
expect(keynote.note).toBe('green room');
|
||||
expect(keynote.triggers).toEqual([automation]);
|
||||
});
|
||||
|
||||
it('patches the provided custom fields on a matched event and keeps the unmapped ones', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['keynote'],
|
||||
entries: {
|
||||
keynote: makeOntimeEvent({
|
||||
id: 'keynote',
|
||||
title: 'Keynote',
|
||||
custom: { lighting: 'warm', song: 'intro theme' },
|
||||
}),
|
||||
},
|
||||
});
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['keynote'],
|
||||
entries: {
|
||||
keynote: makeOntimeEvent({ id: 'keynote', title: 'Opening keynote', custom: { lighting: 'cold' } }),
|
||||
},
|
||||
});
|
||||
|
||||
// the sheet mapped the title and the lighting custom field, but not song
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['title'], custom: ['lighting'] });
|
||||
const keynote = merged.entries.keynote as OntimeEvent;
|
||||
|
||||
expect(keynote.title).toBe('Opening keynote');
|
||||
expect(keynote.custom.lighting).toBe('cold');
|
||||
// an unmapped custom field is kept from the existing event
|
||||
expect(keynote.custom.song).toBe('intro theme');
|
||||
});
|
||||
|
||||
it('infers the time strategy from the provided times when the sheet is unambiguous', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', timeStrategy: TimeStrategy.LockEnd }) },
|
||||
});
|
||||
// the sheet provides only a duration, so the strategy is unambiguously LockDuration
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', duration: 60000 }) },
|
||||
});
|
||||
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['duration'], custom: [] });
|
||||
|
||||
expect((merged.entries.keynote as OntimeEvent).timeStrategy).toBe(TimeStrategy.LockDuration);
|
||||
});
|
||||
|
||||
it('keeps the existing time strategy when the provided times are ambiguous', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', timeStrategy: TimeStrategy.LockEnd }) },
|
||||
});
|
||||
// the sheet provides both an end and a duration, so the strategy cannot be inferred from them
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', timeEnd: 60000, duration: 60000 }) },
|
||||
});
|
||||
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['timeEnd', 'duration'], custom: [] });
|
||||
|
||||
expect((merged.entries.keynote as OntimeEvent).timeStrategy).toBe(TimeStrategy.LockEnd);
|
||||
});
|
||||
|
||||
it('merges a matched group, keeping the fields the sheet cannot express', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['session'],
|
||||
entries: { session: makeOntimeGroup({ id: 'session', title: 'Old session', targetDuration: 3_600_000 }) },
|
||||
});
|
||||
// the sheet cannot express a group's target duration, so the incoming group does not carry one
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['session'],
|
||||
entries: { session: makeOntimeGroup({ id: 'session', title: 'New session', targetDuration: null }) },
|
||||
});
|
||||
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['title'], custom: [] });
|
||||
const session = merged.entries.session as OntimeGroup;
|
||||
|
||||
expect(session.title).toBe('New session');
|
||||
expect(session.targetDuration).toBe(3_600_000);
|
||||
});
|
||||
|
||||
it('merges a matched milestone, keeping the fields the sheet did not map', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['reminder'],
|
||||
entries: { reminder: makeOntimeMilestone({ id: 'reminder', title: 'Reminder', note: 'call talent' }) },
|
||||
});
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['reminder'],
|
||||
entries: { reminder: makeOntimeMilestone({ id: 'reminder', title: 'Green room reminder', note: 'ignored' }) },
|
||||
});
|
||||
|
||||
// only title is mapped, so the milestone's note keeps the existing value
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['title'], custom: [] });
|
||||
const reminder = merged.entries.reminder as OntimeMilestone;
|
||||
|
||||
expect(reminder.title).toBe('Green room reminder');
|
||||
expect(reminder.note).toBe('call talent');
|
||||
});
|
||||
|
||||
it('does not mutate the current rundown and deep-clones the kept automations', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', triggers: [automation] }) },
|
||||
});
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', triggers: [] }) },
|
||||
});
|
||||
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['title'], custom: [] });
|
||||
|
||||
// kept automations are a copy, not a shared reference to the current rundown
|
||||
(merged.entries.keynote as OntimeEvent).triggers.push({ ...automation, id: 'trigger-extra' });
|
||||
expect((current.entries.keynote as OntimeEvent).triggers).toEqual([automation]);
|
||||
});
|
||||
|
||||
it('keeps the not-provided fields through a parseRundown round-trip', () => {
|
||||
const current = makeRundown({
|
||||
id: 'show-rundown',
|
||||
order: ['keynote'],
|
||||
entries: {
|
||||
keynote: makeOntimeEvent({ id: 'keynote', triggers: [automation], timeStrategy: TimeStrategy.LockEnd }),
|
||||
},
|
||||
});
|
||||
const incoming = makeRundown({
|
||||
id: 'spreadsheet-rundown',
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', title: 'Keynote', triggers: [] }) },
|
||||
});
|
||||
|
||||
const merged = mergeRundownPreservingFields(incoming, current, { event: ['title'], custom: [] });
|
||||
const parsed = parseRundown(merged, {});
|
||||
const keynote = parsed.entries.keynote as OntimeEvent;
|
||||
|
||||
expect(keynote.triggers).toEqual([automation]);
|
||||
expect(keynote.timeStrategy).toBe(TimeStrategy.LockEnd);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isLoadedPlayable()', () => {
|
||||
it('returns true when the loaded event still exists and is playable', () => {
|
||||
const rundown = makeRundown({ order: ['keynote'], entries: { keynote: makeOntimeEvent({ id: 'keynote' }) } });
|
||||
expect(isLoadedPlayable('keynote', rundown)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when the loaded event was removed', () => {
|
||||
const rundown = makeRundown({ order: ['welcome'], entries: { welcome: makeOntimeEvent({ id: 'welcome' }) } });
|
||||
expect(isLoadedPlayable('keynote', rundown)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when the loaded event is now skipped', () => {
|
||||
const rundown = makeRundown({
|
||||
order: ['keynote'],
|
||||
entries: { keynote: makeOntimeEvent({ id: 'keynote', skip: true }) },
|
||||
});
|
||||
expect(isLoadedPlayable('keynote', rundown)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when the matched entry is no longer an event', () => {
|
||||
const rundown = makeRundown({ order: ['keynote'], entries: { keynote: makeOntimeGroup({ id: 'keynote' }) } });
|
||||
expect(isLoadedPlayable('keynote', rundown)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import type { Request, Response, Router } from 'express';
|
||||
import express from 'express';
|
||||
import { matchedData } from 'express-validator';
|
||||
import { ErrorResponse, OntimeEntry, ProjectRundownsList, RenumberCues, Rundown } from 'ontime-types';
|
||||
import {
|
||||
ErrorResponse,
|
||||
OntimeEntry,
|
||||
ProjectRundowns,
|
||||
ProjectRundownsList,
|
||||
RenumberCues,
|
||||
Rundown,
|
||||
RundownImportPayload,
|
||||
} from 'ontime-types';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
|
||||
import { getDataProvider } from '../../classes/data-provider/DataProvider.js';
|
||||
@@ -12,7 +20,9 @@ import {
|
||||
applyDelay,
|
||||
batchEditEntries,
|
||||
cloneEntry,
|
||||
applyImportToRundown,
|
||||
createNewRundown,
|
||||
createRundownFromImport,
|
||||
deleteAllEntries,
|
||||
deleteEntries,
|
||||
deleteRundown,
|
||||
@@ -36,6 +46,7 @@ import {
|
||||
entryReorderValidator,
|
||||
entrySwapValidator,
|
||||
rundownArrayOfIds,
|
||||
rundownImportValidator,
|
||||
rundownPatchValidator,
|
||||
rundownPostValidator,
|
||||
} from './rundown.validation.js';
|
||||
@@ -147,6 +158,39 @@ router.delete('/:id', paramsWithId, async (req: Request, res: Response<ProjectRu
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Applies an imported rundown: override or merge into an existing rundown, or create a new one.
|
||||
*/
|
||||
router.post(
|
||||
'/import',
|
||||
rundownImportValidator,
|
||||
async (req: Request, res: Response<ProjectRundownsList | ErrorResponse>) => {
|
||||
try {
|
||||
const { mode, targetRundownId, rundown, customFields, providedFields } = matchedData<RundownImportPayload>(req);
|
||||
let projectRundowns: ProjectRundowns;
|
||||
if (mode === 'new') {
|
||||
projectRundowns = await createRundownFromImport(rundown, customFields);
|
||||
} else {
|
||||
// the validator guarantees this for override/merge, the guard narrows the type and adds defence in depth
|
||||
if (!targetRundownId) {
|
||||
throw new Error('targetRundownId is required when mode is override or merge');
|
||||
}
|
||||
projectRundowns = await applyImportToRundown(
|
||||
mode,
|
||||
targetRundownId,
|
||||
rundown,
|
||||
customFields,
|
||||
providedFields ?? { event: [], custom: [] },
|
||||
);
|
||||
}
|
||||
res.status(200).json({ loaded: getCurrentRundown().id, rundowns: normalisedToRundownArray(projectRundowns) });
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// #endregion operations on project rundowns ======================
|
||||
|
||||
// #region operations on rundown entries ==========================
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
CustomFields,
|
||||
EntryId,
|
||||
EventPostPayload,
|
||||
ImportedFields,
|
||||
InsertOptions,
|
||||
LogOrigin,
|
||||
OntimeEntry,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
ProjectRundowns,
|
||||
RefetchKey,
|
||||
Rundown,
|
||||
RundownImportMergeStrategy,
|
||||
isOntimeDelay,
|
||||
isOntimeEvent,
|
||||
isOntimeGroup,
|
||||
@@ -25,6 +27,7 @@ import { makeNewRundown } from '../../models/dataModel.js';
|
||||
import { setLastLoadedRundown } from '../../services/app-state-service/AppStateService.js';
|
||||
import { runtimeService } from '../../services/runtime-service/runtime.service.js';
|
||||
import { updateRundownData } from '../../stores/runtimeState.js';
|
||||
import { parseCustomFields } from '../custom-fields/customFields.parser.js';
|
||||
import {
|
||||
createTransaction,
|
||||
customFieldMutation,
|
||||
@@ -33,8 +36,15 @@ import {
|
||||
rundownMutation,
|
||||
updateBackgroundRundown,
|
||||
} from './rundown.dao.js';
|
||||
import { parseRundown } from './rundown.parser.js';
|
||||
import type { RundownMetadata } from './rundown.types.js';
|
||||
import { generateEvent, getIntegerAndFraction, hasChanges } from './rundown.utils.js';
|
||||
import {
|
||||
generateEvent,
|
||||
getIntegerAndFraction,
|
||||
hasChanges,
|
||||
mergeRundownPreservingFields,
|
||||
isLoadedPlayable,
|
||||
} from './rundown.utils.js';
|
||||
|
||||
/**
|
||||
* creates a new entry with given data
|
||||
@@ -656,8 +666,8 @@ export async function loadRundown(id: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a new rundown in the cache
|
||||
* and marks it as the currently loaded one
|
||||
* Sets a new rundown in the cache and marks it as the currently loaded one.
|
||||
* Switching to a rundown always stops playback.
|
||||
*/
|
||||
export async function initRundown(
|
||||
rundown: Readonly<Rundown>,
|
||||
@@ -679,6 +689,25 @@ export async function initRundown(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a rebuilt version of the currently loaded rundown in place.
|
||||
* Unlike switching rundowns, this maintains playback when possible
|
||||
*/
|
||||
function applyChangeToCurrentRundown(rundown: Readonly<Rundown>, customFields: Readonly<CustomFields>) {
|
||||
const loadedEvent = runtimeService.getLoadedEventId();
|
||||
if (loadedEvent && !isLoadedPlayable(loadedEvent, rundown)) {
|
||||
runtimeService.stop();
|
||||
}
|
||||
const { rundownMetadata, revision } = rundownCache.init(rundown, customFields);
|
||||
updateRuntimeOnChange(rundownMetadata);
|
||||
|
||||
setImmediate(() => {
|
||||
// notifying the timer hot-reloads the playing event and keeps playback
|
||||
notifyChanges(rundown.id, rundownMetadata, revision, { timer: true, external: true, reload: true });
|
||||
sendRefetch(RefetchKey.ProjectRundowns);
|
||||
});
|
||||
}
|
||||
|
||||
export async function createNewRundown(title: string) {
|
||||
const emptyRundown = makeNewRundown();
|
||||
emptyRundown.title = title;
|
||||
@@ -743,6 +772,86 @@ export async function duplicateExistingRundown(id: string) {
|
||||
return dataProvider.getProjectRundowns();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an imported rundown against the resulting custom fields, then commits those custom
|
||||
* fields. The rundown is validated before the custom-field mutation, so a payload that fails
|
||||
* validation cannot leave a partial custom-field write behind.
|
||||
* @throws if the rundown or custom fields fail validation
|
||||
*/
|
||||
async function parseImportAndCommitCustomFields(
|
||||
source: Readonly<Rundown>,
|
||||
incomingCustomFields: CustomFields,
|
||||
): Promise<Rundown> {
|
||||
const dataProvider = getDataProvider();
|
||||
const parsedCustomFields = parseCustomFields({ customFields: incomingCustomFields });
|
||||
const mergedCustomFields = { ...dataProvider.getCustomFields(), ...parsedCustomFields };
|
||||
const parsed = parseRundown(source, mergedCustomFields);
|
||||
await dataProvider.mergeIntoData({ customFields: parsedCustomFields });
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies an imported rundown onto an existing rundown, keeping the existing identity while
|
||||
* taking structure and order from the incoming data.
|
||||
* - 'override' replaces all content with the incoming data
|
||||
* - 'merge' updates matched entries with only the fields the spreadsheet provided, keeping the rest
|
||||
* (e.g. automations) from the existing entry
|
||||
*
|
||||
* When targeting the loaded rundown this is treated as a change, not a switch, so playback is
|
||||
* maintained when the playing event survives.
|
||||
* @throws if the target rundown does not exist
|
||||
*/
|
||||
export async function applyImportToRundown(
|
||||
strategy: RundownImportMergeStrategy,
|
||||
targetRundownId: string,
|
||||
incomingRundown: Rundown,
|
||||
incomingCustomFields: CustomFields,
|
||||
providedFields: ImportedFields,
|
||||
): Promise<ProjectRundowns> {
|
||||
const dataProvider = getDataProvider();
|
||||
// throws if the rundown was deleted between preview and apply
|
||||
const existing = dataProvider.getRundown(targetRundownId);
|
||||
|
||||
const source =
|
||||
strategy === 'merge'
|
||||
? mergeRundownPreservingFields(incomingRundown, existing, providedFields)
|
||||
: { ...incomingRundown, id: existing.id, title: existing.title, revision: existing.revision + 1 };
|
||||
const parsed = await parseImportAndCommitCustomFields(source, incomingCustomFields);
|
||||
|
||||
if (isCurrentRundown(targetRundownId)) {
|
||||
// applying to the loaded rundown is a change, not a switch: maintain playback when possible
|
||||
applyChangeToCurrentRundown(parsed, dataProvider.getCustomFields());
|
||||
} else {
|
||||
await dataProvider.setRundown(parsed.id, parsed);
|
||||
setImmediate(() => {
|
||||
sendRefetch(RefetchKey.ProjectRundowns);
|
||||
});
|
||||
}
|
||||
|
||||
return dataProvider.getProjectRundowns();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new rundown from an imported rundown and loads it,
|
||||
* so the user immediately sees the imported data.
|
||||
* Loading a rundown stops playback (as with any rundown switch).
|
||||
*/
|
||||
export async function createRundownFromImport(
|
||||
incomingRundown: Rundown,
|
||||
incomingCustomFields: CustomFields,
|
||||
): Promise<ProjectRundowns> {
|
||||
const dataProvider = getDataProvider();
|
||||
|
||||
// assign a fresh id so we never collide with an existing rundown
|
||||
const parsed = await parseImportAndCommitCustomFields({ ...incomingRundown, id: generateId() }, incomingCustomFields);
|
||||
parsed.revision = 0;
|
||||
|
||||
// initRundown persists the new rundown, makes it the loaded rundown and notifies clients
|
||||
await initRundown(parsed, dataProvider.getCustomFields(), true);
|
||||
|
||||
return dataProvider.getProjectRundowns();
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a rundown
|
||||
* @throws if attempting to delete the loaded rundown or the last rundown in the project
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
CustomFields,
|
||||
EntryCustomFields,
|
||||
EntryId,
|
||||
ImportedFields,
|
||||
OntimeBaseEvent,
|
||||
OntimeDelay,
|
||||
OntimeEntry,
|
||||
@@ -11,12 +12,14 @@ import {
|
||||
ProjectRundown,
|
||||
ProjectRundowns,
|
||||
Rundown,
|
||||
RundownEntries,
|
||||
SupportedEntry,
|
||||
TimeStrategy,
|
||||
isOntimeDelay,
|
||||
isOntimeEvent,
|
||||
isOntimeGroup,
|
||||
isOntimeMilestone,
|
||||
isPlayableEvent,
|
||||
} from 'ontime-types';
|
||||
import {
|
||||
createDelay,
|
||||
@@ -225,6 +228,83 @@ export function getUniqueId(rundown: Rundown): EntryId {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an entry patch containing exactly the fields the spreadsheet supplied, for both built-in
|
||||
* and custom fields. Everything the sheet did not map is left out, so applying the patch keeps the
|
||||
* existing value for those fields.
|
||||
*/
|
||||
function buildImportPatch(entry: OntimeEntry, providedFields: ImportedFields): Partial<OntimeEntry> {
|
||||
const source = entry as Record<string, unknown>;
|
||||
const patch: Record<string, unknown> = {};
|
||||
for (const field of providedFields.event) {
|
||||
patch[field] = source[field];
|
||||
}
|
||||
if (providedFields.custom.length > 0) {
|
||||
const entryCustom = (source.custom ?? {}) as EntryCustomFields;
|
||||
const custom: EntryCustomFields = {};
|
||||
for (const key of providedFields.custom) {
|
||||
custom[key] = entryCustom[key] ?? '';
|
||||
}
|
||||
patch.custom = custom;
|
||||
}
|
||||
return patch as Partial<OntimeEntry>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges an imported rundown into an existing one
|
||||
* - the incoming rundown is the source of truth for entry identity and structure (order + grouping)
|
||||
* - a matched entry of the same type is merged field-by-field: a field the sheet provided overwrites
|
||||
* (even when empty), a field the sheet cannot express (an event's automations, a group's target
|
||||
* duration, an unmapped custom field) is kept from the existing entry
|
||||
* - a new id, or an id whose type changed, takes the incoming entry wholesale
|
||||
* - existing entries absent from the incoming rundown are dropped
|
||||
*/
|
||||
export function mergeRundownPreservingFields(
|
||||
incoming: Readonly<Rundown>,
|
||||
existing: Readonly<Rundown>,
|
||||
providedFields: ImportedFields,
|
||||
): Rundown {
|
||||
const entries: RundownEntries = {};
|
||||
|
||||
for (const [id, incomingEntry] of Object.entries(incoming.entries)) {
|
||||
const existingEntry = existing.entries[id];
|
||||
|
||||
// a new id, or one whose type changed, is not compatible for a merge: take the incoming data
|
||||
if (existingEntry === undefined || existingEntry.type !== incomingEntry.type) {
|
||||
entries[id] = incomingEntry;
|
||||
continue;
|
||||
}
|
||||
|
||||
// merge the sheet's data onto the existing entry through the canonical patch function, which
|
||||
// keeps every unmapped field and infers an event's time strategy from the provided times
|
||||
const merged = applyPatchToEntry(existingEntry, buildImportPatch(incomingEntry, providedFields));
|
||||
// grouping comes from the sheet structure, not a data column: a group owns its children, every
|
||||
// other entry knows its parent
|
||||
const structure = isOntimeGroup(incomingEntry)
|
||||
? { entries: incomingEntry.entries }
|
||||
: { parent: incomingEntry.parent };
|
||||
entries[id] = structuredClone({ ...merged, ...structure });
|
||||
}
|
||||
|
||||
return {
|
||||
id: existing.id,
|
||||
title: existing.title,
|
||||
order: [...incoming.order],
|
||||
flatOrder: [...incoming.flatOrder],
|
||||
revision: existing.revision + 1,
|
||||
entries,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the currently playing event survives a change to its rundown,
|
||||
* i.e. it still exists and is playable in the new version.
|
||||
*/
|
||||
export function isLoadedPlayable(loadedEventId: EntryId, rundown: Readonly<Rundown>): boolean {
|
||||
const entry = rundown.entries[loadedEventId];
|
||||
return entry !== undefined && isOntimeEvent(entry) && isPlayableEvent(entry);
|
||||
}
|
||||
|
||||
/** List of event properties which do not need the rundown to be regenerated */
|
||||
enum RegenerateWhitelist {
|
||||
'id', // adding it for completeness, users cannot change ID
|
||||
|
||||
@@ -11,6 +11,27 @@ export const rundownPatchValidator = [
|
||||
requestValidationFunction,
|
||||
];
|
||||
|
||||
export const rundownImportValidator = [
|
||||
body('mode').isString().isIn(['override', 'merge', 'new']),
|
||||
body('targetRundownId')
|
||||
.if(body('mode').isIn(['override', 'merge']))
|
||||
.isString()
|
||||
.trim()
|
||||
.notEmpty()
|
||||
.withMessage('targetRundownId is required when mode is override or merge'),
|
||||
body('rundown').isObject(),
|
||||
body('rundown.entries').isObject(),
|
||||
body('rundown.order').isArray(),
|
||||
body('rundown.flatOrder').isArray(),
|
||||
body('customFields').isObject(),
|
||||
body('providedFields').optional().isObject(),
|
||||
body('providedFields.event').optional().isArray(),
|
||||
body('providedFields.event.*').isString(),
|
||||
body('providedFields.custom').optional().isArray(),
|
||||
body('providedFields.custom.*').isString(),
|
||||
requestValidationFunction,
|
||||
];
|
||||
|
||||
// #endregion operations on project rundowns ======================
|
||||
// #region operations on rundown entries ==========================
|
||||
|
||||
|
||||
Reference in New Issue
Block a user