boards.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196
  1. import escapeForRegex from 'escape-string-regexp';
  2. import { TAPi18n } from '/imports/i18n';
  3. import {
  4. ALLOWED_BOARD_COLORS,
  5. ALLOWED_COLORS,
  6. TYPE_BOARD,
  7. TYPE_TEMPLATE_BOARD,
  8. TYPE_TEMPLATE_CONTAINER,
  9. } from '/config/const';
  10. import Users from "./users";
  11. Boards = new Mongo.Collection('boards');
  12. /**
  13. * This is a Board.
  14. */
  15. Boards.attachSchema(
  16. new SimpleSchema({
  17. title: {
  18. /**
  19. * The title of the board
  20. */
  21. type: String,
  22. },
  23. slug: {
  24. /**
  25. * The title slugified.
  26. */
  27. type: String,
  28. // eslint-disable-next-line consistent-return
  29. autoValue() {
  30. // In some cases (Chinese and Japanese for instance) the `getSlug` function
  31. // return an empty string. This is causes bugs in our application so we set
  32. // a default slug in this case.
  33. // Improvment would be to change client URL after slug is changed
  34. const title = this.field('title');
  35. if (title.isSet && !this.isSet) {
  36. let slug = 'board';
  37. slug = getSlug(title.value) || slug;
  38. return slug;
  39. }
  40. },
  41. },
  42. archived: {
  43. /**
  44. * Is the board archived?
  45. */
  46. type: Boolean,
  47. // eslint-disable-next-line consistent-return
  48. autoValue() {
  49. if (this.isInsert && !this.isSet) {
  50. return false;
  51. }
  52. },
  53. },
  54. archivedAt: {
  55. /**
  56. * Latest archiving time of the board
  57. */
  58. type: Date,
  59. optional: true,
  60. },
  61. createdAt: {
  62. /**
  63. * Creation time of the board
  64. */
  65. type: Date,
  66. // eslint-disable-next-line consistent-return
  67. autoValue() {
  68. if (this.isInsert) {
  69. return new Date();
  70. } else if (this.isUpsert) {
  71. return { $setOnInsert: new Date() };
  72. } else {
  73. this.unset();
  74. }
  75. },
  76. },
  77. // XXX Inconsistent field naming
  78. modifiedAt: {
  79. /**
  80. * Last modification time of the board
  81. */
  82. type: Date,
  83. optional: true,
  84. // eslint-disable-next-line consistent-return
  85. autoValue() {
  86. if (this.isInsert || this.isUpsert || this.isUpdate) {
  87. return new Date();
  88. } else {
  89. this.unset();
  90. }
  91. },
  92. },
  93. // De-normalized number of users that have starred this board
  94. stars: {
  95. /**
  96. * How many stars the board has
  97. */
  98. type: Number,
  99. // eslint-disable-next-line consistent-return
  100. autoValue() {
  101. if (this.isInsert) {
  102. return 0;
  103. }
  104. },
  105. },
  106. // De-normalized label system
  107. labels: {
  108. /**
  109. * List of labels attached to a board
  110. */
  111. type: [Object],
  112. optional: true,
  113. /* Commented out, so does not create labels to new boards.
  114. // eslint-disable-next-line consistent-return
  115. autoValue() {
  116. if (this.isInsert && !this.isSet) {
  117. const colors = Boards.simpleSchema()._schema['labels.$.color']
  118. .allowedValues;
  119. const defaultLabelsColors = _.clone(colors).splice(0, 6);
  120. return defaultLabelsColors.map(color => ({
  121. color,
  122. _id: Random.id(6),
  123. name: '',
  124. }));
  125. }
  126. },
  127. */
  128. },
  129. 'labels.$._id': {
  130. /**
  131. * Unique id of a label
  132. */
  133. // We don't specify that this field must be unique in the board because that
  134. // will cause performance penalties and is not necessary since this field is
  135. // always set on the server.
  136. // XXX Actually if we create a new label, the `_id` is set on the client
  137. // without being overwritten by the server, could it be a problem?
  138. type: String,
  139. },
  140. 'labels.$.name': {
  141. /**
  142. * Name of a label
  143. */
  144. type: String,
  145. optional: true,
  146. },
  147. 'labels.$.color': {
  148. /**
  149. * color of a label.
  150. *
  151. * Can be amongst `green`, `yellow`, `orange`, `red`, `purple`,
  152. * `blue`, `sky`, `lime`, `pink`, `black`,
  153. * `silver`, `peachpuff`, `crimson`, `plum`, `darkgreen`,
  154. * `slateblue`, `magenta`, `gold`, `navy`, `gray`,
  155. * `saddlebrown`, `paleturquoise`, `mistyrose`, `indigo`
  156. */
  157. type: String,
  158. allowedValues: ALLOWED_COLORS,
  159. },
  160. // XXX We might want to maintain more informations under the member sub-
  161. // documents like de-normalized meta-data (the date the member joined the
  162. // board, the number of contributions, etc.).
  163. members: {
  164. /**
  165. * List of members of a board
  166. */
  167. type: [Object],
  168. // eslint-disable-next-line consistent-return
  169. autoValue() {
  170. if (this.isInsert && !this.isSet) {
  171. return [
  172. {
  173. userId: this.userId,
  174. isAdmin: true,
  175. isActive: true,
  176. isNoComments: false,
  177. isCommentOnly: false,
  178. isWorker: false,
  179. },
  180. ];
  181. }
  182. },
  183. },
  184. 'members.$.userId': {
  185. /**
  186. * The uniq ID of the member
  187. */
  188. type: String,
  189. },
  190. 'members.$.isAdmin': {
  191. /**
  192. * Is the member an admin of the board?
  193. */
  194. type: Boolean,
  195. },
  196. 'members.$.isActive': {
  197. /**
  198. * Is the member active?
  199. */
  200. type: Boolean,
  201. },
  202. 'members.$.isNoComments': {
  203. /**
  204. * Is the member not allowed to make comments
  205. */
  206. type: Boolean,
  207. optional: true,
  208. },
  209. 'members.$.isCommentOnly': {
  210. /**
  211. * Is the member only allowed to comment on the board
  212. */
  213. type: Boolean,
  214. optional: true,
  215. },
  216. 'members.$.isWorker': {
  217. /**
  218. * Is the member only allowed to move card, assign himself to card and comment
  219. */
  220. type: Boolean,
  221. optional: true,
  222. },
  223. permission: {
  224. /**
  225. * visibility of the board
  226. */
  227. type: String,
  228. allowedValues: ['public', 'private'],
  229. },
  230. orgs: {
  231. /**
  232. * the list of organizations that a board belongs to
  233. */
  234. type: [Object],
  235. optional: true,
  236. },
  237. 'orgs.$.orgId':{
  238. /**
  239. * The uniq ID of the organization
  240. */
  241. type: String,
  242. },
  243. 'orgs.$.orgDisplayName':{
  244. /**
  245. * The display name of the organization
  246. */
  247. type: String,
  248. },
  249. 'orgs.$.isActive': {
  250. /**
  251. * Is the organization active?
  252. */
  253. type: Boolean,
  254. },
  255. teams: {
  256. /**
  257. * the list of teams that a board belongs to
  258. */
  259. type: [Object],
  260. optional: true,
  261. },
  262. 'teams.$.teamId':{
  263. /**
  264. * The uniq ID of the team
  265. */
  266. type: String,
  267. },
  268. 'teams.$.teamDisplayName':{
  269. /**
  270. * The display name of the team
  271. */
  272. type: String,
  273. },
  274. 'teams.$.isActive': {
  275. /**
  276. * Is the team active?
  277. */
  278. type: Boolean,
  279. },
  280. color: {
  281. /**
  282. * The color of the board.
  283. */
  284. type: String,
  285. allowedValues: ALLOWED_BOARD_COLORS,
  286. // eslint-disable-next-line consistent-return
  287. autoValue() {
  288. if (this.isInsert && !this.isSet) {
  289. return ALLOWED_BOARD_COLORS[0];
  290. }
  291. },
  292. },
  293. description: {
  294. /**
  295. * The description of the board
  296. */
  297. type: String,
  298. optional: true,
  299. },
  300. subtasksDefaultBoardId: {
  301. /**
  302. * The default board ID assigned to subtasks.
  303. */
  304. type: String,
  305. optional: true,
  306. defaultValue: null,
  307. },
  308. subtasksDefaultListId: {
  309. /**
  310. * The default List ID assigned to subtasks.
  311. */
  312. type: String,
  313. optional: true,
  314. defaultValue: null,
  315. },
  316. dateSettingsDefaultBoardId: {
  317. type: String,
  318. optional: true,
  319. defaultValue: null,
  320. },
  321. dateSettingsDefaultListId: {
  322. type: String,
  323. optional: true,
  324. defaultValue: null,
  325. },
  326. allowsSubtasks: {
  327. /**
  328. * Does the board allows subtasks?
  329. */
  330. type: Boolean,
  331. defaultValue: true,
  332. },
  333. allowsAttachments: {
  334. /**
  335. * Does the board allows attachments?
  336. */
  337. type: Boolean,
  338. defaultValue: true,
  339. },
  340. allowsChecklists: {
  341. /**
  342. * Does the board allows checklists?
  343. */
  344. type: Boolean,
  345. defaultValue: true,
  346. },
  347. allowsComments: {
  348. /**
  349. * Does the board allows comments?
  350. */
  351. type: Boolean,
  352. defaultValue: true,
  353. },
  354. allowsDescriptionTitle: {
  355. /**
  356. * Does the board allows description title?
  357. */
  358. type: Boolean,
  359. defaultValue: true,
  360. },
  361. allowsDescriptionText: {
  362. /**
  363. * Does the board allows description text?
  364. */
  365. type: Boolean,
  366. defaultValue: true,
  367. },
  368. allowsCardNumber: {
  369. /**
  370. * Does the board allows card numbers?
  371. */
  372. type: Boolean,
  373. defaultValue: false,
  374. },
  375. allowsActivities: {
  376. /**
  377. * Does the board allows comments?
  378. */
  379. type: Boolean,
  380. defaultValue: true,
  381. },
  382. allowsLabels: {
  383. /**
  384. * Does the board allows labels?
  385. */
  386. type: Boolean,
  387. defaultValue: true,
  388. },
  389. allowsCreator: {
  390. /**
  391. * Does the board allow creator?
  392. */
  393. type: Boolean,
  394. defaultValue: true,
  395. },
  396. allowsAssignee: {
  397. /**
  398. * Does the board allows assignee?
  399. */
  400. type: Boolean,
  401. defaultValue: true,
  402. },
  403. allowsMembers: {
  404. /**
  405. * Does the board allows members?
  406. */
  407. type: Boolean,
  408. defaultValue: true,
  409. },
  410. allowsRequestedBy: {
  411. /**
  412. * Does the board allows requested by?
  413. */
  414. type: Boolean,
  415. defaultValue: true,
  416. },
  417. allowsCardSortingByNumber: {
  418. /**
  419. * Does the board allows card sorting by number?
  420. */
  421. type: Boolean,
  422. defaultValue: true,
  423. },
  424. allowsShowLists: {
  425. /**
  426. * Does the board allows show lists on the card?
  427. */
  428. type: Boolean,
  429. defaultValue: true,
  430. },
  431. allowsAssignedBy: {
  432. /**
  433. * Does the board allows requested by?
  434. */
  435. type: Boolean,
  436. defaultValue: true,
  437. },
  438. allowsReceivedDate: {
  439. /**
  440. * Does the board allows received date?
  441. */
  442. type: Boolean,
  443. defaultValue: true,
  444. },
  445. allowsStartDate: {
  446. /**
  447. * Does the board allows start date?
  448. */
  449. type: Boolean,
  450. defaultValue: true,
  451. },
  452. allowsEndDate: {
  453. /**
  454. * Does the board allows end date?
  455. */
  456. type: Boolean,
  457. defaultValue: true,
  458. },
  459. allowsDueDate: {
  460. /**
  461. * Does the board allows due date?
  462. */
  463. type: Boolean,
  464. defaultValue: true,
  465. },
  466. presentParentTask: {
  467. /**
  468. * Controls how to present the parent task:
  469. *
  470. * - `prefix-with-full-path`: add a prefix with the full path
  471. * - `prefix-with-parent`: add a prefisx with the parent name
  472. * - `subtext-with-full-path`: add a subtext with the full path
  473. * - `subtext-with-parent`: add a subtext with the parent name
  474. * - `no-parent`: does not show the parent at all
  475. */
  476. type: String,
  477. allowedValues: [
  478. 'prefix-with-full-path',
  479. 'prefix-with-parent',
  480. 'subtext-with-full-path',
  481. 'subtext-with-parent',
  482. 'no-parent',
  483. ],
  484. optional: true,
  485. defaultValue: 'no-parent',
  486. },
  487. receivedAt: {
  488. /**
  489. * Date the card was received
  490. */
  491. type: Date,
  492. optional: true,
  493. },
  494. startAt: {
  495. /**
  496. * Starting date of the board.
  497. */
  498. type: Date,
  499. optional: true,
  500. },
  501. dueAt: {
  502. /**
  503. * Due date of the board.
  504. */
  505. type: Date,
  506. optional: true,
  507. },
  508. endAt: {
  509. /**
  510. * End date of the board.
  511. */
  512. type: Date,
  513. optional: true,
  514. },
  515. spentTime: {
  516. /**
  517. * Time spent in the board.
  518. */
  519. type: Number,
  520. decimal: true,
  521. optional: true,
  522. },
  523. isOvertime: {
  524. /**
  525. * Is the board overtimed?
  526. */
  527. type: Boolean,
  528. defaultValue: false,
  529. optional: true,
  530. },
  531. type: {
  532. /**
  533. * The type of board
  534. * possible values: board, template-board, template-container
  535. */
  536. type: String,
  537. defaultValue: TYPE_BOARD,
  538. allowedValues: [TYPE_BOARD, TYPE_TEMPLATE_BOARD, TYPE_TEMPLATE_CONTAINER],
  539. },
  540. sort: {
  541. /**
  542. * Sort value
  543. */
  544. type: Number,
  545. decimal: true,
  546. defaultValue: -1,
  547. },
  548. }),
  549. );
  550. Boards.helpers({
  551. copy() {
  552. const oldId = this._id;
  553. delete this._id;
  554. delete this.slug;
  555. this.title = this.copyTitle();
  556. const _id = Boards.insert(this);
  557. // Copy all swimlanes in board
  558. Swimlanes.find({
  559. boardId: oldId,
  560. archived: false,
  561. }).forEach(swimlane => {
  562. swimlane.type = 'swimlane';
  563. swimlane.copy(_id);
  564. });
  565. // copy custom field definitions
  566. const cfMap = {};
  567. CustomFields.find({ boardIds: oldId }).forEach(cf => {
  568. const id = cf._id;
  569. delete cf._id;
  570. cf.boardIds = [_id];
  571. cfMap[id] = CustomFields.insert(cf);
  572. });
  573. Cards.find({ boardId: _id }).forEach(card => {
  574. Cards.update(card._id, {
  575. $set: {
  576. customFields: card.customFields.map(cf => {
  577. cf._id = cfMap[cf._id];
  578. return cf;
  579. }),
  580. },
  581. });
  582. });
  583. // copy rules, actions, and triggers
  584. const actionsMap = {};
  585. Actions.find({ boardId: oldId }).forEach(action => {
  586. const id = action._id;
  587. delete action._id;
  588. action.boardId = _id;
  589. actionsMap[id] = Actions.insert(action);
  590. });
  591. const triggersMap = {};
  592. Triggers.find({ boardId: oldId }).forEach(trigger => {
  593. const id = trigger._id;
  594. delete trigger._id;
  595. trigger.boardId = _id;
  596. triggersMap[id] = Triggers.insert(trigger);
  597. });
  598. Rules.find({ boardId: oldId }).forEach(rule => {
  599. delete rule._id;
  600. rule.boardId = _id;
  601. rule.actionId = actionsMap[rule.actionId];
  602. rule.triggerId = triggersMap[rule.triggerId];
  603. Rules.insert(rule);
  604. });
  605. return _id;
  606. },
  607. /**
  608. * Return a unique title based on the current title
  609. *
  610. * @returns {string|null}
  611. */
  612. copyTitle() {
  613. return Boards.uniqueTitle(this.title);
  614. },
  615. /**
  616. * Is supplied user authorized to view this board?
  617. */
  618. isVisibleBy(user) {
  619. if (this.isPublic()) {
  620. // public boards are visible to everyone
  621. return true;
  622. } else {
  623. // otherwise you have to be logged-in and active member
  624. return user && this.isActiveMember(user._id);
  625. }
  626. },
  627. /**
  628. * Is the user one of the active members of the board?
  629. *
  630. * @param userId
  631. * @returns {boolean} the member that matches, or undefined/false
  632. */
  633. isActiveMember(userId) {
  634. if (userId) {
  635. return this.members.find(
  636. member => member.userId === userId && member.isActive,
  637. );
  638. } else {
  639. return false;
  640. }
  641. },
  642. isPublic() {
  643. return this.permission === 'public';
  644. },
  645. cards() {
  646. return Cards.find(
  647. { boardId: this._id, archived: false },
  648. { sort: { title: 1 } },
  649. );
  650. },
  651. lists() {
  652. //currentUser = Meteor.user();
  653. //if (currentUser) {
  654. // enabled = Meteor.user().hasSortBy();
  655. //}
  656. //return enabled ? this.newestLists() : this.draggableLists();
  657. return this.draggableLists();
  658. },
  659. newestLists() {
  660. // sorted lists from newest to the oldest, by its creation date or its cards' last modification date
  661. const value = Meteor.user()._getListSortBy();
  662. const sortKey = { starred: -1, [value[0]]: value[1] }; // [["starred",-1],value];
  663. return Lists.find(
  664. {
  665. boardId: this._id,
  666. archived: false,
  667. },
  668. { sort: sortKey },
  669. );
  670. },
  671. draggableLists() {
  672. return Lists.find({ boardId: this._id }, { sort: { sort: 1 } });
  673. },
  674. /** returns the last list
  675. * @returns Document the last list
  676. */
  677. getLastList() {
  678. const ret = Lists.findOne({ boardId: this._id }, { sort: { sort: 'desc' } });
  679. return ret;
  680. },
  681. nullSortLists() {
  682. return Lists.find({
  683. boardId: this._id,
  684. archived: false,
  685. sort: { $eq: null },
  686. });
  687. },
  688. swimlanes() {
  689. return Swimlanes.find(
  690. { boardId: this._id, archived: false },
  691. { sort: { sort: 1 } },
  692. );
  693. },
  694. nextSwimlane(swimlane) {
  695. return Swimlanes.findOne(
  696. {
  697. boardId: this._id,
  698. archived: false,
  699. sort: { $gte: swimlane.sort },
  700. _id: { $ne: swimlane._id },
  701. },
  702. {
  703. sort: { sort: 1 },
  704. },
  705. );
  706. },
  707. nullSortSwimlanes() {
  708. return Swimlanes.find({
  709. boardId: this._id,
  710. archived: false,
  711. sort: { $eq: null },
  712. });
  713. },
  714. hasOvertimeCards() {
  715. const card = Cards.findOne({
  716. isOvertime: true,
  717. boardId: this._id,
  718. archived: false,
  719. });
  720. return card !== undefined;
  721. },
  722. hasSpentTimeCards() {
  723. const card = Cards.findOne({
  724. spentTime: { $gt: 0 },
  725. boardId: this._id,
  726. archived: false,
  727. });
  728. return card !== undefined;
  729. },
  730. activities() {
  731. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  732. },
  733. activeMembers(){
  734. return _.where(this.members, { isActive: true });
  735. },
  736. activeMembers2(members, boardTeamUsers) {
  737. let allMembers = members;
  738. if(this.teams !== undefined && this.teams.length > 0){
  739. let index;
  740. if(boardTeamUsers && boardTeamUsers.count() > 0){
  741. boardTeamUsers.forEach((u) => {
  742. index = allMembers.findIndex(function(m){ return m.userId == u._id});
  743. if(index == -1){
  744. allMembers.push({
  745. "isActive": true,
  746. "isAdmin": u.isAdmin !== undefined ? u.isAdmin : false,
  747. "isCommentOnly" : false,
  748. "isNoComments" : false,
  749. "userId": u._id,
  750. });
  751. }
  752. });
  753. }
  754. }
  755. return allMembers;
  756. },
  757. activeOrgs() {
  758. return _.where(this.orgs, { isActive: true });
  759. },
  760. // hasNotAnyOrg(){
  761. // return this.orgs === undefined || this.orgs.length <= 0;
  762. // },
  763. activeTeams() {
  764. return _.where(this.teams, { isActive: true });
  765. },
  766. // hasNotAnyTeam(){
  767. // return this.teams === undefined || this.teams.length <= 0;
  768. // },
  769. activeAdmins() {
  770. return _.where(this.members, { isActive: true, isAdmin: true });
  771. },
  772. memberUsers() {
  773. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  774. },
  775. getLabel(name, color) {
  776. return _.findWhere(this.labels, { name, color });
  777. },
  778. getLabelById(labelId) {
  779. return _.findWhere(this.labels, { _id: labelId });
  780. },
  781. labelIndex(labelId) {
  782. return _.pluck(this.labels, '_id').indexOf(labelId);
  783. },
  784. memberIndex(memberId) {
  785. return _.pluck(this.members, 'userId').indexOf(memberId);
  786. },
  787. hasMember(memberId) {
  788. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  789. },
  790. hasAdmin(memberId) {
  791. return !!_.findWhere(this.members, {
  792. userId: memberId,
  793. isActive: true,
  794. isAdmin: true,
  795. });
  796. },
  797. hasNoComments(memberId) {
  798. return !!_.findWhere(this.members, {
  799. userId: memberId,
  800. isActive: true,
  801. isAdmin: false,
  802. isNoComments: true,
  803. isWorker: false,
  804. });
  805. },
  806. hasCommentOnly(memberId) {
  807. return !!_.findWhere(this.members, {
  808. userId: memberId,
  809. isActive: true,
  810. isAdmin: false,
  811. isCommentOnly: true,
  812. isWorker: false,
  813. });
  814. },
  815. hasWorker(memberId) {
  816. return !!_.findWhere(this.members, {
  817. userId: memberId,
  818. isActive: true,
  819. isAdmin: false,
  820. isCommentOnly: false,
  821. isWorker: true,
  822. });
  823. },
  824. hasAnyAllowsDate() {
  825. const ret = this.allowsReceivedDate || this.allowsStartDate || this.allowsDueDate || this.allowsEndDate;
  826. return ret;
  827. },
  828. hasAnyAllowsUser() {
  829. const ret = this.allowsCreator || this.allowsMembers || this.allowsAssignee || this.allowsRequestedBy || this.allowsAssignedBy;
  830. return ret;
  831. },
  832. absoluteUrl() {
  833. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  834. },
  835. originRelativeUrl() {
  836. return FlowRouter.path('board', { id: this._id, slug: this.slug });
  837. },
  838. colorClass() {
  839. return `board-color-${this.color}`;
  840. },
  841. customFields() {
  842. return CustomFields.find(
  843. { boardIds: { $in: [this._id] } },
  844. { sort: { name: 1 } },
  845. );
  846. },
  847. // XXX currently mutations return no value so we have an issue when using addLabel in import
  848. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  849. pushLabel(name, color) {
  850. const _id = Random.id(6);
  851. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  852. return _id;
  853. },
  854. /** sets the new label order
  855. * @param newLabelOrderOnlyIds new order array of _id, e.g. Array(4) [ "FvtD34", "PAEgDP", "LjRBxH", "YJ8sZz" ]
  856. */
  857. setNewLabelOrder(newLabelOrderOnlyIds) {
  858. if (this.labels.length == newLabelOrderOnlyIds.length) {
  859. if (this.labels.every(_label => newLabelOrderOnlyIds.indexOf(_label._id) >= 0)) {
  860. const newLabels = _.sortBy(this.labels, _label => newLabelOrderOnlyIds.indexOf(_label._id));
  861. if (this.labels.length == newLabels.length) {
  862. Boards.direct.update(this._id, {$set: {labels: newLabels}});
  863. }
  864. }
  865. }
  866. },
  867. searchBoards(term) {
  868. check(term, Match.OneOf(String, null, undefined));
  869. const query = { boardId: this._id };
  870. query.type = 'cardType-linkedBoard';
  871. query.archived = false;
  872. const projection = { limit: 10, sort: { createdAt: -1 } };
  873. if (term) {
  874. const regex = new RegExp(term, 'i');
  875. query.$or = [{ title: regex }, { description: regex }];
  876. }
  877. return Cards.find(query, projection);
  878. },
  879. searchSwimlanes(term) {
  880. check(term, Match.OneOf(String, null, undefined));
  881. const query = { boardId: this._id };
  882. if (this.isTemplatesBoard()) {
  883. query.type = 'template-swimlane';
  884. query.archived = false;
  885. } else {
  886. query.type = { $nin: ['template-swimlane'] };
  887. }
  888. const projection = { limit: 10, sort: { createdAt: -1 } };
  889. if (term) {
  890. const regex = new RegExp(term, 'i');
  891. query.$or = [{ title: regex }, { description: regex }];
  892. }
  893. return Swimlanes.find(query, projection);
  894. },
  895. searchLists(term) {
  896. let ret = null;
  897. if (term) {
  898. check(term, Match.OneOf(String));
  899. term = term.trim();
  900. }
  901. if (term) {
  902. const query = { boardId: this._id };
  903. if (this.isTemplatesBoard()) {
  904. query.type = 'template-list';
  905. query.archived = false;
  906. } else {
  907. query.type = { $nin: ['template-list'] };
  908. }
  909. const projection = { sort: { createdAt: -1 } };
  910. if (term) {
  911. const regex = new RegExp(term, 'i');
  912. query.$or = [{ title: regex }, { description: regex }];
  913. }
  914. ret = Lists.find(query, projection);
  915. }
  916. return ret;
  917. },
  918. searchCards(term, excludeLinked) {
  919. let ret = null;
  920. if (term) {
  921. check(term, Match.OneOf(String));
  922. term = term.trim();
  923. }
  924. if (term) {
  925. const query = { boardId: this._id };
  926. if (excludeLinked) {
  927. query.linkedId = null;
  928. }
  929. if (this.isTemplatesBoard()) {
  930. query.type = 'template-card';
  931. query.archived = false;
  932. } else {
  933. query.type = { $nin: ['template-card'] };
  934. }
  935. const projection = { sort: { createdAt: -1 } };
  936. const regex = new RegExp(term, 'i');
  937. query.$or = [
  938. { title: regex },
  939. { description: regex },
  940. { customFields: { $elemMatch: { value: regex } } },
  941. ];
  942. ret = Cards.find(query, projection);
  943. }
  944. return ret;
  945. },
  946. // A board alwasy has another board where it deposits subtasks of thasks
  947. // that belong to itself.
  948. getDefaultSubtasksBoardId() {
  949. if (
  950. this.subtasksDefaultBoardId === null ||
  951. this.subtasksDefaultBoardId === undefined
  952. ) {
  953. this.subtasksDefaultBoardId = Boards.insert({
  954. title: `^${this.title}^`,
  955. permission: this.permission,
  956. members: this.members,
  957. color: this.color,
  958. description: TAPi18n.__('default-subtasks-board', {
  959. board: this.title,
  960. }),
  961. });
  962. Swimlanes.insert({
  963. title: TAPi18n.__('default'),
  964. boardId: this.subtasksDefaultBoardId,
  965. });
  966. Boards.update(this._id, {
  967. $set: {
  968. subtasksDefaultBoardId: this.subtasksDefaultBoardId,
  969. },
  970. });
  971. }
  972. return this.subtasksDefaultBoardId;
  973. },
  974. getDefaultSubtasksBoard() {
  975. return Boards.findOne(this.getDefaultSubtasksBoardId());
  976. },
  977. //Date Settings option such as received date, start date and so on.
  978. getDefaultDateSettingsBoardId() {
  979. if (
  980. this.dateSettingsDefaultBoardId === null ||
  981. this.dateSettingsDefaultBoardId === undefined
  982. ) {
  983. this.dateSettingsDefaultBoardId = Boards.insert({
  984. title: `^${this.title}^`,
  985. permission: this.permission,
  986. members: this.members,
  987. color: this.color,
  988. description: TAPi18n.__('default-dates-board', {
  989. board: this.title,
  990. }),
  991. });
  992. Swimlanes.insert({
  993. title: TAPi18n.__('default'),
  994. boardId: this.dateSettingsDefaultBoardId,
  995. });
  996. Boards.update(this._id, {
  997. $set: {
  998. dateSettingsDefaultBoardId: this.dateSettingsDefaultBoardId,
  999. },
  1000. });
  1001. }
  1002. return this.dateSettingsDefaultBoardId;
  1003. },
  1004. getDefaultDateSettingsBoard() {
  1005. return Boards.findOne(this.getDefaultDateSettingsBoardId());
  1006. },
  1007. getDefaultSubtasksListId() {
  1008. if (
  1009. this.subtasksDefaultListId === null ||
  1010. this.subtasksDefaultListId === undefined
  1011. ) {
  1012. this.subtasksDefaultListId = Lists.insert({
  1013. title: TAPi18n.__('queue'),
  1014. boardId: this._id,
  1015. });
  1016. this.setSubtasksDefaultListId(this.subtasksDefaultListId);
  1017. }
  1018. return this.subtasksDefaultListId;
  1019. },
  1020. getDefaultSubtasksList() {
  1021. return Lists.findOne(this.getDefaultSubtasksListId());
  1022. },
  1023. getDefaultDateSettingsListId() {
  1024. if (
  1025. this.dateSettingsDefaultListId === null ||
  1026. this.dateSettingsDefaultListId === undefined
  1027. ) {
  1028. this.dateSettingsDefaultListId = Lists.insert({
  1029. title: TAPi18n.__('queue'),
  1030. boardId: this._id,
  1031. });
  1032. this.setDateSettingsDefaultListId(this.dateSettingsDefaultListId);
  1033. }
  1034. return this.dateSettingsDefaultListId;
  1035. },
  1036. getDefaultDateSettingsList() {
  1037. return Lists.findOne(this.getDefaultDateSettingsListId());
  1038. },
  1039. getDefaultSwimline() {
  1040. let result = Swimlanes.findOne({ boardId: this._id });
  1041. if (result === undefined) {
  1042. Swimlanes.insert({
  1043. title: TAPi18n.__('default'),
  1044. boardId: this._id,
  1045. });
  1046. result = Swimlanes.findOne({ boardId: this._id });
  1047. }
  1048. return result;
  1049. },
  1050. getNextCardNumber() {
  1051. const boardCards = Cards.find(
  1052. {
  1053. boardId: this._id
  1054. },
  1055. {
  1056. sort: { cardNumber: -1 },
  1057. limit: 1
  1058. }
  1059. ).fetch();
  1060. // If no card is assigned to the board, return 1
  1061. if (!boardCards || boardCards.length === 0) {
  1062. return 1;
  1063. }
  1064. const maxCardNr = !!boardCards[0].cardNumber ? boardCards[0].cardNumber : 0;
  1065. return maxCardNr + 1;
  1066. },
  1067. cardsDueInBetween(start, end) {
  1068. return Cards.find({
  1069. boardId: this._id,
  1070. dueAt: { $gte: start, $lte: end },
  1071. });
  1072. },
  1073. cardsInInterval(start, end) {
  1074. return Cards.find({
  1075. boardId: this._id,
  1076. $or: [
  1077. {
  1078. startAt: {
  1079. $lte: start,
  1080. },
  1081. endAt: {
  1082. $gte: start,
  1083. },
  1084. },
  1085. {
  1086. startAt: {
  1087. $lte: end,
  1088. },
  1089. endAt: {
  1090. $gte: end,
  1091. },
  1092. },
  1093. {
  1094. startAt: {
  1095. $gte: start,
  1096. },
  1097. endAt: {
  1098. $lte: end,
  1099. },
  1100. },
  1101. ],
  1102. });
  1103. },
  1104. isTemplateBoard() {
  1105. return this.type === 'template-board';
  1106. },
  1107. isTemplatesBoard() {
  1108. return this.type === 'template-container';
  1109. },
  1110. });
  1111. Boards.mutations({
  1112. archive() {
  1113. return { $set: { archived: true, archivedAt: new Date() } };
  1114. },
  1115. restore() {
  1116. return { $set: { archived: false } };
  1117. },
  1118. rename(title) {
  1119. return { $set: { title } };
  1120. },
  1121. setDescription(description) {
  1122. return { $set: { description } };
  1123. },
  1124. setColor(color) {
  1125. return { $set: { color } };
  1126. },
  1127. setVisibility(visibility) {
  1128. return { $set: { permission: visibility } };
  1129. },
  1130. addLabel(name, color) {
  1131. // If label with the same name and color already exists we don't want to
  1132. // create another one because they would be indistinguishable in the UI
  1133. // (they would still have different `_id` but that is not exposed to the
  1134. // user).
  1135. if (!this.getLabel(name, color)) {
  1136. const _id = Random.id(6);
  1137. return { $push: { labels: { _id, name, color } } };
  1138. }
  1139. return {};
  1140. },
  1141. editLabel(labelId, name, color) {
  1142. if (!this.getLabel(name, color)) {
  1143. const labelIndex = this.labelIndex(labelId);
  1144. return {
  1145. $set: {
  1146. [`labels.${labelIndex}.name`]: name,
  1147. [`labels.${labelIndex}.color`]: color,
  1148. },
  1149. };
  1150. }
  1151. return {};
  1152. },
  1153. removeLabel(labelId) {
  1154. return { $pull: { labels: { _id: labelId } } };
  1155. },
  1156. changeOwnership(fromId, toId) {
  1157. const memberIndex = this.memberIndex(fromId);
  1158. return {
  1159. $set: {
  1160. [`members.${memberIndex}.userId`]: toId,
  1161. },
  1162. };
  1163. },
  1164. addMember(memberId) {
  1165. const memberIndex = this.memberIndex(memberId);
  1166. if (memberIndex >= 0) {
  1167. return {
  1168. $set: {
  1169. [`members.${memberIndex}.isActive`]: true,
  1170. },
  1171. };
  1172. }
  1173. return {
  1174. $push: {
  1175. members: {
  1176. userId: memberId,
  1177. isAdmin: false,
  1178. isActive: true,
  1179. isNoComments: false,
  1180. isCommentOnly: false,
  1181. isWorker: false,
  1182. },
  1183. },
  1184. };
  1185. },
  1186. removeMember(memberId) {
  1187. const memberIndex = this.memberIndex(memberId);
  1188. // we do not allow the only one admin to be removed
  1189. const allowRemove =
  1190. !this.members[memberIndex].isAdmin || this.activeAdmins().length > 1;
  1191. if (!allowRemove) {
  1192. return {
  1193. $set: {
  1194. [`members.${memberIndex}.isActive`]: true,
  1195. },
  1196. };
  1197. }
  1198. return {
  1199. $set: {
  1200. [`members.${memberIndex}.isActive`]: false,
  1201. [`members.${memberIndex}.isAdmin`]: false,
  1202. },
  1203. };
  1204. },
  1205. setMemberPermission(
  1206. memberId,
  1207. isAdmin,
  1208. isNoComments,
  1209. isCommentOnly,
  1210. isWorker,
  1211. currentUserId = Meteor.userId(),
  1212. ) {
  1213. const memberIndex = this.memberIndex(memberId);
  1214. // do not allow change permission of self
  1215. if (memberId === currentUserId) {
  1216. isAdmin = this.members[memberIndex].isAdmin;
  1217. }
  1218. return {
  1219. $set: {
  1220. [`members.${memberIndex}.isAdmin`]: isAdmin,
  1221. [`members.${memberIndex}.isNoComments`]: isNoComments,
  1222. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  1223. [`members.${memberIndex}.isWorker`]: isWorker,
  1224. },
  1225. };
  1226. },
  1227. setAllowsSubtasks(allowsSubtasks) {
  1228. return { $set: { allowsSubtasks } };
  1229. },
  1230. setAllowsCreator(allowsCreator) {
  1231. return { $set: { allowsCreator } };
  1232. },
  1233. setAllowsMembers(allowsMembers) {
  1234. return { $set: { allowsMembers } };
  1235. },
  1236. setAllowsChecklists(allowsChecklists) {
  1237. return { $set: { allowsChecklists } };
  1238. },
  1239. setAllowsAssignee(allowsAssignee) {
  1240. return { $set: { allowsAssignee } };
  1241. },
  1242. setAllowsAssignedBy(allowsAssignedBy) {
  1243. return { $set: { allowsAssignedBy } };
  1244. },
  1245. setAllowsRequestedBy(allowsRequestedBy) {
  1246. return { $set: { allowsRequestedBy } };
  1247. },
  1248. setAllowsCardSortingByNumber(allowsCardSortingByNumber) {
  1249. return { $set: { allowsCardSortingByNumber } };
  1250. },
  1251. setAllowsShowLists(allowsShowLists) {
  1252. return { $set: { allowsShowLists } };
  1253. },
  1254. setAllowsAttachments(allowsAttachments) {
  1255. return { $set: { allowsAttachments } };
  1256. },
  1257. setAllowsLabels(allowsLabels) {
  1258. return { $set: { allowsLabels } };
  1259. },
  1260. setAllowsComments(allowsComments) {
  1261. return { $set: { allowsComments } };
  1262. },
  1263. setAllowsDescriptionTitle(allowsDescriptionTitle) {
  1264. return { $set: { allowsDescriptionTitle } };
  1265. },
  1266. setAllowsCardNumber(allowsCardNumber) {
  1267. return { $set: { allowsCardNumber } };
  1268. },
  1269. setAllowsDescriptionText(allowsDescriptionText) {
  1270. return { $set: { allowsDescriptionText } };
  1271. },
  1272. setAllowsActivities(allowsActivities) {
  1273. return { $set: { allowsActivities } };
  1274. },
  1275. setAllowsReceivedDate(allowsReceivedDate) {
  1276. return { $set: { allowsReceivedDate } };
  1277. },
  1278. setAllowsStartDate(allowsStartDate) {
  1279. return { $set: { allowsStartDate } };
  1280. },
  1281. setAllowsEndDate(allowsEndDate) {
  1282. return { $set: { allowsEndDate } };
  1283. },
  1284. setAllowsDueDate(allowsDueDate) {
  1285. return { $set: { allowsDueDate } };
  1286. },
  1287. setSubtasksDefaultBoardId(subtasksDefaultBoardId) {
  1288. return { $set: { subtasksDefaultBoardId } };
  1289. },
  1290. setSubtasksDefaultListId(subtasksDefaultListId) {
  1291. return { $set: { subtasksDefaultListId } };
  1292. },
  1293. setPresentParentTask(presentParentTask) {
  1294. return { $set: { presentParentTask } };
  1295. },
  1296. move(sortIndex) {
  1297. return { $set: { sort: sortIndex } };
  1298. },
  1299. });
  1300. function boardRemover(userId, doc) {
  1301. [Cards, Lists, Swimlanes, Integrations, Rules, Activities].forEach(
  1302. element => {
  1303. element.remove({ boardId: doc._id });
  1304. },
  1305. );
  1306. }
  1307. Boards.uniqueTitle = title => {
  1308. const m = title.match(
  1309. new RegExp('^(?<title>.*?)\\s*(\\[(?<num>\\d+)]\\s*$|\\s*$)'),
  1310. );
  1311. const base = escapeForRegex(m.groups.title);
  1312. let num = 0;
  1313. Boards.find({ title: new RegExp(`^${base}\\s*\\[\\d+]\\s*$`) }).forEach(
  1314. board => {
  1315. const m = board.title.match(
  1316. new RegExp('^(?<title>.*?)\\s*\\[(?<num>\\d+)]\\s*$'),
  1317. );
  1318. if (m) {
  1319. const n = parseInt(m.groups.num, 10);
  1320. num = num < n ? n : num;
  1321. }
  1322. },
  1323. );
  1324. if (num > 0) {
  1325. return `${base} [${num + 1}]`;
  1326. }
  1327. return title;
  1328. };
  1329. Boards.userSearch = (
  1330. userId,
  1331. selector = {},
  1332. projection = {},
  1333. // includeArchived = false,
  1334. ) => {
  1335. // if (!includeArchived) {
  1336. // selector.archived = false;
  1337. // }
  1338. selector.$or = [{ permission: 'public' }];
  1339. if (userId) {
  1340. selector.$or.push({ members: { $elemMatch: { userId, isActive: true } } });
  1341. }
  1342. return Boards.find(selector, projection);
  1343. };
  1344. Boards.userBoards = (
  1345. userId,
  1346. archived = false,
  1347. selector = {},
  1348. projection = {},
  1349. ) => {
  1350. const user = Users.findOne(userId);
  1351. if (!user) {
  1352. return [];
  1353. }
  1354. if (typeof archived === 'boolean') {
  1355. selector.archived = archived;
  1356. }
  1357. if (!selector.type) {
  1358. selector.type = 'board';
  1359. }
  1360. selector.$or = [
  1361. { permission: 'public' },
  1362. { members: { $elemMatch: { userId, isActive: true } } },
  1363. { orgs: { $elemMatch: { orgId: { $in: user.orgIds() }, isActive: true } } },
  1364. { teams: { $elemMatch: { teamId: { $in: user.teamIds() }, isActive: true } } },
  1365. ];
  1366. return Boards.find(selector, projection);
  1367. };
  1368. Boards.userBoardIds = (userId, archived = false, selector = {}) => {
  1369. return Boards.userBoards(userId, archived, selector, {
  1370. fields: { _id: 1 },
  1371. }).map(board => {
  1372. return board._id;
  1373. });
  1374. };
  1375. Boards.colorMap = () => {
  1376. const colors = {};
  1377. for (const color of Boards.labelColors()) {
  1378. colors[TAPi18n.__(`color-${color}`)] = color;
  1379. }
  1380. return colors;
  1381. };
  1382. Boards.labelColors = () => {
  1383. return ALLOWED_COLORS;
  1384. };
  1385. if (Meteor.isServer) {
  1386. Boards.allow({
  1387. insert: Meteor.userId,
  1388. update: allowIsBoardAdmin,
  1389. remove: allowIsBoardAdmin,
  1390. fetch: ['members'],
  1391. });
  1392. // All logged in users are allowed to reorder boards by dragging at All Boards page and Public Boards page.
  1393. Boards.allow({
  1394. update(userId, board, fieldNames) {
  1395. return _.contains(fieldNames, 'sort');
  1396. },
  1397. fetch: [],
  1398. });
  1399. // The number of users that have starred this board is managed by trusted code
  1400. // and the user is not allowed to update it
  1401. Boards.deny({
  1402. update(userId, board, fieldNames) {
  1403. return _.contains(fieldNames, 'stars');
  1404. },
  1405. fetch: [],
  1406. });
  1407. // We can't remove a member if it is the last administrator
  1408. Boards.deny({
  1409. update(userId, doc, fieldNames, modifier) {
  1410. if (!_.contains(fieldNames, 'members')) return false;
  1411. // We only care in case of a $pull operation, ie remove a member
  1412. if (!_.isObject(modifier.$pull && modifier.$pull.members)) return false;
  1413. // If there is more than one admin, it's ok to remove anyone
  1414. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true })
  1415. .length;
  1416. if (nbAdmins > 1) return false;
  1417. // If all the previous conditions were verified, we can't remove
  1418. // a user if it's an admin
  1419. const removedMemberId = modifier.$pull.members.userId;
  1420. return Boolean(
  1421. _.findWhere(doc.members, {
  1422. userId: removedMemberId,
  1423. isAdmin: true,
  1424. }),
  1425. );
  1426. },
  1427. fetch: ['members'],
  1428. });
  1429. Meteor.methods({
  1430. quitBoard(boardId) {
  1431. check(boardId, String);
  1432. const board = Boards.findOne(boardId);
  1433. if (board) {
  1434. const userId = Meteor.userId();
  1435. const index = board.memberIndex(userId);
  1436. if (index >= 0) {
  1437. board.removeMember(userId);
  1438. return true;
  1439. } else throw new Meteor.Error('error-board-notAMember');
  1440. } else throw new Meteor.Error('error-board-doesNotExist');
  1441. },
  1442. acceptInvite(boardId) {
  1443. check(boardId, String);
  1444. const board = Boards.findOne(boardId);
  1445. if (!board) {
  1446. throw new Meteor.Error('error-board-doesNotExist');
  1447. }
  1448. Meteor.users.update(Meteor.userId(), {
  1449. $pull: {
  1450. 'profile.invitedBoards': boardId,
  1451. },
  1452. });
  1453. },
  1454. myLabelNames() {
  1455. let names = [];
  1456. Boards.userBoards(Meteor.userId()).forEach(board => {
  1457. // Only return labels when they exist.
  1458. if (board.labels !== undefined) {
  1459. names = names.concat(
  1460. board.labels
  1461. .filter(label => !!label.name)
  1462. .map(label => {
  1463. return label.name;
  1464. }),
  1465. );
  1466. } else {
  1467. return [];
  1468. }
  1469. });
  1470. return _.uniq(names).sort();
  1471. },
  1472. myBoardNames() {
  1473. return _.uniq(
  1474. Boards.userBoards(Meteor.userId()).map(board => {
  1475. return board.title;
  1476. }),
  1477. ).sort();
  1478. },
  1479. });
  1480. Meteor.methods({
  1481. archiveBoard(boardId) {
  1482. check(boardId, String);
  1483. const board = Boards.findOne(boardId);
  1484. if (board) {
  1485. const userId = Meteor.userId();
  1486. const index = board.memberIndex(userId);
  1487. if (index >= 0) {
  1488. board.archive();
  1489. return true;
  1490. } else throw new Meteor.Error('error-board-notAMember');
  1491. } else throw new Meteor.Error('error-board-doesNotExist');
  1492. },
  1493. setBoardOrgs(boardOrgsArray, currBoardId){
  1494. check(boardOrgsArray, Array);
  1495. check(currBoardId, String);
  1496. Boards.update(currBoardId, {
  1497. $set: {
  1498. orgs: boardOrgsArray,
  1499. },
  1500. });
  1501. },
  1502. setBoardTeams(boardTeamsArray, membersArray, currBoardId){
  1503. check(boardTeamsArray, Array);
  1504. check(membersArray, Array);
  1505. check(currBoardId, String);
  1506. Boards.update(currBoardId, {
  1507. $set: {
  1508. members: membersArray,
  1509. teams: boardTeamsArray,
  1510. },
  1511. });
  1512. },
  1513. });
  1514. }
  1515. // Insert new board at last position in sort order.
  1516. Boards.before.insert((userId, doc) => {
  1517. const lastBoard = Boards.findOne(
  1518. { sort: { $exists: true } },
  1519. { sort: { sort: -1 } },
  1520. );
  1521. if (lastBoard && typeof lastBoard.sort !== 'undefined') {
  1522. doc.sort = lastBoard.sort + 1;
  1523. }
  1524. });
  1525. if (Meteor.isServer) {
  1526. // Let MongoDB ensure that a member is not included twice in the same board
  1527. Meteor.startup(() => {
  1528. Boards._collection._ensureIndex({ modifiedAt: -1 });
  1529. Boards._collection._ensureIndex(
  1530. {
  1531. _id: 1,
  1532. 'members.userId': 1,
  1533. },
  1534. { unique: true },
  1535. );
  1536. Boards._collection._ensureIndex({ 'members.userId': 1 });
  1537. });
  1538. // Genesis: the first activity of the newly created board
  1539. Boards.after.insert((userId, doc) => {
  1540. Activities.insert({
  1541. userId,
  1542. type: 'board',
  1543. activityTypeId: doc._id,
  1544. activityType: 'createBoard',
  1545. boardId: doc._id,
  1546. });
  1547. });
  1548. // If the user remove one label from a board, we cant to remove reference of
  1549. // this label in any card of this board.
  1550. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1551. if (
  1552. !_.contains(fieldNames, 'labels') ||
  1553. !modifier.$pull ||
  1554. !modifier.$pull.labels ||
  1555. !modifier.$pull.labels._id
  1556. ) {
  1557. return;
  1558. }
  1559. const removedLabelId = modifier.$pull.labels._id;
  1560. Cards.update(
  1561. { boardId: doc._id },
  1562. {
  1563. $pull: {
  1564. labelIds: removedLabelId,
  1565. },
  1566. },
  1567. { multi: true },
  1568. );
  1569. });
  1570. const foreachRemovedMember = (doc, modifier, callback) => {
  1571. Object.keys(modifier).forEach(set => {
  1572. if (modifier[set] !== false) {
  1573. return;
  1574. }
  1575. const parts = set.split('.');
  1576. if (
  1577. parts.length === 3 &&
  1578. parts[0] === 'members' &&
  1579. parts[2] === 'isActive'
  1580. ) {
  1581. callback(doc.members[parts[1]].userId);
  1582. }
  1583. });
  1584. };
  1585. // Remove a member from all objects of the board before leaving the board
  1586. Boards.before.update((userId, doc, fieldNames, modifier) => {
  1587. if (!_.contains(fieldNames, 'members')) {
  1588. return;
  1589. }
  1590. if (modifier.$set) {
  1591. const boardId = doc._id;
  1592. foreachRemovedMember(doc, modifier.$set, memberId => {
  1593. Cards.update(
  1594. { boardId },
  1595. {
  1596. $pull: {
  1597. members: memberId,
  1598. watchers: memberId,
  1599. },
  1600. },
  1601. { multi: true },
  1602. );
  1603. Lists.update(
  1604. { boardId },
  1605. {
  1606. $pull: {
  1607. watchers: memberId,
  1608. },
  1609. },
  1610. { multi: true },
  1611. );
  1612. const board = Boards._transform(doc);
  1613. board.setWatcher(memberId, false);
  1614. // Remove board from users starred list
  1615. if (!board.isPublic()) {
  1616. Users.update(memberId, {
  1617. $pull: {
  1618. 'profile.starredBoards': boardId,
  1619. },
  1620. });
  1621. }
  1622. });
  1623. }
  1624. });
  1625. Boards.before.remove((userId, doc) => {
  1626. boardRemover(userId, doc);
  1627. // Add removeBoard activity to keep it
  1628. Activities.insert({
  1629. userId,
  1630. type: 'board',
  1631. activityTypeId: doc._id,
  1632. activityType: 'removeBoard',
  1633. boardId: doc._id,
  1634. });
  1635. });
  1636. // Add a new activity if we add or remove a member to the board
  1637. Boards.after.update((userId, doc, fieldNames, modifier) => {
  1638. if (!_.contains(fieldNames, 'members')) {
  1639. return;
  1640. }
  1641. // Say hello to the new member
  1642. if (modifier.$push && modifier.$push.members) {
  1643. const memberId = modifier.$push.members.userId;
  1644. Activities.insert({
  1645. userId,
  1646. memberId,
  1647. type: 'member',
  1648. activityType: 'addBoardMember',
  1649. boardId: doc._id,
  1650. });
  1651. }
  1652. // Say goodbye to the former member
  1653. if (modifier.$set) {
  1654. foreachRemovedMember(doc, modifier.$set, memberId => {
  1655. Activities.insert({
  1656. userId,
  1657. memberId,
  1658. type: 'member',
  1659. activityType: 'removeBoardMember',
  1660. boardId: doc._id,
  1661. });
  1662. });
  1663. }
  1664. });
  1665. }
  1666. //BOARDS REST API
  1667. if (Meteor.isServer) {
  1668. /**
  1669. * @operation get_boards_from_user
  1670. * @summary Get all boards attached to a user
  1671. *
  1672. * @param {string} userId the ID of the user to retrieve the data
  1673. * @return_type [{_id: string,
  1674. title: string}]
  1675. */
  1676. JsonRoutes.add('GET', '/api/users/:userId/boards', function(req, res) {
  1677. try {
  1678. Authentication.checkLoggedIn(req.userId);
  1679. const paramUserId = req.params.userId;
  1680. // A normal user should be able to see their own boards,
  1681. // admins can access boards of any user
  1682. Authentication.checkAdminOrCondition(
  1683. req.userId,
  1684. req.userId === paramUserId,
  1685. );
  1686. const data = Boards.find(
  1687. {
  1688. archived: false,
  1689. 'members.userId': paramUserId,
  1690. },
  1691. {
  1692. sort: { sort: 1 /* boards default sorting */ },
  1693. },
  1694. ).map(function(board) {
  1695. return {
  1696. _id: board._id,
  1697. title: board.title,
  1698. };
  1699. });
  1700. JsonRoutes.sendResult(res, { code: 200, data });
  1701. } catch (error) {
  1702. JsonRoutes.sendResult(res, {
  1703. code: 200,
  1704. data: error,
  1705. });
  1706. }
  1707. });
  1708. /**
  1709. * @operation get_public_boards
  1710. * @summary Get all public boards
  1711. *
  1712. * @return_type [{_id: string,
  1713. title: string}]
  1714. */
  1715. JsonRoutes.add('GET', '/api/boards', function(req, res) {
  1716. try {
  1717. Authentication.checkUserId(req.userId);
  1718. JsonRoutes.sendResult(res, {
  1719. code: 200,
  1720. data: Boards.find(
  1721. { permission: 'public' },
  1722. {
  1723. sort: { sort: 1 /* boards default sorting */ },
  1724. },
  1725. ).map(function(doc) {
  1726. return {
  1727. _id: doc._id,
  1728. title: doc.title,
  1729. };
  1730. }),
  1731. });
  1732. } catch (error) {
  1733. JsonRoutes.sendResult(res, {
  1734. code: 200,
  1735. data: error,
  1736. });
  1737. }
  1738. });
  1739. /**
  1740. * @operation get_boards_count
  1741. * @summary Get public and private boards count
  1742. *
  1743. * @return_type {private: integer, public: integer}
  1744. */
  1745. JsonRoutes.add('GET', '/api/boards_count', function(req, res) {
  1746. try {
  1747. Authentication.checkUserId(req.userId);
  1748. JsonRoutes.sendResult(res, {
  1749. code: 200,
  1750. data: {
  1751. private: Boards.find({ permission: 'private' }).count(),
  1752. public: Boards.find({ permission: 'public' }).count(),
  1753. },
  1754. });
  1755. } catch (error) {
  1756. JsonRoutes.sendResult(res, {
  1757. code: 200,
  1758. data: error,
  1759. });
  1760. }
  1761. });
  1762. /**
  1763. * @operation get_board
  1764. * @summary Get the board with that particular ID
  1765. *
  1766. * @param {string} boardId the ID of the board to retrieve the data
  1767. * @return_type Boards
  1768. */
  1769. JsonRoutes.add('GET', '/api/boards/:boardId', function(req, res) {
  1770. try {
  1771. Authentication.checkUserId(req.userId);
  1772. const id = req.params.boardId;
  1773. JsonRoutes.sendResult(res, {
  1774. code: 200,
  1775. data: Boards.findOne({ _id: id }),
  1776. });
  1777. } catch (error) {
  1778. JsonRoutes.sendResult(res, {
  1779. code: 200,
  1780. data: error,
  1781. });
  1782. }
  1783. });
  1784. /**
  1785. * @operation new_board
  1786. * @summary Create a board
  1787. *
  1788. * @description This allows to create a board.
  1789. *
  1790. * The color has to be chosen between `belize`, `nephritis`, `pomegranate`,
  1791. * `pumpkin`, `wisteria`, `moderatepink`, `strongcyan`,
  1792. * `limegreen`, `midnight`, `dark`, `relax`, `corteza`:
  1793. *
  1794. * <img src="https://wekan.github.io/board-colors.png" width="40%" alt="Wekan logo" />
  1795. *
  1796. * @param {string} title the new title of the board
  1797. * @param {string} owner "ABCDE12345" <= User ID in Wekan.
  1798. * (Not username or email)
  1799. * @param {boolean} [isAdmin] is the owner an admin of the board (default true)
  1800. * @param {boolean} [isActive] is the board active (default true)
  1801. * @param {boolean} [isNoComments] disable comments (default false)
  1802. * @param {boolean} [isCommentOnly] only enable comments (default false)
  1803. * @param {boolean} [isWorker] only move cards, assign himself to card and comment (default false)
  1804. * @param {string} [permission] "private" board <== Set to "public" if you
  1805. * want public Wekan board
  1806. * @param {string} [color] the color of the board
  1807. *
  1808. * @return_type {_id: string,
  1809. defaultSwimlaneId: string}
  1810. */
  1811. JsonRoutes.add('POST', '/api/boards', function(req, res) {
  1812. try {
  1813. Authentication.checkUserId(req.userId);
  1814. const id = Boards.insert({
  1815. title: req.body.title,
  1816. members: [
  1817. {
  1818. userId: req.body.owner,
  1819. isAdmin: req.body.isAdmin || true,
  1820. isActive: req.body.isActive || true,
  1821. isNoComments: req.body.isNoComments || false,
  1822. isCommentOnly: req.body.isCommentOnly || false,
  1823. isWorker: req.body.isWorker || false,
  1824. },
  1825. ],
  1826. permission: req.body.permission || 'private',
  1827. color: req.body.color || 'belize',
  1828. });
  1829. const swimlaneId = Swimlanes.insert({
  1830. title: TAPi18n.__('default'),
  1831. boardId: id,
  1832. });
  1833. JsonRoutes.sendResult(res, {
  1834. code: 200,
  1835. data: {
  1836. _id: id,
  1837. defaultSwimlaneId: swimlaneId,
  1838. },
  1839. });
  1840. } catch (error) {
  1841. JsonRoutes.sendResult(res, {
  1842. code: 200,
  1843. data: error,
  1844. });
  1845. }
  1846. });
  1847. /**
  1848. * @operation delete_board
  1849. * @summary Delete a board
  1850. *
  1851. * @param {string} boardId the ID of the board
  1852. */
  1853. JsonRoutes.add('DELETE', '/api/boards/:boardId', function(req, res) {
  1854. try {
  1855. Authentication.checkUserId(req.userId);
  1856. const id = req.params.boardId;
  1857. Boards.remove({ _id: id });
  1858. JsonRoutes.sendResult(res, {
  1859. code: 200,
  1860. data: {
  1861. _id: id,
  1862. },
  1863. });
  1864. } catch (error) {
  1865. JsonRoutes.sendResult(res, {
  1866. code: 200,
  1867. data: error,
  1868. });
  1869. }
  1870. });
  1871. /**
  1872. * @operation add_board_label
  1873. * @summary Add a label to a board
  1874. *
  1875. * @description If the board doesn't have the name/color label, this function
  1876. * adds the label to the board.
  1877. *
  1878. * @param {string} boardId the board
  1879. * @param {string} color the color of the new label
  1880. * @param {string} name the name of the new label
  1881. *
  1882. * @return_type string
  1883. */
  1884. JsonRoutes.add('PUT', '/api/boards/:boardId/labels', function(req, res) {
  1885. Authentication.checkUserId(req.userId);
  1886. const id = req.params.boardId;
  1887. try {
  1888. if (req.body.hasOwnProperty('label')) {
  1889. const board = Boards.findOne({ _id: id });
  1890. const color = req.body.label.color;
  1891. const name = req.body.label.name;
  1892. const labelId = Random.id(6);
  1893. if (!board.getLabel(name, color)) {
  1894. Boards.direct.update(
  1895. { _id: id },
  1896. { $push: { labels: { _id: labelId, name, color } } },
  1897. );
  1898. JsonRoutes.sendResult(res, {
  1899. code: 200,
  1900. data: labelId,
  1901. });
  1902. } else {
  1903. JsonRoutes.sendResult(res, {
  1904. code: 200,
  1905. });
  1906. }
  1907. }
  1908. } catch (error) {
  1909. JsonRoutes.sendResult(res, {
  1910. data: error,
  1911. });
  1912. }
  1913. });
  1914. /**
  1915. * @operation set_board_member_permission
  1916. * @tag Users
  1917. * @summary Change the permission of a member of a board
  1918. *
  1919. * @param {string} boardId the ID of the board that we are changing
  1920. * @param {string} memberId the ID of the user to change permissions
  1921. * @param {boolean} isAdmin admin capability
  1922. * @param {boolean} isNoComments NoComments capability
  1923. * @param {boolean} isCommentOnly CommentsOnly capability
  1924. * @param {boolean} isWorker Worker capability
  1925. */
  1926. JsonRoutes.add('POST', '/api/boards/:boardId/members/:memberId', function(
  1927. req,
  1928. res,
  1929. ) {
  1930. try {
  1931. Authentication.checkUserId(req.userId);
  1932. const boardId = req.params.boardId;
  1933. const memberId = req.params.memberId;
  1934. const { isAdmin, isNoComments, isCommentOnly, isWorker } = req.body;
  1935. const board = Boards.findOne({ _id: boardId });
  1936. function isTrue(data) {
  1937. try {
  1938. return data.toLowerCase() === 'true';
  1939. } catch (error) {
  1940. return data;
  1941. }
  1942. }
  1943. const query = board.setMemberPermission(
  1944. memberId,
  1945. isTrue(isAdmin),
  1946. isTrue(isNoComments),
  1947. isTrue(isCommentOnly),
  1948. isTrue(isWorker),
  1949. req.userId,
  1950. );
  1951. JsonRoutes.sendResult(res, {
  1952. code: 200,
  1953. data: query,
  1954. });
  1955. } catch (error) {
  1956. JsonRoutes.sendResult(res, {
  1957. code: 200,
  1958. data: error,
  1959. });
  1960. }
  1961. });
  1962. //ATTACHMENTS REST API
  1963. /**
  1964. * @operation get_board_attachments
  1965. * @summary Get the list of attachments of a board
  1966. *
  1967. * @param {string} boardId the board ID
  1968. * @return_type [{attachmentId: string,
  1969. * attachmentName: string,
  1970. * attachmentType: string,
  1971. * cardId: string,
  1972. * listId: string,
  1973. * swimlaneId: string}]
  1974. */
  1975. JsonRoutes.add('GET', '/api/boards/:boardId/attachments', function(req, res) {
  1976. Authentication.checkUserId(req.userId);
  1977. const paramBoardId = req.params.boardId;
  1978. JsonRoutes.sendResult(res, {
  1979. code: 200,
  1980. data: Attachments.files
  1981. .find({ boardId: paramBoardId }, { fields: { boardId: 0 } })
  1982. .map(function(doc) {
  1983. return {
  1984. attachmentId: doc._id,
  1985. attachmentName: doc.original.name,
  1986. attachmentType: doc.original.type,
  1987. url: FlowRouter.url(doc.url()),
  1988. urlDownload: `${FlowRouter.url(doc.url())}?download=true&token=`,
  1989. cardId: doc.cardId,
  1990. listId: doc.listId,
  1991. swimlaneId: doc.swimlaneId,
  1992. };
  1993. }),
  1994. });
  1995. });
  1996. }
  1997. export default Boards;