Files
wekan/models/boards.js
T
Lauri Ojansivu c50d7b4ea7 Authorize subtask deposit reads and destination writes
Remove unvalidated deposit and null board IDs from source-card scope. Publish deposit content beneath its own reactive visibility-filtered board cursor, applying destination assignment restrictions and reactive card children. Filter status counts by visible assigned scopes.

Require destination write access before pointer changes and subtask landing structures, and deny client pointer rename bypasses. Summarize blocked writes in Problems. Positive decisions, scope/dispatcher inventory and existing subtask/status suites pass; browser regression syntax-check passes with live execution pending.

Thanks to Wenhao Wu, Southeast University and xet7 !
2026-09-14 12:09:35 +03:00

3245 lines
101 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check, Match } from 'meteor/check';
import { Random } from 'meteor/random';
import { ReactiveCache } from '/imports/reactiveCache';
const { notHelperBoardTitle } = require('/models/lib/helperBoards');
const { boardVisibilitySelectors } = require('/models/lib/boardVisibilitySelectors');
const boardViewSettings = require('/models/lib/boardViewSettings');
import escapeForRegex from 'escape-string-regexp';
import CustomFields from './customFields';
import {
TYPE_BOARD,
TYPE_TEMPLATE_BOARD,
TYPE_TEMPLATE_CONTAINER,
} from '/config/const';
import { BOARD_COLORS, LABEL_COLORS } from '/models/metadata/colors';
import { isHexColor } from '/models/lib/contrastColor';
import { isValidCustomColors } from '/models/lib/themeCategories';
import Actions from '/models/actions';
import Cards from '/models/cards';
import Integrations from '/models/integrations';
import Lists from '/models/lists';
import Rules from '/models/rules';
import Swimlanes from '/models/swimlanes';
import Triggers from '/models/triggers';
import { Counters, incrementCounterAsync } from '/models/counters';
import { pullMemberById } from '/server/lib/removeMember';
import getSlug from 'limax';
import { findWhere, where, groupBy } from '/imports/lib/collectionHelpers';
import {
cardsDueInBetweenSelector,
cardsInIntervalSelector,
cardsReceivedInBetweenSelector,
cardsEndInBetweenSelector,
} from '/models/lib/calendarFilter';
import { generateUniversalAttachmentUrl } from '/models/lib/universalUrlGenerator';
import { buildCardSearchOr, matchingCommentCardIds } from '/models/lib/cardSearch';
const { SimpleSchema } = require('/imports/simpleSchema');
const getTAPi18n = () => require('/imports/i18n').TAPi18n;
function getTranslatedString(key, fallback, options) {
const i18n = getTAPi18n && getTAPi18n();
if (!i18n || !i18n.i18n) {
return fallback;
}
const translated = i18n.__(key, options);
return typeof translated === 'string' ? translated : fallback;
}
function sanitizeBoardMembers(members) {
return (members || []).map(member => ({
userId: member.userId,
isAdmin: !!member.isAdmin,
isActive: member.isActive !== false,
isNoComments: !!member.isNoComments,
isCommentOnly: !!member.isCommentOnly,
isWorker: !!member.isWorker,
isNormalAssignedOnly: !!member.isNormalAssignedOnly,
isCommentAssignedOnly: !!member.isCommentAssignedOnly,
isReadOnly: !!member.isReadOnly,
isReadAssignedOnly: !!member.isReadAssignedOnly,
}));
}
// const escapeForRegex = require('escape-string-regexp');
const Boards = new Mongo.Collection('boards');
/**
* This is a Board.
*/
Boards.attachSchema(
new SimpleSchema({
title: {
/**
* The title of the board
*/
type: String,
},
slug: {
/**
* The title slugified.
*/
type: String,
// eslint-disable-next-line consistent-return
autoValue() {
// In some cases (Chinese and Japanese for instance) the `getSlug` function
// return an empty string. This is causes bugs in our application so we set
// a default slug in this case.
// Improvment would be to change client URL after slug is changed
const title = this.field('title');
if (title.isSet && !this.isSet) {
let slug = 'board';
slug = getSlug(title.value) || slug;
return slug;
}
},
},
archived: {
/**
* Is the board archived?
*/
type: Boolean,
// eslint-disable-next-line consistent-return
autoValue() {
if (this.isInsert && !this.isSet) {
return false;
}
},
},
archivedAt: {
/**
* Latest archiving time of the board
*/
type: Date,
optional: true,
},
createdAt: {
/**
* Creation time of the board
*/
type: Date,
// eslint-disable-next-line consistent-return
autoValue() {
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return { $setOnInsert: new Date() };
} else {
this.unset();
}
},
},
// XXX Inconsistent field naming
modifiedAt: {
/**
* Last modification time of the board
*/
type: Date,
optional: true,
// eslint-disable-next-line consistent-return
autoValue() {
if (this.isInsert || this.isUpsert || this.isUpdate) {
return new Date();
} else {
this.unset();
}
},
},
// De-normalized number of users that have starred this board
stars: {
/**
* How many stars the board has
*/
type: Number,
// eslint-disable-next-line consistent-return
autoValue() {
if (this.isInsert) {
return 0;
}
},
},
// De-normalized label system
labels: {
/**
* List of labels attached to a board
*/
type: Array,
optional: true,
/* Commented out, so does not create labels to new boards.
// eslint-disable-next-line consistent-return
autoValue() {
if (this.isInsert && !this.isSet) {
const colors = Boards.simpleSchema()._schema['labels.$.color']
.allowedValues;
const defaultLabelsColors = [...colors].splice(0, 6);
return defaultLabelsColors.map(color => ({
color,
_id: Random.id(6),
name: '',
}));
}
},
*/
},
'labels.$': {
type: Object,
},
'labels.$._id': {
/**
* Unique id of a label
*/
// We don't specify that this field must be unique in the board because that
// will cause performance penalties and is not necessary since this field is
// always set on the server.
// XXX Actually if we create a new label, the `_id` is set on the client
// without being overwritten by the server, could it be a problem?
type: String,
},
'labels.$.name': {
/**
* Name of a label
*/
type: String,
optional: true,
},
'labels.$.color': {
/**
* color of a label.
*
* Can be amongst `green`, `yellow`, `orange`, `red`, `purple`,
* `blue`, `sky`, `lime`, `pink`, `black`,
* `silver`, `peachpuff`, `crimson`, `plum`, `darkgreen`,
* `slateblue`, `magenta`, `gold`, `navy`, `gray`,
* `saddlebrown`, `paleturquoise`, `mistyrose`, `indigo`
*
* Since #5514 a label color may also be a custom '#rrggbb' hex chosen
* from the color wheel, in addition to the named palette colors above.
*/
type: String,
custom() {
const v = this.value;
if (v === undefined || v === null || v === '') return undefined;
if (LABEL_COLORS.includes(v) || isHexColor(v)) return undefined;
return 'notAllowed';
},
},
'labels.$.dueAt': {
/**
* Optional due date carried by the label itself (#2802), e.g. a
* "milestone" label such as "Sprint 1" that expires on a given date.
* Unset by default so existing labels/boards are unaffected. Filtering
* cards by this label is the existing label filter; no separate
* Milestone object or filter UI is added for this.
*/
type: Date,
optional: true,
},
// XXX We might want to maintain more informations under the member sub-
// documents like de-normalized meta-data (the date the member joined the
// board, the number of contributions, etc.).
members: {
/**
* List of members of a board
*/
type: Array,
// eslint-disable-next-line consistent-return
autoValue() {
if (this.isInsert && !this.isSet) {
return [
{
userId: this.userId,
isAdmin: true,
isActive: true,
isNoComments: false,
isCommentOnly: false,
isWorker: false,
},
];
}
},
},
'members.$': {
type: Object,
},
'members.$.userId': {
/**
* The uniq ID of the member
*/
type: String,
},
'members.$.isAdmin': {
/**
* Is the member an admin of the board?
*/
type: Boolean,
},
'members.$.isActive': {
/**
* Is the member active?
*/
type: Boolean,
},
'members.$.isNoComments': {
/**
* Is the member not allowed to make comments
*/
type: Boolean,
optional: true,
},
'members.$.isCommentOnly': {
/**
* Is the member only allowed to comment on the board
*/
type: Boolean,
optional: true,
},
'members.$.isWorker': {
/**
* Is the member only allowed to move card, assign himself to card and comment
*/
type: Boolean,
optional: true,
},
'members.$.isNormalAssignedOnly': {
/**
* Is the member only allowed to see assigned cards (Normal permission)
*/
type: Boolean,
optional: true,
},
'members.$.isCommentAssignedOnly': {
/**
* Is the member only allowed to comment on assigned cards
*/
type: Boolean,
optional: true,
},
'members.$.isReadOnly': {
/**
* Is the member only allowed to read the board (no comments, no editing)
*/
type: Boolean,
optional: true,
},
'members.$.isReadAssignedOnly': {
/**
* Is the member only allowed to read assigned cards (no comments, no editing)
*/
type: Boolean,
optional: true,
},
permission: {
/**
* visibility of the board
*/
type: String,
allowedValues: ['public', 'private'],
},
orgs: {
/**
* the list of organizations that a board belongs to
*/
type: Array,
optional: true,
},
'orgs.$': {
type: Object,
},
'orgs.$.orgId':{
/**
* The uniq ID of the organization
*/
type: String,
},
'orgs.$.orgDisplayName':{
/**
* The display name of the organization
*/
type: String,
},
'orgs.$.isActive': {
/**
* Is the organization active?
*/
type: Boolean,
},
teams: {
/**
* the list of teams that a board belongs to
*/
type: Array,
optional: true,
},
'teams.$': {
type: Object,
},
'teams.$.teamId':{
/**
* The uniq ID of the team
*/
type: String,
},
'teams.$.teamDisplayName':{
/**
* The display name of the team
*/
type: String,
},
'teams.$.isActive': {
/**
* Is the team active?
*/
type: Boolean,
},
domains: {
/**
* #5850: the list of email-address domains a board is shared with. Every
* user whose primary email is in one of these domains gets board access.
*/
type: Array,
optional: true,
},
'domains.$': {
type: Object,
},
'domains.$.domain': {
/**
* The email-address domain, e.g. example.com
*/
type: String,
},
'domains.$.isActive': {
/**
* Is the domain share active?
*/
type: Boolean,
},
importUsernames: {
/**
* Usernames of imported (e.g. Trello) board members that were not mapped
* to an existing WeKan user during import. Kept so an admin can map them
* to real users later (People panel -> user -> Imported Usernames), after
* which future imports of this board auto-map.
*/
type: Array,
optional: true,
defaultValue: [],
},
'importUsernames.$': {
type: String,
},
color: {
/**
* The color of the board.
*/
type: String,
allowedValues: BOARD_COLORS,
// eslint-disable-next-line consistent-return
autoValue() {
if (this.isInsert && !this.isSet) {
return BOARD_COLORS[0];
}
},
},
// #2489: WIP limit GROUPS - a shared limit across two or more of this
// board's lists together (e.g. "these three middle columns together may
// never hold more than 10 cards total"), on top of the existing per-list
// `wipLimit` in models/lists.js. Deliberately its own small array rather
// than a second WIP-tracking system: the combined count and "over limit"
// decision are pure arithmetic (models/lib/wipLimitGroupDecision.js) and
// the visual indicator it drives is the SAME `.highlight` styling the
// per-list limit already uses (client/components/lists/listHeader.js).
wipLimitGroups: {
/**
* List of board-level WIP limit groups.
*/
type: Array,
optional: true,
},
'wipLimitGroups.$': {
type: Object,
},
'wipLimitGroups.$._id': {
/**
* Unique id of a WIP limit group.
*/
type: String,
},
'wipLimitGroups.$.name': {
/**
* Optional display name for the group (e.g. "Middle columns").
*/
type: String,
optional: true,
},
'wipLimitGroups.$.listIds': {
/**
* The _ids of the board's lists that share this group's limit. At least
* two - a "group" of one is just that list's own individual wipLimit.
*/
type: Array,
},
'wipLimitGroups.$.listIds.$': {
type: String,
},
'wipLimitGroups.$.limit': {
/**
* The combined card-count limit shared by every list in listIds.
*/
type: Number,
defaultValue: 1,
},
'wipLimitGroups.$.enabled': {
/**
* Whether this group's limit is currently in effect. Kept (rather than
* deleting the group) so a temporarily-disabled group's list selection
* and limit are not lost.
*/
type: Boolean,
defaultValue: true,
},
customThemeColors: {
/**
* Optional custom colors for the "flat" (1 color) and "clear" (2 colors,
* a color slide) theme categories — see docs/Theme/Theme.md. Each entry is a
* #rrggbb hex validated on the server; dark/special themes never store these.
* Absent = the named `color` theme's stock colors.
*/
type: Array,
optional: true,
},
'customThemeColors.$': {
type: String,
// Enforced on client AND server by collection2 — a value that is not a plain
// #rrggbb hex can never be stored, so there is no CSS-injection surface.
custom() {
return /^#[0-9a-fA-F]{6}$/.test(this.value) ? undefined : 'notAHexColor';
},
},
backgroundImageURL: {
/**
* The background image URL of the board.
*/
type: String,
optional: true,
},
backgroundImageId: {
/**
* The id of the active board background attachment (a board-level
* Attachment with meta.source === 'board-background'), when the active
* background is an uploaded/imported image rather than an external URL.
*/
type: String,
optional: true,
},
allowsCardCounterList: {
/**
* Show card counter per list
*/
type: Boolean,
defaultValue: false,
},
cardAging: {
/**
* #3984: Visually fade cards that have not been touched for a while
* (Trello-style "card aging"), based on the card's dateLastActivity.
*/
type: Boolean,
defaultValue: false,
},
showDependencies: {
/**
* #3392: PI Program Board "Red Strings". When true, draw colored
* connection lines between cards that have cardDependencies, SAFe
* PI-planning program board style.
*/
type: Boolean,
defaultValue: false,
},
cardAgingDays1: {
/** #3984: days of inactivity for the first (lightest) card-aging fade tier. */
type: Number,
defaultValue: 7,
},
cardAgingDays2: {
/** #3984: days of inactivity for the second card-aging fade tier. */
type: Number,
defaultValue: 14,
},
cardAgingDays3: {
/** #3984: days of inactivity for the third (heaviest) card-aging fade tier. */
type: Number,
defaultValue: 28,
},
allowsBoardMemberList: {
/**
* Show board member list
*/
type: Boolean,
defaultValue: false,
},
description: {
/**
* The description of the board
*/
type: String,
optional: true,
},
subtasksDefaultBoardId: {
/**
* The default board ID assigned to subtasks.
*/
type: String,
optional: true,
defaultValue: null,
},
migrationVersion: {
/**
* The migration version of the board structure.
* New boards are created with the latest version and don't need migration.
*/
type: Number,
// eslint-disable-next-line consistent-return
autoValue() {
if (this.isInsert && !this.isSet) {
return 1; // Latest migration version for new boards
}
},
},
subtasksDefaultListId: {
/**
* The default List ID assigned to subtasks.
*/
type: String,
optional: true,
defaultValue: null,
},
dateSettingsDefaultBoardId: {
type: String,
optional: true,
defaultValue: null,
},
dateSettingsDefaultListId: {
type: String,
optional: true,
defaultValue: null,
},
allowsSubtasks: {
/**
* Does the board allows subtasks?
*/
type: Boolean,
defaultValue: true,
},
allowsSubtasksOnMinicard: {
/**
* Does the board allows subtasks on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsAttachments: {
/**
* Does the board allows attachments?
*/
type: Boolean,
defaultValue: true,
},
allowsAttachmentsOnMinicard: {
/**
* Does the board allows attachments on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsChecklists: {
/**
* Does the board allows checklists?
*/
type: Boolean,
defaultValue: true,
},
allowsChecklistsOnMinicard: {
/**
* Does the board allows checklists on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsCustomFields: {
/** Show assigned custom fields on opened cards? */
type: Boolean,
optional: true,
defaultValue: true,
},
allowsCustomFieldsOnMinicard: {
/** Show assigned custom fields on minicards? Opt-in by default. */
type: Boolean,
optional: true,
defaultValue: false,
},
allowsChecklistCountBadgeOnMinicard: {
/**
* Does the board show the compact checklist item-count badge
* (finished/total, e.g. "0/156") on minicards? Issue #6431: opt-in and
* OFF by default so the (potentially expensive) checklist counting only
* runs when this is enabled in Card Settings > Show on Minicard.
*/
type: Boolean,
defaultValue: false,
},
allowsComments: {
/**
* Does the board allows comments?
*/
type: Boolean,
defaultValue: true,
},
allowsCommentsOnMinicard: {
/**
* #4285: show a card's comments directly on the minicard? Opt-in and
* OFF by default so existing boards are unaffected.
*/
type: Boolean,
defaultValue: false,
},
allowsDescriptionTitle: {
/**
* Does the board allows description title?
*/
type: Boolean,
defaultValue: true,
},
allowsDescriptionTitleOnMinicard: {
/**
* Does the board allows description title on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsDescriptionText: {
/**
* Does the board allows description text?
*/
type: Boolean,
defaultValue: true,
},
allowsDescriptionTextOnMinicard: {
/**
* Does the board allows description text on minicard?
*/
type: Boolean,
defaultValue: false,
},
// #4448: the order the fields of the opened card render in - field keys
// of models/lib/cardFieldOrder.js (the first version stored the five
// SECTION keys; those stay valid). A missing/partial/unknown value falls
// back to the historical fixed order via applyCardOrder() /
// applyCardFieldOrder() there - see that file for what is reorderable.
cardFieldOrder: {
/**
* The order of the opened card's fields (models/lib/cardFieldOrder.js keys)
*/
type: Array,
optional: true,
},
'cardFieldOrder.$': {
type: String,
},
// The same for the minicard, independently: the order its dates, labels,
// avatars, badges and the rest render in, from Board Settings / Card's
// "Show on Minicard" column. applyMinicardOrder() in
// models/lib/cardFieldOrder.js; missing means the historical order.
minicardFieldOrder: {
/**
* The order of the minicard's fields (models/lib/cardFieldOrder.js keys)
*/
type: Array,
optional: true,
},
'minicardFieldOrder.$': {
type: String,
},
allowsCoverAttachmentOnMinicard: {
/**
* Does the board allows cover attachment on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsCoverAttachmentOnCard: {
/**
* Does the board show the cover image on the opened card? Opt-in, OFF by
* default (new Card Settings option).
*/
type: Boolean,
defaultValue: false,
},
allowsBadgeAttachmentOnMinicard: {
/**
* Does the board allows badge attachment on minicard?
*/
type: Boolean,
defaultValue: false,
},
allowsAttachmentCountOnCard: {
/**
* Does the board show the attachment count on the opened card? Opt-in,
* OFF by default (new Card Settings option).
*/
type: Boolean,
defaultValue: false,
},
allowsChecklistCountBadgeOnCard: {
/**
* Does the board show the checklist item-count total (finished/total)
* above all checklists on the opened card? Opt-in, OFF by default so the
* checklist counting only runs when enabled (new Card Settings option).
*/
type: Boolean,
defaultValue: false,
},
allowsCardSortingByNumberOnMinicard: {
/**
* Does the board allows card sorting by number on minicard?
*/
type: Boolean,
defaultValue: false,
},
allowsCardNumber: {
/**
* Does the board allows card numbers?
*/
type: Boolean,
defaultValue: false,
},
// Board-level override of the 3-tier Notification Settings system (see
// models/lib/notificationSettings.js). Unset (optional, no default)
// means "use the Admin Panel default"; an explicit true/false overrides
// it for every member of this board unless a member also has their own
// override, exactly like the admin-default -> board-override ->
// member-override precedence used elsewhere.
notifyOverrideTray: {
type: Boolean,
optional: true,
},
notifyOverrideEmail: {
type: Boolean,
optional: true,
},
allowsCardNumberOnMinicard: {
/**
* Does the board allows card numbers on minicard?
*/
type: Boolean,
defaultValue: false,
},
allowsActivities: {
/**
* Does the board allows comments?
*/
type: Boolean,
defaultValue: true,
},
allowsLabels: {
/**
* Does the board allows labels?
*/
type: Boolean,
defaultValue: true,
},
allowsLabelsOnMinicard: {
/**
* Does the board allows labels on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsCreator: {
/**
* Does the board allow creator?
*/
type: Boolean,
defaultValue: true,
},
allowsCreatorOnMinicard: {
/**
* Does the board allow creator?
*/
type: Boolean,
defaultValue: false,
},
showLabelText: {
/**
* #4256: does this board show label TEXT on its minicards (coloured
* words), or only the coloured bars? Board Settings / Card ("Labels
* text"). A user's own profile.showLabelTextOverride, when set, wins
* over this on every board - see client/lib/minicardLabelText.js.
* Defaults to true (text shown), the historical global default, so an
* existing board with no value stored sees no behaviour change.
*/
type: Boolean,
defaultValue: true,
optional: true,
},
allowsAssignee: {
/**
* Does the board allows assignee?
*/
type: Boolean,
defaultValue: true,
},
allowsAssigneeOnMinicard: {
/**
* Does the board allows assignee on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsMembers: {
/**
* Does the board allows members?
*/
type: Boolean,
defaultValue: true,
},
allowsMembersOnMinicard: {
/**
* Does the board allows members on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsRequestedBy: {
/**
* Does the board allows requested by?
*/
type: Boolean,
defaultValue: true,
},
allowsRequestedByOnMinicard: {
/**
* Does the board allows requested by on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsCardSortingByNumber: {
/**
* Does the board allows card sorting by number?
*/
type: Boolean,
defaultValue: true,
},
allowsShowLists: {
/**
* Does the board allows show lists on the card?
*/
type: Boolean,
defaultValue: true,
},
allowsAssignedBy: {
/**
* Does the board allows requested by?
*/
type: Boolean,
defaultValue: true,
},
allowsAssignedByOnMinicard: {
/**
* Does the board allows requested by on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsShowListsOnMinicard: {
/**
* Does the board allow showing list names on all minicards?
*/
type: Boolean,
defaultValue: false,
},
// #2426: a card's swimlane isn't otherwise visible on its minicard in
// List view (Swimlanes view already groups cards by swimlane), so this
// board-wide toggle shows the swimlane's name at the bottom of the
// minicard. Defaults to false so existing boards see no change.
allowsSwimlaneNameOnMinicard: {
/**
* Does the board allow showing the swimlane name on all minicards?
*/
type: Boolean,
defaultValue: false,
},
allowsChecklistAtMinicard: {
/**
* Does the board allow showing checklists on all minicards?
*/
type: Boolean,
defaultValue: false,
},
allowsReceivedDate: {
/**
* Does the board allows received date?
*/
type: Boolean,
defaultValue: true,
},
// #2530: the "Time spent" field (and its overtime indicator) was only
// reachable through the card's hamburger/context menu. Both the card
// detail view and the minicard already render it unconditionally
// whenever a card has logged time (see getSpentTime() in
// client/components/cards/minicard.jade and cardDetails.jade), so these
// two toggles default to TRUE - matching that existing behaviour rather
// than hiding something boards already show - and only let an admin turn
// it OFF via Card Settings, the same "Show on card"/"Show on minicard"
// pattern used by allowsReceivedDate/allowsReceivedDateOnMinicard above.
allowsSpentTime: {
/**
* Does the board show the accumulated spent-time badge on the opened card?
*/
type: Boolean,
defaultValue: true,
},
allowsSpentTimeOnMinicard: {
/**
* Does the board show the accumulated spent-time badge on the minicard?
*/
type: Boolean,
defaultValue: true,
},
// #6688: the card sections that shipped WITHOUT a Board Settings / Card
// toggle - Stickers, Location, Dependencies, Flowtime, Pomodoro, Vote,
// Planning Poker, Text Notes - and the minicard badges of the ones that
// have one (Stickers, Dependencies, Vote, Poker, the comment count). All
// default to TRUE because every one of them rendered unconditionally
// before, so an existing board keeps showing exactly what it showed; the
// toggle only lets an admin turn one OFF, the allowsSpentTime pattern.
allowsStickers: {
/**
* Does the board show the Stickers section on the opened card?
*/
type: Boolean,
defaultValue: true,
},
allowsStickersOnMinicard: {
/**
* Does the board show the stickers badge on the minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsLocation: {
/**
* Does the board show the Location section on the opened card?
*/
type: Boolean,
defaultValue: true,
},
allowsDependencies: {
/**
* Does the board show the Dependencies section on the opened card?
*/
type: Boolean,
defaultValue: true,
},
allowsDependenciesOnMinicard: {
/**
* Does the board show the dependencies badge on the minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsFlowtime: {
/**
* Does the board show the Flowtime timer on the opened card?
*/
type: Boolean,
defaultValue: true,
},
allowsPomodoro: {
/**
* Does the board show the Pomodoro timer on the opened card?
*/
type: Boolean,
defaultValue: true,
},
allowsVote: {
/**
* Does the board show a card's voting question and buttons on the opened card?
*/
type: Boolean,
defaultValue: true,
},
allowsVoteOnMinicard: {
/**
* Does the board show the vote-count badge on the minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsPoker: {
/**
* Does the board show a card's Planning Poker on the opened card?
*/
type: Boolean,
defaultValue: true,
},
allowsPokerOnMinicard: {
/**
* Does the board show the Planning Poker badge on the minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsTextNotes: {
/**
* Does the board show the Text Notes section on the opened card?
*/
type: Boolean,
defaultValue: true,
},
allowsCommentCountOnMinicard: {
/**
* Does the board show the comment-count badge on the minicard?
*/
type: Boolean,
defaultValue: true,
},
restrictCommentEditing: {
/**
* When true, board admins can NOT edit or delete comments authored by
* other users (only the comment's author can). Default false keeps the
* historical behaviour where board admins may moderate any comment.
*/
type: Boolean,
defaultValue: false,
},
allowsPersonalListWidth: {
/**
* List-width scope for this board (#6409).
* - false (default): list widths are SHARED — stored in `lists.width`,
* the same layout for everyone; only members with write access may
* change them.
* - true: list widths are PERSONAL — each user keeps their own widths in
* their profile (or localStorage when not logged in).
*/
type: Boolean,
defaultValue: false,
},
autoWidth: {
/**
* Shared (per-board) auto-width for all lists (#6409). When true, lists
* fit their content instead of using a fixed width. Used when the board
* is in SHARED list-width mode (allowsPersonalListWidth = false); in
* PERSONAL mode each user's own profile.autoWidthBoards value is used
* instead.
*/
type: Boolean,
optional: true,
defaultValue: false,
},
stickyListHeaders: {
/**
* #3847: when true, every list's header (title/WIP badge/hamburger)
* stays pinned to the top of its own list while that list's cards
* scroll underneath it, instead of scrolling out of view with them.
* Board-wide rather than per-list - freezing one list's header while
* its neighbours scrolled normally would look inconsistent - but the
* toggle itself lives in the List hamburger/action menu
* (listActionPopup in client/components/lists/listHeader.jade) for
* discoverability, per the issue reporter's request.
*/
type: Boolean,
defaultValue: false,
},
listWidthResizeLocked: {
/**
* #6680: when true, the list-width drag-resize handle between lists is
* disabled for everyone on this board, so a viewer who is just
* navigating cannot accidentally drag a list to a strange width.
* Toggled from the top header's lock icon, beside the drag-handles
* toggle. Independent of swimlaneHeightResizeLocked.
*/
type: Boolean,
optional: true,
defaultValue: false,
},
swimlaneHeightResizeLocked: {
/**
* #6680: when true, the swimlane-height drag-resize handle at the top
* of each swimlane is disabled for everyone on this board. Same toggle
* pattern and reasoning as listWidthResizeLocked, independent of it.
*/
type: Boolean,
optional: true,
defaultValue: false,
},
// Board Settings / Board View (docs/Features/Board/Board-View-Settings.md):
// which Board View menu entries this board offers, and which one it opens
// in, separately for a public and a private board. The decisions live in
// models/lib/boardViewSettings.js; a missing entry/side means SHOWN and a
// missing default means Swimlanes, so a board that never opened the popup
// behaves as it always did.
boardViewSettings: {
/**
* Per view: { '<board-view-key>': { showOnPublic: Boolean, showOnPrivate: Boolean } }
*/
type: Object,
blackbox: true,
optional: true,
},
defaultPublicBoardView: {
/**
* The Board View a PUBLIC board opens in when the viewer has no stored
* choice (or a choice this board hides). Always shown on public.
*/
type: String,
optional: true,
defaultValue: 'board-view-swimlanes',
},
defaultPrivateBoardView: {
/**
* The Board View a PRIVATE board opens in when the viewer has no stored
* choice (or a choice this board hides). Always shown on private.
*/
type: String,
optional: true,
defaultValue: 'board-view-swimlanes',
},
// The order of the Board View menu on this board, set with the up/down
// arrows in Board Settings / Board View. Missing, partial or unknown
// values are made whole by normalizeBoardViewOrder() in
// models/lib/boardViewSettings.js, the same way cardFieldOrder is.
boardViewOrder: {
/**
* The Board View menu's order: board-view keys, first to last
*/
type: Array,
optional: true,
},
'boardViewOrder.$': {
type: String,
},
sameWidthForAllLists: {
/**
* #6680: the BOARD-WIDE equivalent of each user's own "same width for
* all lists" (fixed width) choice in the Set Width popup
* (profile.fixedListWidthBoards) - an admin-set toggle, in the top
* header between the two resize-lock icons, that forces every list on
* this board to the single sameWidthForAllListsValue for EVERY viewer,
* overriding their personal fixed-width choice while it is on.
*/
type: Boolean,
optional: true,
defaultValue: false,
},
sameWidthForAllListsValue: {
/**
* The single width (px) every list uses while sameWidthForAllLists is
* on. Any board member with write access may change it by dragging a
* list's resize handle (server/permissions/boards.js allows an update
* touching only this field); turning the mode itself on/off is
* admin-only, like the rest of this board's settings.
*/
type: Number,
optional: true,
defaultValue: 220, // models/lib/listWidth.js DEFAULT_LIST_WIDTH
min: 200, // models/lib/listWidth.js MIN_LIST_WIDTH
},
allowsReceivedDateOnMinicard: {
/**
* Does the board allows received date on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsStartDate: {
/**
* Does the board allows start date?
*/
type: Boolean,
defaultValue: true,
},
allowsStartDateOnMinicard: {
/**
* Does the board allows start date on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsEndDate: {
/**
* Does the board allows end date?
*/
type: Boolean,
defaultValue: true,
},
allowsEndDateOnMinicard: {
/**
* Does the board allows end date on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsDueDate: {
/**
* Does the board allows due date?
*/
type: Boolean,
defaultValue: true,
},
allowsDueDateOnMinicard: {
/**
* Does the board allows due date on minicard?
*/
type: Boolean,
defaultValue: true,
},
allowsDueComplete: {
/**
* Does the board show the "Mark as complete" toggle on cards?
* Issue #6381: opt-in, hidden by default.
*/
type: Boolean,
defaultValue: false,
},
allowsDueCompleteOnMinicard: {
/**
* Does the board show the "Mark as complete" toggle on minicards?
* Separate from the card-details toggle (allowsDueComplete): opt-in,
* hidden by default so it is not shown on minicards unless enabled.
*/
type: Boolean,
defaultValue: false,
},
presentParentTask: {
/**
* Controls how to present the parent task:
*
* - `prefix-with-full-path`: add a prefix with the full path
* - `prefix-with-parent`: add a prefisx with the parent name
* - `subtext-with-full-path`: add a subtext with the full path
* - `subtext-with-parent`: add a subtext with the parent name
* - `no-parent`: does not show the parent at all
*/
type: String,
allowedValues: [
'prefix-with-full-path',
'prefix-with-parent',
'subtext-with-full-path',
'subtext-with-parent',
'no-parent',
],
optional: true,
defaultValue: 'no-parent',
},
receivedAt: {
/**
* Date the card was received
*/
type: Date,
optional: true,
},
startAt: {
/**
* Starting date of the board.
*/
type: Date,
optional: true,
},
dueAt: {
/**
* Due date of the board.
*/
type: Date,
optional: true,
},
endAt: {
/**
* End date of the board.
*/
type: Date,
optional: true,
},
spentTime: {
/**
* Time spent in the board.
*/
type: Number,
optional: true,
},
isOvertime: {
/**
* Is the board overtimed?
*/
type: Boolean,
defaultValue: false,
optional: true,
},
type: {
/**
* The type of board
* possible values: board, template-board, template-container
*/
type: String,
defaultValue: TYPE_BOARD,
allowedValues: [TYPE_BOARD, TYPE_TEMPLATE_BOARD, TYPE_TEMPLATE_CONTAINER],
},
sort: {
/**
* Sort value
*/
type: Number,
defaultValue: -1,
},
showActivities: {
type: Boolean,
defaultValue: false,
},
}),
);
Boards.helpers({
async copy(withoutCards = false) {
const oldId = this._id;
const oldWatchers = this.watchers ? this.watchers.slice() : [];
delete this._id;
delete this.slug;
this.title = await this.copyTitle();
const _id = await Boards.insertAsync(this);
// Temporary remove watchers to disable notifications
await Boards.updateAsync(_id, {
$set: {
watchers: []
},
});
// #4494: repoint subtasks/date-settings defaults that referenced the source
// (template) board to this copy, so subtasks created on the new board are
// NOT dropped onto the template board.
const { remapCopiedBoardDefaults } = require('./lib/boardCopyDefaults');
const defaultsPatch = remapCopiedBoardDefaults(this, oldId, _id);
if (Object.keys(defaultsPatch).length > 0) {
await Boards.updateAsync(_id, { $set: defaultsPatch });
}
// Copy all swimlanes in board. cardIdMap collects old card id -> new card
// id so card-to-card dependencies (#3392 "Red Strings") can be remapped to
// the copies once every card has been created.
const cardIdMap = {};
const swimlanes = await ReactiveCache.getSwimlanes({
boardId: oldId,
archived: false,
});
for (const swimlane of swimlanes) {
swimlane.type = 'swimlane';
await swimlane.copy(_id, null, 'below', '', cardIdMap, withoutCards);
}
// #3392: remap card-to-card dependencies (Red Strings) from the source
// card ids to their copies, dropping any whose target was not copied.
const depCards = await ReactiveCache.getCards({
boardId: _id,
cardDependencies: { $exists: true, $ne: [] },
});
for (const depCard of depCards) {
const remapped = (depCard.cardDependencies || [])
.map(dep => {
// Tolerate legacy bare-string entries as well as { cardId, ... }.
const oldDepId = typeof dep === 'string' ? dep : dep.cardId;
const newDepId = cardIdMap[oldDepId];
if (!newDepId) return null;
return typeof dep === 'string'
? { cardId: newDepId }
: { ...dep, cardId: newDepId };
})
.filter(Boolean);
await Cards.updateAsync(depCard._id, {
$set: { cardDependencies: remapped },
});
}
// copy custom field definitions
const cfMap = {};
const customFields = await ReactiveCache.getCustomFields({ boardIds: oldId });
for (const cf of customFields) {
const id = cf._id;
delete cf._id;
cf.boardIds = [_id];
cfMap[id] = await CustomFields.insertAsync(cf);
}
const cards = await ReactiveCache.getCards({ boardId: _id });
for (const card of cards) {
// Guard against a card with no customFields (the schema defaults it to []
// but a card copied via `.direct` / seeded raw can lack it) — otherwise
// `.map` throws and the whole board copy fails. Skip cards that have none,
// matching the `!this.customFields || !Array.isArray(...)` guard used
// elsewhere in this model.
if (!Array.isArray(card.customFields) || card.customFields.length === 0) continue;
await Cards.updateAsync(card._id, {
$set: {
customFields: card.customFields.map(cf => {
cf._id = cfMap[cf._id];
return cf;
}),
},
});
}
// copy rules, actions, and triggers
const actionsMap = {};
const actions = await ReactiveCache.getActions({ boardId: oldId });
for (const action of actions) {
const id = action._id;
delete action._id;
action.boardId = _id;
actionsMap[id] = await Actions.insertAsync(action);
}
const triggersMap = {};
const triggers = await ReactiveCache.getTriggers({ boardId: oldId });
for (const trigger of triggers) {
const id = trigger._id;
delete trigger._id;
trigger.boardId = _id;
triggersMap[id] = await Triggers.insertAsync(trigger);
}
const rules = await ReactiveCache.getRules({ boardId: oldId });
for (const rule of rules) {
delete rule._id;
rule.boardId = _id;
rule.actionId = actionsMap[rule.actionId];
rule.triggerId = triggersMap[rule.triggerId];
await Rules.insertAsync(rule);
}
// #5592: copy the board's webhooks (Integrations). They are per-board
// children (boardRemover deletes them by boardId) but were not duplicated on
// copy, so a copied board lost all its outgoing webhooks. Re-home each onto
// the new board; the URL/token/activities carry over (the copying user is a
// board admin and already has access to them).
const integrations = await ReactiveCache.getIntegrations({ boardId: oldId });
for (const integration of integrations) {
delete integration._id;
integration.boardId = _id;
await Integrations.insertAsync(integration);
}
// Re-set Watchers to reenable notification
await Boards.updateAsync(_id, {
$set: { watchers: oldWatchers }
});
return _id;
},
/**
* Return a unique title based on the current title
*
* @returns {string|null}
*/
async copyTitle() {
return await Boards.uniqueTitle(this.title);
},
/**
* Is supplied user authorized to view this board?
*/
isVisibleBy(user) {
if (this.isPublic()) {
// public boards are visible to everyone
return true;
} else {
// otherwise you have to be logged-in and active member
return user && this.isActiveMember(user._id);
}
},
/**
* Is the user one of the active members of the board?
*
* @param userId
* @returns {boolean} the member that matches, or undefined/false
*/
isActiveMember(userId) {
if (userId) {
return this.members.find(
member => member.userId === userId && member.isActive,
);
} else {
return false;
}
},
isPublic() {
return this.permission === 'public';
},
hasSharedListsConverted() {
return this.hasSharedListsConverted === true;
},
cards() {
const ret = ReactiveCache.getCards(
{ boardId: this._id, archived: false },
{ sort: { title: 1 } },
);
return ret;
},
lists() {
return this.draggableLists();
},
newestLists() {
// sorted lists from newest to the oldest, by its creation date or its cards' last modification date
const user = ReactiveCache.getCurrentUser();
const value = user._getListSortBy();
const sortKey = { starred: -1, [value[0]]: value[1] }; // [["starred",-1],value];
return ReactiveCache.getLists(
{
boardId: this._id,
archived: false,
deletedAt: null, // soft delete: hide deleted lists (docs/Features/Undo/Undo.md)
},
{ sort: sortKey },
);
},
draggableLists() {
return ReactiveCache.getLists(
{
boardId: this._id,
deletedAt: null, // soft delete: hide deleted lists
},
{ sort: { sort: 1 } }
);
},
/** returns the last list
* @returns Document the last list
*/
getLastList() {
const ret = ReactiveCache.getList({ boardId: this._id, deletedAt: null }, { sort: { sort: 'desc' } });
return ret;
},
nullSortLists() {
return ReactiveCache.getLists({
boardId: this._id,
archived: false,
deletedAt: null,
sort: { $eq: null },
});
},
swimlanes() {
return ReactiveCache.getSwimlanes(
{ boardId: this._id, archived: false },
{ sort: { sort: 1 } },
);
},
nextSwimlane(swimlane) {
return ReactiveCache.getSwimlane(
{
boardId: this._id,
archived: false,
sort: { $gte: swimlane.sort },
_id: { $ne: swimlane._id },
},
{
sort: { sort: 1 },
},
);
},
nullSortSwimlanes() {
return ReactiveCache.getSwimlanes({
boardId: this._id,
archived: false,
sort: { $eq: null },
});
},
hasOvertimeCards() {
const card = ReactiveCache.getCard({
isOvertime: true,
boardId: this._id,
archived: false,
});
return card !== undefined;
},
hasSpentTimeCards() {
const card = ReactiveCache.getCard({
spentTime: { $gt: 0 },
boardId: this._id,
archived: false,
});
return card !== undefined;
},
activities() {
let linkedBoardId = [this._id];
ReactiveCache.getCards({
"type": "cardType-linkedBoard",
"boardId": this._id
}).forEach(card => {
linkedBoardId.push(card.linkedId);
});
const ret = ReactiveCache.getActivities({ boardId: { $in: linkedBoardId } }, { sort: { createdAt: -1 } });
return ret;
},
activeMembers(){
// Depend on the users collection for reactivity when users are loaded
const memberUserIds = this.members.map(x => x.userId);
// Use findOne with limit for reactivity trigger instead of count() which loads all users
if (Meteor.isClient) {
Meteor.users.findOne({ _id: { $in: memberUserIds } }, { fields: { _id: 1 }, limit: 1 });
}
const members = (this.members || []).filter(m => m.isActive === true);
// Group by userId to handle duplicates
const grouped = groupBy(members, 'userId');
const uniqueMembers = Object.values(grouped).map(group => {
// Prefer admin member if exists, otherwise take the first
const selected = group.find(m => m.isAdmin) || group[0];
return selected;
});
// Filter out members where user is not loaded
const filteredMembers = uniqueMembers.filter(member => {
const user = ReactiveCache.getUser(member.userId);
return user !== undefined;
});
// Sort by role priority first (admin, normal, normal-assigned, no-comments, comment-only, comment-assigned, worker, read-only, read-assigned), then by fullname
const sortKey = member => {
const user = ReactiveCache.getUser(member.userId);
let rolePriority = 8; // Default for normal
if (member.isAdmin) rolePriority = 0;
else if (member.isReadAssignedOnly) rolePriority = 8;
else if (member.isReadOnly) rolePriority = 7;
else if (member.isWorker) rolePriority = 6;
else if (member.isCommentAssignedOnly) rolePriority = 5;
else if (member.isCommentOnly) rolePriority = 4;
else if (member.isNoComments) rolePriority = 3;
else if (member.isNormalAssignedOnly) rolePriority = 2;
else rolePriority = 1; // Normal
const fullname = user ? user.profile.fullname : '';
return rolePriority + '-' + fullname;
};
return [...filteredMembers].sort((a, b) => sortKey(a).localeCompare(sortKey(b)));
},
// Active members first (sorted as above), then the inactive/imported ones appended, so
// the sidebar member list shows EVERYONE and which are active vs not — imported
// placeholders and members deactivated by reconciliation (e.g. not in LDAP) stay
// visible (rendered distinguished by userAvatar) instead of silently disappearing.
membersForSidebar() {
const active = this.activeMembers();
const activeIds = new Set(active.map(m => m.userId));
const seen = new Set();
// #6479: a REMOVED member (isActive:false) must NOT appear in the sidebar member
// list. removeMember keeps the entry with isActive:false (#5122: role history /
// re-activation), so if the sidebar showed inactive members too, "Remove from
// board" looked like it did nothing — the avatar stayed. The only inactive entries
// still worth showing here are imported placeholders pending reconciliation
// (authenticationMethod:'imported'); a plain removed account is hidden. Removed
// members remain visible (greyed) where they are still referenced, e.g. as a card
// assignee, via the userAvatar 'inactive-member' styling — just not as current
// board members in this list.
const placeholders = (this.members || []).filter(m => {
if (m.isActive === true || activeIds.has(m.userId) || seen.has(m.userId)) return false;
seen.add(m.userId);
const user = ReactiveCache.getUser(m.userId);
return !!user && user.authenticationMethod === 'imported';
});
return active.concat(placeholders);
},
activeOrgs() {
return where(this.orgs, { isActive: true });
},
// hasNotAnyOrg(){
// return this.orgs === undefined || this.orgs.length <= 0;
// },
activeTeams() {
return where(this.teams, { isActive: true });
},
// #5850: the board's active email-address domains.
activeDomains() {
return where(this.domains, { isActive: true });
},
// hasNotAnyTeam(){
// return this.teams === undefined || this.teams.length <= 0;
// },
activeAdmins() {
return where(this.members, { isActive: true, isAdmin: true });
},
memberUsers() {
return ReactiveCache.getUsers({ _id: { $in: this.members.map(x => x.userId) } });
},
getLabel(name, color) {
return findWhere(this.labels, { name, color });
},
getLabelById(labelId) {
return findWhere(this.labels, { _id: labelId });
},
labelIndex(labelId) {
return this.labels.map(x => x._id).indexOf(labelId);
},
memberIndex(memberId) {
return this.members.map(x => x.userId).indexOf(memberId);
},
hasMember(memberId) {
return !!findWhere(this.members, { userId: memberId, isActive: true });
},
hasAdmin(memberId) {
return !!findWhere(this.members, {
userId: memberId,
isActive: true,
isAdmin: true,
});
},
hasNoComments(memberId) {
return !!findWhere(this.members, {
userId: memberId,
isActive: true,
isAdmin: false,
isNoComments: true,
isWorker: false,
});
},
hasCommentOnly(memberId) {
return !!findWhere(this.members, {
userId: memberId,
isActive: true,
isAdmin: false,
isCommentOnly: true,
isWorker: false,
});
},
hasWorker(memberId) {
return !!findWhere(this.members, {
userId: memberId,
isActive: true,
isAdmin: false,
isCommentOnly: false,
isWorker: true,
});
},
hasNormalAssignedOnly(memberId) {
return !!findWhere(this.members, {
userId: memberId,
isActive: true,
isAdmin: false,
isNormalAssignedOnly: true,
isCommentAssignedOnly: false,
});
},
hasCommentAssignedOnly(memberId) {
return !!findWhere(this.members, {
userId: memberId,
isActive: true,
isAdmin: false,
isNormalAssignedOnly: false,
isCommentAssignedOnly: true,
});
},
hasReadOnly(memberId) {
return !!findWhere(this.members, {
userId: memberId,
isActive: true,
isAdmin: false,
isReadOnly: true,
});
},
hasReadAssignedOnly(memberId) {
return !!findWhere(this.members, {
userId: memberId,
isActive: true,
isAdmin: false,
isReadAssignedOnly: true,
});
},
// Returns the single BOARD-level role key of an active board member (see
// INVITE_TO_BOARD_ROLES). Returns null if the user is not an active member.
// Note: 'board-admin' is the board administrator role and is distinct from
// the global site-admin flag `user.isAdmin`. A member with no restriction
// flag set is a plain 'normal' member.
memberRole(memberId) {
const member = findWhere(this.members, { userId: memberId, isActive: true });
if (!member) return null;
if (member.isAdmin) return 'board-admin';
if (member.isWorker) return 'worker';
if (member.isCommentOnly) return 'comment-only';
if (member.isNoComments) return 'no-comments';
if (member.isNormalAssignedOnly) return 'normal-assigned-only';
if (member.isCommentAssignedOnly) return 'comment-assigned-only';
if (member.isReadOnly) return 'read-only';
if (member.isReadAssignedOnly) return 'read-assigned-only';
return 'normal';
},
hasAnyAllowsDate() {
const ret = this.allowsReceivedDate || this.allowsStartDate || this.allowsDueDate || this.allowsEndDate;
return ret;
},
// The minicard's field order (models/lib/cardFieldOrder.js), canonical.
getMinicardFieldOrder() {
const { applyMinicardOrder } = require('/models/lib/cardFieldOrder');
return applyMinicardOrder(this.minicardFieldOrder);
},
// Board Settings / Card's up/down arrows write through these two, the way
// Board View's popup writes through setBoardViewShown: the order is
// normalised before it is stored, so the database never holds an unknown
// or duplicated key. Who may call them is decided where it is for every
// other board setting - Boards.allow's update rule in
// server/permissions/boards.js, which requires a board admin.
async setCardFieldOrder(order) {
const { applyCardOrder } = require('/models/lib/cardFieldOrder');
return await Boards.updateAsync(this._id, { $set: { cardFieldOrder: applyCardOrder(order) } });
},
async setMinicardFieldOrder(order) {
const { applyMinicardOrder } = require('/models/lib/cardFieldOrder');
return await Boards.updateAsync(this._id, { $set: { minicardFieldOrder: applyMinicardOrder(order) } });
},
hasAnyAllowsUser() {
const ret = this.allowsCreator || this.allowsMembers || this.allowsAssignee || this.allowsRequestedBy || this.allowsAssignedBy;
return ret;
},
// #4448: the resolved, always-complete order of the reorderable card-detail
// sections - see models/lib/cardFieldOrder.js.
getCardFieldOrder() {
const { applyCardFieldOrder } = require('/models/lib/cardFieldOrder');
return applyCardFieldOrder(this.cardFieldOrder);
},
absoluteUrl() {
// Build the URL from the relative path rather than FlowRouter.url():
// FlowRouter is client-only, so on the server (board invitation emails,
// activity notification emails) it has no registered routes and returns a
// generic "/board" link without the board id. Meteor.absoluteUrl() prepends
// ROOT_URL and works on both client and server. It expects no leading slash.
return Meteor.absoluteUrl(this.originRelativeUrl().replace(/^\//, ''));
},
originRelativeUrl() {
// Matches the 'board' route '/b/:id/:slug' (config/router.js). Built as a
// plain string so it resolves correctly on the server too.
return `/b/${this._id}/${this.slug || 'board'}`;
},
colorClass() {
return `board-color-${this.color}`;
},
customFields() {
const ret = ReactiveCache.getCustomFields(
{ boardIds: { $in: [this._id] } },
{ sort: { name: 1 } },
);
return ret;
},
// XXX currently mutations return no value so we have an issue when using addLabel in import
// XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
pushLabel(name, color, dueAt) {
const _id = Random.id(6);
const label = { _id, name, color };
if (dueAt) label.dueAt = dueAt;
Boards.direct.update(this._id, { $push: { labels: label } });
return _id;
},
/** sets the new label order
* @param newLabelOrderOnlyIds new order array of _id, e.g. Array(4) [ "FvtD34", "PAEgDP", "LjRBxH", "YJ8sZz" ]
*/
setNewLabelOrder(newLabelOrderOnlyIds) {
if (this.labels.length == newLabelOrderOnlyIds.length) {
if (this.labels.every(_label => newLabelOrderOnlyIds.indexOf(_label._id) >= 0)) {
const newLabels = [...this.labels].sort((a, b) => newLabelOrderOnlyIds.indexOf(a._id) - newLabelOrderOnlyIds.indexOf(b._id));
if (this.labels.length == newLabels.length) {
Boards.direct.update(this._id, {$set: {labels: newLabels}});
}
}
}
},
searchBoards(term) {
check(term, Match.OneOf(String, null, undefined));
const query = { boardId: this._id };
query.type = 'cardType-linkedBoard';
query.archived = false;
const projection = { limit: 10, sort: { createdAt: -1 } };
if (term) {
const regex = new RegExp(term, 'i');
query.$or = [{ title: regex }, { description: regex }];
}
const ret = ReactiveCache.getCards(query, projection);
return ret;
},
searchSwimlanes(term) {
check(term, Match.OneOf(String, null, undefined));
const query = { boardId: this._id };
if (this.isTemplatesBoard()) {
query.type = 'template-swimlane';
query.archived = false;
} else {
query.type = { $nin: ['template-swimlane'] };
}
const projection = { limit: 10, sort: { createdAt: -1 } };
if (term) {
const regex = new RegExp(term, 'i');
query.$or = [{ title: regex }, { description: regex }];
}
return ReactiveCache.getSwimlanes(query, projection);
},
searchLists(term) {
let ret = null;
if (term) {
check(term, Match.OneOf(String));
term = term.trim();
}
if (term) {
const query = { boardId: this._id };
if (this.isTemplatesBoard()) {
query.type = 'template-list';
query.archived = false;
} else {
query.type = { $nin: ['template-list'] };
}
const projection = { sort: { createdAt: -1 } };
if (term) {
const regex = new RegExp(term, 'i');
query.$or = [{ title: regex }, { description: regex }];
}
ret = ReactiveCache.getLists(query, projection);
}
return ret;
},
searchCards(term, excludeLinked) {
let ret = null;
if (term) {
check(term, Match.OneOf(String));
term = term.trim();
}
if (term) {
const query = { boardId: this._id };
if (excludeLinked) {
query.linkedId = null;
}
if (this.isTemplatesBoard()) {
query.type = 'template-card';
query.archived = false;
} else {
query.type = { $nin: ['template-card'] };
}
const projection = { sort: { createdAt: -1 } };
// #5680: build the $or so numeric custom fields (number / currency, stored
// as JS Numbers) match by value too — a regex alone only matches strings.
query.$or = buildCardSearchOr(term);
// #3841: also find cards whose match is only inside a COMMENT. Comments
// live in a separate collection, so Minimongo can't match them with a
// single query on Cards — pull this board's comment texts, work out
// which cards they belong to (using the same case-insensitive matching
// rule as the rest of the search), and OR those card ids in too.
const comments = ReactiveCache.getCardComments(
{ boardId: this._id },
{ fields: { cardId: 1, text: 1 } },
);
const commentCardIds = matchingCommentCardIds(comments, term);
if (commentCardIds.length) {
query.$or.push({ _id: { $in: commentCardIds } });
}
ret = ReactiveCache.getCards(query, projection);
}
return ret;
},
// A board alwasy has another board where it deposits subtasks of thasks
// that belong to itself.
getDefaultSubtasksBoardId() {
// #3868 / #5788 / #2256: only the SERVER may auto-create the default
// subtasks board (+ its swimlane) — and #6456: on Meteor 3 the server may
// not use the sync insert/update APIs either ("insert is not available on
// the server"), which made addSubtaskCard throw here. This is now a PURE
// getter; the server-side creation lives in getDefaultSubtasksBoardAsync
// (the only path the addSubtaskCard method uses).
return this.subtasksDefaultBoardId;
},
getDefaultSubtasksBoard() {
return ReactiveCache.getBoard(this.getDefaultSubtasksBoardId());
},
async getDefaultSubtasksBoardAsync() {
let boardId = this.getDefaultSubtasksBoardId();
// #6456: server-authoritative lazy creation, once, with the async APIs
// (the sync Boards.insert/Swimlanes.insert/Boards.update this used to rely
// on throw on the Meteor 3 server, so creating a subtask crashed with
// "Exception while invoking method 'addSubtaskCard'").
if (!boardId && Meteor.isServer) {
boardId = await Boards.insertAsync({
title: `^${this.title}^`,
permission: this.permission,
members: sanitizeBoardMembers(this.members),
color: this.color,
description: getTranslatedString(
'default-subtasks-board',
`Default subtasks board for ${this.title}`,
{ board: this.title },
),
});
await Swimlanes.insertAsync({
title: getTranslatedString('default', 'Default'),
boardId,
});
await this.setSubtasksDefaultBoardId(boardId);
this.subtasksDefaultBoardId = boardId;
}
if (!boardId) {
return null;
}
let board = await ReactiveCache.getBoard(boardId);
if (!board) {
board = await Boards.findOneAsync(boardId);
}
return board;
},
//Date Settings option such as received date, start date and so on.
getDefaultDateSettingsBoardId() {
// #6456 (same class): PURE getter. The lazy sync creation this used had
// BOTH bug classes — no Meteor.isServer guard (client-side creation on
// every reactive read, the #2256/#3868 duplicate-boards class) and the
// sync Boards.insert/Swimlanes.insert/Boards.update APIs that throw on the
// Meteor 3 server. Nothing in the codebase calls it today; if a feature
// needs the dates helper board again, add an async server-side ensure like
// getDefaultSubtasksBoardAsync.
return this.dateSettingsDefaultBoardId;
},
getDefaultDateSettingsBoard() {
return ReactiveCache.getBoard(this.getDefaultDateSettingsBoardId());
},
getDefaultSubtasksListId() {
// #3868 / #5788 / #2256 / #6456: PURE getter — client-side creation
// duplicated lists, and the sync Lists.insert this used on the server
// throws on Meteor 3. Server-side creation lives in
// getDefaultSubtasksListAsync.
return this.subtasksDefaultListId;
},
getDefaultSubtasksList() {
return ReactiveCache.getList(this.getDefaultSubtasksListId());
},
async getDefaultSubtasksListAsync() {
let listId = this.getDefaultSubtasksListId();
// #6456: server-authoritative lazy creation with the async APIs (the sync
// Lists.insert + getDefaultSwimline() this relied on throw on the Meteor 3
// server — getDefaultSwimline's sync ReactiveCache read even returns a
// Promise there, so .._id was never valid).
if (!listId && Meteor.isServer) {
const swimlane = await this.getDefaultSwimlineAsync();
listId = await Lists.insertAsync({
title: getTranslatedString('queue', 'Queue'),
boardId: this._id,
swimlaneId: swimlane ? swimlane._id : undefined, // Set default swimlane for subtasks list
});
await this.setSubtasksDefaultListId(listId);
this.subtasksDefaultListId = listId;
}
if (!listId) {
return null;
}
let list = await ReactiveCache.getList(listId);
if (!list) {
list = await Lists.findOneAsync(listId);
}
return list;
},
getDefaultDateSettingsListId() {
// #6456 (same class): PURE getter — see getDefaultDateSettingsBoardId.
return this.dateSettingsDefaultListId;
},
getDefaultDateSettingsList() {
return ReactiveCache.getList(this.getDefaultDateSettingsListId());
},
getDefaultSwimline() {
// Issue #1971: pick a NON-archived swimlane so a card added in List view
// never lands in an archived (invisible-in-swimlane-view) swimlane. The pure
// pickDefaultSwimlane helper prefers the first active swimlane, falling back
// to the first one only when every swimlane is archived (so callers reading
// ._id never crash).
const { pickDefaultSwimlane } = require('./lib/defaultSwimlane');
let result = pickDefaultSwimlane(ReactiveCache.getSwimlanes({ boardId: this._id }));
if (result === undefined && Meteor.isServer && this._id) {
// Issue #6382: only the server may auto-create the default swimlane. On
// the client this getter runs inside reactive render contexts; when a
// board's swimlanes are not yet loaded/subscribed (e.g. the default
// subtasks board viewed via "All boards"), getSwimlanes() is transiently
// empty and every re-render would insert another empty swimlane —
// producing thousands of them and freezing the browser. The server
// creates the default swimlane at board creation and self-heals here.
// Issue #6429: self-heal via a DETERMINISTIC _id so concurrent/repeated
// calls are idempotent (see ensureDefaultSwimlaneId).
result = this.ensureDefaultSwimlaneId();
}
return result;
},
// Deterministic _id for a board's auto-created default swimlane. Because _id
// carries a unique index, an upsert on it can create AT MOST ONE default
// swimlane per board, no matter how many times (or how concurrently) the
// self-heal runs — the fix for #6429 (a check-then-insert race in the getters
// below produced 30 000+ empty "Default" swimlanes on some boards).
defaultSwimlaneId() {
const { defaultSwimlaneId } = require('./lib/defaultSwimlane');
return defaultSwimlaneId(this._id);
},
ensureDefaultSwimlaneId() {
const defaultId = this.defaultSwimlaneId();
// Upsert keyed on the deterministic _id: concurrent self-heals collide on
// the _id unique index, so only one insert wins instead of racing the
// check-then-insert and each inserting a new swimlane.
//
// It must be the ASYNC upsert. Meteor 3 removed the synchronous one on the
// server, and calling it threw
// Error: update is not available on the server. Please use updateAsync()
// out of every `moveSwimlane` that reached this self-heal - the failure an
// admin kept seeing in Admin Panel / Problems / Database problems. This
// getter is SYNCHRONOUS and cannot await, so the upsert is started and not
// waited for: the self-heal still happens, and this call returns whatever
// is in the cache, which the caller already had to handle (it was undefined
// before the self-heal existed too). A caller that needs the swimlane back
// in the same tick uses ensureDefaultSwimlaneIdAsync().
try {
const p = Swimlanes.upsertAsync(
{ _id: defaultId },
{ $setOnInsert: this.defaultSwimlaneFields() },
);
if (p && typeof p.catch === 'function') p.catch(() => {});
} catch (e) {
if (process.env.DEBUG === 'true') {
// eslint-disable-next-line no-console
console.warn('default swimlane self-heal failed:', e && e.message);
}
}
return ReactiveCache.getSwimlane({ _id: defaultId });
},
async ensureDefaultSwimlaneIdAsync() {
const defaultId = this.defaultSwimlaneId();
await Swimlanes.upsertAsync(
{ _id: defaultId },
{ $setOnInsert: this.defaultSwimlaneFields() },
);
return (
(await ReactiveCache.getSwimlane({ _id: defaultId })) ||
(Meteor.isServer ? await Swimlanes.findOneAsync(defaultId) : undefined)
);
},
// Fields for an upsert-inserted default swimlane. archived/type must be set
// explicitly: their schema autoValue/defaultValue only fire on isInsert, not
// on the isUpsert path used here, so omitting them fails required validation.
defaultSwimlaneFields() {
const { defaultSwimlaneFields } = require('./lib/defaultSwimlane');
// Use fallback title if i18n is not available (e.g., during migration).
return defaultSwimlaneFields(this._id, getTranslatedString('default', 'Default'));
},
async getDefaultSwimlineAsync() {
// Issue #1971: prefer a NON-archived swimlane (see getDefaultSwimline).
const { pickDefaultSwimlane } = require('./lib/defaultSwimlane');
// On the server this can run immediately after creating a helper board and
// its first swimlane. The reactive cache may still hold the pre-insert
// empty result, so use the authoritative collection in server methods.
const swimlanes = Meteor.isServer
? await Swimlanes.find({ boardId: this._id }).fetchAsync()
: await ReactiveCache.getSwimlanes({ boardId: this._id });
let result = pickDefaultSwimlane(swimlanes);
if (result === undefined && Meteor.isServer && this._id) {
// Issue #6382: never auto-create swimlanes from the client (see
// getDefaultSwimline) — only the server may insert the default one.
// Issue #6429: idempotent deterministic-_id upsert instead of a racy
// check-then-insert that produced thousands of empty swimlanes.
result = await this.ensureDefaultSwimlaneIdAsync();
}
return result;
},
async getNextCardNumber() {
// Issue #5813 / #4743: the previous implementation read the current max
// cardNumber and returned max + 1. Two concurrent card creations (e.g. a
// burst of REST API calls) both read the same max and both got the same
// number — a read-then-increment race that gave many cards the same number
// and, under load, pegged the CPU. We now allocate card numbers from an
// atomic per-board counter (Counters.incrementCounterAsync), which is a
// single atomic findOneAndUpdate($inc) and is therefore safe under
// concurrency.
const counterName = `cardNumber-${this._id}`;
// rawCollection()/atomic counters are server-only. On the client (where card
// numbers are not authoritative — the server insert recomputes them), fall
// back to the old max + 1 read.
if (!Meteor.isServer) {
const boardCards = await ReactiveCache.getCard(
{ boardId: this._id },
{ sort: { cardNumber: -1 }, limit: 1 },
true,
);
if (!boardCards) {
return 1;
}
const maxCardNr = boardCards.cardNumber ? boardCards.cardNumber : 0;
return maxCardNr + 1;
}
// Lazy seed: the counter does not exist for boards created before this
// change (or for boards imported with existing cards). On first use, seed
// the counter to the board's current max cardNumber so we never reissue a
// number that an existing card already has. This runs once per board.
const existingCounter = await Counters.rawCollection().findOne({ _id: counterName });
if (!existingCounter) {
const boardCards = await ReactiveCache.getCard(
{
boardId: this._id,
},
{
sort: { cardNumber: -1 },
limit: 1,
},
true,
);
const maxCardNr = boardCards && boardCards.cardNumber ? boardCards.cardNumber : 0;
// Seed only if still missing, so two concurrent first-uses don't clobber
// each other (the loser's upsert is a no-op).
await Counters.rawCollection().updateOne(
{ _id: counterName },
{ $setOnInsert: { next_val: maxCardNr } },
{ upsert: true },
);
}
return await incrementCounterAsync(counterName);
},
// #5656: the Calendar view must honor the active board Filter (member /
// assignee / due-date / label / custom-field). `filterSelector` is the object
// produced by Filter._getMongoSelector() on the client (pass a falsy/empty
// value, e.g. from the server or when no filter is active). It is always
// ANDed in via combineWithFilter so it can never be overwritten by — nor
// collide with — the top-level `$or` these interval selectors use.
cardsDueInBetween(start, end, filterSelector) {
const ret = ReactiveCache.getCards(
cardsDueInBetweenSelector(this._id, start, end, filterSelector),
);
return ret;
},
cardsInInterval(start, end, filterSelector) {
const ret = ReactiveCache.getCards(
cardsInIntervalSelector(this._id, start, end, filterSelector),
);
return ret;
},
cardsReceivedInBetween(start, end, filterSelector) {
const ret = ReactiveCache.getCards(
cardsReceivedInBetweenSelector(this._id, start, end, filterSelector),
);
return ret;
},
cardsEndInBetween(start, end, filterSelector) {
const ret = ReactiveCache.getCards(
cardsEndInBetweenSelector(this._id, start, end, filterSelector),
);
return ret;
},
isTemplateBoard() {
return this.type === 'template-board';
},
isTemplatesBoard() {
return this.type === 'template-container';
},
// #5850: any template board (a single template board or the templates
// container). On these, sharing is group-only (orgs/teams/domains); the
// members tab shows only the original creator as an individual.
isAnyTemplateBoard() {
return this.type === 'template-board' || this.type === 'template-container';
},
async archive() {
return await Boards.updateAsync(this._id, { $set: { archived: true, archivedAt: new Date() } });
},
async restore() {
return await Boards.updateAsync(this._id, { $set: { archived: false } });
},
async rename(title) {
return await Boards.updateAsync(this._id, { $set: { title } });
},
async setDescription(description) {
return await Boards.updateAsync(this._id, { $set: { description } });
},
async setColor(color, customThemeColors) {
// docs/Theme/Theme.md: flat/clear themes may carry custom colors; validate the
// count + category here and store only when valid, else clear any previous set.
const modifier = { $set: { color } };
if (customThemeColors && isValidCustomColors(color, customThemeColors)) {
modifier.$set.customThemeColors = customThemeColors;
} else {
modifier.$unset = { customThemeColors: '' };
}
return await Boards.updateAsync(this._id, modifier);
},
// Board-level override of the 3-tier Notification Settings system (see
// models/lib/notificationSettings.js): admin default -> board override ->
// member override. `service` is 'tray' or 'email'; `value` is true/false to
// override, or null/undefined to clear the override and fall back to the
// Admin Panel default.
async setNotifyOverride(service, value) {
const currentUser = await ReactiveCache.getCurrentUser();
if (!(currentUser.isBoardAdmin() || currentUser.isAdmin())) return false;
const field = service === 'email' ? 'notifyOverrideEmail'
: service === 'tray' ? 'notifyOverrideTray'
: null;
if (!field) return false;
const modifier = value === true || value === false
? { $set: { [field]: value } }
: { $unset: { [field]: '' } };
return await Boards.updateAsync(this._id, modifier);
},
async setBackgroundImageURL(backgroundImageURL) {
const currentUser = await ReactiveCache.getCurrentUser();
if (currentUser.isBoardAdmin() || currentUser.isAdmin()) {
return await Boards.updateAsync(this._id, { $set: { backgroundImageURL } });
}
return false;
},
// Set a board-level background attachment as the active board background.
async setBackgroundImage(backgroundId) {
const currentUser = await ReactiveCache.getCurrentUser();
if (currentUser.isBoardAdmin() || currentUser.isAdmin()) {
const backgroundImageURL = generateUniversalAttachmentUrl(backgroundId);
return await Boards.updateAsync(this._id, {
$set: { backgroundImageId: backgroundId, backgroundImageURL },
});
}
return false;
},
async unsetBackgroundImage() {
const currentUser = await ReactiveCache.getCurrentUser();
if (currentUser.isBoardAdmin() || currentUser.isAdmin()) {
return await Boards.updateAsync(this._id, {
$set: { backgroundImageId: '', backgroundImageURL: '' },
});
}
return false;
},
async setVisibility(visibility) {
return await Boards.updateAsync(this._id, { $set: { permission: visibility } });
},
async addLabel(name, color, dueAt) {
if (!this.getLabel(name, color)) {
const _id = Random.id(6);
const label = { _id, name, color };
// #2802: an optional due date turns a label into a "milestone" (e.g.
// "Sprint 1" due 2026-01-15) without a separate Milestone object.
if (dueAt) label.dueAt = dueAt;
return await Boards.updateAsync(this._id, { $push: { labels: label } });
}
return null;
},
async editLabel(labelId, name, color, dueAt) {
if (!this.getLabel(name, color)) {
const labelIndex = this.labelIndex(labelId);
const update = {
$set: {
[`labels.${labelIndex}.name`]: name,
[`labels.${labelIndex}.color`]: color,
},
};
// #2802: keep a label's "milestone" due date unset unless one is
// provided, and clear it explicitly when it is removed in the popup.
if (dueAt) {
update.$set[`labels.${labelIndex}.dueAt`] = dueAt;
} else {
update.$unset = { [`labels.${labelIndex}.dueAt`]: '' };
}
return await Boards.updateAsync(this._id, update);
}
return null;
},
async removeLabel(labelId) {
return await Boards.updateAsync(this._id, { $pull: { labels: { _id: labelId } } });
},
async changeOwnership(fromId, toId) {
const memberIndex = this.memberIndex(fromId);
return await Boards.updateAsync(this._id, {
$set: { [`members.${memberIndex}.userId`]: toId },
});
},
async addMember(memberId) {
const memberIndex = this.memberIndex(memberId);
if (memberIndex >= 0) {
return await Boards.updateAsync(this._id, {
$set: { [`members.${memberIndex}.isActive`]: true },
});
}
return await Boards.updateAsync(this._id, {
$push: {
members: {
userId: memberId,
isAdmin: false,
isActive: true,
isNoComments: false,
isCommentOnly: false,
isWorker: false,
isNormalAssignedOnly: false,
isCommentAssignedOnly: false,
isReadOnly: false,
isReadAssignedOnly: false,
},
},
});
},
async removeMember(memberId) {
const memberIndex = this.memberIndex(memberId);
// #5330: a member entry whose user account has been deleted still appears
// in board.members but has no Users document. Such an orphaned entry can
// never be a meaningful (active) admin and the deactivate-by-index flow
// below would only leave it lingering, so hard-remove it by userId. This
// works whether or not the user still exists since matching is by userId.
if (memberIndex < 0 || !ReactiveCache.getUser(memberId)) {
return await Boards.updateAsync(this._id, {
$set: { members: pullMemberById(this.members, memberId) },
});
}
const allowRemove =
!this.members[memberIndex].isAdmin || this.activeAdmins().length > 1;
if (!allowRemove) {
return await Boards.updateAsync(this._id, {
$set: { [`members.${memberIndex}.isActive`]: true },
});
}
return await Boards.updateAsync(this._id, {
$set: {
[`members.${memberIndex}.isActive`]: false,
[`members.${memberIndex}.isAdmin`]: false,
},
});
},
async setMemberPermission(
memberId,
isAdmin,
isNoComments,
isCommentOnly,
isWorker,
isNormalAssignedOnly = false,
isCommentAssignedOnly = false,
isReadOnly = false,
isReadAssignedOnly = false,
currentUserId = Meteor.userId(),
) {
const memberIndex = this.memberIndex(memberId);
if (memberId === currentUserId) {
isAdmin = this.members[memberIndex].isAdmin;
}
return await Boards.updateAsync(this._id, {
$set: {
[`members.${memberIndex}.isAdmin`]: isAdmin,
[`members.${memberIndex}.isNoComments`]: isNoComments,
[`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
[`members.${memberIndex}.isWorker`]: isWorker,
[`members.${memberIndex}.isNormalAssignedOnly`]: isNormalAssignedOnly,
[`members.${memberIndex}.isCommentAssignedOnly`]: isCommentAssignedOnly,
[`members.${memberIndex}.isReadOnly`]: isReadOnly,
[`members.${memberIndex}.isReadAssignedOnly`]: isReadAssignedOnly,
},
});
},
async setAllowsSubtasks(allowsSubtasks) {
return await Boards.updateAsync(this._id, { $set: { allowsSubtasks } });
},
async setAllowsCreator(allowsCreator) {
return await Boards.updateAsync(this._id, { $set: { allowsCreator } });
},
async setAllowsCreatorOnMinicard(allowsCreatorOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsCreatorOnMinicard } });
},
async setAllowsMembers(allowsMembers) {
return await Boards.updateAsync(this._id, { $set: { allowsMembers } });
},
async setAllowsChecklists(allowsChecklists) {
return await Boards.updateAsync(this._id, { $set: { allowsChecklists } });
},
async setAllowsAssignee(allowsAssignee) {
return await Boards.updateAsync(this._id, { $set: { allowsAssignee } });
},
async setAllowsAssignedBy(allowsAssignedBy) {
return await Boards.updateAsync(this._id, { $set: { allowsAssignedBy } });
},
async setAllowsShowListsOnMinicard(allowsShowListsOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsShowListsOnMinicard } });
},
async setAllowsSwimlaneNameOnMinicard(allowsSwimlaneNameOnMinicard) {
return await Boards.updateAsync(this._id, {
$set: { allowsSwimlaneNameOnMinicard },
});
},
async setAllowsChecklistAtMinicard(allowsChecklistAtMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsChecklistAtMinicard } });
},
async setAllowsRequestedBy(allowsRequestedBy) {
return await Boards.updateAsync(this._id, { $set: { allowsRequestedBy } });
},
async setAllowsCardSortingByNumber(allowsCardSortingByNumber) {
return await Boards.updateAsync(this._id, { $set: { allowsCardSortingByNumber } });
},
async setAllowsShowLists(allowsShowLists) {
return await Boards.updateAsync(this._id, { $set: { allowsShowLists } });
},
async setAllowsAttachments(allowsAttachments) {
return await Boards.updateAsync(this._id, { $set: { allowsAttachments } });
},
async setAllowsLabels(allowsLabels) {
return await Boards.updateAsync(this._id, { $set: { allowsLabels } });
},
async setAllowsComments(allowsComments) {
return await Boards.updateAsync(this._id, { $set: { allowsComments } });
},
async setAllowsCommentsOnMinicard(allowsCommentsOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsCommentsOnMinicard } });
},
async setAllowsDescriptionTitle(allowsDescriptionTitle) {
return await Boards.updateAsync(this._id, { $set: { allowsDescriptionTitle } });
},
async setAllowsCardNumber(allowsCardNumber) {
return await Boards.updateAsync(this._id, { $set: { allowsCardNumber } });
},
async setAllowsDescriptionText(allowsDescriptionText) {
return await Boards.updateAsync(this._id, { $set: { allowsDescriptionText } });
},
async setAllowsDescriptionTextOnMinicard(allowsDescriptionTextOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsDescriptionTextOnMinicard } });
},
async setAllowsCoverAttachmentOnMinicard(allowsCoverAttachmentOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsCoverAttachmentOnMinicard } });
},
async setAllowsBadgeAttachmentOnMinicard(allowsBadgeAttachmentOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsBadgeAttachmentOnMinicard } });
},
async setAllowsCardSortingByNumberOnMinicard(allowsCardSortingByNumberOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsCardSortingByNumberOnMinicard } });
},
// Backward-compatible aliases for legacy call sites.
async setallowsDescriptionTextOnMinicard(allowsDescriptionTextOnMinicard) {
return await this.setAllowsDescriptionTextOnMinicard(allowsDescriptionTextOnMinicard);
},
async setallowsCoverAttachmentOnMinicard(allowsCoverAttachmentOnMinicard) {
return await this.setAllowsCoverAttachmentOnMinicard(allowsCoverAttachmentOnMinicard);
},
async setallowsBadgeAttachmentOnMinicard(allowsBadgeAttachmentOnMinicard) {
return await this.setAllowsBadgeAttachmentOnMinicard(allowsBadgeAttachmentOnMinicard);
},
async setallowsCardSortingByNumberOnMinicard(allowsCardSortingByNumberOnMinicard) {
return await this.setAllowsCardSortingByNumberOnMinicard(allowsCardSortingByNumberOnMinicard);
},
// #4256: this board's own default for showing label text on minicards.
getShowLabelText() {
return this.showLabelText !== false;
},
async setShowLabelText(showLabelText) {
return await Boards.updateAsync(this._id, { $set: { showLabelText } });
},
async setAllowsActivities(allowsActivities) {
return await Boards.updateAsync(this._id, { $set: { allowsActivities } });
},
async setAllowsReceivedDate(allowsReceivedDate) {
return await Boards.updateAsync(this._id, { $set: { allowsReceivedDate } });
},
async setAllowsSpentTime(allowsSpentTime) {
return await Boards.updateAsync(this._id, { $set: { allowsSpentTime } });
},
async setAllowsSpentTimeOnMinicard(allowsSpentTimeOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsSpentTimeOnMinicard } });
},
// #6688: the card sections and minicard badges that had no toggle before.
async setAllowsStickers(allowsStickers) {
return await Boards.updateAsync(this._id, { $set: { allowsStickers } });
},
async setAllowsStickersOnMinicard(allowsStickersOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsStickersOnMinicard } });
},
async setAllowsLocation(allowsLocation) {
return await Boards.updateAsync(this._id, { $set: { allowsLocation } });
},
async setAllowsDependencies(allowsDependencies) {
return await Boards.updateAsync(this._id, { $set: { allowsDependencies } });
},
async setAllowsDependenciesOnMinicard(allowsDependenciesOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsDependenciesOnMinicard } });
},
async setAllowsFlowtime(allowsFlowtime) {
return await Boards.updateAsync(this._id, { $set: { allowsFlowtime } });
},
async setAllowsPomodoro(allowsPomodoro) {
return await Boards.updateAsync(this._id, { $set: { allowsPomodoro } });
},
async setAllowsVote(allowsVote) {
return await Boards.updateAsync(this._id, { $set: { allowsVote } });
},
async setAllowsVoteOnMinicard(allowsVoteOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsVoteOnMinicard } });
},
async setAllowsPoker(allowsPoker) {
return await Boards.updateAsync(this._id, { $set: { allowsPoker } });
},
async setAllowsPokerOnMinicard(allowsPokerOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsPokerOnMinicard } });
},
async setAllowsTextNotes(allowsTextNotes) {
return await Boards.updateAsync(this._id, { $set: { allowsTextNotes } });
},
async setAllowsCommentCountOnMinicard(allowsCommentCountOnMinicard) {
return await Boards.updateAsync(this._id, { $set: { allowsCommentCountOnMinicard } });
},
getRestrictCommentEditing() {
return !!this.restrictCommentEditing;
},
async setRestrictCommentEditing(restrictCommentEditing) {
return await Boards.updateAsync(this._id, {
$set: { restrictCommentEditing: !!restrictCommentEditing },
});
},
getAllowsPersonalListWidth() {
return !!this.allowsPersonalListWidth;
},
async setAllowsPersonalListWidth(allowsPersonalListWidth) {
return await Boards.updateAsync(this._id, {
$set: { allowsPersonalListWidth: !!allowsPersonalListWidth },
});
},
getAutoWidth() {
return !!this.autoWidth;
},
// #3847: board-wide sticky list headers, toggled from the List hamburger
// menu (see server/models/users.js#setStickyListHeaders).
getStickyListHeaders() {
return !!this.stickyListHeaders;
},
async setStickyListHeaders(stickyListHeaders) {
return await Boards.updateAsync(this._id, {
$set: { stickyListHeaders: !!stickyListHeaders },
});
},
async setAutoWidth(autoWidth) {
return await Boards.updateAsync(this._id, {
$set: { autoWidth: !!autoWidth },
});
},
getListWidthResizeLocked() {
return !!this.listWidthResizeLocked;
},
async setListWidthResizeLocked(listWidthResizeLocked) {
return await Boards.updateAsync(this._id, {
$set: { listWidthResizeLocked: !!listWidthResizeLocked },
});
},
getSwimlaneHeightResizeLocked() {
return !!this.swimlaneHeightResizeLocked;
},
async setSwimlaneHeightResizeLocked(swimlaneHeightResizeLocked) {
return await Boards.updateAsync(this._id, {
$set: { swimlaneHeightResizeLocked: !!swimlaneHeightResizeLocked },
});
},
// Board Settings / Board View. Both setters apply the pure modifiers of
// models/lib/boardViewSettings.js and are called from the popup the way
// setSwimlaneHeightResizeLocked is; Boards.allow's update rule
// (server/permissions/boards.js) is what limits them to a board admin.
// A null modifier is a refused click (hiding the default view, an unknown
// view) and writes nothing.
isBoardViewShown(view, visibility) {
return boardViewSettings.isBoardViewShown(this, view, visibility);
},
defaultBoardView(visibility) {
return boardViewSettings.defaultBoardView(this, visibility);
},
async setBoardViewShown(view, visibility, shown) {
const $set = boardViewSettings.showBoardViewModifier(this, view, visibility, shown);
if (!$set) return false;
return await Boards.updateAsync(this._id, { $set });
},
async setDefaultBoardView(view, visibility) {
const $set = boardViewSettings.defaultBoardViewModifier(this, view, visibility);
if (!$set) return false;
return await Boards.updateAsync(this._id, { $set });
},
// The up/down arrows of Board Settings / Board View. Re-reads this
// board's current order, so two quick clicks each move from where the
// previous one left it; a no-op (first row up, last row down) writes
// nothing.
async moveBoardView(view, direction) {
const order = boardViewSettings.moveBoardView(this.boardViewOrder, view, direction);
const before = boardViewSettings.normalizeBoardViewOrder(this.boardViewOrder);
if (order.every((v, i) => v === before[i])) return false;
return await Boards.updateAsync(this._id, { $set: { boardViewOrder: order } });
},
getSameWidthForAllLists() {
return !!this.sameWidthForAllLists;
},
async setSameWidthForAllLists(sameWidthForAllLists) {
return await Boards.updateAsync(this._id, {
$set: { sameWidthForAllLists: !!sameWidthForAllLists },
});
},
// #2489: WIP limit groups - see the schema comment above for what these are.
getWipLimitGroups() {
return Array.isArray(this.wipLimitGroups) ? this.wipLimitGroups : [];
},
async addWipLimitGroup(listIds, limit, name = '') {
const group = {
_id: Random.id(6),
name: name || '',
listIds: Array.isArray(listIds) ? listIds : [],
limit: Number.isFinite(limit) && limit > 0 ? limit : 1,
enabled: true,
};
await Boards.updateAsync(this._id, {
$push: { wipLimitGroups: group },
});
return group._id;
},
async updateWipLimitGroup(groupId, fields = {}) {
const $set = {};
if (Array.isArray(fields.listIds)) {
$set['wipLimitGroups.$.listIds'] = fields.listIds;
}
if (Number.isFinite(fields.limit) && fields.limit > 0) {
$set['wipLimitGroups.$.limit'] = fields.limit;
}
if (typeof fields.name === 'string') {
$set['wipLimitGroups.$.name'] = fields.name;
}
if (typeof fields.enabled === 'boolean') {
$set['wipLimitGroups.$.enabled'] = fields.enabled;
}
if (Object.keys($set).length === 0) {
return 0;
}
return await Boards.updateAsync(
{ _id: this._id, 'wipLimitGroups._id': groupId },
{ $set },
);
},
async removeWipLimitGroup(groupId) {
return await Boards.updateAsync(this._id, {
$pull: { wipLimitGroups: { _id: groupId } },
});
},
getSameWidthForAllListsValue() {
return this.sameWidthForAllListsValue;
},
async setSameWidthForAllListsValue(sameWidthForAllListsValue) {
return await Boards.updateAsync(this._id, {
$set: { sameWidthForAllListsValue: sameWidthForAllListsValue },
});
},
async setAllowsCardCounterList(allowsCardCounterList) {
return await Boards.updateAsync(this._id, { $set: { allowsCardCounterList } });
},
async setCardAging(cardAging) {
return await Boards.updateAsync(this._id, { $set: { cardAging } });
},
async setShowDependencies(showDependencies) {
return await Boards.updateAsync(this._id, { $set: { showDependencies } });
},
async setCardAgingDays(cardAgingDays1, cardAgingDays2, cardAgingDays3) {
return await Boards.updateAsync(this._id, {
$set: { cardAgingDays1, cardAgingDays2, cardAgingDays3 },
});
},
async setAllowsBoardMemberList(allowsBoardMemberList) {
return await Boards.updateAsync(this._id, { $set: { allowsBoardMemberList } });
},
async setAllowsStartDate(allowsStartDate) {
return await Boards.updateAsync(this._id, { $set: { allowsStartDate } });
},
async setAllowsEndDate(allowsEndDate) {
return await Boards.updateAsync(this._id, { $set: { allowsEndDate } });
},
async setAllowsDueDate(allowsDueDate) {
return await Boards.updateAsync(this._id, { $set: { allowsDueDate } });
},
async setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
if (Meteor.isServer && subtasksDefaultBoardId) {
const { canWriteSubtaskDeposit, recordSubtaskDepositDenial } = require('/server/lib/subtaskDepositAccess');
if (!(await canWriteSubtaskDeposit(Meteor.userId(), subtasksDefaultBoardId))) {
recordSubtaskDepositDenial('setSubtasksDefaultBoardId');
throw new Meteor.Error('not-authorized');
}
}
return await Boards.updateAsync(this._id, { $set: { subtasksDefaultBoardId } });
},
async setSubtasksDefaultListId(subtasksDefaultListId) {
return await Boards.updateAsync(this._id, { $set: { subtasksDefaultListId } });
},
async setPresentParentTask(presentParentTask) {
return await Boards.updateAsync(this._id, { $set: { presentParentTask } });
},
async move(sortIndex) {
return await Boards.updateAsync(this._id, { $set: { sort: sortIndex } });
},
async toggleShowActivities() {
return await Boards.updateAsync(this._id, { $set: { showActivities: !this.showActivities } });
},
});
Boards.uniqueTitle = async title => {
const m = title.match(
new RegExp('^(?<title>.*?)\\s*(\\[(?<num>\\d+)]\\s*$|\\s*$)'),
);
const base = escapeForRegex(m.groups.title);
const baseTitle = m.groups.title;
const boards = await ReactiveCache.getBoards({ title: new RegExp(`^${base}\\s*(\\[(?<num>\\d+)]\\s*$|\\s*$)`) });
if (boards.length > 0) {
let num = 0;
const numberedBoards = await ReactiveCache.getBoards({ title: new RegExp(`^${base}\\s*\\[\\d+]\\s*$`) });
for (const board of numberedBoards) {
const m = board.title.match(
new RegExp('^(?<title>.*?)\\s*\\[(?<num>\\d+)]\\s*$'),
);
if (m) {
const n = parseInt(m.groups.num, 10);
num = num < n ? n : num;
}
}
return `${baseTitle} [${num + 1}]`;
}
return title;
};
// Non-async: returns data on client, Promise on server.
// Server callers must await.
// Boards matching `selector` that the user may search. `options.includePublic:
// false` drops the "anybody may open this" clause, the same choice as
// Boards.userBoards - this is what resolves a `board:name` filter, so it has to
// scope the same way the search around it does, or the filter would name a board
// the search cannot return anything from.
Boards.userSearch = (
userId,
selector = {},
projection = {},
options = {},
) => {
selector.$or = options.includePublic === false ? [] : [{ permission: 'public' }];
if (userId) {
selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
}
// An anonymous caller with public boards excluded can reach nothing, and an
// empty `$or` matches NOTHING in Mongo but is an error in some backends - so
// say it explicitly rather than leaving a selector that means "no boards" by
// accident.
if (selector.$or.length === 0) {
return Meteor.isServer ? Promise.resolve([]) : [];
}
return ReactiveCache.getBoards(selector, projection);
};
// The ways a user reaches a board. `{ permission: 'public' }` is the odd one out:
// it is not a relationship to the user at all, it is "anybody may open this". That
// belongs in the boards LIST - a public board is meant to be discoverable - but not
// in a search over "all boards", where it means every public board on the instance
// is searched, and a hit lands the user in somebody else's board they have no part
// in. `options.includePublic: false` leaves it out (see Boards.userBoardIds).
//
// Non-async: returns data on client (for Blaze templates), Promise on server.
// Server callers must await.
Boards.userBoards = (
userId,
archived = false,
selector = {},
projection = {},
options = {},
) => {
const includePublic = options.includePublic !== false;
const _buildSelector = (user) => {
if (!user) return null;
if (typeof archived === 'boolean') {
selector.archived = archived;
}
if (!selector.type) {
selector.type = 'board';
}
// #5582: never surface internal helper boards whose title is wrapped in
// carets (e.g. `^Subtasks^`). Only set this when the caller did not already
// constrain the title.
if (selector.title === undefined) {
selector.title = notHelperBoardTitle();
}
// GHSA-gwc4-fw7p-gw58: the same builder the `board` publication uses, so
// "which boards may this user see" has one answer and cannot drift.
selector.$or = boardVisibilitySelectors({
userId,
orgIds: user.orgIds(),
teamIds: user.teamIds(),
emailDomains: user.emailDomains(),
includePublic,
membersOnly: options.membersOnly === true,
});
return selector;
};
if (Meteor.isServer) {
return (async () => {
const user = await ReactiveCache.getUser(userId);
if (!_buildSelector(user)) return [];
return await ReactiveCache.getBoards(selector, projection);
})();
}
const user = ReactiveCache.getUser(userId);
if (!_buildSelector(user)) return [];
return ReactiveCache.getBoards(selector, projection);
};
Boards.userBoardIds = async (userId, archived = false, selector = {}, options = {}) => {
const boards = await Boards.userBoards(userId, archived, selector, {
fields: { _id: 1 },
}, options);
return boards.map(board => {
return board._id;
});
};
Boards.colorMap = () => {
const colors = {};
try {
const TAPi18n = getTAPi18n();
for (const color of Boards.labelColors()) {
colors[TAPi18n.__(`color-${color}`)] = color;
}
} catch (e) {
// i18n not ready yet, return empty map
// The colorMap will be regenerated when i18n is ready
}
return colors;
};
Boards.labelColors = () => {
return LABEL_COLORS;
};
export default Boards;