csvCreator.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 if (headerRow[i].split('-')[2] === 'currency') {
  107. index.customFields.push({
  108. name: headerRow[i].split('-')[1],
  109. type: headerRow[i].split('-')[2],
  110. currencyCode: headerRow[i].split('-')[3],
  111. position: i,
  112. });
  113. } else {
  114. index.customFields.push({
  115. name: headerRow[i].split('-')[1],
  116. type: headerRow[i].split('-')[2],
  117. position: i,
  118. });
  119. }
  120. }
  121. }
  122. this.fieldIndex = index;
  123. }
  124. createCustomFields(boardId) {
  125. this.fieldIndex.customFields.forEach(customField => {
  126. let settings = {};
  127. if (customField.type === 'dropdown') {
  128. settings = {
  129. dropdownItems: customField.options.map(option => {
  130. return { _id: Random.id(6), name: option };
  131. }),
  132. };
  133. } else if (customField.type === 'currency') {
  134. settings = {
  135. currencyCode: customField.currencyCode,
  136. };
  137. } else {
  138. settings = {};
  139. }
  140. const id = CustomFields.direct.insert({
  141. name: customField.name,
  142. type: customField.type,
  143. settings,
  144. showOnCard: false,
  145. automaticallyOnCard: false,
  146. alwaysOnCard: false,
  147. showLabelOnMiniCard: false,
  148. boardIds: [boardId],
  149. });
  150. customField.id = id;
  151. customField.settings = settings;
  152. });
  153. }
  154. createBoard(csvData) {
  155. const boardToCreate = {
  156. archived: false,
  157. color: 'belize',
  158. createdAt: this._now(),
  159. labels: [],
  160. members: [
  161. {
  162. userId: Meteor.userId(),
  163. wekanId: Meteor.userId(),
  164. isActive: true,
  165. isAdmin: true,
  166. isNoComments: false,
  167. isCommentOnly: false,
  168. swimlaneId: false,
  169. },
  170. ],
  171. modifiedAt: this._now(),
  172. //default is private, should inform user.
  173. permission: 'private',
  174. slug: 'board',
  175. stars: 0,
  176. title: `Imported Board ${this._now()}`,
  177. };
  178. // create labels
  179. const labelsToCreate = new Set();
  180. for (let i = 1; i < csvData.length; i++) {
  181. if (csvData[i][this.fieldIndex.labels]) {
  182. for (const importedLabel of csvData[i][this.fieldIndex.labels].split(
  183. ' ',
  184. )) {
  185. if (importedLabel && importedLabel.length > 0) {
  186. labelsToCreate.add(importedLabel);
  187. }
  188. }
  189. }
  190. }
  191. for (const label of labelsToCreate) {
  192. let labelName, labelColor;
  193. if (label.indexOf('-') > -1) {
  194. labelName = label.split('-')[0];
  195. labelColor = label.split('-')[1];
  196. } else {
  197. labelName = label;
  198. }
  199. const labelToCreate = {
  200. _id: Random.id(6),
  201. color: labelColor ? labelColor : 'black',
  202. name: labelName,
  203. };
  204. boardToCreate.labels.push(labelToCreate);
  205. }
  206. const boardId = Boards.direct.insert(boardToCreate);
  207. Boards.direct.update(boardId, {
  208. $set: {
  209. modifiedAt: this._now(),
  210. },
  211. });
  212. // log activity
  213. Activities.direct.insert({
  214. activityType: 'importBoard',
  215. boardId,
  216. createdAt: this._now(),
  217. source: {
  218. id: boardId,
  219. system: 'CSV/TSV',
  220. },
  221. // We attribute the import to current user,
  222. // not the author from the original object.
  223. userId: this._user(),
  224. });
  225. return boardId;
  226. }
  227. createSwimlanes(boardId) {
  228. const swimlaneToCreate = {
  229. archived: false,
  230. boardId,
  231. createdAt: this._now(),
  232. title: 'Default',
  233. sort: 1,
  234. };
  235. const swimlaneId = Swimlanes.direct.insert(swimlaneToCreate);
  236. Swimlanes.direct.update(swimlaneId, { $set: { updatedAt: this._now() } });
  237. this.swimlane = swimlaneId;
  238. }
  239. createLists(csvData, boardId) {
  240. let numOfCreatedLists = 0;
  241. for (let i = 1; i < csvData.length; i++) {
  242. const listToCreate = {
  243. archived: false,
  244. boardId,
  245. createdAt: this._now(),
  246. };
  247. if (csvData[i][this.fieldIndex.stage]) {
  248. const existingList = Lists.find({
  249. title: csvData[i][this.fieldIndex.stage],
  250. boardId,
  251. }).fetch();
  252. if (existingList.length > 0) {
  253. continue;
  254. } else {
  255. listToCreate.title = csvData[i][this.fieldIndex.stage];
  256. }
  257. } else listToCreate.title = `Imported List ${this._now()}`;
  258. const listId = Lists.direct.insert(listToCreate);
  259. this.lists[csvData[i][this.fieldIndex.stage]] = listId;
  260. numOfCreatedLists++;
  261. Lists.direct.update(listId, {
  262. $set: {
  263. updatedAt: this._now(),
  264. sort: numOfCreatedLists,
  265. },
  266. });
  267. }
  268. }
  269. createCards(csvData, boardId) {
  270. for (let i = 1; i < csvData.length; i++) {
  271. const cardToCreate = {
  272. archived: false,
  273. boardId,
  274. createdAt:
  275. csvData[i][this.fieldIndex.createdAt] !== ' ' || ''
  276. ? this._now(new Date(csvData[i][this.fieldIndex.createdAt]))
  277. : null,
  278. dateLastActivity: this._now(),
  279. description: csvData[i][this.fieldIndex.description],
  280. listId: this.lists[csvData[i][this.fieldIndex.stage]],
  281. swimlaneId: this.swimlane,
  282. sort: -1,
  283. title: csvData[i][this.fieldIndex.title],
  284. userId: this._user(),
  285. startAt:
  286. csvData[i][this.fieldIndex.startAt] !== ' ' || ''
  287. ? this._now(new Date(csvData[i][this.fieldIndex.startAt]))
  288. : null,
  289. dueAt:
  290. csvData[i][this.fieldIndex.dueAt] !== ' ' || ''
  291. ? this._now(new Date(csvData[i][this.fieldIndex.dueAt]))
  292. : null,
  293. endAt:
  294. csvData[i][this.fieldIndex.endAt] !== ' ' || ''
  295. ? this._now(new Date(csvData[i][this.fieldIndex.endAt]))
  296. : null,
  297. spentTime: null,
  298. labelIds: [],
  299. modifiedAt:
  300. csvData[i][this.fieldIndex.modifiedAt] !== ' ' || ''
  301. ? this._now(new Date(csvData[i][this.fieldIndex.modifiedAt]))
  302. : null,
  303. };
  304. // add the labels
  305. if (csvData[i][this.fieldIndex.labels]) {
  306. const board = Boards.findOne(boardId);
  307. for (const importedLabel of csvData[i][this.fieldIndex.labels].split(
  308. ' ',
  309. )) {
  310. if (importedLabel && importedLabel.length > 0) {
  311. let labelToApply;
  312. if (importedLabel.indexOf('-') === -1) {
  313. labelToApply = board.getLabel(importedLabel, 'black');
  314. } else {
  315. labelToApply = board.getLabel(
  316. importedLabel.split('-')[0],
  317. importedLabel.split('-')[1],
  318. );
  319. }
  320. cardToCreate.labelIds.push(labelToApply._id);
  321. }
  322. }
  323. }
  324. // add the members
  325. if (csvData[i][this.fieldIndex.members]) {
  326. const wekanMembers = [];
  327. for (const importedMember of csvData[i][this.fieldIndex.members].split(
  328. ' ',
  329. )) {
  330. if (this.members[importedMember]) {
  331. const wekanId = this.members[importedMember];
  332. if (!wekanMembers.find(wId => wId === wekanId)) {
  333. wekanMembers.push(wekanId);
  334. }
  335. }
  336. }
  337. if (wekanMembers.length > 0) {
  338. cardToCreate.members = wekanMembers;
  339. }
  340. }
  341. // add the custom fields
  342. if (this.fieldIndex.customFields.length > 0) {
  343. const customFields = [];
  344. this.fieldIndex.customFields.forEach(customField => {
  345. if (csvData[i][customField.position] !== ' ') {
  346. if (customField.type === 'dropdown') {
  347. customFields.push({
  348. _id: customField.id,
  349. value: customField.settings.dropdownItems.find(
  350. ({ name }) => name === csvData[i][customField.position],
  351. )._id,
  352. });
  353. } else {
  354. customFields.push({
  355. _id: customField.id,
  356. value: csvData[i][customField.position],
  357. });
  358. }
  359. }
  360. cardToCreate.customFields = customFields;
  361. });
  362. Cards.direct.insert(cardToCreate);
  363. }
  364. }
  365. }
  366. create(board, currentBoardId) {
  367. const isSandstorm =
  368. Meteor.settings &&
  369. Meteor.settings.public &&
  370. Meteor.settings.public.sandstorm;
  371. if (isSandstorm && currentBoardId) {
  372. const currentBoard = Boards.findOne(currentBoardId);
  373. currentBoard.archive();
  374. }
  375. this.mapHeadertoCardFieldIndex(board[0]);
  376. const boardId = this.createBoard(board);
  377. this.createLists(board, boardId);
  378. this.createSwimlanes(boardId);
  379. this.createCustomFields(boardId);
  380. this.createCards(board, boardId);
  381. return boardId;
  382. }
  383. }