Files
wekan/models/userPositionHistory.js
T
Lauri Ojansivu bb4a013939 Collection schemas share one createdAt and one modifiedAt autoValue.
34 schema files wrote the same two autoValue functions out by hand, 65
times in five spellings: createdAt set on insert and $setOnInsert on upsert,
unset otherwise; modifiedAt set on every write. They are now
createdAtAutoValue and modifiedAtAutoValue in models/lib/schemaTimestamps.js,
named by each field as `autoValue: createdAtAutoValue`. models/settings.js,
which may not use import statements, requires them.

Schemas whose rule differs keep their own: changeHistory keeps a createdAt
the caller set, and listSyncCredentials' updatedAt does not unset.

tests/schemaTimestamps runs both functions in SimpleSchema's insert, upsert,
update and validation contexts, and fails when a schema writes either one
out by hand again.

Thanks to xet7 !
2026-11-21 18:27:03 +02:00

486 lines
15 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from '/imports/simpleSchema';
import { ReactiveCache } from '/imports/reactiveCache';
import Boards from '/models/boards';
import Cards from '/models/cards';
import ChecklistItems from '/models/checklistItems';
import Checklists from '/models/checklists';
import Lists from '/models/lists';
import Swimlanes from '/models/swimlanes';
import { createdAtAutoValue } from '/models/lib/schemaTimestamps';
/**
* UserPositionHistory collection - Per-user history of entity movements
* Similar to Activities but specifically for tracking position changes with undo/redo support
*/
const UserPositionHistory = new Mongo.Collection('userPositionHistory');
UserPositionHistory.attachSchema(
new SimpleSchema({
userId: {
/**
* The user who made this change
*/
type: String,
},
boardId: {
/**
* The board where the change occurred
*/
type: String,
},
entityType: {
/**
* Type of entity: 'swimlane', 'list', or 'card'
*/
type: String,
allowedValues: ['swimlane', 'list', 'card', 'checklist', 'checklistItem'],
},
entityId: {
/**
* The ID of the entity that was moved
*/
type: String,
},
actionType: {
/**
* Type of action performed
*/
type: String,
allowedValues: ['move', 'create', 'delete', 'restore', 'archive'],
},
previousState: {
/**
* The state before the change
*/
type: Object,
blackbox: true,
optional: true,
},
newState: {
/**
* The state after the change
*/
type: Object,
blackbox: true,
},
// For easier undo operations, store specific fields
previousSort: {
type: Number,
optional: true,
},
newSort: {
type: Number,
optional: true,
},
previousSwimlaneId: {
type: String,
optional: true,
},
newSwimlaneId: {
type: String,
optional: true,
},
previousListId: {
type: String,
optional: true,
},
newListId: {
type: String,
optional: true,
},
previousBoardId: {
type: String,
optional: true,
},
newBoardId: {
type: String,
optional: true,
},
createdAt: {
/**
* When this history entry was created
*/
type: Date,
autoValue: createdAtAutoValue,
},
// For savepoint/checkpoint feature
isCheckpoint: {
/**
* Whether this is a user-marked checkpoint/savepoint
*/
type: Boolean,
defaultValue: false,
optional: true,
},
checkpointName: {
/**
* User-defined name for the checkpoint
*/
type: String,
optional: true,
},
// For grouping related changes
batchId: {
/**
* ID to group related changes (e.g., moving multiple cards at once)
*/
type: String,
optional: true,
},
// #6478 undo/redo stack: a change that has been undone can be redone until a
// NEW change is recorded (which clears the redo stack). undoneAt orders the
// redo stack (most-recently-undone is redone first).
undone: {
type: Boolean,
defaultValue: false,
optional: true,
},
undoneAt: {
type: Date,
optional: true,
},
}),
);
UserPositionHistory.helpers({
/**
* Get a human-readable description of this change
*/
getDescription() {
const entityName = this.entityType;
const action = this.actionType;
let desc = `${action} ${entityName}`;
if (this.actionType === 'move') {
if (this.previousListId && this.newListId && this.previousListId !== this.newListId) {
desc += ' to different list';
} else if (this.previousSwimlaneId && this.newSwimlaneId && this.previousSwimlaneId !== this.newSwimlaneId) {
desc += ' to different swimlane';
} else if (this.previousSort !== this.newSort) {
desc += ' position';
}
}
return desc;
},
/**
* Can this change be undone?
*/
async canUndo() {
// Can undo if the entity still exists
switch (this.entityType) {
case 'card':
return !!(await ReactiveCache.getCard(this.entityId));
case 'list':
return !!(await ReactiveCache.getList(this.entityId));
case 'swimlane':
return !!(await ReactiveCache.getSwimlane(this.entityId));
case 'checklist':
return !!(await ReactiveCache.getChecklist(this.entityId));
case 'checklistItem':
return !!(await ChecklistItems.findOneAsync(this.entityId));
default:
return false;
}
},
/**
* Soft-delete apply/undo helper (docs/Features/Undo/Undo.md). Marks
* (`deleted=true`) or restores (`deleted=false`) the entity AND its cascade,
* using the history entry's `batchId` as the canonical group so repeated
* undo/redo cycles stay consistent. v1 wires lists (+ their cards); other entity
* types are no-ops here (their delete paths are not yet soft).
*/
async _applyDeleted(deleted) {
if (this.entityType !== 'list') return;
const list = await ReactiveCache.getList(this.entityId);
if (!list) return;
const batchId = this.batchId || list.deleteBatchId || this.entityId;
if (deleted) {
const at = new Date();
const set = { deletedAt: at, deleteBatchId: batchId };
if (this.userId) set.deletedBy = this.userId;
await Lists.updateAsync(list._id, { $set: set });
// Re-mark the list's currently-live cards under the canonical batch.
await Cards.updateAsync(
{ listId: list._id, boardId: list.boardId, deletedAt: null },
{ $set: set },
{ multi: true },
);
} else {
// Restore: $unset all three fields (setting a Date to null trips schema).
const unset = { $unset: { deletedAt: '', deletedBy: '', deleteBatchId: '' } };
await Lists.updateAsync(list._id, unset);
await Cards.updateAsync({ deleteBatchId: batchId }, unset, { multi: true });
}
},
/**
* Undo this change
*/
/**
* PositionHistoryBleed: an entry may act only on an entity that is still on
* the entry's board, for a user who can still write there - and, for a card
* move, on the board it moves to. History documents are data; this is the
* check at execution time, whatever wrote them.
*/
async assertApplicable(destinationBoardIds = [], destinationListId = null) {
if (!Meteor.isServer) return;
const { allowIsBoardMemberWithWriteAccess } = require('/server/lib/utils');
let entityBoardId = null;
switch (this.entityType) {
case 'card': entityBoardId = (await ReactiveCache.getCard(this.entityId) || {}).boardId; break;
case 'list': entityBoardId = (await ReactiveCache.getList(this.entityId) || {}).boardId; break;
case 'swimlane': entityBoardId = (await ReactiveCache.getSwimlane(this.entityId) || {}).boardId; break;
case 'checklist': {
const checklist = await ReactiveCache.getChecklist(this.entityId);
entityBoardId = checklist && (await ReactiveCache.getCard(checklist.cardId) || {}).boardId;
break;
}
case 'checklistItem': {
const item = await ChecklistItems.findOneAsync(this.entityId);
entityBoardId = item && (await ReactiveCache.getCard(item.cardId) || {}).boardId;
break;
}
default: break;
}
const boards = [entityBoardId, ...destinationBoardIds.filter(Boolean)];
// A cross-board card move is recorded under the board it LEFT, so after
// the move (or its undo) the card is on the entry's previous or new board.
const entryBoards = [this.boardId, this.previousBoardId, this.newBoardId].filter(Boolean);
let allowed = !!entityBoardId && entryBoards.includes(entityBoardId);
for (const boardId of boards) {
if (!allowed) break;
allowed = allowIsBoardMemberWithWriteAccess(this.userId, await Boards.findOneAsync(boardId));
}
if (allowed) {
// ListLockBulkBleed: undoing or redoing a card move writes the card in the
// list it is in and into the list it goes to; either may refuse this
// role (#4527), and this runs as server code, past allow/deny.
if (this.entityType === 'card') {
const { assertListsWritable } = require('/server/lib/listPermissionGate');
const card = await ReactiveCache.getCard(this.entityId);
await assertListsWritable(this.userId, await Boards.findOneAsync(card.boardId), [card.listId]);
const destinationBoardId = destinationBoardIds.find(Boolean) || card.boardId;
if (destinationListId) {
await assertListsWritable(this.userId, await Boards.findOneAsync(destinationBoardId), [destinationListId]);
}
}
return;
}
try {
require('/server/lib/canary').tripCanary('history.cross-board', { userId: this.userId });
} catch (e) { /* logging must never break the guard */ }
throw new Meteor.Error('not-authorized', 'This history entry is outside your current access.');
},
async undo() {
if (!(await this.canUndo())) {
throw new Meteor.Error('cannot-undo', 'Entity no longer exists');
}
await this.assertApplicable([this.entityType === 'card' ? this.previousBoardId : null],
this.entityType === 'card' ? this.previousListId : null);
// Soft delete: undo of a 'delete' RESTORES the entity (+ batch); undo of a
// 'restore' re-deletes it. (docs/Features/Undo/Undo.md)
if (this.actionType === 'delete') {
await this._applyDeleted(false);
return;
}
if (this.actionType === 'restore') {
await this._applyDeleted(true);
return;
}
const userId = this.userId;
switch (this.entityType) {
case 'card': {
const card = await ReactiveCache.getCard(this.entityId);
if (card) {
// Restore previous position
const boardId = this.previousBoardId || card.boardId;
const swimlaneId = this.previousSwimlaneId || card.swimlaneId;
const listId = this.previousListId || card.listId;
const sort = this.previousSort !== undefined ? this.previousSort : card.sort;
// History documents are writable from DDP. Re-check the destination at
// execution time so a forged or stale entry cannot cross board bounds.
if (boardId !== card.boardId) {
const destinationBoard = await Boards.findOneAsync(boardId);
if (!destinationBoard || !destinationBoard.hasMember(userId)) {
try {
require('/server/lib/canary').tripCanary(
'history.cross-board',
{ userId },
);
} catch (e) {
/* logging must never break the guard */
}
throw new Meteor.Error(
'not-authorized',
'You do not have access to the destination board.',
);
}
}
await Cards.updateAsync(card._id, {
$set: {
boardId,
swimlaneId,
listId,
sort,
},
});
}
break;
}
case 'list': {
const list = await ReactiveCache.getList(this.entityId);
if (list) {
const sort = this.previousSort !== undefined ? this.previousSort : list.sort;
const swimlaneId = this.previousSwimlaneId || list.swimlaneId;
await Lists.updateAsync(list._id, {
$set: {
sort,
swimlaneId,
},
});
}
break;
}
case 'swimlane': {
const swimlane = await ReactiveCache.getSwimlane(this.entityId);
if (swimlane) {
const sort = this.previousSort !== undefined ? this.previousSort : swimlane.sort;
await Swimlanes.updateAsync(swimlane._id, {
$set: {
sort,
},
});
}
break;
}
case 'checklist': {
const checklist = await ReactiveCache.getChecklist(this.entityId);
if (checklist) {
const sort = this.previousSort !== undefined ? this.previousSort : checklist.sort;
await Checklists.updateAsync(checklist._id, {
$set: {
sort,
},
});
}
break;
}
case 'checklistItem': {
if (typeof ChecklistItems !== 'undefined') {
const item = await ChecklistItems.findOneAsync(this.entityId);
if (item) {
const sort = this.previousSort !== undefined ? this.previousSort : item.sort;
const checklistId = this.previousState?.checklistId || item.checklistId;
await ChecklistItems.updateAsync(item._id, {
$set: {
sort,
checklistId,
},
});
}
}
break;
}
}
},
/**
* #6478: Redo this change — re-apply the NEW position after an undo. Mirrors
* undo() but restores the new* fields instead of the previous* ones.
*/
async redo() {
if (!(await this.canUndo())) {
throw new Meteor.Error('cannot-redo', 'Entity no longer exists');
}
await this.assertApplicable([this.entityType === 'card' ? this.newBoardId : null],
this.entityType === 'card' ? this.newListId : null);
// Soft delete: redo of a 'delete' re-deletes; redo of a 'restore' restores.
if (this.actionType === 'delete') {
await this._applyDeleted(true);
return;
}
if (this.actionType === 'restore') {
await this._applyDeleted(false);
return;
}
switch (this.entityType) {
case 'card': {
const card = await ReactiveCache.getCard(this.entityId);
if (card) {
await Cards.updateAsync(card._id, {
$set: {
boardId: this.newBoardId || card.boardId,
swimlaneId: this.newSwimlaneId || card.swimlaneId,
listId: this.newListId || card.listId,
sort: this.newSort !== undefined ? this.newSort : card.sort,
},
});
}
break;
}
case 'list': {
const list = await ReactiveCache.getList(this.entityId);
if (list) {
await Lists.updateAsync(list._id, {
$set: {
sort: this.newSort !== undefined ? this.newSort : list.sort,
swimlaneId: this.newSwimlaneId || list.swimlaneId,
},
});
}
break;
}
case 'swimlane': {
const swimlane = await ReactiveCache.getSwimlane(this.entityId);
if (swimlane) {
await Swimlanes.updateAsync(swimlane._id, {
$set: { sort: this.newSort !== undefined ? this.newSort : swimlane.sort },
});
}
break;
}
case 'checklist': {
const checklist = await ReactiveCache.getChecklist(this.entityId);
if (checklist) {
await Checklists.updateAsync(checklist._id, {
$set: { sort: this.newSort !== undefined ? this.newSort : checklist.sort },
});
}
break;
}
case 'checklistItem': {
if (typeof ChecklistItems !== 'undefined') {
const item = await ChecklistItems.findOneAsync(this.entityId);
if (item) {
await ChecklistItems.updateAsync(item._id, {
$set: { sort: this.newSort !== undefined ? this.newSort : item.sort },
});
}
}
break;
}
}
},
});
export default UserPositionHistory;