Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { promisify } = require("util");
- const path = require("path");
- const fs = require("fs");
- const moment = require("moment");
- const csv = require("csv");
- const _ = require("lodash");
- const parseCsv = promisify(csv.parse);
- const readFile = promisify(fs.readFile);
- async function importFromCsv() {
- const text = await readFile(path.join(__dirname, "calculate_input.csv"), {
- encoding: "utf8"
- });
- const rows = await parseCsv(text, {
- from: 1,
- columns: [
- "code",
- "date",
- "type",
- "quantity",
- "unitPrice",
- "tradeValue",
- "brokerageGst",
- "gst",
- "contractNote",
- "totalValue"
- ],
- skip_empty_lines: true,
- skip_lines_with_error: true
- });
- return rows.map(row => {
- const { code, date, type, totalValue, quantity } = row;
- return {
- code,
- date: moment(date, "DD/MM/YYYY"),
- type: type.toLowerCase(),
- totalValue: Math.abs(parseFloat(totalValue)),
- quantity: Math.abs(parseInt(quantity, 10))
- };
- });
- }
- async function run() {
- const rows = await importFromCsv();
- const minDate = moment("2018-07-01");
- const maxDate = moment("2019-06-30");
- const soldThisYear = rows.filter(row => {
- const { type, date } = row;
- const isSell = type === "sell";
- const isYear = date.isSameOrAfter(minDate) && date.isSameOrBefore(maxDate);
- return isSell && isYear;
- });
- let allBuys = rows.filter(row => row.type === "buy");
- const transactionPairs = soldThisYear.map(sell => {
- const buy = allBuys.find(buy => {
- const sameCode = buy.code === sell.code;
- const sameQty = buy.quantity === sell.quantity;
- if (sameCode && sameQty) {
- allBuys = _.without(allBuys, buy);
- return buy;
- }
- });
- return { sell, buy };
- });
- const validPairs = transactionPairs.filter(({ buy, sell }) => {
- const valid = buy && sell;
- if (!valid) {
- console.error("Missing transaction: ");
- console.log(" Buy: ", buy);
- console.log(" Sell: ", sell);
- console.log("----------");
- }
- return valid;
- });
- const totalBuy = validPairs.reduce(
- (total, { buy }) => total + buy.totalValue,
- 0
- );
- const totalSell = validPairs.reduce(
- (total, { sell }) => total + sell.totalValue,
- 0
- );
- console.log("Total buy value: ", totalBuy);
- console.log("Total buy value: ", totalSell);
- console.log("Total profit: ", totalSell - totalBuy);
- }
- run();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement