From f88f753ccede4aed6cf15b0fb67e24056e39ed7c Mon Sep 17 00:00:00 2001 From: Marcelo Salloum dos Santos Date: Thu, 29 Aug 2024 11:26:27 -0700 Subject: [PATCH] [SDP-1325] fix code that relied on CSV column order (#143) ### What Fix code that relied on CSV column order ### Why This is an unreasonable assumption. ### Further detail Here's the main change: https://github.com/stellar/stellar-disbursement-platform-frontend/commit/594eb850e7d294ea17c250879717feeb87feaf40 The other commit is a small refactor that doesn't change the main logic. --- src/pages/DisbursementsNew.tsx | 73 +++++++++++++++++----------------- 1 file changed, 36 insertions(+), 37 deletions(-) diff --git a/src/pages/DisbursementsNew.tsx b/src/pages/DisbursementsNew.tsx index 4976034..d8e273d 100644 --- a/src/pages/DisbursementsNew.tsx +++ b/src/pages/DisbursementsNew.tsx @@ -161,43 +161,42 @@ export const DisbursementsNew = () => { }; const calculateDisbursementTotalAmountFromFile = (file?: File) => { - if (file) { - const reader = new FileReader(); - reader.readAsText(file); - const handleLoadFile = () => { - const totalAmount = reader.result - ?.toString() - .split("\n") - .slice(1) - .reduce( - (accumulator, line) => - !line - ? accumulator - : BigNumber(accumulator) - .plus(BigNumber(line.split(",")[2])) - .toNumber(), - 0, - ); - - setDraftDetails({ - ...draftDetails, - stats: { - ...draftDetails?.stats, - totalAmount: totalAmount?.toString() ?? "0", - }, - } as Disbursement); - - // update future balance - const assetBalance = allBalances?.find( - (a) => a.assetCode === draftDetails?.asset.code, - )?.balance; - - if (totalAmount) { - setFutureBalance(Number(assetBalance) - totalAmount); - } - }; - reader.addEventListener("load", handleLoadFile, false); - } + if (!file) return; + + const reader = new FileReader(); + reader.readAsText(file); + + reader.onload = () => { + const csvRows = reader.result?.toString(); + if (!csvRows) return; + + const [header, ...rows] = csvRows.split("\n"); + const amountIndex = header.split(",").indexOf("amount"); + if (amountIndex === -1) return; + + const totalAmount = rows.reduce((accumulator, line) => { + return !line + ? accumulator + : accumulator.plus(BigNumber(line.split(",")[amountIndex])); + }, BigNumber(0)); + + setDraftDetails({ + ...draftDetails, + stats: { + ...draftDetails?.stats, + totalAmount: totalAmount?.toString() ?? "0", + }, + } as Disbursement); + + // update future balance + const assetBalance = + allBalances?.find((a) => a.assetCode === draftDetails?.asset.code) + ?.balance ?? "0"; + + if (totalAmount) { + setFutureBalance(Number(assetBalance) - totalAmount.toNumber()); + } + }; }; const handleViewDetails = () => {