Files
wekan/models/lib/importedTaskPlan.js
T
Lauri Ojansivu ab884547f4 Taiga's blocked state is the card's Blocked flow field, both ways.
WeKan cards have a Blocked flow field with a reason, and the Taiga import
put is_blocked / blocked_note into a "Blocked" custom field, from before the
flow field existed. A normalized task may now carry blocked and
blocked_reason, which the shared import plan writes as the card's flow
field; the importer turns on Board Settings / Card's Blocked display for a
board with a blocked card, since flow fields are off until a board shows
them. Taiga uses it, and its export writes the card's Blocked flow field
(or the custom field of a board imported before) back to is_blocked and
blocked_note.

tests/taigaFormat.test.cjs pinned the custom field and now pins the flow
field, the board display and the export; tests/exportRoundTripFields.test.cjs
holds every format to whether it keeps Blocked.

Thanks to xet7 !
2026-11-20 19:15:34 +02:00

390 lines
18 KiB
JavaScript

'use strict';
// What KanboardCreator writes for one normalized task, decided without a
// database so every external format's mapping can be tested in plain Node.
//
// The normalized task (see models/lib/externalParsers.js) carries, beyond the
// original title/description/column/swimlane/due/owner/tags:
// date_started, date_end, date_creation - dates (see importedDate)
// archived - true for a closed/done-and-archived item
// color - a WeKan card color or a hex value
// due_complete - true when the due date is marked done
// spent_hours - time already spent, in hours
// assignees: [source user key] - more people besides the owner
// checklists: [{ title, items: [{ title, done }] }]
// comments: [{ text, author, authorName, date }]
// watchers: [source user key] - who follows the item
// date_received - when it arrived (receivedAt)
// blocked, blocked_reason - the card's Blocked flow field
// (models/lib/cardFlow.js)
// recurrence - 'daily', 'weekly' or 'monthly'
// (models/lib/recurrenceMap.js)
// email: { direction, from: { name, address }, to: [address], cc: [address],
// subject, messageId, threadIds: [Message-ID], at }
// - a mail message (mbox, .eml,
// Google Takeout Mail): the card is then mail in Board View / Email
// Every one of them is optional; a task without them imports as before.
import { RECURRENCES } from './recurrenceMap.js';
import { importedReactions } from './importedReactions.js';
const HEX6 = /^#?([0-9a-fA-F]{6})$/;
// A source date, or undefined when there is none. Kanboard sends unix seconds
// as a digit string and "0" for "no date"; a date that does not parse is
// dropped rather than stored as an Invalid Date.
export function importedDate(value) {
if (value === undefined || value === null || value === '' || value === false) return undefined;
if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : new Date(value.getTime());
if (typeof value === 'number' || /^\d+$/.test(String(value))) {
const n = Number(value);
if (!Number.isFinite(n) || n <= 0) return undefined;
// Seconds unless the number is already too large to be a seconds value
// for any date before the year 5138.
const date = new Date(n < 1e11 ? n * 1000 : n);
return Number.isNaN(date.getTime()) ? undefined : date;
}
if (typeof value !== 'string') return undefined;
const date = new Date(value);
return Number.isNaN(date.getTime()) ? undefined : date;
}
// A card color WeKan's schema accepts: a palette name, or '#rrggbb'. Source
// hex values without the '#' (Nextcloud Deck's '0082c9') are accepted.
export function importedColor(value, allowedColors = []) {
if (typeof value !== 'string' || !value) return undefined;
const name = value.toLowerCase();
if (allowedColors.includes(name)) return name;
const hex = HEX6.exec(value);
return hex ? `#${hex[1].toLowerCase()}` : undefined;
}
function text(value) {
if (typeof value === 'string') return value;
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
return '';
}
// The card's `email` (models/cards.js) from an imported message, with only
// the keys Board View / Email reads, each a plain value of bounded size: an
// address without spaces or angle brackets, at most MAX_IMPORTED_RECIPIENTS
// of them, a subject and ids of bounded length. A message without a usable
// sender or subject still imports as a card; it is just not mail.
export const MAX_IMPORTED_RECIPIENTS = 50;
const IMPORTED_ADDRESS = /^[^\s@<>(),;:"\\[\]]{1,64}@[A-Za-z0-9.-]{1,253}$/;
const bounded = (value, max) => text(value).replace(/[\r\n]+/g, ' ').trim().slice(0, max);
const importedAddress = value => {
const address = bounded(value, 320).toLowerCase();
return IMPORTED_ADDRESS.test(address) ? address : '';
};
const importedAddresses = values => [...new Set((Array.isArray(values) ? values : [])
.map(importedAddress).filter(Boolean))].slice(0, MAX_IMPORTED_RECIPIENTS);
export function importedEmail(email) {
if (!email || typeof email !== 'object') return undefined;
const fromAddress = importedAddress(email.from && email.from.address);
if (!fromAddress) return undefined;
const at = importedDate(email.at);
// A Message-ID as email to card stores it: "<id@host>" (a parser leaves the
// brackets off, so the sanitizer does not take it for a tag).
const messageIdOf = value => {
const id = bounded(value, 996).replace(/^<|>$/g, '').trim();
return id && !/[\s<>]/.test(id) ? `<${id}>` : '';
};
const messageId = messageIdOf(email.messageId);
const threadIds = [...new Set([messageId, ...(Array.isArray(email.threadIds) ? email.threadIds : [])]
.map(messageIdOf).filter(Boolean))].slice(0, 200);
return {
direction: email.direction === 'out' ? 'out' : 'in',
from: { name: bounded(email.from.name, 200), address: fromAddress },
to: importedAddresses(email.to),
cc: importedAddresses(email.cc),
subject: bounded(email.subject, 255),
...(messageId ? { messageId } : {}),
threadIds,
...(at ? { at } : {}),
};
}
// A comment is attributed to the mapped WeKan user when the source author was
// mapped. Otherwise it is posted by the importing user, and the source
// author's name leads the text so who wrote it is not lost.
export function importedComment(comment, members = {}) {
const body = text(comment && comment.text).trim();
if (!body) return null;
// `author` is the key members are mapped by; `authorName`, when the source
// has one (Jira's account id vs display name), is what a reader sees.
const author = text(comment.author).trim();
const shown = text(comment.authorName).trim() || author;
const userId = (author && members[author]) || null;
// Reactions of a chat message (models/lib/importedReactions.js).
const { reactions, unknown, unmapped } = importedReactions(comment.reactions, members);
return {
text: userId || !shown ? body : `${shown}: ${body}`,
userId,
createdAt: importedDate(comment.date),
...(reactions.length ? { reactions } : {}),
...(unknown ? { reactionsUnknown: unknown } : {}),
...(unmapped ? { reactionsUnmapped: unmapped } : {}),
...(text(comment.ref) ? { ref: text(comment.ref) } : {}),
...(text(comment.reply_to) ? { replyTo: text(comment.reply_to) } : {}),
};
}
// A chat's replies as WeKan's: a comment with `replyTo` (the `ref` of the
// message it answers, on the same card) gets `parentIndex`, the index of the
// top-level comment it belongs under - one level of threading, as WeKan has
// (models/cardComments.js resolveParentId): a reply to a reply goes under the
// first one's parent. A reply whose message is not on the card stays a
// comment of its own, marked "↳ " so a reader still sees it answers one.
export function threadImportedComments(comments) {
const indexOf = new Map();
const out = (Array.isArray(comments) ? comments : []).map(comment => ({ ...comment }));
out.forEach((comment, index) => {
const parent = comment.replyTo && indexOf.has(comment.replyTo) ? indexOf.get(comment.replyTo) : undefined;
if (parent !== undefined && parent !== index) {
comment.parentIndex = out[parent].parentIndex !== undefined ? out[parent].parentIndex : parent;
} else if (comment.replyTo && !/^↳ /.test(comment.text)) {
comment.text = `↳ ${comment.text}`;
}
if (comment.ref && !indexOf.has(comment.ref)) indexOf.set(comment.ref, index);
delete comment.replyTo;
delete comment.ref;
});
return out;
}
// An item may carry `due` (a date) and `assignee` (a source user key): a
// WeKan checklist item has a due date and an assignee too.
export function importedChecklists(checklists, members = {}) {
if (!Array.isArray(checklists)) return [];
return checklists
.map((checklist, index) => ({
title: text(checklist && checklist.title).trim() || 'Checklist',
sort: index,
items: (Array.isArray(checklist && checklist.items) ? checklist.items : [])
.map(item => {
const due = importedDate(item && item.due);
const assignee = item && (typeof item.assignee === 'string' || typeof item.assignee === 'number') ? members[item.assignee] : undefined;
return { title: text(item && item.title).trim(), isFinished: Boolean(item && item.done),
...(due ? { dueAt: due } : {}), ...(assignee ? { assigneeId: assignee } : {}) };
})
.filter(item => item.title)
.map((item, sort) => ({ ...item, sort })),
}))
.filter(checklist => checklist.items.length);
}
// `boardMemberIds` are the new board's members. A source watcher becomes a
// card watcher only when mapped to one of them: watching grants no access,
// but a watcher outside a private board must not receive its notifications.
export function planImportedTask(task, { members = {}, allowedColors = [], boardMemberIds = [], now } = {}) {
const card = {
title: text(task.title) || 'Imported task',
description: text(task.description),
archived: task.archived === true,
};
if (task.requested_by) card.requestedBy = String(task.requested_by);
if (task.assigned_by) card.assignedBy = String(task.assigned_by);
const dates = {
dueAt: task.date_due,
startAt: task.date_started,
endAt: task.date_end,
createdAt: task.date_creation,
receivedAt: task.date_received,
};
for (const [field, value] of Object.entries(dates)) {
const date = importedDate(value);
if (date) card[field] = date;
}
const color = importedColor(task.color, allowedColors);
if (color) card.color = color;
const email = importedEmail(task.email);
if (email) card.email = email;
if (task.due_complete === true && card.dueAt) card.dueComplete = true;
// Blocked, with its reason: the card's Blocked flow field.
if (task.blocked === true) {
card.flow = { blocked: true, ...(text(task.blocked_reason).trim() ? { blockedReason: text(task.blocked_reason).trim().slice(0, 1000) } : {}) };
}
// A repeating source task repeats here too. Its last occurrence counts as
// now: from its creation date, the recurrence job would make a copy of
// every imported card at once.
if (RECURRENCES.includes(task.recurrence)) {
card.recurrenceInterval = task.recurrence;
card.lastRecurrenceAt = now instanceof Date ? new Date(now.getTime()) : new Date();
}
const spent = Number(task.spent_hours);
if (task.spent_hours !== undefined && task.spent_hours !== null && Number.isFinite(spent) && spent > 0) {
card.spentTime = spent;
}
// The owner first, then any further assignees (Deck, GitHub and Asana can
// have several); only source identities that were mapped become members.
const keys = [task.owner_id || task.owner_username || task.owner_name]
.concat(Array.isArray(task.assignees) ? task.assignees : []);
const memberIds = [...new Set(keys
.filter(key => (typeof key === 'string' && key) || (typeof key === 'number' && Number.isFinite(key)))
.map(key => members[key])
.filter(Boolean))];
const watcherKeys = (Array.isArray(task.watchers) ? task.watchers : [])
.filter(key => (typeof key === 'string' && key) || (typeof key === 'number' && Number.isFinite(key)));
const watcherIds = [...new Set(watcherKeys.map(key => members[key]).filter(id => id && boardMemberIds.includes(id)))];
return {
card,
memberIds,
watcherIds,
unwatchedCount: watcherKeys.length - watcherKeys.filter(key => watcherIds.includes(members[key])).length,
checklists: importedChecklists(task.checklists, members),
comments: threadImportedComments((Array.isArray(task.comments) ? task.comments : [])
.map(comment => importedComment(comment, members))
.filter(Boolean)),
};
}
// The board labels for the tasks' tags, one per name. A tag is a name, or
// { name, color } when the source has label colors (Kanri); the first color
// seen for a name wins, and a tag without a usable color is black, as before.
export function planImportedLabels(tasks, allowedColors = []) {
const labels = new Map();
(Array.isArray(tasks) ? tasks : []).forEach(task => {
(Array.isArray(task && task.tags) ? task.tags : []).forEach(tag => {
const name = typeof tag === 'string' ? tag : tag && tag.name;
if (!name || labels.has(name)) return;
labels.set(name, importedColor(tag && tag.color, allowedColors) || 'black');
});
});
return [...labels.entries()].map(([name, color]) => ({ name, color }));
}
// --- Board-level relationships ------------------------------------------------
// Tasks may carry, besides the fields above:
// ref - the source's id for this item
// parent_ref - the ref of its parent item
// dependencies: [{ ref, type }] - links to other items; type is a WeKan
// dependency type (blocks, is-blocked-by,
// related-to, ...)
// custom_fields: { name: value } - values of source custom fields
// Relationships resolve only between items of the same import, after every
// card exists; a reference to anything else is reported, never guessed.
export const MAX_IMPORTED_CUSTOM_FIELDS = 50;
const MAX_CUSTOM_FIELD_NAME = 100;
const MAX_CUSTOM_FIELD_TEXT = 10000;
const DEPENDENCY_TYPES = ['related-to', 'blocks', 'is-blocked-by', 'fixes', 'is-fixed-by', 'duplicates', 'is-duplicated-by'];
function customFieldValue(value) {
if (value === undefined || value === null || value === '') return undefined;
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
if (typeof value === 'boolean') return value;
if (Array.isArray(value)) {
const parts = value.map(customFieldValue).filter(v => v !== undefined).map(String);
return parts.length ? parts.join(', ').slice(0, MAX_CUSTOM_FIELD_TEXT) : undefined;
}
if (typeof value === 'object') {
const named = value.name || value.title || value.value || value.display_value;
return customFieldValue(typeof named === 'object' ? undefined : named);
}
return String(value).slice(0, MAX_CUSTOM_FIELD_TEXT);
}
// One WeKan custom field per distinct source field name, typed from the values
// actually present: all numbers -> number, all booleans -> checkbox, else text.
export function planImportedCustomFields(tasks) {
const values = new Map();
const unsupported = [];
(Array.isArray(tasks) ? tasks : []).forEach(task => {
const fields = task && task.custom_fields;
if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return;
for (const [rawName, rawValue] of Object.entries(fields)) {
const name = String(rawName).trim().slice(0, MAX_CUSTOM_FIELD_NAME);
const value = customFieldValue(rawValue);
if (!name || value === undefined) continue;
if (!values.has(name)) {
if (values.size >= MAX_IMPORTED_CUSTOM_FIELDS) {
if (!unsupported.some(u => u.path === '/custom_fields')) {
unsupported.push({ path: '/custom_fields', reason: `more than ${MAX_IMPORTED_CUSTOM_FIELDS} custom fields; the rest are not imported` });
}
continue;
}
values.set(name, []);
}
values.get(name).push(value);
}
});
const fields = [...values.entries()].map(([name, list]) => ({
name,
type: list.every(v => typeof v === 'number') ? 'number'
: list.every(v => typeof v === 'boolean') ? 'checkbox' : 'text',
}));
return { fields, unsupported };
}
// The [{ name, value }] a card stores for its task, given the planned fields.
export function importedCustomFieldValues(task, fields) {
const source = task && task.custom_fields;
if (!source || typeof source !== 'object' || Array.isArray(source)) return [];
const byName = new Map(fields.map(field => [field.name, field]));
const out = [];
for (const [rawName, rawValue] of Object.entries(source)) {
const field = byName.get(String(rawName).trim().slice(0, MAX_CUSTOM_FIELD_NAME));
let value = customFieldValue(rawValue);
if (!field || value === undefined) continue;
if (field.type === 'text') value = String(value);
out.push({ name: field.name, value });
}
return out;
}
// Parent and dependency links between tasks, as task indexes.
export function planImportedLinks(tasks) {
const list = Array.isArray(tasks) ? tasks : [];
const byRef = new Map();
const unsupported = [];
list.forEach((task, index) => {
const ref = task && task.ref;
if (ref === undefined || ref === null || ref === '') return;
if (byRef.has(String(ref))) {
unsupported.push({ path: `/tasks/${index}/ref`, reason: 'duplicate source id; links resolve to the first item' });
return;
}
byRef.set(String(ref), index);
});
const parents = [];
const dependencies = [];
list.forEach((task, index) => {
if (!task) return;
if (task.parent_ref !== undefined && task.parent_ref !== null && task.parent_ref !== '') {
const parent = byRef.get(String(task.parent_ref));
if (parent === undefined) {
unsupported.push({ path: `/tasks/${index}/parent_ref`, reason: 'parent is not part of this import' });
} else if (parent === index || createsCycle(list, byRef, index, parent)) {
unsupported.push({ path: `/tasks/${index}/parent_ref`, reason: 'parent link would form a cycle' });
} else {
parents.push({ index, parent });
}
}
const deps = [];
(Array.isArray(task.dependencies) ? task.dependencies : []).forEach(dep => {
const target = dep && byRef.get(String(dep.ref));
if (target === undefined) {
unsupported.push({ path: `/tasks/${index}/dependencies`, reason: 'linked item is not part of this import' });
return;
}
if (target === index || deps.some(d => d.target === target)) return;
deps.push({ target, type: DEPENDENCY_TYPES.includes(dep.type) ? dep.type : 'related-to' });
});
if (deps.length) dependencies.push({ index, deps });
});
return { parents, dependencies, unsupported };
}
function createsCycle(list, byRef, index, parent) {
const seen = new Set([index]);
let current = parent;
while (current !== undefined) {
if (seen.has(current)) return true;
seen.add(current);
const ref = list[current] && list[current].parent_ref;
current = ref === undefined || ref === null || ref === '' ? undefined : byRef.get(String(ref));
}
return false;
}