TrainingMaterialCreateForm.tsx 5.34 KB
Newer Older
Stefan Probst's avatar
Stefan Probst committed
1
2
import { useRouter } from 'next/router'
import { useQueryClient } from 'react-query'
Stefan Probst's avatar
Stefan Probst committed
3
4
5

import type { TrainingMaterialCore, TrainingMaterialDto } from '@/api/sshoc'
import { useCreateTrainingMaterial, useGetLoggedInUser } from '@/api/sshoc'
6
import type { ItemCategory } from '@/api/sshoc/types'
Stefan Probst's avatar
Stefan Probst committed
7
8
9
10
11
12
13
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'
14
import { sanitizeFormValues } from '@/lib/sshoc/sanitizeFormValues'
15
import { useValidateCommonFormFields } from '@/lib/sshoc/validateCommonFormFields'
Stefan Probst's avatar
Stefan Probst committed
16
import { useAuth } from '@/modules/auth/AuthContext'
17
import { useErrorHandlers } from '@/modules/error/useErrorHandlers'
Stefan Probst's avatar
Stefan Probst committed
18
import { Form } from '@/modules/form/Form'
19
import { getSingularItemCategoryLabel } from '@/utils/getSingularItemCategoryLabel'
Stefan Probst's avatar
Stefan Probst committed
20

Stefan Probst's avatar
Stefan Probst committed
21
22
23
export interface ItemFormValues extends TrainingMaterialCore {
  draft?: boolean
}
Stefan Probst's avatar
Stefan Probst committed
24
25
26
27
28
29
30
31
32
33
34
35

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

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

36
  const categoryLabel = getSingularItemCategoryLabel(category)
Stefan Probst's avatar
Stefan Probst committed
37

Stefan Probst's avatar
Stefan Probst committed
38
39
40
41
42
  const useItemMutation = useCreateTrainingMaterial

  const toast = useToast()
  const router = useRouter()
  const auth = useAuth()
43
  const user = useGetLoggedInUser()
44
  const handleErrors = useErrorHandlers()
45
  const validateCommonFormFields = useValidateCommonFormFields()
46
47
48
49
  const isAllowedToPublish =
    user.data?.role !== undefined
      ? ['administrator', 'moderator'].includes(user.data.role)
      : false
Stefan Probst's avatar
Stefan Probst committed
50
51
52
  const queryClient = useQueryClient()
  const create = useItemMutation({
    onSuccess(data: TrainingMaterialDto) {
53
54
      toast.success(
        `Successfully ${
55
56
57
58
59
          isAllowedToPublish
            ? 'published'
            : data.status === 'draft'
            ? 'saved as draft'
            : 'submitted'
60
61
        } ${categoryLabel}.`,
      )
Stefan Probst's avatar
Stefan Probst committed
62
63
64
65
66
67
68
69
70
71
72

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

Stefan Probst's avatar
Stefan Probst committed
73
74
75
76
77
      /**
       * if the item is published (i.e. submitted as admin), redirect to details page.
       */
      if (data.status === 'approved') {
        router.push({ pathname: `/${data.category}/${data.persistentId}` })
78
79
      } else if (data.status === 'draft') {
        router.push({ pathname: '/' })
Stefan Probst's avatar
Stefan Probst committed
80
      } else {
81
        router.push({ pathname: '/success' })
Stefan Probst's avatar
Stefan Probst committed
82
      }
Stefan Probst's avatar
Stefan Probst committed
83
    },
84
    onError(error) {
85
86
87
88
89
      toast.error(
        `Failed to ${
          isAllowedToPublish ? 'publish' : 'submit'
        } ${categoryLabel}.`,
      )
90
91
92
93

      if (error instanceof Error) {
        handleErrors(error)
      }
Stefan Probst's avatar
Stefan Probst committed
94
95
96
    },
  })

97
  function onSubmit({ draft, ...unsanitized }: ItemFormValues) {
Stefan Probst's avatar
Stefan Probst committed
98
99
100
101
102
    if (auth.session?.accessToken == null) {
      toast.error('Authentication required.')
      return Promise.reject()
    }

103
    const values = sanitizeFormValues(unsanitized)
Stefan Probst's avatar
Stefan Probst committed
104

Stefan Probst's avatar
Stefan Probst committed
105
106
107
108
109
    return create.mutateAsync([
      { draft },
      values,
      { token: auth.session.accessToken },
    ])
Stefan Probst's avatar
Stefan Probst committed
110
111
112
113
114
  }

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

Stefan Probst's avatar
Stefan Probst committed
115
    validateCommonFormFields(values, errors)
Stefan Probst's avatar
Stefan Probst committed
116
117
118
119
120
121
122
123
124
125
126
127
128
129

    return errors
  }

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

  return (
    <Form
      onSubmit={onSubmit}
      validate={onValidate}
      initialValues={initialValues}
    >
Stefan Probst's avatar
Stefan Probst committed
130
      {({ handleSubmit, form, pristine, invalid, submitting }) => {
Stefan Probst's avatar
Stefan Probst committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
        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"
Stefan Probst's avatar
Stefan Probst committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
                onPress={() => {
                  form.change('draft', true)
                }}
                isDisabled={
                  pristine || invalid || submitting || create.isLoading
                }
                variant="link"
              >
                Save as draft
              </Button>
              <Button
                type="submit"
                onPress={() => {
                  form.change('draft', undefined)
                }}
Stefan Probst's avatar
Stefan Probst committed
163
164
165
166
                isDisabled={
                  pristine || invalid || submitting || create.isLoading
                }
              >
167
                {isAllowedToPublish ? 'Publish' : 'Submit'}
Stefan Probst's avatar
Stefan Probst committed
168
169
170
171
172
173
174
175
              </Button>
            </div>
          </form>
        )
      }}
    </Form>
  )
}