csvCreator.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. import Boards from './boards';
  2. export class CsvCreator {
  3. constructor(data) {
  4. // date to be used for timestamps during import
  5. this._nowDate = new Date();
  6. // index to help keep track of what information a column stores
  7. // each row represents a card
  8. this.fieldIndex = {};
  9. this.lists = {};
  10. // Map of members using username => wekanid
  11. this.members = data.membersMapping ? data.membersMapping : {};
  12. this.swimlane = null;
  13. }
  14. /**
  15. * If dateString is provided,
  16. * return the Date it represents.
  17. * If not, will return the date when it was first called.
  18. * This is useful for us, as we want all import operations to
  19. * have the exact same date for easier later retrieval.
  20. *
  21. * @param {String} dateString a properly formatted Date
  22. */
  23. _now(dateString) {
  24. if (dateString) {
  25. return new Date(dateString);
  26. }
  27. if (!this._nowDate) {
  28. this._nowDate = new Date();
  29. }
  30. return this._nowDate;
  31. }
  32. _user(wekanUserId) {
  33. if (wekanUserId && this.members[wekanUserId]) {
  34. return this.members[wekanUserId];
  35. }
  36. return Meteor.userId();
  37. }
  38. /**
  39. * Map the header row titles to an index to help assign proper values to the cards' fields
  40. * Valid headers (name of card fields):
  41. * title, description, status, owner, member, label, due date, start date, finish date, created at, updated at
  42. * Some header aliases can also be accepted.
  43. * Headers are NOT case-sensitive.
  44. *
  45. * @param {Array} headerRow array from row of headers of imported CSV/TSV for cards
  46. */
  47. mapHeadertoCardFieldIndex(headerRow) {
  48. const index = {};
  49. index.customFields = [];
  50. for (let i = 0; i < headerRow.length; i++) {
  51. switch (headerRow[i].trim().toLowerCase()) {
  52. case 'title':
  53. index.title = i;
  54. break;
  55. case 'description':
  56. index.description = i;
  57. break;
  58. case 'stage':
  59. case 'status':
  60. case 'state':
  61. index.stage = i;
  62. break;
  63. case 'owner':
  64. index.owner = i;
  65. break;
  66. case 'members':
  67. case 'member':
  68. index.members = i;
  69. break;
  70. case 'labels':
  71. case 'label':
  72. index.labels = i;
  73. break;
  74. case 'due date':
  75. case 'deadline':
  76. case 'due at':
  77. index.dueAt = i;
  78. break;
  79. case 'start date':
  80. case 'start at':
  81. index.startAt = i;
  82. break;
  83. case 'finish date':
  84. case 'end at':
  85. index.endAt = i;
  86. break;
  87. case 'creation date':
  88. case 'created at':
  89. index.createdAt = i;
  90. break;
  91. case 'update date':
  92. case 'updated at':
  93. case 'modified at':
  94. case 'modified on':
  95. index.modifiedAt = i;
  96. break;
  97. }
  98. if (headerRow[i].toLowerCase().startsWith('customfield')) {
  99. if (headerRow[i].split('-')[2] === 'dropdown') {
  100. index.customFields.push({
  101. name: headerRow[i].split('-')[1],
  102. type: headerRow[i].split('-')[2],
  103. options: headerRow[i].split('-')[3].split('/'),
  104. position: i,
  105. });
  106. } else {
  107. index.customFields.push({
  108. name: headerRow[i].split('-')[1],
  109. type: headerRow[i].split('-')[2],
  110. position: i,
  111. });
  112. }
  113. }
  114. }
  115. this.fieldIndex = index;
  116. }
  117. createCustomFields(boardId) {
  118. this.fieldIndex.customFields.forEach(customField => {
  119. let settings = {};
  120. if (customField.type === 'dropdown') {
  121. settings = {
  122. dropdownItems: customField.options.map(option => {
  123. return { _id: Random.id(6), name: option };
  124. }),
  125. };
  126. } else {
  127. settings = {};
  128. }
  129. const id = CustomFields.direct.insert({
  130. name: customField.name,
  131. type: customField.type,
  132. settings,
  133. showOnCard: false,
  134. automaticallyOnCard: false,
  135. showLabelOnMiniCard: false,
  136. boardIds: [boardId],
  137. });
  138. customField.id = id;
  139. customField.settings = settings;
  140. });
  141. }
  142. createBoard(csvData) {
  143. const boardToCreate = {
  144. archived: false,
  145. color: 'belize',
  146. createdAt: this._now(),
  147. labels: [],
  148. members: [
  149. {
  150. userId: Meteor.userId(),
  151. wekanId: Meteor.userId(),
  152. isActive: true,
  153. isAdmin: true,
  154. isNoComments: false,
  155. isCommentOnly: false,
  156. swimlaneId: false,
  157. },
  158. ],
  159. modifiedAt: this._now(),
  160. //default is private, should inform user.
  161. permission: 'private',
  162. slug: 'board',
  163. stars: 0,
  164. title: `Imported Board ${this._now()}`,
  165. };
  166. // create labels
  167. const labelsToCreate = new Set();
  168. for (let i = 1; i < csvData.length; i++) {
  169. if (csvData[i][this.fieldIndex.labels]) {
  170. for (const importedLabel of csvData[i][this.fieldIndex.labels].split(
  171. ' ',
  172. )) {
  173. if (importedLabel && importedLabel.length > 0) {
  174. labelsToCreate.add(importedLabel);
  175. }
  176. }
  177. }
  178. }
  179. for (const label of labelsToCreate) {
  180. let labelName, labelColor;
  181. if (label.indexOf('-') > -1) {
  182. labelName = label.split('-')[0];
  183. labelColor = label.split('-')[1];
  184. } else {
  185. labelName = label;
  186. }
  187. const labelToCreate = {
  188. _id: Random.id(6),
  189. color: labelColor ? labelColor : 'black',
  190. name: labelName,
  191. };
  192. boardToCreate.labels.push(labelToCreate);
  193. }
  194. const boardId = Boards.direct.insert(boardToCreate);
  195. Boards.direct.update(boardId, {
  196. $set: {
  197. modifiedAt: this._now(),
  198. },
  199. });
  200. // log activity
  201. Activities.direct.insert({
  202. activityType: 'importBoard',
  203. boardId,
  204. createdAt: this._now(),
  205. source: {
  206. id: boardId,
  207. system: 'CSV/TSV',
  208. },
  209. // We attribute the import to current user,
  210. // not the author from the original object.
  211. userId: this._user(),
  212. });
  213. return boardId;
  214. }
  215. createSwimlanes(boardId) {
  216. const swimlaneToCreate = {
  217. archived: false,
  218. boardId,
  219. createdAt: this._now(),
  220. title: 'Default',
  221. sort: 1,
  222. };
  223. const swimlaneId = Swimlanes.direct.insert(swimlaneToCreate);
  224. Swimlanes.direct.update(swimlaneId, { $set: { updatedAt: this._now() } });
  225. this.swimlane = swimlaneId;
  226. }
  227. createLists(csvData, boardId) {
  228. let numOfCreatedLists = 0;
  229. for (let i = 1; i < csvData.length; i++) {
  230. const listToCreate = {
  231. archived: false,
  232. boardId,
  233. createdAt: this._now(),
  234. };
  235. if (csvData[i][this.fieldIndex.stage]) {
  236. const existingList = Lists.find({
  237. title: csvData[i][this.fieldIndex.stage],
  238. boardId,
  239. }).fetch();
  240. if (existingList.length > 0) {
  241. continue;
  242. } else {
  243. listToCreate.title = csvData[i][this.fieldIndex.stage];
  244. }
  245. } else listToCreate.title = `Imported List ${this._now()}`;
  246. const listId = Lists.direct.insert(listToCreate);
  247. this.lists[csvData[i][this.fieldIndex.stage]] = listId;
  248. numOfCreatedLists++;
  249. Lists.direct.update(listId, {
  250. $set: {
  251. updatedAt: this._now(),
  252. sort: numOfCreatedLists,
  253. },
  254. });
  255. }
  256. }
  257. createCards(csvData, boardId) {
  258. for (let i = 1; i < csvData.length; i++) {
  259. const cardToCreate = {
  260. archived: false,
  261. boardId,
  262. createdAt:
  263. csvData[i][this.fieldIndex.createdAt] !== ' ' || ''
  264. ? this._now(new Date(csvData[i][this.fieldIndex.createdAt]))
  265. : null,
  266. dateLastActivity: this._now(),
  267. description: csvData[i][this.fieldIndex.description],
  268. listId: this.lists[csvData[i][this.fieldIndex.stage]],
  269. swimlaneId: this.swimlane,
  270. sort: -1,
  271. title: csvData[i][this.fieldIndex.title],
  272. userId: this._user(),
  273. startAt:
  274. csvData[i][this.fieldIndex.startAt] !== ' ' || ''
  275. ? this._now(new Date(csvData[i][this.fieldIndex.startAt]))
  276. : null,
  277. dueAt:
  278. csvData[i][this.fieldIndex.dueAt] !== ' ' || ''
  279. ? this._now(new Date(csvData[i][this.fieldIndex.dueAt]))
  280. : null,
  281. endAt:
  282. csvData[i][this.fieldIndex.endAt] !== ' ' || ''
  283. ? this._now(new Date(csvData[i][this.fieldIndex.endAt]))
  284. : null,
  285. spentTime: null,
  286. labelIds: [],
  287. modifiedAt:
  288. csvData[i][this.fieldIndex.modifiedAt] !== ' ' || ''
  289. ? this._now(new Date(csvData[i][this.fieldIndex.modifiedAt]))
  290. : null,
  291. };
  292. // add the labels
  293. if (csvData[i][this.fieldIndex.labels]) {
  294. const board = Boards.findOne(boardId);
  295. for (const importedLabel of csvData[i][this.fieldIndex.labels].split(
  296. ' ',
  297. )) {
  298. if (importedLabel && importedLabel.length > 0) {
  299. let labelToApply;
  300. if (importedLabel.indexOf('-') === -1) {
  301. labelToApply = board.getLabel(importedLabel, 'black');
  302. } else {
  303. labelToApply = board.getLabel(
  304. importedLabel.split('-')[0],
  305. importedLabel.split('-')[1],
  306. );
  307. }
  308. cardToCreate.labelIds.push(labelToApply._id);
  309. }
  310. }
  311. }
  312. // add the members
  313. if (csvData[i][this.fieldIndex.members]) {
  314. const wekanMembers = [];
  315. for (const importedMember of csvData[i][this.fieldIndex.members].split(
  316. ' ',
  317. )) {
  318. if (this.members[importedMember]) {
  319. const wekanId = this.members[importedMember];
  320. if (!wekanMembers.find(wId => wId === wekanId)) {
  321. wekanMembers.push(wekanId);
  322. }
  323. }
  324. }
  325. if (wekanMembers.length > 0) {
  326. cardToCreate.members = wekanMembers;
  327. }
  328. }
  329. // add the custom fields
  330. if (this.fieldIndex.customFields.length > 0) {
  331. const customFields = [];
  332. this.fieldIndex.customFields.forEach(customField => {
  333. if (csvData[i][customField.position] !== ' ') {
  334. if (customField.type === 'dropdown') {
  335. customFields.push({
  336. _id: customField.id,
  337. value: customField.settings.dropdownItems.find(
  338. ({ name }) => name === csvData[i][customField.position],
  339. )._id,
  340. });
  341. } else {
  342. customFields.push({
  343. _id: customField.id,
  344. value: csvData[i][customField.position],
  345. });
  346. }
  347. }
  348. cardToCreate.customFields = customFields;
  349. });
  350. Cards.direct.insert(cardToCreate);
  351. }
  352. }
  353. }
  354. create(board, currentBoardId) {
  355. const isSandstorm =
  356. Meteor.settings &&
  357. Meteor.settings.public &&
  358. Meteor.settings.public.sandstorm;
  359. if (isSandstorm && currentBoardId) {
  360. const currentBoard = Boards.findOne(currentBoardId);
  361. currentBoard.archive();
  362. }
  363. this.mapHeadertoCardFieldIndex(board[0]);
  364. const boardId = this.createBoard(board);
  365. this.createLists(board, boardId);
  366. this.createSwimlanes(boardId);
  367. this.createCustomFields(boardId);
  368. this.createCards(board, boardId);
  369. return boardId;
  370. }
  371. }