DatasetCreateForm.tsx 5.63 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 { DatasetCore, DatasetDto } from '@/api/sshoc'
import { useCreateDataset, 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
14
import { ActorsFormSection } from '@/components/item/ActorsFormSection/ActorsFormSection'
import { DateFormSection } from '@/components/item/DateFormSection/DateFormSection'
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'
15
import { sanitizeFormValues } from '@/lib/sshoc/sanitizeFormValues'
16
import { useValidateCommonFormFields } from '@/lib/sshoc/validateCommonFormFields'
Stefan Probst's avatar
Stefan Probst committed
17
import { validateDateFormFields } from '@/lib/sshoc/validateDateFormFields'
Stefan Probst's avatar
Stefan Probst committed
18
import { useAuth } from '@/modules/auth/AuthContext'
19
import { useErrorHandlers } from '@/modules/error/useErrorHandlers'
Stefan Probst's avatar
Stefan Probst committed
20
import { Form } from '@/modules/form/Form'
21
import { getSingularItemCategoryLabel } from '@/utils/getSingularItemCategoryLabel'
Stefan Probst's avatar
Stefan Probst committed
22

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

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

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

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

Stefan Probst's avatar
Stefan Probst committed
40
41
42
43
44
  const useItemMutation = useCreateDataset

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

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

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

      if (error instanceof Error) {
        handleErrors(error)
      }
Stefan Probst's avatar
Stefan Probst committed
97
98
99
    },
  })

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

106
    const values = sanitizeFormValues(unsanitized)
Stefan Probst's avatar
Stefan Probst committed
107

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

  function onValidate(values: Partial<ItemFormValues>) {
Stefan Probst's avatar
Stefan Probst committed
116
117
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const errors: Partial<Record<keyof typeof values, any>> = {}
Stefan Probst's avatar
Stefan Probst committed
118

Stefan Probst's avatar
Stefan Probst committed
119
120
    validateCommonFormFields(values, errors)
    validateDateFormFields(values, errors)
Stefan Probst's avatar
Stefan Probst committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134

    return errors
  }

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

  return (
    <Form
      onSubmit={onSubmit}
      validate={onValidate}
      initialValues={initialValues}
    >
Stefan Probst's avatar
Stefan Probst committed
135
      {({ handleSubmit, form, pristine, invalid, submitting }) => {
Stefan Probst's avatar
Stefan Probst committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        return (
          <form
            onSubmit={handleSubmit}
            noValidate
            className="flex flex-col space-y-12"
          >
            <MainFormSection />
            <DateFormSection />
            <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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
                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
169
170
171
172
                isDisabled={
                  pristine || invalid || submitting || create.isLoading
                }
              >
173
                {isAllowedToPublish ? 'Publish' : 'Submit'}
Stefan Probst's avatar
Stefan Probst committed
174
175
176
177
178
179
180
181
              </Button>
            </div>
          </form>
        )
      }}
    </Form>
  )
}