boards.js 52 KB

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