2
0

boards.js 51 KB

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