From 56a6f47c7daae088c2017c0d9781ddcf7cee175b Mon Sep 17 00:00:00 2001
From: Sebastian <sebasjm@gmail.com>
Date: Thu, 21 Sep 2023 15:44:17 -0300
Subject: more ui

---
 .../demobank-ui/src/pages/WithdrawalQRCode.tsx     | 159 ++++++++++++++++++---
 1 file changed, 139 insertions(+), 20 deletions(-)

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

diff --git a/packages/demobank-ui/src/pages/WithdrawalQRCode.tsx b/packages/demobank-ui/src/pages/WithdrawalQRCode.tsx
index 2a3a1ec2c..9976babdb 100644
--- a/packages/demobank-ui/src/pages/WithdrawalQRCode.tsx
+++ b/packages/demobank-ui/src/pages/WithdrawalQRCode.tsx
@@ -18,24 +18,29 @@ import {
   Amounts,
   HttpStatusCode,
   Logger,
+  TranslatedString,
   WithdrawUriResult,
   parsePaytoUri,
+  parseWithdrawUri,
+  stringifyWithdrawUri,
 } from "@gnu-taler/taler-util";
-import { ErrorType, notifyInfo, useTranslationContext } from "@gnu-taler/web-util/browser";
+import { ErrorType, RequestError, notify, notifyError, notifyInfo, useTranslationContext } from "@gnu-taler/web-util/browser";
 import { Fragment, VNode, h } from "preact";
 import { Loading } from "../components/Loading.js";
-import { useWithdrawalDetails } from "../hooks/access.js";
+import { useAccessAPI, useWithdrawalDetails } from "../hooks/access.js";
 import { useSettings } from "../hooks/settings.js";
 import { handleNotOkResult } from "./HomePage.js";
-import { QrCodeSection } from "./QrCodeSection.js";
+import { QrCodeSection, QrCodeSectionSimpler } from "./QrCodeSection.js";
 import { WithdrawalConfirmationQuestion } from "./WithdrawalConfirmationQuestion.js";
