Files
wekan/models/jiraCreator.js
T
Lauri Ojansivu 050df89f06 Requested By and Assigned By: a + to set them, and they survive a round
trip.

Both fields were set by clicking the word "Add". They have the round + that
Members and Assignee use now, opening the same editor the text opens - the
same class, so it is the same button and not a second one that looks like
it.

Checking where else they live turned up a ROUND TRIP THAT LOST THEM, which
is the worst shape this bug takes: the export looks complete and the import
reports success. They were exported by the card PDF, the card Excel and the
board CSV, and imported by nothing - a card exported and imported back had
forgotten who asked for it and who assigned it. models/wekanCreator.js and
the per-menu scoped importer both set them now.

The board's streaming Excel TABLE exported neither, so it gained two
columns: header and value in the same commit, because a header without its
value shifts every column after it.

From other trackers, where the idea has another name: Jira's REPORTER is who
asked for the work, and an issue's AUTHOR on GitHub, Gitea, Forgejo and
GitLab is the same thing. Both arrive as Requested By, as free text, so they
survive an import from a tracker nobody on this board has an account on. A
source with no such field - Trello, CSV - gains nothing, and a negative test
says so.

Also two things the grouping left crooked, both visible on an opened card:

- Members, Assignee and Creator were each a full-width row, so the last two
  fell below the first. The class that made a FIELD full width predates the
  groups; the GROUP is the full-width row now, and its fields share it.
- A field whose title the group header had taken over put its + on the first
  line, level with its neighbours' titles. Every field in a group keeps its
  own title again: the group header names the family and folds it, the
  field's title names the field, and the + starts on the line below it.

tests/requestedAssignedByRoundTrip.test.cjs walks the whole way round - the
card, Card Settings, four exports, three importers - because this was found
by looking rather than by anything failing.

Thanks to xet7 !
2026-08-14 03:28:21 +03:00

