FormUtils.js 8.8 KB
import {post} from '../../../utils/fetch';
import {getApproversByRecord} from '../../../utils/formUtil';
/*check approvers from values*/
export const getApproversByValues=(service,record_data,form_name)=>{
	return getApproversByRecord({
        service,
        record_data,
        form_name
    });
}
/*get fields*/
export const loadFormFields=(formName,serverName)=>{
	return post('/hr/loadFormFields',{
        formName:formName,
        baseUrl:serverName
    });
}

/*init field validate*/ 
const createValidateObject=(key,fieldType,validates,validateObject)=>{
	validateObject[key]={
		'required':validates.is_required?validates.is_required:false,
		'max':validates.max_length?validates.max_length:9999,
		'min':validates.min_length?validates.min_length:0,
		'trim':/(^\s*)|(\s*$)/g
	};
	if('mobile'==fieldType) 
		validateObject[key]['mobile']=/^(17[0-9]|13[0-9]|14[0-9]|15[0-9]|18[0-9])\d{8}$/i;
	if('email'==fieldType){ 
		validateObject[key]['email']=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
	}
};
const createTabularValidateObject=(key,sectionType,fields,validateTabularObject)=>{
	validateTabularObject[key]={};
	fields.map((field,i)=>{
		if(field.options&&!field.is_invisible_create){
			const options=JSON.parse(field.options); 
			if(field.type=='lookup')
				createValidateObject(field.name+'_ID',field.type,options,validateTabularObject[key]);   
			else
				createValidateObject(field.name,field.type,options,validateTabularObject[key]);   
		} 
	});
};
const initValidateObject=(validateObject,validateTabularObject,formDefine)=>{
	formDefine.map((section,index)=>{
		if(section.type=='tabular'&&section.fields&&section.fields.length>0){ 
			createTabularValidateObject(section.name,section.type,section.fields,validateTabularObject);
		}else if(section.fields&&section.fields.length>0){
			section.fields.map((field,i)=>{
				if(field.options&&!field.is_invisible_create){
					const options=JSON.parse(field.options); 
					if(field.type=='lookup')
						createValidateObject(field.name+'_ID',field.type,options,validateObject);   
					else
						createValidateObject(field.name,field.type,options,validateObject);   
				} 
			});
        }
	});
}
const valiField=(fieldVali,fieldValue)=>{ 
    if(fieldVali.required&&!fieldValue){
        return '此项是必填项';
    }else if(fieldValue){
        if(fieldVali.max){
            if(fieldValue.length<fieldVali.min||fieldValue.length>fieldVali.max)
                return `当前项输入字符数只能在${fieldVali.min}-${fieldVali.max+1}之间`;
        }
        if(fieldVali.mobile){
            if(!fieldVali.mobile.test(fieldValue))
                return '请输入正确的手机号码';
        }
        if(fieldVali.email){
            if(!fieldVali.email.test(fieldValue))
                return '请输入正确的电子邮箱地址';
        }
        if(fieldValue.replace&&!fieldValue.replace(fieldVali.trim,"")){
        	return '此项不能全是空格';
        }
    }
}
const getValueErrors=(validateObject,values,errors)=>{
	for(let fieldKey in validateObject){
		errors[fieldKey]=valiField(validateObject[fieldKey],values[fieldKey]);  
	}
};
const getTabularValueErrors=(validateTabularObject,values,errors)=>{ 
	Object.keys(validateTabularObject).map((key,keyIndex)=>{
		errors[key]=[]; 
		values[key].map((item,index)=>{
			let tempField={};
			for (let fieldTabularKey in validateTabularObject[key]){    
				tempField[fieldTabularKey]=valiField(validateTabularObject[key][fieldTabularKey],item[fieldTabularKey]);   
			} 
			errors[key].push(tempField);
	    }); 
	}) 
};

export const getValidate=(formDefine)=>{ 
    let validateObject={}; 
    let validateTabularObject={}; 
    if(formDefine&&formDefine.length>0){
    	initValidateObject(validateObject,validateTabularObject,formDefine); 
    }  
    return (values)=>{ 
        const errors = {};
        getValueErrors(validateObject,values,errors);
        getTabularValueErrors(validateTabularObject,values,errors); 
        return errors;
    }
}

