summaryrefslogtreecommitdiff
path: root/packages/frontend/src/components/form/InputPaytoForm.tsx
blob: c52dc3389bd04a3985673dda36619686c033b4d5 (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
/*
 This file is part of GNU Taler
 (C) 2021 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/>
 */

/**
*
* @author Sebastian Javier Marchano (sebasjm)
*/
import { h, VNode, Fragment } from "preact";
import { useCallback, useState } from "preact/hooks";
import { Translate, useTranslator } from "../../i18n";
import { FormErrors, FormProvider } from "./FormProvider";
import { Input } from "./Input";
import { InputGroup } from "./InputGroup";
import { InputSelector } from "./InputSelector";
import { InputProps, useField } from "./useField";

export interface Props<T> extends InputProps<T> {
  isValid?: (e: any) => boolean;
}

// https://datatracker.ietf.org/doc/html/rfc8905
type Entity = {
  target: string,
  path: string,
  path1: string,
  path2: string,
  host: string,
  account: string,
  options: {
    'receiver-name'?: string,
    sender?: string,
    message?: string,
    amount?: string,
    instruction?: string,
    [name: string]: string | undefined,
  },
}

// const targets = ['ach', 'bic', 'iban', 'upi', 'bitcoin', 'ilp', 'void', 'x-taler-bank']
const targets = ['iban', 'x-taler-bank']
const defaultTarget = { target: 'iban', options: {} }

function undefinedIfEmpty<T>(obj: T): T | undefined {
  return Object.keys(obj).some(k => (obj as any)[k] !== undefined) ? obj : undefined
}

export function InputPaytoForm<T>({ name, readonly, label, tooltip }: Props<keyof T>): VNode {
  const { value: paytos, onChange, } = useField<T>(name);

  const [value, valueHandler] = useState<Partial<Entity>>(defaultTarget)

  if (value.path1) {
    if (value.path2) {
      value.path = `/${value.path1}/${value.path2}`
    } else {
      value.path = `/${value.path1}`
    }
  }
  const i18n = useTranslator()

  const url = new URL(`payto://${value.target}${value.path}`)
  const ops = value.options!
  Object.keys(ops).forEach(opt_key => {
    const opt_value = ops[opt_key]
    if (opt_value) url.searchParams.set(opt_key, opt_value)
  })
  const paytoURL = url.toString()

  const errors: FormErrors<Entity> = {
    target: !value.target ? i18n`required` : undefined,
    path1: !value.path1 ? i18n`required` : (
      value.target === 'iban' ? (
        value.path1.length < 4 ? i18n`IBAN numbers usually have more that 4 digits` : (
          value.path1.length > 34 ? i18n`IBAN numbers usually have less that 34 digits` :
          undefined
        )
      ): undefined 
    ),
    path2: value.target === 'x-taler-bank' ? (!value.path2 ? i18n`required` : undefined) : undefined,
    options: undefinedIfEmpty({
      'receiver-name': !value.options?.["receiver-name"] ? i18n`required` : undefined,
    })
  }

  const hasErrors = Object.keys(errors).some(k => (errors as any)[k] !== undefined)

  const submit = useCallback((): void => {
    const alreadyExists = paytos.findIndex((x:string) => x === paytoURL) !== -1;
    if (!alreadyExists) {
      onChange([paytoURL, ...paytos] as any)
    }
    valueHandler(defaultTarget)
  }, [value])


  //FIXME: translating plural singular
  return (
    <InputGroup name="payto" label={label} fixed tooltip={tooltip}>
      <FormProvider<Entity> name="tax" errors={errors} object={value} valueHandler={valueHandler} >

        <InputSelector<Entity> name="target" label={i18n`Target type`} tooltip={i18n`Method to use for wire transfer`} values={targets} />

        {value.target === 'ach' && <Fragment>
          <Input<Entity> name="path1" label={i18n`Routing`} tooltip={i18n`Routing number.`} />
          <Input<Entity> name="path2" label={i18n`Account`} tooltip={i18n`Account number.`} />
        </Fragment>}
        {value.target === 'bic' && <Fragment>
          <Input<Entity> name="path1" label={i18n`Code`} tooltip={i18n`Business Identifier Code.`} />
        </Fragment>}
        {value.target === 'iban' && <Fragment>
          <Input<Entity> name="path1" label={i18n`Account`} tooltip={i18n`Bank Account Number.`} />
        </Fragment>}
        {value.target === 'upi' && <Fragment>
          <Input<Entity> name="path1" label={i18n`Account`} tooltip={i18n`Unified Payment Interface.`} />
        </Fragment>}
        {value.target === 'bitcoin' && <Fragment>
          <Input<Entity> name="path1" label={i18n`Address`} tooltip={i18n`Bitcoin protocol.`} />
        </Fragment>}
        {value.target === 'ilp' && <Fragment>
          <Input<Entity> name="path1" label={i18n`Address`} tooltip={i18n`Interledger protocol.`} />
        </Fragment>}
        {value.target === 'void' && <Fragment>
        </Fragment>}
        {value.target === 'x-taler-bank' && <Fragment>
          <Input<Entity> name="path1" label={i18n`Host`} tooltip={i18n`Bank host.`} />
          <Input<Entity> name="path2" label={i18n`Account`} tooltip={i18n`Bank account.`} />
        </Fragment>}

        <Input name="options.receiver-name" label={i18n`Name`} tooltip={i18n`Bank account owner's name.`} />

        <div class="field is-horizontal">
          <div class="field-label is-normal" />
          <div class="field-body" style={{ display: 'block' }}>
            {paytos.map((v: any, i: number) => <div key={i} class="tags has-addons mt-3 mb-0 mr-3" style={{ flexWrap: 'nowrap' }}>
              <span class="tag is-medium is-info mb-0" style={{ maxWidth: '90%' }}>{v}</span>
              <a class="tag is-medium is-danger is-delete mb-0" onClick={() => {
                onChange(paytos.filter((f: any) => f !== v) as any);
              }} />
            </div>
            )}
            {!paytos.length && i18n`No accounts yet.`}
          </div>
        </div>

        <div class="buttons is-right mt-5">
          <button class="button is-info"
            data-tooltip={i18n`add tax to the tax list`}
            disabled={hasErrors}
            onClick={submit}><Translate>Add</Translate></button>
        </div>
      </FormProvider>
    </InputGroup>
  )
}