csvCreator.js 12 KB

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