/*init field keys*/
const pushTabularFieldKey=(field,section,fieldKeys)=>{
	if(field.type=='lookup'&&field.name){
		fieldKeys.push(section.name+'[].'+field.name+'_ID');//related_form_name
	}else if(field.name)
		fieldKeys.push(section.name+'[].'+field.name);
};
const pushFieldKey=(field,fieldKeys)=>{
	if(field.type=='lookup'&&field.name){
		fieldKeys.push(field.name+'_ID');//related_form_name
	}else if(field.name)
		fieldKeys.push(field.name);
};
export const getFieldKeys=(formDefine)=>{
	const fieldKeys=[];
	if(formDefine&&formDefine.length>0){
		formDefine.map((section,index)=>{
            if(section.type=='tabular'&&section.fields&&section.fields.length>0){ 
				section.fields.map((field,i)=>{
					if(field&&!field.is_invisible_create)
						pushTabularFieldKey(field,section,fieldKeys);
				});
			}else if(section.fields&&section.fields.length>0){
				section.fields.map((field,i)=>{
					if(!field.is_invisible_create)
						pushFieldKey(field,fieldKeys);
				});
			}
		})
    }  
    return fieldKeys;
}
 
/*handle initial values*/
export const handleInitialValues=(values)=>{
	if(values&&values.tabular_sections){
		const temp=Object.assign({}, values);
		delete temp.tabular_sections;
		return Object.assign({}, values.tabular_sections,temp);
	}else
		return values;
}

/*format tabular values*/
export const formatTabularValues=(values,formDefine)=>{
	const tempValues=Object.assign({}, values); 
    const tabular_sections={};
    let hasTabular=false;
    formDefine.map((section,index)=>{
        if(section.type=='tabular'){
            tabular_sections[section.name]=values[section.name];
            delete tempValues[section.name];
            hasTabular=true;
        }
    })
    if(hasTabular)
        tempValues['tabular_sections']=tabular_sections;
    return tempValues;
} 


/*handle ajax back error mesage*/
export const getErrors=(res,reject)=>{
	if(res&&res.code&&res.code>=300&&res.code!=400){ 
		reject({'_error':res.message})
		return true;
	}else if(res&&res.code&&res.code==400){
		const errors=_handleError(res);
		console.log(errors);
		reject(errors)
		return true;
	}else if(res&&res.code&&res.code<300){
		return false;
	}else{
		return false;
	}
}

const _handleError=(res)=>{
	if(res&&res.errors){
		const keys=Object.keys(res.errors);
		const backErro={'_error':res.message};
		keys.map(key=>{
			backErro[key]=res.errors[key].join(",");
		});
		return backErro;
	}else{
		return {'_error':res.message};
	} 
}


export const getReduxFormFieldKeys=(formDefine)=>{
    const {basicInfoSection=[],nonTabularSection=[],fileUploadSection=[],tabularSection=[]}=formDefine;
	const keys=[]; 
	basicInfoSection.map(field=>{
		const {type,name}=field;
		if(field.type=='lookup'&&name){
			keys.push(name+'_ID');//related_form_name
		}else if(name)
			keys.push(name);
	});
	nonTabularSection.map(field=>{
		const {type,name}=field;
		if(field.type=='lookup'&&name){
			keys.push(name+'_ID');//related_form_name
		}else if(name)
			keys.push(name);
	});
	fileUploadSection.map(fileField=>{
		const {name}=fileField;
		if(name)
			keys.push(name);
	}); 
	tabularSection.map(tabular=>{
		const {type,name,fields}=tabular; 
		fields.map(field=>{ 
			keys.push('tabular_sections.'+name+'[].'+field.name);
		}); 
	});  
	return keys;
}

const initReduxFormValidateObject=(validateObject,validateTabularObject,formDefine)=>{
	const {basicInfoSection=[],nonTabularSection=[],fileUploadSection=[],tabularSection=[]}=formDefine;
	basicInfoSection.map((field,i)=>{
		if(field.options&&!field.is_invisible_create){
			const options=JSON.parse(field.options); 
			if(field.type=='lookup')
				createValidateObject(field.name+'_ID',field.type,options,validateObject);   
			else
				createValidateObject(field.name,field.type,options,validateObject);   
		}
	});
	nonTabularSection.map((field,i)=>{
		if(field.options&&!field.is_invisible_create){
			const options=JSON.parse(field.options); 
			if(field.type=='lookup')
				createValidateObject(field.name+'_ID',field.type,options,validateObject);   
			else
				createValidateObject(field.name,field.type,options,validateObject);   
		}
	});
	fileUploadSection.map((field,i)=>{
		if(field.options&&!field.is_invisible_create){
			const options=JSON.parse(field.options);  
			createValidateObject(field.name,field.type,options,validateObject);   
		}
	});
	tabularSection.map((section,i)=>{
		createTabularValidateObject(section.name,section.type,section.fields,validateTabularObject);
		 
	}); 
}

export const getReduxFormValidate=(formDefine)=>{ 
	let validateObject={}; 
    let validateTabularObject={}; 
    initReduxFormValidateObject(validateObject,validateTabularObject,formDefine);  
    return (values)=>{ 
        const errors = {};
        getValueErrors(validateObject,values,errors);
        getTabularValueErrors(validateTabularObject,values,errors); 
        return errors;
    }
}

export default {
	getFieldKeys,
	getValidate,
	handleInitialValues,
	formatTabularValues
};