summaryrefslogtreecommitdiff
path: root/packages/demobank-ui/src/pages/business/ShowCashoutDetails.tsx
blob: 76876df5dcb3d47c66d866796b3e67025d7bd0b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
 This file is part of GNU Taler
 (C) 2022 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */
import {
  Amounts,
  HttpStatusCode,
  TalerError,
  TalerErrorCode,
  TranslatedString
} from "@gnu-taler/taler-util";
import {
  Attention,
  Loading,
  LocalNotificationBanner,
  ShowInputErrorLabel,
  useLocalNotification,
  useTranslationContext
} from "@gnu-taler/web-util/browser";
import { format } from "date-fns";
import { Fragment, VNode, h } from "preact";
import { useState } from "preact/hooks";
import { mutate } from "swr";
import { ErrorLoadingWithDebug } from "../../components/ErrorLoadingWithDebug.js";
import { useBankCoreApiContext } from "../../context/config.js";
import { useBackendState } from "../../hooks/backend.js";
import {
  useCashoutDetails, useConversionInfo
} from "../../hooks/circuit.js";
import {
  undefinedIfEmpty
} from "../../utils.js";
import { RenderAmount } from "../PaytoWireTransferForm.js";
import { assertUnreachable } from "../WithdrawalOperationPage.js";

