Skip to content

Commit

Permalink
Merge pull request #289 from YujithIsura/master
Browse files Browse the repository at this point in the history
backend validation added for partyname
  • Loading branch information
YujithIsura authored Mar 12, 2020
2 parents d808bbb + 30bd61a commit f2877ff
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 21 deletions.
55 changes: 39 additions & 16 deletions client/src/components/AddParty/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import TextField from '@material-ui/core/TextField';
import Grid from '@material-ui/core/Grid';
import "react-datepicker/dist/react-datepicker.css";
import Button from '@material-ui/core/Button';
import { saveParty} from '../../modules/party/state/PartyAction';
import { saveParty,asyncValidateParty} from '../../modules/party/state/PartyAction';
import { getUploadPath} from '../../modules/nomination/state/NominationAction';
import { connect } from 'react-redux';
import MenuItem from '@material-ui/core/MenuItem';
Expand Down Expand Up @@ -94,6 +94,7 @@ class PartyRegistration extends React.Component {
faxList:[],
fax:'',
status:'',
exist:false
}
}

Expand Down Expand Up @@ -182,6 +183,10 @@ class PartyRegistration extends React.Component {
goNext = false;
}

if (this.state.exist === true) {
this.setState({ errorTextPartyName: 'emptyField2' });
}

