TrainingMaterialEditForm.tsx 6.35 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

import type { TrainingMaterialCore, TrainingMaterialDto } from '@/api/sshoc'
5
6
import { useUpdateTrainingMaterial } from '@/api/sshoc'
import { useCurrentUser } from '@/api/sshoc/client'
7
import type { ItemCategory } from '@/api/sshoc/types'
Stefan Probst's avatar
Stefan Probst committed
8
9
import { ActorsFormSection } from '@/components/item/ActorsFormSection/ActorsFormSection'
import { MainFormSection } from '@/components/item/MainFormSection/MainFormSection'
Stefan Probst's avatar
Stefan Probst committed
10
import { MediaFormSection } from '@/components/item/MediaFormSection/MediaFormSection'
Stefan Probst's avatar
Stefan Probst committed
11
12
import { PropertiesFormSection } from '@/components/item/PropertiesFormSection/PropertiesFormSection'
import { RelatedItemsFormSection } from '@/components/item/RelatedItemsFormSection/RelatedItemsFormSection'
13
import { ThumbnailFormSection } from '@/components/item/ThumbnailFormSection/ThumbnailFormSection'
Stefan Probst's avatar
Stefan Probst committed
14
15
import { Button } from '@/elements/Button/Button'
import { useToast } from '@/elements/Toast/useToast'
16
import { useQueryParam } from '@/lib/hooks/useQueryParam'
17
import { sanitizeFormValues } from '@/lib/sshoc/sanitizeFormValues'
18
import { useValidateCommonFormFields } from '@/lib/sshoc/validateCommonFormFields'
Stefan Probst's avatar
Stefan Probst committed
19
import { useAuth } from '@/modules/auth/AuthContext'
20
import { useErrorHandlers } from '@/modules/error/useErrorHandlers'
Stefan Probst's avatar
Stefan Probst committed
21
import { Form } from '@/modules/form/Form'
22
import { getSingularItemCategoryLabel } from '@/utils/getSingularItemCategoryLabel'
Stefan Probst's avatar
Stefan Probst committed
23

Stefan Probst's avatar
Stefan Probst committed
24
25
26
export interface ItemFormValues extends TrainingMaterialCore {
  draft?: boolean
}
Stefan Probst's avatar
Stefan Probst committed
27
28
29
30
31

export interface ItemFormProps<T> {
  id: string
  category: ItemCategory
  initialValues?: Partial<T>
Stefan Probst's avatar
Stefan Probst committed
32
  item?: any
Stefan Probst's avatar
Stefan Probst committed
33
34
35
36
37
38
39
40
}

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

41
  const categoryLabel = getSingularItemCategoryLabel(category)
Stefan Probst's avatar
Stefan Probst committed
42

Stefan Probst's avatar
Stefan Probst committed
43
44
  const useItemMutation = useUpdateTrainingMaterial

45
46
  const isReviewToApprove = useQueryParam('review', false, Boolean)

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

      queryClient.invalidateQueries({
71
        queryKey: ['searchItems'],
Stefan Probst's avatar
Stefan Probst committed
72
73
74
75
76
77
78
      })
      queryClient.invalidateQueries({
        queryKey: ['getTrainingMaterials'],
      })
      queryClient.invalidateQueries({
        queryKey: ['getTrainingMaterial', { id: data.persistentId }],
      })
Stefan Probst's avatar
Stefan Probst committed
79
80
81
82
83
      if (data.status === 'draft') {
        queryClient.invalidateQueries({
          queryKey: ['getMyDraftItems'],
        })
      }
Stefan Probst's avatar
Stefan Probst committed
84

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

      if (error instanceof Error) {
        handleErrors(error)
      }
Stefan Probst's avatar
Stefan Probst committed
108
109
110
    },
  })

111
  async function onSubmit({ draft, ...unsanitized }: ItemFormValues) {
Stefan Probst's avatar
Stefan Probst committed
112
113
114
115
116
    if (auth.session?.accessToken == null) {
      toast.error('Authentication required.')
      return Promise.reject()
    }

117
    const values = sanitizeFormValues(unsanitized)
Stefan Probst's avatar
Stefan Probst committed
118

119
    await create.mutateAsync([
Stefan Probst's avatar
Stefan Probst committed
120
      { id },
Stefan Probst's avatar
Stefan Probst committed
121
      { draft },
Stefan Probst's avatar
Stefan Probst committed
122
123
124
      values,
      { token: auth.session.accessToken },
    ])
125
126
127
128
129
130
131

    /**
     * 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
132
133
134
135
136
  }

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

Stefan Probst's avatar
Stefan Probst committed
137
    validateCommonFormFields(values, errors)
Stefan Probst's avatar
Stefan Probst committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151

    return errors
  }

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

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