boards.js 60 KB

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