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