boards.js 52 KB

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