- fixed fileupload;

This commit is contained in:
Vitalii Kiiko
2024-10-10 14:42:19 +02:00
parent d9e03efa6c
commit 156aac3d20
5 changed files with 132 additions and 87 deletions

View File

@@ -14,6 +14,7 @@ import { mimeTypes } from '../../../../configData';
const Fileupload = ({ const Fileupload = ({
fieldName, fieldName,
setDataFn, setDataFn,
control,
label, label,
errors, errors,
register, register,
@@ -21,7 +22,7 @@ const Fileupload = ({
config = {}, config = {},
infoText = null, infoText = null,
accept = ['image/*'], accept = ['image/*'],
doctype = 'images', doctype = 'document',
maxSize = 100000000, maxSize = 100000000,
emptyText = __('Trascina qui il tuo file', 'gepafin'), emptyText = __('Trascina qui il tuo file', 'gepafin'),
chooseLabel = __('Aggiungi file', 'gepafin'), chooseLabel = __('Aggiungi file', 'gepafin'),
@@ -29,7 +30,7 @@ const Fileupload = ({
sourceId = 0, sourceId = 0,
source = 'application', source = 'application',
disabled = false, disabled = false,
maxFileSize = 100000000 saveFormCallback = () => {}
}) => { }) => {
const [stateFieldData, setStateFieldData] = useState([]); const [stateFieldData, setStateFieldData] = useState([]);
const [acceptFormats, setAcceptFormats] = useState(''); const [acceptFormats, setAcceptFormats] = useState('');
@@ -51,7 +52,9 @@ const Fileupload = ({
setStateFieldData(data.data); setStateFieldData(data.data);
const files = inputRef.current.getFiles(); const files = inputRef.current.getFiles();
inputRef.current.setUploadedFiles(files); inputRef.current.setUploadedFiles(files);
setDataFn(fieldName, data.data, { shouldValidate: true });
inputRef.current.setFiles([]); inputRef.current.setFiles([]);
saveFormCallback();
} }
} }
@@ -60,11 +63,12 @@ const Fileupload = ({
} }
const itemTemplate = (file) => { const itemTemplate = (file) => {
let fileName = file.fileName ? file.fileName : file.name;
return ( return (
<div className="appForm__fileUploadItem"> <div className="appForm__fileUploadItem">
<div> <div>
<span className="appForm__fileUploadItemName"> <span className="appForm__fileUploadItemName">
{file.name} {fileName}
</span> </span>
</div> </div>
<div> <div>
@@ -72,7 +76,9 @@ const Fileupload = ({
{!file.id ? <Tag value={__('In attesa', 'gepafin')} severity="warning"></Tag> : null} {!file.id ? <Tag value={__('In attesa', 'gepafin')} severity="warning"></Tag> : null}
</div> </div>
<div> <div>
<Button icon="pi pi-times" severity="danger" <Button icon="pi pi-times"
severity="danger"
type="button"
disabled={disabled} disabled={disabled}
aria-label={__('Anulla', 'gepafin')} aria-label={__('Anulla', 'gepafin')}
onClick={() => onTemplateRemove(file)}/> onClick={() => onTemplateRemove(file)}/>
@@ -101,6 +107,8 @@ const Fileupload = ({
setStateFieldData(prevState => { setStateFieldData(prevState => {
const newFiles = prevState.filter(o => o.id !== id); const newFiles = prevState.filter(o => o.id !== id);
inputRef.current.setUploadedFiles(newFiles); inputRef.current.setUploadedFiles(newFiles);
setDataFn(fieldName, newFiles, { shouldValidate: true });
saveFormCallback();
return newFiles; return newFiles;
}); });
} }
@@ -154,11 +162,9 @@ const Fileupload = ({
useEffect(() => { useEffect(() => {
if (inputRef.current) { if (inputRef.current) {
const properValue = multiple inputRef.current.setUploadedFiles(defaultValue);
? defaultValue
: !isEmpty(defaultValue) ? [defaultValue] : [];
inputRef.current.setUploadedFiles(properValue);
} }
setStateFieldData(defaultValue);
}, [defaultValue]); }, [defaultValue]);
useEffect(() => { useEffect(() => {
@@ -166,18 +172,12 @@ const Fileupload = ({
setAcceptFormats(accept.join(',').replace(/\*/g, '.\*').replace(/,/g, '|')); setAcceptFormats(accept.join(',').replace(/\*/g, '.\*').replace(/,/g, '|'));
}, [accept]); }, [accept]);
useEffect(() => {
if (inputRef.current) {
inputRef.current.setUploadedFiles(stateFieldData);
}
setDataFn(fieldName, [...stateFieldData], { shouldValidate: true });
}, [stateFieldData])
return ( return (
sourceId || sourceId === 0 sourceId || sourceId === 0
? <> ? <>
<label htmlFor={fieldName} className={classNames({ 'p-error': errors[fieldName] })}> <label htmlFor={fieldName} className={classNames({ 'p-error': errors[fieldName] })}>
{label}{config.required || config.isRequired ? <span className="appForm__field--required">*</span> : null} {label}{config.required || config.isRequired ?
<span className="appForm__field--required">*</span> : null}
{acceptFormats ? ' (' + getPropeMimeLabels(accept) + ')' : null} {acceptFormats ? ' (' + getPropeMimeLabels(accept) + ')' : null}
</label> </label>
<FileUpload <FileUpload

View File

@@ -1,6 +1,6 @@
export const mimeTypes = [ export const mimeTypes = [
{ name: 'PDF', code: 'application/pdf' }, { name: 'PDF', code: 'application/pdf' },
{ name: 'p7m', ext: '.p7m,application/pkcs7-mime,application/x-pkcs7-mime' }, { name: 'p7m', code: '.p7m,application/pkcs7-mime,application/x-pkcs7-mime' },
{ name: 'ZIP', code: 'application/zip' }, { name: 'ZIP', code: 'application/zip' },
{ name: 'Immagine', code: 'image/*' }, { name: 'Immagine', code: 'image/*' },
{ {

View File

@@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import { range } from 'ramda'; import { range } from 'ramda';
import { __ } from '@wordpress/i18n'; //import { __ } from '@wordpress/i18n';
// components // components
import { Steps } from 'primereact/steps'; import { Steps } from 'primereact/steps';
@@ -9,18 +9,18 @@ const ApplicationSteps = ({ totalSteps = 0, activeStepIndex }) => {
const rangeArr = range(1, totalSteps + 1); const rangeArr = range(1, totalSteps + 1);
const items = rangeArr.map(() => ({ label: 'Passo' })); const items = rangeArr.map(() => ({ label: 'Passo' }));
// TODO update to using Steps after primereact is updated /*// TODO update to using Steps after primereact is updated
return( return(
0 !== totalSteps 0 !== totalSteps
? <span>{__('Passo', 'gepafin')}: {activeStepIndex + 1}</span> ? <span>{__('Passo', 'gepafin')}: {activeStepIndex + 1}</span>
: null : null
) )*/
/*return( return(
0 !== totalSteps 0 !== totalSteps
? <Steps model={items} activeIndex={activeStepIndex} readOnly/> ? <Steps model={items} activeIndex={activeStepIndex} readOnly/>
: null : null
)*/ )
} }
export default ApplicationSteps export default ApplicationSteps

View File

@@ -1,7 +1,6 @@
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef, useMemo } from 'react';
import { __, sprintf } from '@wordpress/i18n'; import { __, sprintf } from '@wordpress/i18n';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
import { klona } from 'klona';
import { head, is, pluck, isEmpty } from 'ramda'; import { head, is, pluck, isEmpty } from 'ramda';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { TZDate } from '@date-fns/tz'; import { TZDate } from '@date-fns/tz';
@@ -37,7 +36,7 @@ import ApplicationSteps from './ApplicationSteps';
const BandoApplication = () => { const BandoApplication = () => {
const { id } = useParams(); const { id } = useParams();
const [formData, setFormData] = useState([]); const [formData, setFormData] = useState([]);
const [formInitialData, setFormInitialData] = useState([]); const [formInitialData, setFormInitialData] = useState(null);
const [bandoTitle, setBandoTitle] = useState(''); const [bandoTitle, setBandoTitle] = useState('');
const [formId, setFormId] = useState(''); const [formId, setFormId] = useState('');
const [totalSteps, setTotalSteps] = useState(0); const [totalSteps, setTotalSteps] = useState(0);
@@ -54,9 +53,14 @@ const BandoApplication = () => {
setValue, setValue,
trigger, trigger,
register, register,
getValues getValues,
} = useForm({ defaultValues: {}, mode: 'onChange' }); reset
const values = getValues(); } = useForm({
defaultValues: useMemo(() => {
return formInitialData ? formInitialData : {}
}, [formInitialData]),
mode: 'onChange'
});
const validationFns = { const validationFns = {
isPIVA, isPIVA,
isCodiceFiscale, isCodiceFiscale,
@@ -68,6 +72,7 @@ const BandoApplication = () => {
isMarcaDaBollo isMarcaDaBollo
} }
const activeStepIndex = activeStep - 1; const activeStepIndex = activeStep - 1;
const values = getValues();
const onSubmit = () => { const onSubmit = () => {
const applId = getApplicationId(); const applId = getApplicationId();
@@ -140,7 +145,7 @@ const BandoApplication = () => {
fieldVal = !fieldVal ? null : fieldVal; fieldVal = !fieldVal ? null : fieldVal;
if (formField && formField.name === 'fileupload') { if (formField && formField.name === 'fileupload') {
fieldVal = is(Array, fieldVal) ? fieldVal.map(o => o.id).join(',') : fieldVal; fieldVal = is(Array, fieldVal) ? fieldVal.map(o => o.id).join(',') : null;
} }
acc.push({ acc.push({
'fieldId': cur, 'fieldId': cur,
@@ -245,7 +250,12 @@ const BandoApplication = () => {
fieldId: o.fieldId, fieldId: o.fieldId,
fieldValue: o.fieldValue fieldValue: o.fieldValue
})); }));
setFormInitialData(submitData) const formDataInitial = submitData.reduce((acc, cur) => {
acc[cur.fieldId] = cur.fieldValue;
return acc;
}, {});
console.log('formDataInitial', formDataInitial)
setFormInitialData(formDataInitial);
} }
} }
storeSet.main.unsetAsyncRequest(); storeSet.main.unsetAsyncRequest();
@@ -277,8 +287,10 @@ const BandoApplication = () => {
} }
useEffect(() => { useEffect(() => {
const newFormData = klona(formInitialData); if (formInitialData) {
newFormData.map(o => setValue(o.fieldId, o.fieldValue)); reset();
Object.keys(formInitialData).map(k => setValue(k, formInitialData[k]))
}
}, [formInitialData]); }, [formInitialData]);
useEffect(() => { useEffect(() => {
@@ -312,7 +324,8 @@ const BandoApplication = () => {
{!isAsyncRequest {!isAsyncRequest
? <div className="appPage__content"> ? <div className="appPage__content">
<form className="appForm" onSubmit={handleSubmit(onSubmit)}> <form className="appForm" onSubmit={handleSubmit(onSubmit)}>
{formData.map(o => { {formInitialData
? formData.map(o => {
const label = head(o.settings.filter(o => o.name === 'label')); const label = head(o.settings.filter(o => o.name === 'label'));
const text = head(o.settings.filter(o => o.name === 'text')); const text = head(o.settings.filter(o => o.name === 'text'));
const placeholder = head(o.settings.filter(o => o.name === 'placeholder')); const placeholder = head(o.settings.filter(o => o.name === 'placeholder'));
@@ -323,7 +336,7 @@ const BandoApplication = () => {
let mimeValue = ''; let mimeValue = '';
if (mime) { if (mime) {
mimeValue = mime.value.map(o => o.code); mimeValue = mime.value.map(o => o.code ? o.code : o.ext);
} }
const validations = Object.keys(o.validators).reduce((acc, cur) => { const validations = Object.keys(o.validators).reduce((acc, cur) => {
@@ -357,17 +370,18 @@ const BandoApplication = () => {
control={control} control={control}
register={register} register={register}
errors={errors} errors={errors}
defaultValue={values[o.id]} defaultValue={values[o.id] ? values[o.id] : ''}
maxFractionDigits={step ? step.value : 0} maxFractionDigits={step ? step.value : 0}
accept={mimeValue} accept={mimeValue}
config={validations} config={validations}
options={options ? options.value : []} options={options ? options.value : []}
setDataFn={setValue} setDataFn={setValue}
saveFormCallback={saveDraft}
sourceId={getApplicationId()} sourceId={getApplicationId()}
useGrouping={false} useGrouping={false}
tableColumns={tableColumns ? tableColumns.value : {}} tableColumns={tableColumns ? tableColumns.value : {}}
/> />
})} }) : null}
<div className="appPage__spacer"></div> <div className="appPage__spacer"></div>

View File

@@ -19,6 +19,7 @@ import { AccordionTab } from 'primereact/accordion';
import { Button } from 'primereact/button'; import { Button } from 'primereact/button';
import { Messages } from 'primereact/messages'; import { Messages } from 'primereact/messages';
import { Message } from 'primereact/message'; import { Message } from 'primereact/message';
import { Toast } from 'primereact/toast';
// api // api
import BandoService from '../../service/bando-service'; import BandoService from '../../service/bando-service';
@@ -35,6 +36,7 @@ const BandoViewBeneficiario = () => {
const [newQuestion, setNewQuestion] = useState(''); const [newQuestion, setNewQuestion] = useState('');
const [applicationObj, setApplicationObj] = useState(true); const [applicationObj, setApplicationObj] = useState(true);
const bandoMsgs = useRef(null); const bandoMsgs = useRef(null);
const toast = useRef(null);
const scaricaBando = () => { const scaricaBando = () => {
@@ -66,6 +68,13 @@ const BandoViewBeneficiario = () => {
} }
const errCreateApplCallback = (data) => { const errCreateApplCallback = (data) => {
if (toast.current) {
toast.current.show({
severity: 'error',
summary: '',
detail: data.message
});
}
if (bandoMsgs.current && data.message) { if (bandoMsgs.current && data.message) {
bandoMsgs.current.show([ bandoMsgs.current.show([
{ {
@@ -103,7 +112,7 @@ const BandoViewBeneficiario = () => {
const createCallBack = (data) => { const createCallBack = (data) => {
if (data.status === 'SUCCESS') { if (data.status === 'SUCCESS') {
setNewQuestion(''); setNewQuestion('');
if (bandoMsgs.current && data.message) { /*if (bandoMsgs.current && data.message) {
bandoMsgs.current.show([ bandoMsgs.current.show([
{ {
sticky: true, severity: 'success', summary: '', sticky: true, severity: 'success', summary: '',
@@ -115,13 +124,20 @@ const BandoViewBeneficiario = () => {
setTimeout(() => { setTimeout(() => {
bandoMsgs.current.clear(); bandoMsgs.current.clear();
}, 5000); }, 5000);
}*/
if (toast.current) {
toast.current.show({
severity: 'success',
summary: '',
detail: data.message
});
} }
} }
storeSet.main.unsetAsyncRequest(); storeSet.main.unsetAsyncRequest();
} }
const errCreateCallback = (data) => { const errCreateCallback = (data) => {
if (bandoMsgs.current && data.message) { /*if (bandoMsgs.current && data.message) {
bandoMsgs.current.show([ bandoMsgs.current.show([
{ {
sticky: true, severity: 'error', summary: '', sticky: true, severity: 'error', summary: '',
@@ -129,6 +145,13 @@ const BandoViewBeneficiario = () => {
closable: true closable: true
} }
]); ]);
}*/
if (toast.current && data.message) {
toast.current.show({
severity: 'error',
summary: '',
detail: data.message
});
} }
storeSet.main.unsetAsyncRequest(); storeSet.main.unsetAsyncRequest();
} }
@@ -140,7 +163,7 @@ const BandoViewBeneficiario = () => {
} }
const errGetBandoCallback = (data) => { const errGetBandoCallback = (data) => {
if (bandoMsgs.current && data.message) { /*if (bandoMsgs.current && data.message) {
bandoMsgs.current.show([ bandoMsgs.current.show([
{ {
sticky: true, severity: 'error', summary: '', sticky: true, severity: 'error', summary: '',
@@ -148,6 +171,13 @@ const BandoViewBeneficiario = () => {
closable: true closable: true
} }
]); ]);
}*/
if (toast.current && data.message) {
toast.current.show({
severity: 'error',
summary: '',
detail: data.message
});
} }
set404FromErrorResponse(data); set404FromErrorResponse(data);
} }
@@ -215,6 +245,7 @@ const BandoViewBeneficiario = () => {
<div className="appPage__spacer"></div> <div className="appPage__spacer"></div>
<Messages ref={bandoMsgs}/> <Messages ref={bandoMsgs}/>
<Toast ref={toast}/>
{!isAsyncRequest && !isEmpty(data) {!isAsyncRequest && !isEmpty(data)
? <div className="appPage__content"> ? <div className="appPage__content">