start of client api work.

This commit is contained in:
Keith Woodlock
2012-05-15 16:45:15 +01:00
parent 29ab498e39
commit dc1c39c5ec
9 changed files with 405 additions and 241 deletions
@@ -14,7 +14,8 @@
<c:url value="/" var="rootContext" /> <c:url value="/" var="rootContext" />
<script> <script>
$(document).ready(function() { $(document).ready(function() {
// these helpers are registered for the jsViews and jsRender functionality to fix bug with display zero!
// these helpers are registered for the jsViews and jsRender functionality to fix bug with display zero!
$.views.registerHelpers({ $.views.registerHelpers({
money: function(monetaryObj) { money: function(monetaryObj) {
@@ -23,49 +23,48 @@ div.notespacer {margin-top: 5px; margin-bottom: 5px;}
<script> <script>
$(document).ready(function() { $(document).ready(function() {
// these helpers are registered for the jsViews and jsRender functionality to fix bug with display zero!
$.views.registerHelpers({ $.views.registerHelpers({
money: function(monetaryObj) { money: function(monetaryObj) {
Globalize.culture().numberFormat.currency.symbol = monetaryObj.displaySymbol; Globalize.culture().numberFormat.currency.symbol = monetaryObj.displaySymbol;
var digits = monetaryObj.currencyDigitsAfterDecimal.toFixed(0); var digits = monetaryObj.currencyDigitsAfterDecimal.toFixed(0);
return Globalize.format(monetaryObj.amount, "n" + digits); return Globalize.format(monetaryObj.amount, "n" + digits);
}, },
moneyWithCurrency: function(monetaryObj) { moneyWithCurrency: function(monetaryObj) {
Globalize.culture().numberFormat.currency.symbol = monetaryObj.displaySymbol; Globalize.culture().numberFormat.currency.symbol = monetaryObj.displaySymbol;
var digits = monetaryObj.currencyDigitsAfterDecimal.toFixed(0); var digits = monetaryObj.currencyDigitsAfterDecimal.toFixed(0);
return Globalize.format(monetaryObj.amount, "c" + digits); return Globalize.format(monetaryObj.amount, "c" + digits);
}, },
decimal: function(number, digits) { decimal: function(number, digits) {
try { try {
return Globalize.format(number, "n" + digits); return Globalize.format(number, "n" + digits);
} catch(e) { } catch(e) {
return number +"(NaN)"; return number +"(NaN)";
} }
}, },
number: function(number) { number: function(number) {
try { try {
return Globalize.format(number, "n0"); return Globalize.format(number, "n0");
} catch(e) { } catch(e) {
return number +"(NaN)"; return number +"(NaN)";
} }
}, },
numberGreaterThanZero: function(number) { numberGreaterThanZero: function(number) {
try { try {
var num = number.toFixed(0); var num = number.toFixed(0);
return num > 0; return num > 0;
} catch(e) { } catch(e) {
return false; return false;
} }
}, },
globalDate: function(dateParts) { globalDate: function(localDateAsISOString) {
try { try {
if (dateParts === null) { var dateParts = localDateAsISOString.split("-")
return "";
} else {
var year = dateParts[0]; var year = dateParts[0];
var month = parseInt(dateParts[1]) - 1; // month is zero indexed var month = parseInt(dateParts[1]) - 1; // month is zero indexed
var day = dateParts[2]; var day = dateParts[2];
@@ -74,25 +73,19 @@ $(document).ready(function() {
d.setFullYear(year,month,day); d.setFullYear(year,month,day);
return Globalize.format(d,"dd MMMM yyyy"); return Globalize.format(d,"dd MMMM yyyy");
} } catch(e) {
} catch(e) { return "??";
return "??"; }
} },
}, globalDateTime: function(dateInMillis) {
globalDateTime: function(dateParts) { try {
try { var d = new Date(dateInMillis);
if (dateParts === null) {
return "";
} else {
var d = new Date(dateParts);
return Globalize.format(d,"F"); return Globalize.format(d,"F");
} } catch(e) {
} catch(e) { return "??";
return "??"; }
} }
}
}); });
function removeErrors(placeholderDiv) { function removeErrors(placeholderDiv) {
@@ -128,17 +121,28 @@ $(document).ready(function() {
removeErrors(placeholderDiv); removeErrors(placeholderDiv);
var jsonErrors = JSON.parse(jqXHR.responseText); var jsonErrors = JSON.parse(jqXHR.responseText);
console.log(jsonErrors);
var valErrors = jsonErrors.errors;
console.log(valErrors);
var errorArray = new Array(); var errorArray = new Array();
var arrayIndex = 0; var arrayIndex = 0;
$.each(jsonErrors, function() { $.each(valErrors, function() {
var fieldId = '#' + this.field; var fieldId = '#' + this.parameterName;
$(fieldId).addClass("ui-state-error"); $(fieldId).addClass("ui-state-error");
var errorObj = new Object(); var errorObj = new Object();
errorObj.field = this.field; errorObj.field = this.parameterName;
errorObj.code = this.code; errorObj.code = this.userMessageGlobalisationCode;
errorObj.message = jQuery.i18n.prop(this.code, this.args);
var argArray = new Array();
var argArrayIndex = 0;
$.each(this.args, function() {
argArray[argArrayIndex] = this.value;
argArrayIndex++;
});
console.log(argArray);
// hardcoded support for six arguments
errorObj.message = jQuery.i18n.prop(this.userMessageGlobalisationCode, argArray[0], argArray[1], argArray[2], argArray[3], argArray[4], argArray[5]);
errorObj.value = this.value; errorObj.value = this.value;
errorArray[arrayIndex] = errorObj; errorArray[arrayIndex] = errorObj;
@@ -181,6 +185,29 @@ $(document).ready(function() {
}).dialog('open'); }).dialog('open');
} }
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
if (this.name === 'selectedItems' || this.name === 'notSelectedItems') {
o[this.name] = new Array();
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
}
});
return o;
};
function popupConfirmationDialogAndPost(url, titleCode, width, height, tabIndex, redirectUrl) { function popupConfirmationDialogAndPost(url, titleCode, width, height, tabIndex, redirectUrl) {
var dialogDiv = $("<div id='dialog-form'><div id='formerrors'></div>" + jQuery.i18n.prop('text.confirmation.required') + "</div>"); var dialogDiv = $("<div id='dialog-form'><div id='formerrors'></div>" + jQuery.i18n.prop('text.confirmation.required') + "</div>");
@@ -364,7 +391,6 @@ $(document).ready(function() {
}); });
} }
// "tabTemplate": '<li><a href="<%= "#" %>{href}"><%= "#" %>{label}</a> <span class="ui-icon ui-icon-close">Remove Tab</span></li>',
var tab_counter = 1; var tab_counter = 1;
var $newtabs = $("#newtabs").tabs({ var $newtabs = $("#newtabs").tabs({
@@ -704,7 +730,7 @@ $(document).ready(function() {
<div id="newtabs"> <div id="newtabs">
<ul> <ul>
<li><a href="${clientUrl}" title="clienttab" class="topleveltab">${clientDisplayName}</a></li> <li><a href="http://localhost:8080/mifosng-provider/api/v1/clients/${clientId}" title="clienttab" class="topleveltab">${clientDisplayName}</a></li>
</ul> </ul>
<div id="clienttab"> <div id="clienttab">
</div> </div>
@@ -14,10 +14,6 @@ public interface ReadPlatformService {
Collection<OrganisationReadModel> retrieveAll(); Collection<OrganisationReadModel> retrieveAll();
Collection<ClientData> retrieveAllIndividualClients();
ClientData retrieveIndividualClient(Long clientId);
ClientDataWithAccountsData retrieveClientAccountDetails(Long clientId); ClientDataWithAccountsData retrieveClientAccountDetails(Long clientId);
NewLoanWorkflowStepOneData retrieveClientAndProductDetails(Long clientId, Long productId); NewLoanWorkflowStepOneData retrieveClientAndProductDetails(Long clientId, Long productId);
@@ -13,7 +13,6 @@ import java.util.List;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.mifosng.data.AppUserData; import org.mifosng.data.AppUserData;
@@ -31,6 +30,7 @@ import org.mifosng.data.OfficeData;
import org.mifosng.data.OrganisationReadModel; import org.mifosng.data.OrganisationReadModel;
import org.mifosng.platform.client.domain.Client; import org.mifosng.platform.client.domain.Client;
import org.mifosng.platform.client.domain.ClientRepository; import org.mifosng.platform.client.domain.ClientRepository;
import org.mifosng.platform.client.service.ClientReadPlatformService;
import org.mifosng.platform.currency.domain.ApplicationCurrency; import org.mifosng.platform.currency.domain.ApplicationCurrency;
import org.mifosng.platform.currency.domain.ApplicationCurrencyRepository; import org.mifosng.platform.currency.domain.ApplicationCurrencyRepository;
import org.mifosng.platform.currency.domain.Money; import org.mifosng.platform.currency.domain.Money;
@@ -41,7 +41,6 @@ import org.mifosng.platform.loan.domain.LoanRepository;
import org.mifosng.platform.loan.domain.LoanTransaction; import org.mifosng.platform.loan.domain.LoanTransaction;
import org.mifosng.platform.loan.domain.LoanTransactionRepository; import org.mifosng.platform.loan.domain.LoanTransactionRepository;
import org.mifosng.platform.loanproduct.service.LoanProductReadPlatformService; import org.mifosng.platform.loanproduct.service.LoanProductReadPlatformService;
import org.mifosng.platform.organisation.domain.Organisation;
import org.mifosng.platform.user.domain.AppUser; import org.mifosng.platform.user.domain.AppUser;
import org.mifosng.platform.user.service.AppUserReadPlatformService; import org.mifosng.platform.user.service.AppUserReadPlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -63,11 +62,13 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
private final ApplicationCurrencyRepository applicationCurrencyRepository; private final ApplicationCurrencyRepository applicationCurrencyRepository;
private final LoanProductReadPlatformService loanProductReadPlatformService; private final LoanProductReadPlatformService loanProductReadPlatformService;
private final AppUserReadPlatformService appUserReadPlatformService; private final AppUserReadPlatformService appUserReadPlatformService;
private final ClientReadPlatformService clientReadPlatformService;
@Autowired @Autowired
public ReadPlatformServiceImpl( public ReadPlatformServiceImpl(
final LoanProductReadPlatformService loanProductReadPlatformService, final LoanProductReadPlatformService loanProductReadPlatformService,
final AppUserReadPlatformService appUserReadPlatformService, final AppUserReadPlatformService appUserReadPlatformService,
final ClientReadPlatformService clientReadPlatformService,
final DataSource dataSource, final DataSource dataSource,
final ClientRepository clientRepository, final ClientRepository clientRepository,
final LoanRepository loanRepository, final LoanRepository loanRepository,
@@ -75,6 +76,7 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
final ApplicationCurrencyRepository applicationCurrencyRepository) { final ApplicationCurrencyRepository applicationCurrencyRepository) {
this.loanProductReadPlatformService = loanProductReadPlatformService; this.loanProductReadPlatformService = loanProductReadPlatformService;
this.appUserReadPlatformService = appUserReadPlatformService; this.appUserReadPlatformService = appUserReadPlatformService;
this.clientReadPlatformService = clientReadPlatformService;
this.loanTransactionRepository = loanTransactionRepository; this.loanTransactionRepository = loanTransactionRepository;
this.applicationCurrencyRepository = applicationCurrencyRepository; this.applicationCurrencyRepository = applicationCurrencyRepository;
this.jdbcTemplate = new SimpleJdbcTemplate(dataSource); this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
@@ -125,37 +127,6 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
} }
} }
@Override
public Collection<ClientData> retrieveAllIndividualClients() {
AppUser currentUser = extractAuthenticatedUser();
List<OfficeData> offices = retrieveOffices();
String officeIdsList = generateOfficeIdInClause(offices);
ClientMapper rm = new ClientMapper(offices,
currentUser.getOrganisation());
String sql = "select " + rm.clientSchema()
+ " where c.org_id = ? and c.office_id in (" + officeIdsList
+ ") order by c.lastname ASC, c.firstname ASC";
return this.jdbcTemplate.query(sql, rm, new Object[] { currentUser
.getOrganisation().getId() });
}
private String generateOfficeIdInClause(List<OfficeData> offices) {
String officeIdsList = "";
for (int i = 0; i < offices.size(); i++) {
Long id = offices.get(i).getId();
if (i == 0) {
officeIdsList = id.toString();
} else {
officeIdsList += "," + id.toString();
}
}
return officeIdsList;
}
@Override @Override
public NoteData retrieveClientNote(Long clientId, Long noteId) { public NoteData retrieveClientNote(Long clientId, Long noteId) {
@@ -249,60 +220,6 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
} }
} }
protected static final class ClientMapper implements RowMapper<ClientData> {
private final List<OfficeData> offices;
private final Organisation organisation;
public ClientMapper(final List<OfficeData> offices,
Organisation organisation) {
this.offices = offices;
this.organisation = organisation;
}
public String clientSchema() {
return "c.org_id as orgId, c.office_id as officeId, c.id as id, c.firstname as firstname, c.lastname as lastname, c.external_id as externalId, c.joining_date as joinedDate from portfolio_client c";
}
@Override
public ClientData mapRow(final ResultSet rs, final int rowNum)
throws SQLException {
Long orgId = rs.getLong("orgId");
Long officeId = rs.getLong("officeId");
Long id = rs.getLong("id");
String firstname = rs.getString("firstname");
if (StringUtils.isBlank(firstname)) {
firstname = "";
}
String lastname = rs.getString("lastname");
String externalId = rs.getString("externalId");
LocalDate joinedDate = new LocalDate(rs.getDate("joinedDate"));
String officeName = fromOfficeList(this.offices, officeId);
String orgname = "";
if (organisation.getId().equals(orgId)) {
orgname = organisation.getName();
}
return new ClientData(orgId, orgname, officeId, officeName, id,
firstname, lastname, externalId, joinedDate);
}
private String fromOfficeList(final List<OfficeData> officeList,
final Long officeId) {
String match = "";
for (OfficeData office : officeList) {
if (office.getId().equals(officeId)) {
match = office.getName();
}
}
return match;
}
}
private List<OfficeData> retrieveOffices() { private List<OfficeData> retrieveOffices() {
AppUser currentUser = extractAuthenticatedUser(); AppUser currentUser = extractAuthenticatedUser();
@@ -343,35 +260,13 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
} }
} }
@Override
public ClientData retrieveIndividualClient(final Long clientId) {
try {
AppUser currentUser = extractAuthenticatedUser();
List<OfficeData> offices = retrieveOffices();
ClientMapper rm = new ClientMapper(offices,
currentUser.getOrganisation());
String sql = "select " + rm.clientSchema()
+ " where c.id = ? and c.org_id = ?";
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] {
clientId, currentUser.getOrganisation().getId() });
} catch (EmptyResultDataAccessException e) {
throw new PlatformResourceNotFoundException(
"error.msg.client.id.invalid",
"Client with identifier {0} does not exist", clientId);
}
}
@Override @Override
public ClientDataWithAccountsData retrieveClientAccountDetails( public ClientDataWithAccountsData retrieveClientAccountDetails(
final Long clientId) { final Long clientId) {
AppUser currentUser = extractAuthenticatedUser(); AppUser currentUser = extractAuthenticatedUser();
ClientData clientAccount = retrieveIndividualClient(clientId); ClientData clientAccount = this.clientReadPlatformService.retrieveIndividualClient(clientId);
// TODO - rewrite using jdbc sql approach // TODO - rewrite using jdbc sql approach
Client client = this.clientRepository.findOne(clientsThatMatch( Client client = this.clientRepository.findOne(clientsThatMatch(
@@ -539,7 +434,7 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
workflowData.setSelectedProduct(selectedProduct); workflowData.setSelectedProduct(selectedProduct);
} }
ClientData clientAccount = retrieveIndividualClient(clientId); ClientData clientAccount = this.clientReadPlatformService.retrieveIndividualClient(clientId);
workflowData.setClientId(clientAccount.getId()); workflowData.setClientId(clientAccount.getId());
workflowData.setClientName(clientAccount.getDisplayName()); workflowData.setClientName(clientAccount.getDisplayName());
@@ -0,0 +1,147 @@
package org.mifosng.platform.api;
import java.util.Collection;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.mifosng.data.ClientData;
import org.mifosng.data.ClientList;
import org.mifosng.platform.WritePlatformService;
import org.mifosng.platform.client.service.ClientReadPlatformService;
import org.mifosng.platform.user.domain.AppUser;
import org.mifosng.platform.user.domain.AppUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Path("/v1/clients")
@Component
@Scope("singleton")
public class ClientApiResource {
@Autowired
private ClientReadPlatformService clientReadPlatformService;
@Autowired
private WritePlatformService writePlatformService;
@Autowired
private AppUserRepository appUserRepository;
private void hardcodeUserIntoSecurityContext() {
AppUser currentUser = this.appUserRepository.findOne(Long.valueOf(1));
Authentication auth = new UsernamePasswordAuthenticationToken(currentUser, currentUser, currentUser.getAuthorities());
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(auth);
}
@GET
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON})
public Response retrieveAllIndividualClients() {
hardcodeUserIntoSecurityContext();
Collection<ClientData> clients = this.clientReadPlatformService.retrieveAllIndividualClients();
return Response.ok().entity(new ClientList(clients)).build();
}
@GET
@Path("{clientId}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON})
public Response retrieveClientData(@PathParam("clientId") final Long clientId) {
hardcodeUserIntoSecurityContext();
ClientData clientData = this.clientReadPlatformService.retrieveIndividualClient(clientId);
return Response.ok().entity(clientData).build();
}
// @GET
// @Path("template")
// @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
// @Produces({ MediaType.APPLICATION_JSON})
// public Response newClientDetails() {
//
// hardcodeUserIntoSecurityContext();
//
// ClientData clientData = this.clientReadPlatformService.retrieveNewClientDetails();
//
// return Response.ok().entity(clientData).build();
// }
//
// @POST
// @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
// @Produces({ MediaType.APPLICATION_JSON })
// public Response enrollClient(final EnrollClientCommand command) {
//
// hardcodeUserIntoSecurityContext();
//
// Long clientId = this.writePlatformService.enrollClient(command);
//
// return Response.ok().entity(new EntityIdentifier(clientId)).build();
// }
//
//
// @GET
// @Path("{clientId}/withaccounts")
// @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
// @Produces({ MediaType.APPLICATION_JSON })
// public Response retrieveClientAccount(@PathParam("clientId") final Long clientId) {
//
// hardcodeUserIntoSecurityContext();
//
// ClientDataWithAccountsData clientAccount = this.clientReadPlatformService.retrieveClientAccountDetails(clientId);
//
// return Response.ok().entity(clientAccount).build();
// }
//
// @POST
// @Path("{clientId}/note/new")
// @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
// @Produces({ MediaType.APPLICATION_JSON})
// public Response addNewClientNote(@PathParam("clientId") final Long clientId, final NoteCommand command) {
//
// hardcodeUserIntoSecurityContext();
//
// EntityIdentifier identifier = this.writePlatformService.addClientNote(command);
//
// return Response.ok().entity(identifier).build();
// }
//
// @GET
// @Path("{clientId}/note/all")
// @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
// @Produces({ MediaType.APPLICATION_JSON})
// public Response retrieveAllClientNotes(@PathParam("clientId") final Long clientId) {
//
// Collection<NoteData> notes = this.clientReadPlatformService.retrieveAllClientNotes(clientId);
//
// return Response.ok().entity(new NoteDataList(notes)).build();
// }
//
// @GET
// @Path("{clientId}/note/{noteId}")
// @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
// @Produces({ MediaType.APPLICATION_JSON })
// public Response retrieveClientNote(@PathParam("clientId") final Long clientId, @PathParam("noteId") final Long noteId) {
//
// NoteData note = this.clientReadPlatformService.retrieveClientNote(clientId, noteId);
//
// return Response.ok().entity(note).build();
// }
}
@@ -0,0 +1,12 @@
package org.mifosng.platform.client.service;
import java.util.Collection;
import org.mifosng.data.ClientData;
public interface ClientReadPlatformService {
Collection<ClientData> retrieveAllIndividualClients();
ClientData retrieveIndividualClient(Long clientId);
}
@@ -0,0 +1,143 @@
package org.mifosng.platform.client.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.mifosng.data.ClientData;
import org.mifosng.data.OfficeData;
import org.mifosng.platform.exceptions.PlatformResourceNotFoundException;
import org.mifosng.platform.organisation.domain.Organisation;
import org.mifosng.platform.organisation.service.OfficeReadPlatformService;
import org.mifosng.platform.security.PlatformSecurityContext;
import org.mifosng.platform.user.domain.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class ClientReadPlatformServiceImpl implements ClientReadPlatformService {
private final SimpleJdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context;
private final OfficeReadPlatformService officeReadPlatformService;
@Autowired
public ClientReadPlatformServiceImpl(final PlatformSecurityContext context, final DataSource dataSource, final OfficeReadPlatformService officeReadPlatformService) {
this.context = context;
this.officeReadPlatformService = officeReadPlatformService;
this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
private String generateOfficeIdInClause(List<OfficeData> offices) {
String officeIdsList = "";
for (int i = 0; i < offices.size(); i++) {
Long id = offices.get(i).getId();
if (i == 0) {
officeIdsList = id.toString();
} else {
officeIdsList += "," + id.toString();
}
}
return officeIdsList;
}
@Override
public Collection<ClientData> retrieveAllIndividualClients() {
AppUser currentUser = this.context.authenticatedUser();
List<OfficeData> offices = new ArrayList<OfficeData>(officeReadPlatformService.retrieveAllOffices());
String officeIdsList = generateOfficeIdInClause(offices);
ClientMapper rm = new ClientMapper(offices, currentUser.getOrganisation());
String sql = "select " + rm.clientSchema()
+ " where c.org_id = ? and c.office_id in (" + officeIdsList
+ ") order by c.lastname ASC, c.firstname ASC";
return this.jdbcTemplate.query(sql, rm, new Object[] { currentUser
.getOrganisation().getId() });
}
@Override
public ClientData retrieveIndividualClient(final Long clientId) {
try {
AppUser currentUser = this.context.authenticatedUser();
List<OfficeData> offices = new ArrayList<OfficeData>(officeReadPlatformService.retrieveAllOffices());
ClientMapper rm = new ClientMapper(offices, currentUser.getOrganisation());
String sql = "select " + rm.clientSchema() + " where c.id = ? and c.org_id = ?";
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] {clientId, currentUser.getOrganisation().getId() });
} catch (EmptyResultDataAccessException e) {
throw new PlatformResourceNotFoundException(
"error.msg.client.id.invalid",
"Client with identifier {0} does not exist", clientId);
}
}
private static final class ClientMapper implements RowMapper<ClientData> {
private final List<OfficeData> offices;
private final Organisation organisation;
public ClientMapper(final List<OfficeData> offices,
Organisation organisation) {
this.offices = offices;
this.organisation = organisation;
}
public String clientSchema() {
return "c.org_id as orgId, c.office_id as officeId, c.id as id, c.firstname as firstname, c.lastname as lastname, c.external_id as externalId, c.joining_date as joinedDate from portfolio_client c";
}
@Override
public ClientData mapRow(final ResultSet rs, final int rowNum)
throws SQLException {
Long orgId = rs.getLong("orgId");
Long officeId = rs.getLong("officeId");
Long id = rs.getLong("id");
String firstname = rs.getString("firstname");
if (StringUtils.isBlank(firstname)) {
firstname = "";
}
String lastname = rs.getString("lastname");
String externalId = rs.getString("externalId");
LocalDate joinedDate = new LocalDate(rs.getDate("joinedDate"));
String officeName = fromOfficeList(this.offices, officeId);
String orgname = "";
if (organisation.getId().equals(orgId)) {
orgname = organisation.getName();
}
return new ClientData(orgId, orgname, officeId, officeName, id,
firstname, lastname, externalId, joinedDate);
}
private String fromOfficeList(final List<OfficeData> officeList,
final Long officeId) {
String match = "";
for (OfficeData office : officeList) {
if (office.getId().equals(officeId)) {
match = office.getName();
}
}
return match;
}
}
}
@@ -26,6 +26,7 @@ import org.mifosng.data.command.EnrollClientCommand;
import org.mifosng.data.command.NoteCommand; import org.mifosng.data.command.NoteCommand;
import org.mifosng.platform.ReadPlatformService; import org.mifosng.platform.ReadPlatformService;
import org.mifosng.platform.WritePlatformService; import org.mifosng.platform.WritePlatformService;
import org.mifosng.platform.client.service.ClientReadPlatformService;
import org.mifosng.platform.exceptions.ApplicationDomainRuleException; import org.mifosng.platform.exceptions.ApplicationDomainRuleException;
import org.mifosng.platform.exceptions.UnAuthenticatedUserException; import org.mifosng.platform.exceptions.UnAuthenticatedUserException;
import org.mifosng.platform.exceptions.NewDataValidationException; import org.mifosng.platform.exceptions.NewDataValidationException;
@@ -42,6 +43,9 @@ public class ClientResource {
@Autowired @Autowired
private ReadPlatformService readPlatformService; private ReadPlatformService readPlatformService;
@Autowired
private ClientReadPlatformService clientReadPlatformService;
@Autowired @Autowired
private WritePlatformService writePlatformService; private WritePlatformService writePlatformService;
@@ -51,21 +55,9 @@ public class ClientResource {
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response retrieveAllIndividualClients() { public Response retrieveAllIndividualClients() {
try { Collection<ClientData> clients = this.clientReadPlatformService.retrieveAllIndividualClients();
Collection<ClientData> clients = this.readPlatformService.retrieveAllIndividualClients();
return Response.ok().entity(new ClientList(clients)).build(); return Response.ok().entity(new ClientList(clients)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
} }
@GET @GET
@@ -118,23 +110,13 @@ public class ClientResource {
@Path("{clientId}") @Path("{clientId}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response retrieveClientData(@PathParam("clientId") final Long clientId) { public Response retrieveClientData(
@PathParam("clientId") final Long clientId) {
try { ClientData clientData = this.clientReadPlatformService
ClientData clientData = this.readPlatformService.retrieveIndividualClient(clientId); .retrieveIndividualClient(clientId);
return Response.ok().entity(clientData).build(); return Response.ok().entity(clientData).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
} }
@GET @GET
@@ -1,38 +0,0 @@
package org.mifosng.platform.rest;
import java.util.Collection;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.mifosng.data.OrganisationList;
import org.mifosng.data.OrganisationReadModel;
import org.mifosng.platform.ReadPlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Path("/protected/org")
@Component
@Scope("singleton")
public class TenantResource {
@Autowired
private ReadPlatformService readPlatformService;
@GET
@Path("view")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response retrieveExistingOrganisations() {
Collection<OrganisationReadModel> organisations = this.readPlatformService
.retrieveAll();
return Response.ok().entity(new OrganisationList(organisations))
.build();
}
}