interface Props {
  id: string;
  onCancel: () => void;
}
export function ShowCashoutDetails({
  id,
  onCancel,
}: Props): VNode {
  const { i18n } = useTranslationContext();
  const { state } = useBackendState();
  const creds = state.status !== "loggedIn" ? undefined : state
  const { api } = useBankCoreApiContext()
  const cid = Number.parseInt(id, 10)

  const result = useCashoutDetails(Number.isNaN(cid) ? undefined : cid);
  const [code, setCode] = useState<string | undefined>(undefined);
  const [notification, notify, handleError] = useLocalNotification()
  const info = useConversionInfo();

  if (Number.isNaN(cid)) {
    //TODO: better error message
    return <div>cashout id should be a number</div>
  }
  if (!result) {
    return <Loading />
  }
  if (result instanceof TalerError) {
    return <ErrorLoadingWithDebug error={result} />
  }
  if (result.type === "fail") {
    switch (result.case) {
      case HttpStatusCode.NotFound: return <Attention type="warning" title={i18n.str`This cashout not found. Maybe already aborted.`}>
      </Attention>
      case HttpStatusCode.NotImplemented: return <Attention type="warning" title={i18n.str`Cashouts are not supported`}>
      </Attention>
      default: assertUnreachable(result)
    }
  }
  if (!info) {
    return <Loading />
  }

  if (info instanceof TalerError) {
    return <ErrorLoadingWithDebug error={info} />
  }

  const errors = undefinedIfEmpty({
    code: !code ? i18n.str`required` : undefined,
  });
  /**
   * @deprecated
   */
  const isPending = String(result.body.status).toUpperCase() === "PENDING";
  const { fiat_currency_specification, regional_currency_specification } = info.body
  // won't implement in retry in old API 3:0:3 since request_uid is missing
  async function doAbortCashout() {
    if (!creds) return;
    await handleError(async () => {
      const resp = await api.abortCashoutById(creds, cid);
      if (resp.type === "ok") {
        onCancel();
      } else {
        switch (resp.case) {
          case HttpStatusCode.NotFound: return notify({
            type: "error",
            title: i18n.str`Cashout not found. It may be also mean that it was already aborted.`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case HttpStatusCode.Conflict: return notify({
            type: "error",
            title: i18n.str`Cashout was already confimed.`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case HttpStatusCode.NotImplemented: return notify({
            type: "error",
            title: i18n.str`Cashout operation is not supported.`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          default: {
            assertUnreachable(resp)
          }
        }
      }
    })
  }
  async function doConfirmCashout() {
    if (!creds || !code) return;
    await handleError(async () => {
      const resp = await api.confirmCashoutById(creds, cid, {
        tan: code,
      });
      if (resp.type === "ok") {
        mutate(() => true)//clean cashout state
      } else {
        switch (resp.case) {
          case HttpStatusCode.NotFound: return notify({
            type: "error",
            title: i18n.str`Cashout not found. It may be also mean that it was already aborted.`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case TalerErrorCode.BANK_UNALLOWED_DEBIT: return notify({
            type: "error",
            title: i18n.str`The account does not have sufficient funds`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          });
          case TalerErrorCode.BANK_BAD_CONVERSION: return notify({
            type: "error",
            title: i18n.str`The conversion rate was incorrectly applied`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          });
          case TalerErrorCode.BANK_CONFIRM_ABORT_CONFLICT: return notify({
            type: "error",
            title: i18n.str`The cashout operation is already aborted.`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          });
          case TalerErrorCode.BANK_CONFIRM_INCOMPLETE: return notify({
            type: "error",
            title: i18n.str`Missing destination account.`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case HttpStatusCode.TooManyRequests: return notify({
            type: "error",
            title: i18n.str`Too many failed attempts.`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case HttpStatusCode.NotImplemented: return notify({
            type: "error",
            title: i18n.str`Cashout operation is not supported.`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          case TalerErrorCode.BANK_TAN_CHALLENGE_FAILED: return notify({
            type: "error",
            title: i18n.str`The code for this cashout is invalid.`,
            description: resp.detail.hint as TranslatedString,
            debug: resp.detail,
          })
          default: assertUnreachable(resp)
        }
      }
    })
  }

  return (
    <div>
      <LocalNotificationBanner notification={notification} />
      <div class="grid grid-cols-1 gap-x-8 gap-y-8 pt-10 md:grid-cols-3 bg-gray-100 my-4 px-4 pb-4 rounded-lg">

        <section class="rounded-sm px-4">
          <h2 id="summary-heading" class="font-medium text-lg"><i18n.Translate>Cashout detail</i18n.Translate></h2>
          <dl class="mt-8 space-y-4">
            <div class="justify-between items-center flex">
              <dt class="text-sm text-gray-600"><i18n.Translate>Subject</i18n.Translate></dt>
              <dd class="text-sm ">{result.body.subject}</dd>
            </div>


            <div class="flex items-center justify-between border-t-2 afu pt-4">
              <dt class="flex items-center text-sm text-gray-600">
                <span><i18n.Translate>Status</i18n.Translate></span>
              </dt>
              <dd data-status={result.body.status} class="text-sm uppercase data-[status=pending]:text-yellow-600 data-[status=aborted]:text-red-600 data-[status=confirmed]:text-green-600" >
                {result.body.status}
              </dd>
            </div>
          </dl>
        </section>
        <div class="bg-white shadow-sm ring-1 ring-gray-900/5 sm:rounded-xl md:col-span-2">
          <div class="px-4 py-6 sm:p-8">
            <div class="grid max-w-2xl grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
              <div class="sm:col-span-5">
                <dl class="space-y-4">

                  {result.body.creation_time.t_s !== "never" ?
                    <div class="justify-between items-center flex ">
                      <dt class=" text-gray-600"><i18n.Translate>Created</i18n.Translate></dt>
                      <dd class="text-sm ">
                        {format(result.body.creation_time.t_s * 1000, "dd/MM/yyyy HH:mm:ss")}
                      </dd>
                    </div>
                    : undefined}

                  <div class="flex justify-between items-center border-t-2 afu pt-4">
                    <dt class="text-gray-600"><i18n.Translate>Debited</i18n.Translate></dt>
                    <dd class=" font-medium">
                      <RenderAmount value={Amounts.parseOrThrow(result.body.amount_debit)} negative withColor spec={regional_currency_specification} />
                    </dd>
                  </div>

                  <div class="flex items-center justify-between border-t-2 afu pt-4">
                    <dt class="flex items-center text-gray-600">
                      <span><i18n.Translate>Credited</i18n.Translate></span>

                    </dt>
                    <dd class="text-sm ">
                      <RenderAmount value={Amounts.parseOrThrow(result.body.amount_credit)} withColor spec={fiat_currency_specification} />
                    </dd>
                  </div>

                  {result.body.confirmation_time && result.body.confirmation_time.t_s !== "never" ?
                    <div class="flex justify-between items-center border-t-2 afu pt-4">
                      <dt class="  font-medium"><i18n.Translate>Confirmed</i18n.Translate></dt>
                      <dd class="  font-medium">
                        {format(result.body.confirmation_time.t_s * 1000, "dd/MM/yyyy HH:mm:ss")}
                      </dd>
                    </div>
                    : undefined}
                </dl>
              </div>
            </div>
          </div>

        </div>

        {!isPending ? undefined :
          <Fragment>
            <div />
            <form
              class="bg-white shadow-sm ring-1 ring-gray-900/5"
              autoCapitalize="none"
              autoCorrect="off"
              onSubmit={e => {
                e.preventDefault()
              }}
            >
              <div class="px-4 py-6 sm:p-8">
                <label for="withdraw-amount">
                  Enter the confirmation code
                </label>
                <div class="mt-2">
                  <div class="relative rounded-md shadow-sm">
                    <input
                      type="text"
                      // class="block w-full rounded-md border-0 py-1.5 pl-16 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
                      aria-describedby="answer"
                      autoFocus
                      class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
                      value={code ?? ""}
                      required

                      name="answer"
                      id="answer"
                      autocomplete="off"
                      onChange={(e): void => {
                        setCode(e.currentTarget.value)
                      }}
                    />
                  </div>
                  <ShowInputErrorLabel message={errors?.code} isDirty={code !== undefined} />
                </div>
              </div>
              <div class="flex items-center justify-between gap-x-6 border-t border-gray-900/10 px-4 py-4 sm:px-8">
                <button type="button"
                  class="inline-flex items-center rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-red-500"
                  onClick={doAbortCashout}
                >
                  <i18n.Translate>Abort</i18n.Translate></button>
                <button type="submit"
                  class="disabled:opacity-50 disabled:cursor-default cursor-pointer 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"
                  disabled={!!errors}
                  onClick={(e) => {
                    doConfirmCashout()
                  }}
                >
                  <i18n.Translate>Confirm</i18n.Translate>
                </button>
              </div>
            </form>
          </Fragment>}
      </div>

      <br />
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <button type="button" class="text-sm font-semibold leading-6 text-gray-900"
          onClick={onCancel}
        >
          <i18n.Translate>Cancel</i18n.Translate></button>
      </div>
    </div>
  );
}