summaryrefslogtreecommitdiff
path: root/packages/demobank-ui/src/pages/BusinessAccount.tsx
blob: 4c322764e74e3d206e4006df1080a83a3b61ac57 (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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
/*
 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 {
  AmountJson,
  Amounts,
  HttpStatusCode,
  TranslatedString,
} from "@gnu-taler/taler-util";
import {
  HttpResponse,
  HttpResponsePaginated,
  RequestError,
  useTranslationContext,
} from "@gnu-taler/web-util/lib/index.browser";
import { Fragment, h, VNode } from "preact";
import { useEffect, useMemo, useState } from "preact/hooks";
import { Cashouts } from "../components/Cashouts/index.js";
import { useBackendContext } from "../context/backend.js";
import { ErrorMessage, usePageContext } from "../context/pageState.js";
import { useAccountDetails } from "../hooks/access.js";
import {
  useCashoutDetails,
  useCircuitAccountAPI,
  useRatiosAndFeeConfig,
} from "../hooks/circuit.js";
import {
  buildRequestErrorMessage,
  TanChannel,
  undefinedIfEmpty,
} from "../utils.js";
import { ShowAccountDetails, UpdateAccountPassword } from "./AdminPage.js";
import { ErrorBannerFloat } from "./BankFrame.js";
import { LoginForm } from "./LoginForm.js";
import { ShowInputErrorLabel } from "./ShowInputErrorLabel.js";

interface Props {
  onClose: () => void;
  onRegister: () => void;
  onLoadNotOk: <T>(
    error: HttpResponsePaginated<T, SandboxBackend.SandboxError>,
  ) => VNode;
}
export function BusinessAccount({
  onClose,
  onLoadNotOk,
  onRegister,
}: Props): VNode {
  const { i18n } = useTranslationContext();
  const { pageStateSetter } = usePageContext();
  const backend = useBackendContext();
  const [updatePassword, setUpdatePassword] = useState(false);
  const [newCashout, setNewcashout] = useState(false);
  const [showCashoutDetails, setShowCashoutDetails] = useState<
    string | undefined
  >();
  function showInfoMessage(info: TranslatedString): void {
    pageStateSetter((prev) => ({
      ...prev,
      info,
    }));
  }

  if (backend.state.status === "loggedOut") {
    return <LoginForm onRegister={onRegister} />;
  }

  if (newCashout) {
    return (
      <CreateCashout
        account={backend.state.username}
        onLoadNotOk={onLoadNotOk}
        onCancel={() => {
          setNewcashout(false);
        }}
        onComplete={(id) => {
          showInfoMessage(
            i18n.str`Cashout created. You need to confirm the operation to complete the transaction.`,
          );
          setNewcashout(false);
          setShowCashoutDetails(id);
        }}
      />
    );
  }
  if (showCashoutDetails) {
    return (
      <ShowCashoutDetails
        id={showCashoutDetails}
        onLoadNotOk={onLoadNotOk}
        onCancel={() => {
          setShowCashoutDetails(undefined);
        }}
      />
    );
  }
  if (updatePassword) {
    return (
      <UpdateAccountPassword
        account={backend.state.username}
        onLoadNotOk={onLoadNotOk}
        onUpdateSuccess={() => {
          showInfoMessage(i18n.str`Password changed`);
          setUpdatePassword(false);
        }}
        onClear={() => {
          setUpdatePassword(false);
        }}
      />
    );
  }
  return (
    <div>
      <ShowAccountDetails
        account={backend.state.username}
        onLoadNotOk={onLoadNotOk}
        onUpdateSuccess={() => {
          showInfoMessage(i18n.str`Account updated`);
        }}
        onChangePassword={() => {
          setUpdatePassword(true);
        }}
        onClear={onClose}
      />
      <section style={{ marginTop: "2em" }}>
        <div class="active">
          <h3>{i18n.str`Latest cashouts`}</h3>
          <Cashouts
            account={backend.state.username}
            onSelected={(id) => {
              setShowCashoutDetails(id);
            }}
          />
        </div>
        <br />
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <div />
          <input
            class="pure-button pure-button-primary content"
            type="submit"
            value={i18n.str`New cashout`}
            onClick={async (e) => {
              e.preventDefault();
              setNewcashout(true);
            }}
          />
        </div>
      </section>
    </div>
  );
}

interface PropsCashout {
  account: string;
  onComplete: (id: string) => void;
  onCancel: () => void;
  onLoadNotOk: <T>(
    error: HttpResponsePaginated<T, SandboxBackend.SandboxError>,
  ) => VNode;
}

type FormType = {
  isDebit: boolean;
  amount: string;
  subject: string;
  channel: TanChannel;
};
type ErrorFrom<T> = {
  [P in keyof T]+?: string;
};

// check #7719
function useRatiosAndFeeConfigWithChangeDetection(): HttpResponse<
  SandboxBackend.Circuit.Config & { hasChanged?: boolean },
  SandboxBackend.SandboxError
> {
  const result = useRatiosAndFeeConfig();
  const [oldResult, setOldResult] = useState<
    SandboxBackend.Circuit.Config | undefined
  >(undefined);
  const dataFromBackend = result.ok ? result.data : undefined;
  useEffect(() => {
    // save only the first result of /config to the backend
    if (!dataFromBackend || oldResult !== undefined) return;
    setOldResult(dataFromBackend);
  }, [dataFromBackend]);

  if (!result.ok) return result;

  const data = !oldResult ? result.data : oldResult;
  const hasChanged =
    oldResult &&
    (result.data.name !== oldResult.name ||
      result.data.version !== oldResult.version ||
      result.data.ratios_and_fees.buy_at_ratio !==
        oldResult.ratios_and_fees.buy_at_ratio ||
      result.data.ratios_and_fees.buy_in_fee !==
        oldResult.ratios_and_fees.buy_in_fee ||
      result.data.ratios_and_fees.sell_at_ratio !==
        oldResult.ratios_and_fees.sell_at_ratio ||
      result.data.ratios_and_fees.sell_out_fee !==
        oldResult.ratios_and_fees.sell_out_fee ||
      result.data.fiat_currency !== oldResult.fiat_currency);

  return {
    ...result,
    data: { ...data, hasChanged },
  };
}

function CreateCashout({
  account,
  onComplete,
  onCancel,
  onLoadNotOk,
}: PropsCashout): VNode {
  const { i18n } = useTranslationContext();
  const ratiosResult = useRatiosAndFeeConfig();
  const result = useAccountDetails(account);
  const [error, saveError] = useState<ErrorMessage | undefined>();

  const [form, setForm] = useState<Partial<FormType>>({ isDebit: true });

  const { createCashout } = useCircuitAccountAPI();
  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);
  const balanceIsDebit = result.data.balance.credit_debit_indicator == "debit";
  const limit = balanceIsDebit
    ? Amounts.sub(debitThreshold, balance).amount
    : Amounts.add(balance, debitThreshold).amount;

  const zeroCalc = { debit: zero, credit: zero, beforeFee: zero };
  const [calc, setCalc] = useState(zeroCalc);
  const sellRate = config.ratios_and_fees.sell_at_ratio;
  const sellFee = !config.ratios_and_fees.sell_out_fee
    ? zero
    : Amounts.fromFloat(config.ratios_and_fees.sell_out_fee, balance.currency);
  const fiatCurrency = config.fiat_currency;

  if (!sellRate || sellRate < 0) return <div>error rate</div>;

  const amount = Amounts.parse(`${balance.currency}:${form.amount}`);

  useEffect(() => {
    if (!amount) {
      setCalc(zeroCalc);
    } else {
      if (form.isDebit) {
        calculateFromDebit(amount, sellFee, sellRate).then((r) => {
          setCalc(r);
        });
      } else {
        calculateFromCredit(amount, sellFee, sellRate).then((r) => {
          setCalc(r);
        });
      }
    }
  }, [form.amount, form.isDebit]);

  const balanceAfter = Amounts.sub(balance, calc.debit).amount;

  function updateForm(newForm: typeof form): void {
    setForm(newForm);
  }
  const errors = undefinedIfEmpty<ErrorFrom<typeof form>>({
    amount: !form.amount
      ? i18n.str`required`
      : !amount
      ? i18n.str`could not be parsed`
      : Amounts.cmp(limit, calc.debit) === -1
      ? i18n.str`balance is not enough`
      : Amounts.cmp(calc.beforeFee, sellFee) === -1
      ? i18n.str`the total amount to transfer does not cover the fees`
      : Amounts.isZero(calc.credit)
      ? i18n.str`the total transfer at destination will be zero`
      : undefined,
    channel: !form.channel ? i18n.str`required` : undefined,
  });

  return (
    <div>
      {error && (
        <ErrorBannerFloat error={error} onClear={() => saveError(undefined)} />
      )}
      <h1>New cashout</h1>
      <form class="pure-form">
        <fieldset>
          <label>{i18n.str`Subject`}</label>
          <input
            value={form.subject ?? ""}
            onChange={(e) => {
              form.subject = e.currentTarget.value;
              updateForm(structuredClone(form));
            }}
          />
          <ShowInputErrorLabel
            message={errors?.subject}
            isDirty={form.subject !== undefined}
          />
        </fieldset>
        <fieldset>
          <label>
            {form.isDebit
              ? i18n.str`Amount to send`
              : i18n.str`Amount to receive`}
          </label>
          <div style={{ width: "max-content" }}>
            <input
              type="text"
              readonly
              class="currency-indicator"
              size={
                !form.isDebit ? fiatCurrency.length : balance.currency.length
              }
              maxLength={
                !form.isDebit ? fiatCurrency.length : balance.currency.length
              }
              tabIndex={-1}
              value={!form.isDebit ? fiatCurrency : balance.currency}
            />
            &nbsp;
            <input
              type="number"
              // ref={ref}
              id="withdraw-amount"
              name="withdraw-amount"
              value={form.amount ?? ""}
              onChange={(e): void => {
                form.amount = e.currentTarget.value;
                updateForm(structuredClone(form));
              }}
            />
            &nbsp;
            <label class="toggle">
              <input
                class="toggle-checkbox"
                type="checkbox"
                onChange={(e): void => {
                  form.isDebit = !form.isDebit;
                  updateForm(structuredClone(form));
                }}
              />
              <div class="toggle-switch"></div>
            </label>
          </div>
          <ShowInputErrorLabel
            message={errors?.amount}
            isDirty={form.amount !== undefined}
          />
        </fieldset>
        <fieldset>
          <label>{i18n.str`Conversion rate`}</label>
          <input value={sellRate} disabled />
        </fieldset>
        <fieldset>
          <label>{i18n.str`Balance now`}</label>
          <div style={{ width: "max-content" }}>
            <input
              type="text"
              readonly
              class="currency-indicator"
              size={balance.currency.length}
              maxLength={balance.currency.length}
              tabIndex={-1}
              value={balance.currency}
            />
            &nbsp;
            <input
              type="number"
              id="withdraw-amount"
              disabled
              name="withdraw-amount"
              value={Amounts.stringifyValue(balance)}
            />
          </div>
        </fieldset>
        <fieldset>
          <label
            style={{ fontWeight: "bold", color: "red" }}
          >{i18n.str`Total cost`}</label>
          <div style={{ width: "max-content" }}>
            <input
              type="text"
              readonly
              class="currency-indicator"
              size={balance.currency.length}
              maxLength={balance.currency.length}
              tabIndex={-1}
              value={balance.currency}
            />
            &nbsp;
            <input
              type="number"
              // ref={ref}
              id="withdraw-amount"
              disabled
              name="withdraw-amount"
              value={Amounts.stringifyValue(calc.debit)}
            />
          </div>
        </fieldset>
        <fieldset>
          <label>{i18n.str`Balance after`}</label>
          <div style={{ width: "max-content" }}>
            <input
              type="text"
              readonly
              class="currency-indicator"
              size={balance.currency.length}
              maxLength={balance.currency.length}
              tabIndex={-1}
              value={balance.currency}
            />
            &nbsp;
            <input
              type="number"
              // ref={ref}
              id="withdraw-amount"
              disabled
              name="withdraw-amount"
              value={balanceAfter ? Amounts.stringifyValue(balanceAfter) : ""}
            />
          </div>
        </fieldset>{" "}
        {Amounts.isZero(sellFee) ? undefined : (
          <Fragment>
            <fieldset>
              <label>{i18n.str`Amount after conversion`}</label>
              <div style={{ width: "max-content" }}>
                <input
                  type="text"
                  readonly
                  class="currency-indicator"
                  size={fiatCurrency.length}
                  maxLength={fiatCurrency.length}
                  tabIndex={-1}
                  value={fiatCurrency}
                />
                &nbsp;
                <input
                  // type="number"
                  style={{ color: "black" }}
                  disabled
                  value={Amounts.stringifyValue(calc.beforeFee)}
                />
              </div>
            </fieldset>

            <fieldset>
              <label>{i18n.str`Cashout fee`}</label>
              <div style={{ width: "max-content" }}>
                <input
                  type="text"
                  readonly
                  class="currency-indicator"
                  size={fiatCurrency.length}
                  maxLength={fiatCurrency.length}
                  tabIndex={-1}
                  value={fiatCurrency}
                />
                &nbsp;
                <input
                  // type="number"
                  style={{ color: "black" }}
                  disabled
                  value={Amounts.stringifyValue(sellFee)}
                />
              </div>
            </fieldset>
          </Fragment>
        )}
        <fieldset>
          <label
            style={{ fontWeight: "bold", color: "green" }}
          >{i18n.str`Total cashout transfer`}</label>
          <div style={{ width: "max-content" }}>
            <input
              type="text"
              readonly
              class="currency-indicator"
              size={fiatCurrency.length}
              maxLength={fiatCurrency.length}
              tabIndex={-1}
              value={fiatCurrency}
            />
            &nbsp;
            <input
              type="number"
              // ref={ref}
              id="withdraw-amount"
              disabled
              name="withdraw-amount"
              value={Amounts.stringifyValue(calc.credit)}
            />
          </div>
        </fieldset>
        <fieldset>
          <label>{i18n.str`Confirmation channel`}</label>

          <div class="channel">
            <input
              class={
                "pure-button content " +
                (form.channel === TanChannel.EMAIL
                  ? "pure-button-primary"
                  : "pure-button-secondary")
              }
              type="submit"
              value={i18n.str`Email`}
              onClick={async (e) => {
                e.preventDefault();
                form.channel = TanChannel.EMAIL;
                updateForm(structuredClone(form));
              }}
            />
            <input
              class={
                "pure-button content " +
                (form.channel === TanChannel.SMS
                  ? "pure-button-primary"
                  : "pure-button-secondary")
              }
              type="submit"
              value={i18n.str`SMS`}
              onClick={async (e) => {
                e.preventDefault();
                form.channel = TanChannel.SMS;
                updateForm(structuredClone(form));
              }}
            />
            <input
              class={
                "pure-button content " +
                (form.channel === TanChannel.FILE
                  ? "pure-button-primary"
                  : "pure-button-secondary")
              }
              type="submit"
              value={i18n.str`FILE`}
              onClick={async (e) => {
                e.preventDefault();
                form.channel = TanChannel.FILE;
                updateForm(structuredClone(form));
              }}
            />
          </div>
          <ShowInputErrorLabel
            message={errors?.channel}
            isDirty={form.channel !== undefined}
          />
        </fieldset>
        <br />
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <button
            class="pure-button pure-button-secondary btn-cancel"
            onClick={(e) => {
              e.preventDefault();
              onCancel();
            }}
          >
            {i18n.str`Cancel`}
          </button>

          <button
            class="pure-button pure-button-primary btn-register"
            type="submit"
            disabled={!!errors}
            onClick={async (e) => {
              e.preventDefault();

              if (errors) return;
              try {
                const res = await createCashout({
                  amount_credit: `${fiatCurrency}:${Amounts.stringifyValue(
                    calc.credit,
                  )}`,
                  amount_debit: Amounts.stringify(calc.debit),
                  subject: form.subject,
                  tan_channel: form.channel,
                });
                onComplete(res.data.uuid);
              } catch (error) {
                if (error instanceof RequestError) {
                  saveError(
                    buildRequestErrorMessage(i18n, error.cause, {
                      onClientError: (status) =>
                        status === HttpStatusCode.BadRequest
                          ? i18n.str`The exchange rate was incorrectly applied`
                          : status === HttpStatusCode.Forbidden
                          ? i18n.str`A institutional user tried the operation`
                          : status === HttpStatusCode.Conflict
                          ? i18n.str`Need a contact data where to send the TAN`
                          : status === HttpStatusCode.PreconditionFailed
                          ? i18n.str`The account does not have sufficient funds`
                          : undefined,
                      onServerError: (status) =>
                        status === HttpStatusCode.ServiceUnavailable
                          ? i18n.str`The bank does not support the TAN channel for this operation`
                          : undefined,
                    }),
                  );
                } else {
                  saveError({
                    title: i18n.str`Operation failed, please report`,
                    description:
                      error instanceof Error
                        ? error.message
                        : JSON.stringify(error),
                  });
                }
              }
            }}
          >
            {i18n.str`Create`}
          </button>
        </div>
      </form>
    </div>
  );
}

interface ShowCashoutProps {
  id: string;
  onCancel: () => void;
  onLoadNotOk: <T>(
    error: HttpResponsePaginated<T, SandboxBackend.SandboxError>,
  ) => VNode;
}
export function ShowCashoutDetails({
  id,
  onCancel,
  onLoadNotOk,
}: ShowCashoutProps): VNode {
  const { i18n } = useTranslationContext();
  const result = useCashoutDetails(id);
  const { abortCashout, confirmCashout } = useCircuitAccountAPI();
  const [code, setCode] = useState<string | undefined>(undefined);
  const [error, saveError] = useState<ErrorMessage | undefined>();
  if (!result.ok) return onLoadNotOk(result);
  const errors = undefinedIfEmpty({
    code: !code ? i18n.str`required` : undefined,
  });
  const isPending = String(result.data.status).toUpperCase() === "PENDING";
  return (
    <div>
      <h1>Cashout details {id}</h1>
      {error && (
        <ErrorBannerFloat error={error} onClear={() => saveError(undefined)} />
      )}
      <form class="pure-form">
        <fieldset>
          <label>
            <i18n.Translate>Subject</i18n.Translate>
          </label>
          <input readOnly value={result.data.subject} />
        </fieldset>
        <fieldset>
          <label>
            <i18n.Translate>Created</i18n.Translate>
          </label>
          <input readOnly value={result.data.creation_time ?? ""} />
        </fieldset>
        <fieldset>
          <label>
            <i18n.Translate>Confirmed</i18n.Translate>
          </label>
          <input readOnly value={result.data.confirmation_time ?? ""} />
        </fieldset>
        <fieldset>
          <label>
            <i18n.Translate>Debited</i18n.Translate>
          </label>
          <input readOnly value={result.data.amount_debit} />
        </fieldset>
        <fieldset>
          <label>
            <i18n.Translate>Credit</i18n.Translate>
          </label>
          <input readOnly value={result.data.amount_credit} />
        </fieldset>
        <fieldset>
          <label>
            <i18n.Translate>Status</i18n.Translate>
          </label>
          <input readOnly value={result.data.status} />
        </fieldset>
        <fieldset>
          <label>
            <i18n.Translate>Destination</i18n.Translate>
          </label>
          <input readOnly value={result.data.cashout_address} />
        </fieldset>
        {isPending ? (
          <fieldset>
            <label>
              <i18n.Translate>Code</i18n.Translate>
            </label>
            <input
              value={code ?? ""}
              onChange={(e) => {
                setCode(e.currentTarget.value);
              }}
            />
            <ShowInputErrorLabel
              message={errors?.code}
              isDirty={code !== undefined}
            />
          </fieldset>
        ) : undefined}
      </form>
      <br />
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <button
          class="pure-button pure-button-secondary btn-cancel"
          onClick={(e) => {
            e.preventDefault();
            onCancel();
          }}
        >
          {i18n.str`Back`}
        </button>
        {isPending ? (
          <div>
            <button
              type="submit"
              class="pure-button pure-button-primary button-error"
              onClick={async (e) => {
                e.preventDefault();
                try {
                  await abortCashout(id);
                  onCancel();
                } catch (error) {
                  if (error instanceof RequestError) {
                    saveError(
                      buildRequestErrorMessage(i18n, error.cause, {
                        onClientError: (status) =>
                          status === HttpStatusCode.NotFound
                            ? i18n.str`Cashout not found. It may be also mean that it was already aborted.`
                            : status === HttpStatusCode.PreconditionFailed
                            ? i18n.str`Cashout was already confimed`
                            : undefined,
                      }),
                    );
                  } else {
                    saveError({
                      title: i18n.str`Operation failed, please report`,
                      description:
                        error instanceof Error
                          ? error.message
                          : JSON.stringify(error),
                    });
                  }
                }
              }}
            >
              {i18n.str`Abort`}
            </button>
            &nbsp;
            <button
              type="submit"
              disabled={!code}
              class="pure-button pure-button-primary "
              onClick={async (e) => {
                e.preventDefault();
                try {
                  if (!code) return;
                  const rest = await confirmCashout(id, {
                    tan: code,
                  });
                } catch (error) {
                  if (error instanceof RequestError) {
                    saveError(
                      buildRequestErrorMessage(i18n, error.cause, {
                        onClientError: (status) =>
                          status === HttpStatusCode.NotFound
                            ? i18n.str`Cashout not found. It may be also mean that it was already aborted.`
                            : status === HttpStatusCode.PreconditionFailed
                            ? i18n.str`Cashout was already confimed`
                            : status === HttpStatusCode.Conflict
                            ? i18n.str`Confirmation failed. Maybe the user changed their cash-out address between the creation and the confirmation`
                            : status === HttpStatusCode.Forbidden
                            ? i18n.str`Invalid code`
                            : undefined,
                      }),
                    );
                  } else {
                    saveError({
                      title: i18n.str`Operation failed, please report`,
                      description:
                        error instanceof Error
                          ? error.message
                          : JSON.stringify(error),
                    });
                  }
                }
              }}
            >
              {i18n.str`Confirm`}
            </button>
          </div>
        ) : (
          <div />
        )}
      </div>
    </div>
  );
}

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;
};

async function calculateFromDebit(
  amount: AmountJson,
  sellFee: AmountJson,
  sellRate: number,
): Promise<TransferCalculation> {
  const debit = amount;

  const beforeFee = truncate(Amounts.divide(debit, 1 / sellRate));

  const credit = Amounts.sub(beforeFee, sellFee).amount;
  return { debit, credit, beforeFee };
}

async function calculateFromCredit(
  amount: AmountJson,
  sellFee: AmountJson,
  sellRate: number,
): Promise<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");
}