Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function onOpen(e){
- SpreadsheetApp.getUi().createMenu('Create report')
- .addItem('Rebuild report', 'createReport')
- .addToUi();
- }
- function createReport() {
- const ss = SpreadsheetApp.getActiveSpreadsheet();
- const inputSheet = ss.getSheetByName('Fifo');
- const report = ss.getSheetByName('Report');
- const data = inputSheet.getRange(2, 1, inputSheet.getLastRow() - 1, inputSheet.getLastColumn()).getValues();
- const filterd = data.filter(row => row[2] == 'Buy' || row[2] == 'Sell');
- const sorted = filterd.sort((a, b) => {
- if (a[0] < b[0]) return -1
- if (a[0] > b[0]) return 1
- else return 0
- })
- const securityObject = sorted.reduce((acc, curr) => {
- if (curr[1] in acc) {
- if (curr[2] in acc[curr[1]]) {
- acc[curr[1]][curr[2]].push(curr)
- } else {
- acc[curr[1]] = { ...acc[curr[1]], [curr[2]]: [curr] }
- }
- } else {
- acc[curr[1]] = { [curr[2]]: [curr] }
- }
- return acc
- }, {});
- const objects = [];
- Object.keys(securityObject).forEach(ticker => {
- const tic = securityObject[ticker];
- let index = 0;
- tic.Sell.forEach(sell => {
- const [date, security, , quanity, total, price, account, category] = sell;
- let totalBuy = 0;
- let remainder = quanity;
- do {
- let [, , , buyQuanity, , buyPrice] = tic.Buy[index];
- console.log(`Ticker: ${security} | BuyQuantity: ${buyQuanity} | Remainder ${remainder} | Index: ${index}`);
- if (buyQuanity < remainder) {
- totalBuy += (buyQuanity * buyPrice);
- remainder -= buyQuanity;
- index++;
- } else {
- totalBuy += (remainder * buyPrice);
- securityObject[ticker].Buy[index][3] = (buyQuanity - remainder);
- remainder = 0;
- if (buyQuanity < 1) {
- index++;
- }
- }
- } while (remainder > 0);
- objects.push({
- date,
- security,
- account,
- category,
- totalBuy,
- total,
- result: total - totalBuy
- })
- })
- })
- const convertToSheetsArray = [["Sell Date", "Security", "Account", "Category", "Total Buy", "Total Sell", "Result"]]
- objects.forEach(obj => convertToSheetsArray.push(Object.values(obj)));
- const sheetsArray = convertToSheetsArray.sort((a, b) => {
- if (a[0] < b[0]) return -1
- if (a[0] > b[0]) return 1
- else return 0
- })
- report.getDataRange().clearContent();
- report.getRange(1,1,sheetsArray.length, 7).setValues(sheetsArray);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement