Commit bcb51637 authored by Vijay Akula's avatar Vijay Akula

Added response format for the Account Controller. Performed code

refactoring for AccountService layer.
parent 337099ad
package com.nisum.mytime.controller; package com.nisum.mytime.controller;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.nisum.mytime.exception.handler.MyTimeException; import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.exception.handler.ResponseDetails;
import com.nisum.mytime.model.Account; import com.nisum.mytime.model.Account;
import com.nisum.mytime.service.AccountServiceImpl; import com.nisum.mytime.service.IAccountService;
@RestController @RestController
@RequestMapping("/account")
public class AccountController { public class AccountController {
@Autowired @Autowired
private AccountServiceImpl accountServiceImpl; private IAccountService accountService;
private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
@RequestMapping(value = "/accounts", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> createAccount(@Valid @RequestBody Account account, HttpServletRequest request)
throws MyTimeException {
logger.info("Serving the Account Creation action");
boolean isAccountExists = accountService.isAccountExists(account);
logger.info("is Account exists with the name " + account.getAccountName() + ":::" + isAccountExists);
if (!isAccountExists) {
Account accountPersisted = accountService.createAccount(account);
ResponseDetails createResponseDetails = new ResponseDetails(new Date(), 601, "Account has been created",
"status description",null, request.getContextPath(), "details", accountPersisted);
return new ResponseEntity<ResponseDetails>(createResponseDetails, HttpStatus.OK);
}
ResponseDetails responseDetails = new ResponseDetails(new Date(), 602, "An Account is already existed",
"Choose the different account name",null, request.getContextPath(), "details", account);
@RequestMapping(value = "/accounts", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) return new ResponseEntity<ResponseDetails>(responseDetails, HttpStatus.OK);
public ResponseEntity<String> addAccount(@RequestBody Account account,@RequestParam(value = "action") String action) throws MyTimeException {
String response = accountServiceImpl.addAccount(account, action);
return new ResponseEntity<>(response, HttpStatus.OK);
} }
@RequestMapping(value = "/accounts/{accountId}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> updateAccount(@RequestBody Account account, @PathVariable String accountId,
HttpServletRequest request) throws MyTimeException {
logger.info("Updating the account with details::"+account);
boolean isAccountExists = accountService.isAccountExists(account);
if (isAccountExists == true) {
Account accountPersisted = accountService.updateAccount(account);
ResponseDetails updateRespDetails = new ResponseDetails(new Date(), 604, "Account has been updated",
"status description",null, request.getContextPath(), "details", accountPersisted);
return new ResponseEntity<ResponseDetails>(updateRespDetails, HttpStatus.OK);
}
ResponseDetails responseDetails = new ResponseDetails(new Date(), 605, "Account is Not found",
"Choose the correct updating account name",null, request.getContextPath(), "details", account);
return new ResponseEntity<ResponseDetails>(responseDetails, HttpStatus.OK);
}
@RequestMapping(value = "/accounts", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "/accounts", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Map<Object, Object>>> getAccounts() throws MyTimeException { public ResponseEntity<?> getAccounts(HttpServletRequest request) throws MyTimeException {
List<Map<Object, Object>> acounts = accountServiceImpl.getAccountsList(); List<Map<Object, Object>> accountsList = accountService.getAccountsList();
return new ResponseEntity<>(acounts, HttpStatus.OK); logger.info("The accounts list::" + accountsList);
ResponseDetails getRespDetails = new ResponseDetails(new Date(), 604, "Retrieved the accounts successfully",
"Accounts list", accountsList, request.getContextPath(), "details", null);
return new ResponseEntity<ResponseDetails>(getRespDetails, HttpStatus.OK);
} }
@RequestMapping(value = "/accountNames", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "/accounts/names", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<String>> getAccountNames() throws MyTimeException { public ResponseEntity<?> getAccountNames(HttpServletRequest request) throws MyTimeException {
List<Account> acounts = accountServiceImpl.getAccounts(); List<Account> acountsList = accountService.getAccounts();
List<String> accountNames = new ArrayList<>(); List<String> accountNamesList = new ArrayList<>();
for (Account account : acounts) {
accountNames.add(account.getAccountName()); for (Account account : acountsList) {
accountNamesList.add(account.getAccountName());
} }
return new ResponseEntity<>(accountNames, HttpStatus.OK); logger.info("The account names list::" + accountNamesList);
ResponseDetails getRespDetails = new ResponseDetails(new Date(), 604,
"Retrieved the account names successfully", "Account names list", accountNamesList,
request.getContextPath(), "details", null);
return new ResponseEntity<ResponseDetails>(getRespDetails, HttpStatus.OK);
} }
@RequestMapping(value = "/accounts", method = RequestMethod.DELETE, produces = MediaType.TEXT_PLAIN_VALUE) @RequestMapping(value = "/accounts/{accountId}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> deleteAccount(@RequestParam(value = "accountId") String accountId) public ResponseEntity<?> deleteAccount(@PathVariable String accountId, HttpServletRequest request)
throws MyTimeException { throws MyTimeException {
accountServiceImpl.deleteAccount(accountId); logger.info("Deleting account with accountId:" + accountId);
return new ResponseEntity<>("Deleted Successfully", HttpStatus.OK); Account accountDeleted = accountService.deleteAccount(accountId);
ResponseDetails deleteRespDetails = new ResponseDetails(new Date(), 604,
"Account has been deleted successfully", "status description", null,request.getContextPath(), "details",
accountDeleted);
return new ResponseEntity<ResponseDetails>(deleteRespDetails, HttpStatus.OK);
} }
} }
\ No newline at end of file
package com.nisum.mytime.controller; package com.nisum.mytime.controller;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
...@@ -18,6 +21,7 @@ import org.springframework.web.bind.annotation.RequestParam; ...@@ -18,6 +21,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.nisum.mytime.exception.handler.MyTimeException; import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.exception.handler.ResponseDetails;
import com.nisum.mytime.model.Domains; import com.nisum.mytime.model.Domains;
import com.nisum.mytime.service.DomainService; import com.nisum.mytime.service.DomainService;
...@@ -34,29 +38,48 @@ public class DomainController { ...@@ -34,29 +38,48 @@ public class DomainController {
private DomainService domainService; private DomainService domainService;
@RequestMapping(value = "/domains", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "/domains", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> addDomain(@RequestBody Domains domains) public ResponseEntity<?> addDomain(@RequestBody Domains domain, HttpServletRequest request) throws MyTimeException {
throws MyTimeException { String response = null;
String response=null; response = domainService.addDomains(domain);
response=domainService.addDomains(domains);
return new ResponseEntity<>(response, HttpStatus.OK); ResponseDetails createRespDetails = new ResponseDetails(new Date(), 801, "Domain has been created",
"Domain Creation", null, request.getContextPath(), "details", domain);
return new ResponseEntity<ResponseDetails>(createRespDetails, HttpStatus.OK);
} }
@RequestMapping(value = "/domains", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "/domains", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<HashMap<Object, Object>>> getAccounts() throws MyTimeException { public ResponseEntity<?> getAccounts(HttpServletRequest request) throws MyTimeException {
return new ResponseEntity<>(domainService.getAllDomains(), HttpStatus.OK);
ResponseDetails getRespDetails = new ResponseDetails(new Date(), 804, "Retrieved the domains successfully",
"Domains list", domainService.getAllDomains(), request.getContextPath(), "details", null);
return new ResponseEntity<ResponseDetails>(getRespDetails, HttpStatus.OK);
}
@RequestMapping(value = "/domains", method = RequestMethod.PUT, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<?> updateDomain(@RequestBody Domains domains, HttpServletRequest request)
throws MyTimeException {
String response = null;
response = domainService.updateDomain(domains);
ResponseDetails updateRespDetails = new ResponseDetails(new Date(), 802, "Domain has been updated",
"Domain Updation", null, request.getContextPath(), "Updation Domain details", domains);
return new ResponseEntity<ResponseDetails>(updateRespDetails, HttpStatus.OK);
} }
@RequestMapping(value = "/domains", method = RequestMethod.DELETE, produces = MediaType.TEXT_PLAIN_VALUE) @RequestMapping(value = "/domains", method = RequestMethod.DELETE, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> deleteDomain(@RequestParam String domainId) throws MyTimeException { public ResponseEntity<?> deleteDomain(@RequestParam String domainId, HttpServletRequest request)
throws MyTimeException {
domainService.deleteDomain(domainId); domainService.deleteDomain(domainId);
return new ResponseEntity<>("Success", HttpStatus.OK);
ResponseDetails deleteRespDetails = new ResponseDetails(new Date(), 804, "Domain has been deleted",
"Domain Deletion", null, request.getContextPath(), "Deletion Domain details", domainId);
return new ResponseEntity<ResponseDetails>(deleteRespDetails, HttpStatus.OK);
} }
@RequestMapping(value = "/domains", method = RequestMethod.PUT, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> updateDomain(@RequestBody Domains domains) throws MyTimeException {
String response=null;
response=domainService.updateDomain(domains);
return new ResponseEntity<>(response, HttpStatus.OK);
}
} }
\ No newline at end of file
...@@ -35,6 +35,7 @@ public class ProjectController { ...@@ -35,6 +35,7 @@ public class ProjectController {
@Autowired @Autowired
private AccountRepo accountRepo; private AccountRepo accountRepo;
@Autowired @Autowired
private ProjectRepo projectRepo; private ProjectRepo projectRepo;
@RequestMapping(value = "/employee", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "/employee", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
......
package com.nisum.mytime.exception.handler;
public class AccountNotFoundException extends RuntimeException {
public AccountNotFoundException(String message) {
super(message);
}
}
package com.nisum.mytime.exception.handler; package com.nisum.mytime.exception.handler;
import java.util.Date;
import javax.security.auth.login.AccountNotFoundException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@RestControllerAdvice @RestControllerAdvice
public class GlobalExceptionHandler{ @RestController
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(DataAccessException.class) @ExceptionHandler(DataAccessException.class)
public String handleDataAccessExceptions(DataAccessException ex){ public String handleDataAccessExceptions(DataAccessException ex) {
log.error("DataAccessException occured due to: ",ex); log.error("DataAccessException occured due to: ", ex);
return "DataAccessException occured due to: "+ex.toString(); return "DataAccessException occured due to: " + ex.toString();
} }
@ExceptionHandler(Exception.class) @ExceptionHandler(Exception.class)
public String handleOtherExceptions(Exception ex){ public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
log.error("Exception occured due to: ",ex); log.error("Exception occured due to: ", ex);
return "Exception occured due to: "+ex.toString(); ResponseDetails errorDetails = new ResponseDetails(new Date(), 502, "Internal Server error occured",
ex.getMessage(), null, request.getContextPath(), request.getDescription(false), null);
return new ResponseEntity<Object>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(AccountNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(AccountNotFoundException ex, WebRequest request) {
ResponseDetails errorDetails = new ResponseDetails(new Date(), 602,
"The Account you are looking for is not found", ex.getMessage(), null, request.getContextPath(),
request.getDescription(false), null);
return new ResponseEntity<Object>(errorDetails, HttpStatus.NOT_FOUND);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ResponseDetails errorDetails = new ResponseDetails(new Date(), 702, "Method Arguement is not validated",
"Validation Failed", null, request.getContextPath(), ex.getBindingResult().toString(), null);
return new ResponseEntity<Object>(errorDetails, HttpStatus.BAD_REQUEST);
} }
} }
\ No newline at end of file
package com.nisum.mytime.exception.handler;
import java.util.Date;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@NoArgsConstructor
public class ResponseDetails {
private Date timestamp;
private int statusCode;
private String message;
private String description;
private Object records;
private String uriPath;
private String details;
private Object requestObject;
public ResponseDetails(Date timestamp, int statusCode, String message, String description, Object records,
String path, String details, Object requestObject) {
super();
this.timestamp = timestamp;
this.statusCode = statusCode;
this.message = message;
this.description = description;
this.records = records;
this.uriPath = path;
this.details = details;
this.requestObject = requestObject;
}
}
\ No newline at end of file
...@@ -3,7 +3,12 @@ package com.nisum.mytime.model; ...@@ -3,7 +3,12 @@ package com.nisum.mytime.model;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.bson.types.ObjectId; import org.bson.types.ObjectId;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
...@@ -23,17 +28,24 @@ public class Account implements Serializable { ...@@ -23,17 +28,24 @@ public class Account implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// private ObjectId id;
@Id @Id
private ObjectId id;
private String accountId; private String accountId;
@NotNull
@Size(min=2,max=50,message="Name should have atlast 2 and less than 50 characters")
private String accountName; private String accountName;
private int accountProjectSequence; private Integer accountProjectSequence;
private String status; private String status;
//private String domain; //private String domain;
//List<String> subDomains; //List<String> subDomains;
@NotBlank
private String clientAddress; private String clientAddress;
@NotBlank
private String industryType; private String industryType;
@NotNull
private List<String> deliveryManagers; private List<String> deliveryManagers;
} }
package com.nisum.mytime.service; package com.nisum.mytime.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import com.nisum.mytime.controller.AccountController;
import com.nisum.mytime.exception.handler.MyTimeException; import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.Account; import com.nisum.mytime.model.Account;
import com.nisum.mytime.model.EmployeeRoles;
import com.nisum.mytime.repository.AccountRepo;
import com.nisum.mytime.utils.CommomUtil;
import com.nisum.mytime.utils.MyTimeUtils;
@Service
public class AccountService implements IAccountService {
@Autowired
private AccountRepo accountRepo;
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private RoleInfoService roleInfoService;
@Autowired
private RoleMappingService roleMappingService;
private static final Logger logger = LoggerFactory.getLogger(AccountService.class);
@Override
public Account createAccount(Account accountReq) throws MyTimeException {
accountReq.setAccountId(generateAccountId());
accountReq.setStatus(MyTimeUtils.STRING_Y);
Account accountPersisted = accountRepo.save(accountReq);
if (logger.isInfoEnabled()) {
logger.info("Account has been persisted in database with account details::" + accountPersisted);
}
if (accountPersisted != null) {
List<String> accountDmsList = accountReq.getDeliveryManagers();
if (accountDmsList != null && !accountDmsList.isEmpty() && accountDmsList.size() > 0) {
String roleId = roleInfoService.getRole(MyTimeUtils.ACCOUNT);
logger.info("Going to add DM role id for account delivery managers::::" + accountDmsList);
roleMappingService.saveUniqueEmployeeAndRole(accountDmsList, roleId);
logger.info("Added roleids for delivery managers in rolemapping collection");
}
}
return accountPersisted;
}
@Override
public Account updateAccount(Account accountUpdating) throws MyTimeException {
Account accountBeforeUpdate = accountRepo.findByAccountId(accountUpdating.getAccountId());
accountUpdating.setStatus(accountBeforeUpdate.getStatus());
accountUpdating.setAccountName(accountUpdating.getAccountName().trim());
logger.info("Updating the roleids of DeliveryManagers in RoleMapping Collection");
final String roleId = roleInfoService.getRole(MyTimeUtils.ACCOUNT);
updateRoleIdsForDeliveryManager(accountUpdating, roleId);
logger.info("Deleting the roleids of DeliveryManagers in RoleMapping Collection");
deleteRoleIdsForDeliveryManager(accountUpdating, roleId);
Account accountUpdated = accountRepo.save(accountUpdating);
logger.info("Account updated::"+accountUpdated);
return accountUpdated;
}
@Override
public boolean isAccountExists(Account account) {
Account accountFetched = accountRepo.findByAccountNameIgnoreCase(account.getAccountName());
return (accountFetched != null) ? true : false;
}
@Override
public List<Account> getAccounts() throws MyTimeException {
return accountRepo.findAll();
}
@Override
public List<Map<Object, Object>> getAccountsList() throws MyTimeException {
List<Map<Object, Object>> updatedAccountList = new ArrayList<>();
List<Map<String, String>> updatedEmployeeList = null;
for (Account account : accountRepo.findAll()) {
updatedEmployeeList = new ArrayList<>();
for (EmployeeRoles employeesRole : getEmployeeDetails(account)) {
updatedEmployeeList.add(getEmployeeDetails(employeesRole));
}
updatedAccountList.add(getAccuntDetails(account, updatedEmployeeList));
}
return updatedAccountList;
}
@Override
public Account deleteAccount(String accountId) throws MyTimeException {
// delete the documents for deliveryManagers in rolemapping collection.
logger.info("After updation:: Deleting the Roleids for DeliveryManagers in RoleMapping collection");
deleteRoleidsForDeliveryManagers(accountId);
// updating the status to "InActive".
Query query = new Query(Criteria.where(MyTimeUtils.ACCOUNT_ID).is(accountId));
Update update = new Update();
update.set(MyTimeUtils.STATUS, MyTimeUtils.STRING_N);
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true);
Account updatedAccount = mongoTemplate.findAndModify(query, update, options, Account.class);
logger.info("The account updated::" + updatedAccount);
return updatedAccount;
}
// generating the account id.
// accountId format is "Acc001"
private String generateAccountId() throws MyTimeException {
return (MyTimeUtils.ACC + MyTimeUtils.ZERO_) + (getAccounts().size() + MyTimeUtils.ONE);
}
private void updateRoleIdsForDeliveryManager(Account accountReq, String roleId) throws MyTimeException {
List<String> updatingDmsList = accountReq.getDeliveryManagers();
List<String> persistedDmsList = accountRepo.findByAccountId(accountReq.getAccountId()).getDeliveryManagers();
List<String> dmsAddedByUser = CommomUtil.getAddedManagersList(persistedDmsList, updatingDmsList);
roleMappingService.saveUniqueEmployeeAndRole(dmsAddedByUser, roleId);
}
private void deleteRoleIdsForDeliveryManager(Account accountUpdating, String roleId) throws MyTimeException {
List<String> dmIdList = null;
Map<String, Integer> dmsCountMap = new HashMap<String, Integer>();
List<String> updatingDmsList = accountUpdating.getDeliveryManagers();
List<String> persistedDmsList = accountRepo.findByAccountId(accountUpdating.getAccountId())
.getDeliveryManagers();
List<String> dmsListDeletedByUser = CommomUtil.getDeletedManagersList(persistedDmsList, updatingDmsList);
List<Account> allAccountList = accountRepo.findAll();
if (allAccountList != null && !allAccountList.isEmpty() && allAccountList.size() > 0) {
for (Account acc : allAccountList) {
dmIdList = acc.getDeliveryManagers();
if (dmIdList != null && !dmIdList.isEmpty() && dmIdList.size() > 0) {
for (String dmId : dmIdList) {
if (dmsCountMap.get(dmId) != null)
dmsCountMap.put(dmId, dmsCountMap.get(dmId) + 1);
else
dmsCountMap.put(dmId, 1);
dmIdList = null;
}
}
}
}
for (String empId : dmsListDeletedByUser) {
if (dmsCountMap.get(empId) == 1) {
// Service call for RoleMapping
roleMappingService.deleteRole(empId, roleId);
}
}
}
// fetching the employee details using employeeId.
private List<EmployeeRoles> getEmployeeDetails(Account account) {
List<EmployeeRoles> employeeRoles = mongoTemplate.find(
new Query(Criteria.where(MyTimeUtils.EMPLOYEE_ID).in(account.getDeliveryManagers())),
EmployeeRoles.class);
return employeeRoles;
}
private HashMap<String, String> getEmployeeDetails(EmployeeRoles employeesRole) {
HashMap<String, String> employeeDetails = new HashMap<>();
employeeDetails.put(MyTimeUtils.EMPLOYEE_ID, employeesRole.getEmployeeId());
employeeDetails.put(MyTimeUtils.EMPLOYEE_NAME, employeesRole.getEmployeeName());
return employeeDetails;
}
private Map<Object, Object> getAccuntDetails(Account account, List<Map<String, String>> updatedEmployeeList) {
Map<Object, Object> accountDetails = new HashMap<>();
//accountDetails.put(MyTimeUtils.ID_, account.getId());
accountDetails.put(MyTimeUtils.ACCOUNT_ID, account.getAccountId());
accountDetails.put(MyTimeUtils.ACCOUNT_NAME, account.getAccountName());
accountDetails.put(MyTimeUtils.STATUS, account.getStatus());
accountDetails.put(MyTimeUtils.CLIENT_ADDRESS, account.getClientAddress());
accountDetails.put(MyTimeUtils.INDUSTRY_TYPE, account.getIndustryType());
accountDetails.put(MyTimeUtils.DELIVERY_MANAGERS, updatedEmployeeList);
return accountDetails;
}
private void deleteRoleidsForDeliveryManagers(String accountId) throws MyTimeException {
int occurrences = 0;
List<Account> allAccountsList = null;
List<String> accountDms = null;
List<String> tempDmsList = new ArrayList<String>();
String roleId = roleInfoService.getRole(MyTimeUtils.ACCOUNT);
allAccountsList = accountRepo.findAll();
List<String> accountDmsList = accountRepo.findByAccountId(accountId).getDeliveryManagers();
for (Account account : allAccountsList) {
accountDms = account.getDeliveryManagers();
for (String accountDm : accountDms)
tempDmsList.add(accountDm);
public interface AccountService { accountDms = null;
}
String addAccount(Account account,String action) throws MyTimeException;
List<Account> getAccounts() throws MyTimeException; for (String dmId : accountDmsList) {
occurrences = Collections.frequency(tempDmsList, dmId);
if (occurrences == 1) {
// Service call for RoleMapping
roleMappingService.deleteRole(dmId, roleId);
}
}
}
List<Map<Object, Object>> getAccountsList() throws MyTimeException;
} }
package com.nisum.mytime.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.Account;
import com.nisum.mytime.model.EmployeeRoles;
import com.nisum.mytime.repository.AccountRepo;
import com.nisum.mytime.utils.CommomUtil;
import com.nisum.mytime.utils.MyTimeUtils;
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private AccountRepo accountRepo;
@Autowired
private RoleInfoService roleInfoService;
@Autowired
private RoleMappingService roleMappingService;
@Override
public String addAccount(Account account,String action) throws MyTimeException {
String response = "";
Account accountResult= null;
final String roleId = roleInfoService.getRole(MyTimeUtils.ACCOUNT);
if( action != null && action.trim().equals(MyTimeUtils.STRING_N)) {//N means adding New Account
if(accountRepo.findByAccountNameIgnoreCase(account.getAccountName().trim()) != null) {
response ="Account already exist";
return response;
}
List<String> accDms = account.getDeliveryManagers();
account.setAccountId(generateAccountId());
account.setAccountName(account.getAccountName().trim());
account.setClientAddress(account.getClientAddress().trim());
account.setStatus(MyTimeUtils.STRING_Y);
accountResult = accountRepo.save(account);
if(accDms != null && !accDms.isEmpty() && accDms.size() > 0) {
roleMappingService.saveUniqueEmployeeAndRole(accDms, roleId);
}
if(accountResult.getId() != null) {
response="Saved succesfully";
}else {
response = "Error occured while account creating";
}
}else if(action != null && action.trim().equals("U")){// U means updating existing Account
List<String> employeeIds = null;
List<String> dmsAddedByUser = null;
List<String> dmsDeletedByUser = null;
Map<String, Integer> dmsCount = new HashMap<String,Integer>();
Account accountBeforeUpdate = accountRepo.findByAccountId(account.getAccountId());
boolean dupAccChkFlag = duplicateAccountCheck(account,accountBeforeUpdate);
if(dupAccChkFlag) {
response ="Account already exist";
return response;
}
List<String> updatedAccDms = account.getDeliveryManagers();
List<String> beforeAccUpdateDms = accountBeforeUpdate.getDeliveryManagers();
dmsAddedByUser = CommomUtil.getAddedManagersList(beforeAccUpdateDms, updatedAccDms);
dmsDeletedByUser = CommomUtil.getDeletedManagersList(beforeAccUpdateDms, updatedAccDms);
List<Account> accountList = accountRepo.findAll();
if(accountList != null && !accountList.isEmpty() && accountList.size() >0) {
for (Account acc : accountList) {
employeeIds = acc.getDeliveryManagers();
if(employeeIds != null && !employeeIds.isEmpty() && employeeIds.size() >0) {
for(String eId:employeeIds) {
if(dmsCount.get(eId) != null)
dmsCount.put(eId, dmsCount.get(eId)+1);
else
dmsCount.put(eId, 1);
employeeIds = null;
}
}
}
}
for (String empId : dmsDeletedByUser) {
if(dmsCount.get(empId)==1) {
//Service call for RoleMapping
roleMappingService.deleteRole(empId,roleId);
}
}
account.setStatus(accountBeforeUpdate.getStatus());
account.setAccountName(account.getAccountName().trim());
accountResult = accountRepo.save(account);
roleMappingService.saveUniqueEmployeeAndRole(dmsAddedByUser, roleId);
response="Updated succesfully";
return response;
}
return response;
}
@Override
public List<Account> getAccounts() throws MyTimeException {
return accountRepo.findAll();
}
@Override
public List<Map<Object, Object>> getAccountsList() throws MyTimeException {
List<Map<Object, Object>> updatedAccountList = new ArrayList<>();
List<Map<String, String>> updatedEmployeeList = null;
for (Account account : accountRepo.findAll()) {
updatedEmployeeList = new ArrayList<>();
for (EmployeeRoles employeesRole : getEmployeeDetails(account)) {
updatedEmployeeList.add(getEmployeeDetails(employeesRole));
}
updatedAccountList.add(getAccuntDetails(account, updatedEmployeeList));
}
return updatedAccountList;
}
// fetching the employee details using employeeId.
private List<EmployeeRoles> getEmployeeDetails(Account account) {
List<EmployeeRoles> employeeRoles = mongoTemplate.find(
new Query(Criteria.where(MyTimeUtils.EMPLOYEE_ID).in(account.getDeliveryManagers())),
EmployeeRoles.class);
return employeeRoles;
}
private HashMap<String, String> getEmployeeDetails(EmployeeRoles employeesRole) {
HashMap<String, String> employeeDetails = new HashMap<>();
employeeDetails.put(MyTimeUtils.EMPLOYEE_ID, employeesRole.getEmployeeId());
employeeDetails.put(MyTimeUtils.EMPLOYEE_NAME, employeesRole.getEmployeeName());
return employeeDetails;
}
private Map<Object, Object> getAccuntDetails(Account account, List<Map<String, String>> updatedEmployeeList) {
Map<Object, Object> accountDetails = new HashMap<>();
accountDetails.put(MyTimeUtils.ID_, account.getId());
accountDetails.put(MyTimeUtils.ACCOUNT_ID, account.getAccountId());
accountDetails.put(MyTimeUtils.ACCOUNT_NAME, account.getAccountName());
accountDetails.put(MyTimeUtils.STATUS, account.getStatus());
accountDetails.put(MyTimeUtils.CLIENT_ADDRESS, account.getClientAddress());
accountDetails.put(MyTimeUtils.INDUSTRY_TYPE, account.getIndustryType());
accountDetails.put(MyTimeUtils.DELIVERY_MANAGERS, updatedEmployeeList);
return accountDetails;
}
// updating the status to "InActive".
public Account deleteAccount(String accountId) throws MyTimeException {
int occurrences = 0;
List<Account> accountsList = null;
List<String> accountDms = null;
List<String> accountsDms = new ArrayList<String>();
String roleId = roleInfoService.getRole(MyTimeUtils.ACCOUNT);
accountsList = accountRepo.findAll();
List<String> deletedAccountDms = accountRepo.findByAccountId(accountId).getDeliveryManagers();
for (Account account : accountsList) {
accountDms = account.getDeliveryManagers();
for(String accountDm:accountDms)
accountsDms.add(accountDm);
accountDms = null;
}
for (String dmId : deletedAccountDms) {
occurrences = Collections.frequency(accountsDms, dmId);
if(occurrences==1) {
//Service call for RoleMapping
roleMappingService.deleteRole(dmId,roleId);
}
}
Query query = new Query(Criteria.where(MyTimeUtils.ACCOUNT_ID).is(accountId));
Update update = new Update();
update.set(MyTimeUtils.STATUS, MyTimeUtils.STRING_N);
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true);
return mongoTemplate.findAndModify(query, update, options, Account.class);
}
// generating the account id.
// accountId format is "Acc001"
private String generateAccountId() throws MyTimeException {
return (MyTimeUtils.ACC + MyTimeUtils.ZERO_) + (getAccounts().size() + MyTimeUtils.ONE);
}
private boolean duplicateAccountCheck(Account UpdatedAccount, Account accountBeforeUpdate ) throws MyTimeException {
boolean accDuplicateflag = false;
String updateAccName = UpdatedAccount.getAccountName().trim();
if(accountBeforeUpdate.getAccountName().trim().equalsIgnoreCase(updateAccName)) {
accDuplicateflag = false;
}else {
if(accountRepo.findByAccountNameIgnoreCase(updateAccName) != null) {
accDuplicateflag = true;
}
}
return accDuplicateflag;
}
}
...@@ -55,6 +55,8 @@ public class DomainServiceImpl implements DomainService { ...@@ -55,6 +55,8 @@ public class DomainServiceImpl implements DomainService {
List<Domains> domainList=domainRepo.findByDomainNameAndAccountId(d.getDomainName(), d.getAccountId()); List<Domains> domainList=domainRepo.findByDomainNameAndAccountId(d.getDomainName(), d.getAccountId());
List<Domains> domainListbyAccountId=domainRepo.findByAccountId(d.getAccountId()); List<Domains> domainListbyAccountId=domainRepo.findByAccountId(d.getAccountId());
//Case sensitive logic //Case sensitive logic
for(Domains domains:domainListbyAccountId ) for(Domains domains:domainListbyAccountId )
{ {
......
package com.nisum.mytime.service;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.Account;
@Service
public interface IAccountService {
Account createAccount(Account account) throws MyTimeException;
Account updateAccount(Account account) throws MyTimeException;
boolean isAccountExists(Account account);
List<Account> getAccounts() throws MyTimeException;
List<Map<Object, Object>> getAccountsList() throws MyTimeException;
Account deleteAccount(String accountId) throws MyTimeException;
}
<!DOCTYPE html>
<html>
<body>
<h1>Something went wrong!</h1>
<a href="/myTeam">Go Home</a>
</body>
</html>
\ No newline at end of file
...@@ -27,14 +27,14 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; ...@@ -27,14 +27,14 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.nisum.mytime.controller.AccountController; import com.nisum.mytime.controller.AccountController;
import com.nisum.mytime.model.Account; import com.nisum.mytime.model.Account;
import com.nisum.mytime.service.IAccountService;
import com.nisum.mytime.service.AccountService; import com.nisum.mytime.service.AccountService;
import com.nisum.mytime.service.AccountServiceImpl;
public class AccountControllerTest { public class AccountControllerTest {
@Mock @Mock
AccountServiceImpl Accountserviceimpl; AccountService Accountserviceimpl;
@InjectMocks @InjectMocks
AccountController AccountController; AccountController AccountController;
...@@ -53,11 +53,12 @@ public class AccountControllerTest { ...@@ -53,11 +53,12 @@ public class AccountControllerTest {
list.add("16620"); list.add("16620");
list.add("16632"); list.add("16632");
String responce=null; String responce=null;
Account persistedAccount=null;
Account account = new Account( Account account = new Account(
new ObjectId("5b62b00950e71a6eecc8c98c"), "Acc003", "Nisum", 3, "Acc003", "Nisum", 3,
"Y","HYD","RetailS",list); "Y","HYD","RetailS",list);
when(Accountserviceimpl.addAccount(account,"N")) when(Accountserviceimpl.createAccount(account))
.thenReturn(responce); .thenReturn(persistedAccount);
String jsonvalue = (new ObjectMapper()) String jsonvalue = (new ObjectMapper())
.writeValueAsString(account).toString(); .writeValueAsString(account).toString();
mockMvc.perform(post("/account/accounts").param("action","N") mockMvc.perform(post("/account/accounts").param("action","N")
...@@ -91,11 +92,12 @@ public class AccountControllerTest { ...@@ -91,11 +92,12 @@ public class AccountControllerTest {
list.add("16620"); list.add("16620");
list.add("16632"); list.add("16632");
String responce=null; String responce=null;
Account accountUpdated=null;
Account account = new Account( Account account = new Account(
new ObjectId("5b62b00950e71a6eecc8c98c"), "Acc003", "Nisum", 3, "Acc003", "Nisum", 3,
"Y","HYD","RetailS",list); "Y","HYD","RetailS",list);
when(Accountserviceimpl.addAccount(account,"U")) when(Accountserviceimpl.createAccount(account))
.thenReturn(responce); .thenReturn(accountUpdated);
String jsonvalue = (new ObjectMapper()) String jsonvalue = (new ObjectMapper())
.writeValueAsString(account).toString(); .writeValueAsString(account).toString();
mockMvc.perform(post("/account/accounts").param("action","U") mockMvc.perform(post("/account/accounts").param("action","U")
...@@ -116,7 +118,7 @@ public class AccountControllerTest { ...@@ -116,7 +118,7 @@ public class AccountControllerTest {
HashMap<Object,Object> map1 = new HashMap<Object,Object>(); HashMap<Object,Object> map1 = new HashMap<Object,Object>();
HashMap<Object,Object> map2 = new HashMap<Object,Object>(); HashMap<Object,Object> map2 = new HashMap<Object,Object>();
Account data1 = new Account(); Account data1 = new Account();
data1.setId(new ObjectId("5976ef15874c902c98b8a05d")); // data1.setId(new ObjectId("5976ef15874c902c98b8a05d"));
data1.setAccountId("Acc004"); data1.setAccountId("Acc004");
data1.setAccountName("Govt"); data1.setAccountName("Govt");
data1.setAccountProjectSequence(4); data1.setAccountProjectSequence(4);
...@@ -131,7 +133,7 @@ public class AccountControllerTest { ...@@ -131,7 +133,7 @@ public class AccountControllerTest {
data1.setDeliveryManagers(list); data1.setDeliveryManagers(list);
Account data2 = new Account(); Account data2 = new Account();
data2.setId(new ObjectId("9976ef15874c902c98b8a05d")); //data2.setId(new ObjectId("9976ef15874c902c98b8a05d"));
data2.setAccountId("Acc004"); data2.setAccountId("Acc004");
data2.setAccountName("Govt"); data2.setAccountName("Govt");
data2.setAccountProjectSequence(4); data2.setAccountProjectSequence(4);
......
...@@ -74,18 +74,17 @@ public class ProjectControllerTest { ...@@ -74,18 +74,17 @@ public class ProjectControllerTest {
public void testaddProject() throws Exception { public void testaddProject() throws Exception {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
list.add("16620"); list.add("16620");
//list.add("16632"); list.add("16632");
Project employeeRole1 = new Project( Project employeeRole1 = new Project(
new ObjectId("9976ef15874c902c98b8a05d"), "102","Macys", "OMS","Active",list, new ObjectId("9976ef15874c902c98b8a05d"), "102","Macys", "NisumIndia","Active",list,
list, "Gap", "Billable",new Date(2017 - 11 - 29), list, "Acc001", "DOM001",new Date(2018 - 06 - 29),
new Date(2017 - 12 - 20), list); new Date(2018 - 12 - 20), list);
Account account = new Account(new ObjectId("5b62cca250e71a6eecc8c682"), Account account = new Account( "Acc001", "Macys", 3, "Y","Macys","Retail",list);
"Acc002", "Macys", 2, "Y","Macys","Retail",list);
when(projectService.addProject(employeeRole1)) when(projectService.addProject(employeeRole1))
.thenReturn(employeeRole1); .thenReturn(employeeRole1);
when(accountRepo.findByAccountId("Acc002")).thenReturn(account); when(accountRepo.findByAccountId("Acc001")).thenReturn(account);
String jsonvalue = (new ObjectMapper()) String jsonvalue = (new ObjectMapper())
.writeValueAsString(employeeRole1).toString(); .writeValueAsString(employeeRole1).toString();
mockMvc.perform(post("/project/addProject") mockMvc.perform(post("/project/addProject")
......
...@@ -342,7 +342,7 @@ public class UserControllerTest { ...@@ -342,7 +342,7 @@ public class UserControllerTest {
List<Account> data = new ArrayList<>(); List<Account> data = new ArrayList<>();
Account account1 = new Account(); Account account1 = new Account();
account1.setId(new ObjectId("5976ef15874c902c98b8a05d")); //account1.setId(new ObjectId("5976ef15874c902c98b8a05d"));
account1.setAccountId("01"); account1.setAccountId("01");
account1.setAccountName("GAP"); account1.setAccountName("GAP");
account1.setAccountProjectSequence(1); account1.setAccountProjectSequence(1);
...@@ -350,7 +350,7 @@ public class UserControllerTest { ...@@ -350,7 +350,7 @@ public class UserControllerTest {
data.add(account1); data.add(account1);
Account account2 = new Account(); Account account2 = new Account();
account2.setId(new ObjectId("2476ef15874c902c98b8a05d")); //account2.setId(new ObjectId("2476ef15874c902c98b8a05d"));
account2.setAccountId("02"); account2.setAccountId("02");
account2.setAccountName("MACYS"); account2.setAccountName("MACYS");
account2.setAccountProjectSequence(2); account2.setAccountProjectSequence(2);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment