boards.js 52 KB

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