+import { useEffect, useState } from "preact/hooks";
+import { buildRequestErrorMessage } from "../utils.js";
+import { getInitialBackendBaseURL } from "../hooks/backend.js";
 
 const logger = new Logger("WithdrawalQRCode");
 
 interface Props {
   withdrawUri: WithdrawUriResult;
-  onContinue: () => void;
-  onLoadNotOk: () => void;
+  onClose: () => void;
 }
 /**
  * Offer the QR code (and a clickable taler://-link) to
@@ -44,14 +49,9 @@ interface Props {
  */
 export function WithdrawalQRCode({
   withdrawUri,
-  onContinue,
-  onLoadNotOk,
+  onClose,
 }: Props): VNode {
   const [settings, updateSettings] = useSettings();
-  function clearCurrentWithdrawal(): void {
-    updateSettings("currentWithdrawalOperationId", undefined);
-    onContinue();
-  }
   const { i18n } = useTranslationContext();
   const result = useWithdrawalDetails(withdrawUri.withdrawalOperationId);
   if (!result.ok) {
@@ -62,7 +62,7 @@ export function WithdrawalQRCode({
       result.type === ErrorType.CLIENT &&
       result.status === HttpStatusCode.NotFound
     ) {
-      clearCurrentWithdrawal()
+      onClose()
       return <div>operation not found</div>;
     }
     // onLoadNotOk();
@@ -89,8 +89,7 @@ export function WithdrawalQRCode({
           style={{ float: "right" }}
           onClick={async (e) => {
             e.preventDefault();
-            clearCurrentWithdrawal()
-            onContinue()
+            onClose()
           }}>
           {i18n.str`Continue`}
         </a>
@@ -149,8 +148,7 @@ export function WithdrawalQRCode({
           class="inline-flex w-full justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
           onClick={async (e) => {
             e.preventDefault();
-            clearCurrentWithdrawal()
-            onContinue()
+            onClose()
           }}>
           <i18n.Translate>Continue</i18n.Translate>
         </button>
@@ -165,8 +163,7 @@ export function WithdrawalQRCode({
         withdrawUri={withdrawUri}
         onAborted={() => {
           notifyInfo(i18n.str`Operation canceled`);
-          clearCurrentWithdrawal()
-          onContinue()
+          onClose()
         }}
       />
     );
@@ -196,9 +193,131 @@ export function WithdrawalQRCode({
       }}
       onAborted={() => {
         notifyInfo(i18n.str`Operation canceled`);
-        clearCurrentWithdrawal()
-        onContinue()
+        onClose()
       }}
     />
   );
+}
+
+
+export function WithdrawalOperationState({
+  currency,
+  currentOperation,
+  onClose,
+}: {currency:string, currentOperation: string, onClose: () => void}): VNode {
+  const { i18n } = useTranslationContext();
+  const [settings, updateSettings] = useSettings()
+  const { createWithdrawal } = useAccessAPI();
+
+  const amount = settings.maxWithdrawalAmount
+  async function doSilentStart() {
+    //FIXME: if amount is not enough use balance
+    const parsedAmount = Amounts.parseOrThrow(`${currency}:${amount}`)
+
+    try {
+      const result = await createWithdrawal({
+        amount: Amounts.stringify(parsedAmount),
+      });
+      const uri = parseWithdrawUri(result.data.taler_withdraw_uri);
+      if (!uri) {
+        return notifyError(
+          i18n.str`Server responded with an invalid withdraw URI`,
+          i18n.str`Withdraw URI: ${result.data.taler_withdraw_uri}`);
+      } else {
+        updateSettings("currentWithdrawalOperationId", uri.withdrawalOperationId)
+      }
+    } catch (error) {
+      if (error instanceof RequestError) {
+        notify(
+          buildRequestErrorMessage(i18n, error.cause, {
+            onClientError: (status) =>
+              status === HttpStatusCode.Forbidden
+                ? i18n.str`The operation was rejected due to insufficient funds`
+                : undefined,
+          }),
+        );
+      } else {
+        notifyError(
+          i18n.str`Operation failed, please report`,
+          (error instanceof Error
+            ? error.message
+            : JSON.stringify(error)) as TranslatedString
+        )
+      }
+    }
+  }
+
+  useEffect(() => {
+    doSilentStart()
+  }, [settings.fastWithdrawal, amount])
+
+  const result = useWithdrawalDetails(currentOperation);
+  if (!result.ok) {
+    if (result.loading) {
+      return <Loading />;
+    }
+    if (
+      result.type === ErrorType.CLIENT &&
+      result.status === HttpStatusCode.NotFound
+    ) {
+      onClose()
+      return <div>operation not found</div>;
+    }
+    // onLoadNotOk();
+    return handleNotOkResult(i18n)(result);
+  }
+  const { data } = result;
+
+  const baseUrl = getInitialBackendBaseURL()
+  const uri = stringifyWithdrawUri({
+    bankIntegrationApiBaseUrl: `${baseUrl}/integration-api`,
+    withdrawalOperationId: currentOperation,
+  });
+  const parsedUri = parseWithdrawUri(uri);
+
+  if (data.aborted) {
+    return <div>
+      the operation was aborted, you can create another one
+    </div>
+  }
+
+  if (data.confirmation_done) {
+    return <div>
+      the wire transfer is made, you coin should arrive shortly
+    </div>
+  }
+  if (!parsedUri) {
+    return <div>
+      the operation is not valid, create another one
+    </div>
+  }
+  if (!data.selection_done) {
+    return (
+      <QrCodeSectionSimpler
+        withdrawUri={parsedUri}
+        onAborted={() => {
+          notifyInfo(i18n.str`Operation canceled`);
+          onClose()
+        }}
+      />
+    );
+  }
+
+  if (!data.selected_reserve_pub) {
+    return <div>
+      the exchange is selcted but no reserve pub
+    </div>
+  }
+
+  const account = !data.selected_exchange_account ? undefined : parsePaytoUri(data.selected_exchange_account)
+
+  if (!account) {
+    return <div>
+      the exchange is selected but no account
+    </div>
+  }
+
+  return <div>
+    the operation is wating for the question to be answered
+  </div>;
 }
\ No newline at end of file
-- 
cgit v1.2.3

