TrainingMaterialCreateForm.tsx 3.74 KB
Newer Older
Stefan Probst's avatar
Stefan Probst committed
1
2
3
import { useRouter } from 'next/router'
import { useQueryClient } from 'react-query'
import type { TrainingMaterialCore, TrainingMaterialDto } from '@/api/sshoc'
Stefan Probst's avatar
Stefan Probst committed
4
import { useCreateTrainingMaterial, useGetItemCategories } from '@/api/sshoc'
Stefan Probst's avatar
Stefan Probst committed
5
6
7
8
9
10
11
12
13
import type { ItemCategory } from '@/api/sshoc/types'

import { ActorsFormSection } from '@/components/item/ActorsFormSection/ActorsFormSection'
import { MainFormSection } from '@/components/item/MainFormSection/MainFormSection'
import { PropertiesFormSection } from '@/components/item/PropertiesFormSection/PropertiesFormSection'
import { RelatedItemsFormSection } from '@/components/item/RelatedItemsFormSection/RelatedItemsFormSection'
import { SourceFormSection } from '@/components/item/SourceFormSection/SourceFormSection'
import { Button } from '@/elements/Button/Button'
import { useToast } from '@/elements/Toast/useToast'
Stefan Probst's avatar
Stefan Probst committed
14
import { validate } from '@/lib/sshoc/validate'
Stefan Probst's avatar
Stefan Probst committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { useAuth } from '@/modules/auth/AuthContext'
import { Form } from '@/modules/form/Form'

export type ItemFormValues = TrainingMaterialCore

export interface ItemFormProps<T> {
  category: ItemCategory
  initialValues?: Partial<T>
}

/**
 * Item edit form.
 */
export function ItemForm(props: ItemFormProps<ItemFormValues>): JSX.Element {
  const { category, initialValues } = props

Stefan Probst's avatar
Stefan Probst committed
31
32
33
  const categories = useGetItemCategories()
  const categoryLabel = categories.data?.[category] ?? category

Stefan Probst's avatar
Stefan Probst committed
34
35
36
37
38
39
40
41
  const useItemMutation = useCreateTrainingMaterial

  const toast = useToast()
  const router = useRouter()
  const auth = useAuth()
  const queryClient = useQueryClient()
  const create = useItemMutation({
    onSuccess(data: TrainingMaterialDto) {
Stefan Probst's avatar
Stefan Probst committed
42
      toast.success(`Successfully created ${categoryLabel}.`)
Stefan Probst's avatar
Stefan Probst committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56

      queryClient.invalidateQueries({
        queryKey: ['itemSearch'],
      })
      queryClient.invalidateQueries({
        queryKey: ['getTrainingMaterials'],
      })
      // queryClient.invalidateQueries({
      //   queryKey: ['getTrainingMaterial', { id: data.persistentId }],
      // })

      router.push({ pathname: `/${data.category}/${data.persistentId}` })
    },
    onError() {
Stefan Probst's avatar
Stefan Probst committed
57
      toast.error(`Failed to create ${categoryLabel}.`)
Stefan Probst's avatar
Stefan Probst committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    },
  })

  function onSubmit(values: ItemFormValues) {
    if (auth.session?.accessToken == null) {
      toast.error('Authentication required.')
      return Promise.reject()
    }

    /**
     * Backend crashes with `source: {}`.
     */
    if (values.source && values.source.id === undefined) {
      delete values.source
    }

    return create.mutateAsync([{}, values, { token: auth.session.accessToken }])
  }

  function onValidate(values: Partial<ItemFormValues>) {
    const errors: Partial<Record<keyof typeof values, string>> = {}

Stefan Probst's avatar
Stefan Probst committed
80
    validate(values, errors)
Stefan Probst's avatar
Stefan Probst committed
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

    return errors
  }

  function onCancel() {
    router.push('/')
  }

  return (
    <Form
      onSubmit={onSubmit}
      validate={onValidate}
      initialValues={initialValues}
    >
      {({ handleSubmit, pristine, invalid, submitting }) => {
        return (
          <form
            onSubmit={handleSubmit}
            noValidate
            className="flex flex-col space-y-12"
          >
            <MainFormSection />
            <ActorsFormSection />
            <PropertiesFormSection />
            <RelatedItemsFormSection />
            <SourceFormSection />
            <div className="flex items-center justify-end space-x-6">
              <Button onPress={onCancel} variant="link">
                Cancel
              </Button>
              <Button
                type="submit"
                isDisabled={
                  pristine || invalid || submitting || create.isLoading
                }
              >
                Submit
              </Button>
            </div>
          </form>
        )
      }}
    </Form>
  )
}