if (goNext) {
saveParty(this.state);
onCloseModal();
Expand Down Expand Up @@ -321,6 +326,20 @@ class PartyRegistration extends React.Component {
this.setState({...this.state, faxList});
}

asyncValidation = name => event => {
if (event.target.value) {
asyncValidateParty(event.target.value).then((data) => {
if (data.exist === true) {
this.setState({ exist: data.exist });
} else {
this.setState({ exist: data.exist });
}
})
} else {
this.setState({ exist: false });
}
}

render() {
const { classes, onCloseModal} = this.props;
const { errorTextPartyType,errorTextSecretaryName,errorTextAbbreviation,errorTextApprovedSymbol,errorTextAddress,errorTextTitle,errorTextPartyName,errorTextPhone,errorTextFax } = this.state;
Expand All @@ -345,9 +364,13 @@ class PartyRegistration extends React.Component {
style={{width:'100%'}}
className={classes.textField}
value={this.state.partyName}
onChange={this.handleChange("partyName")}
// onChange={this.handleChange("partyName")}
onChange={(evt) => {
this.handleChange("partyName")(evt)
this.asyncValidation('partyName')(evt)
}}
margin="normal"
helperText={errorTextPartyName === "emptyField" ? 'This field is required!' : ''}
helperText={errorTextPartyName === "emptyField" ? 'This field is required!' : errorTextPartyName === "emptyField2" ? 'This party name already been used!' : ' '}
/>
</Grid>
</Grid>
Expand Down Expand Up @@ -399,19 +422,7 @@ class PartyRegistration extends React.Component {
</Grid>
</Grid>
<Grid style={{ marginLeft: 12,marginBottom:20 }} container direction="row" justify="flex-start" alignItems="stretch" spacing={2}>
<Grid container item lg={4}>
<TextField
error={errorTextSecretaryName}
label="Name of the Secretary"
style={{width:'100%'}}
className={classes.textField}
value={this.state.secretaryName}
onChange={this.handleChange("secretaryName")}
margin="normal"
helperText={errorTextSecretaryName === "emptyField" ? 'This field is required!' : ''}
/>
</Grid>
<Grid container item lg={2}>
<Grid container item lg={2}>
<FormControl style={{width:'80%'}} error={(errorTextPartyType) ? true : false} >
<Select
value={this.state.title}
Expand All @@ -433,6 +444,18 @@ class PartyRegistration extends React.Component {
<FormHelperText style={{marginLeft:18}}>{(errorTextTitle==='emptyField') ? 'This field is required!' : ''}</FormHelperText>
</FormControl>
</Grid>
<Grid container item lg={4}>
<TextField
error={errorTextSecretaryName}
label="Name of the Secretary"
style={{width:'100%'}}
className={classes.textField}
value={this.state.secretaryName}
onChange={this.handleChange("secretaryName")}
margin="normal"
helperText={errorTextSecretaryName === "emptyField" ? 'This field is required!' : ''}
/>
</Grid>
<Grid container item lg={4}>
<TextField
id="outlined-multiline-static"
Expand Down
12 changes: 12 additions & 0 deletions client/src/modules/party/state/PartyAction.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,3 +226,15 @@ function blobToDataURL(blob, callback) {
a.readAsDataURL(blob);
}

export const asyncValidateParty = function asyncValidateParty(partyName) {
let promises = [];
if(partyName){
promises.push(axios.get(`${API_BASE_URL}/teams/validations/${partyName}`));
return axios.all(promises)
.then(args =>{
return {
exist: args[0].data,
}
});
}
}
18 changes: 17 additions & 1 deletion server/src/repository/validation.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { DBError } from 'Errors';
import { DbConnection } from './dataSource';
import { DbConnectionTeam } from './teamDataSource';
import { formatQueryToBulkInsert, formatDataToBulkInsert} from './sqlHelper';
const uuidv4 = require('uuid/v4');


const ELECTION_NAME_VALIDATE_QUERY = `SELECT COUNT( * ) AS COUNT FROM ELECTION WHERE NAME = :electionName `;
const PARTY_NAME_VALIDATE_QUERY = `SELECT COUNT( * ) AS COUNT FROM TEAM WHERE PARTY_NAME = :partyName `;

const TEMPLATE_NAME_VALIDATE_QUERY = `SELECT COUNT( * ) AS COUNT FROM ELECTION_MODULE WHERE NAME = :templateName `;
const ELECTION_STATUS_VALIDATE_QUERY = `SELECT COUNT(*) AS COUNT FROM PAYMENT P LEFT JOIN NOMINATION N ON P.NOMINATION_ID = N.ID
WHERE N.ELECTION_ID = :electionId`;
Expand All @@ -23,6 +26,18 @@ const fetchElectionCount = (electionName) => {
throw new DBError(error);
});
};
const fetchPartyCount = (partyName) => {
const params = {partyName: partyName};
return DbConnectionTeam()
.query(PARTY_NAME_VALIDATE_QUERY,
{
replacements: params,
type: DbConnectionTeam().QueryTypes.SELECT,
}).catch((error) => {
console.log(error);
throw new DBError(error);
});
};
const fetchTemplateCount = (templateName) => {
const params = {templateName: templateName};
return DbConnection()
Expand Down Expand Up @@ -80,5 +95,6 @@ export default {
fetchTemplateCount,
fetchPaymentsByElectionId,
fetchTemplatesByModuleId,
fetchNominationsByNominationId
fetchNominationsByNominationId,
fetchPartyCount
};
3 changes: 2 additions & 1 deletion server/src/routes/constants/URLSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ export const URL_SCHEMA = Joi.object().keys({
keyName: Joi.string(),
sid: Joi.string(),
teamType: Joi.string(),
documentId: Joi.string().max(36).regex(/^[A-Za-z0-9-]+$/)
documentId: Joi.string().max(36).regex(/^[A-Za-z0-9-]+$/),
partyName: Joi.string()
});
14 changes: 12 additions & 2 deletions server/src/routes/teamRouter.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import _ from 'lodash';
import { GET, POST, PUT, DELETE } from 'HttpMethods';
import {TeamService,UploadService} from 'Service';
import {TeamService,UploadService,ValidationService} from 'Service';
import {createRoutes} from '../middleware/Router';
import {HTTP_CODE_201, HTTP_CODE_200} from '../routes/constants/HttpCodes';

Expand Down Expand Up @@ -79,7 +79,17 @@ export const initTeamRouter = (app) => {
return UploadService.getDownloadImage(downloadSid,res,next)
.catch(error => next(error));
},
},
},
{
method: GET,
path: '/teams/validations/:partyName',
schema: {},
handler: (req, res, next) => {
return ValidationService.validatePartyByPartyName(req)
.then((result) => res.status(HTTP_CODE_201).send(result))
.catch(error => next(error));
}
},
]);
};

Expand Down
20 changes: 19 additions & 1 deletion server/src/service/validationService.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,23 @@ const validateElectionsByElectionName = async (req) => {
}
};

const validatePartyByPartyName = async (req) => {
let exist = '';

if(req.params.partyName){
exist = await validationRepo.fetchPartyCount(req.params.partyName);
}
if (!_.isEmpty(exist)) {
if(exist[0].COUNT>0){
return true;
}else{
return false;
}
} else {
throw new ApiError("party name is not found");
}
};

const validateTemplateByTemplateName = async (req) => {

let exist = '';
Expand Down Expand Up @@ -94,5 +111,6 @@ export default {
validateTemplateByTemplateName,
validateElectionStatus,
validateElectionTemplateStatus,
validateNominationStatus
validateNominationStatus,
validatePartyByPartyName
}

0 comments on commit f2877ff

Please sign in to comment.