csvCreator.js 12 KB

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