Stored Sync rules bring a card's labels to another board as Card.copy and Card.move do.

Since #1759 a card copied or moved to another board brings its labels: a
label that board lacks is created there when the actor is its admin. The
stored (durable) rule copyCard, move to another board and move-all onto
another board still matched by name only and dropped the rest, so the
durable copy or move was no longer the ordinary one - the parity three
server tests check - and the card lost a label a direct copy would keep.

The durable plans now use the same planCrossBoardLabels with the rule's
actor. The labels to create are saved in the command (copy) or move
(single move, and each move-all unit), so a replay creates nothing twice:
each is pushed only when no label with its id is on that board yet, before
the card that names it is written. In a move-all, a label created for one
card is that board's label for the next, as when Card.move moves them one
by one. Commands saved before this, without the labels, still validate.

The server tests now expect the created label, once across a replay, and
the ordinary copy or move finding it; the card-move test gains the negative
of a mover who is not the new board's admin, where the label is dropped and
its activity removed. The command tests cover the new field, its validation
and an older command without it.

Thanks to xet7 !
This commit is contained in:
Lauri Ojansivu committed 2026-10-10 11:44:19 +03:00
1 parent 650849f98d
commit d1de4a1fe6
8 files changed
+222 -57

No files matched your search

+11 -1
View File
@@ -92,6 +92,9 @@ function prepareRuleCopyCardCommand({ plan, activity, effectId, index, noop = fa
const elsewhere = base.targetBoardId !== base.boardId;
if (elsewhere !== Boolean(crossBoard) || (crossBoard && (!Array.isArray(crossBoard.labelIds) ||
!Array.isArray(crossBoard.customFields)))) fail('invalid');
const createLabels = crossBoard && crossBoard.createLabels ? crossBoard.createLabels : [];
if (!Array.isArray(createLabels) || createLabels.some(label => !label || !text(label._id) ||
typeof label.name !== 'string' || !label.name || !crossBoard.labelIds.includes(label._id))) fail('invalid');
const newCardId = derivedId(base._id, 'card', card._id);
// Card.copy's document.
const doc = { ...copy(card) };
@@ -111,6 +114,8 @@ function prepareRuleCopyCardCommand({ plan, activity, effectId, index, noop = fa
const checklistIdOf = id => derivedId(base._id, 'checklist', id);
const subtaskIdOf = id => derivedId(base._id, 'subtask', id);
command.card = doc;
// #1759: labels the target board lacks, created there before the copy.
command.createLabels = createLabels.map(label => ({ _id: label._id, name: label.name, color: label.color }));
command.coverId = copiedCover;
command.cardActivity = creationActivity(base, doc, destination, createdAt, 'card');
command.attachments = attachments.map(file => ({ sourceId: file._id, attachmentId: attachmentIdFor(base._id, file._id) }));
@@ -158,7 +163,9 @@ function validateRuleCopyCardCommand(row, context) {
const base = identity(context);
const keys = row?.noop ? [...Object.keys(base), 'createdAt', 'noop', 'checksum']
: [...Object.keys(base), 'createdAt', 'noop', 'card', 'coverId', 'cardActivity', 'attachments', 'checklists', 'items',
'subtasks', 'subtaskChecklists', 'subtaskItems', 'comments', 'recorded', 'checksum'];
'subtasks', 'subtaskChecklists', 'subtaskItems', 'comments', 'recorded', 'checksum',
// #1759's labels to create; a command stored before them has none.
...(row && Object.prototype.hasOwnProperty.call(row, 'createLabels') ? ['createLabels'] : [])];
if (!row || Object.keys(row).sort().join(',') !== keys.sort().join(',') ||
Object.entries(base).some(([key, value]) => canonical(row[key]) !== canonical(value)) ||
!(row.createdAt instanceof Date) || typeof row.noop !== 'boolean') fail('command-invalid');
@@ -176,6 +183,9 @@ function validateRuleCopyCardCommand(row, context) {
canonical(creationActivity(base, subtask.card, destination, row.createdAt, 'subtask')) !==
canonical({ receiptId: subtask.receiptId, activity: subtask.activity })) fail('command-invalid');
}
if (row.createLabels !== undefined && (!Array.isArray(row.createLabels) || row.createLabels.some(label =>
!label || !text(label._id) || typeof label.name !== 'string' || !label.name ||
!(card.labelIds || []).includes(label._id)))) fail('command-invalid');
const ownCards = new Set([card._id, ...row.subtasks.map(subtask => subtask.card._id)]);
const checklistIds = new Set([...row.checklists, ...row.subtaskChecklists].map(list => list._id));
if ([...row.checklists, ...row.subtaskChecklists].some(list => !ownCards.has(list.cardId) ||
+14 -3
View File
@@ -142,7 +142,9 @@ function effectsFor({ base, before, after, titles, labelActivities, createdAt, r
// boardId, targetBoardId, cardId } - the command's, or a move-all unit's.
// card - the card (raw document) on the board it leaves;
// target - { boardId, listId, swimlaneId, sort } (sort null: its own);
// mapped - { labelIds, cardNumber, customFields } for the target board;
// mapped - { labelIds, cardNumber, customFields } for the target board,
// and createLabels: the labels it lacks, created there first
// (#1759; only when there are any, so an older move reads the same);
// allowedMemberIds - the target board's active members;
// titles - { boardName, oldBoardName, swimlaneName } for the activity;
// labelActivities - the card's addedLabel activities, { _id, labelId };
@@ -173,7 +175,10 @@ function buildMove({ base, card, target, mapped, allowedMemberIds, titles, label
const savedTitles = { boardName: String(titles.boardName ?? ''), oldBoardName: String(titles.oldBoardName ?? ''),
swimlaneName: String(titles.swimlaneName ?? '') };
const savedLabels = labelActivities.map(row => ({ _id: row._id, labelId: row.labelId ?? null }));
const createLabels = Array.isArray(mapped.createLabels)
? mapped.createLabels.map(label => ({ _id: label?._id, name: label?.name, color: label?.color })) : [];
return { before, after, titles: savedTitles, labelActivities: savedLabels,
...(createLabels.length ? { createLabels } : {}),
effects: effectsFor({ base, before, after, titles: savedTitles, labelActivities: savedLabels, createdAt, redoRows }) };
}
@@ -193,7 +198,11 @@ function validMove(move, base, createdAt) {
!Array.isArray(move.after.fields.labelIds) || !Array.isArray(move.after.fields.customFields) ||
!Number.isSafeInteger(move.after.fields.cardNumber) || canonical(move.after.fields.cardDependencies) !== canonical([]) ||
!move.titles || Object.keys(move.titles).sort().join(',') !== 'boardName,oldBoardName,swimlaneName' ||
!Array.isArray(move.labelActivities)) return false;
!Array.isArray(move.labelActivities) ||
// #1759's labels to create: named, and each one the moved card carries.
(Object.hasOwn(move, 'createLabels') && (!Array.isArray(move.createLabels) || !move.createLabels.length ||
move.createLabels.some(label => !label || !text(label._id) || typeof label.name !== 'string' || !label.name ||
!move.after.fields.labelIds.includes(label._id))))) return false;
// The saved effects are what this move writes (the redo targets are the
// capture's, checked when they are written).
const expected = effectsFor({ base, before: move.before, after: move.after, titles: move.titles,
@@ -224,6 +233,7 @@ function validateRuleMoveBoardCommand(row, context) {
const base = identity(context);
const elsewhere = !!row && Object.hasOwn(row, 'fromBoard');
const keys = [...Object.keys(base), ...(elsewhere ? ['fromBoard'] : []), 'before', 'after', 'titles', 'labelActivities',
...(row && Object.hasOwn(row, 'createLabels') ? ['createLabels'] : []),
'createdAt', 'effects', 'checksum'].sort().join(',');
if (!row || Object.keys(row).sort().join(',') !== keys ||
(elsewhere && (!text(row.fromBoard) || row.fromBoard === base.boardId || row.fromBoard === base.targetBoardId)) ||
@@ -291,7 +301,8 @@ function validateRuleMoveAllBoardCommand(row, context) {
if (checksum !== sha256(canonical(content))) fail('command-invalid');
const seen = new Set();
for (const unit of row.units) {
if (!unit || Object.keys(unit).sort().join(',') !== 'after,before,cardId,effects,labelActivities,titles' ||
if (!unit || Object.keys(unit).filter(key => key !== 'createLabels').sort().join(',') !==
'after,before,cardId,effects,labelActivities,titles' ||
!text(unit.cardId) || seen.has(unit.cardId) || unit.after.place.sort !== unit.before.place.sort ||
!validMove(unit, unitBase(base, unit.cardId), row.createdAt)) fail('command-invalid');
seen.add(unit.cardId);
@@ -11,45 +11,69 @@ import Activities from '/models/activities';
// A card moved to another board keeps its addedLabel activities, re-pointed at
// the new board's label of the same name (#3907's intent). The before-update
// hook that does it ran twice per update, and the second run deleted them all.
//
// #1759: a label the new board lacks is created there when the mover is that
// board's admin, and the card and its activity follow it; anybody else's move
// still drops it, and its activity with it.
async function moveWithLabels({ adminOnTarget }) {
const actor = Random.id(), from = Random.id(), to = Random.id(), cardId = Random.id();
const ids = { fromList: Random.id(), fromLane: Random.id(), toList: Random.id(), toLane: Random.id() };
const members = [{ userId: actor, isAdmin: true, isActive: true }];
const targetMembers = [{ userId: actor, isAdmin: adminOnTarget, isActive: true }];
const context = { userId: actor, isSimulation: false, connection: null, setUserId() {}, unblock() {} };
try {
await Meteor.users.rawCollection().insertOne({ _id: actor, username: `move-labels-${actor}` });
await Boards.rawCollection().insertMany([
{ _id: from, title: 'From', members, labels: [{ _id: 'urgent-from', name: 'Urgent', color: 'red' },
{ _id: 'gone-from', name: 'Gone', color: 'blue' }] },
{ _id: to, title: 'To', members: targetMembers, labels: [{ _id: 'urgent-to', name: 'Urgent', color: 'red' }] },
]);
await Swimlanes.rawCollection().insertMany([{ _id: ids.fromLane, boardId: from, title: 'Lane', sort: 0 },
{ _id: ids.toLane, boardId: to, title: 'Lane', sort: 0 }]);
await Lists.rawCollection().insertMany([{ _id: ids.fromList, boardId: from, title: 'List', sort: 0 },
{ _id: ids.toList, boardId: to, title: 'List', sort: 0 }]);
await Cards.rawCollection().insertOne({ _id: cardId, boardId: from, listId: ids.fromList, swimlaneId: ids.fromLane,
title: 'Pump', sort: 0, archived: false, labelIds: ['urgent-from', 'gone-from'] });
await Activities.rawCollection().insertMany([
{ _id: Random.id(), activityType: 'addedLabel', cardId, boardId: from, labelId: 'urgent-from', userId: actor },
{ _id: Random.id(), activityType: 'addedLabel', cardId, boardId: from, labelId: 'gone-from', userId: actor },
]);
const card = await Cards.findOneAsync(cardId);
await DDP._CurrentMethodInvocation.withValue(context, () => card.move(to, ids.toLane, ids.toList));
const labels = (await Boards.rawCollection().findOne({ _id: to })).labels;
const kept = await Activities.rawCollection().find({ cardId, activityType: 'addedLabel' }, { sort: { labelId: 1 } })
.toArray();
return { labels, labelIds: (await Cards.rawCollection().findOne({ _id: cardId })).labelIds,
kept: kept.map(a => [a.labelId, a.boardId]), to };
} finally {
await Activities.rawCollection().deleteMany({ cardId });
await Cards.rawCollection().deleteMany({ _id: cardId });
await Lists.rawCollection().deleteMany({ boardId: { $in: [from, to] } });
await Swimlanes.rawCollection().deleteMany({ boardId: { $in: [from, to] } });
await Boards.rawCollection().deleteMany({ _id: { $in: [from, to] } });
await Meteor.users.rawCollection().deleteMany({ _id: actor });
}
}
describe('Card move to another board', function () {
this.timeout(30000);
it('keeps the card\'s addedLabel activities, pointed at the new board\'s labels', async function () {
if (!Meteor.isAppTest) this.skip();
const actor = Random.id(), from = Random.id(), to = Random.id(), cardId = Random.id();
const ids = { fromList: Random.id(), fromLane: Random.id(), toList: Random.id(), toLane: Random.id() };
const members = [{ userId: actor, isAdmin: true, isActive: true }];
const context = { userId: actor, isSimulation: false, connection: null, setUserId() {}, unblock() {} };
try {
await Meteor.users.rawCollection().insertOne({ _id: actor, username: `move-labels-${actor}` });
await Boards.rawCollection().insertMany([
{ _id: from, title: 'From', members, labels: [{ _id: 'urgent-from', name: 'Urgent', color: 'red' },
{ _id: 'gone-from', name: 'Gone', color: 'blue' }] },
{ _id: to, title: 'To', members, labels: [{ _id: 'urgent-to', name: 'Urgent', color: 'red' }] },
]);
await Swimlanes.rawCollection().insertMany([{ _id: ids.fromLane, boardId: from, title: 'Lane', sort: 0 },
{ _id: ids.toLane, boardId: to, title: 'Lane', sort: 0 }]);
await Lists.rawCollection().insertMany([{ _id: ids.fromList, boardId: from, title: 'List', sort: 0 },
{ _id: ids.toList, boardId: to, title: 'List', sort: 0 }]);
await Cards.rawCollection().insertOne({ _id: cardId, boardId: from, listId: ids.fromList, swimlaneId: ids.fromLane,
title: 'Pump', sort: 0, archived: false, labelIds: ['urgent-from', 'gone-from'] });
await Activities.rawCollection().insertMany([
{ _id: Random.id(), activityType: 'addedLabel', cardId, boardId: from, labelId: 'urgent-from', userId: actor },
{ _id: Random.id(), activityType: 'addedLabel', cardId, boardId: from, labelId: 'gone-from', userId: actor },
]);
const card = await Cards.findOneAsync(cardId);
await DDP._CurrentMethodInvocation.withValue(context, () => card.move(to, ids.toLane, ids.toList));
assert.deepEqual((await Cards.rawCollection().findOne({ _id: cardId })).labelIds, ['urgent-to']);
const kept = await Activities.rawCollection().find({ cardId, activityType: 'addedLabel' }).toArray();
// The first label maps by position to the new board's label; the second
// has no counterpart there, so its activity goes, as updateActivities does.
assert.deepEqual(kept.map(a => [a.labelId, a.boardId]), [['urgent-to', to]]);
} finally {
await Activities.rawCollection().deleteMany({ cardId });
await Cards.rawCollection().deleteMany({ _id: cardId });
await Lists.rawCollection().deleteMany({ boardId: { $in: [from, to] } });
await Swimlanes.rawCollection().deleteMany({ boardId: { $in: [from, to] } });
await Boards.rawCollection().deleteMany({ _id: { $in: [from, to] } });
await Meteor.users.rawCollection().deleteMany({ _id: actor });
}
const { labels, labelIds, kept, to } = await moveWithLabels({ adminOnTarget: true });
const gone = labels.filter(label => label.name === 'Gone');
assert.equal(gone.length, 1, '#1759: the board admin\'s move creates the missing label there, once');
assert.equal(gone[0].color, 'blue');
assert.deepEqual(labelIds, ['urgent-to', gone[0]._id]);
// Both activities follow their label, by position, as updateActivities does.
assert.deepEqual(kept.sort(), [[gone[0]._id, to], ['urgent-to', to]].sort());
});
it('negative: a mover who is not the new board\'s admin creates no label there', async function () {
if (!Meteor.isAppTest) this.skip();
const { labels, labelIds, kept, to } = await moveWithLabels({ adminOnTarget: false });
assert.deepEqual(labels.map(label => label.name), ['Urgent'], 'no label created');
assert.deepEqual(labelIds, ['urgent-to']);
// The second label has no counterpart there, so its activity goes.
assert.deepEqual(kept, [['urgent-to', to]]);
});
});
+10 -2
View File
@@ -159,8 +159,14 @@ describe('Stored Sync rule copyCard', function () {
const copies = await Cards.rawCollection().find({ boardId: destId }).toArray();
assert.equal(copies.length, 1);
const copied = copies[0];
assert.deepEqual([copied.listId, copied.swimlaneId, copied.labelIds], [destListId, destLaneId, ['urgent-there']],
'that board\'s list, and its label of the same name');
// #1759: the actor is that board's admin, so its missing "Local" label is
// created there - once, the replay below included - as Card.copy does.
const localLabels = async () => ((await Boards.rawCollection().findOne({ _id: destId })).labels || [])
.filter(label => label.name === 'Local');
const [local] = await localLabels();
assert.ok(local && local.color === 'blue', 'the missing label is created on that board');
assert.deepEqual([copied.listId, copied.swimlaneId, copied.labelIds], [destListId, destLaneId, ['urgent-there', local._id]],
'that board\'s list, its label of the same name, and the one created');
assert.ok(Number.isSafeInteger(copied.cardNumber) && copied.cardNumber > 0, 'a number from that board');
const checklists = await Checklists.rawCollection().find({ cardId: copied._id }).toArray();
assert.deepEqual(checklists.map(list => list.boardId), [destId]);
@@ -174,6 +180,7 @@ describe('Stored Sync rule copyCard', function () {
boardId: destId }), 1);
assert.equal(await runStoredSyncRules(input), input.effectId, 'replay');
assert.equal(await Cards.rawCollection().countDocuments({ boardId: destId }), 1);
assert.equal((await localLabels()).length, 1, 'the replay creates no second label');
// Parity: the ordinary Card.copy to that board makes the same card.
const context = { userId: actor, isSimulation: false, connection: null, setUserId() {}, unblock() {} };
@@ -184,6 +191,7 @@ describe('Stored Sync rule copyCard', function () {
const comparable = card => Object.fromEntries(Object.entries(card).filter(([key]) =>
!['_id', 'cardNumber', 'sort', 'createdAt', 'modifiedAt', 'dateLastActivity', 'listEnteredAt', 'coverId'].includes(key)));
assert.deepEqual(comparable(copied), comparable(ordinary), 'the durable copy is the ordinary copy');
assert.equal((await localLabels()).length, 1, 'the ordinary copy found the label the rule created');
assert.equal(ordinary.cardNumber, copied.cardNumber + 1, 'the copy and its replay took one number between them');
// Negative: a destination that has not opted in is refused before anything is copied.
+12 -2
View File
@@ -107,8 +107,15 @@ describe('Stored Sync rule moves to another board', function () {
assert.equal(await runStoredSyncRules(input), input.effectId);
const moved = await Cards.rawCollection().findOne({ _id: ids.card });
// #1759: the actor is that board's admin, so its missing "Local" label is
// created there - once, the replay below included - as Card.move does.
const localLabels = async () => ((await Boards.rawCollection().findOne({ _id: to })).labels || [])
.filter(label => label.name === 'Local');
const [local] = await localLabels();
assert.ok(local && local.color === 'blue', 'the missing label is created on that board');
assert.deepEqual([moved.boardId, moved.listId, moved.swimlaneId, moved.labelIds, moved.members, moved.cardDependencies],
[to, ids.inbox, ids.toLane, ['urgent-to'], [actor], []], 'labels by name, members of that board, no dependencies');
[to, ids.inbox, ids.toLane, ['urgent-to', local._id], [actor], []],
'labels by name or created, members of that board, no dependencies');
assert.ok(Number.isSafeInteger(moved.cardNumber) && moved.cardNumber > 0);
assert.deepEqual([moved.scrum, moved.scrumRevision], [{ issueType: 'Story', sprintId: `sprint-${to}` }, 5],
'that board\'s sprint of the same name; no release there, none kept');
@@ -117,7 +124,8 @@ describe('Stored Sync rule moves to another board', function () {
assert.deepEqual((await Cards.rawCollection().findOne({ _id: ids.blocked })).cardDependencies, [],
'the board left keeps no dependency on it');
const labelled = await Activities.rawCollection().find({ cardId: ids.card, activityType: 'addedLabel' }).toArray();
assert.deepEqual(labelled.map(a => [a.labelId, a.boardId]), [['urgent-to', to]]);
assert.deepEqual(labelled.map(a => [a.labelId, a.boardId]).sort(), [['urgent-to', to], [local._id, to]].sort(),
'both activities follow their label');
const counts = async () => [
await Activities.rawCollection().countDocuments({ cardId: ids.card, activityType: 'moveCardBoard' }),
await ChangeHistory.rawCollection().countDocuments({ entityId: ids.card, group: 'position' }),
@@ -128,6 +136,7 @@ describe('Stored Sync rule moves to another board', function () {
assert.deepEqual(await counts(), [1, 1, 1, 1, 1], 'each record once, not the hook\'s and the command\'s');
assert.equal(await runStoredSyncRules(input), input.effectId, 'replay');
assert.deepEqual(await counts(), [1, 1, 1, 1, 1]);
assert.equal((await localLabels()).length, 1, 'the replay creates no second label');
assert.equal((await Cards.rawCollection().findOne({ _id: ids.card })).cardNumber, moved.cardNumber);
// Parity: the ordinary Card.move of an identical card lands the same way.
@@ -137,6 +146,7 @@ describe('Stored Sync rule moves to another board', function () {
const comparable = doc => Object.fromEntries(Object.entries(doc).filter(([key]) => !['_id', 'title', 'cardNumber',
'listEnteredAt', 'modifiedAt', 'dateLastActivity', 'createdAt'].includes(key)));
assert.deepEqual(comparable(moved), comparable(ordinary), 'the durable move is the ordinary move');
assert.equal((await localLabels()).length, 1, 'the ordinary move found the label the rule created');
// Negative: a destination that opted out keeps the board on direct Sync.
await Boards.rawCollection().updateOne({ _id: to }, { $set: { syncEffectsEnabled: false } });
+49 -13
View File
@@ -699,21 +699,27 @@ async function captureRuleMoveBoard({ plan, saved, action, commandContext, conte
]);
if (!fromBoard || !toBoard || !list || !swimlane || !raw) throw new Error('sync-rule-move-board-target-missing');
return prepareRuleMoveBoardCommand({ ...commandContext, fromBoardId,
...await boardMoveInputs({ raw, model: card, fromBoard, toBoard, target, swimlaneTitle: swimlane.title }),
...await boardMoveInputs({ raw, model: card, fromBoard, toBoard, target, swimlaneTitle: swimlane.title,
actorId: plan.actorId }),
createdAt: new Date(), redoRows: await boardRedoRows(action.boardId, plan.actorId) });
}
// Card.move's choices for one card going to another board, by the same
// lookups: labels by name, custom fields mapped (and shared), the next card
// number, that board's active members; and the card's addedLabel activities.
async function boardMoveInputs({ raw, model, fromBoard, toBoard, target, swimlaneTitle }) {
const names = (fromBoard.labels || []).filter(label => (raw.labelIds || []).includes(label._id)).map(label => label.name);
const labelIds = (toBoard.labels || []).filter(label => label.name && names.includes(label.name)).map(label => label._id);
// lookups: labels by name - and, #1759, the ones that board lacks created
// there when the actor is its admin - custom fields mapped (and shared), the
// next card number, that board's active members; and the card's addedLabel
// activities.
async function boardMoveInputs({ raw, model, fromBoard, toBoard, target, swimlaneTitle, actorId }) {
const labels = crossBoardLabelPlan(fromBoard, raw.labelIds, toBoard, actorId);
// A label created for an earlier card of the same move-all is that board's
// label for the next one, as it is when Card.move moves them one by one.
if (labels.create.length) toBoard.labels = [...(toBoard.labels || []), ...labels.create];
const labelIds = labels.labelIds;
const customFields = await model.mapCustomFieldsToBoard(toBoard._id);
const labelActivities = await Activities.rawCollection().find({ activityType: 'addedLabel', cardId: raw._id },
{ projection: { labelId: 1 }, sort: { _id: 1 } }).toArray();
return { card: raw, target, labelActivities,
mapped: { labelIds, cardNumber: await toBoard.getNextCardNumber(),
mapped: { labelIds, createLabels: labels.create, cardNumber: await toBoard.getNextCardNumber(),
customFields: Array.isArray(customFields) ? customFields : [],
// Its sprint and release by name on that board (models/lib/scrumCopy.js).
scrumPlanning: raw.scrum && (raw.scrum.sprintId || require('/models/lib/scrum').cardReleaseIds(raw.scrum).length)
@@ -771,7 +777,7 @@ export async function runStoredSyncRuleMoveAllBoard({ index, completeDelivery =
const raw = await Cards.rawCollection().findOne({ _id: model._id, boardId: fromBoardId });
if (!raw) continue;
moves.push(await boardMoveInputs({ raw, model, fromBoard, toBoard, swimlaneTitle: lane.title,
target: { boardId: action.boardId, listId: to._id, swimlaneId: lane._id, sort: null } }));
target: { boardId: action.boardId, listId: to._id, swimlaneId: lane._id, sort: null }, actorId: plan.actorId }));
}
}
const candidate = prepareRuleMoveAllBoardCommand({ ...commandContext, moves, createdAt: new Date(), fromBoardId,
@@ -829,6 +835,8 @@ async function applyRuleMoveBoard(command, { guard, completeDelivery, options })
const actor = work => DDP._CurrentMethodInvocation.withValue({ userId: command.actorId, isSimulation: false }, work);
const raw = Cards.rawCollection();
const { place } = command.after;
// The labels the card brings to that board (#1759), before the card names them.
await createPlannedLabels(place.boardId, command.createLabels, actor, guard);
await guard();
if (!await raw.findOne(ruleMoveBoardAfter(command))) {
if (!await raw.findOne(ruleMoveBoardBefore(command))) throw new Error('sync-rule-move-board-changed');
@@ -1035,12 +1043,14 @@ async function captureRuleCopyCard({ plan, action, commandContext, commands }) {
mayReadField(policy.definitions.get(field._id), plan.boardId, policy.adminBoards));
const customFieldIds = readable.map(field => field._id);
// On another board: labels by name, and custom fields mapped (and shared)
// to that board, as Card.copy does.
// to that board, as Card.copy does. #1759: a label that board lacks is
// created there when the actor is its admin, as Card.copy's
// crossBoardLabelIds does; the labels to create are part of the command, so
// a replay creates them once.
let crossBoard = null;
if (targetBoardId !== plan.boardId) {
const names = (sourceBoard.labels || []).filter(label => (source.labelIds || []).includes(label._id))
.map(label => label.name);
crossBoard = { labelIds: filterCopiedLabelIds(board.labels || [], names),
const labels = crossBoardLabelPlan(sourceBoard, source.labelIds, board, plan.actorId);
crossBoard = { labelIds: labels.labelIds, createLabels: labels.create,
customFields: await model.mapCustomFieldsToBoard.call({ customFields: readable }, targetBoardId) };
}
const dependencies = [];
@@ -1078,6 +1088,30 @@ async function captureRuleCopyCard({ plan, action, commandContext, commands }) {
createdAt });
}
// #1759's label plan for a card that goes to another board: Card.copy and
// Card.move's own rule (models/lib/crossBoardLabels.js), with the rule's actor.
function crossBoardLabelPlan(sourceBoard, labelIds, targetBoard, actorId) {
const { planCrossBoardLabels } = require('/models/lib/crossBoardLabels');
const { Random } = require('meteor/random');
return planCrossBoardLabels({
sourceLabels: (sourceBoard && sourceBoard.labels) || [],
labelIds: labelIds || [],
destLabels: (targetBoard && targetBoard.labels) || [],
canCreate: Boolean(targetBoard && actorId && typeof targetBoard.hasAdmin === 'function' && targetBoard.hasAdmin(actorId)),
newId: () => Random.id(6),
});
}
// The labels a command creates on its target board, each once: a label already
// there by its id (an earlier run of the same command) is not added again.
async function createPlannedLabels(boardId, labels, actor, guard) {
for (const label of labels || []) {
await guard();
await actor(() => Boards.updateAsync({ _id: boardId, 'labels._id': { $ne: label._id } },
{ $push: { labels: { _id: label._id, name: label.name, color: label.color } } }));
}
}
export async function runStoredSyncRuleCopyCard({ index, completeDelivery = runStoredSyncActivityDelivery, ...options }) {
const context = executionContext(options), plan = await capture(context);
const invocation = plan.actions[index], action = invocation?.action;
@@ -1127,7 +1161,9 @@ export async function runStoredSyncRuleCopyCard({ index, completeDelivery = runS
if (!await collection.rawCollection().findOne({ _id: doc._id })) await collection.direct.insertAsync(doc, options);
};
// The copy, then its creation activity (which runs the copy's own rules).
// The labels the copy brings to that board (#1759), then the copy, then its
// creation activity (which runs the copy's own rules).
await createPlannedLabels(command.targetBoardId, command.createLabels, actor, guard);
await insertCard(command.card);
await deliver(command.cardActivity);
// Its attachments, each file once, with the History row from the plan.