boards.js 50 KB

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