commit to tidy up staff changes showing as modified

This commit is contained in:
John Woodlock
2012-09-10 00:10:29 +10:00
parent 06ac7a46e2
commit 1877562ea8
9 changed files with 699 additions and 699 deletions
@@ -1,153 +1,153 @@
package org.mifosng.platform.api;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang.StringUtils;
import org.mifosng.platform.api.commands.StaffCommand;
import org.mifosng.platform.api.data.EntityIdentifier;
import org.mifosng.platform.api.data.OfficeLookup;
import org.mifosng.platform.api.data.StaffData;
import org.mifosng.platform.api.infrastructure.ApiDataConversionService;
import org.mifosng.platform.api.infrastructure.ApiJsonSerializerService;
import org.mifosng.platform.api.infrastructure.ApiParameterHelper;
import org.mifosng.platform.organisation.service.OfficeReadPlatformService;
import org.mifosng.platform.staff.service.StaffReadPlatformService;
import org.mifosng.platform.staff.service.StaffWritePlatformService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Path("/staff")
@Component
@Scope("singleton")
public class StaffApiResource {
@Autowired
private StaffReadPlatformService readPlatformService;
@Autowired
private StaffWritePlatformService writePlatformService;
@Autowired
private ApiDataConversionService apiDataConversionService;
@Autowired
private ApiJsonSerializerService apiJsonSerializerService;
@Autowired
private OfficeReadPlatformService officeReadPlatformService;
private final static Logger logger = LoggerFactory
.getLogger(StaffApiResource.class);
@GET
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveStaff(@Context final UriInfo uriInfo,
@QueryParam("sqlSearch") final String sqlSearch,
@QueryParam("officeId") final Integer officeId) {
Set<String> responseParameters = ApiParameterHelper
.extractFieldsForResponseIfProvided(uriInfo
.getQueryParameters());
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo
.getQueryParameters());
final String extraCriteria = getStaffCriteria(sqlSearch, officeId);
final Collection<StaffData> staff = this.readPlatformService
.retrieveAllStaff(extraCriteria);
return this.apiJsonSerializerService.serializeStaffDataToJson(
prettyPrint, responseParameters, staff);
}
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response createStaff(final String jsonRequestBody) {
final StaffCommand command = this.apiDataConversionService
.convertJsonToStaffCommand(null, jsonRequestBody);
final Long staffId = this.writePlatformService.createStaff(command);
return Response.ok().entity(new EntityIdentifier(staffId)).build();
}
@GET
@Path("{staffId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retreiveStaff(@PathParam("staffId") final Long staffId,
@Context final UriInfo uriInfo) {
final Set<String> responseParameters = ApiParameterHelper
.extractFieldsForResponseIfProvided(uriInfo
.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo
.getQueryParameters());
boolean template = ApiParameterHelper.template(uriInfo
.getQueryParameters());
final StaffData staff = this.readPlatformService.retrieveStaff(staffId);
if (template) {
staff.setAllowedOffices(new ArrayList<OfficeLookup>(
officeReadPlatformService.retrieveAllOfficesForLookup()));
}
return this.apiJsonSerializerService.serializeStaffDataToJson(
prettyPrint, responseParameters, staff);
}
@PUT
@Path("{staffId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response updateStaff(@PathParam("staffId") final Long staffId,
final String jsonRequestBody) {
final StaffCommand command = this.apiDataConversionService
.convertJsonToStaffCommand(staffId, jsonRequestBody);
final Long entityId = this.writePlatformService.updateStaff(command);
return Response.ok().entity(new EntityIdentifier(entityId)).build();
}
private String getStaffCriteria(String sqlSearch, Integer officeId) {
String extraCriteria = "";
if (sqlSearch != null) {
extraCriteria = " and (" + sqlSearch + ")";
}
if (officeId != null) {
extraCriteria += " and office_id = " + officeId;
}
if (StringUtils.isNotBlank(extraCriteria)) {
extraCriteria = extraCriteria.substring(4);
}
logger.info("extraCriteria; " + extraCriteria);
return extraCriteria;
}
package org.mifosng.platform.api;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang.StringUtils;
import org.mifosng.platform.api.commands.StaffCommand;
import org.mifosng.platform.api.data.EntityIdentifier;
import org.mifosng.platform.api.data.OfficeLookup;
import org.mifosng.platform.api.data.StaffData;
import org.mifosng.platform.api.infrastructure.ApiDataConversionService;
import org.mifosng.platform.api.infrastructure.ApiJsonSerializerService;
import org.mifosng.platform.api.infrastructure.ApiParameterHelper;
import org.mifosng.platform.organisation.service.OfficeReadPlatformService;
import org.mifosng.platform.staff.service.StaffReadPlatformService;
import org.mifosng.platform.staff.service.StaffWritePlatformService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Path("/staff")
@Component
@Scope("singleton")
public class StaffApiResource {
@Autowired
private StaffReadPlatformService readPlatformService;
@Autowired
private StaffWritePlatformService writePlatformService;
@Autowired
private ApiDataConversionService apiDataConversionService;
@Autowired
private ApiJsonSerializerService apiJsonSerializerService;
@Autowired
private OfficeReadPlatformService officeReadPlatformService;
private final static Logger logger = LoggerFactory
.getLogger(StaffApiResource.class);
@GET
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveStaff(@Context final UriInfo uriInfo,
@QueryParam("sqlSearch") final String sqlSearch,
@QueryParam("officeId") final Integer officeId) {
Set<String> responseParameters = ApiParameterHelper
.extractFieldsForResponseIfProvided(uriInfo
.getQueryParameters());
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo
.getQueryParameters());
final String extraCriteria = getStaffCriteria(sqlSearch, officeId);
final Collection<StaffData> staff = this.readPlatformService
.retrieveAllStaff(extraCriteria);
return this.apiJsonSerializerService.serializeStaffDataToJson(
prettyPrint, responseParameters, staff);
}
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response createStaff(final String jsonRequestBody) {
final StaffCommand command = this.apiDataConversionService
.convertJsonToStaffCommand(null, jsonRequestBody);
final Long staffId = this.writePlatformService.createStaff(command);
return Response.ok().entity(new EntityIdentifier(staffId)).build();
}
@GET
@Path("{staffId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retreiveStaff(@PathParam("staffId") final Long staffId,
@Context final UriInfo uriInfo) {
final Set<String> responseParameters = ApiParameterHelper
.extractFieldsForResponseIfProvided(uriInfo
.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo
.getQueryParameters());
boolean template = ApiParameterHelper.template(uriInfo
.getQueryParameters());
final StaffData staff = this.readPlatformService.retrieveStaff(staffId);
if (template) {
staff.setAllowedOffices(new ArrayList<OfficeLookup>(
officeReadPlatformService.retrieveAllOfficesForLookup()));
}
return this.apiJsonSerializerService.serializeStaffDataToJson(
prettyPrint, responseParameters, staff);
}
@PUT
@Path("{staffId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response updateStaff(@PathParam("staffId") final Long staffId,
final String jsonRequestBody) {
final StaffCommand command = this.apiDataConversionService
.convertJsonToStaffCommand(staffId, jsonRequestBody);
final Long entityId = this.writePlatformService.updateStaff(command);
return Response.ok().entity(new EntityIdentifier(entityId)).build();
}
private String getStaffCriteria(String sqlSearch, Integer officeId) {
String extraCriteria = "";
if (sqlSearch != null) {
extraCriteria = " and (" + sqlSearch + ")";
}
if (officeId != null) {
extraCriteria += " and office_id = " + officeId;
}
if (StringUtils.isNotBlank(extraCriteria)) {
extraCriteria = extraCriteria.substring(4);
}
logger.info("extraCriteria; " + extraCriteria);
return extraCriteria;
}
}
@@ -1,65 +1,65 @@
package org.mifosng.platform.api.commands;
import java.util.Set;
/**
* Immutable command for creating or updating details of a staff member.
*/
public class StaffCommand {
private final Long id;
private final String firstName;
private final String lastName;
private final Long officeId;
private final boolean loanOfficerFlag;
private final Set<String> modifiedParameters;
public StaffCommand(final Set<String> modifiedParameters, final Long id,
final Long officeId, final String firstName, final String lastName,
final boolean loanOfficerFlag) {
this.modifiedParameters = modifiedParameters;
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.officeId = officeId;
this.loanOfficerFlag = loanOfficerFlag;
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Long getOfficeId() {
return officeId;
}
public boolean isLoanOfficerFlag() {
return loanOfficerFlag;
}
public boolean isFirstNameChanged() {
return this.modifiedParameters.contains("firstname");
}
public boolean isLastNameChanged() {
return this.modifiedParameters.contains("lastname");
}
public boolean isLoanOfficerFlagChanged() {
return this.modifiedParameters.contains("loanOfficerFlag");
}
public boolean isOfficeChanged() {
return this.modifiedParameters.contains("officeId");
}
package org.mifosng.platform.api.commands;
import java.util.Set;
/**
* Immutable command for creating or updating details of a staff member.
*/
public class StaffCommand {
private final Long id;
private final String firstName;
private final String lastName;
private final Long officeId;
private final boolean loanOfficerFlag;
private final Set<String> modifiedParameters;
public StaffCommand(final Set<String> modifiedParameters, final Long id,
final Long officeId, final String firstName, final String lastName,
final boolean loanOfficerFlag) {
this.modifiedParameters = modifiedParameters;
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.officeId = officeId;
this.loanOfficerFlag = loanOfficerFlag;
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Long getOfficeId() {
return officeId;
}
public boolean isLoanOfficerFlag() {
return loanOfficerFlag;
}
public boolean isFirstNameChanged() {
return this.modifiedParameters.contains("firstname");
}
public boolean isLastNameChanged() {
return this.modifiedParameters.contains("lastname");
}
public boolean isLoanOfficerFlagChanged() {
return this.modifiedParameters.contains("loanOfficerFlag");
}
public boolean isOfficeChanged() {
return this.modifiedParameters.contains("officeId");
}
}
@@ -1,84 +1,84 @@
package org.mifosng.platform.api.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class StaffData implements Serializable {
private Long id;
private String firstname;
private String lastname;
private String displayName;
private final Long officeId;
private final String officeName;
private final Boolean loanOfficerFlag;
private List<OfficeLookup> allowedOffices = new ArrayList<OfficeLookup>();
public StaffData(final Long id, final String firstname,
final String lastname, final String displayName,
final Long officeId, final String officeName,
final Boolean loanOfficerFlag) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.displayName = displayName;
this.officeName = officeName;
this.loanOfficerFlag = loanOfficerFlag;
this.officeId = officeId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public Long getOfficeId() {
return officeId;
}
public String getOfficeName() {
return officeName;
}
public Boolean getLoanOfficerFlag() {
return loanOfficerFlag;
}
public List<OfficeLookup> getAllowedOffices() {
return allowedOffices;
}
public void setAllowedOffices(List<OfficeLookup> allowedOffices) {
this.allowedOffices = allowedOffices;
}
package org.mifosng.platform.api.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class StaffData implements Serializable {
private Long id;
private String firstname;
private String lastname;
private String displayName;
private final Long officeId;
private final String officeName;
private final Boolean loanOfficerFlag;
private List<OfficeLookup> allowedOffices = new ArrayList<OfficeLookup>();
public StaffData(final Long id, final String firstname,
final String lastname, final String displayName,
final Long officeId, final String officeName,
final Boolean loanOfficerFlag) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.displayName = displayName;
this.officeName = officeName;
this.loanOfficerFlag = loanOfficerFlag;
this.officeId = officeId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public Long getOfficeId() {
return officeId;
}
public String getOfficeName() {
return officeName;
}
public Boolean getLoanOfficerFlag() {
return loanOfficerFlag;
}
public List<OfficeLookup> getAllowedOffices() {
return allowedOffices;
}
public void setAllowedOffices(List<OfficeLookup> allowedOffices) {
this.allowedOffices = allowedOffices;
}
}
@@ -1,13 +1,13 @@
package org.mifosng.platform.exceptions;
/**
* A {@link RuntimeException} thrown when staff resources are not found.
*/
public class StaffNotFoundException extends
AbstractPlatformResourceNotFoundException {
public StaffNotFoundException(final Long id) {
super("error.msg.staff.id.invalid", "Staff with identifier " + id
+ " does not exist", id);
}
package org.mifosng.platform.exceptions;
/**
* A {@link RuntimeException} thrown when staff resources are not found.
*/
public class StaffNotFoundException extends
AbstractPlatformResourceNotFoundException {
public StaffNotFoundException(final Long id) {
super("error.msg.staff.id.invalid", "Staff with identifier " + id
+ " does not exist", id);
}
}
@@ -1,95 +1,95 @@
package org.mifosng.platform.staff.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.apache.commons.lang.StringUtils;
import org.mifosng.platform.api.commands.StaffCommand;
import org.mifosng.platform.infrastructure.AbstractAuditableCustom;
import org.mifosng.platform.organisation.domain.Office;
import org.mifosng.platform.user.domain.AppUser;
@Entity
@Table(name = "m_staff", uniqueConstraints = { @UniqueConstraint(columnNames = { "display_name" }, name = "display_name") })
public class Staff extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "firstname", length = 50)
private String firstname;
@Column(name = "lastname", length = 50)
private String lastname;
@SuppressWarnings("unused")
@Column(name = "display_name", length = 100)
private String displayName;
// Office to which this employee belongs
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "office_id", nullable = false)
private Office office;
// Flag determines if employee is a loan Officer
@SuppressWarnings("unused")
@Column(name = "is_loan_officer ", nullable = false)
private Boolean loanOfficerFlag;
public static Staff createNew(Office staffOffice, final String firstname,
final String lastname, boolean isLoanOfficer) {
return new Staff(staffOffice, firstname, lastname, isLoanOfficer);
}
protected Staff() {
//
}
private Staff(final Office staffOffice, final String firstname,
final String lastname, final boolean isLoanOfficer) {
this.office = staffOffice;
this.firstname = StringUtils.defaultIfEmpty(firstname, null);
this.lastname = StringUtils.defaultIfEmpty(lastname, null);
this.loanOfficerFlag = isLoanOfficer;
deriveDisplayName(firstname);
}
public void update(final StaffCommand command, final Office staffOffice) {
if (command.isOfficeChanged()) {
this.office = staffOffice;
}
if (command.isFirstNameChanged()) {
this.firstname = StringUtils.defaultIfEmpty(command.getFirstName(),
null);
}
if (command.isLastNameChanged()) {
this.lastname = StringUtils.defaultIfEmpty(command.getLastName(),
null);
}
if (command.isLastNameChanged() || command.isFirstNameChanged()) {
deriveDisplayName(firstname);
}
if (command.isLoanOfficerFlagChanged()) {
this.loanOfficerFlag = command.isLoanOfficerFlag();
}
}
private void deriveDisplayName(final String firstname) {
if (!StringUtils.isBlank(firstname)) {
this.displayName = this.lastname + ", " + this.firstname;
} else {
this.displayName = this.lastname;
}
}
public Boolean getLoanOfficerFlag() {
return loanOfficerFlag;
}
package org.mifosng.platform.staff.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.apache.commons.lang.StringUtils;
import org.mifosng.platform.api.commands.StaffCommand;
import org.mifosng.platform.infrastructure.AbstractAuditableCustom;
import org.mifosng.platform.organisation.domain.Office;
import org.mifosng.platform.user.domain.AppUser;
@Entity
@Table(name = "m_staff", uniqueConstraints = { @UniqueConstraint(columnNames = { "display_name" }, name = "display_name") })
public class Staff extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "firstname", length = 50)
private String firstname;
@Column(name = "lastname", length = 50)
private String lastname;
@SuppressWarnings("unused")
@Column(name = "display_name", length = 100)
private String displayName;
// Office to which this employee belongs
@SuppressWarnings("unused")
@ManyToOne
@JoinColumn(name = "office_id", nullable = false)
private Office office;
// Flag determines if employee is a loan Officer
@SuppressWarnings("unused")
@Column(name = "is_loan_officer ", nullable = false)
private Boolean loanOfficerFlag;
public static Staff createNew(Office staffOffice, final String firstname,
final String lastname, boolean isLoanOfficer) {
return new Staff(staffOffice, firstname, lastname, isLoanOfficer);
}
protected Staff() {
//
}
private Staff(final Office staffOffice, final String firstname,
final String lastname, final boolean isLoanOfficer) {
this.office = staffOffice;
this.firstname = StringUtils.defaultIfEmpty(firstname, null);
this.lastname = StringUtils.defaultIfEmpty(lastname, null);
this.loanOfficerFlag = isLoanOfficer;
deriveDisplayName(firstname);
}
public void update(final StaffCommand command, final Office staffOffice) {
if (command.isOfficeChanged()) {
this.office = staffOffice;
}
if (command.isFirstNameChanged()) {
this.firstname = StringUtils.defaultIfEmpty(command.getFirstName(),
null);
}
if (command.isLastNameChanged()) {
this.lastname = StringUtils.defaultIfEmpty(command.getLastName(),
null);
}
if (command.isLastNameChanged() || command.isFirstNameChanged()) {
deriveDisplayName(firstname);
}
if (command.isLoanOfficerFlagChanged()) {
this.loanOfficerFlag = command.isLoanOfficerFlag();
}
}
private void deriveDisplayName(final String firstname) {
if (!StringUtils.isBlank(firstname)) {
this.displayName = this.lastname + ", " + this.firstname;
} else {
this.displayName = this.lastname;
}
}
public Boolean getLoanOfficerFlag() {
return loanOfficerFlag;
}
}
@@ -1,68 +1,68 @@
package org.mifosng.platform.staff.service;
import java.util.ArrayList;
import java.util.List;
import org.mifosng.platform.DataValidatorBuilder;
import org.mifosng.platform.api.commands.StaffCommand;
import org.mifosng.platform.api.data.ApiParameterError;
import org.mifosng.platform.exceptions.PlatformApiDataValidationException;
public class StaffCommandValidator {
private final StaffCommand command;
public StaffCommandValidator(StaffCommand command) {
this.command = command;
}
public void validateForCreate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(
dataValidationErrors).resource("staff");
baseDataValidator.reset().parameter("firstname")
.value(command.getFirstName()).ignoreIfNull()
.notExceedingLengthOf(50);
baseDataValidator.reset().parameter("lastname")
.value(command.getLastName()).notBlank()
.notExceedingLengthOf(50);
baseDataValidator.reset().parameter("officeId")
.value(command.getOfficeId()).notNull()
.integerGreaterThanZero();
if (!dataValidationErrors.isEmpty()) {
throw new PlatformApiDataValidationException(
"validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors);
}
}
public void validateForUpdate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(
dataValidationErrors).resource("staff");
baseDataValidator.reset().parameter("id").value(command.getId())
.notNull();
baseDataValidator.reset().parameter("firstname")
.value(command.getFirstName()).ignoreIfNull()
.notExceedingLengthOf(50);
baseDataValidator.reset().parameter("lastname")
.value(command.getFirstName()).ignoreIfNull().notBlank()
.notExceedingLengthOf(50);
baseDataValidator.reset().anyOfNotNull(command.getFirstName(),
command.getLastName());
if (!dataValidationErrors.isEmpty()) {
throw new PlatformApiDataValidationException(
"validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors);
}
}
package org.mifosng.platform.staff.service;
import java.util.ArrayList;
import java.util.List;
import org.mifosng.platform.DataValidatorBuilder;
import org.mifosng.platform.api.commands.StaffCommand;
import org.mifosng.platform.api.data.ApiParameterError;
import org.mifosng.platform.exceptions.PlatformApiDataValidationException;
public class StaffCommandValidator {
private final StaffCommand command;
public StaffCommandValidator(StaffCommand command) {
this.command = command;
}
public void validateForCreate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(
dataValidationErrors).resource("staff");
baseDataValidator.reset().parameter("firstname")
.value(command.getFirstName()).ignoreIfNull()
.notExceedingLengthOf(50);
baseDataValidator.reset().parameter("lastname")
.value(command.getLastName()).notBlank()
.notExceedingLengthOf(50);
baseDataValidator.reset().parameter("officeId")
.value(command.getOfficeId()).notNull()
.integerGreaterThanZero();
if (!dataValidationErrors.isEmpty()) {
throw new PlatformApiDataValidationException(
"validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors);
}
}
public void validateForUpdate() {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(
dataValidationErrors).resource("staff");
baseDataValidator.reset().parameter("id").value(command.getId())
.notNull();
baseDataValidator.reset().parameter("firstname")
.value(command.getFirstName()).ignoreIfNull()
.notExceedingLengthOf(50);
baseDataValidator.reset().parameter("lastname")
.value(command.getFirstName()).ignoreIfNull().notBlank()
.notExceedingLengthOf(50);
baseDataValidator.reset().anyOfNotNull(command.getFirstName(),
command.getLastName());
if (!dataValidationErrors.isEmpty()) {
throw new PlatformApiDataValidationException(
"validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors);
}
}
}
@@ -1,12 +1,12 @@
package org.mifosng.platform.staff.service;
import java.util.Collection;
import org.mifosng.platform.api.data.StaffData;
public interface StaffReadPlatformService {
StaffData retrieveStaff(Long staffId);
Collection<StaffData> retrieveAllStaff(final String extraCriteria);
package org.mifosng.platform.staff.service;
import java.util.Collection;
import org.mifosng.platform.api.data.StaffData;
public interface StaffReadPlatformService {
StaffData retrieveStaff(Long staffId);
Collection<StaffData> retrieveAllStaff(final String extraCriteria);
}
@@ -1,88 +1,88 @@
package org.mifosng.platform.staff.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.mifosng.platform.api.data.StaffData;
import org.mifosng.platform.exceptions.StaffNotFoundException;
import org.mifosng.platform.infrastructure.TenantAwareRoutingDataSource;
import org.mifosng.platform.security.PlatformSecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
@Service
public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context;
@Autowired
public StaffReadPlatformServiceImpl(final PlatformSecurityContext context,
final TenantAwareRoutingDataSource dataSource) {
this.context = context;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
private static final class StaffMapper implements RowMapper<StaffData> {
public String schema() {
return " s.id as id,s.office_id as officeId, o.name as officeName, s.firstname as firstname, s.lastname as lastname,"
+ " s.display_name as displayName, s.is_loan_officer as isLoanOfficer from m_staff s "
+ " join m_office o on o.id = s.office_id";
}
@Override
public StaffData mapRow(final ResultSet rs, final int rowNum)
throws SQLException {
Long id = rs.getLong("id");
String firstname = rs.getString("firstname");
String lastname = rs.getString("lastname");
String displayName = rs.getString("displayName");
Long officeId = rs.getLong("officeId");
boolean isLoanOfficer = rs.getBoolean("isLoanOfficer");
String officeName = rs.getString("officeName");
return new StaffData(id, firstname, lastname, displayName,
officeId, officeName, isLoanOfficer);
}
}
@Override
public Collection<StaffData> retrieveAllStaff(final String extraCriteria) {
context.authenticatedUser();
StaffMapper rm = new StaffMapper();
String sql = "select " + rm.schema();
if (StringUtils.isNotBlank(extraCriteria)) {
sql += " where " + extraCriteria;
}
sql = sql + " order by s.lastname";
return this.jdbcTemplate.query(sql, rm, new Object[] {});
}
@Override
public StaffData retrieveStaff(final Long staffId) {
try {
context.authenticatedUser();
StaffMapper rm = new StaffMapper();
String sql = "select " + rm.schema() + " where s.id = ?";
StaffData selectedStaff = this.jdbcTemplate.queryForObject(sql, rm,
new Object[] { staffId });
return selectedStaff;
} catch (EmptyResultDataAccessException e) {
throw new StaffNotFoundException(staffId);
}
}
package org.mifosng.platform.staff.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.mifosng.platform.api.data.StaffData;
import org.mifosng.platform.exceptions.StaffNotFoundException;
import org.mifosng.platform.infrastructure.TenantAwareRoutingDataSource;
import org.mifosng.platform.security.PlatformSecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
@Service
public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context;
@Autowired
public StaffReadPlatformServiceImpl(final PlatformSecurityContext context,
final TenantAwareRoutingDataSource dataSource) {
this.context = context;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
private static final class StaffMapper implements RowMapper<StaffData> {
public String schema() {
return " s.id as id,s.office_id as officeId, o.name as officeName, s.firstname as firstname, s.lastname as lastname,"
+ " s.display_name as displayName, s.is_loan_officer as isLoanOfficer from m_staff s "
+ " join m_office o on o.id = s.office_id";
}
@Override
public StaffData mapRow(final ResultSet rs, final int rowNum)
throws SQLException {
Long id = rs.getLong("id");
String firstname = rs.getString("firstname");
String lastname = rs.getString("lastname");
String displayName = rs.getString("displayName");
Long officeId = rs.getLong("officeId");
boolean isLoanOfficer = rs.getBoolean("isLoanOfficer");
String officeName = rs.getString("officeName");
return new StaffData(id, firstname, lastname, displayName,
officeId, officeName, isLoanOfficer);
}
}
@Override
public Collection<StaffData> retrieveAllStaff(final String extraCriteria) {
context.authenticatedUser();
StaffMapper rm = new StaffMapper();
String sql = "select " + rm.schema();
if (StringUtils.isNotBlank(extraCriteria)) {
sql += " where " + extraCriteria;
}
sql = sql + " order by s.lastname";
return this.jdbcTemplate.query(sql, rm, new Object[] {});
}
@Override
public StaffData retrieveStaff(final Long staffId) {
try {
context.authenticatedUser();
StaffMapper rm = new StaffMapper();
String sql = "select " + rm.schema() + " where s.id = ?";
StaffData selectedStaff = this.jdbcTemplate.queryForObject(sql, rm,
new Object[] { staffId });
return selectedStaff;
} catch (EmptyResultDataAccessException e) {
throw new StaffNotFoundException(staffId);
}
}
}
@@ -1,130 +1,130 @@
package org.mifosng.platform.staff.service;
import org.apache.commons.lang.StringUtils;
import org.mifosng.platform.api.commands.StaffCommand;
import org.mifosng.platform.exceptions.OfficeNotFoundException;
import org.mifosng.platform.exceptions.PlatformDataIntegrityException;
import org.mifosng.platform.exceptions.StaffNotFoundException;
import org.mifosng.platform.organisation.domain.Office;
import org.mifosng.platform.organisation.domain.OfficeRepository;
import org.mifosng.platform.security.PlatformSecurityContext;
import org.mifosng.platform.staff.domain.Staff;
import org.mifosng.platform.staff.domain.StaffRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class StaffWritePlatformServiceJpaRepositoryImpl implements
StaffWritePlatformService {
private final static Logger logger = LoggerFactory
.getLogger(StaffWritePlatformServiceJpaRepositoryImpl.class);
private final PlatformSecurityContext context;
private final StaffRepository staffRepository;
private final OfficeRepository officeRepository;
@Autowired
public StaffWritePlatformServiceJpaRepositoryImpl(
final PlatformSecurityContext context,
final StaffRepository staffRepository,
final OfficeRepository officeRepository) {
this.context = context;
this.staffRepository = staffRepository;
this.officeRepository = officeRepository;
}
@Transactional
@Override
public Long createStaff(final StaffCommand command) {
try {
context.authenticatedUser();
StaffCommandValidator validator = new StaffCommandValidator(command);
validator.validateForCreate();
Office staffOffice = this.officeRepository.findOne(command
.getOfficeId());
if (staffOffice == null) {
throw new OfficeNotFoundException(command.getOfficeId());
}
Staff staff = Staff.createNew(staffOffice, command.getFirstName(),
command.getLastName(), command.isLoanOfficerFlag());
this.staffRepository.saveAndFlush(staff);
return staff.getId();
} catch (DataIntegrityViolationException dve) {
handleStaffDataIntegrityIssues(command, dve);
return Long.valueOf(-1);
}
}
@Transactional
@Override
public Long updateStaff(final StaffCommand command) {
try {
context.authenticatedUser();
StaffCommandValidator validator = new StaffCommandValidator(command);
validator.validateForUpdate();
final Long staffId = command.getId();
Staff staff = this.staffRepository.findOne(staffId);
if (staff == null) {
throw new StaffNotFoundException(staffId);
}
Office staffOffice = null;
Long officeId = command.getOfficeId();
if (command.isOfficeChanged() && officeId != null) {
staffOffice = this.officeRepository.findOne(officeId);
if (staffOffice == null) {
throw new OfficeNotFoundException(command.getOfficeId());
}
}
staff.update(command, staffOffice);
this.staffRepository.saveAndFlush(staff);
return staff.getId();
} catch (DataIntegrityViolationException dve) {
handleStaffDataIntegrityIssues(command, dve);
return Long.valueOf(-1);
}
}
/*
* Guaranteed to throw an exception no matter what the data integrity issue
* is.
*/
private void handleStaffDataIntegrityIssues(final StaffCommand command,
DataIntegrityViolationException dve) {
Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("display_name")) {
String displayName = command.getLastName();
if (!StringUtils.isBlank(command.getFirstName())) {
displayName = command.getLastName() + ", "
+ command.getFirstName();
}
throw new PlatformDataIntegrityException(
"error.msg.staff.duplicate.displayName",
"A staff with the given display name '" + displayName
+ "' already exists", "displayName", displayName);
}
logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException(
"error.msg.staff.unknown.data.integrity.issue",
"Unknown data integrity issue with resource: "
+ realCause.getMessage());
}
package org.mifosng.platform.staff.service;
import org.apache.commons.lang.StringUtils;
import org.mifosng.platform.api.commands.StaffCommand;
import org.mifosng.platform.exceptions.OfficeNotFoundException;
import org.mifosng.platform.exceptions.PlatformDataIntegrityException;
import org.mifosng.platform.exceptions.StaffNotFoundException;
import org.mifosng.platform.organisation.domain.Office;
import org.mifosng.platform.organisation.domain.OfficeRepository;
import org.mifosng.platform.security.PlatformSecurityContext;
import org.mifosng.platform.staff.domain.Staff;
import org.mifosng.platform.staff.domain.StaffRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class StaffWritePlatformServiceJpaRepositoryImpl implements
StaffWritePlatformService {
private final static Logger logger = LoggerFactory
.getLogger(StaffWritePlatformServiceJpaRepositoryImpl.class);
private final PlatformSecurityContext context;
private final StaffRepository staffRepository;
private final OfficeRepository officeRepository;
@Autowired
public StaffWritePlatformServiceJpaRepositoryImpl(
final PlatformSecurityContext context,
final StaffRepository staffRepository,
final OfficeRepository officeRepository) {
this.context = context;
this.staffRepository = staffRepository;
this.officeRepository = officeRepository;
}
@Transactional
@Override
public Long createStaff(final StaffCommand command) {
try {
context.authenticatedUser();
StaffCommandValidator validator = new StaffCommandValidator(command);
validator.validateForCreate();
Office staffOffice = this.officeRepository.findOne(command
.getOfficeId());
if (staffOffice == null) {
throw new OfficeNotFoundException(command.getOfficeId());
}
Staff staff = Staff.createNew(staffOffice, command.getFirstName(),
command.getLastName(), command.isLoanOfficerFlag());
this.staffRepository.saveAndFlush(staff);
return staff.getId();
} catch (DataIntegrityViolationException dve) {
handleStaffDataIntegrityIssues(command, dve);
return Long.valueOf(-1);
}
}
@Transactional
@Override
public Long updateStaff(final StaffCommand command) {
try {
context.authenticatedUser();
StaffCommandValidator validator = new StaffCommandValidator(command);
validator.validateForUpdate();
final Long staffId = command.getId();
Staff staff = this.staffRepository.findOne(staffId);
if (staff == null) {
throw new StaffNotFoundException(staffId);
}
Office staffOffice = null;
Long officeId = command.getOfficeId();
if (command.isOfficeChanged() && officeId != null) {
staffOffice = this.officeRepository.findOne(officeId);
if (staffOffice == null) {
throw new OfficeNotFoundException(command.getOfficeId());
}
}
staff.update(command, staffOffice);
this.staffRepository.saveAndFlush(staff);
return staff.getId();
} catch (DataIntegrityViolationException dve) {
handleStaffDataIntegrityIssues(command, dve);
return Long.valueOf(-1);
}
}
/*
* Guaranteed to throw an exception no matter what the data integrity issue
* is.
*/
private void handleStaffDataIntegrityIssues(final StaffCommand command,
DataIntegrityViolationException dve) {
Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("display_name")) {
String displayName = command.getLastName();
if (!StringUtils.isBlank(command.getFirstName())) {
displayName = command.getLastName() + ", "
+ command.getFirstName();
}
throw new PlatformDataIntegrityException(
"error.msg.staff.duplicate.displayName",
"A staff with the given display name '" + displayName
+ "' already exists", "displayName", displayName);
}
logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException(
"error.msg.staff.unknown.data.integrity.issue",
"Unknown data integrity issue with resource: "
+ realCause.getMessage());
}
}