|
| 1 | +import { useEffect, useMemo, useState } from 'react' |
| 2 | +import { useNavigate } from 'react-router-dom' |
| 3 | +import { useTranslation } from 'react-i18next' |
| 4 | +import { FormProvider, useForm } from 'react-hook-form' |
| 5 | +import { |
| 6 | + Accordion, |
| 7 | + Alert, |
| 8 | + Button, |
| 9 | + Col, |
| 10 | + Form, |
| 11 | + RequiredInputSymbol |
| 12 | +} from '@iqss/dataverse-design-system' |
| 13 | +import { |
| 14 | + type MetadataBlockInfo, |
| 15 | + type MetadataField |
| 16 | +} from '@/metadata-block-info/domain/models/MetadataBlockInfo' |
| 17 | +import { |
| 18 | + MetadataFieldsHelper, |
| 19 | + type DatasetMetadataFormValues |
| 20 | +} from '../../DatasetMetadataForm/MetadataFieldsHelper' |
| 21 | +import { MetadataBlockFormFields } from '../../DatasetMetadataForm/MetadataForm/MetadataBlockFormFields' |
| 22 | +import { RequiredFieldText } from '../../RequiredFieldText/RequiredFieldText' |
| 23 | +import { RouteWithParams } from '@/sections/Route.enum' |
| 24 | +import { TemplateRepository } from '@/templates/domain/repositories/TemplateRepository' |
| 25 | +import { useGetTemplatesByCollectionId } from '@/dataset/domain/hooks/useGetTemplatesByCollectionId' |
| 26 | +import { SubmissionStatus, useSubmitTemplate } from '../../useSubmitTemplate' |
| 27 | +import { TemplateInfo } from '@/templates/domain/models/TemplateInfo' |
| 28 | +import styles from './index.module.scss' |
| 29 | + |
| 30 | +interface TemplateFormProps { |
| 31 | + collectionId: string |
| 32 | + templateRepository: TemplateRepository |
| 33 | + metadataBlocksInfo: MetadataBlockInfo[] |
| 34 | + formDefaultValues: DatasetMetadataFormValues |
| 35 | + metadataFieldsForMapping: Record<string, Record<string, MetadataField>> |
| 36 | +} |
| 37 | + |
| 38 | +export const TemplateForm = ({ |
| 39 | + collectionId, |
| 40 | + templateRepository, |
| 41 | + metadataBlocksInfo, |
| 42 | + formDefaultValues, |
| 43 | + metadataFieldsForMapping |
| 44 | +}: TemplateFormProps) => { |
| 45 | + const { t } = useTranslation('datasetTemplates') |
| 46 | + const navigate = useNavigate() |
| 47 | + const [validationError, setValidationError] = useState<string | null>(null) |
| 48 | + const [templateName, setTemplateName] = useState('') |
| 49 | + const [navigateToTermsPending, setNavigateToTermsPending] = useState(false) |
| 50 | + const { submissionStatus, submitError, submitTemplate } = useSubmitTemplate(collectionId) |
| 51 | + |
| 52 | + const { datasetTemplates: templates, fetchDatasetTemplates } = useGetTemplatesByCollectionId({ |
| 53 | + templateRepository, |
| 54 | + collectionIdOrAlias: collectionId |
| 55 | + }) |
| 56 | + |
| 57 | + const currentTemplateId = useMemo(() => { |
| 58 | + const normalizedName = templateName.trim().toLowerCase() |
| 59 | + if (!normalizedName) return null |
| 60 | + |
| 61 | + const match = templates.find( |
| 62 | + (template) => template.name.trim().toLowerCase() === normalizedName |
| 63 | + ) |
| 64 | + return match?.id ?? null |
| 65 | + }, [templates, templateName]) |
| 66 | + |
| 67 | + useEffect(() => { |
| 68 | + if (!navigateToTermsPending) return |
| 69 | + if (currentTemplateId === null) return |
| 70 | + |
| 71 | + setNavigateToTermsPending(false) |
| 72 | + navigate(RouteWithParams.TEMPLATES_EDIT_TERMS(collectionId, currentTemplateId), { |
| 73 | + state: { fromCreateTemplate: true } |
| 74 | + }) |
| 75 | + }, [collectionId, currentTemplateId, navigate, navigateToTermsPending]) |
| 76 | + |
| 77 | + const form = useForm({ mode: 'onChange', defaultValues: formDefaultValues }) |
| 78 | + |
| 79 | + useEffect(() => { |
| 80 | + form.reset(formDefaultValues) |
| 81 | + }, [form, formDefaultValues]) |
| 82 | + |
| 83 | + const handleSaveAndAddTerms = () => { |
| 84 | + if (!templateName.trim()) { |
| 85 | + setValidationError(t('createTemplate.errors.nameRequired')) |
| 86 | + return |
| 87 | + } |
| 88 | + |
| 89 | + setValidationError(null) |
| 90 | + |
| 91 | + void form.handleSubmit(async (formValues) => { |
| 92 | + const formValuesBackToDots = MetadataFieldsHelper.replaceSlashKeysWithDot(formValues) |
| 93 | + const datasetDto = MetadataFieldsHelper.formatFormValuesToDatasetDTO( |
| 94 | + formValuesBackToDots, |
| 95 | + 'create' |
| 96 | + ) |
| 97 | + const templateFields = datasetDto.metadataBlocks.flatMap((metadataBlock) => |
| 98 | + MetadataFieldsHelper.buildTemplateFieldsFromMetadataValues( |
| 99 | + metadataBlock.fields, |
| 100 | + metadataFieldsForMapping[metadataBlock.name] ?? {} |
| 101 | + ) |
| 102 | + ) |
| 103 | + |
| 104 | + const templatePayload: TemplateInfo = { |
| 105 | + name: templateName.trim(), |
| 106 | + fields: templateFields |
| 107 | + } |
| 108 | + |
| 109 | + const didSubmit = await submitTemplate(templatePayload) |
| 110 | + if (!didSubmit) return |
| 111 | + |
| 112 | + await fetchDatasetTemplates() |
| 113 | + setNavigateToTermsPending(true) |
| 114 | + })() |
| 115 | + } |
| 116 | + |
| 117 | + return ( |
| 118 | + <FormProvider {...form}> |
| 119 | + <form noValidate={true}> |
| 120 | + {submissionStatus === SubmissionStatus.SubmitComplete && ( |
| 121 | + <Alert variant="success" dismissible={false}> |
| 122 | + {t('createTemplate.alerts.success')} |
| 123 | + </Alert> |
| 124 | + )} |
| 125 | + {(validationError ?? submitError) && ( |
| 126 | + <Alert variant="danger" dismissible={false}> |
| 127 | + {validationError ?? submitError} |
| 128 | + </Alert> |
| 129 | + )} |
| 130 | + <Form.Group className={styles['template-name-row']} controlId="template-name"> |
| 131 | + <Form.Group.Label column sm={3}> |
| 132 | + {t('createTemplate.templateName')} |
| 133 | + <RequiredInputSymbol /> |
| 134 | + </Form.Group.Label> |
| 135 | + <Col sm={9}> |
| 136 | + <Form.Group.Input |
| 137 | + type="text" |
| 138 | + required |
| 139 | + isInvalid={Boolean(validationError)} |
| 140 | + value={templateName} |
| 141 | + onChange={(event) => { |
| 142 | + const nextValue = event.target.value |
| 143 | + setTemplateName(nextValue) |
| 144 | + if (validationError && nextValue.trim()) { |
| 145 | + setValidationError(null) |
| 146 | + } |
| 147 | + }} |
| 148 | + /> |
| 149 | + {validationError && ( |
| 150 | + <Form.Group.Feedback type="invalid">{validationError}</Form.Group.Feedback> |
| 151 | + )} |
| 152 | + </Col> |
| 153 | + </Form.Group> |
| 154 | + <RequiredFieldText /> |
| 155 | + <Accordion defaultActiveKey="0" className={styles.accordion}> |
| 156 | + {metadataBlocksInfo.map((metadataBlock, index) => ( |
| 157 | + <Accordion.Item |
| 158 | + eventKey={index.toString()} |
| 159 | + id={`metadata-block-item-${metadataBlock.name}`} |
| 160 | + key={metadataBlock.id}> |
| 161 | + <Accordion.Header>{metadataBlock.displayName}</Accordion.Header> |
| 162 | + <Accordion.Body> |
| 163 | + <MetadataBlockFormFields metadataBlock={metadataBlock} /> |
| 164 | + </Accordion.Body> |
| 165 | + </Accordion.Item> |
| 166 | + ))} |
| 167 | + </Accordion> |
| 168 | + <div className={styles['form-actions']}> |
| 169 | + <Button |
| 170 | + type="button" |
| 171 | + onClick={handleSaveAndAddTerms} |
| 172 | + disabled={submissionStatus === SubmissionStatus.IsSubmitting}> |
| 173 | + {t('createTemplate.saveAddTerms')} |
| 174 | + </Button> |
| 175 | + <Button |
| 176 | + type="button" |
| 177 | + variant="secondary" |
| 178 | + withSpacing |
| 179 | + onClick={() => navigate(RouteWithParams.COLLECTION_TEMPLATES(collectionId))}> |
| 180 | + {t('createTemplate.cancel')} |
| 181 | + </Button> |
| 182 | + </div> |
| 183 | + </form> |
| 184 | + </FormProvider> |
| 185 | + ) |
| 186 | +} |
0 commit comments