TrainingMaterialCreateForm.tsx 5.15 KB
Newer Older
Stefan Probst's avatar
Stefan Probst committed
1
2
import { useRouter } from 'next/router'
import { useQueryClient } from 'react-query'
3
4
5
6
7
8
import {
  TrainingMaterialCore,
  TrainingMaterialDto,
  useCreateTrainingMaterial,
  useGetLoggedInUser,
} from '@/api/sshoc'
Stefan Probst's avatar
Stefan Probst committed
9
import type { ItemCategory, ItemSearchQuery } from '@/api/sshoc/types'
Stefan Probst's avatar
Stefan Probst committed
10
11
12
13
14
15
16
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
17
import { validateCommonFormFields } from '@/lib/sshoc/validateCommonFormFields'
Stefan Probst's avatar
Stefan Probst committed
18
19
import { useAuth } from '@/modules/auth/AuthContext'
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
45
46
47
48
  const user = useGetLoggedInUser()
  const isAllowedToPublish =
    user.data?.role !== undefined
      ? ['administrator', 'moderator'].includes(user.data.role)
      : false
Stefan Probst's avatar
Stefan Probst committed
49
50
51
  const queryClient = useQueryClient()
  const create = useItemMutation({
    onSuccess(data: TrainingMaterialDto) {
52
53
54
55
56
      toast.success(
        `Successfully ${
          isAllowedToPublish ? 'published' : 'submitted'
        } ${categoryLabel}.`,
      )
Stefan Probst's avatar
Stefan Probst committed
57
58
59
60
61
62
63
64
65
66
67

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

Stefan Probst's avatar
Stefan Probst committed
68
69
70
71
72
73
74
75
76
77
78
79
80
      /**
       * 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}` })
      } else {
        // TODO: redirect to separate page explaining that the submmited item is in moderation queue
        const query: ItemSearchQuery = {
          categories: [data.category!],
          order: ['label'],
        }
        router.push({ pathname: '/search', query })
      }
Stefan Probst's avatar
Stefan Probst committed
81
82
    },
    onError() {
83
84
85
86
87
      toast.error(
        `Failed to ${
          isAllowedToPublish ? 'publish' : 'submit'
        } ${categoryLabel}.`,
      )
Stefan Probst's avatar
Stefan Probst committed
88
89
90
    },
  })

Stefan Probst's avatar
Stefan Probst committed
91
  function onSubmit({ draft, ...values }: ItemFormValues) {
Stefan Probst's avatar
Stefan Probst committed
92
93
94
95
96
97
98
99
100
101
102
103
    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
    }

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

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

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

    return errors
  }

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

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