boards.js 53 KB

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