summaryrefslogtreecommitdiff
path: root/src/containers/ContractorForm.tsx
blob: 7f0d66048357678417f53c227994a6133cd52617 (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
import React from 'react';
import { useParams, useHistory } from 'react-router-dom';
import { Formik, Form, Field } from 'formik';
import Page, { Action } from './Page';
import Input from '../components/Input';
import { useContractor } from '../hooks/useAPIClient';
import { post, patch } from '../requests';

interface Params {
  id: string;
}

const actions: Action[] = [
  { name: 'Назад', variant: 'outlined', route: '..' },
  { name: 'Сохранить', type: 'submit', form: 'contractorForm' },
];

const ContractorForm: React.FC = () => {
  const history = useHistory();
  const { id } = useParams<Params>();
  const { data: contractor } = useContractor(id);

  const onSubmit = (values: any) => {
    const promise = id
      ? patch(`/contractors/${id}`, values)
      : post('/contractors', values);
    return promise.then(() => history.push('/contractors'));
  };

  return (
    <Page title={id ? contractor?.name : 'Новый контрагент'} actions={actions}>
      {(!id || contractor) && (
        <Formik
          initialValues={contractor || { name: '', debt: '', vatId: '' }}
          onSubmit={onSubmit}
        >
          {() => (
            <Form id="contractorForm">
              <div className="max-w-lg">
                <Field name="name" label="Название" as={Input} />
                <Field name="vatId" label="УНП" as={Input} />
                <Field name="debt" type="number" label="Долг ($)" as={Input} />
              </div>
            </Form>
          )}
        </Formik>
      )}
    </Page>
  );
};

export default ContractorForm;