From d1de4a1fe647fd327deb1c3be9939fb337b5c30b Mon Sep 17 00:00:00 2001 From: Lauri Ojansivu Date: Sat, 10 Oct 2026 11:44:19 +0300 Subject: [PATCH] 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 ! --- server/lib/syncRuleCopyCardCommand.js | 12 ++- server/lib/syncRuleMoveBoardCommand.js | 17 +++- .../tests/cardMoveLabelActivities.tests.js | 96 ++++++++++++------- server/lib/tests/storedRuleCopyCard.tests.js | 12 ++- server/lib/tests/storedRuleMoveBoard.tests.js | 14 ++- server/notifications/storedRulePlans.js | 62 +++++++++--- tests/syncRuleCopyCardCommand.test.cjs | 31 ++++++ tests/syncRuleMoveBoardCommand.test.cjs | 35 +++++++ 8 files changed, 222 insertions(+), 57 deletions(-) diff --git a/server/lib/syncRuleCopyCardCommand.js b/server/lib/syncRuleCopyCardCommand.js index 5af20a828f..fc971c4b18 100644 --- a/server/lib/syncRuleCopyCardCommand.js +++ b/server/lib/syncRuleCopyCardCommand.js @@ -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) || diff --git a/server/lib/syncRuleMoveBoardCommand.js b/server/lib/syncRuleMoveBoardCommand.js index 0e1fbfa704..df1c434a56 100644 --- a/server/lib/syncRuleMoveBoardCommand.js +++ b/server/lib/syncRuleMoveBoardCommand.js @@ -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); diff --git a/server/lib/tests/cardMoveLabelActivities.tests.js b/server/lib/tests/cardMoveLabelActivities.tests.js index eeed1ea71f..7fc3439a60 100644 --- a/server/lib/tests/cardMoveLabelActivities.tests.js +++ b/server/lib/tests/cardMoveLabelActivities.tests.js @@ -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]]); }); }); diff --git a/server/lib/tests/storedRuleCopyCard.tests.js b/server/lib/tests/storedRuleCopyCard.tests.js index e37d1e89f4..6a12640fd4 100644 --- a/server/lib/tests/storedRuleCopyCard.tests.js +++ b/server/lib/tests/storedRuleCopyCard.tests.js @@ -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. diff --git a/server/lib/tests/storedRuleMoveBoard.tests.js b/server/lib/tests/storedRuleMoveBoard.tests.js index f89a40cad5..355771cd11 100644 --- a/server/lib/tests/storedRuleMoveBoard.tests.js +++ b/server/lib/tests/storedRuleMoveBoard.tests.js @@ -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 } }); diff --git a/server/notifications/storedRulePlans.js b/server/notifications/storedRulePlans.js index 6101dc703c..45044c9556 100644 --- a/server/notifications/storedRulePlans.js +++ b/server/notifications/storedRulePlans.js @@ -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. diff --git a/tests/syncRuleCopyCardCommand.test.cjs b/tests/syncRuleCopyCardCommand.test.cjs index db38c959eb..27f73ceb59 100644 --- a/tests/syncRuleCopyCardCommand.test.cjs +++ b/tests/syncRuleCopyCardCommand.test.cjs @@ -94,6 +94,37 @@ test('a copy to another board lives there, with that board\'s labels and custom elsewhere.context), /command-invalid/); }); +test('#1759: the labels another board lacks are created there, once, as Card.copy does', async () => { + const elsewhere = await fixture({ boardId: 'other' }); + const subtaskDocs = [{ title: 'Sub', boardId: 'other', listId: 'next', swimlaneId: 'lane' }]; + const created = { _id: 'new-local', name: 'Local', color: 'blue' }; + const crossBoard = { labelIds: ['urgent-there', 'new-local'], createLabels: [created], customFields: [] }; + const command = elsewhere.prepare({ crossBoard, subtaskDocs }); + assert.deepEqual(command.createLabels, [created], 'the command names the labels to create'); + assert.deepEqual(command.card.labelIds, ['urgent-there', 'new-local'], 'and the copy carries them'); + assert.deepEqual(C.validateRuleCopyCardCommand(command, elsewhere.context), command); + // A command stored before #1759 has no createLabels, and still runs. + const resum = row => { const { checksum, recorded, ...content } = row; + return { ...content, recorded, checksum: sha256(canonical(content)) }; }; + const { createLabels, ...older } = command; + assert.deepEqual(C.validateRuleCopyCardCommand(resum(older), elsewhere.context), resum(older)); + // Negative: a label to create that the copy does not carry, or one without + // a name, is refused when the command is made and when it is read back. + assert.throws(() => elsewhere.prepare({ subtaskDocs, + crossBoard: { ...crossBoard, createLabels: [{ _id: 'stray', name: 'Stray', color: 'red' }] } }), /invalid/); + assert.throws(() => elsewhere.prepare({ subtaskDocs, + crossBoard: { ...crossBoard, createLabels: [{ ...created, name: '' }] } }), /invalid/); + assert.throws(() => C.validateRuleCopyCardCommand(resum({ ...command, + createLabels: [{ _id: 'stray', name: 'Stray', color: 'red' }] }), elsewhere.context), /command-invalid/); + // The runner plans them with Card.copy's own rule and creates each once. + const plans = fs.readFileSync(path.join(ROOT, 'server/notifications/storedRulePlans.js'), 'utf8'); + assert.match(plans, /planCrossBoardLabels\(\{/); + assert.match(plans, /canCreate: Boolean\(targetBoard && actorId && typeof targetBoard\.hasAdmin === 'function' && targetBoard\.hasAdmin\(actorId\)\)/); + assert.match(plans, /Boards\.updateAsync\(\{ _id: boardId, 'labels\._id': \{ \$ne: label\._id \} \}/, + 'a label already there by its id is not added again on a replay'); + assert.match(plans, /await createPlannedLabels\(command\.targetBoardId, command\.createLabels, actor, guard\);\s*await insertCard\(command\.card\);/); +}); + test('negative: tampering and foreign records are refused; a noop stays a noop', async () => { const f = await fixture(); const command = f.prepare(); diff --git a/tests/syncRuleMoveBoardCommand.test.cjs b/tests/syncRuleMoveBoardCommand.test.cjs index 4e8bf12879..01a106930d 100644 --- a/tests/syncRuleMoveBoardCommand.test.cjs +++ b/tests/syncRuleMoveBoardCommand.test.cjs @@ -153,6 +153,41 @@ test('move-all onto another board: one whole move per card, each keeping its sor assert.deepEqual(M.prepareRuleMoveAllBoardCommand({ ...f.context, moves: [], createdAt: new Date(1) }).units, []); }); +test('#1759: the labels the new board lacks are created there before the card names them', async () => { + const f = await fixture(); + const created = { _id: 'local-to', name: 'Local', color: 'blue' }; + const mapped = { labelIds: ['urgent-to', 'local-to'], createLabels: [created], cardNumber: 41, + customFields: [{ _id: 'cf-to', value: 1 }] }; + const command = f.prepare({ mapped }); + assert.deepEqual(command.createLabels, [created]); + assert.deepEqual(command.after.fields.labelIds, ['urgent-to', 'local-to']); + assert.deepEqual(command.effects.labelActivities, [{ _id: 'a1', labelId: 'urgent-to', boardId: 'to' }, + { _id: 'a2', labelId: 'local-to', boardId: 'to' }], 'the second activity follows the created label'); + assert.deepEqual(M.validateRuleMoveBoardCommand(command, f.context), command); + // Nothing to create: the command keeps its older shape, without the key. + assert.ok(!Object.hasOwn(f.prepare(), 'createLabels')); + // Negative: a label to create that the card does not carry, an unnamed one, + // or an empty list written into a command, is refused. + assert.throws(() => f.prepare({ mapped: { ...mapped, createLabels: [{ _id: 'stray', name: 'Stray', color: 'red' }] } }), + /invalid/); + assert.throws(() => f.prepare({ mapped: { ...mapped, createLabels: [{ ...created, name: '' }] } }), /invalid/); + assert.throws(() => M.validateRuleMoveBoardCommand(resum({ ...command, createLabels: [] }), f.context), /command-invalid/); + // Move-all: a unit carries its own labels to create. + const all = await fixture([{ _id: 'all', boardId: 'to', actionType: 'moveAllCardsInList', fromListName: 'Doing', + listName: 'Done' }]); + const unit = { card: all.card, target: { boardId: 'to', listId: 'done', swimlaneId: 'lane-to', sort: null }, mapped, + allowedMemberIds: ['actor'], titles: { boardName: 'To', oldBoardName: 'From', swimlaneName: 'Lane' } }; + const moveAll = M.prepareRuleMoveAllBoardCommand({ ...all.context, moves: [unit], createdAt: new Date(1) }); + assert.deepEqual(moveAll.units[0].createLabels, [created]); + // The runner plans with Card.move's own rule, shares a created label with + // the next card of a move-all, and creates each once before the update. + const plans = fs.readFileSync(path.join(ROOT, 'server/notifications/storedRulePlans.js'), 'utf8'); + assert.match(plans, /const labels = crossBoardLabelPlan\(fromBoard, raw\.labelIds, toBoard, actorId\);/); + assert.match(plans, /if \(labels\.create\.length\) toBoard\.labels = \[\.\.\.\(toBoard\.labels \|\| \[\]\), \.\.\.labels\.create\];/); + assert.match(plans, /await createPlannedLabels\(place\.boardId, command\.createLabels, actor, guard\);\s*await guard\(\);\s*if \(!await raw\.findOne\(ruleMoveBoardAfter\(command\)\)\)/); + assert.equal((plans.match(/actorId: plan\.actorId \}\)/g) || []).length >= 2, true, 'both captures pass the actor'); +}); + test('wiring: move-all onto another board has its runner, and the guard follows its units', () => { const plans = fs.readFileSync(path.join(ROOT, 'server/notifications/storedRulePlans.js'), 'utf8'); assert.match(plans, /moveAllCardsInList: \(\{ invocation \}\) => \(isOtherBoardMoveAll\(invocation\.action, plan\.boardId\)\s*\? runStoredSyncRuleMoveAllBoard : runStoredSyncRuleMoveAll\)/);