Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. const { promisify } = require("util");
  2. const path = require("path");
  3. const fs = require("fs");
  4. const moment = require("moment");
  5. const csv = require("csv");
  6. const _ = require("lodash");
  7.  
  8. const parseCsv = promisify(csv.parse);
  9. const readFile = promisify(fs.readFile);
  10.  
  11. async function importFromCsv() {
  12. const text = await readFile(path.join(__dirname, "calculate_input.csv"), {
  13. encoding: "utf8"
  14. });
  15.  
  16. const rows = await parseCsv(text, {
  17. from: 1,
  18. columns: [
  19. "code",
  20. "date",
  21. "type",
  22. "quantity",
  23. "unitPrice",
  24. "tradeValue",
  25. "brokerageGst",
  26. "gst",
  27. "contractNote",
  28. "totalValue"
  29. ],
  30. skip_empty_lines: true,
  31. skip_lines_with_error: true
  32. });
  33.  
  34. return rows.map(row => {
  35. const { code, date, type, totalValue, quantity } = row;
  36. return {
  37. code,
  38. date: moment(date, "DD/MM/YYYY"),
  39. type: type.toLowerCase(),
  40. totalValue: Math.abs(parseFloat(totalValue)),
  41. quantity: Math.abs(parseInt(quantity, 10))
  42. };
  43. });
  44. }
  45.  
  46. async function run() {
  47. const rows = await importFromCsv();
  48. const minDate = moment("2018-07-01");
  49. const maxDate = moment("2019-06-30");
  50.  
  51. const soldThisYear = rows.filter(row => {
  52. const { type, date } = row;
  53. const isSell = type === "sell";
  54. const isYear = date.isSameOrAfter(minDate) && date.isSameOrBefore(maxDate);
  55. return isSell && isYear;
  56. });
  57.  
  58. let allBuys = rows.filter(row => row.type === "buy");
  59.  
  60. const transactionPairs = soldThisYear.map(sell => {
  61. const buy = allBuys.find(buy => {
  62. const sameCode = buy.code === sell.code;
  63. const sameQty = buy.quantity === sell.quantity;
  64. if (sameCode && sameQty) {
  65. allBuys = _.without(allBuys, buy);
  66. return buy;
  67. }
  68. });
  69.  
  70. return { sell, buy };
  71. });
  72.  
  73. const validPairs = transactionPairs.filter(({ buy, sell }) => {
  74. const valid = buy && sell;
  75. if (!valid) {
  76. console.error("Missing transaction: ");
  77. console.log(" Buy: ", buy);
  78. console.log(" Sell: ", sell);
  79. console.log("----------");
  80. }
  81. return valid;
  82. });
  83.  
  84. const totalBuy = validPairs.reduce(
  85. (total, { buy }) => total + buy.totalValue,
  86. 0
  87. );
  88.  
  89. const totalSell = validPairs.reduce(
  90. (total, { sell }) => total + sell.totalValue,
  91. 0
  92. );
  93.  
  94. console.log("Total buy value: ", totalBuy);
  95. console.log("Total buy value: ", totalSell);
  96. console.log("Total profit: ", totalSell - totalBuy);
  97. }
  98.  
  99. run();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement