boards.js 52 KB

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