From 0bf92a44df14f1946df2b1cd58a6b0b92b5befa2 Mon Sep 17 00:00:00 2001
From: Sebastian <sebasjm@gmail.com>
Date: Wed, 15 Mar 2023 09:25:23 -0300
Subject: test login with an endpoint and cleaner calculation

---
 packages/demobank-ui/src/pages/BusinessAccount.tsx | 111 +++++++++++++--------
 1 file changed, 69 insertions(+), 42 deletions(-)

(limited to 'packages/demobank-ui/src/pages/BusinessAccount.tsx')

diff --git a/packages/demobank-ui/src/pages/BusinessAccount.tsx b/packages/demobank-ui/src/pages/BusinessAccount.tsx
index 128b47114..258802e58 100644
--- a/packages/demobank-ui/src/pages/BusinessAccount.tsx
+++ b/packages/demobank-ui/src/pages/BusinessAccount.tsx
@@ -237,6 +237,7 @@ function CreateCashout({
   if (!result.ok) return onLoadNotOk(result);
   if (!ratiosResult.ok) return onLoadNotOk(ratiosResult);
   const config = ratiosResult.data;
+
   const balance = Amounts.parseOrThrow(result.data.balance.amount);
   const debitThreshold = Amounts.parseOrThrow(result.data.debitThreshold);
   const zero = Amounts.zeroOfCurrency(balance.currency);
@@ -254,23 +255,14 @@ function CreateCashout({
   if (!sellRate || sellRate < 0) return <div>error rate</div>;
 
   const amount = Amounts.parse(`${balance.currency}:${form.amount}`);
-  const amount_debit = !amount
-    ? zero
-    : form.isDebit
-    ? amount
-    : truncate(Amounts.divide(Amounts.add(amount, sellFee).amount, sellRate));
-  const credit_before_fee = !amount
-    ? zero
-    : form.isDebit
-    ? truncate(Amounts.divide(amount, 1 / sellRate))
-    : Amounts.add(amount, sellFee).amount;
 
-  const __amount_credit = Amounts.sub(credit_before_fee, sellFee).amount;
-  const amount_credit = Amounts.parseOrThrow(
-    `${fiatCurrency}:${Amounts.stringifyValue(__amount_credit)}`,
-  );
+  const calc = !amount
+    ? { debit: zero, credit: zero, beforeFee: zero }
+    : !form.isDebit
+    ? calculateFromCredit(amount, sellFee, sellRate)
+    : calculateFromDebit(amount, sellFee, sellRate);
 
-  const balanceAfter = Amounts.sub(balance, amount_debit).amount;
+  const balanceAfter = Amounts.sub(balance, calc.debit).amount;
 
   function updateForm(newForm: typeof form): void {
     setForm(newForm);
@@ -280,11 +272,11 @@ function CreateCashout({
       ? i18n.str`required`
       : !amount
       ? i18n.str`could not be parsed`
-      : Amounts.cmp(limit, amount_debit) === -1
+      : Amounts.cmp(limit, calc.debit) === -1
       ? i18n.str`balance is not enough`
-      : Amounts.cmp(credit_before_fee, sellFee) === -1
+      : Amounts.cmp(calc.beforeFee, sellFee) === -1
       ? i18n.str`the total amount to transfer does not cover the fees`
-      : Amounts.isZero(amount_credit)
+      : Amounts.isZero(calc.credit)
       ? i18n.str`the total transfer at destination will be zero`
       : undefined,
     channel: !form.channel ? i18n.str`required` : undefined,
@@ -408,7 +400,7 @@ function CreateCashout({
               id="withdraw-amount"
               disabled
               name="withdraw-amount"
-              value={amount_debit ? Amounts.stringifyValue(amount_debit) : ""}
+              value={Amounts.stringifyValue(calc.debit)}
             />
           </div>
         </fieldset>
@@ -454,7 +446,7 @@ function CreateCashout({
                   // type="number"
                   style={{ color: "black" }}
                   disabled
-                  value={Amounts.stringifyValue(credit_before_fee)}
+                  value={Amounts.stringifyValue(calc.beforeFee)}
                 />
               </div>
             </fieldset>
@@ -503,7 +495,7 @@ function CreateCashout({
               id="withdraw-amount"
               disabled
               name="withdraw-amount"
-              value={amount_credit ? Amounts.stringifyValue(amount_credit) : ""}
+              value={Amounts.stringifyValue(calc.credit)}
             />
           </div>
         </fieldset>
@@ -584,8 +576,10 @@ function CreateCashout({
               if (errors) return;
               try {
                 const res = await createCashout({
-                  amount_credit: Amounts.stringify(amount_credit),
-                  amount_debit: Amounts.stringify(amount_debit),
+                  amount_credit: `${fiatCurrency}:${Amounts.stringifyValue(
+                    calc.credit,
+                  )}`,
+                  amount_debit: Amounts.stringify(calc.debit),
                   subject: form.subject,
                   tan_channel: form.channel,
                 });
@@ -630,25 +624,6 @@ function CreateCashout({
   );
 }
 
-const MAX_AMOUNT_DIGIT = 2;
-/**
- * Truncate the amount of digits to display
- * in the form based on the fee calculations
- *
- * Backend must have the same truncation
- * @param a
- * @returns
- */
-function truncate(a: AmountJson): AmountJson {
-  const str = Amounts.stringify(a);
-  const idx = str.indexOf(".");
-  if (idx === -1) {
-    return a;
-  }
-  const truncated = str.substring(0, idx + 1 + MAX_AMOUNT_DIGIT);
-  return Amounts.parseOrThrow(truncated);
-}
-
 interface ShowCashoutProps {
   id: string;
   onCancel: () => void;
@@ -836,6 +811,58 @@ export function ShowCashoutDetails({
   );
 }
 
+const MAX_AMOUNT_DIGIT = 2;
+/**
+ * Truncate the amount of digits to display
+ * in the form based on the fee calculations
+ *
+ * Backend must have the same truncation
+ * @param a
+ * @returns
+ */
+function truncate(a: AmountJson): AmountJson {
+  const str = Amounts.stringify(a);
+  const idx = str.indexOf(".");
+  if (idx === -1) {
+    return a;
+  }
+  const truncated = str.substring(0, idx + 1 + MAX_AMOUNT_DIGIT);
+  return Amounts.parseOrThrow(truncated);
+}
+
+type TransferCalculation = {
+  debit: AmountJson;
+  credit: AmountJson;
+  beforeFee: AmountJson;
+};
+
+function calculateFromDebit(
+  amount: AmountJson,
+  sellFee: AmountJson,
+  sellRate: number,
+): TransferCalculation {
+  const debit = amount;
+
+  const beforeFee = truncate(Amounts.divide(debit, 1 / sellRate));
+
+  const credit = Amounts.sub(beforeFee, sellFee).amount;
+  return { debit, credit, beforeFee };
+}
+
+function calculateFromCredit(
+  amount: AmountJson,
+  sellFee: AmountJson,
+  sellRate: number,
+): TransferCalculation {
+  const credit = amount;
+
+  const beforeFee = Amounts.add(credit, sellFee).amount;
+
+  const debit = truncate(Amounts.divide(beforeFee, sellRate));
+
+  return { debit, credit, beforeFee };
+}
+
 export function assertUnreachable(x: never): never {
   throw new Error("Didn't expect to get here");
 }
-- 
cgit v1.2.3

