TrainingMaterialCreateForm.tsx 5.95 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
import { ActorsFormSection } from '@/components/item/ActorsFormSection/ActorsFormSection'
import { MainFormSection } from '@/components/item/MainFormSection/MainFormSection'
Stefan Probst's avatar
Stefan Probst committed
9
import { MediaFormSection } from '@/components/item/MediaFormSection/MediaFormSection'
Stefan Probst's avatar
Stefan Probst committed
10
11
import { PropertiesFormSection } from '@/components/item/PropertiesFormSection/PropertiesFormSection'
import { RelatedItemsFormSection } from '@/components/item/RelatedItemsFormSection/RelatedItemsFormSection'
12
import { ThumbnailFormSection } from '@/components/item/ThumbnailFormSection/ThumbnailFormSection'
Stefan Probst's avatar
Stefan Probst committed
13
14
import { Button } from '@/elements/Button/Button'
import { useToast } from '@/elements/Toast/useToast'
15
import { sanitizeFormValues } from '@/lib/sshoc/sanitizeFormValues'
16
import { useValidateCommonFormFields } from '@/lib/sshoc/validateCommonFormFields'
Stefan Probst's avatar
Stefan Probst committed
17
import { useAuth } from '@/modules/auth/AuthContext'
18
import { useErrorHandlers } from '@/modules/error/useErrorHandlers'
Stefan Probst's avatar
Stefan Probst committed
19
import { Form } from '@/modules/form/Form'
20
import { getSingularItemCategoryLabel } from '@/utils/getSingularItemCategoryLabel'
Stefan Probst's avatar
Stefan Probst committed
21

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

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

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

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

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

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

      queryClient.invalidateQueries({
65
        queryKey: ['searchItems'],
Stefan Probst's avatar
Stefan Probst committed
66
67
68
69
70
71
72
      })
      queryClient.invalidateQueries({
        queryKey: ['getTrainingMaterials'],
      })
      // queryClient.invalidateQueries({
      //   queryKey: ['getTrainingMaterial', { id: data.persistentId }],
      // })
Stefan Probst's avatar
Stefan Probst committed
73
74
75
76
77
      if (data.status === 'draft') {
        queryClient.invalidateQueries({
          queryKey: ['getMyDraftItems'],
        })
      }
Stefan Probst's avatar
Stefan Probst committed
78

Stefan Probst's avatar
Stefan Probst committed
79
80
81
82
83
      /**
       * 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}` })
84
      } else if (data.status === 'draft') {
85
86
        /** Stay on page and don't clear form when saving as draft. */
        // router.push({ pathname: '/' })
87
        window.scroll(0, 0)
Stefan Probst's avatar
Stefan Probst committed
88
      } else {
89
        router.push({ pathname: '/success' })
Stefan Probst's avatar
Stefan Probst committed
90
      }
Stefan Probst's avatar
Stefan Probst committed
91
    },
92
    onError(error) {
93
94
95
96
97
      toast.error(
        `Failed to ${
          isAllowedToPublish ? 'publish' : 'submit'
        } ${categoryLabel}.`,
      )
98
99
100
101

      if (error instanceof Error) {
        handleErrors(error)
      }
Stefan Probst's avatar
Stefan Probst committed
102
103
104
    },
  })

105
  async function onSubmit({ draft, ...unsanitized }: ItemFormValues) {
Stefan Probst's avatar
Stefan Probst committed
106
107
108
109
110
    if (auth.session?.accessToken == null) {
      toast.error('Authentication required.')
      return Promise.reject()
    }

111
    const values = sanitizeFormValues(unsanitized)
Stefan Probst's avatar
Stefan Probst committed
112

113
    await create.mutateAsync([
Stefan Probst's avatar
Stefan Probst committed
114
115
116
117
      { draft },
      values,
      { token: auth.session.accessToken },
    ])
118
119
120
121
122
123
124

    /**
     * If `onSubmit` resolves to `undefined` it's a successful submit.
     * If the promise resolves to something else the submit has failed.
     * If the promise rejects it's a network error (or similar).
     */
    return Promise.resolve()
Stefan Probst's avatar
Stefan Probst committed
125
126
127
128
129
  }

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

Stefan Probst's avatar
Stefan Probst committed
130
    validateCommonFormFields(values, errors)
Stefan Probst's avatar
Stefan Probst committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144

    return errors
  }

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

  return (
    <Form
      onSubmit={onSubmit}
      validate={onValidate}
      initialValues={initialValues}
    >
Stefan Probst's avatar
Stefan Probst committed
145
      {({ handleSubmit, form, pristine, invalid, submitting }) => {
Stefan Probst's avatar
Stefan Probst committed
146
147
148
149
150
151
152
153
154
        return (
          <form
            onSubmit={handleSubmit}
            noValidate
            className="flex flex-col space-y-12"
          >
            <MainFormSection />
            <ActorsFormSection />
            <PropertiesFormSection />
Stefan Probst's avatar
Stefan Probst committed
155
            <MediaFormSection />
156
            <ThumbnailFormSection />
Stefan Probst's avatar
Stefan Probst committed
157
158
159
160
161
162
163
            <RelatedItemsFormSection />
            <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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
                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
179
180
181
182
                isDisabled={
                  pristine || invalid || submitting || create.isLoading
                }
              >
183
                {isAllowedToPublish ? 'Publish' : 'Submit'}
Stefan Probst's avatar
Stefan Probst committed
184
185
186
187
188
189
190
191
              </Button>
            </div>
          </form>
        )
      }}
    </Form>
  )
}