Files
wekan/server/models/checklists.js
T
Lauri Ojansivu 6d99ad73c4 Preserve time history and record reversible move reasons
Keep card and checklist activity after deletion, retain card snapshots for
flow reports, and show recorded hour adjustments by their actual author in
Time and its PDF/Excel exports. Record whole positions centrally, including
optional move reasons and direct REST edits. Append undo/redo checkpoints
so blocker intervals and time corrections follow reversals through time.

Audit the open time-related requests against existing features. Exact inline
activity timestamps requested in #1673 already exist in dateDisplay and the
activities template; add a browser regression for that existing behavior.

Reuse established locale terminology for the new compact labels. Labels
outside English and Finnish are low-confidence glossary combinations for
human review; existing translations remain untouched.

Validation: 43 focused Node suites pass. Fifteen Chromium scenarios pass
across flow analytics, time history and existing REST move coverage, including
real chart and Time PDF/Excel exports, undo/redo, retention and access denial.

Thanks to ladistrupl, zombah and xet7 !

Fixes #1598,
Fixes #1673,
2026-09-26 23:00:58 +03:00

383 lines
12 KiB
JavaScript

import { parseDueAt, checklistWithItems } from '/server/lib/checklistDeadlines';
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import { Authentication } from '/server/authentication';
import { sendJsonResult } from '/server/apiMiddleware';
import { ReactiveCache } from '/imports/reactiveCache';
import { requireBoardMutation } from '/models/lib/boardMutationGuard';
import Checklists from '/models/checklists';
import ChecklistItems from '/models/checklistItems';
import Activities from '/models/activities';
import { ensureIndex } from '/server/lib/mongoStartup';
import { backfillBoardIdFromCard } from '/server/lib/denormalizeBoardId';
Meteor.methods({
async moveChecklist(checklistId, newCardId) {
check(checklistId, String);
check(newCardId, String);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in.');
}
const checklist = await ReactiveCache.getChecklist(checklistId);
if (!checklist) {
throw new Meteor.Error('checklist-not-found', 'Checklist not found');
}
const newCard = await ReactiveCache.getCard(newCardId);
if (!newCard) {
throw new Meteor.Error('card-not-found', 'Target card not found');
}
const sourceCard = await ReactiveCache.getCard(checklist.cardId);
const sourceBoard = sourceCard && await ReactiveCache.getBoard(sourceCard.boardId);
const targetBoard = await ReactiveCache.getBoard(newCard.boardId);
requireBoardMutation(this.userId, sourceBoard, 'moveChecklist:source', Meteor);
requireBoardMutation(this.userId, targetBoard, 'moveChecklist:destination', Meteor);
const activities = await ReactiveCache.getActivities({ checklistId });
for (const activity of activities) {
await Activities.updateAsync(activity._id, {
$set: {
cardId: newCardId,
},
});
}
const checklistItems = await ReactiveCache.getChecklistItems({ checklistId });
for (const checklistItem of checklistItems) {
await ChecklistItems.updateAsync(checklistItem._id, {
$set: {
cardId: newCardId,
},
});
}
await Checklists.updateAsync(checklistId, {
$set: {
cardId: newCardId,
},
});
return checklistId;
},
});
// --- Denormalized boardId (see models/checklists.js schema) -----------------
// Set boardId from the card on insert, and re-sync it whenever the checklist is
// moved to another card, so the board publication can filter checklists by a
// single reactive cursor on boardId and still see checklists on newly added
// cards. Server-authoritative: the board publication runs on the server, so the
// server document carrying boardId is what matters.
Checklists.before.insert(async (userId, doc) => {
if (!doc.boardId && doc.cardId) {
const card = await ReactiveCache.getCard(doc.cardId);
if (card) {
doc.boardId = card.boardId;
}
}
});
Checklists.before.update(async (userId, doc, fieldNames, modifier) => {
const newCardId = modifier && modifier.$set && modifier.$set.cardId;
if (newCardId && newCardId !== doc.cardId) {
const card = await ReactiveCache.getCard(newCardId);
if (card) {
modifier.$set.boardId = card.boardId;
}
}
});
Meteor.startup(async () => {
await ensureIndex(Checklists, { modifiedAt: -1 });
await ensureIndex(Checklists, { cardId: 1, createdAt: 1 });
await ensureIndex(Checklists, { boardId: 1 });
// Backfill existing rows in the background (memory-safe, idempotent) so it
// never blocks or OOMs startup. New checklists already get boardId on insert.
Meteor.defer(() => {
backfillBoardIdFromCard(Checklists, { label: 'checklists' });
});
});
Checklists.after.insert(async (userId, doc) => {
const card = await ReactiveCache.getCard(doc.cardId);
if (!card) {
console.warn('[Checklists.after.insert] Card not found for cardId:', doc.cardId, '— skipping addChecklist activity.');
return;
}
await Activities.insertAsync({
userId,
activityType: 'addChecklist',
cardId: doc.cardId,
boardId: card.boardId,
checklistId: doc._id,
checklistName: doc.title,
listId: card.listId,
swimlaneId: card.swimlaneId,
});
});
Checklists.before.remove(async (userId, doc) => {
try {
// #1598: keep the checklist's timestamped activity trail.
// When a whole list/card is deleted, the parent card may already be gone by
// the time its checklists are removed (cascade delete). Skip the activity
// then instead of dereferencing an undefined card, which would throw an
// unhandled rejection and crash SyncedCron.
const card = await ReactiveCache.getCard(doc.cardId);
if (!card) {
console.warn('[Checklists.before.remove] Card not found for cardId:', doc.cardId, '— skipping removeChecklist activity.');
return;
}
await Activities.insertAsync({
userId,
activityType: 'removeChecklist',
cardId: doc.cardId,
boardId: card.boardId,
checklistId: doc._id,
checklistName: doc.title,
listId: card.listId,
swimlaneId: card.swimlaneId,
});
} catch (e) {
console.error('[Checklists.before.remove] Error while processing checklist deletion for doc._id:', doc._id, e);
}
});
WebApp.handlers.get(
'/api/boards/:boardId/cards/:cardId/checklists',
async function(req, res) {
const paramBoardId = req.params.boardId;
const paramCardId = req.params.cardId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
const card = await ReactiveCache.getCard({
_id: paramCardId,
boardId: paramBoardId,
});
if (!card) {
sendJsonResult(res, {
code: 404,
data: { error: 'Card not found or does not belong to the specified board' },
});
return;
}
const checklists = await Promise.all((await ReactiveCache.getChecklists({ cardId: paramCardId }, { sort: ['sort'] }))
.map(doc => checklistWithItems(doc, ReactiveCache)));
if (checklists) {
sendJsonResult(res, {
code: 200,
data: checklists,
});
} else {
sendJsonResult(res, {
code: 500,
});
}
},
);
WebApp.handlers.get(
'/api/boards/:boardId/cards/:cardId/checklists/:checklistId',
async function(req, res) {
const paramBoardId = req.params.boardId;
const paramChecklistId = req.params.checklistId;
const paramCardId = req.params.cardId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
const card = await ReactiveCache.getCard({
_id: paramCardId,
boardId: paramBoardId,
});
if (!card) {
sendJsonResult(res, {
code: 404,
data: { error: 'Card not found or does not belong to the specified board' },
});
return;
}
const checklist = await ReactiveCache.getChecklist({
_id: paramChecklistId,
cardId: paramCardId,
});
if (checklist) {
sendJsonResult(res, {
code: 200,
data: await checklistWithItems(checklist, ReactiveCache),
});
} else {
sendJsonResult(res, {
code: 500,
});
}
},
);
WebApp.handlers.post(
'/api/boards/:boardId/cards/:cardId/checklists',
async function(req, res) {
const paramBoardId = req.params.boardId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const paramCardId = req.params.cardId;
const card = await ReactiveCache.getCard({
_id: paramCardId,
boardId: paramBoardId,
});
if (!card) {
sendJsonResult(res, {
code: 404,
data: { error: 'Card not found or does not belong to the specified board' },
});
return;
}
const deadline = parseDueAt(req.body);
if (deadline.error) {
sendJsonResult(res, { code: 400, data: { error: deadline.error } });
return;
}
const id = await Checklists.insertAsync({
title: req.body.title,
...(deadline.dueAt ? { dueAt: deadline.dueAt } : {}),
cardId: paramCardId,
sort: 0,
});
if (id) {
let items = req.body.items || [];
if (typeof items === 'string') {
if (items === '') {
items = [];
} else {
items = [items];
}
}
for (const [idx, item] of items.entries()) {
await ChecklistItems.insertAsync({
cardId: paramCardId,
checklistId: id,
title: item,
sort: idx,
});
}
sendJsonResult(res, {
code: 200,
data: {
_id: id,
},
});
} else {
sendJsonResult(res, {
code: 400,
});
}
},
);
// #1037: GET/POST/DELETE were exposed for a checklist but there was no way to
// rename one over the REST API - a client had to delete and re-create it,
// losing the checklistId and its items. Mirrors the DELETE handler right below
// it (same lookup / auth), and lists.js's own PUT for the same "edit the
// title of a thing on the board" shape. `title` and optional `dueAt` are accepted: the other
// per-checklist toggles (hideCheckedChecklistItems, resetInterval, etc.) are
// not exposed anywhere over the REST API yet and are out of scope here.
WebApp.handlers.put(
'/api/boards/:boardId/cards/:cardId/checklists/:checklistId',
async function(req, res) {
const paramBoardId = req.params.boardId;
const paramCardId = req.params.cardId;
const paramChecklistId = req.params.checklistId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const card = await ReactiveCache.getCard({
_id: paramCardId,
boardId: paramBoardId,
});
if (!card) {
sendJsonResult(res, {
code: 404,
data: { error: 'Card not found or does not belong to the specified board' },
});
return;
}
const checklist = await ReactiveCache.getChecklist({
_id: paramChecklistId,
cardId: paramCardId,
});
if (!checklist) {
sendJsonResult(res, {
code: 404,
data: { error: 'Checklist not found or does not belong to the specified card' },
});
return;
}
const deadline = parseDueAt(req.body);
const hasTitle = Object.prototype.hasOwnProperty.call(req.body || {}, 'title');
if (deadline.error || (hasTitle && (typeof req.body.title !== 'string' || !req.body.title.trim())) || (!hasTitle && !Object.prototype.hasOwnProperty.call(deadline, 'dueAt'))) {
sendJsonResult(res, { code: 400, data: { error: deadline.error || 'title or dueAt is required' } });
return;
}
const modifier = {};
if (hasTitle) modifier.$set = { title: req.body.title };
if (Object.prototype.hasOwnProperty.call(deadline, 'dueAt')) {
if (deadline.dueAt === null) modifier.$unset = { dueAt: '' };
else modifier.$set = { ...modifier.$set, dueAt: deadline.dueAt };
}
await Checklists.direct.updateAsync({ _id: paramChecklistId, cardId: paramCardId }, modifier);
sendJsonResult(res, {
code: 200,
data: {
_id: paramChecklistId,
},
});
},
);
WebApp.handlers.delete(
'/api/boards/:boardId/cards/:cardId/checklists/:checklistId',
async function(req, res) {
const paramBoardId = req.params.boardId;
const paramCardId = req.params.cardId;
const paramChecklistId = req.params.checklistId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const card = await ReactiveCache.getCard({
_id: paramCardId,
boardId: paramBoardId,
});
if (!card) {
sendJsonResult(res, {
code: 404,
data: { error: 'Card not found or does not belong to the specified board' },
});
return;
}
const checklist = await ReactiveCache.getChecklist({
_id: paramChecklistId,
cardId: paramCardId,
});
if (!checklist) {
sendJsonResult(res, {
code: 404,
data: { error: 'Checklist not found or does not belong to the specified card' },
});
return;
}
await Checklists.removeAsync({ _id: paramChecklistId });
sendJsonResult(res, {
code: 200,
data: {
_id: paramChecklistId,
},
});
},
);