boards.js 52 KB

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