267 lines
9.1 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { ReactiveCache } from '/imports/reactiveCache';
import Activities from '/models/activities';
import Boards from './boards';
import Cards from '/models/cards';
import Lists from '/models/lists';
import Swimlanes from '/models/swimlanes';
import Rules from '/models/rules';
import Triggers from '/models/triggers';
import Actions from '/models/actions';
import {
DEFAULT_DEPENDENCY_TYPE,
normalizeDependency,
} from '/models/metadata/dependencies';
// Creates a WeKan board from a Jira export.
//
// Jira has no single "board JSON" like Trello. This importer accepts the JSON
// produced by the Jira Cloud REST search API (or a hand-assembled equivalent):
//
// {
// "board": { "name": "..." }, // optional
// "issues": [ { "key": "PROJ-1", "fields": {
// "summary", "description", "status": { "name" },
// "labels": [], "assignee": { "accountId"|"name"|"emailAddress" },
// "duedate", "created", "updated" } } ],
// "automationRules": [ { "title", "trigger": {...}, "action": {...} } ] // optional
// }
//
// Issue statuses become lists (the Jira workflow columns), each issue becomes a
// card, Jira labels become board labels, and recognizable automation rules are
// mapped to WeKan rules (best effort).
export class JiraCreator {
constructor(data) {
this._nowDate = new Date();
this.members = data && data.membersMapping ? data.membersMapping : {};
this.lists = {};
this.swimlane = null;
// #3392: Jira issue key -> new card id, for mapping issue links to
// card-to-card dependencies ("Red Strings") after all cards are created.
this.cardsByKey = {};
}
_now(dateString) {
if (dateString) return new Date(dateString);
if (!this._nowDate) this._nowDate = new Date();
return this._nowDate;
}
_user(jiraUserId) {
if (jiraUserId && this.members[jiraUserId]) return this.members[jiraUserId];
return Meteor.userId();
}
_issues(data) {
if (Array.isArray(data)) return data;
return data.issues || [];
}
async createBoard(data) {
const title =
(data.board && data.board.name) ||
(this._issues(data)[0] &&
this._issues(data)[0].fields &&
this._issues(data)[0].fields.project &&
this._issues(data)[0].fields.project.name) ||
`Imported Jira Board ${this._now()}`;
const boardToCreate = {
archived: false,
color: 'belize',
createdAt: this._now(),
labels: [],
members: [
{
userId: Meteor.userId(),
wekanId: Meteor.userId(),
isActive: true,
isAdmin: true,
isNoComments: false,
isCommentOnly: false,
swimlaneId: false,
},
],
modifiedAt: this._now(),
permission: 'private',
slug: 'board',
stars: 0,
title,
};
// Jira labels => board labels.
const labelNames = new Set();
for (const issue of this._issues(data)) {
const labels = (issue.fields && issue.fields.labels) || [];
labels.forEach(l => labelNames.add(l));
}
for (const name of labelNames) {
boardToCreate.labels.push({ _id: Random.id(6), color: 'black', name });
}
const boardId = await Boards.direct.insertAsync(boardToCreate);
await Activities.direct.insertAsync({
activityType: 'importBoard',
boardId,
createdAt: this._now(),
source: { id: boardId, system: 'Jira' },
userId: this._user(),
});
return boardId;
}
async createSwimlanes(boardId) {
const swimlaneId = await Swimlanes.direct.insertAsync({
archived: false,
boardId,
createdAt: this._now(),
title: 'Default',
sort: 1,
});
this.swimlane = swimlaneId;
}
async createLists(data, boardId) {
let sort = 0;
for (const issue of this._issues(data)) {
const statusName =
(issue.fields && issue.fields.status && issue.fields.status.name) ||
'Imported';
if (this.lists[statusName]) continue;
const listId = await Lists.direct.insertAsync({
archived: false,
boardId,
createdAt: this._now(),
title: statusName,
sort,
});
this.lists[statusName] = listId;
sort += 1;
}
}
async createCards(data, boardId) {
const board = await ReactiveCache.getBoard(boardId);
for (const issue of this._issues(data)) {
const fields = issue.fields || {};
const statusName = (fields.status && fields.status.name) || 'Imported';
const titleParts = [];
if (issue.key) titleParts.push(`[${issue.key}]`);
if (fields.summary) titleParts.push(fields.summary);
const cardToCreate = {
archived: false,
boardId,
dateLastActivity: this._now(),
description: typeof fields.description === 'string' ? fields.description : '',
listId: this.lists[statusName],
swimlaneId: this.swimlane,
sort: -1,
title: titleParts.join(' ') || 'Imported issue',
userId: this._user(),
labelIds: [],
};
// Jira's REPORTER is WeKan's "Requested By": the person who asked for the
// work, as opposed to the assignee who does it. It is a free-text field
// here, so it takes the display name rather than needing a mapped user -
// which is what makes it survive an import from a Jira nobody on this
// board has an account on.
const reporter = fields.reporter;
if (reporter) {
cardToCreate.requestedBy = reporter.displayName || reporter.name
|| reporter.emailAddress || reporter.accountId || '';
}
if (fields.created) cardToCreate.createdAt = this._now(fields.created);
if (fields.duedate) cardToCreate.dueAt = this._now(fields.duedate);
if (fields.updated) cardToCreate.modifiedAt = this._now(fields.updated);
// Labels.
for (const labelName of fields.labels || []) {
const label = board.getLabel(labelName, 'black');
if (label) cardToCreate.labelIds.push(label._id);
}
// Assignee => member (when mapped).
const assignee = fields.assignee;
if (assignee) {
const key = assignee.accountId || assignee.name || assignee.emailAddress;
if (key && this.members[key]) {
cardToCreate.members = [this.members[key]];
}
}
const cardId = await Cards.direct.insertAsync(cardToCreate);
if (issue.key) this.cardsByKey[issue.key] = cardId;
}
}
// #3392: best-effort mapping of Jira issue links to card-to-card dependencies
// ("Red Strings"). Jira link type names are matched loosely: "blocks" maps to
// blocks / is-blocked-by depending on direction, everything else to related-to.
async createDependencies(data) {
for (const issue of this._issues(data)) {
const fromId = this.cardsByKey[issue.key];
if (!fromId) continue;
const links = (issue.fields || {}).issuelinks || [];
const deps = [];
for (const link of links) {
const typeName = ((link.type && link.type.name) || '').toLowerCase();
let targetKey = null;
let depType = DEFAULT_DEPENDENCY_TYPE;
if (link.outwardIssue) {
targetKey = link.outwardIssue.key;
if (typeName.includes('block')) depType = 'blocks';
} else if (link.inwardIssue) {
targetKey = link.inwardIssue.key;
if (typeName.includes('block')) depType = 'is-blocked-by';
}
if (!targetKey) continue;
const toId = this.cardsByKey[targetKey];
if (!toId || toId === fromId) continue;
if (deps.find(d => d.cardId === toId)) continue;
deps.push(normalizeDependency({ cardId: toId, type: depType }));
}
if (deps.length) {
await Cards.direct.updateAsync(fromId, {
$set: { cardDependencies: deps },
});
}
}
}
// Best-effort: import automation rules that already use, or closely resemble,
// the WeKan { title, trigger, action } shape. Jira's native automation export
// is proprietary; rules that cannot be mapped are skipped.
async createRules(data, boardId) {
const rules = data.automationRules || [];
let imported = 0;
for (const r of rules) {
if (!r || !r.trigger || !r.action) continue;
const triggerId = await Triggers.insertAsync({ ...r.trigger, boardId });
const actionId = await Actions.insertAsync({ ...r.action, boardId });
await Rules.insertAsync({
title: r.title || 'Imported Jira rule',
triggerId,
actionId,
boardId,
});
imported += 1;
}
return imported;
}
async create(board, currentBoardId) {
const isSandstorm =
Meteor.settings && Meteor.settings.public && Meteor.settings.public.sandstorm;
if (isSandstorm && currentBoardId) {
const currentBoard = await ReactiveCache.getBoard(currentBoardId);
await currentBoard.archive();
}
const boardId = await this.createBoard(board);
await this.createSwimlanes(boardId);
await this.createLists(board, boardId);
await this.createCards(board, boardId);
await this.createDependencies(board);
await this.createRules(board, boardId);
return boardId;
}
}