csvCreator.js 12 KB

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